@gala-chain/launchpad-sdk 9.0.0-rc.1 → 9.0.0-rc.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/CHANGELOG.md +77 -1
  2. package/EXAMPLES.md +1 -1
  3. package/MIGRATING-TO-9.0.md +1 -1
  4. package/dist/LaunchpadSDK.d.ts +2 -2
  5. package/dist/LaunchpadSDK.d.ts.map +1 -1
  6. package/dist/auth/SessionAuthService.d.ts.map +1 -1
  7. package/dist/constants/version.generated.d.ts +1 -1
  8. package/dist/index.browser.d.ts +1 -1
  9. package/dist/index.browser.d.ts.map +1 -1
  10. package/dist/index.browser.esm.js +1 -1
  11. package/dist/index.cjs +1 -1
  12. package/dist/index.esm.js +1 -1
  13. package/dist/index.js +1 -1
  14. package/dist/launchpad/bundle-submission.d.ts.map +1 -1
  15. package/dist/launchpad/writes.d.ts.map +1 -1
  16. package/dist/native.cjs +1 -1
  17. package/dist/native.esm.js +1 -1
  18. package/dist/schemas/pagination.d.ts.map +1 -1
  19. package/dist/schemas/primitives.d.ts +3 -3
  20. package/dist/schemas/primitives.d.ts.map +1 -1
  21. package/dist/schemas/trade.d.ts +1 -1
  22. package/dist/schemas/user.d.ts +5 -5
  23. package/dist/schemas/validators.d.ts +7 -7
  24. package/dist/schemas/validators.d.ts.map +1 -1
  25. package/dist/services/BanService.d.ts.map +1 -1
  26. package/dist/services/BundleService.d.ts.map +1 -1
  27. package/dist/services/ContentFlagService.d.ts.map +1 -1
  28. package/dist/services/EventsBatcherService.d.ts.map +1 -1
  29. package/dist/services/EventsQueryService.d.ts.map +1 -1
  30. package/dist/services/GalaChainBalanceService.d.ts.map +1 -1
  31. package/dist/services/HolderService.d.ts.map +1 -1
  32. package/dist/services/MessagesService.d.ts.map +1 -1
  33. package/dist/services/NftCollectionService.d.ts.map +1 -1
  34. package/dist/services/OEmbedService.d.ts.map +1 -1
  35. package/dist/services/OverseerService.d.ts.map +1 -1
  36. package/dist/services/PoolService.d.ts +4 -1
  37. package/dist/services/PoolService.d.ts.map +1 -1
  38. package/dist/services/StreamWebSocketService.d.ts.map +1 -1
  39. package/dist/services/TradeService.d.ts.map +1 -1
  40. package/dist/services/UserService.d.ts.map +1 -1
  41. package/dist/services/WebSocketAdminService.d.ts.map +1 -1
  42. package/dist/signing/signers.d.ts.map +1 -1
  43. package/dist/types/cache-management.dto.d.ts +1 -1
  44. package/dist/types/cache-management.dto.d.ts.map +1 -1
  45. package/dist/types/constraints.d.ts +2 -2
  46. package/dist/types/launchpad.dto.d.ts +22 -0
  47. package/dist/types/launchpad.dto.d.ts.map +1 -1
  48. package/dist/types/options.dto.d.ts +1 -1
  49. package/dist/types/options.dto.d.ts.map +1 -1
  50. package/dist/types/trade.dto.d.ts.map +1 -1
  51. package/dist/types/user.dto.d.ts.map +1 -1
  52. package/dist/utils/address-formatter.d.ts +85 -0
  53. package/dist/utils/address-formatter.d.ts.map +1 -1
  54. package/dist/utils/error-factories.d.ts +4 -4
  55. package/dist/utils/errors.d.ts +1 -1
  56. package/dist/utils/nft-helpers.d.ts +2 -1
  57. package/dist/utils/nft-helpers.d.ts.map +1 -1
  58. package/dist/utils/primitives.d.ts +1 -1
  59. package/dist/utils/primitives.d.ts.map +1 -1
  60. package/dist/utils/validation-helpers.d.ts +1 -1
  61. package/dist/utils/validation-helpers.d.ts.map +1 -1
  62. package/package.json +1 -1
package/dist/index.esm.js CHANGED
@@ -1 +1 @@
1
- import{getAddress as e,computeAddress as t,isAddress as n,BrowserProvider as r,Wallet as s}from"ethers";import{GALA_CHAIN_ENVIRONMENTS as i,BrowserWalletSigner as o,generateEIP712Types as a,ethereumAddressOfAccount as c,GalaWalletSigner as l,withGalaWalletIdentity as d,PrivateKeySigner as u,isTokenClassKey as h,GatewayReads as g,isGalaError as m,GatewayWrites as f,tokenDetailsOf as p,isWalletUserRejection as E,walletDeclineCode as A,createWallet as v}from"@gala-chain/gala-core-sdk";import{z as T}from"zod";import{PrivateKeyProvider as y,isPrivateKeyProvider as S}from"@gala-chain/gala-core-sdk/providers";import{ChainCallDTO as b,TokenClassKey as N}from"@gala-chain/api";import{v4 as w}from"uuid";import{io as k}from"socket.io-client";import _ from"bignumber.js";import I,{AxiosHeaders as D}from"axios";const C={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"},R="/v1/users/referrals/url",O="/v1/users/referrals",M="/v1/users/referrals/summary",L="/v1/tokens/:tokenName/start-stream",U="/v1/tokens/:tokenName/stop-stream",F="/v1/tokens/:tokenName/stream/disable",P="/v1/tokens/:tokenName/stream/enable",x="/v1/tokens/:tokenName/reset-key",B="/v1/tokens/:tokenName/recordings",G="/v1/tokens/:tokenName/recordings/:assetId/download",$="/v1/tokens/:tokenName/recordings/:assetId",K="/v1/tokens/:tokenName/simulcasts",H="/v1/tokens/:tokenName/simulcasts",W="/v1/tokens/:tokenName/simulcasts/:targetId",V="/v1/config",j="/v1/config",q="/v1/config",z="/v1/tokens/:tokenName/role",X="/v1/roles",Q="/v1/permissions",Y="/v1/tokens/:tokenName/credentials",J="/auth/login",Z="/auth/logout",ee="/auth/refresh",te="/auth/session",ne="/v1/tokens/:tokenName/bans",re="/v1/tokens/:tokenName/bans",se="/v1/tokens/:tokenName/bans/:userAddress",ie="/v1/tokens/:tokenName/bans/:userAddress",oe="/v1/tokens/:tokenName/active-users",ae="/v1/user-bans",ce="/v1/user-bans",le="/v1/user-bans/:userAddress",de="/v1/user-bans/:userAddress",ue={CREATE:"/v1/api-keys",LIST:"/v1/api-keys",GET:"/v1/api-keys/:id",UPDATE:"/v1/api-keys/:id",REVOKE:"/v1/api-keys/:id"},he="/v1/moderator-invites",ge="/v1/moderator-invites/claim",me="/v1/moderated-tokens",fe="/v1/moderator-invites",pe="/v1/moderator-invites/:id",Ee="/v1/moderator-invites/:id/role",Ae="/v1/moderator-invites/:id",ve="/v1/moderator-invites/code/:code",Te={CREATE:"/v1/content-flags",LIST:"/v1/content-flags",DISMISS:"/v1/content-flags/:id/dismiss",ACTION:"/v1/content-flags/:id/action"},ye="/v1/overseer-invites",Se="/v1/overseer-invites",be="/v1/overseer-invites/code/:code",Ne="/v1/overseer-invites/claim",we="/v1/overseer-invites/:id",ke="/v1/overseers",_e="/v1/overseers",Ie="/v1/overseers/:address",De="/v1/overseers/me",Ce="/v1/overseer-summary",Re="/v1/overseer-summary/bans",Oe="/v1/overseer-summary/token-bans",Me="/v1/overseer-summary/invites",Le="/v1/overseer-summary/flags",Ue="/v1/overseer-summary/users",Fe="/v1/users",Pe="/v1/users/:address/summary",xe="/v1/cache/flush/address/:address",Be="/v1/cache/flush/token/:tokenName",Ge="/v1/cache/flush/all",$e="/v1/cache/flush/wallet-aliases/:address",Ke="/v1/cache/flush/wallet-aliases",He="/v1/token-bans",We="/v1/token-bans",Ve="/v1/token-bans/:tokenName",je="/v1/token-bans/:tokenName",qe="/v1/reactions",ze="/v1/reactions",Xe="/v1/trades",Qe={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"},Ye="/v1/restricted-token-names",Je="/v1/restricted-token-names",Ze="/live/:tokenName/chat",et="/live/:tokenName/chat",tt="/live/:tokenName/chat",nt="/live/:tokenName/chat/slow-mode",rt="/v1/events",st="/v1/events/stats",it="/health",ot={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"},at="/v1/stats",ct="/v1/trading/fee",lt="/v1/trading/sale-details",dt="/v1/trading/quote",ut="/v1/trading/premint-quote",ht={GET_LEADERBOARD:"/weekly-challenge",GET_TOKEN_HISTORY:"/weekly-challenge/history/:vaultAddress"},gt="/v1/notifications/register",mt="/v1/notifications/unregister",ft="/v1/notifications/preferences",pt="/v1/notifications/preferences",Et="/v1/config/client-flags",At={NATIVE:"native",EXACT:"exact"},vt={RECENT:"recent",POPULAR:"popular"},Tt=["RECENT","POPULAR","RECORDINGS","SECONDS_STREAMED"],yt=["IDLE","ACTIVE","DISABLED"],St=100,bt={LOCAL:"local",EXTERNAL:"external"},Nt={REQUIRED:"REQUIRED",INVALID_TYPE:"INVALID_TYPE",INVALID_VALUE:"INVALID_VALUE",INVALID_FORMAT:"INVALID_FORMAT",TOO_SHORT:"TOO_SHORT",TOO_LONG:"TOO_LONG",TOO_LARGE:"TOO_LARGE",TOO_SMALL:"TOO_SMALL",EMPTY_ARRAY:"EMPTY_ARRAY",ARRAY_TOO_LARGE:"ARRAY_TOO_LARGE",ZERO_VALUE:"ZERO_VALUE",INVALID_TICK_SPACING:"INVALID_TICK_SPACING",INVALID_FEE_TIER:"INVALID_FEE_TIER",INVALID_RANGE:"INVALID_RANGE",INVALID_PARAMETERS:"INVALID_PARAMETERS",NOT_FOUND:"NOT_FOUND",INVALID_DATA:"INVALID_DATA"};class wt extends Error{constructor(e,t,n){super(e),this.field=t,this.code=n,this.name="ValidationError"}}class kt extends wt{constructor(e){super(e,"token","TOKEN_RESTRICTED"),this.name="TokenRestrictedError"}}function _t(e){return"object"==typeof e&&null!==e}function It(e){if(null==e||""===e)return{};if(!_t(e)||Array.isArray(e))return{body:e};const t=Reflect.get(e,"message"),n="string"==typeof t?t:Array.isArray(t)&&t.every(e=>"string"==typeof e)?t.join(","):void 0,r=Reflect.get(e,"error"),s=Reflect.get(e,"details");return{...void 0===n?{}:{serverMessage:n},..."string"==typeof r&&""!==r?{serverError:r}:{},...void 0===s?{}:{details:s},body:e}}function Dt(e){if(e instanceof Ct)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(!_t(e))return;const t=Reflect.get(e,"response");return _t(t)?t:void 0}(e);return void 0===t?{}:It(Reflect.get(t,"data"))}class Ct extends Error{constructor(e,t,n,r=Dt(n)){super(e),this.name="NetworkError",this.statusCode=t,this.originalError=n,this.serverMessage=r.serverMessage,this.serverError=r.serverError,this.details=r.details,this.body=r.body}}class Rt 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 Mt(e){return e instanceof Error}function Lt(e){return Mt(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 Ut(e){return Mt(e)||"object"==typeof e&&null!==e&&"stack"in e&&"string"==typeof e.stack?e.stack:void 0}function Ft(e){if(function(e){return"object"==typeof e&&null!==e&&"code"in e&&("string"==typeof e.code||"number"==typeof e.code)}(e))return e.code}function Pt(e){return"object"==typeof e&&null!==e&&"message"in e&&("response"in e||"request"in e||"config"in e)}function xt(e,t){if(null==e||"object"!=typeof e)throw new Error(`${t}: No response - expected object, got ${typeof e}`);const n=e;if(!("Status"in n))throw new Error(`${t}: Response missing 'Status' property`);const r=n.Status;if("number"!=typeof r)throw new Error(`${t}: Response Status must be a number, got ${typeof r}`);if(1!==r)throw new Error(`${t}: Response status indicates failure (Status: ${r})`);return n}function 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 Gt(e,t){return void 0!==t?t:e.charAt(0).toUpperCase()+e.slice(1)}function $t(e,t){return new wt(`Token "${e}" not found. Please verify the token name is correct.`,"tokenName","TOKEN_NOT_FOUND")}function Kt(e,t){const n=Gt(e,t);return new wt(`${n} is required`,e,"REQUIRED")}function Ht(e,t,n){const r=Gt(e,n);return new wt(`${r} must be ${t}`,e,"INVALID_FORMAT")}function Wt(e,t,n,r){return new Ct(e,t,n,r)}function Vt(e,t){return new Rt(e,t)}function jt(e,t,n){return new Ot(e,t,n)}function qt(e,t,n,r,s){const i=Gt(e,s);return new wt(`${i} must be between ${t} and ${n}${void 0!==r?`, received: ${r}`:""}`,e,"OUT_OF_RANGE")}function zt(e,t,n,r){const s=Gt(e,r);return new wt(`${s} must be at least ${t}${void 0!==n?`, received: ${n}`:""}`,e,"TOO_SMALL")}function Xt(e,t,n,r){const s=Gt(e,r);return new wt(`${s} must be at most ${t}${void 0!==n?`, received: ${n}`:""}`,e,"TOO_LARGE")}function Qt(e,t,n,r){const s=Gt(e,r),i=void 0!==n?`, received: ${"object"==typeof n?"object":String(n)}`:"";return new wt(`${s} must be ${t}${i}`,e,"INVALID_TYPE")}function Yt(e,t,n){const r=Gt(e,n);return new wt(`${r} must be a valid number${void 0!==t?`: "${t}"`:""}`,e,"INVALID_NUMBER")}function Jt(e,t,n,r){const s=Gt(e,r);return new wt(`Invalid ${s}: ${t}. Must be one of: ${n.join(", ")}`,e,"INVALID_ENUM")}function Zt(e,t){if(e.length<2)return Kt(void 0!==e[0]&&""!==e[0]?e[0]:"field");let n;if(2===e.length)n=e.join(" or ");else{n=`${e.slice(0,-1).join(", ")} or ${e[e.length-1]??"field"}`}return new wt(`At least one of ${n} must be provided`,e[0],"REQUIRED")}function en(e,t,n,r){const s=Gt(e,r);return new wt(`${s} must be at most ${t} characters${void 0!==n?`, received: ${n}`:""}`,e,"TOO_LONG")}function tn(e,t){const n=Gt(e,t);return new wt(`${n} cannot be empty`,e,"EMPTY_STRING")}function nn(e){return null!=e&&"object"==typeof e&&"data"in e}function rn(e,t,n=!1){const r=!0===e.error,s=n&&(null===e.data||void 0===e.data);if(r||s){const n=e?.statusCode??e.status??void 0;throw Wt(e?.message??t,n,void 0,r?It(e):void 0)}}function sn(e){if(nn(e))return e.data}function on(e,t="No data found in response"){if(!nn(e))throw Wt(t);const n=e.data;if(null==n)throw Wt(t);return n}async function an(e,t={}){return dn(e,t,e=>{if(void 0===e.data)throw new wt(`${t.errorContext??"Operation failed"}: No data returned from API`,"data","NO_DATA");return e.data})}async function cn(e,t={}){const{errorContext:n="Operation failed",logger:r,debugLogEnabled:s=!1}=t;s&&r&&r.debug(`${n}: starting operation`);try{const t=await e();return s&&r&&r.debug(`${n}: completed successfully`),t}catch(e){throw r&&r.error(n,{error:e}),e}}async function ln(e,t={}){return dn(e,t,e=>e)}async function dn(e,t,n){const{errorContext:r="Operation failed",logger:s,debugLogEnabled:i=!1}=t;i&&s&&s.debug(`${r}: starting operation`);try{const t=await e();if(null==t)throw new wt(`${r}: No response from server`,"response","NO_RESPONSE");return rn(t,r,!0),i&&s&&s.debug(`${r}: completed successfully`),n(t)}catch(e){throw s&&s.error(r,{error:e}),e}}const un={BASE_PRICE:1650667151e-14,PRICE_SCALING_FACTOR:1166069e-12,TRADING_FEE_FACTOR:.001,GAS_FEE:"1",DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY:1e7};function hn(e){return e.trim().toLowerCase()}function gn(e){return e.trim().toUpperCase()}function mn(e){return e.trim().toUpperCase()}var fn;!function(e){e.DEBUG="DEBUG",e.INFO="INFO",e.WARN="WARN",e.ERROR="ERROR"}(fn||(fn={}));class pn{constructor(e){this.levelPriority={[fn.DEBUG]:0,[fn.INFO]:1,[fn.WARN]:2,[fn.ERROR]:3},this.debugEnabled=e.debug,this.context=e.context??"SDK",this.minLevel=e.minLevel??(e.debug?fn.DEBUG:fn.INFO)}debug(e,t){this.log(fn.DEBUG,e,t)}info(e,t){this.log(fn.INFO,e,t)}warn(e,t){this.log(fn.WARN,e,t)}error(e,t){this.log(fn.ERROR,e,t)}log(e,t,n){if(this.levelPriority[e]<this.levelPriority[this.minLevel])return;if(e===fn.DEBUG&&!this.debugEnabled)return;const r=`[${(new Date).toISOString()}] [${this.context}] [${e}]`,s=this.getConsoleMethod(e);void 0!==n?Mt(n)?s(`${r} ${t}`,n.message,Ut(n)??""):s(`${r} ${t}`,n):s(`${r} ${t}`)}getConsoleMethod(e){switch(e){case fn.DEBUG:return console.debug;case fn.INFO:return console.info;case fn.WARN:return console.warn;case fn.ERROR:return console.error;default:return console.log}}child(e){return new pn({debug:this.debugEnabled,context:`${this.context}:${e}`,minLevel:this.minLevel})}isDebugEnabled(){return this.debugEnabled&&this.levelPriority[fn.DEBUG]>=this.levelPriority[this.minLevel]}}function En(e){return null==e||""===e}function An(e){return null==e}const vn=new pn({debug:!1,context:"DateUtils"});function Tn(e,t){if(null==e)return new Date;if(e instanceof Date)return isNaN(e.getTime())?new Date:e;try{const t=new Date(e);return isNaN(t.getTime())?(vn.warn(`Invalid date string received: "${e}". Using fallback.`),new Date):t}catch(t){return vn.warn(`Date parsing error for "${e}":`,t),new Date}}function yn(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 Sn(e,t=0){if(En(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 bn(e,t,n){if(An(e))return t;if("bigint"==typeof e)try{return Number(e)}catch{return t}if("number"==typeof e)return isNaN(e)?t:Math.floor(e);const r=parseInt(String(e),10);return isNaN(r)?t:r}function Nn(e,t=0){if(An(e))return t;if("number"==typeof e)return isNaN(e)?t:e;return Sn(String(e).replace("%","").trim(),t)}function wn(e,t=18){const n=Sn(e,0);if(0===n)return"0";return n.toFixed(t).replace(/\.?0+$/,"")}function kn(e){return wn(e,8)}function _n(e){return wn(e,18)}function In(e,t,n,r){if("number"!=typeof e)throw Qt(r,"a number",e,r);if(e<t||e>n)throw qt(r,t,n,e)}function Dn(e,t,n){if("string"!=typeof e)throw Qt(n,"a string",e,n);if(e.length>t)throw Xt(n,t,e.length)}function Cn(e,t){if("number"!=typeof e)throw Qt(t,"a number",e,t);if(!Number.isInteger(e))throw Qt(t,"an integer",e,t);if(e<=0)throw zt(t,1,e,t)}function Rn(e,t,n=!1){if("string"!=typeof e)throw Qt(t,"a string",e,t);if(!n&&0===e.trim().length)throw Kt(t,`${t} (non-empty string)`)}function On(e,t){if("ASC"!==e&&"DESC"!==e)throw new wt(`${t} must be either 'ASC' or 'DESC'`,t,"INVALID_ENUM_VALUE")}function Mn(e,t,n,r){const s="string"==typeof e?parseFloat(e):e;if(!isFinite(s))throw new wt(`${r} must be a valid finite number between ${t} and ${n}`,r,"INVALID_NUMBER");if(s<t||s>n)throw qt(r,t,n,s,r)}function Ln(e,t,n){const r="string"==typeof e?parseFloat(e):e,s="string"==typeof t?parseFloat(t):t;if(!isFinite(r))throw new wt(`${n} minFee must be a valid finite number`,n,"INVALID_FEE_MINIMUM");if(!isFinite(s))throw new wt(`${n} maxFee must be a valid finite number`,n,"INVALID_FEE_MAXIMUM");if(r<.1)throw new wt(`${n} minFee must be >= 0.1, received ${r}`,n,"INVALID_FEE_MINIMUM");if(s>.5)throw new wt(`${n} maxFee must be <= 0.5, received ${s}`,n,"INVALID_FEE_MAXIMUM");if(r>s)throw new wt(`${n} minFee (${r}) must be <= maxFee (${s})`,n,"INVALID_FEE_RANGE")}function Un(e,t,n,r){const s="string"==typeof e?parseFloat(e):e,i="string"==typeof t?parseFloat(t):t;if(!isFinite(s))throw new wt(`${n} must be a valid finite number`,n,"INVALID_MIN_VALUE");if(!isFinite(i))throw new wt(`${r} must be a valid finite number`,r,"INVALID_MAX_VALUE");if(s>i)throw new wt(`${n} (${s}) must be less than or equal to ${r} (${i})`,n,"INVALID_RANGE")}function Fn(e,t,n){if(!t.includes(e))throw new wt(`${n} must be one of [${t.map(e=>String(e)).join(", ")}], received "${e}"`,n,"INVALID_ENUM_VALUE")}const Pn={ETH_ADDRESS:/^0x[0-9a-fA-F]{40}$/,BACKEND_ADDRESS:/^eth\|(0x)?[0-9a-fA-F]{40}$/,CLIENT_ADDRESS:/^client\|[a-zA-Z0-9_-]+$/},xn=function(e){return"string"==typeof e&&e.trim().length>0},Bn=En,Gn=An;function $n(e,t,n=100,r,s){if(void 0!==s&&"string"!=typeof s)throw new wt("cursor must be a string","cursor",Nt.INVALID_TYPE);const i=r??t,o=void 0!==r?"pageSize":"limit";if(void 0!==i&&(Cn(i,o),i>n))throw new wt(`${o} must be at most ${n}`,o,Nt.TOO_LARGE)}function Kn(e){const t=Object.values(e);return e=>"string"==typeof e&&t.includes(e)}function Hn(e){return Object.values(e)}function Wn(e,t,n){if(!xn(e))throw Kt(t);const r=e.trim();if(0===r.length)throw Kt(t);if(r.length<n.MIN_LENGTH)throw qt(t,n.MIN_LENGTH,n.MAX_LENGTH,r.length,`${t} length`);if(r.length>n.MAX_LENGTH)throw qt(t,n.MIN_LENGTH,n.MAX_LENGTH,r.length,`${t} length`);if(!n.PATTERN.test(r))throw new wt(`${t} must be ${n.DESCRIPTION}`,t,Nt.INVALID_FORMAT)}function Vn(e,t,n){if(null==e)return;if("string"!=typeof e)throw Qt(t,"a string",e);const r=e.trim();if(0!==r.length&&!n.PATTERN.test(r))throw new wt(`${t} must be ${n.DESCRIPTION}`,t,Nt.INVALID_FORMAT)}function jn(e,t){if("string"!=typeof e)return!1;const n=e.trim();return 0!==n.length&&t.PATTERN.test(n)}function qn(e,t,n){if(null==e)throw Kt(t,t);if("string"!=typeof e)throw Qt(t,"a string",e);const r=e.trim();if(0===r.length)throw Kt(t,t);if(!n.PATTERN.test(r))throw new wt(`${t} must be ${n.DESCRIPTION}`,t,Nt.INVALID_FORMAT)}function zn(e){return t=>{if(null==t||"object"!=typeof t)return!1;const n=t;for(const{field:t,type:r,nullable:s=!1,optional:i=!1,validator:o}of e){const e=n[t];if((!i||void 0!==e)&&(!s||null!==e)){if(typeof e!==r)return!1;if(o&&!o(e))return!1}}return!0}}const Xn={requiredString:e=>t=>Gn(t)?`${e} is required`:"string"!=typeof t?`${e} must be a string`:0===t.trim().length?`${e} cannot be empty`:void 0,maxLength:(e,t)=>n=>{if(!Bn(n))return"string"!=typeof n?`${e} must be a string`:n.length>t?`${e} must be at most ${t} characters`:void 0},positiveInteger:e=>t=>{if(!Gn(t))return"number"==typeof t&&Number.isInteger(t)?t<1?`${e} must be a positive integer`:void 0:`${e} must be an integer`},requiredPositiveInteger:e=>t=>Gn(t)?`${e} is required`:"number"==typeof t&&Number.isInteger(t)?t<1?`${e} must be a positive integer`:void 0:`${e} must be an integer`,enumValue:(e,t)=>n=>{if(!Gn(n))return t.includes(n)?void 0:`${e} must be one of: ${t.join(", ")}`},requiredEnumValue:(e,t)=>n=>Gn(n)?`${e} is required`:t.includes(n)?void 0:`${e} must be one of: ${t.join(", ")}`,isoDate:e=>t=>{if(!Gn(t))return"string"!=typeof t?`${e} must be a string`:yn(t)?void 0:`${e} must be a valid ISO 8601 date string`},walletAddress:(e,t=!1)=>n=>{if(Gn(n))return t?`${e} is required`:void 0;if("string"!=typeof n)return`${e} must be a string`;return Pn.ETH_ADDRESS.test(n)||Pn.BACKEND_ADDRESS.test(n)||Pn.CLIENT_ADDRESS.test(n)?void 0:`${e} must be a valid wallet address`}};function Qn(e){return t=>{const n=[],r=t;for(const t of e){const{field:e,required:s,type:i,validator:o}=t,a=r[e];if(s){if(Gn(a)){n.push(`${e} is required`);continue}if("string"===i){if("string"!=typeof a){n.push(`${e} must be a string`);continue}if(0===a.trim().length){n.push(`${e} is required`);continue}}}if(!Gn(a))if(void 0===i||typeof a===i){if(void 0!==o){const e=o(a,r);null!=e&&""!==e&&n.push(e)}}else n.push(`${e} must be a ${i}`)}return n}}function Yn(e){return""===e||0===e.trim().length}function Jn(e,t,n){if(!Gn(e)){if("string"!=typeof e)throw Qt(t,"a string",e,t);if(e.length>n)throw new wt(`${t} must be at most ${n} characters`,t,Nt.TOO_LARGE)}}function Zn(e,t){Gn(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 Qt(t,"a date",e,t);if(isNaN(n.getTime()))throw new wt(`${t} must be a valid date`,t,Nt.INVALID_FORMAT)}(e,t)}function er(e,t,n){try{Cn(e,t)}catch{throw function(e,t,n,r="OPERATION_FAILED"){return new wt(`${e} failed: ${t}`,n,r)}(n,"must be a positive integer",t)}}function tr(e,t,n="status"){void 0!==e&&function(e,t,n){const r=Object.values(t);if(!r.includes(e))throw new wt(`${n} must be one of: ${r.join(", ")}`,n,Nt.INVALID_FORMAT)}(e,t,n)}class nr{constructor(e,t=!1,n){this.http=e,this.logger=new pn({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 Rt("JWT authentication required. Call sdk.login() first.")}return this.jwtAuth.getJwtHeaders()}isCalledFromUserCode(){const e=Ut(new Error)??"";return!(!e.includes("expect")&&!e.includes("jest"))||!(!e.includes("tests/")&&!e.includes(".test.ts"))}validatePositiveInteger(e,t,n){er(e,t,n)}}class rr{constructor(e=!1,t){this.logger=t||new pn({debug:e,context:this.constructor.name})}}class sr extends rr{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 ir extends sr{constructor(e=!1){super(e)}normalizeKey(e){return hn(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>=ir.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??un.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY.toString()}has(e){const t=this.normalizeKey(e);return this.cache.has(t)}clear(e){if(void 0!==e&&""!==e){const t=this.normalizeKey(e);this.cache.delete(t)}else super.clear()}dumpAsObject(){const e={};return this.cache.forEach((t,n)=>{e[n]=t}),e}getStats(){const e=this.buildBaseStats(),{cacheSize:t,oldestEntry:n}=this.calculateCacheSizeAndAge();return{...e,totalTokens:e.totalItems,cacheSize:t,oldestEntry:n}}calculateCacheSizeAndAge(){let e=Date.now(),t=0;return this.cache.forEach((n,r)=>{n.lastUpdated<e&&(e=n.lastUpdated);let s=0;s+=2*r.length,void 0!==n.reverseBondingCurveMinFeeFactor&&(s+=8),void 0!==n.reverseBondingCurveMaxFeeFactor&&(s+=8),void 0!==n.reverseBondingCurveNetFeeFactor&&(s+=8),s+=8,void 0!==n.vaultAddress&&""!==n.vaultAddress&&(s+=2*n.vaultAddress.length),void 0!==n.maxSupply&&""!==n.maxSupply&&(s+=2*n.maxSupply.length),void 0!==n.symbol&&""!==n.symbol&&(s+=2*n.symbol.length),s+=32,t+=s}),{cacheSize:t,oldestEntry:this.cache.size>0?e:0}}getByTokenId(e){const t=`token:${hn(e)}`;return this.cache.get(t)??null}setByTokenId(e,t){const n=`token:${hn(e)}`;this.updateCacheEntry(n,t)}hasByTokenId(e){const t=`token:${hn(e)}`;return this.cache.has(t)}}ir.MAX_CACHE_SIZE=1e4;const or={MIN_LENGTH:1,MAX_LENGTH:20,PATTERN:/^[a-zA-Z0-9]{1,20}$/,DESCRIPTION:"1-20 letters and digits"},ar={MIN_LENGTH:1,MAX_LENGTH:50,PATTERN:/^[a-zA-Z0-9]{1,50}$/,DESCRIPTION:"1-50 letters and digits"},cr={MIN_LENGTH:1,MAX_LENGTH:255,PATTERN:/^[a-zA-Z0-9]{1,255}$/,DESCRIPTION:"1-255 letters and digits"},lr={MIN_LENGTH:1,MAX_LENGTH:50,PATTERN:/^[\s\S]{1,50}$/,DESCRIPTION:"1-50 characters"},dr={MIN_LENGTH:1,MAX_LENGTH:100,PATTERN:/^(?![\s\S]*<[^>]*>)[\s\S]{1,100}$/,DESCRIPTION:"1-100 characters without HTML"},ur=100,hr=100,gr=50,mr={PATTERN:/^(eth\|[0-9a-fA-F]{40}|client\|[a-zA-Z0-9_-]+)$/},fr=100,pr={COMMENTS_V1:{MAX_LENGTH:2e3},CHAT_MESSAGE:{MIN_LENGTH:1,MAX_LENGTH:500},CHAT_MESSAGES_V1:{MAX_LENGTH:500},BAN_REASON:{MAX_LENGTH:500},DESCRIPTION:{MAX_LENGTH:255},FLAG_DETAILS:{MAX_LENGTH:1e3},CONTENT_ID:{MAX_LENGTH:100}},Er={CHAT_MESSAGE:{PATTERN:/^chat-\d{13}-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i},CONTENT_REACTION:{MAX_LENGTH:64,PATTERN:/^(msg-\d{13}-[a-f0-9]{32}|chat-\d{13}-[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})$/}},Ar=60,vr=31536e3,Tr={MAX_LENGTH:64,PATTERN:/^(galaswap-operation-|galaconnect-operation-)/},yr={PATTERN:/^[a-fA-F0-9]{64}$/,MAX_LENGTH:64},Sr=1,br=100,Nr={FULL_NAME:{MIN_LENGTH:2,MAX_LENGTH:20,ALPHABETS_ONLY_PATTERN:/^[a-zA-Z]+(?: [a-zA-Z]+)?$/}},wr={ETHEREUM:Pn.ETH_ADDRESS,ETHEREUM_NO_PREFIX:/^[a-fA-F0-9]{40}$/,BACKEND:Pn.BACKEND_ADDRESS,CLIENT:Pn.CLIENT_ADDRESS};class kr{toBackendFormat(t){if(!xn(t))throw new wt("Address is required and must be a string","address","REQUIRED");let n=t;if(t.startsWith("eth|")){if(n=t.slice(4),!/^[a-fA-F0-9]{40}$/.test(n))throw new wt(`Invalid Ethereum address format in backend address. Expected 40 hex characters after 'eth|'. Got: "${t}"`,"address","INVALID_FORMAT");return t}if(n=Ir(t),!/^[a-fA-F0-9]{40}$/.test(n))throw new wt(`Invalid Ethereum address format. Expected 40 hex characters (with or without 0x prefix). Got: "${t}"`,"address","INVALID_FORMAT");return`eth|${e(`0x${n}`).slice(2)}`}toEthereumFormat(e){if(!xn(e))throw new wt("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 wt(`Invalid backend address format. Expected "eth|{40-hex-characters}" or "eth|0x{40-hex-characters}". Got: "${e}"`,"address","INVALID_FORMAT");const n=t[1],r=void 0!==n&&""!==n?6:4;return`0x${e.substring(r)}`}normalizeInput(e){if(void 0!==e&&""!==e){if(e.startsWith("client|")){if(!wr.CLIENT.test(e))throw new wt(`Invalid client address format: "${e}"`,"address","INVALID_FORMAT");return e}if(e.startsWith("eth|")){if(!wr.BACKEND.test(e))throw new wt(`Invalid backend address format: "${e}"`,"address","INVALID_FORMAT");return e}return this.toBackendFormat(e)}}isValid(e){return!!xn(e)&&(!!wr.ETHEREUM.test(e)||(!!wr.ETHEREUM_NO_PREFIX.test(e)||(!!wr.BACKEND.test(e)||!!wr.CLIENT.test(e))))}assertValid(e,t="address"){if(!this.isValid(e))throw new wt(`${t} must be a valid wallet address (Ethereum or backend format)`,t,"INVALID_FORMAT")}detectFormat(e){return xn(e)?wr.ETHEREUM.test(e)||wr.ETHEREUM_NO_PREFIX.test(e)?"ethereum":wr.BACKEND.test(e)?"backend":wr.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 Ir(e).toLowerCase();if(/^[a-fA-F0-9]{40}$/.test(e))return e.toLowerCase();throw new wt(`Cannot extract hex from address: "${e}". Expected Ethereum or backend format.`,"address","INVALID_FORMAT")}}const _r=new kr;function Ir(e){return e.startsWith("0x")?e.slice(2):e}function Dr(e){return _r.toBackendFormat(e)}function Cr(e){return _r.toEthereumFormat(e)}function Rr(e){return _r.normalizeInput(e)}function Or(e){return _r.isValid(e)}const Mr=/^(eth\|[a-f0-9]{40}|client\|[a-f0-9]{24})$/;function Lr(e){if(!xn(e))return!1;const t=e.toLowerCase().trim();if(t.startsWith("eth|")||t.startsWith("client|")||t.startsWith("service|"))return Mr.test(t.replace(/0x/g,""));const n=t.replace(/^0x/,"");return Mr.test(/^[0-9a-f]{24}$/.test(n)?`client|${n}`:`eth|${n}`)}function Ur(e,t){if(!Lr(e))throw new wt(`${t} must be a GalaChain user address (eth|<40 hex>, 0x<40 hex> or client|<24 hex>)`,t,"INVALID_FORMAT")}function Fr(e,t="address"){_r.assertValid(e,t)}function Pr(e){const t="string"==typeof e?e:e.address;return _r.toBackendFormat(t)}var xr=Object.freeze({__proto__:null,AddressFormatter:kr,assertBackendUserAddress:Ur,assertValidWalletAddress:Fr,fromBackendAddressFormat:Cr,isBackendUserAddress:Lr,isValidAddress:Or,normalizeAddressInput:Rr,stripHexPrefix:Ir,toBackendAddressFormat:Dr,toBackendAddressFromEthers:Pr});const Br=T.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"),Gr=Br.max(20,"Token name must be at most 20 characters"),$r=T.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"),Kr=T.string({message:"Token symbol is required"}).min(1,"Token symbol must be at least 1 character").max(8,"Token symbol must be at most 8 characters").regex(/^[A-Z]{1,8}$/,"Token symbol must be uppercase letters only"),Hr=T.string({message:"Token description is required"}).min(1,"Token description is required").max(500,"Token description must be at most 500 characters"),Wr=T.string().min(1,"Token name must be at least 1 character").max(50,"Token name must be at most 50 characters"),Vr=T.string().min(1,"Search query must be at least 1 character").max(100,"Search query must be at most 100 characters"),jr=T.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"),qr=T.string().regex(Pn.BACKEND_ADDRESS,"Address must be in format: eth|[40-hex-chars]"),zr=T.string().regex(Pn.ETH_ADDRESS,"Invalid Ethereum address format"),Xr=T.string().refine(e=>Pn.BACKEND_ADDRESS.test(e)||Pn.ETH_ADDRESS.test(e)||Pn.CLIENT_ADDRESS.test(e),"Address must be eth|[40-hex], 0x[40-hex], or client|[identifier] format").transform(e=>(new kr).normalizeInput(e)??e),Qr=T.string().refine(e=>Pn.BACKEND_ADDRESS.test(e)||/^service\|Token\$Unit\$[A-Z0-9]+\$eth:[0-9a-fA-F]{40}\$launchpad$/.test(e),"Invalid vault address format"),Yr=T.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>Sn(e,0)>0,"Amount must be greater than zero"),Jr=T.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>Sn(e,0)>=0,"Amount must be zero or greater"),Zr=T.string().url("Must be a valid URL").regex(/^https?:\/\//,"URL must start with http:// or https://"),es=T.string().optional().refine(e=>void 0===e||""===e||/^https?:\/\/.+\..+/.test(e),"Must be a valid URL if provided"),ts=T.number().int("Page must be an integer").min(1,"Page must be at least 1").max(1e3,"Page must be at most 1000").default(1);function ns(e=100){return T.number().int("Limit must be an integer").min(1,"Limit must be at least 1").max(e,`Limit must be at most ${e}`).default(10)}const rs=ns(100),ss=ns(20),is=ns(20),os=T.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"),as=T.string().max(255,"Filename must be at most 255 characters"),cs=T.enum(["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"]),ls=T.string().datetime("Must be a valid ISO 8601 date string"),ds=T.number().int("Timestamp must be an integer").min(0,"Timestamp must be non-negative"),us=T.string().regex(/^0x[a-fA-F0-9]{64}$/,"Private key must be format: 0x + 64 hex characters"),hs=T.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"),gs=T.string().regex(/^galaconnect-operation-[a-z0-9-]+$/,"Unique key must be format: galaconnect-operation-{unique-id}"),ms=[".png",".jpg",".jpeg",".gif",".webp",".svg"],fs=T.object({file:T.union([T.instanceof(File),T.instanceof(Buffer)]),name:as,size:os,type:cs}),ps=T.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"),Es=T.instanceof(Buffer).refine(e=>e.length>=1&&e.length<=10485760,"Buffer size must be between 1 byte and 10MB"),As=T.union([ps,Es]),vs=T.enum([".png",".jpg",".jpeg",".gif",".webp",".svg"]),Ts=as.refine(e=>{const t=e.slice(e.lastIndexOf(".")).toLowerCase();return ms.includes(t)},`Filename must end with one of: ${ms.join(", ")}`),ys=T.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"),Ss=T.string().min(1,"Token category must not be empty").default("Unit"),bs=T.string().min(1,"Token collection must not be empty").default("Token"),Ns=T.object({minFeePortion:T.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal string").refine(e=>Sn(e,0)>=.1,"Minimum fee must be >= 0.1").refine(e=>Sn(e,0)<=.5,"Minimum fee must be <= 0.5").default("0.1"),maxFeePortion:T.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal string").refine(e=>Sn(e,0)>=.1,"Maximum fee must be >= 0.1").refine(e=>Sn(e,0)<=.5,"Maximum fee must be <= 0.5").default("0.5")}).refine(e=>Sn(e.maxFeePortion,0)>=Sn(e.minFeePortion,0),{message:"Maximum fee must be >= minimum fee",path:["maxFeePortion"]}),ws=T.object({tokenName:Br,tokenSymbol:Kr,tokenDescription:Hr,tokenImage:T.union([T.instanceof(File),T.instanceof(Buffer),T.string().url("Token image must be a valid URL")]).optional(),preBuyQuantity:Jr.default("0"),websiteUrl:es,telegramUrl:es,twitterUrl:es,instagramUrl:es,facebookUrl:es,redditUrl:es,tiktokUrl:es,tokenCategory:Ss,tokenCollection:bs,reverseBondingCurveConfiguration:Ns.optional(),saleStartTime:T.number().int().positive().optional(),privateKey:us.optional()}),ks=T.object({file:T.union([T.instanceof(File),T.instanceof(Buffer)]),tokenName:Br}),_s=T.enum(Tt),Is=T.object({tokenName:$r.optional(),symbol:Kr.optional()}).refine(e=>void 0!==e.tokenName||void 0!==e.symbol,"At least one of tokenName or symbol is required"),Ds=T.enum(["NATIVE","MEME"]),Cs=T.enum(["IN","OUT"]),Rs=T.object({from:T.number().int("From timestamp must be an integer").min(173e6,"From timestamp must be at least 173000000"),to:T.number().int("To timestamp must be an integer").min(173e6,"To timestamp must be at least 173000000"),resolution:T.number().int("Resolution must be an integer").min(1,"Resolution must be at least 1"),tokenName:Gr}),Os=T.object({tokenName:Gr,slippageToleranceFactor:T.number().min(0).max(1).optional(),maxAcceptableReverseBondingCurveFeeSlippageFactor:T.number().min(0).max(1).optional(),privateKey:us.optional()}),Ms=T.object({offset:T.number().int().min(0).default(0),pageSize:T.number().int().min(1).max(100).default(10)}),Ls=T.object({offset:T.number().int().min(0).default(0),pageSize:T.number().int().min(1).max(20).default(10)}),Us=T.object({offset:T.number().int().min(0).default(0),pageSize:T.number().int().min(1).max(20).default(10)}),Fs=Ms.extend({type:T.enum(["RECENT","POPULAR"]).optional(),tokenName:T.string().min(1).max(50).optional(),search:T.string().min(1).max(100).optional()}),Ps=Ls.extend({tokenName:T.string().min(1).max(50).optional(),search:T.string().min(1).max(100).optional()}),xs=Us.extend({tradeType:T.enum(["BUY","SELL"]).optional(),tokenName:T.string().min(1).max(50).optional(),userAddress:T.string().regex(/^(0x[a-fA-F0-9]{40}|eth\|[a-fA-F0-9]{40})$/).optional(),startDate:T.string().datetime().optional(),endDate:T.string().datetime().optional(),sortOrder:T.enum(["ASC","DESC"]).default("DESC")}),Bs={page:T.number().int().min(1),limit:T.number().int().min(1),total:T.number().int().min(0),totalPages:T.number().int().min(0),hasNext:T.boolean(),hasPrevious:T.boolean()},Gs=T.object(Bs);function $s(e){return T.object({data:T.array(e),...Bs})}const Ks=T.enum(["buy","sell"]),Hs=T.enum(["BUY","SELL"]),Ws=T.object({tradeType:Ks,tokenAmount:Yr,vaultAddress:Qr,userAddress:Xr,slippageTolerance:Yr.optional(),deadline:T.number().int().positive().optional()}),Vs=T.object({tokenSymbol:Kr,nativeTokenQuantity:Yr,expectedToken:Yr,maxAcceptableReverseBondingCurveFee:Jr.default("0").optional()}),js=T.object({tokenSymbol:Kr,tokenQuantity:Yr,expectedNativeToken:Yr,maxAcceptableReverseBondingCurveFee:Jr.default("0").optional()}),qs=Us.extend({tokenName:Wr.optional()}),zs=T.object({page:T.number().int().min(1).max(1e3).default(1).optional(),limit:T.number().int().min(1).max(20).default(10).optional()}),Xs=T.enum(["NATIVE","MEME"]),Qs=T.enum(["IN","OUT"]),Ys=T.object({type:Xs,method:Qs,vaultAddress:Qr,amount:Yr}),Js=T.object({nativeTokenQuantity:Yr}),Zs=T.object({vaultAddress:Qr}),ei=T.object({minFeePortion:Yr,maxFeePortion:Yr}),ti=T.enum(["both","held","created"]),ni=Ls.extend({type:ti.optional(),address:Xr.optional(),search:Vr.optional(),tokenName:Wr.optional()}),ri=T.object({address:Xr.optional(),refresh:T.boolean().optional()}),si=T.object({profileImage:T.string().nullable().optional(),fullName:jr.optional(),address:Xr.optional(),privateKey:us.optional()}),ii=T.object({file:T.union([T.instanceof(File),T.instanceof(Buffer)]),address:Xr.optional(),privateKey:us.optional()}),oi=T.object({address:Xr,tokenId:T.union([T.string(),T.object({collection:T.string(),category:T.string(),type:T.string(),additionalKey:T.string()}),T.object({collection:T.string(),category:T.string(),type:T.string(),additionalKey:T.string(),instance:T.string()})]).optional(),tokenName:Wr.optional(),withExpired:T.boolean().optional()}).refine(e=>void 0!==e.tokenId||void 0!==e.tokenName,"At least one token identifier (tokenId or tokenName) is required");function ai(e){return t=>{const n=e.safeParse(t);return{success:n.success,data:n.success?n.data:void 0,errors:n.success?void 0:n.error.issues.map(e=>e.message)}}}const ci=ai(Br),li=ai(Kr),di=ai(Hr),ui=ai(Xr),hi=ai(Qr),gi=ai(Yr),mi=ai(jr),fi=ai(Vr),pi=ai(Wr),Ei=ai(ws),Ai=ai(ys),vi=ai(ks),Ti=ai(Is),yi=ai(ni),Si=ai(ri),bi=ai(si),Ni=ai(ii),wi=ai(oi),ki=ai(Ws),_i=ai(Vs),Ii=ai(js),Di=ai(qs),Ci=ai(zs),Ri=ai(Ys),Oi=ai(Js),Mi=ai(Zs);function Li(e){return Ei(e).success}function Ui(e){const t=Ei(e);return t.success?[]:t.errors??["Unknown validation error"]}function Fi(e){const t=Ui(e);if(t.length>0)throw new Error(`LaunchTokenData validation failed:\n${t.map(e=>`- ${e}`).join("\n")}`)}function Pi(e,t){return"string"==typeof e[t]}function xi(e,t){return void 0===e[t]||"string"==typeof e[t]}function Bi(e,t){return void 0===e[t]||"number"==typeof e[t]}function Gi(e,t){switch(t){case"string":return"string"==typeof e;case"number":return"number"==typeof e;case"boolean":return"boolean"==typeof e;case"object":return null!==e&&"object"==typeof e&&!Array.isArray(e);case"array":return Array.isArray(e);case"optional-string":return void 0===e||"string"==typeof e;case"optional-number":return void 0===e||"number"==typeof e;case"optional-boolean":return void 0===e||"boolean"==typeof e;case"optional-object":return void 0===e||null!==e&&"object"==typeof e&&!Array.isArray(e);case"optional-array":return void 0===e||Array.isArray(e);default:return!1}}function $i(e){return t=>{if(null==t||"object"!=typeof t||Array.isArray(t))return!1;const n=t;for(const[t,r]of Object.entries(e)){if(!Gi(n[t],r))return!1}return!0}}Kn({BUY:"buy",SELL:"sell"});const Ki=$i({nativeTokenQuantity:"string"});function Hi(e,t="0"){return function(e,t="0"){if(En(e))return new _(t);if(_.isBigNumber(e))return e.isNaN()?new _(t):e;try{const n=new _(e);return n.isNaN()||!n.isFinite()?new _(t):n}catch{return new _(t)}}(e,t)}function Wi(e,t){return void 0!==t?Hi(e).toFixed(t):Hi(e).toFixed()}function Vi(e){const t=Hi(e),n=Math.log(1.0001),r=t.toNumber();return Math.log(r)/n}function ji(e){return Hi(e).isZero()}function qi(e,t){return Hi(e).isLessThan(Hi(t))}function zi(...e){e.forEach(e=>{if(e.isNaN())throw Yt("value","NaN");if(!e.isFinite())throw Xt("value","finite");if(e.isLessThanOrEqualTo(0))throw zt("value","0",e.toString())})}function Xi(...e){e.forEach(e=>{if(e.isNaN())throw Yt("value","NaN");if(!e.isFinite())throw Xt("value","finite");if(e.isLessThan(0))throw zt("value","0",e.toString())})}function Qi(e,t,n){if(e.isNaN())throw Yt(t,"NaN");if(!e.isFinite())throw Xt(t,"finite");if(e.isLessThanOrEqualTo(0))throw zt(t,"0",e.toString())}function Yi(e,t,n="0"){const r=Hi(t);return ji(r)?Hi(n):Hi(e).dividedBy(r)}const Ji={calculateBuyWithExact(e,t){const n=Sn(e),r=Sn(t),{BASE_PRICE:s,PRICE_SCALING_FACTOR:i,TRADING_FEE_FACTOR:o,GAS_FEE:a}=un,c=function(e,t){const n=Math.pow(10,t);return Math.ceil(e*n)/n}(s*(Math.exp((r+n)*i)-Math.exp(r*i))/i,8),l=Wi(Hi(c).multipliedBy(o));return{amount:c.toString(),reverseBondingCurveFee:"0",transactionFee:l,gasFee:a}},calculateBuyWithNative(e,t){const n=Sn(e),r=Sn(t),{BASE_PRICE:s,PRICE_SCALING_FACTOR:i,TRADING_FEE_FACTOR:o,GAS_FEE:a}=un,c=Math.log(n*i/s+Math.exp(r*i))/i-r,l=Wi(Hi(c).multipliedBy(o));return{amount:c.toString(),reverseBondingCurveFee:"0",transactionFee:l,gasFee:a}},calculateSellWithExact(e,t,n,r,s){const i=Sn(e),o=Sn(t),a=Sn(n),{BASE_PRICE:c,PRICE_SCALING_FACTOR:l,TRADING_FEE_FACTOR:d,GAS_FEE:u}=un,h=c*(Math.exp(o*l)-Math.exp((o-i)*l))/l,g=Hi(h),m=r+o/a*(s-r),f=Wi(g.multipliedBy(m),8),p=Wi(g.multipliedBy(d));return{amount:h.toString(),reverseBondingCurveFee:f,transactionFee:p,gasFee:u}},calculateSellWithNative(e,t,n,r,s){const i=Sn(e),o=Sn(t),a=Sn(n),{BASE_PRICE:c,PRICE_SCALING_FACTOR:l,TRADING_FEE_FACTOR:d,GAS_FEE:u}=un;if(i>=c*(Math.exp(o*l)-1)/l){const e=Hi(i),t=r+o/a*(s-r),n=Wi(e.multipliedBy(t),8),c=Wi(e.multipliedBy(d));return{amount:o.toString(),reverseBondingCurveFee:n,transactionFee:c,gasFee:u}}const h=o-Math.log(Math.exp(o*l)-i*l/c)/l,g=Hi(i),m=r+o/a*(s-r),f=Wi(g.multipliedBy(m),8),p=Wi(g.multipliedBy(d));return{amount:h.toString(),reverseBondingCurveFee:f,transactionFee:p,gasFee:u}}};function Zi(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function eo(e,t){if(!function(e){if(!Zi(e)||"string"!=typeof e.calculatedQuantity)return!1;const t=e.extraFees;return Zi(t)&&"string"==typeof t.reverseBondingCurve&&"string"==typeof t.transactionFees}(e))throw Wt(`Malformed trade quote from the launchpad backend (${t})`);return{amount:e.calculatedQuantity,reverseBondingCurveFee:e.extraFees.reverseBondingCurve,transactionFee:e.extraFees.transactionFees,gasFee:un.GAS_FEE}}class to{validate(e,t={}){const{allowZero:n=!0,minimum:r,maximum:s,maxDecimals:i=to.MAX_DECIMAL_PLACES,fieldName:o="amount"}=t;if(!xn(e))throw new wt(`${o} cannot be empty or whitespace-only. Provide a valid numeric string.`,o,"INVALID_NUMERIC_STRING");if(/[eE]/.test(e))throw new wt(`${o} cannot use scientific notation. Use standard decimal format (e.g., "1000" instead of "1e3").`,o,"INVALID_NUMERIC_STRING");const a=Sn(e,NaN);if(isNaN(a))throw new wt(`${o} must be a valid numeric string. Received: "${e}"`,o,"INVALID_NUMERIC_STRING");if(!isFinite(a))throw new wt(`${o} must be a finite number. Cannot be Infinity or -Infinity.`,o,"INVALID_NUMERIC_STRING");if(a<0)throw new wt(`${o} must be non-negative. Received: "${e}"`,o,"INVALID_NUMERIC_STRING");if(!n&&0===a)throw new wt(`${o} must be greater than zero. Received: "${e}"`,o,"INVALID_NUMERIC_STRING");const c=Hi(e),l=c.decimalPlaces()??0;if(l>i)throw new wt(`${o} cannot exceed ${i} decimal places. Received: ${l} decimal places`,o,"PRECISION_EXCEEDED");if(void 0!==r&&qi(c,r))throw new wt(`${o} must be at least ${r}. Received: "${e}"`,o,"BELOW_MINIMUM");if(void 0!==s&&(d=s,Hi(c).isGreaterThan(Hi(d))))throw new wt(`${o} cannot exceed ${s}. Received: "${e}"`,o,"EXCEEDS_MAXIMUM");var d}parseAmount(e,t="0"){return Hi(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 Wi(e,t)}clampAmount(e,t,n){const r=Hi(e),s=Hi(t),i=Hi(n);return function(e,t,n){const r=Hi(e),s=Hi(t),i=Hi(n);return r.isGreaterThanOrEqualTo(s)&&r.isLessThanOrEqualTo(i)}(r,s,i)?Wi(r):qi(r,s)?Wi(s):Wi(i)}}function no(e,t){throw new wt(e.join("; "),t,"VALIDATION_ERROR")}function ro(e){const t=ci(e);!t.success&&t.errors&&no(t.errors,"tokenName")}function so(e){const t=Rs.safeParse(e);var n;t.success||no((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 io(e,t,n=!0){oo.validate(e,{fieldName:t,allowZero:n})}to.MAX_DECIMAL_PLACES=18,to.MIN_POSITIVE="0.00000000000000001";const oo=new to;class ao{constructor(e,t,n,r="local",s){this.http=e,this.logger=t,this.bundleHttp=n,this.defaultCalculateAmountMode=r,this.launchpadWrites=s,this.metadataCache=new ir}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 Ht("options","an options object");const{tokenName:t,amount:n,type:r,currentSupply:s}=e;return"external"===this.validateAmountCalculationInputs(t,n,r,e.mode,[At.NATIVE,At.EXACT],'"native" or "exact"')?this.calculateBuyAmountExternal({tokenName:t,amount:n,type:r}):this.calculateBuyAmountLocal(this.addIfDefined({tokenName:t,amount:n,type:r},"currentSupply",s))}async calculateBuyAmountExternal(e){const{tokenName:t,amount:n,type:r}=e;return this.validateExternalAmountInputs(t,n),"exact"===r?this.fetchBackendQuote({tokenName:t,amount:n,type:"MEME",method:"OUT"},`Failed to calculate buy amount for ${t} (exact tokens)`):this.fetchBackendQuote({tokenName:t,amount:n,type:"NATIVE",method:"IN"},`Failed to calculate buy amount for ${t} (native/GALA budget)`)}async fetchBackendQuote(e,t){return eo(await an(()=>this.http.get(dt,{...e}),{errorContext:t}),t)}async calculateSellAmount(e){const{tokenName:t,amount:n,type:r,currentSupply:s,maxSupply:i,reverseBondingCurveMaxFeeFactor:o,reverseBondingCurveMinFeeFactor:a}=e;if("external"===this.validateAmountCalculationInputs(t,n,r,e.mode,[At.EXACT,At.NATIVE],'"exact" or "native"'))return this.calculateSellAmountExternal({tokenName:t,amount:n,type:r});{const e={tokenName:t,amount:n,type:r,...void 0!==s&&{currentSupply:s},...void 0!==i&&{maxSupply:i},...void 0!==o&&{reverseBondingCurveMaxFeeFactor:o},...void 0!==a&&{reverseBondingCurveMinFeeFactor:a}};return this.calculateSellAmountLocal(e)}}async calculateSellAmountExternal(e){const{tokenName:t,amount:n,type:r}=e;return this.validateExternalAmountInputs(t,n),"exact"===r?this.fetchBackendQuote({tokenName:t,amount:n,type:"MEME",method:"IN"},`Failed to calculate sell amount for ${t} (exact tokens)`):this.fetchBackendQuote({tokenName:t,amount:n,type:"NATIVE",method:"OUT"},`Failed to calculate sell amount for ${t} (native/GALA target)`)}async calculateBuyAmountLocal(e){const{tokenName:t,amount:n,type:r,currentSupply:s}=e;if(!xn(n))throw Kt("amount","Amount");if(r!==At.NATIVE&&r!==At.EXACT)throw Qt("type",'"native" or "exact"',r);void 0!==s&&io(s,"currentSupply");const i=null==s||""===s;if(i&&(null==t||""===t))throw Kt("tokenName","Token name (required when currentSupply is not provided)");null!=t&&""!==t&&ro(t);let o=s;if(i){o=(await this.fetchPoolDetailsForCalculation(t)).currentSupply}return r===At.EXACT?Ji.calculateBuyWithExact(n,o):Ji.calculateBuyWithNative(n,o)}async calculateSellAmountLocal(e){const{tokenName:t,amount:n,type:r,currentSupply:s,maxSupply:i,reverseBondingCurveMaxFeeFactor:o,reverseBondingCurveMinFeeFactor:a}=e;if(!xn(n))throw Kt("amount","Amount");if(r!==At.EXACT&&r!==At.NATIVE)throw Qt("type",'"exact" or "native"',r);void 0!==s&&io(s,"currentSupply");const c=null==s||""===s||null==i||""===i||void 0===o||void 0===a;if(c&&(null==t||""===t))throw Kt("tokenName","Token name (required when currentSupply, maxSupply, or fee factors are not provided)");null!=t&&""!==t&&ro(t);let l=s,d=i,u=o,h=a;if(c&&null!=t&&""!==t){const e=this.metadataCache.getByName(t);d=d??this.metadataCache.getMaxSupply(t),u=u??e?.reverseBondingCurveMaxFeeFactor,h=h??e?.reverseBondingCurveMinFeeFactor,null!=l&&""!==l||(l=await this.fetchCurrentSupply(t));if(void 0===u||void 0===h){const e=await this.fetchPoolDetailsForCalculation(t);u=u??e.reverseBondingCurveMaxFeeFactor,h=h??e.reverseBondingCurveMinFeeFactor}}return r===At.EXACT?Ji.calculateSellWithExact(n,l,d,h,u):Ji.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 Pi(t,"tokenName")&&function(e){return void 0===e.calculateAmountMode||"local"===e.calculateAmountMode||"external"===e.calculateAmountMode}(t)&&xi(t,"currentSupply")}(e))throw Qt("options","CalculateBuyAmountForGraduationOptions or string (token name)",typeof e);const{tokenName:n,calculateAmountMode:r,currentSupply:s}=t;ro(n);const i=await this.fetchSaleDetails(n),o=s??Wi(Hi(i.maxSupply).minus(i.sellingTokenQuantity)),a=i.sellingTokenQuantity;if("0"===a)throw Kt("tokenName",`Token ${n} is already graduated (no tokens remaining in pool)`);const c={tokenName:n,amount:a,type:"exact",currentSupply:o,...void 0!==r&&{mode:r}};return{...await this.calculateBuyAmount(c),remainingTokens:a}}async launchToken(e){if(void 0!==this.launchpadWrites){return(await this.launchpadWrites.createSale(e)).bundleId}if(!this.bundleHttp)throw Vt("Bundle backend client not configured. LaunchToken requires bundleHttp client.","bundleHttp");Fi(e);const t=void 0!==e.preBuyQuantity&&""!==e.preBuyQuantity?e.preBuyQuantity:"0",n=Sn(t);if(0===n&&"0"!==t)throw Yt("preBuyQuantity",t,"Pre-buy quantity");if(n<0)throw Yt("preBuyQuantity",t,"Pre-buy quantity");if(e.reverseBondingCurveConfiguration){const{minFeePortion:t,maxFeePortion:n}=e.reverseBondingCurveConfiguration;Ln(t,n,"reverseBondingCurve")}throw new Error("Legacy launchToken signing is unavailable; configure the v6 launchpad write transport.")}async calculateInitialBuyAmount(e){if(!Ki(e))throw Ht("data","valid pre-mint calculation data");const t="Failed to calculate initial buy amount";return eo(await an(()=>this.http.get(ut,{amount:e.nativeTokenQuantity}),{errorContext:t}),t)}async fetchPoolDetailsForCalculation(e){const t=await this.fetchSaleDetails(e),n=Wi(Hi(t.maxSupply).minus(t.sellingTokenQuantity)),r=t.sellingTokenQuantity,s=t.maxSupply;let i=.5,o=.1;const a=t.reverseBondingCurveConfiguration;null!=a?.maxFeePortion&&(i=Nn(a.maxFeePortion,.5)),null!=a?.minFeePortion&&(o=Nn(a.minFeePortion,.1)),void 0===a&&this.logger.debug(`Pool details missing reverse bonding curve configuration for token ${e}, using defaults (min: 0.1, max: 0.5)`);const c=i-o;return this.metadataCache.set(e,{maxSupply:s,reverseBondingCurveMaxFeeFactor:i,reverseBondingCurveMinFeeFactor:o,reverseBondingCurveNetFeeFactor:c}),{currentSupply:n,remainingTokens:r,maxSupply:s,reverseBondingCurveMaxFeeFactor:i,reverseBondingCurveMinFeeFactor:o,reverseBondingCurveNetFeeFactor:c}}async fetchCurrentSupply(e){ro(e);const t=await this.fetchSaleDetails(e),n=Wi(Hi(t.maxSupply).minus(t.sellingTokenQuantity)),r=t.maxSupply;return this.metadataCache.set(e,{maxSupply:r}),n}async fetchPoolDetails(e){ro(e);const t=await this.fetchSaleDetails(e),{reverseBondingCurveConfiguration:n,...r}=t,s=n?.minFeePortion??"0",i=n?.maxFeePortion??"0";return{...r,reverseBondingCurveMinFeePortion:s,reverseBondingCurveMaxFeePortion:i,hasReverseBondingCurveFee:!ji(s)||!ji(i),isGraduated:"Finished"===t.saleStatus}}async fetchSaleDetails(e){return Wn(e,"tokenName",or),an(()=>this.http.get(lt,{tokenName:e}),{errorContext:`Failed to fetch sale details for ${e}`})}validateAmountCalculationInputs(e,t,n,r,s,i){const o=r??this.defaultCalculateAmountMode;if("local"!==o&&"external"!==o)throw Qt("mode",'"local" or "external"',o);if(!xn(e))throw Kt("tokenName","Token name");if(!xn(t))throw Kt("amount","Amount");if("string"!=typeof n||!s.includes(n))throw Qt("type",i,n);return o}validateExternalAmountInputs(e,t){if("string"!=typeof e||""===e)throw new wt("Token name must be a non-empty string","tokenName","INVALID_TOKEN_NAME");if("string"!=typeof t||""===t)throw new wt("Amount must be a non-empty string","amount","INVALID_AMOUNT")}getAddress(){return this.http.getAddress()}formatAddressForBackend(e){return Dr(e)}validateTokenName(e){return ro(e)}validatePagination(e){void 0!==e.pageSize&&$n(0,void 0,100,e.pageSize)}warmCacheFromPoolData(e,t){this.metadataCache.warmFromPoolData(e,t)}getCacheStats(){return this.metadataCache.getStats()}clearCache(e){this.metadataCache.clear(e)}}const co={REFRESH_THRESHOLD_MS:3e5,DEFAULT_EXPIRY_S:86400,LOGIN_MESSAGE_PREFIX:"Sign in to Launchpad t:",AUTH_HEADER:"Authorization",BEARER_PREFIX:"Bearer "};class lo{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 uo;!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"}(uo||(uo={}));class ho extends Error{constructor(e,t,n,r){super(t),this.type=e,this.originalError=n,this.statusCode=r,this.name="AuthError"}}class go{constructor(e,t=co.REFRESH_THRESHOLD_MS){this.tokenState=null,this.STORAGE_KEYS={ACCESS_TOKEN:"lpad_access_token",ACCESS_EXPIRES:"lpad_access_expires",REFRESH_TOKEN:"lpad_refresh_token",REFRESH_EXPIRES:"lpad_refresh_expires"},this.storage=e??new lo,this.refreshThresholdMs=t}setToken(e,t){if(!xn(e))throw new ho(uo.SIGNATURE_FAILED,"JWT token must be a non-empty string");if("number"!=typeof t)throw new ho(uo.SIGNATURE_FAILED,"Token expiration must be a positive finite number (seconds)");if(!Number.isFinite(t))throw new ho(uo.SIGNATURE_FAILED,"Token expiration must be a positive finite number (seconds)");if(t<=0)throw new ho(uo.SIGNATURE_FAILED,"Token expiration must be a positive finite number (seconds)");const n=Date.now();this.tokenState={token:e.trim(),issuedAt:n,expiresAt:n+1e3*t},this.storage.set(this.STORAGE_KEYS.ACCESS_TOKEN,e.trim()),this.storage.set(this.STORAGE_KEYS.ACCESS_EXPIRES,String(this.tokenState.expiresAt))}async setTokens(e,t,n,r){if(this.setToken(e,t),n){const e=Date.now()+1e3*(r??7776e3);if(!this.tokenState)throw new ho(uo.SIGNATURE_FAILED,"Access token must be set before refresh token");this.tokenState.refreshToken=n.trim(),this.tokenState.refreshExpiresAt=e,await this.storage.set(this.STORAGE_KEYS.REFRESH_TOKEN,n.trim()),await this.storage.set(this.STORAGE_KEYS.REFRESH_EXPIRES,String(e))}}getToken(){return this.tokenState?.token??null}hasToken(){return null!==this.tokenState}isExpired(){return!this.tokenState||Date.now()>=this.tokenState.expiresAt}shouldRefresh(e){if(!this.tokenState)return!1;const t=e??this.refreshThresholdMs,n=this.tokenState.expiresAt-Date.now();return n>0&&n<=t}getTimeUntilExpiry(){if(!this.tokenState)return 0;const e=this.tokenState.expiresAt-Date.now();return Math.max(0,e)}getExpiresAt(){return this.tokenState?.expiresAt??null}getAuthorizationHeader(){const e=this.getToken();return null===e||""===e?null:`${co.BEARER_PREFIX}${e}`}getJwtHeaders(){const e=this.getAuthorizationHeader();if(null===e||""===e)throw new ho(uo.WALLET_NOT_CONNECTED,"No JWT token available. Call login() first.");return{[co.AUTH_HEADER]:e}}async getRefreshToken(){if(!this.tokenState?.refreshToken){const e=await this.storage.get(this.STORAGE_KEYS.REFRESH_TOKEN),t=await this.storage.get(this.STORAGE_KEYS.REFRESH_EXPIRES);if(e&&t){const n=Number(t);if(Number.isFinite(n)&&Date.now()<n)return e}return null}return null!==this.tokenState.refreshExpiresAt&&void 0!==this.tokenState.refreshExpiresAt&&(!Number.isFinite(this.tokenState.refreshExpiresAt)||Date.now()>=this.tokenState.refreshExpiresAt)?null:this.tokenState.refreshToken??null}async restoreFromStorage(){const e=await this.storage.get(this.STORAGE_KEYS.ACCESS_TOKEN),t=await this.storage.get(this.STORAGE_KEYS.ACCESS_EXPIRES);if(!e||!t)return!1;const n=Number(t);if(!Number.isFinite(n)||Date.now()>=n)return!1;const r=Date.now();this.tokenState={token:e,issuedAt:r,expiresAt:n};const s=await this.storage.get(this.STORAGE_KEYS.REFRESH_TOKEN),i=await this.storage.get(this.STORAGE_KEYS.REFRESH_EXPIRES);if(s&&i){const e=Number(i);Number.isFinite(e)&&Date.now()<e&&(this.tokenState.refreshToken=s,this.tokenState.refreshExpiresAt=e)}return!0}async clear(){this.tokenState=null,await this.storage.remove(this.STORAGE_KEYS.ACCESS_TOKEN),await this.storage.remove(this.STORAGE_KEYS.ACCESS_EXPIRES),await this.storage.remove(this.STORAGE_KEYS.REFRESH_TOKEN),await this.storage.remove(this.STORAGE_KEYS.REFRESH_EXPIRES)}isValid(){return this.hasToken()&&!this.isExpired()}getDebugInfo(){return{hasToken:this.hasToken(),isExpired:this.isExpired(),shouldRefresh:this.shouldRefresh(),timeUntilExpiryMs:this.getTimeUntilExpiry(),expiresAt:this.tokenState?new Date(this.tokenState.expiresAt):null}}}class mo extends go{getJwtHeaders(){return{}}}async function fo(e,t,n,r){try{return await e()}catch(e){throw r?(r(e,t,n),new Error("Unreachable after error handler")):(n&&n.error(`${t}:`,e),function(e,t,n){n&&n.error(`${t}:`,e);const r=(Pt(e)?e.response?.status:void 0)??(e instanceof Ct?e.statusCode:void 0);return Wt(`${t}: ${Lt(e)}`,r,Mt(e)?e:void 0)}(e,t,n))}}function po(e,t){return t instanceof ho?t:new ho(uo.SIGNATURE_FAILED,`${e}: ${Lt(t)}`,Mt(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 Eo{constructor(e,t,n,r=!1,s){this.http=e,this.signatureAuth=t,this.jwtAuth=n,this.session=s,this.refreshPromise=null,this.loginPromise=null,this.logger=new pn({debug:r,context:"SessionAuthService"})}async loginWithSignature(e){if(Fr(e.address,"address"),!xn(e.message)||!xn(e.signature))throw new ho(uo.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 Fr(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:J,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 po("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 ho(uo.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 fo(async()=>{const e=Date.now(),t=`${co.LOGIN_MESSAGE_PREFIX}${e}`;this.logger.debug("Generating login signature",{message:t,timestamp:e});const n=await this.signatureAuth.signMessage(t),r=this.signatureAuth.getAddress();Fr(r,"address");const s={address:r,message:t,signature:n.signature};this.logger.debug("Sending login request",{address:r,message:t});const i=await this.http.post(J,s),o=this.extractLoginData(i);return await this.jwtAuth.setTokens(o.accessToken,o.expiresIn,o.refreshToken,o.refreshExpiresIn),this.logger.debug("Login successful",{address:o.address,expiresIn:o.expiresIn,hasRefreshToken:!!o.refreshToken}),o},"SessionAuthService.performLogin",this.logger,e=>{if(e instanceof ho)throw e;throw new ho(uo.SIGNATURE_FAILED,`Login failed: ${Lt(e)}`,Mt(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 ho(uo.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:ee,data:{},withSession:!1});return this.extractLoginData(e)}catch(e){throw po("Token refresh failed",e)}}async performRefresh(){return fo(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(ee,{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(ee,{},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 ho)throw e;throw new ho(uo.SIGNATURE_FAILED,`Token refresh failed: ${Lt(e)}`,Mt(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:Z,data:{allDevices:t},withSession:!1,...null!==n&&""!==n&&{headers:{Authorization:`${co.BEARER_PREFIX}${n}`}}})}catch(e){throw po("Logout failed",e)}return}if(t&&this.jwtAuth.hasToken()&&!this.jwtAuth.isExpired())try{await this.http.post(Z,{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 ho(uo.WALLET_NOT_CONNECTED,"Not authenticated. Call login() first.");return fo(async()=>{const e=await this.http.get(te,void 0,this.jwtAuth.getJwtHeaders());return this.extractSessionData(e)},"SessionAuthService.getSession",this.logger,e=>{if(e instanceof ho)throw e;throw new ho(uo.SIGNATURE_FAILED,`Failed to get session: ${Lt(e)}`,Mt(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 ho(uo.WALLET_NOT_CONNECTED,"The app session has no access token.");return e}if(!this.jwtAuth.hasToken())throw new ho(uo.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 ho(uo.SIGNATURE_FAILED,""!==Lt(e)?Lt(e):"Authentication failed");const t=on(e,"No data in authentication response"),{accessToken:n,expiresIn:r,address:s,refreshToken:i,refreshExpiresIn:o}=t;if(!xn(n))throw new ho(uo.SIGNATURE_FAILED,"Invalid access token in response");if("number"!=typeof r||r<=0)throw new ho(uo.SIGNATURE_FAILED,"Invalid expiration in response");return{accessToken:n,expiresIn:r,address:s,...void 0!==i&&{refreshToken:i},...void 0!==o&&{refreshExpiresIn:o}}}extractSessionData(e){if(e.error)throw new ho(uo.SIGNATURE_FAILED,""!==Lt(e)?Lt(e):"Failed to get session");return on(e,"No data in session response")}}class Ao{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{Rn(e.messagePrefix,"messagePrefix",!1)}catch{throw new ho(uo.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=y.fromWallet(this.wallet),this.cachedAddress=this.wallet.address,this.cachedGalaAddress=Dr(this.wallet.address)}catch(e){if(e instanceof ho)throw e;if(e instanceof wt&&("INVALID_ADDRESS"===e.code||"INVALID_FORMAT"===e.code||"address"===e.field))throw new ho(uo.INVALID_ADDRESS,e.message);if(null!==e&&"object"==typeof e&&"message"in e)throw new ho(uo.WALLET_NOT_CONNECTED,e.message);throw e}}setWallet(e){if(void 0!==e){if("object"!=typeof e||!("address"in e))throw new ho(uo.WALLET_NOT_CONNECTED,"Invalid wallet: must be an ethers Wallet instance or undefined");if("string"!=typeof e.address||""===e.address)throw new ho(uo.INVALID_ADDRESS,"Wallet address is not available");this.walletProvider=y.fromWallet(e),this.cachedAddress=e.address,this.cachedGalaAddress=Dr(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 n=void 0!==e&&S(e)?t(e.exportPrivateKey()):void 0;this.cachedAddress=n,this.cachedGalaAddress=void 0===n?void 0:Dr(n)}getWalletProvider(){return this.walletProvider}async cacheAddress(){this.walletProvider&&(this.cachedAddress=await this.walletProvider.getAddress(),this.cachedGalaAddress=await this.walletProvider.getGalaAddress())}async generateSignature(){await this.validateWalletAsync();try{const e=Date.now(),t=`${this.messagePrefix} ${e}`,n=await this.walletProvider.signMessage(t);return{message:t,signature:n,address:await this.walletProvider.getGalaAddress(),timestamp:e}}catch(e){if(e instanceof ho)throw e;throw new ho(uo.SIGNATURE_FAILED,"Failed to generate signature for authentication",Mt(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 ho(uo.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 ho(uo.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 ho(uo.WALLET_NOT_CONNECTED,"Wallet private key not available for @gala-chain signing");return this.wallet.privateKey}if(void 0!==this.walletProvider&&S(this.walletProvider))return this.walletProvider.exportPrivateKey();throw new ho(uo.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 ho(uo.WALLET_NOT_CONNECTED,"Private key not available with this wallet provider");try{return await this.walletProvider.getPrivateKey()}catch(e){throw new ho(uo.WALLET_NOT_CONNECTED,"Private key not available. External wallet providers cannot access private keys. Use PrivateKeyProvider for @gala-chain signing operations.",Mt(e)?e:void 0)}}formatAddress(e){try{return Dr(e)}catch{throw new ho(uo.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 ho)throw e;throw new ho(uo.SIGNATURE_FAILED,Lt(e),Mt(e)?e:new Error(Lt(e)))}}async generateAuthHeaders(e,t){await this.validateWalletAsync();try{const n=Date.now(),r=`${this.messagePrefix} ${t.toUpperCase()} ${e} ${n}`,s=await this.walletProvider.signMessage(r);return{"x-signature":s,"x-address":await this.walletProvider.getGalaAddress(),"x-message":r,"x-timestamp":n.toString()}}catch(e){if(e instanceof ho)throw e;throw new ho(uo.SIGNATURE_FAILED,"Failed to generate authentication headers",Mt(e)?e:new Error(Lt(e)))}}async signTypedData(e,t,n){await this.validateWalletAsync();try{const r={};for(const[e,n]of Object.entries(t))r[e]=n.map(e=>({name:e.name,type:e.type}));return await this.walletProvider.signTypedData(e,r,n)}catch(e){if(e instanceof ho)throw e;throw new ho(uo.SIGNATURE_FAILED,"Failed to sign typed data",Mt(e)?e:new Error(Lt(e)))}}async generateCustomSignature(e){if(!xn(e))throw new ho(uo.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 ho)throw e;throw new ho(uo.SIGNATURE_FAILED,"Failed to generate custom message signature",Mt(e)?e:new Error(Lt(e)))}}validateWallet(){if(this.ensureWalletProvider(),!this.walletProvider)throw new ho(uo.WALLET_NOT_CONNECTED,"Wallet is required for authentication")}async validateWalletAsync(){if(this.ensureWalletProvider(),!this.walletProvider)throw new ho(uo.WALLET_NOT_CONNECTED,"Wallet is required for authentication");if(!this.walletProvider.isConnected())throw new ho(uo.WALLET_NOT_CONNECTED,"Wallet is not connected. Call connect() on the wallet provider first.")}}const vo={prod:{...i.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:{...i.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 To(e){return vo[e]}var yo,So;!function(e){e.PROCESSED="PROCESSED",e.COMPLETED="COMPLETED",e.SUCCESS="SUCCESS",e.FAILED="FAILED",e.ERROR="ERROR",e.PROCESSING="PROCESSING",e.PENDING="PENDING"}(yo||(yo={})),function(e){e.PENDING="pending",e.PROCESSING="processing",e.COMPLETED="completed",e.FAILED="failed",e.TIMEOUT="timeout"}(So||(So={}));const bo={[yo.PROCESSED]:So.COMPLETED,[yo.COMPLETED]:So.COMPLETED,[yo.SUCCESS]:So.COMPLETED,[yo.FAILED]:So.FAILED,[yo.ERROR]:So.FAILED,[yo.PROCESSING]:So.PROCESSING,[yo.PENDING]:So.PENDING},No="9.0.0-rc.1",wo={DEFAULT_PAGE_SIZE:50,MAX_PAGE_SIZE:1e3,SAFETY_MAX_PAGES:1e4,DEFAULT_OFFSET:0,DEFAULT_LIMIT:10,BACKEND_MAX_PAGE_SIZE:20},ko={MAX_CONCURRENT_FETCHES:5,PAGE_SIZE:50,BACKEND_PAGE_SIZE:20};function _o(e,t=wo.DEFAULT_LIMIT){if("number"!=typeof e||!Number.isInteger(e)||e<0)throw Qt("offset","a non-negative integer",e);return Cn(t,"limit"),{offset:e,limit:t}}function Io(e,t,n){if("number"!=typeof e||!Number.isInteger(e)||e<0)throw Qt("offset","a non-negative integer",e);Cn(t,"limit")}function Do(e,t=1,n=wo.BACKEND_MAX_PAGE_SIZE){return Math.max(t,Math.min(n,Math.ceil(e??t)))}function Co(e,t){if("number"!=typeof e||!Number.isInteger(e))throw Qt("total","a non-negative integer",e);if(e<0)throw qt("total",0,1/0,e);if("number"!=typeof t||!Number.isInteger(t))throw Qt("limit","a non-negative integer",t);if(t<0)throw qt("limit",0,1/0,t);return 0===t?1:0===e?0:Math.ceil(e/t)}function Ro(e,t,n){if("number"!=typeof e||!Number.isInteger(e))throw Qt("offset","a non-negative integer",e);if(e<0)throw qt("offset",0,1/0,e);return e+t<n}function Oo(e){return"string"==typeof e||null===e?e:void 0}function Mo(e){if("object"!=typeof e||null===e)return{hasNextPage:!1};const t=Reflect.get(e,"hasNextPage"),n=Reflect.get(e,"hasPreviousPage"),r=Oo(Reflect.get(e,"endCursor")),s=Oo(Reflect.get(e,"startCursor"));return{hasNextPage:!0===t,...void 0===r?{}:{endCursor:r},..."boolean"==typeof n?{hasPreviousPage:n}:{},...void 0===s?{}:{startCursor:s}}}function Lo(e,t){const{hasNextPage:n,endCursor:r}=e;if(n&&"string"==typeof r&&""!==r&&r!==t)return r}function Uo(e){return"string"==typeof e?e:"number"==typeof e||"boolean"==typeof e||"bigint"==typeof e?String(e):JSON.stringify(e)??""}function Fo(e,t){const n={};void 0!==e.cursor&&(n.cursor=e.cursor);const r=void 0!==e.pageSize?Math.min(e.pageSize,t):t;return n.pageSize=String(r),n}const Po={tokenName:"lowercase",address:"lowercase",userAddress:"lowercase",assetId:"as given",targetId:"as given",id:"as given",code:"as given"};function xo(e,t){let n=e;for(const[e,r]of Object.entries(t)){const t=Po[e];if(void 0===t)throw new Error(`buildEndpoint: path parameter :${e} has no casing in PATH_PARAM_CASING`);n=n.replace(`:${e}`,encodeURIComponent("lowercase"===t?r.toLowerCase():r))}return n}function Bo(e,t,n){for(const r of n){const n=t[r];null!=n&&""!==n&&(e[r]=Uo(n))}return e}const Go="x-api-key";class $o extends nr{constructor(e,t,n,r=!1,s){super(e,r),this.adminApiKey=t??void 0,this.jwtAuth=n,this.userApiKey=s??void 0}setJwtAuth(e){this.jwtAuth=e}validateTokenName(e,t){!function(e,t){if(!xn(e))throw Kt("tokenName","Token name");const n=hn(e);if(!t.PATTERN.test(n))throw Ht("tokenName",t.DESCRIPTION,"Token name")}(e,t)}validateRequiredString(e,t,n){!function(e,t,n){if(!xn(e))throw Kt(t,n)}(e,t,n)}validateOptionalString(e,t,n,r){!function(e,t,n,r){if(null!=e){if("string"!=typeof e)throw Qt(t,"string",typeof e,n);if(e.length>r)throw Xt(t,r,e.length,n)}}(e,t,n,r)}validateOptionalNumber(e,t,n,r,s,i,o){!function(e,t,n,r,s){if(null!=e){if("number"!=typeof e)throw Qt(t,"number",typeof e,n);if(e<r||e>s)throw qt(t,r,s,e,n)}}(e,t,n,r,s)}validateOptionalDate(e,t,n){!function(e,t,n){if(null!=e&&!yn(e))throw Ht(t,"a valid ISO 8601 date string",n)}(e,t,n)}validatePositiveInteger(e,t,n){er(e,t,n)}validateStatusFilter(e,t,n="status"){tr(e,t,n)}buildPaginationParams(e,t){return Fo(e,t)}addOptionalFilterParams(e,t,n){return Bo(e,t,n)}buildEndpoint(e,t){return xo(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 Rt("Admin API key required for this operation. Set streamAdminApiKey in SDK config.");return{[Go]:this.adminApiKey}}getJwtHeaders(){if(!this.jwtAuth)throw new Rt("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?{[Go]:this.userApiKey}:this.getJwtHeaders()}extractData(e){return rn(e,"Backend request failed",!0),on(e,"No data in backend response")}extractDataOrNull(e){return rn(e,"Backend request failed",!1),e.data??null}async toggleFeature(e,t,n){this.validateTokenName(e,n);const r=this.buildEndpoint(t,{tokenName:e}),s=await this.http.post(r,{},this.getAdminHeaders()),i=this.extractData(s);return{enabled:i.enabled,tokenName:i.tokenName??hn(e)}}}class Ko extends $o{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async getSettings(){return{settings:(await this.http.get(ot.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(ot.UPDATE_SETTINGS,t,this.getDualAuthHeaders())).settings}}async getModeration(e){this.validatePositiveInteger(e.flagId,"flagId","Flag ID");const t=ot.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=ot.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(ot.GET_STATUS,{},this.getDualAuthHeaders())).status}}}const Ho={MODERATOR:"MODERATOR",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MANAGER:"MANAGER",OWNER:"OWNER"},Wo=Hn(Ho),Vo={MANAGE_COMMENTS:"MANAGE_COMMENTS",MANAGE_CHAT:"MANAGE_CHAT",BAN_USERS:"BAN_USERS",UNBAN_USERS:"UNBAN_USERS",MANAGE_SIMULCAST:"MANAGE_SIMULCAST",GET_STREAM_KEY:"GET_STREAM_KEY",STOP_STREAM:"STOP_STREAM",RESET_STREAM_KEY:"RESET_STREAM_KEY",START_STREAM:"START_STREAM",DELETE_RECORDINGS:"DELETE_RECORDINGS",MANAGE_STREAM_SETTINGS:"MANAGE_STREAM_SETTINGS"},jo={MANAGE_COMMUNITY:"MANAGE_COMMUNITY",MANAGE_STREAM:"MANAGE_STREAM",MANAGE_SETTINGS:"MANAGE_SETTINGS",MANAGE_RECORDINGS:"MANAGE_RECORDINGS",VIEW_ANALYTICS:"VIEW_ANALYTICS"},qo=Object.values(jo);function zo(e){return Wo.includes(e)}function Xo(e){const t=[];return void 0===e.role||null===e.role?t.push("Role is required"):zo(e.role)||t.push(`Invalid role. Must be one of: ${Wo.join(", ")}`),Yo(e,t),t}function Qo(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||zo(e.role)||t.push(`Invalid role. Must be one of: ${Wo.join(", ")}`),Yo(e,t,!0),t}function Yo(e,t,n=!1){const r=t.length;if(Bt(t,()=>{Jn(e.description,"description",255)}),t.length>r&&(t[r]="Description must be 255 characters or less"),void 0!==e.tokenNames){const n=t.length;Bt(t,()=>{if(!Array.isArray(e.tokenNames))throw Qt("tokenNames","an array",e.tokenNames);if(!e.tokenNames.every(e=>"string"==typeof e))throw Qt("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,()=>{Zn(e.expiresAt,"expiresAt")}),t.length>n&&(t[n]="expiresAt must be a valid ISO 8601 date string")}}function Jo(e){if(void 0!==e.pageSize&&("number"!=typeof e.pageSize||e.pageSize<1||e.pageSize>ur))throw Qt("pageSize",`number between 1 and ${ur}`,typeof e.pageSize);if(void 0!==e.cursor&&("string"!=typeof e.cursor||""===e.cursor.trim()))throw Qt("cursor","non-empty string",typeof e.cursor)}const Zo={[Ho.MODERATOR]:1,[Ho.TECHNICAL_PRODUCER]:1,[Ho.MANAGER]:2,[Ho.OWNER]:3};function ea(e,t){return e===Ho.MANAGER?t!==Ho.OWNER:e===Ho.OWNER||e===t}class ta extends nr{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),rn(n,"API key operation failed",!0),e.data}validateApiKeyId(e){this.validatePositiveInteger(e,"id","API key ID")}async create(e){const t=Xo(e);if(t.length>0)throw new wt(t.join("; "),"options","VALIDATION_FAILED");this.logger.debug("Creating API key",{role:e.role,delegateAllTokens:e.delegateAllTokens});const n={role:e.role};void 0!==e.description&&(n.description=e.description),void 0!==e.delegateAllTokens&&(n.delegateAllTokens=e.delegateAllTokens),void 0!==e.tokenNames&&e.tokenNames.length>0&&(n.tokenNames=e.tokenNames),void 0!==e.expiresAt&&(n.expiresAt=e.expiresAt),void 0!==e.tokenPermissions&&(n.tokenPermissions=e.tokenPermissions);const r=await this.http.post(ue.CREATE,n,this.getJwtHeaders()),s=this.extractData(r);return this.logger.debug("API key created",{id:s.id,keyPrefix:s.keyPrefix}),s}async findAll(e={}){Jo(e),this.logger.debug("Listing API keys",e);const t=Fo(e,ur),n=await this.http.get(ue.LIST,t,this.getJwtHeaders()),r=this.extractData(n);return this.logger.debug("Listed API keys",{count:r.apiKeys.length,total:r.pageInfo.totalCount}),r}async findOne(e){this.validateApiKeyId(e),this.logger.debug("Getting API key",{id:e});const t=ue.GET.replace(":id",String(e)),n=await this.http.get(t,{},this.getJwtHeaders()),r=this.extractData(n);return this.logger.debug("Got API key",{id:r.id,keyPrefix:r.keyPrefix}),r}async update(e,t){this.validateApiKeyId(e);const n=Qo(t);if(n.length>0)throw new wt(n.join("; "),"options","VALIDATION_FAILED");this.logger.debug("Updating API key",{id:e,options:t});const r={};void 0!==t.role&&(r.role=t.role),void 0!==t.description&&(r.description=t.description),void 0!==t.delegateAllTokens&&(r.delegateAllTokens=t.delegateAllTokens),void 0!==t.tokenNames&&(r.tokenNames=t.tokenNames),void 0!==t.expiresAt&&(r.expiresAt=t.expiresAt),void 0!==t.tokenPermissions&&(r.tokenPermissions=t.tokenPermissions);const s=ue.UPDATE.replace(":id",String(e)),i=await this.http.patch(s,r,this.getJwtHeaders()),o=this.extractData(i);return this.logger.debug("Updated API key",{id:o.id,keyPrefix:o.keyPrefix}),o}async revoke(e){this.validateApiKeyId(e),this.logger.debug("Revoking API key",{id:e});const t=ue.REVOKE.replace(":id",String(e));await this.http.delete(t,{},this.getJwtHeaders()),this.logger.debug("API key revoked",{id:e})}getRoles(){return[...Wo]}}const na={ONE_HOUR:3600,ONE_DAY:86400,ONE_WEEK:604800,ONE_MONTH:2592e3},ra={VIEWERS:"viewers",CHAT_PARTICIPANTS:"chat_participants"},sa=Kn(ra),ia=zn([{field:"id",type:"number"},{field:"userAddress",type:"string"},{field:"bannedBy",type:"string"},{field:"createdAt",type:"string"},{field:"isPermanent",type:"boolean"},{field:"tokenName",type:"string",nullable:!0},{field:"reason",type:"string",nullable:!0},{field:"expiresAt",type:"string",nullable:!0}]),oa=zn([{field:"tokenName",type:"string",nullable:!0},{field:"isGlobal",type:"boolean"},{field:"isPermanent",type:"boolean"}]),aa=zn([{field:"tokenName",type:"string",nullable:!0},{field:"isGlobal",type:"boolean"}]),ca=zn([{field:"tokenName",type:"string"},{field:"action",type:"string",validator:e=>"CHAT_MESSAGE"===e||"COMMENT"===e||"REACTION"===e}]);function la(e){return null==e||""===e||"string"==typeof e&&(!Yn(e)&&e.length<=pr.BAN_REASON.MAX_LENGTH)}function da(e){return!!Gn(e)||"number"==typeof e&&(e>=Ar&&e<=vr)}function ua(e){if(!xn(e.userAddress))throw Kt("userAddress");if(!la(e.reason))throw new wt(`reason must be at most ${pr.BAN_REASON.MAX_LENGTH} characters`,"reason","TOO_LONG");if(!da(e.durationSeconds))throw new wt(`durationSeconds must be between ${Ar} and ${vr} seconds`,"durationSeconds","OUT_OF_RANGE")}class ha extends $o{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async createBan(e){!function(e){Wn(e.tokenName,"tokenName",cr),ua(e)}(e);const t=this.buildEndpoint(ne,{tokenName:e.tokenName}),n=ga(e),r=await this.http.post(t,n,this.getMultiAuthHeaders());return{ban:this.extractData(r),tokenName:hn(e.tokenName)}}async removeBan(e){!function(e){if(Wn(e.tokenName,"tokenName",cr),!xn(e.userAddress))throw Kt("userAddress")}(e);const t=this.buildEndpoint(ie,{tokenName:e.tokenName,userAddress:e.userAddress}),n=await this.http.delete(t,{},this.getMultiAuthHeaders()),r=this.extractDataOrNull(n);return{removed:r?.removed??!0,tokenName:hn(e.tokenName),userAddress:r?.userAddress??e.userAddress.toLowerCase()}}async listBans(e){!function(e){Wn(e.tokenName,"tokenName",cr),$n(0,void 0,ur,e.pageSize)}(e);const t=this.buildEndpoint(re,{tokenName:e.tokenName}),n=this.buildPaginationParams(e,ur);this.addOptionalFilterParams(n,e,["search","name","userAddress"]);const r=await this.http.get(t,n,this.getMultiAuthHeaders()),s=this.extractData(r);return{items:s.bans,pageInfo:s.pageInfo}}async getBanStatus(e){!function(e){if(Wn(e.tokenName,"tokenName",cr),!xn(e.userAddress))throw Kt("userAddress")}(e);const t=this.buildEndpoint(se,{tokenName:e.tokenName,userAddress:e.userAddress}),n=await this.http.get(t,{},this.getMultiAuthHeaders()),r=this.extractDataOrNull(n);return{banned:null!==r,...null!==r&&{ban:r},tokenName:hn(e.tokenName),userAddress:e.userAddress.toLowerCase()}}async getActiveUsers(e){!function(e){if(Wn(e.tokenName,"tokenName",cr),void 0!==e.type&&!sa(e.type))throw new wt(`type must be one of: ${Object.values(ra).join(", ")}`,"type",Nt.INVALID_VALUE)}(e);const t=this.buildEndpoint(oe,{tokenName:e.tokenName}),n={};this.addOptionalFilterParams(n,e,["type","search","name","userAddress"]);const r=await this.http.get(t,n,this.getMultiAuthHeaders());return this.extractData(r)}async createGlobalBan(e){!function(e){ua(e)}(e);const t=ga(e),n=await this.http.post(ae,t,this.getDualAuthHeaders());return{ban:this.extractData(n)}}async removeGlobalBan(e){!function(e){if(!xn(e.userAddress))throw Kt("userAddress")}(e);const t=this.buildEndpoint(de,{userAddress:e.userAddress}),n=await this.http.delete(t,{},this.getDualAuthHeaders()),r=this.extractDataOrNull(n);return{removed:r?.removed??!0,userAddress:r?.userAddress??e.userAddress.toLowerCase()}}async listGlobalBans(e){const t=e??{pageSize:20};!function(e){$n(0,void 0,ur,e.pageSize)}(t);const n=this.buildPaginationParams(t,ur);this.addOptionalFilterParams(n,t,["search","name","userAddress"]);const r=await this.http.get(ce,n,this.getDualAuthHeaders()),s=this.extractData(r);return{items:s.bans,pageInfo:s.pageInfo}}async getGlobalBan(e){!function(e){if(!xn(e.userAddress))throw Kt("userAddress")}(e);const t=this.buildEndpoint(le,{userAddress:e.userAddress}),n=await this.http.get(t,{},this.getDualAuthHeaders()),r=this.extractDataOrNull(n);return{banned:null!==r,...null!==r&&{ban:r},userAddress:e.userAddress.toLowerCase()}}}function ga(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 ma(e){return{maxAcceptableReverseBondingCurveFee:kn(e.maxAcceptableReverseBondingCurveFee)}}const fa={BuyNativeDto:class extends b{constructor(e,t,n="0",r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=kn(t),this.expectedToken=_n(n),this.extraFees=ma(r)}},BuyExactDto:class extends b{constructor(e,t,n,r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=_n(t),this.expectedNativeToken=kn(n),this.extraFees=ma(r)}},SellExactDto:class extends b{constructor(e,t,n="0",r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=_n(t),this.expectedNativeToken=kn(n),this.extraFees=ma(r)}},SellNativeDto:class extends b{constructor(e,t,n,r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=kn(t),this.expectedToken=_n(n),this.extraFees=ma(r)}}};function pa(e,t,n){let r;In(t,0,1,"slippageToleranceFactor");try{r=function(e,t){if(An(e)||""===e)throw Kt(t);if(_.isBigNumber(e)){if(e.isNaN())throw Yt(t,"NaN");return e}try{const n=new _(e);if(n.isNaN())throw Yt(t,e);if(!n.isFinite())throw Yt(t,e);return n}catch(n){if(n instanceof wt)throw n;throw Yt(t,e)}}(e,"expectedAmount")}catch{throw new Error(`Invalid expected amount: ${e}. Must be a valid number`)}if(0===t)return e;const s=r.multipliedBy(t);let i;switch(n){case"buy-native":case"sell-exact":i=r.minus(s);break;case"buy-exact":case"sell-native":i=r.plus(s);break;default:throw new Error(`Unknown operation type: ${n}`)}return Hi(i).isLessThan(0)&&(i=Hi(0)),Wi(i)}function Ea(e,t){if(!xn(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 Aa(e,t,n,r){const s=e?.split?.(t)??[],i=void 0!==n?` (${n})`:"";return new wt(`Invalid ${"|"===t?"pipe":"dollar"}-delimited token: "${e}" (${s.length} parts)${i}. Expected format: "collection${t}category${t}type${t}additionalKey" (4 parts minimum). Received: [${s.map(e=>`"${e}"`).join(", ")}]. Error: ${Lt(r)}`,"token",`INVALID_${"|"===t?"PIPE":"DOLLAR"}_DELIMITED_TOKEN`)}function va(e,t,n){try{const n=Ea(e,t),r=n[n.length-1],s=n[n.length-2],i=n[n.length-3],o=n.slice(0,n.length-3).join(t);if(void 0===o||void 0===i||void 0===s||void 0===r||""===r||""===o||""===i||""===s)throw new Error("All components (collection, category, type, additionalKey) must be non-empty");return{collection:o,category:i,type:s,additionalKey:r}}catch(r){throw Aa(e,t,n,r)}}function Ta(e){return function(e,t,n){try{const n=Ea(e,t),[r,s,i,...o]=n;if(""===r||""===s||""===i)throw new Error("Collection, category, and type must be non-empty");const a=o.join(t);if(void 0===r||void 0===s||void 0===i||""===a)throw new Error("AdditionalKey must be non-empty");return{collection:r,category:s,type:i,additionalKey:a}}catch(r){throw Aa(e,t,n,r)}}(e,"|","pipe-delimited token")}class ya 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 Sa={name:"GalaChain"},ba={name:"ethereum",chainId:1};function Na(e){if("string"!=typeof e)throw new Error("Wallet returned an invalid signature");return e}function wa(e){const t={};for(const[n,r]of Object.entries(e))void 0!==r&&(t[n]=ka(r));return t}function ka(e){return Array.isArray(e)?e.map(ka):"object"==typeof e&&null!==e?wa(e):e}function _a(e,t,n,r){return{...e,signature:t,types:n,domain:r}}class Ia extends u{constructor(e){super(e),this.typedDataWallet=new s(e),this.walletAddress=`eth|${this.typedDataWallet.address.slice(2)}`}async signTypedData(e,t){const n=wa(t),r=a(e,n);return _a(n,await this.typedDataWallet.signTypedData(Sa,r,n),r,Sa)}}class Da extends l{constructor(e,t={}){const{verifyActiveAccount:n,...r}=t;if(super(e,r),this.typedDataWallet=t.wallet,!0===n){const e=c(this.walletAddress)??(void 0===this.selectAddress?void 0:c(this.selectAddress));if(void 0===e)throw new ya("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=wa(t),r=a(e,n),s={domain:ba,types:r,message:n,Primary_type:e},i=this.typedDataWallet??function(){const e=globalThis.window,t=e?.gala;if(void 0===t)throw new Error("Gala wallet is not available");return t}();void 0!==this.verifiedKey&&await async function(e,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"}),r=Array.isArray(t)?t[0]:void 0;n="string"==typeof r&&""!==r?r:void 0}const r=void 0===n?void 0:c(n);if(void 0===r||r.toLowerCase()!==t.toLowerCase())throw new ya("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}})}(i,this.verifiedKey);const o=await this.typedDataAccount(i);return _a(n,Na(await d(i,this.selectAddress??o,()=>i.request({method:"eth_signTypedData",params:[JSON.stringify(s),o]}))),r,ba)}async typedDataAccount(e){if(n(this.walletAddress))return this.walletAddress;const t=await e.request({method:"eth_accounts"}),r=Array.isArray(t)?t[0]:void 0,s="string"==typeof r?r.replace(/^eth\|/,"0x"):"";if(!n(s))throw new Error("Gala Wallet did not report an Ethereum account to sign typed data with");return s}}class Ca extends o{constructor(e,t,n){super(e,t,n),this.typedDataProvider=e}async signTypedData(t,r){const s=wa(r),i=this.typedDataProvider,o=await i.getNetwork(),c={name:o.name,chainId:Number(o.chainId)},l=a(t,s),d=await i.getSigner(),u=e(await d.getAddress());if(n(this.walletAddress)&&u!==e(this.walletAddress))throw new ya(`Wallet account ${u} is not the account this signer was created for (${this.walletAddress}); reconnect before signing.`,"WALLET_ACCOUNT_CHANGED",{details:{walletAccount:u,signerAccount:this.walletAddress}});return _a(s,Na(await d.signTypedData(c,l,s)),l,c)}static fromEip1193(e,t,n){const s=new r(e);return new Ca({request:t=>e.request(t),getNetwork:()=>s.getNetwork(),getSigner:()=>s.getSigner()},c(t)??t,n)}}function Ra(e){const[t,n]=e.split("|",2);if("service"!==t||void 0===n)throw new Error(`Invalid vaultAddress format (expected service|<collection>$<category>$<type>$<additionalKey>$launchpad): ${e}`);const r=n.split("$"),s=r[r.length-1],i=r.slice(0,-1),o=i.slice(0,-3).join("$"),[a,c,l]=i.slice(-3);if("launchpad"!==s||i.length<4||""===o||void 0===a||void 0===c||void 0===l||""===a||""===c||""===l)throw new Error(`Invalid vaultAddress format (expected service|<collection>$<category>$<type>$<additionalKey>$launchpad): ${e}`);return{collection:o,category:a,type:c,additionalKey:l}}function Oa(e){const{collection:t,category:n,type:r}=Ra(e),s=`${t}$${n}$${r}$none`,i="GALA$Unit$none$none";return[`$service$${s}$launchpad`,`$tokenBalance$${s}$${e}`,`$tokenBalance$${s}$${e}`,`$tokenBalance$${i}$${e}`,`$tokenBalance$${i}$${e}`]}function Ma(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 La(e){return`${e.collection}|${e.category}|${e.type}|${e.additionalKey}`}function Ua(e){if("string"==typeof e){if(!xn(t=e)||!t.includes("|"))throw new wt(`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=Ta(n.slice(0,4).join("|")),t=n[4]??"0";return{...e,instance:t.length>0?t:"0"}}return{...Ta(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(!h(e))throw new wt("Invalid tokenId object format. All fields (collection, category, type, additionalKey) must be non-empty strings","tokenId","INVALID_TOKEN_ID_FORMAT");return e}if(!h(e))throw new wt("Invalid tokenId object format. All fields (collection, category, type, additionalKey) are required","tokenId","INVALID_TOKEN_ID_FORMAT");return{...e,instance:"0"}}throw new wt(`Invalid tokenId type: ${typeof e}. Expected string, TokenClassKey, or TokenInstanceKey`,"tokenId","INVALID_TOKEN_ID_TYPE")}function Fa(e){return function(e){try{if(!xn(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 va((n.length>=5&&"launchpad"===n[n.length-1]?n.slice(0,-1):n).join("$"),"$","vault address")}catch(t){throw new wt(`Invalid vault address: "${e}". Expected format: "service|Token$Unit$SYMBOL$additionalKey$launchpad". Error: ${Lt(t)}`,"vaultAddress","INVALID_VAULT_ADDRESS_FORMAT")}}(e)}function Pa(e){return{...Fa(e),instance:"0"}}function xa(e){const t=Fa(e);if("Token"!==t.collection)throw new wt(`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 Ba,Ga,$a,Ka,Ha=Object.freeze({__proto__:null,extractTokenSymbolFromVault:xa,normalizeToTokenInstanceKey:Ua,parseVaultAddressToTokenClassKey:Fa,parseVaultAddressToTokenInstance:Pa});class Wa extends rr{constructor(e=!1){super(e)}generateStringsInstructions(e){try{this.logger.debug("🔧 Generating stringsInstructions for:",e);const t=Oa(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 wt(`Failed to generate stringsInstructions: ${t}`,"vaultAddress","INVALID_VAULT_ADDRESS")}}createGalaInstance(){const e=new N;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(!xn(e))throw Kt("vaultAddress","Vault address");try{const t=xa(e);return this.logger.debug("🔍 Extracted token symbol:",{vaultAddress:e,tokenSymbol:t}),t}catch(e){if(e instanceof wt)throw Ht("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad");throw e}}validateVaultAddress(e){if(!xn(e))throw Kt("vaultAddress","Vault address");if(!e.startsWith("service|Token$Unit$"))throw Ht("vaultAddress",'starting with "service|Token$Unit$"');if(!e.endsWith("$launchpad"))throw Ht("vaultAddress",'ending with "$launchpad"');const t=function(e){if(!xn(e))return null;const t=e.match(/^service\|Token\$Unit\$([^$]+)\$eth:([a-fA-F0-9]{40})\$launchpad$/);if(!t)return null;const n=t[1],r=t[2];return void 0===n||void 0===r?null:{tokenSymbol:n,creatorAddress:r.toLowerCase()}}(e);if(!t)throw Ht("vaultAddress","valid vault address format (service|Token$Unit$SYMBOL$eth:address$launchpad)");const n=t.tokenSymbol;if(""===n||!/^[A-Za-z]{1,10}$/.test(n))throw Ht("vaultAddress","containing a 1-10 letter token symbol (case insensitive)");return this.logger.debug("✅ Vault address validation passed:",e),!0}generateTokenClassKeyString(e,t,n,r){return`${e}$${t}$${n}$${r}`}parseTokenClassKeyString(e){try{return va(e,"$","dollar-delimited token")}catch(e){if(e instanceof wt)throw Ht("stringKey","format: collection$category$type$additionalKey (4 parts)");throw e}}}function Va(e){return"object"==typeof e&&null!==e?e:void 0}class ja extends nr{constructor(e,t,n=!1,r,s,i=.05,o=.01,a){if(super(e,n),this.tokenResolver=t,this._walletProvider=r,this.userAddress=s,this.defaultSlippageToleranceFactor=i,this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor=o,this.sellFeeCeiling=a,this.bundleEndpoint="/bundle",null!==this._walletProvider&&void 0!==this._walletProvider&&null!=s){const e=Va(this._walletProvider),t=e?.privateKey;"string"==typeof t?this.signer=new Ia(t):function(e){const t=Va(e);return"function"==typeof t?.request}(this._walletProvider)&&void 0!==this.userAddress&&(this.signer=new Ca(this._walletProvider,this.userAddress)),this.tokenKeyService=new Wa(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 cn(()=>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:nn(n),error:n.error}),this.handleBundleResponse(n))}catch(e){if(e instanceof wt)return{success:!1,error:Lt(e)};throw e}}validateBundleData(e){if(null==e)throw Kt("bundleData","Bundle data");if(null===e.signedDto||void 0===e.signedDto)throw Kt("signedDto","Signed DTO");if(!xn(e.method))throw Kt("method","Method name");if(!Array.isArray(e.stringsInstructions))throw Ht("stringsInstructions","an array of resource tracking strings");if(0===e.stringsInstructions.length)throw new wt("stringsInstructions cannot be empty","stringsInstructions","EMPTY_ARRAY");const t=["BuyWithNative","BuyExactToken","SellExactToken","SellWithNative"];if(!t.includes(e.method))throw Ht("method",`one of: ${t.join(", ")}`);e.stringsInstructions.forEach((e,t)=>{if(!xn(e))throw new wt(`stringsInstructions[${t}] must be a non-empty string`,`stringsInstructions[${t}]`,"INVALID_INSTRUCTION");if("string"!=typeof(n=e)||!n.includes("$"))throw new wt(`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=sn(e);if(null!=t&&!1===e.error)return this.logger.debug("✅ Bundle transaction successful:",t),{success:!0,data:t};const n=("string"==typeof e.error?e.error:e.message)??"Bundle transaction failed";return this.logger.debug("❌ Bundle transaction failed:",n),{success:!1,error:n}}formatErrorMessage(e){if("string"==typeof e)return e;if(Pt(e)&&null!==e.response&&void 0!==e.response){const t=sn(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(!xn(e))throw Kt("transactionId","Transaction ID");let t;this.logger.debug("🔍 Checking bundler transaction result:",e);try{t=await cn(()=>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 wt)return{success:!1,error:Lt(e)};throw e}}async cancelTransaction(e){try{if(!xn(e))throw Kt("transactionId","Transaction ID");let t;this.logger.debug("🚫 Cancelling transaction:",e);try{t=await cn(()=>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 wt)return{success:!1,error:Lt(e)};throw e}}async getHealthStatus(){this.logger.debug("🏥 Checking bundle service health");try{const e=await cn(()=>this.http.get(`${this.bundleEndpoint}/health`),{errorContext:"Bundle service health check failed",logger:this.logger});return null==e?{success:!1,error:"No response from bundle service health check"}:(this.logger.debug("💚 Bundle service health:",e),{success:!0,data:e})}catch(e){return{success:!1,error:this.formatErrorMessage(e)}}}async buyToken(e){this.ensureTradingServicesAvailable();const{tokenName:t,amount:n,type:r,expectedAmount:s}=e,{effectiveSlippageFactor:i,effectiveMaxFee:o,vaultAddress:a}=await this.prepareTradingOperation(t,e.maxAcceptableReverseBondingCurveFee,e.maxAcceptableReverseBondingCurveFeeSlippageFactor,e.slippageToleranceFactor);if("native"===r){if(null==s||""===s)throw new wt("expectedAmount is required for native buy operations. Use getBuyTokenAmount() first to calculate expected tokens.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=pa(s,i,"buy-native");this.logger.debug("BuyNative slippage applied:",{originalExpectedTokens:s,slippageFactor:i,adjustedMinTokens:e});const t=new fa.BuyNativeDto(a,n,e,{maxAcceptableReverseBondingCurveFee:o});return await this.executeBundleTransaction(t,"BuyWithNative",a)}{if(null==s||""===s)throw new wt("expectedAmount is required for exact buy operations. Use getBuyTokenAmount() first to calculate expected GALA cost.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=pa(s,i,"buy-exact");this.logger.debug("BuyExact slippage applied:",{originalExpectedGalaCost:s,slippageFactor:i,adjustedMaxGalaCost:e});const t=new fa.BuyExactDto(a,n,e,{maxAcceptableReverseBondingCurveFee:o});return await this.executeBundleTransaction(t,"BuyExactToken",a)}}async sellToken(e){this.ensureTradingServicesAvailable();const{tokenName:t,amount:n,type:r,expectedAmount:s}=e,{effectiveSlippageFactor:i,effectiveMaxFee:o,vaultAddress:a}=await this.prepareTradingOperation(t,e.maxAcceptableReverseBondingCurveFee,e.maxAcceptableReverseBondingCurveFeeSlippageFactor,e.slippageToleranceFactor),c=async()=>void 0===e.maxAcceptableReverseBondingCurveFee?this.defaultSellFeeCeiling(e,a):o;if("exact"===r){if(null==s||""===s)throw new wt("expectedAmount is required for exact sell operations. Use getSellTokenAmount() first to calculate expected GALA.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=pa(s,i,"sell-exact");this.logger.debug("SellExact slippage applied:",{originalExpectedGala:s,slippageFactor:i,adjustedMinGala:e});const t={maxAcceptableReverseBondingCurveFee:await c()},r=new fa.SellExactDto(a,n,e,t);return await this.executeBundleTransaction(r,"SellExactToken",a)}{if(null==s||""===s)throw new wt("expectedAmount is required for native sell operations. Use getSellTokenAmount() first to calculate tokens to sell.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=pa(s,i,"sell-native");this.logger.debug("SellNative slippage applied:",{originalExpectedTokensToSell:s,slippageFactor:i,adjustedMaxTokensToSell:e});const t={maxAcceptableReverseBondingCurveFee:await c()},r=new fa.SellNativeDto(a,n,e,t);return await this.executeBundleTransaction(r,"SellWithNative",a)}}async prepareTradingOperation(e,t,n,r){const{effectiveSlippageFactor:s,effectiveMaxFee:i}=this.calculateEffectiveSlippage(t,n,r),o=await this.resolveTokenNameToVault(e);if(null==o)throw $t(e);return{effectiveSlippageFactor:s,effectiveMaxFee:i,vaultAddress:o}}async defaultSellFeeCeiling(e,t){if(void 0===this.sellFeeCeiling)throw Vt("Cannot quote the reverse bonding curve fee for this sell. Pass maxAcceptableReverseBondingCurveFee.","maxAcceptableReverseBondingCurveFee");return this.sellFeeCeiling({method:"exact"===e.type?"SellExactToken":"SellWithNative",vaultAddress:t,quantity:e.amount,tokenName:e.tokenName,feeSlippageFactor:e.maxAcceptableReverseBondingCurveFeeSlippageFactor??this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor})}calculateEffectiveSlippage(e,t,n){const r=n??this.defaultSlippageToleranceFactor,s=t??this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor;let i=e??"0";return null!=e&&(i=pa(e,s,"buy-exact"),this.logger.debug("Reverse bonding curve fee slippage applied:",{baseFee:e,slippageFactor:s,adjustedMaxFee:i})),{effectiveSlippageFactor:r,effectiveFeeSlippageFactor:s,effectiveMaxFee:i}}ensureTradingServicesAvailable(){if(!this.signer||!this.tokenKeyService)throw Vt("Trading services not available. BundleService requires walletProvider and userAddress for trading operations.","walletProvider");if(null===this.userAddress||void 0===this.userAddress)throw Kt("userAddress","User address")}async executeBundleTransaction(e,t,n){this.ensureTradingServicesAvailable();try{e.uniqueKey=`galaswap-operation-${Date.now()}_${w().replace(/-/gu,"").substring(0,26)}`;const r=await this.signer.signObject(t,e),s=this.tokenKeyService.generateStringsInstructions(n),i={stringsInstructions:s,method:t,signedDto:r};this.logger.debug("📦 Bundle transaction data:",{method:t,stringsInstructions:s,dtoKeys:Object.keys(r)});const o=await this.submitTransaction(i);if(o.success){const e=sn(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 a=o.error;throw new Ot("string"==typeof a?a:"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 qa extends nr{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(Et),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"}(Ba||(Ba={})),function(e){e.INAPPROPRIATE_CONTENT="INAPPROPRIATE_CONTENT",e.SPAM="SPAM",e.HARASSMENT="HARASSMENT",e.SCAM="SCAM",e.OTHER="OTHER"}(Ga||(Ga={})),function(e){e.PENDING="PENDING",e.DISMISSED="DISMISSED",e.ACTIONED="ACTIONED"}($a||($a={})),function(e){e.DELETE_CONTENT="DELETE_CONTENT",e.BAN_USER="BAN_USER",e.DELETE_AND_BAN="DELETE_AND_BAN"}(Ka||(Ka={}));const za={[Ga.INAPPROPRIATE_CONTENT]:"Inappropriate Content",[Ga.SPAM]:"Spam",[Ga.HARASSMENT]:"Harassment",[Ga.SCAM]:"Scam",[Ga.OTHER]:"Other"},Xa={[$a.PENDING]:"Pending",[$a.DISMISSED]:"Dismissed",[$a.ACTIONED]:"Actioned"},Qa={[Ka.DELETE_CONTENT]:"Delete Content",[Ka.BAN_USER]:"Ban User",[Ka.DELETE_AND_BAN]:"Delete & Ban"},Ya={[Ba.CHAT_MESSAGE]:"Chat Message",[Ba.COMMENT]:"Comment",[Ba.STREAM]:"Stream",[Ba.RECORDING]:"Recording"},Ja=500,Za=Kn(Ba),ec=Kn(Ga),tc=Kn($a),nc=Kn(Ka),rc=zn([{field:"id",type:"number"},{field:"tokenName",type:"string"},{field:"contentType",type:"string",validator:Za},{field:"contentId",type:"string"},{field:"reporterAddress",type:"string"},{field:"reportedUserAddress",type:"string"},{field:"status",type:"string",validator:tc}]),sc={TOKEN_NAME:or,TOKEN_NAME_FILTER:ar,CONTENT_ID:pr.CONTENT_ID,DETAILS:pr.FLAG_DETAILS,PAGINATION:{MAX_LIMIT:ur}};function ic(e,t,n="tokenName"){Wn(e,n,t)}function oc(e){if(void 0!==e.contentType&&!Za(e.contentType))throw Ht("contentType",`one of: ${Object.values(Ba).join(", ")}`,"Content type");if(void 0!==e.status&&!tc(e.status))throw Ht("status",`one of: ${Object.values($a).join(", ")}`);if(void 0!==e.reason&&!ec(e.reason))throw Ht("reason",`one of: ${Object.values(Ga).join(", ")}`);if(void 0!==e.reporterAddress&&!xn(e.reporterAddress))throw Qt("reporterAddress","a non-empty string",typeof e.reporterAddress);if(void 0!==e.reporterAddress&&Ur(e.reporterAddress,"reporterAddress"),void 0!==e.reportedUserAddress&&!xn(e.reportedUserAddress))throw Qt("reportedUserAddress","a non-empty string",typeof e.reportedUserAddress);void 0!==e.reportedUserAddress&&Ur(e.reportedUserAddress,"reportedUserAddress"),$n(0,void 0,sc.PAGINATION.MAX_LIMIT,e.pageSize)}class ac extends $o{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async createFlag(e){!function(e){if(ic(e.tokenName,sc.TOKEN_NAME),void 0===e.contentType)throw Kt("contentType","Content type");if(!Za(e.contentType))throw Ht("contentType",`one of: ${Object.values(Ba).join(", ")}`,"Content type");if(!xn(e.contentId))throw Kt("contentId","Content ID");if(e.contentId.length>sc.CONTENT_ID.MAX_LENGTH)throw Xt("contentId",sc.CONTENT_ID.MAX_LENGTH,e.contentId.length,"Content ID");if(!xn(e.reportedUserAddress))throw Kt("reportedUserAddress","Reported user address");if(Ur(e.reportedUserAddress,"reportedUserAddress"),!(e.contentType!==Ba.STREAM&&e.contentType!==Ba.RECORDING||void 0!==e.reason&&null!==e.reason))throw Kt("reason","Reason");if(void 0!==e.reason&&!ec(e.reason))throw Ht("reason",`one of: ${Object.values(Ga).join(", ")}`,"Reason");if(void 0!==e.details&&!xn(e.details))throw Qt("details","a non-empty string",typeof e.details);if(void 0!==e.details&&e.details.length>sc.DETAILS.MAX_LENGTH)throw Xt("details",sc.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(Te.CREATE,t,this.getMultiAuthHeaders());return{flag:this.extractData(n).flag}}async listFlags(e){return function(e){ic(e.tokenName,sc.TOKEN_NAME_FILTER),oc(e)}(e),this.fetchFlagList(e)}async listGlobalFlags(e={}){return function(e){void 0!==e.tokenName&&ic(e.tokenName,sc.TOKEN_NAME_FILTER),oc(e)}(e),this.fetchFlagList(e)}async dismissFlag(e){!function(e){if(void 0===e.flagId||null===e.flagId)throw Kt("flagId","Flag ID");try{Cn(e.flagId,"flagId")}catch{throw Ht("flagId","a positive integer","Flag ID")}}(e);const t=Te.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 Kt("flagId","Flag ID");try{Cn(e.flagId,"flagId")}catch{throw Ht("flagId","a positive integer","Flag ID")}if(void 0===e.action)throw Kt("action","Action");if(!nc(e.action))throw Ht("action",`one of: ${Object.values(Ka).join(", ")}`,"Action")}(e);const t=Te.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=Fo(e,ur);Bo(t,e,["tokenName","contentType","status","reason","reporterAddress","reportedUserAddress"]);const n=await this.http.get(Te.LIST,t,this.getMultiAuthHeaders()),r=this.extractData(n);return{items:r.flags,pageInfo:r.pageInfo}}}const cc=["heart","fire","laugh","wow","thumbs_up"],lc={heart:"❤️",fire:"🔥",laugh:"😂",wow:"😮",thumbs_up:"👍"};class dc extends $o{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}validateMessageId(e){if(!xn(e))throw Kt("messageId","Message ID");if(Dn(e,Er.CONTENT_REACTION.MAX_LENGTH,"messageId"),!Er.CONTENT_REACTION.PATTERN.test(e))throw Ht("messageId","msg-{timestamp}-{uuid} or chat-{timestamp}-{uuid} format","Message ID")}validateReactionType(e){if(!xn(e))throw Kt("reactionType","Reaction type");if(!cc.includes(e))throw Ht("reactionType",`one of: ${cc.join(", ")}`,"Reaction type")}async addContentReaction(e){this.validateMessageId(e.messageId),this.validateReactionType(e.reactionType);const t=qe,n={messageId:e.messageId,reactionType:e.reactionType},r=await this.http.post(t,n,this.getMultiAuthHeaders()),s=this.extractData(r),{created:i,...o}=s;return{data:o,created:i}}async removeContentReaction(e){this.validateMessageId(e.messageId),this.validateReactionType(e.reactionType);const t=`${ze}?${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 uc="Token name is required and must be a string";const hc="GALA|Unit|none|none";class gc extends rr{constructor(e,t,n,r=!1){super(r),this.dexBackendHttp=e,this.cache=t,this.fetchTokenDetails=n}async fetchLaunchpadTokenSpotPrice(e,t,n){if(!xn(e))throw new wt(uc,"tokenName",Nt.REQUIRED);let r;if(void 0!==n)try{this.logger.debug(`Checking graduation status for token: ${e}`);const t=await n(e);!0===t.isGraduated&&(r=La(t.sellingToken))}catch(t){this.logger.debug(`Could not determine graduation status for ${e}, falling back to bonding curve: ${Lt(t)}`)}if(void 0!==r)return this.logger.debug(`Token ${e} is graduated, using its swap backend price`),this.fetchMarketUsdPrice(r);try{this.logger.debug(`Using bonding curve calculation for token: ${e}`);const n=await t({tokenName:e,amount:"1",type:"native"}),r=await this.fetchMarketUsdPrice(hc),s=Sn(n.amount,0)/1e18;if(s<=0)throw new wt(`Invalid token amount calculation: ${s}`,"amount","INVALID_CALCULATION");return{symbol:mn(e),price:r.price/s}}catch(t){throw Wt(`Failed to calculate launchpad token spot price for ${e}: ${Lt(t)}`,void 0,Mt(t)?t:void 0)}}async resolveAuthoritativeSymbol(e){if(e===hc)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 Wt("GalaChainService not available for token metadata fetch",500);n=(await this.fetchTokenDetails(e)).symbol}catch(t){throw Wt(`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 Wt(`Token class for ${e} has no symbol`);return this.cache?.setByTokenId(e,{symbol:n}),n}async fetchMarketUsdPrice(e){try{const t=function(e){if(!xn(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 Wt("DEX Backend API client not configured");const n=await this.resolveAuthoritativeSymbol(e),r=await this.dexBackendHttp.request({method:"GET",url:"/market/price",params:{assetIds:t}}),s=null!==r&&"object"==typeof r?r:{},i=Object.keys(s).find(e=>e.toUpperCase()===n.toUpperCase()),o=void 0!==i?s[i]:1===Object.keys(s).length?Object.values(s)[0]:void 0,a=o?.price;if("number"!=typeof a||!Number.isFinite(a))throw new wt(`Invalid price response: no market price for ${t}`,"data","INVALID_RESPONSE");return this.logger.debug(`Swap backend price for ${n}: $${a}`),{symbol:n,price:a}}catch(e){if(e instanceof wt)throw e;throw Wt(`Failed to fetch DEX spot price: ${Lt(e)}`)}}}const mc={BATCH_SIZE:20,FLUSH_INTERVAL_MS:3e3,MAX_QUEUE_SIZE:1e3,FLUSH_ON_PAGE_HIDE:!0,FLUSH_ON_PAGE_UNLOAD:!0,DEBUG:!1},fc={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"};class pc{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 pn({debug:t.debug??!1,context:"EventsBatcherService"}),this.config={batchSize:t.batchSize??mc.BATCH_SIZE,flushIntervalMs:t.flushIntervalMs??mc.FLUSH_INTERVAL_MS,maxQueueSize:t.maxQueueSize??mc.MAX_QUEUE_SIZE,flushOnPageHide:t.flushOnPageHide??mc.FLUSH_ON_PAGE_HIDE,flushOnPageUnload:t.flushOnPageUnload??mc.FLUSH_ON_PAGE_UNLOAD,debug:t.debug??mc.DEBUG},this.setupPageLifecycleListeners()}track(e,t,n){if(this.isShuttingDown)return void this.logger.warn("EventsBatcher is shutting down, ignoring track call");const r={eventType:e,payload:t,clientTimestamp:(new Date).toISOString(),...void 0!==n?.userAddress&&""!==n.userAddress&&{userAddress:n.userAddress},...void 0!==n?.tokenName&&""!==n.tokenName&&{tokenName:n.tokenName},...void 0!==n?.sessionId&&""!==n.sessionId&&{sessionId:n.sessionId}};this.buffer(r),n?.immediate&&this.scheduleFlush(0)}async flush(){if(0===this.eventBuffer.length)return;this.cancelFlushTimer();const e=this.eventBuffer.splice(0);this.logger.debug(`Flushing ${e.length} events`);try{const t=await this.submitEvents(e);this.totalFlushed+=t.accepted,this.lastFlushTime=Date.now(),this.lastError=void 0,this.logger.debug(`Flush successful, accepted ${t.accepted} events`)}catch(t){throw this.eventBuffer.unshift(...e),this.lastError=t instanceof Error?t.message:String(t),this.logger.error(`Flush failed: ${this.lastError}`),t}}getStats(){const e={bufferedCount:this.eventBuffer.length,totalQueued:this.totalQueued,totalFlushed:this.totalFlushed,totalDropped:this.totalDropped};return void 0!==this.lastFlushTime&&(e.lastFlushTime=this.lastFlushTime),void 0!==this.lastError&&(e.lastError=this.lastError),e}configure(e){void 0!==e.batchSize&&(this.config.batchSize=e.batchSize),void 0!==e.flushIntervalMs&&(this.config.flushIntervalMs=e.flushIntervalMs),void 0!==e.maxQueueSize&&(this.config.maxQueueSize=e.maxQueueSize),void 0!==e.flushOnPageHide&&(this.config.flushOnPageHide=e.flushOnPageHide),void 0!==e.flushOnPageUnload&&(this.config.flushOnPageUnload=e.flushOnPageUnload)}async shutdown(e=5e3){if(this.isShuttingDown=!0,this.removePageLifecycleListeners(),0!==this.eventBuffer.length)try{await Promise.race([this.flush(),new Promise((t,n)=>setTimeout(()=>n(new Error("Flush timeout during shutdown")),e))])}catch(e){this.logger.error(`Shutdown flush failed: ${e instanceof Error?e.message:String(e)}`)}}buffer(e){this.eventBuffer.length>=this.config.maxQueueSize&&(this.eventBuffer.shift(),this.totalDropped++,this.logger.warn("Event buffer full, dropped oldest event")),this.eventBuffer.push(e),this.totalQueued++,this.eventBuffer.length>=this.config.batchSize?this.scheduleFlush(0):this.scheduleFlush(this.config.flushIntervalMs)}scheduleFlush(e){null===this.flushTimer&&(this.flushTimer=setTimeout(()=>{this.flushTimer=null,this.flush().catch(e=>{this.logger.error(`Scheduled flush failed: ${e instanceof Error?e.message:String(e)}`)})},e))}cancelFlushTimer(){null!==this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null)}async submitEvents(e){return await this.httpClient.post("/v1/events",{events:e})}setupPageLifecycleListeners(){"undefined"!=typeof document&&(this.config.flushOnPageHide&&document.addEventListener("visibilitychange",this.handleVisibilityChange),this.config.flushOnPageUnload&&window.addEventListener("beforeunload",this.handleBeforeUnload))}removePageLifecycleListeners(){"undefined"!=typeof document&&(this.config.flushOnPageHide&&document.removeEventListener("visibilitychange",this.handleVisibilityChange),this.config.flushOnPageUnload&&window.removeEventListener("beforeunload",this.handleBeforeUnload))}flushWithBeacon(){if("undefined"==typeof navigator||!navigator.sendBeacon)return;const e=this.eventBuffer.splice(0),t=JSON.stringify({events:e});try{const n=this.getBaseUrl();navigator.sendBeacon(`${n}/v1/events`,t)?(this.totalFlushed+=e.length,this.lastFlushTime=Date.now()):(this.eventBuffer.unshift(...e),this.logger.warn("sendBeacon returned false, events re-buffered"))}catch(t){this.eventBuffer.unshift(...e),this.logger.error(`sendBeacon failed: ${t instanceof Error?t.message:String(t)}`)}}getBaseUrl(){const e=this.httpClient.config;return e?.baseUrl??""}}const Ec=["createdAt","eventType","userAddress"],Ac=["last_hour","today","yesterday","last_7_days","last_30_days","custom"],vc=["sdk","frontend","backend","mcp"];function Tc(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function yc(e){return"number"==typeof e&&Number.isFinite(e)}function Sc(e){return Tc(e)&&yc(e.id)&&"string"==typeof e.eventType&&Tc(e.payload)&&"string"==typeof e.createdAt&&"string"==typeof e.updatedAt}function bc(e,t,n){if(!t.some(t=>t===e))throw new wt(`${n} must be one of: ${t.join(", ")}`,n,Nt.INVALID_VALUE)}class Nc extends $o{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async getEventStats(){return function(e){if(!(Tc(e)&&yc(e.totalEvents)&&yc(e.todayEvents)&&yc(e.uniqueUsers)&&yc(e.uniqueTokens)&&Tc(e.eventsByType)))throw Wt("Malformed event statistics response");const t={};for(const[n,r]of Object.entries(e.eventsByType)){if(!yc(r))throw Wt("Malformed event statistics response");t[n]=r}return{totalEvents:e.totalEvents,todayEvents:e.todayEvents,uniqueUsers:e.uniqueUsers,uniqueTokens:e.uniqueTokens,eventsByType:t}}(await this.http.get(st,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 wt("limit must be an integer from 1 to 100","limit",Nt.INVALID_VALUE);if(void 0!==e.page&&(!Number.isInteger(e.page)||e.page<1))throw new wt("page must be a positive integer","page",Nt.INVALID_VALUE);void 0!==e.sortBy&&bc(e.sortBy,Ec,"sortBy"),void 0!==e.sortOrder&&bc(e.sortOrder,["asc","desc"],"sortOrder"),void 0!==e.timePreset&&bc(e.timePreset,Ac,"timePreset"),void 0!==e.source&&bc(e.source,vc,"source")}(e);const t={},n=new URLSearchParams;for(const[r,s]of Object.entries(e))if(void 0!==s&&("string"!=typeof s||""!==s)){if(Array.isArray(s)){const e=s.map(String);if(0===e.length)continue;for(const t of 1===e.length?[...e,...e]:e)n.append(r,t);continue}t[r]=s}const r=n.toString(),s=""===r?rt:`${rt}?${r}`;return function(e){if(!Tc(e)||!Array.isArray(e.data)||!Tc(e.pagination))throw Wt("Malformed events response");const t=e.pagination,n=e.data;if(!(yc(t.page)&&yc(t.limit)&&yc(t.total)&&yc(t.totalPages)&&n.every(Sc)))throw Wt("Malformed events response");return{data:n,pagination:{page:t.page,limit:t.limit,total:t.total,totalPages:t.totalPages}}}(await this.http.get(s,t,this.getDualAuthHeaders()))}}function wc(e){let t;return{requestor:async(n,r)=>{const s="string"==typeof r?.body?JSON.parse(r.body):void 0,{data:i,status:o,headers:a}=await e(n,s);t=i;const c=void 0===i?"":JSON.stringify(i),l="number"==typeof o?o:200;return{ok:l>=200&&l<300,status:l,json:()=>Promise.resolve(i),text:()=>Promise.resolve(c),headers:a??{}}},answer:()=>t}}const kc=new Set(["GATEWAY_READ_REJECTED","GATEWAY_READ_RESPONSE_INVALID"]);class _c extends nr{constructor(e,t=!1){super(e,t)}async fetchGalaBalance(e){return this.fetchTokenBalance(e)}async fetchTokenBalance(e,t=!1){try{const{requestor:n}=wc(async(e,t)=>({data:await this.http.post(e,t)})),r=new g({gatewayBaseUrl:"",httpRequestor:n,requestTimeoutMs:1/0}),{owner:s,collection:i,category:o,type:a,additionalKey:c}=e,l=await r.fetchTokenBalance({owner:s,tokenClassKey:{collection:i,category:o,type:a,additionalKey:c},includeExpiredHolds:t});return void 0===l?null:function(e){if("0"===e.quantity)return null;const{collection:t,category:n}=e.tokenClassKey,r={quantity:e.quantity,collection:t,category:n,tokenId:La(e.tokenClassKey)};return e.inUseHolds.length>0&&(r.inUseHolds=[...e.inUseHolds],r.inUseQuantity=e.inUseQuantity),e.lockedHolds.length>0&&(r.lockedHolds=[...e.lockedHolds],r.lockedQuantity=e.lockedQuantity),void 0===r.lockedQuantity&&void 0===r.inUseQuantity||(r.availableQuantity=e.availableQuantity),r}(l)}catch(e){if(m(e)&&kc.has(e.code))return null;throw Wt(`Failed to fetch token balance from GalaChain: ${Lt(e)}`,void 0,Mt(e)?e:void 0)}}}function Ic(e){if(null==e||"object"!=typeof e)return!1;const t=e;return xn(t.amount)&&(void 0!==t.tokenId||xn(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 Dc(e){if(null==e||"object"!=typeof e)return!1;const t=e;return xn(t.amount)&&(void 0!==t.tokenId||xn(t.tokenName))&&(void 0===t.name||"string"==typeof t.name)}function Cc(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every(Ic)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}function Rc(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every(Dc)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}const Oc=100,Mc=100;var Lc,Uc;!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"}(Lc||(Lc={}));class Fc 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"}(Uc||(Uc={}));class Pc extends Error{constructor(e,t,n){super(e),this.type=t,this.details=n,this.name="TransferError"}}function xc(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 Bc(e,t,n,r="[DEBUG] Token resolution (launchpad)"){const s=await t.resolveTokenToVault(e);if(null!==s){const t=Pa(s);return n.debug(r,{tokenName:e,vaultAddress:s,tokenInstance:{collection:t.collection,category:t.category,type:t.type,instance:t.instance}}),t}throw new wt(`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 Gc extends nr{constructor(e,t,n,r=!1,s){super(e,r),this.wallet=t,this.tokenResolver=n,this.writer=s,this.nativeSigner=t?new Ia(t.privateKey):void 0}writeIdentity(){return void 0!==this.wallet&&void 0!==this.nativeSigner?{signer:this.nativeSigner,walletAddress:Dr(this.wallet.address)}:this.writer}}function $c(e,t){const{collection:n,category:r,type:s,additionalKey:i,instance:o}=e;return{tokenClassKey:{collection:n,category:r,type:s,additionalKey:i},instance:o,quantity:t}}const Kc=new Set(["GATEWAY_WRITE_REJECTED","GATEWAY_RESPONSE_INVALID","GATEWAY_HTTP_ERROR"]);function Hc(e,{signer:t,walletAddress:n}){const{requestor:r,answer:s}=wc((t,n)=>e.postWithMeta(t,n));return{writes:new f({gatewayBaseUrl:"",signer:t,walletAddress:n,httpRequestor:r,requestTimeoutMs:1/0,uniqueKeyPrefix:"galaconnect-operation-"}),answer:s}}async function Wc(e,t,n){let r;try{r=await t(e.writes)}catch(t){throw function(e){return m(e)&&Kc.has(e.code)}(t)&&n(e.answer(),void 0),t}return n(e.answer(),r)}function Vc(e){return void 0===e||""===e?{}:{uniqueKey:e}}const jc=100,qc=100;class zc extends Gc{async lockTokens(e){this.validateLockTokensData(e);const t=this.writeIdentity();if(void 0===t)throw new Fc("Wallet required for token lock operations",Lc.WALLET_REQUIRED);return fo(async()=>{const n=Hc(this.http,t),r=n.writes.walletAddress,s=[],i=[];let o=r;const a=e.tokens.find(e=>void 0!==e.lockAuthority);void 0!==a?.lockAuthority&&(o=Dr(a.lockAuthority));const c=e.tokens.find(e=>void 0!==e.expires),l=e.tokens.find(e=>void 0!==e.name);for(const t of e.tokens){const e=await this.resolveTokenEntry(t);i.push($c(e,t.amount)),s.push({tokenClassKey:{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey},quantity:t.amount,lockAuthority:void 0!==t.lockAuthority?Dr(t.lockAuthority):o})}return Wc(n,t=>t.lockTokens({tokens:i,lockAuthority:o,...void 0!==c?.expires&&{expires:c.expires},...void 0!==l?.name&&{name:l.name},...Vc(e.uniqueKey)}),(e,t)=>(this.assertLockAnswer(e,"Token lock failed"),this.extractLockResult(e,t,s)))},"Token lock failed",this.logger,t=>{throw this.handleLockError(t,"Token lock failed",e)})}async unlockTokens(e){this.validateUnlockTokensData(e);const t=this.writeIdentity();if(void 0===t)throw new Fc("Wallet required for token unlock operations",Lc.WALLET_REQUIRED);return fo(async()=>{const n=[],r=[],s=e.tokens.find(e=>void 0!==e.name);for(const t of e.tokens){const e=await this.resolveTokenEntry(t);r.push($c(e,t.amount)),n.push({tokenClassKey:{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey},quantity:t.amount})}return Wc(Hc(this.http,t),t=>t.unlockTokens({tokens:r,...void 0!==s?.name&&{name:s.name},...Vc(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{xt(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 Fc(`${Lt(t)}${n}`,Lc.NETWORK_ERROR)}}validateSharedTokenEntry(e,t,n){if(void 0===e.tokenId&&void 0===e.tokenName)throw new Fc("Must provide either tokenId or tokenName for token identification",Lc.TOKEN_NOT_FOUND);if(void 0!==e.tokenName)try{qn(e.tokenName,"tokenName",cr)}catch{throw new Fc("Invalid token name format",Lc.TOKEN_NOT_FOUND,{tokenName:e.tokenName})}try{zi(Hi(e.amount))}catch{throw new Fc(Ht(t,"a positive number",n).message,Lc.INVALID_AMOUNT,{amount:e.amount})}}validateLockTokensData(e){if(!Cc(e))throw new Fc("Invalid lock data: missing required fields",Lc.VALIDATION_ERROR);if(e.tokens.length>jc)throw new Fc(`Batch size exceeds maximum limit of ${jc} tokens per lock operation`,Lc.VALIDATION_ERROR);for(const t of e.tokens){if(this.validateSharedTokenEntry(t,"lockAmount","Lock amount"),void 0!==t.lockAuthority&&!Or(t.lockAuthority))throw new Fc("Invalid lock authority address format",Lc.VALIDATION_ERROR,{lockAuthority:t.lockAuthority});if(void 0!==t.expires)try{Cn(t.expires,"expires")}catch{throw new Fc(Ht("expires","a positive integer (epoch milliseconds)","Expires").message,Lc.VALIDATION_ERROR)}}}validateUnlockTokensData(e){if(!Rc(e))throw new Fc("Invalid unlock data: missing required fields",Lc.VALIDATION_ERROR);if(e.tokens.length>qc)throw new Fc(`Batch size exceeds maximum limit of ${qc} tokens per unlock operation`,Lc.VALIDATION_ERROR);for(const t of e.tokens)this.validateSharedTokenEntry(t,"unlockAmount","Unlock amount")}transactionIdOf(e,t){const n=Array.isArray(e.Data)?e.Data[0]:void 0;return t?.transactionId??n?.transactionId??n?.txnId??n?.TxnId??n?.id??void 0}extractLockResult(e,t,n){const r=this.transactionIdOf(e,t),s=t?.blockNumber;return{...void 0!==r&&{transactionId:r},...void 0!==s&&{blockNumber:s},locked:n}}extractUnlockResult(e,t,n){const r=this.transactionIdOf(e,t),s=t?.blockNumber;return{...void 0!==r&&{transactionId:r},...void 0!==s&&{blockNumber:s},unlocked:n}}handleLockError(e,t,n){if(e instanceof Fc)return e;if(m(e)&&"pre_send"===e.phase)return new Fc(`${t}: ${e.message}`,"SIGNING_FAILED"===(r=e.code)?Lc.SIGNATURE_FAILED:"INVALID_TOKEN_REFERENCE"===r?Lc.TOKEN_NOT_FOUND:"INVALID_QUANTITY"===r?Lc.INVALID_AMOUNT:Lc.VALIDATION_ERROR,xc(n));var r;let s=t,i=Lc.NETWORK_ERROR;if(Pt(e)){const n=e.response?.data;if("object"==typeof n&&null!==n){const e=n.Message;"string"==typeof e&&e.length>0&&(s=`${t}: ${e}`);const r="string"==typeof e?e.toLowerCase():"";r.includes("insufficient")||r.includes("balance")?i=Lc.INSUFFICIENT_BALANCE:r.includes("lock")&&r.includes("not found")?i=Lc.LOCK_NOT_FOUND:r.includes("not found")||r.includes("token")?i=Lc.TOKEN_NOT_FOUND:r.includes("authority")?i=Lc.NOT_LOCK_AUTHORITY:r.includes("expired")&&(i=Lc.LOCK_EXPIRED)}}else Mt(e)&&(s=`${t}: ${Lt(e)}`);return new Fc(s,i,xc(n))}async resolveTokenInstance(e){return fo(async()=>Bc(e,this.tokenResolver,this.logger),`Failed to resolve token '${e}'`,this.logger,t=>{if(t instanceof Pc)throw new Fc(Lt(t),Lc.TOKEN_NOT_FOUND);throw new Fc(`Failed to resolve token '${e}': ${Lt(t)}`,Lc.TOKEN_NOT_FOUND,{tokenName:e})})}async resolveTokenEntry(e){if(void 0!==e.tokenId){const t=Ua(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 Fc("Must provide either tokenId or tokenName for token identification",Lc.TOKEN_NOT_FOUND)}}const Xc=new Set(["GATEWAY_READ_REJECTED","GATEWAY_READ_RESPONSE_INVALID","TOKEN_CLASS_NOT_FOUND"]);function Qc(e){const t=e?.Data;return Array.isArray(t)?t:void 0}class Yc extends nr{constructor(e,t=!1,n){super(e,t),this.publicAxios=n}async fetchTokenClassFromChain(e){try{const t="string"==typeof e?Ua(e):e,{collection:n,category:r,type:s,additionalKey:i}=t,o={collection:n,category:r,type:s,additionalKey:i},a="Failed to fetch token class from GalaChain";return await this.readPublic(e=>e.fetchTokenClass(o),e=>{if(xt(e,a),void 0===Qc(e)?.[0])throw Wt(`Token not found on GalaChain: ${La(o)}`,404)},()=>Wt(`Token not found on GalaChain: ${La(o)}`,404))}catch(e){return this.handleTokenServiceError(e,"Token not found on GalaChain","Failed to fetch token class from GalaChain")}}async fetchTokenClassesWithSupply(e){try{if(null==e||0===e.length)throw Kt("tokenClasses","Token classes array");return await this.readPublic(t=>t.fetchTokenClassesWithSupply(e),e=>{if(xt(e,"Failed to fetch token classes with supply from GalaChain"),0===(Qc(e)?.length??0))throw Wt("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 Kt("publicAxios","Public Axios instance");const r=this.publicAxios,{requestor:s,answer:i}=wc(async(e,t)=>{const n=await r.post(e,t);return{data:n.data,status:n.status}});try{return await e(new g({gatewayBaseUrl:"",httpRequestor:s,requestTimeoutMs:1/0}))}catch(e){if(m(e)&&Xc.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 wt)throw e;if(Pt(e)&&404===e.response?.status)throw Wt(t,404,Mt(e)?e:void 0);if(Mt(e)&&"Error"===e.name&&Lt(e).includes("status indicates failure"))throw Wt(Lt(e),400,Mt(e)?e:void 0);const r=Lt(e);if(r.includes("Token not found")){if(e instanceof Error)throw e;throw new Error(r)}throw Wt(`${n}: ${r}`,void 0,Mt(e)?e:void 0)}}function Jc(e){if(null==e||"object"!=typeof e)return!1;const t=e;return xn(t.amount)&&(void 0!==t.tokenId||xn(t.tokenName))}function Zc(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every(Jc)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}const el=50;var tl;!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"}(tl||(tl={}));class nl extends Error{constructor(e,t,n){super(e),this.type=t,this.details=n,this.name="BurnError"}}const rl={validateAmount(e){const t=Hi(e);try{Qi(t,"amount")}catch(t){throw new Pc(t.message,Uc.INVALID_AMOUNT,{amount:e})}},validateUniqueKey(e){if(!Gn(e)&&xn(e)){if(e.length>Tr.MAX_LENGTH)throw new wt(`Unique key too long. Maximum length: ${Tr.MAX_LENGTH}`);if(!Tr.PATTERN.test(e))throw new Pc('Invalid unique key format. Must start with "galaswap-operation-" or "galaconnect-operation-"',Uc.INVALID_AMOUNT,{uniqueKey:e})}}},sl="gala-transfer-successful",il="token-transfer-successful",ol="token-locked-successfully",al="token-unlocked-successfully",cl="transfer-successful-no-id",ll=50;class dl extends Gc{async transferGala(e){this.validateTransferGalaData(e);const t=this.writeIdentity();if(void 0===t)throw new Pc("Wallet required for GALA transfer operations",Uc.WALLET_REQUIRED);try{const n=Dr(e.recipientAddress),r=Hc(this.http,t);return await Wc(r,t=>t.transferGala({to:n,quantity:e.amount,...Vc(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 Pc("Wallet required for token transfer operations",Uc.WALLET_REQUIRED);try{const n=Dr(e.to),r=await this.tokenInstanceOf(e.tokenId,e.tokenName,()=>new Pc("Must provide either tokenId or tokenName for token identification",Uc.TOKEN_NOT_FOUND)),s=Hc(this.http,t);return await Wc(s,t=>t.transferToken({to:n,...$c(r,e.amount),...Vc(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 Pc)throw t;throw new Pc(`Failed to resolve token class key for '${e}': ${Lt(t)}`,Uc.TOKEN_NOT_FOUND,{tokenName:e})}}async burnTokens(e){this.validateBurnTokensData(e);const t=this.writeIdentity();if(void 0===t)throw new nl("Wallet required for token burn operations",tl.WALLET_REQUIRED);try{const n=[];for(const t of e.tokens){const e=await this.tokenInstanceOf(t.tokenId,t.tokenName,()=>new nl("Must provide either tokenId or tokenName for token identification",tl.TOKEN_NOT_FOUND));n.push($c(e,t.amount))}const r=Hc(this.http,t);return await Wc(r,t=>t.burnTokens({tokens:n,...Vc(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 xn(t.recipientAddress)&&xn(t.amount)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)}(e))throw new wt("Invalid GALA transfer data: missing required fields");if(!Or(e.recipientAddress))throw new Pc("Invalid recipient address format",Uc.INVALID_RECIPIENT,{recipientAddress:e.recipientAddress});rl.validateAmount(e.amount),rl.validateUniqueKey(e.uniqueKey)}validateTransferTokenData(e){if(!function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return xn(t.to)&&xn(t.amount)&&(void 0!==t.tokenId||xn(t.tokenName))&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)}(e))throw new wt("Invalid token transfer data: missing required fields");if(!Or(e.to))throw new Pc("Invalid recipient address format",Uc.INVALID_RECIPIENT,{recipientAddress:e.to});if(!(null!==e.tokenId&&void 0!==e.tokenId||null!==e.tokenName&&void 0!==e.tokenName))throw new Pc("Must provide either tokenId or tokenName for token identification",Uc.TOKEN_NOT_FOUND);if(null!==e.tokenName&&void 0!==e.tokenName)try{qn(e.tokenName,"tokenName",cr)}catch{throw new Pc("Invalid token name format",Uc.TOKEN_NOT_FOUND,{tokenName:e.tokenName})}rl.validateAmount(e.amount),rl.validateUniqueKey(e.uniqueKey)}validateBurnTokensData(e){if(!Zc(e))throw new nl("Invalid burn data: missing required fields",tl.VALIDATION_ERROR);if(e.tokens.length>ll)throw new nl(`Batch size exceeds maximum limit of ${ll} tokens per burn operation`,tl.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 nl("Must provide either tokenId or tokenName for token identification",tl.TOKEN_NOT_FOUND);const e=Hi(t.amount);try{zi(e)}catch{throw new nl("Burn amount must be a positive number",tl.INVALID_AMOUNT,{amount:t.amount})}}}async tokenInstanceOf(e,t,n){if(null!=e){const t=Ua(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 Bc(e,this.tokenResolver,this.logger,`[DEBUG] Token resolution for '${e}' (launchpad):`)}catch(t){if(t instanceof Pc)throw t;throw new Pc(`Failed to resolve token '${e}': ${Lt(t)}`,Uc.TOKEN_NOT_FOUND,{tokenName:e})}}extractTransferResult(e,t,n){if(null==e)throw new Pc("No response from GalaChain transfer service",Uc.NETWORK_ERROR);const r=t?.blockNumber,s="object"==typeof e&&"Status"in e;s&&xt(e,"Extract transaction ID");const i=s&&"Data"in e,o=t?.transactionId;if(void 0!==o)return{transactionId:o,...void 0!==r?{blockNumber:r}:{}};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!==r?{blockNumber:r}:{}}}}let e=cl;if(t.Data.length>0)switch(n){case"gala":e=sl;break;case"token":e=il;break;case"lock":e=ol;break;case"unlock":e=al}return{transactionId:e,...void 0!==r?{blockNumber:r}:{}}}}throw new Pc("Operation succeeded but transaction ID could not be extracted (missing x-transaction-id header and body fields)",Uc.NETWORK_ERROR)}burnResultOf(e,t){if(null==e)throw new nl("No response from GalaChain burn service",tl.NETWORK_ERROR);try{xt(e,"Token burn operation")}catch(e){throw new Ct(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 r=Array.isArray(e.Data)?e.Data[0]:void 0,s=t?.transactionId??r?.transactionId??r?.txnId??r?.TxnId??r?.id??void 0,i=t?.blockNumber;return{...void 0!==s&&{transactionId:s},...void 0!==i&&{blockNumber:i},burned:n}}handleTransferError(e,t,n){if(e instanceof Pc)return e;if(e instanceof wt)return new Pc(Lt(e),Uc.INVALID_AMOUNT);if(m(e)&&"pre_send"===e.phase)return new Pc(e.message,"SIGNING_FAILED"===(r=e.code)?Uc.SIGNATURE_FAILED:"INVALID_WALLET_ADDRESS"===r?Uc.INVALID_RECIPIENT:"INVALID_TOKEN_REFERENCE"===r?Uc.TOKEN_NOT_FOUND:Uc.INVALID_AMOUNT);var r;if(Pt(e)&&e.response){const t=e.response.status,r=e.response.data;if(400===t){const e=r?.message;return new Pc(("string"==typeof e?e:void 0)??"Invalid transfer request",Uc.INVALID_AMOUNT)}if(403===t)return new Pc("Insufficient balance for transfer",Uc.INSUFFICIENT_BALANCE);if(404===t){const e={};return"tokenName"in n&&(e.tokenName=n.tokenName),new Pc("Token not found",Uc.TOKEN_NOT_FOUND,e)}}if("object"==typeof e&&null!==e&&"code"in e&&("ECONNABORTED"===Ft(e)||"ETIMEDOUT"===Ft(e)))return new Pc("Transfer request timed out",Uc.NETWORK_ERROR);const s=""!==Lt(e)?Lt(e):t;return new Pc(s,Uc.NETWORK_ERROR)}handleBurnError(e,t,n){if(e instanceof nl)return e;if(m(e)&&"pre_send"===e.phase)return new nl(`${t}: ${e.message}`,"SIGNING_FAILED"===(r=e.code)?tl.SIGNATURE_FAILED:"INVALID_TOKEN_REFERENCE"===r?tl.TOKEN_NOT_FOUND:"INVALID_QUANTITY"===r?tl.INVALID_AMOUNT:tl.VALIDATION_ERROR,xc(n));var r;let s=t,i=tl.NETWORK_ERROR;if(Pt(e)){const n=e.response?.data;if("object"==typeof n){const e=n.Message;if("string"==typeof e&&e.length>0){s=`${t}: ${e}`;const n=e.toLowerCase();n.includes("insufficient")||n.includes("balance")?i=tl.INSUFFICIENT_BALANCE:(n.includes("not found")||n.includes("token"))&&(i=tl.TOKEN_NOT_FOUND)}}}else Mt(e)&&(s=`${t}: ${Lt(e)}`);return new nl(s,i,xc(n))}}class ul extends nr{constructor(e,t,n,r=!1,s,i){super(e,r),this.balanceService=new _c(e,r),this.tokenService=new Yc(e,r,s),this.lockService=new zc(e,t,n,r,i),this.transferService=new dl(e,t,n,r,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 p(await this.fetchTokenClassFromChain(e))}catch(t){if(Mt(t)&&("NetworkError"===t.name||Lt(t).includes("Token not found")))throw t;throw Wt(`Failed to fetch token details from GalaChain for ${"string"==typeof e?e:La(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)}}class hl extends nr{async getHealth(){const e=(await this.http.get(it)).data;if(null==e)throw Wt("Health check answered no data");return e}}class gl extends Error{constructor(e,t,n){super(e),this.filename=t,this.mimeType=n,this.name="FileValidationError"}}function ml(e,t,n){if(null==e)throw new gl("File is required",t,n);if("undefined"!=typeof File&&e instanceof File){const t=ps.safeParse(e);if(!t.success){const n=t.error.issues.map(e=>e.message).join("; ");throw new gl(n,e.name,e.type)}return}if(Buffer.isBuffer(e)){if(void 0===t||""===t)throw new gl("Filename is required when uploading Buffer objects",t,n);const r=Es.safeParse(e);if(!r.success){const e=r.error.issues.map(e=>e.message).join("; ");throw new gl(e,t,n)}try{Dn(t,255,"filename")}catch(e){throw new gl(e.message,t,n)}const s=["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"];if(!s.includes(n))throw new gl(`Invalid file type "${n}" is not allowed. Allowed types: ${s.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),o=[".png",".jpg",".jpeg",".gif",".webp",".svg"];if(!o.includes(i))throw new gl(`File extension "${i}" is not allowed. Allowed extensions: ${o.join(", ")}`,t,n);const a=function(e){switch(e.toLowerCase()){case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";case".gif":return"image/gif";case".webp":return"image/webp";case".svg":return"image/svg+xml";default:return"application/octet-stream"}}(i);if(a!==n&&"application/octet-stream"!==a)throw new gl(`File extension "${i}" does not match MIME type "${n}"`,t,n);return}throw new gl("File must be a File object (browser) or Buffer (Node.js)",t,n)}function fl(e,t="image",n){const r=new FormData;if("undefined"!=typeof File&&e instanceof File)r.append(t,e);else{if(!Buffer.isBuffer(e))throw Ht("file","a File object (browser) or Buffer (Node.js)");{const s=new Blob([e],{type:"image/png"});r.append(t,s,n)}}return r}class pl extends nr{constructor(e,t,n=!1){super(e,n,t)}async uploadImageByTokenName(e){const{tokenName:t,options:n}=e;Wn(t,"tokenName",cr);const r=`${t}.png`;ml(n.file,r,"image/png");try{const e=fl(n.file,"image",r),s=await an(()=>this.http.request({method:"POST",url:xo(C.UPLOAD_IMAGE,{tokenName:t}),data:e,headers:this.getJwtHeaders()}),{errorContext:"Image upload failed"});return"string"==typeof s?s:""}catch(e){if(e instanceof Rt)throw e;if(Mt(e)&&Lt(e).includes("FormData"))throw Vt("File upload failed: FormData not supported in this environment. Ensure you have proper polyfills for Node.js environments.","FormData");throw e}}}function El(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 wt("At least one config option must be provided (chatEnabled, commentsEnabled, streamingEnabled, nextLiveStreamAt, streamLanguage, or social URLs)","options",Nt.REQUIRED);if(void 0!==e.chatEnabled&&"boolean"!=typeof e.chatEnabled)throw Qt("chatEnabled","boolean");if(void 0!==e.commentsEnabled&&"boolean"!=typeof e.commentsEnabled)throw Qt("commentsEnabled","boolean");if(void 0!==e.streamingEnabled&&"boolean"!=typeof e.streamingEnabled)throw Qt("streamingEnabled","boolean");if(void 0!==e.streamLanguage&&"string"!=typeof e.streamLanguage)throw Qt("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 Qt(n,"string or null")}if(void 0!==e.nextLiveStreamAt&&null!==e.nextLiveStreamAt){if("string"!=typeof e.nextLiveStreamAt)throw Qt("nextLiveStreamAt","string or null");const t=new Date(e.nextLiveStreamAt);if(isNaN(t.getTime()))throw new wt("nextLiveStreamAt must be a valid ISO date string","nextLiveStreamAt",Nt.INVALID_FORMAT)}}function Al(e){if(Gn(e)||"object"!=typeof e)return{};const t={};for(const[n,r]of Object.entries(e))Gn(r)||(xn(r)?t[n]=r:"number"==typeof r||"boolean"==typeof r?t[n]=r.toString():Array.isArray(r)?t[n]=r.join(","):t[n]="object"==typeof r?JSON.stringify(r):String(r));return t}var vl=Object.freeze({__proto__:null,adaptQueryParams:Al});function Tl(e,t){if(null==e)return[];if(Array.isArray(e))return e;const n=e[t];return Array.isArray(n)?n:[]}function yl(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.owner&&""!==t.owner}function Sl(e){return"string"==typeof e.quantity&&""!==e.quantity}class bl extends nr{constructor(e,t,n=!1){super(e,n,t)}async fetchPools(e={}){const t=function(e){const t=e.pageSize??wo.DEFAULT_LIMIT;if(!Number.isInteger(t)||t<1||t>St)throw qt("pageSize",1,St,t);const n={pageSize:String(t)};xn(e.cursor)&&(n.cursor=e.cursor);void 0!==e.type&&(n.type=_l("type",e.type,Tt));xn(e.tokenName)&&(Wn(e.tokenName,"tokenName",or),n.tokenName=e.tokenName);if(xn(e.search)){if(e.search.length>Nl)throw en("search",Nl,e.search.length);n.search=e.search}!0===e.hasUpcomingShows&&(n.hasUpcomingShows="true");if(xn(e.language)){if(!kl.test(e.language))throw Ht("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>wl)throw qt("recentlyStreamed",1,wl,t);n.recentlyStreamed=String(t)}!0===e.hasRecordings&&(n.hasRecordings="true");void 0!==e.streamStatus&&(n.streamStatus=_l("streamStatus",e.streamStatus,yt));return n}(e),n=sn(await ln(()=>this.http.get(C.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:Mo(n?.pageInfo)}}async fetchAllPools(e){const t=[];let n;for(;;){const r={...e,pageSize:100,...void 0!==n&&{cursor:n}},s=await this.fetchPools(r);if(t.push(...s.items),0===s.items.length)break;const i=Lo(s.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=Ti(e);!t.success&&t.errors&&no(t.errors,"options")}(e),xn(e.tokenName)&&Wn(e.tokenName,"tokenName",lr);try{const t=await this.http.post(C.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===xn(e.symbol)){return!n.symbolAvailable}if(!0===xn(e.tokenName)){return!n.nameAvailable}return!1}catch(e){const t=String(e),n=e,r="string"==typeof n.message?n.message:"";if(t.includes("404")||t.includes("Pool not found")||r.includes("404")||r.includes("Pool not found"))return!1;const s="number"==typeof n.statusCode?n.statusCode:null;if(404===s)return!1;if(t.includes("400")||t.includes("Missing required pool identifier")||r.includes("400")||r.includes("Missing required pool identifier"))return!1;if(400===s&&r.includes("Missing required pool identifier"))return!1;throw e}}async isTokenNameAvailable(e){try{return!await this.checkPool({tokenName:e})}catch{return!1}}async isTokenSymbolAvailable(e){try{return!await this.checkPool({symbol:e})}catch{return!1}}async fetchVolumeData(e){if(!function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Pi(t,"tokenName")&&Bi(t,"from")&&Bi(t,"to")&&Bi(t,"resolution")}(e))throw new wt("Invalid options provided. Expected { tokenName: string, from?: number, to?: number, resolution?: number }","options","INVALID_OPTIONS");const{tokenName:t,from:n,to:r,resolution:s}=e;if(Wn(t,"tokenName",or),null==n||null==r||null==s)throw new wt("Graph options (from, to, resolution) are required","options","MISSING_GRAPH_OPTIONS");const i={tokenName:t,from:n,to:r,resolution:s};so(i);const o=Al(i),a=await an(()=>this.http.get(C.CHART,o),{errorContext:"Failed to fetch graph data"});if(!Array.isArray(a.data)||"boolean"!=typeof a.isPreviousData)throw new Ct("Invalid chart response: expected { data: candles, isPreviousData }");return{dataPoints:a.data,isPreviousData:a.isPreviousData,..."number"==typeof a.nextTime&&{nextTime:a.nextTime}}}async fetchTokenDistribution(e){if(""===e||null==e)throw Kt("tokenName","Token name");let t;Wn(e,"tokenName",or);try{t=await ln(()=>this.http.get(`${C.GET_TOKEN_DISTRIBUTION}?tokenName=${e}`),{errorContext:"Failed to fetch token distribution"})}catch(t){if(Pt(t)&&500===t.response?.status)throw Wt(`Token distribution data temporarily unavailable for ${e}. This is a backend issue - please try again later.`,500,Mt(t)?t:void 0);throw t}return function(e,t,n=Wi){if(!Array.isArray(e))throw Wt("Invalid API response: expected array of holders",t);for(const n of e){if(!yl(n))throw Wt("Invalid holder data: missing or invalid owner field",t);if(!Sl(n))throw Wt("Invalid holder data: missing or invalid quantity field",t);const e=Sn(n.quantity,NaN);if(isNaN(e)||!isFinite(e))throw Wt(`Invalid holder quantity: "${n.quantity}"`,t)}const r=e,s=r.reduce((e,t)=>e.plus(t.quantity),Hi(0));return{holders:r.map(e=>({address:e.owner,balance:e.quantity,percentage:Yi(Hi(e.quantity),s,Hi(0)).multipliedBy(100).toNumber()})),totalSupply:n(s),totalHolders:r.length,lastUpdated:new Date}}(sn(t),t.status,e=>e.toFixed())}async fetchUserHolderContext(e,t){if(""===e||null==e)throw Kt("tokenName","Token name");if(""===t||null==t)throw Kt("userAddress","User address");return Wn(e,"tokenName",or),an(()=>this.http.get(`${C.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");Wn(e,"tokenName",cr);try{const t=C.GET_TOKEN.replace(":tokenName",e.toLowerCase().trim()),n=sn(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 Ct?new Ct(`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&&Wn(e.tokenName,"tokenName",lr);try{const t=await this.http.post(C.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(!xn(e))throw Kt("tokenName","Token name");Wn(e,"tokenName",cr);const t=C.TOKEN_STATS.replace(":tokenName",e.toLowerCase().trim());try{const e=sn(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 Kt("tokenName","Token name");Wn(e,"tokenName",cr),El(t);const n=C.UPDATE_TOKEN_CONFIG.replace(":tokenName",e.toLowerCase().trim()),r={};void 0!==t.chatEnabled&&(r.chatEnabled=t.chatEnabled),void 0!==t.commentsEnabled&&(r.commentsEnabled=t.commentsEnabled),void 0!==t.streamingEnabled&&(r.streamingEnabled=t.streamingEnabled),void 0!==t.nextLiveStreamAt&&(r.nextLiveStreamAt=t.nextLiveStreamAt),void 0!==t.streamLanguage&&(r.streamLanguage=t.streamLanguage),void 0!==t.websiteUrl&&(r.websiteUrl=t.websiteUrl),void 0!==t.telegramUrl&&(r.telegramUrl=t.telegramUrl),void 0!==t.twitterUrl&&(r.twitterUrl=t.twitterUrl),void 0!==t.instagramUrl&&(r.instagramUrl=t.instagramUrl),void 0!==t.facebookUrl&&(r.facebookUrl=t.facebookUrl),void 0!==t.redditUrl&&(r.redditUrl=t.redditUrl),void 0!==t.tiktokUrl&&(r.tiktokUrl=t.tiktokUrl),await this.http.patch(n,r,this.getJwtHeaders())}async getTokenConfig(e){if(!xn(e))throw Kt("tokenName","Token name");Wn(e,"tokenName",cr);const t=C.UPDATE_TOKEN_CONFIG.replace(":tokenName",e.toLowerCase().trim()),n=sn(await this.http.get(t));if(void 0===n)throw new Error(`Invalid response: missing token config data for "${e}"`);return n}}const Nl=255,wl=720,kl=/^[a-z]{2}(-[A-Z]{2})?$/u;function _l(e,t,n){const r="string"==typeof t?t.toUpperCase():void 0,s=n.find(e=>e===r);if(void 0===s)throw Jt(e,t,n);return s}function Il(e){if(void 0!==e.tokenName){if(!xn(e.tokenName))throw Qt("tokenName","a non-empty string",typeof e.tokenName);qn(e.tokenName,"tokenName",or)}if(void 0!==e.userAddress){if(!xn(e.userAddress))throw Qt("userAddress","a non-empty string",typeof e.userAddress);if(e.userAddress.length>fr)throw Xt("userAddress",fr,e.userAddress.length)}if(void 0!==e.search){if("string"!=typeof e.search)throw Qt("search","a string",typeof e.search);if(e.search.length>256)throw Xt("search",256,e.search.length)}if($n(0,void 0,gr,e.pageSize),void 0!==e.txnType&&"BUY"!==e.txnType&&"SELL"!==e.txnType)throw Ht("txnType",'"BUY" or "SELL"');if(void 0!==e.startDate){if(!xn(e.startDate))throw Qt("startDate","a non-empty string",typeof e.startDate);if(isNaN(Date.parse(e.startDate)))throw Ht("startDate","a valid ISO 8601 date")}if(void 0!==e.endDate){if(!xn(e.endDate))throw Qt("endDate","a non-empty string",typeof e.endDate);if(isNaN(Date.parse(e.endDate)))throw Ht("endDate","a valid ISO 8601 date")}if(void 0!==e.minAmount)try{In(e.minAmount,0,Number.MAX_SAFE_INTEGER,"minAmount")}catch{throw Ht("minAmount","a non-negative number")}if(void 0!==e.maxAmount)try{In(e.maxAmount,0,Number.MAX_SAFE_INTEGER,"maxAmount")}catch{throw Ht("maxAmount","a non-negative number")}void 0!==e.minAmount&&void 0!==e.maxAmount&&function(e,t,n="range"){const r="number"==typeof e?e:Number(e),s="number"==typeof t?t:Number(t);if(isNaN(r)||isNaN(s))throw Qt(n,"numeric values",void 0,n);if(r>s)throw new wt(`Minimum value (${r}) must be less than or equal to maximum value (${s}) for ${n}`,n,Nt.INVALID_RANGE)}(e.minAmount,e.maxAmount,"amountRange")}class Dl extends nr{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 Pi(t,"tokenName")&&(void 0===t.tradeType||"buy"===t.tradeType||"sell"===t.tradeType)&&xi(t,"userAddress")&&Bi(t,"offset")&&Bi(t,"pageSize")&&Bi(t,"page")&&Bi(t,"limit")}(e))throw new wt("Invalid options provided. Expected { tokenName: string, tradeType?: string, userAddress?: string, cursor?: string, pageSize?: number, startDate?: Date, endDate?: Date, sortOrder?: string }","options","INVALID_OPTIONS");const{tokenName:t,cursor:n,pageSize:r=wo.DEFAULT_LIMIT}=e;if(!xn(t))throw Kt("tokenName","Token name");const s={pageSize:String(Math.min(r,hr))};void 0!==n&&(s.cursor=n);const i=await this.http.get(xo(C.GET_TRADES,{tokenName:t}),s);if(null==i)throw new wt("No response from trade service","response","NO_RESPONSE");const o=sn(i),a=Tl(o,"trades"),c=o?.pageInfo;return{items:a,pageInfo:c??{hasNextPage:!1}}}buildTradesQueryParams(e){const t={};null!==e.tokenName&&void 0!==e.tokenName&&e.tokenName.length>0&&(t.tokenName=hn(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?Do(e.pageSize,1,gr):gr;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){Il(e);const t=this.buildTradesQueryParams(e);return an(()=>this.http.get(Xe,t),{errorContext:"Failed to fetch trades"})}}cr.MIN_LENGTH,cr.MAX_LENGTH;function Cl(e){return!!xn(e)&&mr.PATTERN.test(e)}function Rl(e,t,n=1){if(null==e||""===e)return null;if("string"!=typeof e)return null;const r=e.trim();return r.length<n?null:r}function Ol(e,t){return e.toLowerCase()===t.toLowerCase()}function Ml(e){return e.toLowerCase()}function Ll(e,t){return e.toLowerCase().includes(t.toLowerCase())}function Ul(e,t,n,r){return e===n&&t===r||e===r&&t===n}function Fl(e){if(""===e||"string"!=typeof e)return null;if(e.includes("|")){const t=e.split("|");if(t.length>=2){const e=t[1];if(void 0!==e&&xl(e))return Bl(e)}return null}return xl(e)?Bl(e):null}function Pl(e){return null==e||"string"!=typeof e||0===e.trim().length}function xl(e){if(""===e||"string"!=typeof e)return!1;const t=e.startsWith("0x")?e.slice(2):e;return/^[0-9a-fA-F]{40}$/.test(t)}function Bl(e){return e.startsWith("0x")?e.slice(2):e}Kn({BOTH:"both",HELD:"held",CREATED:"created"});function Gl(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function $l(e){return"number"==typeof e&&Number.isFinite(e)}function Kl(e){return null===e||"string"==typeof e}function Hl(e){return Array.isArray(e)&&e.every(e=>Gl(e)&&"string"==typeof e.badgeName&&"boolean"==typeof e.isActive)}function Wl(e){return Gl(e)&&"string"==typeof e.address&&Kl(e.fullName)&&Kl(e.profileImage)&&Kl(e.bio)&&function(e){return Gl(e)&&$l(e.tokensCreated)&&$l(e.tokensGraduated)&&$l(e.graduationRate)&&$l(e.totalTrades)&&"string"==typeof e.totalVolumeGala&&Kl(e.totalVolumeUsd)&&(null===e.holdingsCount||$l(e.holdingsCount))&&Kl(e.accountCreatedAt)&&$l(e.accountAgeDays)}(e.stats)&&Hl(e.launchBadge)&&Hl(e.successBadge)&&Hl(e.volumeBadge)&&Hl(e.engagementBadge)&&"boolean"==typeof e.isLiveStreaming&&Kl(e.liveStreamToken)}class Vl extends nr{constructor(e,t,n=!1){super(e,n,t)}async fetchProfile(e){const t=e??this.http.getAddress();if(""===t||null==t||!Cl(t))throw Ht("address","eth|[40-hex-chars] or client|[identifier]","Address");if(void 0===e){const e=await an(()=>this.http.get(C.GET_CURRENT_USER,void 0,this.getJwtHeaders()),{errorContext:"Failed to fetch profile"});if(!(Gl(n=e)&&"string"==typeof n.address&&Kl(n.fullName)&&Kl(n.profileImage)&&"string"==typeof n.bio&&Hl(n.launchBadge)&&Hl(n.successBadge)))throw Wt("Malformed profile response");return e}var n;const r=await an(()=>this.http.get(C.GET_PROFILE.replace(":address",t)),{errorContext:"Failed to fetch profile"});if(!Wl(r))throw Wt("Malformed profile response");return r}async updateProfile(e){this.validateUpdateProfileData(e);const t={};void 0!==e.fullName&&(t.fullName=e.fullName.trim()),void 0!==e.profileImage&&(t.profileImage=e.profileImage),await an(()=>this.http.put(C.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=fl(e.file,"image",t),r=await an(()=>this.http.request({method:"POST",url:C.UPLOAD_PROFILE_IMAGE,data:n,headers:this.getJwtHeaders()}),{errorContext:"Image upload failed"});return"string"==typeof r?r:""}catch(e){if(e instanceof wt||e instanceof Rt)throw e;if(e instanceof Ct)throw new Ct(`Profile image upload failed: ${Lt(e)}`,e.statusCode,e);throw new wt(`Profile image upload failed: ${Lt(e)}`,"file","UPLOAD_FAILED")}}async fetchTokenList(e){if(void 0!==e.status&&"created"!==e.type)throw new wt("status filters only apply when type=created","status","INVALID_FILTER");const t=e.tokenName,n={...e},r="created"===e.type;r&&(delete n.tokenName,void 0!==t&&void 0===n.search&&(n.search=t));const s=await this.buildFetchRequest(C.GET_TOKEN_LIST,n,{includeType:!0,requestType:e.type??"both",responseKey:r?"launches":"token",errorMessage:"Failed to fetch token list"});return r&&void 0!==t?{...s,tokens:s.tokens.filter(e=>e.tokenName===t||e.name===t)}:s}async fetchTokensHeld(e){if(void 0!==e.type&&"held"!==e.type)throw new wt("fetchTokensHeld only supports type=held","type","INVALID_TYPE");if(void 0!==e.status)throw new wt("status filters only apply when type=created","status","INVALID_FILTER");return this.buildFetchRequest(C.GET_TOKENS_HELD,e,{includeType:!0,requestType:"held",responseKey:"token",errorMessage:"Failed to fetch tokens held"})}async fetchTokensCreated(e){const{cursor:t,pageSize:n,search:r,tokenName:s,status:i}=e??{};if(void 0!==e?.type&&"created"!==e.type)throw new wt("fetchTokensCreated only supports type=created","type","INVALID_TYPE");const o=e?.address??this.http.getAddress();if(null==o||""===o)throw new wt("Wallet address not available - wallet not configured","address","NO_WALLET");const a={type:"created",address:o,pageSize:n??wo.DEFAULT_LIMIT};return void 0!==t&&(a.cursor=t),void 0!==r&&(a.search=r),void 0!==s&&void 0===r&&(a.search=s),void 0!==s&&(a.tokenName=s),void 0!==i&&(a.status=i),this.fetchTokenList(a)}async getManagedTokens(e={}){const t={};return void 0!==e.cursor&&(t.cursor=e.cursor),void 0!==e.pageSize&&(t.pageSize=String(Math.min(e.pageSize,hr))),an(()=>this.http.get(C.GET_MANAGED_TOKENS,t,this.getJwtHeaders()),{errorContext:"Failed to fetch managed tokens"})}async getUserGalaBalance(e){if("string"!=typeof e||""===e.trim())throw Kt("address","Address");return an(()=>this.http.get(xo(C.GET_GALA_BALANCE,{address:e.trim()})),{errorContext:"Failed to fetch GALA balance"})}async fetchReferralCode(){return an(()=>this.http.get(C.GET_REFERRAL_CODE,void 0,this.getJwtHeaders()),{errorContext:"Failed to fetch referral code"})}async buildFetchRequest(e,t,n){this.validateGetTokenListOptions(t);const r=Fo({pageSize:t.pageSize??wo.DEFAULT_LIMIT,...void 0!==t.cursor&&{cursor:t.cursor}},hr);Bo(r,t,["address","search","tokenName","status"]),n.includeType&&!e.includes("?type=")&&(r.type=n.requestType);let s=e;const i=t.address??this.http.getAddress();if(e.includes(":address")){if(0===i.length)throw Kt("address","User address");s=e.replace(":address",i),delete r.address}const o=sn(await ln(()=>this.http.get(s,r),{errorContext:n.errorMessage}));return{tokens:Tl(o,n.responseKey).map(e=>{const t="string"==typeof e.tokenName?e.tokenName:"",r="string"==typeof e.name?e.name:t,s="string"==typeof e.createdAt?e.createdAt:"",o=e.metadata,a={...e};return delete a.metadata,{...a,id:"string"==typeof e.id?e.id:t,name:r,symbol:"string"==typeof e.symbol?e.symbol:"",type:n.requestType,address:i,balance:"string"==typeof e.balance?e.balance:"string"==typeof e.quantity?e.quantity:"0",decimals:"number"==typeof e.decimals?e.decimals:0,...null!==o&&"object"==typeof o?{metadata:o}:{},createdAt:s,updatedAt:"string"==typeof e.updatedAt?e.updatedAt:s}}),pageInfo:Mo(o?.pageInfo)}}validateGetTokenListOptions(e){const t=e.pageSize??wo.DEFAULT_LIMIT;if(t<1||t>hr)throw new wt(`pageSize must be between 1 and ${hr}`,"pageSize","OUT_OF_RANGE");if(void 0!==e.address&&!Cl(e.address))throw Ht("address","eth|[40-hex-chars] or client|[identifier]","Address");const n=Rl(e.search);if(null!==n&&!(xn(r=n)&&r.length>=Sr&&r.length<=br))throw qt("search",Sr,br,n.length,"Search query");var r;const s=Rl(e.tokenName);if(!(null===s||xn(i=s)&&cr.PATTERN.test(i)))throw Ht("tokenName",cr.DESCRIPTION,"Token name");var i}validateUpdateProfileData(e){if(void 0!==e.address&&!Cl(e.address))throw Ht("address","eth|[40-hex-chars] or client|[identifier]","Address");if(void 0===e.fullName&&void 0===e.profileImage)throw new wt("At least one of fullName and profileImage must be provided","options","REQUIRED");if(void 0!==e.fullName&&(t=e.fullName.trim(),!(xn(t)&&t.length>=Nr.FULL_NAME.MIN_LENGTH&&t.length<=Nr.FULL_NAME.MAX_LENGTH&&Nr.FULL_NAME.ALPHABETS_ONLY_PATTERN.test(t))))throw qt("fullName",Nr.FULL_NAME.MIN_LENGTH,Nr.FULL_NAME.MAX_LENGTH,e.fullName.trim().length,"Full name");var t;if("string"==typeof e.profileImage&&e.profileImage.trim().length>2048)throw new wt("profileImage must not exceed 2048 characters","profileImage","TOO_LONG")}validateUploadProfileImageOptions(e){if(void 0!==e.address&&!Cl(e.address))throw Ht("address","eth|[40-hex-chars] or client|[identifier]","Address")}}class jl{constructor(e,t,n=!1){this.http=e,this.poolService=new bl(e,t,n),this.tradeService=new Dl(e,n),this.userService=new Vl(e,t,n),this.imageService=new pl(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 ro(e)}async fetchToken(e){return this.poolService.fetchToken(e)}async validateToken(e){return this.poolService.validateToken(e)}async fetchTokenStats(e){return this.poolService.fetchTokenStats(e)}async updateTokenConfig(e,t){return this.poolService.updateTokenConfig(e,t)}async getTokenConfig(e){return this.poolService.getTokenConfig(e)}}function ql(e,t){if(void 0!==e){if(!xn(e))throw Qt("tokenName","string");qn(e,"tokenName",or)}if(void 0!==t){if(!xn(t))throw Qt("userAddress","string");if(t.length>fr)throw new wt(`userAddress must be at most ${fr} characters`,"userAddress",Nt.TOO_LONG)}}const zl={CHAT_MESSAGE:"CHAT_MESSAGE",COMMENT:"COMMENT"},Xl={PAGINATION:{MAX_LIMIT:gr},CONTENT:{CHAT_MAX_LENGTH:pr.CHAT_MESSAGES_V1.MAX_LENGTH,COMMENT_MAX_LENGTH:pr.COMMENTS_V1.MAX_LENGTH}};function Ql(e){const t=void 0!==e.type,n=void 0!==e.tokenName&&""!==e.tokenName,r=void 0!==e.userAddress&&""!==e.userAddress;if(!t&&!n&&!r)throw Zt(["type","tokenName","userAddress"]);if(void 0!==e.type&&e.type!==zl.CHAT_MESSAGE&&e.type!==zl.COMMENT)throw new wt(`type must be one of: ${Object.values(zl).join(", ")}`,"type",Nt.INVALID_VALUE);ql(e.tokenName,e.userAddress),void 0!==e.pageSize&&$n(0,void 0,gr,e.pageSize)}function Yl(e){if(void 0===e.type||null===e.type)throw Kt("type");if(e.type!==zl.CHAT_MESSAGE&&e.type!==zl.COMMENT)throw new wt(`type must be one of: ${Object.values(zl).join(", ")}`,"type",Nt.INVALID_VALUE);if(!xn(e.tokenName))throw Kt("tokenName");if(qn(e.tokenName,"tokenName",or),!xn(e.content))throw Kt("content");if(0===e.content.trim().length)throw tn("content","Content");const t=e.type===zl.CHAT_MESSAGE?Xl.CONTENT.CHAT_MAX_LENGTH:Xl.CONTENT.COMMENT_MAX_LENGTH;if(e.content.length>t)throw en("content",t,e.content.length)}function Jl(e){if(!xn(e.content))throw Kt("content");if(0===e.content.trim().length)throw tn("content","Content");const t=Math.max(Xl.CONTENT.CHAT_MAX_LENGTH,Xl.CONTENT.COMMENT_MAX_LENGTH);if(e.content.length>t)throw en("content",t,e.content.length)}function Zl(e){if(!xn(e))throw Kt("id","Message ID");const t=Er.CHAT_MESSAGE.PATTERN.test(e),n=/^msg-\d{13}-[a-f0-9]{32}$/.test(e);if(!t&&!n)throw new wt("Invalid message ID format. Expected: chat-{timestamp}-{uuid} or msg-{timestamp}-{uuid}","id",Nt.INVALID_FORMAT)}function ed(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function td(e){return null===e||"string"==typeof e}function nd(e){return ed(e)&&td(e.fullName)&&td(e.profileImage)}function rd(e){if(!ed(e))return!1;const t=e.reactions;return"string"==typeof e.id&&"string"==typeof e.messageId&&"string"==typeof e.tokenName&&td(e.tokenImage)&&"string"==typeof e.userAddress&&nd(e.user)&&nd(e.userProfile)&&"string"==typeof e.content&&"string"==typeof e.createdAt&&td(e.updatedAt)&&td(e.deletedAt)&&"number"==typeof e.flagCount&&ed(t)&&ed(t.counts)}function sd(e){return e===zl.CHAT_MESSAGE||e===zl.COMMENT}class id extends $o{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}validateContent(e,t){if(!xn(e))throw Kt("content","Message content");if(0===e.trim().length)throw Kt("content","Message content");Dn(e,t===zl.CHAT_MESSAGE?pr.CHAT_MESSAGES_V1.MAX_LENGTH:pr.COMMENTS_V1.MAX_LENGTH,"content")}validateMessageId(e){if(!xn(e))throw Kt("id","Message ID");if(e.length<10||e.length>64)throw Ht("id","valid message ID format","Message ID")}validateMessageType(e){if(e!==zl.CHAT_MESSAGE&&e!==zl.COMMENT)throw new wt(`type must be one of: ${Object.values(zl).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,or);const r={};void 0!==e.cursor&&(r.cursor=e.cursor),r.pageSize=e.pageSize??wo.DEFAULT_LIMIT;const s=Fo(r,gr),i={};void 0!==s.pageSize&&(i.pageSize=s.pageSize),void 0!==s.cursor&&(i.cursor=s.cursor),t&&(i.type=e.type.toUpperCase()),n&&(i.tokenName=hn(e.tokenName)),void 0!==e.userAddress&&""!==e.userAddress&&(i.userAddress=e.userAddress),void 0!==e.search&&""!==e.search&&(i.search=e.search);const o=await this.http.get(Qe.GET_MESSAGES,i),a=this.extractData(o);return{messages:a.messages,pageInfo:a.pageInfo}}async createMessage(e){this.validateMessageType(e.type),this.validateTokenName(e.tokenName,or),this.validateContent(e.content,e.type);const t={type:e.type,tokenName:hn(e.tokenName),content:e.content.trim()},n=await this.http.post(Qe.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(Qe.UPDATE_MESSAGE,e),r={content:t.content.trim()},s=await this.http.put(n,r,this.getJwtHeaders());return{message:this.extractData(s)}}async deleteMessage(e){this.validateMessageId(e);const t=this.buildEndpointWithId(Qe.DELETE_MESSAGE,e);return await this.http.delete(t,void 0,this.getDualAuthHeaders()),{success:!0}}async getPinnedMessage(e){this.validateTokenName(e,cr);const t=await this.http.get(Qe.GET_PINNED,{tokenName:hn(e)});return{message:this.extractDataOrNull(t)}}async pinMessage(e){this.validateMessageId(e);const t=Qe.PIN_MESSAGE.replace(":id",e);return await this.http.post(t,{},this.getDualAuthHeaders()),{success:!0}}async unpinMessage(e){this.validateMessageId(e);const t=Qe.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 Wt("Malformed message statistics response");const r=e.totalMessages,s=e.todayMessages,i=e.uniqueUsers,o=e.uniqueTokens,a=e.messagesByType;if(!(t(r)&&t(s)&&t(i)&&t(o)&&n(a)))throw Wt("Malformed message statistics response");const c={};for(const[e,n]of Object.entries(a)){if(!t(n))throw Wt("Malformed message statistics response");c[e]=n}return{totalMessages:r,todayMessages:s,uniqueUsers:i,uniqueTokens:o,messagesByType:c}}(await this.http.get(Qe.GET_MESSAGE_STATS,void 0,this.getDualAuthHeaders()))}}const od={MODERATOR:"MODERATOR",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MANAGER:"MANAGER"},ad=Hn(od),cd={TOKEN:"TOKEN",ALL_OWNER_TOKENS:"ALL_OWNER_TOKENS"},ld=Hn(cd),dd={PENDING:"PENDING",CLAIMED:"CLAIMED",REVOKED:"REVOKED",EXPIRED:"EXPIRED"},ud=Hn(dd);function hd(e){return ad.includes(e)}function gd(e){return ud.includes(e)}function md(e){return yr.PATTERN.test(e)}const fd=zn([{field:"id",type:"number"},{field:"inviteScope",type:"string"},{field:"tokenName",type:"string",nullable:!0},{field:"role",type:"string"},{field:"inviteCode",type:"string"},{field:"inviteUrl",type:"string"},{field:"status",type:"string"},{field:"createdAt",type:"string"}]),pd=zn([{field:"tokenName",type:"string"},{field:"tokenSymbol",type:"string"},{field:"role",type:"string"},{field:"inviteScope",type:"string"},{field:"creatorAddress",type:"string"},{field:"claimedAt",type:"string"}]),Ed=zn([{field:"inviteScope",type:"string"},{field:"tokenName",type:"string",nullable:!0},{field:"tokenSymbol",type:"string",nullable:!0},{field:"role",type:"string"},{field:"status",type:"string"},{field:"invitedBy",type:"string"}]);function Ad(e){return ld.includes(e)}function vd(e){const t=[],n=e.inviteScope??cd.TOKEN;return void 0===e.inviteScope||Ad(e.inviteScope)||Bt(t,()=>{throw Jt("inviteScope",e.inviteScope,ld,"Invite scope")}),n===cd.TOKEN?Bt(t,()=>{Wn(e.tokenName??"","tokenName",or)}):n===cd.ALL_OWNER_TOKENS&&void 0!==e.tokenName&&""!==e.tokenName&&t.push("Token name should not be provided for ALL_OWNER_TOKENS scope invites"),hd(e.role)||Bt(t,()=>{throw Jt("role",e.role,ad,"Role")}),void 0!==e.description&&""!==e.description&&Bt(t,()=>{Dn(e.description,pr.DESCRIPTION.MAX_LENGTH,"description")}),void 0===e.expiresAt||""===e.expiresAt||yn(e.expiresAt)||Bt(t,()=>{throw function(e,t="a valid date",n){const r=Gt(e,n);return new wt(`${r} must be ${t}`,e,"INVALID_DATE")}("expiresAt","ISO 8601 format")}),t}function Td(e){const t=[];return xn(e)?md(e)||t.push("Invalid invite code format"):t.push(Kt("inviteCode","Invite code").message),t}function yd(e){const t=[];return Bt(t,()=>{Wn(e.tokenName??"","tokenName",or)}),void 0===e.status||gd(e.status)||Bt(t,()=>{throw Jt("status",e.status,ud,"Status")}),Bt(t,()=>{$n(0,void 0,ur,e.pageSize)}),t}class Sd extends $o{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}validateRole(e){if(!xn(e))throw Kt("role","Role");if(!hd(e))throw Ht("role",`one of: ${ad.join(", ")}`,"Role")}validateInviteCodeFormat(e){if(!xn(e))throw Kt("inviteCode","Invite code");if(e.length>yr.MAX_LENGTH)throw Ht("inviteCode",`at most ${String(yr.MAX_LENGTH)} characters`,"Invite code")}validateInviteScope(e){if(void 0!==e&&!Ad(e))throw new wt(`Invalid invite scope. Must be one of: ${ld.join(", ")}`,"inviteScope","INVALID_VALUE")}async createInvite(e){this.validateInviteScope(e.inviteScope);const t=e.inviteScope??cd.TOKEN;if(t===cd.TOKEN){if(void 0===e.tokenName||""===e.tokenName)throw new wt("Token name is required for TOKEN scope invites","tokenName","REQUIRED");this.validateTokenName(e.tokenName,or)}else if(t===cd.ALL_OWNER_TOKENS&&e.tokenName)throw new wt("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",pr.DESCRIPTION.MAX_LENGTH),this.validateOptionalDate(e.expiresAt,"expiresAt","Expiration date");const n=he,r={inviteScope:t,role:e.role};t===cd.TOKEN&&null!==e.tokenName&&void 0!==e.tokenName&&""!==e.tokenName&&(r.tokenName=hn(e.tokenName)),void 0!==e.description&&(r.description=e.description),void 0!==e.expiresAt&&(r.expiresAt=e.expiresAt);const s=await this.http.post(n,r,this.getMultiAuthHeaders());return{invite:this.extractData(s)}}async listInvites(e){void 0!==e.tokenName&&""!==e.tokenName&&this.validateTokenName(e.tokenName,or),this.validateStatusFilter(e.status,dd);const t=fe,n={...this.buildPaginationParams(e,gr)};void 0!==e.tokenName&&""!==e.tokenName&&(n.tokenName=hn(e.tokenName)),void 0!==e.status&&(n.status=e.status);const r=await this.http.get(t,n,this.getMultiAuthHeaders()),s=this.extractData(r);return{items:s.invites,pageInfo:s.pageInfo}}async revokeInvite(e){this.validatePositiveInteger(e,"inviteId","Invite ID");const t=this.buildEndpoint(pe,{id:String(e)});rn(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(Ee,{id:String(e.inviteId)}),n={role:e.role},r=await this.http.patch(t,n,this.getMultiAuthHeaders());return{invite:this.extractData(r)}}async updateInvite(e){if(this.validatePositiveInteger(e.inviteId,"inviteId","Invite ID"),void 0===e.role&&void 0===e.description)throw new wt("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",pr.DESCRIPTION.MAX_LENGTH);const t=this.buildEndpoint(Ae,{id:String(e.inviteId)}),n={};void 0!==e.role&&(n.role=e.role),void 0!==e.description&&(n.description=e.description);const r=await this.http.patch(t,n,this.getMultiAuthHeaders());return{invite:this.extractData(r)}}async claimInvite(e){this.validateInviteCodeFormat(e.inviteCode);const t=ge,n={inviteCode:e.inviteCode},r=await this.http.post(t,n,this.getMultiAuthHeaders()),s=this.extractData(r);return"tokenName"in s&&void 0!==s.tokenName?{token:s}:{blanketAccess:s}}async getModeratedTokens(e){const t=me,n=this.buildPaginationParams(e??{},gr),r=await this.http.get(t,n,this.getMultiAuthHeaders()),s=this.extractData(r);return{items:s.tokens,pageInfo:s.pageInfo}}async getInviteByCode(e){this.validateInviteCodeFormat(e);const t=this.buildEndpoint(ve,{code:e}),n=await this.http.get(t,{});return this.extractData(n)}}const bd={COLLECTION_CLAIM_FEE:"10000",TOKEN_CLASS_CREATE_FEE:"1000",DESCRIPTIONS:{COLLECTION_CLAIM:"10,000 GALA to claim a collection name",TOKEN_CLASS_CREATE:"1,000 GALA to create a token class",MINT:"Dynamic fee estimated via DryRun endpoint"}};function Nd(e){return parseFloat(bd[e])}function wd(e){return`${e}-${Date.now()}-${Math.random().toString(36).substring(2,11)}`}function kd(){return Date.now()+6e4}function _d(e){return""!==e&&"string"==typeof e&&/^[a-zA-Z0-9]{3,50}$/.test(e)}function Id(e){try{return Math.floor(parseFloat(String(e))??0).toString()}catch{return"0"}}function Dd(e){return""!==e&&"string"==typeof e&&/^eth\|[0-9a-fA-F]{40}$/.test(e)}class Cd extends nr{constructor(e){super(e)}getCollectionClaimFee(){return bd.COLLECTION_CLAIM_FEE}getTokenClassCreateFee(){return bd.TOKEN_CLASS_CREATE_FEE}async estimateMintFee(e){try{if(this.logger.debug("Estimating mint fee",e),0===e.collection.length||0===e.type.length||0===e.category.length||0===e.quantity.length)throw new Error("Missing required parameters for mint fee estimation");if(!Dd(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=bd.COLLECTION_CLAIM_FEE;n.collectionClaim=e,t=String(BigInt(t)+BigInt(e))}if((e.createTokenClasses??0)>0){const r=bd.TOKEN_CLASS_CREATE_FEE,s=String(BigInt(r)*BigInt(e.createTokenClasses));n.tokenClassCreate=r,n.tokenClassCount=e.createTokenClasses,t=String(BigInt(t)+BigInt(s))}return{totalFee:t,breakdown:n}}async claimCollection(e){try{if(this.logger.debug("Claiming NFT collection",e.collectionName),!_d(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:kd(),uniqueKey:wd("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),!Dd(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),!_d(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(!_d(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?Id(e.maxSupply):void 0,maxCapacity:void 0!==e.maxCapacity?Id(e.maxCapacity):void 0,additionalKey:e.additionalKey,expiresAt:kd(),uniqueKey:wd("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),!_d(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(!Dd(e.ownerAddress))throw new Error(`Invalid owner address: ${e.ownerAddress}`);const n=this.estimateMintFee({collection:e.collection,type:e.type,category:e.category,quantity:e.quantity,ownerAddress:e.ownerAddress});this.logger.debug("Estimated mint fee:",n);const r={collection:e.collection,type:e.type,category:e.category,quantity:e.quantity,owner:e.ownerAddress,additionalKey:e.additionalKey??"none",expiresAt:kd(),uniqueKey:wd("mint")};this.logger.debug("Built mint DTO",r);const s=`mint-${Date.now()}`,i=Array.from({length:t},(e,t)=>t+1);return{transactionId:s,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}),!Dd(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}=wc(async(e,t)=>({data:await this.http.post(e,t)}));return new g({gatewayBaseUrl:"",httpRequestor:e,requestTimeoutMs:1/0})}allAuthorizations(){return this.reads().fetchAllNftCollectionAuthorizations({pageSize:1e3})}}class Rd extends nr{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(gt,{token:e.token,platform:e.platform,...void 0!==e.deviceId?{deviceId:e.deviceId}:{}},t),r=this.extractData(n);return this.logger.debug("Push token registered",{registered:r.registered}),r}async unregisterPushToken(e){this.logger.debug("Unregistering push token");const t=this.getJwtHeaders(),n=await this.http.request({method:"DELETE",url:mt,data:{token:e},headers:t}),r=this.extractData(n);return this.logger.debug("Push token unregistered",{unregistered:r.unregistered}),r}async getPreferences(){this.logger.debug("Fetching notification preferences");const e=this.getJwtHeaders(),t=await this.http.get(ft,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(pt,e,t),r=this.extractData(n);return this.logger.debug("Updated notification preferences",{tradesEnabled:r.tradesEnabled,streamsEnabled:r.streamsEnabled}),{preferences:r}}}class Od extends nr{constructor(e,t=!1){super(e,t)}async getHomeOEmbedJson(e={}){this.logger.debug("Fetching home oEmbed (JSON)");const t=await this.http.get(C.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(C.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 wt("tokenName is required","tokenName","REQUIRED_FIELD");this.logger.debug("Fetching pool oEmbed (JSON)",{tokenName:t});const n=C.OEMBED_BUY_SELL.replace(":tokenName",t.toLowerCase().trim()),r=await this.http.get(n,{format:"json"});return this.logger.debug("Fetched pool oEmbed (JSON)",{tokenName:t,title:r.title}),{oembed:r}}async getPoolOEmbedHtml(e){const{tokenName:t}=e;if(null==t||"string"!=typeof t||""===t.trim())throw new wt("tokenName is required","tokenName","REQUIRED_FIELD");this.logger.debug("Fetching pool oEmbed (HTML)",{tokenName:t});const n=C.OEMBED_BUY_SELL.replace(":tokenName",t.toLowerCase().trim()),r=await this.http.get(n,{},{responseType:"text"});return this.logger.debug("Fetched pool oEmbed (HTML)",{tokenName:t}),{html:r}}async getProfileOEmbedJson(e){const{address:t}=e;if(null==t||"string"!=typeof t||""===t.trim())throw new wt("address is required","address","REQUIRED_FIELD");this.logger.debug("Fetching profile oEmbed (JSON)",{address:t});const n=C.OEMBED_PROFILE.replace(":address",encodeURIComponent(t.toLowerCase().trim())),r=await this.http.get(n,{format:"json"});return this.logger.debug("Fetched profile oEmbed (JSON)",{address:t,title:r.title}),{oembed:r}}async getProfileOEmbedHtml(e){const{address:t}=e;if(null==t||"string"!=typeof t||""===t.trim())throw new wt("address is required","address","REQUIRED_FIELD");this.logger.debug("Fetching profile oEmbed (HTML)",{address:t});const n=C.OEMBED_PROFILE.replace(":address",encodeURIComponent(t.toLowerCase().trim())),r=await this.http.get(n,{},{responseType:"text"});return this.logger.debug("Fetched profile oEmbed (HTML)",{address:t}),{html:r}}}function Md(e){if(!xn(e))throw Kt("address","Address")}const Ld={PENDING:"PENDING",CLAIMED:"CLAIMED",REVOKED:"REVOKED",EXPIRED:"EXPIRED"},Ud={ACTIVE:"ACTIVE",REVOKED:"REVOKED"},Fd=Kn(Ld),Pd=Kn(Ud);function xd(e){if(e.status!==Ld.PENDING)return!1;if(null!==e.expiresAt&&void 0!==e.expiresAt){if(Tn(e.expiresAt)<=new Date)return!1}return!0}function Bd(e){try{Jn(e.description,"description",255)}catch(e){if(e instanceof wt){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(!xn(e.expiresAt))throw new Error("expiresAt must be a non-empty string");try{Zn(e.expiresAt,"expiresAt")}catch(e){if(e instanceof wt)throw new Error("expiresAt must be a valid ISO 8601 date string");throw e}if(yn(e.expiresAt)){if(Tn(e.expiresAt)<=new Date)throw new Error("expiresAt must be in the future")}}}function Gd(e){if(void 0!==e.status&&!Fd(e.status))throw Jt("status",e.status,Object.values(Ld),"status");$n(0,void 0,50,e.pageSize,e.cursor)}function $d(e){if(void 0!==e.status&&!Pd(e.status))throw Jt("status",e.status,Object.values(Ud),"status");$n(0,void 0,50,e.pageSize,e.cursor)}function Kd(e){if(!xn(e))throw new Error("Invite code must be a non-empty string");Dn(e,yr.MAX_LENGTH,"code")}function Hd(e){if(!xn(e))throw new Error("Address must be a non-empty string");try{Fr(e,"address")}catch{throw new Error("Invalid wallet address format. Must be eth|..., 0x..., or client|... format")}}function Wd(e){try{Cn(e,"id")}catch(e){if(e instanceof wt)throw new Error("Invite ID must be a positive integer");throw e}}function Vd(e){if(null==e||"object"!=typeof e)throw new wt("Options are required");if(void 0!==e.search){if("string"!=typeof e.search)throw new wt("Search must be a string");if(0===e.search.length)throw new wt("Search query cannot be empty string")}if(void 0!==e.sortBy){if("string"!=typeof e.sortBy)throw new wt("Sort field must be a string");if(0===e.sortBy.length)throw new wt("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 wt('Sort order must be "asc" or "desc"')}}function jd(e){if(null==e||"object"!=typeof e)throw new wt("Options are required");if(!xn(e.userAddress))throw new wt("userAddress is required and must be a non-empty string");try{Fr(e.userAddress,"userAddress")}catch{throw new wt("Invalid wallet address format. Must be eth|..., 0x..., or client|... format")}if(void 0!==e.description){if("string"!=typeof e.description)throw new wt("description must be a string");if(e.description.length>255)throw new wt("description must be at most 255 characters")}}class qd extends $o{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}validateInviteCodeFormat(e){if(!xn(e))throw Kt("inviteCode","Invite code");Kd(e)}validateWalletAddressFormat(e){if(!xn(e))throw Kt("address","Address");Hd(e)}async createInvite(e={}){Bd(e),this.validateOptionalString(e.description,"description","Description",pr.DESCRIPTION.MAX_LENGTH),this.validateOptionalDate(e.expiresAt,"expiresAt","Expiration date");const t=ye,n={};void 0!==e.description&&(n.description=e.description),void 0!==e.expiresAt&&(n.expiresAt=e.expiresAt);const r=await this.http.post(t,n,this.getDualAuthHeaders());return{invite:this.extractData(r)}}async listInvites(e={}){Gd(e),this.validateStatusFilter(e.status,Ld);const t=Se,n={...this.buildPaginationParams(e,gr)};void 0!==e.status&&(n.status=e.status);const r=await this.http.get(t,n,this.getDualAuthHeaders()),s=this.extractData(r);return{items:s.invites,pageInfo:s.pageInfo}}async getInviteByCode(e){this.validateInviteCodeFormat(e);const t=this.buildEndpoint(be,{code:e}),n=await this.http.get(t,{});return this.extractData(n)}async revokeInvite(e){Wd(e);const t=this.buildEndpoint(we,{id:String(e)});rn(await this.http.delete(t,void 0,this.getDualAuthHeaders()),"Failed to revoke invite")}async claimInvite(e){this.validateInviteCodeFormat(e);const t=Ne,n={inviteCode:e},r=await this.http.post(t,n,this.getJwtHeaders());return{invite:this.extractData(r)}}async listOverseers(e={}){$d(e),this.validateStatusFilter(e.status,Ud);const t=ke,n={...this.buildPaginationParams(e,gr)};void 0!==e.status&&(n.status=e.status);const r=await this.http.get(t,n,this.getDualAuthHeaders()),s=this.extractData(r);return{items:s.overseers,pageInfo:s.pageInfo}}async createOverseerDirect(e){jd(e),this.validateWalletAddressFormat(e.userAddress),this.validateOptionalString(e.description,"description","Description",pr.DESCRIPTION.MAX_LENGTH);const t=_e,n={userAddress:e.userAddress};void 0!==e.description&&(n.description=e.description);const r=await this.http.post(t,n,this.getDualAuthHeaders());return{overseer:this.extractData(r)}}async revokeOverseer(e){this.validateWalletAddressFormat(e);const t=this.buildEndpoint(Ie,{address:e});rn(await this.http.delete(t,void 0,this.getDualAuthHeaders()),"Failed to revoke overseer")}async getMyStatus(){const e=De,t=await this.http.get(e,{},this.getJwtHeaders());return this.extractData(t)}async getSummary(){const e=Ce,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getBanStats(){const e=Re,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getTokenBanStats(){const e=Oe,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getInviteStats(){const e=Me,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getFlagStats(){const e=Le,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getUserStats(){const e=Ue,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async listOverseerUsers(e){const t=e??{};Object.keys(t).length>0&&Vd(t);const n=Fe,r=this.buildPaginationParams(t,gr);void 0!==t.search&&""!==t.search&&(r.search=t.search),void 0!==t.sortBy&&""!==t.sortBy&&(r.sortBy=t.sortBy),void 0!==t.sortOrder&&(r.sortOrder=t.sortOrder);const s=await this.http.get(n,r,this.getDualAuthHeaders()),i=this.extractData(s);return{items:i.users,pageInfo:i.pageInfo}}async getOverseerUserSummary(e){if(!xn(e))throw Kt("address","User address");Hd(e);const t=this.buildEndpoint(Pe,{address:e}),n=await this.http.get(t,{},this.getDualAuthHeaders());return this.extractData(n)}async flushCacheByAddress(e){Md(e);const t=this.buildEndpoint(xe,{address:e}),n=await this.http.delete(t,void 0,this.getDualAuthHeaders());return this.extractData(n)}async flushCacheByToken(e){!function(e){if(!xn(e))throw Kt("tokenName","Token name")}(e);const t=this.buildEndpoint(Be,{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 wt("Safety confirmation required: must pass confirm=true to flush all cache","confirm","CONFIRMATION_REQUIRED")}(e);const t=Ge,n=await this.http.delete(t,{confirm:"true"},this.getDualAuthHeaders());return this.extractData(n)}async flushWalletAliasCache(e){if(void 0!==e){Md(e);const t=this.buildEndpoint($e,{address:e}),n=await this.http.delete(t,void 0,this.getDualAuthHeaders());return this.extractData(n)}const t=Ke,n=await this.http.delete(t,{confirm:"true"},this.getDualAuthHeaders());return this.extractData(n)}}function zd(e){const t=[];return 0===Object.keys(e).length&&t.push("At least one field (streamingEnabled, chatEnabled, commentsEnabled, webhooksEnabled, aiModerationEnabled) must be provided"),void 0!==e.streamingEnabled&&"boolean"!=typeof e.streamingEnabled&&t.push("streamingEnabled must be a boolean"),void 0!==e.chatEnabled&&"boolean"!=typeof e.chatEnabled&&t.push("chatEnabled must be a boolean"),void 0!==e.commentsEnabled&&"boolean"!=typeof e.commentsEnabled&&t.push("commentsEnabled must be a boolean"),void 0!==e.webhooksEnabled&&"boolean"!=typeof e.webhooksEnabled&&t.push("webhooksEnabled must be a boolean"),void 0!==e.aiModerationEnabled&&"boolean"!=typeof e.aiModerationEnabled&&t.push("aiModerationEnabled must be a boolean"),t}class Xd extends nr{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),rn(t,"Platform config operation failed",!0),e.data}async getPlatformConfig(){const e=await this.http.get(V);return this.extractData(e)}async updatePlatformConfig(e){const t=zd(e);if(t.length>0)throw new wt(t.join("; "),"options","VALIDATION_FAILED");const n=await this.http.put(j,e,this.getJwtHeaders());return this.extractData(n)}async getAvailableRoles(){const e=await this.http.get(X);return this.extractData(e)}}class Qd extends nr{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(at),t=this.extractData(e);return this.logger.debug("Fetched platform stats",{totalTokens:t.totalTokens,timestamp:t.timestamp}),{stats:t}}}class Yd extends $o{constructor(e,t,n,r){super(e,t,n,!1,r)}async getRestrictedNames(){try{return{success:!0,data:(await this.http.get(Ye,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 wt("Content is required");return{success:!0,data:(await this.http.put(Je,{content:e.content},this.getJwtHeaders())).data}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}}class Jd extends $o{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async getChatStatus(e){if(null==e||""===e)throw Kt("tokenName","Token name");return this.validateTokenName(e,cr),fo(async()=>{const t=this.buildEndpoint(Ze,{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 Kt("tokenName","Token name");return this.validateTokenName(e,cr),fo(async()=>{const t=this.buildEndpoint(tt,{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 Kt("tokenName","Token name");return this.validateTokenName(e,cr),fo(async()=>{const t=this.buildEndpoint(et,{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??hn(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 Kt("tokenName","Token name");if(this.validateTokenName(e,cr),"number"!=typeof t||t<0||t>600)throw new Error("slowModeSeconds must be a number between 0 and 600");return fo(async()=>{const n=this.buildEndpoint(nt,{tokenName:e}),r=await this.http.patch(n,{slowModeSeconds:t},this.getDualAuthHeaders());return this.extractData(r)},`Failed to set slow mode for token: ${e}`,this.logger)}}const Zd={IDLE:"IDLE",ACTIVE:"ACTIVE",DISABLED:"DISABLED"},eu={PREPARING:"preparing",READY:"ready",ERRORED:"errored"},tu={IDLE:"idle",STARTING:"starting",BROADCASTING:"broadcasting",ERRORED:"errored"},nu={YOUTUBE:"youtube",TWITCH:"twitch",FACEBOOK:"facebook",CUSTOM:"custom"},ru=Kn(Zd),su=Kn(eu),iu=Kn(nu);function ou(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&ru(t.status)&&(null===t.playbackId||"string"==typeof t.playbackId)&&"boolean"==typeof t.isLive}function au(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"number"==typeof t.viewerCount}const cu={OWNER:"OWNER",MANAGER:"MANAGER",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MODERATOR:"MODERATOR"},lu={OWNER:"OWNER",MODERATOR:"MODERATOR"};Kn(cu),Kn(lu);const du={MANAGE_COMMENTS:"MANAGE_COMMENTS",MANAGE_CHAT:"MANAGE_CHAT",BAN_USERS:"BAN_USERS",UNBAN_USERS:"UNBAN_USERS",MANAGE_SIMULCAST:"MANAGE_SIMULCAST",GET_STREAM_KEY:"GET_STREAM_KEY",STOP_STREAM:"STOP_STREAM",RESET_STREAM_KEY:"RESET_STREAM_KEY",START_STREAM:"START_STREAM",DELETE_RECORDINGS:"DELETE_RECORDINGS",MANAGE_STREAM_SETTINGS:"MANAGE_STREAM_SETTINGS"},uu={...cu,OVERSEER:"OVERSEER"},hu=Kn(uu);function gu(e){if(null==e||"object"!=typeof e)return!1;const t=e,n=t.permissions;return Array.isArray(n)&&n.every(e=>"string"==typeof e)&&(null===t.source||"owner"===t.source||"moderator_invite"===t.source||"api_key"===t.source||"overseer"===t.source)&&(void 0===t.matchedPreset||null===t.matchedPreset||"MODERATOR"===t.matchedPreset||"TECHNICAL_PRODUCER"===t.matchedPreset||"MANAGER"===t.matchedPreset)&&"boolean"==typeof t.isOwner&&"boolean"==typeof t.isOverseer}function mu(e,t="tokenName"){Wn(e,t,cr)}const fu=/^rtmps?:\/\/\S+$/u,pu=255;function Eu(e){if(mu(e.tokenName),!xn(e.language))throw Kt("language");if(t=e.language,!xn(t)||!/^[a-z]{2}(-[A-Z]{2})?$/.test(t))throw new wt('language must be a valid ISO 639-1 code (e.g., "en", "es", "zh-CN")',"language",Nt.INVALID_FORMAT);var t}const Au={STREAM_STARTED:"stream.started",STREAM_STOPPED:"stream.stopped",RECORDING_READY:"recording.ready",SIMULCAST_ERROR:"simulcast.error"};class vu extends $o{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async startStream(e){this.validateTokenName(e,cr);const t=this.buildEndpoint(L,{tokenName:e}),n=await this.http.post(t,{},this.getJwtHeaders());return this.extractData(n)}async stopStream(e){this.validateTokenName(e,cr);const t=this.buildEndpoint(U,{tokenName:e});await this.http.post(t,{},this.getJwtHeaders())}async disableStream(e){return this.toggleFeature(e,F,cr)}async enableStream(e){return this.toggleFeature(e,P,cr)}async resetStreamKey(e){this.validateTokenName(e,cr);const t=this.buildEndpoint(x,{tokenName:e}),n=await this.http.post(t,{},this.getJwtHeaders());return this.extractData(n)}async getStreamCredentials(e){this.validateTokenName(e,cr);const t=this.buildEndpoint(Y,{tokenName:e}),n=await this.http.get(t,{},this.getJwtHeaders());return this.extractData(n)}async getRecordings(e){!function(e){mu(e.tokenName)}(e);const t=this.buildEndpoint(B,{tokenName:e.tokenName}),n=await this.http.get(t),r=this.extractData(n);if(!Array.isArray(r))throw Wt("Invalid recordings response: expected an array of recordings");return{recordings:r,tokenName:hn(e.tokenName)}}async getRecordingDownload(e,t){this.validateTokenName(e,cr),this.validateRequiredString(t,"assetId","Asset ID");const n=this.buildEndpoint(G,{tokenName:e,assetId:t}),r=await this.http.get(n,{},this.getJwtHeaders());return this.extractData(r)}async deleteRecording(e,t){this.validateTokenName(e,cr),this.validateRequiredString(t,"assetId","Asset ID");const n=this.buildEndpoint($,{tokenName:e,assetId:t});await this.http.delete(n,void 0,this.getJwtHeaders())}async getSimulcastTargets(e){this.validateTokenName(e,cr);const t=this.buildEndpoint(K,{tokenName:e}),n=await this.http.get(t,void 0,this.getJwtHeaders()),r=this.extractData(n);if(!Array.isArray(r))throw Wt("Invalid simulcast response: expected an array of targets");return{targets:r,tokenName:hn(e)}}async addSimulcastTarget(e){!function(e){if(mu(e.tokenName),!xn(e.platform))throw Kt("platform");if(!iu(e.platform))throw new wt("platform must be one of: 'youtube', 'twitch', 'facebook', 'custom'","platform",Nt.INVALID_VALUE);if(!xn(e.url))throw Kt("url");if(!fu.test(e.url))throw new wt("url must be a valid RTMP or RTMPS URL","url",Nt.INVALID_FORMAT);if(e.url.length>2048)throw new wt(`url must not exceed ${String(2048)} characters`,"url",Nt.TOO_LONG);if(!xn(e.streamKey))throw Kt("streamKey");if(e.streamKey.length>pu)throw new wt(`streamKey must not exceed ${String(pu)} characters`,"streamKey",Nt.TOO_LONG);if(void 0!==e.passthrough){if("string"!=typeof e.passthrough)throw new wt("passthrough must be a string","passthrough",Nt.INVALID_TYPE);if(e.passthrough.length>pu)throw new wt(`passthrough must not exceed ${String(pu)} characters`,"passthrough",Nt.TOO_LONG)}}(e);const t=this.buildEndpoint(H,{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:hn(e.tokenName)}}async removeSimulcastTarget(e,t){this.validateTokenName(e,cr),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(V);return this.extractData(e)}async disableGlobalStreaming(){const e=await this.http.put(j,{},this.getAdminHeaders());return this.extractData(e)}async enableGlobalStreaming(){const e=await this.http.put(q,{},this.getAdminHeaders());return this.extractData(e)}async setNextLiveStream(e){let t;!function(e){if(mu(e.tokenName),null!==e.nextLiveStreamAt){if(!(e.nextLiveStreamAt instanceof Date||xn(e.nextLiveStreamAt)))throw new wt("nextLiveStreamAt must be a Date, ISO 8601 string, or null","nextLiveStreamAt",Nt.INVALID_TYPE);if("string"==typeof e.nextLiveStreamAt){const t=Date.parse(e.nextLiveStreamAt);if(isNaN(t))throw new wt("nextLiveStreamAt must be a valid ISO 8601 date string","nextLiveStreamAt",Nt.INVALID_FORMAT)}}}(e),t=null===e.nextLiveStreamAt?null:e.nextLiveStreamAt instanceof Date?e.nextLiveStreamAt.toISOString():e.nextLiveStreamAt;const n=`/v1/tokens/${e.tokenName.toLowerCase().trim()}`;await this.http.patch(n,{nextLiveStreamAt:t},this.getJwtHeaders())}async clearNextLiveStream(e){this.validateTokenName(e,cr);const t=`/v1/tokens/${e.toLowerCase().trim()}`;await this.http.patch(t,{nextLiveStreamAt:null},this.getJwtHeaders())}async setStreamLanguage(e){Eu(e);const t=`/v1/tokens/${e.tokenName.toLowerCase().trim()}`;await this.http.patch(t,{streamLanguage:e.language},this.getJwtHeaders())}async getStreamRole(e){!function(e){mu(e.tokenName)}(e);const t=this.buildEndpoint(z,{tokenName:e.tokenName}),n=this.jwtAuth?this.getJwtHeaders():{},r=await this.http.get(t,{},n);return this.extractData(r)}async getAvailableRoles(){const e=await this.http.get(X);return this.extractData(e)}async getTokenAccess(e){!function(e){mu(e.tokenName)}(e);const t=await this.http.get(Q,{tokenName:hn(e.tokenName)},this.getJwtHeaders());return this.extractData(t)}async setNextLiveStreamCountdown(e,t){return this.setNextLiveStream({tokenName:e,nextLiveStreamAt:t})}}const Tu={SUBSCRIBE:"subscribe_token",UNSUBSCRIBE:"unsubscribe_token",SUBSCRIBE_COMMENT:"subscribe_comment",UNSUBSCRIBE_COMMENT:"unsubscribe_comment",SUBSCRIBE_GLOBAL_FEED:"subscribe_global_feed",UNSUBSCRIBE_GLOBAL_FEED:"unsubscribe_global_feed",SUBSCRIBE_EVENTS_FIREHOSE:"subscribe_events_firehose",UNSUBSCRIBE_EVENTS_FIREHOSE:"unsubscribe_events_firehose",AUTHENTICATE:"authenticate",SEND_CHAT:"send_stream_chat",SEND_REACTION:"SEND_STREAM_REACTION",TYPING_START:"typing_start",TYPING_STOP:"typing_stop",STREAM_STATUS:"STREAM_STATUS",RECORDING_STATUS:"RECORDING_STATUS",RECORDINGS_COUNT_UPDATED:"RECORDINGS_COUNT_UPDATED",SIMULCAST_STATUS:"SIMULCAST_STATUS",DOWNLOAD_READY:"DOWNLOAD_READY",STREAM_COUNTDOWN_UPDATED:"STREAM_COUNTDOWN_UPDATED",STREAM_LANGUAGE_UPDATED:"STREAM_LANGUAGE_UPDATED",VIEWER_COUNT:"VIEWER_COUNT",STREAM_CONTROL_STATUS_CHANGED:"STREAM_CONTROL_STATUS_CHANGED",STREAM_GLOBAL_STATUS:"STREAM_GLOBAL_STATUS",ENGAGEMENT_STATS_UPDATED:"ENGAGEMENT_STATS_UPDATED",CHAT_MESSAGE:"STREAM_CHAT_MESSAGE",CHAT_SENT:"STREAM_CHAT_SENT",CHAT_UPDATED:"STREAM_CHAT_UPDATED",CHAT_DELETED:"STREAM_CHAT_DELETED",CHAT_PINNED:"STREAM_CHAT_PINNED",CHAT_UNPINNED:"STREAM_CHAT_UNPINNED",CHAT_STATUS:"CHAT_STATUS_CHANGED",SLOW_MODE_CHANGED:"SLOW_MODE_CHANGED",CHAT_GLOBAL_STATUS:"STREAM_CHAT_GLOBAL_STATUS",USER_TYPING:"USER_TYPING",CHAT_ERROR:"stream_chat_error",REACTION:"STREAM_REACTION",REACTION_ERROR:"stream_reaction_error",CONTENT_REACTION_ADDED:"CONTENT_REACTION_ADDED",CONTENT_REACTION_REMOVED:"CONTENT_REACTION_REMOVED",COMMENT_CREATED:"COMMENT_CREATED",COMMENT_UPDATED:"COMMENT_UPDATED",COMMENT_DELETED:"COMMENT_DELETED",TRADE_EXECUTED:"TRADE_EXECUTED",TRADE_UPDATE_NOTIFY:"TRADE_UPDATE_NOTIFY",BALANCE_UPDATED:"BALANCE_UPDATED",STATS_UPDATED:"STATS_UPDATED",USER_BANNED:"USER_BANNED",USER_UNBANNED:"USER_UNBANNED",BAN_ENFORCEMENT:"BAN_ENFORCEMENT",TOKEN_BANNED:"TOKEN_BANNED",TOKEN_UNBANNED:"TOKEN_UNBANNED",CONTENT_FLAGGED:"CONTENT_FLAGGED",FLAG_RESOLVED:"FLAG_RESOLVED",AI_MODERATION_COMPLETE:"AI_MODERATION_COMPLETE",AI_MODERATION_FAILED:"AI_MODERATION_FAILED",MODERATOR_INVITE_CREATED:"MODERATOR_INVITE_CREATED",MODERATOR_ADDED:"MODERATOR_ADDED",MODERATOR_REMOVED:"MODERATOR_REMOVED",MODERATOR_ROLE_UPDATED:"MODERATOR_ROLE_UPDATED",OVERSEER_ADDED:"OVERSEER_ADDED",OVERSEER_REMOVED:"OVERSEER_REMOVED",POOL_CREATED:"POOL_CREATED",POOL_METADATA_UPDATED:"POOL_METADATA_UPDATED",POOL_SOCIAL_LINKS_UPDATED:"POOL_SOCIAL_LINKS_UPDATED",POOL_BADGE_ASSIGNED:"POOL_BADGE_ASSIGNED",TOKEN_CONFIG_UPDATED:"TOKEN_CONFIG_UPDATED",HOLDER_COUNT_UPDATED:"HOLDER_COUNT_UPDATED",USER_PROFILE_UPDATED:"USER_PROFILE_UPDATED",API_KEY_CREATED:"API_KEY_CREATED",API_KEY_UPDATED:"API_KEY_UPDATED",API_KEY_REVOKED:"API_KEY_REVOKED",SITE_CONFIG_CHANGED:"SITE_CONFIG_CHANGED",COMMENTS_GLOBAL_STATUS:"COMMENTS_GLOBAL_STATUS",WEBHOOKS_GLOBAL_STATUS:"WEBHOOKS_GLOBAL_STATUS",AI_MODERATION_GLOBAL_STATUS:"AI_MODERATION_GLOBAL_STATUS",EVENT:"EVENT",CONNECTION:"connection",CHAT_AUTHENTICATED:"authenticated",CHAT_AUTH_ERROR:"stream_chat_auth_error",EXCEPTION:"exception",STREAM_SUBSCRIBED:"token_subscribed",STREAM_UNSUBSCRIBED:"token_unsubscribed",ROOM_SUBSCRIBED:"room_subscribed",ROOM_LEFT:"room_left",GLOBAL_FEED_SUBSCRIBED:"global_feed_subscribed",GLOBAL_FEED_UNSUBSCRIBED:"global_feed_unsubscribed",EVENTS_FIREHOSE_SUBSCRIBED:"events_firehose_subscribed",EVENTS_FIREHOSE_UNSUBSCRIBED:"events_firehose_unsubscribed"},yu=e=>Su(e.flagId);function Su(e){return"string"==typeof e||"number"==typeof e?String(e):void 0}function bu(e,t){const n=t.map(t=>Su(e[t]));return n.every(e=>void 0!==e)?n.join("|"):void 0}const Nu={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=>Su(e.id)},FLAG_RESOLVED:{duplicateKey:e=>bu(e,["id","status","reviewedAt"])},AI_MODERATION_COMPLETE:{duplicateKey:yu},AI_MODERATION_FAILED:{duplicateKey:yu},MODERATOR_INVITE_CREATED:{},MODERATOR_ADDED:{},MODERATOR_REMOVED:{},MODERATOR_ROLE_UPDATED:{},OVERSEER_ADDED:{token:"none",duplicateKey:e=>bu(e,["userAddress","addedAt"])},OVERSEER_REMOVED:{token:"none",duplicateKey:e=>bu(e,["userAddress","removedAt"])},POOL_CREATED:{duplicateKey:e=>bu(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 wu(e){return Nu[e]}const ku=Object.keys(Nu);const _u="token:",Iu="comment:",Du="global:feed",Cu="global:events_firehose";function Ru(e){if(e.startsWith(_u)){const t={tokenName:e.slice(_u.length)};return{join:{event:Tu.SUBSCRIBE,payload:t},leave:{event:Tu.UNSUBSCRIBE,payload:t}}}if(e.startsWith(Iu)){const t={tokenName:e.slice(8)};return{join:{event:Tu.SUBSCRIBE_COMMENT,payload:t},leave:{event:Tu.UNSUBSCRIBE_COMMENT,payload:t}}}return e===Cu?{join:{event:Tu.SUBSCRIBE_EVENTS_FIREHOSE},leave:{event:Tu.UNSUBSCRIBE_EVENTS_FIREHOSE}}:{join:{event:Tu.SUBSCRIBE_GLOBAL_FEED},leave:{event:Tu.UNSUBSCRIBE_GLOBAL_FEED}}}const Ou=new Set(["token_subscribed","room_subscribed","global_feed_subscribed","events_firehose_subscribed"]);const Mu={STREAM_CHAT_GLOBAL_STATUS:"chatEnabled",STREAM_GLOBAL_STATUS:"streamingEnabled",COMMENTS_GLOBAL_STATUS:"commentsEnabled",WEBHOOKS_GLOBAL_STATUS:"webhooksEnabled",AI_MODERATION_GLOBAL_STATUS:"aiModerationEnabled"},Lu=["STREAM_STATUS","TRADE_EXECUTED","HOLDER_COUNT_UPDATED","POOL_BADGE_ASSIGNED","VIEWER_COUNT","TOKEN_CONFIG_UPDATED","STATS_UPDATED","POOL_CREATED"],Uu=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"]),Fu=new Set(["COMMENT_CREATED","COMMENT_UPDATED","COMMENT_DELETED"]);const Pu={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"},xu={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"},Bu=()=>{};function Gu(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function $u(e,t){return t}function Ku(e){return`${_u}${e}`}function Hu(e){return`${Iu}${e}`}function Wu(e){const t=hn(e);if(""===t)throw Kt("tokenName","Token name");return t}class Vu extends rr{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 Rt("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 k}register(e,t,n={}){if(this.disposed)return Bu;const r={name:e,deliver:t,token:n.token,filter:n.filter,room:n.room,active:!0};let s=this.subscribers.get(e);return void 0===s&&(s=new Set,this.subscribers.set(e,s)),s.add(r),void 0!==n.room&&this.acquireRoom(n.room),this.openIfNeeded(),()=>{this.release(r)}}release(e){if(!e.active)return;e.active=!1;const t=this.subscribers.get(e.name);t?.delete(e),0===t?.size&&this.subscribers.delete(e.name),void 0!==e.room&&this.releaseRoom(e.room)}hold(e){if(this.disposed)return Bu;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: ${Lt(e)}`)})}acquireRoom(e){this.roomRefs.set(e,(this.roomRefs.get(e)??0)+1),this.syncRoom(e)}releaseRoom(e){const t=(this.roomRefs.get(e)??1)-1;t<=0?this.roomRefs.delete(e):this.roomRefs.set(e,t),this.syncRoom(e)}syncRoom(e){const t=this.liveSocket();if(null===t)return;const n=(this.roomRefs.get(e)??0)>0,r=this.roomStates.get(e);if(n&&void 0===r){if(function(e){return e===Cu}(e)&&!this.authenticated)return;this.joinRoom(t,e)}else n||"joined"!==r?.phase||(t.emit(Ru(e).leave.event,Ru(e).leave.payload),this.roomStates.delete(e))}syncAllRooms(){for(const e of new Set([...this.roomRefs.keys(),...this.roomStates.keys()]))this.syncRoom(e)}joinRoom(e,t){const n=setTimeout(()=>{const e=this.roomStates.get(t);"joining"===e?.phase&&(this.roomStates.delete(t),this.rejectWaiters(t,new Error(`Subscription to ${t} timed out after ${this.config.subscriptionTimeout}ms`)))},this.config.subscriptionTimeout);this.roomStates.set(t,{phase:"joining",timer:n});const r=Ru(t).join;e.emit(r.event,r.payload)}onRoomAcknowledged(e){const t=this.roomStates.get(e);void 0!==t?.timer&&clearTimeout(t.timer),this.roomStates.set(e,{phase:"joined",timer:void 0});const n=this.roomWaiters.get(e);if(void 0!==n){this.roomWaiters.delete(e);const t=e.startsWith(_u)?e.slice(_u.length):e;for(const r of n)clearTimeout(r.timer),r.resolve({room:e,tokenName:t})}this.syncRoom(e)}rejectWaiters(e,t){const n=this.roomWaiters.get(e);if(void 0!==n){this.roomWaiters.delete(e);for(const e of n)clearTimeout(e.timer),e.reject(t)}}clearRoomStates(){for(const e of this.roomStates.values())void 0!==e.timer&&clearTimeout(e.timer);this.roomStates.clear()}onServerEvent(e,t){try{this.applyEffects(e,t)}catch(t){this.logger.error(`Error handling ${e}:`,t)}if((!Gu(t)||!this.isDuplicate(e,t))&&(this.deliver(e,t,Gu(t)?function(e,t){const n=wu(e).token??"payload";if("none"===n)return;if("room"===n){const e=t.room;return"string"==typeof e&&e.startsWith(_u)?e.slice(_u.length):void 0}const r=t.tokenName;return"string"==typeof r&&""!==r?r:void 0}(e,t):void 0),Gu(t)))for(const n of function(e,t){if("TOKEN_CONFIG_UPDATED"!==e)return[];const n=t.tokenName;if("string"!=typeof n)return[];const r=[];if("nextLiveStreamAt"in t){const e=t.nextLiveStreamAt;r.push({name:"STREAM_COUNTDOWN_UPDATED",payload:{tokenName:n,nextLiveStreamAt:"string"==typeof e?e:null}})}const s=t.streamLanguage;return"string"==typeof s&&r.push({name:"STREAM_LANGUAGE_UPDATED",payload:{tokenName:n,language:s}}),r}(e,t))this.deliver(n.name,n.payload,n.payload.tokenName)}isDuplicate(e,t){const n=wu(e).duplicateKey?.(t);if(void 0===n)return!1;const r=Date.now(),s=`${e}:${n}`,i=this.recentOccurrences.get(s);if(void 0!==i&&r-i<5e3)return!0;if(this.recentOccurrences.set(s,r),this.recentOccurrences.size>256)for(const[e,t]of this.recentOccurrences)r-t>=5e3&&this.recentOccurrences.delete(e);return!1}deliver(e,t,n){const r=this.subscribers.get(e);if(void 0===r)return;const s=void 0===n?void 0:hn(n);for(const n of[...r])n.active&&(void 0!==n.token&&n.token!==s||(void 0===n.filter||this.passes(n,t))&&this.invoke(e,n.deliver,t))}passes(e,t){try{return e.filter?.(t)??!0}catch(t){return this.logger.error(`Error in a ${e.name} filter:`,t),!1}}invoke(e,t,n){try{const r=t(n);r instanceof Promise&&r.catch(t=>{this.logger.error(`Error in a ${e} subscriber:`,t)})}catch(t){this.logger.error(`Error in a ${e} subscriber:`,t)}}applyEffects(e,t){if("authenticated"===e)null!==this.inFlight?this.inFlight.settle(!0):this.adoptLateAuthentication();else if("stream_chat_auth_error"===e)this.authenticated=!1,this.inFlight?.settle(!1);else if("exception"===e)this.inFlight?.settle(!1);else if(function(e){return Ou.has(e)}(e))Gu(t)&&"string"==typeof t.room&&this.onRoomAcknowledged(t.room);else{const n=Mu[e];void 0!==n&&(this.siteConfig={...this.siteConfig,[n]:ju(t)})}}liveSocket(){return null!==this.socket&&this.socket.connected?this.socket:null}connect(){if(this.disposed)return Promise.reject(new Rt("The stream WebSocket service has been disposed."));if(!this.isSocketIOAvailable)return Promise.reject(new Rt('Socket.IO not available. Install "socket.io-client" package.'));const e=this.socket??this.createSocket();if(e.connected)return Promise.resolve();if(null===this.connectAttempt){let e=()=>{},t=()=>{};const n=new Promise((n,r)=>{e=n,t=r});this.connectAttempt={promise:n,resolve:e,reject:t}}return e.connect(),this.connectAttempt.promise}createSocket(){this.logger.debug(`🔌 Connecting to Stream WebSocket: ${this.config.url}`);const e=k(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 ku)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: ${Lt(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?Bu:(this.connectionStateListeners.add(e),()=>{this.connectionStateListeners.delete(e)})}onReconnect(e){return this.disposed?Bu:(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: ${Lt(e)}`),null}}authenticate(e){if(""===e)return Promise.reject(Kt("token","Authentication token"));const t=this.pendingAuthenticate;if(null!==t&&t.token===e&&t.generation===this.connectionGeneration)return t.promise;this.authSequence+=1;const n=this.authSequence,r=this.runAuthenticate(e,n).finally(()=>{this.pendingAuthenticate?.promise===r&&(this.pendingAuthenticate=null)});return this.pendingAuthenticate={token:e,generation:this.connectionGeneration,promise:r},r}async runAuthenticate(e,t){if(this.disposed)return!1;const n=e??await this.resolveToken();if(t!==this.authSequence||null===n)return!1;void 0!==e&&(this.lastExplicitToken=e);try{await this.connect()}catch(e){return this.logger.warn(`Cannot authenticate, the connection failed: ${Lt(e)}`),!1}for(;null!==this.inFlight;)if(await this.inFlight.settled,t!==this.authSequence)return!1;const r=this.liveSocket();if(t!==this.authSequence||null===r)return!1;if(this.authenticated&&this.authenticatedToken===n&&this.authenticatedGeneration===this.connectionGeneration)return!0;const s=this.beginAuthentication(t,n);this.lastEmitted={seq:t,token:n,generation:this.connectionGeneration},this.logger.debug("📡 Authenticating with stream server"),r.emit(Tu.AUTHENTICATE,{token:n});return await s.result&&t===this.authSequence}beginAuthentication(e,t){let n=()=>{};const r=new Promise(e=>{n=e}),s={seq:e,token:t,generation:this.connectionGeneration,result:r,settled:r.then(()=>{}),timer:void 0,settle:e=>{this.finishAuthentication(s,e,n)}};return s.timer=setTimeout(()=>{this.logger.warn("Stream WebSocket authentication timed out"),s.settle(!1)},this.config.subscriptionTimeout),this.inFlight=s,s}finishAuthentication(e,t,n){if(this.inFlight!==e)return;void 0!==e.timer&&clearTimeout(e.timer),this.inFlight=null;const r=e.seq===this.authSequence&&e.generation===this.connectionGeneration;t&&r&&this.markAuthenticated(e.token,e.generation),n(t&&r)}markAuthenticated(e,t){this.authenticated=!0,this.authenticatedToken=e,this.authenticatedGeneration=t,this.wantsAuthentication=!0,this.syncAllRooms()}adoptLateAuthentication(){const e=this.lastEmitted;null===e||this.authenticated||e.seq===this.authSequence&&e.generation===this.connectionGeneration&&this.markAuthenticated(e.token,e.generation)}deauthenticate(){this.authSequence+=1;const e=this.authenticated||null!==this.inFlight;this.inFlight?.settle(!1),this.pendingAuthenticate=null,this.wantsAuthentication=!1,this.lastExplicitToken=null,this.authenticated=!1,this.authenticatedToken=null,this.authenticatedGeneration=-1,e&&null!==this.socket&&!this.disposed&&(this.socket.disconnect(),this.socket.connect())}isAuthenticatedForChat(){return this.authenticated}isConnected(){return this.socket?.connected??!1}requireReady(){const e=this.liveSocket();if(null===e)throw new wt("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(!this.authenticated)throw new wt("Not authenticated. Call authenticate() first.","auth","NOT_AUTHENTICATED");return e}sendChatMessage(e,t){if(""===e)throw Kt("tokenName","Token name");if(""===t)throw Kt("content","Message content");const n=this.requireReady(),r=hn(e);this.logger.debug(`📡 Sending chat message to ${r}: ${t.slice(0,30)}...`),n.emit(Tu.SEND_CHAT,{tokenName:r,content:t})}sendReaction(e,t,n=0){if(""===e)throw Kt("tokenName","Token name");if(""===t)throw Kt("emoji");const r=this.requireReady(),s=hn(e);this.logger.debug(`📡 Sending reaction to ${s}: ${t}`),r.emit(Tu.SEND_REACTION,{tokenName:s,emoji:t,streamTime:n})}sendTypingStart(e){this.sendTypingEvent(e,Tu.TYPING_START)}sendTypingStop(e){this.sendTypingEvent(e,Tu.TYPING_STOP)}sendTypingEvent(e,t){if(""===e)throw Kt("tokenName","Token name");this.requireReady().emit(t,{tokenName:hn(e)})}subscribeToken(e,t,n){const r=Wu(t);return this.register(e,e=>n($u(0,e)),{token:r,room:Ku(r)})}joinTokenRoom(e){return this.hold(Ku(Wu(e)))}subscribeComment(e,t,n){const r=Wu(t);return this.register(e,e=>n($u(0,e)),{token:r,room:Hu(r)})}subscribeFeed(e,t){return this.register(e,e=>t($u(0,e)),{room:Du})}subscribeEvent(e,t){return this.register(e,e=>t($u(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:hn(e.tokenName),r=e.userAddress?.toLowerCase();return void 0!==t||void 0!==n||void 0!==r?e=>{if(!Gu(e))return!1;const s=e.eventType;if(void 0!==t&&("string"!=typeof s||!t.includes(s.toLowerCase())))return!1;const i=e.tokenName;if(void 0!==n&&("string"!=typeof i||hn(i)!==n))return!1;const o=e.userAddress;return void 0===r||"string"==typeof o&&o.toLowerCase()===r}:void 0}(t);return this.register("EVENT",t=>e($u(0,t)),{room:Cu,...void 0!==n&&{filter:n}})}subscribeFeedTokenEvents(e){const t=Lu.map(t=>this.register(t,n=>e(function(e,t){return{event:e,data:$u(0,t)}}(t,n)),{room:Du}));return()=>{for(const e of t)e()}}subscribeToGlobalFeed(e={}){const t=this.registerCallbacks(e,xu,()=>({})),n=this.hold(Du);return()=>{t(),n()}}addCallbacks(e){return this.registerCallbacks(e,Pu,()=>({}))}registerCallbacks(e,t,n){const r=[],s={...e};for(const[e,i]of Object.entries(t)){const t=s[e];"function"==typeof t&&r.push(this.register(i,e=>Reflect.apply(t,void 0,[e]),n(i)))}return()=>{for(const e of r)e()}}async subscribeToStream(e,t={}){const n=Wu(e),r=Ku(n),s=this.epoch;if(await this.connect(),s!==this.epoch||this.disposed)throw new Error("WebSocket disconnected");const i=this.registerCallbacks(t,Pu,e=>{return t=e,Uu.has(t)?{token:n}:function(e){return Fu.has(e)}(e)?{token:n,room:Hu(n)}:{};var t}),o=this.hold(r),a={release:()=>{i(),o()}},c=this.explicitHolds.get(n)??[];c.push(a),this.explicitHolds.set(n,c);try{return await this.waitForRoom(r,n)}catch(e){throw this.dropExplicitHold(n,a),e}}waitForRoom(e,t){return"joined"===this.roomStates.get(e)?.phase?Promise.resolve({room:e,tokenName:t}):new Promise((n,r)=>{const s={resolve:n,reject:r,timer:setTimeout(()=>{this.roomWaiters.get(e)?.delete(s),r(new Error(`Subscription to ${t} timed out after ${this.config.subscriptionTimeout}ms`))},this.config.subscriptionTimeout)},i=this.roomWaiters.get(e)??new Set;i.add(s),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=hn(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(_u)&&e.push(t.slice(_u.length));return e}isSubscribedToGlobalFeed(){return(this.roomRefs.get(Du)??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 ju(e){if(!Gu(e))return;const t=e.enabled;return"boolean"==typeof t?t:void 0}function qu(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"number"==typeof t.id&&"string"==typeof t.tokenName&&"string"==typeof t.bannedBy&&"string"==typeof t.createdAt&&(null===t.reason||"string"==typeof t.reason)}function zu(e){return null==e||""===e||"string"==typeof e&&(!Yn(e)&&e.length<=pr.BAN_REASON.MAX_LENGTH)}function Xu(e){if(Wn(e.tokenName,"tokenName",or),!zu(e.reason))throw new wt(`reason must be at most ${pr.BAN_REASON.MAX_LENGTH} characters`,"reason","TOO_LONG")}function Qu(e){Wn(e.tokenName,"tokenName",cr)}function Yu(e){$n(0,void 0,ur,e.pageSize)}function Ju(e){Wn(e.tokenName,"tokenName",cr)}class Zu extends $o{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async banToken(e){Xu(e);const t=He,n={tokenName:hn(e.tokenName)};if(void 0!==e.reason)try{Rn(e.reason,"reason",!0),e.reason.trim().length>0&&(n.reason=e.reason)}catch{}const r=await this.http.post(t,n,this.getDualAuthHeaders());return{ban:this.extractData(r),tokenName:hn(e.tokenName)}}async unbanToken(e){Qu(e);const t=this.buildEndpoint(je,{tokenName:e.tokenName});return rn(await this.http.delete(t,void 0,this.getDualAuthHeaders()),"Failed to unban token",!1),{tokenName:hn(e.tokenName)}}async listTokenBans(e={}){Yu(e);const t=We,n=this.buildPaginationParams(e,ur);this.addOptionalFilterParams(n,e,["search"]);const r=await this.http.get(t,n,this.getDualAuthHeaders()),s=this.extractData(r);return{items:s.bans,pageInfo:s.pageInfo}}async getTokenBan(e){Ju(e);const t=this.buildEndpoint(Ve,{tokenName:e.tokenName}),n=await this.http.get(t,{},this.getDualAuthHeaders()),r=this.extractDataOrNull(n);return{banned:null!==r,...null!==r&&{ban:r},tokenName:hn(e.tokenName)}}async isTokenBanned(e){return this.getTokenBan(e)}}class eh extends rr{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(!xn(e))throw Kt("tokenName","Token name");const t=hn(e),n=this.getCacheEntry(t);if(null!==n)return this.cacheHits++,this.updateAccessOrder(t),n.vaultAddress;this.cacheMisses++;const r=await this.poolService.resolveTokenNameToVault(e);if(null!==r&&""!==r){const e=this.parseVaultAddressToTokenClassKey(r);this.setCacheEntry(t,{vaultAddress:r,tokenClassKey:e,cachedAt:Date.now()})}return r}async resolveTokenClassKey(e){if(!xn(e))throw Kt("tokenName","Token name");const t=hn(e),n=this.getCacheEntry(t);if(null!==n)return this.cacheHits++,this.updateAccessOrder(t),n.tokenClassKey;this.cacheMisses++;const r=await this.poolService.resolveTokenNameToVault(e);if(null===r||""===r)throw $t(e);const s=this.parseVaultAddressToTokenClassKey(r);return this.setCacheEntry(t,{vaultAddress:r,tokenClassKey:s,cachedAt:Date.now()}),s}get(e){const t=this.getCacheEntry(hn(e));return t?.vaultAddress??null}getCacheEntry(e){return this.cache.get(e)??null}setCacheEntry(e,t){this.cache.size>=eh.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=hn(e),r=this.parseVaultAddressToTokenClassKey(t);this.setCacheEntry(n,{vaultAddress:t,tokenClassKey:r,cachedAt:Date.now()})}clear(){this.cache.clear(),this.accessOrder=new Set,this.cacheHits=0,this.cacheMisses=0}getStats(){const e=Array.from(this.cache.values()).map(e=>e.cachedAt),t=this.cacheHits+this.cacheMisses;return{size:this.cache.size,keys:Array.from(this.cache.keys()),maxSize:eh.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(hn(e));return t?.tokenClassKey??null}preWarm(e){for(const{tokenName:t,vaultAddress:n}of e)this.set(t,n)}preWarmWithTokenClassKey(e){for(const{tokenName:t,vaultAddress:n,tokenClassKey:r}of e){const e=hn(t);this.setCacheEntry(e,{vaultAddress:n,tokenClassKey:r,cachedAt:Date.now()})}}parseVaultAddressToTokenClassKey(e){try{return Fa(e)}catch(e){if(e instanceof wt)throw Ht("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad","Vault address");throw e}}}eh.MAX_CACHE_SIZE=1e4;class th extends nr{constructor(e,t=!1){super(e,t)}async fetchLaunchpadFee(){const e=await an(()=>this.http.get(ct),{errorContext:"Failed to fetch launchpad fee"});if("number"!=typeof e.feeAmount||!Number.isFinite(e.feeAmount))throw new wt("Failed to fetch launchpad fee: no feeAmount in the response","feeAmount","INVALID_RESPONSE");return e.feeAmount}async fetchSaleDetails(e){return an(()=>this.http.get(lt,{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 eo(await an(()=>void 0===n?this.http.get(dt,t):this.http.request({method:"GET",url:dt,params:t,signal:n}),{errorContext:`Failed to get trade quote for ${e.tokenName}`}),`trade quote for ${e.tokenName}`)}async getPremintQuote(e){return eo(await an(()=>this.http.get(ut,{amount:e}),{errorContext:"Failed to get premint quote"}),"premint quote")}}class nh extends $o{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async emitTradeExecuted(e,t){this.validateTokenName(e,dr);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,dr);const r={action:"balance_updated",userAddress:e,tokenName:t,payload:n};await this.emitEvent(r)}async emitStreamStatus(e,t,n=!0){this.validateTokenName(e,dr);const r={action:"stream_status",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitViewerCount(e,t,n=!1){this.validateTokenName(e,dr);const r={action:"viewer_count",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitStreamCountdown(e,t,n=!0){this.validateTokenName(e,dr);const r={action:"stream_countdown",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitChatMessage(e,t,n=!1){this.validateTokenName(e,dr);const r={action:"chat_message",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitChatStatus(e,t,n=!1){this.validateTokenName(e,dr);const r={action:"chat_status",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitTypingIndicator(e,t,n=!1){this.validateTokenName(e,dr);const r={action:"typing_indicator",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitTokenBanned(e,t){this.validateTokenName(e,dr);const n={action:"token_banned",tokenName:e,payload:t,broadcast:!0};await this.emitEvent(n)}async emitTokenUnbanned(e,t){this.validateTokenName(e,dr);const n={action:"token_unbanned",tokenName:e,payload:t,broadcast:!0};await this.emitEvent(n)}async emitModeratorAdded(e,t,n=!1){this.validateTokenName(e,dr);const r={action:"moderator_added",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitModeratorRemoved(e,t,n=!1){this.validateTokenName(e,dr);const r={action:"moderator_removed",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitUserProfileUpdated(e,t){this.validateRequiredString(e,"userAddress","User Address");const n={action:"user_profile_updated",userAddress:e,payload:t};await this.emitEvent(n)}async emitSiteConfigChanged(e){const t={action:"site_config_changed",payload:e,broadcast:!0};await this.emitEvent(t)}async emitFeatureStatus(e){const t={action:"feature_status",payload:e,broadcast:!0};await this.emitEvent(t)}async emitEvent(e){this.validateRequiredString(e.action,"action","Event Action");const t=this.buildEndpoint("/v1/websocket",{});await this.http.post(t,e,this.getDualAuthHeaders())}async getConnectedClients(e){const t=this.buildEndpoint("/v1/connected-clients",{}),n={};void 0!==e?.room&&""!==e.room&&(n.room=e.room),void 0!==e?.tokenName&&(n.tokenName=e.tokenName),void 0!==e?.userAddress&&(n.userAddress=e.userAddress),void 0!==e?.userAddresses&&(n.userAddresses=e.userAddresses),void 0!==e?.authenticated&&(n.authenticated=e.authenticated),void 0!==e?.isOverseer&&(n.isOverseer=e.isOverseer),void 0!==e?.minConnectionSeconds&&(n.minConnectionSeconds=e.minConnectionSeconds),void 0!==e?.offset&&(n.offset=e.offset),void 0!==e?.limit&&(n.limit=e.limit);const r=await this.http.get(t,Object.keys(n).length>0?n:void 0,this.getDualAuthHeaders());return this.extractData(r)}async isUserOnline(e){this.validateRequiredString(e,"userAddress","User Address");const t=await this.getConnectedClients({userAddress:e,limit:1});if(0===t.clients.length)return{online:!1};const n=t.clients[0];return void 0===n?{online:!1}:{online:!0,socketId:n.socketId,rooms:n.rooms,connectedAt:n.connectedAt}}async getOnlineUsers(e){if(!Array.isArray(e)||0===e.length)throw new Rt("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,dr);const n={tokenName:e};void 0!==t?.authenticated&&(n.authenticated=t.authenticated),void 0!==t?.limit&&(n.limit=t.limit);const r=await this.getConnectedClients(n);return{clients:r.clients,count:r.summary.totalConnected,authenticatedCount:r.summary.authenticatedCount}}async getOnlineOverseers(){const e=await this.getConnectedClients({isOverseer:!0});return{clients:e.clients,count:e.summary.totalConnected}}async emitRecordingStatus(e,t){this.validateTokenName(e,dr);const n={action:"recording_status",tokenName:e,payload:t};await this.emitEvent(n)}async emitRecordingsCountUpdated(e,t){this.validateTokenName(e,dr);const n={action:"recordings_count_updated",tokenName:e,payload:t};await this.emitEvent(n)}async emitDownloadReady(e,t){this.validateTokenName(e,dr);const n={action:"download_ready",tokenName:e,payload:t};await this.emitEvent(n)}}class rh{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 sh{constructor(e=0){this.defaultTtlMs=e,this.cache=new Map}get(e){const t=this.cache.get(e);if(t){if(!(void 0!==t.expiresAt&&Date.now()>t.expiresAt))return t.value;this.cache.delete(e)}}set(e,t,n){const r=n??this.defaultTtlMs,s={value:t};r>0&&(s.expiresAt=Date.now()+r),this.cache.set(e,s)}has(e){return void 0!==this.get(e)}delete(e){this.cache.delete(e)}clear(){this.cache.clear()}get size(){return this.cache.size}}class ih extends rr{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 rh({maxAttempts:this.config.reconnectAttempts??5,baseDelayMs:this.config.reconnectDelay??2e3}),this.eventBuffer=new sh(3e4),this.isSocketIOAvailable=this.checkSocketIOAvailability(),ih.instances.add(this)}checkSocketIOAvailability(){try{return"function"==typeof k||(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)=>{fo(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=k(this.config.url,{transports:["websocket"],reconnection:!0,reconnectionAttempts:this.config.reconnectAttempts??5,reconnectionDelay:this.config.reconnectDelay??2e3}),this.socket.on("connect",()=>{this.logger.debug("✅ Socket.IO connected successfully:",this.socket?.id),this.logger.debug("📡 Connected to bundle backend WebSocket:",this.config.url),this.logger.debug("🔗 Ready to monitor transaction updates"),this.reconnectionManager.reset(),e()}),this.socket.on("connect_error",e=>{this.logger.error("❌ Socket.IO connection error:",e),t(e)}),this.socket.on("disconnect",e=>{this.logger.debug(`🔌 Socket.IO disconnected: ${e}`),this.handleReconnect()}),this.socket.on("error",e=>{this.logger.error("❌ Socket.IO error:",e)}),this.socket.onAny((e,...t)=>{if(""!==e&&t.length>0&&"object"==typeof t[0]&&null!==t[0]){const n=t[0],r=n.status??n.Status;"string"==typeof r&&(this.logger.debug(`📡 [Event Buffer] Buffering event for ${e}: ${r}`),this.eventBuffer.size>=this.MAX_BUFFER_SIZE&&this.logger.warn(`📡 [Event Buffer] Buffer approaching limit (${this.eventBuffer.size}/${this.MAX_BUFFER_SIZE})`),this.eventBuffer.set(e,n))}this.debug&&this.logger.debug(`📡 [WebSocket Event] "${e}":`,JSON.stringify(t,null,2))}),this.hasOnAnyListener=!0},"Socket.IO connection failed",this.logger,e=>{this.logger.error("Socket.IO connection failed:",e);const n=Mt(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 r=this.config.timeout??3e5,s=setTimeout(()=>{if(this.listeners.has(e)){const n=Math.round(r/1e3),s={transactionId:e,status:So.TIMEOUT,message:`Transaction monitoring timeout - no response after ${n} seconds`,timestamp:Date.now()};this.logger.debug(`📡 Transaction timeout for ${e} (${n}s)`),t(s),this.listeners.delete(e),this.timeouts.delete(e),this.socket?.off(e)}},r);if(this.timeouts.set(e,s),this.socket?.connected)this.socket.off(e),this.logger.debug(`📡 Listening for transaction updates: ${e}`),this.logger.debug(`📡 WebSocket connection ID: ${String(this.socket.id)}`),this.logger.debug(`📡 WebSocket URL: ${this.config.url}`),this.socket.on(e,n=>{this.processTransactionEvent(e,n,t)});else{const n={transactionId:e,status:So.FAILED,message:"WebSocket not connected - cannot monitor transaction",timestamp:Date.now()};t(n),this.listeners.delete(e),this.timeouts.delete(e)}await Promise.resolve()}processTransactionEvent(e,t,n){this.logger.debug(`📡 Socket.IO transaction update for ${e}:`,JSON.stringify(t,null,2));const r=t,s=r?.data,i=r?.status??r?.Status??s?.status??s?.Status;let o=r?.message??r?.Message??s?.message??s?.Message??r?.error??s?.error;xn(o)||(o=i===yo.FAILED||i===yo.ERROR?"Transaction failed - check transaction details":i===yo.COMPLETED||i===yo.PROCESSED||i===yo.SUCCESS?"Transaction completed successfully":null!=i?`Transaction status: ${String(i)}`:"Unknown transaction status");const a=r?.blockHash??s?.blockHash,c=r?.gasUsed??s?.gasUsed,l=r?.Data??s?.Data,d={transactionId:e,status:this.mapSocketStatus(i),message:"string"==typeof o?o:"Transaction update received",timestamp:Date.now(),...null!=a?{blockHash:a}:{},...null!=c?{gasUsed:c}:{},...null!=l?{data:l}:{}};if(this.logger.debug(`📡 Mapped status for ${e}: ${String(i)} -> ${d.status}`),this.logger.debug(`📡 Final message: "${String(o)}"`),n(d),d.status===So.COMPLETED||d.status===So.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===So.COMPLETED?t(e):e.status!==So.FAILED&&e.status!==So.TIMEOUT||n(new Error(`Transaction ${String(e.status)}: ${e.message}`))})})}mapSocketStatus(e){const t=e?.toUpperCase();return bo[t]??So.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")),ih.instances.delete(this)}static cleanupAll(e=!1){for(const e of ih.instances)e.disconnect();ih.instances.clear()}isConnected(){return this.socket?.connected??!1}getSocket(){return this.socket}}ih.instances=new Set;class oh extends nr{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 wt("limit must be between 1 and 50","limit","INVALID_LIMIT");this.logger.debug("Fetching weekly challenge leaderboard",{limit:t});const n={limit:String(t)},r=await this.http.get(ht.GET_LEADERBOARD,n),s=this.extractData(r);return this.logger.debug("Fetched weekly challenge leaderboard",{count:s.count}),{leaderboard:s}}async getTokenHistory(e){const{vaultAddress:t}=e;if("string"!=typeof t||""===t.trim())throw new wt("vaultAddress is required","vaultAddress","REQUIRED_FIELD");this.logger.debug("Fetching token weekly history",{vaultAddress:t});const n=ht.GET_TOKEN_HISTORY.replace(":vaultAddress",encodeURIComponent(t)),r=await this.http.get(n),s=this.extractData(r);return this.logger.debug("Fetched token weekly history",{count:s.length}),{snapshots:s}}}const ah=["CreateSale","BuyWithNative","BuyExactToken","SellWithNative","SellExactToken"];class ch{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 lh{constructor(e){this.bundleBaseUrl=vh(e.bundleBaseUrl),this.launchpadBaseUrl=vh(e.launchpadBaseUrl),this.signer=e.signer,this.walletAddress=e.walletAddress,this.requestor=e.httpRequestor??fetch.bind(globalThis),this.socketFactory=e.socketFactory??(e=>k(e,{transports:["websocket"]})),this.bundleSocketFactory=e.bundleSocketFactory}attach(e){const{bundleId:t,method:n,uniqueKey:r,tokenName:s}=e;if("string"!=typeof t||""===t)throw uh("bundleId");if(i=n,!ah.some(e=>e===i))throw uh("method");var i;if("string"!=typeof r||""===r)throw uh("uniqueKey");if(void 0!==s&&("string"!=typeof s||""===s))throw uh("tokenName");if("CreateSale"===n&&void 0===s)throw uh("tokenName");const o={method:n,dto:{uniqueKey:r,...void 0===s?{}:{tokenName:s}},stringsInstructions:[]};return new ch({bundleId:t,uniqueKey:r,method:n,wait:e=>this.waitForResult(o,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 ya)return e;if(E(e)){const t=e instanceof Error?e.message:"The signature was rejected in the wallet.",n=A(e);return new ya(t,"WALLET_USER_REJECTED",{details:void 0===n?{}:{walletCode:n}})}const t=e instanceof Error?e.message:"Launchpad signing failed.";return new ya(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`,s=await this.requestor(r,{method:"POST",headers:{"content-type":"application/json","X-Wallet-Address":this.walletAddress},body:JSON.stringify({stringsInstructions:e.stringsInstructions,method:e.method,signedDto:n})}),i=await Eh(s);if(!s.ok)throw gh(s.status,i,r);const o=function(e){if("string"==typeof e&&""!==e)return e;if(!Ah(e))throw new ya("Bundler returned no bundle id.","INVALID_BUNDLE_RESPONSE");const t=e.data,n=e.bundleId;if("string"==typeof t&&""!==t)return t;if(Ah(t)&&"string"==typeof t.bundleId&&""!==t.bundleId)return t.bundleId;if("string"==typeof n&&""!==n)return n;throw new ya("Bundler returned no bundle id.","INVALID_BUNDLE_RESPONSE")}(i),a=ph(e.dto,"uniqueKey");return new ch({bundleId:o,uniqueKey:a,method:e.method,wait:t=>this.waitForResult(e,o,t)})}waitForResult(e,t,n={}){const r=n.timeoutMs??6e4,s=n.pollIntervalMs??2500,i=n.signal;return new Promise((n,o)=>{const a=this.confirmationUrl(e,t);if(!0===i?.aborted)return void o(dh(e.method,t));const c=Date.now(),l=new AbortController,d=void 0===this.bundleSocketFactory;let u,h,g,m=!1;const f=()=>{p(()=>o(dh(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())},E=()=>{p(()=>o(function(e,t){const n="string"==typeof e.dto.uniqueKey?e.dto.uniqueKey:"";return new ya(`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(E,r);try{u=(this.bundleSocketFactory??this.socketFactory)(this.bundleBaseUrl),h=e=>{const t=function(e){if(!Ah(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?o(hh(t.data)):n(t)})},u.on(t,h)}catch{u=void 0,h=void 0}this.pollConfirmation({request:e,confirmationUrl:a,startedAt:c,timeoutMs:r,pollIntervalMs:s,signal:l.signal,onReadFailure:e=>{g=e}}).then(e=>{void 0===e?E():p(()=>n(e))},e=>p(()=>o(e instanceof Error?e:new Error(String(e)))))})}confirmationUrl(e,t){return"CreateSale"===e.method?function(e,t){const n=ph(t,"tokenName");return`${e}/v1/tokens/${encodeURIComponent(n)}`}(this.launchpadBaseUrl,e.dto):`${this.bundleBaseUrl}/bundle?id=${encodeURIComponent(t)}`}async pollConfirmation(e){const{request:t,confirmationUrl:n,startedAt:r,timeoutMs:s,pollIntervalMs:i,signal:o,onReadFailure:a}=e;for(;!o.aborted&&Date.now()-r<=s;){const e=await this.readConfirmation(t,n,o);if(o.aborted)return;if("processed"===e.kind)return e.result;if("failed"===e.kind)throw hh(e.data);a("read-failed"===e.kind?e.error:void 0);const c=s-(Date.now()-r);if(c<=0)break;await Th(Math.min(Math.max(0,i),c),o)}}async readConfirmation(e,t,n){try{const r=await this.requestor(t,{method:"GET",signal:n}),s=await Eh(r);if("CreateSale"===e.method)return r.ok?{kind:"processed",result:{status:"PROCESSED",data:fh(s)}}:404===r.status||202===r.status?{kind:"pending"}:{kind:"read-failed",error:gh(r.status,s,t)};if(!r.ok)return{kind:"read-failed",error:gh(r.status,s,t)};const i=Ah(s)?s.status:void 0;return"COMPLETED"===i||"PROCESSED"===i?{kind:"processed",result:{status:"PROCESSED",data:s}}:"FAILED"===i?{kind:"failed",data:s}:{kind:"pending"}}catch(e){const n=e instanceof Error?e.message:"The bundle confirmation read failed.";return{kind:"read-failed",error:new ya(n,"BUNDLE_REQUEST_FAILED",{details:{url:t}})}}}}function dh(e,t){return new ya("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 uh(e){return new ya(`Cannot attach to a launchpad bundle: ${e} is missing or not accepted.`,"INVALID_BUNDLE_ATTACHMENT",{details:{field:e}})}function hh(e){const t=mh(e)??"Launchpad bundle failed on chain.";return new ya(t,"BUNDLE_FAILED",{chainMessage:t})}function gh(e,t,n){const r=mh(t)??`Bundle request failed with HTTP ${e}`;return new ya(r,"BUNDLE_REQUEST_FAILED",{status:e,chainMessage:r,details:{body:t,url:n}})}function mh(e){if("string"==typeof e&&""!==e)return e;if(Ah(e))for(const t of["chainMessage","message","Message","error"]){const n=e[t];if("string"==typeof n&&""!==n)return n;if(Ah(n)){const e=mh(n);if(void 0!==e)return e}}}function fh(e){return Ah(e)?e.data??e.Data??e:e}function ph(e,t){const n=e[t];if("string"!=typeof n||""===n)throw new ya(`Missing ${t} in launchpad DTO.`,"INVALID_LAUNCHPAD_DTO");return n}async function Eh(e){try{return await e.json()}catch{return e.text()}}function Ah(e){return"object"==typeof e&&null!==e}function vh(e){return e.replace(/\/$/u,"")}function Th(e,t){return new Promise(n=>{if(t.aborted)return void n();const r=()=>{clearTimeout(s),n()},s=setTimeout(()=>{t.removeEventListener("abort",r),n()},e);t.addEventListener("abort",r,{once:!0})})}function yh(e,t){if(!/^\d+(\.\d+)?$/.test(e))throw new wt(`Quoted reverse bonding curve fee is not a non-negative number: ${e}`,"extraFees","INVALID_QUOTED_FEE");if(!Number.isFinite(t)||t<0)throw new wt(`Fee slippage factor must be a non-negative number, got ${String(t)}`,"maxAcceptableReverseBondingCurveFeeSlippageFactor","INVALID_FEE_SLIPPAGE_FACTOR");return new _(e).multipliedBy(new _(1).plus(new _(String(t)))).decimalPlaces(8,_.ROUND_UP).toFixed()}function Sh(e){return async t=>{const n=t.tokenName??await async function(e,t){const n=Ra(t).type,r=await e.findTokenNameByVault(t,n);if(void 0===r)throw new wt(`Could not find the launchpad token for vault ${t}, so the reverse bonding curve fee ceiling cannot be quoted. Pass tokenName, or pass extraFees.maxAcceptableReverseBondingCurveFee explicitly.`,"tokenName","TOKEN_NOT_FOUND_FOR_VAULT");return r}(e,t.vaultAddress);return yh((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 bh={minFeePortion:"0.1",maxFeePortion:"0.5"},Nh=/^(?:\d+\.?\d*|\.\d+)$/u,wh=/^[0-9A-Z]+$/u,kh=/^[A-Za-z0-9]+$/u,_h=new _("0.1"),Ih=new _("0.5");function Dh(e){if("string"!=typeof e||!Nh.test(e))return;const t=new _(e);return t.isFinite()?t.toFixed():void 0}function Ch(e){return"string"==typeof e&&""!==e}function Rh(e,t,n){void 0!==n&&"string"!=typeof n&&e.push(`${t} must be a string`)}function Oh(e,t,n){void 0===n||Ch(n)||e.push(`${t} must be a non-empty string`)}function Mh(e){const t=[];if("object"!=typeof e||null===e)throw new wt("CreateSale input must be an object","data","VALIDATION_ERROR");const n={...e},r=n.tokenName;Ch(r)?kh.test(r)||t.push("Token name can only contain letters and numbers"):t.push("Token name is required");const s=n.tokenSymbol;Ch(s)?wh.test(s.toUpperCase())||t.push("Token symbol can only contain letters and numbers"):t.push("Token symbol is required");const i=n.tokenDescription;Ch(i)?i.length>1e3&&t.push("Token description must be at most 1000 characters"):t.push("Token description is required");const o=n.tokenImage;Ch(o)?o.length>500&&t.push("Token image must be at most 500 characters"):t.push("Token image is required");const a=n.preBuyQuantity;void 0!==a&&void 0===Dh(a)&&t.push("preBuyQuantity must be a non-negative decimal number");for(const e of["websiteUrl","telegramUrl","twitterUrl","instagramUrl","facebookUrl","redditUrl","tiktokUrl"])Rh(t,e,n[e]);Oh(t,"tokenCategory",n.tokenCategory),Oh(t,"tokenCollection",n.tokenCollection);const c=n.saleStartTime;if(void 0===c||Number.isInteger(c)||t.push("saleStartTime must be an integer"),function(e,t){if(void 0!==t&&("object"!=typeof t||null===t))return void e.push("reverseBondingCurveConfiguration must be an object");const n=t??{},r=n.minFeePortion??bh.minFeePortion,s=n.maxFeePortion??bh.maxFeePortion,i=Dh(r),o=Dh(s);if(void 0===i&&e.push("minFeePortion must be a decimal number"),void 0===o&&e.push("maxFeePortion must be a decimal number"),void 0===i||void 0===o)return;const a=new _(i),c=new _(o);a.isLessThan(_h)&&e.push("minFeePortion must be greater than or equal to 0.1"),c.isGreaterThan(Ih)&&e.push("maxFeePortion must be less than or equal to 0.5"),a.isGreaterThan(c)&&e.push("minFeePortion must be less than or equal to maxFeePortion")}(t,n.reverseBondingCurveConfiguration),t.length>0)throw new wt(t.join("; "),"data","VALIDATION_ERROR")}class Lh{constructor(e){this.transport=e.transport,this.walletAddress=e.walletAddress,this.sellFeeCeiling=e.sellFeeCeiling}createSale(e){Mh(e);const t=function(e,t){const n={tokenName:e.tokenName,tokenSymbol:e.tokenSymbol,tokenDescription:e.tokenDescription,tokenImage:e.tokenImage,preBuyQuantity:Dh(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??Uh(t)},r=e.reverseBondingCurveConfiguration;n.reverseBondingCurveConfiguration={minFeePortion:Dh(r?.minFeePortion??bh.minFeePortion),maxFeePortion:Dh(r?.maxFeePortion??bh.maxFeePortion)},void 0!==e.saleStartTime&&(n.saleStartTime=e.saleStartTime);return n}(e,this.walletAddress);return this.transport.submit({method:"CreateSale",dto:t,stringsInstructions:Ma(e)})}attach(e){return this.transport.attach(e)}buyWithNative(e){return this.submitTrade("BuyWithNative",e,{nativeTokenQuantity:e.quantity,expectedToken:e.expectedAmount})}buyExactToken(e){return this.submitTrade("BuyExactToken",e,{tokenQuantity:e.quantity,expectedNativeToken:e.expectedAmount})}sellWithNative(e){return this.submitTrade("SellWithNative",e,{nativeTokenQuantity:e.quantity,expectedToken:e.expectedAmount})}sellExactToken(e){return this.submitTrade("SellExactToken",e,{tokenQuantity:e.quantity,expectedNativeToken:e.expectedAmount})}async submitTrade(e,t,n){const r={vaultAddress:t.vaultAddress,...n,extraFees:t.extraFees??await this.defaultExtraFees(e,t),uniqueKey:t.uniqueKey??Uh(this.walletAddress)};return this.transport.submit({method:e,dto:r,stringsInstructions:Oa(t.vaultAddress)})}async defaultExtraFees(e,t){if("BuyWithNative"===e||"BuyExactToken"===e)return{maxAcceptableReverseBondingCurveFee:"0"};if(void 0===this.sellFeeCeiling)throw new wt("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 Uh(e){return`galaswap-operation-${w()}-${Date.now()}-${e}`}function Fh(e,t=3e4){return I.create({baseURL:e,timeout:t,headers:{"Content-Type":"application/json"}})}const Ph=new Set(["accesstoken","refreshtoken","token","password","privatekey","secret","apikey","api_key","rawkey","authorization","x-api-key","bearer","streamadminapikey","userapikey","signature","signedpayload"]);function xh(e,t=0){if(t>5)return"[...]";if(null==e)return e;if(Array.isArray(e))return e.map(e=>xh(e,t+1));if(e instanceof Map){const n={};for(const[r,s]of e.entries()){const e=String(r);n[e]=Ph.has(e.toLowerCase())?"[REDACTED]":xh(s,t+1)}return n}if("object"==typeof e){const n={};for(const[r,s]of Object.entries(e))n[r]=Ph.has(r.toLowerCase())?"[REDACTED]":xh(s,t+1);return n}return e}class Bh{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 pn({debug:this.debug,context:"HttpClient"});const r=t.baseUrl??To("stage").launchpadBaseUrl,s=t.timeout??6e4;this.axios=Fh(r,s),t.headers&&(this.axios.defaults.headers.common={...this.axios.defaults.headers.common,...t.headers}),void 0!==this.session&&"omit"!==this.session.credentials&&(this.axios.defaults.withCredentials=!0),this.setupInterceptors()}async request(e){return(await this.requestWithMeta(e)).data}async requestWithMeta(e){return fo(async()=>{const t=void 0!==this.session&&!1!==e.withSession&&!function(e){return void 0!==e&&Object.keys(e).some(e=>"authorization"===e.toLowerCase())}(e.headers),n=t&&void 0!==this.session?await this.session.accessToken():null,r=this.toAxiosConfig(e,n);e.headers&&this.logger.debug("Custom headers provided:",Object.keys(r.headers??{}));const s=e.data instanceof FormData?"[FormData object - multipart/form-data]":xh(e.data);this.logger.debug("Request:",{method:e.method,url:e.url?.split("?")[0],baseURL:this.axios.defaults.baseURL,params:xh(r.params),data:s,isFormData:e.data instanceof FormData,contentType:r.headers?.["Content-Type"]??"not set"});const i=await this.sendWithSession(e,r,t,n),o=function(e){const t={};if(null==e||"object"!=typeof e)return t;for(const[n,r]of Object.entries(e))"string"==typeof r?t[n.toLowerCase()]=r:"number"!=typeof r&&"boolean"!=typeof r||(t[n.toLowerCase()]=String(r));return t}(i.headers);return this.logger.debug("Response:",{status:i.status,data:xh(i.data),transactionId:o["x-transaction-id"],blockNumber:o["x-block-number"]}),{data:i.data,headers:o,status:i.status}},`HTTP ${e.method} ${e.url}`,this.logger)}toAxiosConfig(e,t){const n=null===t?e.headers:{...e.headers,Authorization:`Bearer ${t}`},r={method:e.method,url:e.url,data:e.data,...void 0!==e.params&&{params:Al(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 D(n);e.set("Content-Type",void 0),r.headers=e,this.logger.debug("FormData detected - clearing the JSON Content-Type default for the multipart upload")}return r}async sendWithSession(e,t,n,r){try{return await this.axios.request(t)}catch(t){if(!n||void 0===this.session||!function(e){if("object"!=typeof e||null===e||!("response"in e))return!1;const t=e.response;return"object"==typeof t&&null!==t&&"status"in t&&401===t.status}(t))throw t;const s=await this.session.onUnauthorized(r);if(null===s)throw t;return this.logger.debug("Retrying once with the refreshed session token"),await this.axios.request(this.toAxiosConfig(e,s))}}async get(e,t,n){return this.request({method:"GET",url:e,...t&&{params:t},...n&&{headers:n}})}async post(e,t,n){return this.request({method:"POST",url:e,data:t,...n&&{headers:n}})}async postWithMeta(e,t,n){return this.requestWithMeta({method:"POST",url:e,data:t,...n&&{headers:n}})}async put(e,t,n){return this.request({method:"PUT",url:e,data:t,...n&&{headers:n}})}async delete(e,t,n){return this.request({method:"DELETE",url:e,...t&&{params:t},...n&&{headers:n}})}async patch(e,t,n){return this.request({method:"PATCH",url:e,data:t,...n&&{headers:n}})}getAddress(){return this.auth.getAddress()}getEthereumAddress(){return this.auth.getEthereumAddress()}async signMessage(e){return(await this.auth.signMessage(e)).signature}async signTypedData(e,t,n){return await this.auth.signTypedData(e,t,n)}async signCustomMessage(e){return fo(async()=>{const t=await this.auth.generateCustomSignature(e);return this.logger.debug("Generated custom signature:",{message:e,address:t.address,ethereumAddress:this.auth.getEthereumAddress()}),{signature:t.signature,address:t.address,ethereumAddress:this.auth.getEthereumAddress()}},"Failed to generate custom signature for message",this.logger)}setupInterceptors(){this.requestInterceptorId=this.axios.interceptors.request.use(async e=>{if(e.headers??(e.headers={}),this.signRequests&&this.auth?.hasWallet()){const t=await this.auth.generateSignature();e.headers.Sign=t.signature,this.logger.debug("Added signature header:",{address:t.address,message:t.message,timestamp:t.timestamp})}else this.logger.debug("Skipping signature header (no wallet, or signRequests is off)");return e.data instanceof FormData||(e.headers["Content-Type"]="application/json"),this.logger.debug("Final request header keys being sent:",Object.keys(e.headers)),e},e=>Promise.reject(e instanceof Error?e:new Error(String(e)))),this.responseInterceptorId=this.axios.interceptors.response.use(e=>e,e=>{const t=e;if(void 0!==t.response){const n=t.response.data,r={message:n?.message??Lt(e),...n&&"string"==typeof n.error&&""!==n.error&&{error:n.error},statusCode:t.response.status,...n&&Boolean(n.details)&&{details:n.details},...n&&Boolean(n.timestamp)&&{timestamp:n.timestamp},...n&&Boolean(n.path)&&{path:n.path}};t.launchpadError=r,this.logger.error("Backend error:",r)}else void 0!==t.request?this.logger.error("Network error:",t.message??"Unknown error"):this.logger.error("Request setup error:",t.message??"Unknown error");return Promise.reject(e instanceof Error?e:new Error(String(e)))})}cleanup(){void 0!==this.requestInterceptorId&&(this.axios.interceptors.request.eject(this.requestInterceptorId),this.requestInterceptorId=void 0),void 0!==this.responseInterceptorId&&(this.axios.interceptors.response.eject(this.responseInterceptorId),this.responseInterceptorId=void 0),this.logger.debug("Interceptors cleaned up")}}class Gh extends Error{constructor(e,t){super(e),this.cause=t,this.name="WebSocketError"}}class $h extends Gh{constructor(e,t){super(`WebSocket confirmation timeout for transaction ${e} after ${t}ms`),this.name="WebSocketTimeoutError"}}class Kh 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 Hh(e,t){if(Gn(e))throw new Gh(`Invalid WebSocket response received for transaction ${t}: response is null or undefined`);if("object"!=typeof e)throw new Gh(`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 Gh(`Invalid WebSocket response received for transaction ${t}: missing status field`)}function Wh(e,t,n,r){Hh(e,t);const s=e,i=s.data??{};if(!function(e){if(Gn(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 Gh(`Invalid trade data received for transaction ${t}`);const o={transactionId:t,type:n,method:"native"===r.type?"native":"exact",inputAmount:i.inputQuantity??r.amount,outputAmount:i.outputQuantity??r.expectedAmount??"0",totalFees:i.totalFees??"0",tokenName:r.tokenName,vaultAddress:i.vaultAddress??"",timestamp:Date.now()};return void 0!==s.blockHash&&(o.blockHash=s.blockHash),void 0!==s.gasUsed&&(o.gasUsed=s.gasUsed),void 0!==r.slippageToleranceFactor&&(o.slippageTolerance=r.slippageToleranceFactor),o}function Vh(e){return void 0!==e&&S(e)?new s(e.exportPrivateKey()):void 0}const jh={MUSIC:"$MUSIC",GMUSIC:"$GMUSIC"};function qh(e){if(void 0===e||!("walletAddress"in e))return;const t=e.walletAddress;return"string"==typeof t&&""!==t?t:void 0}const zh=/^(?:eth\||0x)([0-9a-fA-F]{40})$/;function Xh(e,t,n){if(void 0===e||void 0===t)return;const r=zh.exec(e)?.[1],s=zh.exec(t)?.[1];if(void 0!==r&&void 0!==s&&r.toLowerCase()!==s.toLowerCase())throw Vt(`${n} ${t} is not the identity of the configured signing key (${e}); writes would be signed as the key, not as ${n}.`,n)}class Qh{constructor(e){let t,n;this.walletGeneration=0,e.walletProvider?(t=e.walletProvider,n=Vh(e.walletProvider)):e.wallet&&(n=e.wallet,t=y.fromWallet(e.wallet)),this.wallet=n;const r=e.env??"prod",s=To(r);this.environment=r,this.config={baseUrl:e.launchpadBaseUrl??s.launchpadBaseUrl,gatewayBaseUrl:s.gatewayBaseUrl,bundleBaseUrl:s.bundleBaseUrl,webSocketUrl:s.webSocketUrl,dexApiBaseUrl:s.dexApiBaseUrl,dexBackendBaseUrl:s.dexBackendBaseUrl,launchpadFrontendUrl:s.launchpadFrontendUrl,timeout:3e4,debug:!1,...e};const i=e.signer??(void 0!==n?new Ia(n.privateKey):void 0),o=void 0!==n?`eth|${n.address.slice(2)}`:qh(i);Xh(o,e.walletAddress,"walletAddress"),Xh(o,e.galaChainAddress,"galaChainAddress");const a=e.walletAddress??e.galaChainAddress??(void 0!==n?`eth|${n.address.slice(2)}`:qh(i)),c=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."))},l=a??"";this.tokenWriter=void 0===n&&void 0!==e.signer&&void 0!==a?{signer:e.signer,walletAddress:a}:void 0;const d=new lh({bundleBaseUrl:this.config.bundleBaseUrl,launchpadBaseUrl:this.config.baseUrl,signer:c,walletAddress:l,...void 0!==e.httpRequestor&&{httpRequestor:e.httpRequestor},bundleSocketFactory:e.bundleSocketFactory}),u=Sh({getTradeQuote:e=>this.tradingQuotesService.getTradeQuote(e),findTokenNameByVault:(e,t)=>this.findTokenNameByVault(e,t),defaultFeeSlippageFactor:()=>this.maxAcceptableReverseBondingCurveFeeSlippageFactor});this.sellFeeCeiling=u,this.launchpad=new Lh({transport:d,walletAddress:l,sellFeeCeiling:u}),this.logger=new pn({debug:this.config.debug??!1,context:"LaunchpadSDK"}),this.validateConfiguration(),this.slippageToleranceFactor=void 0===e.slippageToleranceFactor?Qh.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR:this.parseSlippageToleranceFactor(e.slippageToleranceFactor),this.maxAcceptableReverseBondingCurveFeeSlippageFactor=void 0===e.maxAcceptableReverseBondingCurveFeeSlippageFactor?Qh.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR:this.parseFeeSlippageFactor(e.maxAcceptableReverseBondingCurveFeeSlippageFactor),this.calculateAmountMode=e.calculateAmountMode??Qh.DEFAULT_CALCULATE_AMOUNT_MODE,this.galaChainAddressOverride=e.galaChainAddress,this.signerWalletAddress=e.walletAddress??(void 0===n?a:void 0),this.auth=new Ao({wallet:n,walletProvider:t,messagePrefix:"Create a GalaChain Wallet"});const h=e.session;if(void 0!==h){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)}(h))throw Vt("session must provide accessToken() and onUnauthorized()","session");if(void 0!==e.accessToken&&""!==e.accessToken)throw Vt("Pass either session or accessToken, not both: the session owns the token.","accessToken")}if(this.jwtAuth=void 0===h?new go:new mo,void 0!==e.accessToken&&""!==e.accessToken){const t=e.accessTokenExpiresIn??86400;this.jwtAuth.setToken(e.accessToken,t)}this.http=new Bh(this.auth,this.config,{signRequests:!0,session:h}),this.sessionAuth=new Eo(this.http,this.auth,this.jwtAuth,e.debug??!1,h);const g={signRequests:!1};this.galaChainHttp=new Bh(this.auth,{...this.config,baseUrl:this.config.gatewayBaseUrl},g),this.bundleHttp=new Bh(this.auth,{...this.config,baseUrl:this.config.bundleBaseUrl},g),this.dexApiHttp=new Bh(this.auth,{...this.config,baseUrl:this.config.dexApiBaseUrl},g),this.dexBackendHttp=new Bh(this.auth,{...this.config,baseUrl:this.config.dexBackendBaseUrl},g),this.galaChainPublicAxios=Fh(this.config.gatewayBaseUrl,this.config.timeout??3e4),this.cache=new ir(e.debug??!1),this.launchpadService=new jl(this.http,this.jwtAuth),this.tokenResolverService=new eh(this.launchpadService.poolService),this.launchpadAPI=new ao(this.http,this.logger,this.bundleHttp,this.calculateAmountMode,this.launchpad),this.galaChainService=new ul(this.galaChainHttp,n,this.tokenResolverService,e.debug??!1,this.galaChainPublicAxios,this.tokenWriter),this.priceService=new gc(this.dexBackendHttp,this.cache,e=>this.galaChainService.fetchTokenDetails(e),e.debug??!1),this.bundleService=this.createBundleService(),this.websocketService=new ih({url:this.config.webSocketUrl},this.config.debug),this.nftCollectionService=new Cd(this.galaChainHttp),this.tradingQuotesService=new th(this.http,e.debug??!1)}createOverrideSdk(e){if(!xn(e))throw Vt("Invalid privateKey: must be a non-empty string","privateKey");if(!e.match(/^0x[a-fA-F0-9]{64}$/))throw Vt('Invalid privateKey format: must be "0x" followed by 64 hexadecimal characters',"privateKey");const t=new s(e),n={...this.config,wallet:t};return new Qh(n)}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 Kt("wallet","Wallet");return this.wallet}assertTokenWriter(){if(void 0===this.wallet&&void 0===this.tokenWriter)throw Kt("wallet","Wallet")}setWallet(e){if(null==e||"object"!=typeof e||!("address"in e))throw new wt("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 ja(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 ul(this.galaChainHttp,this.wallet,this.tokenResolverService,this.config.debug??!1,this.galaChainPublicAxios)}setWalletProvider(e){this.auth.setWalletProvider(e),this.wallet=e?Vh(e):void 0,this.onWalletChanged()}getWallet(){return this.wallet}get events(){return this.getEventsBatcherService()}getWalletProvider(){return this.auth.getWalletProvider()}hasWallet(){return this.auth.hasWallet()}getConfig(){const{wallet:e,walletProvider:t,signer:n,httpRequestor:r,streamAdminApiKey:s,userApiKey:i,accessToken:o,headers:a,...c}=this.config;return{...c,...void 0!==s&&{streamAdminApiKey:"[REDACTED]"},...void 0!==i&&{userApiKey:"[REDACTED]"},...void 0!==o&&{accessToken:"[REDACTED]"},...void 0!==a&&{headers:Object.fromEntries(Object.keys(a).map(e=>[e,"[REDACTED]"]))},environment:this.environment,slippageToleranceFactor:this.slippageToleranceFactor,maxAcceptableReverseBondingCurveFeeSlippageFactor:this.maxAcceptableReverseBondingCurveFeeSlippageFactor,calculateAmountMode:this.calculateAmountMode,gasFee:un.GAS_FEE}}getVersion(){return No}getUrlByTokenName(e){const t=this.config.launchpadFrontendUrl;if(void 0===t||""===t)throw Vt("launchpadFrontendUrl not configured in SDK","launchpadFrontendUrl");return`${t.replace(/\/$/,"")}/buy-sell/${e}`}async fetchPools(e){const t=await this.launchpadService.fetchPools(e??{});return await this.warmCacheFromPools(t.items),t}async fetchAllPools(e){const t=await this.launchpadService.fetchAllPools(e);return await this.warmCacheFromPools(t.items),t}async fetchTokenDistribution(e){return this.launchpadService.fetchTokenDistribution(e)}async getTopHolders(e,t=10){const n=await this.fetchTokenDistribution(e),r=Math.min(t,100);return n.holders.slice(0,r).map((e,t)=>({...e,rank:t+1}))}async getHolderCount(e){const t=await this.fetchTokenDistribution(e);return{count:t.totalHolders,totalBalance:t.totalSupply}}async getHolderRank(e,t){const n=await this.fetchTokenDistribution(e),r=n.holders.findIndex(e=>e.address.toLowerCase()===t.toLowerCase());if(-1===r)return null;const s=n.holders[r];return void 0===s?null:{rank:r+1,balance:s.balance,holderCount:n.totalHolders}}async getHoldersByBalance(e,t){const n=await this.fetchTokenDistribution(e),r=t?.minBalance??0,s=t?.maxBalance??1/0,i=Math.min(t?.limit??100,1e3),o=new Map;return n.holders.forEach((e,t)=>{o.set(e.address,t+1)}),n.holders.filter(e=>{const t=parseFloat(e.balance);return t>=r&&t<=s}).map(e=>({...e,rank:o.get(e.address)??0})).slice(0,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 wt("fetchTokenPrice prices a launchpad token by tokenName; a token by class key is priced by gswap-sdk (gSwap.market.getPrice)","tokenId",Nt.INVALID_PARAMETERS);const n=t.tokenName;return this.priceService.fetchLaunchpadTokenSpotPrice("string"==typeof n?n:"",e=>this.launchpadAPI.calculateBuyAmount(e),e=>this.fetchPoolDetails(e))}async fetchTokenDetails(e){return this.galaChainService.fetchTokenDetails(e)}async fetchLaunchTokenFee(){return this.tradingQuotesService.fetchLaunchpadFee()}async fetchTokenClassesWithSupply(e){return this.galaChainService.fetchTokenClassesWithSupply(e)}async fetchPoolDetails(e){const t=await this.launchpadAPI.fetchPoolDetails(e),n=await this.launchpadAPI.fetchPoolDetailsForCalculation(e);return t.currentSupply=n.currentSupply,t.reverseBondingCurveMaxFeeFactor=n.reverseBondingCurveMaxFeeFactor,t.reverseBondingCurveMinFeeFactor=n.reverseBondingCurveMinFeeFactor,t.reverseBondingCurveNetFeeFactor=n.reverseBondingCurveNetFeeFactor,t.tokenName=e,t}async fetchPoolDetailsForCalculation(e){return this.launchpadAPI.fetchPoolDetailsForCalculation(e)}async isTokenGraduated(e){return(await this.fetchPoolDetails(e)).isGraduated}async fetchVolumeData(e){return this.launchpadService.fetchVolumeData(e)}async fetchTrades(e){return this.launchpadService.fetchTrades(e)}async fetchGalaBalance(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return xr}),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(Vt("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,Vt(`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")})),this.coreBridgeLoad)}async coreBridge(){const e=this.walletGeneration,t=await this.loadCoreBridge();if(e!==this.walletGeneration)throw Vt("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 Ia(t.privateKey)}})}return this._wrapService}getStreamingService(){return this._streamingService??(this._streamingService=new vu(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._streamingService}getStreamChatService(){return this._streamChatService??(this._streamChatService=new Jd(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._streamChatService}getBanService(){return this._banService??(this._banService=new ha(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._banService}getTokenBanService(){return this._tokenBanService??(this._tokenBanService=new Zu(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._tokenBanService}getAIModerationService(){return this._aiModerationService??(this._aiModerationService=new Ko(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._aiModerationService}getWeeklyChallengeService(){return this._weeklyChallengeService??(this._weeklyChallengeService=new oh(this.http,this.config.debug??!1)),this._weeklyChallengeService}getOEmbedService(){return this._oembedService??(this._oembedService=new Od(this.http,this.config.debug??!1)),this._oembedService}getPlatformStatsService(){return this._platformStatsService??(this._platformStatsService=new Qd(this.http,this.config.debug??!1)),this._platformStatsService}getHealthService(){return this._healthService??(this._healthService=new hl(this.http,this.config.debug??!1)),this._healthService}getEventsQueryService(){return this._eventsQueryService??(this._eventsQueryService=new Nc(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._eventsQueryService}getNotificationService(){return this._notificationService??(this._notificationService=new Rd(this.http,this.config.debug??!1,this.jwtAuth)),this._notificationService}getClientConfigService(){return this._clientConfigService??(this._clientConfigService=new qa(this.http,this.config.debug??!1)),this._clientConfigService}getApiKeyService(){return this._apiKeyService??(this._apiKeyService=new ta(this.http,this.jwtAuth,this.config.debug??!1)),this._apiKeyService}getModeratorService(){return this._moderatorService??(this._moderatorService=new Sd(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._moderatorService}getFlagService(){return this._flagService??(this._flagService=new ac(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._flagService}getOverseerService(){return this._overseerService??(this._overseerService=new qd(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._overseerService}getWebSocketAdminService(){return this._websocketAdminService??(this._websocketAdminService=new nh(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._websocketAdminService}getContentReactionService(){return this._contentReactionService??(this._contentReactionService=new dc(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 xr}),n=t(e);if(void 0===n)throw new wt(`Invalid address format: "${e}". Expected formats: eth|0x..., 0x..., or client|...`);return n}getMessagesService(){return this._messagesService??(this._messagesService=new id(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._messagesService}getRestrictedNamesService(){return this._restrictedNamesService??(this._restrictedNamesService=new Yd(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.userApiKey)),this._restrictedNamesService}getPlatformConfigService(){return this._platformConfigService??(this._platformConfigService=new Xd(this.http,this.jwtAuth,this.config.debug??!1)),this._platformConfigService}getEventsBatcherService(){return this._eventsBatcherService??(this._eventsBatcherService=new pc(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 Vu({url:this.config.streamWebSocketUrl,tokenProvider:()=>this.streamSocketToken(),...void 0!==this.config.streamReconnectAttempts&&{reconnectAttempts:this.config.streamReconnectAttempts},...void 0!==this.config.streamReconnectDelay&&{reconnectDelay:this.config.streamReconnectDelay},...void 0!==this.config.streamReconnectDelayMax&&{reconnectDelayMax:this.config.streamReconnectDelayMax}},this.config.debug??!1)}return this._streamWebSocketService}async streamSocketToken(){const e=this.config.session;return void 0!==e?e.accessToken():this.ensureValidToken()}get realtime(){return this.getStreamWebSocketService()}async fetchEthereumWalletTokenBalance(e,t){return this.getBridgeService(await this.coreBridge()).fetchEthereumWalletTokenBalance(e,t)}async fetchEthereumWalletNativeBalance(e){return this.getBridgeService(await this.coreBridge()).fetchEthereumWalletNativeBalance(e)}async fetchSolanaWalletTokenBalance(e,t){return this.getBridgeService(await this.coreBridge()).fetchSolanaWalletTokenBalance(e,t)}async fetchSolanaWalletNativeBalance(e){return this.getBridgeService(await this.coreBridge()).fetchSolanaWalletNativeBalance(e)}async requestSolanaDevnetAirdrop(e,t){return this.getBridgeService(await this.coreBridge()).requestSolanaDevnetAirdrop(e,t)}async getSolanaTransactionStatus(e){return this.getBridgeService(await this.coreBridge()).getSolanaTransactionStatus(e)}async getEthereumTransactionStatus(e){return this.getBridgeService(await this.coreBridge()).getEthereumTransactionStatus(e)}async fetchEthereumWalletAllBalances(e){return this.getBridgeService(await this.coreBridge()).fetchEthereumWalletAllBalances(e)}async fetchSolanaWalletAllBalances(e){return this.getBridgeService(await this.coreBridge()).fetchSolanaWalletAllBalances(e)}async fetchBridgeableTokensByNetwork(e){return this.getBridgeableTokenService(await this.coreBridge()).fetchBridgeableTokensByNetwork(e)}async fetchAllBridgeableTokensByNetwork(e){return this.getBridgeableTokenService(await this.coreBridge()).fetchAllBridgeableTokensByNetwork(e)}async fetchAllTokensBridgeableToEthereum(){return this.getBridgeableTokenService(await this.coreBridge()).fetchAllTokensBridgeableToEthereum()}async fetchAllTokensBridgeableToSolana(){return this.getBridgeableTokenService(await this.coreBridge()).fetchAllTokensBridgeableToSolana()}async isTokenBridgeableToNetwork(e){return this.getBridgeableTokenService(await this.coreBridge()).isTokenBridgeableToNetwork(e)}async isTokenBridgeableToEthereum(e){return this.getBridgeableTokenService(await this.coreBridge()).isTokenBridgeableToEthereum(e)}async isTokenBridgeableToSolana(e){return this.getBridgeableTokenService(await this.coreBridge()).isTokenBridgeableToSolana(e)}async fetchWrappableTokens(e={}){return this.getWrappableTokenService(await this.coreBridge()).fetchWrappableTokens(e)}async fetchAllWrappableTokens(){return this.getWrappableTokenService(await this.coreBridge()).fetchAllWrappableTokens()}async getWrappableToken(e){return this.getWrappableTokenService(await this.coreBridge()).getWrappableToken(e)}async getWrapCounterpart(e){return this.getWrappableTokenService(await this.coreBridge()).getWrapCounterpart(e)}async isTokenWrappable(e){return this.getWrappableTokenService(await this.coreBridge()).isTokenWrappable(e)}async wrapToken(e){return this.getWrapService(await this.coreBridge()).wrapToken(e)}async unwrapToken(e){return this.getWrapService(await this.coreBridge()).unwrapToken(e)}async estimateWrapFee(e,t){return this.getWrapService(await this.coreBridge()).estimateWrapFee(e,t)}async estimateUnwrapFee(e,t){return this.getWrapService(await this.coreBridge()).estimateUnwrapFee(e,t)}async login(){return this.sessionAuth.login()}async loginWithSignature(e){return this.sessionAuth.loginWithSignature(e)}async loginWithDevBypass(e){return this.sessionAuth.loginWithDevBypass(e)}async refreshToken(){return this.sessionAuth.refresh()}async logout(e){return this.sessionAuth.logout(e)}isAuthenticated(){return this.sessionAuth.isAuthenticated()}shouldRefreshToken(e){return this.sessionAuth.shouldRefresh(e)}async getSession(){return this.sessionAuth.getSession()}getAccessToken(){return this.sessionAuth.getAccessToken()}async ensureValidToken(e){return this.sessionAuth.ensureValidToken(e)}async startStream(e){return this.getStreamingService().startStream(e)}async stopStream(e){return this.getStreamingService().stopStream(e)}async disableStream(e){return this.getStreamingService().disableStream(e)}async enableStream(e){return this.getStreamingService().enableStream(e)}async resetStreamKey(e){return this.getStreamingService().resetStreamKey(e)}async getStreamCredentials(e){return this.getStreamingService().getStreamCredentials(e)}async getStreamRecordings(e){return this.getStreamingService().getRecordings(e)}async getRecordingDownload(e,t){return this.getStreamingService().getRecordingDownload(e,t)}async deleteRecording(e,t){return this.getStreamingService().deleteRecording(e,t)}async getSimulcastTargets(e){return this.getStreamingService().getSimulcastTargets(e)}async addSimulcastTarget(e){return this.getStreamingService().addSimulcastTarget(e)}async removeSimulcastTarget(e,t){return this.getStreamingService().removeSimulcastTarget(e,t)}async getGlobalStreamingStatus(){return this.getStreamingService().getGlobalStreamingStatus()}async setNextLiveStreamCountdown(e,t){return this.getStreamingService().setNextLiveStreamCountdown(e,t)}async setGlobalStreamingEnabled(e){const t=this.getStreamingService();return e?t.enableGlobalStreaming():t.disableGlobalStreaming()}async getStreamRole(e){return this.getStreamingService().getStreamRole(e)}async getAvailableRoles(){return this.getStreamingService().getAvailableRoles()}async getTokenAccess(e){return this.getStreamingService().getTokenAccess(e)}async getChatStatus(e){return this.getStreamChatService().getChatStatus(e)}async disableChat(e){return this.getStreamChatService().disableChat(e)}async enableChat(e){return this.getStreamChatService().enableChat(e)}async getPinnedChatMessage(e){const t=this.getMessagesService();return{tokenName:e,pinnedMessage:(await t.getPinnedMessage(e)).message}}async pinChatMessage(e,t){const n=this.getMessagesService();await n.pinMessage(t);return{tokenName:e,pinnedMessage:(await n.getPinnedMessage(e)).message}}async unpinChatMessage(e){const t=this.getMessagesService(),n=await t.getPinnedMessage(e);return n.message?(await t.unpinMessage(n.message.messageId),{tokenName:e,unpinned:!0,unpinnedMessageId:n.message.messageId}):{tokenName:e,unpinned:!1}}async setSlowMode(e,t){return this.getStreamChatService().setSlowMode(e,t)}async createBan(e){return this.getBanService().createBan(e)}async removeBan(e){return this.getBanService().removeBan(e)}async listBans(e){return this.getBanService().listBans(e)}async getBanStatus(e){return this.getBanService().getBanStatus(e)}async getActiveUsers(e){return this.getBanService().getActiveUsers(e)}async createGlobalBan(e){return this.getBanService().createGlobalBan(e)}async removeGlobalBan(e){return this.getBanService().removeGlobalBan(e)}async listGlobalBans(e){return this.getBanService().listGlobalBans(e)}async getGlobalBan(e){return this.getBanService().getGlobalBan(e)}async createApiKey(e){return this.getApiKeyService().create(e)}async listApiKeys(e={}){return this.getApiKeyService().findAll(e)}async getApiKey(e){return this.getApiKeyService().findOne(e)}async updateApiKey(e,t){return this.getApiKeyService().update(e,t)}async revokeApiKey(e){return this.getApiKeyService().revoke(e)}getApiKeyRoles(){return this.getApiKeyService().getRoles()}async createModeratorInvite(e){return this.getModeratorService().createInvite(e)}async claimModeratorInvite(e){return this.getModeratorService().claimInvite(e)}async getModeratedTokens(e){return this.getModeratorService().getModeratedTokens(e)}async listModeratorInvites(e){return this.getModeratorService().listInvites(e)}async getActiveModerators(e){return(await this.listModeratorInvites({tokenName:e,status:"CLAIMED"})).items.filter(e=>null!==e.claimedBy).map(e=>({address:e.claimedBy,role:e.role,joinedAt:e.claimedAt,inviteId:e.id}))}async revokeModeratorInvite(e){return this.getModeratorService().revokeInvite(e)}async updateModeratorInviteRole(e){return this.getModeratorService().updateInviteRole(e)}async updateModeratorInvite(e){return this.getModeratorService().updateInvite(e)}async getModeratorInviteByCode(e){return this.getModeratorService().getInviteByCode(e)}async createFlag(e){return this.getFlagService().createFlag(e)}async listFlags(e){return this.getFlagService().listFlags(e)}async listGlobalFlags(e={}){return this.getFlagService().listGlobalFlags(e)}async dismissFlag(e){return this.getFlagService().dismissFlag(e)}async actionFlag(e){return this.getFlagService().actionFlag(e)}async createOverseerInvite(e={}){return this.getOverseerService().createInvite(e)}async listOverseerInvites(e={}){return this.getOverseerService().listInvites(e)}async getOverseerInviteByCode(e){return this.getOverseerService().getInviteByCode(e)}async claimOverseerInvite(e){return this.getOverseerService().claimInvite(e)}async revokeOverseerInvite(e){return this.getOverseerService().revokeInvite(e)}async listOverseers(e={}){return this.getOverseerService().listOverseers(e)}async createOverseerDirect(e){return this.getOverseerService().createOverseerDirect(e)}async revokeOverseer(e){return this.getOverseerService().revokeOverseer(e)}async getMyOverseerStatus(){return this.getOverseerService().getMyStatus()}async getOverseerSummary(){return this.getOverseerService().getSummary()}async getBanStats(){return this.getOverseerService().getBanStats()}async getTokenBanStats(){return this.getOverseerService().getTokenBanStats()}async getInviteStats(){return this.getOverseerService().getInviteStats()}async getFlagStats(){return this.getOverseerService().getFlagStats()}async getUserStats(){return this.getOverseerService().getUserStats()}async listOverseerUsers(e){return this.getOverseerService().listOverseerUsers(e)}async getOverseerUserSummary(e){return this.getOverseerService().getOverseerUserSummary(e)}async flushCacheByAddress(e){return this.getOverseerService().flushCacheByAddress(e)}async flushCacheByToken(e){return this.getOverseerService().flushCacheByToken(e)}async flushAllCache(e){return this.getOverseerService().flushAllCache(e)}async flushWalletAliasCache(e){return this.getOverseerService().flushWalletAliasCache(e)}async emitWebSocketEvent(e){return this.getWebSocketAdminService().emitEvent(e)}async emitTradeExecuted(e,t){return this.getWebSocketAdminService().emitTradeExecuted(e,t)}async emitBalanceUpdated(e,t,n){return this.getWebSocketAdminService().emitBalanceUpdated(e,t,n)}async emitStreamStatus(e,t){return this.getWebSocketAdminService().emitStreamStatus(e,t)}async emitViewerCount(e,t){return this.getWebSocketAdminService().emitViewerCount(e,t)}async emitStreamCountdown(e,t){return this.getWebSocketAdminService().emitStreamCountdown(e,t)}async emitChatMessage(e,t){return this.getWebSocketAdminService().emitChatMessage(e,t)}async emitChatStatus(e,t){return this.getWebSocketAdminService().emitChatStatus(e,t)}async emitTypingIndicator(e,t){return this.getWebSocketAdminService().emitTypingIndicator(e,t)}async emitTokenBanned(e,t){return this.getWebSocketAdminService().emitTokenBanned(e,t)}async emitTokenUnbanned(e,t){return this.getWebSocketAdminService().emitTokenUnbanned(e,t)}async emitModeratorAdded(e,t){return this.getWebSocketAdminService().emitModeratorAdded(e,t)}async emitModeratorRemoved(e,t){return this.getWebSocketAdminService().emitModeratorRemoved(e,t)}async emitUserProfileUpdated(e,t){return this.getWebSocketAdminService().emitUserProfileUpdated(e,t)}async emitSiteConfigChanged(e){return this.getWebSocketAdminService().emitSiteConfigChanged(e)}async emitFeatureStatus(e){return this.getWebSocketAdminService().emitFeatureStatus(e)}async emitRecordingStatus(e,t){return this.getWebSocketAdminService().emitRecordingStatus(e,t)}async emitRecordingsCountUpdated(e,t){return this.getWebSocketAdminService().emitRecordingsCountUpdated(e,t)}async emitDownloadReady(e,t){return this.getWebSocketAdminService().emitDownloadReady(e,t)}async getConnectedClients(e){return this.getWebSocketAdminService().getConnectedClients(e)}async isUserOnline(e){return this.getWebSocketAdminService().isUserOnline(e)}async getOnlineUsers(e){return this.getWebSocketAdminService().getOnlineUsers(e)}async getTokenViewers(e,t){return this.getWebSocketAdminService().getTokenViewers(e,t)}async getOnlineOverseers(){return this.getWebSocketAdminService().getOnlineOverseers()}async banToken(e){return this.getTokenBanService().banToken(e)}async unbanToken(e){return this.getTokenBanService().unbanToken(e)}async listTokenBans(e={}){return this.getTokenBanService().listTokenBans(e)}async getTokenBan(e){return this.getTokenBanService().getTokenBan(e)}async isTokenBanned(e){return this.getTokenBanService().isTokenBanned(e)}async getAIModerationSettings(){return this.getAIModerationService().getSettings()}async updateAIModerationSettings(e){return this.getAIModerationService().updateSettings(e)}async getAIModeration(e){return this.getAIModerationService().getModeration(e)}async triggerAIModeration(e){return this.getAIModerationService().triggerModeration(e)}async getAIModerationStatus(){return this.getAIModerationService().getStatus()}async getWeeklyChallengeLeaderboard(e={}){return this.getWeeklyChallengeService().getLeaderboard(e)}async getTokenWeeklyHistory(e){return this.getWeeklyChallengeService().getTokenHistory(e)}async getHomeOEmbed(e={}){return this.getOEmbedService().getHomeOEmbedJson(e)}async getPoolOEmbed(e){return this.getOEmbedService().getPoolOEmbedJson(e)}async getProfileOEmbed(e){return this.getOEmbedService().getProfileOEmbedJson(e)}async getPlatformStats(){return this.getPlatformStatsService().getStats()}async getHealth(){return this.getHealthService().getHealth()}async getEventStats(){return this.getEventsQueryService().getEventStats()}async queryEvents(e={}){return this.getEventsQueryService().queryEvents(e)}async registerPushToken(e){return this.getNotificationService().registerPushToken(e)}async unregisterPushToken(e){return this.getNotificationService().unregisterPushToken(e)}async fetchNotificationPreferences(){return this.getNotificationService().getPreferences()}async updateNotificationPreferences(e){return this.getNotificationService().updatePreferences(e)}async fetchClientFlags(){return this.getClientConfigService().getClientFlags()}async addContentReaction(e){return this.getContentReactionService().addContentReaction(e)}async removeContentReaction(e){return this.getContentReactionService().removeContentReaction(e)}async addReactionToChatMessage(e){return this.getContentReactionService().addReactionToChatMessage(e)}async removeReactionFromChatMessage(e){return this.getContentReactionService().removeReactionFromChatMessage(e)}async addReactionToComment(e){return this.getContentReactionService().addReactionToComment(e)}async removeReactionFromComment(e){return this.getContentReactionService().removeReactionFromComment(e)}async getComments(e){const t=this.buildMessageFetchOptions(e,"COMMENT"),n=await this.fetchMessages(t);return{messages:n.messages,pageInfo:n.pageInfo}}async createComment(e){return{comment:(await this.createMessage({type:"COMMENT",tokenName:e.tokenName,content:e.content})).message}}async updateComment(e,t){return{comment:(await this.updateMessage(e,{content:t.content,type:"COMMENT"})).message}}async deleteComment(e){return{success:(await this.deleteMessage(e)).success}}async getChatMessages(e){const t=this.buildMessageFetchOptions(e,"CHAT_MESSAGE"),n=await this.fetchMessages(t);return{messages:n.messages,pageInfo:n.pageInfo}}async sendChatMessage(e){return{message:(await this.createMessage({type:"CHAT_MESSAGE",tokenName:e.tokenName,content:e.content})).message}}async updateChatMessage(e,t){return{message:(await this.updateMessage(e,{content:t.content,type:"CHAT_MESSAGE"})).message}}async deleteChatMessage(e){await this.deleteMessage(e)}async fetchMessages(e){return this.getMessagesService().fetchMessages(e)}async createMessage(e){return this.getMessagesService().createMessage(e)}async updateMessage(e,t){return this.getMessagesService().updateMessage(e,t)}async deleteMessage(e){return this.getMessagesService().deleteMessage(e)}async getPinnedMessage(e){return this.getMessagesService().getPinnedMessage(e)}async pinMessage(e){return this.getMessagesService().pinMessage(e)}async unpinMessage(e){return this.getMessagesService().unpinMessage(e)}async getMessageStats(){return this.getMessagesService().getMessageStats()}async getPlatformConfig(){return this.getPlatformConfigService().getPlatformConfig()}async updatePlatformConfig(e){return this.getPlatformConfigService().updatePlatformConfig(e)}async getRestrictedNames(){return this.getRestrictedNamesService().getRestrictedNames()}async updateRestrictedNames(e){return this.getRestrictedNamesService().updateRestrictedNames(e)}async updateTokenConfig(e,t){return this.launchpadService.poolService.updateTokenConfig(e,t)}async getTokenConfig(e){return this.launchpadService.poolService.getTokenConfig(e)}async getTrades(e){return this.launchpadService.getTrades(e)}async getRecentTrades(e,t=50){return this.getTrades({...void 0!==e&&{tokenName:e},pageSize:Math.min(t,500)})}async getPoolRealtimeState(e){const[t,n,r,s]=await Promise.allSettled([this.getHolderCount(e),this.getTokenConfig(e),this.getRecentTrades(e,10),this.fetchTokenPrice({tokenName:e})]);return{tokenName:e,holderCount:"fulfilled"===t.status?t.value:null,..."rejected"===t.status&&{holderCountError:String(t.reason)},chatConfig:"fulfilled"===n.status?n.value:null,..."rejected"===n.status&&{chatConfigError:String(n.reason)},recentTrades:"fulfilled"===r.status?r.value:null,..."rejected"===r.status&&{recentTradesError:String(r.reason)},price:"fulfilled"===s.status?s.value:null,..."rejected"===s.status&&{priceError:String(s.reason)}}}async fetchLaunchpadFee(){return this.tradingQuotesService.fetchLaunchpadFee()}async fetchSaleDetails(e){return this.tradingQuotesService.fetchSaleDetails(e)}async getTradeQuote(e){return this.tradingQuotesService.getTradeQuote(e)}async getPremintQuote(e){return this.tradingQuotesService.getPremintQuote(e)}async connectStreamWebSocket(e){const t=this.getStreamWebSocketService();await t.connect(),e&&t.addCallbacks(e)}async authenticateStreamWebSocket(e){return this.getStreamWebSocketService().authenticate(e)}deauthenticateStreamWebSocket(){this._streamWebSocketService?.deauthenticate()}async subscribeToStream(e,t){return this.getStreamWebSocketService().subscribeToStream(e,t)}unsubscribeFromStream(e){this.getStreamWebSocketService().unsubscribeFromStream(e)}sendStreamChatViaWebSocket(e,t){this.getStreamWebSocketService().sendChatMessage(e,t)}sendStreamReaction(e,t,n=0){this.getStreamWebSocketService().sendReaction(e,t,n)}sendTypingStart(e){return this.getStreamWebSocketService().sendTypingStart(e)}sendTypingStop(e){return this.getStreamWebSocketService().sendTypingStop(e)}disconnectStreamWebSocket(){this._streamWebSocketService&&this._streamWebSocketService.disconnect()}isStreamWebSocketConnected(){return!!this._streamWebSocketService&&this._streamWebSocketService.isConnected()}onStreamStatusChanged(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_STATUS",e)}onUserBanned(e){return this.getStreamWebSocketService().subscribeEvent("USER_BANNED",e)}onUserUnbanned(e){return this.getStreamWebSocketService().subscribeEvent("USER_UNBANNED",e)}onBanEnforcement(e){return this.getStreamWebSocketService().subscribeEvent("BAN_ENFORCEMENT",e)}watchBanEnforcement(e,t={}){const n=(e,n,r,s)=>(void 0===t.actionType||t.actionType===e)&&((void 0===t.userAddress||t.userAddress===n)&&((void 0===t.tokenName||t.tokenName===r)&&!!(void 0===t.reason||null!==s&&s.includes(t.reason)))),r=this.onUserBanned(t=>{const r=t.userAddress??null,s=t.reason??null;n("BANNED",r,t.tokenName,s)&&e({actionType:"BANNED",userAddress:r,tokenName:t.tokenName,reason:s,...void 0!==t.expiresAt&&{expiresAt:t.expiresAt}})}),s=this.onUserUnbanned(t=>{const r=t.userAddress??null;n("UNBANNED",r,t.tokenName,null)&&e({actionType:"UNBANNED",userAddress:r,tokenName:t.tokenName,reason:null})}),i=this.onBanEnforcement(t=>{const r=t.reason??null;n("ENFORCEMENT",null,t.tokenName,r)&&e({actionType:"ENFORCEMENT",userAddress:null,tokenName:t.tokenName,reason:r,...void 0!==t.expiresAt&&{expiresAt:t.expiresAt}})});return()=>{r(),s(),i()}}watchTokenRoomEvent(e,t,n,r){const s=r.tokenName;if(void 0===s||""===s)throw new Error(`${e} requires a tokenName filter - these are per-token stream events with no way to watch every token at once.`);return t(s,n)}watchCommentCreated(e,t={}){return this.watchTokenRoomEvent("watchCommentCreated",(e,t)=>this.getStreamWebSocketService().subscribeCommentCreated(e,t),n=>{void 0!==t.authorAddress&&t.authorAddress!==n.userAddress||void 0!==t.minLength&&n.content.length<t.minLength||e(n)},t)}watchHolderCountUpdated(e,t={}){return this.watchTokenRoomEvent("watchHolderCountUpdated",(e,t)=>this.getStreamWebSocketService().subscribeHolderCountUpdated(e,t),n=>{void 0!==t.minThreshold&&Math.abs(n.change??0)<t.minThreshold||e(n)},t)}watchModeratorAdded(e,t={}){return this.watchTokenRoomEvent("watchModeratorAdded",(e,t)=>this.getStreamWebSocketService().subscribeModeratorAdded(e,t),e,t)}watchPoolMetadataUpdated(e,t={}){return this.watchTokenRoomEvent("watchPoolMetadataUpdated",(e,t)=>this.getStreamWebSocketService().subscribePoolMetadataUpdated(e,t),e,t)}watchTradeExecuted(e,t={}){return this.watchTokenRoomEvent("watchTradeExecuted",(e,t)=>this.getStreamWebSocketService().subscribeTradeExecuted(e,t),n=>{void 0!==t.tradeType&&t.tradeType!==n.tradeType||void 0!==t.userAddress&&t.userAddress!==n.userAddress||void 0!==t.minAmount&&Number(n.inputAmount)<t.minAmount||e(n)},t)}watchTokenBanned(e,t={}){return this.watchTokenRoomEvent("watchTokenBanned",(e,t)=>this.getStreamWebSocketService().subscribeTokenBanned(e,t),e,t)}watchModeratorChanged(e,t={}){const n=(e,n)=>(void 0===t.eventType||t.eventType===e)&&(void 0===t.moderatorAddress||t.moderatorAddress===n),r=this.watchModeratorAdded(t=>{n("ADDED",t.userAddress)&&e({actionType:"ADDED",tokenName:t.tokenName,moderatorAddress:t.userAddress,role:t.role})},t),s=this.watchTokenRoomEvent("watchModeratorRemoved",(e,t)=>this.getStreamWebSocketService().subscribeModeratorRemoved(e,t),t=>{n("REMOVED",t.userAddress)&&e({actionType:"REMOVED",tokenName:t.tokenName,moderatorAddress:t.userAddress})},t),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()=>{r(),s(),i()}}watchPoolUpdated(e,t={}){const n=e=>void 0===t.updateType||t.updateType===e,r=this.watchPoolMetadataUpdated(t=>{n("METADATA")&&e({updateType:"METADATA",tokenName:t.tokenName,details:t})},t),s=this.watchTokenRoomEvent("watchPoolSocialLinksUpdated",(e,t)=>this.getStreamWebSocketService().subscribePoolSocialLinksUpdated(e,t),t=>{n("SOCIAL_LINKS")&&e({updateType:"SOCIAL_LINKS",tokenName:t.tokenName,details:t})},t),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()=>{r(),s(),i()}}watchTokenBanChanged(e,t={}){const n=e=>void 0===t.banStatus||t.banStatus===e,r=this.watchTokenBanned(t=>{n("BANNED")&&e({banStatus:"BANNED",tokenName:t.tokenName,reason:t.reason})},t),s=this.watchTokenRoomEvent("watchTokenUnbanned",(e,t)=>this.getStreamWebSocketService().subscribeTokenUnbanned(e,t),t=>{n("UNBANNED")&&e({banStatus:"UNBANNED",tokenName:t.tokenName})},t);return()=>{r(),s()}}onContentFlagged(e){return this.getStreamWebSocketService().subscribeEvent("CONTENT_FLAGGED",e)}onFlagResolved(e){return this.getStreamWebSocketService().subscribeEvent("FLAG_RESOLVED",e)}onStreamChatMessage(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_CHAT_MESSAGE",e)}onStreamChatUpdated(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_CHAT_UPDATED",e)}onStreamChatDeleted(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_CHAT_DELETED",e)}onStreamChatPinned(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_CHAT_PINNED",e)}onStreamChatUnpinned(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_CHAT_UNPINNED",e)}onChatStatusChanged(e){return this.getStreamWebSocketService().subscribeEvent("CHAT_STATUS_CHANGED",e)}onViewerCountChanged(e){return this.getStreamWebSocketService().subscribeEvent("VIEWER_COUNT",e)}onRecordingStatusChanged(e){return this.getStreamWebSocketService().subscribeEvent("RECORDING_STATUS",e)}onSimulcastStatusChanged(e){return this.getStreamWebSocketService().subscribeEvent("SIMULCAST_STATUS",e)}onDownloadReady(e){return this.getStreamWebSocketService().subscribeEvent("DOWNLOAD_READY",e)}onRecordingsCountUpdated(e){return this.getStreamWebSocketService().subscribeEvent("RECORDINGS_COUNT_UPDATED",e)}onUserTyping(e){return this.getStreamWebSocketService().subscribeEvent("USER_TYPING",e)}onStreamReaction(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_REACTION",e)}onContentReactionAdded(e){return this.getStreamWebSocketService().subscribeEvent("CONTENT_REACTION_ADDED",e)}onContentReactionRemoved(e){return this.getStreamWebSocketService().subscribeEvent("CONTENT_REACTION_REMOVED",e)}onStreamCountdownUpdated(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_COUNTDOWN_UPDATED",e)}onStreamLanguageUpdated(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_LANGUAGE_UPDATED",e)}onStreamControlStatusChanged(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_CONTROL_STATUS_CHANGED",e)}onConnection(e){return this.getStreamWebSocketService().subscribeEvent("connection",e)}onAuthenticated(e){return this.getStreamWebSocketService().subscribeEvent("authenticated",e)}onTokenSubscribed(e){return this.getStreamWebSocketService().subscribeEvent("token_subscribed",e)}onTokenUnsubscribed(e){return this.getStreamWebSocketService().subscribeEvent("token_unsubscribed",e)}onRoomSubscribed(e){return this.getStreamWebSocketService().subscribeEvent("room_subscribed",e)}onRoomLeft(e){return this.getStreamWebSocketService().subscribeEvent("room_left",e)}onEngagementStatsUpdated(e){return this.getStreamWebSocketService().subscribeEvent("ENGAGEMENT_STATS_UPDATED",e)}async estimateBridgeFee(e){return this.getBridgeService(await this.coreBridge()).estimateBridgeFee(e)}async bridgeOut(e){return this.getBridgeService(await this.coreBridge()).bridgeOut(e)}async bridgeIn(e){return this.getBridgeService(await this.coreBridge()).bridgeIn(e)}async getBridgeStatus(e){return this.getBridgeService(await this.coreBridge()).getBridgeStatus(e)}async getSupportedBridgeTokens(){const e=this.getBridgeService(await this.coreBridge()),t=e.getSupportedBridgeTokens();return{tokens:t,totalCount:t.length,supportedChains:e.getSupportedBridgeChains()}}async fetchTokenBalance(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return xr}),n=t(e.address);if(void 0!==e.tokenId&&""!==e.tokenId){const{normalizeToTokenInstanceKey:t}=await Promise.resolve().then(function(){return Ha}),r=t(e.tokenId),{collection:s,category:i,type:o,additionalKey:a}=r;return this.galaChainService.fetchTokenBalance({owner:n,collection:s,category:i,additionalKey:a,type:o},e.withExpired??!1)}if(void 0!==e.tokenName&&""!==e.tokenName){const t=mn(e.tokenName),r=jh[t];if(void 0!==r)return this.galaChainService.fetchTokenBalance({owner:n,collection:r,category:"Unit",additionalKey:"none",type:"none"},e.withExpired??!1)}if(void 0!==e.tokenName&&""!==e.tokenName){const t=(await this.fetchTokensHeld({tokenName:e.tokenName,pageSize:1,...void 0!==n?{address:n}:{}})).tokens[0];if(void 0===t)return null;const r=await this.resolveTokenClassKey(e.tokenName);return{quantity:t.balance,collection:r.collection,category:r.category,tokenId:La(r)}}throw Kt("tokenId or tokenName","Either tokenId or tokenName")}async fetchLockedBalance(e){const t=await this.fetchTokenBalance(e);if(!t)return null;const n="lockedHolds"in t||"lockedQuantity"in t;return{tokenId:t.tokenId,lockedQuantity:n?t.lockedQuantity??"0":"0",lockedHolds:n?t.lockedHolds??[]:[]}}async fetchAvailableBalance(e){const t=await this.fetchTokenBalance(e);if(!t)return null;const n="availableQuantity"in t;return{tokenId:t.tokenId,availableQuantity:n?t.availableQuantity??String(t.quantity):String(t.quantity),totalQuantity:String(t.quantity)}}async calculateBuyAmount(e){return this.launchpadAPI.calculateBuyAmount(e)}async calculateSellAmount(e){return this.launchpadAPI.calculateSellAmount(e)}async calculateBuyAmountLocal(e){return this.launchpadAPI.calculateBuyAmountLocal(e)}async calculateSellAmountLocal(e){return this.launchpadAPI.calculateSellAmountLocal(e)}async calculateBuyAmountExternal(e){return this.launchpadAPI.calculateBuyAmountExternal(e)}async calculateSellAmountExternal(e){return this.launchpadAPI.calculateSellAmountExternal(e)}async calculateBuyAmountForGraduation(e){return this.launchpadAPI.calculateBuyAmountForGraduation(e)}async graduateToken(e){const{tokenName:t,slippageToleranceFactor:n,maxAcceptableReverseBondingCurveFeeSlippageFactor:r,privateKey:s,calculateAmountMode:i,currentSupply:o}=e;let a=t;void 0===i&&void 0===o||(a={tokenName:t,...void 0!==i&&{calculateAmountMode:i},...void 0!==o&&{currentSupply:o}});const c=await this.calculateBuyAmountForGraduation(a),l={tokenName:t,amount:c.remainingTokens,type:"exact",expectedAmount:c.amount,maxAcceptableReverseBondingCurveFee:c.reverseBondingCurveFee,slippageToleranceFactor:this.slippageToleranceFactor};return void 0!==n&&(l.slippageToleranceFactor=n),void 0!==r&&(l.maxAcceptableReverseBondingCurveFeeSlippageFactor=r),void 0!==s&&(l.privateKey=s),await this.buy(l)}async calculateInitialBuyAmount(e){const t={nativeTokenQuantity:e};return this.launchpadAPI.calculateInitialBuyAmount(t)}async buy(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...r}=e;return t.buy(r)}this.validateWallet(),await this.ensureWebSocketConnection();const t=(await this.bundleService.buyToken(e)).data,n=t?.transactionId;if(void 0===n||""===n)throw jt("No transaction ID returned from buy operation");return this.waitForConfirmation(n,t=>Wh(t,n,"buy",e))}async sell(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...r}=e;return t.sell(r)}this.validateWallet(),await this.ensureWebSocketConnection();const t=(await this.bundleService.sellToken(e)).data,n=t?.transactionId;if(void 0===n||""===n)throw jt("No transaction ID returned from sell operation");return this.waitForConfirmation(n,t=>Wh(t,n,"sell",e))}async getBundlerTransactionResult(e){return this.bundleService.getBundlerTransactionResult(e)}async launchToken(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...r}=e;return t.launchToken(r)}this.validateWallet(),await this.ensureWebSocketConnection();const t=await this.launchpadAPI.launchToken(e);return this.waitForConfirmation(t,n=>{Hh(n,t);const r=n.data??{};if(!function(e){if(Gn(e)||"object"!=typeof e)return!1;const t=e;return!(void 0!==t.vaultAddress&&"string"!=typeof t.vaultAddress||void 0!==t.tokenStringKey&&"string"!=typeof t.tokenStringKey||void 0!==t.creatorAddress&&"string"!=typeof t.creatorAddress)}(r))throw new Gh(`Invalid launch data received for transaction ${t}`);const s={transactionId:t,vaultAddress:r.vaultAddress??"",tokenStringKey:r.tokenStringKey??"",tokenName:e.tokenName,tokenSymbol:e.tokenSymbol,creatorAddress:r.creatorAddress??this.getAddress(),timestamp:Date.now(),...void 0!==n.blockHash&&""!==n.blockHash?{blockHash:n.blockHash}:{},...void 0!==n.gasUsed?{gasUsed:n.gasUsed}:{}};return"string"==typeof e.tokenImage&&(s.tokenImage=e.tokenImage),void 0!==e.preBuyQuantity&&(s.preBuyQuantity=e.preBuyQuantity),""!==s.vaultAddress&&this.tokenResolverService.set(e.tokenName,s.vaultAddress),s})}async uploadTokenImage(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...r}=e;return t.uploadTokenImage(r)}return this.launchpadService.uploadImageByTokenName(e)}async checkPoolExists(e,t){return this.launchpadService.checkPoolExists(e,t)}async isTokenNameAvailable(e){return this.launchpadService.isTokenNameAvailable(e)}async isTokenSymbolAvailable(e){return this.launchpadService.isTokenSymbolAvailable(e)}async fetchToken(e){return this.launchpadService.fetchToken(e)}async validateToken(e){return this.launchpadService.validateToken(e)}async fetchTokenStats(e){return this.launchpadService.fetchTokenStats(e)}async fetchProfile(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return xr}),n=t(e)??this.getAddress();return this.launchpadService.fetchProfile(n)}async fetchReferralUrl(){this.validateWallet();const e=this.getAddress();return await this.dexApiHttp.get(R,void 0,{"x-wallet-address":e})}async fetchReferrals(e){const t=await this.resolveReferralAddress(e?.address),n=e?.page??1,r=e?.limit??10,s={pageNumber:n,limit:r,sortBy:e?.sortBy??"joined",sortDir:e?.sortDir??"desc"},i=await this.dexApiHttp.get(O,s,{"x-wallet-address":t});if(!Array.isArray(i))throw new Ct("Unexpected API response: expected array, got "+typeof i);return{referrals:i,page:n,limit:r,hasMore:i.length===r}}async fetchAllReferrals(e){const t=await async function(e,t={}){const{maxPages:n=1e4,logger:r,pageSize:s=20,concurrency:i=1,startPage:o=1}=t,a=[];let c=o;const l=o+n-1;let d=!0,u=0;if(i<=1)for(;d&&c<=l;){r&&r.debug(`Auto-pagination: fetching page ${c} with limit ${s}`);const t=await e(c,s);if(null==t||!Array.isArray(t.items)){r&&r.warn("Auto-pagination: received invalid result structure, stopping");break}if(a.push(...t.items),u=t.total,r&&r.debug(`Auto-pagination: page ${c} returned ${t.items.length} items, hasNext: ${String(t.hasNext)}`),0===t.items.length){r&&r.debug(`Auto-pagination: no items returned on page ${c}, exiting loop`);break}d=t.hasNext,c++}else for(r&&r.debug(`Auto-pagination: using concurrent mode with concurrency=${i}`);d&&c<=l;){const t=[];for(let e=0;e<i&&c+e<=l;e++)t.push(c+e);r&&r.debug(`Auto-pagination: fetching pages ${t.join(", ")} concurrently`);const n=t.map(t=>e(t,s).catch(e=>{const n=e,i=n.statusCode??n.response?.status??n.originalError?.response?.status??n.status??n.launchpadError?.statusCode;if(400===i||404===i)return r&&r.debug(`Auto-pagination: page ${t} returned ${i} (end of pagination)`,{statusCode:i}),{items:[],total:0,totalPages:0,page:t,limit:s,hasNext:!1,hasPrevious:!1};throw e})),o=await Promise.all(n);for(const e of o){if(null==e||!Array.isArray(e.items)){r&&r.warn("Auto-pagination: received invalid result structure in batch, stopping"),d=!1;break}if(0===e.items.length){r&&r.debug("Auto-pagination: empty page in batch, reached end of results"),d=!1;break}if(a.push(...e.items),u=e.total,!e.hasNext){d=!1;break}}c+=t.length,r&&r.debug(`Auto-pagination: batch complete, total items so far: ${a.length}`)}return c>l&&r&&r.warn(`Auto-pagination: exceeded maxPages limit of ${n} (maxPage=${l}), stopping iteration`),r&&r.debug(`Auto-pagination: completed with total items: ${a.length}, total count: ${u}`),{items:a,total:u}}((t,n)=>this.fetchReferrals({...e,page:t,limit:n}).then(e=>({items:e.referrals,page:e.page,limit:e.limit,total:0,totalPages:0,hasNext:e.hasMore,hasPrevious:e.page>1})),{maxPages:100,pageSize:100,logger:this.logger});return{referrals:t.items,total:t.items.length}}async fetchReferralsSummary(e){const t=await this.resolveReferralAddress(e?.address),n=await this.dexApiHttp.get(M,void 0,{"x-wallet-address":t});if(void 0===n||"number"!=typeof n.referralCount||void 0===n.rewardTotals)throw new Ct(`Unexpected API response: expected { referralCount, rewardTotals }, got ${JSON.stringify(n)}`);return n}async updateProfile(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return xr}),{address:n,...r}=e,s=void 0===n?void 0:t(n),i={...r,...void 0!==s&&{address:s}};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 xr}),n=void 0===e.address?void 0:t(e.address)??e.address,r={...e,...void 0!==n&&{address:n}};if(void 0!==r.privateKey&&""!==r.privateKey){const e=this.createOverrideSdk(r.privateKey),{privateKey:t,...n}=r;return e.uploadProfileImage(n)}return this.launchpadService.uploadProfileImage(r)}async fetchTokensHeld(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return xr}),n=t(e?.address)??this.getAddress(),r={pageSize:e?.pageSize??10,address:n,...void 0!==e?.cursor?{cursor:e.cursor}:{}};return void 0!==e?.tokenName&&""!==e.tokenName&&(r.tokenName=e.tokenName),void 0!==e?.search&&""!==e.search&&(r.search=e.search),this.launchpadService.fetchTokensHeld(r)}async fetchTokensCreated(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return xr}),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 xr}),n={...e,recipientAddress:t(e.recipientAddress)};if(void 0!==n.privateKey&&""!==n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...r}=n;return e.transferGala(r)}return this.assertTokenWriter(),this.galaChainService.transferGala(n)}async transferToken(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return xr}),n={...e,to:t(e.to)};if(void 0!==n.privateKey&&""!==n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...r}=n;return e.transferToken(r)}return this.assertTokenWriter(),this.galaChainService.transferToken(n)}async resolveTokenClassKey(e){return this.galaChainService.resolveTokenClassKey(e)}async convertTokenNameToTokenClassKey(e){return this.resolveTokenClassKey(e)}async lockTokens(e){const t=await Promise.all(e.tokens.map(async e=>{if(void 0!==e.lockAuthority&&""!==e.lockAuthority){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return xr});return{...e,lockAuthority:t(e.lockAuthority)}}return e})),n={...e,tokens:t};if(void 0!==n.privateKey&&""!==n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...r}=n;return e.lockTokens(r)}return this.assertTokenWriter(),this.galaChainService.lockTokens(n)}async unlockTokens(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...r}=e;return t.unlockTokens(r)}return this.assertTokenWriter(),this.galaChainService.unlockTokens(e)}async burnTokens(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...r}=e;return t.burnTokens(r)}return this.assertTokenWriter(),this.galaChainService.burnTokens(e)}async resolveVaultAddress(e){return this.tokenResolverService.resolveTokenToVault(e)}async findTokenNameByVault(e,t){let n;for(let r=0;r<10;r+=1){const r=await this.launchpadService.poolService.fetchPools({search:t,pageSize:100,...void 0===n?{}:{cursor:n}}),s=r.items.find(t=>t.vaultAddress===e);if(void 0!==s)return s.tokenName;const i=Lo(r.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{In(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 Vt("baseUrl is required in configuration","baseUrl");if(void 0===this.config.webSocketUrl||""===this.config.webSocketUrl)throw Vt("webSocketUrl is required in configuration","webSocketUrl");try{new URL(this.config.baseUrl)}catch{throw Vt(`Invalid baseUrl format: ${this.config.baseUrl}`,"baseUrl")}try{new URL(this.config.webSocketUrl)}catch{throw Vt(`Invalid webSocketUrl format: ${this.config.webSocketUrl}`,"webSocketUrl")}if(void 0!==this.config.gatewayBaseUrl&&""!==this.config.gatewayBaseUrl)try{new URL(this.config.gatewayBaseUrl)}catch{throw Vt(`Invalid gatewayBaseUrl format: ${this.config.gatewayBaseUrl}`,"gatewayBaseUrl")}if(void 0!==this.config.bundleBaseUrl&&""!==this.config.bundleBaseUrl)try{new URL(this.config.bundleBaseUrl)}catch{throw Vt(`Invalid bundleBaseUrl format: ${this.config.bundleBaseUrl}`,"bundleBaseUrl")}if(void 0!==this.config.launchpadFrontendUrl&&""!==this.config.launchpadFrontendUrl)try{new URL(this.config.launchpadFrontendUrl)}catch{throw Vt(`Invalid launchpadFrontendUrl format: ${this.config.launchpadFrontendUrl}`,"launchpadFrontendUrl")}}parseSlippageToleranceFactor(e){const t=Sn("string"==typeof e||"number"==typeof e?e:String(e),Qh.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR);return t<0||t>1?(this.logger.warn(`Invalid slippage tolerance factor: ${String(e)}, using default: ${Qh.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR}`),Qh.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR):t}parseFeeSlippageFactor(e){const t=Sn("string"==typeof e||"number"==typeof e?e:String(e),Qh.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: ${Qh.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR}`),Qh.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!==So.COMPLETED)throw new Kh(e,n.status,n.message);let r;try{r=t(n)}catch(t){if(t instanceof Gh)throw t;throw new Gh(`Failed to transform WebSocket response for transaction ${e}`,Mt(t)?t:new Error(Lt(t)))}return this.logger.debug(`Transaction confirmed: ${e}`,r),r}catch(t){if(this.logger.error(`Transaction confirmation failed: ${e}`,t),t instanceof Kh||t instanceof Gh)throw t;throw new Gh(`WebSocket confirmation failed for transaction ${e}`,Mt(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 cf});e.forEach(e=>{if(!n(e))return;const r=t(e,this.logger);r&&this.launchpadAPI.warmCacheFromPoolData(e.tokenName,r)})}connectWebSocket(){this.websocketService.connect()}disconnectWebSocket(){this.websocketService.disconnect()}isWebSocketConnected(){return this.websocketService.isConnected()}subscribeToEvent(e,t){const n=this.websocketService.getSocket();return n?(n.on(e,t),()=>{n.off(e,t),this.logger.debug(`Unsubscribed from event: "${e}"`)}):(this.logger.warn(`⚠️ WebSocket not connected - subscribing to "${e}" without connection`),()=>{})}onLaunchpadTokenCreation(e,t){const n=1e3,r=Math.max(t?.intervalMs??3e4,n);null!=t?.intervalMs&&t.intervalMs<n&&this.logger.warn(`Poll interval ${t.intervalMs}ms is below minimum 1000ms. Using minimum interval instead.`);const s=t?.creatorAddress,i=new Map;let o=!0,a=null;let c=0;const l=async()=>{if(o){try{const t=await this.fetchPools({type:"recent",pageSize:20});c>0&&(this.logger.debug("Successfully recovered from polling errors"),c=0),t.items.forEach(t=>{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!==s&&""!==s&&t.creatorAddress!==s||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(o){const e=Math.min(Math.max(c-1,0),2),t=r*Math.pow(2,e);a=setTimeout(()=>{l()},t)}}};return l(),()=>{o=!1,a&&clearTimeout(a),this.logger.debug("Stopped watching for launchpad token creation")}}matchesCreatorFilter(e,t){return void 0===t||""===t||e.creatorAddress===t}subscribeToTokenCreations(e,t){if(this.logger.debug("Subscribing to token creation broadcasts"+(void 0!==t?.creatorFilter&&""!==t.creatorFilter?` (filter: ${t.creatorFilter})`:"")),null===this.websocketService||void 0===this.websocketService)throw Vt("WebSocket service not initialized. Ensure websocketUrl is configured and the service is connected.","websocketService");let n=!1,r=null;const s=(n,...r)=>{try{if(r.length>0&&"object"==typeof r[0]&&null!==r[0]){const n=r[0].data;if(void 0!==n?.Data&&null!==n.Data&&"object"==typeof n.Data){const r=n.Data;if("CreateSale"===r.functionName){const n=(e,t="")=>{const n=r[e];return"string"==typeof n&&""!==n?n:t},s={tokenName:n("tokenName"),symbol:n("symbol"),creatorAddress:n("creatorAddress"),description:n("description"),image:n("image"),vaultAddress:n("vaultAddress"),tokenStringKey:n("tokenStringKey"),preBuyQuantity:n("initialBuyQuantity","0"),websiteUrl:n("websiteUrl"),telegramUrl:n("telegramUrl"),twitterUrl:n("twitterUrl"),instagramUrl:n("instagramUrl"),facebookUrl:n("facebookUrl"),redditUrl:n("redditUrl"),tiktokUrl:n("tiktokUrl"),isFinalized:!0===r.isFinalized};this.matchesCreatorFilter(s,t?.creatorFilter)&&e(s)}}}}catch(e){this.logger.warn(`Error processing token creation broadcast: ${Lt(e)}`)}};let i=this.websocketService.getSocket();if(i)i.onAny(s),n=!0,this.logger.debug("Token creation broadcast listener registered");else{this.logger.debug("WebSocket not yet connected, initiating connection..."),this.websocketService.connect().catch(e=>{const n=new Error(`WebSocket connection failed: ${Lt(e)}`);this.logger.warn("Failed to establish WebSocket connection:",e),t?.onError&&t.onError(n)});let e=0;const o=()=>{if(i=this.websocketService.getSocket(),!i&&e<Qh.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS)return e++,void(r=setTimeout(()=>o(),Qh.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS));if(!i&&e>=Qh.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS){const e=new Error(`WebSocket not available after ${Qh.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS*Qh.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(s),n=!0,this.logger.debug("Token creation broadcast listener registered"))};o()}return()=>{try{if(null!==r&&(clearTimeout(r),r=null,this.logger.debug("Cleared token creation broadcast polling timeout")),!n)return void this.logger.debug("Cleanup called before listener registration - no action needed");const e=this.websocketService.getSocket();e&&(e.offAny(s),n=!1,this.logger.debug("Stopped listening to token creation broadcasts"))}catch(e){this.logger.warn("Error removing token creation listener:",e)}}}getNftCollectionClaimFee(){return this.nftCollectionService.getCollectionClaimFee()}getNftTokenClassCreateFee(){return this.nftCollectionService.getTokenClassCreateFee()}estimateNftMintFee(e){return this.nftCollectionService.estimateMintFee(e)}estimateNftOperationFees(e){return this.nftCollectionService.estimateNftOperationFees(e)}claimNftCollection(e){return this.nftCollectionService.claimCollection(e)}fetchNftCollections(e){return this.nftCollectionService.fetchUserCollections(e)}isNftCollectionAvailable(e){return this.nftCollectionService.isCollectionAvailable(e)}createNftTokenClass(e){return this.nftCollectionService.createTokenClass(e)}fetchNftTokenClasses(e){return this.nftCollectionService.fetchTokenClasses(e)}mintNft(e){return this.nftCollectionService.mintNft(e)}fetchNftBalances(e,t){return this.nftCollectionService.fetchNftBalances(e,t)}async cleanup(){try{if(this.logger.debug("Starting cleanup..."),void 0!==this._eventsBatcherService)try{await this._eventsBatcherService.shutdown(5e3),this._eventsBatcherService=void 0}catch(e){this.logger.warn("Error during events shutdown:",e)}this.http.cleanup(),null!==this.websocketService&&void 0!==this.websocketService&&this.websocketService.disconnect(),void 0!==this._streamWebSocketService&&(this._streamWebSocketService.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 pn({debug:e,context:"LaunchpadSDK"});t.debug("Starting global cleanup..."),ih.cleanupAll(e),t.debug("Global cleanup completed")}}function Yh(e){Gn(e)&&(e={});const{wallet:t,env:n,config:r={},...i}=e,o={...{...i,...r}};delete o.wallet,delete o.env,delete o.config;const a=!Gn(o.signer)||!Gn(o.walletProvider);let c;if(Gn(t))c=a?void 0:new s(v().privateKey);else if("string"==typeof t)c=new s(v(t).privateKey);else{if(!(t instanceof s))throw Vt("Invalid wallet input. Expected string (private key or mnemonic) or Wallet instance.","wallet");c=t}const l={...void 0!==c?{wallet:c}:{},...void 0!==n?{env:n}:{},debug:!1,timeout:3e4,...o};return new Qh(l)}function Jh(e){const t=v(e);return{...t,wallet:new s(t.privateKey)}}function Zh(){const e=globalThis;return e.process?.env??{}}Qh.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR=.15,Qh.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR=.01,Qh.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY=un.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY,Qh.DEFAULT_CALCULATE_AMOUNT_MODE=bt.LOCAL,Qh.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS=30,Qh.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS=100;class eg{constructor(){this.utilityInstance=!0,this.utilityInstance}static async quickSetup(e={}){const t=e.environment??this.detectEnvironment(),n=this.setupWallet(e.privateKey),r=this.buildSdkConfig(e,t,n),s=new Qh(r),i={sdk:s,wallet:n,config:r};if(!1!==e.autoValidate){const e=await this.validateSetup(s,n);return{...i,validation:e}}return i}static readOnlySetup(e={}){const t=e.environment??this.detectEnvironment(),n=this.buildSdkConfig(e,t),r=new Qh(n);return Promise.resolve({sdk:r,config:n})}static async validateSetup(e,t){const n=[],r=[],s={canTrade:!1,canCreateTokens:!1,hasBalance:!1,connectionHealthy:!1};try{const t=await e.fetchGalaBalance(e.getAddress());if(s.connectionHealthy=!0,void 0!==t?.quantity&&""!==t.quantity){const e=Sn(t.quantity,0);s.hasBalance=e>0,s.canTrade=e>=.1,s.canCreateTokens=e>=100,0===e?r.push("Wallet has zero GALA balance - cannot perform transactions"):e<.1?r.push("GALA balance too low for trading (minimum 0.1 GALA)"):e<100&&r.push("GALA balance too low for token creation (minimum 100 GALA)")}else n.push("Failed to fetch GALA balance: No balance returned")}catch(e){n.push(`Balance check error: ${Lt(e)}`)}try{const t=await e.fetchPools({type:"recent",pageSize:1});null!==t.items&&void 0!==t.items&&0!==t.items.length||r.push("Pool listing not accessible - some features may be limited")}catch(e){r.push(`Pool access test failed: ${Lt(e)}`)}return{ready:0===n.length&&s.connectionHealthy,sdk:e,wallet:t??Jh(),issues:n,warnings:r,capabilities:s}}static getRecommendedConfig(e,t="general"){const n={environment:e,autoValidate:!0};switch(e){case"prod":Object.assign(n,{debug:!1,timeout:3e4});break;case"stage":Object.assign(n,{debug:!0,timeout:45e3})}switch(t){case"trading":n.timeout=1.5*(n.timeout??3e4);break;case"creation":n.timeout=2*(n.timeout??3e4);break;case"monitoring":n.timeout=.5*(n.timeout??3e4);break;case"general":break;default:throw new Error(`Unexpected useCase: ${String(t)}`)}return n}static async multiWalletSetup(e,t="stage"){const n={};for(const[r,s]of Object.entries(e)){const{sdk:e}=await this.quickSetup({environment:t,privateKey:s,agentId:`multi-wallet-${r}`,autoValidate:!1});n[r]=e}return n}static detectEnvironment(){return"stage"===(Zh().LAUNCHPAD_ENV??Zh().ENVIRONMENT)?"stage":"prod"}static setupWallet(e){if(void 0===e||""===e){const e=Zh().PRIVATE_KEY;return void 0!==e&&""!==e?Jh(e):Jh()}return"generate"===e?Jh():Jh(e)}static buildSdkConfig(e,t,n){const r=e.galaChainAddress??Zh().WALLET_ADDRESS;return{wallet:n?.wallet,baseUrl:e.baseUrl??this.getDefaultBaseUrl(t),timeout:e.timeout??this.getDefaultTimeout(t),debug:e.debug??"prod"!==t,...this.getEnvironmentDefaults(t),...e.config??{},...void 0!==r&&""!==r?{galaChainAddress:r}:{},env:t}}static getDefaultBaseUrl(e){return To(e).launchpadBaseUrl}static getDefaultTimeout(e){switch(e){case"prod":return 3e4;case"stage":return 45e3}}static getEnvironmentDefaults(e){const t=To(e);return{bundleBaseUrl:t.bundleBaseUrl,gatewayBaseUrl:t.gatewayBaseUrl}}}function tg(e,t,n){const r="number"==typeof e?new _(e):e;if(r.isLessThan(0)||r.isGreaterThan(1))throw new Error(`Progress must be between 0 and 1, got: ${r.toString()}`);if(n<t)throw new Error(`maxFee must be >= minFee, got minFee: ${t}, maxFee: ${n}`);const s=n-t;return new _(t).plus(new _(s).multipliedBy(r))}function ng(e,t,n){if(e>=t)throw new Error(`tickLower must be < tickUpper, got: ${e} >= ${t}`);if(n<=0)throw new Error(`tickSpacing must be > 0, got: ${n}`);return{tickLower:Math.floor(e/n)*n,tickUpper:Math.ceil(t/n)*n}}function rg(e,t,n=60){const r=Hi(e),s=Hi(t);if(r.isLessThanOrEqualTo(0)||s.isLessThanOrEqualTo(0))throw new Error("Prices must be positive");if(r.isGreaterThanOrEqualTo(s))throw new Error(`minPrice must be < maxPrice, got: ${r.toString()} >= ${s.toString()}`);const i=Math.floor(Vi(r)),o=Math.ceil(Vi(s)),a=Math.floor(i/n)*n,c=Math.ceil(o/n)*n;return{minTick:a,maxTick:c,actualMinPrice:new _(1.0001).pow(a),actualMaxPrice:new _(1.0001).pow(c)}}function sg(e,t){if(0===e.length)return-1;if(t<0||t>100)throw new Error(`Percentile must be between 0 and 100, got: ${t}`);const n=(e.length-1)*(t/100),r=Math.floor(n);return Math.min(r,e.length-1)}function ig(e,t){if(t<0)throw new Error(`decimals must be >= 0, got: ${t}`);const n=Hi(e),r=new _(10).pow(t);return n.multipliedBy(r).integerValue(_.ROUND_UP).dividedBy(r)}function og(e,t,n,r="0"){const s=Hi(t);if(ji(s))return Hi(r);const i=Hi(e).dividedBy(s);if(null!=n){const e=Hi(n);if(e.isLessThan(0))throw new Error(`minimum must be >= 0, got: ${e.toString()}`);if(i.isLessThan(e))return e}return i}function ag(e,t){if(t<=0)throw new Error(`tickSpacing must be > 0, got: ${t}`);return Math.floor(e/t)*t}function cg(e,t){if(t<0)throw new Error(`feeFactor must be >= 0, got: ${t}`);return Hi(e).multipliedBy(t).integerValue(_.ROUND_DOWN)}function lg(e,t){const n=new Map;for(const r of e){const e=t(r);n.has(e)||n.set(e,[]),n.get(e).push(r)}return n}function dg(e){if(null==e||"object"!=typeof e)throw new Error("Token must be an object");const t=e,n=(xn(t.name)?t.name:void 0)??(xn(t.tokenName)?t.tokenName:void 0)??"";if(!xn(n))throw new Error("Token name is required and must be a non-empty string");const r=(xn(t.symbol)?t.symbol:void 0)??(xn(t.tokenSymbol)?t.tokenSymbol:void 0)??"";if(!xn(r))throw new Error("Token symbol is required and must be a non-empty string");let s=8;"number"==typeof t.decimals&&t.decimals>=0&&(s=Math.floor(t.decimals));const i={name:n,symbol:r,decimals:s};return xn(t.address)&&(i.address=t.address),"boolean"==typeof t.verified&&(i.verified=t.verified),i}function ug(e,t,n=null){if(null==e||"object"!=typeof e)return n;const r=e;for(const e of t){const t=e.split(".");let n=r;for(const e of t){if(null==n||"object"!=typeof n){n=null;break}n=n[e]}if(xn(n))return n;if(null!=n&&""!==n)return n}return n}function hg(e,t){return e.map(e=>{const n={};for(const[r,s]of Object.entries(t)){const t=s(e);void 0!==t&&(n[r]=t)}return n})}function gg(e,t,n=!0){const r=new Map;if(e.forEach((e,n)=>{const s=t(e);r.set(s,n)}),n){const n=new Set;return e.filter(e=>{const r=t(e);return!n.has(r)&&(n.add(r),!0)})}return e.filter((e,n)=>{const s=t(e);return r.get(s)===n})}function mg(e,t){const n={...e};for(const[e,r]of Object.entries(t))void 0!==r&&(n[e]=r);return n}class fg{constructor(){this.rooms=new Set}addRoom(e){this.rooms.add(e)}removeRoom(e){this.rooms.delete(e)}getRooms(){return Array.from(this.rooms)}isSubscribedTo(e){return this.rooms.has(e)}clear(){this.rooms.clear()}get size(){return this.rooms.size}}class pg{constructor(e,t,n=50){this.seen=new Set,this.extractor=e,this.dedupeKeyFn=t,this.maxDepth=n}walk(e){const t=[],n=new WeakSet,r=(e,s=0)=>{if(s>this.maxDepth)return;if(null==e||"object"!=typeof e)return;if(n.has(e))return;n.add(e);const i=this.extractor(e);if(null!==i){const e=this.dedupeKeyFn(i);this.seen.has(e)||(this.seen.add(e),t.push(i))}for(const t of Object.values(e))r(t,s+1)};return r(e,0),t}reset(){this.seen.clear()}getSeenCount(){return this.seen.size}}class Eg{constructor(){this.pending=new Map}addPending(e,t){this.removePending(e);const n=setTimeout(()=>{this.pending.delete(e)},t);this.pending.set(e,{timeoutId:n,addedAt:Date.now()})}removePending(e){const t=this.pending.get(e);t&&(clearTimeout(t.timeoutId),this.pending.delete(e))}isPending(e){return this.pending.has(e)}getPendingCount(){return this.pending.size}clearExpired(){for(const[e,t]of this.pending.entries())null==t&&this.pending.delete(e)}clear(){for(const e of this.pending.values())clearTimeout(e.timeoutId);this.pending.clear()}}class Ag{constructor(e){this.globalCallbacks=[],this.roomCallbacks=new Map,this.logger=e}registerGlobalCallback(e){this.globalCallbacks.push(e)}registerRoomCallback(e,t){const n=this.roomCallbacks.get(e)??[];n.push(t),this.roomCallbacks.set(e,n)}dispatch(e,t){for(const e of this.globalCallbacks)try{e(t)}catch(e){this.logger?.error(`Error in global callback: ${Lt(e)}`)}const n=this.roomCallbacks.get(e);if(n)for(const r of n)try{r(t)}catch(t){this.logger?.error(`Error in room callback for ${e}: ${Lt(t)}`)}}clear(){this.globalCallbacks=[],this.roomCallbacks.clear()}clearRoom(e){this.roomCallbacks.delete(e)}}class vg{constructor(){this.filters=[]}addFilter(e){return this.filters.push(e),this}forward(e){for(const t of this.filters)if(!t(e))return!1;return!0}clearFilters(){this.filters=[]}get filterCount(){return this.filters.length}}class Tg{constructor(e){this.listeners=[],this.logger=e}register(e,t){this.listeners.push({id:e,cleanup:t})}async cleanup(){const e=[];for(let t=this.listeners.length-1;t>=0;t--){const n=this.listeners[t];if(void 0===n)continue;const{id:r,cleanup:s}=n;try{await s()}catch(t){const n=t instanceof Error?t:new Error(String(t));e.push(n),this.logger?.error(`Cleanup error for listener ${r}:`,n)}}return this.listeners=[],e}clear(){this.listeners=[]}get size(){return this.listeners.length}}class yg{constructor(e={},t){this.events=[],this.timeouts=new Map,this.maxSize=e.maxSize??100,this.defaultTtlMs=e.defaultTtlMs??3e4,this.logger=t}push(e){if(this.events.length>=this.maxSize){const e=0;this.events.shift();const t=this.timeouts.get(e);t&&(clearTimeout(t),this.timeouts.delete(e)),this.logger?.warn(`Buffer full (${this.maxSize}), dropped oldest event`)}this.events.push(e);const t=this.events.length-1,n=setTimeout(()=>{this.events[t]===e&&this.events.splice(t,1),this.timeouts.delete(t)},this.defaultTtlMs);this.timeouts.set(t,n)}getAll(){return[...this.events]}clear(){for(const e of this.timeouts.values())clearTimeout(e);this.events=[],this.timeouts.clear()}get size(){return this.events.length}}class Sg{constructor(e={},t){this.pendingIndicators=new Map,this.activeIndicators=new Set,this.delayMs=e.delayMs??3e3,this.onTyping=e.onTyping,this.onStopTyping=e.onStopTyping}indicate(e,t){const n=`${e}:${t}`,r=this.pendingIndicators.get(n);r&&clearTimeout(r),this.activeIndicators.has(n)||(this.activeIndicators.add(n),this.onTyping?.(e,t));const s=setTimeout(()=>{this.activeIndicators.delete(n),this.pendingIndicators.delete(n),this.onStopTyping?.(e,t)},this.delayMs);this.pendingIndicators.set(n,s)}stopTyping(e,t){const n=`${e}:${t}`,r=this.pendingIndicators.get(n);r&&(clearTimeout(r),this.pendingIndicators.delete(n)),this.activeIndicators.has(n)&&(this.activeIndicators.delete(n),this.onStopTyping?.(e,t))}clear(){for(const e of this.pendingIndicators.values())clearTimeout(e);this.pendingIndicators.clear(),this.activeIndicators.clear()}get activeCount(){return this.activeIndicators.size}}const bg=5,Ng=8,wg=18,kg={PAGE:"page",LIMIT:"limit",TOKEN_NAME:"tokenName",VAULT_ADDRESS:"vaultAddress",USER_ADDRESS:"userAddress",TRADE_TYPE:"tradeType",POOL_TYPE:"type",SEARCH:"search",SORT_ORDER:"sortOrder",START_DATE:"startDate",END_DATE:"endDate"},_g=5,Ig=5;function Dg(e){const t={};return void 0!==e.cursor&&(t.cursor=e.cursor),void 0!==e.pageSize&&(t.pageSize=e.pageSize),t}function Cg(e,t){return Dg({...e,...t})}function Rg(e,t){return void 0===t?e:{...e,cursor:t}}function Og(e){return"string"==typeof e?e:"number"==typeof e||"boolean"==typeof e||"bigint"==typeof e?String(e):JSON.stringify(e)??""}async function Mg(e,t,n,r){const s=r?.logger,i=[];i.length=e.length;let o=0,a=0;s?.debug(`Starting concurrent batch requests: ${e.length} URLs, batch size: ${t}`);for(let r=0;r<e.length;r+=t){const c=e.slice(r,r+t),l=r;try{const t=c.map((t,r)=>{const c=l+r;return(async()=>{try{const r=await n(t);return i[c]=r,o++,s?.debug(`Fetched [${c+1}/${e.length}]: ${t}`),r}catch(n){throw a++,s?.warn(`Failed [${c+1}/${e.length}]: ${t} - ${Lt(n)}`),n}})()}),r=await Promise.allSettled(t);for(let e=0;e<r.length;e++){const t=r[e];"rejected"===t?.status&&s?.debug(`Promise rejected in batch at index ${l+e}`)}}catch(e){s?.error(`Batch processing error at index ${r}: ${Lt(e)}`)}}return s?.debug(`Batch complete: ${o} succeeded, ${a} failed`),i}function Lg(e){const t={page:1,pageSize:20,totalCount:-1,hasMore:!1};if(null==e||"object"!=typeof e)return t;const n=e,r=bn(Og(n.page??n.Page??n.current??1),t.page),s=bn(Og(n.pageSize??n.limit??n.size??t.pageSize),t.pageSize),i=n.data,o=i?.meta;let a;a="number"==typeof n.totalCount?n.totalCount:"number"==typeof n.total?n.total:"number"==typeof o?.totalItems?o.totalItems:"number"==typeof i?.count?i.count:bn(Og(n.totalCount??n.total??-1),t.totalCount);let c=t.hasMore;return"boolean"==typeof n.hasMore?c=n.hasMore:"boolean"==typeof n.has_more?c=n.has_more:"boolean"==typeof o?.hasMore&&(c=o.hasMore),{page:r,pageSize:s,totalCount:a,hasMore:c}}function Ug(e){if(null==e||"object"!=typeof e)return"";const t=[];for(const[n,r]of Object.entries(e)){if(Bn(r))continue;let e;e="string"==typeof r?r:"number"==typeof r||"boolean"==typeof r?String(r):Array.isArray(r)?r.map(e=>Og(e)).join(","):Og(r);const s=encodeURIComponent(n),i=encodeURIComponent(e);t.push(`${s}=${i}`)}return t.length>0?`?${t.join("&")}`:""}async function Fg(e,t){const n=t?.maxRetries??3,r=t?.backoffMs??100,s=t?.retryableStatus??[429,503,504];let i,o=0;for(;o<=n;)try{return await e()}catch(e){i=e,o++;const t=Bg(e),a=s.includes(t);if(o>n||!a)throw e;const c=r*Math.pow(2,o-1);await new Promise(e=>setTimeout(e,c))}throw i}function Pg(e){const t={statusCode:0,errorMessage:"Unknown error",raw:e};if(null==e)return t;const n=e;let r=t.statusCode;"number"==typeof n.status?r=n.status:"number"==typeof n.statusCode?r=n.statusCode:"number"==typeof n.code&&(r=n.code);let s,i=t.errorMessage;"string"==typeof n.message?i=n.message:"string"==typeof n.error?i=n.error:e instanceof Error?i=e.message:"string"==typeof e&&(i=e);const o=n.response;if(o){const e=o.data;if("object"==typeof e&&null!==e){s=e;const t=e;"string"==typeof t.message?i=t.message:"string"==typeof t.error&&(i=t.error)}}const a={statusCode:r,errorMessage:i,raw:e};return null!=s&&(a.errorData=s),a}async function xg(e,t,n){const r=n?.logger,s=n?.fetcher??(async e=>{const t=await fetch(e);if(!t.ok)throw new Error(`HTTP ${t.status}`);return t.json()});r?.debug(`Aggregating from ${e.length} endpoints`);const i=e.map(async(t,n)=>{try{const i=await s(t);return r?.debug(`Endpoint [${n+1}/${e.length}] succeeded: ${t}`),i}catch(s){return void r?.warn(`Endpoint [${n+1}/${e.length}] failed: ${t} - ${Lt(s)}`)}}),o=(await Promise.allSettled(i)).map(e=>{if("fulfilled"===e.status)return e.value});return r?.debug(`Aggregating ${o.filter(e=>void 0!==e).length} successful results`),t(o)}function Bg(e){if(null==e||"object"!=typeof e)return 0;const t=e;if("number"==typeof t.status)return t.status;if("number"==typeof t.statusCode)return t.statusCode;if("number"==typeof t.code)return t.code;const n=t.response;return n&&"number"==typeof n.status?n.status:0}function Gg(e){const t=e.trim().toLowerCase();if(0===t.length)throw new Error("Token name cannot be empty");return t}function $g(e){if(void 0!==e&&e.length>0&&!/^[a-z0-9]+$/.test(e.toLowerCase()))throw new Error(`Invalid asset extension format: "${e}". Must contain only alphanumeric characters.`)}function Kg(e,t){return`${e.replace(/\/$/,"")}${t}`}function Hg(e,t){const n=Gg(e);return Kg(t,`/v1/tokens/${encodeURIComponent(n)}/assets/image`)}function Wg(e,t,n="jpg"){const r=Gg(e);$g(n);return Kg(t,`/v1/tokens/${encodeURIComponent(r)}/assets/thumbnail.${n.toLowerCase()}`)}function Vg(e,t,n="gif"){const r=Gg(e);$g(n);return Kg(t,`/v1/tokens/${encodeURIComponent(r)}/assets/animated.${n.toLowerCase()}`)}function jg(e,t){const n=Gg(e);return Kg(t,`/v1/tokens/${encodeURIComponent(n)}/assets/poster.jpg`)}function qg(e,t,n="vtt"){const r=Gg(e);$g(n);return Kg(t,`/v1/tokens/${encodeURIComponent(r)}/assets/storyboard.${n.toLowerCase()}`)}function zg(e,t){const n=Gg(e);return Kg(t,`/v1/tokens/${encodeURIComponent(n)}/assets/live.m3u8`)}function Xg(e,t,n,r){const s=Gg(e),i=t.trim().toLowerCase();if(0===i.length)throw new Error("Asset type cannot be empty");$g(r);const o=void 0!==r&&r.length>0?`.${r.toLowerCase()}`:"";return Kg(n,`/v1/tokens/${encodeURIComponent(s)}/assets/${encodeURIComponent(i)}${o}`)}function Qg(e,t,n,r="jpg"){const s=Gg(e),i=t.trim();if(0===i.length)throw new Error("Recording ID cannot be empty");$g(r);return Kg(n,`/v1/tokens/${encodeURIComponent(s)}/recordings/${encodeURIComponent(i)}/assets/thumbnail.${r.toLowerCase()}`)}function Yg(e,t,n,r="gif"){const s=Gg(e),i=t.trim();if(0===i.length)throw new Error("Recording ID cannot be empty");$g(r);return Kg(n,`/v1/tokens/${encodeURIComponent(s)}/recordings/${encodeURIComponent(i)}/assets/animated.${r.toLowerCase()}`)}function Jg(e,t,n){const r=Gg(e),s=t.trim();if(0===s.length)throw new Error("Recording ID cannot be empty");return Kg(n,`/v1/tokens/${encodeURIComponent(r)}/recordings/${encodeURIComponent(s)}/assets/poster.jpg`)}function Zg(e,t,n,r="vtt"){const s=Gg(e),i=t.trim();if(0===i.length)throw new Error("Recording ID cannot be empty");$g(r);return Kg(n,`/v1/tokens/${encodeURIComponent(s)}/recordings/${encodeURIComponent(i)}/assets/storyboard.${r.toLowerCase()}`)}function em(e,t,n){const r=Gg(e),s=t.trim();if(0===s.length)throw new Error("Recording ID cannot be empty");return Kg(n,`/v1/tokens/${encodeURIComponent(r)}/recordings/${encodeURIComponent(s)}/assets/stream.m3u8`)}function tm(e,t,n,r,s){const i=Gg(e),o=t.trim(),a=n.trim().toLowerCase();if(0===o.length)throw new Error("Recording ID cannot be empty");if(0===a.length)throw new Error("Asset type cannot be empty");$g(s);const c=void 0!==s&&s.length>0?`.${s.toLowerCase()}`:"";return Kg(r,`/v1/tokens/${encodeURIComponent(i)}/recordings/${encodeURIComponent(o)}/assets/${encodeURIComponent(a)}${c}`)}const nm=new Map;function rm(e,t){const n=e;return nm.set(n,{createdAt:Date.now(),label:t}),n}function sm(e){const t=e;nm.delete(t)}function im(){const e=nm.size;return nm.clear(),e}function om(){const e=Array.from(nm.entries()).map(([e,t])=>({id:e,...t}));return{size:nm.size,entries:e}}class am extends nr{constructor(e,t=!1){super(e,t)}async getChart(e){if(null==e)throw Kt("options","Chart options");const{tokenName:t,from:n,to:r,resolution:s}=e;if(null==t||""===t)throw Kt("tokenName","Token name");if(null==n)throw Kt("from","Start timestamp");if(null==r)throw Kt("to","End timestamp");if(null==s)throw Kt("resolution","Data resolution interval");Wn(t,"tokenName",or);const i=173e6;if("number"!=typeof n||n<i)throw new wt("from must be a valid timestamp (min: 173000000)","from","INVALID_TIMESTAMP");if("number"!=typeof r||r<i)throw new wt("to must be a valid timestamp (min: 173000000)","to","INVALID_TIMESTAMP");if("number"!=typeof s||s<1)throw new wt("resolution must be a number >= 1","resolution","INVALID_RESOLUTION");const{adaptQueryParams:o}=await Promise.resolve().then(function(){return vl}),a=o({tokenName:t,from:n,to:r,resolution:s}),c=await ln(()=>this.http.get(C.CHART,a),{errorContext:"Failed to fetch chart data"}),l=sn(c);if(null==l||"object"!=typeof l)throw Wt("Invalid API response: missing or invalid data",c.status??500);const d=l,u=d.data;if(!Array.isArray(u))throw Wt("Invalid API response: expected data array",c.status??500);const h={dataPoints:u.map(e=>{if("object"!=typeof e||null===e)throw Wt("Invalid API response: invalid data point structure",c.status??500);const t=e,n=t.startTime??t.timestamp,r=t.openPrice??t.value,s=t.closePrice??t.value,i=t.lowPrice??t.value,o=t.highPrice??t.value,a=t.volume??"0";return{startTime:"number"==typeof n?n:Number(n),openPrice:String(r),closePrice:String(s),lowPrice:String(i),highPrice:String(o),volume:String(a)}})};return"boolean"==typeof d.isPreviousData&&(h.isPreviousData=d.isPreviousData),h}}const cm={NEW_HOLDER:"NEW_HOLDER",EXITED_HOLDER:"EXITED_HOLDER",BALANCE_CHANGED:"BALANCE_CHANGED"},lm=$i({type:"string",userAddress:"string",balance:"string",rank:"number",previousRank:"optional-number"}),dm=$i({tokenName:"string",userAddress:"string",quantity:"optional-string",percentage:"optional-number",holderTier:"optional-object",isCreator:"boolean",rank:"optional-number"});function um(e){return"string"==typeof e&&(e===cm.NEW_HOLDER||e===cm.EXITED_HOLDER||e===cm.BALANCE_CHANGED)}cr.MIN_LENGTH,cr.MAX_LENGTH,cr.PATTERN;Kn({ENABLED:"ENABLED",DISABLED:"DISABLED",ADMIN_DISABLED:"ADMIN_DISABLED"});function hm(e){return"global"===e||"token"===e}function gm(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.messageId&&"string"==typeof t.content&&"string"==typeof t.userAddress&&"string"==typeof t.tokenName&&"string"==typeof t.createdAt}function mm(e){return gm(e)}function fm(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.message}function pm(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.messageId&&"string"==typeof t.deletedAt}function Em(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.messageId&&"string"==typeof t.content&&"string"==typeof t.userAddress&&"string"==typeof t.pinnedBy&&"string"==typeof t.pinnedAt}function Am(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&Em(t.pinnedMessage)}function vm(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.unpinnedMessageId}function Tm(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"boolean"==typeof t.enabled&&(void 0===t.reason||hm(t.reason))}function ym(e){return!!xn(e)&&(e.length>=pr.CHAT_MESSAGE.MIN_LENGTH&&e.length<=pr.CHAT_MESSAGE.MAX_LENGTH)}function Sm(e){return!!xn(e)&&cr.PATTERN.test(e)}function bm(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.emoji&&"number"==typeof t.timestamp&&"number"==typeof t.streamTime}function Nm(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.message}const wm=Kn({RATE_LIMITED:"RATE_LIMITED",INVALID_EMOJI:"INVALID_EMOJI",NOT_AUTHENTICATED:"NOT_AUTHENTICATED",STREAM_NOT_LIVE:"STREAM_NOT_LIVE"});function km(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.userAddress&&"string"==typeof t.fullName&&(void 0===t.profileImage||"string"==typeof t.profileImage)}function _m(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&Array.isArray(t.typingUsers)&&t.typingUsers.every(km)}const Im={ONE_SECOND_MS:1e3,ONE_MINUTE_MS:6e4,ONE_HOUR_MS:36e5,ONE_DAY_MS:864e5,ONE_WEEK_MS:6048e5,ONE_MONTH_MS:2592e6};var Dm,Cm,Rm,Om,Mm,Lm;!function(e){e.PENDING="PENDING",e.PROCESSING="PROCESSING",e.COMPLETED="COMPLETED",e.FAILED="FAILED"}(Dm||(Dm={})),function(e){e.TEXT="TEXT",e.IMAGE="IMAGE",e.VIDEO="VIDEO"}(Cm||(Cm={})),function(e){e.NO_ACTION="NO_ACTION",e.REVIEW_REQUIRED="REVIEW_REQUIRED",e.DELETE_CONTENT="DELETE_CONTENT",e.BAN_USER="BAN_USER",e.DELETE_AND_BAN="DELETE_AND_BAN"}(Rm||(Rm={})),function(e){e.VIOLENCE="VIOLENCE",e.HATE_SPEECH="HATE_SPEECH",e.SEXUAL_CONTENT="SEXUAL_CONTENT",e.HARASSMENT="HARASSMENT",e.SPAM="SPAM",e.SCAM="SCAM",e.SELF_HARM="SELF_HARM",e.ILLEGAL_ACTIVITY="ILLEGAL_ACTIVITY",e.MISINFORMATION="MISINFORMATION",e.COPYRIGHT="COPYRIGHT",e.SAFE="SAFE"}(Om||(Om={})),function(e){e.QUICK="QUICK",e.DETAILED="DETAILED"}(Mm||(Mm={})),function(e){e.DISABLED="DISABLED",e.ADVISORY="ADVISORY"}(Lm||(Lm={}));const Um={[Dm.PENDING]:"Pending",[Dm.PROCESSING]:"Processing",[Dm.COMPLETED]:"Completed",[Dm.FAILED]:"Failed"},Fm={[Rm.NO_ACTION]:"No Action Needed",[Rm.REVIEW_REQUIRED]:"Human Review Required",[Rm.DELETE_CONTENT]:"Delete Content",[Rm.BAN_USER]:"Ban User",[Rm.DELETE_AND_BAN]:"Delete & Ban"},Pm={[Om.VIOLENCE]:"Violence",[Om.HATE_SPEECH]:"Hate Speech",[Om.SEXUAL_CONTENT]:"Sexual Content",[Om.HARASSMENT]:"Harassment",[Om.SPAM]:"Spam",[Om.SCAM]:"Scam",[Om.SELF_HARM]:"Self Harm",[Om.ILLEGAL_ACTIVITY]:"Illegal Activity",[Om.MISINFORMATION]:"Misinformation",[Om.COPYRIGHT]:"Copyright",[Om.SAFE]:"Safe"},xm={[Mm.QUICK]:"Quick Scan",[Mm.DETAILED]:"Detailed Scan"},Bm={[Cm.TEXT]:"Text",[Cm.IMAGE]:"Image",[Cm.VIDEO]:"Video"},Gm={[Lm.DISABLED]:"Disabled",[Lm.ADVISORY]:"Advisory"},$m=Kn(Dm),Km=Kn(Cm),Hm=Kn(Rm),Wm=Kn(Om),Vm=Kn(Mm),jm=Kn(Lm),qm=zn([{field:"id",type:"number"},{field:"flagId",type:"number"},{field:"status",type:"string",validator:$m},{field:"analysisType",type:"string",validator:Km},{field:"provider",type:"string"}]),zm=zn([{field:"enabled",type:"boolean"},{field:"mode",type:"string",validator:jm},{field:"provider",type:"string"}]);function Xm(e){return null!==e.analysisTier}function Qm(e){return!0===e.escalatedFromQuick}function Ym(e,t){if(!Xm(e)||null===e.tokensUsed)return 0;const n=1500*t.maxFrames;if(0===n)return 0;const r=(n-e.tokensUsed)/n*100;return Math.max(0,Math.round(r))}function Jm(e){if(!(void 0!==e.tokenName&&""!==e.tokenName||void 0!==e.userAddress&&""!==e.userAddress))throw Zt(["tokenName","userAddress"]);void 0!==e.tokenName&&""!==e.tokenName&&qn(e.tokenName,"tokenName",or),$n(0,void 0,gr,e.pageSize,e.cursor)}function Zm(e){if(!xn(e.tokenName))throw Kt("tokenName","Token name");qn(e.tokenName,"tokenName",or),tf(e.content)}function ef(e){tf(e.content)}function tf(e){if(!xn(e))throw Kt("content");if(0===e.trim().length)throw tn("content","Content");if(e.length>pr.COMMENTS_V1.MAX_LENGTH)throw en("content",pr.COMMENTS_V1.MAX_LENGTH,e.length)}function nf(e){if(!(void 0!==e.tokenName&&""!==e.tokenName||void 0!==e.userAddress&&""!==e.userAddress))throw new wt("At least one of tokenName or userAddress is required","options",Nt.REQUIRED);ql(e.tokenName,e.userAddress),void 0!==e.pageSize&&$n(0,void 0,gr,e.pageSize)}function rf(e){if(!xn(e.tokenName))throw Kt("tokenName");qn(e.tokenName,"tokenName",or),of(e.content)}function sf(e){of(e.content)}function of(e){if(!xn(e))throw Kt("content");if(0===e.trim().length)throw new wt("content cannot be empty","content",Nt.REQUIRED);if(e.length>pr.CHAT_MESSAGES_V1.MAX_LENGTH)throw new wt(`content must be at most ${pr.CHAT_MESSAGES_V1.MAX_LENGTH} characters`,"content",Nt.TOO_LONG)}function af(e){if(!xn(e))throw Kt("id","Message ID");if(!Er.CHAT_MESSAGE.PATTERN.test(e))throw new wt("Invalid message ID format. Expected: chat-{timestamp}-{uuid}","id",Nt.INVALID_FORMAT)}var cf=Object.freeze({__proto__:null,extractMetadataFromPoolData:function(e,t){const n={};if(void 0!==e.vaultAddress&&(n.vaultAddress=e.vaultAddress),void 0!==e.reverseBondingCurveMinFeePortion){const r=Sn(e.reverseBondingCurveMinFeePortion,NaN);isNaN(r)?t&&t.debug(`Skipping invalid reverseBondingCurveMinFeePortion for ${e.tokenName}: "${e.reverseBondingCurveMinFeePortion}"`):n.reverseBondingCurveMinFeeFactor=r}if(void 0!==e.reverseBondingCurveMaxFeePortion){const r=Sn(e.reverseBondingCurveMaxFeePortion,NaN);isNaN(r)?t&&t.debug(`Skipping invalid reverseBondingCurveMaxFeePortion for ${e.tokenName}: "${e.reverseBondingCurveMaxFeePortion}"`):n.reverseBondingCurveMaxFeeFactor=r}return void 0!==n.reverseBondingCurveMaxFeeFactor&&void 0!==n.reverseBondingCurveMinFeeFactor&&(n.reverseBondingCurveNetFeeFactor=n.reverseBondingCurveMaxFeeFactor-n.reverseBondingCurveMinFeeFactor),Object.keys(n).length>0?n:null},isValidPoolForCaching:function(e){if(null===e||"object"!=typeof e)return!1;const t=e;return"tokenName"in t&&"string"==typeof t.tokenName&&t.tokenName.length>0}});export{ra as ACTIVE_USER_TYPE,Lm as AIModerationMode,Rm as AIRecommendation,Gm as AI_MODE_LABELS,Fm as AI_RECOMMENDATION_LABELS,qo as ALL_PERMISSIONS,Pm as ANALYSIS_CATEGORY_LABELS,Um as ANALYSIS_STATUS_LABELS,xm as ANALYSIS_TIER_LABELS,Bm as ANALYSIS_TYPE_LABELS,Vo as API_KEY_PERMISSION,Ho as API_KEY_ROLE,Wo as API_KEY_ROLES,Zo as API_KEY_ROLE_HIERARCHY,kr as AddressFormatter,eg as AgentConfig,Om as AnalysisCategory,Dm as AnalysisStatus,Mm as AnalysisTier,Cm as AnalysisType,ho as AuthError,uo as AuthErrorType,na as BAN_DURATIONS,Ca as BrowserWalletSigner,ch as BundleSubmission,lh as BundlerTransport,nl as BurnError,tl as BurnErrorType,bt as CALCULATION_MODES,cc as CONTENT_REACTION_TYPES,Ya as CONTENT_TYPE_LABELS,am as ChartService,Rt as ConfigurationError,Ba as ContentType,mc as DEFAULT_EVENTS_CONFIG,_g as DEFAULT_PRICING_CONCURRENCY,bh as DEFAULT_REVERSE_BONDING_CURVE_CONFIGURATION,Ig as DEFAULT_WEBSOCKET_RECONNECT_ATTEMPTS,vo as ENVIRONMENT_URLS,Nt as ERROR_CODES,Ec as EVENT_SORT_FIELDS,vc as EVENT_SOURCES,Ac as EVENT_TIME_PRESETS,fc as EVENT_TYPES,uu as EXTENDED_STREAM_ROLE,yg as EventBufferWithAutoCleanup,pc as EventsBatcherService,Nc as EventsQueryService,Qa as FLAG_ACTION_LABELS,Ja as FLAG_DETAILS_MAX_LENGTH,za as FLAG_REASON_LABELS,Xa as FLAG_STATUS_LABELS,gl as FileValidationError,Ka as FlagAction,Ga as FlagReason,$a as FlagStatus,Ng as GALA_DECIMALS,Da as GalaWalletSigner,Ag as GlobalAndRoomCallbackDispatcher,cm as HOLDER_DELTA_TYPES,hl as HealthService,ms as IMAGE_EXTENSIONS,dd as INVITE_STATUS,ud as INVITE_STATUSES,co as JWT_CONSTANTS,wg as LAUNCHPAD_TOKEN_DECIMALS,ah as LAUNCHPAD_WRITE_METHODS,Qh as LaunchpadSDK,ya as LaunchpadSDKError,Lh as LaunchpadWrites,Tg as ListenerCleanupManager,Fc as LockError,Lc as LockErrorType,el as MAX_BURN_BATCH_SIZE,bg as MAX_CONCURRENT_POOL_FETCHES,Oc as MAX_LOCK_BATCH_SIZE,Mc as MAX_UNLOCK_BATCH_SIZE,Xl as MESSAGES_CONSTRAINTS,zl as MESSAGE_TYPES,od as MODERATOR_ROLE,ad as MODERATOR_ROLES,bd as NFT_FEES,Ct as NetworkError,Cd as NftCollectionService,Od as OEmbedService,Ld as OVERSEER_INVITE_STATUS,Ud as OVERSEER_STATUS,wo as PAGINATION_DEFAULTS,jo as PERMISSION,ko as POOL_FETCH_CONFIG,Tt as POOL_FETCH_TYPES,St as POOL_LIST_MAX_PAGE_SIZE,yt as POOL_STREAM_STATUSES,vt as POOL_TYPES,pg as PayloadWalkerWithDeduplication,Eg as PendingSubscriptionTracker,Qd as PlatformStatsService,Ia as PrivateKeySigner,kg as QUERY_FIELD_NAMES,lc as REACTION_EMOJI_MAP,eu as RECORDING_STATUS,lu as ROLE_SOURCE,fg as RoomSubscriptionManager,So as SDKTransactionStatus,No as SDK_VERSION,Au as SIMULATE_EVENT_TYPE,nu as SIMULCAST_PLATFORM,tu as SIMULCAST_STATUS,Tu as STREAM_EVENTS,du as STREAM_PERMISSION,cu as STREAM_ROLE,Zd as STREAM_STATUS,vg as SelectiveEventForwarding,Vu as StreamWebSocketService,Im as TIME_CONSTANTS,lr as TOKEN_NAME_AVAILABILITY_CONSTRAINT,or as TOKEN_NAME_DTO_CONSTRAINT,dr as TOKEN_NAME_EVENT_CONSTRAINT,ar as TOKEN_NAME_FILTER_CONSTRAINT,cr as TOKEN_NAME_PATH_CONSTRAINT,At as TRADING_TYPES,kt as TokenRestrictedError,th as TradingQuotesService,Ot as TransactionError,Kh as TransactionFailedError,Sg as TypingIndicatorDebouncer,wt as ValidationError,Gh as WebSocketError,$h as WebSocketTimeoutError,oh as WeeklyChallengeService,Rg as addCursorToPagination,qr as addressFormatSchema,xg as aggregateMultipleApiSources,Cs as amountMethodSchema,Ds as amountTypeSchema,Fr as assertValidWalletAddress,$r as availabilityTokenNameSchema,Ul as bidirectionalTokenMatch,ps as browserFileSchema,Es as bufferFileSchema,Mg as buildConcurrentBatchRequests,Ug as buildQueryParametersWithValidation,Dg as buildSafePaginationOptions,Vs as buyTokensDataSchema,tg as calculateLinearFeeInterpolation,Js as calculatePreMintDataSchema,cg as calculateScaledFeeAmount,Co as calculateTotalPages,Gt as capitalize,Ol as caseInsensitiveTokenComparison,Is as checkPoolOptionsSchema,Xn as commonValidators,mg as conditionalSpreadBuilder,Rl as conditionalTrimAndValidateString,Yh as createLaunchpadSDK,ns as createLimitSchema,Qn as createOptionsValidator,$s as createPaginatedResultSchema,_o as createPaginationQuery,Ws as createTradeDataSchema,ig as decimalRoundingUp,gg as deduplicateByKey,Gr as dtoTokenNameSchema,Ml as errorMessageCaseNormalization,zr as ethereumAddressSchema,ug as extractFieldWithFallbackPath,Lg as extractPaginationMetadata,yh as feeCeilingFromQuotedFee,ri as fetchGalaBalanceOptionsSchema,Zs as fetchPoolDetailsDataSchema,oi as fetchTokenBalanceOptionsSchema,os as fileSizeSchema,fs as fileUploadSchema,as as filenameSchema,Xr as flexibleAddressSchema,As as flexibleFileSchema,kn as formatGalaForDTO,_n as formatLaunchpadTokenForDTO,Cr as fromBackendAddressFormat,jr as fullNameSchema,Oa as generateBuySellStringsInstructions,Ma as generateCreateSaleStringsInstructions,Ys as getAmountOptionsSchema,To as getEnvironmentConfig,om as getIntervalRegistryStats,Ui as getLaunchTokenDataValidationErrors,Nd as getNftFeeAsNumber,Yg as getRecordingAnimatedUrl,tm as getRecordingAssetUrl,Jg as getRecordingPosterUrl,Zg as getRecordingStoryboardUrl,em as getRecordingStreamUrl,Qg as getRecordingThumbnailUrl,Ym as getTieredModerationSavings,Vg as getTokenAnimatedUrl,Xg as getTokenAssetUrl,Hg as getTokenImageUrl,zg as getTokenLiveStreamUrl,jg as getTokenPosterUrl,qg as getTokenStoryboardUrl,Wg as getTokenThumbnailUrl,qs as getTradeOptionsSchema,Os as graduateTokenOptionsSchema,Rs as graphDataOptionsSchema,lg as groupByKey,Ro as hasMorePages,Fl as hexStringExtractionAndNormalization,vs as imageExtensionSchema,Ts as imageFilenameSchema,cs as imageMimeTypeSchema,ks as imageUploadOptionsSchema,qm as isAIModerationData,jm as isAIModerationMode,zm as isAIModerationSettings,Hm as isAIRecommendation,sa as isActiveUserType,Wm as isAnalysisCategory,$m as isAnalysisStatus,Vm as isAnalysisTier,Km as isAnalysisType,ia as isBanData,ca as isBanEnforcementEvent,Jc as isBurnTokenEntry,Zc as isBurnTokensData,hm as isChatDisabledReason,Tm as isChatStatusResponse,xd as isClaimableInvite,Za as isContentType,Bn as isEmptyValue,hu as isExtendedStreamRole,nc as isFlagAction,rc as isFlagData,ec as isFlagReason,tc as isFlagStatus,lm as isHolderDelta,um as isHolderDeltaType,Ic as isLockTokenEntry,Cc as isLockTokensData,rd as isMessage,sd as isMessageType,pd as isModeratedToken,Xm as isModerationTiered,fd as isModeratorInvite,xn as isNonEmptyString,Fd as isOverseerInviteStatus,Pd as isOverseerStatus,Em as isPinnedMessage,Ed as isPublicInviteInfo,wm as isReactionErrorCode,su as isRecordingStatus,iu as isSimulcastPlatform,pm as isStreamChatDeletedEvent,fm as isStreamChatErrorEvent,gm as isStreamChatMessage,mm as isStreamChatMessageEvent,Am as isStreamChatPinnedEvent,vm as isStreamChatUnpinnedEvent,Nm as isStreamReactionErrorEvent,bm as isStreamReactionEvent,ru as isStreamStatus,ou as isStreamStatusEvent,gu as isTokenAccessResult,qu as isTokenBanData,_m as isTypingIndicatorEvent,km as isTypingUser,Dc as isUnlockTokenEntry,Rc as isUnlockTokensData,oa as isUserBannedEvent,dm as isUserHoldingData,aa as isUserUnbannedEvent,Or as isValidAddress,zo as isValidApiKeyRole,da as isValidBanDuration,la as isValidBanReason,ym as isValidChatContent,Sm as isValidChatTokenName,md as isValidInviteCode,gd as isValidInviteStatus,Li as isValidLaunchTokenData,hd as isValidModeratorRole,zu as isValidTokenBanReason,jn as isValidTokenName,au as isViewerCountEvent,ls as isoDateStringSchema,ws as launchTokenDataSchema,Cg as mergeSafePaginationOptions,Jr as nonNegativeDecimalStringSchema,Rr as normalizeAddressInput,hg as normalizeDataWithMapping,Ll as normalizeErrorMessage,Do as normalizeLimit,gn as normalizeTokenKey,hn as normalizeTokenName,mn as normalizeTokenSymbol,es as optionalUrlSchema,ts as pageNumberSchema,Gs as paginationResultMetaSchema,Pg as parseHttpErrorResponse,Ra as parseLaunchpadVaultAddress,sg as percentileIndexCalculation,_s as poolFetchTypeSchema,Fs as poolPaginationSchema,Yr as positiveDecimalStringSchema,rg as priceTickRangeMapping,us as privateKeySchema,rm as registerInterval,Xi as requireNonNegative,zi as requirePositive,Qi as requirePositiveWithContext,Fg as retryableHttpRequest,Ns as reverseBondingCurveConfigSchema,ei as reverseBondingCurveConfigurationSchema,ea as roleHasSufficientPermission,ng as roundTickBoundaries,ag as roundTickToSpacing,og as safeDivideWithMinimum,Vr as searchQuerySchema,js as sellTokensDataSchema,rs as standardLimitSchema,Ms as standardPaginationSchema,ds as timestampSchema,Dr as toBackendAddressFormat,Pr as toBackendAddressFromEthers,Ss as tokenCategorySchema,bs as tokenCollectionSchema,Hr as tokenDescriptionSchema,ni as tokenListOptionsSchema,Br as tokenNameSchema,Kr as tokenSymbolSchema,ys as tokenUrlsSchema,Qs as tradeCalculationMethodSchema,Xs as tradeCalculationTypeSchema,is as tradeLimitSchema,zs as tradeListParamsSchema,Us as tradePaginationSchema,xs as tradePaginationWithFiltersSchema,Hs as tradeTypeBackendSchema,Ks as tradeTypeSchema,hs as transactionIdSchema,dg as transformRawApiTokenToDomainModel,Pl as trimmedLengthValidation,gs as uniqueKeySchema,im as unregisterAllIntervals,sm as unregisterInterval,si as updateProfileDataSchema,ii as uploadProfileImageOptionsSchema,Zr as urlSchema,ss as userLimitSchema,Ls as userPaginationSchema,Wr as userTokenNameSchema,ti as userTokenTypeSchema,Ps as userTokensPaginationSchema,ui as validateAddress,gi as validateAmountString,Xu as validateBanTokenOptions,_i as validateBuyTokensData,Oi as validateCalculatePreMintData,af as validateChatMessageId,Ti as validateCheckPoolOptions,Fn as validateConstrainedEnumVariant,Xo as validateCreateApiKeyOptions,rf as validateCreateChatMessageOptions,Zm as validateCreateCommentOptions,Yl as validateCreateMessageOptions,vd as validateCreateModeratorInviteOptions,jd as validateCreateOverseerDirectOptions,Bd as validateCreateOverseerInviteOptions,ki as validateCreateTradeData,Mn as validateDecimalRangeStrict,Ln as validateFeePortionConstraints,Si as validateFetchGalaBalanceOptions,Ql as validateFetchMessagesOptions,Mi as validateFetchPoolDetailsData,wi as validateFetchTokenBalanceOptions,mi as validateFullName,Ri as validateGetAmountOptions,nf as validateGetChatMessagesOptions,Jm as validateGetCommentsOptions,Ju as validateGetTokenBanOptions,Di as validateGetTradeOptions,Il as validateGetTradesOptions,vi as validateImageUploadOptions,Td as validateInviteCode,Fi as validateLaunchTokenData,Jo as validateListApiKeysOptions,yd as validateListModeratorInvitesOptions,Gd as validateListOverseerInvitesOptions,$d as validateListOverseersOptions,Yu as validateListTokenBansOptions,Vd as validateListUsersOptions,Zl as validateMessageId,Un as validateMinMaxRelationship,Vn as validateOptionalTokenName,Kd as validateOverseerInviteCode,Wd as validateOverseerInviteId,Hd as validateOverseerWalletAddress,Io as validatePaginationParams,fi as validateSearchQuery,Ii as validateSellTokensData,On as validateSortOrderDirection,di as validateTokenDescription,yi as validateTokenListOptions,qn as validateTokenName,li as validateTokenSymbol,Ai as validateTokenUrls,Ci as validateTradeListParams,Qu as validateUnbanTokenOptions,Qo as validateUpdateApiKeyOptions,sf as validateUpdateChatMessageOptions,ef as validateUpdateCommentOptions,Jl as validateUpdateMessageOptions,zd as validateUpdatePlatformConfigOptions,bi as validateUpdateProfileData,El as validateUpdateTokenConfigOptions,Ni as validateUploadProfileImageOptions,pi as validateUserTokenName,hi as validateVaultAddress,Qr as vaultAddressSchema,Qm as wasModerationEscalated};
1
+ import{galaChainUserRef as e,GALA_CHAIN_ENVIRONMENTS as t,BrowserWalletSigner as n,generateEIP712Types as r,ethereumAddressOfAccount as s,GalaWalletSigner as i,withGalaWalletIdentity as o,PrivateKeySigner as a,isTokenClassKey as c,GatewayReads as l,isGalaError as d,GatewayWrites as u,tokenDetailsOf as h,isWalletUserRejection as g,walletDeclineCode as m,createWallet as f}from"@gala-chain/gala-core-sdk";import{computeAddress as p,getAddress as E,isAddress as A,BrowserProvider as v,Wallet as T}from"ethers";import{z as y}from"zod";import{PrivateKeyProvider as S,isPrivateKeyProvider as b}from"@gala-chain/gala-core-sdk/providers";import{ChainCallDTO as N,TokenClassKey as w}from"@gala-chain/api";import{v4 as k}from"uuid";import{io as _}from"socket.io-client";import I from"bignumber.js";import C,{AxiosHeaders as D}from"axios";const R={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"},O="/v1/users/referrals/url",M="/v1/users/referrals",L="/v1/users/referrals/summary",U="/v1/tokens/:tokenName/start-stream",F="/v1/tokens/:tokenName/stop-stream",P="/v1/tokens/:tokenName/stream/disable",x="/v1/tokens/:tokenName/stream/enable",B="/v1/tokens/:tokenName/reset-key",G="/v1/tokens/:tokenName/recordings",$="/v1/tokens/:tokenName/recordings/:assetId/download",K="/v1/tokens/:tokenName/recordings/:assetId",H="/v1/tokens/:tokenName/simulcasts",W="/v1/tokens/:tokenName/simulcasts",V="/v1/tokens/:tokenName/simulcasts/:targetId",j="/v1/config",q="/v1/config",z="/v1/config",Q="/v1/tokens/:tokenName/role",X="/v1/roles",Y="/v1/permissions",J="/v1/tokens/:tokenName/credentials",Z="/auth/login",ee="/auth/logout",te="/auth/refresh",ne="/auth/session",re="/v1/tokens/:tokenName/bans",se="/v1/tokens/:tokenName/bans",ie="/v1/tokens/:tokenName/bans/:userAddress",oe="/v1/tokens/:tokenName/bans/:userAddress",ae="/v1/tokens/:tokenName/active-users",ce="/v1/user-bans",le="/v1/user-bans",de="/v1/user-bans/:userAddress",ue="/v1/user-bans/:userAddress",he={CREATE:"/v1/api-keys",LIST:"/v1/api-keys",GET:"/v1/api-keys/:id",UPDATE:"/v1/api-keys/:id",REVOKE:"/v1/api-keys/:id"},ge="/v1/moderator-invites",me="/v1/moderator-invites/claim",fe="/v1/moderated-tokens",pe="/v1/moderator-invites",Ee="/v1/moderator-invites/:id",Ae="/v1/moderator-invites/:id/role",ve="/v1/moderator-invites/:id",Te="/v1/moderator-invites/code/:code",ye={CREATE:"/v1/content-flags",LIST:"/v1/content-flags",DISMISS:"/v1/content-flags/:id/dismiss",ACTION:"/v1/content-flags/:id/action"},Se="/v1/overseer-invites",be="/v1/overseer-invites",Ne="/v1/overseer-invites/code/:code",we="/v1/overseer-invites/claim",ke="/v1/overseer-invites/:id",_e="/v1/overseers",Ie="/v1/overseers",Ce="/v1/overseers/:address",De="/v1/overseers/me",Re="/v1/overseer-summary",Oe="/v1/overseer-summary/bans",Me="/v1/overseer-summary/token-bans",Le="/v1/overseer-summary/invites",Ue="/v1/overseer-summary/flags",Fe="/v1/overseer-summary/users",Pe="/v1/users",xe="/v1/users/:address/summary",Be="/v1/cache/flush/address/:address",Ge="/v1/cache/flush/token/:tokenName",$e="/v1/cache/flush/all",Ke="/v1/cache/flush/wallet-aliases/:address",He="/v1/cache/flush/wallet-aliases",We="/v1/token-bans",Ve="/v1/token-bans",je="/v1/token-bans/:tokenName",qe="/v1/token-bans/:tokenName",ze="/v1/reactions",Qe="/v1/reactions",Xe="/v1/trades",Ye={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"},Je="/v1/restricted-token-names",Ze="/v1/restricted-token-names",et="/live/:tokenName/chat",tt="/live/:tokenName/chat",nt="/live/:tokenName/chat",rt="/live/:tokenName/chat/slow-mode",st="/v1/events",it="/v1/events/stats",ot="/health",at={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"},ct="/v1/stats",lt="/v1/trading/fee",dt="/v1/trading/sale-details",ut="/v1/trading/quote",ht="/v1/trading/premint-quote",gt={GET_LEADERBOARD:"/weekly-challenge",GET_TOKEN_HISTORY:"/weekly-challenge/history/:vaultAddress"},mt="/v1/notifications/register",ft="/v1/notifications/unregister",pt="/v1/notifications/preferences",Et="/v1/notifications/preferences",At="/v1/config/client-flags",vt={NATIVE:"native",EXACT:"exact"},Tt={RECENT:"recent",POPULAR:"popular"},yt=["RECENT","POPULAR","RECORDINGS","SECONDS_STREAMED"],St=["IDLE","ACTIVE","DISABLED"],bt=100,Nt={LOCAL:"local",EXTERNAL:"external"},wt={REQUIRED:"REQUIRED",INVALID_TYPE:"INVALID_TYPE",INVALID_VALUE:"INVALID_VALUE",INVALID_FORMAT:"INVALID_FORMAT",TOO_SHORT:"TOO_SHORT",TOO_LONG:"TOO_LONG",TOO_LARGE:"TOO_LARGE",TOO_SMALL:"TOO_SMALL",EMPTY_ARRAY:"EMPTY_ARRAY",ARRAY_TOO_LARGE:"ARRAY_TOO_LARGE",ZERO_VALUE:"ZERO_VALUE",INVALID_TICK_SPACING:"INVALID_TICK_SPACING",INVALID_FEE_TIER:"INVALID_FEE_TIER",INVALID_RANGE:"INVALID_RANGE",INVALID_PARAMETERS:"INVALID_PARAMETERS",NOT_FOUND:"NOT_FOUND",INVALID_DATA:"INVALID_DATA"};class kt extends Error{constructor(e,t,n){super(e),this.field=t,this.code=n,this.name="ValidationError"}}class _t extends kt{constructor(e){super(e,"token","TOKEN_RESTRICTED"),this.name="TokenRestrictedError"}}function It(e){return"object"==typeof e&&null!==e}function Ct(e){if(null==e||""===e)return{};if(!It(e)||Array.isArray(e))return{body:e};const t=Reflect.get(e,"message"),n="string"==typeof t?t:Array.isArray(t)&&t.every(e=>"string"==typeof e)?t.join(","):void 0,r=Reflect.get(e,"error"),s=Reflect.get(e,"details");return{...void 0===n?{}:{serverMessage:n},..."string"==typeof r&&""!==r?{serverError:r}:{},...void 0===s?{}:{details:s},body:e}}function Dt(e){if(e instanceof Rt)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(!It(e))return;const t=Reflect.get(e,"response");return It(t)?t:void 0}(e);return void 0===t?{}:Ct(Reflect.get(t,"data"))}class Rt extends Error{constructor(e,t,n,r=Dt(n)){super(e),this.name="NetworkError",this.statusCode=t,this.originalError=n,this.serverMessage=r.serverMessage,this.serverError=r.serverError,this.details=r.details,this.body=r.body}}class Ot extends Error{constructor(e,t){super(e),this.field=t,this.name="ConfigurationError"}}class Mt extends Error{constructor(e,t,n){super(e),this.transactionId=t,this.code=n,this.name="TransactionError"}}function Lt(e){return e instanceof Error}function Ut(e){return Lt(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 Ft(e){return Lt(e)||"object"==typeof e&&null!==e&&"stack"in e&&"string"==typeof e.stack?e.stack:void 0}function Pt(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 xt(e){return"object"==typeof e&&null!==e&&"message"in e&&("response"in e||"request"in e||"config"in e)}function Bt(e,t){if(null==e||"object"!=typeof e)throw new Error(`${t}: No response - expected object, got ${typeof e}`);const n=e;if(!("Status"in n))throw new Error(`${t}: Response missing 'Status' property`);const r=n.Status;if("number"!=typeof r)throw new Error(`${t}: Response Status must be a number, got ${typeof r}`);if(1!==r)throw new Error(`${t}: Response status indicates failure (Status: ${r})`);return n}function Gt(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 $t(e,t){return void 0!==t?t:e.charAt(0).toUpperCase()+e.slice(1)}function Kt(e,t){return new kt(`Token "${e}" not found. Please verify the token name is correct.`,"tokenName","TOKEN_NOT_FOUND")}function Ht(e,t){const n=$t(e,t);return new kt(`${n} is required`,e,"REQUIRED")}function Wt(e,t,n){const r=$t(e,n);return new kt(`${r} must be ${t}`,e,"INVALID_FORMAT")}function Vt(e,t,n,r){return new Rt(e,t,n,r)}function jt(e,t){return new Ot(e,t)}function qt(e,t,n){return new Mt(e,t,n)}function zt(e,t,n,r,s){const i=$t(e,s);return new kt(`${i} must be between ${t} and ${n}${void 0!==r?`, received: ${r}`:""}`,e,"OUT_OF_RANGE")}function Qt(e,t,n,r){const s=$t(e,r);return new kt(`${s} must be at least ${t}${void 0!==n?`, received: ${n}`:""}`,e,"TOO_SMALL")}function Xt(e,t,n,r){const s=$t(e,r);return new kt(`${s} must be at most ${t}${void 0!==n?`, received: ${n}`:""}`,e,"TOO_LARGE")}function Yt(e,t,n,r){const s=$t(e,r),i=void 0!==n?`, received: ${"object"==typeof n?"object":String(n)}`:"";return new kt(`${s} must be ${t}${i}`,e,"INVALID_TYPE")}function Jt(e,t,n){const r=$t(e,n);return new kt(`${r} must be a valid number${void 0!==t?`: "${t}"`:""}`,e,"INVALID_NUMBER")}function Zt(e,t,n,r){const s=$t(e,r);return new kt(`Invalid ${s}: ${t}. Must be one of: ${n.join(", ")}`,e,"INVALID_ENUM")}function en(e,t){if(e.length<2)return Ht(void 0!==e[0]&&""!==e[0]?e[0]:"field");let n;if(2===e.length)n=e.join(" or ");else{n=`${e.slice(0,-1).join(", ")} or ${e[e.length-1]??"field"}`}return new kt(`At least one of ${n} must be provided`,e[0],"REQUIRED")}function tn(e,t,n,r){const s=$t(e,r);return new kt(`${s} must be at most ${t} characters${void 0!==n?`, received: ${n}`:""}`,e,"TOO_LONG")}function nn(e,t){const n=$t(e,t);return new kt(`${n} cannot be empty`,e,"EMPTY_STRING")}function rn(e){return null!=e&&"object"==typeof e&&"data"in e}function sn(e,t,n=!1){const r=!0===e.error,s=n&&(null===e.data||void 0===e.data);if(r||s){const n=e?.statusCode??e.status??void 0;throw Vt(e?.message??t,n,void 0,r?Ct(e):void 0)}}function on(e){if(rn(e))return e.data}function an(e,t="No data found in response"){if(!rn(e))throw Vt(t);const n=e.data;if(null==n)throw Vt(t);return n}async function cn(e,t={}){return un(e,t,e=>{if(void 0===e.data)throw new kt(`${t.errorContext??"Operation failed"}: No data returned from API`,"data","NO_DATA");return e.data})}async function ln(e,t={}){const{errorContext:n="Operation failed",logger:r,debugLogEnabled:s=!1}=t;s&&r&&r.debug(`${n}: starting operation`);try{const t=await e();return s&&r&&r.debug(`${n}: completed successfully`),t}catch(e){throw r&&r.error(n,{error:e}),e}}async function dn(e,t={}){return un(e,t,e=>e)}async function un(e,t,n){const{errorContext:r="Operation failed",logger:s,debugLogEnabled:i=!1}=t;i&&s&&s.debug(`${r}: starting operation`);try{const t=await e();if(null==t)throw new kt(`${r}: No response from server`,"response","NO_RESPONSE");return sn(t,r,!0),i&&s&&s.debug(`${r}: completed successfully`),n(t)}catch(e){throw s&&s.error(r,{error:e}),e}}const hn={BASE_PRICE:1650667151e-14,PRICE_SCALING_FACTOR:1166069e-12,TRADING_FEE_FACTOR:.001,GAS_FEE:"1",DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY:1e7};function gn(e){return e.trim().toLowerCase()}function mn(e){return e.trim().toUpperCase()}function fn(e){return e.trim().toUpperCase()}var pn;!function(e){e.DEBUG="DEBUG",e.INFO="INFO",e.WARN="WARN",e.ERROR="ERROR"}(pn||(pn={}));class En{constructor(e){this.levelPriority={[pn.DEBUG]:0,[pn.INFO]:1,[pn.WARN]:2,[pn.ERROR]:3},this.debugEnabled=e.debug,this.context=e.context??"SDK",this.minLevel=e.minLevel??(e.debug?pn.DEBUG:pn.INFO)}debug(e,t){this.log(pn.DEBUG,e,t)}info(e,t){this.log(pn.INFO,e,t)}warn(e,t){this.log(pn.WARN,e,t)}error(e,t){this.log(pn.ERROR,e,t)}log(e,t,n){if(this.levelPriority[e]<this.levelPriority[this.minLevel])return;if(e===pn.DEBUG&&!this.debugEnabled)return;const r=`[${(new Date).toISOString()}] [${this.context}] [${e}]`,s=this.getConsoleMethod(e);void 0!==n?Lt(n)?s(`${r} ${t}`,n.message,Ft(n)??""):s(`${r} ${t}`,n):s(`${r} ${t}`)}getConsoleMethod(e){switch(e){case pn.DEBUG:return console.debug;case pn.INFO:return console.info;case pn.WARN:return console.warn;case pn.ERROR:return console.error;default:return console.log}}child(e){return new En({debug:this.debugEnabled,context:`${this.context}:${e}`,minLevel:this.minLevel})}isDebugEnabled(){return this.debugEnabled&&this.levelPriority[pn.DEBUG]>=this.levelPriority[this.minLevel]}}function An(e){return"string"==typeof e&&e.trim().length>0}function vn(e){return null==e||""===e}function Tn(e){return null==e}const yn=new En({debug:!1,context:"DateUtils"});function Sn(e,t){if(null==e)return new Date;if(e instanceof Date)return isNaN(e.getTime())?new Date:e;try{const t=new Date(e);return isNaN(t.getTime())?(yn.warn(`Invalid date string received: "${e}". Using fallback.`),new Date):t}catch(t){return yn.warn(`Date parsing error for "${e}":`,t),new Date}}function bn(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 Nn(t,n="address"){try{if("string"==typeof t&&/^eth\|0x/iu.test(t))throw new Error("eth|0x is not an address form");return e(t,n)}catch{throw new kt(`${n} must be a GalaChain user address: eth|<40 hex> (\`eth|0x...\` is not a valid form), 0x<40 hex>, <40 hex> or client|<id>, and a mixed-case Ethereum address must carry its EIP-55 checksum (got "${String(t)}")`,n,"INVALID_FORMAT")}}function wn(e,t="address"){return Nn(e,t).toLowerCase()}function kn(e,t){return xn(e)??wn(e,t)}function _n(e){return Cn(e)?wn(e):e.trim().toLowerCase()}function In(e,t){const n=e=>Cn(e)?wn(e):e.toLowerCase();return n(e)===n(t)}function Cn(e){try{return Nn(e),!0}catch{return!1}}class Dn{toBackendFormat(e){if(!An(e))throw new kt("Address is required and must be a string","address","REQUIRED");return Nn(e,"address")}toEthereumFormat(e){if(!An(e))throw new kt("Backend address is required and must be a string","address","REQUIRED");if(!e.match(/^eth\|([0-9a-fA-F]{40})$/i))throw new kt(`Invalid backend address format. Expected "eth|{40-hex-characters}" (\`eth|0x...\` is not a valid form). Got: "${e}"`,"address","INVALID_FORMAT");return`0x${e.substring(4)}`}normalizeInput(e){if(void 0!==e&&""!==e)return Nn(e,"address")}normalizeForBackend(e){if(void 0!==e&&""!==e)return wn(e,"address")}isValid(e){return Cn(e)}assertValid(e,t="address"){if(!this.isValid(e))throw new kt(`${t} must be a valid wallet address (eth|<40 hex>, 0x<40 hex>, <40 hex> or client|<id>; \`eth|0x...\` is not a valid form; a mixed-case address must carry its EIP-55 checksum)`,t,"INVALID_FORMAT")}detectFormat(e){return An(e)&&Cn(e)?e.startsWith("client|")?"client":e.startsWith("eth|")?"backend":"ethereum":null}normalize(e){if(void 0!==e&&""!==e)return e.toLowerCase()}extractHex(e){const t=Cn(e)?Nn(e):void 0;if(void 0!==t&&t.startsWith("eth|"))return t.substring(4).toLowerCase();throw new kt(`Cannot extract hex from address: "${e}". Expected Ethereum or backend format.`,"address","INVALID_FORMAT")}}const Rn=new Dn;function On(e){return Rn.toBackendFormat(e)}function Mn(e){return Rn.toEthereumFormat(e)}function Ln(e){return Rn.normalizeInput(e)}function Un(e){return Rn.isValid(e)}const Fn=/^(eth\|[a-f0-9]{40}|client\|[a-f0-9]{24})$/;function Pn(e){return void 0!==xn(e)}function xn(e){if(!An(e))return;const t=e.trim(),n=/^[0-9a-fA-F]{24}$/u.test(t)?`client|${t}`:t;if(!Cn(n))return;const r=wn(n);return Fn.test(r)?r:void 0}function Bn(e,t){if(!Pn(e))throw new kt(`${t} must be a GalaChain user address (eth|<40 hex> (\`eth|0x...\` is not a valid form), 0x<40 hex>, <40 hex> or client|<24 hex>)`,t,"INVALID_FORMAT")}function Gn(e,t="address"){Rn.assertValid(e,t)}function $n(e){const t="string"==typeof e?e:e.address;return Rn.toBackendFormat(t)}var Kn=Object.freeze({__proto__:null,AddressFormatter:Dn,assertBackendUserAddress:Bn,assertValidWalletAddress:Gn,backendUserAddress:xn,backendUserParam:kn,backendUserRef:wn,fromBackendAddressFormat:Mn,isBackendUserAddress:Pn,isUserRef:Cn,isValidAddress:Un,normalizeAddressInput:Ln,sameUserAddress:In,toBackendAddressFormat:On,toBackendAddressFromEthers:$n,userAddressFilter:_n,userRef:Nn});function Hn(e,t=0){if(vn(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 Wn(e,t,n){if(Tn(e))return t;if("bigint"==typeof e)try{return Number(e)}catch{return t}if("number"==typeof e)return isNaN(e)?t:Math.floor(e);const r=parseInt(String(e),10);return isNaN(r)?t:r}function Vn(e,t=0){if(Tn(e))return t;if("number"==typeof e)return isNaN(e)?t:e;return Hn(String(e).replace("%","").trim(),t)}function jn(e,t=18){const n=Hn(e,0);if(0===n)return"0";return n.toFixed(t).replace(/\.?0+$/,"")}function qn(e){return jn(e,8)}function zn(e){return jn(e,18)}function Qn(e,t,n,r){if("number"!=typeof e)throw Yt(r,"a number",e,r);if(e<t||e>n)throw zt(r,t,n,e)}function Xn(e,t,n){if("string"!=typeof e)throw Yt(n,"a string",e,n);if(e.length>t)throw Xt(n,t,e.length)}function Yn(e,t){if("number"!=typeof e)throw Yt(t,"a number",e,t);if(!Number.isInteger(e))throw Yt(t,"an integer",e,t);if(e<=0)throw Qt(t,1,e,t)}function Jn(e,t,n=!1){if("string"!=typeof e)throw Yt(t,"a string",e,t);if(!n&&0===e.trim().length)throw Ht(t,`${t} (non-empty string)`)}function Zn(e,t){if("ASC"!==e&&"DESC"!==e)throw new kt(`${t} must be either 'ASC' or 'DESC'`,t,"INVALID_ENUM_VALUE")}function er(e,t,n,r){const s="string"==typeof e?parseFloat(e):e;if(!isFinite(s))throw new kt(`${r} must be a valid finite number between ${t} and ${n}`,r,"INVALID_NUMBER");if(s<t||s>n)throw zt(r,t,n,s,r)}function tr(e,t,n){const r="string"==typeof e?parseFloat(e):e,s="string"==typeof t?parseFloat(t):t;if(!isFinite(r))throw new kt(`${n} minFee must be a valid finite number`,n,"INVALID_FEE_MINIMUM");if(!isFinite(s))throw new kt(`${n} maxFee must be a valid finite number`,n,"INVALID_FEE_MAXIMUM");if(r<.1)throw new kt(`${n} minFee must be >= 0.1, received ${r}`,n,"INVALID_FEE_MINIMUM");if(s>.5)throw new kt(`${n} maxFee must be <= 0.5, received ${s}`,n,"INVALID_FEE_MAXIMUM");if(r>s)throw new kt(`${n} minFee (${r}) must be <= maxFee (${s})`,n,"INVALID_FEE_RANGE")}function nr(e,t,n,r){const s="string"==typeof e?parseFloat(e):e,i="string"==typeof t?parseFloat(t):t;if(!isFinite(s))throw new kt(`${n} must be a valid finite number`,n,"INVALID_MIN_VALUE");if(!isFinite(i))throw new kt(`${r} must be a valid finite number`,r,"INVALID_MAX_VALUE");if(s>i)throw new kt(`${n} (${s}) must be less than or equal to ${r} (${i})`,n,"INVALID_RANGE")}function rr(e,t,n){if(!t.includes(e))throw new kt(`${n} must be one of [${t.map(e=>String(e)).join(", ")}], received "${e}"`,n,"INVALID_ENUM_VALUE")}const sr={ETH_ADDRESS:/^0x[0-9a-fA-F]{40}$/,BACKEND_ADDRESS:/^eth\|[0-9a-fA-F]{40}$/},ir=An,or=vn,ar=Tn;function cr(e,t,n=100,r,s){if(void 0!==s&&"string"!=typeof s)throw new kt("cursor must be a string","cursor",wt.INVALID_TYPE);const i=r??t,o=void 0!==r?"pageSize":"limit";if(void 0!==i&&(Yn(i,o),i>n))throw new kt(`${o} must be at most ${n}`,o,wt.TOO_LARGE)}function lr(e){const t=Object.values(e);return e=>"string"==typeof e&&t.includes(e)}function dr(e){return Object.values(e)}function ur(e,t,n){if(!ir(e))throw Ht(t);const r=e.trim();if(0===r.length)throw Ht(t);if(r.length<n.MIN_LENGTH)throw zt(t,n.MIN_LENGTH,n.MAX_LENGTH,r.length,`${t} length`);if(r.length>n.MAX_LENGTH)throw zt(t,n.MIN_LENGTH,n.MAX_LENGTH,r.length,`${t} length`);if(!n.PATTERN.test(r))throw new kt(`${t} must be ${n.DESCRIPTION}`,t,wt.INVALID_FORMAT)}function hr(e,t,n){if(null==e)return;if("string"!=typeof e)throw Yt(t,"a string",e);const r=e.trim();if(0!==r.length&&!n.PATTERN.test(r))throw new kt(`${t} must be ${n.DESCRIPTION}`,t,wt.INVALID_FORMAT)}function gr(e,t){if("string"!=typeof e)return!1;const n=e.trim();return 0!==n.length&&t.PATTERN.test(n)}function mr(e,t,n){if(null==e)throw Ht(t,t);if("string"!=typeof e)throw Yt(t,"a string",e);const r=e.trim();if(0===r.length)throw Ht(t,t);if(!n.PATTERN.test(r))throw new kt(`${t} must be ${n.DESCRIPTION}`,t,wt.INVALID_FORMAT)}function fr(e){return t=>{if(null==t||"object"!=typeof t)return!1;const n=t;for(const{field:t,type:r,nullable:s=!1,optional:i=!1,validator:o}of e){const e=n[t];if((!i||void 0!==e)&&(!s||null!==e)){if(typeof e!==r)return!1;if(o&&!o(e))return!1}}return!0}}const pr={requiredString:e=>t=>ar(t)?`${e} is required`:"string"!=typeof t?`${e} must be a string`:0===t.trim().length?`${e} cannot be empty`:void 0,maxLength:(e,t)=>n=>{if(!or(n))return"string"!=typeof n?`${e} must be a string`:n.length>t?`${e} must be at most ${t} characters`:void 0},positiveInteger:e=>t=>{if(!ar(t))return"number"==typeof t&&Number.isInteger(t)?t<1?`${e} must be a positive integer`:void 0:`${e} must be an integer`},requiredPositiveInteger:e=>t=>ar(t)?`${e} is required`:"number"==typeof t&&Number.isInteger(t)?t<1?`${e} must be a positive integer`:void 0:`${e} must be an integer`,enumValue:(e,t)=>n=>{if(!ar(n))return t.includes(n)?void 0:`${e} must be one of: ${t.join(", ")}`},requiredEnumValue:(e,t)=>n=>ar(n)?`${e} is required`:t.includes(n)?void 0:`${e} must be one of: ${t.join(", ")}`,isoDate:e=>t=>{if(!ar(t))return"string"!=typeof t?`${e} must be a string`:bn(t)?void 0:`${e} must be a valid ISO 8601 date string`},walletAddress:(e,t=!1)=>n=>ar(n)?t?`${e} is required`:void 0:"string"!=typeof n?`${e} must be a string`:Cn(n)?void 0:`${e} must be a valid wallet address`};function Er(e){return t=>{const n=[],r=t;for(const t of e){const{field:e,required:s,type:i,validator:o}=t,a=r[e];if(s){if(ar(a)){n.push(`${e} is required`);continue}if("string"===i){if("string"!=typeof a){n.push(`${e} must be a string`);continue}if(0===a.trim().length){n.push(`${e} is required`);continue}}}if(!ar(a))if(void 0===i||typeof a===i){if(void 0!==o){const e=o(a,r);null!=e&&""!==e&&n.push(e)}}else n.push(`${e} must be a ${i}`)}return n}}function Ar(e){return""===e||0===e.trim().length}function vr(e,t,n){if(!ar(e)){if("string"!=typeof e)throw Yt(t,"a string",e,t);if(e.length>n)throw new kt(`${t} must be at most ${n} characters`,t,wt.TOO_LARGE)}}function Tr(e,t){ar(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 Yt(t,"a date",e,t);if(isNaN(n.getTime()))throw new kt(`${t} must be a valid date`,t,wt.INVALID_FORMAT)}(e,t)}function yr(e,t,n){try{Yn(e,t)}catch{throw function(e,t,n,r="OPERATION_FAILED"){return new kt(`${e} failed: ${t}`,n,r)}(n,"must be a positive integer",t)}}function Sr(e,t,n="status"){void 0!==e&&function(e,t,n){const r=Object.values(t);if(!r.includes(e))throw new kt(`${n} must be one of: ${r.join(", ")}`,n,wt.INVALID_FORMAT)}(e,t,n)}class br{constructor(e,t=!1,n){this.http=e,this.logger=new En({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 Ot("JWT authentication required. Call sdk.login() first.")}return this.jwtAuth.getJwtHeaders()}isCalledFromUserCode(){const e=Ft(new Error)??"";return!(!e.includes("expect")&&!e.includes("jest"))||!(!e.includes("tests/")&&!e.includes(".test.ts"))}validatePositiveInteger(e,t,n){yr(e,t,n)}}class Nr{constructor(e=!1,t){this.logger=t||new En({debug:e,context:this.constructor.name})}}class wr extends Nr{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 kr extends wr{constructor(e=!1){super(e)}normalizeKey(e){return gn(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>=kr.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??hn.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY.toString()}has(e){const t=this.normalizeKey(e);return this.cache.has(t)}clear(e){if(void 0!==e&&""!==e){const t=this.normalizeKey(e);this.cache.delete(t)}else super.clear()}dumpAsObject(){const e={};return this.cache.forEach((t,n)=>{e[n]=t}),e}getStats(){const e=this.buildBaseStats(),{cacheSize:t,oldestEntry:n}=this.calculateCacheSizeAndAge();return{...e,totalTokens:e.totalItems,cacheSize:t,oldestEntry:n}}calculateCacheSizeAndAge(){let e=Date.now(),t=0;return this.cache.forEach((n,r)=>{n.lastUpdated<e&&(e=n.lastUpdated);let s=0;s+=2*r.length,void 0!==n.reverseBondingCurveMinFeeFactor&&(s+=8),void 0!==n.reverseBondingCurveMaxFeeFactor&&(s+=8),void 0!==n.reverseBondingCurveNetFeeFactor&&(s+=8),s+=8,void 0!==n.vaultAddress&&""!==n.vaultAddress&&(s+=2*n.vaultAddress.length),void 0!==n.maxSupply&&""!==n.maxSupply&&(s+=2*n.maxSupply.length),void 0!==n.symbol&&""!==n.symbol&&(s+=2*n.symbol.length),s+=32,t+=s}),{cacheSize:t,oldestEntry:this.cache.size>0?e:0}}getByTokenId(e){const t=`token:${gn(e)}`;return this.cache.get(t)??null}setByTokenId(e,t){const n=`token:${gn(e)}`;this.updateCacheEntry(n,t)}hasByTokenId(e){const t=`token:${gn(e)}`;return this.cache.has(t)}}kr.MAX_CACHE_SIZE=1e4;const _r={MIN_LENGTH:1,MAX_LENGTH:25,PATTERN:/^[a-zA-Z0-9]{1,25}$/,DESCRIPTION:"1-25 letters and digits"},Ir={MIN_LENGTH:1,MAX_LENGTH:50,PATTERN:/^[a-zA-Z0-9]{1,50}$/,DESCRIPTION:"1-50 letters and digits"},Cr={MIN_LENGTH:1,MAX_LENGTH:255,PATTERN:/^[a-zA-Z0-9]{1,255}$/,DESCRIPTION:"1-255 letters and digits"},Dr={MIN_LENGTH:1,MAX_LENGTH:50,PATTERN:/^[\s\S]{1,50}$/,DESCRIPTION:"1-50 characters"},Rr={MIN_LENGTH:1,MAX_LENGTH:100,PATTERN:/^(?![\s\S]*<[^>]*>)[\s\S]{1,100}$/,DESCRIPTION:"1-100 characters without HTML"},Or=100,Mr=100,Lr=50,Ur=100,Fr={COMMENTS_V1:{MAX_LENGTH:2e3},CHAT_MESSAGE:{MIN_LENGTH:1,MAX_LENGTH:500},CHAT_MESSAGES_V1:{MAX_LENGTH:500},BAN_REASON:{MAX_LENGTH:500},DESCRIPTION:{MAX_LENGTH:255},FLAG_DETAILS:{MAX_LENGTH:1e3},CONTENT_ID:{MAX_LENGTH:100}},Pr={CHAT_MESSAGE:{PATTERN:/^chat-\d{13}-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i},CONTENT_REACTION:{MAX_LENGTH:64,PATTERN:/^(msg-\d{13}-[a-f0-9]{32}|chat-\d{13}-[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})$/}},xr=60,Br=31536e3,Gr={MAX_LENGTH:64,PATTERN:/^(galaswap-operation-|galaconnect-operation-)/},$r={PATTERN:/^[a-fA-F0-9]{64}$/,MAX_LENGTH:64},Kr=1,Hr=100,Wr={FULL_NAME:{MIN_LENGTH:2,MAX_LENGTH:20,ALPHABETS_ONLY_PATTERN:/^[a-zA-Z]+(?: [a-zA-Z]+)?$/}},Vr=y.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"),jr=Vr.max(25,"Token name must be at most 25 characters"),qr=y.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"),zr=y.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"),Qr=y.string({message:"Token description is required"}).min(1,"Token description is required").max(500,"Token description must be at most 500 characters"),Xr=y.string().min(1,"Token name must be at least 1 character").max(50,"Token name must be at most 50 characters"),Yr=y.string().min(1,"Search query must be at least 1 character").max(100,"Search query must be at most 100 characters"),Jr=y.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"),Zr=y.string().regex(sr.BACKEND_ADDRESS,"Address must be in format: eth|[40-hex-chars]"),es=y.string().regex(sr.ETH_ADDRESS,"Invalid Ethereum address format"),ts=y.string().refine(e=>Cn(e),"Address must be eth|[40-hex], 0x[40-hex], [40-hex] or client|[identifier] (eth|0x... is not a valid form; a mixed-case address must carry its EIP-55 checksum)").transform(e=>Nn(e)),ns=y.string().refine(e=>/^eth\|(0x)?[0-9a-fA-F]{40}$/.test(e)||/^service\|Token\$Unit\$[A-Z0-9]+\$eth:[0-9a-fA-F]{40}\$launchpad$/.test(e),"Invalid vault address format"),rs=y.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>Hn(e,0)>0,"Amount must be greater than zero"),ss=y.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>Hn(e,0)>=0,"Amount must be zero or greater"),is=y.string().url("Must be a valid URL").regex(/^https?:\/\//,"URL must start with http:// or https://"),os=y.string().optional().refine(e=>void 0===e||""===e||/^https?:\/\/.+\..+/.test(e),"Must be a valid URL if provided"),as=y.number().int("Page must be an integer").min(1,"Page must be at least 1").max(1e3,"Page must be at most 1000").default(1);function cs(e=100){return y.number().int("Limit must be an integer").min(1,"Limit must be at least 1").max(e,`Limit must be at most ${e}`).default(10)}const ls=cs(100),ds=cs(20),us=cs(20),hs=y.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"),gs=y.string().max(255,"Filename must be at most 255 characters"),ms=y.enum(["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"]),fs=y.string().datetime("Must be a valid ISO 8601 date string"),ps=y.number().int("Timestamp must be an integer").min(0,"Timestamp must be non-negative"),Es=y.string().regex(/^0x[a-fA-F0-9]{64}$/,"Private key must be format: 0x + 64 hex characters"),As=y.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"),vs=y.string().regex(/^galaconnect-operation-[a-z0-9-]+$/,"Unique key must be format: galaconnect-operation-{unique-id}"),Ts=[".png",".jpg",".jpeg",".gif",".webp",".svg"],ys=y.object({file:y.union([y.instanceof(File),y.instanceof(Buffer)]),name:gs,size:hs,type:ms}),Ss=y.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"),bs=y.instanceof(Buffer).refine(e=>e.length>=1&&e.length<=10485760,"Buffer size must be between 1 byte and 10MB"),Ns=y.union([Ss,bs]),ws=y.enum([".png",".jpg",".jpeg",".gif",".webp",".svg"]),ks=gs.refine(e=>{const t=e.slice(e.lastIndexOf(".")).toLowerCase();return Ts.includes(t)},`Filename must end with one of: ${Ts.join(", ")}`),_s=y.object({websiteUrl:os,telegramUrl:os,twitterUrl:os,instagramUrl:os,facebookUrl:os,redditUrl:os,tiktokUrl:os}).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"),Is=y.string().min(1,"Token category must not be empty").default("Unit"),Cs=y.string().min(1,"Token collection must not be empty").default("Token"),Ds=y.object({minFeePortion:y.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal string").refine(e=>Hn(e,0)>=.1,"Minimum fee must be >= 0.1").refine(e=>Hn(e,0)<=.5,"Minimum fee must be <= 0.5").default("0.1"),maxFeePortion:y.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal string").refine(e=>Hn(e,0)>=.1,"Maximum fee must be >= 0.1").refine(e=>Hn(e,0)<=.5,"Maximum fee must be <= 0.5").default("0.5")}).refine(e=>Hn(e.maxFeePortion,0)>=Hn(e.minFeePortion,0),{message:"Maximum fee must be >= minimum fee",path:["maxFeePortion"]}),Rs=y.object({tokenName:Vr,tokenSymbol:zr,tokenDescription:Qr,tokenImage:y.union([y.instanceof(File),y.instanceof(Buffer),y.string().url("Token image must be a valid URL")]).optional(),preBuyQuantity:ss.default("0"),websiteUrl:os,telegramUrl:os,twitterUrl:os,instagramUrl:os,facebookUrl:os,redditUrl:os,tiktokUrl:os,tokenCategory:Is,tokenCollection:Cs,reverseBondingCurveConfiguration:Ds.optional(),saleStartTime:y.number().int().positive().optional(),privateKey:Es.optional()}),Os=y.object({file:y.union([y.instanceof(File),y.instanceof(Buffer)]),tokenName:Vr}),Ms=y.enum(yt),Ls=y.object({tokenName:qr.optional(),symbol:zr.optional()}).refine(e=>void 0!==e.tokenName||void 0!==e.symbol,"At least one of tokenName or symbol is required"),Us=y.enum(["NATIVE","MEME"]),Fs=y.enum(["IN","OUT"]),Ps=y.object({from:y.number().int("From timestamp must be an integer").min(173e6,"From timestamp must be at least 173000000"),to:y.number().int("To timestamp must be an integer").min(173e6,"To timestamp must be at least 173000000"),resolution:y.number().int("Resolution must be an integer").min(1,"Resolution must be at least 1"),tokenName:jr}),xs=y.object({tokenName:jr,slippageToleranceFactor:y.number().min(0).max(1).optional(),maxAcceptableReverseBondingCurveFeeSlippageFactor:y.number().min(0).max(1).optional(),privateKey:Es.optional()}),Bs=y.object({offset:y.number().int().min(0).default(0),pageSize:y.number().int().min(1).max(100).default(10)}),Gs=y.object({offset:y.number().int().min(0).default(0),pageSize:y.number().int().min(1).max(20).default(10)}),$s=y.object({offset:y.number().int().min(0).default(0),pageSize:y.number().int().min(1).max(20).default(10)}),Ks=Bs.extend({type:y.enum(["RECENT","POPULAR"]).optional(),tokenName:y.string().min(1).max(50).optional(),search:y.string().min(1).max(100).optional()}),Hs=Gs.extend({tokenName:y.string().min(1).max(50).optional(),search:y.string().min(1).max(100).optional()}),Ws=$s.extend({tradeType:y.enum(["BUY","SELL"]).optional(),tokenName:y.string().min(1).max(50).optional(),userAddress:y.string().refine(Cn,"userAddress must be eth|<40 hex>, 0x<40 hex>, <40 hex> or client|<id> (eth|0x... is not a valid form; a mixed-case address must carry its EIP-55 checksum)").optional(),startDate:y.string().datetime().optional(),endDate:y.string().datetime().optional(),sortOrder:y.enum(["ASC","DESC"]).default("DESC")}),Vs={page:y.number().int().min(1),limit:y.number().int().min(1),total:y.number().int().min(0),totalPages:y.number().int().min(0),hasNext:y.boolean(),hasPrevious:y.boolean()},js=y.object(Vs);function qs(e){return y.object({data:y.array(e),...Vs})}const zs=y.enum(["buy","sell"]),Qs=y.enum(["BUY","SELL"]),Xs=y.object({tradeType:zs,tokenAmount:rs,vaultAddress:ns,userAddress:ts,slippageTolerance:rs.optional(),deadline:y.number().int().positive().optional()}),Ys=y.object({tokenSymbol:zr,nativeTokenQuantity:rs,expectedToken:rs,maxAcceptableReverseBondingCurveFee:ss.default("0").optional()}),Js=y.object({tokenSymbol:zr,tokenQuantity:rs,expectedNativeToken:rs,maxAcceptableReverseBondingCurveFee:ss.default("0").optional()}),Zs=$s.extend({tokenName:Xr.optional()}),ei=y.object({page:y.number().int().min(1).max(1e3).default(1).optional(),limit:y.number().int().min(1).max(20).default(10).optional()}),ti=y.enum(["NATIVE","MEME"]),ni=y.enum(["IN","OUT"]),ri=y.object({type:ti,method:ni,vaultAddress:ns,amount:rs}),si=y.object({nativeTokenQuantity:rs}),ii=y.object({vaultAddress:ns}),oi=y.object({minFeePortion:rs,maxFeePortion:rs}),ai=y.enum(["both","held","created"]),ci=Gs.extend({type:ai.optional(),address:ts.optional(),search:Yr.optional(),tokenName:Xr.optional()}),li=y.object({address:ts.optional(),refresh:y.boolean().optional()}),di=y.object({profileImage:y.string().nullable().optional(),fullName:Jr.optional(),address:ts.optional(),privateKey:Es.optional()}),ui=y.object({file:y.union([y.instanceof(File),y.instanceof(Buffer)]),address:ts.optional(),privateKey:Es.optional()}),hi=y.object({address:ts,tokenId:y.union([y.string(),y.object({collection:y.string(),category:y.string(),type:y.string(),additionalKey:y.string()}),y.object({collection:y.string(),category:y.string(),type:y.string(),additionalKey:y.string(),instance:y.string()})]).optional(),tokenName:Xr.optional(),withExpired:y.boolean().optional()}).refine(e=>void 0!==e.tokenId||void 0!==e.tokenName,"At least one token identifier (tokenId or tokenName) is required");function gi(e){return t=>{const n=e.safeParse(t);return{success:n.success,data:n.success?n.data:void 0,errors:n.success?void 0:n.error.issues.map(e=>e.message)}}}const mi=gi(Vr),fi=gi(zr),pi=gi(Qr),Ei=gi(ts),Ai=gi(ns),vi=gi(rs),Ti=gi(Jr),yi=gi(Yr),Si=gi(Xr),bi=gi(Rs),Ni=gi(_s),wi=gi(Os),ki=gi(Ls),_i=gi(ci),Ii=gi(li),Ci=gi(di),Di=gi(ui),Ri=gi(hi),Oi=gi(Xs),Mi=gi(Ys),Li=gi(Js),Ui=gi(Zs),Fi=gi(ei),Pi=gi(ri),xi=gi(si),Bi=gi(ii);function Gi(e){return bi(e).success}function $i(e){const t=bi(e);return t.success?[]:t.errors??["Unknown validation error"]}function Ki(e){const t=$i(e);if(t.length>0)throw new Error(`LaunchTokenData validation failed:\n${t.map(e=>`- ${e}`).join("\n")}`)}function Hi(e,t){return"string"==typeof e[t]}function Wi(e,t){return void 0===e[t]||"string"==typeof e[t]}function Vi(e,t){return void 0===e[t]||"number"==typeof e[t]}function ji(e,t){switch(t){case"string":return"string"==typeof e;case"number":return"number"==typeof e;case"boolean":return"boolean"==typeof e;case"object":return null!==e&&"object"==typeof e&&!Array.isArray(e);case"array":return Array.isArray(e);case"optional-string":return void 0===e||"string"==typeof e;case"optional-number":return void 0===e||"number"==typeof e;case"optional-boolean":return void 0===e||"boolean"==typeof e;case"optional-object":return void 0===e||null!==e&&"object"==typeof e&&!Array.isArray(e);case"optional-array":return void 0===e||Array.isArray(e);default:return!1}}function qi(e){return t=>{if(null==t||"object"!=typeof t||Array.isArray(t))return!1;const n=t;for(const[t,r]of Object.entries(e)){if(!ji(n[t],r))return!1}return!0}}lr({BUY:"buy",SELL:"sell"});const zi=qi({nativeTokenQuantity:"string"});function Qi(e,t="0"){return function(e,t="0"){if(vn(e))return new I(t);if(I.isBigNumber(e))return e.isNaN()?new I(t):e;try{const n=new I(e);return n.isNaN()||!n.isFinite()?new I(t):n}catch{return new I(t)}}(e,t)}function Xi(e,t){return void 0!==t?Qi(e).toFixed(t):Qi(e).toFixed()}function Yi(e){const t=Qi(e),n=Math.log(1.0001),r=t.toNumber();return Math.log(r)/n}function Ji(e){return Qi(e).isZero()}function Zi(e,t){return Qi(e).isLessThan(Qi(t))}function eo(...e){e.forEach(e=>{if(e.isNaN())throw Jt("value","NaN");if(!e.isFinite())throw Xt("value","finite");if(e.isLessThanOrEqualTo(0))throw Qt("value","0",e.toString())})}function to(...e){e.forEach(e=>{if(e.isNaN())throw Jt("value","NaN");if(!e.isFinite())throw Xt("value","finite");if(e.isLessThan(0))throw Qt("value","0",e.toString())})}function no(e,t,n){if(e.isNaN())throw Jt(t,"NaN");if(!e.isFinite())throw Xt(t,"finite");if(e.isLessThanOrEqualTo(0))throw Qt(t,"0",e.toString())}function ro(e,t,n="0"){const r=Qi(t);return Ji(r)?Qi(n):Qi(e).dividedBy(r)}const so={calculateBuyWithExact(e,t){const n=Hn(e),r=Hn(t),{BASE_PRICE:s,PRICE_SCALING_FACTOR:i,TRADING_FEE_FACTOR:o,GAS_FEE:a}=hn,c=function(e,t){const n=Math.pow(10,t);return Math.ceil(e*n)/n}(s*(Math.exp((r+n)*i)-Math.exp(r*i))/i,8),l=Xi(Qi(c).multipliedBy(o));return{amount:c.toString(),reverseBondingCurveFee:"0",transactionFee:l,gasFee:a}},calculateBuyWithNative(e,t){const n=Hn(e),r=Hn(t),{BASE_PRICE:s,PRICE_SCALING_FACTOR:i,TRADING_FEE_FACTOR:o,GAS_FEE:a}=hn,c=Math.log(n*i/s+Math.exp(r*i))/i-r,l=Xi(Qi(c).multipliedBy(o));return{amount:c.toString(),reverseBondingCurveFee:"0",transactionFee:l,gasFee:a}},calculateSellWithExact(e,t,n,r,s){const i=Hn(e),o=Hn(t),a=Hn(n),{BASE_PRICE:c,PRICE_SCALING_FACTOR:l,TRADING_FEE_FACTOR:d,GAS_FEE:u}=hn,h=c*(Math.exp(o*l)-Math.exp((o-i)*l))/l,g=Qi(h),m=r+o/a*(s-r),f=Xi(g.multipliedBy(m),8),p=Xi(g.multipliedBy(d));return{amount:h.toString(),reverseBondingCurveFee:f,transactionFee:p,gasFee:u}},calculateSellWithNative(e,t,n,r,s){const i=Hn(e),o=Hn(t),a=Hn(n),{BASE_PRICE:c,PRICE_SCALING_FACTOR:l,TRADING_FEE_FACTOR:d,GAS_FEE:u}=hn;if(i>=c*(Math.exp(o*l)-1)/l){const e=Qi(i),t=r+o/a*(s-r),n=Xi(e.multipliedBy(t),8),c=Xi(e.multipliedBy(d));return{amount:o.toString(),reverseBondingCurveFee:n,transactionFee:c,gasFee:u}}const h=o-Math.log(Math.exp(o*l)-i*l/c)/l,g=Qi(i),m=r+o/a*(s-r),f=Xi(g.multipliedBy(m),8),p=Xi(g.multipliedBy(d));return{amount:h.toString(),reverseBondingCurveFee:f,transactionFee:p,gasFee:u}}};function io(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function oo(e,t){if(!function(e){if(!io(e)||"string"!=typeof e.calculatedQuantity)return!1;const t=e.extraFees;return io(t)&&"string"==typeof t.reverseBondingCurve&&"string"==typeof t.transactionFees}(e))throw Vt(`Malformed trade quote from the launchpad backend (${t})`);return{amount:e.calculatedQuantity,reverseBondingCurveFee:e.extraFees.reverseBondingCurve,transactionFee:e.extraFees.transactionFees,gasFee:hn.GAS_FEE}}class ao{validate(e,t={}){const{allowZero:n=!0,minimum:r,maximum:s,maxDecimals:i=ao.MAX_DECIMAL_PLACES,fieldName:o="amount"}=t;if(!ir(e))throw new kt(`${o} cannot be empty or whitespace-only. Provide a valid numeric string.`,o,"INVALID_NUMERIC_STRING");if(/[eE]/.test(e))throw new kt(`${o} cannot use scientific notation. Use standard decimal format (e.g., "1000" instead of "1e3").`,o,"INVALID_NUMERIC_STRING");const a=Hn(e,NaN);if(isNaN(a))throw new kt(`${o} must be a valid numeric string. Received: "${e}"`,o,"INVALID_NUMERIC_STRING");if(!isFinite(a))throw new kt(`${o} must be a finite number. Cannot be Infinity or -Infinity.`,o,"INVALID_NUMERIC_STRING");if(a<0)throw new kt(`${o} must be non-negative. Received: "${e}"`,o,"INVALID_NUMERIC_STRING");if(!n&&0===a)throw new kt(`${o} must be greater than zero. Received: "${e}"`,o,"INVALID_NUMERIC_STRING");const c=Qi(e),l=c.decimalPlaces()??0;if(l>i)throw new kt(`${o} cannot exceed ${i} decimal places. Received: ${l} decimal places`,o,"PRECISION_EXCEEDED");if(void 0!==r&&Zi(c,r))throw new kt(`${o} must be at least ${r}. Received: "${e}"`,o,"BELOW_MINIMUM");if(void 0!==s&&(d=s,Qi(c).isGreaterThan(Qi(d))))throw new kt(`${o} cannot exceed ${s}. Received: "${e}"`,o,"EXCEEDS_MAXIMUM");var d}parseAmount(e,t="0"){return Qi(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 Xi(e,t)}clampAmount(e,t,n){const r=Qi(e),s=Qi(t),i=Qi(n);return function(e,t,n){const r=Qi(e),s=Qi(t),i=Qi(n);return r.isGreaterThanOrEqualTo(s)&&r.isLessThanOrEqualTo(i)}(r,s,i)?Xi(r):Zi(r,s)?Xi(s):Xi(i)}}function co(e,t){throw new kt(e.join("; "),t,"VALIDATION_ERROR")}function lo(e){const t=mi(e);!t.success&&t.errors&&co(t.errors,"tokenName")}function uo(e){const t=Ps.safeParse(e);var n;t.success||co((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 ho(e,t,n=!0){go.validate(e,{fieldName:t,allowZero:n})}ao.MAX_DECIMAL_PLACES=18,ao.MIN_POSITIVE="0.00000000000000001";const go=new ao;class mo{constructor(e,t,n,r="local",s){this.http=e,this.logger=t,this.bundleHttp=n,this.defaultCalculateAmountMode=r,this.launchpadWrites=s,this.metadataCache=new kr}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 Wt("options","an options object");const{tokenName:t,amount:n,type:r,currentSupply:s}=e;return"external"===this.validateAmountCalculationInputs(t,n,r,e.mode,[vt.NATIVE,vt.EXACT],'"native" or "exact"')?this.calculateBuyAmountExternal({tokenName:t,amount:n,type:r}):this.calculateBuyAmountLocal(this.addIfDefined({tokenName:t,amount:n,type:r},"currentSupply",s))}async calculateBuyAmountExternal(e){const{tokenName:t,amount:n,type:r}=e;return this.validateExternalAmountInputs(t,n),"exact"===r?this.fetchBackendQuote({tokenName:t,amount:n,type:"MEME",method:"OUT"},`Failed to calculate buy amount for ${t} (exact tokens)`):this.fetchBackendQuote({tokenName:t,amount:n,type:"NATIVE",method:"IN"},`Failed to calculate buy amount for ${t} (native/GALA budget)`)}async fetchBackendQuote(e,t){return oo(await cn(()=>this.http.get(ut,{...e}),{errorContext:t}),t)}async calculateSellAmount(e){const{tokenName:t,amount:n,type:r,currentSupply:s,maxSupply:i,reverseBondingCurveMaxFeeFactor:o,reverseBondingCurveMinFeeFactor:a}=e;if("external"===this.validateAmountCalculationInputs(t,n,r,e.mode,[vt.EXACT,vt.NATIVE],'"exact" or "native"'))return this.calculateSellAmountExternal({tokenName:t,amount:n,type:r});{const e={tokenName:t,amount:n,type:r,...void 0!==s&&{currentSupply:s},...void 0!==i&&{maxSupply:i},...void 0!==o&&{reverseBondingCurveMaxFeeFactor:o},...void 0!==a&&{reverseBondingCurveMinFeeFactor:a}};return this.calculateSellAmountLocal(e)}}async calculateSellAmountExternal(e){const{tokenName:t,amount:n,type:r}=e;return this.validateExternalAmountInputs(t,n),"exact"===r?this.fetchBackendQuote({tokenName:t,amount:n,type:"MEME",method:"IN"},`Failed to calculate sell amount for ${t} (exact tokens)`):this.fetchBackendQuote({tokenName:t,amount:n,type:"NATIVE",method:"OUT"},`Failed to calculate sell amount for ${t} (native/GALA target)`)}async calculateBuyAmountLocal(e){const{tokenName:t,amount:n,type:r,currentSupply:s}=e;if(!ir(n))throw Ht("amount","Amount");if(r!==vt.NATIVE&&r!==vt.EXACT)throw Yt("type",'"native" or "exact"',r);void 0!==s&&ho(s,"currentSupply");const i=null==s||""===s;if(i&&(null==t||""===t))throw Ht("tokenName","Token name (required when currentSupply is not provided)");null!=t&&""!==t&&lo(t);let o=s;if(i){o=(await this.fetchPoolDetailsForCalculation(t)).currentSupply}return r===vt.EXACT?so.calculateBuyWithExact(n,o):so.calculateBuyWithNative(n,o)}async calculateSellAmountLocal(e){const{tokenName:t,amount:n,type:r,currentSupply:s,maxSupply:i,reverseBondingCurveMaxFeeFactor:o,reverseBondingCurveMinFeeFactor:a}=e;if(!ir(n))throw Ht("amount","Amount");if(r!==vt.EXACT&&r!==vt.NATIVE)throw Yt("type",'"exact" or "native"',r);void 0!==s&&ho(s,"currentSupply");const c=null==s||""===s||null==i||""===i||void 0===o||void 0===a;if(c&&(null==t||""===t))throw Ht("tokenName","Token name (required when currentSupply, maxSupply, or fee factors are not provided)");null!=t&&""!==t&&lo(t);let l=s,d=i,u=o,h=a;if(c&&null!=t&&""!==t){const e=this.metadataCache.getByName(t);d=d??this.metadataCache.getMaxSupply(t),u=u??e?.reverseBondingCurveMaxFeeFactor,h=h??e?.reverseBondingCurveMinFeeFactor,null!=l&&""!==l||(l=await this.fetchCurrentSupply(t));if(void 0===u||void 0===h){const e=await this.fetchPoolDetailsForCalculation(t);u=u??e.reverseBondingCurveMaxFeeFactor,h=h??e.reverseBondingCurveMinFeeFactor}}return r===vt.EXACT?so.calculateSellWithExact(n,l,d,h,u):so.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 Hi(t,"tokenName")&&function(e){return void 0===e.calculateAmountMode||"local"===e.calculateAmountMode||"external"===e.calculateAmountMode}(t)&&Wi(t,"currentSupply")}(e))throw Yt("options","CalculateBuyAmountForGraduationOptions or string (token name)",typeof e);const{tokenName:n,calculateAmountMode:r,currentSupply:s}=t;lo(n);const i=await this.fetchSaleDetails(n),o=s??Xi(Qi(i.maxSupply).minus(i.sellingTokenQuantity)),a=i.sellingTokenQuantity;if("0"===a)throw Ht("tokenName",`Token ${n} is already graduated (no tokens remaining in pool)`);const c={tokenName:n,amount:a,type:"exact",currentSupply:o,...void 0!==r&&{mode:r}};return{...await this.calculateBuyAmount(c),remainingTokens:a}}async launchToken(e){if(void 0!==this.launchpadWrites){return(await this.launchpadWrites.createSale(e)).bundleId}if(!this.bundleHttp)throw jt("Bundle backend client not configured. LaunchToken requires bundleHttp client.","bundleHttp");Ki(e);const t=void 0!==e.preBuyQuantity&&""!==e.preBuyQuantity?e.preBuyQuantity:"0",n=Hn(t);if(0===n&&"0"!==t)throw Jt("preBuyQuantity",t,"Pre-buy quantity");if(n<0)throw Jt("preBuyQuantity",t,"Pre-buy quantity");if(e.reverseBondingCurveConfiguration){const{minFeePortion:t,maxFeePortion:n}=e.reverseBondingCurveConfiguration;tr(t,n,"reverseBondingCurve")}throw new Error("Legacy launchToken signing is unavailable; configure the v6 launchpad write transport.")}async calculateInitialBuyAmount(e){if(!zi(e))throw Wt("data","valid pre-mint calculation data");const t="Failed to calculate initial buy amount";return oo(await cn(()=>this.http.get(ht,{amount:e.nativeTokenQuantity}),{errorContext:t}),t)}async fetchPoolDetailsForCalculation(e){const t=await this.fetchSaleDetails(e),n=Xi(Qi(t.maxSupply).minus(t.sellingTokenQuantity)),r=t.sellingTokenQuantity,s=t.maxSupply;let i=.5,o=.1;const a=t.reverseBondingCurveConfiguration;null!=a?.maxFeePortion&&(i=Vn(a.maxFeePortion,.5)),null!=a?.minFeePortion&&(o=Vn(a.minFeePortion,.1)),void 0===a&&this.logger.debug(`Pool details missing reverse bonding curve configuration for token ${e}, using defaults (min: 0.1, max: 0.5)`);const c=i-o;return this.metadataCache.set(e,{maxSupply:s,reverseBondingCurveMaxFeeFactor:i,reverseBondingCurveMinFeeFactor:o,reverseBondingCurveNetFeeFactor:c}),{currentSupply:n,remainingTokens:r,maxSupply:s,reverseBondingCurveMaxFeeFactor:i,reverseBondingCurveMinFeeFactor:o,reverseBondingCurveNetFeeFactor:c}}async fetchCurrentSupply(e){lo(e);const t=await this.fetchSaleDetails(e),n=Xi(Qi(t.maxSupply).minus(t.sellingTokenQuantity)),r=t.maxSupply;return this.metadataCache.set(e,{maxSupply:r}),n}async fetchPoolDetails(e){lo(e);const t=await this.fetchSaleDetails(e),{reverseBondingCurveConfiguration:n,...r}=t,s=n?.minFeePortion??"0",i=n?.maxFeePortion??"0";return{...r,reverseBondingCurveMinFeePortion:s,reverseBondingCurveMaxFeePortion:i,hasReverseBondingCurveFee:!Ji(s)||!Ji(i),isGraduated:"Finished"===t.saleStatus}}async fetchSaleDetails(e){return ur(e,"tokenName",_r),cn(()=>this.http.get(dt,{tokenName:e}),{errorContext:`Failed to fetch sale details for ${e}`})}validateAmountCalculationInputs(e,t,n,r,s,i){const o=r??this.defaultCalculateAmountMode;if("local"!==o&&"external"!==o)throw Yt("mode",'"local" or "external"',o);if(!ir(e))throw Ht("tokenName","Token name");if(!ir(t))throw Ht("amount","Amount");if("string"!=typeof n||!s.includes(n))throw Yt("type",i,n);return o}validateExternalAmountInputs(e,t){if("string"!=typeof e||""===e)throw new kt("Token name must be a non-empty string","tokenName","INVALID_TOKEN_NAME");if("string"!=typeof t||""===t)throw new kt("Amount must be a non-empty string","amount","INVALID_AMOUNT")}getAddress(){return this.http.getAddress()}formatAddressForBackend(e){return On(e)}validateTokenName(e){return lo(e)}validatePagination(e){void 0!==e.pageSize&&cr(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 fo={REFRESH_THRESHOLD_MS:3e5,DEFAULT_EXPIRY_S:86400,LOGIN_MESSAGE_PREFIX:"Sign in to Launchpad t:",AUTH_HEADER:"Authorization",BEARER_PREFIX:"Bearer "};class po{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 Eo;!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"}(Eo||(Eo={}));class Ao extends Error{constructor(e,t,n,r){super(t),this.type=e,this.originalError=n,this.statusCode=r,this.name="AuthError"}}class vo{constructor(e,t=fo.REFRESH_THRESHOLD_MS){this.tokenState=null,this.STORAGE_KEYS={ACCESS_TOKEN:"lpad_access_token",ACCESS_EXPIRES:"lpad_access_expires",REFRESH_TOKEN:"lpad_refresh_token",REFRESH_EXPIRES:"lpad_refresh_expires"},this.storage=e??new po,this.refreshThresholdMs=t}setToken(e,t){if(!ir(e))throw new Ao(Eo.SIGNATURE_FAILED,"JWT token must be a non-empty string");if("number"!=typeof t)throw new Ao(Eo.SIGNATURE_FAILED,"Token expiration must be a positive finite number (seconds)");if(!Number.isFinite(t))throw new Ao(Eo.SIGNATURE_FAILED,"Token expiration must be a positive finite number (seconds)");if(t<=0)throw new Ao(Eo.SIGNATURE_FAILED,"Token expiration must be a positive finite number (seconds)");const n=Date.now();this.tokenState={token:e.trim(),issuedAt:n,expiresAt:n+1e3*t},this.storage.set(this.STORAGE_KEYS.ACCESS_TOKEN,e.trim()),this.storage.set(this.STORAGE_KEYS.ACCESS_EXPIRES,String(this.tokenState.expiresAt))}async setTokens(e,t,n,r){if(this.setToken(e,t),n){const e=Date.now()+1e3*(r??7776e3);if(!this.tokenState)throw new Ao(Eo.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:`${fo.BEARER_PREFIX}${e}`}getJwtHeaders(){const e=this.getAuthorizationHeader();if(null===e||""===e)throw new Ao(Eo.WALLET_NOT_CONNECTED,"No JWT token available. Call login() first.");return{[fo.AUTH_HEADER]:e}}async getRefreshToken(){if(!this.tokenState?.refreshToken){const e=await this.storage.get(this.STORAGE_KEYS.REFRESH_TOKEN),t=await this.storage.get(this.STORAGE_KEYS.REFRESH_EXPIRES);if(e&&t){const n=Number(t);if(Number.isFinite(n)&&Date.now()<n)return e}return null}return null!==this.tokenState.refreshExpiresAt&&void 0!==this.tokenState.refreshExpiresAt&&(!Number.isFinite(this.tokenState.refreshExpiresAt)||Date.now()>=this.tokenState.refreshExpiresAt)?null:this.tokenState.refreshToken??null}async restoreFromStorage(){const e=await this.storage.get(this.STORAGE_KEYS.ACCESS_TOKEN),t=await this.storage.get(this.STORAGE_KEYS.ACCESS_EXPIRES);if(!e||!t)return!1;const n=Number(t);if(!Number.isFinite(n)||Date.now()>=n)return!1;const r=Date.now();this.tokenState={token:e,issuedAt:r,expiresAt:n};const s=await this.storage.get(this.STORAGE_KEYS.REFRESH_TOKEN),i=await this.storage.get(this.STORAGE_KEYS.REFRESH_EXPIRES);if(s&&i){const e=Number(i);Number.isFinite(e)&&Date.now()<e&&(this.tokenState.refreshToken=s,this.tokenState.refreshExpiresAt=e)}return!0}async clear(){this.tokenState=null,await this.storage.remove(this.STORAGE_KEYS.ACCESS_TOKEN),await this.storage.remove(this.STORAGE_KEYS.ACCESS_EXPIRES),await this.storage.remove(this.STORAGE_KEYS.REFRESH_TOKEN),await this.storage.remove(this.STORAGE_KEYS.REFRESH_EXPIRES)}isValid(){return this.hasToken()&&!this.isExpired()}getDebugInfo(){return{hasToken:this.hasToken(),isExpired:this.isExpired(),shouldRefresh:this.shouldRefresh(),timeUntilExpiryMs:this.getTimeUntilExpiry(),expiresAt:this.tokenState?new Date(this.tokenState.expiresAt):null}}}class To extends vo{getJwtHeaders(){return{}}}async function yo(e,t,n,r){try{return await e()}catch(e){throw r?(r(e,t,n),new Error("Unreachable after error handler")):(n&&n.error(`${t}:`,e),function(e,t,n){n&&n.error(`${t}:`,e);const r=(xt(e)?e.response?.status:void 0)??(e instanceof Rt?e.statusCode:void 0);return Vt(`${t}: ${Ut(e)}`,r,Lt(e)?e:void 0)}(e,t,n))}}function So(e,t){return t instanceof Ao?t:new Ao(Eo.SIGNATURE_FAILED,`${e}: ${Ut(t)}`,Lt(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 bo{constructor(e,t,n,r=!1,s){this.http=e,this.signatureAuth=t,this.jwtAuth=n,this.session=s,this.refreshPromise=null,this.loginPromise=null,this.logger=new En({debug:r,context:"SessionAuthService"})}async loginWithSignature(e){const t=Nn(e.address,"address");if(!ir(e.message)||!ir(e.signature))throw new Ao(Eo.SIGNATURE_FAILED,"A login needs the signed message and its signature.");const n={address:t,message:e.message,signature:e.signature,...void 0!==e.publicKey&&{publicKey:e.publicKey},...void 0!==this.session&&{cookieSession:!0}};return this.postLogin(n)}async loginWithDevBypass(e){return this.postLogin({address:Nn(e,"address"),...void 0!==this.session&&{cookieSession:!0}})}async postLogin(e){try{const t=await this.http.request({method:"POST",url:Z,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 So("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 Ao(Eo.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 yo(async()=>{const e=Date.now(),t=`${fo.LOGIN_MESSAGE_PREFIX}${e}`;this.logger.debug("Generating login signature",{message:t,timestamp:e});const n=await this.signatureAuth.signMessage(t),r=Nn(this.signatureAuth.getAddress(),"address"),s={address:r,message:t,signature:n.signature};this.logger.debug("Sending login request",{address:r,message:t});const i=await this.http.post(Z,s),o=this.extractLoginData(i);return await this.jwtAuth.setTokens(o.accessToken,o.expiresIn,o.refreshToken,o.refreshExpiresIn),this.logger.debug("Login successful",{address:o.address,expiresIn:o.expiresIn,hasRefreshToken:!!o.refreshToken}),o},"SessionAuthService.performLogin",this.logger,e=>{if(e instanceof Ao)throw e;throw new Ao(Eo.SIGNATURE_FAILED,`Login failed: ${Ut(e)}`,Lt(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 Ao(Eo.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:te,data:{},withSession:!1});return this.extractLoginData(e)}catch(e){throw So("Token refresh failed",e)}}async performRefresh(){return yo(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(te,{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(te,{},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 Ao)throw e;throw new Ao(Eo.SIGNATURE_FAILED,`Token refresh failed: ${Ut(e)}`,Lt(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:ee,data:{allDevices:t},withSession:!1,...null!==n&&""!==n&&{headers:{Authorization:`${fo.BEARER_PREFIX}${n}`}}})}catch(e){throw So("Logout failed",e)}return}if(t&&this.jwtAuth.hasToken()&&!this.jwtAuth.isExpired())try{await this.http.post(ee,{allDevices:!0},this.jwtAuth.getJwtHeaders()),this.logger.debug("Logged out from all devices")}catch(e){this.logger.warn(`Failed to revoke all-device sessions (server-side revocation may be incomplete): ${Ut(e)}`)}else t&&this.logger.debug("Skipping server-side revocation: no valid local token available");await this.jwtAuth.clear()}async getSession(){if(!this.jwtAuth.hasToken())throw new Ao(Eo.WALLET_NOT_CONNECTED,"Not authenticated. Call login() first.");return yo(async()=>{const e=await this.http.get(ne,void 0,this.jwtAuth.getJwtHeaders());return this.extractSessionData(e)},"SessionAuthService.getSession",this.logger,e=>{if(e instanceof Ao)throw e;throw new Ao(Eo.SIGNATURE_FAILED,`Failed to get session: ${Ut(e)}`,Lt(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 Ao(Eo.WALLET_NOT_CONNECTED,"The app session has no access token.");return e}if(!this.jwtAuth.hasToken())throw new Ao(Eo.WALLET_NOT_CONNECTED,"Not authenticated. Call login() first.");if(this.jwtAuth.isExpired()){if(await this.jwtAuth.getRefreshToken()){this.logger.debug("Token expired - refresh token available, attempting refresh");try{return(await this.refresh()).accessToken}catch(e){this.logger.warn(`Refresh failed after expiry: ${Ut(e)} - attempting re-login`)}}else this.logger.debug("Token expired - no refresh token available, attempting re-login");return(await this.login()).accessToken}if(this.jwtAuth.shouldRefresh(e)){this.logger.debug("Token near expiry - refreshing");return(await this.refresh()).accessToken}return this.jwtAuth.getToken()}extractLoginData(e){if(e.error)throw new Ao(Eo.SIGNATURE_FAILED,""!==Ut(e)?Ut(e):"Authentication failed");const t=an(e,"No data in authentication response"),{accessToken:n,expiresIn:r,address:s,refreshToken:i,refreshExpiresIn:o}=t;if(!ir(n))throw new Ao(Eo.SIGNATURE_FAILED,"Invalid access token in response");if("number"!=typeof r||r<=0)throw new Ao(Eo.SIGNATURE_FAILED,"Invalid expiration in response");return{accessToken:n,expiresIn:r,address:s,...void 0!==i&&{refreshToken:i},...void 0!==o&&{refreshExpiresIn:o}}}extractSessionData(e){if(e.error)throw new Ao(Eo.SIGNATURE_FAILED,""!==Ut(e)?Ut(e):"Failed to get session");return an(e,"No data in session response")}}class No{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{Jn(e.messagePrefix,"messagePrefix",!1)}catch{throw new Ao(Eo.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=S.fromWallet(this.wallet),this.cachedAddress=this.wallet.address,this.cachedGalaAddress=On(this.wallet.address)}catch(e){if(e instanceof Ao)throw e;if(e instanceof kt&&("INVALID_ADDRESS"===e.code||"INVALID_FORMAT"===e.code||"address"===e.field))throw new Ao(Eo.INVALID_ADDRESS,e.message);if(null!==e&&"object"==typeof e&&"message"in e)throw new Ao(Eo.WALLET_NOT_CONNECTED,e.message);throw e}}setWallet(e){if(void 0!==e){if("object"!=typeof e||!("address"in e))throw new Ao(Eo.WALLET_NOT_CONNECTED,"Invalid wallet: must be an ethers Wallet instance or undefined");if("string"!=typeof e.address||""===e.address)throw new Ao(Eo.INVALID_ADDRESS,"Wallet address is not available");this.walletProvider=S.fromWallet(e),this.cachedAddress=e.address,this.cachedGalaAddress=On(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 t=void 0!==e&&b(e)?p(e.exportPrivateKey()):void 0;this.cachedAddress=t,this.cachedGalaAddress=void 0===t?void 0:On(t)}getWalletProvider(){return this.walletProvider}async cacheAddress(){this.walletProvider&&(this.cachedAddress=await this.walletProvider.getAddress(),this.cachedGalaAddress=Nn(await this.walletProvider.getGalaAddress(),"address"))}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 Ao)throw e;throw new Ao(Eo.SIGNATURE_FAILED,"Failed to generate signature for authentication",Lt(e)?e:new Error(Ut(e)))}}getAddress(){if(this.validateWallet(),this.cachedGalaAddress)return this.cachedGalaAddress;if(this.wallet)return this.formatAddress(this.wallet.address);throw new Ao(Eo.WALLET_NOT_CONNECTED,"Address not available. For external wallets, call cacheAddress() after connecting.")}async getAddressAsync(){return await this.validateWalletAsync(),Nn(await this.walletProvider.getGalaAddress(),"address")}getEthereumAddress(){if(this.validateWallet(),this.cachedAddress)return this.cachedAddress;if(this.wallet)return this.wallet.address;throw new Ao(Eo.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 Ao(Eo.WALLET_NOT_CONNECTED,"Wallet private key not available for @gala-chain signing");return this.wallet.privateKey}if(void 0!==this.walletProvider&&b(this.walletProvider))return this.walletProvider.exportPrivateKey();throw new Ao(Eo.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 Ao(Eo.WALLET_NOT_CONNECTED,"Private key not available with this wallet provider");try{return await this.walletProvider.getPrivateKey()}catch(e){throw new Ao(Eo.WALLET_NOT_CONNECTED,"Private key not available. External wallet providers cannot access private keys. Use PrivateKeyProvider for @gala-chain signing operations.",Lt(e)?e:void 0)}}formatAddress(e){try{return On(e)}catch{throw new Ao(Eo.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 Ao)throw e;throw new Ao(Eo.SIGNATURE_FAILED,Ut(e),Lt(e)?e:new Error(Ut(e)))}}async generateAuthHeaders(e,t){await this.validateWalletAsync();try{const n=Date.now(),r=`${this.messagePrefix} ${t.toUpperCase()} ${e} ${n}`,s=await this.walletProvider.signMessage(r);return{"x-signature":s,"x-address":await this.walletProvider.getGalaAddress(),"x-message":r,"x-timestamp":n.toString()}}catch(e){if(e instanceof Ao)throw e;throw new Ao(Eo.SIGNATURE_FAILED,"Failed to generate authentication headers",Lt(e)?e:new Error(Ut(e)))}}async signTypedData(e,t,n){await this.validateWalletAsync();try{const r={};for(const[e,n]of Object.entries(t))r[e]=n.map(e=>({name:e.name,type:e.type}));return await this.walletProvider.signTypedData(e,r,n)}catch(e){if(e instanceof Ao)throw e;throw new Ao(Eo.SIGNATURE_FAILED,"Failed to sign typed data",Lt(e)?e:new Error(Ut(e)))}}async generateCustomSignature(e){if(!ir(e))throw new Ao(Eo.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 Ao)throw e;throw new Ao(Eo.SIGNATURE_FAILED,"Failed to generate custom message signature",Lt(e)?e:new Error(Ut(e)))}}validateWallet(){if(this.ensureWalletProvider(),!this.walletProvider)throw new Ao(Eo.WALLET_NOT_CONNECTED,"Wallet is required for authentication")}async validateWalletAsync(){if(this.ensureWalletProvider(),!this.walletProvider)throw new Ao(Eo.WALLET_NOT_CONNECTED,"Wallet is required for authentication");if(!this.walletProvider.isConnected())throw new Ao(Eo.WALLET_NOT_CONNECTED,"Wallet is not connected. Call connect() on the wallet provider first.")}}const wo={prod:{...t.prod,bundleBaseUrl:"https://bundle-backend-prod1.defi.gala.com",launchpadBaseUrl:"https://lpad-backend-prod1.defi.gala.com",dexBackendBaseUrl:"https://dex-backend-prod1.defi.gala.com",webSocketUrl:"https://bundle-backend-prod1.defi.gala.com",launchpadFrontendUrl:"https://lpad-frontend-prod1.defi.gala.com"},stage:{...t.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 ko(e){return wo[e]}var _o,Io;!function(e){e.PROCESSED="PROCESSED",e.COMPLETED="COMPLETED",e.SUCCESS="SUCCESS",e.FAILED="FAILED",e.ERROR="ERROR",e.PROCESSING="PROCESSING",e.PENDING="PENDING"}(_o||(_o={})),function(e){e.PENDING="pending",e.PROCESSING="processing",e.COMPLETED="completed",e.FAILED="failed",e.TIMEOUT="timeout"}(Io||(Io={}));const Co={[_o.PROCESSED]:Io.COMPLETED,[_o.COMPLETED]:Io.COMPLETED,[_o.SUCCESS]:Io.COMPLETED,[_o.FAILED]:Io.FAILED,[_o.ERROR]:Io.FAILED,[_o.PROCESSING]:Io.PROCESSING,[_o.PENDING]:Io.PENDING},Do="9.0.0-rc.3",Ro={DEFAULT_PAGE_SIZE:50,MAX_PAGE_SIZE:1e3,SAFETY_MAX_PAGES:1e4,DEFAULT_OFFSET:0,DEFAULT_LIMIT:10,BACKEND_MAX_PAGE_SIZE:20},Oo={MAX_CONCURRENT_FETCHES:5,PAGE_SIZE:50,BACKEND_PAGE_SIZE:20};function Mo(e,t=Ro.DEFAULT_LIMIT){if("number"!=typeof e||!Number.isInteger(e)||e<0)throw Yt("offset","a non-negative integer",e);return Yn(t,"limit"),{offset:e,limit:t}}function Lo(e,t,n){if("number"!=typeof e||!Number.isInteger(e)||e<0)throw Yt("offset","a non-negative integer",e);Yn(t,"limit")}function Uo(e,t=1,n=Ro.BACKEND_MAX_PAGE_SIZE){return Math.max(t,Math.min(n,Math.ceil(e??t)))}function Fo(e,t){if("number"!=typeof e||!Number.isInteger(e))throw Yt("total","a non-negative integer",e);if(e<0)throw zt("total",0,1/0,e);if("number"!=typeof t||!Number.isInteger(t))throw Yt("limit","a non-negative integer",t);if(t<0)throw zt("limit",0,1/0,t);return 0===t?1:0===e?0:Math.ceil(e/t)}function Po(e,t,n){if("number"!=typeof e||!Number.isInteger(e))throw Yt("offset","a non-negative integer",e);if(e<0)throw zt("offset",0,1/0,e);return e+t<n}function xo(e){return"string"==typeof e||null===e?e:void 0}function Bo(e){if("object"!=typeof e||null===e)return{hasNextPage:!1};const t=Reflect.get(e,"hasNextPage"),n=Reflect.get(e,"hasPreviousPage"),r=xo(Reflect.get(e,"endCursor")),s=xo(Reflect.get(e,"startCursor"));return{hasNextPage:!0===t,...void 0===r?{}:{endCursor:r},..."boolean"==typeof n?{hasPreviousPage:n}:{},...void 0===s?{}:{startCursor:s}}}function Go(e,t){const{hasNextPage:n,endCursor:r}=e;if(n&&"string"==typeof r&&""!==r&&r!==t)return r}function $o(e){return"string"==typeof e?e:"number"==typeof e||"boolean"==typeof e||"bigint"==typeof e?String(e):JSON.stringify(e)??""}function Ko(e,t){const n={};void 0!==e.cursor&&(n.cursor=e.cursor);const r=void 0!==e.pageSize?Math.min(e.pageSize,t):t;return n.pageSize=String(r),n}const Ho={tokenName:"lowercase",address:"lowercase",userAddress:"lowercase",assetId:"as given",targetId:"as given",id:"as given",code:"as given"};function Wo(e,t){let n=e;for(const[e,r]of Object.entries(t)){const t=Ho[e];if(void 0===t)throw new Error(`buildEndpoint: path parameter :${e} has no casing in PATH_PARAM_CASING`);n=n.replace(`:${e}`,encodeURIComponent("lowercase"===t?r.toLowerCase():r))}return n}function Vo(e,t,n){for(const r of n){const n=t[r];null!=n&&""!==n&&(e[r]=$o(n))}return e}const jo="x-api-key";class qo extends br{constructor(e,t,n,r=!1,s){super(e,r),this.adminApiKey=t??void 0,this.jwtAuth=n,this.userApiKey=s??void 0}setJwtAuth(e){this.jwtAuth=e}validateTokenName(e,t){!function(e,t){if(!ir(e))throw Ht("tokenName","Token name");const n=gn(e);if(!t.PATTERN.test(n))throw Wt("tokenName",t.DESCRIPTION,"Token name")}(e,t)}validateRequiredString(e,t,n){!function(e,t,n){if(!ir(e))throw Ht(t,n)}(e,t,n)}validateOptionalString(e,t,n,r){!function(e,t,n,r){if(null!=e){if("string"!=typeof e)throw Yt(t,"string",typeof e,n);if(e.length>r)throw Xt(t,r,e.length,n)}}(e,t,n,r)}validateOptionalNumber(e,t,n,r,s,i,o){!function(e,t,n,r,s){if(null!=e){if("number"!=typeof e)throw Yt(t,"number",typeof e,n);if(e<r||e>s)throw zt(t,r,s,e,n)}}(e,t,n,r,s)}validateOptionalDate(e,t,n){!function(e,t,n){if(null!=e&&!bn(e))throw Wt(t,"a valid ISO 8601 date string",n)}(e,t,n)}validatePositiveInteger(e,t,n){yr(e,t,n)}validateStatusFilter(e,t,n="status"){Sr(e,t,n)}buildPaginationParams(e,t){return Ko(e,t)}addOptionalFilterParams(e,t,n){return Vo(e,t,n)}buildEndpoint(e,t){return Wo(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 Ot("Admin API key required for this operation. Set streamAdminApiKey in SDK config.");return{[jo]:this.adminApiKey}}getJwtHeaders(){if(!this.jwtAuth)throw new Ot("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?{[jo]:this.userApiKey}:this.getJwtHeaders()}extractData(e){return sn(e,"Backend request failed",!0),an(e,"No data in backend response")}extractDataOrNull(e){return sn(e,"Backend request failed",!1),e.data??null}async toggleFeature(e,t,n){this.validateTokenName(e,n);const r=this.buildEndpoint(t,{tokenName:e}),s=await this.http.post(r,{},this.getAdminHeaders()),i=this.extractData(s);return{enabled:i.enabled,tokenName:i.tokenName??gn(e)}}}class zo extends qo{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async getSettings(){return{settings:(await this.http.get(at.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(at.UPDATE_SETTINGS,t,this.getDualAuthHeaders())).settings}}async getModeration(e){this.validatePositiveInteger(e.flagId,"flagId","Flag ID");const t=at.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=at.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(at.GET_STATUS,{},this.getDualAuthHeaders())).status}}}const Qo={MODERATOR:"MODERATOR",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MANAGER:"MANAGER",OWNER:"OWNER"},Xo=dr(Qo),Yo={MANAGE_COMMENTS:"MANAGE_COMMENTS",MANAGE_CHAT:"MANAGE_CHAT",BAN_USERS:"BAN_USERS",UNBAN_USERS:"UNBAN_USERS",MANAGE_SIMULCAST:"MANAGE_SIMULCAST",GET_STREAM_KEY:"GET_STREAM_KEY",STOP_STREAM:"STOP_STREAM",RESET_STREAM_KEY:"RESET_STREAM_KEY",START_STREAM:"START_STREAM",DELETE_RECORDINGS:"DELETE_RECORDINGS",MANAGE_STREAM_SETTINGS:"MANAGE_STREAM_SETTINGS"},Jo={MANAGE_COMMUNITY:"MANAGE_COMMUNITY",MANAGE_STREAM:"MANAGE_STREAM",MANAGE_SETTINGS:"MANAGE_SETTINGS",MANAGE_RECORDINGS:"MANAGE_RECORDINGS",VIEW_ANALYTICS:"VIEW_ANALYTICS"},Zo=Object.values(Jo);function ea(e){return Xo.includes(e)}function ta(e){const t=[];return void 0===e.role||null===e.role?t.push("Role is required"):ea(e.role)||t.push(`Invalid role. Must be one of: ${Xo.join(", ")}`),ra(e,t),t}function na(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||ea(e.role)||t.push(`Invalid role. Must be one of: ${Xo.join(", ")}`),ra(e,t,!0),t}function ra(e,t,n=!1){const r=t.length;if(Gt(t,()=>{vr(e.description,"description",255)}),t.length>r&&(t[r]="Description must be 255 characters or less"),void 0!==e.tokenNames){const n=t.length;Gt(t,()=>{if(!Array.isArray(e.tokenNames))throw Yt("tokenNames","an array",e.tokenNames);if(!e.tokenNames.every(e=>"string"==typeof e))throw Yt("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;Gt(t,()=>{Tr(e.expiresAt,"expiresAt")}),t.length>n&&(t[n]="expiresAt must be a valid ISO 8601 date string")}}function sa(e){if(void 0!==e.pageSize&&("number"!=typeof e.pageSize||e.pageSize<1||e.pageSize>Or))throw Yt("pageSize",`number between 1 and ${Or}`,typeof e.pageSize);if(void 0!==e.cursor&&("string"!=typeof e.cursor||""===e.cursor.trim()))throw Yt("cursor","non-empty string",typeof e.cursor)}const ia={[Qo.MODERATOR]:1,[Qo.TECHNICAL_PRODUCER]:1,[Qo.MANAGER]:2,[Qo.OWNER]:3};function oa(e,t){return e===Qo.MANAGER?t!==Qo.OWNER:e===Qo.OWNER||e===t}class aa extends br{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),sn(n,"API key operation failed",!0),e.data}validateApiKeyId(e){this.validatePositiveInteger(e,"id","API key ID")}async create(e){const t=ta(e);if(t.length>0)throw new kt(t.join("; "),"options","VALIDATION_FAILED");this.logger.debug("Creating API key",{role:e.role,delegateAllTokens:e.delegateAllTokens});const n={role:e.role};void 0!==e.description&&(n.description=e.description),void 0!==e.delegateAllTokens&&(n.delegateAllTokens=e.delegateAllTokens),void 0!==e.tokenNames&&e.tokenNames.length>0&&(n.tokenNames=e.tokenNames),void 0!==e.expiresAt&&(n.expiresAt=e.expiresAt),void 0!==e.tokenPermissions&&(n.tokenPermissions=e.tokenPermissions);const r=await this.http.post(he.CREATE,n,this.getJwtHeaders()),s=this.extractData(r);return this.logger.debug("API key created",{id:s.id,keyPrefix:s.keyPrefix}),s}async findAll(e={}){sa(e),this.logger.debug("Listing API keys",e);const t=Ko(e,Or),n=await this.http.get(he.LIST,t,this.getJwtHeaders()),r=this.extractData(n);return this.logger.debug("Listed API keys",{count:r.apiKeys.length,total:r.pageInfo.totalCount}),r}async findOne(e){this.validateApiKeyId(e),this.logger.debug("Getting API key",{id:e});const t=he.GET.replace(":id",String(e)),n=await this.http.get(t,{},this.getJwtHeaders()),r=this.extractData(n);return this.logger.debug("Got API key",{id:r.id,keyPrefix:r.keyPrefix}),r}async update(e,t){this.validateApiKeyId(e);const n=na(t);if(n.length>0)throw new kt(n.join("; "),"options","VALIDATION_FAILED");this.logger.debug("Updating API key",{id:e,options:t});const r={};void 0!==t.role&&(r.role=t.role),void 0!==t.description&&(r.description=t.description),void 0!==t.delegateAllTokens&&(r.delegateAllTokens=t.delegateAllTokens),void 0!==t.tokenNames&&(r.tokenNames=t.tokenNames),void 0!==t.expiresAt&&(r.expiresAt=t.expiresAt),void 0!==t.tokenPermissions&&(r.tokenPermissions=t.tokenPermissions);const s=he.UPDATE.replace(":id",String(e)),i=await this.http.patch(s,r,this.getJwtHeaders()),o=this.extractData(i);return this.logger.debug("Updated API key",{id:o.id,keyPrefix:o.keyPrefix}),o}async revoke(e){this.validateApiKeyId(e),this.logger.debug("Revoking API key",{id:e});const t=he.REVOKE.replace(":id",String(e));await this.http.delete(t,{},this.getJwtHeaders()),this.logger.debug("API key revoked",{id:e})}getRoles(){return[...Xo]}}const ca={ONE_HOUR:3600,ONE_DAY:86400,ONE_WEEK:604800,ONE_MONTH:2592e3},la={VIEWERS:"viewers",CHAT_PARTICIPANTS:"chat_participants"},da=lr(la),ua=fr([{field:"id",type:"number"},{field:"userAddress",type:"string"},{field:"bannedBy",type:"string"},{field:"createdAt",type:"string"},{field:"isPermanent",type:"boolean"},{field:"tokenName",type:"string",nullable:!0},{field:"reason",type:"string",nullable:!0},{field:"expiresAt",type:"string",nullable:!0}]),ha=fr([{field:"tokenName",type:"string",nullable:!0},{field:"isGlobal",type:"boolean"},{field:"isPermanent",type:"boolean"}]),ga=fr([{field:"tokenName",type:"string",nullable:!0},{field:"isGlobal",type:"boolean"}]),ma=fr([{field:"tokenName",type:"string"},{field:"action",type:"string",validator:e=>"CHAT_MESSAGE"===e||"COMMENT"===e||"REACTION"===e}]);function fa(e){return null==e||""===e||"string"==typeof e&&(!Ar(e)&&e.length<=Fr.BAN_REASON.MAX_LENGTH)}function pa(e){return!!ar(e)||"number"==typeof e&&(e>=xr&&e<=Br)}function Ea(e){if(!ir(e.userAddress))throw Ht("userAddress");if(!fa(e.reason))throw new kt(`reason must be at most ${Fr.BAN_REASON.MAX_LENGTH} characters`,"reason","TOO_LONG");if(!pa(e.durationSeconds))throw new kt(`durationSeconds must be between ${xr} and ${Br} seconds`,"durationSeconds","OUT_OF_RANGE")}class Aa extends qo{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async createBan(e){!function(e){ur(e.tokenName,"tokenName",Cr),Ea(e)}(e);const t=this.buildEndpoint(re,{tokenName:e.tokenName}),n=va(e),r=await this.http.post(t,n,this.getMultiAuthHeaders());return{ban:this.extractData(r),tokenName:gn(e.tokenName)}}async removeBan(e){!function(e){if(ur(e.tokenName,"tokenName",Cr),!ir(e.userAddress))throw Ht("userAddress")}(e);const t=wn(e.userAddress,"userAddress"),n=this.buildEndpoint(oe,{tokenName:e.tokenName,userAddress:t}),r=await this.http.delete(n,{},this.getMultiAuthHeaders()),s=this.extractDataOrNull(r);return{removed:s?.removed??!0,tokenName:gn(e.tokenName),userAddress:s?.userAddress??t}}async listBans(e){!function(e){ur(e.tokenName,"tokenName",Cr),cr(0,void 0,Or,e.pageSize)}(e);const t=this.buildEndpoint(se,{tokenName:e.tokenName}),n=this.buildPaginationParams(e,Or);this.addOptionalFilterParams(n,e,["search","name","userAddress"]),void 0!==n.userAddress&&(n.userAddress=_n(n.userAddress));const r=await this.http.get(t,n,this.getMultiAuthHeaders()),s=this.extractData(r);return{items:s.bans,pageInfo:s.pageInfo}}async getBanStatus(e){!function(e){if(ur(e.tokenName,"tokenName",Cr),!ir(e.userAddress))throw Ht("userAddress")}(e);const t=wn(e.userAddress,"userAddress"),n=this.buildEndpoint(ie,{tokenName:e.tokenName,userAddress:t}),r=await this.http.get(n,{},this.getMultiAuthHeaders()),s=this.extractDataOrNull(r);return{banned:null!==s,...null!==s&&{ban:s},tokenName:gn(e.tokenName),userAddress:t}}async getActiveUsers(e){!function(e){if(ur(e.tokenName,"tokenName",Cr),void 0!==e.type&&!da(e.type))throw new kt(`type must be one of: ${Object.values(la).join(", ")}`,"type",wt.INVALID_VALUE)}(e);const t=this.buildEndpoint(ae,{tokenName:e.tokenName}),n={};this.addOptionalFilterParams(n,e,["type","search","name","userAddress"]),void 0!==n.userAddress&&(n.userAddress=_n(n.userAddress));const r=await this.http.get(t,n,this.getMultiAuthHeaders());return this.extractData(r)}async createGlobalBan(e){!function(e){Ea(e)}(e);const t=va(e),n=await this.http.post(ce,t,this.getDualAuthHeaders());return{ban:this.extractData(n)}}async removeGlobalBan(e){!function(e){if(!ir(e.userAddress))throw Ht("userAddress")}(e);const t=wn(e.userAddress,"userAddress"),n=this.buildEndpoint(ue,{userAddress:t}),r=await this.http.delete(n,{},this.getDualAuthHeaders()),s=this.extractDataOrNull(r);return{removed:s?.removed??!0,userAddress:s?.userAddress??t}}async listGlobalBans(e){const t=e??{pageSize:20};!function(e){cr(0,void 0,Or,e.pageSize)}(t);const n=this.buildPaginationParams(t,Or);this.addOptionalFilterParams(n,t,["search","name","userAddress"]),void 0!==n.userAddress&&(n.userAddress=_n(n.userAddress));const r=await this.http.get(le,n,this.getDualAuthHeaders()),s=this.extractData(r);return{items:s.bans,pageInfo:s.pageInfo}}async getGlobalBan(e){!function(e){if(!ir(e.userAddress))throw Ht("userAddress")}(e);const t=wn(e.userAddress,"userAddress"),n=this.buildEndpoint(de,{userAddress:t}),r=await this.http.get(n,{},this.getDualAuthHeaders()),s=this.extractDataOrNull(r);return{banned:null!==s,...null!==s&&{ban:s},userAddress:t}}}function va(e){const t={userAddress:wn(e.userAddress,"userAddress")};return void 0!==e.reason&&(t.reason=e.reason),void 0!==e.durationSeconds&&(t.durationSeconds=e.durationSeconds),t}function Ta(e){return{maxAcceptableReverseBondingCurveFee:qn(e.maxAcceptableReverseBondingCurveFee)}}const ya={BuyNativeDto:class extends N{constructor(e,t,n="0",r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=qn(t),this.expectedToken=zn(n),this.extraFees=Ta(r)}},BuyExactDto:class extends N{constructor(e,t,n,r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=zn(t),this.expectedNativeToken=qn(n),this.extraFees=Ta(r)}},SellExactDto:class extends N{constructor(e,t,n="0",r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=zn(t),this.expectedNativeToken=qn(n),this.extraFees=Ta(r)}},SellNativeDto:class extends N{constructor(e,t,n,r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=qn(t),this.expectedToken=zn(n),this.extraFees=Ta(r)}}};function Sa(e,t,n){let r;Qn(t,0,1,"slippageToleranceFactor");try{r=function(e,t){if(Tn(e)||""===e)throw Ht(t);if(I.isBigNumber(e)){if(e.isNaN())throw Jt(t,"NaN");return e}try{const n=new I(e);if(n.isNaN())throw Jt(t,e);if(!n.isFinite())throw Jt(t,e);return n}catch(n){if(n instanceof kt)throw n;throw Jt(t,e)}}(e,"expectedAmount")}catch{throw new Error(`Invalid expected amount: ${e}. Must be a valid number`)}if(0===t)return e;const s=r.multipliedBy(t);let i;switch(n){case"buy-native":case"sell-exact":i=r.minus(s);break;case"buy-exact":case"sell-native":i=r.plus(s);break;default:throw new Error(`Unknown operation type: ${n}`)}return Qi(i).isLessThan(0)&&(i=Qi(0)),Xi(i)}function ba(e,t){if(!ir(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 Na(e,t,n,r){const s=e?.split?.(t)??[],i=void 0!==n?` (${n})`:"";return new kt(`Invalid ${"|"===t?"pipe":"dollar"}-delimited token: "${e}" (${s.length} parts)${i}. Expected format: "collection${t}category${t}type${t}additionalKey" (4 parts minimum). Received: [${s.map(e=>`"${e}"`).join(", ")}]. Error: ${Ut(r)}`,"token",`INVALID_${"|"===t?"PIPE":"DOLLAR"}_DELIMITED_TOKEN`)}function wa(e,t,n){try{const n=ba(e,t),r=n[n.length-1],s=n[n.length-2],i=n[n.length-3],o=n.slice(0,n.length-3).join(t);if(void 0===o||void 0===i||void 0===s||void 0===r||""===r||""===o||""===i||""===s)throw new Error("All components (collection, category, type, additionalKey) must be non-empty");return{collection:o,category:i,type:s,additionalKey:r}}catch(r){throw Na(e,t,n,r)}}function ka(e){return function(e,t,n){try{const n=ba(e,t),[r,s,i,...o]=n;if(""===r||""===s||""===i)throw new Error("Collection, category, and type must be non-empty");const a=o.join(t);if(void 0===r||void 0===s||void 0===i||""===a)throw new Error("AdditionalKey must be non-empty");return{collection:r,category:s,type:i,additionalKey:a}}catch(r){throw Na(e,t,n,r)}}(e,"|","pipe-delimited token")}class _a 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 Ia={name:"GalaChain"},Ca={name:"ethereum",chainId:1};function Da(e){if("string"!=typeof e)throw new Error("Wallet returned an invalid signature");return e}function Ra(e,t){if(/^eth\|0x/iu.test(e))throw new _a(`${t} must not be written eth|0x...: use eth|<40 hex>, 0x<40 hex> or client|<id>`,"INVALID_SIGNER_OPTIONS",{details:{[t]:e}});return e}function Oa(e){const t={};for(const[n,r]of Object.entries(e))void 0!==r&&(t[n]=Ma(r));return t}function Ma(e){return Array.isArray(e)?e.map(Ma):"object"==typeof e&&null!==e?Oa(e):e}function La(e,t,n,r){return{...e,signature:t,types:n,domain:r}}class Ua extends a{constructor(e){super(e),this.typedDataWallet=new T(e),this.walletAddress=`eth|${this.typedDataWallet.address.slice(2)}`}async signTypedData(e,t){const n=Oa(t),s=r(e,n);return La(n,await this.typedDataWallet.signTypedData(Ia,s,n),s,Ia)}}class Fa extends i{constructor(e,t={}){const{verifyActiveAccount:n,...r}=t;if(super(Ra(e,"walletAddress"),{...r,...void 0!==r.selectAddress&&{selectAddress:Ra(r.selectAddress,"selectAddress")}}),this.typedDataWallet=t.wallet,!0===n){const e=s(this.walletAddress)??(void 0===this.selectAddress?void 0:s(this.selectAddress));if(void 0===e)throw new _a("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=Oa(t),i=r(e,n),a={domain:Ca,types:i,message:n,Primary_type:e},c=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"}),r=Array.isArray(t)?t[0]:void 0;n="string"==typeof r&&""!==r?r:void 0}const r=void 0===n?void 0:s(n);if(void 0===r||r.toLowerCase()!==t.toLowerCase())throw new _a("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}})}(c,this.verifiedKey);const l=await this.typedDataAccount(c);return La(n,Da(await o(c,this.selectAddress??l,()=>c.request({method:"eth_signTypedData",params:[JSON.stringify(a),l]}))),i,Ca)}async typedDataAccount(e){if(A(this.walletAddress))return this.walletAddress;const t=await e.request({method:"eth_accounts"}),n=Array.isArray(t)?t[0]:void 0,r="string"==typeof n?n.replace(/^eth\|/,"0x"):"";if(!A(r))throw new Error("Gala Wallet did not report an Ethereum account to sign typed data with");return r}}class Pa extends n{constructor(e,t,n){super(e,Ra(t,"walletAddress"),n),this.typedDataProvider=e}async signTypedData(e,t){const n=Oa(t),s=this.typedDataProvider,i=await s.getNetwork(),o={name:i.name,chainId:Number(i.chainId)},a=r(e,n),c=await s.getSigner(),l=E(await c.getAddress());if(A(this.walletAddress)&&l!==E(this.walletAddress))throw new _a(`Wallet account ${l} is not the account this signer was created for (${this.walletAddress}); reconnect before signing.`,"WALLET_ACCOUNT_CHANGED",{details:{walletAccount:l,signerAccount:this.walletAddress}});return La(n,Da(await c.signTypedData(o,a,n)),a,o)}static fromEip1193(e,t,n){const r=new v(e);return new Pa({request:t=>e.request(t),getNetwork:()=>r.getNetwork(),getSigner:()=>r.getSigner()},s(t)??t,n)}}function xa(e){const[t,n]=e.split("|",2);if("service"!==t||void 0===n)throw new Error(`Invalid vaultAddress format (expected service|<collection>$<category>$<type>$<additionalKey>$launchpad): ${e}`);const r=n.split("$"),s=r[r.length-1],i=r.slice(0,-1),o=i.slice(0,-3).join("$"),[a,c,l]=i.slice(-3);if("launchpad"!==s||i.length<4||""===o||void 0===a||void 0===c||void 0===l||""===a||""===c||""===l)throw new Error(`Invalid vaultAddress format (expected service|<collection>$<category>$<type>$<additionalKey>$launchpad): ${e}`);return{collection:o,category:a,type:c,additionalKey:l}}function Ba(e){const{collection:t,category:n,type:r}=xa(e),s=`${t}$${n}$${r}$none`,i="GALA$Unit$none$none";return[`$service$${s}$launchpad`,`$tokenBalance$${s}$${e}`,`$tokenBalance$${s}$${e}`,`$tokenBalance$${i}$${e}`,`$tokenBalance$${i}$${e}`]}function Ga(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 $a(e){return`${e.collection}|${e.category}|${e.type}|${e.additionalKey}`}function Ka(e){if("string"==typeof e){if(!ir(t=e)||!t.includes("|"))throw new kt(`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=ka(n.slice(0,4).join("|")),t=n[4]??"0";return{...e,instance:t.length>0?t:"0"}}return{...ka(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(!c(e))throw new kt("Invalid tokenId object format. All fields (collection, category, type, additionalKey) must be non-empty strings","tokenId","INVALID_TOKEN_ID_FORMAT");return e}if(!c(e))throw new kt("Invalid tokenId object format. All fields (collection, category, type, additionalKey) are required","tokenId","INVALID_TOKEN_ID_FORMAT");return{...e,instance:"0"}}throw new kt(`Invalid tokenId type: ${typeof e}. Expected string, TokenClassKey, or TokenInstanceKey`,"tokenId","INVALID_TOKEN_ID_TYPE")}function Ha(e){return function(e){try{if(!ir(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 wa((n.length>=5&&"launchpad"===n[n.length-1]?n.slice(0,-1):n).join("$"),"$","vault address")}catch(t){throw new kt(`Invalid vault address: "${e}". Expected format: "service|Token$Unit$SYMBOL$additionalKey$launchpad". Error: ${Ut(t)}`,"vaultAddress","INVALID_VAULT_ADDRESS_FORMAT")}}(e)}function Wa(e){return{...Ha(e),instance:"0"}}function Va(e){const t=Ha(e);if("Token"!==t.collection)throw new kt(`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 ja,qa,za,Qa,Xa=Object.freeze({__proto__:null,extractTokenSymbolFromVault:Va,normalizeToTokenInstanceKey:Ka,parseVaultAddressToTokenClassKey:Ha,parseVaultAddressToTokenInstance:Wa});class Ya extends Nr{constructor(e=!1){super(e)}generateStringsInstructions(e){try{this.logger.debug("🔧 Generating stringsInstructions for:",e);const t=Ba(e);return this.logger.debug("✅ Generated stringsInstructions:",t),t}catch(e){this.logger.error("❌ Failed to generate stringsInstructions:",e);const t=Ut(e);throw new kt(`Failed to generate stringsInstructions: ${t}`,"vaultAddress","INVALID_VAULT_ADDRESS")}}createGalaInstance(){const e=new w;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(!ir(e))throw Ht("vaultAddress","Vault address");try{const t=Va(e);return this.logger.debug("🔍 Extracted token symbol:",{vaultAddress:e,tokenSymbol:t}),t}catch(e){if(e instanceof kt)throw Wt("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad");throw e}}validateVaultAddress(e){if(!ir(e))throw Ht("vaultAddress","Vault address");if(!e.startsWith("service|Token$Unit$"))throw Wt("vaultAddress",'starting with "service|Token$Unit$"');if(!e.endsWith("$launchpad"))throw Wt("vaultAddress",'ending with "$launchpad"');const t=function(e){if(!ir(e))return null;const t=e.match(/^service\|Token\$Unit\$([^$]+)\$eth:([a-fA-F0-9]{40})\$launchpad$/);if(!t)return null;const n=t[1],r=t[2];return void 0===n||void 0===r?null:{tokenSymbol:n,creatorAddress:r.toLowerCase()}}(e);if(!t)throw Wt("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 Wt("vaultAddress","containing a 1-10 letter token symbol (case insensitive)");return this.logger.debug("✅ Vault address validation passed:",e),!0}generateTokenClassKeyString(e,t,n,r){return`${e}$${t}$${n}$${r}`}parseTokenClassKeyString(e){try{return wa(e,"$","dollar-delimited token")}catch(e){if(e instanceof kt)throw Wt("stringKey","format: collection$category$type$additionalKey (4 parts)");throw e}}}function Ja(e){return"object"==typeof e&&null!==e?e:void 0}class Za extends br{constructor(e,t,n=!1,r,i,o=.05,a=.01,c){if(super(e,n),this.tokenResolver=t,this._walletProvider=r,this.userAddress=i,this.defaultSlippageToleranceFactor=o,this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor=a,this.sellFeeCeiling=c,this.bundleEndpoint="/bundle",null!==this._walletProvider&&void 0!==this._walletProvider&&null!=i){const e=Ja(this._walletProvider),t=e?.privateKey;if("string"==typeof t)this.signer=new Ua(t);else if(function(e){const t=Ja(e);return"function"==typeof t?.request}(this._walletProvider)&&void 0!==this.userAddress){const e=Nn(this.userAddress,"userAddress");this.signer=new Pa(this._walletProvider,s(e)??e)}this.tokenKeyService=new Ya(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 ln(()=>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:rn(n),error:n.error}),this.handleBundleResponse(n))}catch(e){if(e instanceof kt)return{success:!1,error:Ut(e)};throw e}}validateBundleData(e){if(null==e)throw Ht("bundleData","Bundle data");if(null===e.signedDto||void 0===e.signedDto)throw Ht("signedDto","Signed DTO");if(!ir(e.method))throw Ht("method","Method name");if(!Array.isArray(e.stringsInstructions))throw Wt("stringsInstructions","an array of resource tracking strings");if(0===e.stringsInstructions.length)throw new kt("stringsInstructions cannot be empty","stringsInstructions","EMPTY_ARRAY");const t=["BuyWithNative","BuyExactToken","SellExactToken","SellWithNative"];if(!t.includes(e.method))throw Wt("method",`one of: ${t.join(", ")}`);e.stringsInstructions.forEach((e,t)=>{if(!ir(e))throw new kt(`stringsInstructions[${t}] must be a non-empty string`,`stringsInstructions[${t}]`,"INVALID_INSTRUCTION");if("string"!=typeof(n=e)||!n.includes("$"))throw new kt(`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=on(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(xt(e)&&null!==e.response&&void 0!==e.response){const t=on(e.response);if(null!=t&&"object"==typeof t){const e=t;if(null!==e.error&&void 0!==e.error)return"string"==typeof e.error?e.error:JSON.stringify(e.error);if(null!==e.message&&void 0!==e.message)return"string"==typeof e.message?e.message:JSON.stringify(e.message)}}return Ut(e)??"Unknown bundle transaction error"}async getBundlerTransactionResult(e){try{if(!ir(e))throw Ht("transactionId","Transaction ID");let t;this.logger.debug("🔍 Checking bundler transaction result:",e);try{t=await ln(()=>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 kt)return{success:!1,error:Ut(e)};throw e}}async cancelTransaction(e){try{if(!ir(e))throw Ht("transactionId","Transaction ID");let t;this.logger.debug("🚫 Cancelling transaction:",e);try{t=await ln(()=>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 kt)return{success:!1,error:Ut(e)};throw e}}async getHealthStatus(){this.logger.debug("🏥 Checking bundle service health");try{const e=await ln(()=>this.http.get(`${this.bundleEndpoint}/health`),{errorContext:"Bundle service health check failed",logger:this.logger});return null==e?{success:!1,error:"No response from bundle service health check"}:(this.logger.debug("💚 Bundle service health:",e),{success:!0,data:e})}catch(e){return{success:!1,error:this.formatErrorMessage(e)}}}async buyToken(e){this.ensureTradingServicesAvailable();const{tokenName:t,amount:n,type:r,expectedAmount:s}=e,{effectiveSlippageFactor:i,effectiveMaxFee:o,vaultAddress:a}=await this.prepareTradingOperation(t,e.maxAcceptableReverseBondingCurveFee,e.maxAcceptableReverseBondingCurveFeeSlippageFactor,e.slippageToleranceFactor);if("native"===r){if(null==s||""===s)throw new kt("expectedAmount is required for native buy operations. Use getBuyTokenAmount() first to calculate expected tokens.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Sa(s,i,"buy-native");this.logger.debug("BuyNative slippage applied:",{originalExpectedTokens:s,slippageFactor:i,adjustedMinTokens:e});const t=new ya.BuyNativeDto(a,n,e,{maxAcceptableReverseBondingCurveFee:o});return await this.executeBundleTransaction(t,"BuyWithNative",a)}{if(null==s||""===s)throw new kt("expectedAmount is required for exact buy operations. Use getBuyTokenAmount() first to calculate expected GALA cost.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Sa(s,i,"buy-exact");this.logger.debug("BuyExact slippage applied:",{originalExpectedGalaCost:s,slippageFactor:i,adjustedMaxGalaCost:e});const t=new ya.BuyExactDto(a,n,e,{maxAcceptableReverseBondingCurveFee:o});return await this.executeBundleTransaction(t,"BuyExactToken",a)}}async sellToken(e){this.ensureTradingServicesAvailable();const{tokenName:t,amount:n,type:r,expectedAmount:s}=e,{effectiveSlippageFactor:i,effectiveMaxFee:o,vaultAddress:a}=await this.prepareTradingOperation(t,e.maxAcceptableReverseBondingCurveFee,e.maxAcceptableReverseBondingCurveFeeSlippageFactor,e.slippageToleranceFactor),c=async()=>void 0===e.maxAcceptableReverseBondingCurveFee?this.defaultSellFeeCeiling(e,a):o;if("exact"===r){if(null==s||""===s)throw new kt("expectedAmount is required for exact sell operations. Use getSellTokenAmount() first to calculate expected GALA.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Sa(s,i,"sell-exact");this.logger.debug("SellExact slippage applied:",{originalExpectedGala:s,slippageFactor:i,adjustedMinGala:e});const t={maxAcceptableReverseBondingCurveFee:await c()},r=new ya.SellExactDto(a,n,e,t);return await this.executeBundleTransaction(r,"SellExactToken",a)}{if(null==s||""===s)throw new kt("expectedAmount is required for native sell operations. Use getSellTokenAmount() first to calculate tokens to sell.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Sa(s,i,"sell-native");this.logger.debug("SellNative slippage applied:",{originalExpectedTokensToSell:s,slippageFactor:i,adjustedMaxTokensToSell:e});const t={maxAcceptableReverseBondingCurveFee:await c()},r=new ya.SellNativeDto(a,n,e,t);return await this.executeBundleTransaction(r,"SellWithNative",a)}}async prepareTradingOperation(e,t,n,r){const{effectiveSlippageFactor:s,effectiveMaxFee:i}=this.calculateEffectiveSlippage(t,n,r),o=await this.resolveTokenNameToVault(e);if(null==o)throw Kt(e);return{effectiveSlippageFactor:s,effectiveMaxFee:i,vaultAddress:o}}async defaultSellFeeCeiling(e,t){if(void 0===this.sellFeeCeiling)throw jt("Cannot quote the reverse bonding curve fee for this sell. Pass maxAcceptableReverseBondingCurveFee.","maxAcceptableReverseBondingCurveFee");return this.sellFeeCeiling({method:"exact"===e.type?"SellExactToken":"SellWithNative",vaultAddress:t,quantity:e.amount,tokenName:e.tokenName,feeSlippageFactor:e.maxAcceptableReverseBondingCurveFeeSlippageFactor??this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor})}calculateEffectiveSlippage(e,t,n){const r=n??this.defaultSlippageToleranceFactor,s=t??this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor;let i=e??"0";return null!=e&&(i=Sa(e,s,"buy-exact"),this.logger.debug("Reverse bonding curve fee slippage applied:",{baseFee:e,slippageFactor:s,adjustedMaxFee:i})),{effectiveSlippageFactor:r,effectiveFeeSlippageFactor:s,effectiveMaxFee:i}}ensureTradingServicesAvailable(){if(!this.signer||!this.tokenKeyService)throw jt("Trading services not available. BundleService requires walletProvider and userAddress for trading operations.","walletProvider");if(null===this.userAddress||void 0===this.userAddress)throw Ht("userAddress","User address")}async executeBundleTransaction(e,t,n){this.ensureTradingServicesAvailable();try{e.uniqueKey=`galaswap-operation-${Date.now()}_${k().replace(/-/gu,"").substring(0,26)}`;const r=await this.signer.signObject(t,e),s=this.tokenKeyService.generateStringsInstructions(n),i={stringsInstructions:s,method:t,signedDto:r};this.logger.debug("📦 Bundle transaction data:",{method:t,stringsInstructions:s,dtoKeys:Object.keys(r)});const o=await this.submitTransaction(i);if(o.success){const e=on(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 a=o.error;throw new Mt("string"==typeof a?a:"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 ec extends br{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(At),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"}(ja||(ja={})),function(e){e.INAPPROPRIATE_CONTENT="INAPPROPRIATE_CONTENT",e.SPAM="SPAM",e.HARASSMENT="HARASSMENT",e.SCAM="SCAM",e.OTHER="OTHER"}(qa||(qa={})),function(e){e.PENDING="PENDING",e.DISMISSED="DISMISSED",e.ACTIONED="ACTIONED"}(za||(za={})),function(e){e.DELETE_CONTENT="DELETE_CONTENT",e.BAN_USER="BAN_USER",e.DELETE_AND_BAN="DELETE_AND_BAN"}(Qa||(Qa={}));const tc={[qa.INAPPROPRIATE_CONTENT]:"Inappropriate Content",[qa.SPAM]:"Spam",[qa.HARASSMENT]:"Harassment",[qa.SCAM]:"Scam",[qa.OTHER]:"Other"},nc={[za.PENDING]:"Pending",[za.DISMISSED]:"Dismissed",[za.ACTIONED]:"Actioned"},rc={[Qa.DELETE_CONTENT]:"Delete Content",[Qa.BAN_USER]:"Ban User",[Qa.DELETE_AND_BAN]:"Delete & Ban"},sc={[ja.CHAT_MESSAGE]:"Chat Message",[ja.COMMENT]:"Comment",[ja.STREAM]:"Stream",[ja.RECORDING]:"Recording"},ic=500,oc=lr(ja),ac=lr(qa),cc=lr(za),lc=lr(Qa),dc=fr([{field:"id",type:"number"},{field:"tokenName",type:"string"},{field:"contentType",type:"string",validator:oc},{field:"contentId",type:"string"},{field:"reporterAddress",type:"string"},{field:"reportedUserAddress",type:"string"},{field:"status",type:"string",validator:cc}]),uc={TOKEN_NAME:_r,TOKEN_NAME_FILTER:Ir,CONTENT_ID:Fr.CONTENT_ID,DETAILS:Fr.FLAG_DETAILS,PAGINATION:{MAX_LIMIT:Or}};function hc(e,t,n="tokenName"){ur(e,n,t)}function gc(e){if(void 0!==e.contentType&&!oc(e.contentType))throw Wt("contentType",`one of: ${Object.values(ja).join(", ")}`,"Content type");if(void 0!==e.status&&!cc(e.status))throw Wt("status",`one of: ${Object.values(za).join(", ")}`);if(void 0!==e.reason&&!ac(e.reason))throw Wt("reason",`one of: ${Object.values(qa).join(", ")}`);if(void 0!==e.reporterAddress&&!ir(e.reporterAddress))throw Yt("reporterAddress","a non-empty string",typeof e.reporterAddress);if(void 0!==e.reporterAddress&&Bn(e.reporterAddress,"reporterAddress"),void 0!==e.reportedUserAddress&&!ir(e.reportedUserAddress))throw Yt("reportedUserAddress","a non-empty string",typeof e.reportedUserAddress);void 0!==e.reportedUserAddress&&Bn(e.reportedUserAddress,"reportedUserAddress"),cr(0,void 0,uc.PAGINATION.MAX_LIMIT,e.pageSize)}class mc extends qo{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async createFlag(e){!function(e){if(hc(e.tokenName,uc.TOKEN_NAME),void 0===e.contentType)throw Ht("contentType","Content type");if(!oc(e.contentType))throw Wt("contentType",`one of: ${Object.values(ja).join(", ")}`,"Content type");if(!ir(e.contentId))throw Ht("contentId","Content ID");if(e.contentId.length>uc.CONTENT_ID.MAX_LENGTH)throw Xt("contentId",uc.CONTENT_ID.MAX_LENGTH,e.contentId.length,"Content ID");if(!ir(e.reportedUserAddress))throw Ht("reportedUserAddress","Reported user address");if(Bn(e.reportedUserAddress,"reportedUserAddress"),!(e.contentType!==ja.STREAM&&e.contentType!==ja.RECORDING||void 0!==e.reason&&null!==e.reason))throw Ht("reason","Reason");if(void 0!==e.reason&&!ac(e.reason))throw Wt("reason",`one of: ${Object.values(qa).join(", ")}`,"Reason");if(void 0!==e.details&&!ir(e.details))throw Yt("details","a non-empty string",typeof e.details);if(void 0!==e.details&&e.details.length>uc.DETAILS.MAX_LENGTH)throw Xt("details",uc.DETAILS.MAX_LENGTH,e.details.length)}(e);const t={tokenName:e.tokenName,contentType:e.contentType,contentId:e.contentId,reportedUserAddress:kn(e.reportedUserAddress,"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(ye.CREATE,t,this.getMultiAuthHeaders());return{flag:this.extractData(n).flag}}async listFlags(e){return function(e){hc(e.tokenName,uc.TOKEN_NAME_FILTER),gc(e)}(e),this.fetchFlagList(e)}async listGlobalFlags(e={}){return function(e){void 0!==e.tokenName&&hc(e.tokenName,uc.TOKEN_NAME_FILTER),gc(e)}(e),this.fetchFlagList(e)}async dismissFlag(e){!function(e){if(void 0===e.flagId||null===e.flagId)throw Ht("flagId","Flag ID");try{Yn(e.flagId,"flagId")}catch{throw Wt("flagId","a positive integer","Flag ID")}}(e);const t=ye.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 Ht("flagId","Flag ID");try{Yn(e.flagId,"flagId")}catch{throw Wt("flagId","a positive integer","Flag ID")}if(void 0===e.action)throw Ht("action","Action");if(!lc(e.action))throw Wt("action",`one of: ${Object.values(Qa).join(", ")}`,"Action")}(e);const t=ye.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=Ko(e,Or);Vo(t,e,["tokenName","contentType","status","reason","reporterAddress","reportedUserAddress"]);for(const e of["reporterAddress","reportedUserAddress"]){const n=t[e];void 0!==n&&(t[e]=kn(n,e))}const n=await this.http.get(ye.LIST,t,this.getMultiAuthHeaders()),r=this.extractData(n);return{items:r.flags,pageInfo:r.pageInfo}}}const fc=["heart","fire","laugh","wow","thumbs_up"],pc={heart:"❤️",fire:"🔥",laugh:"😂",wow:"😮",thumbs_up:"👍"};class Ec extends qo{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}validateMessageId(e){if(!ir(e))throw Ht("messageId","Message ID");if(Xn(e,Pr.CONTENT_REACTION.MAX_LENGTH,"messageId"),!Pr.CONTENT_REACTION.PATTERN.test(e))throw Wt("messageId","msg-{timestamp}-{uuid} or chat-{timestamp}-{uuid} format","Message ID")}validateReactionType(e){if(!ir(e))throw Ht("reactionType","Reaction type");if(!fc.includes(e))throw Wt("reactionType",`one of: ${fc.join(", ")}`,"Reaction type")}async addContentReaction(e){this.validateMessageId(e.messageId),this.validateReactionType(e.reactionType);const t=ze,n={messageId:e.messageId,reactionType:e.reactionType},r=await this.http.post(t,n,this.getMultiAuthHeaders()),s=this.extractData(r),{created:i,...o}=s;return{data:o,created:i}}async removeContentReaction(e){this.validateMessageId(e.messageId),this.validateReactionType(e.reactionType);const t=`${Qe}?${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 Ac="Token name is required and must be a string";const vc="GALA|Unit|none|none";class Tc extends Nr{constructor(e,t,n,r=!1){super(r),this.dexBackendHttp=e,this.cache=t,this.fetchTokenDetails=n}async fetchLaunchpadTokenSpotPrice(e,t,n){if(!ir(e))throw new kt(Ac,"tokenName",wt.REQUIRED);let r;if(void 0!==n)try{this.logger.debug(`Checking graduation status for token: ${e}`);const t=await n(e);!0===t.isGraduated&&(r=$a(t.sellingToken))}catch(t){this.logger.debug(`Could not determine graduation status for ${e}, falling back to bonding curve: ${Ut(t)}`)}if(void 0!==r)return this.logger.debug(`Token ${e} is graduated, using its swap backend price`),this.fetchMarketUsdPrice(r);try{this.logger.debug(`Using bonding curve calculation for token: ${e}`);const n=await t({tokenName:e,amount:"1",type:"native"}),r=await this.fetchMarketUsdPrice(vc),s=Hn(n.amount,0)/1e18;if(s<=0)throw new kt(`Invalid token amount calculation: ${s}`,"amount","INVALID_CALCULATION");return{symbol:fn(e),price:r.price/s}}catch(t){throw Vt(`Failed to calculate launchpad token spot price for ${e}: ${Ut(t)}`,void 0,Lt(t)?t:void 0)}}async resolveAuthoritativeSymbol(e){if(e===vc)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 Vt("GalaChainService not available for token metadata fetch",500);n=(await this.fetchTokenDetails(e)).symbol}catch(t){throw Vt(`Could not resolve the symbol for ${e} from the token class, and a symbol cannot be derived from the class key: ${Ut(t)}`)}if(""===n)throw Vt(`Token class for ${e} has no symbol`);return this.cache?.setByTokenId(e,{symbol:n}),n}async fetchMarketUsdPrice(e){try{const t=function(e){if(!ir(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 Vt("DEX Backend API client not configured");const n=await this.resolveAuthoritativeSymbol(e),r=await this.dexBackendHttp.request({method:"GET",url:"/market/price",params:{assetIds:t}}),s=null!==r&&"object"==typeof r?r:{},i=Object.keys(s).find(e=>e.toUpperCase()===n.toUpperCase()),o=void 0!==i?s[i]:1===Object.keys(s).length?Object.values(s)[0]:void 0,a=o?.price;if("number"!=typeof a||!Number.isFinite(a))throw new kt(`Invalid price response: no market price for ${t}`,"data","INVALID_RESPONSE");return this.logger.debug(`Swap backend price for ${n}: $${a}`),{symbol:n,price:a}}catch(e){if(e instanceof kt)throw e;throw Vt(`Failed to fetch DEX spot price: ${Ut(e)}`)}}}const yc={BATCH_SIZE:20,FLUSH_INTERVAL_MS:3e3,MAX_QUEUE_SIZE:1e3,FLUSH_ON_PAGE_HIDE:!0,FLUSH_ON_PAGE_UNLOAD:!0,DEBUG:!1},Sc={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"};class bc{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 En({debug:t.debug??!1,context:"EventsBatcherService"}),this.config={batchSize:t.batchSize??yc.BATCH_SIZE,flushIntervalMs:t.flushIntervalMs??yc.FLUSH_INTERVAL_MS,maxQueueSize:t.maxQueueSize??yc.MAX_QUEUE_SIZE,flushOnPageHide:t.flushOnPageHide??yc.FLUSH_ON_PAGE_HIDE,flushOnPageUnload:t.flushOnPageUnload??yc.FLUSH_ON_PAGE_UNLOAD,debug:t.debug??yc.DEBUG},this.setupPageLifecycleListeners()}track(e,t,n){if(this.isShuttingDown)return void this.logger.warn("EventsBatcher is shutting down, ignoring track call");const r={eventType:e,payload:t,clientTimestamp:(new Date).toISOString(),...void 0!==n?.userAddress&&""!==n.userAddress&&{userAddress:wn(n.userAddress,"userAddress")},...void 0!==n?.tokenName&&""!==n.tokenName&&{tokenName:n.tokenName},...void 0!==n?.sessionId&&""!==n.sessionId&&{sessionId:n.sessionId}};this.buffer(r),n?.immediate&&this.scheduleFlush(0)}async flush(){if(0===this.eventBuffer.length)return;this.cancelFlushTimer();const e=this.eventBuffer.splice(0);this.logger.debug(`Flushing ${e.length} events`);try{const t=await this.submitEvents(e);this.totalFlushed+=t.accepted,this.lastFlushTime=Date.now(),this.lastError=void 0,this.logger.debug(`Flush successful, accepted ${t.accepted} events`)}catch(t){throw this.eventBuffer.unshift(...e),this.lastError=t instanceof Error?t.message:String(t),this.logger.error(`Flush failed: ${this.lastError}`),t}}getStats(){const e={bufferedCount:this.eventBuffer.length,totalQueued:this.totalQueued,totalFlushed:this.totalFlushed,totalDropped:this.totalDropped};return void 0!==this.lastFlushTime&&(e.lastFlushTime=this.lastFlushTime),void 0!==this.lastError&&(e.lastError=this.lastError),e}configure(e){void 0!==e.batchSize&&(this.config.batchSize=e.batchSize),void 0!==e.flushIntervalMs&&(this.config.flushIntervalMs=e.flushIntervalMs),void 0!==e.maxQueueSize&&(this.config.maxQueueSize=e.maxQueueSize),void 0!==e.flushOnPageHide&&(this.config.flushOnPageHide=e.flushOnPageHide),void 0!==e.flushOnPageUnload&&(this.config.flushOnPageUnload=e.flushOnPageUnload)}async shutdown(e=5e3){if(this.isShuttingDown=!0,this.removePageLifecycleListeners(),0!==this.eventBuffer.length)try{await Promise.race([this.flush(),new Promise((t,n)=>setTimeout(()=>n(new Error("Flush timeout during shutdown")),e))])}catch(e){this.logger.error(`Shutdown flush failed: ${e instanceof Error?e.message:String(e)}`)}}buffer(e){this.eventBuffer.length>=this.config.maxQueueSize&&(this.eventBuffer.shift(),this.totalDropped++,this.logger.warn("Event buffer full, dropped oldest event")),this.eventBuffer.push(e),this.totalQueued++,this.eventBuffer.length>=this.config.batchSize?this.scheduleFlush(0):this.scheduleFlush(this.config.flushIntervalMs)}scheduleFlush(e){null===this.flushTimer&&(this.flushTimer=setTimeout(()=>{this.flushTimer=null,this.flush().catch(e=>{this.logger.error(`Scheduled flush failed: ${e instanceof Error?e.message:String(e)}`)})},e))}cancelFlushTimer(){null!==this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null)}async submitEvents(e){return await this.httpClient.post("/v1/events",{events:e})}setupPageLifecycleListeners(){"undefined"!=typeof document&&(this.config.flushOnPageHide&&document.addEventListener("visibilitychange",this.handleVisibilityChange),this.config.flushOnPageUnload&&window.addEventListener("beforeunload",this.handleBeforeUnload))}removePageLifecycleListeners(){"undefined"!=typeof document&&(this.config.flushOnPageHide&&document.removeEventListener("visibilitychange",this.handleVisibilityChange),this.config.flushOnPageUnload&&window.removeEventListener("beforeunload",this.handleBeforeUnload))}flushWithBeacon(){if("undefined"==typeof navigator||!navigator.sendBeacon)return;const e=this.eventBuffer.splice(0),t=JSON.stringify({events:e});try{const n=this.getBaseUrl();navigator.sendBeacon(`${n}/v1/events`,t)?(this.totalFlushed+=e.length,this.lastFlushTime=Date.now()):(this.eventBuffer.unshift(...e),this.logger.warn("sendBeacon returned false, events re-buffered"))}catch(t){this.eventBuffer.unshift(...e),this.logger.error(`sendBeacon failed: ${t instanceof Error?t.message:String(t)}`)}}getBaseUrl(){const e=this.httpClient.config;return e?.baseUrl??""}}const Nc=["createdAt","eventType","userAddress"],wc=["last_hour","today","yesterday","last_7_days","last_30_days","custom"],kc=["sdk","frontend","backend","mcp"];function _c(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Ic(e){return"number"==typeof e&&Number.isFinite(e)}function Cc(e){return _c(e)&&Ic(e.id)&&"string"==typeof e.eventType&&_c(e.payload)&&"string"==typeof e.createdAt&&"string"==typeof e.updatedAt}function Dc(e,t,n){if(!t.some(t=>t===e))throw new kt(`${n} must be one of: ${t.join(", ")}`,n,wt.INVALID_VALUE)}class Rc extends qo{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async getEventStats(){return function(e){if(!(_c(e)&&Ic(e.totalEvents)&&Ic(e.todayEvents)&&Ic(e.uniqueUsers)&&Ic(e.uniqueTokens)&&_c(e.eventsByType)))throw Vt("Malformed event statistics response");const t={};for(const[n,r]of Object.entries(e.eventsByType)){if(!Ic(r))throw Vt("Malformed event statistics response");t[n]=r}return{totalEvents:e.totalEvents,todayEvents:e.todayEvents,uniqueUsers:e.uniqueUsers,uniqueTokens:e.uniqueTokens,eventsByType:t}}(await this.http.get(it,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 kt("limit must be an integer from 1 to 100","limit",wt.INVALID_VALUE);if(void 0!==e.page&&(!Number.isInteger(e.page)||e.page<1))throw new kt("page must be a positive integer","page",wt.INVALID_VALUE);void 0!==e.sortBy&&Dc(e.sortBy,Nc,"sortBy"),void 0!==e.sortOrder&&Dc(e.sortOrder,["asc","desc"],"sortOrder"),void 0!==e.timePreset&&Dc(e.timePreset,wc,"timePreset"),void 0!==e.source&&Dc(e.source,kc,"source")}(e);const t={},n=new URLSearchParams;for(const[r,s]of Object.entries(e))if(void 0!==s&&("string"!=typeof s||""!==s)){if(Array.isArray(s)){const e=s.map(String);if(0===e.length)continue;for(const t of 1===e.length?[...e,...e]:e)n.append(r,t);continue}t[r]="userAddress"===r&&"string"==typeof s?wn(s,"userAddress"):s}const r=n.toString(),s=""===r?st:`${st}?${r}`;return function(e){if(!_c(e)||!Array.isArray(e.data)||!_c(e.pagination))throw Vt("Malformed events response");const t=e.pagination,n=e.data;if(!(Ic(t.page)&&Ic(t.limit)&&Ic(t.total)&&Ic(t.totalPages)&&n.every(Cc)))throw Vt("Malformed events response");return{data:n,pagination:{page:t.page,limit:t.limit,total:t.total,totalPages:t.totalPages}}}(await this.http.get(s,t,this.getDualAuthHeaders()))}}function Oc(e){let t;return{requestor:async(n,r)=>{const s="string"==typeof r?.body?JSON.parse(r.body):void 0,{data:i,status:o,headers:a}=await e(n,s);t=i;const c=void 0===i?"":JSON.stringify(i),l="number"==typeof o?o:200;return{ok:l>=200&&l<300,status:l,json:()=>Promise.resolve(i),text:()=>Promise.resolve(c),headers:a??{}}},answer:()=>t}}const Mc=new Set(["GATEWAY_READ_REJECTED","GATEWAY_READ_RESPONSE_INVALID"]);class Lc extends br{constructor(e,t=!1){super(e,t)}async fetchGalaBalance(e){return this.fetchTokenBalance(e)}async fetchTokenBalance(e,t=!1){const n=Nn(e.owner,"owner");try{const{requestor:r}=Oc(async(e,t)=>({data:await this.http.post(e,t)})),s=new l({gatewayBaseUrl:"",httpRequestor:r,requestTimeoutMs:1/0}),{collection:i,category:o,type:a,additionalKey:c}=e,d=await s.fetchTokenBalance({owner:n,tokenClassKey:{collection:i,category:o,type:a,additionalKey:c},includeExpiredHolds:t});return void 0===d?null:function(e){if("0"===e.quantity)return null;const{collection:t,category:n}=e.tokenClassKey,r={quantity:e.quantity,collection:t,category:n,tokenId:$a(e.tokenClassKey)};return e.inUseHolds.length>0&&(r.inUseHolds=[...e.inUseHolds],r.inUseQuantity=e.inUseQuantity),e.lockedHolds.length>0&&(r.lockedHolds=[...e.lockedHolds],r.lockedQuantity=e.lockedQuantity),void 0===r.lockedQuantity&&void 0===r.inUseQuantity||(r.availableQuantity=e.availableQuantity),r}(d)}catch(e){if(d(e)&&Mc.has(e.code))return null;throw Vt(`Failed to fetch token balance from GalaChain: ${Ut(e)}`,void 0,Lt(e)?e:void 0)}}}function Uc(e){if(null==e||"object"!=typeof e)return!1;const t=e;return ir(t.amount)&&(void 0!==t.tokenId||ir(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 Fc(e){if(null==e||"object"!=typeof e)return!1;const t=e;return ir(t.amount)&&(void 0!==t.tokenId||ir(t.tokenName))&&(void 0===t.name||"string"==typeof t.name)}function Pc(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every(Uc)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}function xc(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every(Fc)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}const Bc=100,Gc=100;var $c,Kc;!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"}($c||($c={}));class Hc 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"}(Kc||(Kc={}));class Wc extends Error{constructor(e,t,n){super(e),this.type=t,this.details=n,this.name="TransferError"}}function Vc(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 jc(e,t,n,r="[DEBUG] Token resolution (launchpad)"){const s=await t.resolveTokenToVault(e);if(null!==s){const t=Wa(s);return n.debug(r,{tokenName:e,vaultAddress:s,tokenInstance:{collection:t.collection,category:t.category,type:t.type,instance:t.instance}}),t}throw new kt(`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 qc extends br{constructor(e,t,n,r=!1,s){super(e,r),this.wallet=t,this.tokenResolver=n,this.writer=s,this.nativeSigner=t?new Ua(t.privateKey):void 0}writeIdentity(){return void 0!==this.wallet&&void 0!==this.nativeSigner?{signer:this.nativeSigner,walletAddress:On(this.wallet.address)}:this.writer}}function zc(e,t){const{collection:n,category:r,type:s,additionalKey:i,instance:o}=e;return{tokenClassKey:{collection:n,category:r,type:s,additionalKey:i},instance:o,quantity:t}}const Qc=new Set(["GATEWAY_WRITE_REJECTED","GATEWAY_RESPONSE_INVALID","GATEWAY_HTTP_ERROR"]);function Xc(e,{signer:t,walletAddress:n}){const{requestor:r,answer:s}=Oc((t,n)=>e.postWithMeta(t,n));return{writes:new u({gatewayBaseUrl:"",signer:t,walletAddress:n,httpRequestor:r,requestTimeoutMs:1/0,uniqueKeyPrefix:"galaconnect-operation-"}),answer:s}}async function Yc(e,t,n){let r;try{r=await t(e.writes)}catch(t){throw function(e){return d(e)&&Qc.has(e.code)}(t)&&n(e.answer(),void 0),t}return n(e.answer(),r)}function Jc(e){return void 0===e||""===e?{}:{uniqueKey:e}}const Zc=100,el=100;class tl extends qc{async lockTokens(e){this.validateLockTokensData(e);const t=this.writeIdentity();if(void 0===t)throw new Hc("Wallet required for token lock operations",$c.WALLET_REQUIRED);return yo(async()=>{const n=Xc(this.http,t),r=n.writes.walletAddress,s=[],i=[];let o=r;const a=e.tokens.find(e=>void 0!==e.lockAuthority);void 0!==a?.lockAuthority&&(o=On(a.lockAuthority));const c=e.tokens.find(e=>void 0!==e.expires),l=e.tokens.find(e=>void 0!==e.name);for(const t of e.tokens){const e=await this.resolveTokenEntry(t);i.push(zc(e,t.amount)),s.push({tokenClassKey:{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey},quantity:t.amount,lockAuthority:void 0!==t.lockAuthority?On(t.lockAuthority):o})}return Yc(n,t=>t.lockTokens({tokens:i,lockAuthority:o,...void 0!==c?.expires&&{expires:c.expires},...void 0!==l?.name&&{name:l.name},...Jc(e.uniqueKey)}),(e,t)=>(this.assertLockAnswer(e,"Token lock failed"),this.extractLockResult(e,t,s)))},"Token lock failed",this.logger,t=>{throw this.handleLockError(t,"Token lock failed",e)})}async unlockTokens(e){this.validateUnlockTokensData(e);const t=this.writeIdentity();if(void 0===t)throw new Hc("Wallet required for token unlock operations",$c.WALLET_REQUIRED);return yo(async()=>{const n=[],r=[],s=e.tokens.find(e=>void 0!==e.name);for(const t of e.tokens){const e=await this.resolveTokenEntry(t);r.push(zc(e,t.amount)),n.push({tokenClassKey:{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey},quantity:t.amount})}return Yc(Xc(this.http,t),t=>t.unlockTokens({tokens:r,...void 0!==s?.name&&{name:s.name},...Jc(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{Bt(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 Hc(`${Ut(t)}${n}`,$c.NETWORK_ERROR)}}validateSharedTokenEntry(e,t,n){if(void 0===e.tokenId&&void 0===e.tokenName)throw new Hc("Must provide either tokenId or tokenName for token identification",$c.TOKEN_NOT_FOUND);if(void 0!==e.tokenName)try{mr(e.tokenName,"tokenName",Cr)}catch{throw new Hc("Invalid token name format",$c.TOKEN_NOT_FOUND,{tokenName:e.tokenName})}try{eo(Qi(e.amount))}catch{throw new Hc(Wt(t,"a positive number",n).message,$c.INVALID_AMOUNT,{amount:e.amount})}}validateLockTokensData(e){if(!Pc(e))throw new Hc("Invalid lock data: missing required fields",$c.VALIDATION_ERROR);if(e.tokens.length>Zc)throw new Hc(`Batch size exceeds maximum limit of ${Zc} tokens per lock operation`,$c.VALIDATION_ERROR);for(const t of e.tokens){if(this.validateSharedTokenEntry(t,"lockAmount","Lock amount"),void 0!==t.lockAuthority&&!Un(t.lockAuthority))throw new Hc("Invalid lock authority address format",$c.VALIDATION_ERROR,{lockAuthority:t.lockAuthority});if(void 0!==t.expires)try{Yn(t.expires,"expires")}catch{throw new Hc(Wt("expires","a positive integer (epoch milliseconds)","Expires").message,$c.VALIDATION_ERROR)}}}validateUnlockTokensData(e){if(!xc(e))throw new Hc("Invalid unlock data: missing required fields",$c.VALIDATION_ERROR);if(e.tokens.length>el)throw new Hc(`Batch size exceeds maximum limit of ${el} tokens per unlock operation`,$c.VALIDATION_ERROR);for(const t of e.tokens)this.validateSharedTokenEntry(t,"unlockAmount","Unlock amount")}transactionIdOf(e,t){const n=Array.isArray(e.Data)?e.Data[0]:void 0;return t?.transactionId??n?.transactionId??n?.txnId??n?.TxnId??n?.id??void 0}extractLockResult(e,t,n){const r=this.transactionIdOf(e,t),s=t?.blockNumber;return{...void 0!==r&&{transactionId:r},...void 0!==s&&{blockNumber:s},locked:n}}extractUnlockResult(e,t,n){const r=this.transactionIdOf(e,t),s=t?.blockNumber;return{...void 0!==r&&{transactionId:r},...void 0!==s&&{blockNumber:s},unlocked:n}}handleLockError(e,t,n){if(e instanceof Hc)return e;if(d(e)&&"pre_send"===e.phase)return new Hc(`${t}: ${e.message}`,"SIGNING_FAILED"===(r=e.code)?$c.SIGNATURE_FAILED:"INVALID_TOKEN_REFERENCE"===r?$c.TOKEN_NOT_FOUND:"INVALID_QUANTITY"===r?$c.INVALID_AMOUNT:$c.VALIDATION_ERROR,Vc(n));var r;let s=t,i=$c.NETWORK_ERROR;if(xt(e)){const n=e.response?.data;if("object"==typeof n&&null!==n){const e=n.Message;"string"==typeof e&&e.length>0&&(s=`${t}: ${e}`);const r="string"==typeof e?e.toLowerCase():"";r.includes("insufficient")||r.includes("balance")?i=$c.INSUFFICIENT_BALANCE:r.includes("lock")&&r.includes("not found")?i=$c.LOCK_NOT_FOUND:r.includes("not found")||r.includes("token")?i=$c.TOKEN_NOT_FOUND:r.includes("authority")?i=$c.NOT_LOCK_AUTHORITY:r.includes("expired")&&(i=$c.LOCK_EXPIRED)}}else Lt(e)&&(s=`${t}: ${Ut(e)}`);return new Hc(s,i,Vc(n))}async resolveTokenInstance(e){return yo(async()=>jc(e,this.tokenResolver,this.logger),`Failed to resolve token '${e}'`,this.logger,t=>{if(t instanceof Wc)throw new Hc(Ut(t),$c.TOKEN_NOT_FOUND);throw new Hc(`Failed to resolve token '${e}': ${Ut(t)}`,$c.TOKEN_NOT_FOUND,{tokenName:e})})}async resolveTokenEntry(e){if(void 0!==e.tokenId){const t=Ka(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 Hc("Must provide either tokenId or tokenName for token identification",$c.TOKEN_NOT_FOUND)}}const nl=new Set(["GATEWAY_READ_REJECTED","GATEWAY_READ_RESPONSE_INVALID","TOKEN_CLASS_NOT_FOUND"]);function rl(e){const t=e?.Data;return Array.isArray(t)?t:void 0}class sl extends br{constructor(e,t=!1,n){super(e,t),this.publicAxios=n}async fetchTokenClassFromChain(e){try{const t="string"==typeof e?Ka(e):e,{collection:n,category:r,type:s,additionalKey:i}=t,o={collection:n,category:r,type:s,additionalKey:i},a="Failed to fetch token class from GalaChain";return await this.readPublic(e=>e.fetchTokenClass(o),e=>{if(Bt(e,a),void 0===rl(e)?.[0])throw Vt(`Token not found on GalaChain: ${$a(o)}`,404)},()=>Vt(`Token not found on GalaChain: ${$a(o)}`,404))}catch(e){return this.handleTokenServiceError(e,"Token not found on GalaChain","Failed to fetch token class from GalaChain")}}async fetchTokenClassesWithSupply(e){try{if(null==e||0===e.length)throw Ht("tokenClasses","Token classes array");return await this.readPublic(t=>t.fetchTokenClassesWithSupply(e),e=>{if(Bt(e,"Failed to fetch token classes with supply from GalaChain"),0===(rl(e)?.length??0))throw Vt("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 Ht("publicAxios","Public Axios instance");const r=this.publicAxios,{requestor:s,answer:i}=Oc(async(e,t)=>{const n=await r.post(e,t);return{data:n.data,status:n.status}});try{return await e(new l({gatewayBaseUrl:"",httpRequestor:s,requestTimeoutMs:1/0}))}catch(e){if(d(e)&&nl.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 kt)throw e;if(xt(e)&&404===e.response?.status)throw Vt(t,404,Lt(e)?e:void 0);if(Lt(e)&&"Error"===e.name&&Ut(e).includes("status indicates failure"))throw Vt(Ut(e),400,Lt(e)?e:void 0);const r=Ut(e);if(r.includes("Token not found")){if(e instanceof Error)throw e;throw new Error(r)}throw Vt(`${n}: ${r}`,void 0,Lt(e)?e:void 0)}}function il(e){if(null==e||"object"!=typeof e)return!1;const t=e;return ir(t.amount)&&(void 0!==t.tokenId||ir(t.tokenName))}function ol(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every(il)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}const al=50;var cl;!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"}(cl||(cl={}));class ll extends Error{constructor(e,t,n){super(e),this.type=t,this.details=n,this.name="BurnError"}}const dl={validateAmount(e){const t=Qi(e);try{no(t,"amount")}catch(t){throw new Wc(t.message,Kc.INVALID_AMOUNT,{amount:e})}},validateUniqueKey(e){if(!ar(e)&&ir(e)){if(e.length>Gr.MAX_LENGTH)throw new kt(`Unique key too long. Maximum length: ${Gr.MAX_LENGTH}`);if(!Gr.PATTERN.test(e))throw new Wc('Invalid unique key format. Must start with "galaswap-operation-" or "galaconnect-operation-"',Kc.INVALID_AMOUNT,{uniqueKey:e})}}},ul="gala-transfer-successful",hl="token-transfer-successful",gl="token-locked-successfully",ml="token-unlocked-successfully",fl="transfer-successful-no-id",pl=50;class El extends qc{async transferGala(e){this.validateTransferGalaData(e);const t=this.writeIdentity();if(void 0===t)throw new Wc("Wallet required for GALA transfer operations",Kc.WALLET_REQUIRED);try{const n=On(e.recipientAddress),r=Xc(this.http,t);return await Yc(r,t=>t.transferGala({to:n,quantity:e.amount,...Jc(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 Wc("Wallet required for token transfer operations",Kc.WALLET_REQUIRED);try{const n=On(e.to),r=await this.tokenInstanceOf(e.tokenId,e.tokenName,()=>new Wc("Must provide either tokenId or tokenName for token identification",Kc.TOKEN_NOT_FOUND)),s=Xc(this.http,t);return await Yc(s,t=>t.transferToken({to:n,...zc(r,e.amount),...Jc(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 Wc)throw t;throw new Wc(`Failed to resolve token class key for '${e}': ${Ut(t)}`,Kc.TOKEN_NOT_FOUND,{tokenName:e})}}async burnTokens(e){this.validateBurnTokensData(e);const t=this.writeIdentity();if(void 0===t)throw new ll("Wallet required for token burn operations",cl.WALLET_REQUIRED);try{const n=[];for(const t of e.tokens){const e=await this.tokenInstanceOf(t.tokenId,t.tokenName,()=>new ll("Must provide either tokenId or tokenName for token identification",cl.TOKEN_NOT_FOUND));n.push(zc(e,t.amount))}const r=Xc(this.http,t);return await Yc(r,t=>t.burnTokens({tokens:n,...Jc(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 ir(t.recipientAddress)&&ir(t.amount)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)}(e))throw new kt("Invalid GALA transfer data: missing required fields");if(!Un(e.recipientAddress))throw new Wc("Invalid recipient address format",Kc.INVALID_RECIPIENT,{recipientAddress:e.recipientAddress});dl.validateAmount(e.amount),dl.validateUniqueKey(e.uniqueKey)}validateTransferTokenData(e){if(!function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return ir(t.to)&&ir(t.amount)&&(void 0!==t.tokenId||ir(t.tokenName))&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)}(e))throw new kt("Invalid token transfer data: missing required fields");if(!Un(e.to))throw new Wc("Invalid recipient address format",Kc.INVALID_RECIPIENT,{recipientAddress:e.to});if(!(null!==e.tokenId&&void 0!==e.tokenId||null!==e.tokenName&&void 0!==e.tokenName))throw new Wc("Must provide either tokenId or tokenName for token identification",Kc.TOKEN_NOT_FOUND);if(null!==e.tokenName&&void 0!==e.tokenName)try{mr(e.tokenName,"tokenName",Cr)}catch{throw new Wc("Invalid token name format",Kc.TOKEN_NOT_FOUND,{tokenName:e.tokenName})}dl.validateAmount(e.amount),dl.validateUniqueKey(e.uniqueKey)}validateBurnTokensData(e){if(!ol(e))throw new ll("Invalid burn data: missing required fields",cl.VALIDATION_ERROR);if(e.tokens.length>pl)throw new ll(`Batch size exceeds maximum limit of ${pl} tokens per burn operation`,cl.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 ll("Must provide either tokenId or tokenName for token identification",cl.TOKEN_NOT_FOUND);const e=Qi(t.amount);try{eo(e)}catch{throw new ll("Burn amount must be a positive number",cl.INVALID_AMOUNT,{amount:t.amount})}}}async tokenInstanceOf(e,t,n){if(null!=e){const t=Ka(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 jc(e,this.tokenResolver,this.logger,`[DEBUG] Token resolution for '${e}' (launchpad):`)}catch(t){if(t instanceof Wc)throw t;throw new Wc(`Failed to resolve token '${e}': ${Ut(t)}`,Kc.TOKEN_NOT_FOUND,{tokenName:e})}}extractTransferResult(e,t,n){if(null==e)throw new Wc("No response from GalaChain transfer service",Kc.NETWORK_ERROR);const r=t?.blockNumber,s="object"==typeof e&&"Status"in e;s&&Bt(e,"Extract transaction ID");const i=s&&"Data"in e,o=t?.transactionId;if(void 0!==o)return{transactionId:o,...void 0!==r?{blockNumber:r}:{}};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!==r?{blockNumber:r}:{}}}}let e=fl;if(t.Data.length>0)switch(n){case"gala":e=ul;break;case"token":e=hl;break;case"lock":e=gl;break;case"unlock":e=ml}return{transactionId:e,...void 0!==r?{blockNumber:r}:{}}}}throw new Wc("Operation succeeded but transaction ID could not be extracted (missing x-transaction-id header and body fields)",Kc.NETWORK_ERROR)}burnResultOf(e,t){if(null==e)throw new ll("No response from GalaChain burn service",cl.NETWORK_ERROR);try{Bt(e,"Token burn operation")}catch(e){throw new Rt(Ut(e),500)}return this.extractBurnResult(e,t)}extractBurnResult(e,t){const n=[];if(null!==e.Data&&void 0!==e.Data&&Array.isArray(e.Data))for(const t of e.Data)n.push({collection:t.collection??"",category:t.category??"",type:t.type??"",additionalKey:t.additionalKey??"",instance:t.instance??"0",quantity:t.quantity??"0",burnedBy:t.burnedBy??""});const r=Array.isArray(e.Data)?e.Data[0]:void 0,s=t?.transactionId??r?.transactionId??r?.txnId??r?.TxnId??r?.id??void 0,i=t?.blockNumber;return{...void 0!==s&&{transactionId:s},...void 0!==i&&{blockNumber:i},burned:n}}handleTransferError(e,t,n){if(e instanceof Wc)return e;if(e instanceof kt)return new Wc(Ut(e),Kc.INVALID_AMOUNT);if(d(e)&&"pre_send"===e.phase)return new Wc(e.message,"SIGNING_FAILED"===(r=e.code)?Kc.SIGNATURE_FAILED:"INVALID_WALLET_ADDRESS"===r?Kc.INVALID_RECIPIENT:"INVALID_TOKEN_REFERENCE"===r?Kc.TOKEN_NOT_FOUND:Kc.INVALID_AMOUNT);var r;if(xt(e)&&e.response){const t=e.response.status,r=e.response.data;if(400===t){const e=r?.message;return new Wc(("string"==typeof e?e:void 0)??"Invalid transfer request",Kc.INVALID_AMOUNT)}if(403===t)return new Wc("Insufficient balance for transfer",Kc.INSUFFICIENT_BALANCE);if(404===t){const e={};return"tokenName"in n&&(e.tokenName=n.tokenName),new Wc("Token not found",Kc.TOKEN_NOT_FOUND,e)}}if("object"==typeof e&&null!==e&&"code"in e&&("ECONNABORTED"===Pt(e)||"ETIMEDOUT"===Pt(e)))return new Wc("Transfer request timed out",Kc.NETWORK_ERROR);const s=""!==Ut(e)?Ut(e):t;return new Wc(s,Kc.NETWORK_ERROR)}handleBurnError(e,t,n){if(e instanceof ll)return e;if(d(e)&&"pre_send"===e.phase)return new ll(`${t}: ${e.message}`,"SIGNING_FAILED"===(r=e.code)?cl.SIGNATURE_FAILED:"INVALID_TOKEN_REFERENCE"===r?cl.TOKEN_NOT_FOUND:"INVALID_QUANTITY"===r?cl.INVALID_AMOUNT:cl.VALIDATION_ERROR,Vc(n));var r;let s=t,i=cl.NETWORK_ERROR;if(xt(e)){const n=e.response?.data;if("object"==typeof n){const e=n.Message;if("string"==typeof e&&e.length>0){s=`${t}: ${e}`;const n=e.toLowerCase();n.includes("insufficient")||n.includes("balance")?i=cl.INSUFFICIENT_BALANCE:(n.includes("not found")||n.includes("token"))&&(i=cl.TOKEN_NOT_FOUND)}}}else Lt(e)&&(s=`${t}: ${Ut(e)}`);return new ll(s,i,Vc(n))}}class Al extends br{constructor(e,t,n,r=!1,s,i){super(e,r),this.balanceService=new Lc(e,r),this.tokenService=new sl(e,r,s),this.lockService=new tl(e,t,n,r,i),this.transferService=new El(e,t,n,r,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 h(await this.fetchTokenClassFromChain(e))}catch(t){if(Lt(t)&&("NetworkError"===t.name||Ut(t).includes("Token not found")))throw t;throw Vt(`Failed to fetch token details from GalaChain for ${"string"==typeof e?e:$a(e)}: ${Ut(t)}`,500)}}async fetchTokenClassesWithSupply(e){return this.tokenService.fetchTokenClassesWithSupply(e)}async transferGala(e){return this.transferService.transferGala(e)}async transferToken(e){return this.transferService.transferToken(e)}async resolveTokenClassKey(e){return this.transferService.resolveTokenClassKey(e)}async lockTokens(e){return this.lockService.lockTokens(e)}async unlockTokens(e){return this.lockService.unlockTokens(e)}async burnTokens(e){return this.transferService.burnTokens(e)}}class vl extends br{async getHealth(){const e=(await this.http.get(ot)).data;if(null==e)throw Vt("Health check answered no data");return e}}class Tl extends Error{constructor(e,t,n){super(e),this.filename=t,this.mimeType=n,this.name="FileValidationError"}}function yl(e,t,n){if(null==e)throw new Tl("File is required",t,n);if("undefined"!=typeof File&&e instanceof File){const t=Ss.safeParse(e);if(!t.success){const n=t.error.issues.map(e=>e.message).join("; ");throw new Tl(n,e.name,e.type)}return}if(Buffer.isBuffer(e)){if(void 0===t||""===t)throw new Tl("Filename is required when uploading Buffer objects",t,n);const r=bs.safeParse(e);if(!r.success){const e=r.error.issues.map(e=>e.message).join("; ");throw new Tl(e,t,n)}try{Xn(t,255,"filename")}catch(e){throw new Tl(e.message,t,n)}const s=["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"];if(!s.includes(n))throw new Tl(`Invalid file type "${n}" is not allowed. Allowed types: ${s.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),o=[".png",".jpg",".jpeg",".gif",".webp",".svg"];if(!o.includes(i))throw new Tl(`File extension "${i}" is not allowed. Allowed extensions: ${o.join(", ")}`,t,n);const a=function(e){switch(e.toLowerCase()){case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";case".gif":return"image/gif";case".webp":return"image/webp";case".svg":return"image/svg+xml";default:return"application/octet-stream"}}(i);if(a!==n&&"application/octet-stream"!==a)throw new Tl(`File extension "${i}" does not match MIME type "${n}"`,t,n);return}throw new Tl("File must be a File object (browser) or Buffer (Node.js)",t,n)}function Sl(e,t="image",n){const r=new FormData;if("undefined"!=typeof File&&e instanceof File)r.append(t,e);else{if(!Buffer.isBuffer(e))throw Wt("file","a File object (browser) or Buffer (Node.js)");{const s=new Blob([e],{type:"image/png"});r.append(t,s,n)}}return r}class bl extends br{constructor(e,t,n=!1){super(e,n,t)}async uploadImageByTokenName(e){const{tokenName:t,options:n}=e;ur(t,"tokenName",Cr);const r=`${t}.png`;yl(n.file,r,"image/png");try{const e=Sl(n.file,"image",r),s=await cn(()=>this.http.request({method:"POST",url:Wo(R.UPLOAD_IMAGE,{tokenName:t}),data:e,headers:this.getJwtHeaders()}),{errorContext:"Image upload failed"});return"string"==typeof s?s:""}catch(e){if(e instanceof Ot)throw e;if(Lt(e)&&Ut(e).includes("FormData"))throw jt("File upload failed: FormData not supported in this environment. Ensure you have proper polyfills for Node.js environments.","FormData");throw e}}}function Nl(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 kt("At least one config option must be provided (chatEnabled, commentsEnabled, streamingEnabled, nextLiveStreamAt, streamLanguage, or social URLs)","options",wt.REQUIRED);if(void 0!==e.chatEnabled&&"boolean"!=typeof e.chatEnabled)throw Yt("chatEnabled","boolean");if(void 0!==e.commentsEnabled&&"boolean"!=typeof e.commentsEnabled)throw Yt("commentsEnabled","boolean");if(void 0!==e.streamingEnabled&&"boolean"!=typeof e.streamingEnabled)throw Yt("streamingEnabled","boolean");if(void 0!==e.streamLanguage&&"string"!=typeof e.streamLanguage)throw Yt("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 Yt(n,"string or null")}if(void 0!==e.nextLiveStreamAt&&null!==e.nextLiveStreamAt){if("string"!=typeof e.nextLiveStreamAt)throw Yt("nextLiveStreamAt","string or null");const t=new Date(e.nextLiveStreamAt);if(isNaN(t.getTime()))throw new kt("nextLiveStreamAt must be a valid ISO date string","nextLiveStreamAt",wt.INVALID_FORMAT)}}function wl(e){if(ar(e)||"object"!=typeof e)return{};const t={};for(const[n,r]of Object.entries(e))ar(r)||(ir(r)?t[n]=r:"number"==typeof r||"boolean"==typeof r?t[n]=r.toString():Array.isArray(r)?t[n]=r.join(","):t[n]="object"==typeof r?JSON.stringify(r):String(r));return t}var kl=Object.freeze({__proto__:null,adaptQueryParams:wl});function _l(e,t){if(null==e)return[];if(Array.isArray(e))return e;const n=e[t];return Array.isArray(n)?n:[]}function Il(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.owner&&""!==t.owner}function Cl(e){return"string"==typeof e.quantity&&""!==e.quantity}class Dl extends br{constructor(e,t,n=!1){super(e,n,t)}async fetchPools(e={}){const t=function(e){const t=e.pageSize??Ro.DEFAULT_LIMIT;if(!Number.isInteger(t)||t<1||t>bt)throw zt("pageSize",1,bt,t);const n={pageSize:String(t)};ir(e.cursor)&&(n.cursor=e.cursor);void 0!==e.type&&(n.type=Ll("type",e.type,yt));ir(e.tokenName)&&(ur(e.tokenName,"tokenName",_r),n.tokenName=e.tokenName);if(ir(e.search)){if(e.search.length>Rl)throw tn("search",Rl,e.search.length);n.search=e.search}!0===e.hasUpcomingShows&&(n.hasUpcomingShows="true");if(ir(e.language)){if(!Ml.test(e.language))throw Wt("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>Ol)throw zt("recentlyStreamed",1,Ol,t);n.recentlyStreamed=String(t)}!0===e.hasRecordings&&(n.hasRecordings="true");void 0!==e.streamStatus&&(n.streamStatus=Ll("streamStatus",e.streamStatus,St));if(void 0!==e.isGraduated){if("boolean"!=typeof e.isGraduated)throw Yt("isGraduated","boolean",e.isGraduated);n.isGraduated=e.isGraduated?"true":"false"}void 0!==e.creatorAddress&&(n.creatorAddress=function(e){if("string"!=typeof e)throw Yt("creatorAddress","string",e);return Bn(e,"creatorAddress"),xn(e)??e}(e.creatorAddress));return n}(e),n=on(await dn(()=>this.http.get(R.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:Bo(n?.pageInfo)}}async fetchAllPools(e){const t=[];let n;for(;;){const r={...e,pageSize:100,...void 0!==n&&{cursor:n}},s=await this.fetchPools(r);if(t.push(...s.items),0===s.items.length)break;const i=Go(s.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=ki(e);!t.success&&t.errors&&co(t.errors,"options")}(e),ir(e.tokenName)&&ur(e.tokenName,"tokenName",Dr);try{const t=await this.http.post(R.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===ir(e.symbol)){return!n.symbolAvailable}if(!0===ir(e.tokenName)){return!n.nameAvailable}return!1}catch(e){const t=String(e),n=e,r="string"==typeof n.message?n.message:"";if(t.includes("404")||t.includes("Pool not found")||r.includes("404")||r.includes("Pool not found"))return!1;const s="number"==typeof n.statusCode?n.statusCode:null;if(404===s)return!1;if(t.includes("400")||t.includes("Missing required pool identifier")||r.includes("400")||r.includes("Missing required pool identifier"))return!1;if(400===s&&r.includes("Missing required pool identifier"))return!1;throw e}}async isTokenNameAvailable(e){try{return!await this.checkPool({tokenName:e})}catch{return!1}}async isTokenSymbolAvailable(e){try{return!await this.checkPool({symbol:e})}catch{return!1}}async fetchVolumeData(e){if(!function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Hi(t,"tokenName")&&Vi(t,"from")&&Vi(t,"to")&&Vi(t,"resolution")}(e))throw new kt("Invalid options provided. Expected { tokenName: string, from?: number, to?: number, resolution?: number }","options","INVALID_OPTIONS");const{tokenName:t,from:n,to:r,resolution:s}=e;if(ur(t,"tokenName",_r),null==n||null==r||null==s)throw new kt("Graph options (from, to, resolution) are required","options","MISSING_GRAPH_OPTIONS");const i={tokenName:t,from:n,to:r,resolution:s};uo(i);const o=wl(i),a=await cn(()=>this.http.get(R.CHART,o),{errorContext:"Failed to fetch graph data"});if(!Array.isArray(a.data)||"boolean"!=typeof a.isPreviousData)throw new Rt("Invalid chart response: expected { data: candles, isPreviousData }");return{dataPoints:a.data,isPreviousData:a.isPreviousData,..."number"==typeof a.nextTime&&{nextTime:a.nextTime}}}async fetchTokenDistribution(e){if(""===e||null==e)throw Ht("tokenName","Token name");let t;ur(e,"tokenName",_r);try{t=await dn(()=>this.http.get(`${R.GET_TOKEN_DISTRIBUTION}?tokenName=${e}`),{errorContext:"Failed to fetch token distribution"})}catch(t){if(xt(t)&&500===t.response?.status)throw Vt(`Token distribution data temporarily unavailable for ${e}. This is a backend issue - please try again later.`,500,Lt(t)?t:void 0);throw t}return function(e,t,n=Xi){if(!Array.isArray(e))throw Vt("Invalid API response: expected array of holders",t);for(const n of e){if(!Il(n))throw Vt("Invalid holder data: missing or invalid owner field",t);if(!Cl(n))throw Vt("Invalid holder data: missing or invalid quantity field",t);const e=Hn(n.quantity,NaN);if(isNaN(e)||!isFinite(e))throw Vt(`Invalid holder quantity: "${n.quantity}"`,t)}const r=e,s=r.reduce((e,t)=>e.plus(t.quantity),Qi(0));return{holders:r.map(e=>({address:e.owner,balance:e.quantity,percentage:ro(Qi(e.quantity),s,Qi(0)).multipliedBy(100).toNumber()})),totalSupply:n(s),totalHolders:r.length,lastUpdated:new Date}}(on(t),t.status,e=>e.toFixed())}async fetchUserHolderContext(e,t){if(""===e||null==e)throw Ht("tokenName","Token name");if(""===t||null==t)throw Ht("userAddress","User address");return ur(e,"tokenName",_r),cn(()=>this.http.get(`${R.GET_TOKEN_DISTRIBUTION}?tokenName=${e}`,{userAddress:wn(t,"userAddress")}),{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");ur(e,"tokenName",Cr);try{const t=R.GET_TOKEN.replace(":tokenName",e.toLowerCase().trim()),n=on(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 Rt?new Rt(`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&&ur(e.tokenName,"tokenName",Dr);try{const t=await this.http.post(R.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(!ir(e))throw Ht("tokenName","Token name");ur(e,"tokenName",Cr);const t=R.TOKEN_STATS.replace(":tokenName",e.toLowerCase().trim());try{const e=on(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 Ht("tokenName","Token name");ur(e,"tokenName",Cr),Nl(t);const n=R.UPDATE_TOKEN_CONFIG.replace(":tokenName",e.toLowerCase().trim()),r={};void 0!==t.chatEnabled&&(r.chatEnabled=t.chatEnabled),void 0!==t.commentsEnabled&&(r.commentsEnabled=t.commentsEnabled),void 0!==t.streamingEnabled&&(r.streamingEnabled=t.streamingEnabled),void 0!==t.nextLiveStreamAt&&(r.nextLiveStreamAt=t.nextLiveStreamAt),void 0!==t.streamLanguage&&(r.streamLanguage=t.streamLanguage),void 0!==t.websiteUrl&&(r.websiteUrl=t.websiteUrl),void 0!==t.telegramUrl&&(r.telegramUrl=t.telegramUrl),void 0!==t.twitterUrl&&(r.twitterUrl=t.twitterUrl),void 0!==t.instagramUrl&&(r.instagramUrl=t.instagramUrl),void 0!==t.facebookUrl&&(r.facebookUrl=t.facebookUrl),void 0!==t.redditUrl&&(r.redditUrl=t.redditUrl),void 0!==t.tiktokUrl&&(r.tiktokUrl=t.tiktokUrl),await this.http.patch(n,r,this.getJwtHeaders())}async getTokenConfig(e){if(!ir(e))throw Ht("tokenName","Token name");ur(e,"tokenName",Cr);const t=R.UPDATE_TOKEN_CONFIG.replace(":tokenName",e.toLowerCase().trim()),n=on(await this.http.get(t));if(void 0===n)throw new Error(`Invalid response: missing token config data for "${e}"`);return n}}const Rl=255,Ol=720,Ml=/^[a-z]{2}(-[A-Z]{2})?$/u;function Ll(e,t,n){const r="string"==typeof t?t.toUpperCase():void 0,s=n.find(e=>e===r);if(void 0===s)throw Zt(e,t,n);return s}function Ul(e){if(void 0!==e.tokenName){if(!ir(e.tokenName))throw Yt("tokenName","a non-empty string",typeof e.tokenName);mr(e.tokenName,"tokenName",_r)}if(void 0!==e.userAddress){if(!ir(e.userAddress))throw Yt("userAddress","a non-empty string",typeof e.userAddress);if(e.userAddress.length>Ur)throw Xt("userAddress",Ur,e.userAddress.length)}if(void 0!==e.search){if("string"!=typeof e.search)throw Yt("search","a string",typeof e.search);if(e.search.length>256)throw Xt("search",256,e.search.length)}if(cr(0,void 0,Lr,e.pageSize),void 0!==e.txnType&&"BUY"!==e.txnType&&"SELL"!==e.txnType)throw Wt("txnType",'"BUY" or "SELL"');if(void 0!==e.startDate){if(!ir(e.startDate))throw Yt("startDate","a non-empty string",typeof e.startDate);if(isNaN(Date.parse(e.startDate)))throw Wt("startDate","a valid ISO 8601 date")}if(void 0!==e.endDate){if(!ir(e.endDate))throw Yt("endDate","a non-empty string",typeof e.endDate);if(isNaN(Date.parse(e.endDate)))throw Wt("endDate","a valid ISO 8601 date")}if(void 0!==e.minAmount)try{Qn(e.minAmount,0,Number.MAX_SAFE_INTEGER,"minAmount")}catch{throw Wt("minAmount","a non-negative number")}if(void 0!==e.maxAmount)try{Qn(e.maxAmount,0,Number.MAX_SAFE_INTEGER,"maxAmount")}catch{throw Wt("maxAmount","a non-negative number")}void 0!==e.minAmount&&void 0!==e.maxAmount&&function(e,t,n="range"){const r="number"==typeof e?e:Number(e),s="number"==typeof t?t:Number(t);if(isNaN(r)||isNaN(s))throw Yt(n,"numeric values",void 0,n);if(r>s)throw new kt(`Minimum value (${r}) must be less than or equal to maximum value (${s}) for ${n}`,n,wt.INVALID_RANGE)}(e.minAmount,e.maxAmount,"amountRange")}class Fl extends br{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 Hi(t,"tokenName")&&(void 0===t.tradeType||"buy"===t.tradeType||"sell"===t.tradeType)&&Wi(t,"userAddress")&&Vi(t,"offset")&&Vi(t,"pageSize")&&Vi(t,"page")&&Vi(t,"limit")}(e))throw new kt("Invalid options provided. Expected { tokenName: string, tradeType?: string, userAddress?: string, cursor?: string, pageSize?: number, startDate?: Date, endDate?: Date, sortOrder?: string }","options","INVALID_OPTIONS");const{tokenName:t,cursor:n,pageSize:r=Ro.DEFAULT_LIMIT}=e;if(!ir(t))throw Ht("tokenName","Token name");const s={pageSize:String(Math.min(r,Mr))};void 0!==n&&(s.cursor=n);const i=await this.http.get(Wo(R.GET_TRADES,{tokenName:t}),s);if(null==i)throw new kt("No response from trade service","response","NO_RESPONSE");const o=on(i),a=_l(o,"trades"),c=o?.pageInfo;return{items:a,pageInfo:c??{hasNextPage:!1}}}buildTradesQueryParams(e){const t={};null!==e.tokenName&&void 0!==e.tokenName&&e.tokenName.length>0&&(t.tokenName=gn(e.tokenName)),null!==e.userAddress&&void 0!==e.userAddress&&e.userAddress.length>0&&(t.userAddress=wn(e.userAddress,"userAddress")),null!==e.search&&void 0!==e.search&&e.search.length>0&&(t.search=e.search);const n=void 0!==e.pageSize?Uo(e.pageSize,1,Lr):Lr;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){Ul(e);const t=this.buildTradesQueryParams(e);return cn(()=>this.http.get(Xe,t),{errorContext:"Failed to fetch trades"})}}Cr.MIN_LENGTH,Cr.MAX_LENGTH;function Pl(e){return ir(e)&&Cn(e)}function xl(e,t,n=1){if(null==e||""===e)return null;if("string"!=typeof e)return null;const r=e.trim();return r.length<n?null:r}function Bl(e,t){return e.toLowerCase()===t.toLowerCase()}function Gl(e){return e.toLowerCase()}function $l(e,t){return e.toLowerCase().includes(t.toLowerCase())}function Kl(e,t,n,r){return e===n&&t===r||e===r&&t===n}function Hl(e){if(""===e||"string"!=typeof e)return null;if(e.includes("|")){const t=e.split("|");if(t.length>=2){const e=t[1];if(void 0!==e&&Vl(e))return jl(e)}return null}return Vl(e)?jl(e):null}function Wl(e){return null==e||"string"!=typeof e||0===e.trim().length}function Vl(e){if(""===e||"string"!=typeof e)return!1;const t=e.startsWith("0x")?e.slice(2):e;return/^[0-9a-fA-F]{40}$/.test(t)}function jl(e){return e.startsWith("0x")?e.slice(2):e}lr({BOTH:"both",HELD:"held",CREATED:"created"});function ql(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function zl(e){return"number"==typeof e&&Number.isFinite(e)}function Ql(e){return null===e||"string"==typeof e}function Xl(e){return Array.isArray(e)&&e.every(e=>ql(e)&&"string"==typeof e.badgeName&&"boolean"==typeof e.isActive)}function Yl(e){return ql(e)&&"string"==typeof e.address&&Ql(e.fullName)&&Ql(e.profileImage)&&Ql(e.bio)&&function(e){return ql(e)&&zl(e.tokensCreated)&&zl(e.tokensGraduated)&&zl(e.graduationRate)&&zl(e.totalTrades)&&"string"==typeof e.totalVolumeGala&&Ql(e.totalVolumeUsd)&&(null===e.holdingsCount||zl(e.holdingsCount))&&Ql(e.accountCreatedAt)&&zl(e.accountAgeDays)}(e.stats)&&Xl(e.launchBadge)&&Xl(e.successBadge)&&Xl(e.volumeBadge)&&Xl(e.engagementBadge)&&"boolean"==typeof e.isLiveStreaming&&Ql(e.liveStreamToken)}class Jl extends br{constructor(e,t,n=!1){super(e,n,t)}async fetchProfile(e){const t=e??this.http.getAddress();if(""===t||null==t||!Pl(t))throw Wt("address","eth|[40-hex-chars] or client|[identifier]","Address");if(void 0===e){const e=await cn(()=>this.http.get(R.GET_CURRENT_USER,void 0,this.getJwtHeaders()),{errorContext:"Failed to fetch profile"});if(!(ql(n=e)&&"string"==typeof n.address&&Ql(n.fullName)&&Ql(n.profileImage)&&"string"==typeof n.bio&&Xl(n.launchBadge)&&Xl(n.successBadge)))throw Vt("Malformed profile response");return e}var n;const r=await cn(()=>this.http.get(R.GET_PROFILE.replace(":address",wn(t,"address"))),{errorContext:"Failed to fetch profile"});if(!Yl(r))throw Vt("Malformed profile response");return r}async updateProfile(e){this.validateUpdateProfileData(e);const t={};void 0!==e.fullName&&(t.fullName=e.fullName.trim()),void 0!==e.profileImage&&(t.profileImage=e.profileImage),await cn(()=>this.http.put(R.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=Sl(e.file,"image",t),r=await cn(()=>this.http.request({method:"POST",url:R.UPLOAD_PROFILE_IMAGE,data:n,headers:this.getJwtHeaders()}),{errorContext:"Image upload failed"});return"string"==typeof r?r:""}catch(e){if(e instanceof kt||e instanceof Ot)throw e;if(e instanceof Rt)throw new Rt(`Profile image upload failed: ${Ut(e)}`,e.statusCode,e);throw new kt(`Profile image upload failed: ${Ut(e)}`,"file","UPLOAD_FAILED")}}async fetchTokenList(e){if(void 0!==e.status&&"created"!==e.type)throw new kt("status filters only apply when type=created","status","INVALID_FILTER");const t=e.tokenName,n={...e},r="created"===e.type;r&&(delete n.tokenName,void 0!==t&&void 0===n.search&&(n.search=t));const s=await this.buildFetchRequest(R.GET_TOKEN_LIST,n,{includeType:!0,requestType:e.type??"both",responseKey:r?"launches":"token",errorMessage:"Failed to fetch token list"});return r&&void 0!==t?{...s,tokens:s.tokens.filter(e=>e.tokenName===t||e.name===t)}:s}async fetchTokensHeld(e){if(void 0!==e.type&&"held"!==e.type)throw new kt("fetchTokensHeld only supports type=held","type","INVALID_TYPE");if(void 0!==e.status)throw new kt("status filters only apply when type=created","status","INVALID_FILTER");return this.buildFetchRequest(R.GET_TOKENS_HELD,e,{includeType:!0,requestType:"held",responseKey:"token",errorMessage:"Failed to fetch tokens held"})}async fetchTokensCreated(e){const{cursor:t,pageSize:n,search:r,tokenName:s,status:i}=e??{};if(void 0!==e?.type&&"created"!==e.type)throw new kt("fetchTokensCreated only supports type=created","type","INVALID_TYPE");const o=e?.address??this.http.getAddress();if(null==o||""===o)throw new kt("Wallet address not available - wallet not configured","address","NO_WALLET");const a={type:"created",address:o,pageSize:n??Ro.DEFAULT_LIMIT};return void 0!==t&&(a.cursor=t),void 0!==r&&(a.search=r),void 0!==s&&void 0===r&&(a.search=s),void 0!==s&&(a.tokenName=s),void 0!==i&&(a.status=i),this.fetchTokenList(a)}async getManagedTokens(e={}){const t={};return void 0!==e.cursor&&(t.cursor=e.cursor),void 0!==e.pageSize&&(t.pageSize=String(Math.min(e.pageSize,Mr))),cn(()=>this.http.get(R.GET_MANAGED_TOKENS,t,this.getJwtHeaders()),{errorContext:"Failed to fetch managed tokens"})}async getUserGalaBalance(e){if("string"!=typeof e||""===e.trim())throw Ht("address","Address");const t=wn(e.trim(),"address");return cn(()=>this.http.get(Wo(R.GET_GALA_BALANCE,{address:t})),{errorContext:"Failed to fetch GALA balance"})}async fetchReferralCode(){return cn(()=>this.http.get(R.GET_REFERRAL_CODE,void 0,this.getJwtHeaders()),{errorContext:"Failed to fetch referral code"})}async buildFetchRequest(e,t,n){this.validateGetTokenListOptions(t);const r=Ko({pageSize:t.pageSize??Ro.DEFAULT_LIMIT,...void 0!==t.cursor&&{cursor:t.cursor}},Mr);Vo(r,t,["address","search","tokenName","status"]),n.includeType&&!e.includes("?type=")&&(r.type=n.requestType);let s=e;const i=wn(t.address??this.http.getAddress(),"address");if(void 0!==t.address&&(r.address=i),e.includes(":address")){if(0===i.length)throw Ht("address","User address");s=e.replace(":address",i),delete r.address}const o=on(await dn(()=>this.http.get(s,r),{errorContext:n.errorMessage}));return{tokens:_l(o,n.responseKey).map(e=>{const t="string"==typeof e.tokenName?e.tokenName:"",r="string"==typeof e.name?e.name:t,s="string"==typeof e.createdAt?e.createdAt:"",o=e.metadata,a={...e};return delete a.metadata,{...a,id:"string"==typeof e.id?e.id:t,name:r,symbol:"string"==typeof e.symbol?e.symbol:"",type:n.requestType,address:i,balance:"string"==typeof e.balance?e.balance:"string"==typeof e.quantity?e.quantity:"0",decimals:"number"==typeof e.decimals?e.decimals:0,...null!==o&&"object"==typeof o?{metadata:o}:{},createdAt:s,updatedAt:"string"==typeof e.updatedAt?e.updatedAt:s}}),pageInfo:Bo(o?.pageInfo)}}validateGetTokenListOptions(e){const t=e.pageSize??Ro.DEFAULT_LIMIT;if(t<1||t>Mr)throw new kt(`pageSize must be between 1 and ${Mr}`,"pageSize","OUT_OF_RANGE");if(void 0!==e.address&&!Pl(e.address))throw Wt("address","eth|[40-hex-chars] or client|[identifier]","Address");const n=xl(e.search);if(null!==n&&!(ir(r=n)&&r.length>=Kr&&r.length<=Hr))throw zt("search",Kr,Hr,n.length,"Search query");var r;const s=xl(e.tokenName);if(!(null===s||ir(i=s)&&Cr.PATTERN.test(i)))throw Wt("tokenName",Cr.DESCRIPTION,"Token name");var i}validateUpdateProfileData(e){if(void 0!==e.address&&!Pl(e.address))throw Wt("address","eth|[40-hex-chars] or client|[identifier]","Address");if(void 0===e.fullName&&void 0===e.profileImage)throw new kt("At least one of fullName and profileImage must be provided","options","REQUIRED");if(void 0!==e.fullName&&(t=e.fullName.trim(),!(ir(t)&&t.length>=Wr.FULL_NAME.MIN_LENGTH&&t.length<=Wr.FULL_NAME.MAX_LENGTH&&Wr.FULL_NAME.ALPHABETS_ONLY_PATTERN.test(t))))throw zt("fullName",Wr.FULL_NAME.MIN_LENGTH,Wr.FULL_NAME.MAX_LENGTH,e.fullName.trim().length,"Full name");var t;if("string"==typeof e.profileImage&&e.profileImage.trim().length>2048)throw new kt("profileImage must not exceed 2048 characters","profileImage","TOO_LONG")}validateUploadProfileImageOptions(e){if(void 0!==e.address&&!Pl(e.address))throw Wt("address","eth|[40-hex-chars] or client|[identifier]","Address")}}class Zl{constructor(e,t,n=!1){this.http=e,this.poolService=new Dl(e,t,n),this.tradeService=new Fl(e,n),this.userService=new Jl(e,t,n),this.imageService=new bl(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 lo(e)}async fetchToken(e){return this.poolService.fetchToken(e)}async validateToken(e){return this.poolService.validateToken(e)}async fetchTokenStats(e){return this.poolService.fetchTokenStats(e)}async updateTokenConfig(e,t){return this.poolService.updateTokenConfig(e,t)}async getTokenConfig(e){return this.poolService.getTokenConfig(e)}}function ed(e,t){if(void 0!==e){if(!ir(e))throw Yt("tokenName","string");mr(e,"tokenName",_r)}if(void 0!==t){if(!ir(t))throw Yt("userAddress","string");if(t.length>Ur)throw new kt(`userAddress must be at most ${Ur} characters`,"userAddress",wt.TOO_LONG)}}const td={CHAT_MESSAGE:"CHAT_MESSAGE",COMMENT:"COMMENT"},nd={PAGINATION:{MAX_LIMIT:Lr},CONTENT:{CHAT_MAX_LENGTH:Fr.CHAT_MESSAGES_V1.MAX_LENGTH,COMMENT_MAX_LENGTH:Fr.COMMENTS_V1.MAX_LENGTH}};function rd(e){const t=void 0!==e.type,n=void 0!==e.tokenName&&""!==e.tokenName,r=void 0!==e.userAddress&&""!==e.userAddress;if(!t&&!n&&!r)throw en(["type","tokenName","userAddress"]);if(void 0!==e.type&&e.type!==td.CHAT_MESSAGE&&e.type!==td.COMMENT)throw new kt(`type must be one of: ${Object.values(td).join(", ")}`,"type",wt.INVALID_VALUE);ed(e.tokenName,e.userAddress),void 0!==e.pageSize&&cr(0,void 0,Lr,e.pageSize)}function sd(e){if(void 0===e.type||null===e.type)throw Ht("type");if(e.type!==td.CHAT_MESSAGE&&e.type!==td.COMMENT)throw new kt(`type must be one of: ${Object.values(td).join(", ")}`,"type",wt.INVALID_VALUE);if(!ir(e.tokenName))throw Ht("tokenName");if(mr(e.tokenName,"tokenName",_r),!ir(e.content))throw Ht("content");if(0===e.content.trim().length)throw nn("content","Content");const t=e.type===td.CHAT_MESSAGE?nd.CONTENT.CHAT_MAX_LENGTH:nd.CONTENT.COMMENT_MAX_LENGTH;if(e.content.length>t)throw tn("content",t,e.content.length)}function id(e){if(!ir(e.content))throw Ht("content");if(0===e.content.trim().length)throw nn("content","Content");const t=Math.max(nd.CONTENT.CHAT_MAX_LENGTH,nd.CONTENT.COMMENT_MAX_LENGTH);if(e.content.length>t)throw tn("content",t,e.content.length)}function od(e){if(!ir(e))throw Ht("id","Message ID");const t=Pr.CHAT_MESSAGE.PATTERN.test(e),n=/^msg-\d{13}-[a-f0-9]{32}$/.test(e);if(!t&&!n)throw new kt("Invalid message ID format. Expected: chat-{timestamp}-{uuid} or msg-{timestamp}-{uuid}","id",wt.INVALID_FORMAT)}function ad(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function cd(e){return null===e||"string"==typeof e}function ld(e){return ad(e)&&cd(e.fullName)&&cd(e.profileImage)}function dd(e){if(!ad(e))return!1;const t=e.reactions;return"string"==typeof e.id&&"string"==typeof e.messageId&&"string"==typeof e.tokenName&&cd(e.tokenImage)&&"string"==typeof e.userAddress&&ld(e.user)&&ld(e.userProfile)&&"string"==typeof e.content&&"string"==typeof e.createdAt&&cd(e.updatedAt)&&cd(e.deletedAt)&&"number"==typeof e.flagCount&&ad(t)&&ad(t.counts)}function ud(e){return e===td.CHAT_MESSAGE||e===td.COMMENT}class hd extends qo{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}validateContent(e,t){if(!ir(e))throw Ht("content","Message content");if(0===e.trim().length)throw Ht("content","Message content");Xn(e,t===td.CHAT_MESSAGE?Fr.CHAT_MESSAGES_V1.MAX_LENGTH:Fr.COMMENTS_V1.MAX_LENGTH,"content")}validateMessageId(e){if(!ir(e))throw Ht("id","Message ID");if(e.length<10||e.length>64)throw Wt("id","valid message ID format","Message ID")}validateMessageType(e){if(e!==td.CHAT_MESSAGE&&e!==td.COMMENT)throw new kt(`type must be one of: ${Object.values(td).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,_r);const r={};void 0!==e.cursor&&(r.cursor=e.cursor),r.pageSize=e.pageSize??Ro.DEFAULT_LIMIT;const s=Ko(r,Lr),i={};void 0!==s.pageSize&&(i.pageSize=s.pageSize),void 0!==s.cursor&&(i.cursor=s.cursor),t&&(i.type=e.type.toUpperCase()),n&&(i.tokenName=gn(e.tokenName)),void 0!==e.userAddress&&""!==e.userAddress&&(i.userAddress=wn(e.userAddress,"userAddress")),void 0!==e.search&&""!==e.search&&(i.search=e.search);const o=await this.http.get(Ye.GET_MESSAGES,i),a=this.extractData(o);return{messages:a.messages,pageInfo:a.pageInfo}}async createMessage(e){this.validateMessageType(e.type),this.validateTokenName(e.tokenName,_r),this.validateContent(e.content,e.type);const t={type:e.type,tokenName:gn(e.tokenName),content:e.content.trim()},n=await this.http.post(Ye.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(Ye.UPDATE_MESSAGE,e),r={content:t.content.trim()},s=await this.http.put(n,r,this.getJwtHeaders());return{message:this.extractData(s)}}async deleteMessage(e){this.validateMessageId(e);const t=this.buildEndpointWithId(Ye.DELETE_MESSAGE,e);return await this.http.delete(t,void 0,this.getDualAuthHeaders()),{success:!0}}async getPinnedMessage(e){this.validateTokenName(e,Cr);const t=await this.http.get(Ye.GET_PINNED,{tokenName:gn(e)});return{message:this.extractDataOrNull(t)}}async pinMessage(e){this.validateMessageId(e);const t=Ye.PIN_MESSAGE.replace(":id",e);return await this.http.post(t,{},this.getDualAuthHeaders()),{success:!0}}async unpinMessage(e){this.validateMessageId(e);const t=Ye.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 Vt("Malformed message statistics response");const r=e.totalMessages,s=e.todayMessages,i=e.uniqueUsers,o=e.uniqueTokens,a=e.messagesByType;if(!(t(r)&&t(s)&&t(i)&&t(o)&&n(a)))throw Vt("Malformed message statistics response");const c={};for(const[e,n]of Object.entries(a)){if(!t(n))throw Vt("Malformed message statistics response");c[e]=n}return{totalMessages:r,todayMessages:s,uniqueUsers:i,uniqueTokens:o,messagesByType:c}}(await this.http.get(Ye.GET_MESSAGE_STATS,void 0,this.getDualAuthHeaders()))}}const gd={MODERATOR:"MODERATOR",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MANAGER:"MANAGER"},md=dr(gd),fd={TOKEN:"TOKEN",ALL_OWNER_TOKENS:"ALL_OWNER_TOKENS"},pd=dr(fd),Ed={PENDING:"PENDING",CLAIMED:"CLAIMED",REVOKED:"REVOKED",EXPIRED:"EXPIRED"},Ad=dr(Ed);function vd(e){return md.includes(e)}function Td(e){return Ad.includes(e)}function yd(e){return $r.PATTERN.test(e)}const Sd=fr([{field:"id",type:"number"},{field:"inviteScope",type:"string"},{field:"tokenName",type:"string",nullable:!0},{field:"role",type:"string"},{field:"inviteCode",type:"string"},{field:"inviteUrl",type:"string"},{field:"status",type:"string"},{field:"createdAt",type:"string"}]),bd=fr([{field:"tokenName",type:"string"},{field:"tokenSymbol",type:"string"},{field:"role",type:"string"},{field:"inviteScope",type:"string"},{field:"creatorAddress",type:"string"},{field:"claimedAt",type:"string"}]),Nd=fr([{field:"inviteScope",type:"string"},{field:"tokenName",type:"string",nullable:!0},{field:"tokenSymbol",type:"string",nullable:!0},{field:"role",type:"string"},{field:"status",type:"string"},{field:"invitedBy",type:"string"}]);function wd(e){return pd.includes(e)}function kd(e){const t=[],n=e.inviteScope??fd.TOKEN;return void 0===e.inviteScope||wd(e.inviteScope)||Gt(t,()=>{throw Zt("inviteScope",e.inviteScope,pd,"Invite scope")}),n===fd.TOKEN?Gt(t,()=>{ur(e.tokenName??"","tokenName",_r)}):n===fd.ALL_OWNER_TOKENS&&void 0!==e.tokenName&&""!==e.tokenName&&t.push("Token name should not be provided for ALL_OWNER_TOKENS scope invites"),vd(e.role)||Gt(t,()=>{throw Zt("role",e.role,md,"Role")}),void 0!==e.description&&""!==e.description&&Gt(t,()=>{Xn(e.description,Fr.DESCRIPTION.MAX_LENGTH,"description")}),void 0===e.expiresAt||""===e.expiresAt||bn(e.expiresAt)||Gt(t,()=>{throw function(e,t="a valid date",n){const r=$t(e,n);return new kt(`${r} must be ${t}`,e,"INVALID_DATE")}("expiresAt","ISO 8601 format")}),t}function _d(e){const t=[];return ir(e)?yd(e)||t.push("Invalid invite code format"):t.push(Ht("inviteCode","Invite code").message),t}function Id(e){const t=[];return Gt(t,()=>{ur(e.tokenName??"","tokenName",_r)}),void 0===e.status||Td(e.status)||Gt(t,()=>{throw Zt("status",e.status,Ad,"Status")}),Gt(t,()=>{cr(0,void 0,Or,e.pageSize)}),t}class Cd extends qo{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}validateRole(e){if(!ir(e))throw Ht("role","Role");if(!vd(e))throw Wt("role",`one of: ${md.join(", ")}`,"Role")}validateInviteCodeFormat(e){if(!ir(e))throw Ht("inviteCode","Invite code");if(e.length>$r.MAX_LENGTH)throw Wt("inviteCode",`at most ${String($r.MAX_LENGTH)} characters`,"Invite code")}validateInviteScope(e){if(void 0!==e&&!wd(e))throw new kt(`Invalid invite scope. Must be one of: ${pd.join(", ")}`,"inviteScope","INVALID_VALUE")}async createInvite(e){this.validateInviteScope(e.inviteScope);const t=e.inviteScope??fd.TOKEN;if(t===fd.TOKEN){if(void 0===e.tokenName||""===e.tokenName)throw new kt("Token name is required for TOKEN scope invites","tokenName","REQUIRED");this.validateTokenName(e.tokenName,_r)}else if(t===fd.ALL_OWNER_TOKENS&&e.tokenName)throw new kt("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",Fr.DESCRIPTION.MAX_LENGTH),this.validateOptionalDate(e.expiresAt,"expiresAt","Expiration date");const n=ge,r={inviteScope:t,role:e.role};t===fd.TOKEN&&null!==e.tokenName&&void 0!==e.tokenName&&""!==e.tokenName&&(r.tokenName=gn(e.tokenName)),void 0!==e.description&&(r.description=e.description),void 0!==e.expiresAt&&(r.expiresAt=e.expiresAt);const s=await this.http.post(n,r,this.getMultiAuthHeaders());return{invite:this.extractData(s)}}async listInvites(e){void 0!==e.tokenName&&""!==e.tokenName&&this.validateTokenName(e.tokenName,_r),this.validateStatusFilter(e.status,Ed);const t=pe,n={...this.buildPaginationParams(e,Lr)};void 0!==e.tokenName&&""!==e.tokenName&&(n.tokenName=gn(e.tokenName)),void 0!==e.status&&(n.status=e.status);const r=await this.http.get(t,n,this.getMultiAuthHeaders()),s=this.extractData(r);return{items:s.invites,pageInfo:s.pageInfo}}async revokeInvite(e){this.validatePositiveInteger(e,"inviteId","Invite ID");const t=this.buildEndpoint(Ee,{id:String(e)});sn(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(Ae,{id:String(e.inviteId)}),n={role:e.role},r=await this.http.patch(t,n,this.getMultiAuthHeaders());return{invite:this.extractData(r)}}async updateInvite(e){if(this.validatePositiveInteger(e.inviteId,"inviteId","Invite ID"),void 0===e.role&&void 0===e.description)throw new kt("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",Fr.DESCRIPTION.MAX_LENGTH);const t=this.buildEndpoint(ve,{id:String(e.inviteId)}),n={};void 0!==e.role&&(n.role=e.role),void 0!==e.description&&(n.description=e.description);const r=await this.http.patch(t,n,this.getMultiAuthHeaders());return{invite:this.extractData(r)}}async claimInvite(e){this.validateInviteCodeFormat(e.inviteCode);const t=me,n={inviteCode:e.inviteCode},r=await this.http.post(t,n,this.getMultiAuthHeaders()),s=this.extractData(r);return"tokenName"in s&&void 0!==s.tokenName?{token:s}:{blanketAccess:s}}async getModeratedTokens(e){const t=fe,n=this.buildPaginationParams(e??{},Lr),r=await this.http.get(t,n,this.getMultiAuthHeaders()),s=this.extractData(r);return{items:s.tokens,pageInfo:s.pageInfo}}async getInviteByCode(e){this.validateInviteCodeFormat(e);const t=this.buildEndpoint(Te,{code:e}),n=await this.http.get(t,{});return this.extractData(n)}}const Dd={COLLECTION_CLAIM_FEE:"10000",TOKEN_CLASS_CREATE_FEE:"1000",DESCRIPTIONS:{COLLECTION_CLAIM:"10,000 GALA to claim a collection name",TOKEN_CLASS_CREATE:"1,000 GALA to create a token class",MINT:"Dynamic fee estimated via DryRun endpoint"}};function Rd(e){return parseFloat(Dd[e])}function Od(e){return`${e}-${Date.now()}-${Math.random().toString(36).substring(2,11)}`}function Md(){return Date.now()+6e4}function Ld(e){return""!==e&&"string"==typeof e&&/^[a-zA-Z0-9]{3,50}$/.test(e)}function Ud(e){try{return Math.floor(parseFloat(String(e))??0).toString()}catch{return"0"}}function Fd(e){return""!==e&&"string"==typeof e&&Cn(e)}class Pd extends br{constructor(e){super(e)}getCollectionClaimFee(){return Dd.COLLECTION_CLAIM_FEE}getTokenClassCreateFee(){return Dd.TOKEN_CLASS_CREATE_FEE}async estimateMintFee(e){try{if(this.logger.debug("Estimating mint fee",e),0===e.collection.length||0===e.type.length||0===e.category.length||0===e.quantity.length)throw new Error("Missing required parameters for mint fee estimation");if(!Fd(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=Dd.COLLECTION_CLAIM_FEE;n.collectionClaim=e,t=String(BigInt(t)+BigInt(e))}if((e.createTokenClasses??0)>0){const r=Dd.TOKEN_CLASS_CREATE_FEE,s=String(BigInt(r)*BigInt(e.createTokenClasses));n.tokenClassCreate=r,n.tokenClassCount=e.createTokenClasses,t=String(BigInt(t)+BigInt(s))}return{totalFee:t,breakdown:n}}async claimCollection(e){try{if(this.logger.debug("Claiming NFT collection",e.collectionName),!Ld(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:Md(),uniqueKey:Od("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),!Fd(e))throw new Error(`Invalid wallet address format: ${e}`);const t=(await this.allAuthorizations()).filter(t=>t.authorizedUsers.some(t=>In(t,e))).map(t=>({authorizedUser:Nn(e,"walletAddress"),collection:t.collection}));return this.logger.debug(`Found ${t.length} collections for user`),t}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),!Ld(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(!Ld(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?Ud(e.maxSupply):void 0,maxCapacity:void 0!==e.maxCapacity?Ud(e.maxCapacity):void 0,additionalKey:e.additionalKey,expiresAt:Md(),uniqueKey:Od("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),!Ld(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(!Fd(e.ownerAddress))throw new Error(`Invalid owner address: ${e.ownerAddress}`);const n=this.estimateMintFee({collection:e.collection,type:e.type,category:e.category,quantity:e.quantity,ownerAddress:e.ownerAddress});this.logger.debug("Estimated mint fee:",n);const r={collection:e.collection,type:e.type,category:e.category,quantity:e.quantity,owner:Nn(e.ownerAddress,"ownerAddress"),additionalKey:e.additionalKey??"none",expiresAt:Md(),uniqueKey:Od("mint")};this.logger.debug("Built mint DTO",r);const s=`mint-${Date.now()}`,i=Array.from({length:t},(e,t)=>t+1);return{transactionId:s,mintedQuantity:e.quantity,owner:Nn(e.ownerAddress,"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}),!Fd(e))throw new Error(`Invalid owner address: ${e}`);const n=(await this.reads().fetchNftBalances({owner:Nn(e,"ownerAddress"),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}=Oc(async(e,t)=>({data:await this.http.post(e,t)}));return new l({gatewayBaseUrl:"",httpRequestor:e,requestTimeoutMs:1/0})}allAuthorizations(){return this.reads().fetchAllNftCollectionAuthorizations({pageSize:1e3})}}class xd extends br{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(mt,{token:e.token,platform:e.platform,...void 0!==e.deviceId?{deviceId:e.deviceId}:{}},t),r=this.extractData(n);return this.logger.debug("Push token registered",{registered:r.registered}),r}async unregisterPushToken(e){this.logger.debug("Unregistering push token");const t=this.getJwtHeaders(),n=await this.http.request({method:"DELETE",url:ft,data:{token:e},headers:t}),r=this.extractData(n);return this.logger.debug("Push token unregistered",{unregistered:r.unregistered}),r}async getPreferences(){this.logger.debug("Fetching notification preferences");const e=this.getJwtHeaders(),t=await this.http.get(pt,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(Et,e,t),r=this.extractData(n);return this.logger.debug("Updated notification preferences",{tradesEnabled:r.tradesEnabled,streamsEnabled:r.streamsEnabled}),{preferences:r}}}class Bd extends br{constructor(e,t=!1){super(e,t)}async getHomeOEmbedJson(e={}){this.logger.debug("Fetching home oEmbed (JSON)");const t=await this.http.get(R.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(R.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 kt("tokenName is required","tokenName","REQUIRED_FIELD");this.logger.debug("Fetching pool oEmbed (JSON)",{tokenName:t});const n=R.OEMBED_BUY_SELL.replace(":tokenName",t.toLowerCase().trim()),r=await this.http.get(n,{format:"json"});return this.logger.debug("Fetched pool oEmbed (JSON)",{tokenName:t,title:r.title}),{oembed:r}}async getPoolOEmbedHtml(e){const{tokenName:t}=e;if(null==t||"string"!=typeof t||""===t.trim())throw new kt("tokenName is required","tokenName","REQUIRED_FIELD");this.logger.debug("Fetching pool oEmbed (HTML)",{tokenName:t});const n=R.OEMBED_BUY_SELL.replace(":tokenName",t.toLowerCase().trim()),r=await this.http.get(n,{},{responseType:"text"});return this.logger.debug("Fetched pool oEmbed (HTML)",{tokenName:t}),{html:r}}async getProfileOEmbedJson(e){const{address:t}=e;if(null==t||"string"!=typeof t||""===t.trim())throw new kt("address is required","address","REQUIRED_FIELD");this.logger.debug("Fetching profile oEmbed (JSON)",{address:t});const n=R.OEMBED_PROFILE.replace(":address",encodeURIComponent(wn(t.trim(),"address"))),r=await this.http.get(n,{format:"json"});return this.logger.debug("Fetched profile oEmbed (JSON)",{address:t,title:r.title}),{oembed:r}}async getProfileOEmbedHtml(e){const{address:t}=e;if(null==t||"string"!=typeof t||""===t.trim())throw new kt("address is required","address","REQUIRED_FIELD");this.logger.debug("Fetching profile oEmbed (HTML)",{address:t});const n=R.OEMBED_PROFILE.replace(":address",encodeURIComponent(wn(t.trim(),"address"))),r=await this.http.get(n,{},{responseType:"text"});return this.logger.debug("Fetched profile oEmbed (HTML)",{address:t}),{html:r}}}function Gd(e){if(!ir(e))throw Ht("address","Address");Nn(e,"address")}const $d={PENDING:"PENDING",CLAIMED:"CLAIMED",REVOKED:"REVOKED",EXPIRED:"EXPIRED"},Kd={ACTIVE:"ACTIVE",REVOKED:"REVOKED"},Hd=lr($d),Wd=lr(Kd);function Vd(e){if(e.status!==$d.PENDING)return!1;if(null!==e.expiresAt&&void 0!==e.expiresAt){if(Sn(e.expiresAt)<=new Date)return!1}return!0}function jd(e){try{vr(e.description,"description",255)}catch(e){if(e instanceof kt){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(!ir(e.expiresAt))throw new Error("expiresAt must be a non-empty string");try{Tr(e.expiresAt,"expiresAt")}catch(e){if(e instanceof kt)throw new Error("expiresAt must be a valid ISO 8601 date string");throw e}if(bn(e.expiresAt)){if(Sn(e.expiresAt)<=new Date)throw new Error("expiresAt must be in the future")}}}function qd(e){if(void 0!==e.status&&!Hd(e.status))throw Zt("status",e.status,Object.values($d),"status");cr(0,void 0,50,e.pageSize,e.cursor)}function zd(e){if(void 0!==e.status&&!Wd(e.status))throw Zt("status",e.status,Object.values(Kd),"status");cr(0,void 0,50,e.pageSize,e.cursor)}function Qd(e){if(!ir(e))throw new Error("Invite code must be a non-empty string");Xn(e,$r.MAX_LENGTH,"code")}function Xd(e){if(!ir(e))throw new Error("Address must be a non-empty string");try{Gn(e,"address")}catch{throw new Error("Invalid wallet address format. Must be eth|..., 0x..., or client|... format")}}function Yd(e){try{Yn(e,"id")}catch(e){if(e instanceof kt)throw new Error("Invite ID must be a positive integer");throw e}}function Jd(e){if(null==e||"object"!=typeof e)throw new kt("Options are required");if(void 0!==e.search){if("string"!=typeof e.search)throw new kt("Search must be a string");if(0===e.search.length)throw new kt("Search query cannot be empty string")}if(void 0!==e.sortBy){if("string"!=typeof e.sortBy)throw new kt("Sort field must be a string");if(0===e.sortBy.length)throw new kt("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 kt('Sort order must be "asc" or "desc"')}}function Zd(e){if(null==e||"object"!=typeof e)throw new kt("Options are required");if(!ir(e.userAddress))throw new kt("userAddress is required and must be a non-empty string");try{Gn(e.userAddress,"userAddress")}catch{throw new kt("Invalid wallet address format. Must be eth|..., 0x..., or client|... format")}if(void 0!==e.description){if("string"!=typeof e.description)throw new kt("description must be a string");if(e.description.length>255)throw new kt("description must be at most 255 characters")}}class eu extends qo{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}validateInviteCodeFormat(e){if(!ir(e))throw Ht("inviteCode","Invite code");Qd(e)}validateWalletAddressFormat(e){if(!ir(e))throw Ht("address","Address");Xd(e)}async createInvite(e={}){jd(e),this.validateOptionalString(e.description,"description","Description",Fr.DESCRIPTION.MAX_LENGTH),this.validateOptionalDate(e.expiresAt,"expiresAt","Expiration date");const t=Se,n={};void 0!==e.description&&(n.description=e.description),void 0!==e.expiresAt&&(n.expiresAt=e.expiresAt);const r=await this.http.post(t,n,this.getDualAuthHeaders());return{invite:this.extractData(r)}}async listInvites(e={}){qd(e),this.validateStatusFilter(e.status,$d);const t=be,n={...this.buildPaginationParams(e,Lr)};void 0!==e.status&&(n.status=e.status);const r=await this.http.get(t,n,this.getDualAuthHeaders()),s=this.extractData(r);return{items:s.invites,pageInfo:s.pageInfo}}async getInviteByCode(e){this.validateInviteCodeFormat(e);const t=this.buildEndpoint(Ne,{code:e}),n=await this.http.get(t,{});return this.extractData(n)}async revokeInvite(e){Yd(e);const t=this.buildEndpoint(ke,{id:String(e)});sn(await this.http.delete(t,void 0,this.getDualAuthHeaders()),"Failed to revoke invite")}async claimInvite(e){this.validateInviteCodeFormat(e);const t=we,n={inviteCode:e},r=await this.http.post(t,n,this.getJwtHeaders());return{invite:this.extractData(r)}}async listOverseers(e={}){zd(e),this.validateStatusFilter(e.status,Kd);const t=_e,n={...this.buildPaginationParams(e,Lr)};void 0!==e.status&&(n.status=e.status);const r=await this.http.get(t,n,this.getDualAuthHeaders()),s=this.extractData(r);return{items:s.overseers,pageInfo:s.pageInfo}}async createOverseerDirect(e){Zd(e),this.validateWalletAddressFormat(e.userAddress),this.validateOptionalString(e.description,"description","Description",Fr.DESCRIPTION.MAX_LENGTH);const t=Ie,n={userAddress:wn(e.userAddress,"userAddress")};void 0!==e.description&&(n.description=e.description);const r=await this.http.post(t,n,this.getDualAuthHeaders());return{overseer:this.extractData(r)}}async revokeOverseer(e){this.validateWalletAddressFormat(e);const t=this.buildEndpoint(Ce,{address:wn(e,"address")});sn(await this.http.delete(t,void 0,this.getDualAuthHeaders()),"Failed to revoke overseer")}async getMyStatus(){const e=De,t=await this.http.get(e,{},this.getJwtHeaders());return this.extractData(t)}async getSummary(){const e=Re,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getBanStats(){const e=Oe,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getTokenBanStats(){const e=Me,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getInviteStats(){const e=Le,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getFlagStats(){const e=Ue,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getUserStats(){const e=Fe,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async listOverseerUsers(e){const t=e??{};Object.keys(t).length>0&&Jd(t);const n=Pe,r=this.buildPaginationParams(t,Lr);void 0!==t.search&&""!==t.search&&(r.search=t.search),void 0!==t.sortBy&&""!==t.sortBy&&(r.sortBy=t.sortBy),void 0!==t.sortOrder&&(r.sortOrder=t.sortOrder);const s=await this.http.get(n,r,this.getDualAuthHeaders()),i=this.extractData(s);return{items:i.users,pageInfo:i.pageInfo}}async getOverseerUserSummary(e){if(!ir(e))throw Ht("address","User address");Xd(e);const t=this.buildEndpoint(xe,{address:wn(e,"address")}),n=await this.http.get(t,{},this.getDualAuthHeaders());return this.extractData(n)}async flushCacheByAddress(e){Gd(e);const t=this.buildEndpoint(Be,{address:wn(e,"address")}),n=await this.http.delete(t,void 0,this.getDualAuthHeaders());return this.extractData(n)}async flushCacheByToken(e){!function(e){if(!ir(e))throw Ht("tokenName","Token name")}(e);const t=this.buildEndpoint(Ge,{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 kt("Safety confirmation required: must pass confirm=true to flush all cache","confirm","CONFIRMATION_REQUIRED")}(e);const t=$e,n=await this.http.delete(t,{confirm:"true"},this.getDualAuthHeaders());return this.extractData(n)}async flushWalletAliasCache(e){if(void 0!==e){Gd(e);const t=this.buildEndpoint(Ke,{address:wn(e,"address")}),n=await this.http.delete(t,void 0,this.getDualAuthHeaders());return this.extractData(n)}const t=He,n=await this.http.delete(t,{confirm:"true"},this.getDualAuthHeaders());return this.extractData(n)}}function tu(e){const t=[];return 0===Object.keys(e).length&&t.push("At least one field (streamingEnabled, chatEnabled, commentsEnabled, webhooksEnabled, aiModerationEnabled) must be provided"),void 0!==e.streamingEnabled&&"boolean"!=typeof e.streamingEnabled&&t.push("streamingEnabled must be a boolean"),void 0!==e.chatEnabled&&"boolean"!=typeof e.chatEnabled&&t.push("chatEnabled must be a boolean"),void 0!==e.commentsEnabled&&"boolean"!=typeof e.commentsEnabled&&t.push("commentsEnabled must be a boolean"),void 0!==e.webhooksEnabled&&"boolean"!=typeof e.webhooksEnabled&&t.push("webhooksEnabled must be a boolean"),void 0!==e.aiModerationEnabled&&"boolean"!=typeof e.aiModerationEnabled&&t.push("aiModerationEnabled must be a boolean"),t}class nu extends br{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),sn(t,"Platform config operation failed",!0),e.data}async getPlatformConfig(){const e=await this.http.get(j);return this.extractData(e)}async updatePlatformConfig(e){const t=tu(e);if(t.length>0)throw new kt(t.join("; "),"options","VALIDATION_FAILED");const n=await this.http.put(q,e,this.getJwtHeaders());return this.extractData(n)}async getAvailableRoles(){const e=await this.http.get(X);return this.extractData(e)}}class ru extends br{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(ct),t=this.extractData(e);return this.logger.debug("Fetched platform stats",{totalTokens:t.totalTokens,timestamp:t.timestamp}),{stats:t}}}class su extends qo{constructor(e,t,n,r){super(e,t,n,!1,r)}async getRestrictedNames(){try{return{success:!0,data:(await this.http.get(Je,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 kt("Content is required");return{success:!0,data:(await this.http.put(Ze,{content:e.content},this.getJwtHeaders())).data}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}}class iu extends qo{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async getChatStatus(e){if(null==e||""===e)throw Ht("tokenName","Token name");return this.validateTokenName(e,Cr),yo(async()=>{const t=this.buildEndpoint(et,{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 Ht("tokenName","Token name");return this.validateTokenName(e,Cr),yo(async()=>{const t=this.buildEndpoint(nt,{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 Ht("tokenName","Token name");return this.validateTokenName(e,Cr),yo(async()=>{const t=this.buildEndpoint(tt,{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??gn(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 Ht("tokenName","Token name");if(this.validateTokenName(e,Cr),"number"!=typeof t||t<0||t>600)throw new Error("slowModeSeconds must be a number between 0 and 600");return yo(async()=>{const n=this.buildEndpoint(rt,{tokenName:e}),r=await this.http.patch(n,{slowModeSeconds:t},this.getDualAuthHeaders());return this.extractData(r)},`Failed to set slow mode for token: ${e}`,this.logger)}}const ou={IDLE:"IDLE",ACTIVE:"ACTIVE",DISABLED:"DISABLED"},au={PREPARING:"preparing",READY:"ready",ERRORED:"errored"},cu={IDLE:"idle",STARTING:"starting",BROADCASTING:"broadcasting",ERRORED:"errored"},lu={YOUTUBE:"youtube",TWITCH:"twitch",FACEBOOK:"facebook",CUSTOM:"custom"},du=lr(ou),uu=lr(au),hu=lr(lu);function gu(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&du(t.status)&&(null===t.playbackId||"string"==typeof t.playbackId)&&"boolean"==typeof t.isLive}function mu(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"number"==typeof t.viewerCount}const fu={OWNER:"OWNER",MANAGER:"MANAGER",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MODERATOR:"MODERATOR"},pu={OWNER:"OWNER",MODERATOR:"MODERATOR"};lr(fu),lr(pu);const Eu={MANAGE_COMMENTS:"MANAGE_COMMENTS",MANAGE_CHAT:"MANAGE_CHAT",BAN_USERS:"BAN_USERS",UNBAN_USERS:"UNBAN_USERS",MANAGE_SIMULCAST:"MANAGE_SIMULCAST",GET_STREAM_KEY:"GET_STREAM_KEY",STOP_STREAM:"STOP_STREAM",RESET_STREAM_KEY:"RESET_STREAM_KEY",START_STREAM:"START_STREAM",DELETE_RECORDINGS:"DELETE_RECORDINGS",MANAGE_STREAM_SETTINGS:"MANAGE_STREAM_SETTINGS"},Au={...fu,OVERSEER:"OVERSEER"},vu=lr(Au);function Tu(e){if(null==e||"object"!=typeof e)return!1;const t=e,n=t.permissions;return Array.isArray(n)&&n.every(e=>"string"==typeof e)&&(null===t.source||"owner"===t.source||"moderator_invite"===t.source||"api_key"===t.source||"overseer"===t.source)&&(void 0===t.matchedPreset||null===t.matchedPreset||"MODERATOR"===t.matchedPreset||"TECHNICAL_PRODUCER"===t.matchedPreset||"MANAGER"===t.matchedPreset)&&"boolean"==typeof t.isOwner&&"boolean"==typeof t.isOverseer}function yu(e,t="tokenName"){ur(e,t,Cr)}const Su=/^rtmps?:\/\/\S+$/u,bu=255;function Nu(e){if(yu(e.tokenName),!ir(e.language))throw Ht("language");if(t=e.language,!ir(t)||!/^[a-z]{2}(-[A-Z]{2})?$/.test(t))throw new kt('language must be a valid ISO 639-1 code (e.g., "en", "es", "zh-CN")',"language",wt.INVALID_FORMAT);var t}const wu={STREAM_STARTED:"stream.started",STREAM_STOPPED:"stream.stopped",RECORDING_READY:"recording.ready",SIMULCAST_ERROR:"simulcast.error"};class ku extends qo{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async startStream(e){this.validateTokenName(e,Cr);const t=this.buildEndpoint(U,{tokenName:e}),n=await this.http.post(t,{},this.getJwtHeaders());return this.extractData(n)}async stopStream(e){this.validateTokenName(e,Cr);const t=this.buildEndpoint(F,{tokenName:e});await this.http.post(t,{},this.getJwtHeaders())}async disableStream(e){return this.toggleFeature(e,P,Cr)}async enableStream(e){return this.toggleFeature(e,x,Cr)}async resetStreamKey(e){this.validateTokenName(e,Cr);const t=this.buildEndpoint(B,{tokenName:e}),n=await this.http.post(t,{},this.getJwtHeaders());return this.extractData(n)}async getStreamCredentials(e){this.validateTokenName(e,Cr);const t=this.buildEndpoint(J,{tokenName:e}),n=await this.http.get(t,{},this.getJwtHeaders());return this.extractData(n)}async getRecordings(e){!function(e){yu(e.tokenName)}(e);const t=this.buildEndpoint(G,{tokenName:e.tokenName}),n=await this.http.get(t),r=this.extractData(n);if(!Array.isArray(r))throw Vt("Invalid recordings response: expected an array of recordings");return{recordings:r,tokenName:gn(e.tokenName)}}async getRecordingDownload(e,t){this.validateTokenName(e,Cr),this.validateRequiredString(t,"assetId","Asset ID");const n=this.buildEndpoint($,{tokenName:e,assetId:t}),r=await this.http.get(n,{},this.getJwtHeaders());return this.extractData(r)}async deleteRecording(e,t){this.validateTokenName(e,Cr),this.validateRequiredString(t,"assetId","Asset ID");const n=this.buildEndpoint(K,{tokenName:e,assetId:t});await this.http.delete(n,void 0,this.getJwtHeaders())}async getSimulcastTargets(e){this.validateTokenName(e,Cr);const t=this.buildEndpoint(H,{tokenName:e}),n=await this.http.get(t,void 0,this.getJwtHeaders()),r=this.extractData(n);if(!Array.isArray(r))throw Vt("Invalid simulcast response: expected an array of targets");return{targets:r,tokenName:gn(e)}}async addSimulcastTarget(e){!function(e){if(yu(e.tokenName),!ir(e.platform))throw Ht("platform");if(!hu(e.platform))throw new kt("platform must be one of: 'youtube', 'twitch', 'facebook', 'custom'","platform",wt.INVALID_VALUE);if(!ir(e.url))throw Ht("url");if(!Su.test(e.url))throw new kt("url must be a valid RTMP or RTMPS URL","url",wt.INVALID_FORMAT);if(e.url.length>2048)throw new kt(`url must not exceed ${String(2048)} characters`,"url",wt.TOO_LONG);if(!ir(e.streamKey))throw Ht("streamKey");if(e.streamKey.length>bu)throw new kt(`streamKey must not exceed ${String(bu)} characters`,"streamKey",wt.TOO_LONG);if(void 0!==e.passthrough){if("string"!=typeof e.passthrough)throw new kt("passthrough must be a string","passthrough",wt.INVALID_TYPE);if(e.passthrough.length>bu)throw new kt(`passthrough must not exceed ${String(bu)} characters`,"passthrough",wt.TOO_LONG)}}(e);const t=this.buildEndpoint(W,{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:gn(e.tokenName)}}async removeSimulcastTarget(e,t){this.validateTokenName(e,Cr),this.validateRequiredString(t,"targetId","Target ID");const n=this.buildEndpoint(V,{tokenName:e,targetId:t});await this.http.delete(n,void 0,this.getJwtHeaders())}async getGlobalStreamingStatus(){const e=await this.http.get(j);return this.extractData(e)}async disableGlobalStreaming(){const e=await this.http.put(q,{},this.getAdminHeaders());return this.extractData(e)}async enableGlobalStreaming(){const e=await this.http.put(z,{},this.getAdminHeaders());return this.extractData(e)}async setNextLiveStream(e){let t;!function(e){if(yu(e.tokenName),null!==e.nextLiveStreamAt){if(!(e.nextLiveStreamAt instanceof Date||ir(e.nextLiveStreamAt)))throw new kt("nextLiveStreamAt must be a Date, ISO 8601 string, or null","nextLiveStreamAt",wt.INVALID_TYPE);if("string"==typeof e.nextLiveStreamAt){const t=Date.parse(e.nextLiveStreamAt);if(isNaN(t))throw new kt("nextLiveStreamAt must be a valid ISO 8601 date string","nextLiveStreamAt",wt.INVALID_FORMAT)}}}(e),t=null===e.nextLiveStreamAt?null:e.nextLiveStreamAt instanceof Date?e.nextLiveStreamAt.toISOString():e.nextLiveStreamAt;const n=`/v1/tokens/${e.tokenName.toLowerCase().trim()}`;await this.http.patch(n,{nextLiveStreamAt:t},this.getJwtHeaders())}async clearNextLiveStream(e){this.validateTokenName(e,Cr);const t=`/v1/tokens/${e.toLowerCase().trim()}`;await this.http.patch(t,{nextLiveStreamAt:null},this.getJwtHeaders())}async setStreamLanguage(e){Nu(e);const t=`/v1/tokens/${e.tokenName.toLowerCase().trim()}`;await this.http.patch(t,{streamLanguage:e.language},this.getJwtHeaders())}async getStreamRole(e){!function(e){yu(e.tokenName)}(e);const t=this.buildEndpoint(Q,{tokenName:e.tokenName}),n=this.jwtAuth?this.getJwtHeaders():{},r=await this.http.get(t,{},n);return this.extractData(r)}async getAvailableRoles(){const e=await this.http.get(X);return this.extractData(e)}async getTokenAccess(e){!function(e){yu(e.tokenName)}(e);const t=await this.http.get(Y,{tokenName:gn(e.tokenName)},this.getJwtHeaders());return this.extractData(t)}async setNextLiveStreamCountdown(e,t){return this.setNextLiveStream({tokenName:e,nextLiveStreamAt:t})}}const _u={SUBSCRIBE:"subscribe_token",UNSUBSCRIBE:"unsubscribe_token",SUBSCRIBE_COMMENT:"subscribe_comment",UNSUBSCRIBE_COMMENT:"unsubscribe_comment",SUBSCRIBE_GLOBAL_FEED:"subscribe_global_feed",UNSUBSCRIBE_GLOBAL_FEED:"unsubscribe_global_feed",SUBSCRIBE_EVENTS_FIREHOSE:"subscribe_events_firehose",UNSUBSCRIBE_EVENTS_FIREHOSE:"unsubscribe_events_firehose",AUTHENTICATE:"authenticate",SEND_CHAT:"send_stream_chat",SEND_REACTION:"SEND_STREAM_REACTION",TYPING_START:"typing_start",TYPING_STOP:"typing_stop",STREAM_STATUS:"STREAM_STATUS",RECORDING_STATUS:"RECORDING_STATUS",RECORDINGS_COUNT_UPDATED:"RECORDINGS_COUNT_UPDATED",SIMULCAST_STATUS:"SIMULCAST_STATUS",DOWNLOAD_READY:"DOWNLOAD_READY",STREAM_COUNTDOWN_UPDATED:"STREAM_COUNTDOWN_UPDATED",STREAM_LANGUAGE_UPDATED:"STREAM_LANGUAGE_UPDATED",VIEWER_COUNT:"VIEWER_COUNT",STREAM_CONTROL_STATUS_CHANGED:"STREAM_CONTROL_STATUS_CHANGED",STREAM_GLOBAL_STATUS:"STREAM_GLOBAL_STATUS",ENGAGEMENT_STATS_UPDATED:"ENGAGEMENT_STATS_UPDATED",CHAT_MESSAGE:"STREAM_CHAT_MESSAGE",CHAT_SENT:"STREAM_CHAT_SENT",CHAT_UPDATED:"STREAM_CHAT_UPDATED",CHAT_DELETED:"STREAM_CHAT_DELETED",CHAT_PINNED:"STREAM_CHAT_PINNED",CHAT_UNPINNED:"STREAM_CHAT_UNPINNED",CHAT_STATUS:"CHAT_STATUS_CHANGED",SLOW_MODE_CHANGED:"SLOW_MODE_CHANGED",CHAT_GLOBAL_STATUS:"STREAM_CHAT_GLOBAL_STATUS",USER_TYPING:"USER_TYPING",CHAT_ERROR:"stream_chat_error",REACTION:"STREAM_REACTION",REACTION_ERROR:"stream_reaction_error",CONTENT_REACTION_ADDED:"CONTENT_REACTION_ADDED",CONTENT_REACTION_REMOVED:"CONTENT_REACTION_REMOVED",COMMENT_CREATED:"COMMENT_CREATED",COMMENT_UPDATED:"COMMENT_UPDATED",COMMENT_DELETED:"COMMENT_DELETED",TRADE_EXECUTED:"TRADE_EXECUTED",TRADE_UPDATE_NOTIFY:"TRADE_UPDATE_NOTIFY",BALANCE_UPDATED:"BALANCE_UPDATED",STATS_UPDATED:"STATS_UPDATED",USER_BANNED:"USER_BANNED",USER_UNBANNED:"USER_UNBANNED",BAN_ENFORCEMENT:"BAN_ENFORCEMENT",TOKEN_BANNED:"TOKEN_BANNED",TOKEN_UNBANNED:"TOKEN_UNBANNED",CONTENT_FLAGGED:"CONTENT_FLAGGED",FLAG_RESOLVED:"FLAG_RESOLVED",AI_MODERATION_COMPLETE:"AI_MODERATION_COMPLETE",AI_MODERATION_FAILED:"AI_MODERATION_FAILED",MODERATOR_INVITE_CREATED:"MODERATOR_INVITE_CREATED",MODERATOR_ADDED:"MODERATOR_ADDED",MODERATOR_REMOVED:"MODERATOR_REMOVED",MODERATOR_ROLE_UPDATED:"MODERATOR_ROLE_UPDATED",OVERSEER_ADDED:"OVERSEER_ADDED",OVERSEER_REMOVED:"OVERSEER_REMOVED",POOL_CREATED:"POOL_CREATED",POOL_METADATA_UPDATED:"POOL_METADATA_UPDATED",POOL_SOCIAL_LINKS_UPDATED:"POOL_SOCIAL_LINKS_UPDATED",POOL_BADGE_ASSIGNED:"POOL_BADGE_ASSIGNED",TOKEN_CONFIG_UPDATED:"TOKEN_CONFIG_UPDATED",HOLDER_COUNT_UPDATED:"HOLDER_COUNT_UPDATED",USER_PROFILE_UPDATED:"USER_PROFILE_UPDATED",API_KEY_CREATED:"API_KEY_CREATED",API_KEY_UPDATED:"API_KEY_UPDATED",API_KEY_REVOKED:"API_KEY_REVOKED",SITE_CONFIG_CHANGED:"SITE_CONFIG_CHANGED",COMMENTS_GLOBAL_STATUS:"COMMENTS_GLOBAL_STATUS",WEBHOOKS_GLOBAL_STATUS:"WEBHOOKS_GLOBAL_STATUS",AI_MODERATION_GLOBAL_STATUS:"AI_MODERATION_GLOBAL_STATUS",EVENT:"EVENT",CONNECTION:"connection",CHAT_AUTHENTICATED:"authenticated",CHAT_AUTH_ERROR:"stream_chat_auth_error",EXCEPTION:"exception",STREAM_SUBSCRIBED:"token_subscribed",STREAM_UNSUBSCRIBED:"token_unsubscribed",ROOM_SUBSCRIBED:"room_subscribed",ROOM_LEFT:"room_left",GLOBAL_FEED_SUBSCRIBED:"global_feed_subscribed",GLOBAL_FEED_UNSUBSCRIBED:"global_feed_unsubscribed",EVENTS_FIREHOSE_SUBSCRIBED:"events_firehose_subscribed",EVENTS_FIREHOSE_UNSUBSCRIBED:"events_firehose_unsubscribed"},Iu=e=>Cu(e.flagId);function Cu(e){return"string"==typeof e||"number"==typeof e?String(e):void 0}function Du(e,t){const n=t.map(t=>Cu(e[t]));return n.every(e=>void 0!==e)?n.join("|"):void 0}const Ru={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=>Cu(e.id)},FLAG_RESOLVED:{duplicateKey:e=>Du(e,["id","status","reviewedAt"])},AI_MODERATION_COMPLETE:{duplicateKey:Iu},AI_MODERATION_FAILED:{duplicateKey:Iu},MODERATOR_INVITE_CREATED:{},MODERATOR_ADDED:{},MODERATOR_REMOVED:{},MODERATOR_ROLE_UPDATED:{},OVERSEER_ADDED:{token:"none",duplicateKey:e=>Du(e,["userAddress","addedAt"])},OVERSEER_REMOVED:{token:"none",duplicateKey:e=>Du(e,["userAddress","removedAt"])},POOL_CREATED:{duplicateKey:e=>Du(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 Ou(e){return Ru[e]}const Mu=Object.keys(Ru);const Lu="token:",Uu="comment:",Fu="global:feed",Pu="global:events_firehose";function xu(e){if(e.startsWith(Lu)){const t={tokenName:e.slice(Lu.length)};return{join:{event:_u.SUBSCRIBE,payload:t},leave:{event:_u.UNSUBSCRIBE,payload:t}}}if(e.startsWith(Uu)){const t={tokenName:e.slice(8)};return{join:{event:_u.SUBSCRIBE_COMMENT,payload:t},leave:{event:_u.UNSUBSCRIBE_COMMENT,payload:t}}}return e===Pu?{join:{event:_u.SUBSCRIBE_EVENTS_FIREHOSE},leave:{event:_u.UNSUBSCRIBE_EVENTS_FIREHOSE}}:{join:{event:_u.SUBSCRIBE_GLOBAL_FEED},leave:{event:_u.UNSUBSCRIBE_GLOBAL_FEED}}}const Bu=new Set(["token_subscribed","room_subscribed","global_feed_subscribed","events_firehose_subscribed"]);const Gu={STREAM_CHAT_GLOBAL_STATUS:"chatEnabled",STREAM_GLOBAL_STATUS:"streamingEnabled",COMMENTS_GLOBAL_STATUS:"commentsEnabled",WEBHOOKS_GLOBAL_STATUS:"webhooksEnabled",AI_MODERATION_GLOBAL_STATUS:"aiModerationEnabled"},$u=["STREAM_STATUS","TRADE_EXECUTED","HOLDER_COUNT_UPDATED","POOL_BADGE_ASSIGNED","VIEWER_COUNT","TOKEN_CONFIG_UPDATED","STATS_UPDATED","POOL_CREATED"],Ku=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"]),Hu=new Set(["COMMENT_CREATED","COMMENT_UPDATED","COMMENT_DELETED"]);const Wu={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"},Vu={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"},ju=()=>{};function qu(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function zu(e,t){return t}function Qu(e){return`${Lu}${e}`}function Xu(e){return`${Uu}${e}`}function Yu(e){const t=gn(e);if(""===t)throw Ht("tokenName","Token name");return t}class Ju extends Nr{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 Ot("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 _}register(e,t,n={}){if(this.disposed)return ju;const r={name:e,deliver:t,token:n.token,filter:n.filter,room:n.room,active:!0};let s=this.subscribers.get(e);return void 0===s&&(s=new Set,this.subscribers.set(e,s)),s.add(r),void 0!==n.room&&this.acquireRoom(n.room),this.openIfNeeded(),()=>{this.release(r)}}release(e){if(!e.active)return;e.active=!1;const t=this.subscribers.get(e.name);t?.delete(e),0===t?.size&&this.subscribers.delete(e.name),void 0!==e.room&&this.releaseRoom(e.room)}hold(e){if(this.disposed)return ju;let t=!0;return this.acquireRoom(e),this.openIfNeeded(),()=>{t&&(t=!1,this.releaseRoom(e))}}openIfNeeded(){this.config.autoConnect&&!this.disposed&&(null===this.socket||this.reconnectExhausted)&&this.connect().catch(e=>{this.logger.warn(`Stream WebSocket connect failed: ${Ut(e)}`)})}acquireRoom(e){this.roomRefs.set(e,(this.roomRefs.get(e)??0)+1),this.syncRoom(e)}releaseRoom(e){const t=(this.roomRefs.get(e)??1)-1;t<=0?this.roomRefs.delete(e):this.roomRefs.set(e,t),this.syncRoom(e)}syncRoom(e){const t=this.liveSocket();if(null===t)return;const n=(this.roomRefs.get(e)??0)>0,r=this.roomStates.get(e);if(n&&void 0===r){if(function(e){return e===Pu}(e)&&!this.authenticated)return;this.joinRoom(t,e)}else n||"joined"!==r?.phase||(t.emit(xu(e).leave.event,xu(e).leave.payload),this.roomStates.delete(e))}syncAllRooms(){for(const e of new Set([...this.roomRefs.keys(),...this.roomStates.keys()]))this.syncRoom(e)}joinRoom(e,t){const n=setTimeout(()=>{const e=this.roomStates.get(t);"joining"===e?.phase&&(this.roomStates.delete(t),this.rejectWaiters(t,new Error(`Subscription to ${t} timed out after ${this.config.subscriptionTimeout}ms`)))},this.config.subscriptionTimeout);this.roomStates.set(t,{phase:"joining",timer:n});const r=xu(t).join;e.emit(r.event,r.payload)}onRoomAcknowledged(e){const t=this.roomStates.get(e);void 0!==t?.timer&&clearTimeout(t.timer),this.roomStates.set(e,{phase:"joined",timer:void 0});const n=this.roomWaiters.get(e);if(void 0!==n){this.roomWaiters.delete(e);const t=e.startsWith(Lu)?e.slice(Lu.length):e;for(const r of n)clearTimeout(r.timer),r.resolve({room:e,tokenName:t})}this.syncRoom(e)}rejectWaiters(e,t){const n=this.roomWaiters.get(e);if(void 0!==n){this.roomWaiters.delete(e);for(const e of n)clearTimeout(e.timer),e.reject(t)}}clearRoomStates(){for(const e of this.roomStates.values())void 0!==e.timer&&clearTimeout(e.timer);this.roomStates.clear()}onServerEvent(e,t){try{this.applyEffects(e,t)}catch(t){this.logger.error(`Error handling ${e}:`,t)}if((!qu(t)||!this.isDuplicate(e,t))&&(this.deliver(e,t,qu(t)?function(e,t){const n=Ou(e).token??"payload";if("none"===n)return;if("room"===n){const e=t.room;return"string"==typeof e&&e.startsWith(Lu)?e.slice(Lu.length):void 0}const r=t.tokenName;return"string"==typeof r&&""!==r?r:void 0}(e,t):void 0),qu(t)))for(const n of function(e,t){if("TOKEN_CONFIG_UPDATED"!==e)return[];const n=t.tokenName;if("string"!=typeof n)return[];const r=[];if("nextLiveStreamAt"in t){const e=t.nextLiveStreamAt;r.push({name:"STREAM_COUNTDOWN_UPDATED",payload:{tokenName:n,nextLiveStreamAt:"string"==typeof e?e:null}})}const s=t.streamLanguage;return"string"==typeof s&&r.push({name:"STREAM_LANGUAGE_UPDATED",payload:{tokenName:n,language:s}}),r}(e,t))this.deliver(n.name,n.payload,n.payload.tokenName)}isDuplicate(e,t){const n=Ou(e).duplicateKey?.(t);if(void 0===n)return!1;const r=Date.now(),s=`${e}:${n}`,i=this.recentOccurrences.get(s);if(void 0!==i&&r-i<5e3)return!0;if(this.recentOccurrences.set(s,r),this.recentOccurrences.size>256)for(const[e,t]of this.recentOccurrences)r-t>=5e3&&this.recentOccurrences.delete(e);return!1}deliver(e,t,n){const r=this.subscribers.get(e);if(void 0===r)return;const s=void 0===n?void 0:gn(n);for(const n of[...r])n.active&&(void 0!==n.token&&n.token!==s||(void 0===n.filter||this.passes(n,t))&&this.invoke(e,n.deliver,t))}passes(e,t){try{return e.filter?.(t)??!0}catch(t){return this.logger.error(`Error in a ${e.name} filter:`,t),!1}}invoke(e,t,n){try{const r=t(n);r instanceof Promise&&r.catch(t=>{this.logger.error(`Error in a ${e} subscriber:`,t)})}catch(t){this.logger.error(`Error in a ${e} subscriber:`,t)}}applyEffects(e,t){if("authenticated"===e)null!==this.inFlight?this.inFlight.settle(!0):this.adoptLateAuthentication();else if("stream_chat_auth_error"===e)this.authenticated=!1,this.inFlight?.settle(!1);else if("exception"===e)this.inFlight?.settle(!1);else if(function(e){return Bu.has(e)}(e))qu(t)&&"string"==typeof t.room&&this.onRoomAcknowledged(t.room);else{const n=Gu[e];void 0!==n&&(this.siteConfig={...this.siteConfig,[n]:Zu(t)})}}liveSocket(){return null!==this.socket&&this.socket.connected?this.socket:null}connect(){if(this.disposed)return Promise.reject(new Ot("The stream WebSocket service has been disposed."));if(!this.isSocketIOAvailable)return Promise.reject(new Ot('Socket.IO not available. Install "socket.io-client" package.'));const e=this.socket??this.createSocket();if(e.connected)return Promise.resolve();if(null===this.connectAttempt){let e=()=>{},t=()=>{};const n=new Promise((n,r)=>{e=n,t=r});this.connectAttempt={promise:n,resolve:e,reject:t}}return e.connect(),this.connectAttempt.promise}createSocket(){this.logger.debug(`🔌 Connecting to Stream WebSocket: ${this.config.url}`);const e=_(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 Mu)e.on(t,e=>{this.onServerEvent(t,e)});const t=e=>{this.logger.debug(`🔄 Stream WebSocket reconnect attempt ${String(e)}`)},n=()=>{this.reconnectExhausted=!0,this.logger.error("❌ Stream WebSocket max reconnection attempts reached")};e.io.on("reconnect_attempt",t),e.io.on("reconnect_failed",n),this.managerCleanups.push(()=>e.io.off("reconnect_attempt",t),()=>e.io.off("reconnect_failed",n))}onSocketConnect(){this.connectionGeneration+=1;const e=this.connectionGeneration,t=this.hasConnected;this.hasConnected=!0,this.logger.debug(`✅ Stream WebSocket connected: ${String(this.socket?.id)}`),this.reconnectExhausted=!1,this.clearRoomStates(),this.authenticated=!1,this.notifyConnectionState(!0),this.settleConnectWaiters(void 0),this.wantsAuthentication?this.restoreAfterReconnect(e):(this.syncAllRooms(),t&&this.notifyReconnect())}async restoreAfterReconnect(e){try{await this.authenticate()}catch(e){this.logger.warn(`Re-authentication after reconnect failed: ${Ut(e)}`)}e!==this.connectionGeneration||this.disposed||(this.syncAllRooms(),this.notifyReconnect())}onSocketDisconnect(e){this.logger.debug(`🔌 Stream WebSocket disconnected: ${e}`),this.authenticated=!1,this.inFlight?.settle(!1),this.clearRoomStates(),this.notifyConnectionState(!1),"io server disconnect"!==e||null===this.socket||this.disposed||this.socket.connect()}settleConnectWaiters(e){const t=this.connectAttempt;this.connectAttempt=null,null!==t&&(void 0===e?t.resolve():t.reject(e))}notifyConnectionState(e){for(const t of[...this.connectionStateListeners])this.invoke("connection state",t,e)}notifyReconnect(){for(const e of[...this.reconnectListeners])this.invoke("reconnect",e,void 0)}onConnectionStateChange(e){return this.disposed?ju:(this.connectionStateListeners.add(e),()=>{this.connectionStateListeners.delete(e)})}onReconnect(e){return this.disposed?ju:(this.reconnectListeners.add(e),()=>{this.reconnectListeners.delete(e)})}async resolveToken(){const e=this.config.tokenProvider;if(void 0===e)return this.lastExplicitToken;try{const t=await e();return null!==t&&""!==t?t:null}catch(e){return this.logger.warn(`The token provider failed: ${Ut(e)}`),null}}authenticate(e){if(""===e)return Promise.reject(Ht("token","Authentication token"));const t=this.pendingAuthenticate;if(null!==t&&t.token===e&&t.generation===this.connectionGeneration)return t.promise;this.authSequence+=1;const n=this.authSequence,r=this.runAuthenticate(e,n).finally(()=>{this.pendingAuthenticate?.promise===r&&(this.pendingAuthenticate=null)});return this.pendingAuthenticate={token:e,generation:this.connectionGeneration,promise:r},r}async runAuthenticate(e,t){if(this.disposed)return!1;const n=e??await this.resolveToken();if(t!==this.authSequence||null===n)return!1;void 0!==e&&(this.lastExplicitToken=e);try{await this.connect()}catch(e){return this.logger.warn(`Cannot authenticate, the connection failed: ${Ut(e)}`),!1}for(;null!==this.inFlight;)if(await this.inFlight.settled,t!==this.authSequence)return!1;const r=this.liveSocket();if(t!==this.authSequence||null===r)return!1;if(this.authenticated&&this.authenticatedToken===n&&this.authenticatedGeneration===this.connectionGeneration)return!0;const s=this.beginAuthentication(t,n);this.lastEmitted={seq:t,token:n,generation:this.connectionGeneration},this.logger.debug("📡 Authenticating with stream server"),r.emit(_u.AUTHENTICATE,{token:n});return await s.result&&t===this.authSequence}beginAuthentication(e,t){let n=()=>{};const r=new Promise(e=>{n=e}),s={seq:e,token:t,generation:this.connectionGeneration,result:r,settled:r.then(()=>{}),timer:void 0,settle:e=>{this.finishAuthentication(s,e,n)}};return s.timer=setTimeout(()=>{this.logger.warn("Stream WebSocket authentication timed out"),s.settle(!1)},this.config.subscriptionTimeout),this.inFlight=s,s}finishAuthentication(e,t,n){if(this.inFlight!==e)return;void 0!==e.timer&&clearTimeout(e.timer),this.inFlight=null;const r=e.seq===this.authSequence&&e.generation===this.connectionGeneration;t&&r&&this.markAuthenticated(e.token,e.generation),n(t&&r)}markAuthenticated(e,t){this.authenticated=!0,this.authenticatedToken=e,this.authenticatedGeneration=t,this.wantsAuthentication=!0,this.syncAllRooms()}adoptLateAuthentication(){const e=this.lastEmitted;null===e||this.authenticated||e.seq===this.authSequence&&e.generation===this.connectionGeneration&&this.markAuthenticated(e.token,e.generation)}deauthenticate(){this.authSequence+=1;const e=this.authenticated||null!==this.inFlight;this.inFlight?.settle(!1),this.pendingAuthenticate=null,this.wantsAuthentication=!1,this.lastExplicitToken=null,this.authenticated=!1,this.authenticatedToken=null,this.authenticatedGeneration=-1,e&&null!==this.socket&&!this.disposed&&(this.socket.disconnect(),this.socket.connect())}isAuthenticatedForChat(){return this.authenticated}isConnected(){return this.socket?.connected??!1}requireReady(){const e=this.liveSocket();if(null===e)throw new kt("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(!this.authenticated)throw new kt("Not authenticated. Call authenticate() first.","auth","NOT_AUTHENTICATED");return e}sendChatMessage(e,t){if(""===e)throw Ht("tokenName","Token name");if(""===t)throw Ht("content","Message content");const n=this.requireReady(),r=gn(e);this.logger.debug(`📡 Sending chat message to ${r}: ${t.slice(0,30)}...`),n.emit(_u.SEND_CHAT,{tokenName:r,content:t})}sendReaction(e,t,n=0){if(""===e)throw Ht("tokenName","Token name");if(""===t)throw Ht("emoji");const r=this.requireReady(),s=gn(e);this.logger.debug(`📡 Sending reaction to ${s}: ${t}`),r.emit(_u.SEND_REACTION,{tokenName:s,emoji:t,streamTime:n})}sendTypingStart(e){this.sendTypingEvent(e,_u.TYPING_START)}sendTypingStop(e){this.sendTypingEvent(e,_u.TYPING_STOP)}sendTypingEvent(e,t){if(""===e)throw Ht("tokenName","Token name");this.requireReady().emit(t,{tokenName:gn(e)})}subscribeToken(e,t,n){const r=Yu(t);return this.register(e,e=>n(zu(0,e)),{token:r,room:Qu(r)})}joinTokenRoom(e){return this.hold(Qu(Yu(e)))}subscribeComment(e,t,n){const r=Yu(t);return this.register(e,e=>n(zu(0,e)),{token:r,room:Xu(r)})}subscribeFeed(e,t){return this.register(e,e=>t(zu(0,e)),{room:Fu})}subscribeEvent(e,t){return this.register(e,e=>t(zu(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:gn(e.tokenName),r=e.userAddress;return void 0!==t||void 0!==n||void 0!==r?e=>{if(!qu(e))return!1;const s=e.eventType;if(void 0!==t&&("string"!=typeof s||!t.includes(s.toLowerCase())))return!1;const i=e.tokenName;if(void 0!==n&&("string"!=typeof i||gn(i)!==n))return!1;const o=e.userAddress;return void 0===r||"string"==typeof o&&In(o,r)}:void 0}(t);return this.register("EVENT",t=>e(zu(0,t)),{room:Pu,...void 0!==n&&{filter:n}})}subscribeFeedTokenEvents(e){const t=$u.map(t=>this.register(t,n=>e(function(e,t){return{event:e,data:zu(0,t)}}(t,n)),{room:Fu}));return()=>{for(const e of t)e()}}subscribeToGlobalFeed(e={}){const t=this.registerCallbacks(e,Vu,()=>({})),n=this.hold(Fu);return()=>{t(),n()}}addCallbacks(e){return this.registerCallbacks(e,Wu,()=>({}))}registerCallbacks(e,t,n){const r=[],s={...e};for(const[e,i]of Object.entries(t)){const t=s[e];"function"==typeof t&&r.push(this.register(i,e=>Reflect.apply(t,void 0,[e]),n(i)))}return()=>{for(const e of r)e()}}async subscribeToStream(e,t={}){const n=Yu(e),r=Qu(n),s=this.epoch;if(await this.connect(),s!==this.epoch||this.disposed)throw new Error("WebSocket disconnected");const i=this.registerCallbacks(t,Wu,e=>{return t=e,Ku.has(t)?{token:n}:function(e){return Hu.has(e)}(e)?{token:n,room:Xu(n)}:{};var t}),o=this.hold(r),a={release:()=>{i(),o()}},c=this.explicitHolds.get(n)??[];c.push(a),this.explicitHolds.set(n,c);try{return await this.waitForRoom(r,n)}catch(e){throw this.dropExplicitHold(n,a),e}}waitForRoom(e,t){return"joined"===this.roomStates.get(e)?.phase?Promise.resolve({room:e,tokenName:t}):new Promise((n,r)=>{const s={resolve:n,reject:r,timer:setTimeout(()=>{this.roomWaiters.get(e)?.delete(s),r(new Error(`Subscription to ${t} timed out after ${this.config.subscriptionTimeout}ms`))},this.config.subscriptionTimeout)},i=this.roomWaiters.get(e)??new Set;i.add(s),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=gn(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(Lu)&&e.push(t.slice(Lu.length));return e}isSubscribedToGlobalFeed(){return(this.roomRefs.get(Fu)??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 Zu(e){if(!qu(e))return;const t=e.enabled;return"boolean"==typeof t?t:void 0}function eh(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"number"==typeof t.id&&"string"==typeof t.tokenName&&"string"==typeof t.bannedBy&&"string"==typeof t.createdAt&&(null===t.reason||"string"==typeof t.reason)}function th(e){return null==e||""===e||"string"==typeof e&&(!Ar(e)&&e.length<=Fr.BAN_REASON.MAX_LENGTH)}function nh(e){if(ur(e.tokenName,"tokenName",_r),!th(e.reason))throw new kt(`reason must be at most ${Fr.BAN_REASON.MAX_LENGTH} characters`,"reason","TOO_LONG")}function rh(e){ur(e.tokenName,"tokenName",Cr)}function sh(e){cr(0,void 0,Or,e.pageSize)}function ih(e){ur(e.tokenName,"tokenName",Cr)}class oh extends qo{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async banToken(e){nh(e);const t=We,n={tokenName:gn(e.tokenName)};if(void 0!==e.reason)try{Jn(e.reason,"reason",!0),e.reason.trim().length>0&&(n.reason=e.reason)}catch{}const r=await this.http.post(t,n,this.getDualAuthHeaders());return{ban:this.extractData(r),tokenName:gn(e.tokenName)}}async unbanToken(e){rh(e);const t=this.buildEndpoint(qe,{tokenName:e.tokenName});return sn(await this.http.delete(t,void 0,this.getDualAuthHeaders()),"Failed to unban token",!1),{tokenName:gn(e.tokenName)}}async listTokenBans(e={}){sh(e);const t=Ve,n=this.buildPaginationParams(e,Or);this.addOptionalFilterParams(n,e,["search"]);const r=await this.http.get(t,n,this.getDualAuthHeaders()),s=this.extractData(r);return{items:s.bans,pageInfo:s.pageInfo}}async getTokenBan(e){ih(e);const t=this.buildEndpoint(je,{tokenName:e.tokenName}),n=await this.http.get(t,{},this.getDualAuthHeaders()),r=this.extractDataOrNull(n);return{banned:null!==r,...null!==r&&{ban:r},tokenName:gn(e.tokenName)}}async isTokenBanned(e){return this.getTokenBan(e)}}class ah extends Nr{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(!ir(e))throw Ht("tokenName","Token name");const t=gn(e),n=this.getCacheEntry(t);if(null!==n)return this.cacheHits++,this.updateAccessOrder(t),n.vaultAddress;this.cacheMisses++;const r=await this.poolService.resolveTokenNameToVault(e);if(null!==r&&""!==r){const e=this.parseVaultAddressToTokenClassKey(r);this.setCacheEntry(t,{vaultAddress:r,tokenClassKey:e,cachedAt:Date.now()})}return r}async resolveTokenClassKey(e){if(!ir(e))throw Ht("tokenName","Token name");const t=gn(e),n=this.getCacheEntry(t);if(null!==n)return this.cacheHits++,this.updateAccessOrder(t),n.tokenClassKey;this.cacheMisses++;const r=await this.poolService.resolveTokenNameToVault(e);if(null===r||""===r)throw Kt(e);const s=this.parseVaultAddressToTokenClassKey(r);return this.setCacheEntry(t,{vaultAddress:r,tokenClassKey:s,cachedAt:Date.now()}),s}get(e){const t=this.getCacheEntry(gn(e));return t?.vaultAddress??null}getCacheEntry(e){return this.cache.get(e)??null}setCacheEntry(e,t){this.cache.size>=ah.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=gn(e),r=this.parseVaultAddressToTokenClassKey(t);this.setCacheEntry(n,{vaultAddress:t,tokenClassKey:r,cachedAt:Date.now()})}clear(){this.cache.clear(),this.accessOrder=new Set,this.cacheHits=0,this.cacheMisses=0}getStats(){const e=Array.from(this.cache.values()).map(e=>e.cachedAt),t=this.cacheHits+this.cacheMisses;return{size:this.cache.size,keys:Array.from(this.cache.keys()),maxSize:ah.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(gn(e));return t?.tokenClassKey??null}preWarm(e){for(const{tokenName:t,vaultAddress:n}of e)this.set(t,n)}preWarmWithTokenClassKey(e){for(const{tokenName:t,vaultAddress:n,tokenClassKey:r}of e){const e=gn(t);this.setCacheEntry(e,{vaultAddress:n,tokenClassKey:r,cachedAt:Date.now()})}}parseVaultAddressToTokenClassKey(e){try{return Ha(e)}catch(e){if(e instanceof kt)throw Wt("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad","Vault address");throw e}}}ah.MAX_CACHE_SIZE=1e4;class ch extends br{constructor(e,t=!1){super(e,t)}async fetchLaunchpadFee(){const e=await cn(()=>this.http.get(lt),{errorContext:"Failed to fetch launchpad fee"});if("number"!=typeof e.feeAmount||!Number.isFinite(e.feeAmount))throw new kt("Failed to fetch launchpad fee: no feeAmount in the response","feeAmount","INVALID_RESPONSE");return e.feeAmount}async fetchSaleDetails(e){return cn(()=>this.http.get(dt,{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 oo(await cn(()=>void 0===n?this.http.get(ut,t):this.http.request({method:"GET",url:ut,params:t,signal:n}),{errorContext:`Failed to get trade quote for ${e.tokenName}`}),`trade quote for ${e.tokenName}`)}async getPremintQuote(e){return oo(await cn(()=>this.http.get(ht,{amount:e}),{errorContext:"Failed to get premint quote"}),"premint quote")}}class lh extends qo{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async emitTradeExecuted(e,t){this.validateTokenName(e,Rr);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,Rr);const r={action:"balance_updated",userAddress:wn(e,"userAddress"),tokenName:t,payload:n};await this.emitEvent(r)}async emitStreamStatus(e,t,n=!0){this.validateTokenName(e,Rr);const r={action:"stream_status",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitViewerCount(e,t,n=!1){this.validateTokenName(e,Rr);const r={action:"viewer_count",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitStreamCountdown(e,t,n=!0){this.validateTokenName(e,Rr);const r={action:"stream_countdown",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitChatMessage(e,t,n=!1){this.validateTokenName(e,Rr);const r={action:"chat_message",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitChatStatus(e,t,n=!1){this.validateTokenName(e,Rr);const r={action:"chat_status",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitTypingIndicator(e,t,n=!1){this.validateTokenName(e,Rr);const r={action:"typing_indicator",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitTokenBanned(e,t){this.validateTokenName(e,Rr);const n={action:"token_banned",tokenName:e,payload:t,broadcast:!0};await this.emitEvent(n)}async emitTokenUnbanned(e,t){this.validateTokenName(e,Rr);const n={action:"token_unbanned",tokenName:e,payload:t,broadcast:!0};await this.emitEvent(n)}async emitModeratorAdded(e,t,n=!1){this.validateTokenName(e,Rr);const r={action:"moderator_added",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitModeratorRemoved(e,t,n=!1){this.validateTokenName(e,Rr);const r={action:"moderator_removed",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitUserProfileUpdated(e,t){this.validateRequiredString(e,"userAddress","User Address");const n={action:"user_profile_updated",userAddress:wn(e,"userAddress"),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=Nn(e.userAddress,"userAddress")),void 0!==e?.userAddresses&&(n.userAddresses=e.userAddresses.split(",").map(e=>Nn(e.trim(),"userAddresses")).join(",")),void 0!==e?.authenticated&&(n.authenticated=e.authenticated),void 0!==e?.isOverseer&&(n.isOverseer=e.isOverseer),void 0!==e?.minConnectionSeconds&&(n.minConnectionSeconds=e.minConnectionSeconds),void 0!==e?.offset&&(n.offset=e.offset),void 0!==e?.limit&&(n.limit=e.limit);const r=await this.http.get(t,Object.keys(n).length>0?n:void 0,this.getDualAuthHeaders());return this.extractData(r)}async isUserOnline(e){this.validateRequiredString(e,"userAddress","User Address");const t=await this.getConnectedClients({userAddress:e,limit:1});if(0===t.clients.length)return{online:!1};const n=t.clients[0];return void 0===n?{online:!1}:{online:!0,socketId:n.socketId,rooms:n.rooms,connectedAt:n.connectedAt}}async getOnlineUsers(e){if(!Array.isArray(e)||0===e.length)throw new Ot("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.some(t=>In(t,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,Rr);const n={tokenName:e};void 0!==t?.authenticated&&(n.authenticated=t.authenticated),void 0!==t?.limit&&(n.limit=t.limit);const r=await this.getConnectedClients(n);return{clients:r.clients,count:r.summary.totalConnected,authenticatedCount:r.summary.authenticatedCount}}async getOnlineOverseers(){const e=await this.getConnectedClients({isOverseer:!0});return{clients:e.clients,count:e.summary.totalConnected}}async emitRecordingStatus(e,t){this.validateTokenName(e,Rr);const n={action:"recording_status",tokenName:e,payload:t};await this.emitEvent(n)}async emitRecordingsCountUpdated(e,t){this.validateTokenName(e,Rr);const n={action:"recordings_count_updated",tokenName:e,payload:t};await this.emitEvent(n)}async emitDownloadReady(e,t){this.validateTokenName(e,Rr);const n={action:"download_ready",tokenName:e,payload:t};await this.emitEvent(n)}}class dh{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 uh{constructor(e=0){this.defaultTtlMs=e,this.cache=new Map}get(e){const t=this.cache.get(e);if(t){if(!(void 0!==t.expiresAt&&Date.now()>t.expiresAt))return t.value;this.cache.delete(e)}}set(e,t,n){const r=n??this.defaultTtlMs,s={value:t};r>0&&(s.expiresAt=Date.now()+r),this.cache.set(e,s)}has(e){return void 0!==this.get(e)}delete(e){this.cache.delete(e)}clear(){this.cache.clear()}get size(){return this.cache.size}}class hh extends Nr{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 dh({maxAttempts:this.config.reconnectAttempts??5,baseDelayMs:this.config.reconnectDelay??2e3}),this.eventBuffer=new uh(3e4),this.isSocketIOAvailable=this.checkSocketIOAvailability(),hh.instances.add(this)}checkSocketIOAvailability(){try{return"function"==typeof _||(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)=>{yo(async()=>{if(!this.isSocketIOAvailable){const e=new Error('Socket.IO not available in current environment. Install "socket.io-client" package.');throw this.logger.error("❌ Socket.IO connection failed:",Ut(e)),e}this.logger.debug("🔌 Connecting to Socket.IO server:",this.config.url),this.socket=_(this.config.url,{transports:["websocket"],reconnection:!0,reconnectionAttempts:this.config.reconnectAttempts??5,reconnectionDelay:this.config.reconnectDelay??2e3}),this.socket.on("connect",()=>{this.logger.debug("✅ Socket.IO connected successfully:",this.socket?.id),this.logger.debug("📡 Connected to bundle backend WebSocket:",this.config.url),this.logger.debug("🔗 Ready to monitor transaction updates"),this.reconnectionManager.reset(),e()}),this.socket.on("connect_error",e=>{this.logger.error("❌ Socket.IO connection error:",e),t(e)}),this.socket.on("disconnect",e=>{this.logger.debug(`🔌 Socket.IO disconnected: ${e}`),this.handleReconnect()}),this.socket.on("error",e=>{this.logger.error("❌ Socket.IO error:",e)}),this.socket.onAny((e,...t)=>{if(""!==e&&t.length>0&&"object"==typeof t[0]&&null!==t[0]){const n=t[0],r=n.status??n.Status;"string"==typeof r&&(this.logger.debug(`📡 [Event Buffer] Buffering event for ${e}: ${r}`),this.eventBuffer.size>=this.MAX_BUFFER_SIZE&&this.logger.warn(`📡 [Event Buffer] Buffer approaching limit (${this.eventBuffer.size}/${this.MAX_BUFFER_SIZE})`),this.eventBuffer.set(e,n))}this.debug&&this.logger.debug(`📡 [WebSocket Event] "${e}":`,JSON.stringify(t,null,2))}),this.hasOnAnyListener=!0},"Socket.IO connection failed",this.logger,e=>{this.logger.error("Socket.IO connection failed:",e);const n=Lt(e)?e:new Error(Ut(e));throw t(n),n}).catch(t)})}async monitorTransaction(e,t){this.listeners.set(e,t),this.logger.debug(`📡 Starting to monitor transaction: ${e}`),this.logger.debug(`📡 WebSocket connected: ${String(this.socket?.connected??!1)}`);const n=this.eventBuffer.get(e);null!=n&&(this.logger.debug(`📡 [Event Buffer] Found buffered event for ${e}, delivering immediately`),setImmediate(()=>{this.processTransactionEvent(e,n,t)}),this.eventBuffer.delete(e));const r=this.config.timeout??3e5,s=setTimeout(()=>{if(this.listeners.has(e)){const n=Math.round(r/1e3),s={transactionId:e,status:Io.TIMEOUT,message:`Transaction monitoring timeout - no response after ${n} seconds`,timestamp:Date.now()};this.logger.debug(`📡 Transaction timeout for ${e} (${n}s)`),t(s),this.listeners.delete(e),this.timeouts.delete(e),this.socket?.off(e)}},r);if(this.timeouts.set(e,s),this.socket?.connected)this.socket.off(e),this.logger.debug(`📡 Listening for transaction updates: ${e}`),this.logger.debug(`📡 WebSocket connection ID: ${String(this.socket.id)}`),this.logger.debug(`📡 WebSocket URL: ${this.config.url}`),this.socket.on(e,n=>{this.processTransactionEvent(e,n,t)});else{const n={transactionId:e,status:Io.FAILED,message:"WebSocket not connected - cannot monitor transaction",timestamp:Date.now()};t(n),this.listeners.delete(e),this.timeouts.delete(e)}await Promise.resolve()}processTransactionEvent(e,t,n){this.logger.debug(`📡 Socket.IO transaction update for ${e}:`,JSON.stringify(t,null,2));const r=t,s=r?.data,i=r?.status??r?.Status??s?.status??s?.Status;let o=r?.message??r?.Message??s?.message??s?.Message??r?.error??s?.error;ir(o)||(o=i===_o.FAILED||i===_o.ERROR?"Transaction failed - check transaction details":i===_o.COMPLETED||i===_o.PROCESSED||i===_o.SUCCESS?"Transaction completed successfully":null!=i?`Transaction status: ${String(i)}`:"Unknown transaction status");const a=r?.blockHash??s?.blockHash,c=r?.gasUsed??s?.gasUsed,l=r?.Data??s?.Data,d={transactionId:e,status:this.mapSocketStatus(i),message:"string"==typeof o?o:"Transaction update received",timestamp:Date.now(),...null!=a?{blockHash:a}:{},...null!=c?{gasUsed:c}:{},...null!=l?{data:l}:{}};if(this.logger.debug(`📡 Mapped status for ${e}: ${String(i)} -> ${d.status}`),this.logger.debug(`📡 Final message: "${String(o)}"`),n(d),d.status===Io.COMPLETED||d.status===Io.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===Io.COMPLETED?t(e):e.status!==Io.FAILED&&e.status!==Io.TIMEOUT||n(new Error(`Transaction ${String(e.status)}: ${e.message}`))})})}mapSocketStatus(e){const t=e?.toUpperCase();return Co[t]??Io.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")),hh.instances.delete(this)}static cleanupAll(e=!1){for(const e of hh.instances)e.disconnect();hh.instances.clear()}isConnected(){return this.socket?.connected??!1}getSocket(){return this.socket}}hh.instances=new Set;class gh extends br{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 kt("limit must be between 1 and 50","limit","INVALID_LIMIT");this.logger.debug("Fetching weekly challenge leaderboard",{limit:t});const n={limit:String(t)},r=await this.http.get(gt.GET_LEADERBOARD,n),s=this.extractData(r);return this.logger.debug("Fetched weekly challenge leaderboard",{count:s.count}),{leaderboard:s}}async getTokenHistory(e){const{vaultAddress:t}=e;if("string"!=typeof t||""===t.trim())throw new kt("vaultAddress is required","vaultAddress","REQUIRED_FIELD");this.logger.debug("Fetching token weekly history",{vaultAddress:t});const n=gt.GET_TOKEN_HISTORY.replace(":vaultAddress",encodeURIComponent(t)),r=await this.http.get(n),s=this.extractData(r);return this.logger.debug("Fetched token weekly history",{count:s.length}),{snapshots:s}}}const mh=["CreateSale","BuyWithNative","BuyExactToken","SellWithNative","SellExactToken"];class fh{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 ph{constructor(e){this.bundleBaseUrl=kh(e.bundleBaseUrl),this.launchpadBaseUrl=kh(e.launchpadBaseUrl),this.signer=e.signer,this.walletAddress=""===e.walletAddress?"":Nn(e.walletAddress,"walletAddress"),this.requestor=e.httpRequestor??fetch.bind(globalThis),this.socketFactory=e.socketFactory??(e=>_(e,{transports:["websocket"]})),this.bundleSocketFactory=e.bundleSocketFactory}attach(e){const{bundleId:t,method:n,uniqueKey:r,tokenName:s}=e;if("string"!=typeof t||""===t)throw Ah("bundleId");if(i=n,!mh.some(e=>e===i))throw Ah("method");var i;if("string"!=typeof r||""===r)throw Ah("uniqueKey");if(void 0!==s&&("string"!=typeof s||""===s))throw Ah("tokenName");if("CreateSale"===n&&void 0===s)throw Ah("tokenName");const o={method:n,dto:{uniqueKey:r,...void 0===s?{}:{tokenName:s}},stringsInstructions:[]};return new fh({bundleId:t,uniqueKey:r,method:n,wait:e=>this.waitForResult(o,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 _a)return e;if(g(e)){const t=e instanceof Error?e.message:"The signature was rejected in the wallet.",n=m(e);return new _a(t,"WALLET_USER_REJECTED",{details:void 0===n?{}:{walletCode:n}})}const t=e instanceof Error?e.message:"Launchpad signing failed.";return new _a(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`,s=await this.requestor(r,{method:"POST",headers:{"content-type":"application/json","X-Wallet-Address":this.walletAddress},body:JSON.stringify({stringsInstructions:e.stringsInstructions,method:e.method,signedDto:n})}),i=await Nh(s);if(!s.ok)throw Th(s.status,i,r);const o=function(e){if("string"==typeof e&&""!==e)return e;if(!wh(e))throw new _a("Bundler returned no bundle id.","INVALID_BUNDLE_RESPONSE");const t=e.data,n=e.bundleId;if("string"==typeof t&&""!==t)return t;if(wh(t)&&"string"==typeof t.bundleId&&""!==t.bundleId)return t.bundleId;if("string"==typeof n&&""!==n)return n;throw new _a("Bundler returned no bundle id.","INVALID_BUNDLE_RESPONSE")}(i),a=bh(e.dto,"uniqueKey");return new fh({bundleId:o,uniqueKey:a,method:e.method,wait:t=>this.waitForResult(e,o,t)})}waitForResult(e,t,n={}){const r=n.timeoutMs??6e4,s=n.pollIntervalMs??2500,i=n.signal;return new Promise((n,o)=>{const a=this.confirmationUrl(e,t);if(!0===i?.aborted)return void o(Eh(e.method,t));const c=Date.now(),l=new AbortController,d=void 0===this.bundleSocketFactory;let u,h,g,m=!1;const f=()=>{p(()=>o(Eh(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())},E=()=>{p(()=>o(function(e,t){const n="string"==typeof e.dto.uniqueKey?e.dto.uniqueKey:"";return new _a(`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(E,r);try{u=(this.bundleSocketFactory??this.socketFactory)(this.bundleBaseUrl),h=e=>{const t=function(e){if(!wh(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?o(vh(t.data)):n(t)})},u.on(t,h)}catch{u=void 0,h=void 0}this.pollConfirmation({request:e,confirmationUrl:a,startedAt:c,timeoutMs:r,pollIntervalMs:s,signal:l.signal,onReadFailure:e=>{g=e}}).then(e=>{void 0===e?E():p(()=>n(e))},e=>p(()=>o(e instanceof Error?e:new Error(String(e)))))})}confirmationUrl(e,t){return"CreateSale"===e.method?function(e,t){const n=bh(t,"tokenName");return`${e}/v1/tokens/${encodeURIComponent(n)}`}(this.launchpadBaseUrl,e.dto):`${this.bundleBaseUrl}/bundle?id=${encodeURIComponent(t)}`}async pollConfirmation(e){const{request:t,confirmationUrl:n,startedAt:r,timeoutMs:s,pollIntervalMs:i,signal:o,onReadFailure:a}=e;for(;!o.aborted&&Date.now()-r<=s;){const e=await this.readConfirmation(t,n,o);if(o.aborted)return;if("processed"===e.kind)return e.result;if("failed"===e.kind)throw vh(e.data);a("read-failed"===e.kind?e.error:void 0);const c=s-(Date.now()-r);if(c<=0)break;await _h(Math.min(Math.max(0,i),c),o)}}async readConfirmation(e,t,n){try{const r=await this.requestor(t,{method:"GET",signal:n}),s=await Nh(r);if("CreateSale"===e.method)return r.ok?{kind:"processed",result:{status:"PROCESSED",data:Sh(s)}}:404===r.status||202===r.status?{kind:"pending"}:{kind:"read-failed",error:Th(r.status,s,t)};if(!r.ok)return{kind:"read-failed",error:Th(r.status,s,t)};const i=wh(s)?s.status:void 0;return"COMPLETED"===i||"PROCESSED"===i?{kind:"processed",result:{status:"PROCESSED",data:s}}:"FAILED"===i?{kind:"failed",data:s}:{kind:"pending"}}catch(e){const n=e instanceof Error?e.message:"The bundle confirmation read failed.";return{kind:"read-failed",error:new _a(n,"BUNDLE_REQUEST_FAILED",{details:{url:t}})}}}}function Eh(e,t){return new _a("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 Ah(e){return new _a(`Cannot attach to a launchpad bundle: ${e} is missing or not accepted.`,"INVALID_BUNDLE_ATTACHMENT",{details:{field:e}})}function vh(e){const t=yh(e)??"Launchpad bundle failed on chain.";return new _a(t,"BUNDLE_FAILED",{chainMessage:t})}function Th(e,t,n){const r=yh(t)??`Bundle request failed with HTTP ${e}`;return new _a(r,"BUNDLE_REQUEST_FAILED",{status:e,chainMessage:r,details:{body:t,url:n}})}function yh(e){if("string"==typeof e&&""!==e)return e;if(wh(e))for(const t of["chainMessage","message","Message","error"]){const n=e[t];if("string"==typeof n&&""!==n)return n;if(wh(n)){const e=yh(n);if(void 0!==e)return e}}}function Sh(e){return wh(e)?e.data??e.Data??e:e}function bh(e,t){const n=e[t];if("string"!=typeof n||""===n)throw new _a(`Missing ${t} in launchpad DTO.`,"INVALID_LAUNCHPAD_DTO");return n}async function Nh(e){try{return await e.json()}catch{return e.text()}}function wh(e){return"object"==typeof e&&null!==e}function kh(e){return e.replace(/\/$/u,"")}function _h(e,t){return new Promise(n=>{if(t.aborted)return void n();const r=()=>{clearTimeout(s),n()},s=setTimeout(()=>{t.removeEventListener("abort",r),n()},e);t.addEventListener("abort",r,{once:!0})})}function Ih(e,t){if(!/^\d+(\.\d+)?$/.test(e))throw new kt(`Quoted reverse bonding curve fee is not a non-negative number: ${e}`,"extraFees","INVALID_QUOTED_FEE");if(!Number.isFinite(t)||t<0)throw new kt(`Fee slippage factor must be a non-negative number, got ${String(t)}`,"maxAcceptableReverseBondingCurveFeeSlippageFactor","INVALID_FEE_SLIPPAGE_FACTOR");return new I(e).multipliedBy(new I(1).plus(new I(String(t)))).decimalPlaces(8,I.ROUND_UP).toFixed()}function Ch(e){return async t=>{const n=t.tokenName??await async function(e,t){const n=xa(t).type,r=await e.findTokenNameByVault(t,n);if(void 0===r)throw new kt(`Could not find the launchpad token for vault ${t}, so the reverse bonding curve fee ceiling cannot be quoted. Pass tokenName, or pass extraFees.maxAcceptableReverseBondingCurveFee explicitly.`,"tokenName","TOKEN_NOT_FOUND_FOR_VAULT");return r}(e,t.vaultAddress);return Ih((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 Dh={minFeePortion:"0.1",maxFeePortion:"0.5"},Rh=/^(?:\d+\.?\d*|\.\d+)$/u,Oh=/^[0-9A-Z]+$/u,Mh=/^[A-Za-z0-9]+$/u,Lh=new I("0.1"),Uh=new I("0.5");function Fh(e){if("string"!=typeof e||!Rh.test(e))return;const t=new I(e);return t.isFinite()?t.toFixed():void 0}function Ph(e){return"string"==typeof e&&""!==e}function xh(e,t,n){void 0!==n&&"string"!=typeof n&&e.push(`${t} must be a string`)}function Bh(e,t,n){void 0===n||Ph(n)||e.push(`${t} must be a non-empty string`)}function Gh(e){const t=[];if("object"!=typeof e||null===e)throw new kt("CreateSale input must be an object","data","VALIDATION_ERROR");const n={...e},r=n.tokenName;Ph(r)?Mh.test(r)||t.push("Token name can only contain letters and numbers"):t.push("Token name is required");const s=n.tokenSymbol;Ph(s)?Oh.test(s.toUpperCase())||t.push("Token symbol can only contain letters and numbers"):t.push("Token symbol is required");const i=n.tokenDescription;Ph(i)?i.length>1e3&&t.push("Token description must be at most 1000 characters"):t.push("Token description is required");const o=n.tokenImage;Ph(o)?o.length>500&&t.push("Token image must be at most 500 characters"):t.push("Token image is required");const a=n.preBuyQuantity;void 0!==a&&void 0===Fh(a)&&t.push("preBuyQuantity must be a non-negative decimal number");for(const e of["websiteUrl","telegramUrl","twitterUrl","instagramUrl","facebookUrl","redditUrl","tiktokUrl"])xh(t,e,n[e]);Bh(t,"tokenCategory",n.tokenCategory),Bh(t,"tokenCollection",n.tokenCollection);const c=n.saleStartTime;if(void 0===c||Number.isInteger(c)||t.push("saleStartTime must be an integer"),function(e,t){if(void 0!==t&&("object"!=typeof t||null===t))return void e.push("reverseBondingCurveConfiguration must be an object");const n=t??{},r=n.minFeePortion??Dh.minFeePortion,s=n.maxFeePortion??Dh.maxFeePortion,i=Fh(r),o=Fh(s);if(void 0===i&&e.push("minFeePortion must be a decimal number"),void 0===o&&e.push("maxFeePortion must be a decimal number"),void 0===i||void 0===o)return;const a=new I(i),c=new I(o);a.isLessThan(Lh)&&e.push("minFeePortion must be greater than or equal to 0.1"),c.isGreaterThan(Uh)&&e.push("maxFeePortion must be less than or equal to 0.5"),a.isGreaterThan(c)&&e.push("minFeePortion must be less than or equal to maxFeePortion")}(t,n.reverseBondingCurveConfiguration),t.length>0)throw new kt(t.join("; "),"data","VALIDATION_ERROR")}class $h{constructor(e){this.transport=e.transport,this.walletAddress=""===e.walletAddress?"":Nn(e.walletAddress,"walletAddress"),this.sellFeeCeiling=e.sellFeeCeiling}createSale(e){Gh(e);const t=function(e,t){const n={tokenName:e.tokenName,tokenSymbol:e.tokenSymbol,tokenDescription:e.tokenDescription,tokenImage:e.tokenImage,preBuyQuantity:Fh(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??Kh(t)},r=e.reverseBondingCurveConfiguration;n.reverseBondingCurveConfiguration={minFeePortion:Fh(r?.minFeePortion??Dh.minFeePortion),maxFeePortion:Fh(r?.maxFeePortion??Dh.maxFeePortion)},void 0!==e.saleStartTime&&(n.saleStartTime=e.saleStartTime);return n}(e,this.walletAddress);return this.transport.submit({method:"CreateSale",dto:t,stringsInstructions:Ga(e)})}attach(e){return this.transport.attach(e)}buyWithNative(e){return this.submitTrade("BuyWithNative",e,{nativeTokenQuantity:e.quantity,expectedToken:e.expectedAmount})}buyExactToken(e){return this.submitTrade("BuyExactToken",e,{tokenQuantity:e.quantity,expectedNativeToken:e.expectedAmount})}sellWithNative(e){return this.submitTrade("SellWithNative",e,{nativeTokenQuantity:e.quantity,expectedToken:e.expectedAmount})}sellExactToken(e){return this.submitTrade("SellExactToken",e,{tokenQuantity:e.quantity,expectedNativeToken:e.expectedAmount})}async submitTrade(e,t,n){const r={vaultAddress:t.vaultAddress,...n,extraFees:t.extraFees??await this.defaultExtraFees(e,t),uniqueKey:t.uniqueKey??Kh(this.walletAddress)};return this.transport.submit({method:e,dto:r,stringsInstructions:Ba(t.vaultAddress)})}async defaultExtraFees(e,t){if("BuyWithNative"===e||"BuyExactToken"===e)return{maxAcceptableReverseBondingCurveFee:"0"};if(void 0===this.sellFeeCeiling)throw new kt("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 Kh(e){return`galaswap-operation-${k()}-${Date.now()}-${e}`}function Hh(e,t=3e4){return C.create({baseURL:e,timeout:t,headers:{"Content-Type":"application/json"}})}const Wh=new Set(["accesstoken","refreshtoken","token","password","privatekey","secret","apikey","api_key","rawkey","authorization","x-api-key","bearer","streamadminapikey","userapikey","signature","signedpayload"]);function Vh(e,t=0){if(t>5)return"[...]";if(null==e)return e;if(Array.isArray(e))return e.map(e=>Vh(e,t+1));if(e instanceof Map){const n={};for(const[r,s]of e.entries()){const e=String(r);n[e]=Wh.has(e.toLowerCase())?"[REDACTED]":Vh(s,t+1)}return n}if("object"==typeof e){const n={};for(const[r,s]of Object.entries(e))n[r]=Wh.has(r.toLowerCase())?"[REDACTED]":Vh(s,t+1);return n}return e}class jh{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 En({debug:this.debug,context:"HttpClient"});const r=t.baseUrl??ko("stage").launchpadBaseUrl,s=t.timeout??6e4;this.axios=Hh(r,s),t.headers&&(this.axios.defaults.headers.common={...this.axios.defaults.headers.common,...t.headers}),void 0!==this.session&&"omit"!==this.session.credentials&&(this.axios.defaults.withCredentials=!0),this.setupInterceptors()}async request(e){return(await this.requestWithMeta(e)).data}async requestWithMeta(e){return yo(async()=>{const t=void 0!==this.session&&!1!==e.withSession&&!function(e){return void 0!==e&&Object.keys(e).some(e=>"authorization"===e.toLowerCase())}(e.headers),n=t&&void 0!==this.session?await this.session.accessToken():null,r=this.toAxiosConfig(e,n);e.headers&&this.logger.debug("Custom headers provided:",Object.keys(r.headers??{}));const s=e.data instanceof FormData?"[FormData object - multipart/form-data]":Vh(e.data);this.logger.debug("Request:",{method:e.method,url:e.url?.split("?")[0],baseURL:this.axios.defaults.baseURL,params:Vh(r.params),data:s,isFormData:e.data instanceof FormData,contentType:r.headers?.["Content-Type"]??"not set"});const i=await this.sendWithSession(e,r,t,n),o=function(e){const t={};if(null==e||"object"!=typeof e)return t;for(const[n,r]of Object.entries(e))"string"==typeof r?t[n.toLowerCase()]=r:"number"!=typeof r&&"boolean"!=typeof r||(t[n.toLowerCase()]=String(r));return t}(i.headers);return this.logger.debug("Response:",{status:i.status,data:Vh(i.data),transactionId:o["x-transaction-id"],blockNumber:o["x-block-number"]}),{data:i.data,headers:o,status:i.status}},`HTTP ${e.method} ${e.url}`,this.logger)}toAxiosConfig(e,t){const n=null===t?e.headers:{...e.headers,Authorization:`Bearer ${t}`},r={method:e.method,url:e.url,data:e.data,...void 0!==e.params&&{params:wl(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 D(n);e.set("Content-Type",void 0),r.headers=e,this.logger.debug("FormData detected - clearing the JSON Content-Type default for the multipart upload")}return r}async sendWithSession(e,t,n,r){try{return await this.axios.request(t)}catch(t){if(!n||void 0===this.session||!function(e){if("object"!=typeof e||null===e||!("response"in e))return!1;const t=e.response;return"object"==typeof t&&null!==t&&"status"in t&&401===t.status}(t))throw t;const s=await this.session.onUnauthorized(r);if(null===s)throw t;return this.logger.debug("Retrying once with the refreshed session token"),await this.axios.request(this.toAxiosConfig(e,s))}}async get(e,t,n){return this.request({method:"GET",url:e,...t&&{params:t},...n&&{headers:n}})}async post(e,t,n){return this.request({method:"POST",url:e,data:t,...n&&{headers:n}})}async postWithMeta(e,t,n){return this.requestWithMeta({method:"POST",url:e,data:t,...n&&{headers:n}})}async put(e,t,n){return this.request({method:"PUT",url:e,data:t,...n&&{headers:n}})}async delete(e,t,n){return this.request({method:"DELETE",url:e,...t&&{params:t},...n&&{headers:n}})}async patch(e,t,n){return this.request({method:"PATCH",url:e,data:t,...n&&{headers:n}})}getAddress(){return this.auth.getAddress()}getEthereumAddress(){return this.auth.getEthereumAddress()}async signMessage(e){return(await this.auth.signMessage(e)).signature}async signTypedData(e,t,n){return await this.auth.signTypedData(e,t,n)}async signCustomMessage(e){return yo(async()=>{const t=await this.auth.generateCustomSignature(e);return this.logger.debug("Generated custom signature:",{message:e,address:t.address,ethereumAddress:this.auth.getEthereumAddress()}),{signature:t.signature,address:t.address,ethereumAddress:this.auth.getEthereumAddress()}},"Failed to generate custom signature for message",this.logger)}setupInterceptors(){this.requestInterceptorId=this.axios.interceptors.request.use(async e=>{if(e.headers??(e.headers={}),this.signRequests&&this.auth?.hasWallet()){const t=await this.auth.generateSignature();e.headers.Sign=t.signature,this.logger.debug("Added signature header:",{address:t.address,message:t.message,timestamp:t.timestamp})}else this.logger.debug("Skipping signature header (no wallet, or signRequests is off)");return e.data instanceof FormData||(e.headers["Content-Type"]="application/json"),this.logger.debug("Final request header keys being sent:",Object.keys(e.headers)),e},e=>Promise.reject(e instanceof Error?e:new Error(String(e)))),this.responseInterceptorId=this.axios.interceptors.response.use(e=>e,e=>{const t=e;if(void 0!==t.response){const n=t.response.data,r={message:n?.message??Ut(e),...n&&"string"==typeof n.error&&""!==n.error&&{error:n.error},statusCode:t.response.status,...n&&Boolean(n.details)&&{details:n.details},...n&&Boolean(n.timestamp)&&{timestamp:n.timestamp},...n&&Boolean(n.path)&&{path:n.path}};t.launchpadError=r,this.logger.error("Backend error:",r)}else void 0!==t.request?this.logger.error("Network error:",t.message??"Unknown error"):this.logger.error("Request setup error:",t.message??"Unknown error");return Promise.reject(e instanceof Error?e:new Error(String(e)))})}cleanup(){void 0!==this.requestInterceptorId&&(this.axios.interceptors.request.eject(this.requestInterceptorId),this.requestInterceptorId=void 0),void 0!==this.responseInterceptorId&&(this.axios.interceptors.response.eject(this.responseInterceptorId),this.responseInterceptorId=void 0),this.logger.debug("Interceptors cleaned up")}}class qh extends Error{constructor(e,t){super(e),this.cause=t,this.name="WebSocketError"}}class zh extends qh{constructor(e,t){super(`WebSocket confirmation timeout for transaction ${e} after ${t}ms`),this.name="WebSocketTimeoutError"}}class Qh 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 Xh(e,t){if(ar(e))throw new qh(`Invalid WebSocket response received for transaction ${t}: response is null or undefined`);if("object"!=typeof e)throw new qh(`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 qh(`Invalid WebSocket response received for transaction ${t}: missing status field`)}function Yh(e,t,n,r){Xh(e,t);const s=e,i=s.data??{};if(!function(e){if(ar(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 qh(`Invalid trade data received for transaction ${t}`);const o={transactionId:t,type:n,method:"native"===r.type?"native":"exact",inputAmount:i.inputQuantity??r.amount,outputAmount:i.outputQuantity??r.expectedAmount??"0",totalFees:i.totalFees??"0",tokenName:r.tokenName,vaultAddress:i.vaultAddress??"",timestamp:Date.now()};return void 0!==s.blockHash&&(o.blockHash=s.blockHash),void 0!==s.gasUsed&&(o.gasUsed=s.gasUsed),void 0!==r.slippageToleranceFactor&&(o.slippageTolerance=r.slippageToleranceFactor),o}function Jh(e){return void 0!==e&&b(e)?new T(e.exportPrivateKey()):void 0}const Zh={MUSIC:"$MUSIC",GMUSIC:"$GMUSIC"};function eg(e){if(void 0===e||!("walletAddress"in e))return;const t=e.walletAddress;return"string"==typeof t&&""!==t?t:void 0}const tg=/^(?:eth\||0x)([0-9a-fA-F]{40})$/;function ng(e,t,n){if(void 0===e||void 0===t)return;const r=tg.exec(e)?.[1],s=tg.exec(t)?.[1];if(void 0!==r&&void 0!==s&&r.toLowerCase()!==s.toLowerCase())throw jt(`${n} ${t} is not the identity of the configured signing key (${e}); writes would be signed as the key, not as ${n}.`,n)}class rg{constructor(e){let t,n;this.walletGeneration=0,e.walletProvider?(t=e.walletProvider,n=Jh(e.walletProvider)):e.wallet&&(n=e.wallet,t=S.fromWallet(e.wallet)),this.wallet=n;const r=e.env??"prod",s=ko(r);this.environment=r,this.config={baseUrl:e.launchpadBaseUrl??s.launchpadBaseUrl,gatewayBaseUrl:s.gatewayBaseUrl,bundleBaseUrl:s.bundleBaseUrl,webSocketUrl:s.webSocketUrl,dexApiBaseUrl:s.dexApiBaseUrl,dexBackendBaseUrl:s.dexBackendBaseUrl,launchpadFrontendUrl:s.launchpadFrontendUrl,timeout:3e4,debug:!1,...e};const i=e.signer??(void 0!==n?new Ua(n.privateKey):void 0),o=void 0!==n?`eth|${n.address.slice(2)}`:eg(i),a=void 0===e.walletAddress?void 0:Nn(e.walletAddress,"walletAddress"),c=void 0===e.galaChainAddress?void 0:Nn(e.galaChainAddress,"galaChainAddress");ng(o,a,"walletAddress"),ng(o,c,"galaChainAddress");const l=a??c??(void 0!==n?`eth|${n.address.slice(2)}`:eg(i)),d=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."))},u=l??"";this.tokenWriter=void 0===n&&void 0!==e.signer&&void 0!==l?{signer:e.signer,walletAddress:l}:void 0;const h=new ph({bundleBaseUrl:this.config.bundleBaseUrl,launchpadBaseUrl:this.config.baseUrl,signer:d,walletAddress:u,...void 0!==e.httpRequestor&&{httpRequestor:e.httpRequestor},bundleSocketFactory:e.bundleSocketFactory}),g=Ch({getTradeQuote:e=>this.tradingQuotesService.getTradeQuote(e),findTokenNameByVault:(e,t)=>this.findTokenNameByVault(e,t),defaultFeeSlippageFactor:()=>this.maxAcceptableReverseBondingCurveFeeSlippageFactor});this.sellFeeCeiling=g,this.launchpad=new $h({transport:h,walletAddress:u,sellFeeCeiling:g}),this.logger=new En({debug:this.config.debug??!1,context:"LaunchpadSDK"}),this.validateConfiguration(),this.slippageToleranceFactor=void 0===e.slippageToleranceFactor?rg.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR:this.parseSlippageToleranceFactor(e.slippageToleranceFactor),this.maxAcceptableReverseBondingCurveFeeSlippageFactor=void 0===e.maxAcceptableReverseBondingCurveFeeSlippageFactor?rg.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR:this.parseFeeSlippageFactor(e.maxAcceptableReverseBondingCurveFeeSlippageFactor),this.calculateAmountMode=e.calculateAmountMode??rg.DEFAULT_CALCULATE_AMOUNT_MODE,this.galaChainAddressOverride=c,this.signerWalletAddress=a??(void 0===n?l:void 0),this.auth=new No({wallet:n,walletProvider:t,messagePrefix:"Create a GalaChain Wallet"});const m=e.session;if(void 0!==m){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)}(m))throw jt("session must provide accessToken() and onUnauthorized()","session");if(void 0!==e.accessToken&&""!==e.accessToken)throw jt("Pass either session or accessToken, not both: the session owns the token.","accessToken")}if(this.jwtAuth=void 0===m?new vo:new To,void 0!==e.accessToken&&""!==e.accessToken){const t=e.accessTokenExpiresIn??86400;this.jwtAuth.setToken(e.accessToken,t)}this.http=new jh(this.auth,this.config,{signRequests:!0,session:m}),this.sessionAuth=new bo(this.http,this.auth,this.jwtAuth,e.debug??!1,m);const f={signRequests:!1};this.galaChainHttp=new jh(this.auth,{...this.config,baseUrl:this.config.gatewayBaseUrl},f),this.bundleHttp=new jh(this.auth,{...this.config,baseUrl:this.config.bundleBaseUrl},f),this.dexApiHttp=new jh(this.auth,{...this.config,baseUrl:this.config.dexApiBaseUrl},f),this.dexBackendHttp=new jh(this.auth,{...this.config,baseUrl:this.config.dexBackendBaseUrl},f),this.galaChainPublicAxios=Hh(this.config.gatewayBaseUrl,this.config.timeout??3e4),this.cache=new kr(e.debug??!1),this.launchpadService=new Zl(this.http,this.jwtAuth),this.tokenResolverService=new ah(this.launchpadService.poolService),this.launchpadAPI=new mo(this.http,this.logger,this.bundleHttp,this.calculateAmountMode,this.launchpad),this.galaChainService=new Al(this.galaChainHttp,n,this.tokenResolverService,e.debug??!1,this.galaChainPublicAxios,this.tokenWriter),this.priceService=new Tc(this.dexBackendHttp,this.cache,e=>this.galaChainService.fetchTokenDetails(e),e.debug??!1),this.bundleService=this.createBundleService(),this.websocketService=new hh({url:this.config.webSocketUrl},this.config.debug),this.nftCollectionService=new Pd(this.galaChainHttp),this.tradingQuotesService=new ch(this.http,e.debug??!1)}createOverrideSdk(e){if(!ir(e))throw jt("Invalid privateKey: must be a non-empty string","privateKey");if(!e.match(/^0x[a-fA-F0-9]{64}$/))throw jt('Invalid privateKey format: must be "0x" followed by 64 hexadecimal characters',"privateKey");const t=new T(e),n={...this.config,wallet:t};return new rg(n)}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 Ht("wallet","Wallet");return this.wallet}assertTokenWriter(){if(void 0===this.wallet&&void 0===this.tokenWriter)throw Ht("wallet","Wallet")}setWallet(e){if(null==e||"object"!=typeof e||!("address"in e))throw new kt("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 Za(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 Al(this.galaChainHttp,this.wallet,this.tokenResolverService,this.config.debug??!1,this.galaChainPublicAxios)}setWalletProvider(e){this.auth.setWalletProvider(e),this.wallet=e?Jh(e):void 0,this.onWalletChanged()}getWallet(){return this.wallet}get events(){return this.getEventsBatcherService()}getWalletProvider(){return this.auth.getWalletProvider()}hasWallet(){return this.auth.hasWallet()}getConfig(){const{wallet:e,walletProvider:t,signer:n,httpRequestor:r,streamAdminApiKey:s,userApiKey:i,accessToken:o,headers:a,...c}=this.config;return{...c,...void 0!==s&&{streamAdminApiKey:"[REDACTED]"},...void 0!==i&&{userApiKey:"[REDACTED]"},...void 0!==o&&{accessToken:"[REDACTED]"},...void 0!==a&&{headers:Object.fromEntries(Object.keys(a).map(e=>[e,"[REDACTED]"]))},environment:this.environment,slippageToleranceFactor:this.slippageToleranceFactor,maxAcceptableReverseBondingCurveFeeSlippageFactor:this.maxAcceptableReverseBondingCurveFeeSlippageFactor,calculateAmountMode:this.calculateAmountMode,gasFee:hn.GAS_FEE}}getVersion(){return Do}getUrlByTokenName(e){const t=this.config.launchpadFrontendUrl;if(void 0===t||""===t)throw jt("launchpadFrontendUrl not configured in SDK","launchpadFrontendUrl");return`${t.replace(/\/$/,"")}/buy-sell/${e}`}async fetchPools(e){const t=await this.launchpadService.fetchPools(e??{});return await this.warmCacheFromPools(t.items),t}async fetchAllPools(e){const t=await this.launchpadService.fetchAllPools(e);return await this.warmCacheFromPools(t.items),t}async fetchTokenDistribution(e){return this.launchpadService.fetchTokenDistribution(e)}async getTopHolders(e,t=10){const n=await this.fetchTokenDistribution(e),r=Math.min(t,100);return n.holders.slice(0,r).map((e,t)=>({...e,rank:t+1}))}async getHolderCount(e){const t=await this.fetchTokenDistribution(e);return{count:t.totalHolders,totalBalance:t.totalSupply}}async getHolderRank(e,t){const n=wn(t,"userAddress"),r=await this.fetchTokenDistribution(e),s=r.holders.findIndex(e=>e.address.toLowerCase()===n);if(-1===s)return null;const i=r.holders[s];return void 0===i?null:{rank:s+1,balance:i.balance,holderCount:r.totalHolders}}async getHoldersByBalance(e,t){const n=await this.fetchTokenDistribution(e),r=t?.minBalance??0,s=t?.maxBalance??1/0,i=Math.min(t?.limit??100,1e3),o=new Map;return n.holders.forEach((e,t)=>{o.set(e.address,t+1)}),n.holders.filter(e=>{const t=parseFloat(e.balance);return t>=r&&t<=s}).map(e=>({...e,rank:o.get(e.address)??0})).slice(0,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 kt("fetchTokenPrice prices a launchpad token by tokenName; a token by class key is priced by gswap-sdk (gSwap.market.getPrice)","tokenId",wt.INVALID_PARAMETERS);const n=t.tokenName;return this.priceService.fetchLaunchpadTokenSpotPrice("string"==typeof n?n:"",e=>this.launchpadAPI.calculateBuyAmount(e),e=>this.fetchPoolDetails(e))}async fetchTokenDetails(e){return this.galaChainService.fetchTokenDetails(e)}async fetchLaunchTokenFee(){return this.tradingQuotesService.fetchLaunchpadFee()}async fetchTokenClassesWithSupply(e){return this.galaChainService.fetchTokenClassesWithSupply(e)}async fetchPoolDetails(e){const t=await this.launchpadAPI.fetchPoolDetails(e),n=await this.launchpadAPI.fetchPoolDetailsForCalculation(e);return t.currentSupply=n.currentSupply,t.reverseBondingCurveMaxFeeFactor=n.reverseBondingCurveMaxFeeFactor,t.reverseBondingCurveMinFeeFactor=n.reverseBondingCurveMinFeeFactor,t.reverseBondingCurveNetFeeFactor=n.reverseBondingCurveNetFeeFactor,t.tokenName=e,t}async fetchPoolDetailsForCalculation(e){return this.launchpadAPI.fetchPoolDetailsForCalculation(e)}async isTokenGraduated(e){return(await this.fetchPoolDetails(e)).isGraduated}async fetchVolumeData(e){return this.launchpadService.fetchVolumeData(e)}async fetchTrades(e){return this.launchpadService.fetchTrades(e)}async fetchGalaBalance(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Kn}),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(jt("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,jt(`The bridge and wrap methods use @gala-chain/gala-core-sdk/bridge, which needs its optional peers ethers, @solana/web3.js and @solana/spl-token installed: ${Ut(e)}`,"bridge")})),this.coreBridgeLoad)}async coreBridge(){const e=this.walletGeneration,t=await this.loadCoreBridge();if(e!==this.walletGeneration)throw jt("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 Ua(t.privateKey)}})}return this._wrapService}getStreamingService(){return this._streamingService??(this._streamingService=new ku(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._streamingService}getStreamChatService(){return this._streamChatService??(this._streamChatService=new iu(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._streamChatService}getBanService(){return this._banService??(this._banService=new Aa(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._banService}getTokenBanService(){return this._tokenBanService??(this._tokenBanService=new oh(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._tokenBanService}getAIModerationService(){return this._aiModerationService??(this._aiModerationService=new zo(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._aiModerationService}getWeeklyChallengeService(){return this._weeklyChallengeService??(this._weeklyChallengeService=new gh(this.http,this.config.debug??!1)),this._weeklyChallengeService}getOEmbedService(){return this._oembedService??(this._oembedService=new Bd(this.http,this.config.debug??!1)),this._oembedService}getPlatformStatsService(){return this._platformStatsService??(this._platformStatsService=new ru(this.http,this.config.debug??!1)),this._platformStatsService}getHealthService(){return this._healthService??(this._healthService=new vl(this.http,this.config.debug??!1)),this._healthService}getEventsQueryService(){return this._eventsQueryService??(this._eventsQueryService=new Rc(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._eventsQueryService}getNotificationService(){return this._notificationService??(this._notificationService=new xd(this.http,this.config.debug??!1,this.jwtAuth)),this._notificationService}getClientConfigService(){return this._clientConfigService??(this._clientConfigService=new ec(this.http,this.config.debug??!1)),this._clientConfigService}getApiKeyService(){return this._apiKeyService??(this._apiKeyService=new aa(this.http,this.jwtAuth,this.config.debug??!1)),this._apiKeyService}getModeratorService(){return this._moderatorService??(this._moderatorService=new Cd(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._moderatorService}getFlagService(){return this._flagService??(this._flagService=new mc(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._flagService}getOverseerService(){return this._overseerService??(this._overseerService=new eu(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._overseerService}getWebSocketAdminService(){return this._websocketAdminService??(this._websocketAdminService=new lh(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._websocketAdminService}getContentReactionService(){return this._contentReactionService??(this._contentReactionService=new Ec(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}}}resolveReferralAddress(e){return void 0===e||""===e?this.getAddress():Nn(e,"address")}getMessagesService(){return this._messagesService??(this._messagesService=new hd(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._messagesService}getRestrictedNamesService(){return this._restrictedNamesService??(this._restrictedNamesService=new su(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.userApiKey)),this._restrictedNamesService}getPlatformConfigService(){return this._platformConfigService??(this._platformConfigService=new nu(this.http,this.jwtAuth,this.config.debug??!1)),this._platformConfigService}getEventsBatcherService(){return this._eventsBatcherService??(this._eventsBatcherService=new bc(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 Ju({url:this.config.streamWebSocketUrl,tokenProvider:()=>this.streamSocketToken(),...void 0!==this.config.streamReconnectAttempts&&{reconnectAttempts:this.config.streamReconnectAttempts},...void 0!==this.config.streamReconnectDelay&&{reconnectDelay:this.config.streamReconnectDelay},...void 0!==this.config.streamReconnectDelayMax&&{reconnectDelayMax:this.config.streamReconnectDelayMax}},this.config.debug??!1)}return this._streamWebSocketService}async streamSocketToken(){const e=this.config.session;return void 0!==e?e.accessToken():this.ensureValidToken()}get realtime(){return this.getStreamWebSocketService()}async fetchEthereumWalletTokenBalance(e,t){return this.getBridgeService(await this.coreBridge()).fetchEthereumWalletTokenBalance(e,t)}async fetchEthereumWalletNativeBalance(e){return this.getBridgeService(await this.coreBridge()).fetchEthereumWalletNativeBalance(e)}async fetchSolanaWalletTokenBalance(e,t){return this.getBridgeService(await this.coreBridge()).fetchSolanaWalletTokenBalance(e,t)}async fetchSolanaWalletNativeBalance(e){return this.getBridgeService(await this.coreBridge()).fetchSolanaWalletNativeBalance(e)}async requestSolanaDevnetAirdrop(e,t){return this.getBridgeService(await this.coreBridge()).requestSolanaDevnetAirdrop(e,t)}async getSolanaTransactionStatus(e){return this.getBridgeService(await this.coreBridge()).getSolanaTransactionStatus(e)}async getEthereumTransactionStatus(e){return this.getBridgeService(await this.coreBridge()).getEthereumTransactionStatus(e)}async fetchEthereumWalletAllBalances(e){return this.getBridgeService(await this.coreBridge()).fetchEthereumWalletAllBalances(e)}async fetchSolanaWalletAllBalances(e){return this.getBridgeService(await this.coreBridge()).fetchSolanaWalletAllBalances(e)}async fetchBridgeableTokensByNetwork(e){return this.getBridgeableTokenService(await this.coreBridge()).fetchBridgeableTokensByNetwork(e)}async fetchAllBridgeableTokensByNetwork(e){return this.getBridgeableTokenService(await this.coreBridge()).fetchAllBridgeableTokensByNetwork(e)}async fetchAllTokensBridgeableToEthereum(){return this.getBridgeableTokenService(await this.coreBridge()).fetchAllTokensBridgeableToEthereum()}async fetchAllTokensBridgeableToSolana(){return this.getBridgeableTokenService(await this.coreBridge()).fetchAllTokensBridgeableToSolana()}async isTokenBridgeableToNetwork(e){return this.getBridgeableTokenService(await this.coreBridge()).isTokenBridgeableToNetwork(e)}async isTokenBridgeableToEthereum(e){return this.getBridgeableTokenService(await this.coreBridge()).isTokenBridgeableToEthereum(e)}async isTokenBridgeableToSolana(e){return this.getBridgeableTokenService(await this.coreBridge()).isTokenBridgeableToSolana(e)}async fetchWrappableTokens(e={}){return this.getWrappableTokenService(await this.coreBridge()).fetchWrappableTokens(e)}async fetchAllWrappableTokens(){return this.getWrappableTokenService(await this.coreBridge()).fetchAllWrappableTokens()}async getWrappableToken(e){return this.getWrappableTokenService(await this.coreBridge()).getWrappableToken(e)}async getWrapCounterpart(e){return this.getWrappableTokenService(await this.coreBridge()).getWrapCounterpart(e)}async isTokenWrappable(e){return this.getWrappableTokenService(await this.coreBridge()).isTokenWrappable(e)}async wrapToken(e){return this.getWrapService(await this.coreBridge()).wrapToken(e)}async unwrapToken(e){return this.getWrapService(await this.coreBridge()).unwrapToken(e)}async estimateWrapFee(e,t){return this.getWrapService(await this.coreBridge()).estimateWrapFee(e,t)}async estimateUnwrapFee(e,t){return this.getWrapService(await this.coreBridge()).estimateUnwrapFee(e,t)}async login(){return this.sessionAuth.login()}async loginWithSignature(e){return this.sessionAuth.loginWithSignature(e)}async loginWithDevBypass(e){return this.sessionAuth.loginWithDevBypass(e)}async refreshToken(){return this.sessionAuth.refresh()}async logout(e){return this.sessionAuth.logout(e)}isAuthenticated(){return this.sessionAuth.isAuthenticated()}shouldRefreshToken(e){return this.sessionAuth.shouldRefresh(e)}async getSession(){return this.sessionAuth.getSession()}getAccessToken(){return this.sessionAuth.getAccessToken()}async ensureValidToken(e){return this.sessionAuth.ensureValidToken(e)}async startStream(e){return this.getStreamingService().startStream(e)}async stopStream(e){return this.getStreamingService().stopStream(e)}async disableStream(e){return this.getStreamingService().disableStream(e)}async enableStream(e){return this.getStreamingService().enableStream(e)}async resetStreamKey(e){return this.getStreamingService().resetStreamKey(e)}async getStreamCredentials(e){return this.getStreamingService().getStreamCredentials(e)}async getStreamRecordings(e){return this.getStreamingService().getRecordings(e)}async getRecordingDownload(e,t){return this.getStreamingService().getRecordingDownload(e,t)}async deleteRecording(e,t){return this.getStreamingService().deleteRecording(e,t)}async getSimulcastTargets(e){return this.getStreamingService().getSimulcastTargets(e)}async addSimulcastTarget(e){return this.getStreamingService().addSimulcastTarget(e)}async removeSimulcastTarget(e,t){return this.getStreamingService().removeSimulcastTarget(e,t)}async getGlobalStreamingStatus(){return this.getStreamingService().getGlobalStreamingStatus()}async setNextLiveStreamCountdown(e,t){return this.getStreamingService().setNextLiveStreamCountdown(e,t)}async setGlobalStreamingEnabled(e){const t=this.getStreamingService();return e?t.enableGlobalStreaming():t.disableGlobalStreaming()}async getStreamRole(e){return this.getStreamingService().getStreamRole(e)}async getAvailableRoles(){return this.getStreamingService().getAvailableRoles()}async getTokenAccess(e){return this.getStreamingService().getTokenAccess(e)}async getChatStatus(e){return this.getStreamChatService().getChatStatus(e)}async disableChat(e){return this.getStreamChatService().disableChat(e)}async enableChat(e){return this.getStreamChatService().enableChat(e)}async getPinnedChatMessage(e){const t=this.getMessagesService();return{tokenName:e,pinnedMessage:(await t.getPinnedMessage(e)).message}}async pinChatMessage(e,t){const n=this.getMessagesService();await n.pinMessage(t);return{tokenName:e,pinnedMessage:(await n.getPinnedMessage(e)).message}}async unpinChatMessage(e){const t=this.getMessagesService(),n=await t.getPinnedMessage(e);return n.message?(await t.unpinMessage(n.message.messageId),{tokenName:e,unpinned:!0,unpinnedMessageId:n.message.messageId}):{tokenName:e,unpinned:!1}}async setSlowMode(e,t){return this.getStreamChatService().setSlowMode(e,t)}async createBan(e){return this.getBanService().createBan(e)}async removeBan(e){return this.getBanService().removeBan(e)}async listBans(e){return this.getBanService().listBans(e)}async getBanStatus(e){return this.getBanService().getBanStatus(e)}async getActiveUsers(e){return this.getBanService().getActiveUsers(e)}async createGlobalBan(e){return this.getBanService().createGlobalBan(e)}async removeGlobalBan(e){return this.getBanService().removeGlobalBan(e)}async listGlobalBans(e){return this.getBanService().listGlobalBans(e)}async getGlobalBan(e){return this.getBanService().getGlobalBan(e)}async createApiKey(e){return this.getApiKeyService().create(e)}async listApiKeys(e={}){return this.getApiKeyService().findAll(e)}async getApiKey(e){return this.getApiKeyService().findOne(e)}async updateApiKey(e,t){return this.getApiKeyService().update(e,t)}async revokeApiKey(e){return this.getApiKeyService().revoke(e)}getApiKeyRoles(){return this.getApiKeyService().getRoles()}async createModeratorInvite(e){return this.getModeratorService().createInvite(e)}async claimModeratorInvite(e){return this.getModeratorService().claimInvite(e)}async getModeratedTokens(e){return this.getModeratorService().getModeratedTokens(e)}async listModeratorInvites(e){return this.getModeratorService().listInvites(e)}async getActiveModerators(e){return(await this.listModeratorInvites({tokenName:e,status:"CLAIMED"})).items.filter(e=>null!==e.claimedBy).map(e=>({address:e.claimedBy,role:e.role,joinedAt:e.claimedAt,inviteId:e.id}))}async revokeModeratorInvite(e){return this.getModeratorService().revokeInvite(e)}async updateModeratorInviteRole(e){return this.getModeratorService().updateInviteRole(e)}async updateModeratorInvite(e){return this.getModeratorService().updateInvite(e)}async getModeratorInviteByCode(e){return this.getModeratorService().getInviteByCode(e)}async createFlag(e){return this.getFlagService().createFlag(e)}async listFlags(e){return this.getFlagService().listFlags(e)}async listGlobalFlags(e={}){return this.getFlagService().listGlobalFlags(e)}async dismissFlag(e){return this.getFlagService().dismissFlag(e)}async actionFlag(e){return this.getFlagService().actionFlag(e)}async createOverseerInvite(e={}){return this.getOverseerService().createInvite(e)}async listOverseerInvites(e={}){return this.getOverseerService().listInvites(e)}async getOverseerInviteByCode(e){return this.getOverseerService().getInviteByCode(e)}async claimOverseerInvite(e){return this.getOverseerService().claimInvite(e)}async revokeOverseerInvite(e){return this.getOverseerService().revokeInvite(e)}async listOverseers(e={}){return this.getOverseerService().listOverseers(e)}async createOverseerDirect(e){return this.getOverseerService().createOverseerDirect(e)}async revokeOverseer(e){return this.getOverseerService().revokeOverseer(e)}async getMyOverseerStatus(){return this.getOverseerService().getMyStatus()}async getOverseerSummary(){return this.getOverseerService().getSummary()}async getBanStats(){return this.getOverseerService().getBanStats()}async getTokenBanStats(){return this.getOverseerService().getTokenBanStats()}async getInviteStats(){return this.getOverseerService().getInviteStats()}async getFlagStats(){return this.getOverseerService().getFlagStats()}async getUserStats(){return this.getOverseerService().getUserStats()}async listOverseerUsers(e){return this.getOverseerService().listOverseerUsers(e)}async getOverseerUserSummary(e){return this.getOverseerService().getOverseerUserSummary(e)}async flushCacheByAddress(e){return this.getOverseerService().flushCacheByAddress(e)}async flushCacheByToken(e){return this.getOverseerService().flushCacheByToken(e)}async flushAllCache(e){return this.getOverseerService().flushAllCache(e)}async flushWalletAliasCache(e){return this.getOverseerService().flushWalletAliasCache(e)}async emitWebSocketEvent(e){return this.getWebSocketAdminService().emitEvent(e)}async emitTradeExecuted(e,t){return this.getWebSocketAdminService().emitTradeExecuted(e,t)}async emitBalanceUpdated(e,t,n){return this.getWebSocketAdminService().emitBalanceUpdated(e,t,n)}async emitStreamStatus(e,t){return this.getWebSocketAdminService().emitStreamStatus(e,t)}async emitViewerCount(e,t){return this.getWebSocketAdminService().emitViewerCount(e,t)}async emitStreamCountdown(e,t){return this.getWebSocketAdminService().emitStreamCountdown(e,t)}async emitChatMessage(e,t){return this.getWebSocketAdminService().emitChatMessage(e,t)}async emitChatStatus(e,t){return this.getWebSocketAdminService().emitChatStatus(e,t)}async emitTypingIndicator(e,t){return this.getWebSocketAdminService().emitTypingIndicator(e,t)}async emitTokenBanned(e,t){return this.getWebSocketAdminService().emitTokenBanned(e,t)}async emitTokenUnbanned(e,t){return this.getWebSocketAdminService().emitTokenUnbanned(e,t)}async emitModeratorAdded(e,t){return this.getWebSocketAdminService().emitModeratorAdded(e,t)}async emitModeratorRemoved(e,t){return this.getWebSocketAdminService().emitModeratorRemoved(e,t)}async emitUserProfileUpdated(e,t){return this.getWebSocketAdminService().emitUserProfileUpdated(e,t)}async emitSiteConfigChanged(e){return this.getWebSocketAdminService().emitSiteConfigChanged(e)}async emitFeatureStatus(e){return this.getWebSocketAdminService().emitFeatureStatus(e)}async emitRecordingStatus(e,t){return this.getWebSocketAdminService().emitRecordingStatus(e,t)}async emitRecordingsCountUpdated(e,t){return this.getWebSocketAdminService().emitRecordingsCountUpdated(e,t)}async emitDownloadReady(e,t){return this.getWebSocketAdminService().emitDownloadReady(e,t)}async getConnectedClients(e){return this.getWebSocketAdminService().getConnectedClients(e)}async isUserOnline(e){return this.getWebSocketAdminService().isUserOnline(e)}async getOnlineUsers(e){return this.getWebSocketAdminService().getOnlineUsers(e)}async getTokenViewers(e,t){return this.getWebSocketAdminService().getTokenViewers(e,t)}async getOnlineOverseers(){return this.getWebSocketAdminService().getOnlineOverseers()}async banToken(e){return this.getTokenBanService().banToken(e)}async unbanToken(e){return this.getTokenBanService().unbanToken(e)}async listTokenBans(e={}){return this.getTokenBanService().listTokenBans(e)}async getTokenBan(e){return this.getTokenBanService().getTokenBan(e)}async isTokenBanned(e){return this.getTokenBanService().isTokenBanned(e)}async getAIModerationSettings(){return this.getAIModerationService().getSettings()}async updateAIModerationSettings(e){return this.getAIModerationService().updateSettings(e)}async getAIModeration(e){return this.getAIModerationService().getModeration(e)}async triggerAIModeration(e){return this.getAIModerationService().triggerModeration(e)}async getAIModerationStatus(){return this.getAIModerationService().getStatus()}async getWeeklyChallengeLeaderboard(e={}){return this.getWeeklyChallengeService().getLeaderboard(e)}async getTokenWeeklyHistory(e){return this.getWeeklyChallengeService().getTokenHistory(e)}async getHomeOEmbed(e={}){return this.getOEmbedService().getHomeOEmbedJson(e)}async getPoolOEmbed(e){return this.getOEmbedService().getPoolOEmbedJson(e)}async getProfileOEmbed(e){return this.getOEmbedService().getProfileOEmbedJson(e)}async getPlatformStats(){return this.getPlatformStatsService().getStats()}async getHealth(){return this.getHealthService().getHealth()}async getEventStats(){return this.getEventsQueryService().getEventStats()}async queryEvents(e={}){return this.getEventsQueryService().queryEvents(e)}async registerPushToken(e){return this.getNotificationService().registerPushToken(e)}async unregisterPushToken(e){return this.getNotificationService().unregisterPushToken(e)}async fetchNotificationPreferences(){return this.getNotificationService().getPreferences()}async updateNotificationPreferences(e){return this.getNotificationService().updatePreferences(e)}async fetchClientFlags(){return this.getClientConfigService().getClientFlags()}async addContentReaction(e){return this.getContentReactionService().addContentReaction(e)}async removeContentReaction(e){return this.getContentReactionService().removeContentReaction(e)}async addReactionToChatMessage(e){return this.getContentReactionService().addReactionToChatMessage(e)}async removeReactionFromChatMessage(e){return this.getContentReactionService().removeReactionFromChatMessage(e)}async addReactionToComment(e){return this.getContentReactionService().addReactionToComment(e)}async removeReactionFromComment(e){return this.getContentReactionService().removeReactionFromComment(e)}async getComments(e){const t=this.buildMessageFetchOptions(e,"COMMENT"),n=await this.fetchMessages(t);return{messages:n.messages,pageInfo:n.pageInfo}}async createComment(e){return{comment:(await this.createMessage({type:"COMMENT",tokenName:e.tokenName,content:e.content})).message}}async updateComment(e,t){return{comment:(await this.updateMessage(e,{content:t.content,type:"COMMENT"})).message}}async deleteComment(e){return{success:(await this.deleteMessage(e)).success}}async getChatMessages(e){const t=this.buildMessageFetchOptions(e,"CHAT_MESSAGE"),n=await this.fetchMessages(t);return{messages:n.messages,pageInfo:n.pageInfo}}async sendChatMessage(e){return{message:(await this.createMessage({type:"CHAT_MESSAGE",tokenName:e.tokenName,content:e.content})).message}}async updateChatMessage(e,t){return{message:(await this.updateMessage(e,{content:t.content,type:"CHAT_MESSAGE"})).message}}async deleteChatMessage(e){await this.deleteMessage(e)}async fetchMessages(e){return this.getMessagesService().fetchMessages(e)}async createMessage(e){return this.getMessagesService().createMessage(e)}async updateMessage(e,t){return this.getMessagesService().updateMessage(e,t)}async deleteMessage(e){return this.getMessagesService().deleteMessage(e)}async getPinnedMessage(e){return this.getMessagesService().getPinnedMessage(e)}async pinMessage(e){return this.getMessagesService().pinMessage(e)}async unpinMessage(e){return this.getMessagesService().unpinMessage(e)}async getMessageStats(){return this.getMessagesService().getMessageStats()}async getPlatformConfig(){return this.getPlatformConfigService().getPlatformConfig()}async updatePlatformConfig(e){return this.getPlatformConfigService().updatePlatformConfig(e)}async getRestrictedNames(){return this.getRestrictedNamesService().getRestrictedNames()}async updateRestrictedNames(e){return this.getRestrictedNamesService().updateRestrictedNames(e)}async updateTokenConfig(e,t){return this.launchpadService.poolService.updateTokenConfig(e,t)}async getTokenConfig(e){return this.launchpadService.poolService.getTokenConfig(e)}async getTrades(e){return this.launchpadService.getTrades(e)}async getRecentTrades(e,t=50){return this.getTrades({...void 0!==e&&{tokenName:e},pageSize:Math.min(t,500)})}async getPoolRealtimeState(e){const[t,n,r,s]=await Promise.allSettled([this.getHolderCount(e),this.getTokenConfig(e),this.getRecentTrades(e,10),this.fetchTokenPrice({tokenName:e})]);return{tokenName:e,holderCount:"fulfilled"===t.status?t.value:null,..."rejected"===t.status&&{holderCountError:String(t.reason)},chatConfig:"fulfilled"===n.status?n.value:null,..."rejected"===n.status&&{chatConfigError:String(n.reason)},recentTrades:"fulfilled"===r.status?r.value:null,..."rejected"===r.status&&{recentTradesError:String(r.reason)},price:"fulfilled"===s.status?s.value:null,..."rejected"===s.status&&{priceError:String(s.reason)}}}async fetchLaunchpadFee(){return this.tradingQuotesService.fetchLaunchpadFee()}async fetchSaleDetails(e){return this.tradingQuotesService.fetchSaleDetails(e)}async getTradeQuote(e){return this.tradingQuotesService.getTradeQuote(e)}async getPremintQuote(e){return this.tradingQuotesService.getPremintQuote(e)}async connectStreamWebSocket(e){const t=this.getStreamWebSocketService();await t.connect(),e&&t.addCallbacks(e)}async authenticateStreamWebSocket(e){return this.getStreamWebSocketService().authenticate(e)}deauthenticateStreamWebSocket(){this._streamWebSocketService?.deauthenticate()}async subscribeToStream(e,t){return this.getStreamWebSocketService().subscribeToStream(e,t)}unsubscribeFromStream(e){this.getStreamWebSocketService().unsubscribeFromStream(e)}sendStreamChatViaWebSocket(e,t){this.getStreamWebSocketService().sendChatMessage(e,t)}sendStreamReaction(e,t,n=0){this.getStreamWebSocketService().sendReaction(e,t,n)}sendTypingStart(e){return this.getStreamWebSocketService().sendTypingStart(e)}sendTypingStop(e){return this.getStreamWebSocketService().sendTypingStop(e)}disconnectStreamWebSocket(){this._streamWebSocketService&&this._streamWebSocketService.disconnect()}isStreamWebSocketConnected(){return!!this._streamWebSocketService&&this._streamWebSocketService.isConnected()}onStreamStatusChanged(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_STATUS",e)}onUserBanned(e){return this.getStreamWebSocketService().subscribeEvent("USER_BANNED",e)}onUserUnbanned(e){return this.getStreamWebSocketService().subscribeEvent("USER_UNBANNED",e)}onBanEnforcement(e){return this.getStreamWebSocketService().subscribeEvent("BAN_ENFORCEMENT",e)}watchBanEnforcement(e,t={}){const n=(e,n,r,s)=>(void 0===t.actionType||t.actionType===e)&&(!!(void 0===t.userAddress||null!==n&&In(t.userAddress,n))&&((void 0===t.tokenName||t.tokenName===r)&&!!(void 0===t.reason||null!==s&&s.includes(t.reason)))),r=this.onUserBanned(t=>{const r=t.userAddress??null,s=t.reason??null;n("BANNED",r,t.tokenName,s)&&e({actionType:"BANNED",userAddress:r,tokenName:t.tokenName,reason:s,...void 0!==t.expiresAt&&{expiresAt:t.expiresAt}})}),s=this.onUserUnbanned(t=>{const r=t.userAddress??null;n("UNBANNED",r,t.tokenName,null)&&e({actionType:"UNBANNED",userAddress:r,tokenName:t.tokenName,reason:null})}),i=this.onBanEnforcement(t=>{const r=t.reason??null;n("ENFORCEMENT",null,t.tokenName,r)&&e({actionType:"ENFORCEMENT",userAddress:null,tokenName:t.tokenName,reason:r,...void 0!==t.expiresAt&&{expiresAt:t.expiresAt}})});return()=>{r(),s(),i()}}watchTokenRoomEvent(e,t,n,r){const s=r.tokenName;if(void 0===s||""===s)throw new Error(`${e} requires a tokenName filter - these are per-token stream events with no way to watch every token at once.`);return t(s,n)}watchCommentCreated(e,t={}){return this.watchTokenRoomEvent("watchCommentCreated",(e,t)=>this.getStreamWebSocketService().subscribeCommentCreated(e,t),n=>{(void 0===t.authorAddress||In(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||In(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&&!In(t.moderatorAddress,n)),r=this.watchModeratorAdded(t=>{n("ADDED",t.userAddress)&&e({actionType:"ADDED",tokenName:t.tokenName,moderatorAddress:t.userAddress,role:t.role})},t),s=this.watchTokenRoomEvent("watchModeratorRemoved",(e,t)=>this.getStreamWebSocketService().subscribeModeratorRemoved(e,t),t=>{n("REMOVED",t.userAddress)&&e({actionType:"REMOVED",tokenName:t.tokenName,moderatorAddress:t.userAddress})},t),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()=>{r(),s(),i()}}watchPoolUpdated(e,t={}){const n=e=>void 0===t.updateType||t.updateType===e,r=this.watchPoolMetadataUpdated(t=>{n("METADATA")&&e({updateType:"METADATA",tokenName:t.tokenName,details:t})},t),s=this.watchTokenRoomEvent("watchPoolSocialLinksUpdated",(e,t)=>this.getStreamWebSocketService().subscribePoolSocialLinksUpdated(e,t),t=>{n("SOCIAL_LINKS")&&e({updateType:"SOCIAL_LINKS",tokenName:t.tokenName,details:t})},t),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()=>{r(),s(),i()}}watchTokenBanChanged(e,t={}){const n=e=>void 0===t.banStatus||t.banStatus===e,r=this.watchTokenBanned(t=>{n("BANNED")&&e({banStatus:"BANNED",tokenName:t.tokenName,reason:t.reason})},t),s=this.watchTokenRoomEvent("watchTokenUnbanned",(e,t)=>this.getStreamWebSocketService().subscribeTokenUnbanned(e,t),t=>{n("UNBANNED")&&e({banStatus:"UNBANNED",tokenName:t.tokenName})},t);return()=>{r(),s()}}onContentFlagged(e){return this.getStreamWebSocketService().subscribeEvent("CONTENT_FLAGGED",e)}onFlagResolved(e){return this.getStreamWebSocketService().subscribeEvent("FLAG_RESOLVED",e)}onStreamChatMessage(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_CHAT_MESSAGE",e)}onStreamChatUpdated(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_CHAT_UPDATED",e)}onStreamChatDeleted(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_CHAT_DELETED",e)}onStreamChatPinned(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_CHAT_PINNED",e)}onStreamChatUnpinned(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_CHAT_UNPINNED",e)}onChatStatusChanged(e){return this.getStreamWebSocketService().subscribeEvent("CHAT_STATUS_CHANGED",e)}onViewerCountChanged(e){return this.getStreamWebSocketService().subscribeEvent("VIEWER_COUNT",e)}onRecordingStatusChanged(e){return this.getStreamWebSocketService().subscribeEvent("RECORDING_STATUS",e)}onSimulcastStatusChanged(e){return this.getStreamWebSocketService().subscribeEvent("SIMULCAST_STATUS",e)}onDownloadReady(e){return this.getStreamWebSocketService().subscribeEvent("DOWNLOAD_READY",e)}onRecordingsCountUpdated(e){return this.getStreamWebSocketService().subscribeEvent("RECORDINGS_COUNT_UPDATED",e)}onUserTyping(e){return this.getStreamWebSocketService().subscribeEvent("USER_TYPING",e)}onStreamReaction(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_REACTION",e)}onContentReactionAdded(e){return this.getStreamWebSocketService().subscribeEvent("CONTENT_REACTION_ADDED",e)}onContentReactionRemoved(e){return this.getStreamWebSocketService().subscribeEvent("CONTENT_REACTION_REMOVED",e)}onStreamCountdownUpdated(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_COUNTDOWN_UPDATED",e)}onStreamLanguageUpdated(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_LANGUAGE_UPDATED",e)}onStreamControlStatusChanged(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_CONTROL_STATUS_CHANGED",e)}onConnection(e){return this.getStreamWebSocketService().subscribeEvent("connection",e)}onAuthenticated(e){return this.getStreamWebSocketService().subscribeEvent("authenticated",e)}onTokenSubscribed(e){return this.getStreamWebSocketService().subscribeEvent("token_subscribed",e)}onTokenUnsubscribed(e){return this.getStreamWebSocketService().subscribeEvent("token_unsubscribed",e)}onRoomSubscribed(e){return this.getStreamWebSocketService().subscribeEvent("room_subscribed",e)}onRoomLeft(e){return this.getStreamWebSocketService().subscribeEvent("room_left",e)}onEngagementStatsUpdated(e){return this.getStreamWebSocketService().subscribeEvent("ENGAGEMENT_STATS_UPDATED",e)}async estimateBridgeFee(e){return this.getBridgeService(await this.coreBridge()).estimateBridgeFee(e)}async bridgeOut(e){return this.getBridgeService(await this.coreBridge()).bridgeOut(e)}async bridgeIn(e){return this.getBridgeService(await this.coreBridge()).bridgeIn(e)}async getBridgeStatus(e){return this.getBridgeService(await this.coreBridge()).getBridgeStatus(e)}async getSupportedBridgeTokens(){const e=this.getBridgeService(await this.coreBridge()),t=e.getSupportedBridgeTokens();return{tokens:t,totalCount:t.length,supportedChains:e.getSupportedBridgeChains()}}async fetchTokenBalance(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Kn}),n=t(e.address);if(void 0!==e.tokenId&&""!==e.tokenId){const{normalizeToTokenInstanceKey:t}=await Promise.resolve().then(function(){return Xa}),r=t(e.tokenId),{collection:s,category:i,type:o,additionalKey:a}=r;return this.galaChainService.fetchTokenBalance({owner:n,collection:s,category:i,additionalKey:a,type:o},e.withExpired??!1)}if(void 0!==e.tokenName&&""!==e.tokenName){const t=fn(e.tokenName),r=Zh[t];if(void 0!==r)return this.galaChainService.fetchTokenBalance({owner:n,collection:r,category:"Unit",additionalKey:"none",type:"none"},e.withExpired??!1)}if(void 0!==e.tokenName&&""!==e.tokenName){const t=(await this.fetchTokensHeld({tokenName:e.tokenName,pageSize:1,...void 0!==n?{address:n}:{}})).tokens[0];if(void 0===t)return null;const r=await this.resolveTokenClassKey(e.tokenName);return{quantity:t.balance,collection:r.collection,category:r.category,tokenId:$a(r)}}throw Ht("tokenId or tokenName","Either tokenId or tokenName")}async fetchLockedBalance(e){const t=await this.fetchTokenBalance(e);if(!t)return null;const n="lockedHolds"in t||"lockedQuantity"in t;return{tokenId:t.tokenId,lockedQuantity:n?t.lockedQuantity??"0":"0",lockedHolds:n?t.lockedHolds??[]:[]}}async fetchAvailableBalance(e){const t=await this.fetchTokenBalance(e);if(!t)return null;const n="availableQuantity"in t;return{tokenId:t.tokenId,availableQuantity:n?t.availableQuantity??String(t.quantity):String(t.quantity),totalQuantity:String(t.quantity)}}async calculateBuyAmount(e){return this.launchpadAPI.calculateBuyAmount(e)}async calculateSellAmount(e){return this.launchpadAPI.calculateSellAmount(e)}async calculateBuyAmountLocal(e){return this.launchpadAPI.calculateBuyAmountLocal(e)}async calculateSellAmountLocal(e){return this.launchpadAPI.calculateSellAmountLocal(e)}async calculateBuyAmountExternal(e){return this.launchpadAPI.calculateBuyAmountExternal(e)}async calculateSellAmountExternal(e){return this.launchpadAPI.calculateSellAmountExternal(e)}async calculateBuyAmountForGraduation(e){return this.launchpadAPI.calculateBuyAmountForGraduation(e)}async graduateToken(e){const{tokenName:t,slippageToleranceFactor:n,maxAcceptableReverseBondingCurveFeeSlippageFactor:r,privateKey:s,calculateAmountMode:i,currentSupply:o}=e;let a=t;void 0===i&&void 0===o||(a={tokenName:t,...void 0!==i&&{calculateAmountMode:i},...void 0!==o&&{currentSupply:o}});const c=await this.calculateBuyAmountForGraduation(a),l={tokenName:t,amount:c.remainingTokens,type:"exact",expectedAmount:c.amount,maxAcceptableReverseBondingCurveFee:c.reverseBondingCurveFee,slippageToleranceFactor:this.slippageToleranceFactor};return void 0!==n&&(l.slippageToleranceFactor=n),void 0!==r&&(l.maxAcceptableReverseBondingCurveFeeSlippageFactor=r),void 0!==s&&(l.privateKey=s),await this.buy(l)}async calculateInitialBuyAmount(e){const t={nativeTokenQuantity:e};return this.launchpadAPI.calculateInitialBuyAmount(t)}async buy(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...r}=e;return t.buy(r)}this.validateWallet(),await this.ensureWebSocketConnection();const t=(await this.bundleService.buyToken(e)).data,n=t?.transactionId;if(void 0===n||""===n)throw qt("No transaction ID returned from buy operation");return this.waitForConfirmation(n,t=>Yh(t,n,"buy",e))}async sell(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...r}=e;return t.sell(r)}this.validateWallet(),await this.ensureWebSocketConnection();const t=(await this.bundleService.sellToken(e)).data,n=t?.transactionId;if(void 0===n||""===n)throw qt("No transaction ID returned from sell operation");return this.waitForConfirmation(n,t=>Yh(t,n,"sell",e))}async getBundlerTransactionResult(e){return this.bundleService.getBundlerTransactionResult(e)}async launchToken(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...r}=e;return t.launchToken(r)}this.validateWallet(),await this.ensureWebSocketConnection();const t=await this.launchpadAPI.launchToken(e);return this.waitForConfirmation(t,n=>{Xh(n,t);const r=n.data??{};if(!function(e){if(ar(e)||"object"!=typeof e)return!1;const t=e;return!(void 0!==t.vaultAddress&&"string"!=typeof t.vaultAddress||void 0!==t.tokenStringKey&&"string"!=typeof t.tokenStringKey||void 0!==t.creatorAddress&&"string"!=typeof t.creatorAddress)}(r))throw new qh(`Invalid launch data received for transaction ${t}`);const s={transactionId:t,vaultAddress:r.vaultAddress??"",tokenStringKey:r.tokenStringKey??"",tokenName:e.tokenName,tokenSymbol:e.tokenSymbol,creatorAddress:r.creatorAddress??this.getAddress(),timestamp:Date.now(),...void 0!==n.blockHash&&""!==n.blockHash?{blockHash:n.blockHash}:{},...void 0!==n.gasUsed?{gasUsed:n.gasUsed}:{}};return"string"==typeof e.tokenImage&&(s.tokenImage=e.tokenImage),void 0!==e.preBuyQuantity&&(s.preBuyQuantity=e.preBuyQuantity),""!==s.vaultAddress&&this.tokenResolverService.set(e.tokenName,s.vaultAddress),s})}async uploadTokenImage(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...r}=e;return t.uploadTokenImage(r)}return this.launchpadService.uploadImageByTokenName(e)}async checkPoolExists(e,t){return this.launchpadService.checkPoolExists(e,t)}async isTokenNameAvailable(e){return this.launchpadService.isTokenNameAvailable(e)}async isTokenSymbolAvailable(e){return this.launchpadService.isTokenSymbolAvailable(e)}async fetchToken(e){return this.launchpadService.fetchToken(e)}async validateToken(e){return this.launchpadService.validateToken(e)}async fetchTokenStats(e){return this.launchpadService.fetchTokenStats(e)}async fetchProfile(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Kn}),n=t(e)??this.getAddress();return this.launchpadService.fetchProfile(n)}async fetchReferralUrl(){this.validateWallet();const e=this.getAddress();return await this.dexApiHttp.get(O,void 0,{"x-wallet-address":e})}async fetchReferrals(e){const t=this.resolveReferralAddress(e?.address),n=e?.page??1,r=e?.limit??10,s={pageNumber:n,limit:r,sortBy:e?.sortBy??"joined",sortDir:e?.sortDir??"desc"},i=await this.dexApiHttp.get(M,s,{"x-wallet-address":t});if(!Array.isArray(i))throw new Rt("Unexpected API response: expected array, got "+typeof i);return{referrals:i,page:n,limit:r,hasMore:i.length===r}}async fetchAllReferrals(e){const t=await async function(e,t={}){const{maxPages:n=1e4,logger:r,pageSize:s=20,concurrency:i=1,startPage:o=1}=t,a=[];let c=o;const l=o+n-1;let d=!0,u=0;if(i<=1)for(;d&&c<=l;){r&&r.debug(`Auto-pagination: fetching page ${c} with limit ${s}`);const t=await e(c,s);if(null==t||!Array.isArray(t.items)){r&&r.warn("Auto-pagination: received invalid result structure, stopping");break}if(a.push(...t.items),u=t.total,r&&r.debug(`Auto-pagination: page ${c} returned ${t.items.length} items, hasNext: ${String(t.hasNext)}`),0===t.items.length){r&&r.debug(`Auto-pagination: no items returned on page ${c}, exiting loop`);break}d=t.hasNext,c++}else for(r&&r.debug(`Auto-pagination: using concurrent mode with concurrency=${i}`);d&&c<=l;){const t=[];for(let e=0;e<i&&c+e<=l;e++)t.push(c+e);r&&r.debug(`Auto-pagination: fetching pages ${t.join(", ")} concurrently`);const n=t.map(t=>e(t,s).catch(e=>{const n=e,i=n.statusCode??n.response?.status??n.originalError?.response?.status??n.status??n.launchpadError?.statusCode;if(400===i||404===i)return r&&r.debug(`Auto-pagination: page ${t} returned ${i} (end of pagination)`,{statusCode:i}),{items:[],total:0,totalPages:0,page:t,limit:s,hasNext:!1,hasPrevious:!1};throw e})),o=await Promise.all(n);for(const e of o){if(null==e||!Array.isArray(e.items)){r&&r.warn("Auto-pagination: received invalid result structure in batch, stopping"),d=!1;break}if(0===e.items.length){r&&r.debug("Auto-pagination: empty page in batch, reached end of results"),d=!1;break}if(a.push(...e.items),u=e.total,!e.hasNext){d=!1;break}}c+=t.length,r&&r.debug(`Auto-pagination: batch complete, total items so far: ${a.length}`)}return c>l&&r&&r.warn(`Auto-pagination: exceeded maxPages limit of ${n} (maxPage=${l}), stopping iteration`),r&&r.debug(`Auto-pagination: completed with total items: ${a.length}, total count: ${u}`),{items:a,total:u}}((t,n)=>this.fetchReferrals({...e,page:t,limit:n}).then(e=>({items:e.referrals,page:e.page,limit:e.limit,total:0,totalPages:0,hasNext:e.hasMore,hasPrevious:e.page>1})),{maxPages:100,pageSize:100,logger:this.logger});return{referrals:t.items,total:t.items.length}}async fetchReferralsSummary(e){const t=this.resolveReferralAddress(e?.address),n=await this.dexApiHttp.get(L,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 Kn}),{address:n,...r}=e,s=void 0===n?void 0:t(n),i={...r,...void 0!==s&&{address:s}};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 Kn}),n=void 0===e.address?void 0:t(e.address)??e.address,r={...e,...void 0!==n&&{address:n}};if(void 0!==r.privateKey&&""!==r.privateKey){const e=this.createOverrideSdk(r.privateKey),{privateKey:t,...n}=r;return e.uploadProfileImage(n)}return this.launchpadService.uploadProfileImage(r)}async fetchTokensHeld(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Kn}),n=t(e?.address)??this.getAddress(),r={pageSize:e?.pageSize??10,address:n,...void 0!==e?.cursor?{cursor:e.cursor}:{}};return void 0!==e?.tokenName&&""!==e.tokenName&&(r.tokenName=e.tokenName),void 0!==e?.search&&""!==e.search&&(r.search=e.search),this.launchpadService.fetchTokensHeld(r)}async fetchTokensCreated(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Kn}),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 Kn}),n={...e,recipientAddress:t(e.recipientAddress)};if(void 0!==n.privateKey&&""!==n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...r}=n;return e.transferGala(r)}return this.assertTokenWriter(),this.galaChainService.transferGala(n)}async transferToken(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Kn}),n={...e,to:t(e.to)};if(void 0!==n.privateKey&&""!==n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...r}=n;return e.transferToken(r)}return this.assertTokenWriter(),this.galaChainService.transferToken(n)}async resolveTokenClassKey(e){return this.galaChainService.resolveTokenClassKey(e)}async convertTokenNameToTokenClassKey(e){return this.resolveTokenClassKey(e)}async lockTokens(e){const t=await Promise.all(e.tokens.map(async e=>{if(void 0!==e.lockAuthority&&""!==e.lockAuthority){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Kn});return{...e,lockAuthority:t(e.lockAuthority)}}return e})),n={...e,tokens:t};if(void 0!==n.privateKey&&""!==n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...r}=n;return e.lockTokens(r)}return this.assertTokenWriter(),this.galaChainService.lockTokens(n)}async unlockTokens(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...r}=e;return t.unlockTokens(r)}return this.assertTokenWriter(),this.galaChainService.unlockTokens(e)}async burnTokens(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...r}=e;return t.burnTokens(r)}return this.assertTokenWriter(),this.galaChainService.burnTokens(e)}async resolveVaultAddress(e){return this.tokenResolverService.resolveTokenToVault(e)}async findTokenNameByVault(e,t){let n;for(let r=0;r<10;r+=1){const r=await this.launchpadService.poolService.fetchPools({search:t,pageSize:100,...void 0===n?{}:{cursor:n}}),s=r.items.find(t=>t.vaultAddress===e);if(void 0!==s)return s.tokenName;const i=Go(r.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{Qn(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 jt("baseUrl is required in configuration","baseUrl");if(void 0===this.config.webSocketUrl||""===this.config.webSocketUrl)throw jt("webSocketUrl is required in configuration","webSocketUrl");try{new URL(this.config.baseUrl)}catch{throw jt(`Invalid baseUrl format: ${this.config.baseUrl}`,"baseUrl")}try{new URL(this.config.webSocketUrl)}catch{throw jt(`Invalid webSocketUrl format: ${this.config.webSocketUrl}`,"webSocketUrl")}if(void 0!==this.config.gatewayBaseUrl&&""!==this.config.gatewayBaseUrl)try{new URL(this.config.gatewayBaseUrl)}catch{throw jt(`Invalid gatewayBaseUrl format: ${this.config.gatewayBaseUrl}`,"gatewayBaseUrl")}if(void 0!==this.config.bundleBaseUrl&&""!==this.config.bundleBaseUrl)try{new URL(this.config.bundleBaseUrl)}catch{throw jt(`Invalid bundleBaseUrl format: ${this.config.bundleBaseUrl}`,"bundleBaseUrl")}if(void 0!==this.config.launchpadFrontendUrl&&""!==this.config.launchpadFrontendUrl)try{new URL(this.config.launchpadFrontendUrl)}catch{throw jt(`Invalid launchpadFrontendUrl format: ${this.config.launchpadFrontendUrl}`,"launchpadFrontendUrl")}}parseSlippageToleranceFactor(e){const t=Hn("string"==typeof e||"number"==typeof e?e:String(e),rg.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR);return t<0||t>1?(this.logger.warn(`Invalid slippage tolerance factor: ${String(e)}, using default: ${rg.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR}`),rg.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR):t}parseFeeSlippageFactor(e){const t=Hn("string"==typeof e||"number"==typeof e?e:String(e),rg.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: ${rg.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR}`),rg.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!==Io.COMPLETED)throw new Qh(e,n.status,n.message);let r;try{r=t(n)}catch(t){if(t instanceof qh)throw t;throw new qh(`Failed to transform WebSocket response for transaction ${e}`,Lt(t)?t:new Error(Ut(t)))}return this.logger.debug(`Transaction confirmed: ${e}`,r),r}catch(t){if(this.logger.error(`Transaction confirmation failed: ${e}`,t),t instanceof Qh||t instanceof qh)throw t;throw new qh(`WebSocket confirmation failed for transaction ${e}`,Lt(t)?t:new Error(Ut(t)))}}async warmCacheFromPools(e){if(void 0===e||!Array.isArray(e))return;const{extractMetadataFromPoolData:t,isValidPoolForCaching:n}=await Promise.resolve().then(function(){return ff});e.forEach(e=>{if(!n(e))return;const r=t(e,this.logger);r&&this.launchpadAPI.warmCacheFromPoolData(e.tokenName,r)})}connectWebSocket(){this.websocketService.connect()}disconnectWebSocket(){this.websocketService.disconnect()}isWebSocketConnected(){return this.websocketService.isConnected()}subscribeToEvent(e,t){const n=this.websocketService.getSocket();return n?(n.on(e,t),()=>{n.off(e,t),this.logger.debug(`Unsubscribed from event: "${e}"`)}):(this.logger.warn(`⚠️ WebSocket not connected - subscribing to "${e}" without connection`),()=>{})}onLaunchpadTokenCreation(e,t){const n=1e3,r=Math.max(t?.intervalMs??3e4,n);null!=t?.intervalMs&&t.intervalMs<n&&this.logger.warn(`Poll interval ${t.intervalMs}ms is below minimum 1000ms. Using minimum interval instead.`);const s=t?.creatorAddress,i=new Map;let o=!0,a=null;let c=0;const l=async()=>{if(o){try{const t=await this.fetchPools({type:"recent",pageSize:20});c>0&&(this.logger.debug("Successfully recovered from polling errors"),c=0),t.items.forEach(t=>{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!==s&&""!==s&&t.creatorAddress!==s||e(t))})}catch(e){c++;const t=Ut(e);c>=5?this.logger.error(`Polling for new launchpad tokens failed ${c} consecutive times. Last error: ${t}. Continuing to retry...`):c>1?this.logger.warn(`Error polling for new launchpad tokens (attempt ${c}/5): ${t}`):this.logger.debug(`Error polling for new launchpad tokens: ${t}`)}if(o){const e=Math.min(Math.max(c-1,0),2),t=r*Math.pow(2,e);a=setTimeout(()=>{l()},t)}}};return l(),()=>{o=!1,a&&clearTimeout(a),this.logger.debug("Stopped watching for launchpad token creation")}}matchesCreatorFilter(e,t){return void 0===t||""===t||e.creatorAddress===t}subscribeToTokenCreations(e,t){if(this.logger.debug("Subscribing to token creation broadcasts"+(void 0!==t?.creatorFilter&&""!==t.creatorFilter?` (filter: ${t.creatorFilter})`:"")),null===this.websocketService||void 0===this.websocketService)throw jt("WebSocket service not initialized. Ensure websocketUrl is configured and the service is connected.","websocketService");let n=!1,r=null;const s=(n,...r)=>{try{if(r.length>0&&"object"==typeof r[0]&&null!==r[0]){const n=r[0].data;if(void 0!==n?.Data&&null!==n.Data&&"object"==typeof n.Data){const r=n.Data;if("CreateSale"===r.functionName){const n=(e,t="")=>{const n=r[e];return"string"==typeof n&&""!==n?n:t},s={tokenName:n("tokenName"),symbol:n("symbol"),creatorAddress:n("creatorAddress"),description:n("description"),image:n("image"),vaultAddress:n("vaultAddress"),tokenStringKey:n("tokenStringKey"),preBuyQuantity:n("initialBuyQuantity","0"),websiteUrl:n("websiteUrl"),telegramUrl:n("telegramUrl"),twitterUrl:n("twitterUrl"),instagramUrl:n("instagramUrl"),facebookUrl:n("facebookUrl"),redditUrl:n("redditUrl"),tiktokUrl:n("tiktokUrl"),isFinalized:!0===r.isFinalized};this.matchesCreatorFilter(s,t?.creatorFilter)&&e(s)}}}}catch(e){this.logger.warn(`Error processing token creation broadcast: ${Ut(e)}`)}};let i=this.websocketService.getSocket();if(i)i.onAny(s),n=!0,this.logger.debug("Token creation broadcast listener registered");else{this.logger.debug("WebSocket not yet connected, initiating connection..."),this.websocketService.connect().catch(e=>{const n=new Error(`WebSocket connection failed: ${Ut(e)}`);this.logger.warn("Failed to establish WebSocket connection:",e),t?.onError&&t.onError(n)});let e=0;const o=()=>{if(i=this.websocketService.getSocket(),!i&&e<rg.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS)return e++,void(r=setTimeout(()=>o(),rg.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS));if(!i&&e>=rg.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS){const e=new Error(`WebSocket not available after ${rg.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS*rg.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(s),n=!0,this.logger.debug("Token creation broadcast listener registered"))};o()}return()=>{try{if(null!==r&&(clearTimeout(r),r=null,this.logger.debug("Cleared token creation broadcast polling timeout")),!n)return void this.logger.debug("Cleanup called before listener registration - no action needed");const e=this.websocketService.getSocket();e&&(e.offAny(s),n=!1,this.logger.debug("Stopped listening to token creation broadcasts"))}catch(e){this.logger.warn("Error removing token creation listener:",e)}}}getNftCollectionClaimFee(){return this.nftCollectionService.getCollectionClaimFee()}getNftTokenClassCreateFee(){return this.nftCollectionService.getTokenClassCreateFee()}estimateNftMintFee(e){return this.nftCollectionService.estimateMintFee(e)}estimateNftOperationFees(e){return this.nftCollectionService.estimateNftOperationFees(e)}claimNftCollection(e){return this.nftCollectionService.claimCollection(e)}fetchNftCollections(e){return this.nftCollectionService.fetchUserCollections(e)}isNftCollectionAvailable(e){return this.nftCollectionService.isCollectionAvailable(e)}createNftTokenClass(e){return this.nftCollectionService.createTokenClass(e)}fetchNftTokenClasses(e){return this.nftCollectionService.fetchTokenClasses(e)}mintNft(e){return this.nftCollectionService.mintNft(e)}fetchNftBalances(e,t){return this.nftCollectionService.fetchNftBalances(e,t)}async cleanup(){try{if(this.logger.debug("Starting cleanup..."),void 0!==this._eventsBatcherService)try{await this._eventsBatcherService.shutdown(5e3),this._eventsBatcherService=void 0}catch(e){this.logger.warn("Error during events shutdown:",e)}this.http.cleanup(),null!==this.websocketService&&void 0!==this.websocketService&&this.websocketService.disconnect(),void 0!==this._streamWebSocketService&&(this._streamWebSocketService.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 En({debug:e,context:"LaunchpadSDK"});t.debug("Starting global cleanup..."),hh.cleanupAll(e),t.debug("Global cleanup completed")}}function sg(e){ar(e)&&(e={});const{wallet:t,env:n,config:r={},...s}=e,i={...{...s,...r}};delete i.wallet,delete i.env,delete i.config;const o=!ar(i.signer)||!ar(i.walletProvider);let a;if(ar(t))a=o?void 0:new T(f().privateKey);else if("string"==typeof t)a=new T(f(t).privateKey);else{if(!(t instanceof T))throw jt("Invalid wallet input. Expected string (private key or mnemonic) or Wallet instance.","wallet");a=t}const c={...void 0!==a?{wallet:a}:{},...void 0!==n?{env:n}:{},debug:!1,timeout:3e4,...i};return new rg(c)}function ig(e){const t=f(e);return{...t,wallet:new T(t.privateKey)}}function og(){const e=globalThis;return e.process?.env??{}}rg.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR=.15,rg.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR=.01,rg.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY=hn.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY,rg.DEFAULT_CALCULATE_AMOUNT_MODE=Nt.LOCAL,rg.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS=30,rg.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS=100;class ag{constructor(){this.utilityInstance=!0,this.utilityInstance}static async quickSetup(e={}){const t=e.environment??this.detectEnvironment(),n=this.setupWallet(e.privateKey),r=this.buildSdkConfig(e,t,n),s=new rg(r),i={sdk:s,wallet:n,config:r};if(!1!==e.autoValidate){const e=await this.validateSetup(s,n);return{...i,validation:e}}return i}static readOnlySetup(e={}){const t=e.environment??this.detectEnvironment(),n=this.buildSdkConfig(e,t),r=new rg(n);return Promise.resolve({sdk:r,config:n})}static async validateSetup(e,t){const n=[],r=[],s={canTrade:!1,canCreateTokens:!1,hasBalance:!1,connectionHealthy:!1};try{const t=await e.fetchGalaBalance(e.getAddress());if(s.connectionHealthy=!0,void 0!==t?.quantity&&""!==t.quantity){const e=Hn(t.quantity,0);s.hasBalance=e>0,s.canTrade=e>=.1,s.canCreateTokens=e>=100,0===e?r.push("Wallet has zero GALA balance - cannot perform transactions"):e<.1?r.push("GALA balance too low for trading (minimum 0.1 GALA)"):e<100&&r.push("GALA balance too low for token creation (minimum 100 GALA)")}else n.push("Failed to fetch GALA balance: No balance returned")}catch(e){n.push(`Balance check error: ${Ut(e)}`)}try{const t=await e.fetchPools({type:"recent",pageSize:1});null!==t.items&&void 0!==t.items&&0!==t.items.length||r.push("Pool listing not accessible - some features may be limited")}catch(e){r.push(`Pool access test failed: ${Ut(e)}`)}return{ready:0===n.length&&s.connectionHealthy,sdk:e,wallet:t??ig(),issues:n,warnings:r,capabilities:s}}static getRecommendedConfig(e,t="general"){const n={environment:e,autoValidate:!0};switch(e){case"prod":Object.assign(n,{debug:!1,timeout:3e4});break;case"stage":Object.assign(n,{debug:!0,timeout:45e3})}switch(t){case"trading":n.timeout=1.5*(n.timeout??3e4);break;case"creation":n.timeout=2*(n.timeout??3e4);break;case"monitoring":n.timeout=.5*(n.timeout??3e4);break;case"general":break;default:throw new Error(`Unexpected useCase: ${String(t)}`)}return n}static async multiWalletSetup(e,t="stage"){const n={};for(const[r,s]of Object.entries(e)){const{sdk:e}=await this.quickSetup({environment:t,privateKey:s,agentId:`multi-wallet-${r}`,autoValidate:!1});n[r]=e}return n}static detectEnvironment(){return"stage"===(og().LAUNCHPAD_ENV??og().ENVIRONMENT)?"stage":"prod"}static setupWallet(e){if(void 0===e||""===e){const e=og().PRIVATE_KEY;return void 0!==e&&""!==e?ig(e):ig()}return"generate"===e?ig():ig(e)}static buildSdkConfig(e,t,n){const r=e.galaChainAddress??og().WALLET_ADDRESS;return{wallet:n?.wallet,baseUrl:e.baseUrl??this.getDefaultBaseUrl(t),timeout:e.timeout??this.getDefaultTimeout(t),debug:e.debug??"prod"!==t,...this.getEnvironmentDefaults(t),...e.config??{},...void 0!==r&&""!==r?{galaChainAddress:r}:{},env:t}}static getDefaultBaseUrl(e){return ko(e).launchpadBaseUrl}static getDefaultTimeout(e){switch(e){case"prod":return 3e4;case"stage":return 45e3}}static getEnvironmentDefaults(e){const t=ko(e);return{bundleBaseUrl:t.bundleBaseUrl,gatewayBaseUrl:t.gatewayBaseUrl}}}function cg(e,t,n){const r="number"==typeof e?new I(e):e;if(r.isLessThan(0)||r.isGreaterThan(1))throw new Error(`Progress must be between 0 and 1, got: ${r.toString()}`);if(n<t)throw new Error(`maxFee must be >= minFee, got minFee: ${t}, maxFee: ${n}`);const s=n-t;return new I(t).plus(new I(s).multipliedBy(r))}function lg(e,t,n){if(e>=t)throw new Error(`tickLower must be < tickUpper, got: ${e} >= ${t}`);if(n<=0)throw new Error(`tickSpacing must be > 0, got: ${n}`);return{tickLower:Math.floor(e/n)*n,tickUpper:Math.ceil(t/n)*n}}function dg(e,t,n=60){const r=Qi(e),s=Qi(t);if(r.isLessThanOrEqualTo(0)||s.isLessThanOrEqualTo(0))throw new Error("Prices must be positive");if(r.isGreaterThanOrEqualTo(s))throw new Error(`minPrice must be < maxPrice, got: ${r.toString()} >= ${s.toString()}`);const i=Math.floor(Yi(r)),o=Math.ceil(Yi(s)),a=Math.floor(i/n)*n,c=Math.ceil(o/n)*n;return{minTick:a,maxTick:c,actualMinPrice:new I(1.0001).pow(a),actualMaxPrice:new I(1.0001).pow(c)}}function ug(e,t){if(0===e.length)return-1;if(t<0||t>100)throw new Error(`Percentile must be between 0 and 100, got: ${t}`);const n=(e.length-1)*(t/100),r=Math.floor(n);return Math.min(r,e.length-1)}function hg(e,t){if(t<0)throw new Error(`decimals must be >= 0, got: ${t}`);const n=Qi(e),r=new I(10).pow(t);return n.multipliedBy(r).integerValue(I.ROUND_UP).dividedBy(r)}function gg(e,t,n,r="0"){const s=Qi(t);if(Ji(s))return Qi(r);const i=Qi(e).dividedBy(s);if(null!=n){const e=Qi(n);if(e.isLessThan(0))throw new Error(`minimum must be >= 0, got: ${e.toString()}`);if(i.isLessThan(e))return e}return i}function mg(e,t){if(t<=0)throw new Error(`tickSpacing must be > 0, got: ${t}`);return Math.floor(e/t)*t}function fg(e,t){if(t<0)throw new Error(`feeFactor must be >= 0, got: ${t}`);return Qi(e).multipliedBy(t).integerValue(I.ROUND_DOWN)}function pg(e,t){const n=new Map;for(const r of e){const e=t(r);n.has(e)||n.set(e,[]),n.get(e).push(r)}return n}function Eg(e){if(null==e||"object"!=typeof e)throw new Error("Token must be an object");const t=e,n=(ir(t.name)?t.name:void 0)??(ir(t.tokenName)?t.tokenName:void 0)??"";if(!ir(n))throw new Error("Token name is required and must be a non-empty string");const r=(ir(t.symbol)?t.symbol:void 0)??(ir(t.tokenSymbol)?t.tokenSymbol:void 0)??"";if(!ir(r))throw new Error("Token symbol is required and must be a non-empty string");let s=8;"number"==typeof t.decimals&&t.decimals>=0&&(s=Math.floor(t.decimals));const i={name:n,symbol:r,decimals:s};return ir(t.address)&&(i.address=t.address),"boolean"==typeof t.verified&&(i.verified=t.verified),i}function Ag(e,t,n=null){if(null==e||"object"!=typeof e)return n;const r=e;for(const e of t){const t=e.split(".");let n=r;for(const e of t){if(null==n||"object"!=typeof n){n=null;break}n=n[e]}if(ir(n))return n;if(null!=n&&""!==n)return n}return n}function vg(e,t){return e.map(e=>{const n={};for(const[r,s]of Object.entries(t)){const t=s(e);void 0!==t&&(n[r]=t)}return n})}function Tg(e,t,n=!0){const r=new Map;if(e.forEach((e,n)=>{const s=t(e);r.set(s,n)}),n){const n=new Set;return e.filter(e=>{const r=t(e);return!n.has(r)&&(n.add(r),!0)})}return e.filter((e,n)=>{const s=t(e);return r.get(s)===n})}function yg(e,t){const n={...e};for(const[e,r]of Object.entries(t))void 0!==r&&(n[e]=r);return n}class Sg{constructor(){this.rooms=new Set}addRoom(e){this.rooms.add(e)}removeRoom(e){this.rooms.delete(e)}getRooms(){return Array.from(this.rooms)}isSubscribedTo(e){return this.rooms.has(e)}clear(){this.rooms.clear()}get size(){return this.rooms.size}}class bg{constructor(e,t,n=50){this.seen=new Set,this.extractor=e,this.dedupeKeyFn=t,this.maxDepth=n}walk(e){const t=[],n=new WeakSet,r=(e,s=0)=>{if(s>this.maxDepth)return;if(null==e||"object"!=typeof e)return;if(n.has(e))return;n.add(e);const i=this.extractor(e);if(null!==i){const e=this.dedupeKeyFn(i);this.seen.has(e)||(this.seen.add(e),t.push(i))}for(const t of Object.values(e))r(t,s+1)};return r(e,0),t}reset(){this.seen.clear()}getSeenCount(){return this.seen.size}}class Ng{constructor(){this.pending=new Map}addPending(e,t){this.removePending(e);const n=setTimeout(()=>{this.pending.delete(e)},t);this.pending.set(e,{timeoutId:n,addedAt:Date.now()})}removePending(e){const t=this.pending.get(e);t&&(clearTimeout(t.timeoutId),this.pending.delete(e))}isPending(e){return this.pending.has(e)}getPendingCount(){return this.pending.size}clearExpired(){for(const[e,t]of this.pending.entries())null==t&&this.pending.delete(e)}clear(){for(const e of this.pending.values())clearTimeout(e.timeoutId);this.pending.clear()}}class wg{constructor(e){this.globalCallbacks=[],this.roomCallbacks=new Map,this.logger=e}registerGlobalCallback(e){this.globalCallbacks.push(e)}registerRoomCallback(e,t){const n=this.roomCallbacks.get(e)??[];n.push(t),this.roomCallbacks.set(e,n)}dispatch(e,t){for(const e of this.globalCallbacks)try{e(t)}catch(e){this.logger?.error(`Error in global callback: ${Ut(e)}`)}const n=this.roomCallbacks.get(e);if(n)for(const r of n)try{r(t)}catch(t){this.logger?.error(`Error in room callback for ${e}: ${Ut(t)}`)}}clear(){this.globalCallbacks=[],this.roomCallbacks.clear()}clearRoom(e){this.roomCallbacks.delete(e)}}class kg{constructor(){this.filters=[]}addFilter(e){return this.filters.push(e),this}forward(e){for(const t of this.filters)if(!t(e))return!1;return!0}clearFilters(){this.filters=[]}get filterCount(){return this.filters.length}}class _g{constructor(e){this.listeners=[],this.logger=e}register(e,t){this.listeners.push({id:e,cleanup:t})}async cleanup(){const e=[];for(let t=this.listeners.length-1;t>=0;t--){const n=this.listeners[t];if(void 0===n)continue;const{id:r,cleanup:s}=n;try{await s()}catch(t){const n=t instanceof Error?t:new Error(String(t));e.push(n),this.logger?.error(`Cleanup error for listener ${r}:`,n)}}return this.listeners=[],e}clear(){this.listeners=[]}get size(){return this.listeners.length}}class Ig{constructor(e={},t){this.events=[],this.timeouts=new Map,this.maxSize=e.maxSize??100,this.defaultTtlMs=e.defaultTtlMs??3e4,this.logger=t}push(e){if(this.events.length>=this.maxSize){const e=0;this.events.shift();const t=this.timeouts.get(e);t&&(clearTimeout(t),this.timeouts.delete(e)),this.logger?.warn(`Buffer full (${this.maxSize}), dropped oldest event`)}this.events.push(e);const t=this.events.length-1,n=setTimeout(()=>{this.events[t]===e&&this.events.splice(t,1),this.timeouts.delete(t)},this.defaultTtlMs);this.timeouts.set(t,n)}getAll(){return[...this.events]}clear(){for(const e of this.timeouts.values())clearTimeout(e);this.events=[],this.timeouts.clear()}get size(){return this.events.length}}class Cg{constructor(e={},t){this.pendingIndicators=new Map,this.activeIndicators=new Set,this.delayMs=e.delayMs??3e3,this.onTyping=e.onTyping,this.onStopTyping=e.onStopTyping}indicate(e,t){const n=`${e}:${t}`,r=this.pendingIndicators.get(n);r&&clearTimeout(r),this.activeIndicators.has(n)||(this.activeIndicators.add(n),this.onTyping?.(e,t));const s=setTimeout(()=>{this.activeIndicators.delete(n),this.pendingIndicators.delete(n),this.onStopTyping?.(e,t)},this.delayMs);this.pendingIndicators.set(n,s)}stopTyping(e,t){const n=`${e}:${t}`,r=this.pendingIndicators.get(n);r&&(clearTimeout(r),this.pendingIndicators.delete(n)),this.activeIndicators.has(n)&&(this.activeIndicators.delete(n),this.onStopTyping?.(e,t))}clear(){for(const e of this.pendingIndicators.values())clearTimeout(e);this.pendingIndicators.clear(),this.activeIndicators.clear()}get activeCount(){return this.activeIndicators.size}}const Dg=5,Rg=8,Og=18,Mg={PAGE:"page",LIMIT:"limit",TOKEN_NAME:"tokenName",VAULT_ADDRESS:"vaultAddress",USER_ADDRESS:"userAddress",TRADE_TYPE:"tradeType",POOL_TYPE:"type",SEARCH:"search",SORT_ORDER:"sortOrder",START_DATE:"startDate",END_DATE:"endDate"},Lg=5,Ug=5;function Fg(e){const t={};return void 0!==e.cursor&&(t.cursor=e.cursor),void 0!==e.pageSize&&(t.pageSize=e.pageSize),t}function Pg(e,t){return Fg({...e,...t})}function xg(e,t){return void 0===t?e:{...e,cursor:t}}function Bg(e){return"string"==typeof e?e:"number"==typeof e||"boolean"==typeof e||"bigint"==typeof e?String(e):JSON.stringify(e)??""}async function Gg(e,t,n,r){const s=r?.logger,i=[];i.length=e.length;let o=0,a=0;s?.debug(`Starting concurrent batch requests: ${e.length} URLs, batch size: ${t}`);for(let r=0;r<e.length;r+=t){const c=e.slice(r,r+t),l=r;try{const t=c.map((t,r)=>{const c=l+r;return(async()=>{try{const r=await n(t);return i[c]=r,o++,s?.debug(`Fetched [${c+1}/${e.length}]: ${t}`),r}catch(n){throw a++,s?.warn(`Failed [${c+1}/${e.length}]: ${t} - ${Ut(n)}`),n}})()}),r=await Promise.allSettled(t);for(let e=0;e<r.length;e++){const t=r[e];"rejected"===t?.status&&s?.debug(`Promise rejected in batch at index ${l+e}`)}}catch(e){s?.error(`Batch processing error at index ${r}: ${Ut(e)}`)}}return s?.debug(`Batch complete: ${o} succeeded, ${a} failed`),i}function $g(e){const t={page:1,pageSize:20,totalCount:-1,hasMore:!1};if(null==e||"object"!=typeof e)return t;const n=e,r=Wn(Bg(n.page??n.Page??n.current??1),t.page),s=Wn(Bg(n.pageSize??n.limit??n.size??t.pageSize),t.pageSize),i=n.data,o=i?.meta;let a;a="number"==typeof n.totalCount?n.totalCount:"number"==typeof n.total?n.total:"number"==typeof o?.totalItems?o.totalItems:"number"==typeof i?.count?i.count:Wn(Bg(n.totalCount??n.total??-1),t.totalCount);let c=t.hasMore;return"boolean"==typeof n.hasMore?c=n.hasMore:"boolean"==typeof n.has_more?c=n.has_more:"boolean"==typeof o?.hasMore&&(c=o.hasMore),{page:r,pageSize:s,totalCount:a,hasMore:c}}function Kg(e){if(null==e||"object"!=typeof e)return"";const t=[];for(const[n,r]of Object.entries(e)){if(or(r))continue;let e;e="string"==typeof r?r:"number"==typeof r||"boolean"==typeof r?String(r):Array.isArray(r)?r.map(e=>Bg(e)).join(","):Bg(r);const s=encodeURIComponent(n),i=encodeURIComponent(e);t.push(`${s}=${i}`)}return t.length>0?`?${t.join("&")}`:""}async function Hg(e,t){const n=t?.maxRetries??3,r=t?.backoffMs??100,s=t?.retryableStatus??[429,503,504];let i,o=0;for(;o<=n;)try{return await e()}catch(e){i=e,o++;const t=jg(e),a=s.includes(t);if(o>n||!a)throw e;const c=r*Math.pow(2,o-1);await new Promise(e=>setTimeout(e,c))}throw i}function Wg(e){const t={statusCode:0,errorMessage:"Unknown error",raw:e};if(null==e)return t;const n=e;let r=t.statusCode;"number"==typeof n.status?r=n.status:"number"==typeof n.statusCode?r=n.statusCode:"number"==typeof n.code&&(r=n.code);let s,i=t.errorMessage;"string"==typeof n.message?i=n.message:"string"==typeof n.error?i=n.error:e instanceof Error?i=e.message:"string"==typeof e&&(i=e);const o=n.response;if(o){const e=o.data;if("object"==typeof e&&null!==e){s=e;const t=e;"string"==typeof t.message?i=t.message:"string"==typeof t.error&&(i=t.error)}}const a={statusCode:r,errorMessage:i,raw:e};return null!=s&&(a.errorData=s),a}async function Vg(e,t,n){const r=n?.logger,s=n?.fetcher??(async e=>{const t=await fetch(e);if(!t.ok)throw new Error(`HTTP ${t.status}`);return t.json()});r?.debug(`Aggregating from ${e.length} endpoints`);const i=e.map(async(t,n)=>{try{const i=await s(t);return r?.debug(`Endpoint [${n+1}/${e.length}] succeeded: ${t}`),i}catch(s){return void r?.warn(`Endpoint [${n+1}/${e.length}] failed: ${t} - ${Ut(s)}`)}}),o=(await Promise.allSettled(i)).map(e=>{if("fulfilled"===e.status)return e.value});return r?.debug(`Aggregating ${o.filter(e=>void 0!==e).length} successful results`),t(o)}function jg(e){if(null==e||"object"!=typeof e)return 0;const t=e;if("number"==typeof t.status)return t.status;if("number"==typeof t.statusCode)return t.statusCode;if("number"==typeof t.code)return t.code;const n=t.response;return n&&"number"==typeof n.status?n.status:0}function qg(e){const t=e.trim().toLowerCase();if(0===t.length)throw new Error("Token name cannot be empty");return t}function zg(e){if(void 0!==e&&e.length>0&&!/^[a-z0-9]+$/.test(e.toLowerCase()))throw new Error(`Invalid asset extension format: "${e}". Must contain only alphanumeric characters.`)}function Qg(e,t){return`${e.replace(/\/$/,"")}${t}`}function Xg(e,t){const n=qg(e);return Qg(t,`/v1/tokens/${encodeURIComponent(n)}/assets/image`)}function Yg(e,t,n="jpg"){const r=qg(e);zg(n);return Qg(t,`/v1/tokens/${encodeURIComponent(r)}/assets/thumbnail.${n.toLowerCase()}`)}function Jg(e,t,n="gif"){const r=qg(e);zg(n);return Qg(t,`/v1/tokens/${encodeURIComponent(r)}/assets/animated.${n.toLowerCase()}`)}function Zg(e,t){const n=qg(e);return Qg(t,`/v1/tokens/${encodeURIComponent(n)}/assets/poster.jpg`)}function em(e,t,n="vtt"){const r=qg(e);zg(n);return Qg(t,`/v1/tokens/${encodeURIComponent(r)}/assets/storyboard.${n.toLowerCase()}`)}function tm(e,t){const n=qg(e);return Qg(t,`/v1/tokens/${encodeURIComponent(n)}/assets/live.m3u8`)}function nm(e,t,n,r){const s=qg(e),i=t.trim().toLowerCase();if(0===i.length)throw new Error("Asset type cannot be empty");zg(r);const o=void 0!==r&&r.length>0?`.${r.toLowerCase()}`:"";return Qg(n,`/v1/tokens/${encodeURIComponent(s)}/assets/${encodeURIComponent(i)}${o}`)}function rm(e,t,n,r="jpg"){const s=qg(e),i=t.trim();if(0===i.length)throw new Error("Recording ID cannot be empty");zg(r);return Qg(n,`/v1/tokens/${encodeURIComponent(s)}/recordings/${encodeURIComponent(i)}/assets/thumbnail.${r.toLowerCase()}`)}function sm(e,t,n,r="gif"){const s=qg(e),i=t.trim();if(0===i.length)throw new Error("Recording ID cannot be empty");zg(r);return Qg(n,`/v1/tokens/${encodeURIComponent(s)}/recordings/${encodeURIComponent(i)}/assets/animated.${r.toLowerCase()}`)}function im(e,t,n){const r=qg(e),s=t.trim();if(0===s.length)throw new Error("Recording ID cannot be empty");return Qg(n,`/v1/tokens/${encodeURIComponent(r)}/recordings/${encodeURIComponent(s)}/assets/poster.jpg`)}function om(e,t,n,r="vtt"){const s=qg(e),i=t.trim();if(0===i.length)throw new Error("Recording ID cannot be empty");zg(r);return Qg(n,`/v1/tokens/${encodeURIComponent(s)}/recordings/${encodeURIComponent(i)}/assets/storyboard.${r.toLowerCase()}`)}function am(e,t,n){const r=qg(e),s=t.trim();if(0===s.length)throw new Error("Recording ID cannot be empty");return Qg(n,`/v1/tokens/${encodeURIComponent(r)}/recordings/${encodeURIComponent(s)}/assets/stream.m3u8`)}function cm(e,t,n,r,s){const i=qg(e),o=t.trim(),a=n.trim().toLowerCase();if(0===o.length)throw new Error("Recording ID cannot be empty");if(0===a.length)throw new Error("Asset type cannot be empty");zg(s);const c=void 0!==s&&s.length>0?`.${s.toLowerCase()}`:"";return Qg(r,`/v1/tokens/${encodeURIComponent(i)}/recordings/${encodeURIComponent(o)}/assets/${encodeURIComponent(a)}${c}`)}const lm=new Map;function dm(e,t){const n=e;return lm.set(n,{createdAt:Date.now(),label:t}),n}function um(e){const t=e;lm.delete(t)}function hm(){const e=lm.size;return lm.clear(),e}function gm(){const e=Array.from(lm.entries()).map(([e,t])=>({id:e,...t}));return{size:lm.size,entries:e}}class mm extends br{constructor(e,t=!1){super(e,t)}async getChart(e){if(null==e)throw Ht("options","Chart options");const{tokenName:t,from:n,to:r,resolution:s}=e;if(null==t||""===t)throw Ht("tokenName","Token name");if(null==n)throw Ht("from","Start timestamp");if(null==r)throw Ht("to","End timestamp");if(null==s)throw Ht("resolution","Data resolution interval");ur(t,"tokenName",_r);const i=173e6;if("number"!=typeof n||n<i)throw new kt("from must be a valid timestamp (min: 173000000)","from","INVALID_TIMESTAMP");if("number"!=typeof r||r<i)throw new kt("to must be a valid timestamp (min: 173000000)","to","INVALID_TIMESTAMP");if("number"!=typeof s||s<1)throw new kt("resolution must be a number >= 1","resolution","INVALID_RESOLUTION");const{adaptQueryParams:o}=await Promise.resolve().then(function(){return kl}),a=o({tokenName:t,from:n,to:r,resolution:s}),c=await dn(()=>this.http.get(R.CHART,a),{errorContext:"Failed to fetch chart data"}),l=on(c);if(null==l||"object"!=typeof l)throw Vt("Invalid API response: missing or invalid data",c.status??500);const d=l,u=d.data;if(!Array.isArray(u))throw Vt("Invalid API response: expected data array",c.status??500);const h={dataPoints:u.map(e=>{if("object"!=typeof e||null===e)throw Vt("Invalid API response: invalid data point structure",c.status??500);const t=e,n=t.startTime??t.timestamp,r=t.openPrice??t.value,s=t.closePrice??t.value,i=t.lowPrice??t.value,o=t.highPrice??t.value,a=t.volume??"0";return{startTime:"number"==typeof n?n:Number(n),openPrice:String(r),closePrice:String(s),lowPrice:String(i),highPrice:String(o),volume:String(a)}})};return"boolean"==typeof d.isPreviousData&&(h.isPreviousData=d.isPreviousData),h}}const fm={NEW_HOLDER:"NEW_HOLDER",EXITED_HOLDER:"EXITED_HOLDER",BALANCE_CHANGED:"BALANCE_CHANGED"},pm=qi({type:"string",userAddress:"string",balance:"string",rank:"number",previousRank:"optional-number"}),Em=qi({tokenName:"string",userAddress:"string",quantity:"optional-string",percentage:"optional-number",holderTier:"optional-object",isCreator:"boolean",rank:"optional-number"});function Am(e){return"string"==typeof e&&(e===fm.NEW_HOLDER||e===fm.EXITED_HOLDER||e===fm.BALANCE_CHANGED)}Cr.MIN_LENGTH,Cr.MAX_LENGTH,Cr.PATTERN;lr({ENABLED:"ENABLED",DISABLED:"DISABLED",ADMIN_DISABLED:"ADMIN_DISABLED"});function vm(e){return"global"===e||"token"===e}function Tm(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.messageId&&"string"==typeof t.content&&"string"==typeof t.userAddress&&"string"==typeof t.tokenName&&"string"==typeof t.createdAt}function ym(e){return Tm(e)}function Sm(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.message}function bm(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.messageId&&"string"==typeof t.deletedAt}function Nm(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.messageId&&"string"==typeof t.content&&"string"==typeof t.userAddress&&"string"==typeof t.pinnedBy&&"string"==typeof t.pinnedAt}function wm(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&Nm(t.pinnedMessage)}function km(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.unpinnedMessageId}function _m(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"boolean"==typeof t.enabled&&(void 0===t.reason||vm(t.reason))}function Im(e){return!!ir(e)&&(e.length>=Fr.CHAT_MESSAGE.MIN_LENGTH&&e.length<=Fr.CHAT_MESSAGE.MAX_LENGTH)}function Cm(e){return!!ir(e)&&Cr.PATTERN.test(e)}function Dm(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.emoji&&"number"==typeof t.timestamp&&"number"==typeof t.streamTime}function Rm(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.message}const Om=lr({RATE_LIMITED:"RATE_LIMITED",INVALID_EMOJI:"INVALID_EMOJI",NOT_AUTHENTICATED:"NOT_AUTHENTICATED",STREAM_NOT_LIVE:"STREAM_NOT_LIVE"});function Mm(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.userAddress&&"string"==typeof t.fullName&&(void 0===t.profileImage||"string"==typeof t.profileImage)}function Lm(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&Array.isArray(t.typingUsers)&&t.typingUsers.every(Mm)}const Um={ONE_SECOND_MS:1e3,ONE_MINUTE_MS:6e4,ONE_HOUR_MS:36e5,ONE_DAY_MS:864e5,ONE_WEEK_MS:6048e5,ONE_MONTH_MS:2592e6};var Fm,Pm,xm,Bm,Gm,$m;!function(e){e.PENDING="PENDING",e.PROCESSING="PROCESSING",e.COMPLETED="COMPLETED",e.FAILED="FAILED"}(Fm||(Fm={})),function(e){e.TEXT="TEXT",e.IMAGE="IMAGE",e.VIDEO="VIDEO"}(Pm||(Pm={})),function(e){e.NO_ACTION="NO_ACTION",e.REVIEW_REQUIRED="REVIEW_REQUIRED",e.DELETE_CONTENT="DELETE_CONTENT",e.BAN_USER="BAN_USER",e.DELETE_AND_BAN="DELETE_AND_BAN"}(xm||(xm={})),function(e){e.VIOLENCE="VIOLENCE",e.HATE_SPEECH="HATE_SPEECH",e.SEXUAL_CONTENT="SEXUAL_CONTENT",e.HARASSMENT="HARASSMENT",e.SPAM="SPAM",e.SCAM="SCAM",e.SELF_HARM="SELF_HARM",e.ILLEGAL_ACTIVITY="ILLEGAL_ACTIVITY",e.MISINFORMATION="MISINFORMATION",e.COPYRIGHT="COPYRIGHT",e.SAFE="SAFE"}(Bm||(Bm={})),function(e){e.QUICK="QUICK",e.DETAILED="DETAILED"}(Gm||(Gm={})),function(e){e.DISABLED="DISABLED",e.ADVISORY="ADVISORY"}($m||($m={}));const Km={[Fm.PENDING]:"Pending",[Fm.PROCESSING]:"Processing",[Fm.COMPLETED]:"Completed",[Fm.FAILED]:"Failed"},Hm={[xm.NO_ACTION]:"No Action Needed",[xm.REVIEW_REQUIRED]:"Human Review Required",[xm.DELETE_CONTENT]:"Delete Content",[xm.BAN_USER]:"Ban User",[xm.DELETE_AND_BAN]:"Delete & Ban"},Wm={[Bm.VIOLENCE]:"Violence",[Bm.HATE_SPEECH]:"Hate Speech",[Bm.SEXUAL_CONTENT]:"Sexual Content",[Bm.HARASSMENT]:"Harassment",[Bm.SPAM]:"Spam",[Bm.SCAM]:"Scam",[Bm.SELF_HARM]:"Self Harm",[Bm.ILLEGAL_ACTIVITY]:"Illegal Activity",[Bm.MISINFORMATION]:"Misinformation",[Bm.COPYRIGHT]:"Copyright",[Bm.SAFE]:"Safe"},Vm={[Gm.QUICK]:"Quick Scan",[Gm.DETAILED]:"Detailed Scan"},jm={[Pm.TEXT]:"Text",[Pm.IMAGE]:"Image",[Pm.VIDEO]:"Video"},qm={[$m.DISABLED]:"Disabled",[$m.ADVISORY]:"Advisory"},zm=lr(Fm),Qm=lr(Pm),Xm=lr(xm),Ym=lr(Bm),Jm=lr(Gm),Zm=lr($m),ef=fr([{field:"id",type:"number"},{field:"flagId",type:"number"},{field:"status",type:"string",validator:zm},{field:"analysisType",type:"string",validator:Qm},{field:"provider",type:"string"}]),tf=fr([{field:"enabled",type:"boolean"},{field:"mode",type:"string",validator:Zm},{field:"provider",type:"string"}]);function nf(e){return null!==e.analysisTier}function rf(e){return!0===e.escalatedFromQuick}function sf(e,t){if(!nf(e)||null===e.tokensUsed)return 0;const n=1500*t.maxFrames;if(0===n)return 0;const r=(n-e.tokensUsed)/n*100;return Math.max(0,Math.round(r))}function of(e){if(!(void 0!==e.tokenName&&""!==e.tokenName||void 0!==e.userAddress&&""!==e.userAddress))throw en(["tokenName","userAddress"]);void 0!==e.tokenName&&""!==e.tokenName&&mr(e.tokenName,"tokenName",_r),cr(0,void 0,Lr,e.pageSize,e.cursor)}function af(e){if(!ir(e.tokenName))throw Ht("tokenName","Token name");mr(e.tokenName,"tokenName",_r),lf(e.content)}function cf(e){lf(e.content)}function lf(e){if(!ir(e))throw Ht("content");if(0===e.trim().length)throw nn("content","Content");if(e.length>Fr.COMMENTS_V1.MAX_LENGTH)throw tn("content",Fr.COMMENTS_V1.MAX_LENGTH,e.length)}function df(e){if(!(void 0!==e.tokenName&&""!==e.tokenName||void 0!==e.userAddress&&""!==e.userAddress))throw new kt("At least one of tokenName or userAddress is required","options",wt.REQUIRED);ed(e.tokenName,e.userAddress),void 0!==e.pageSize&&cr(0,void 0,Lr,e.pageSize)}function uf(e){if(!ir(e.tokenName))throw Ht("tokenName");mr(e.tokenName,"tokenName",_r),gf(e.content)}function hf(e){gf(e.content)}function gf(e){if(!ir(e))throw Ht("content");if(0===e.trim().length)throw new kt("content cannot be empty","content",wt.REQUIRED);if(e.length>Fr.CHAT_MESSAGES_V1.MAX_LENGTH)throw new kt(`content must be at most ${Fr.CHAT_MESSAGES_V1.MAX_LENGTH} characters`,"content",wt.TOO_LONG)}function mf(e){if(!ir(e))throw Ht("id","Message ID");if(!Pr.CHAT_MESSAGE.PATTERN.test(e))throw new kt("Invalid message ID format. Expected: chat-{timestamp}-{uuid}","id",wt.INVALID_FORMAT)}var ff=Object.freeze({__proto__:null,extractMetadataFromPoolData:function(e,t){const n={};if(void 0!==e.vaultAddress&&(n.vaultAddress=e.vaultAddress),void 0!==e.reverseBondingCurveMinFeePortion){const r=Hn(e.reverseBondingCurveMinFeePortion,NaN);isNaN(r)?t&&t.debug(`Skipping invalid reverseBondingCurveMinFeePortion for ${e.tokenName}: "${e.reverseBondingCurveMinFeePortion}"`):n.reverseBondingCurveMinFeeFactor=r}if(void 0!==e.reverseBondingCurveMaxFeePortion){const r=Hn(e.reverseBondingCurveMaxFeePortion,NaN);isNaN(r)?t&&t.debug(`Skipping invalid reverseBondingCurveMaxFeePortion for ${e.tokenName}: "${e.reverseBondingCurveMaxFeePortion}"`):n.reverseBondingCurveMaxFeeFactor=r}return void 0!==n.reverseBondingCurveMaxFeeFactor&&void 0!==n.reverseBondingCurveMinFeeFactor&&(n.reverseBondingCurveNetFeeFactor=n.reverseBondingCurveMaxFeeFactor-n.reverseBondingCurveMinFeeFactor),Object.keys(n).length>0?n:null},isValidPoolForCaching:function(e){if(null===e||"object"!=typeof e)return!1;const t=e;return"tokenName"in t&&"string"==typeof t.tokenName&&t.tokenName.length>0}});export{la as ACTIVE_USER_TYPE,$m as AIModerationMode,xm as AIRecommendation,qm as AI_MODE_LABELS,Hm as AI_RECOMMENDATION_LABELS,Zo as ALL_PERMISSIONS,Wm as ANALYSIS_CATEGORY_LABELS,Km as ANALYSIS_STATUS_LABELS,Vm as ANALYSIS_TIER_LABELS,jm as ANALYSIS_TYPE_LABELS,Yo as API_KEY_PERMISSION,Qo as API_KEY_ROLE,Xo as API_KEY_ROLES,ia as API_KEY_ROLE_HIERARCHY,Dn as AddressFormatter,ag as AgentConfig,Bm as AnalysisCategory,Fm as AnalysisStatus,Gm as AnalysisTier,Pm as AnalysisType,Ao as AuthError,Eo as AuthErrorType,ca as BAN_DURATIONS,Pa as BrowserWalletSigner,fh as BundleSubmission,ph as BundlerTransport,ll as BurnError,cl as BurnErrorType,Nt as CALCULATION_MODES,fc as CONTENT_REACTION_TYPES,sc as CONTENT_TYPE_LABELS,mm as ChartService,Ot as ConfigurationError,ja as ContentType,yc as DEFAULT_EVENTS_CONFIG,Lg as DEFAULT_PRICING_CONCURRENCY,Dh as DEFAULT_REVERSE_BONDING_CURVE_CONFIGURATION,Ug as DEFAULT_WEBSOCKET_RECONNECT_ATTEMPTS,wo as ENVIRONMENT_URLS,wt as ERROR_CODES,Nc as EVENT_SORT_FIELDS,kc as EVENT_SOURCES,wc as EVENT_TIME_PRESETS,Sc as EVENT_TYPES,Au as EXTENDED_STREAM_ROLE,Ig as EventBufferWithAutoCleanup,bc as EventsBatcherService,Rc as EventsQueryService,rc as FLAG_ACTION_LABELS,ic as FLAG_DETAILS_MAX_LENGTH,tc as FLAG_REASON_LABELS,nc as FLAG_STATUS_LABELS,Tl as FileValidationError,Qa as FlagAction,qa as FlagReason,za as FlagStatus,Rg as GALA_DECIMALS,Fa as GalaWalletSigner,wg as GlobalAndRoomCallbackDispatcher,fm as HOLDER_DELTA_TYPES,vl as HealthService,Ts as IMAGE_EXTENSIONS,Ed as INVITE_STATUS,Ad as INVITE_STATUSES,fo as JWT_CONSTANTS,Og as LAUNCHPAD_TOKEN_DECIMALS,mh as LAUNCHPAD_WRITE_METHODS,rg as LaunchpadSDK,_a as LaunchpadSDKError,$h as LaunchpadWrites,_g as ListenerCleanupManager,Hc as LockError,$c as LockErrorType,al as MAX_BURN_BATCH_SIZE,Dg as MAX_CONCURRENT_POOL_FETCHES,Bc as MAX_LOCK_BATCH_SIZE,Gc as MAX_UNLOCK_BATCH_SIZE,nd as MESSAGES_CONSTRAINTS,td as MESSAGE_TYPES,gd as MODERATOR_ROLE,md as MODERATOR_ROLES,Dd as NFT_FEES,Rt as NetworkError,Pd as NftCollectionService,Bd as OEmbedService,$d as OVERSEER_INVITE_STATUS,Kd as OVERSEER_STATUS,Ro as PAGINATION_DEFAULTS,Jo as PERMISSION,Oo as POOL_FETCH_CONFIG,yt as POOL_FETCH_TYPES,bt as POOL_LIST_MAX_PAGE_SIZE,St as POOL_STREAM_STATUSES,Tt as POOL_TYPES,bg as PayloadWalkerWithDeduplication,Ng as PendingSubscriptionTracker,ru as PlatformStatsService,Ua as PrivateKeySigner,Mg as QUERY_FIELD_NAMES,pc as REACTION_EMOJI_MAP,au as RECORDING_STATUS,pu as ROLE_SOURCE,Sg as RoomSubscriptionManager,Io as SDKTransactionStatus,Do as SDK_VERSION,wu as SIMULATE_EVENT_TYPE,lu as SIMULCAST_PLATFORM,cu as SIMULCAST_STATUS,_u as STREAM_EVENTS,Eu as STREAM_PERMISSION,fu as STREAM_ROLE,ou as STREAM_STATUS,kg as SelectiveEventForwarding,Ju as StreamWebSocketService,Um as TIME_CONSTANTS,Dr as TOKEN_NAME_AVAILABILITY_CONSTRAINT,_r as TOKEN_NAME_DTO_CONSTRAINT,Rr as TOKEN_NAME_EVENT_CONSTRAINT,Ir as TOKEN_NAME_FILTER_CONSTRAINT,Cr as TOKEN_NAME_PATH_CONSTRAINT,vt as TRADING_TYPES,_t as TokenRestrictedError,ch as TradingQuotesService,Mt as TransactionError,Qh as TransactionFailedError,Cg as TypingIndicatorDebouncer,kt as ValidationError,qh as WebSocketError,zh as WebSocketTimeoutError,gh as WeeklyChallengeService,xg as addCursorToPagination,Zr as addressFormatSchema,Vg as aggregateMultipleApiSources,Fs as amountMethodSchema,Us as amountTypeSchema,Gn as assertValidWalletAddress,qr as availabilityTokenNameSchema,wn as backendUserRef,Kl as bidirectionalTokenMatch,Ss as browserFileSchema,bs as bufferFileSchema,Gg as buildConcurrentBatchRequests,Kg as buildQueryParametersWithValidation,Fg as buildSafePaginationOptions,Ys as buyTokensDataSchema,cg as calculateLinearFeeInterpolation,si as calculatePreMintDataSchema,fg as calculateScaledFeeAmount,Fo as calculateTotalPages,$t as capitalize,Bl as caseInsensitiveTokenComparison,Ls as checkPoolOptionsSchema,pr as commonValidators,yg as conditionalSpreadBuilder,xl as conditionalTrimAndValidateString,sg as createLaunchpadSDK,cs as createLimitSchema,Er as createOptionsValidator,qs as createPaginatedResultSchema,Mo as createPaginationQuery,Xs as createTradeDataSchema,hg as decimalRoundingUp,Tg as deduplicateByKey,jr as dtoTokenNameSchema,Gl as errorMessageCaseNormalization,es as ethereumAddressSchema,Ag as extractFieldWithFallbackPath,$g as extractPaginationMetadata,Ih as feeCeilingFromQuotedFee,li as fetchGalaBalanceOptionsSchema,ii as fetchPoolDetailsDataSchema,hi as fetchTokenBalanceOptionsSchema,hs as fileSizeSchema,ys as fileUploadSchema,gs as filenameSchema,ts as flexibleAddressSchema,Ns as flexibleFileSchema,qn as formatGalaForDTO,zn as formatLaunchpadTokenForDTO,Mn as fromBackendAddressFormat,Jr as fullNameSchema,Ba as generateBuySellStringsInstructions,Ga as generateCreateSaleStringsInstructions,ri as getAmountOptionsSchema,ko as getEnvironmentConfig,gm as getIntervalRegistryStats,$i as getLaunchTokenDataValidationErrors,Rd as getNftFeeAsNumber,sm as getRecordingAnimatedUrl,cm as getRecordingAssetUrl,im as getRecordingPosterUrl,om as getRecordingStoryboardUrl,am as getRecordingStreamUrl,rm as getRecordingThumbnailUrl,sf as getTieredModerationSavings,Jg as getTokenAnimatedUrl,nm as getTokenAssetUrl,Xg as getTokenImageUrl,tm as getTokenLiveStreamUrl,Zg as getTokenPosterUrl,em as getTokenStoryboardUrl,Yg as getTokenThumbnailUrl,Zs as getTradeOptionsSchema,xs as graduateTokenOptionsSchema,Ps as graphDataOptionsSchema,pg as groupByKey,Po as hasMorePages,Hl as hexStringExtractionAndNormalization,ws as imageExtensionSchema,ks as imageFilenameSchema,ms as imageMimeTypeSchema,Os as imageUploadOptionsSchema,ef as isAIModerationData,Zm as isAIModerationMode,tf as isAIModerationSettings,Xm as isAIRecommendation,da as isActiveUserType,Ym as isAnalysisCategory,zm as isAnalysisStatus,Jm as isAnalysisTier,Qm as isAnalysisType,ua as isBanData,ma as isBanEnforcementEvent,il as isBurnTokenEntry,ol as isBurnTokensData,vm as isChatDisabledReason,_m as isChatStatusResponse,Vd as isClaimableInvite,oc as isContentType,or as isEmptyValue,vu as isExtendedStreamRole,lc as isFlagAction,dc as isFlagData,ac as isFlagReason,cc as isFlagStatus,pm as isHolderDelta,Am as isHolderDeltaType,Uc as isLockTokenEntry,Pc as isLockTokensData,dd as isMessage,ud as isMessageType,bd as isModeratedToken,nf as isModerationTiered,Sd as isModeratorInvite,ir as isNonEmptyString,Hd as isOverseerInviteStatus,Wd as isOverseerStatus,Nm as isPinnedMessage,Nd as isPublicInviteInfo,Om as isReactionErrorCode,uu as isRecordingStatus,hu as isSimulcastPlatform,bm as isStreamChatDeletedEvent,Sm as isStreamChatErrorEvent,Tm as isStreamChatMessage,ym as isStreamChatMessageEvent,wm as isStreamChatPinnedEvent,km as isStreamChatUnpinnedEvent,Rm as isStreamReactionErrorEvent,Dm as isStreamReactionEvent,du as isStreamStatus,gu as isStreamStatusEvent,Tu as isTokenAccessResult,eh as isTokenBanData,Lm as isTypingIndicatorEvent,Mm as isTypingUser,Fc as isUnlockTokenEntry,xc as isUnlockTokensData,ha as isUserBannedEvent,Em as isUserHoldingData,Cn as isUserRef,ga as isUserUnbannedEvent,Un as isValidAddress,ea as isValidApiKeyRole,pa as isValidBanDuration,fa as isValidBanReason,Im as isValidChatContent,Cm as isValidChatTokenName,yd as isValidInviteCode,Td as isValidInviteStatus,Gi as isValidLaunchTokenData,vd as isValidModeratorRole,th as isValidTokenBanReason,gr as isValidTokenName,mu as isViewerCountEvent,fs as isoDateStringSchema,Rs as launchTokenDataSchema,Pg as mergeSafePaginationOptions,ss as nonNegativeDecimalStringSchema,Ln as normalizeAddressInput,vg as normalizeDataWithMapping,$l as normalizeErrorMessage,Uo as normalizeLimit,mn as normalizeTokenKey,gn as normalizeTokenName,fn as normalizeTokenSymbol,os as optionalUrlSchema,as as pageNumberSchema,js as paginationResultMetaSchema,Wg as parseHttpErrorResponse,xa as parseLaunchpadVaultAddress,ug as percentileIndexCalculation,Ms as poolFetchTypeSchema,Ks as poolPaginationSchema,rs as positiveDecimalStringSchema,dg as priceTickRangeMapping,Es as privateKeySchema,dm as registerInterval,to as requireNonNegative,eo as requirePositive,no as requirePositiveWithContext,Hg as retryableHttpRequest,Ds as reverseBondingCurveConfigSchema,oi as reverseBondingCurveConfigurationSchema,oa as roleHasSufficientPermission,lg as roundTickBoundaries,mg as roundTickToSpacing,gg as safeDivideWithMinimum,Yr as searchQuerySchema,Js as sellTokensDataSchema,ls as standardLimitSchema,Bs as standardPaginationSchema,ps as timestampSchema,On as toBackendAddressFormat,$n as toBackendAddressFromEthers,Is as tokenCategorySchema,Cs as tokenCollectionSchema,Qr as tokenDescriptionSchema,ci as tokenListOptionsSchema,Vr as tokenNameSchema,zr as tokenSymbolSchema,_s as tokenUrlsSchema,ni as tradeCalculationMethodSchema,ti as tradeCalculationTypeSchema,us as tradeLimitSchema,ei as tradeListParamsSchema,$s as tradePaginationSchema,Ws as tradePaginationWithFiltersSchema,Qs as tradeTypeBackendSchema,zs as tradeTypeSchema,As as transactionIdSchema,Eg as transformRawApiTokenToDomainModel,Wl as trimmedLengthValidation,vs as uniqueKeySchema,hm as unregisterAllIntervals,um as unregisterInterval,di as updateProfileDataSchema,ui as uploadProfileImageOptionsSchema,is as urlSchema,ds as userLimitSchema,Gs as userPaginationSchema,Nn as userRef,Xr as userTokenNameSchema,ai as userTokenTypeSchema,Hs as userTokensPaginationSchema,Ei as validateAddress,vi as validateAmountString,nh as validateBanTokenOptions,Mi as validateBuyTokensData,xi as validateCalculatePreMintData,mf as validateChatMessageId,ki as validateCheckPoolOptions,rr as validateConstrainedEnumVariant,ta as validateCreateApiKeyOptions,uf as validateCreateChatMessageOptions,af as validateCreateCommentOptions,sd as validateCreateMessageOptions,kd as validateCreateModeratorInviteOptions,Zd as validateCreateOverseerDirectOptions,jd as validateCreateOverseerInviteOptions,Oi as validateCreateTradeData,er as validateDecimalRangeStrict,tr as validateFeePortionConstraints,Ii as validateFetchGalaBalanceOptions,rd as validateFetchMessagesOptions,Bi as validateFetchPoolDetailsData,Ri as validateFetchTokenBalanceOptions,Ti as validateFullName,Pi as validateGetAmountOptions,df as validateGetChatMessagesOptions,of as validateGetCommentsOptions,ih as validateGetTokenBanOptions,Ui as validateGetTradeOptions,Ul as validateGetTradesOptions,wi as validateImageUploadOptions,_d as validateInviteCode,Ki as validateLaunchTokenData,sa as validateListApiKeysOptions,Id as validateListModeratorInvitesOptions,qd as validateListOverseerInvitesOptions,zd as validateListOverseersOptions,sh as validateListTokenBansOptions,Jd as validateListUsersOptions,od as validateMessageId,nr as validateMinMaxRelationship,hr as validateOptionalTokenName,Qd as validateOverseerInviteCode,Yd as validateOverseerInviteId,Xd as validateOverseerWalletAddress,Lo as validatePaginationParams,yi as validateSearchQuery,Li as validateSellTokensData,Zn as validateSortOrderDirection,pi as validateTokenDescription,_i as validateTokenListOptions,mr as validateTokenName,fi as validateTokenSymbol,Ni as validateTokenUrls,Fi as validateTradeListParams,rh as validateUnbanTokenOptions,na as validateUpdateApiKeyOptions,hf as validateUpdateChatMessageOptions,cf as validateUpdateCommentOptions,id as validateUpdateMessageOptions,tu as validateUpdatePlatformConfigOptions,Ci as validateUpdateProfileData,Nl as validateUpdateTokenConfigOptions,Di as validateUploadProfileImageOptions,Si as validateUserTokenName,Ai as validateVaultAddress,ns as vaultAddressSchema,rf as wasModerationEscalated};