@gala-chain/launchpad-sdk 9.0.0-rc.1 → 9.0.0-rc.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +16 -1
- package/EXAMPLES.md +1 -1
- package/MIGRATING-TO-9.0.md +1 -1
- package/dist/LaunchpadSDK.d.ts +2 -2
- package/dist/constants/version.generated.d.ts +1 -1
- package/dist/index.browser.esm.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.esm.js +1 -1
- package/dist/index.js +1 -1
- package/dist/native.cjs +1 -1
- package/dist/native.esm.js +1 -1
- package/dist/schemas/primitives.d.ts +2 -2
- package/dist/services/PoolService.d.ts +4 -1
- package/dist/services/PoolService.d.ts.map +1 -1
- package/dist/types/constraints.d.ts +2 -2
- package/dist/types/launchpad.dto.d.ts +22 -0
- package/dist/types/launchpad.dto.d.ts.map +1 -1
- package/dist/types/options.dto.d.ts +1 -1
- package/dist/types/options.dto.d.ts.map +1 -1
- package/dist/utils/error-factories.d.ts +4 -4
- package/dist/utils/errors.d.ts +1 -1
- package/dist/utils/validation-helpers.d.ts +1 -1
- 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{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:25,PATTERN:/^[a-zA-Z0-9]{1,25}$/,DESCRIPTION:"1-25 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(25,"Token name must be at most 25 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.2",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));if(void 0!==e.isGraduated){if("boolean"!=typeof e.isGraduated)throw Qt("isGraduated","boolean",e.isGraduated);n.isGraduated=e.isGraduated?"true":"false"}void 0!==e.creatorAddress&&(n.creatorAddress=function(e){if("string"!=typeof e)throw Qt("creatorAddress","string",e);Ur(e,"creatorAddress");const t=e.toLowerCase().trim();if(t.startsWith("eth|")||t.startsWith("client|"))return t.replace(/0x/g,"");const n=t.replace(/^0x/,"");return/^[0-9a-f]{24}$/.test(n)?`client|${n}`:`eth|${n}`}(e.creatorAddress));return n}(e),n=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};
|