@gala-chain/launchpad-sdk 9.0.0-rc.6 → 9.1.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.esm.js CHANGED
@@ -1 +1 @@
1
- import{galaChainUserRef as e,isGalaError as t,GALA_CHAIN_ENVIRONMENTS as n,BrowserWalletSigner as r,generateEIP712Types as s,ethereumAddressOfAccount as i,GalaWalletSigner as o,withGalaWalletIdentity as a,PrivateKeySigner as c,isTokenClassKey as l,GatewayReads as d,GatewayWrites as u,tokenDetailsOf as h,isWalletUserRejection as g,walletDeclineCode as m,createWallet as f}from"@gala-chain/gala-core-sdk";import{computeAddress as p,getAddress as E,isAddress as A,BrowserProvider as v,Wallet as T}from"ethers";import{z as y}from"zod";import{PrivateKeyProvider as S,isPrivateKeyProvider as b}from"@gala-chain/gala-core-sdk/providers";import{ChainCallDTO as N,TokenClassKey as w}from"@gala-chain/api";import{v4 as k}from"uuid";import{io as _}from"socket.io-client";import I from"bignumber.js";import D,{AxiosHeaders as C}from"axios";const R={UPLOAD_IMAGE:"/v1/tokens/:tokenName/image",FETCH_POOLS:"/v1/tokens",GET_TOKEN:"/v1/tokens/:tokenName",GET_TOKEN_DISTRIBUTION:"/v1/holders",CHART:"/v1/chart",GET_TRADES:"/v1/tokens/:tokenName/trades",GET_PROFILE:"/v1/users/:address",UPDATE_PROFILE:"/v1/users/me",GET_CURRENT_USER:"/v1/users/me/profile",UPLOAD_PROFILE_IMAGE:"/v1/users/me/image",GET_TOKEN_LIST:"/v1/users/:address/tokens",GET_TOKENS_HELD:"/v1/users/:address/tokens",GET_GALA_BALANCE:"/v1/users/:address/gala-balance",GET_REFERRAL_CODE:"/v1/connect/users/referrals/code",GET_MANAGED_TOKENS:"/v1/users/me/managed-tokens",VALIDATE_TOKEN:"/v1/utils/validate-token",UPDATE_TOKEN_CONFIG:"/v1/tokens/:tokenName",TOKEN_STATS:"/v1/tokens/:tokenName/stats",OEMBED:"/oembed",OEMBED_BUY_SELL:"/oembed/buy-sell/:tokenName",OEMBED_PROFILE:"/oembed/profile/:address"},O="/v1/users/referrals/url",M="/v1/users/referrals",L="/v1/users/referrals/summary",U="/v1/tokens/:tokenName/start-stream",F="/v1/tokens/:tokenName/stop-stream",P="/v1/tokens/:tokenName/stream/disable",x="/v1/tokens/:tokenName/stream/enable",B="/v1/tokens/:tokenName/reset-key",G="/v1/tokens/:tokenName/recordings",$="/v1/tokens/:tokenName/recordings/:assetId/download",K="/v1/tokens/:tokenName/recordings/:assetId",H="/v1/tokens/:tokenName/simulcasts",W="/v1/tokens/:tokenName/simulcasts",V="/v1/tokens/:tokenName/simulcasts/:targetId",j="/v1/config",q="/v1/config",z="/v1/config",X="/v1/tokens/:tokenName/role",Q="/v1/roles",Y="/v1/permissions",J="/v1/tokens/:tokenName/credentials",Z="/auth/login",ee="/auth/logout",te="/auth/refresh",ne="/auth/session",re="/v1/tokens/:tokenName/bans",se="/v1/tokens/:tokenName/bans",ie="/v1/tokens/:tokenName/bans/:userAddress",oe="/v1/tokens/:tokenName/bans/:userAddress",ae="/v1/tokens/:tokenName/active-users",ce="/v1/user-bans",le="/v1/user-bans",de="/v1/user-bans/:userAddress",ue="/v1/user-bans/:userAddress",he={CREATE:"/v1/api-keys",LIST:"/v1/api-keys",GET:"/v1/api-keys/:id",UPDATE:"/v1/api-keys/:id",REVOKE:"/v1/api-keys/:id"},ge="/v1/moderator-invites",me="/v1/moderator-invites/claim",fe="/v1/moderated-tokens",pe="/v1/moderator-invites",Ee="/v1/moderator-invites/:id",Ae="/v1/moderator-invites/:id/role",ve="/v1/moderator-invites/:id",Te="/v1/moderator-invites/code/:code",ye={CREATE:"/v1/content-flags",LIST:"/v1/content-flags",DISMISS:"/v1/content-flags/:id/dismiss",ACTION:"/v1/content-flags/:id/action"},Se="/v1/overseer-invites",be="/v1/overseer-invites",Ne="/v1/overseer-invites/code/:code",we="/v1/overseer-invites/claim",ke="/v1/overseer-invites/:id",_e="/v1/overseers",Ie="/v1/overseers",De="/v1/overseers/:address",Ce="/v1/overseers/me",Re="/v1/overseer-summary",Oe="/v1/overseer-summary/bans",Me="/v1/overseer-summary/token-bans",Le="/v1/overseer-summary/invites",Ue="/v1/overseer-summary/flags",Fe="/v1/overseer-summary/users",Pe="/v1/users",xe="/v1/users/:address/summary",Be="/v1/cache/flush/address/:address",Ge="/v1/cache/flush/token/:tokenName",$e="/v1/cache/flush/all",Ke="/v1/cache/flush/wallet-aliases/:address",He="/v1/cache/flush/wallet-aliases",We="/v1/token-bans",Ve="/v1/token-bans",je="/v1/token-bans/:tokenName",qe="/v1/token-bans/:tokenName",ze="/v1/reactions",Xe="/v1/reactions",Qe="/v1/trades",Ye={GET_MESSAGES:"/v1/messages",CREATE_MESSAGE:"/v1/messages",UPDATE_MESSAGE:"/v1/messages/:id",DELETE_MESSAGE:"/v1/messages/:id",GET_PINNED:"/v1/messages/pinned",PIN_MESSAGE:"/v1/messages/:id/pin",UNPIN_MESSAGE:"/v1/messages/:id/pin",GET_MESSAGE_STATS:"/v1/messages/stats"},Je="/v1/restricted-token-names",Ze="/v1/restricted-token-names",et="/live/:tokenName/chat",tt="/live/:tokenName/chat",nt="/live/:tokenName/chat",rt="/live/:tokenName/chat/slow-mode",st="/v1/events",it="/v1/events/stats",ot="/health",at={GET_SETTINGS:"/v1/ai-moderation/settings",UPDATE_SETTINGS:"/v1/ai-moderation/settings",GET_MODERATION:"/v1/ai-moderation/flags/:flagId",TRIGGER_MODERATION:"/v1/ai-moderation/flags/:flagId/analyze",GET_STATUS:"/v1/ai-moderation/status"},ct="/v1/stats",lt="/v1/trading/fee",dt="/v1/trading/sale-details",ut="/v1/trading/quote",ht="/v1/trading/premint-quote",gt={GET_LEADERBOARD:"/weekly-challenge",GET_TOKEN_HISTORY:"/weekly-challenge/history/:vaultAddress"},mt="/v1/notifications/register",ft="/v1/notifications/unregister",pt="/v1/notifications/preferences",Et="/v1/notifications/preferences",At="/v1/config/client-flags",vt={NATIVE:"native",EXACT:"exact"},Tt={RECENT:"recent",POPULAR:"popular"},yt=["RECENT","POPULAR","RECORDINGS","SECONDS_STREAMED"],St=["IDLE","ACTIVE","DISABLED"],bt=100,Nt={LOCAL:"local",EXTERNAL:"external"},wt={REQUIRED:"REQUIRED",INVALID_TYPE:"INVALID_TYPE",INVALID_VALUE:"INVALID_VALUE",INVALID_FORMAT:"INVALID_FORMAT",TOO_SHORT:"TOO_SHORT",TOO_LONG:"TOO_LONG",TOO_LARGE:"TOO_LARGE",TOO_SMALL:"TOO_SMALL",EMPTY_ARRAY:"EMPTY_ARRAY",ARRAY_TOO_LARGE:"ARRAY_TOO_LARGE",ZERO_VALUE:"ZERO_VALUE",INVALID_TICK_SPACING:"INVALID_TICK_SPACING",INVALID_FEE_TIER:"INVALID_FEE_TIER",INVALID_RANGE:"INVALID_RANGE",INVALID_PARAMETERS:"INVALID_PARAMETERS",NOT_FOUND:"NOT_FOUND",INVALID_DATA:"INVALID_DATA"};class kt extends Error{constructor(e,t,n){super(e),this.field=t,this.code=n,this.name="ValidationError"}}class _t extends kt{constructor(e){super(e,"token","TOKEN_RESTRICTED"),this.name="TokenRestrictedError"}}function It(e){return"object"==typeof e&&null!==e}function Dt(e){if(null==e||""===e)return{};if(!It(e)||Array.isArray(e))return{body:e};const t=Reflect.get(e,"message"),n="string"==typeof t?t:Array.isArray(t)&&t.every(e=>"string"==typeof e)?t.join(","):void 0,r=Reflect.get(e,"error"),s=Reflect.get(e,"details");return{...void 0===n?{}:{serverMessage:n},..."string"==typeof r&&""!==r?{serverError:r}:{},...void 0===s?{}:{details:s},body:e}}function Ct(e){if(e instanceof Rt)return{...void 0===e.serverMessage?{}:{serverMessage:e.serverMessage},...void 0===e.serverError?{}:{serverError:e.serverError},...void 0===e.details?{}:{details:e.details},...void 0===e.body?{}:{body:e.body}};const t=function(e){if(!It(e))return;const t=Reflect.get(e,"response");return It(t)?t:void 0}(e);return void 0===t?{}:Dt(Reflect.get(t,"data"))}class Rt extends Error{constructor(e,t,n,r=Ct(n)){super(e),this.name="NetworkError",this.statusCode=t,this.originalError=n,this.serverMessage=r.serverMessage,this.serverError=r.serverError,this.details=r.details,this.body=r.body}}class Ot extends Error{constructor(e,t){super(e),this.field=t,this.name="ConfigurationError"}}class Mt extends Error{constructor(e,t,n){super(e),this.transactionId=t,this.code=n,this.name="TransactionError"}}function Lt(e){return e instanceof Error}function Ut(e){return Lt(e)||function(e){return"object"==typeof e&&null!==e&&"message"in e&&"string"==typeof e.message}(e)?e.message:"string"==typeof e?e:String(e)}function Ft(e){return Lt(e)||"object"==typeof e&&null!==e&&"stack"in e&&"string"==typeof e.stack?e.stack:void 0}function Pt(e){if(function(e){return"object"==typeof e&&null!==e&&"code"in e&&("string"==typeof e.code||"number"==typeof e.code)}(e))return e.code}function xt(e){return"object"==typeof e&&null!==e&&"message"in e&&("response"in e||"request"in e||"config"in e)}function Bt(e,t){if(null==e||"object"!=typeof e)throw new Error(`${t}: No response - expected object, got ${typeof e}`);const n=e;if(!("Status"in n))throw new Error(`${t}: Response missing 'Status' property`);const r=n.Status;if("number"!=typeof r)throw new Error(`${t}: Response Status must be a number, got ${typeof r}`);if(1!==r)throw new Error(`${t}: Response status indicates failure (Status: ${r})`);return n}function Gt(e,t,n){try{t()}catch(t){if(!function(e){return e instanceof Error&&"ValidationError"===e.name}(t))throw t;{const n=t.message;e.push(n)}}}function $t(e,t){return void 0!==t?t:e.charAt(0).toUpperCase()+e.slice(1)}function Kt(e,t){return new kt(`Token "${e}" not found. Please verify the token name is correct.`,"tokenName","TOKEN_NOT_FOUND")}function Ht(e,t){const n=$t(e,t);return new kt(`${n} is required`,e,"REQUIRED")}function Wt(e,t,n){const r=$t(e,n);return new kt(`${r} must be ${t}`,e,"INVALID_FORMAT")}function Vt(e,t,n,r){return new Rt(e,t,n,r)}function jt(e,t){return new Ot(e,t)}function qt(e,t,n){return new Mt(e,t,n)}function zt(e,t,n,r,s){const i=$t(e,s);return new kt(`${i} must be between ${t} and ${n}${void 0!==r?`, received: ${r}`:""}`,e,"OUT_OF_RANGE")}function Xt(e,t,n,r){const s=$t(e,r);return new kt(`${s} must be at least ${t}${void 0!==n?`, received: ${n}`:""}`,e,"TOO_SMALL")}function Qt(e,t,n,r){const s=$t(e,r);return new kt(`${s} must be at most ${t}${void 0!==n?`, received: ${n}`:""}`,e,"TOO_LARGE")}function Yt(e,t,n,r){const s=$t(e,r),i=void 0!==n?`, received: ${"object"==typeof n?"object":String(n)}`:"";return new kt(`${s} must be ${t}${i}`,e,"INVALID_TYPE")}function Jt(e,t,n){const r=$t(e,n);return new kt(`${r} must be a valid number${void 0!==t?`: "${t}"`:""}`,e,"INVALID_NUMBER")}function Zt(e,t,n,r){const s=$t(e,r);return new kt(`Invalid ${s}: ${t}. Must be one of: ${n.join(", ")}`,e,"INVALID_ENUM")}function en(e,t){if(e.length<2)return Ht(void 0!==e[0]&&""!==e[0]?e[0]:"field");let n;if(2===e.length)n=e.join(" or ");else{n=`${e.slice(0,-1).join(", ")} or ${e[e.length-1]??"field"}`}return new kt(`At least one of ${n} must be provided`,e[0],"REQUIRED")}function tn(e,t,n,r){const s=$t(e,r);return new kt(`${s} must be at most ${t} characters${void 0!==n?`, received: ${n}`:""}`,e,"TOO_LONG")}function nn(e,t){const n=$t(e,t);return new kt(`${n} cannot be empty`,e,"EMPTY_STRING")}function rn(e){return null!=e&&"object"==typeof e&&"data"in e}function sn(e,t,n=!1){const r=!0===e.error,s=n&&(null===e.data||void 0===e.data);if(r||s){const n=e?.statusCode??e.status??void 0;throw Vt(e?.message??t,n,void 0,r?Dt(e):void 0)}}function on(e){if(rn(e))return e.data}function an(e,t="No data found in response"){if(!rn(e))throw Vt(t);const n=e.data;if(null==n)throw Vt(t);return n}async function cn(e,t={}){return un(e,t,e=>{if(void 0===e.data)throw new kt(`${t.errorContext??"Operation failed"}: No data returned from API`,"data","NO_DATA");return e.data})}async function ln(e,t={}){const{errorContext:n="Operation failed",logger:r,debugLogEnabled:s=!1}=t;s&&r&&r.debug(`${n}: starting operation`);try{const t=await e();return s&&r&&r.debug(`${n}: completed successfully`),t}catch(e){throw r&&r.error(n,{error:e}),e}}async function dn(e,t={}){return un(e,t,e=>e)}async function un(e,t,n){const{errorContext:r="Operation failed",logger:s,debugLogEnabled:i=!1}=t;i&&s&&s.debug(`${r}: starting operation`);try{const t=await e();if(null==t)throw new kt(`${r}: No response from server`,"response","NO_RESPONSE");return sn(t,r,!0),i&&s&&s.debug(`${r}: completed successfully`),n(t)}catch(e){throw s&&s.error(r,{error:e}),e}}const hn={BASE_PRICE:1650667151e-14,PRICE_SCALING_FACTOR:1166069e-12,TRADING_FEE_FACTOR:.001,GAS_FEE:"1",DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY:1e7};function gn(e){return e.trim().toLowerCase()}function mn(e){return e.trim().toUpperCase()}function fn(e){return e.trim().toUpperCase()}var pn;!function(e){e.DEBUG="DEBUG",e.INFO="INFO",e.WARN="WARN",e.ERROR="ERROR"}(pn||(pn={}));class En{constructor(e){this.levelPriority={[pn.DEBUG]:0,[pn.INFO]:1,[pn.WARN]:2,[pn.ERROR]:3},this.debugEnabled=e.debug,this.context=e.context??"SDK",this.minLevel=e.minLevel??(e.debug?pn.DEBUG:pn.INFO)}debug(e,t){this.log(pn.DEBUG,e,t)}info(e,t){this.log(pn.INFO,e,t)}warn(e,t){this.log(pn.WARN,e,t)}error(e,t){this.log(pn.ERROR,e,t)}log(e,t,n){if(this.levelPriority[e]<this.levelPriority[this.minLevel])return;if(e===pn.DEBUG&&!this.debugEnabled)return;const r=`[${(new Date).toISOString()}] [${this.context}] [${e}]`,s=this.getConsoleMethod(e);void 0!==n?Lt(n)?s(`${r} ${t}`,n.message,Ft(n)??""):s(`${r} ${t}`,n):s(`${r} ${t}`)}getConsoleMethod(e){switch(e){case pn.DEBUG:return console.debug;case pn.INFO:return console.info;case pn.WARN:return console.warn;case pn.ERROR:return console.error;default:return console.log}}child(e){return new En({debug:this.debugEnabled,context:`${this.context}:${e}`,minLevel:this.minLevel})}isDebugEnabled(){return this.debugEnabled&&this.levelPriority[pn.DEBUG]>=this.levelPriority[this.minLevel]}}function An(e){return"string"==typeof e&&e.trim().length>0}function vn(e){return null==e||""===e}function Tn(e){return null==e}const yn=new En({debug:!1,context:"DateUtils"});function Sn(e,t){if(null==e)return new Date;if(e instanceof Date)return isNaN(e.getTime())?new Date:e;try{const t=new Date(e);return isNaN(t.getTime())?(yn.warn(`Invalid date string received: "${e}". Using fallback.`),new Date):t}catch(t){return yn.warn(`Date parsing error for "${e}":`,t),new Date}}function bn(e){if(null==e)return!1;if(e instanceof Date)return!isNaN(e.getTime());if("string"!=typeof e)return!1;const t=new Date(e);return!isNaN(t.getTime())}function Nn(n,r){if("string"==typeof n&&/^eth\|0[xX]/u.test(n))try{e(n,r)}catch(e){if(t(e)&&"INVALID_ETH_USER_REF_PREFIX"===e.code)return e.message}}function wn(t,n="address"){const r=Nn(t,n);if(void 0!==r)throw new kt(r,n,"INVALID_FORMAT");try{return e(t,n)}catch{throw new kt(`${n} must be a GalaChain user address: eth|<40 hex> (\`eth|0x...\` is not a valid form), 0x<40 hex>, <40 hex> or client|<id>, and a mixed-case Ethereum address must carry its EIP-55 checksum (got "${String(t)}")`,n,"INVALID_FORMAT")}}function kn(e,t="address"){return wn(e,t).toLowerCase()}function _n(e,t){return Bn(e)??kn(e,t)}function In(e){return Cn(e)?kn(e):e.trim().toLowerCase()}function Dn(e,t){const n=e=>Cn(e)?kn(e):e.toLowerCase();return n(e)===n(t)}function Cn(e){try{return wn(e),!0}catch{return!1}}class Rn{toBackendFormat(e){if(!An(e))throw new kt("Address is required and must be a string","address","REQUIRED");return wn(e,"address")}toEthereumFormat(e){if(!An(e))throw new kt("Backend address is required and must be a string","address","REQUIRED");if(!e.match(/^eth\|([0-9a-fA-F]{40})$/i)){const t=Nn(e,"address");if(void 0!==t)throw new kt(t,"address","INVALID_FORMAT");throw new kt(`Invalid backend address format. Expected "eth|{40-hex-characters}" (\`eth|0x...\` is not a valid form). Got: "${e}"`,"address","INVALID_FORMAT")}return`0x${e.substring(4)}`}normalizeInput(e){if(void 0!==e&&""!==e)return wn(e,"address")}normalizeForBackend(e){if(void 0!==e&&""!==e)return kn(e,"address")}isValid(e){return Cn(e)}assertValid(e,t="address"){if(!this.isValid(e)){const n=Nn(e,t);if(void 0!==n)throw new kt(n,t,"INVALID_FORMAT");throw new kt(`${t} must be a valid wallet address (eth|<40 hex>, 0x<40 hex>, <40 hex> or client|<id>; \`eth|0x...\` is not a valid form; a mixed-case address must carry its EIP-55 checksum)`,t,"INVALID_FORMAT")}}detectFormat(e){return An(e)&&Cn(e)?e.startsWith("client|")?"client":e.startsWith("eth|")?"backend":"ethereum":null}normalize(e){if(void 0!==e&&""!==e)return e.toLowerCase()}extractHex(e){const t=Cn(e)?wn(e):void 0;if(void 0!==t&&t.startsWith("eth|"))return t.substring(4).toLowerCase();throw new kt(`Cannot extract hex from address: "${e}". Expected Ethereum or backend format.`,"address","INVALID_FORMAT")}}const On=new Rn;function Mn(e){return On.toBackendFormat(e)}function Ln(e){return On.toEthereumFormat(e)}function Un(e){return On.normalizeInput(e)}function Fn(e){return On.isValid(e)}const Pn=/^(eth\|[a-f0-9]{40}|client\|[a-f0-9]{24})$/;function xn(e){return void 0!==Bn(e)}function Bn(e){if(!An(e))return;const t=e.trim(),n=/^[0-9a-fA-F]{24}$/u.test(t)?`client|${t}`:t;if(!Cn(n))return;const r=kn(n);return Pn.test(r)?r:void 0}function Gn(e,t){if(!xn(e)){const n=Nn(e,t);if(void 0!==n)throw new kt(n,t,"INVALID_FORMAT");throw new kt(`${t} must be a GalaChain user address (eth|<40 hex> (\`eth|0x...\` is not a valid form), 0x<40 hex>, <40 hex> or client|<24 hex>)`,t,"INVALID_FORMAT")}}function $n(e,t="address"){On.assertValid(e,t)}function Kn(e){const t="string"==typeof e?e:e.address;return On.toBackendFormat(t)}var Hn=Object.freeze({__proto__:null,AddressFormatter:Rn,assertBackendUserAddress:Gn,assertValidWalletAddress:$n,backendUserAddress:Bn,backendUserParam:_n,backendUserRef:kn,ethZeroXRefusal:Nn,fromBackendAddressFormat:Ln,isBackendUserAddress:xn,isUserRef:Cn,isValidAddress:Fn,normalizeAddressInput:Un,sameUserAddress:Dn,toBackendAddressFormat:Mn,toBackendAddressFromEthers:Kn,userAddressFilter:In,userRef:wn});function Wn(e,t=0){if(vn(e))return t;if("number"==typeof e)return isNaN(e)||!isFinite(e)?t:e;const n=parseFloat(e);return isNaN(n)||!isFinite(n)?t:n}function Vn(e,t,n){if(Tn(e))return t;if("bigint"==typeof e)try{return Number(e)}catch{return t}if("number"==typeof e)return isNaN(e)?t:Math.floor(e);const r=parseInt(String(e),10);return isNaN(r)?t:r}function jn(e,t=0){if(Tn(e))return t;if("number"==typeof e)return isNaN(e)?t:e;return Wn(String(e).replace("%","").trim(),t)}function qn(e,t=18){const n=Wn(e,0);if(0===n)return"0";return n.toFixed(t).replace(/\.?0+$/,"")}function zn(e){return qn(e,8)}function Xn(e){return qn(e,18)}function Qn(e,t,n,r){if("number"!=typeof e)throw Yt(r,"a number",e,r);if(e<t||e>n)throw zt(r,t,n,e)}function Yn(e,t,n){if("string"!=typeof e)throw Yt(n,"a string",e,n);if(e.length>t)throw Qt(n,t,e.length)}function Jn(e,t){if("number"!=typeof e)throw Yt(t,"a number",e,t);if(!Number.isInteger(e))throw Yt(t,"an integer",e,t);if(e<=0)throw Xt(t,1,e,t)}function Zn(e,t,n=!1){if("string"!=typeof e)throw Yt(t,"a string",e,t);if(!n&&0===e.trim().length)throw Ht(t,`${t} (non-empty string)`)}function er(e,t){if("ASC"!==e&&"DESC"!==e)throw new kt(`${t} must be either 'ASC' or 'DESC'`,t,"INVALID_ENUM_VALUE")}function tr(e,t,n,r){const s="string"==typeof e?parseFloat(e):e;if(!isFinite(s))throw new kt(`${r} must be a valid finite number between ${t} and ${n}`,r,"INVALID_NUMBER");if(s<t||s>n)throw zt(r,t,n,s,r)}function nr(e,t,n){const r="string"==typeof e?parseFloat(e):e,s="string"==typeof t?parseFloat(t):t;if(!isFinite(r))throw new kt(`${n} minFee must be a valid finite number`,n,"INVALID_FEE_MINIMUM");if(!isFinite(s))throw new kt(`${n} maxFee must be a valid finite number`,n,"INVALID_FEE_MAXIMUM");if(r<.1)throw new kt(`${n} minFee must be >= 0.1, received ${r}`,n,"INVALID_FEE_MINIMUM");if(s>.5)throw new kt(`${n} maxFee must be <= 0.5, received ${s}`,n,"INVALID_FEE_MAXIMUM");if(r>s)throw new kt(`${n} minFee (${r}) must be <= maxFee (${s})`,n,"INVALID_FEE_RANGE")}function rr(e,t,n,r){const s="string"==typeof e?parseFloat(e):e,i="string"==typeof t?parseFloat(t):t;if(!isFinite(s))throw new kt(`${n} must be a valid finite number`,n,"INVALID_MIN_VALUE");if(!isFinite(i))throw new kt(`${r} must be a valid finite number`,r,"INVALID_MAX_VALUE");if(s>i)throw new kt(`${n} (${s}) must be less than or equal to ${r} (${i})`,n,"INVALID_RANGE")}function sr(e,t,n){if(!t.includes(e))throw new kt(`${n} must be one of [${t.map(e=>String(e)).join(", ")}], received "${e}"`,n,"INVALID_ENUM_VALUE")}const ir={ETH_ADDRESS:/^0x[0-9a-fA-F]{40}$/,BACKEND_ADDRESS:/^eth\|[0-9a-fA-F]{40}$/},or=An,ar=vn,cr=Tn;function lr(e,t,n=100,r,s){if(void 0!==s&&"string"!=typeof s)throw new kt("cursor must be a string","cursor",wt.INVALID_TYPE);const i=r??t,o=void 0!==r?"pageSize":"limit";if(void 0!==i&&(Jn(i,o),i>n))throw new kt(`${o} must be at most ${n}`,o,wt.TOO_LARGE)}function dr(e){const t=Object.values(e);return e=>"string"==typeof e&&t.includes(e)}function ur(e){return Object.values(e)}function hr(e,t,n){if(!or(e))throw Ht(t);const r=e.trim();if(0===r.length)throw Ht(t);if(r.length<n.MIN_LENGTH)throw zt(t,n.MIN_LENGTH,n.MAX_LENGTH,r.length,`${t} length`);if(r.length>n.MAX_LENGTH)throw zt(t,n.MIN_LENGTH,n.MAX_LENGTH,r.length,`${t} length`);if(!n.PATTERN.test(r))throw new kt(`${t} must be ${n.DESCRIPTION}`,t,wt.INVALID_FORMAT)}function gr(e,t,n){if(null==e)return;if("string"!=typeof e)throw Yt(t,"a string",e);const r=e.trim();if(0!==r.length&&!n.PATTERN.test(r))throw new kt(`${t} must be ${n.DESCRIPTION}`,t,wt.INVALID_FORMAT)}function mr(e,t){if("string"!=typeof e)return!1;const n=e.trim();return 0!==n.length&&t.PATTERN.test(n)}function fr(e,t,n){if(null==e)throw Ht(t,t);if("string"!=typeof e)throw Yt(t,"a string",e);const r=e.trim();if(0===r.length)throw Ht(t,t);if(!n.PATTERN.test(r))throw new kt(`${t} must be ${n.DESCRIPTION}`,t,wt.INVALID_FORMAT)}function pr(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 Er={requiredString:e=>t=>cr(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(!ar(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(!cr(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=>cr(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(!cr(n))return t.includes(n)?void 0:`${e} must be one of: ${t.join(", ")}`},requiredEnumValue:(e,t)=>n=>cr(n)?`${e} is required`:t.includes(n)?void 0:`${e} must be one of: ${t.join(", ")}`,isoDate:e=>t=>{if(!cr(t))return"string"!=typeof t?`${e} must be a string`:bn(t)?void 0:`${e} must be a valid ISO 8601 date string`},walletAddress:(e,t=!1)=>n=>cr(n)?t?`${e} is required`:void 0:"string"!=typeof n?`${e} must be a string`:Cn(n)?void 0:Nn(n,e)??`${e} must be a valid wallet address`};function Ar(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(cr(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(!cr(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 vr(e){return""===e||0===e.trim().length}function Tr(e,t,n){if(!cr(e)){if("string"!=typeof e)throw Yt(t,"a string",e,t);if(e.length>n)throw new kt(`${t} must be at most ${n} characters`,t,wt.TOO_LARGE)}}function yr(e,t){cr(e)||function(e,t){const n=e instanceof Date?e:"string"==typeof e||"number"==typeof e?new Date(e):void 0;if(void 0===n)throw Yt(t,"a date",e,t);if(isNaN(n.getTime()))throw new kt(`${t} must be a valid date`,t,wt.INVALID_FORMAT)}(e,t)}function Sr(e,t,n){try{Jn(e,t)}catch{throw function(e,t,n,r="OPERATION_FAILED"){return new kt(`${e} failed: ${t}`,n,r)}(n,"must be a positive integer",t)}}function br(e,t,n="status"){void 0!==e&&function(e,t,n){const r=Object.values(t);if(!r.includes(e))throw new kt(`${n} must be one of: ${r.join(", ")}`,n,wt.INVALID_FORMAT)}(e,t,n)}class Nr{constructor(e,t=!1,n){this.http=e,this.logger=new En({debug:t,context:this.constructor.name}),this.jwtAuth=n}setJwtAuth(e){this.jwtAuth=e}getJwtHeaders(){if(!this.jwtAuth){const e=globalThis;if("test"===e.process?.env?.NODE_ENV&&!this.isCalledFromUserCode())return{};throw new Ot("JWT authentication required. Call sdk.login() first.")}return this.jwtAuth.getJwtHeaders()}isCalledFromUserCode(){const e=Ft(new Error)??"";return!(!e.includes("expect")&&!e.includes("jest"))||!(!e.includes("tests/")&&!e.includes(".test.ts"))}validatePositiveInteger(e,t,n){Sr(e,t,n)}}class wr{constructor(e=!1,t){this.logger=t||new En({debug:e,context:this.constructor.name})}}class kr extends wr{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 _r extends kr{constructor(e=!1){super(e)}normalizeKey(e){return gn(e).replace(/\s+/g," ").replace(/[\u0000-\u001F\u007F-\u009F\u200B-\u200D\uFEFF]/g,"")}getLRUKey(){return this.cache.keys().next().value??null}updateCacheEntry(e,t){const n=this.cache.get(e);if(this.cache.has(e)&&this.cache.delete(e),this.cache.size>=_r.MAX_CACHE_SIZE){const e=this.getLRUKey();null!==e&&this.cache.delete(e)}this.cache.set(e,{...n??{},...t,lastUpdated:Date.now()})}warmFromPoolData(e,t){const n=this.normalizeKey(e);this.updateCacheEntry(n,t)}set(e,t){const n=this.normalizeKey(e);this.updateCacheEntry(n,t)}getByName(e){const t=this.normalizeKey(e);return this.cache.get(t)}getMaxSupply(e){const t=this.normalizeKey(e),n=this.cache.get(t);return n?.maxSupply??hn.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY.toString()}has(e){const t=this.normalizeKey(e);return this.cache.has(t)}clear(e){if(void 0!==e&&""!==e){const t=this.normalizeKey(e);this.cache.delete(t)}else super.clear()}dumpAsObject(){const e={};return this.cache.forEach((t,n)=>{e[n]=t}),e}getStats(){const e=this.buildBaseStats(),{cacheSize:t,oldestEntry:n}=this.calculateCacheSizeAndAge();return{...e,totalTokens:e.totalItems,cacheSize:t,oldestEntry:n}}calculateCacheSizeAndAge(){let e=Date.now(),t=0;return this.cache.forEach((n,r)=>{n.lastUpdated<e&&(e=n.lastUpdated);let s=0;s+=2*r.length,void 0!==n.reverseBondingCurveMinFeeFactor&&(s+=8),void 0!==n.reverseBondingCurveMaxFeeFactor&&(s+=8),void 0!==n.reverseBondingCurveNetFeeFactor&&(s+=8),s+=8,void 0!==n.vaultAddress&&""!==n.vaultAddress&&(s+=2*n.vaultAddress.length),void 0!==n.maxSupply&&""!==n.maxSupply&&(s+=2*n.maxSupply.length),void 0!==n.symbol&&""!==n.symbol&&(s+=2*n.symbol.length),s+=32,t+=s}),{cacheSize:t,oldestEntry:this.cache.size>0?e:0}}getByTokenId(e){const t=`token:${gn(e)}`;return this.cache.get(t)??null}setByTokenId(e,t){const n=`token:${gn(e)}`;this.updateCacheEntry(n,t)}hasByTokenId(e){const t=`token:${gn(e)}`;return this.cache.has(t)}}_r.MAX_CACHE_SIZE=1e4;const Ir={MIN_LENGTH:1,MAX_LENGTH:25,PATTERN:/^[a-zA-Z0-9]{1,25}$/,DESCRIPTION:"1-25 letters and digits"},Dr={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"},Rr={MIN_LENGTH:1,MAX_LENGTH:50,PATTERN:/^[\s\S]{1,50}$/,DESCRIPTION:"1-50 characters"},Or={MIN_LENGTH:1,MAX_LENGTH:100,PATTERN:/^(?![\s\S]*<[^>]*>)[\s\S]{1,100}$/,DESCRIPTION:"1-100 characters without HTML"},Mr=100,Lr=100,Ur=50,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}},xr={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})$/}},Br=60,Gr=31536e3,$r={MAX_LENGTH:64,PATTERN:/^(galaswap-operation-|galaconnect-operation-)/},Kr={PATTERN:/^[a-fA-F0-9]{64}$/,MAX_LENGTH:64},Hr=1,Wr=100,Vr={FULL_NAME:{MIN_LENGTH:2,MAX_LENGTH:20,ALPHABETS_ONLY_PATTERN:/^[a-zA-Z]+(?: [a-zA-Z]+)?$/}},jr=y.string({message:"Token name is required"}).min(1,"Token name must be at least 1 character").regex(/^[a-zA-Z0-9]+$/,"Token name can only contain letters and numbers"),qr=jr.max(25,"Token name must be at most 25 characters"),zr=y.string({message:"Token name is required"}).min(1,"Token name must be at least 1 character").max(50,"Token name must be at most 50 characters"),Xr=y.string({message:"Token symbol is required"}).min(1,"Token symbol must be at least 1 character").max(8,"Token symbol must be at most 8 characters").regex(/^[A-Z]{1,8}$/,"Token symbol must be uppercase letters only"),Qr=y.string({message:"Token description is required"}).min(1,"Token description is required").max(500,"Token description must be at most 500 characters"),Yr=y.string().min(1,"Token name must be at least 1 character").max(50,"Token name must be at most 50 characters"),Jr=y.string().min(1,"Search query must be at least 1 character").max(100,"Search query must be at most 100 characters"),Zr=y.string().min(1,"Full name is required").max(100,"Full name must be at most 100 characters").regex(/^[a-zA-Z\s]+$/,"Full name can only contain letters and spaces"),es=y.string().regex(ir.BACKEND_ADDRESS,"Address must be in format: eth|[40-hex-chars]"),ts=y.string().regex(ir.ETH_ADDRESS,"Invalid Ethereum address format"),ns=y.string().refine(e=>Cn(e),{error:e=>Nn(e.input,"address")??"Address must be eth|[40-hex], 0x[40-hex], [40-hex] or client|[identifier] (a mixed-case address must carry its EIP-55 checksum)"}).transform(e=>wn(e)),rs=y.string().refine(e=>/^eth\|[0-9a-fA-F]{40}$/.test(e)||/^service\|Token\$Unit\$[A-Z0-9]+\$eth:[0-9a-fA-F]{40}\$launchpad$/.test(e),"Invalid vault address format"),ss=y.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>Wn(e,0)>0,"Amount must be greater than zero"),is=y.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>Wn(e,0)>=0,"Amount must be zero or greater"),os=y.string().url("Must be a valid URL").regex(/^https?:\/\//,"URL must start with http:// or https://"),as=y.string().optional().refine(e=>void 0===e||""===e||/^https?:\/\/.+\..+/.test(e),"Must be a valid URL if provided"),cs=y.number().int("Page must be an integer").min(1,"Page must be at least 1").max(1e3,"Page must be at most 1000").default(1);function ls(e=100){return y.number().int("Limit must be an integer").min(1,"Limit must be at least 1").max(e,`Limit must be at most ${e}`).default(10)}const ds=ls(100),us=ls(20),hs=ls(20),gs=y.number().int("File size must be an integer").min(1,"File must be at least 1 byte").max(10485760,"File must be at most 10MB"),ms=y.string().max(255,"Filename must be at most 255 characters"),fs=y.enum(["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"]),ps=y.string().datetime("Must be a valid ISO 8601 date string"),Es=y.number().int("Timestamp must be an integer").min(0,"Timestamp must be non-negative"),As=y.string().regex(/^0x[a-fA-F0-9]{64}$/,"Private key must be format: 0x + 64 hex characters"),vs=y.string().regex(/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/,"Transaction ID must be in UUID format"),Ts=y.string().regex(/^galaconnect-operation-[a-z0-9-]+$/,"Unique key must be format: galaconnect-operation-{unique-id}"),ys=[".png",".jpg",".jpeg",".gif",".webp",".svg"],Ss=y.object({file:y.union([y.instanceof(File),y.instanceof(Buffer)]),name:ms,size:gs,type:fs}),bs=y.instanceof(File).refine(e=>e.size>=1&&e.size<=10485760,"File size must be between 1 byte and 10MB").refine(e=>["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"].includes(e.type),"File must be a valid image type (PNG, JPG, JPEG, GIF, WebP, or SVG)").refine(e=>e.name.length<=255,"Filename must be at most 255 characters"),Ns=y.instanceof(Buffer).refine(e=>e.length>=1&&e.length<=10485760,"Buffer size must be between 1 byte and 10MB"),ws=y.union([bs,Ns]),ks=y.enum([".png",".jpg",".jpeg",".gif",".webp",".svg"]),_s=ms.refine(e=>{const t=e.slice(e.lastIndexOf(".")).toLowerCase();return ys.includes(t)},`Filename must end with one of: ${ys.join(", ")}`),Is=y.object({websiteUrl:as,telegramUrl:as,twitterUrl:as,instagramUrl:as,facebookUrl:as,redditUrl:as,tiktokUrl:as}).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"),Ds=y.string().min(1,"Token category must not be empty").default("Unit"),Cs=y.string().min(1,"Token collection must not be empty").default("Token"),Rs=y.object({minFeePortion:y.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal string").refine(e=>Wn(e,0)>=.1,"Minimum fee must be >= 0.1").refine(e=>Wn(e,0)<=.5,"Minimum fee must be <= 0.5").default("0.1"),maxFeePortion:y.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal string").refine(e=>Wn(e,0)>=.1,"Maximum fee must be >= 0.1").refine(e=>Wn(e,0)<=.5,"Maximum fee must be <= 0.5").default("0.5")}).refine(e=>Wn(e.maxFeePortion,0)>=Wn(e.minFeePortion,0),{message:"Maximum fee must be >= minimum fee",path:["maxFeePortion"]}),Os=y.object({tokenName:jr,tokenSymbol:Xr,tokenDescription:Qr,tokenImage:y.union([y.instanceof(File),y.instanceof(Buffer),y.string().url("Token image must be a valid URL")]).optional(),preBuyQuantity:is.default("0"),websiteUrl:as,telegramUrl:as,twitterUrl:as,instagramUrl:as,facebookUrl:as,redditUrl:as,tiktokUrl:as,tokenCategory:Ds,tokenCollection:Cs,reverseBondingCurveConfiguration:Rs.optional(),saleStartTime:y.number().int().positive().optional(),privateKey:As.optional()}),Ms=y.object({file:y.union([y.instanceof(File),y.instanceof(Buffer)]),tokenName:jr}),Ls=y.enum(yt),Us=y.object({tokenName:zr.optional(),symbol:Xr.optional()}).refine(e=>void 0!==e.tokenName||void 0!==e.symbol,"At least one of tokenName or symbol is required"),Fs=y.enum(["NATIVE","MEME"]),Ps=y.enum(["IN","OUT"]),xs=y.object({from:y.number().int("From timestamp must be an integer").min(173e6,"From timestamp must be at least 173000000"),to:y.number().int("To timestamp must be an integer").min(173e6,"To timestamp must be at least 173000000"),resolution:y.number().int("Resolution must be an integer").min(1,"Resolution must be at least 1"),tokenName:qr}),Bs=y.object({tokenName:qr,slippageToleranceFactor:y.number().min(0).max(1).optional(),maxAcceptableReverseBondingCurveFeeSlippageFactor:y.number().min(0).max(1).optional(),privateKey:As.optional()}),Gs=y.object({offset:y.number().int().min(0).default(0),pageSize:y.number().int().min(1).max(100).default(10)}),$s=y.object({offset:y.number().int().min(0).default(0),pageSize:y.number().int().min(1).max(20).default(10)}),Ks=y.object({offset:y.number().int().min(0).default(0),pageSize:y.number().int().min(1).max(20).default(10)}),Hs=Gs.extend({type:y.enum(["RECENT","POPULAR"]).optional(),tokenName:y.string().min(1).max(50).optional(),search:y.string().min(1).max(100).optional()}),Ws=$s.extend({tokenName:y.string().min(1).max(50).optional(),search:y.string().min(1).max(100).optional()}),Vs=Ks.extend({tradeType:y.enum(["BUY","SELL"]).optional(),tokenName:y.string().min(1).max(50).optional(),userAddress:y.string().refine(Cn,{error:e=>Nn(e.input,"userAddress")??"userAddress must be eth|<40 hex>, 0x<40 hex>, <40 hex> or client|<id> (a mixed-case address must carry its EIP-55 checksum)"}).optional(),startDate:y.string().datetime().optional(),endDate:y.string().datetime().optional(),sortOrder:y.enum(["ASC","DESC"]).default("DESC")}),js={page:y.number().int().min(1),limit:y.number().int().min(1),total:y.number().int().min(0),totalPages:y.number().int().min(0),hasNext:y.boolean(),hasPrevious:y.boolean()},qs=y.object(js);function zs(e){return y.object({data:y.array(e),...js})}const Xs=y.enum(["buy","sell"]),Qs=y.enum(["BUY","SELL"]),Ys=y.object({tradeType:Xs,tokenAmount:ss,vaultAddress:rs,userAddress:ns,slippageTolerance:ss.optional(),deadline:y.number().int().positive().optional()}),Js=y.object({tokenSymbol:Xr,nativeTokenQuantity:ss,expectedToken:ss,maxAcceptableReverseBondingCurveFee:is.default("0").optional()}),Zs=y.object({tokenSymbol:Xr,tokenQuantity:ss,expectedNativeToken:ss,maxAcceptableReverseBondingCurveFee:is.default("0").optional()}),ei=Ks.extend({tokenName:Yr.optional()}),ti=y.object({page:y.number().int().min(1).max(1e3).default(1).optional(),limit:y.number().int().min(1).max(20).default(10).optional()}),ni=y.enum(["NATIVE","MEME"]),ri=y.enum(["IN","OUT"]),si=y.object({type:ni,method:ri,vaultAddress:rs,amount:ss}),ii=y.object({nativeTokenQuantity:ss}),oi=y.object({vaultAddress:rs}),ai=y.object({minFeePortion:ss,maxFeePortion:ss}),ci=y.enum(["both","held","created"]),li=$s.extend({type:ci.optional(),address:ns.optional(),search:Jr.optional(),tokenName:Yr.optional()}),di=y.object({address:ns.optional(),refresh:y.boolean().optional()}),ui=y.object({profileImage:y.string().nullable().optional(),fullName:Zr.optional(),address:ns.optional(),privateKey:As.optional()}),hi=y.object({file:y.union([y.instanceof(File),y.instanceof(Buffer)]),address:ns.optional(),privateKey:As.optional()}),gi=y.object({address:ns,tokenId:y.union([y.string(),y.object({collection:y.string(),category:y.string(),type:y.string(),additionalKey:y.string()}),y.object({collection:y.string(),category:y.string(),type:y.string(),additionalKey:y.string(),instance:y.string()})]).optional(),tokenName:Yr.optional(),withExpired:y.boolean().optional()}).refine(e=>void 0!==e.tokenId||void 0!==e.tokenName,"At least one token identifier (tokenId or tokenName) is required");function mi(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 fi=mi(jr),pi=mi(Xr),Ei=mi(Qr),Ai=mi(ns),vi=mi(rs),Ti=mi(ss),yi=mi(Zr),Si=mi(Jr),bi=mi(Yr),Ni=mi(Os),wi=mi(Is),ki=mi(Ms),_i=mi(Us),Ii=mi(li),Di=mi(di),Ci=mi(ui),Ri=mi(hi),Oi=mi(gi),Mi=mi(Ys),Li=mi(Js),Ui=mi(Zs),Fi=mi(ei),Pi=mi(ti),xi=mi(si),Bi=mi(ii),Gi=mi(oi);function $i(e){return Ni(e).success}function Ki(e){const t=Ni(e);return t.success?[]:t.errors??["Unknown validation error"]}function Hi(e){const t=Ki(e);if(t.length>0)throw new Error(`LaunchTokenData validation failed:\n${t.map(e=>`- ${e}`).join("\n")}`)}function Wi(e,t){return"string"==typeof e[t]}function Vi(e,t){return void 0===e[t]||"string"==typeof e[t]}function ji(e,t){return void 0===e[t]||"number"==typeof e[t]}function qi(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 zi(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(!qi(n[t],r))return!1}return!0}}dr({BUY:"buy",SELL:"sell"});const Xi=zi({nativeTokenQuantity:"string"});function Qi(e,t="0"){return function(e,t="0"){if(vn(e))return new I(t);if(I.isBigNumber(e))return e.isNaN()?new I(t):e;try{const n=new I(e);return n.isNaN()||!n.isFinite()?new I(t):n}catch{return new I(t)}}(e,t)}function Yi(e,t){return void 0!==t?Qi(e).toFixed(t):Qi(e).toFixed()}function Ji(e){const t=Qi(e),n=Math.log(1.0001),r=t.toNumber();return Math.log(r)/n}function Zi(e){return Qi(e).isZero()}function eo(e,t){return Qi(e).isLessThan(Qi(t))}function to(...e){e.forEach(e=>{if(e.isNaN())throw Jt("value","NaN");if(!e.isFinite())throw Qt("value","finite");if(e.isLessThanOrEqualTo(0))throw Xt("value","0",e.toString())})}function no(...e){e.forEach(e=>{if(e.isNaN())throw Jt("value","NaN");if(!e.isFinite())throw Qt("value","finite");if(e.isLessThan(0))throw Xt("value","0",e.toString())})}function ro(e,t,n){if(e.isNaN())throw Jt(t,"NaN");if(!e.isFinite())throw Qt(t,"finite");if(e.isLessThanOrEqualTo(0))throw Xt(t,"0",e.toString())}function so(e,t,n="0"){const r=Qi(t);return Zi(r)?Qi(n):Qi(e).dividedBy(r)}const io={calculateBuyWithExact(e,t){const n=Wn(e),r=Wn(t),{BASE_PRICE:s,PRICE_SCALING_FACTOR:i,TRADING_FEE_FACTOR:o,GAS_FEE:a}=hn,c=function(e,t){const n=Math.pow(10,t);return Math.ceil(e*n)/n}(s*(Math.exp((r+n)*i)-Math.exp(r*i))/i,8),l=Yi(Qi(c).multipliedBy(o));return{amount:c.toString(),reverseBondingCurveFee:"0",transactionFee:l,gasFee:a}},calculateBuyWithNative(e,t){const n=Wn(e),r=Wn(t),{BASE_PRICE:s,PRICE_SCALING_FACTOR:i,TRADING_FEE_FACTOR:o,GAS_FEE:a}=hn,c=Math.log(n*i/s+Math.exp(r*i))/i-r,l=Yi(Qi(c).multipliedBy(o));return{amount:c.toString(),reverseBondingCurveFee:"0",transactionFee:l,gasFee:a}},calculateSellWithExact(e,t,n,r,s){const i=Wn(e),o=Wn(t),a=Wn(n),{BASE_PRICE:c,PRICE_SCALING_FACTOR:l,TRADING_FEE_FACTOR:d,GAS_FEE:u}=hn,h=c*(Math.exp(o*l)-Math.exp((o-i)*l))/l,g=Qi(h),m=r+o/a*(s-r),f=Yi(g.multipliedBy(m),8),p=Yi(g.multipliedBy(d));return{amount:h.toString(),reverseBondingCurveFee:f,transactionFee:p,gasFee:u}},calculateSellWithNative(e,t,n,r,s){const i=Wn(e),o=Wn(t),a=Wn(n),{BASE_PRICE:c,PRICE_SCALING_FACTOR:l,TRADING_FEE_FACTOR:d,GAS_FEE:u}=hn;if(i>=c*(Math.exp(o*l)-1)/l){const e=Qi(i),t=r+o/a*(s-r),n=Yi(e.multipliedBy(t),8),c=Yi(e.multipliedBy(d));return{amount:o.toString(),reverseBondingCurveFee:n,transactionFee:c,gasFee:u}}const h=o-Math.log(Math.exp(o*l)-i*l/c)/l,g=Qi(i),m=r+o/a*(s-r),f=Yi(g.multipliedBy(m),8),p=Yi(g.multipliedBy(d));return{amount:h.toString(),reverseBondingCurveFee:f,transactionFee:p,gasFee:u}}};function oo(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function ao(e,t){if(!function(e){if(!oo(e)||"string"!=typeof e.calculatedQuantity)return!1;const t=e.extraFees;return oo(t)&&"string"==typeof t.reverseBondingCurve&&"string"==typeof t.transactionFees}(e))throw Vt(`Malformed trade quote from the launchpad backend (${t})`);return{amount:e.calculatedQuantity,reverseBondingCurveFee:e.extraFees.reverseBondingCurve,transactionFee:e.extraFees.transactionFees,gasFee:hn.GAS_FEE}}class co{validate(e,t={}){const{allowZero:n=!0,minimum:r,maximum:s,maxDecimals:i=co.MAX_DECIMAL_PLACES,fieldName:o="amount"}=t;if(!or(e))throw new kt(`${o} cannot be empty or whitespace-only. Provide a valid numeric string.`,o,"INVALID_NUMERIC_STRING");if(/[eE]/.test(e))throw new kt(`${o} cannot use scientific notation. Use standard decimal format (e.g., "1000" instead of "1e3").`,o,"INVALID_NUMERIC_STRING");const a=Wn(e,NaN);if(isNaN(a))throw new kt(`${o} must be a valid numeric string. Received: "${e}"`,o,"INVALID_NUMERIC_STRING");if(!isFinite(a))throw new kt(`${o} must be a finite number. Cannot be Infinity or -Infinity.`,o,"INVALID_NUMERIC_STRING");if(a<0)throw new kt(`${o} must be non-negative. Received: "${e}"`,o,"INVALID_NUMERIC_STRING");if(!n&&0===a)throw new kt(`${o} must be greater than zero. Received: "${e}"`,o,"INVALID_NUMERIC_STRING");const c=Qi(e),l=c.decimalPlaces()??0;if(l>i)throw new kt(`${o} cannot exceed ${i} decimal places. Received: ${l} decimal places`,o,"PRECISION_EXCEEDED");if(void 0!==r&&eo(c,r))throw new kt(`${o} must be at least ${r}. Received: "${e}"`,o,"BELOW_MINIMUM");if(void 0!==s&&(d=s,Qi(c).isGreaterThan(Qi(d))))throw new kt(`${o} cannot exceed ${s}. Received: "${e}"`,o,"EXCEEDS_MAXIMUM");var d}parseAmount(e,t="0"){return Qi(e,t)}isValid(e,t={}){try{return null==e||""===e?!1!==t.allowZero:(this.validate(e,t),!0)}catch{return!1}}formatAmount(e,t){return Yi(e,t)}clampAmount(e,t,n){const r=Qi(e),s=Qi(t),i=Qi(n);return function(e,t,n){const r=Qi(e),s=Qi(t),i=Qi(n);return r.isGreaterThanOrEqualTo(s)&&r.isLessThanOrEqualTo(i)}(r,s,i)?Yi(r):eo(r,s)?Yi(s):Yi(i)}}function lo(e,t){throw new kt(e.join("; "),t,"VALIDATION_ERROR")}function uo(e){const t=fi(e);!t.success&&t.errors&&lo(t.errors,"tokenName")}function ho(e){const t=xs.safeParse(e);var n;t.success||lo((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 go(e,t,n=!0){mo.validate(e,{fieldName:t,allowZero:n})}co.MAX_DECIMAL_PLACES=18,co.MIN_POSITIVE="0.00000000000000001";const mo=new co;class fo{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 _r}createSale(e){if(void 0===this.launchpadWrites)throw new Error("Launchpad write transport is not configured.");return this.launchpadWrites.createSale(e)}addIfDefined(e,t,n){return void 0!==n&&(e[t]=n),e}async calculateBuyAmount(e){if(null==e||"object"!=typeof e)throw Wt("options","an options object");const{tokenName:t,amount:n,type:r,currentSupply:s}=e;return"external"===this.validateAmountCalculationInputs(t,n,r,e.mode,[vt.NATIVE,vt.EXACT],'"native" or "exact"')?this.calculateBuyAmountExternal({tokenName:t,amount:n,type:r}):this.calculateBuyAmountLocal(this.addIfDefined({tokenName:t,amount:n,type:r},"currentSupply",s))}async calculateBuyAmountExternal(e){const{tokenName:t,amount:n,type:r}=e;return this.validateExternalAmountInputs(t,n),"exact"===r?this.fetchBackendQuote({tokenName:t,amount:n,type:"MEME",method:"OUT"},`Failed to calculate buy amount for ${t} (exact tokens)`):this.fetchBackendQuote({tokenName:t,amount:n,type:"NATIVE",method:"IN"},`Failed to calculate buy amount for ${t} (native/GALA budget)`)}async fetchBackendQuote(e,t){return ao(await cn(()=>this.http.get(ut,{...e}),{errorContext:t}),t)}async calculateSellAmount(e){const{tokenName:t,amount:n,type:r,currentSupply:s,maxSupply:i,reverseBondingCurveMaxFeeFactor:o,reverseBondingCurveMinFeeFactor:a}=e;if("external"===this.validateAmountCalculationInputs(t,n,r,e.mode,[vt.EXACT,vt.NATIVE],'"exact" or "native"'))return this.calculateSellAmountExternal({tokenName:t,amount:n,type:r});{const e={tokenName:t,amount:n,type:r,...void 0!==s&&{currentSupply:s},...void 0!==i&&{maxSupply:i},...void 0!==o&&{reverseBondingCurveMaxFeeFactor:o},...void 0!==a&&{reverseBondingCurveMinFeeFactor:a}};return this.calculateSellAmountLocal(e)}}async calculateSellAmountExternal(e){const{tokenName:t,amount:n,type:r}=e;return this.validateExternalAmountInputs(t,n),"exact"===r?this.fetchBackendQuote({tokenName:t,amount:n,type:"MEME",method:"IN"},`Failed to calculate sell amount for ${t} (exact tokens)`):this.fetchBackendQuote({tokenName:t,amount:n,type:"NATIVE",method:"OUT"},`Failed to calculate sell amount for ${t} (native/GALA target)`)}async calculateBuyAmountLocal(e){const{tokenName:t,amount:n,type:r,currentSupply:s}=e;if(!or(n))throw Ht("amount","Amount");if(r!==vt.NATIVE&&r!==vt.EXACT)throw Yt("type",'"native" or "exact"',r);void 0!==s&&go(s,"currentSupply");const i=null==s||""===s;if(i&&(null==t||""===t))throw Ht("tokenName","Token name (required when currentSupply is not provided)");null!=t&&""!==t&&uo(t);let o=s;if(i){o=(await this.fetchPoolDetailsForCalculation(t)).currentSupply}return r===vt.EXACT?io.calculateBuyWithExact(n,o):io.calculateBuyWithNative(n,o)}async calculateSellAmountLocal(e){const{tokenName:t,amount:n,type:r,currentSupply:s,maxSupply:i,reverseBondingCurveMaxFeeFactor:o,reverseBondingCurveMinFeeFactor:a}=e;if(!or(n))throw Ht("amount","Amount");if(r!==vt.EXACT&&r!==vt.NATIVE)throw Yt("type",'"exact" or "native"',r);void 0!==s&&go(s,"currentSupply");const c=null==s||""===s||null==i||""===i||void 0===o||void 0===a;if(c&&(null==t||""===t))throw Ht("tokenName","Token name (required when currentSupply, maxSupply, or fee factors are not provided)");null!=t&&""!==t&&uo(t);let l=s,d=i,u=o,h=a;if(c&&null!=t&&""!==t){const e=this.metadataCache.getByName(t);d=d??this.metadataCache.getMaxSupply(t),u=u??e?.reverseBondingCurveMaxFeeFactor,h=h??e?.reverseBondingCurveMinFeeFactor,null!=l&&""!==l||(l=await this.fetchCurrentSupply(t));if(void 0===u||void 0===h){const e=await this.fetchPoolDetailsForCalculation(t);u=u??e.reverseBondingCurveMaxFeeFactor,h=h??e.reverseBondingCurveMinFeeFactor}}return r===vt.EXACT?io.calculateSellWithExact(n,l,d,h,u):io.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 Wi(t,"tokenName")&&function(e){return void 0===e.calculateAmountMode||"local"===e.calculateAmountMode||"external"===e.calculateAmountMode}(t)&&Vi(t,"currentSupply")}(e))throw Yt("options","CalculateBuyAmountForGraduationOptions or string (token name)",typeof e);const{tokenName:n,calculateAmountMode:r,currentSupply:s}=t;uo(n);const i=await this.fetchSaleDetails(n),o=s??Yi(Qi(i.maxSupply).minus(i.sellingTokenQuantity)),a=i.sellingTokenQuantity;if("0"===a)throw Ht("tokenName",`Token ${n} is already graduated (no tokens remaining in pool)`);const c={tokenName:n,amount:a,type:"exact",currentSupply:o,...void 0!==r&&{mode:r}};return{...await this.calculateBuyAmount(c),remainingTokens:a}}async launchToken(e){if(void 0!==this.launchpadWrites){return(await this.launchpadWrites.createSale(e)).bundleId}if(!this.bundleHttp)throw jt("Bundle backend client not configured. LaunchToken requires bundleHttp client.","bundleHttp");Hi(e);const t=void 0!==e.preBuyQuantity&&""!==e.preBuyQuantity?e.preBuyQuantity:"0",n=Wn(t);if(0===n&&"0"!==t)throw Jt("preBuyQuantity",t,"Pre-buy quantity");if(n<0)throw Jt("preBuyQuantity",t,"Pre-buy quantity");if(e.reverseBondingCurveConfiguration){const{minFeePortion:t,maxFeePortion:n}=e.reverseBondingCurveConfiguration;nr(t,n,"reverseBondingCurve")}throw new Error("Legacy launchToken signing is unavailable; configure the v6 launchpad write transport.")}async calculateInitialBuyAmount(e){if(!Xi(e))throw Wt("data","valid pre-mint calculation data");const t="Failed to calculate initial buy amount";return ao(await cn(()=>this.http.get(ht,{amount:e.nativeTokenQuantity}),{errorContext:t}),t)}async fetchPoolDetailsForCalculation(e){const t=await this.fetchSaleDetails(e),n=Yi(Qi(t.maxSupply).minus(t.sellingTokenQuantity)),r=t.sellingTokenQuantity,s=t.maxSupply;let i=.5,o=.1;const a=t.reverseBondingCurveConfiguration;null!=a?.maxFeePortion&&(i=jn(a.maxFeePortion,.5)),null!=a?.minFeePortion&&(o=jn(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){uo(e);const t=await this.fetchSaleDetails(e),n=Yi(Qi(t.maxSupply).minus(t.sellingTokenQuantity)),r=t.maxSupply;return this.metadataCache.set(e,{maxSupply:r}),n}async fetchPoolDetails(e){uo(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:!Zi(s)||!Zi(i),isGraduated:"Finished"===t.saleStatus}}async fetchSaleDetails(e){return hr(e,"tokenName",Ir),cn(()=>this.http.get(dt,{tokenName:e}),{errorContext:`Failed to fetch sale details for ${e}`})}validateAmountCalculationInputs(e,t,n,r,s,i){const o=r??this.defaultCalculateAmountMode;if("local"!==o&&"external"!==o)throw Yt("mode",'"local" or "external"',o);if(!or(e))throw Ht("tokenName","Token name");if(!or(t))throw Ht("amount","Amount");if("string"!=typeof n||!s.includes(n))throw Yt("type",i,n);return o}validateExternalAmountInputs(e,t){if("string"!=typeof e||""===e)throw new kt("Token name must be a non-empty string","tokenName","INVALID_TOKEN_NAME");if("string"!=typeof t||""===t)throw new kt("Amount must be a non-empty string","amount","INVALID_AMOUNT")}getAddress(){return this.http.getAddress()}formatAddressForBackend(e){return Mn(e)}validateTokenName(e){return uo(e)}validatePagination(e){void 0!==e.pageSize&&lr(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 po={REFRESH_THRESHOLD_MS:3e5,DEFAULT_EXPIRY_S:86400,LOGIN_MESSAGE_PREFIX:"Sign in to Launchpad t:",AUTH_HEADER:"Authorization",BEARER_PREFIX:"Bearer "};class Eo{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 Ao;!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"}(Ao||(Ao={}));class vo extends Error{constructor(e,t,n,r){super(t),this.type=e,this.originalError=n,this.statusCode=r,this.name="AuthError"}}class To{constructor(e,t=po.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 Eo,this.refreshThresholdMs=t}setToken(e,t){if(!or(e))throw new vo(Ao.SIGNATURE_FAILED,"JWT token must be a non-empty string");if("number"!=typeof t)throw new vo(Ao.SIGNATURE_FAILED,"Token expiration must be a positive finite number (seconds)");if(!Number.isFinite(t))throw new vo(Ao.SIGNATURE_FAILED,"Token expiration must be a positive finite number (seconds)");if(t<=0)throw new vo(Ao.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 vo(Ao.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:`${po.BEARER_PREFIX}${e}`}getJwtHeaders(){const e=this.getAuthorizationHeader();if(null===e||""===e)throw new vo(Ao.WALLET_NOT_CONNECTED,"No JWT token available. Call login() first.");return{[po.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 yo extends To{getJwtHeaders(){return{}}}async function So(e,t,n,r){try{return await e()}catch(e){throw r?(r(e,t,n),new Error("Unreachable after error handler")):(n&&n.error(`${t}:`,e),function(e,t,n){n&&n.error(`${t}:`,e);const r=(xt(e)?e.response?.status:void 0)??(e instanceof Rt?e.statusCode:void 0);return Vt(`${t}: ${Ut(e)}`,r,Lt(e)?e:void 0)}(e,t,n))}}function bo(e,t){return t instanceof vo?t:new vo(Ao.SIGNATURE_FAILED,`${e}: ${Ut(t)}`,Lt(t)?t:void 0,function(e){if("object"==typeof e&&null!==e){if("statusCode"in e&&"number"==typeof e.statusCode)return e.statusCode;if("response"in e&&"object"==typeof e.response&&null!==e.response){const t=e.response;if("status"in t&&"number"==typeof t.status)return t.status}}}(t))}class No{constructor(e,t,n,r=!1,s){this.http=e,this.signatureAuth=t,this.jwtAuth=n,this.session=s,this.refreshPromise=null,this.loginPromise=null,this.logger=new En({debug:r,context:"SessionAuthService"})}async loginWithSignature(e){const t=wn(e.address,"address");if(!or(e.message)||!or(e.signature))throw new vo(Ao.SIGNATURE_FAILED,"A login needs the signed message and its signature.");const n={address:t,message:e.message,signature:e.signature,...void 0!==e.publicKey&&{publicKey:e.publicKey},...void 0!==this.session&&{cookieSession:!0}};return this.postLogin(n)}async loginWithDevBypass(e){return this.postLogin({address:wn(e,"address"),...void 0!==this.session&&{cookieSession:!0}})}async postLogin(e){try{const t=await this.http.request({method:"POST",url:Z,data:e,withSession:!1}),n=this.extractLoginData(t);return void 0===this.session&&await this.jwtAuth.setTokens(n.accessToken,n.expiresIn,n.refreshToken,n.refreshExpiresIn),n}catch(e){throw bo("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 vo(Ao.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 So(async()=>{const e=Date.now(),t=`${po.LOGIN_MESSAGE_PREFIX}${e}`;this.logger.debug("Generating login signature",{message:t,timestamp:e});const n=await this.signatureAuth.signMessage(t),r=wn(this.signatureAuth.getAddress(),"address"),s={address:r,message:t,signature:n.signature};this.logger.debug("Sending login request",{address:r,message:t});const i=await this.http.post(Z,s),o=this.extractLoginData(i);return await this.jwtAuth.setTokens(o.accessToken,o.expiresIn,o.refreshToken,o.refreshExpiresIn),this.logger.debug("Login successful",{address:o.address,expiresIn:o.expiresIn,hasRefreshToken:!!o.refreshToken}),o},"SessionAuthService.performLogin",this.logger,e=>{if(e instanceof vo)throw e;throw new vo(Ao.SIGNATURE_FAILED,`Login failed: ${Ut(e)}`,Lt(e)?e:void 0)})}async refresh(){if(this.refreshPromise)return this.logger.debug("Refresh already in progress, reusing existing promise"),this.refreshPromise;if(void 0!==this.session){this.refreshPromise=this.performCookieRefresh();try{return await this.refreshPromise}finally{this.refreshPromise=null}}if(!this.jwtAuth.hasToken())throw new vo(Ao.WALLET_NOT_CONNECTED,"No token to refresh. Call login() first.");this.refreshPromise=this.performRefresh();try{return await this.refreshPromise}finally{this.refreshPromise=null}}async performCookieRefresh(){try{const e=await this.http.request({method:"POST",url:te,data:{},withSession:!1});return this.extractLoginData(e)}catch(e){throw bo("Token refresh failed",e)}}async performRefresh(){return So(async()=>{this.logger.debug("Refreshing JWT token");const e=await this.jwtAuth.getRefreshToken();if(e){this.logger.debug("Using refresh token flow");const t=await this.http.post(te,{refreshToken:e}),n=this.extractLoginData(t);return await this.jwtAuth.setTokens(n.accessToken,n.expiresIn,n.refreshToken,n.refreshExpiresIn),this.logger.debug("Token refreshed successfully via refresh token",{address:n.address,expiresIn:n.expiresIn,hasNewRefreshToken:!!n.refreshToken}),n}this.logger.debug("Using legacy access token refresh");const t=await this.http.post(te,{},this.jwtAuth.getJwtHeaders()),n=this.extractLoginData(t);return this.jwtAuth.setToken(n.accessToken,n.expiresIn),this.logger.debug("Token refreshed successfully via access token",{address:n.address,expiresIn:n.expiresIn}),n},"SessionAuthService.performRefresh",this.logger,e=>{if(e instanceof vo)throw e;throw new vo(Ao.SIGNATURE_FAILED,`Token refresh failed: ${Ut(e)}`,Lt(e)?e:void 0)})}async logout(e){this.logger.debug("Logging out",{allDevices:e?.allDevices});const t=e?.allDevices??!1;if(void 0!==this.session){const n=e?.accessToken??null;try{await this.http.request({method:"POST",url:ee,data:{allDevices:t},withSession:!1,...null!==n&&""!==n&&{headers:{Authorization:`${po.BEARER_PREFIX}${n}`}}})}catch(e){throw bo("Logout failed",e)}return}if(t&&this.jwtAuth.hasToken()&&!this.jwtAuth.isExpired())try{await this.http.post(ee,{allDevices:!0},this.jwtAuth.getJwtHeaders()),this.logger.debug("Logged out from all devices")}catch(e){this.logger.warn(`Failed to revoke all-device sessions (server-side revocation may be incomplete): ${Ut(e)}`)}else t&&this.logger.debug("Skipping server-side revocation: no valid local token available");await this.jwtAuth.clear()}async getSession(){if(!this.jwtAuth.hasToken())throw new vo(Ao.WALLET_NOT_CONNECTED,"Not authenticated. Call login() first.");return So(async()=>{const e=await this.http.get(ne,void 0,this.jwtAuth.getJwtHeaders());return this.extractSessionData(e)},"SessionAuthService.getSession",this.logger,e=>{if(e instanceof vo)throw e;throw new vo(Ao.SIGNATURE_FAILED,`Failed to get session: ${Ut(e)}`,Lt(e)?e:void 0)})}getAccessToken(){return this.jwtAuth.getToken()}isAuthenticated(){return this.jwtAuth.isValid()}shouldRefresh(e){return this.jwtAuth.shouldRefresh(e)}async ensureValidToken(e){if(void 0!==this.session){const e=await this.session.accessToken();if(null===e||""===e)throw new vo(Ao.WALLET_NOT_CONNECTED,"The app session has no access token.");return e}if(!this.jwtAuth.hasToken())throw new vo(Ao.WALLET_NOT_CONNECTED,"Not authenticated. Call login() first.");if(this.jwtAuth.isExpired()){if(await this.jwtAuth.getRefreshToken()){this.logger.debug("Token expired - refresh token available, attempting refresh");try{return(await this.refresh()).accessToken}catch(e){this.logger.warn(`Refresh failed after expiry: ${Ut(e)} - attempting re-login`)}}else this.logger.debug("Token expired - no refresh token available, attempting re-login");return(await this.login()).accessToken}if(this.jwtAuth.shouldRefresh(e)){this.logger.debug("Token near expiry - refreshing");return(await this.refresh()).accessToken}return this.jwtAuth.getToken()}extractLoginData(e){if(e.error)throw new vo(Ao.SIGNATURE_FAILED,""!==Ut(e)?Ut(e):"Authentication failed");const t=an(e,"No data in authentication response"),{accessToken:n,expiresIn:r,address:s,refreshToken:i,refreshExpiresIn:o}=t;if(!or(n))throw new vo(Ao.SIGNATURE_FAILED,"Invalid access token in response");if("number"!=typeof r||r<=0)throw new vo(Ao.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 vo(Ao.SIGNATURE_FAILED,""!==Ut(e)?Ut(e):"Failed to get session");return an(e,"No data in session response")}}class wo{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{Zn(e.messagePrefix,"messagePrefix",!1)}catch{throw new vo(Ao.SIGNATURE_FAILED,"Message prefix cannot be empty")}}hasWallet(){return void 0!==this.walletProvider||void 0!==this.wallet}ensureWalletProvider(){if(this.wallet&&!this.walletProvider)try{this.walletProvider=S.fromWallet(this.wallet),this.cachedAddress=this.wallet.address,this.cachedGalaAddress=Mn(this.wallet.address)}catch(e){if(e instanceof vo)throw e;if(e instanceof kt&&("INVALID_ADDRESS"===e.code||"INVALID_FORMAT"===e.code||"address"===e.field))throw new vo(Ao.INVALID_ADDRESS,e.message);if(null!==e&&"object"==typeof e&&"message"in e)throw new vo(Ao.WALLET_NOT_CONNECTED,e.message);throw e}}setWallet(e){if(void 0!==e){if("object"!=typeof e||!("address"in e))throw new vo(Ao.WALLET_NOT_CONNECTED,"Invalid wallet: must be an ethers Wallet instance or undefined");if("string"!=typeof e.address||""===e.address)throw new vo(Ao.INVALID_ADDRESS,"Wallet address is not available");this.walletProvider=S.fromWallet(e),this.cachedAddress=e.address,this.cachedGalaAddress=Mn(e.address)}else this.walletProvider=void 0,this.cachedAddress=void 0,this.cachedGalaAddress=void 0;this.wallet=e}setWalletProvider(e){this.walletProvider=e,this.wallet=void 0;const t=void 0!==e&&b(e)?p(e.exportPrivateKey()):void 0;this.cachedAddress=t,this.cachedGalaAddress=void 0===t?void 0:Mn(t)}getWalletProvider(){return this.walletProvider}async cacheAddress(){this.walletProvider&&(this.cachedAddress=await this.walletProvider.getAddress(),this.cachedGalaAddress=wn(await this.walletProvider.getGalaAddress(),"address"))}async generateSignature(){await this.validateWalletAsync();try{const e=Date.now(),t=`${this.messagePrefix} ${e}`,n=await this.walletProvider.signMessage(t);return{message:t,signature:n,address:await this.walletProvider.getGalaAddress(),timestamp:e}}catch(e){if(e instanceof vo)throw e;throw new vo(Ao.SIGNATURE_FAILED,"Failed to generate signature for authentication",Lt(e)?e:new Error(Ut(e)))}}getAddress(){if(this.validateWallet(),this.cachedGalaAddress)return this.cachedGalaAddress;if(this.wallet)return this.formatAddress(this.wallet.address);throw new vo(Ao.WALLET_NOT_CONNECTED,"Address not available. For external wallets, call cacheAddress() after connecting.")}async getAddressAsync(){return await this.validateWalletAsync(),wn(await this.walletProvider.getGalaAddress(),"address")}getEthereumAddress(){if(this.validateWallet(),this.cachedAddress)return this.cachedAddress;if(this.wallet)return this.wallet.address;throw new vo(Ao.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 vo(Ao.WALLET_NOT_CONNECTED,"Wallet private key not available for @gala-chain signing");return this.wallet.privateKey}if(void 0!==this.walletProvider&&b(this.walletProvider))return this.walletProvider.exportPrivateKey();throw new vo(Ao.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 vo(Ao.WALLET_NOT_CONNECTED,"Private key not available with this wallet provider");try{return await this.walletProvider.getPrivateKey()}catch(e){throw new vo(Ao.WALLET_NOT_CONNECTED,"Private key not available. External wallet providers cannot access private keys. Use PrivateKeyProvider for @gala-chain signing operations.",Lt(e)?e:void 0)}}formatAddress(e){try{return Mn(e)}catch{throw new vo(Ao.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 vo)throw e;throw new vo(Ao.SIGNATURE_FAILED,Ut(e),Lt(e)?e:new Error(Ut(e)))}}async generateAuthHeaders(e,t){await this.validateWalletAsync();try{const n=Date.now(),r=`${this.messagePrefix} ${t.toUpperCase()} ${e} ${n}`,s=await this.walletProvider.signMessage(r);return{"x-signature":s,"x-address":await this.walletProvider.getGalaAddress(),"x-message":r,"x-timestamp":n.toString()}}catch(e){if(e instanceof vo)throw e;throw new vo(Ao.SIGNATURE_FAILED,"Failed to generate authentication headers",Lt(e)?e:new Error(Ut(e)))}}async signTypedData(e,t,n){await this.validateWalletAsync();try{const r={};for(const[e,n]of Object.entries(t))r[e]=n.map(e=>({name:e.name,type:e.type}));return await this.walletProvider.signTypedData(e,r,n)}catch(e){if(e instanceof vo)throw e;throw new vo(Ao.SIGNATURE_FAILED,"Failed to sign typed data",Lt(e)?e:new Error(Ut(e)))}}async generateCustomSignature(e){if(!or(e))throw new vo(Ao.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 vo)throw e;throw new vo(Ao.SIGNATURE_FAILED,"Failed to generate custom message signature",Lt(e)?e:new Error(Ut(e)))}}validateWallet(){if(this.ensureWalletProvider(),!this.walletProvider)throw new vo(Ao.WALLET_NOT_CONNECTED,"Wallet is required for authentication")}async validateWalletAsync(){if(this.ensureWalletProvider(),!this.walletProvider)throw new vo(Ao.WALLET_NOT_CONNECTED,"Wallet is required for authentication");if(!this.walletProvider.isConnected())throw new vo(Ao.WALLET_NOT_CONNECTED,"Wallet is not connected. Call connect() on the wallet provider first.")}}const ko={prod:{...n.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:{...n.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 _o(e){return ko[e]}var Io,Do;!function(e){e.PROCESSED="PROCESSED",e.COMPLETED="COMPLETED",e.SUCCESS="SUCCESS",e.FAILED="FAILED",e.ERROR="ERROR",e.PROCESSING="PROCESSING",e.PENDING="PENDING"}(Io||(Io={})),function(e){e.PENDING="pending",e.PROCESSING="processing",e.COMPLETED="completed",e.FAILED="failed",e.TIMEOUT="timeout"}(Do||(Do={}));const Co={[Io.PROCESSED]:Do.COMPLETED,[Io.COMPLETED]:Do.COMPLETED,[Io.SUCCESS]:Do.COMPLETED,[Io.FAILED]:Do.FAILED,[Io.ERROR]:Do.FAILED,[Io.PROCESSING]:Do.PROCESSING,[Io.PENDING]:Do.PENDING},Ro="9.0.0-rc.6",Oo={DEFAULT_PAGE_SIZE:50,MAX_PAGE_SIZE:1e3,SAFETY_MAX_PAGES:1e4,DEFAULT_OFFSET:0,DEFAULT_LIMIT:10,BACKEND_MAX_PAGE_SIZE:20},Mo={MAX_CONCURRENT_FETCHES:5,PAGE_SIZE:50,BACKEND_PAGE_SIZE:20};function Lo(e,t=Oo.DEFAULT_LIMIT){if("number"!=typeof e||!Number.isInteger(e)||e<0)throw Yt("offset","a non-negative integer",e);return Jn(t,"limit"),{offset:e,limit:t}}function Uo(e,t,n){if("number"!=typeof e||!Number.isInteger(e)||e<0)throw Yt("offset","a non-negative integer",e);Jn(t,"limit")}function Fo(e,t=1,n=Oo.BACKEND_MAX_PAGE_SIZE){return Math.max(t,Math.min(n,Math.ceil(e??t)))}function Po(e,t){if("number"!=typeof e||!Number.isInteger(e))throw Yt("total","a non-negative integer",e);if(e<0)throw zt("total",0,1/0,e);if("number"!=typeof t||!Number.isInteger(t))throw Yt("limit","a non-negative integer",t);if(t<0)throw zt("limit",0,1/0,t);return 0===t?1:0===e?0:Math.ceil(e/t)}function xo(e,t,n){if("number"!=typeof e||!Number.isInteger(e))throw Yt("offset","a non-negative integer",e);if(e<0)throw zt("offset",0,1/0,e);return e+t<n}function Bo(e){return"string"==typeof e||null===e?e:void 0}function Go(e){if("object"!=typeof e||null===e)return{hasNextPage:!1};const t=Reflect.get(e,"hasNextPage"),n=Reflect.get(e,"hasPreviousPage"),r=Bo(Reflect.get(e,"endCursor")),s=Bo(Reflect.get(e,"startCursor"));return{hasNextPage:!0===t,...void 0===r?{}:{endCursor:r},..."boolean"==typeof n?{hasPreviousPage:n}:{},...void 0===s?{}:{startCursor:s}}}function $o(e,t){const{hasNextPage:n,endCursor:r}=e;if(n&&"string"==typeof r&&""!==r&&r!==t)return r}function Ko(e){return"string"==typeof e?e:"number"==typeof e||"boolean"==typeof e||"bigint"==typeof e?String(e):JSON.stringify(e)??""}function Ho(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 Wo={tokenName:"lowercase",address:"lowercase",userAddress:"lowercase",assetId:"as given",targetId:"as given",id:"as given",code:"as given"};function Vo(e,t){let n=e;for(const[e,r]of Object.entries(t)){const t=Wo[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 jo(e,t,n){for(const r of n){const n=t[r];null!=n&&""!==n&&(e[r]=Ko(n))}return e}const qo="x-api-key";class zo 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(!or(e))throw Ht("tokenName","Token name");const n=gn(e);if(!t.PATTERN.test(n))throw Wt("tokenName",t.DESCRIPTION,"Token name")}(e,t)}validateRequiredString(e,t,n){!function(e,t,n){if(!or(e))throw Ht(t,n)}(e,t,n)}validateOptionalString(e,t,n,r){!function(e,t,n,r){if(null!=e){if("string"!=typeof e)throw Yt(t,"string",typeof e,n);if(e.length>r)throw Qt(t,r,e.length,n)}}(e,t,n,r)}validateOptionalNumber(e,t,n,r,s,i,o){!function(e,t,n,r,s){if(null!=e){if("number"!=typeof e)throw Yt(t,"number",typeof e,n);if(e<r||e>s)throw zt(t,r,s,e,n)}}(e,t,n,r,s)}validateOptionalDate(e,t,n){!function(e,t,n){if(null!=e&&!bn(e))throw Wt(t,"a valid ISO 8601 date string",n)}(e,t,n)}validatePositiveInteger(e,t,n){Sr(e,t,n)}validateStatusFilter(e,t,n="status"){br(e,t,n)}buildPaginationParams(e,t){return Ho(e,t)}addOptionalFilterParams(e,t,n){return jo(e,t,n)}buildEndpoint(e,t){return Vo(e,t)}buildEndpointWithId(e,t){return e.replace(":id",encodeURIComponent(t))}validateAndBuildTokenEndpoint(e,t,n){return this.validateTokenName(e,t),this.buildEndpoint(n,{tokenName:e})}getAdminHeaders(){if(void 0===this.adminApiKey||""===this.adminApiKey)throw new Ot("Admin API key required for this operation. Set streamAdminApiKey in SDK config.");return{[qo]:this.adminApiKey}}getJwtHeaders(){if(!this.jwtAuth)throw new Ot("JWT authentication required. Call sdk.login() first.");return this.jwtAuth.getJwtHeaders()}hasJwtAuth(){return this.jwtAuth?.isValid()??!1}hasAdminApiKey(){return void 0!==this.adminApiKey&&""!==this.adminApiKey}getDualAuthHeaders(){return void 0!==this.adminApiKey&&""!==this.adminApiKey?this.getAdminHeaders():this.getJwtHeaders()}getMultiAuthHeaders(){return void 0!==this.userApiKey&&""!==this.userApiKey?{[qo]:this.userApiKey}:this.getJwtHeaders()}extractData(e){return sn(e,"Backend request failed",!0),an(e,"No data in backend response")}extractDataOrNull(e){return sn(e,"Backend request failed",!1),e.data??null}async toggleFeature(e,t,n){this.validateTokenName(e,n);const r=this.buildEndpoint(t,{tokenName:e}),s=await this.http.post(r,{},this.getAdminHeaders()),i=this.extractData(s);return{enabled:i.enabled,tokenName:i.tokenName??gn(e)}}}class Xo extends zo{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async getSettings(){return{settings:(await this.http.get(at.GET_SETTINGS,{},this.getDualAuthHeaders())).settings}}async updateSettings(e){const t={};void 0!==e.enabled&&(t.enabled=e.enabled),void 0!==e.mode&&(t.mode=e.mode),void 0!==e.provider&&(t.provider=e.provider);return{settings:(await this.http.post(at.UPDATE_SETTINGS,t,this.getDualAuthHeaders())).settings}}async getModeration(e){this.validatePositiveInteger(e.flagId,"flagId","Flag ID");const t=at.GET_MODERATION.replace(":flagId",String(e.flagId));return{moderation:(await this.http.get(t,{},this.getDualAuthHeaders())).analysis}}async triggerModeration(e){this.validatePositiveInteger(e.flagId,"flagId","Flag ID");const t=at.TRIGGER_MODERATION.replace(":flagId",String(e.flagId)),n=await this.http.post(t,{},this.getDualAuthHeaders());return{queued:n.queued,message:n.message.length>0?n.message:"Moderation queued successfully"}}async getStatus(){return{status:(await this.http.get(at.GET_STATUS,{},this.getDualAuthHeaders())).status}}}const Qo={MODERATOR:"MODERATOR",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MANAGER:"MANAGER",OWNER:"OWNER"},Yo=ur(Qo),Jo={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"},Zo={MANAGE_COMMUNITY:"MANAGE_COMMUNITY",MANAGE_STREAM:"MANAGE_STREAM",MANAGE_SETTINGS:"MANAGE_SETTINGS",MANAGE_RECORDINGS:"MANAGE_RECORDINGS",VIEW_ANALYTICS:"VIEW_ANALYTICS"},ea=Object.values(Zo);function ta(e){return Yo.includes(e)}function na(e){const t=[];return void 0===e.role||null===e.role?t.push("Role is required"):ta(e.role)||t.push(`Invalid role. Must be one of: ${Yo.join(", ")}`),sa(e,t),t}function ra(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||ta(e.role)||t.push(`Invalid role. Must be one of: ${Yo.join(", ")}`),sa(e,t,!0),t}function sa(e,t,n=!1){const r=t.length;if(Gt(t,()=>{Tr(e.description,"description",255)}),t.length>r&&(t[r]="Description must be 255 characters or less"),void 0!==e.tokenNames){const n=t.length;Gt(t,()=>{if(!Array.isArray(e.tokenNames))throw Yt("tokenNames","an array",e.tokenNames);if(!e.tokenNames.every(e=>"string"==typeof e))throw Yt("tokenNames","contain only strings")});for(let e=n;e<t.length;e++){const n=t[e];n?.includes("array")?t[e]="tokenNames must be an array":n?.includes("string")&&(t[e]="tokenNames must contain only strings")}}if(void 0!==e.expiresAt&&(!n||null!==e.expiresAt)){const n=t.length;Gt(t,()=>{yr(e.expiresAt,"expiresAt")}),t.length>n&&(t[n]="expiresAt must be a valid ISO 8601 date string")}}function ia(e){if(void 0!==e.pageSize&&("number"!=typeof e.pageSize||e.pageSize<1||e.pageSize>Mr))throw Yt("pageSize",`number between 1 and ${Mr}`,typeof e.pageSize);if(void 0!==e.cursor&&("string"!=typeof e.cursor||""===e.cursor.trim()))throw Yt("cursor","non-empty string",typeof e.cursor)}const oa={[Qo.MODERATOR]:1,[Qo.TECHNICAL_PRODUCER]:1,[Qo.MANAGER]:2,[Qo.OWNER]:3};function aa(e,t){return e===Qo.MANAGER?t!==Qo.OWNER:e===Qo.OWNER||e===t}class ca 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),sn(n,"API key operation failed",!0),e.data}validateApiKeyId(e){this.validatePositiveInteger(e,"id","API key ID")}async create(e){const t=na(e);if(t.length>0)throw new kt(t.join("; "),"options","VALIDATION_FAILED");this.logger.debug("Creating API key",{role:e.role,delegateAllTokens:e.delegateAllTokens});const n={role:e.role};void 0!==e.description&&(n.description=e.description),void 0!==e.delegateAllTokens&&(n.delegateAllTokens=e.delegateAllTokens),void 0!==e.tokenNames&&e.tokenNames.length>0&&(n.tokenNames=e.tokenNames),void 0!==e.expiresAt&&(n.expiresAt=e.expiresAt),void 0!==e.tokenPermissions&&(n.tokenPermissions=e.tokenPermissions);const r=await this.http.post(he.CREATE,n,this.getJwtHeaders()),s=this.extractData(r);return this.logger.debug("API key created",{id:s.id,keyPrefix:s.keyPrefix}),s}async findAll(e={}){ia(e),this.logger.debug("Listing API keys",e);const t=Ho(e,Mr),n=await this.http.get(he.LIST,t,this.getJwtHeaders()),r=this.extractData(n);return this.logger.debug("Listed API keys",{count:r.apiKeys.length,total:r.pageInfo.totalCount}),r}async findOne(e){this.validateApiKeyId(e),this.logger.debug("Getting API key",{id:e});const t=he.GET.replace(":id",String(e)),n=await this.http.get(t,{},this.getJwtHeaders()),r=this.extractData(n);return this.logger.debug("Got API key",{id:r.id,keyPrefix:r.keyPrefix}),r}async update(e,t){this.validateApiKeyId(e);const n=ra(t);if(n.length>0)throw new kt(n.join("; "),"options","VALIDATION_FAILED");this.logger.debug("Updating API key",{id:e,options:t});const r={};void 0!==t.role&&(r.role=t.role),void 0!==t.description&&(r.description=t.description),void 0!==t.delegateAllTokens&&(r.delegateAllTokens=t.delegateAllTokens),void 0!==t.tokenNames&&(r.tokenNames=t.tokenNames),void 0!==t.expiresAt&&(r.expiresAt=t.expiresAt),void 0!==t.tokenPermissions&&(r.tokenPermissions=t.tokenPermissions);const s=he.UPDATE.replace(":id",String(e)),i=await this.http.patch(s,r,this.getJwtHeaders()),o=this.extractData(i);return this.logger.debug("Updated API key",{id:o.id,keyPrefix:o.keyPrefix}),o}async revoke(e){this.validateApiKeyId(e),this.logger.debug("Revoking API key",{id:e});const t=he.REVOKE.replace(":id",String(e));await this.http.delete(t,{},this.getJwtHeaders()),this.logger.debug("API key revoked",{id:e})}getRoles(){return[...Yo]}}const la={ONE_HOUR:3600,ONE_DAY:86400,ONE_WEEK:604800,ONE_MONTH:2592e3},da={VIEWERS:"viewers",CHAT_PARTICIPANTS:"chat_participants"},ua=dr(da),ha=pr([{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}]),ga=pr([{field:"tokenName",type:"string",nullable:!0},{field:"isGlobal",type:"boolean"},{field:"isPermanent",type:"boolean"}]),ma=pr([{field:"tokenName",type:"string",nullable:!0},{field:"isGlobal",type:"boolean"}]),fa=pr([{field:"tokenName",type:"string"},{field:"action",type:"string",validator:e=>"CHAT_MESSAGE"===e||"COMMENT"===e||"REACTION"===e}]);function pa(e){return null==e||""===e||"string"==typeof e&&(!vr(e)&&e.length<=Pr.BAN_REASON.MAX_LENGTH)}function Ea(e){return!!cr(e)||"number"==typeof e&&(e>=Br&&e<=Gr)}function Aa(e){if(!or(e.userAddress))throw Ht("userAddress");if(!pa(e.reason))throw new kt(`reason must be at most ${Pr.BAN_REASON.MAX_LENGTH} characters`,"reason","TOO_LONG");if(!Ea(e.durationSeconds))throw new kt(`durationSeconds must be between ${Br} and ${Gr} seconds`,"durationSeconds","OUT_OF_RANGE")}class va extends zo{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async createBan(e){!function(e){hr(e.tokenName,"tokenName",Cr),Aa(e)}(e);const t=this.buildEndpoint(re,{tokenName:e.tokenName}),n=Ta(e),r=await this.http.post(t,n,this.getMultiAuthHeaders());return{ban:this.extractData(r),tokenName:gn(e.tokenName)}}async removeBan(e){!function(e){if(hr(e.tokenName,"tokenName",Cr),!or(e.userAddress))throw Ht("userAddress")}(e);const t=kn(e.userAddress,"userAddress"),n=this.buildEndpoint(oe,{tokenName:e.tokenName,userAddress:t}),r=await this.http.delete(n,{},this.getMultiAuthHeaders()),s=this.extractDataOrNull(r);return{removed:s?.removed??!0,tokenName:gn(e.tokenName),userAddress:s?.userAddress??t}}async listBans(e){!function(e){hr(e.tokenName,"tokenName",Cr),lr(0,void 0,Mr,e.pageSize)}(e);const t=this.buildEndpoint(se,{tokenName:e.tokenName}),n=this.buildPaginationParams(e,Mr);this.addOptionalFilterParams(n,e,["search","name","userAddress"]),void 0!==n.userAddress&&(n.userAddress=In(n.userAddress));const r=await this.http.get(t,n,this.getMultiAuthHeaders()),s=this.extractData(r);return{items:s.bans,pageInfo:s.pageInfo}}async getBanStatus(e){!function(e){if(hr(e.tokenName,"tokenName",Cr),!or(e.userAddress))throw Ht("userAddress")}(e);const t=kn(e.userAddress,"userAddress"),n=this.buildEndpoint(ie,{tokenName:e.tokenName,userAddress:t}),r=await this.http.get(n,{},this.getMultiAuthHeaders()),s=this.extractDataOrNull(r);return{banned:null!==s,...null!==s&&{ban:s},tokenName:gn(e.tokenName),userAddress:t}}async getActiveUsers(e){!function(e){if(hr(e.tokenName,"tokenName",Cr),void 0!==e.type&&!ua(e.type))throw new kt(`type must be one of: ${Object.values(da).join(", ")}`,"type",wt.INVALID_VALUE)}(e);const t=this.buildEndpoint(ae,{tokenName:e.tokenName}),n={};this.addOptionalFilterParams(n,e,["type","search","name","userAddress"]),void 0!==n.userAddress&&(n.userAddress=In(n.userAddress));const r=await this.http.get(t,n,this.getMultiAuthHeaders());return this.extractData(r)}async createGlobalBan(e){!function(e){Aa(e)}(e);const t=Ta(e),n=await this.http.post(ce,t,this.getDualAuthHeaders());return{ban:this.extractData(n)}}async removeGlobalBan(e){!function(e){if(!or(e.userAddress))throw Ht("userAddress")}(e);const t=kn(e.userAddress,"userAddress"),n=this.buildEndpoint(ue,{userAddress:t}),r=await this.http.delete(n,{},this.getDualAuthHeaders()),s=this.extractDataOrNull(r);return{removed:s?.removed??!0,userAddress:s?.userAddress??t}}async listGlobalBans(e){const t=e??{pageSize:20};!function(e){lr(0,void 0,Mr,e.pageSize)}(t);const n=this.buildPaginationParams(t,Mr);this.addOptionalFilterParams(n,t,["search","name","userAddress"]),void 0!==n.userAddress&&(n.userAddress=In(n.userAddress));const r=await this.http.get(le,n,this.getDualAuthHeaders()),s=this.extractData(r);return{items:s.bans,pageInfo:s.pageInfo}}async getGlobalBan(e){!function(e){if(!or(e.userAddress))throw Ht("userAddress")}(e);const t=kn(e.userAddress,"userAddress"),n=this.buildEndpoint(de,{userAddress:t}),r=await this.http.get(n,{},this.getDualAuthHeaders()),s=this.extractDataOrNull(r);return{banned:null!==s,...null!==s&&{ban:s},userAddress:t}}}function Ta(e){const t={userAddress:kn(e.userAddress,"userAddress")};return void 0!==e.reason&&(t.reason=e.reason),void 0!==e.durationSeconds&&(t.durationSeconds=e.durationSeconds),t}function ya(e){return{maxAcceptableReverseBondingCurveFee:zn(e.maxAcceptableReverseBondingCurveFee)}}const Sa={BuyNativeDto:class extends N{constructor(e,t,n="0",r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=zn(t),this.expectedToken=Xn(n),this.extraFees=ya(r)}},BuyExactDto:class extends N{constructor(e,t,n,r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=Xn(t),this.expectedNativeToken=zn(n),this.extraFees=ya(r)}},SellExactDto:class extends N{constructor(e,t,n="0",r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=Xn(t),this.expectedNativeToken=zn(n),this.extraFees=ya(r)}},SellNativeDto:class extends N{constructor(e,t,n,r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=zn(t),this.expectedToken=Xn(n),this.extraFees=ya(r)}}};function ba(e,t,n){let r;Qn(t,0,1,"slippageToleranceFactor");try{r=function(e,t){if(Tn(e)||""===e)throw Ht(t);if(I.isBigNumber(e)){if(e.isNaN())throw Jt(t,"NaN");return e}try{const n=new I(e);if(n.isNaN())throw Jt(t,e);if(!n.isFinite())throw Jt(t,e);return n}catch(n){if(n instanceof kt)throw n;throw Jt(t,e)}}(e,"expectedAmount")}catch{throw new Error(`Invalid expected amount: ${e}. Must be a valid number`)}if(0===t)return e;const s=r.multipliedBy(t);let i;switch(n){case"buy-native":case"sell-exact":i=r.minus(s);break;case"buy-exact":case"sell-native":i=r.plus(s);break;default:throw new Error(`Unknown operation type: ${n}`)}return Qi(i).isLessThan(0)&&(i=Qi(0)),Yi(i)}function Na(e,t){if(!or(e))throw new Error("Input must be a non-empty string");const n=e.split(t);if(n.length<4)throw new Error(`Invalid ${"|"===t?"pipe":"dollar"}-delimited token format. Expected 4+ parts separated by ${t}, got ${n.length}`);return n}function wa(e,t,n,r){const s=e?.split?.(t)??[],i=void 0!==n?` (${n})`:"";return new kt(`Invalid ${"|"===t?"pipe":"dollar"}-delimited token: "${e}" (${s.length} parts)${i}. Expected format: "collection${t}category${t}type${t}additionalKey" (4 parts minimum). Received: [${s.map(e=>`"${e}"`).join(", ")}]. Error: ${Ut(r)}`,"token",`INVALID_${"|"===t?"PIPE":"DOLLAR"}_DELIMITED_TOKEN`)}function ka(e,t,n){try{const n=Na(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 wa(e,t,n,r)}}function _a(e){return function(e,t,n){try{const n=Na(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 wa(e,t,n,r)}}(e,"|","pipe-delimited token")}class Ia 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 Da={name:"GalaChain"},Ca={name:"ethereum",chainId:1};function Ra(e){if("string"!=typeof e)throw new Error("Wallet returned an invalid signature");return e}function Oa(e,t){const n=Nn(e,t);if(void 0!==n)throw new Ia(n,"INVALID_SIGNER_OPTIONS",{details:{[t]:e}});return e}function Ma(e){const t={};for(const[n,r]of Object.entries(e))void 0!==r&&(t[n]=La(r));return t}function La(e){return Array.isArray(e)?e.map(La):"object"==typeof e&&null!==e?Ma(e):e}function Ua(e,t,n,r){return{...e,signature:t,types:n,domain:r}}class Fa extends c{constructor(e){super(e),this.typedDataWallet=new T(e),this.walletAddress=`eth|${this.typedDataWallet.address.slice(2)}`}async signTypedData(e,t){const n=Ma(t),r=s(e,n);return Ua(n,await this.typedDataWallet.signTypedData(Da,r,n),r,Da)}}class Pa extends o{constructor(e,t={}){const{verifyActiveAccount:n,...r}=t;if(super(Oa(e,"walletAddress"),{...r,...void 0!==r.selectAddress&&{selectAddress:Oa(r.selectAddress,"selectAddress")}}),this.typedDataWallet=t.wallet,!0===n){const e=i(this.walletAddress)??(void 0===this.selectAddress?void 0:i(this.selectAddress));if(void 0===e)throw new Ia("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=Ma(t),r=s(e,n),o={domain:Ca,types:r,message:n,Primary_type:e},c=this.typedDataWallet??function(){const e=globalThis.window,t=e?.gala;if(void 0===t)throw new Error("Gala wallet is not available");return t}();void 0!==this.verifiedKey&&await async function(e,t){let n="address"in e&&"string"==typeof e.address&&""!==e.address?e.address:void 0;if(void 0===n){const t=await e.request({method:"eth_accounts"}),r=Array.isArray(t)?t[0]:void 0;n="string"==typeof r&&""!==r?r:void 0}const r=void 0===n?void 0:i(n);if(void 0===r||r.toLowerCase()!==t.toLowerCase())throw new Ia("Your wallet's active account has changed. Please switch back to the connected account or reconnect your wallet.","WALLET_ACCOUNT_CHANGED",{details:{walletAccount:n??null,signerAccount:t}})}(c,this.verifiedKey);const l=await this.typedDataAccount(c);return Ua(n,Ra(await a(c,this.selectAddress??l,()=>c.request({method:"eth_signTypedData",params:[JSON.stringify(o),l]}))),r,Ca)}async typedDataAccount(e){if(A(this.walletAddress))return this.walletAddress;const t=await e.request({method:"eth_accounts"}),n=Array.isArray(t)?t[0]:void 0,r="string"==typeof n?n.replace(/^eth\|/,"0x"):"";if(!A(r))throw new Error("Gala Wallet did not report an Ethereum account to sign typed data with");return r}}class xa extends r{constructor(e,t,n){super(e,Oa(t,"walletAddress"),n),this.typedDataProvider=e}async signTypedData(e,t){const n=Ma(t),r=this.typedDataProvider,i=await r.getNetwork(),o={name:i.name,chainId:Number(i.chainId)},a=s(e,n),c=await r.getSigner(),l=E(await c.getAddress());if(A(this.walletAddress)&&l!==E(this.walletAddress))throw new Ia(`Wallet account ${l} is not the account this signer was created for (${this.walletAddress}); reconnect before signing.`,"WALLET_ACCOUNT_CHANGED",{details:{walletAccount:l,signerAccount:this.walletAddress}});return Ua(n,Ra(await c.signTypedData(o,a,n)),a,o)}static fromEip1193(e,t,n){const r=new v(e);return new xa({request:t=>e.request(t),getNetwork:()=>r.getNetwork(),getSigner:()=>r.getSigner()},i(t)??t,n)}}function Ba(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 Ga(e){const{collection:t,category:n,type:r}=Ba(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 $a(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 Ka(e){return`${e.collection}|${e.category}|${e.type}|${e.additionalKey}`}function Ha(e){if("string"==typeof e){if(!or(t=e)||!t.includes("|"))throw new kt(`Invalid tokenId string format: "${e}". Expected pipe-delimited format: "collection|category|type|additionalKey" or "collection|category|type|additionalKey|instance"`,"tokenId","INVALID_TOKEN_ID_FORMAT");const n=e.split("|");if(n.length>=5){const e=_a(n.slice(0,4).join("|")),t=n[4]??"0";return{...e,instance:t.length>0?t:"0"}}return{..._a(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(!l(e))throw new kt("Invalid tokenId object format. All fields (collection, category, type, additionalKey) must be non-empty strings","tokenId","INVALID_TOKEN_ID_FORMAT");return e}if(!l(e))throw new kt("Invalid tokenId object format. All fields (collection, category, type, additionalKey) are required","tokenId","INVALID_TOKEN_ID_FORMAT");return{...e,instance:"0"}}throw new kt(`Invalid tokenId type: ${typeof e}. Expected string, TokenClassKey, or TokenInstanceKey`,"tokenId","INVALID_TOKEN_ID_TYPE")}function Wa(e){return function(e){try{if(!or(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 ka((n.length>=5&&"launchpad"===n[n.length-1]?n.slice(0,-1):n).join("$"),"$","vault address")}catch(t){throw new kt(`Invalid vault address: "${e}". Expected format: "service|Token$Unit$SYMBOL$additionalKey$launchpad". Error: ${Ut(t)}`,"vaultAddress","INVALID_VAULT_ADDRESS_FORMAT")}}(e)}function Va(e){return{...Wa(e),instance:"0"}}function ja(e){const t=Wa(e);if("Token"!==t.collection)throw new kt(`Cannot extract a token symbol from vault address "${e}": collection "${t.collection}" is not the launchpad "Token" collection, and a symbol cannot be derived from a class key.`,"vaultAddress","SYMBOL_NOT_DERIVABLE_FROM_KEY");return t.type}var qa,za,Xa,Qa,Ya=Object.freeze({__proto__:null,extractTokenSymbolFromVault:ja,normalizeToTokenInstanceKey:Ha,parseVaultAddressToTokenClassKey:Wa,parseVaultAddressToTokenInstance:Va});class Ja extends wr{constructor(e=!1){super(e)}generateStringsInstructions(e){try{this.logger.debug("🔧 Generating stringsInstructions for:",e);const t=Ga(e);return this.logger.debug("✅ Generated stringsInstructions:",t),t}catch(e){this.logger.error("❌ Failed to generate stringsInstructions:",e);const t=Ut(e);throw new kt(`Failed to generate stringsInstructions: ${t}`,"vaultAddress","INVALID_VAULT_ADDRESS")}}createGalaInstance(){const e=new w;return e.collection="GALA",e.category="Unit",e.type="none",e.additionalKey="none",this.logger.debug("🟡 Created GALA instance:",{stringKey:e.toStringKey()}),e}extractTokenSymbolFromVault(e){if(!or(e))throw Ht("vaultAddress","Vault address");try{const t=ja(e);return this.logger.debug("🔍 Extracted token symbol:",{vaultAddress:e,tokenSymbol:t}),t}catch(e){if(e instanceof kt)throw Wt("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad");throw e}}validateVaultAddress(e){if(!or(e))throw Ht("vaultAddress","Vault address");if(!e.startsWith("service|Token$Unit$"))throw Wt("vaultAddress",'starting with "service|Token$Unit$"');if(!e.endsWith("$launchpad"))throw Wt("vaultAddress",'ending with "$launchpad"');const t=function(e){if(!or(e))return null;const t=e.match(/^service\|Token\$Unit\$([^$]+)\$eth:([a-fA-F0-9]{40})\$launchpad$/);if(!t)return null;const n=t[1],r=t[2];return void 0===n||void 0===r?null:{tokenSymbol:n,creatorAddress:r.toLowerCase()}}(e);if(!t)throw Wt("vaultAddress","valid vault address format (service|Token$Unit$SYMBOL$eth:address$launchpad)");const n=t.tokenSymbol;if(""===n||!/^[A-Za-z]{1,10}$/.test(n))throw Wt("vaultAddress","containing a 1-10 letter token symbol (case insensitive)");return this.logger.debug("✅ Vault address validation passed:",e),!0}generateTokenClassKeyString(e,t,n,r){return`${e}$${t}$${n}$${r}`}parseTokenClassKeyString(e){try{return ka(e,"$","dollar-delimited token")}catch(e){if(e instanceof kt)throw Wt("stringKey","format: collection$category$type$additionalKey (4 parts)");throw e}}}function Za(e){return"object"==typeof e&&null!==e?e:void 0}class ec extends Nr{constructor(e,t,n=!1,r,s,o=.05,a=.01,c){if(super(e,n),this.tokenResolver=t,this._walletProvider=r,this.userAddress=s,this.defaultSlippageToleranceFactor=o,this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor=a,this.sellFeeCeiling=c,this.bundleEndpoint="/bundle",null!==this._walletProvider&&void 0!==this._walletProvider&&null!=s){const e=Za(this._walletProvider),t=e?.privateKey;if("string"==typeof t)this.signer=new Fa(t);else if(function(e){const t=Za(e);return"function"==typeof t?.request}(this._walletProvider)&&void 0!==this.userAddress){const e=wn(this.userAddress,"userAddress");this.signer=new xa(this._walletProvider,i(e)??e)}this.tokenKeyService=new Ja(n)}}async submitTransaction(e){try{this.validateBundleData(e),this.logger.debug("📦 Submitting bundle transaction:",{method:e.method,stringsInstructionsCount:e.stringsInstructions.length,signedDtoKeys:Object.keys(e.signedDto)});const t=this.formatBundleRequest(e);this.logger.debug("🚀 Bundle request payload:",{...t,signedDto:"[REDACTED - Contains signature]"});let n=null;try{n=await ln(()=>this.http.post(this.bundleEndpoint,t),{errorContext:"Bundle transaction submission failed",logger:this.logger})}catch(e){return{success:!1,error:this.formatErrorMessage(e)}}return null==n?{success:!1,error:"No response from bundle API"}:(this.logger.debug("📥 Bundle API response:",{success:n.success,hasData:rn(n),error:n.error}),this.handleBundleResponse(n))}catch(e){if(e instanceof kt)return{success:!1,error:Ut(e)};throw e}}validateBundleData(e){if(null==e)throw Ht("bundleData","Bundle data");if(null===e.signedDto||void 0===e.signedDto)throw Ht("signedDto","Signed DTO");if(!or(e.method))throw Ht("method","Method name");if(!Array.isArray(e.stringsInstructions))throw Wt("stringsInstructions","an array of resource tracking strings");if(0===e.stringsInstructions.length)throw new kt("stringsInstructions cannot be empty","stringsInstructions","EMPTY_ARRAY");const t=["BuyWithNative","BuyExactToken","SellExactToken","SellWithNative"];if(!t.includes(e.method))throw Wt("method",`one of: ${t.join(", ")}`);e.stringsInstructions.forEach((e,t)=>{if(!or(e))throw new kt(`stringsInstructions[${t}] must be a non-empty string`,`stringsInstructions[${t}]`,"INVALID_INSTRUCTION");if("string"!=typeof(n=e)||!n.includes("$"))throw new kt(`stringsInstructions[${t}] must start with '$': ${e}`,`stringsInstructions[${t}]`,"INVALID_INSTRUCTION_FORMAT");var n}),this.logger.debug("✅ Bundle data validation passed")}formatBundleRequest(e){return{signedDto:e.signedDto,stringsInstructions:e.stringsInstructions,method:e.method}}handleBundleResponse(e){const t=on(e);if(null!=t&&!1===e.error)return this.logger.debug("✅ Bundle transaction successful:",t),{success:!0,data:t};const n=("string"==typeof e.error?e.error:e.message)??"Bundle transaction failed";return this.logger.debug("❌ Bundle transaction failed:",n),{success:!1,error:n}}formatErrorMessage(e){if("string"==typeof e)return e;if(xt(e)&&null!==e.response&&void 0!==e.response){const t=on(e.response);if(null!=t&&"object"==typeof t){const e=t;if(null!==e.error&&void 0!==e.error)return"string"==typeof e.error?e.error:JSON.stringify(e.error);if(null!==e.message&&void 0!==e.message)return"string"==typeof e.message?e.message:JSON.stringify(e.message)}}return Ut(e)??"Unknown bundle transaction error"}async getBundlerTransactionResult(e){try{if(!or(e))throw Ht("transactionId","Transaction ID");let t;this.logger.debug("🔍 Checking bundler transaction result:",e);try{t=await ln(()=>this.http.get(`${this.bundleEndpoint}?id=${e}`),{errorContext:"Failed to get bundler transaction result",logger:this.logger})}catch(e){return{success:!1,error:this.formatErrorMessage(e)}}return null==t?{success:!1,error:"No response from bundler transaction query"}:(this.logger.debug("📊 Bundler transaction result:",t),{success:!0,data:t})}catch(e){if(e instanceof kt)return{success:!1,error:Ut(e)};throw e}}async cancelTransaction(e){try{if(!or(e))throw Ht("transactionId","Transaction ID");let t;this.logger.debug("🚫 Cancelling transaction:",e);try{t=await ln(()=>this.http.delete(`${this.bundleEndpoint}/${e}`),{errorContext:"Failed to cancel transaction",logger:this.logger})}catch(e){return{success:!1,error:this.formatErrorMessage(e)}}return null==t?{success:!1,error:"No response from transaction cancellation"}:(this.logger.debug("🗑️ Transaction cancellation response:",t),{success:!0,data:t})}catch(e){if(e instanceof kt)return{success:!1,error:Ut(e)};throw e}}async getHealthStatus(){this.logger.debug("🏥 Checking bundle service health");try{const e=await ln(()=>this.http.get(`${this.bundleEndpoint}/health`),{errorContext:"Bundle service health check failed",logger:this.logger});return null==e?{success:!1,error:"No response from bundle service health check"}:(this.logger.debug("💚 Bundle service health:",e),{success:!0,data:e})}catch(e){return{success:!1,error:this.formatErrorMessage(e)}}}async buyToken(e){this.ensureTradingServicesAvailable();const{tokenName:t,amount:n,type:r,expectedAmount:s}=e,{effectiveSlippageFactor:i,effectiveMaxFee:o,vaultAddress:a}=await this.prepareTradingOperation(t,e.maxAcceptableReverseBondingCurveFee,e.maxAcceptableReverseBondingCurveFeeSlippageFactor,e.slippageToleranceFactor);if("native"===r){if(null==s||""===s)throw new kt("expectedAmount is required for native buy operations. Use getBuyTokenAmount() first to calculate expected tokens.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=ba(s,i,"buy-native");this.logger.debug("BuyNative slippage applied:",{originalExpectedTokens:s,slippageFactor:i,adjustedMinTokens:e});const t=new Sa.BuyNativeDto(a,n,e,{maxAcceptableReverseBondingCurveFee:o});return await this.executeBundleTransaction(t,"BuyWithNative",a)}{if(null==s||""===s)throw new kt("expectedAmount is required for exact buy operations. Use getBuyTokenAmount() first to calculate expected GALA cost.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=ba(s,i,"buy-exact");this.logger.debug("BuyExact slippage applied:",{originalExpectedGalaCost:s,slippageFactor:i,adjustedMaxGalaCost:e});const t=new Sa.BuyExactDto(a,n,e,{maxAcceptableReverseBondingCurveFee:o});return await this.executeBundleTransaction(t,"BuyExactToken",a)}}async sellToken(e){this.ensureTradingServicesAvailable();const{tokenName:t,amount:n,type:r,expectedAmount:s}=e,{effectiveSlippageFactor:i,effectiveMaxFee:o,vaultAddress:a}=await this.prepareTradingOperation(t,e.maxAcceptableReverseBondingCurveFee,e.maxAcceptableReverseBondingCurveFeeSlippageFactor,e.slippageToleranceFactor),c=async()=>void 0===e.maxAcceptableReverseBondingCurveFee?this.defaultSellFeeCeiling(e,a):o;if("exact"===r){if(null==s||""===s)throw new kt("expectedAmount is required for exact sell operations. Use getSellTokenAmount() first to calculate expected GALA.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=ba(s,i,"sell-exact");this.logger.debug("SellExact slippage applied:",{originalExpectedGala:s,slippageFactor:i,adjustedMinGala:e});const t={maxAcceptableReverseBondingCurveFee:await c()},r=new Sa.SellExactDto(a,n,e,t);return await this.executeBundleTransaction(r,"SellExactToken",a)}{if(null==s||""===s)throw new kt("expectedAmount is required for native sell operations. Use getSellTokenAmount() first to calculate tokens to sell.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=ba(s,i,"sell-native");this.logger.debug("SellNative slippage applied:",{originalExpectedTokensToSell:s,slippageFactor:i,adjustedMaxTokensToSell:e});const t={maxAcceptableReverseBondingCurveFee:await c()},r=new Sa.SellNativeDto(a,n,e,t);return await this.executeBundleTransaction(r,"SellWithNative",a)}}async prepareTradingOperation(e,t,n,r){const{effectiveSlippageFactor:s,effectiveMaxFee:i}=this.calculateEffectiveSlippage(t,n,r),o=await this.resolveTokenNameToVault(e);if(null==o)throw Kt(e);return{effectiveSlippageFactor:s,effectiveMaxFee:i,vaultAddress:o}}async defaultSellFeeCeiling(e,t){if(void 0===this.sellFeeCeiling)throw jt("Cannot quote the reverse bonding curve fee for this sell. Pass maxAcceptableReverseBondingCurveFee.","maxAcceptableReverseBondingCurveFee");return this.sellFeeCeiling({method:"exact"===e.type?"SellExactToken":"SellWithNative",vaultAddress:t,quantity:e.amount,tokenName:e.tokenName,feeSlippageFactor:e.maxAcceptableReverseBondingCurveFeeSlippageFactor??this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor})}calculateEffectiveSlippage(e,t,n){const r=n??this.defaultSlippageToleranceFactor,s=t??this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor;let i=e??"0";return null!=e&&(i=ba(e,s,"buy-exact"),this.logger.debug("Reverse bonding curve fee slippage applied:",{baseFee:e,slippageFactor:s,adjustedMaxFee:i})),{effectiveSlippageFactor:r,effectiveFeeSlippageFactor:s,effectiveMaxFee:i}}ensureTradingServicesAvailable(){if(!this.signer||!this.tokenKeyService)throw jt("Trading services not available. BundleService requires walletProvider and userAddress for trading operations.","walletProvider");if(null===this.userAddress||void 0===this.userAddress)throw Ht("userAddress","User address")}async executeBundleTransaction(e,t,n){this.ensureTradingServicesAvailable();try{e.uniqueKey=`galaswap-operation-${Date.now()}_${k().replace(/-/gu,"").substring(0,26)}`;const r=await this.signer.signObject(t,e),s=this.tokenKeyService.generateStringsInstructions(n),i={stringsInstructions:s,method:t,signedDto:r};this.logger.debug("📦 Bundle transaction data:",{method:t,stringsInstructions:s,dtoKeys:Object.keys(r)});const o=await this.submitTransaction(i);if(o.success){const e=on(o);if(null!=e)return this.logger.debug("✅ Bundle transaction submitted:",e),{success:!0,data:{transactionId:e,message:"Transaction submitted successfully. Monitor WebSocket for completion."}}}const a=o.error;throw new Mt("string"==typeof a?a:"Bundle transaction failed",void 0,"BUNDLE_FAILED")}catch(e){throw this.logger.error("❌ Bundle transaction error:",e),e}}async resolveTokenNameToVault(e){return await this.tokenResolver.resolveTokenToVault(e)}}class tc 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(At),t=this.extractData(e);return this.logger.debug("Fetched client feature flags",{flagCount:Object.keys(t.flags).length}),{flags:t.flags}}}!function(e){e.CHAT_MESSAGE="CHAT_MESSAGE",e.COMMENT="COMMENT",e.STREAM="STREAM",e.RECORDING="RECORDING"}(qa||(qa={})),function(e){e.INAPPROPRIATE_CONTENT="INAPPROPRIATE_CONTENT",e.SPAM="SPAM",e.HARASSMENT="HARASSMENT",e.SCAM="SCAM",e.OTHER="OTHER"}(za||(za={})),function(e){e.PENDING="PENDING",e.DISMISSED="DISMISSED",e.ACTIONED="ACTIONED"}(Xa||(Xa={})),function(e){e.DELETE_CONTENT="DELETE_CONTENT",e.BAN_USER="BAN_USER",e.DELETE_AND_BAN="DELETE_AND_BAN"}(Qa||(Qa={}));const nc={[za.INAPPROPRIATE_CONTENT]:"Inappropriate Content",[za.SPAM]:"Spam",[za.HARASSMENT]:"Harassment",[za.SCAM]:"Scam",[za.OTHER]:"Other"},rc={[Xa.PENDING]:"Pending",[Xa.DISMISSED]:"Dismissed",[Xa.ACTIONED]:"Actioned"},sc={[Qa.DELETE_CONTENT]:"Delete Content",[Qa.BAN_USER]:"Ban User",[Qa.DELETE_AND_BAN]:"Delete & Ban"},ic={[qa.CHAT_MESSAGE]:"Chat Message",[qa.COMMENT]:"Comment",[qa.STREAM]:"Stream",[qa.RECORDING]:"Recording"},oc=500,ac=dr(qa),cc=dr(za),lc=dr(Xa),dc=dr(Qa),uc=pr([{field:"id",type:"number"},{field:"tokenName",type:"string"},{field:"contentType",type:"string",validator:ac},{field:"contentId",type:"string"},{field:"reporterAddress",type:"string"},{field:"reportedUserAddress",type:"string"},{field:"status",type:"string",validator:lc}]),hc={TOKEN_NAME:Ir,TOKEN_NAME_FILTER:Dr,CONTENT_ID:Pr.CONTENT_ID,DETAILS:Pr.FLAG_DETAILS,PAGINATION:{MAX_LIMIT:Mr}};function gc(e,t,n="tokenName"){hr(e,n,t)}function mc(e){if(void 0!==e.contentType&&!ac(e.contentType))throw Wt("contentType",`one of: ${Object.values(qa).join(", ")}`,"Content type");if(void 0!==e.status&&!lc(e.status))throw Wt("status",`one of: ${Object.values(Xa).join(", ")}`);if(void 0!==e.reason&&!cc(e.reason))throw Wt("reason",`one of: ${Object.values(za).join(", ")}`);if(void 0!==e.reporterAddress&&!or(e.reporterAddress))throw Yt("reporterAddress","a non-empty string",typeof e.reporterAddress);if(void 0!==e.reporterAddress&&Gn(e.reporterAddress,"reporterAddress"),void 0!==e.reportedUserAddress&&!or(e.reportedUserAddress))throw Yt("reportedUserAddress","a non-empty string",typeof e.reportedUserAddress);void 0!==e.reportedUserAddress&&Gn(e.reportedUserAddress,"reportedUserAddress"),lr(0,void 0,hc.PAGINATION.MAX_LIMIT,e.pageSize)}class fc extends zo{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async createFlag(e){!function(e){if(gc(e.tokenName,hc.TOKEN_NAME),void 0===e.contentType)throw Ht("contentType","Content type");if(!ac(e.contentType))throw Wt("contentType",`one of: ${Object.values(qa).join(", ")}`,"Content type");if(!or(e.contentId))throw Ht("contentId","Content ID");if(e.contentId.length>hc.CONTENT_ID.MAX_LENGTH)throw Qt("contentId",hc.CONTENT_ID.MAX_LENGTH,e.contentId.length,"Content ID");if(!or(e.reportedUserAddress))throw Ht("reportedUserAddress","Reported user address");if(Gn(e.reportedUserAddress,"reportedUserAddress"),!(e.contentType!==qa.STREAM&&e.contentType!==qa.RECORDING||void 0!==e.reason&&null!==e.reason))throw Ht("reason","Reason");if(void 0!==e.reason&&!cc(e.reason))throw Wt("reason",`one of: ${Object.values(za).join(", ")}`,"Reason");if(void 0!==e.details&&!or(e.details))throw Yt("details","a non-empty string",typeof e.details);if(void 0!==e.details&&e.details.length>hc.DETAILS.MAX_LENGTH)throw Qt("details",hc.DETAILS.MAX_LENGTH,e.details.length)}(e);const t={tokenName:e.tokenName,contentType:e.contentType,contentId:e.contentId,reportedUserAddress:_n(e.reportedUserAddress,"reportedUserAddress")};null!==e.reason&&void 0!==e.reason&&(t.reason=e.reason),null!==e.details&&void 0!==e.details&&(t.details=e.details);const n=await this.http.post(ye.CREATE,t,this.getMultiAuthHeaders());return{flag:this.extractData(n).flag}}async listFlags(e){return function(e){gc(e.tokenName,hc.TOKEN_NAME_FILTER),mc(e)}(e),this.fetchFlagList(e)}async listGlobalFlags(e={}){return function(e){void 0!==e.tokenName&&gc(e.tokenName,hc.TOKEN_NAME_FILTER),mc(e)}(e),this.fetchFlagList(e)}async dismissFlag(e){!function(e){if(void 0===e.flagId||null===e.flagId)throw Ht("flagId","Flag ID");try{Jn(e.flagId,"flagId")}catch{throw Wt("flagId","a positive integer","Flag ID")}}(e);const t=ye.DISMISS.replace(":id",e.flagId.toString()),n=await this.http.post(t,{},this.getMultiAuthHeaders());return{flag:this.extractData(n).flag}}async actionFlag(e){!function(e){if(void 0===e.flagId||null===e.flagId)throw Ht("flagId","Flag ID");try{Jn(e.flagId,"flagId")}catch{throw Wt("flagId","a positive integer","Flag ID")}if(void 0===e.action)throw Ht("action","Action");if(!dc(e.action))throw Wt("action",`one of: ${Object.values(Qa).join(", ")}`,"Action")}(e);const t=ye.ACTION.replace(":id",e.flagId.toString()),n=await this.http.post(t,{action:e.action},this.getMultiAuthHeaders());return{flag:this.extractData(n).flag}}async fetchFlagList(e){const t=Ho(e,Mr);jo(t,e,["tokenName","contentType","status","reason","reporterAddress","reportedUserAddress"]);for(const e of["reporterAddress","reportedUserAddress"]){const n=t[e];void 0!==n&&(t[e]=_n(n,e))}const n=await this.http.get(ye.LIST,t,this.getMultiAuthHeaders()),r=this.extractData(n);return{items:r.flags,pageInfo:r.pageInfo}}}const pc=["heart","fire","laugh","wow","thumbs_up"],Ec={heart:"❤️",fire:"🔥",laugh:"😂",wow:"😮",thumbs_up:"👍"};class Ac extends zo{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}validateMessageId(e){if(!or(e))throw Ht("messageId","Message ID");if(Yn(e,xr.CONTENT_REACTION.MAX_LENGTH,"messageId"),!xr.CONTENT_REACTION.PATTERN.test(e))throw Wt("messageId","msg-{timestamp}-{uuid} or chat-{timestamp}-{uuid} format","Message ID")}validateReactionType(e){if(!or(e))throw Ht("reactionType","Reaction type");if(!pc.includes(e))throw Wt("reactionType",`one of: ${pc.join(", ")}`,"Reaction type")}async addContentReaction(e){this.validateMessageId(e.messageId),this.validateReactionType(e.reactionType);const t=ze,n={messageId:e.messageId,reactionType:e.reactionType},r=await this.http.post(t,n,this.getMultiAuthHeaders()),s=this.extractData(r),{created:i,...o}=s;return{data:o,created:i}}async removeContentReaction(e){this.validateMessageId(e.messageId),this.validateReactionType(e.reactionType);const t=`${Xe}?${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 vc="Token name is required and must be a string";const Tc="GALA|Unit|none|none";class yc extends wr{constructor(e,t,n,r=!1){super(r),this.dexBackendHttp=e,this.cache=t,this.fetchTokenDetails=n}async fetchLaunchpadTokenSpotPrice(e,t,n){if(!or(e))throw new kt(vc,"tokenName",wt.REQUIRED);let r;if(void 0!==n)try{this.logger.debug(`Checking graduation status for token: ${e}`);const t=await n(e);!0===t.isGraduated&&(r=Ka(t.sellingToken))}catch(t){this.logger.debug(`Could not determine graduation status for ${e}, falling back to bonding curve: ${Ut(t)}`)}if(void 0!==r)return this.logger.debug(`Token ${e} is graduated, using its swap backend price`),this.fetchMarketUsdPrice(r);try{this.logger.debug(`Using bonding curve calculation for token: ${e}`);const n=await t({tokenName:e,amount:"1",type:"native"}),r=await this.fetchMarketUsdPrice(Tc),s=Wn(n.amount,0)/1e18;if(s<=0)throw new kt(`Invalid token amount calculation: ${s}`,"amount","INVALID_CALCULATION");return{symbol:fn(e),price:r.price/s}}catch(t){throw Vt(`Failed to calculate launchpad token spot price for ${e}: ${Ut(t)}`,void 0,Lt(t)?t:void 0)}}async resolveAuthoritativeSymbol(e){if(e===Tc)return"GALA";const t=this.cache?.getByTokenId(e);if(null!=t?.symbol&&""!==t.symbol)return t.symbol;let n;this.logger.debug(`Symbol cache miss for ${e}, reading the token class`);try{if(void 0===this.fetchTokenDetails)throw Vt("GalaChainService not available for token metadata fetch",500);n=(await this.fetchTokenDetails(e)).symbol}catch(t){throw Vt(`Could not resolve the symbol for ${e} from the token class, and a symbol cannot be derived from the class key: ${Ut(t)}`)}if(""===n)throw Vt(`Token class for ${e} has no symbol`);return this.cache?.setByTokenId(e,{symbol:n}),n}async fetchMarketUsdPrice(e){try{const t=function(e){if(!or(e))throw new Error("Invalid token format: token must be a non-empty string");return e.replace(/\|/g,"$")}(e);if(this.logger.debug(`Fetching swap backend price for token: ${t}`),void 0===this.dexBackendHttp)throw Vt("DEX Backend API client not configured");const n=await this.resolveAuthoritativeSymbol(e),r=await this.dexBackendHttp.request({method:"GET",url:"/market/price",params:{assetIds:t}}),s=null!==r&&"object"==typeof r?r:{},i=Object.keys(s).find(e=>e.toUpperCase()===n.toUpperCase()),o=void 0!==i?s[i]:1===Object.keys(s).length?Object.values(s)[0]:void 0,a=o?.price;if("number"!=typeof a||!Number.isFinite(a))throw new kt(`Invalid price response: no market price for ${t}`,"data","INVALID_RESPONSE");return this.logger.debug(`Swap backend price for ${n}: $${a}`),{symbol:n,price:a}}catch(e){if(e instanceof kt)throw e;throw Vt(`Failed to fetch DEX spot price: ${Ut(e)}`)}}}const Sc={BATCH_SIZE:20,FLUSH_INTERVAL_MS:3e3,MAX_QUEUE_SIZE:1e3,FLUSH_ON_PAGE_HIDE:!0,FLUSH_ON_PAGE_UNLOAD:!0,DEBUG:!1},bc={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 Nc{constructor(e,t={}){this.eventBuffer=[],this.flushTimer=null,this.isShuttingDown=!1,this.totalQueued=0,this.totalFlushed=0,this.totalDropped=0,this.handleVisibilityChange=()=>{"hidden"===document.visibilityState&&this.eventBuffer.length>0&&this.flushWithBeacon()},this.handleBeforeUnload=()=>{this.eventBuffer.length>0&&this.flushWithBeacon()},this.httpClient=e,this.logger=new En({debug:t.debug??!1,context:"EventsBatcherService"}),this.config={batchSize:t.batchSize??Sc.BATCH_SIZE,flushIntervalMs:t.flushIntervalMs??Sc.FLUSH_INTERVAL_MS,maxQueueSize:t.maxQueueSize??Sc.MAX_QUEUE_SIZE,flushOnPageHide:t.flushOnPageHide??Sc.FLUSH_ON_PAGE_HIDE,flushOnPageUnload:t.flushOnPageUnload??Sc.FLUSH_ON_PAGE_UNLOAD,debug:t.debug??Sc.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:kn(n.userAddress,"userAddress")},...void 0!==n?.tokenName&&""!==n.tokenName&&{tokenName:n.tokenName},...void 0!==n?.sessionId&&""!==n.sessionId&&{sessionId:n.sessionId}};this.buffer(r),n?.immediate&&this.scheduleFlush(0)}async flush(){if(0===this.eventBuffer.length)return;this.cancelFlushTimer();const e=this.eventBuffer.splice(0);this.logger.debug(`Flushing ${e.length} events`);try{const t=await this.submitEvents(e);this.totalFlushed+=t.accepted,this.lastFlushTime=Date.now(),this.lastError=void 0,this.logger.debug(`Flush successful, accepted ${t.accepted} events`)}catch(t){throw this.eventBuffer.unshift(...e),this.lastError=t instanceof Error?t.message:String(t),this.logger.error(`Flush failed: ${this.lastError}`),t}}getStats(){const e={bufferedCount:this.eventBuffer.length,totalQueued:this.totalQueued,totalFlushed:this.totalFlushed,totalDropped:this.totalDropped};return void 0!==this.lastFlushTime&&(e.lastFlushTime=this.lastFlushTime),void 0!==this.lastError&&(e.lastError=this.lastError),e}configure(e){void 0!==e.batchSize&&(this.config.batchSize=e.batchSize),void 0!==e.flushIntervalMs&&(this.config.flushIntervalMs=e.flushIntervalMs),void 0!==e.maxQueueSize&&(this.config.maxQueueSize=e.maxQueueSize),void 0!==e.flushOnPageHide&&(this.config.flushOnPageHide=e.flushOnPageHide),void 0!==e.flushOnPageUnload&&(this.config.flushOnPageUnload=e.flushOnPageUnload)}async shutdown(e=5e3){if(this.isShuttingDown=!0,this.removePageLifecycleListeners(),0!==this.eventBuffer.length)try{await Promise.race([this.flush(),new Promise((t,n)=>setTimeout(()=>n(new Error("Flush timeout during shutdown")),e))])}catch(e){this.logger.error(`Shutdown flush failed: ${e instanceof Error?e.message:String(e)}`)}}buffer(e){this.eventBuffer.length>=this.config.maxQueueSize&&(this.eventBuffer.shift(),this.totalDropped++,this.logger.warn("Event buffer full, dropped oldest event")),this.eventBuffer.push(e),this.totalQueued++,this.eventBuffer.length>=this.config.batchSize?this.scheduleFlush(0):this.scheduleFlush(this.config.flushIntervalMs)}scheduleFlush(e){null===this.flushTimer&&(this.flushTimer=setTimeout(()=>{this.flushTimer=null,this.flush().catch(e=>{this.logger.error(`Scheduled flush failed: ${e instanceof Error?e.message:String(e)}`)})},e))}cancelFlushTimer(){null!==this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null)}async submitEvents(e){return await this.httpClient.post("/v1/events",{events:e})}setupPageLifecycleListeners(){"undefined"!=typeof document&&(this.config.flushOnPageHide&&document.addEventListener("visibilitychange",this.handleVisibilityChange),this.config.flushOnPageUnload&&window.addEventListener("beforeunload",this.handleBeforeUnload))}removePageLifecycleListeners(){"undefined"!=typeof document&&(this.config.flushOnPageHide&&document.removeEventListener("visibilitychange",this.handleVisibilityChange),this.config.flushOnPageUnload&&window.removeEventListener("beforeunload",this.handleBeforeUnload))}flushWithBeacon(){if("undefined"==typeof navigator||!navigator.sendBeacon)return;const e=this.eventBuffer.splice(0),t=JSON.stringify({events:e});try{const n=this.getBaseUrl();navigator.sendBeacon(`${n}/v1/events`,t)?(this.totalFlushed+=e.length,this.lastFlushTime=Date.now()):(this.eventBuffer.unshift(...e),this.logger.warn("sendBeacon returned false, events re-buffered"))}catch(t){this.eventBuffer.unshift(...e),this.logger.error(`sendBeacon failed: ${t instanceof Error?t.message:String(t)}`)}}getBaseUrl(){const e=this.httpClient.config;return e?.baseUrl??""}}const wc=["createdAt","eventType","userAddress"],kc=["last_hour","today","yesterday","last_7_days","last_30_days","custom"],_c=["sdk","frontend","backend","mcp"];function Ic(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Dc(e){return"number"==typeof e&&Number.isFinite(e)}function Cc(e){return Ic(e)&&Dc(e.id)&&"string"==typeof e.eventType&&Ic(e.payload)&&"string"==typeof e.createdAt&&"string"==typeof e.updatedAt}function Rc(e,t,n){if(!t.some(t=>t===e))throw new kt(`${n} must be one of: ${t.join(", ")}`,n,wt.INVALID_VALUE)}class Oc extends zo{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async getEventStats(){return function(e){if(!(Ic(e)&&Dc(e.totalEvents)&&Dc(e.todayEvents)&&Dc(e.uniqueUsers)&&Dc(e.uniqueTokens)&&Ic(e.eventsByType)))throw Vt("Malformed event statistics response");const t={};for(const[n,r]of Object.entries(e.eventsByType)){if(!Dc(r))throw Vt("Malformed event statistics response");t[n]=r}return{totalEvents:e.totalEvents,todayEvents:e.todayEvents,uniqueUsers:e.uniqueUsers,uniqueTokens:e.uniqueTokens,eventsByType:t}}(await this.http.get(it,void 0,this.getDualAuthHeaders()))}async queryEvents(e={}){!function(e){if(void 0!==e.limit&&(!Number.isInteger(e.limit)||e.limit<1||e.limit>100))throw new kt("limit must be an integer from 1 to 100","limit",wt.INVALID_VALUE);if(void 0!==e.page&&(!Number.isInteger(e.page)||e.page<1))throw new kt("page must be a positive integer","page",wt.INVALID_VALUE);void 0!==e.sortBy&&Rc(e.sortBy,wc,"sortBy"),void 0!==e.sortOrder&&Rc(e.sortOrder,["asc","desc"],"sortOrder"),void 0!==e.timePreset&&Rc(e.timePreset,kc,"timePreset"),void 0!==e.source&&Rc(e.source,_c,"source")}(e);const t={},n=new URLSearchParams;for(const[r,s]of Object.entries(e))if(void 0!==s&&("string"!=typeof s||""!==s)){if(Array.isArray(s)){const e=s.map(String);if(0===e.length)continue;for(const t of 1===e.length?[...e,...e]:e)n.append(r,t);continue}t[r]="userAddress"===r&&"string"==typeof s?kn(s,"userAddress"):s}const r=n.toString(),s=""===r?st:`${st}?${r}`;return function(e){if(!Ic(e)||!Array.isArray(e.data)||!Ic(e.pagination))throw Vt("Malformed events response");const t=e.pagination,n=e.data;if(!(Dc(t.page)&&Dc(t.limit)&&Dc(t.total)&&Dc(t.totalPages)&&n.every(Cc)))throw Vt("Malformed events response");return{data:n,pagination:{page:t.page,limit:t.limit,total:t.total,totalPages:t.totalPages}}}(await this.http.get(s,t,this.getDualAuthHeaders()))}}function Mc(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 Lc=new Set(["GATEWAY_READ_REJECTED","GATEWAY_READ_RESPONSE_INVALID"]);class Uc extends Nr{constructor(e,t=!1){super(e,t)}async fetchGalaBalance(e){return this.fetchTokenBalance(e)}async fetchTokenBalance(e,n=!1){const r=wn(e.owner,"owner");try{const{requestor:t}=Mc(async(e,t)=>({data:await this.http.post(e,t)})),s=new d({gatewayBaseUrl:"",httpRequestor:t,requestTimeoutMs:1/0}),{collection:i,category:o,type:a,additionalKey:c}=e,l=await s.fetchTokenBalance({owner:r,tokenClassKey:{collection:i,category:o,type:a,additionalKey:c},includeExpiredHolds:n});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:Ka(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(t(e)&&Lc.has(e.code))return null;throw Vt(`Failed to fetch token balance from GalaChain: ${Ut(e)}`,void 0,Lt(e)?e:void 0)}}}function Fc(e){if(null==e||"object"!=typeof e)return!1;const t=e;return or(t.amount)&&(void 0!==t.tokenId||or(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 Pc(e){if(null==e||"object"!=typeof e)return!1;const t=e;return or(t.amount)&&(void 0!==t.tokenId||or(t.tokenName))&&(void 0===t.name||"string"==typeof t.name)}function xc(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every(Fc)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}function Bc(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every(Pc)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}const Gc=100,$c=100;var Kc,Hc;!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"}(Kc||(Kc={}));class Wc 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"}(Hc||(Hc={}));class Vc extends Error{constructor(e,t,n){super(e),this.type=t,this.details=n,this.name="TransferError"}}function jc(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 qc(e,t,n,r="[DEBUG] Token resolution (launchpad)"){const s=await t.resolveTokenToVault(e);if(null!==s){const t=Va(s);return n.debug(r,{tokenName:e,vaultAddress:s,tokenInstance:{collection:t.collection,category:t.category,type:t.type,instance:t.instance}}),t}throw new kt(`Token "${e}" is not a launchpad token (no vault address found), and a token class key cannot be derived from a name. Pass an explicit tokenId (collection|category|type|additionalKey) for standard GalaChain tokens.`,"tokenName","TOKEN_CLASS_KEY_NOT_DERIVABLE")}class zc 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 Fa(t.privateKey):void 0}writeIdentity(){return void 0!==this.wallet&&void 0!==this.nativeSigner?{signer:this.nativeSigner,walletAddress:Mn(this.wallet.address)}:this.writer}}function Xc(e,t){const{collection:n,category:r,type:s,additionalKey:i,instance:o}=e;return{tokenClassKey:{collection:n,category:r,type:s,additionalKey:i},instance:o,quantity:t}}const Qc=new Set(["GATEWAY_WRITE_REJECTED","GATEWAY_RESPONSE_INVALID","GATEWAY_HTTP_ERROR"]);function Yc(e,{signer:t,walletAddress:n}){const{requestor:r,answer:s}=Mc((t,n)=>e.postWithMeta(t,n));return{writes:new u({gatewayBaseUrl:"",signer:t,walletAddress:n,httpRequestor:r,requestTimeoutMs:1/0,uniqueKeyPrefix:"galaconnect-operation-"}),answer:s}}async function Jc(e,n,r){let s;try{s=await n(e.writes)}catch(n){throw function(e){return t(e)&&Qc.has(e.code)}(n)&&r(e.answer(),void 0),n}return r(e.answer(),s)}function Zc(e){return void 0===e||""===e?{}:{uniqueKey:e}}const el=100,tl=100;class nl extends zc{async lockTokens(e){this.validateLockTokensData(e);const t=this.writeIdentity();if(void 0===t)throw new Wc("Wallet required for token lock operations",Kc.WALLET_REQUIRED);return So(async()=>{const n=Yc(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=Mn(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(Xc(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?Mn(t.lockAuthority):o})}return Jc(n,t=>t.lockTokens({tokens:i,lockAuthority:o,...void 0!==c?.expires&&{expires:c.expires},...void 0!==l?.name&&{name:l.name},...Zc(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 Wc("Wallet required for token unlock operations",Kc.WALLET_REQUIRED);return So(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(Xc(e,t.amount)),n.push({tokenClassKey:{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey},quantity:t.amount})}return Jc(Yc(this.http,t),t=>t.unlockTokens({tokens:r,...void 0!==s?.name&&{name:s.name},...Zc(e.uniqueKey)}),(e,t)=>(this.assertLockAnswer(e,"Token unlock failed"),this.extractUnlockResult(e,t,n)))},"Token unlock failed",this.logger,t=>{throw this.handleLockError(t,"Token unlock failed",e)})}assertLockAnswer(e,t){try{Bt(e,t)}catch(t){const n=function(e){if(null==e||"object"!=typeof e)return"";const t=e.Message;return"string"==typeof t&&t.trim().length>0?` - ${t}`:""}(e);throw new Wc(`${Ut(t)}${n}`,Kc.NETWORK_ERROR)}}validateSharedTokenEntry(e,t,n){if(void 0===e.tokenId&&void 0===e.tokenName)throw new Wc("Must provide either tokenId or tokenName for token identification",Kc.TOKEN_NOT_FOUND);if(void 0!==e.tokenName)try{fr(e.tokenName,"tokenName",Cr)}catch{throw new Wc("Invalid token name format",Kc.TOKEN_NOT_FOUND,{tokenName:e.tokenName})}try{to(Qi(e.amount))}catch{throw new Wc(Wt(t,"a positive number",n).message,Kc.INVALID_AMOUNT,{amount:e.amount})}}validateLockTokensData(e){if(!xc(e))throw new Wc("Invalid lock data: missing required fields",Kc.VALIDATION_ERROR);if(e.tokens.length>el)throw new Wc(`Batch size exceeds maximum limit of ${el} tokens per lock operation`,Kc.VALIDATION_ERROR);for(const t of e.tokens){if(this.validateSharedTokenEntry(t,"lockAmount","Lock amount"),void 0!==t.lockAuthority&&!Fn(t.lockAuthority))throw new Wc("Invalid lock authority address format",Kc.VALIDATION_ERROR,{lockAuthority:t.lockAuthority});if(void 0!==t.expires)try{Jn(t.expires,"expires")}catch{throw new Wc(Wt("expires","a positive integer (epoch milliseconds)","Expires").message,Kc.VALIDATION_ERROR)}}}validateUnlockTokensData(e){if(!Bc(e))throw new Wc("Invalid unlock data: missing required fields",Kc.VALIDATION_ERROR);if(e.tokens.length>tl)throw new Wc(`Batch size exceeds maximum limit of ${tl} tokens per unlock operation`,Kc.VALIDATION_ERROR);for(const t of e.tokens)this.validateSharedTokenEntry(t,"unlockAmount","Unlock amount")}transactionIdOf(e,t){const n=Array.isArray(e.Data)?e.Data[0]:void 0;return t?.transactionId??n?.transactionId??n?.txnId??n?.TxnId??n?.id??void 0}extractLockResult(e,t,n){const r=this.transactionIdOf(e,t),s=t?.blockNumber;return{...void 0!==r&&{transactionId:r},...void 0!==s&&{blockNumber:s},locked:n}}extractUnlockResult(e,t,n){const r=this.transactionIdOf(e,t),s=t?.blockNumber;return{...void 0!==r&&{transactionId:r},...void 0!==s&&{blockNumber:s},unlocked:n}}handleLockError(e,n,r){if(e instanceof Wc)return e;if(t(e)&&"pre_send"===e.phase)return new Wc(`${n}: ${e.message}`,"SIGNING_FAILED"===(s=e.code)?Kc.SIGNATURE_FAILED:"INVALID_TOKEN_REFERENCE"===s?Kc.TOKEN_NOT_FOUND:"INVALID_QUANTITY"===s?Kc.INVALID_AMOUNT:Kc.VALIDATION_ERROR,jc(r));var s;let i=n,o=Kc.NETWORK_ERROR;if(xt(e)){const t=e.response?.data;if("object"==typeof t&&null!==t){const e=t.Message;"string"==typeof e&&e.length>0&&(i=`${n}: ${e}`);const r="string"==typeof e?e.toLowerCase():"";r.includes("insufficient")||r.includes("balance")?o=Kc.INSUFFICIENT_BALANCE:r.includes("lock")&&r.includes("not found")?o=Kc.LOCK_NOT_FOUND:r.includes("not found")||r.includes("token")?o=Kc.TOKEN_NOT_FOUND:r.includes("authority")?o=Kc.NOT_LOCK_AUTHORITY:r.includes("expired")&&(o=Kc.LOCK_EXPIRED)}}else Lt(e)&&(i=`${n}: ${Ut(e)}`);return new Wc(i,o,jc(r))}async resolveTokenInstance(e){return So(async()=>qc(e,this.tokenResolver,this.logger),`Failed to resolve token '${e}'`,this.logger,t=>{if(t instanceof Vc)throw new Wc(Ut(t),Kc.TOKEN_NOT_FOUND);throw new Wc(`Failed to resolve token '${e}': ${Ut(t)}`,Kc.TOKEN_NOT_FOUND,{tokenName:e})})}async resolveTokenEntry(e){if(void 0!==e.tokenId){const t=Ha(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 Wc("Must provide either tokenId or tokenName for token identification",Kc.TOKEN_NOT_FOUND)}}const rl=new Set(["GATEWAY_READ_REJECTED","GATEWAY_READ_RESPONSE_INVALID","TOKEN_CLASS_NOT_FOUND"]);function sl(e){const t=e?.Data;return Array.isArray(t)?t:void 0}class il extends Nr{constructor(e,t=!1,n){super(e,t),this.publicAxios=n}async fetchTokenClassFromChain(e){try{const t="string"==typeof e?Ha(e):e,{collection:n,category:r,type:s,additionalKey:i}=t,o={collection:n,category:r,type:s,additionalKey:i},a="Failed to fetch token class from GalaChain";return await this.readPublic(e=>e.fetchTokenClass(o),e=>{if(Bt(e,a),void 0===sl(e)?.[0])throw Vt(`Token not found on GalaChain: ${Ka(o)}`,404)},()=>Vt(`Token not found on GalaChain: ${Ka(o)}`,404))}catch(e){return this.handleTokenServiceError(e,"Token not found on GalaChain","Failed to fetch token class from GalaChain")}}async fetchTokenClassesWithSupply(e){try{if(null==e||0===e.length)throw Ht("tokenClasses","Token classes array");return await this.readPublic(t=>t.fetchTokenClassesWithSupply(e),e=>{if(Bt(e,"Failed to fetch token classes with supply from GalaChain"),0===(sl(e)?.length??0))throw Vt("No token supply data found for requested token classes",404)},void 0)}catch(e){return this.handleTokenServiceError(e,"Token supply data not found on GalaChain","Failed to fetch token classes with supply from GalaChain")}}async readPublic(e,n,r){if(!this.publicAxios)throw Ht("publicAxios","Public Axios instance");const s=this.publicAxios,{requestor:i,answer:o}=Mc(async(e,t)=>{const n=await s.post(e,t);return{data:n.data,status:n.status}});try{return await e(new d({gatewayBaseUrl:"",httpRequestor:i,requestTimeoutMs:1/0}))}catch(e){if(t(e)&&rl.has(e.code)&&(n(o()),"TOKEN_CLASS_NOT_FOUND"===e.code&&void 0!==r))throw r();throw e}}handleTokenServiceError(e,t,n){if(e instanceof kt)throw e;if(xt(e)&&404===e.response?.status)throw Vt(t,404,Lt(e)?e:void 0);if(Lt(e)&&"Error"===e.name&&Ut(e).includes("status indicates failure"))throw Vt(Ut(e),400,Lt(e)?e:void 0);const r=Ut(e);if(r.includes("Token not found")){if(e instanceof Error)throw e;throw new Error(r)}throw Vt(`${n}: ${r}`,void 0,Lt(e)?e:void 0)}}function ol(e){if(null==e||"object"!=typeof e)return!1;const t=e;return or(t.amount)&&(void 0!==t.tokenId||or(t.tokenName))}function al(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every(ol)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}const cl=50;var ll;!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"}(ll||(ll={}));class dl extends Error{constructor(e,t,n){super(e),this.type=t,this.details=n,this.name="BurnError"}}const ul={validateAmount(e){const t=Qi(e);try{ro(t,"amount")}catch(t){throw new Vc(t.message,Hc.INVALID_AMOUNT,{amount:e})}},validateUniqueKey(e){if(!cr(e)&&or(e)){if(e.length>$r.MAX_LENGTH)throw new kt(`Unique key too long. Maximum length: ${$r.MAX_LENGTH}`);if(!$r.PATTERN.test(e))throw new Vc('Invalid unique key format. Must start with "galaswap-operation-" or "galaconnect-operation-"',Hc.INVALID_AMOUNT,{uniqueKey:e})}}},hl="gala-transfer-successful",gl="token-transfer-successful",ml="token-locked-successfully",fl="token-unlocked-successfully",pl="transfer-successful-no-id",El=50;class Al extends zc{async transferGala(e){this.validateTransferGalaData(e);const t=this.writeIdentity();if(void 0===t)throw new Vc("Wallet required for GALA transfer operations",Hc.WALLET_REQUIRED);try{const n=Mn(e.recipientAddress),r=Yc(this.http,t);return await Jc(r,t=>t.transferGala({to:n,quantity:e.amount,...Zc(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 Vc("Wallet required for token transfer operations",Hc.WALLET_REQUIRED);try{const n=Mn(e.to),r=await this.tokenInstanceOf(e.tokenId,e.tokenName,()=>new Vc("Must provide either tokenId or tokenName for token identification",Hc.TOKEN_NOT_FOUND)),s=Yc(this.http,t);return await Jc(s,t=>t.transferToken({to:n,...Xc(r,e.amount),...Zc(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 Vc)throw t;throw new Vc(`Failed to resolve token class key for '${e}': ${Ut(t)}`,Hc.TOKEN_NOT_FOUND,{tokenName:e})}}async burnTokens(e){this.validateBurnTokensData(e);const t=this.writeIdentity();if(void 0===t)throw new dl("Wallet required for token burn operations",ll.WALLET_REQUIRED);try{const n=[];for(const t of e.tokens){const e=await this.tokenInstanceOf(t.tokenId,t.tokenName,()=>new dl("Must provide either tokenId or tokenName for token identification",ll.TOKEN_NOT_FOUND));n.push(Xc(e,t.amount))}const r=Yc(this.http,t);return await Jc(r,t=>t.burnTokens({tokens:n,...Zc(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 or(t.recipientAddress)&&or(t.amount)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)}(e))throw new kt("Invalid GALA transfer data: missing required fields");if(!Fn(e.recipientAddress))throw new Vc("Invalid recipient address format",Hc.INVALID_RECIPIENT,{recipientAddress:e.recipientAddress});ul.validateAmount(e.amount),ul.validateUniqueKey(e.uniqueKey)}validateTransferTokenData(e){if(!function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return or(t.to)&&or(t.amount)&&(void 0!==t.tokenId||or(t.tokenName))&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)}(e))throw new kt("Invalid token transfer data: missing required fields");if(!Fn(e.to))throw new Vc("Invalid recipient address format",Hc.INVALID_RECIPIENT,{recipientAddress:e.to});if(!(null!==e.tokenId&&void 0!==e.tokenId||null!==e.tokenName&&void 0!==e.tokenName))throw new Vc("Must provide either tokenId or tokenName for token identification",Hc.TOKEN_NOT_FOUND);if(null!==e.tokenName&&void 0!==e.tokenName)try{fr(e.tokenName,"tokenName",Cr)}catch{throw new Vc("Invalid token name format",Hc.TOKEN_NOT_FOUND,{tokenName:e.tokenName})}ul.validateAmount(e.amount),ul.validateUniqueKey(e.uniqueKey)}validateBurnTokensData(e){if(!al(e))throw new dl("Invalid burn data: missing required fields",ll.VALIDATION_ERROR);if(e.tokens.length>El)throw new dl(`Batch size exceeds maximum limit of ${El} tokens per burn operation`,ll.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 dl("Must provide either tokenId or tokenName for token identification",ll.TOKEN_NOT_FOUND);const e=Qi(t.amount);try{to(e)}catch{throw new dl("Burn amount must be a positive number",ll.INVALID_AMOUNT,{amount:t.amount})}}}async tokenInstanceOf(e,t,n){if(null!=e){const t=Ha(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 qc(e,this.tokenResolver,this.logger,`[DEBUG] Token resolution for '${e}' (launchpad):`)}catch(t){if(t instanceof Vc)throw t;throw new Vc(`Failed to resolve token '${e}': ${Ut(t)}`,Hc.TOKEN_NOT_FOUND,{tokenName:e})}}extractTransferResult(e,t,n){if(null==e)throw new Vc("No response from GalaChain transfer service",Hc.NETWORK_ERROR);const r=t?.blockNumber,s="object"==typeof e&&"Status"in e;s&&Bt(e,"Extract transaction ID");const i=s&&"Data"in e,o=t?.transactionId;if(void 0!==o)return{transactionId:o,...void 0!==r?{blockNumber:r}:{}};if(i){const t=e;if(Array.isArray(t.Data)){for(const e of t.Data)if(null!=e&&"object"==typeof e){const t=e;for(const e of["transactionId","txnId","TxnId","id","txId"]){const n=t[e];if("string"==typeof n&&n.length>0)return{transactionId:n,...void 0!==r?{blockNumber:r}:{}}}}let e=pl;if(t.Data.length>0)switch(n){case"gala":e=hl;break;case"token":e=gl;break;case"lock":e=ml;break;case"unlock":e=fl}return{transactionId:e,...void 0!==r?{blockNumber:r}:{}}}}throw new Vc("Operation succeeded but transaction ID could not be extracted (missing x-transaction-id header and body fields)",Hc.NETWORK_ERROR)}burnResultOf(e,t){if(null==e)throw new dl("No response from GalaChain burn service",ll.NETWORK_ERROR);try{Bt(e,"Token burn operation")}catch(e){throw new Rt(Ut(e),500)}return this.extractBurnResult(e,t)}extractBurnResult(e,t){const n=[];if(null!==e.Data&&void 0!==e.Data&&Array.isArray(e.Data))for(const t of e.Data)n.push({collection:t.collection??"",category:t.category??"",type:t.type??"",additionalKey:t.additionalKey??"",instance:t.instance??"0",quantity:t.quantity??"0",burnedBy:t.burnedBy??""});const r=Array.isArray(e.Data)?e.Data[0]:void 0,s=t?.transactionId??r?.transactionId??r?.txnId??r?.TxnId??r?.id??void 0,i=t?.blockNumber;return{...void 0!==s&&{transactionId:s},...void 0!==i&&{blockNumber:i},burned:n}}handleTransferError(e,n,r){if(e instanceof Vc)return e;if(e instanceof kt)return new Vc(Ut(e),Hc.INVALID_AMOUNT);if(t(e)&&"pre_send"===e.phase)return new Vc(e.message,"SIGNING_FAILED"===(s=e.code)?Hc.SIGNATURE_FAILED:"INVALID_WALLET_ADDRESS"===s?Hc.INVALID_RECIPIENT:"INVALID_TOKEN_REFERENCE"===s?Hc.TOKEN_NOT_FOUND:Hc.INVALID_AMOUNT);var s;if(xt(e)&&e.response){const t=e.response.status,n=e.response.data;if(400===t){const e=n?.message;return new Vc(("string"==typeof e?e:void 0)??"Invalid transfer request",Hc.INVALID_AMOUNT)}if(403===t)return new Vc("Insufficient balance for transfer",Hc.INSUFFICIENT_BALANCE);if(404===t){const e={};return"tokenName"in r&&(e.tokenName=r.tokenName),new Vc("Token not found",Hc.TOKEN_NOT_FOUND,e)}}if("object"==typeof e&&null!==e&&"code"in e&&("ECONNABORTED"===Pt(e)||"ETIMEDOUT"===Pt(e)))return new Vc("Transfer request timed out",Hc.NETWORK_ERROR);const i=""!==Ut(e)?Ut(e):n;return new Vc(i,Hc.NETWORK_ERROR)}handleBurnError(e,n,r){if(e instanceof dl)return e;if(t(e)&&"pre_send"===e.phase)return new dl(`${n}: ${e.message}`,"SIGNING_FAILED"===(s=e.code)?ll.SIGNATURE_FAILED:"INVALID_TOKEN_REFERENCE"===s?ll.TOKEN_NOT_FOUND:"INVALID_QUANTITY"===s?ll.INVALID_AMOUNT:ll.VALIDATION_ERROR,jc(r));var s;let i=n,o=ll.NETWORK_ERROR;if(xt(e)){const t=e.response?.data;if("object"==typeof t){const e=t.Message;if("string"==typeof e&&e.length>0){i=`${n}: ${e}`;const t=e.toLowerCase();t.includes("insufficient")||t.includes("balance")?o=ll.INSUFFICIENT_BALANCE:(t.includes("not found")||t.includes("token"))&&(o=ll.TOKEN_NOT_FOUND)}}}else Lt(e)&&(i=`${n}: ${Ut(e)}`);return new dl(i,o,jc(r))}}class vl extends Nr{constructor(e,t,n,r=!1,s,i){super(e,r),this.balanceService=new Uc(e,r),this.tokenService=new il(e,r,s),this.lockService=new nl(e,t,n,r,i),this.transferService=new Al(e,t,n,r,i)}async fetchGalaBalance(e){return this.balanceService.fetchGalaBalance(e)}async fetchTokenBalance(e,t=!1){return this.balanceService.fetchTokenBalance(e,t)}async fetchTokenClassFromChain(e){return this.tokenService.fetchTokenClassFromChain(e)}async fetchTokenDetails(e){try{return h(await this.fetchTokenClassFromChain(e))}catch(t){if(Lt(t)&&("NetworkError"===t.name||Ut(t).includes("Token not found")))throw t;throw Vt(`Failed to fetch token details from GalaChain for ${"string"==typeof e?e:Ka(e)}: ${Ut(t)}`,500)}}async fetchTokenClassesWithSupply(e){return this.tokenService.fetchTokenClassesWithSupply(e)}async transferGala(e){return this.transferService.transferGala(e)}async transferToken(e){return this.transferService.transferToken(e)}async resolveTokenClassKey(e){return this.transferService.resolveTokenClassKey(e)}async lockTokens(e){return this.lockService.lockTokens(e)}async unlockTokens(e){return this.lockService.unlockTokens(e)}async burnTokens(e){return this.transferService.burnTokens(e)}}class Tl extends Nr{async getHealth(){const e=(await this.http.get(ot)).data;if(null==e)throw Vt("Health check answered no data");return e}}class yl extends Error{constructor(e,t,n){super(e),this.filename=t,this.mimeType=n,this.name="FileValidationError"}}function Sl(e,t,n){if(null==e)throw new yl("File is required",t,n);if("undefined"!=typeof File&&e instanceof File){const t=bs.safeParse(e);if(!t.success){const n=t.error.issues.map(e=>e.message).join("; ");throw new yl(n,e.name,e.type)}return}if(Buffer.isBuffer(e)){if(void 0===t||""===t)throw new yl("Filename is required when uploading Buffer objects",t,n);const r=Ns.safeParse(e);if(!r.success){const e=r.error.issues.map(e=>e.message).join("; ");throw new yl(e,t,n)}try{Yn(t,255,"filename")}catch(e){throw new yl(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 yl(`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 yl(`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 yl(`File extension "${i}" does not match MIME type "${n}"`,t,n);return}throw new yl("File must be a File object (browser) or Buffer (Node.js)",t,n)}function bl(e,t="image",n){const r=new FormData;if("undefined"!=typeof File&&e instanceof File)r.append(t,e);else{if(!Buffer.isBuffer(e))throw Wt("file","a File object (browser) or Buffer (Node.js)");{const s=new Blob([e],{type:"image/png"});r.append(t,s,n)}}return r}class Nl extends Nr{constructor(e,t,n=!1){super(e,n,t)}async uploadImageByTokenName(e){const{tokenName:t,options:n}=e;hr(t,"tokenName",Cr);const r=`${t}.png`;Sl(n.file,r,"image/png");try{const e=bl(n.file,"image",r),s=await cn(()=>this.http.request({method:"POST",url:Vo(R.UPLOAD_IMAGE,{tokenName:t}),data:e,headers:this.getJwtHeaders()}),{errorContext:"Image upload failed"});return"string"==typeof s?s:""}catch(e){if(e instanceof Ot)throw e;if(Lt(e)&&Ut(e).includes("FormData"))throw jt("File upload failed: FormData not supported in this environment. Ensure you have proper polyfills for Node.js environments.","FormData");throw e}}}function wl(e){if(!!(void 0===e.chatEnabled&&void 0===e.commentsEnabled&&void 0===e.streamingEnabled&&void 0===e.nextLiveStreamAt&&void 0===e.streamLanguage&&void 0===e.websiteUrl&&void 0===e.telegramUrl&&void 0===e.twitterUrl&&void 0===e.instagramUrl&&void 0===e.facebookUrl&&void 0===e.redditUrl&&void 0===e.tiktokUrl))throw new kt("At least one config option must be provided (chatEnabled, commentsEnabled, streamingEnabled, nextLiveStreamAt, streamLanguage, or social URLs)","options",wt.REQUIRED);if(void 0!==e.chatEnabled&&"boolean"!=typeof e.chatEnabled)throw Yt("chatEnabled","boolean");if(void 0!==e.commentsEnabled&&"boolean"!=typeof e.commentsEnabled)throw Yt("commentsEnabled","boolean");if(void 0!==e.streamingEnabled&&"boolean"!=typeof e.streamingEnabled)throw Yt("streamingEnabled","boolean");if(void 0!==e.streamLanguage&&"string"!=typeof e.streamLanguage)throw Yt("streamLanguage","string");const t=["websiteUrl","telegramUrl","twitterUrl","instagramUrl","facebookUrl","redditUrl","tiktokUrl"];for(const n of t){const t=e[n];if(null!=t&&"string"!=typeof t)throw Yt(n,"string or null")}if(void 0!==e.nextLiveStreamAt&&null!==e.nextLiveStreamAt){if("string"!=typeof e.nextLiveStreamAt)throw Yt("nextLiveStreamAt","string or null");const t=new Date(e.nextLiveStreamAt);if(isNaN(t.getTime()))throw new kt("nextLiveStreamAt must be a valid ISO date string","nextLiveStreamAt",wt.INVALID_FORMAT)}}function kl(e){if(cr(e)||"object"!=typeof e)return{};const t={};for(const[n,r]of Object.entries(e))cr(r)||(or(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 _l=Object.freeze({__proto__:null,adaptQueryParams:kl});function Il(e,t){if(null==e)return[];if(Array.isArray(e))return e;const n=e[t];return Array.isArray(n)?n:[]}function Dl(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.owner&&""!==t.owner}function Cl(e){return"string"==typeof e.quantity&&""!==e.quantity}class Rl extends Nr{constructor(e,t,n=!1){super(e,n,t)}async fetchPools(e={}){const t=function(e){const t=e.pageSize??Oo.DEFAULT_LIMIT;if(!Number.isInteger(t)||t<1||t>bt)throw zt("pageSize",1,bt,t);const n={pageSize:String(t)};or(e.cursor)&&(n.cursor=e.cursor);void 0!==e.type&&(n.type=Ul("type",e.type,yt));or(e.tokenName)&&(hr(e.tokenName,"tokenName",Ir),n.tokenName=e.tokenName);if(or(e.search)){if(e.search.length>Ol)throw tn("search",Ol,e.search.length);n.search=e.search}!0===e.hasUpcomingShows&&(n.hasUpcomingShows="true");if(or(e.language)){if(!Ll.test(e.language))throw Wt("language",'an ISO 639-1 code such as "en" or "zh-CN"');n.language=e.language}if(void 0!==e.recentlyStreamed){const t=e.recentlyStreamed;if(!Number.isInteger(t)||t<1||t>Ml)throw zt("recentlyStreamed",1,Ml,t);n.recentlyStreamed=String(t)}!0===e.hasRecordings&&(n.hasRecordings="true");void 0!==e.streamStatus&&(n.streamStatus=Ul("streamStatus",e.streamStatus,St));if(void 0!==e.isGraduated){if("boolean"!=typeof e.isGraduated)throw Yt("isGraduated","boolean",e.isGraduated);n.isGraduated=e.isGraduated?"true":"false"}void 0!==e.creatorAddress&&(n.creatorAddress=function(e){if("string"!=typeof e)throw Yt("creatorAddress","string",e);return Gn(e,"creatorAddress"),Bn(e)??e}(e.creatorAddress));return n}(e),n=on(await dn(()=>this.http.get(R.FETCH_POOLS,t),{errorContext:"Failed to fetch pools"}));return{items:function(e){if(!e)return[];let t=[];if(e.tokens)if(Array.isArray(e.tokens))t=e.tokens.map(e=>({...e,createdAt:e.created_at??e.createdAt??""}));else{const n=e.tokens;t=[{...n,createdAt:n.created_at??n.createdAt??""}]}else null!==e.pools&&void 0!==e.pools&&Array.isArray(e.pools)&&(t=e.pools.map(e=>({...e,createdAt:e.created_at??e.createdAt??""})));return t}(n),pageInfo:Go(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=$o(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=_i(e);!t.success&&t.errors&&lo(t.errors,"options")}(e),or(e.tokenName)&&hr(e.tokenName,"tokenName",Rr);try{const t=await this.http.post(R.VALIDATE_TOKEN,{tokenName:e.tokenName,symbol:e.symbol});if(null==t)throw new Error("Invalid response from check pool endpoint");const n=t.data??t;if(null==n)throw new Error("Invalid response from check pool endpoint");if(!0===or(e.symbol)){return!n.symbolAvailable}if(!0===or(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 Wi(t,"tokenName")&&ji(t,"from")&&ji(t,"to")&&ji(t,"resolution")}(e))throw new kt("Invalid options provided. Expected { tokenName: string, from?: number, to?: number, resolution?: number }","options","INVALID_OPTIONS");const{tokenName:t,from:n,to:r,resolution:s}=e;if(hr(t,"tokenName",Ir),null==n||null==r||null==s)throw new kt("Graph options (from, to, resolution) are required","options","MISSING_GRAPH_OPTIONS");const i={tokenName:t,from:n,to:r,resolution:s};ho(i);const o=kl(i),a=await cn(()=>this.http.get(R.CHART,o),{errorContext:"Failed to fetch graph data"});if(!Array.isArray(a.data)||"boolean"!=typeof a.isPreviousData)throw new Rt("Invalid chart response: expected { data: candles, isPreviousData }");return{dataPoints:a.data,isPreviousData:a.isPreviousData,..."number"==typeof a.nextTime&&{nextTime:a.nextTime}}}async fetchTokenDistribution(e){if(""===e||null==e)throw Ht("tokenName","Token name");let t;hr(e,"tokenName",Ir);try{t=await dn(()=>this.http.get(`${R.GET_TOKEN_DISTRIBUTION}?tokenName=${e}`),{errorContext:"Failed to fetch token distribution"})}catch(t){if(xt(t)&&500===t.response?.status)throw Vt(`Token distribution data temporarily unavailable for ${e}. This is a backend issue - please try again later.`,500,Lt(t)?t:void 0);throw t}return function(e,t,n=Yi){if(!Array.isArray(e))throw Vt("Invalid API response: expected array of holders",t);for(const n of e){if(!Dl(n))throw Vt("Invalid holder data: missing or invalid owner field",t);if(!Cl(n))throw Vt("Invalid holder data: missing or invalid quantity field",t);const e=Wn(n.quantity,NaN);if(isNaN(e)||!isFinite(e))throw Vt(`Invalid holder quantity: "${n.quantity}"`,t)}const r=e,s=r.reduce((e,t)=>e.plus(t.quantity),Qi(0));return{holders:r.map(e=>({address:e.owner,balance:e.quantity,percentage:so(Qi(e.quantity),s,Qi(0)).multipliedBy(100).toNumber()})),totalSupply:n(s),totalHolders:r.length,lastUpdated:new Date}}(on(t),t.status,e=>e.toFixed())}async fetchUserHolderContext(e,t){if(""===e||null==e)throw Ht("tokenName","Token name");if(""===t||null==t)throw Ht("userAddress","User address");return hr(e,"tokenName",Ir),cn(()=>this.http.get(`${R.GET_TOKEN_DISTRIBUTION}?tokenName=${e}`,{userAddress:kn(t,"userAddress")}),{errorContext:"Failed to fetch user holder context"})}async resolveTokenNameToVault(e){const t=await this.fetchPools({tokenName:e});if(null!==t.items&&void 0!==t.items&&Array.isArray(t.items)&&t.items.length>0)return t.items[0]?.vaultAddress??null;if(null!==t.items&&void 0!==t.items&&"object"==typeof t.items){const e=t.items.tokens;return e?.vaultAddress??null}return null}async fetchToken(e){if(null==e||"string"!=typeof e||""===e.trim())throw new Error("Token name is required and must be a non-empty string");hr(e,"tokenName",Cr);try{const t=R.GET_TOKEN.replace(":tokenName",e.toLowerCase().trim()),n=on(await this.http.get(t));if(null!=n?.tokens){const t=Array.isArray(n.tokens)?n.tokens[0]:n.tokens;if(null==t)throw new Error(`Token not found: ${e}`);return t}throw new Error(`Invalid response format when fetching token: ${e}`)}catch(t){const n=String(t);if(n.includes("404")||n.includes("not found"))throw t instanceof Rt?new Rt(`Token not found: ${e}`,t.statusCode,t):new Error(`Token not found: ${e}`);throw t}}async validateToken(e){if(!(null!==e.tokenName&&void 0!==e.tokenName||null!==e.symbol&&void 0!==e.symbol))throw new Error("At least one of tokenName or symbol is required");if(null!==e.tokenName&&void 0!==e.tokenName&&("string"!=typeof e.tokenName||""===e.tokenName.trim()))throw new Error("tokenName must be a non-empty string");if(null!==e.symbol&&void 0!==e.symbol&&("string"!=typeof e.symbol||""===e.symbol.trim()))throw new Error("symbol must be a non-empty string");null!==e.tokenName&&void 0!==e.tokenName&&hr(e.tokenName,"tokenName",Rr);try{const t=await this.http.post(R.VALIDATE_TOKEN,{tokenName:e.tokenName?.toLowerCase().trim(),symbol:e.symbol?.toUpperCase().trim()});if(null==t)throw new Error("Invalid response from validation endpoint");const n=t.data??t;if(null==n)throw new Error("Invalid response from validation endpoint");return n}catch(e){throw this.logger.warn(`Token validation failed: ${String(e)}`),e}}async fetchTokenStats(e){if(!or(e))throw Ht("tokenName","Token name");hr(e,"tokenName",Cr);const t=R.TOKEN_STATS.replace(":tokenName",e.toLowerCase().trim());try{const e=on(await this.http.get(t));if(!function(e){if("object"!=typeof e||null===e)return!1;const t=new Map(Object.entries(e));return["holdersCount","chatMessageCount","commentCount","roomCount"].every(e=>{const n=t.get(e);return"number"==typeof n&&Number.isFinite(n)})}(e))throw new Error("Invalid response: missing stats data");return{success:!0,data:{holdersCount:e.holdersCount,chatMessageCount:e.chatMessageCount,commentCount:e.commentCount,roomCount:e.roomCount}}}catch(t){throw this.logger.warn(`Failed to fetch token stats for ${e}: ${String(t)}`),t}}async updateTokenConfig(e,t){if(""===e||null==e)throw Ht("tokenName","Token name");hr(e,"tokenName",Cr),wl(t);const n=R.UPDATE_TOKEN_CONFIG.replace(":tokenName",e.toLowerCase().trim()),r={};void 0!==t.chatEnabled&&(r.chatEnabled=t.chatEnabled),void 0!==t.commentsEnabled&&(r.commentsEnabled=t.commentsEnabled),void 0!==t.streamingEnabled&&(r.streamingEnabled=t.streamingEnabled),void 0!==t.nextLiveStreamAt&&(r.nextLiveStreamAt=t.nextLiveStreamAt),void 0!==t.streamLanguage&&(r.streamLanguage=t.streamLanguage),void 0!==t.websiteUrl&&(r.websiteUrl=t.websiteUrl),void 0!==t.telegramUrl&&(r.telegramUrl=t.telegramUrl),void 0!==t.twitterUrl&&(r.twitterUrl=t.twitterUrl),void 0!==t.instagramUrl&&(r.instagramUrl=t.instagramUrl),void 0!==t.facebookUrl&&(r.facebookUrl=t.facebookUrl),void 0!==t.redditUrl&&(r.redditUrl=t.redditUrl),void 0!==t.tiktokUrl&&(r.tiktokUrl=t.tiktokUrl),await this.http.patch(n,r,this.getJwtHeaders())}async getTokenConfig(e){if(!or(e))throw Ht("tokenName","Token name");hr(e,"tokenName",Cr);const t=R.UPDATE_TOKEN_CONFIG.replace(":tokenName",e.toLowerCase().trim()),n=on(await this.http.get(t));if(void 0===n)throw new Error(`Invalid response: missing token config data for "${e}"`);return n}}const Ol=255,Ml=720,Ll=/^[a-z]{2}(-[A-Z]{2})?$/u;function Ul(e,t,n){const r="string"==typeof t?t.toUpperCase():void 0,s=n.find(e=>e===r);if(void 0===s)throw Zt(e,t,n);return s}function Fl(e){if(void 0!==e.tokenName){if(!or(e.tokenName))throw Yt("tokenName","a non-empty string",typeof e.tokenName);fr(e.tokenName,"tokenName",Ir)}if(void 0!==e.userAddress){if(!or(e.userAddress))throw Yt("userAddress","a non-empty string",typeof e.userAddress);if(e.userAddress.length>Fr)throw Qt("userAddress",Fr,e.userAddress.length)}if(void 0!==e.search){if("string"!=typeof e.search)throw Yt("search","a string",typeof e.search);if(e.search.length>256)throw Qt("search",256,e.search.length)}if(lr(0,void 0,Ur,e.pageSize),void 0!==e.txnType&&"BUY"!==e.txnType&&"SELL"!==e.txnType)throw Wt("txnType",'"BUY" or "SELL"');if(void 0!==e.startDate){if(!or(e.startDate))throw Yt("startDate","a non-empty string",typeof e.startDate);if(isNaN(Date.parse(e.startDate)))throw Wt("startDate","a valid ISO 8601 date")}if(void 0!==e.endDate){if(!or(e.endDate))throw Yt("endDate","a non-empty string",typeof e.endDate);if(isNaN(Date.parse(e.endDate)))throw Wt("endDate","a valid ISO 8601 date")}if(void 0!==e.minAmount)try{Qn(e.minAmount,0,Number.MAX_SAFE_INTEGER,"minAmount")}catch{throw Wt("minAmount","a non-negative number")}if(void 0!==e.maxAmount)try{Qn(e.maxAmount,0,Number.MAX_SAFE_INTEGER,"maxAmount")}catch{throw Wt("maxAmount","a non-negative number")}void 0!==e.minAmount&&void 0!==e.maxAmount&&function(e,t,n="range"){const r="number"==typeof e?e:Number(e),s="number"==typeof t?t:Number(t);if(isNaN(r)||isNaN(s))throw Yt(n,"numeric values",void 0,n);if(r>s)throw new kt(`Minimum value (${r}) must be less than or equal to maximum value (${s}) for ${n}`,n,wt.INVALID_RANGE)}(e.minAmount,e.maxAmount,"amountRange")}class Pl 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 Wi(t,"tokenName")&&(void 0===t.tradeType||"buy"===t.tradeType||"sell"===t.tradeType)&&Vi(t,"userAddress")&&ji(t,"offset")&&ji(t,"pageSize")&&ji(t,"page")&&ji(t,"limit")}(e))throw new kt("Invalid options provided. Expected { tokenName: string, tradeType?: string, userAddress?: string, cursor?: string, pageSize?: number, startDate?: Date, endDate?: Date, sortOrder?: string }","options","INVALID_OPTIONS");const{tokenName:t,cursor:n,pageSize:r=Oo.DEFAULT_LIMIT}=e;if(!or(t))throw Ht("tokenName","Token name");const s={pageSize:String(Math.min(r,Lr))};void 0!==n&&(s.cursor=n);const i=await this.http.get(Vo(R.GET_TRADES,{tokenName:t}),s);if(null==i)throw new kt("No response from trade service","response","NO_RESPONSE");const o=on(i),a=Il(o,"trades"),c=o?.pageInfo;return{items:a,pageInfo:c??{hasNextPage:!1}}}buildTradesQueryParams(e){const t={};null!==e.tokenName&&void 0!==e.tokenName&&e.tokenName.length>0&&(t.tokenName=gn(e.tokenName)),null!==e.userAddress&&void 0!==e.userAddress&&e.userAddress.length>0&&(t.userAddress=kn(e.userAddress,"userAddress")),null!==e.search&&void 0!==e.search&&e.search.length>0&&(t.search=e.search);const n=void 0!==e.pageSize?Fo(e.pageSize,1,Ur):Ur;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){Fl(e);const t=this.buildTradesQueryParams(e);return cn(()=>this.http.get(Qe,t),{errorContext:"Failed to fetch trades"})}}Cr.MIN_LENGTH,Cr.MAX_LENGTH;function xl(e){return or(e)&&Cn(e)}function Bl(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 Gl(e,t){return e.toLowerCase()===t.toLowerCase()}function $l(e){return e.toLowerCase()}function Kl(e,t){return e.toLowerCase().includes(t.toLowerCase())}function Hl(e,t,n,r){return e===n&&t===r||e===r&&t===n}function Wl(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&&jl(e))return ql(e)}return null}return jl(e)?ql(e):null}function Vl(e){return null==e||"string"!=typeof e||0===e.trim().length}function jl(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 ql(e){return e.startsWith("0x")?e.slice(2):e}dr({BOTH:"both",HELD:"held",CREATED:"created"});function zl(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Xl(e){return"number"==typeof e&&Number.isFinite(e)}function Ql(e){return null===e||"string"==typeof e}function Yl(e){return Array.isArray(e)&&e.every(e=>zl(e)&&"string"==typeof e.badgeName&&"boolean"==typeof e.isActive)}function Jl(e){return zl(e)&&"string"==typeof e.address&&Ql(e.fullName)&&Ql(e.profileImage)&&Ql(e.bio)&&function(e){return zl(e)&&Xl(e.tokensCreated)&&Xl(e.tokensGraduated)&&Xl(e.graduationRate)&&Xl(e.totalTrades)&&"string"==typeof e.totalVolumeGala&&Ql(e.totalVolumeUsd)&&(null===e.holdingsCount||Xl(e.holdingsCount))&&Ql(e.accountCreatedAt)&&Xl(e.accountAgeDays)}(e.stats)&&Yl(e.launchBadge)&&Yl(e.successBadge)&&Yl(e.volumeBadge)&&Yl(e.engagementBadge)&&"boolean"==typeof e.isLiveStreaming&&Ql(e.liveStreamToken)}class Zl extends Nr{constructor(e,t,n=!1){super(e,n,t)}async fetchProfile(e){const t=e??this.http.getAddress();if(""===t||null==t||!xl(t))throw Wt("address","eth|[40-hex-chars] or client|[identifier]","Address");if(void 0===e){const e=await cn(()=>this.http.get(R.GET_CURRENT_USER,void 0,this.getJwtHeaders()),{errorContext:"Failed to fetch profile"});if(!(zl(n=e)&&"string"==typeof n.address&&Ql(n.fullName)&&Ql(n.profileImage)&&"string"==typeof n.bio&&Yl(n.launchBadge)&&Yl(n.successBadge)))throw Vt("Malformed profile response");return e}var n;const r=await cn(()=>this.http.get(R.GET_PROFILE.replace(":address",kn(t,"address"))),{errorContext:"Failed to fetch profile"});if(!Jl(r))throw Vt("Malformed profile response");return r}async updateProfile(e){this.validateUpdateProfileData(e);const t={};void 0!==e.fullName&&(t.fullName=e.fullName.trim()),void 0!==e.profileImage&&(t.profileImage=e.profileImage),await cn(()=>this.http.put(R.UPDATE_PROFILE,t,this.getJwtHeaders()),{errorContext:"Profile update failed"})}async uploadProfileImage(e){this.validateUploadProfileImageOptions(e);try{const t=void 0===e.address?"profile-image.png":`profile-image-${e.address}.png`,n=bl(e.file,"image",t),r=await cn(()=>this.http.request({method:"POST",url:R.UPLOAD_PROFILE_IMAGE,data:n,headers:this.getJwtHeaders()}),{errorContext:"Image upload failed"});return"string"==typeof r?r:""}catch(e){if(e instanceof kt||e instanceof Ot)throw e;if(e instanceof Rt)throw new Rt(`Profile image upload failed: ${Ut(e)}`,e.statusCode,e);throw new kt(`Profile image upload failed: ${Ut(e)}`,"file","UPLOAD_FAILED")}}async fetchTokenList(e){if(void 0!==e.status&&"created"!==e.type)throw new kt("status filters only apply when type=created","status","INVALID_FILTER");const t=e.tokenName,n={...e},r="created"===e.type;r&&(delete n.tokenName,void 0!==t&&void 0===n.search&&(n.search=t));const s=await this.buildFetchRequest(R.GET_TOKEN_LIST,n,{includeType:!0,requestType:e.type??"both",responseKey:r?"launches":"token",errorMessage:"Failed to fetch token list"});return r&&void 0!==t?{...s,tokens:s.tokens.filter(e=>e.tokenName===t||e.name===t)}:s}async fetchTokensHeld(e){if(void 0!==e.type&&"held"!==e.type)throw new kt("fetchTokensHeld only supports type=held","type","INVALID_TYPE");if(void 0!==e.status)throw new kt("status filters only apply when type=created","status","INVALID_FILTER");return this.buildFetchRequest(R.GET_TOKENS_HELD,e,{includeType:!0,requestType:"held",responseKey:"token",errorMessage:"Failed to fetch tokens held"})}async fetchTokensCreated(e){const{cursor:t,pageSize:n,search:r,tokenName:s,status:i}=e??{};if(void 0!==e?.type&&"created"!==e.type)throw new kt("fetchTokensCreated only supports type=created","type","INVALID_TYPE");const o=e?.address??this.http.getAddress();if(null==o||""===o)throw new kt("Wallet address not available - wallet not configured","address","NO_WALLET");const a={type:"created",address:o,pageSize:n??Oo.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,Lr))),cn(()=>this.http.get(R.GET_MANAGED_TOKENS,t,this.getJwtHeaders()),{errorContext:"Failed to fetch managed tokens"})}async getUserGalaBalance(e){if("string"!=typeof e||""===e.trim())throw Ht("address","Address");const t=kn(e.trim(),"address");return cn(()=>this.http.get(Vo(R.GET_GALA_BALANCE,{address:t})),{errorContext:"Failed to fetch GALA balance"})}async fetchReferralCode(){return cn(()=>this.http.get(R.GET_REFERRAL_CODE,void 0,this.getJwtHeaders()),{errorContext:"Failed to fetch referral code"})}async buildFetchRequest(e,t,n){this.validateGetTokenListOptions(t);const r=Ho({pageSize:t.pageSize??Oo.DEFAULT_LIMIT,...void 0!==t.cursor&&{cursor:t.cursor}},Lr);jo(r,t,["address","search","tokenName","status"]),n.includeType&&!e.includes("?type=")&&(r.type=n.requestType);let s=e;const i=kn(t.address??this.http.getAddress(),"address");if(void 0!==t.address&&(r.address=i),e.includes(":address")){if(0===i.length)throw Ht("address","User address");s=e.replace(":address",i),delete r.address}const o=on(await dn(()=>this.http.get(s,r),{errorContext:n.errorMessage}));return{tokens:Il(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:Go(o?.pageInfo)}}validateGetTokenListOptions(e){const t=e.pageSize??Oo.DEFAULT_LIMIT;if(t<1||t>Lr)throw new kt(`pageSize must be between 1 and ${Lr}`,"pageSize","OUT_OF_RANGE");if(void 0!==e.address&&!xl(e.address))throw Wt("address","eth|[40-hex-chars] or client|[identifier]","Address");const n=Bl(e.search);if(null!==n&&!(or(r=n)&&r.length>=Hr&&r.length<=Wr))throw zt("search",Hr,Wr,n.length,"Search query");var r;const s=Bl(e.tokenName);if(!(null===s||or(i=s)&&Cr.PATTERN.test(i)))throw Wt("tokenName",Cr.DESCRIPTION,"Token name");var i}validateUpdateProfileData(e){if(void 0!==e.address&&!xl(e.address))throw Wt("address","eth|[40-hex-chars] or client|[identifier]","Address");if(void 0===e.fullName&&void 0===e.profileImage)throw new kt("At least one of fullName and profileImage must be provided","options","REQUIRED");if(void 0!==e.fullName&&(t=e.fullName.trim(),!(or(t)&&t.length>=Vr.FULL_NAME.MIN_LENGTH&&t.length<=Vr.FULL_NAME.MAX_LENGTH&&Vr.FULL_NAME.ALPHABETS_ONLY_PATTERN.test(t))))throw zt("fullName",Vr.FULL_NAME.MIN_LENGTH,Vr.FULL_NAME.MAX_LENGTH,e.fullName.trim().length,"Full name");var t;if("string"==typeof e.profileImage&&e.profileImage.trim().length>2048)throw new kt("profileImage must not exceed 2048 characters","profileImage","TOO_LONG")}validateUploadProfileImageOptions(e){if(void 0!==e.address&&!xl(e.address))throw Wt("address","eth|[40-hex-chars] or client|[identifier]","Address")}}class ed{constructor(e,t,n=!1){this.http=e,this.poolService=new Rl(e,t,n),this.tradeService=new Pl(e,n),this.userService=new Zl(e,t,n),this.imageService=new Nl(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 uo(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 td(e,t){if(void 0!==e){if(!or(e))throw Yt("tokenName","string");fr(e,"tokenName",Ir)}if(void 0!==t){if(!or(t))throw Yt("userAddress","string");if(t.length>Fr)throw new kt(`userAddress must be at most ${Fr} characters`,"userAddress",wt.TOO_LONG)}}const nd={CHAT_MESSAGE:"CHAT_MESSAGE",COMMENT:"COMMENT"},rd={PAGINATION:{MAX_LIMIT:Ur},CONTENT:{CHAT_MAX_LENGTH:Pr.CHAT_MESSAGES_V1.MAX_LENGTH,COMMENT_MAX_LENGTH:Pr.COMMENTS_V1.MAX_LENGTH}};function sd(e){const t=void 0!==e.type,n=void 0!==e.tokenName&&""!==e.tokenName,r=void 0!==e.userAddress&&""!==e.userAddress;if(!t&&!n&&!r)throw en(["type","tokenName","userAddress"]);if(void 0!==e.type&&e.type!==nd.CHAT_MESSAGE&&e.type!==nd.COMMENT)throw new kt(`type must be one of: ${Object.values(nd).join(", ")}`,"type",wt.INVALID_VALUE);td(e.tokenName,e.userAddress),void 0!==e.pageSize&&lr(0,void 0,Ur,e.pageSize)}function id(e){if(void 0===e.type||null===e.type)throw Ht("type");if(e.type!==nd.CHAT_MESSAGE&&e.type!==nd.COMMENT)throw new kt(`type must be one of: ${Object.values(nd).join(", ")}`,"type",wt.INVALID_VALUE);if(!or(e.tokenName))throw Ht("tokenName");if(fr(e.tokenName,"tokenName",Ir),!or(e.content))throw Ht("content");if(0===e.content.trim().length)throw nn("content","Content");const t=e.type===nd.CHAT_MESSAGE?rd.CONTENT.CHAT_MAX_LENGTH:rd.CONTENT.COMMENT_MAX_LENGTH;if(e.content.length>t)throw tn("content",t,e.content.length)}function od(e){if(!or(e.content))throw Ht("content");if(0===e.content.trim().length)throw nn("content","Content");const t=Math.max(rd.CONTENT.CHAT_MAX_LENGTH,rd.CONTENT.COMMENT_MAX_LENGTH);if(e.content.length>t)throw tn("content",t,e.content.length)}function ad(e){if(!or(e))throw Ht("id","Message ID");const t=xr.CHAT_MESSAGE.PATTERN.test(e),n=/^msg-\d{13}-[a-f0-9]{32}$/.test(e);if(!t&&!n)throw new kt("Invalid message ID format. Expected: chat-{timestamp}-{uuid} or msg-{timestamp}-{uuid}","id",wt.INVALID_FORMAT)}function cd(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function ld(e){return null===e||"string"==typeof e}function dd(e){return cd(e)&&ld(e.fullName)&&ld(e.profileImage)}function ud(e){if(!cd(e))return!1;const t=e.reactions;return"string"==typeof e.id&&"string"==typeof e.messageId&&"string"==typeof e.tokenName&&ld(e.tokenImage)&&"string"==typeof e.userAddress&&dd(e.user)&&dd(e.userProfile)&&"string"==typeof e.content&&"string"==typeof e.createdAt&&ld(e.updatedAt)&&ld(e.deletedAt)&&"number"==typeof e.flagCount&&cd(t)&&cd(t.counts)}function hd(e){return e===nd.CHAT_MESSAGE||e===nd.COMMENT}class gd extends zo{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}validateContent(e,t){if(!or(e))throw Ht("content","Message content");if(0===e.trim().length)throw Ht("content","Message content");Yn(e,t===nd.CHAT_MESSAGE?Pr.CHAT_MESSAGES_V1.MAX_LENGTH:Pr.COMMENTS_V1.MAX_LENGTH,"content")}validateMessageId(e){if(!or(e))throw Ht("id","Message ID");if(e.length<10||e.length>64)throw Wt("id","valid message ID format","Message ID")}validateMessageType(e){if(e!==nd.CHAT_MESSAGE&&e!==nd.COMMENT)throw new kt(`type must be one of: ${Object.values(nd).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,Ir);const r={};void 0!==e.cursor&&(r.cursor=e.cursor),r.pageSize=e.pageSize??Oo.DEFAULT_LIMIT;const s=Ho(r,Ur),i={};void 0!==s.pageSize&&(i.pageSize=s.pageSize),void 0!==s.cursor&&(i.cursor=s.cursor),t&&(i.type=e.type.toUpperCase()),n&&(i.tokenName=gn(e.tokenName)),void 0!==e.userAddress&&""!==e.userAddress&&(i.userAddress=kn(e.userAddress,"userAddress")),void 0!==e.search&&""!==e.search&&(i.search=e.search);const o=await this.http.get(Ye.GET_MESSAGES,i),a=this.extractData(o);return{messages:a.messages,pageInfo:a.pageInfo}}async createMessage(e){this.validateMessageType(e.type),this.validateTokenName(e.tokenName,Ir),this.validateContent(e.content,e.type);const t={type:e.type,tokenName:gn(e.tokenName),content:e.content.trim()},n=await this.http.post(Ye.CREATE_MESSAGE,t,this.getJwtHeaders());return{message:this.extractData(n)}}async updateMessage(e,t){this.validateMessageId(e),this.validateContent(t.content,t.type);const n=this.buildEndpointWithId(Ye.UPDATE_MESSAGE,e),r={content:t.content.trim()},s=await this.http.put(n,r,this.getJwtHeaders());return{message:this.extractData(s)}}async deleteMessage(e){this.validateMessageId(e);const t=this.buildEndpointWithId(Ye.DELETE_MESSAGE,e);return await this.http.delete(t,void 0,this.getDualAuthHeaders()),{success:!0}}async getPinnedMessage(e){this.validateTokenName(e,Cr);const t=await this.http.get(Ye.GET_PINNED,{tokenName:gn(e)});return{message:this.extractDataOrNull(t)}}async pinMessage(e){this.validateMessageId(e);const t=Ye.PIN_MESSAGE.replace(":id",e);return await this.http.post(t,{},this.getDualAuthHeaders()),{success:!0}}async unpinMessage(e){this.validateMessageId(e);const t=Ye.UNPIN_MESSAGE.replace(":id",e);return await this.http.delete(t,void 0,this.getDualAuthHeaders()),{success:!0}}async getMessageStats(){return function(e){const t=e=>"number"==typeof e&&Number.isFinite(e),n=e=>"object"==typeof e&&null!==e&&!Array.isArray(e);if(!n(e))throw Vt("Malformed message statistics response");const r=e.totalMessages,s=e.todayMessages,i=e.uniqueUsers,o=e.uniqueTokens,a=e.messagesByType;if(!(t(r)&&t(s)&&t(i)&&t(o)&&n(a)))throw Vt("Malformed message statistics response");const c={};for(const[e,n]of Object.entries(a)){if(!t(n))throw Vt("Malformed message statistics response");c[e]=n}return{totalMessages:r,todayMessages:s,uniqueUsers:i,uniqueTokens:o,messagesByType:c}}(await this.http.get(Ye.GET_MESSAGE_STATS,void 0,this.getDualAuthHeaders()))}}const md={MODERATOR:"MODERATOR",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MANAGER:"MANAGER"},fd=ur(md),pd={TOKEN:"TOKEN",ALL_OWNER_TOKENS:"ALL_OWNER_TOKENS"},Ed=ur(pd),Ad={PENDING:"PENDING",CLAIMED:"CLAIMED",REVOKED:"REVOKED",EXPIRED:"EXPIRED"},vd=ur(Ad);function Td(e){return fd.includes(e)}function yd(e){return vd.includes(e)}function Sd(e){return Kr.PATTERN.test(e)}const bd=pr([{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"}]),Nd=pr([{field:"tokenName",type:"string"},{field:"tokenSymbol",type:"string"},{field:"role",type:"string"},{field:"inviteScope",type:"string"},{field:"creatorAddress",type:"string"},{field:"claimedAt",type:"string"}]),wd=pr([{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 kd(e){return Ed.includes(e)}function _d(e){const t=[],n=e.inviteScope??pd.TOKEN;return void 0===e.inviteScope||kd(e.inviteScope)||Gt(t,()=>{throw Zt("inviteScope",e.inviteScope,Ed,"Invite scope")}),n===pd.TOKEN?Gt(t,()=>{hr(e.tokenName??"","tokenName",Ir)}):n===pd.ALL_OWNER_TOKENS&&void 0!==e.tokenName&&""!==e.tokenName&&t.push("Token name should not be provided for ALL_OWNER_TOKENS scope invites"),Td(e.role)||Gt(t,()=>{throw Zt("role",e.role,fd,"Role")}),void 0!==e.description&&""!==e.description&&Gt(t,()=>{Yn(e.description,Pr.DESCRIPTION.MAX_LENGTH,"description")}),void 0===e.expiresAt||""===e.expiresAt||bn(e.expiresAt)||Gt(t,()=>{throw function(e,t="a valid date",n){const r=$t(e,n);return new kt(`${r} must be ${t}`,e,"INVALID_DATE")}("expiresAt","ISO 8601 format")}),t}function Id(e){const t=[];return or(e)?Sd(e)||t.push("Invalid invite code format"):t.push(Ht("inviteCode","Invite code").message),t}function Dd(e){const t=[];return Gt(t,()=>{hr(e.tokenName??"","tokenName",Ir)}),void 0===e.status||yd(e.status)||Gt(t,()=>{throw Zt("status",e.status,vd,"Status")}),Gt(t,()=>{lr(0,void 0,Mr,e.pageSize)}),t}class Cd extends zo{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}validateRole(e){if(!or(e))throw Ht("role","Role");if(!Td(e))throw Wt("role",`one of: ${fd.join(", ")}`,"Role")}validateInviteCodeFormat(e){if(!or(e))throw Ht("inviteCode","Invite code");if(e.length>Kr.MAX_LENGTH)throw Wt("inviteCode",`at most ${String(Kr.MAX_LENGTH)} characters`,"Invite code")}validateInviteScope(e){if(void 0!==e&&!kd(e))throw new kt(`Invalid invite scope. Must be one of: ${Ed.join(", ")}`,"inviteScope","INVALID_VALUE")}async createInvite(e){this.validateInviteScope(e.inviteScope);const t=e.inviteScope??pd.TOKEN;if(t===pd.TOKEN){if(void 0===e.tokenName||""===e.tokenName)throw new kt("Token name is required for TOKEN scope invites","tokenName","REQUIRED");this.validateTokenName(e.tokenName,Ir)}else if(t===pd.ALL_OWNER_TOKENS&&e.tokenName)throw new kt("Token name should not be provided for ALL_OWNER_TOKENS scope invites","tokenName","INVALID_VALUE");this.validateRole(e.role),this.validateOptionalString(e.description,"description","Description",Pr.DESCRIPTION.MAX_LENGTH),this.validateOptionalDate(e.expiresAt,"expiresAt","Expiration date");const n=ge,r={inviteScope:t,role:e.role};t===pd.TOKEN&&null!==e.tokenName&&void 0!==e.tokenName&&""!==e.tokenName&&(r.tokenName=gn(e.tokenName)),void 0!==e.description&&(r.description=e.description),void 0!==e.expiresAt&&(r.expiresAt=e.expiresAt);const s=await this.http.post(n,r,this.getMultiAuthHeaders());return{invite:this.extractData(s)}}async listInvites(e){void 0!==e.tokenName&&""!==e.tokenName&&this.validateTokenName(e.tokenName,Ir),this.validateStatusFilter(e.status,Ad);const t=pe,n={...this.buildPaginationParams(e,Ur)};void 0!==e.tokenName&&""!==e.tokenName&&(n.tokenName=gn(e.tokenName)),void 0!==e.status&&(n.status=e.status);const r=await this.http.get(t,n,this.getMultiAuthHeaders()),s=this.extractData(r);return{items:s.invites,pageInfo:s.pageInfo}}async revokeInvite(e){this.validatePositiveInteger(e,"inviteId","Invite ID");const t=this.buildEndpoint(Ee,{id:String(e)});sn(await this.http.delete(t,void 0,this.getMultiAuthHeaders()),"Failed to revoke invite")}async updateInviteRole(e){this.validatePositiveInteger(e.inviteId,"inviteId","Invite ID"),this.validateRole(e.role);const t=this.buildEndpoint(Ae,{id:String(e.inviteId)}),n={role:e.role},r=await this.http.patch(t,n,this.getMultiAuthHeaders());return{invite:this.extractData(r)}}async updateInvite(e){if(this.validatePositiveInteger(e.inviteId,"inviteId","Invite ID"),void 0===e.role&&void 0===e.description)throw new kt("At least one of role or description must be provided","options","REQUIRED");void 0!==e.role&&this.validateRole(e.role),void 0!==e.description&&this.validateOptionalString(e.description,"description","Description",Pr.DESCRIPTION.MAX_LENGTH);const t=this.buildEndpoint(ve,{id:String(e.inviteId)}),n={};void 0!==e.role&&(n.role=e.role),void 0!==e.description&&(n.description=e.description);const r=await this.http.patch(t,n,this.getMultiAuthHeaders());return{invite:this.extractData(r)}}async claimInvite(e){this.validateInviteCodeFormat(e.inviteCode);const t=me,n={inviteCode:e.inviteCode},r=await this.http.post(t,n,this.getMultiAuthHeaders()),s=this.extractData(r);return"tokenName"in s&&void 0!==s.tokenName?{token:s}:{blanketAccess:s}}async getModeratedTokens(e){const t=fe,n=this.buildPaginationParams(e??{},Ur),r=await this.http.get(t,n,this.getMultiAuthHeaders()),s=this.extractData(r);return{items:s.tokens,pageInfo:s.pageInfo}}async getInviteByCode(e){this.validateInviteCodeFormat(e);const t=this.buildEndpoint(Te,{code:e}),n=await this.http.get(t,{});return this.extractData(n)}}const Rd={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 Od(e){return parseFloat(Rd[e])}function Md(e){return`${e}-${Date.now()}-${Math.random().toString(36).substring(2,11)}`}function Ld(){return Date.now()+6e4}function Ud(e){return""!==e&&"string"==typeof e&&/^[a-zA-Z0-9]{3,50}$/.test(e)}function Fd(e){try{return Math.floor(parseFloat(String(e))??0).toString()}catch{return"0"}}function Pd(e){return""!==e&&"string"==typeof e&&Cn(e)}class xd extends Nr{constructor(e){super(e)}getCollectionClaimFee(){return Rd.COLLECTION_CLAIM_FEE}getTokenClassCreateFee(){return Rd.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(!Pd(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=Rd.COLLECTION_CLAIM_FEE;n.collectionClaim=e,t=String(BigInt(t)+BigInt(e))}if((e.createTokenClasses??0)>0){const r=Rd.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),!Ud(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:Ld(),uniqueKey:Md("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),!Pd(e))throw new Error(`Invalid wallet address format: ${e}`);const t=(await this.allAuthorizations()).filter(t=>t.authorizedUsers.some(t=>Dn(t,e))).map(t=>({authorizedUser:wn(e,"walletAddress"),collection:t.collection}));return this.logger.debug(`Found ${t.length} collections for user`),t}catch(e){throw this.logger.error("Failed to fetch user collections",e),e}}async isCollectionAvailable(e){try{if(this.logger.debug("Checking collection availability",e),!Ud(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(!Ud(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?Fd(e.maxSupply):void 0,maxCapacity:void 0!==e.maxCapacity?Fd(e.maxCapacity):void 0,additionalKey:e.additionalKey,expiresAt:Ld(),uniqueKey:Md("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),!Ud(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(!Pd(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:wn(e.ownerAddress,"ownerAddress"),additionalKey:e.additionalKey??"none",expiresAt:Ld(),uniqueKey:Md("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:wn(e.ownerAddress,"ownerAddress"),tokenInstances:i,tokenClass:{collection:e.collection,type:e.type,category:e.category}}}catch(e){throw this.logger.error("Failed to mint NFT",e),e}}async fetchNftBalances(e,t){try{if(this.logger.debug("Fetching NFT balances for",{ownerAddress:e,collectionFilter:t}),!Pd(e))throw new Error(`Invalid owner address: ${e}`);const n=(await this.reads().fetchNftBalances({owner:wn(e,"ownerAddress"),collection:t})).map(e=>({owner:e.owner,collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey,instanceIds:[...e.instanceIds],totalOwned:e.instanceIds.length}));return this.logger.debug(`Found ${n.length} NFT balances`),n}catch(e){throw this.logger.error("Failed to fetch NFT balances",e),e}}reads(){const{requestor:e}=Mc(async(e,t)=>({data:await this.http.post(e,t)}));return new d({gatewayBaseUrl:"",httpRequestor:e,requestTimeoutMs:1/0})}allAuthorizations(){return this.reads().fetchAllNftCollectionAuthorizations({pageSize:1e3})}}class Bd 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(mt,{token:e.token,platform:e.platform,...void 0!==e.deviceId?{deviceId:e.deviceId}:{}},t),r=this.extractData(n);return this.logger.debug("Push token registered",{registered:r.registered}),r}async unregisterPushToken(e){this.logger.debug("Unregistering push token");const t=this.getJwtHeaders(),n=await this.http.request({method:"DELETE",url:ft,data:{token:e},headers:t}),r=this.extractData(n);return this.logger.debug("Push token unregistered",{unregistered:r.unregistered}),r}async getPreferences(){this.logger.debug("Fetching notification preferences");const e=this.getJwtHeaders(),t=await this.http.get(pt,void 0,e),n=this.extractData(t);return this.logger.debug("Fetched notification preferences",{tradesEnabled:n.tradesEnabled,streamsEnabled:n.streamsEnabled}),{preferences:n}}async updatePreferences(e){this.logger.debug("Updating notification preferences",e);const t=this.getJwtHeaders(),n=await this.http.put(Et,e,t),r=this.extractData(n);return this.logger.debug("Updated notification preferences",{tradesEnabled:r.tradesEnabled,streamsEnabled:r.streamsEnabled}),{preferences:r}}}class Gd 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(R.OEMBED,{format:"json"});return this.logger.debug("Fetched home oEmbed (JSON)",{title:t.title}),{oembed:t}}async getHomeOEmbedHtml(e={}){this.logger.debug("Fetching home oEmbed (HTML)");const t=await this.http.get(R.OEMBED,{},{responseType:"text"});return this.logger.debug("Fetched home oEmbed (HTML)"),{html:t}}async getPoolOEmbedJson(e){const{tokenName:t}=e;if(null==t||"string"!=typeof t||""===t.trim())throw new kt("tokenName is required","tokenName","REQUIRED_FIELD");this.logger.debug("Fetching pool oEmbed (JSON)",{tokenName:t});const n=R.OEMBED_BUY_SELL.replace(":tokenName",t.toLowerCase().trim()),r=await this.http.get(n,{format:"json"});return this.logger.debug("Fetched pool oEmbed (JSON)",{tokenName:t,title:r.title}),{oembed:r}}async getPoolOEmbedHtml(e){const{tokenName:t}=e;if(null==t||"string"!=typeof t||""===t.trim())throw new kt("tokenName is required","tokenName","REQUIRED_FIELD");this.logger.debug("Fetching pool oEmbed (HTML)",{tokenName:t});const n=R.OEMBED_BUY_SELL.replace(":tokenName",t.toLowerCase().trim()),r=await this.http.get(n,{},{responseType:"text"});return this.logger.debug("Fetched pool oEmbed (HTML)",{tokenName:t}),{html:r}}async getProfileOEmbedJson(e){const{address:t}=e;if(null==t||"string"!=typeof t||""===t.trim())throw new kt("address is required","address","REQUIRED_FIELD");this.logger.debug("Fetching profile oEmbed (JSON)",{address:t});const n=R.OEMBED_PROFILE.replace(":address",encodeURIComponent(kn(t.trim(),"address"))),r=await this.http.get(n,{format:"json"});return this.logger.debug("Fetched profile oEmbed (JSON)",{address:t,title:r.title}),{oembed:r}}async getProfileOEmbedHtml(e){const{address:t}=e;if(null==t||"string"!=typeof t||""===t.trim())throw new kt("address is required","address","REQUIRED_FIELD");this.logger.debug("Fetching profile oEmbed (HTML)",{address:t});const n=R.OEMBED_PROFILE.replace(":address",encodeURIComponent(kn(t.trim(),"address"))),r=await this.http.get(n,{},{responseType:"text"});return this.logger.debug("Fetched profile oEmbed (HTML)",{address:t}),{html:r}}}function $d(e){if(!or(e))throw Ht("address","Address");wn(e,"address")}const Kd={PENDING:"PENDING",CLAIMED:"CLAIMED",REVOKED:"REVOKED",EXPIRED:"EXPIRED"},Hd={ACTIVE:"ACTIVE",REVOKED:"REVOKED"},Wd=dr(Kd),Vd=dr(Hd);function jd(e){if(e.status!==Kd.PENDING)return!1;if(null!==e.expiresAt&&void 0!==e.expiresAt){if(Sn(e.expiresAt)<=new Date)return!1}return!0}function qd(e){try{Tr(e.description,"description",255)}catch(e){if(e instanceof kt){throw e.message.includes("255")?new Error("description must be at most 255 characters"):new Error("description must be a string")}throw e}if(void 0!==e.expiresAt){if(!or(e.expiresAt))throw new Error("expiresAt must be a non-empty string");try{yr(e.expiresAt,"expiresAt")}catch(e){if(e instanceof kt)throw new Error("expiresAt must be a valid ISO 8601 date string");throw e}if(bn(e.expiresAt)){if(Sn(e.expiresAt)<=new Date)throw new Error("expiresAt must be in the future")}}}function zd(e){if(void 0!==e.status&&!Wd(e.status))throw Zt("status",e.status,Object.values(Kd),"status");lr(0,void 0,50,e.pageSize,e.cursor)}function Xd(e){if(void 0!==e.status&&!Vd(e.status))throw Zt("status",e.status,Object.values(Hd),"status");lr(0,void 0,50,e.pageSize,e.cursor)}function Qd(e){if(!or(e))throw new Error("Invite code must be a non-empty string");Yn(e,Kr.MAX_LENGTH,"code")}function Yd(e){if(!or(e))throw new Error("Address must be a non-empty string");try{$n(e,"address")}catch{throw new Error("Invalid wallet address format. Must be eth|..., 0x..., or client|... format")}}function Jd(e){try{Jn(e,"id")}catch(e){if(e instanceof kt)throw new Error("Invite ID must be a positive integer");throw e}}function Zd(e){if(null==e||"object"!=typeof e)throw new kt("Options are required");if(void 0!==e.search){if("string"!=typeof e.search)throw new kt("Search must be a string");if(0===e.search.length)throw new kt("Search query cannot be empty string")}if(void 0!==e.sortBy){if("string"!=typeof e.sortBy)throw new kt("Sort field must be a string");if(0===e.sortBy.length)throw new kt("Sort field cannot be empty string")}if(void 0!==e.sortOrder){const t="string"==typeof e.sortOrder?e.sortOrder.toLowerCase():"";if("asc"!==t&&"desc"!==t)throw new kt('Sort order must be "asc" or "desc"')}}function eu(e){if(null==e||"object"!=typeof e)throw new kt("Options are required");if(!or(e.userAddress))throw new kt("userAddress is required and must be a non-empty string");try{$n(e.userAddress,"userAddress")}catch{throw new kt("Invalid wallet address format. Must be eth|..., 0x..., or client|... format")}if(void 0!==e.description){if("string"!=typeof e.description)throw new kt("description must be a string");if(e.description.length>255)throw new kt("description must be at most 255 characters")}}class tu extends zo{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}validateInviteCodeFormat(e){if(!or(e))throw Ht("inviteCode","Invite code");Qd(e)}validateWalletAddressFormat(e){if(!or(e))throw Ht("address","Address");Yd(e)}async createInvite(e={}){qd(e),this.validateOptionalString(e.description,"description","Description",Pr.DESCRIPTION.MAX_LENGTH),this.validateOptionalDate(e.expiresAt,"expiresAt","Expiration date");const t=Se,n={};void 0!==e.description&&(n.description=e.description),void 0!==e.expiresAt&&(n.expiresAt=e.expiresAt);const r=await this.http.post(t,n,this.getDualAuthHeaders());return{invite:this.extractData(r)}}async listInvites(e={}){zd(e),this.validateStatusFilter(e.status,Kd);const t=be,n={...this.buildPaginationParams(e,Ur)};void 0!==e.status&&(n.status=e.status);const r=await this.http.get(t,n,this.getDualAuthHeaders()),s=this.extractData(r);return{items:s.invites,pageInfo:s.pageInfo}}async getInviteByCode(e){this.validateInviteCodeFormat(e);const t=this.buildEndpoint(Ne,{code:e}),n=await this.http.get(t,{});return this.extractData(n)}async revokeInvite(e){Jd(e);const t=this.buildEndpoint(ke,{id:String(e)});sn(await this.http.delete(t,void 0,this.getDualAuthHeaders()),"Failed to revoke invite")}async claimInvite(e){this.validateInviteCodeFormat(e);const t=we,n={inviteCode:e},r=await this.http.post(t,n,this.getJwtHeaders());return{invite:this.extractData(r)}}async listOverseers(e={}){Xd(e),this.validateStatusFilter(e.status,Hd);const t=_e,n={...this.buildPaginationParams(e,Ur)};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){eu(e),this.validateWalletAddressFormat(e.userAddress),this.validateOptionalString(e.description,"description","Description",Pr.DESCRIPTION.MAX_LENGTH);const t=Ie,n={userAddress:kn(e.userAddress,"userAddress")};void 0!==e.description&&(n.description=e.description);const r=await this.http.post(t,n,this.getDualAuthHeaders());return{overseer:this.extractData(r)}}async revokeOverseer(e){this.validateWalletAddressFormat(e);const t=this.buildEndpoint(De,{address:kn(e,"address")});sn(await this.http.delete(t,void 0,this.getDualAuthHeaders()),"Failed to revoke overseer")}async getMyStatus(){const e=Ce,t=await this.http.get(e,{},this.getJwtHeaders());return this.extractData(t)}async getSummary(){const e=Re,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getBanStats(){const e=Oe,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getTokenBanStats(){const e=Me,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getInviteStats(){const e=Le,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getFlagStats(){const e=Ue,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getUserStats(){const e=Fe,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async listOverseerUsers(e){const t=e??{};Object.keys(t).length>0&&Zd(t);const n=Pe,r=this.buildPaginationParams(t,Ur);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(!or(e))throw Ht("address","User address");Yd(e);const t=this.buildEndpoint(xe,{address:kn(e,"address")}),n=await this.http.get(t,{},this.getDualAuthHeaders());return this.extractData(n)}async flushCacheByAddress(e){$d(e);const t=this.buildEndpoint(Be,{address:kn(e,"address")}),n=await this.http.delete(t,void 0,this.getDualAuthHeaders());return this.extractData(n)}async flushCacheByToken(e){!function(e){if(!or(e))throw Ht("tokenName","Token name")}(e);const t=this.buildEndpoint(Ge,{tokenName:e}),n=await this.http.delete(t,void 0,this.getDualAuthHeaders());return this.extractData(n)}async flushAllCache(e){!function(e){if(!0!==e)throw new kt("Safety confirmation required: must pass confirm=true to flush all cache","confirm","CONFIRMATION_REQUIRED")}(e);const t=$e,n=await this.http.delete(t,{confirm:"true"},this.getDualAuthHeaders());return this.extractData(n)}async flushWalletAliasCache(e){if(void 0!==e){$d(e);const t=this.buildEndpoint(Ke,{address:kn(e,"address")}),n=await this.http.delete(t,void 0,this.getDualAuthHeaders());return this.extractData(n)}const t=He,n=await this.http.delete(t,{confirm:"true"},this.getDualAuthHeaders());return this.extractData(n)}}function nu(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 ru 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),sn(t,"Platform config operation failed",!0),e.data}async getPlatformConfig(){const e=await this.http.get(j);return this.extractData(e)}async updatePlatformConfig(e){const t=nu(e);if(t.length>0)throw new kt(t.join("; "),"options","VALIDATION_FAILED");const n=await this.http.put(q,e,this.getJwtHeaders());return this.extractData(n)}async getAvailableRoles(){const e=await this.http.get(Q);return this.extractData(e)}}class su 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(ct),t=this.extractData(e);return this.logger.debug("Fetched platform stats",{totalTokens:t.totalTokens,timestamp:t.timestamp}),{stats:t}}}class iu extends zo{constructor(e,t,n,r){super(e,t,n,!1,r)}async getRestrictedNames(){try{return{success:!0,data:(await this.http.get(Je,void 0,this.getJwtHeaders())).data}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}async updateRestrictedNames(e){try{if("string"!=typeof e.content)throw new kt("Content is required");return{success:!0,data:(await this.http.put(Ze,{content:e.content},this.getJwtHeaders())).data}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}}class ou extends zo{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async getChatStatus(e){if(null==e||""===e)throw Ht("tokenName","Token name");return this.validateTokenName(e,Cr),So(async()=>{const t=this.buildEndpoint(et,{tokenName:e}),n=await this.http.get(t);return this.buildChatStatusResponse(e,this.extractData(n))},`Failed to get chat status for token: ${e}`,this.logger)}async disableChat(e){if(null==e||""===e)throw Ht("tokenName","Token name");return this.validateTokenName(e,Cr),So(async()=>{const t=this.buildEndpoint(nt,{tokenName:e}),n=await this.http.post(t,{enabled:!1},this.getDualAuthHeaders());return this.buildChatStatusResponse(e,this.extractData(n))},`Failed to disable chat for token: ${e}`,this.logger)}async enableChat(e){if(null==e||""===e)throw Ht("tokenName","Token name");return this.validateTokenName(e,Cr),So(async()=>{const t=this.buildEndpoint(tt,{tokenName:e}),n=await this.http.post(t,{enabled:!0},this.getDualAuthHeaders());return this.buildChatStatusResponse(e,this.extractData(n))},`Failed to enable chat for token: ${e}`,this.logger)}buildChatStatusResponse(e,t){const n={enabled:t.enabled,tokenName:t.tokenName??gn(e)};return void 0!==t.status&&null!==t.status&&(n.status=t.status),"global"!==t.reason&&"token"!==t.reason||(n.reason=t.reason),"number"==typeof t.slowModeSeconds&&(n.slowModeSeconds=t.slowModeSeconds),n}async setSlowMode(e,t){if(null==e||""===e)throw Ht("tokenName","Token name");if(this.validateTokenName(e,Cr),"number"!=typeof t||t<0||t>600)throw new Error("slowModeSeconds must be a number between 0 and 600");return So(async()=>{const n=this.buildEndpoint(rt,{tokenName:e}),r=await this.http.patch(n,{slowModeSeconds:t},this.getDualAuthHeaders());return this.extractData(r)},`Failed to set slow mode for token: ${e}`,this.logger)}}const au={IDLE:"IDLE",ACTIVE:"ACTIVE",DISABLED:"DISABLED"},cu={PREPARING:"preparing",READY:"ready",ERRORED:"errored"},lu={IDLE:"idle",STARTING:"starting",BROADCASTING:"broadcasting",ERRORED:"errored"},du={YOUTUBE:"youtube",TWITCH:"twitch",FACEBOOK:"facebook",CUSTOM:"custom"},uu=dr(au),hu=dr(cu),gu=dr(du);function mu(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&uu(t.status)&&(null===t.playbackId||"string"==typeof t.playbackId)&&"boolean"==typeof t.isLive}function fu(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"number"==typeof t.viewerCount}const pu={OWNER:"OWNER",MANAGER:"MANAGER",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MODERATOR:"MODERATOR"},Eu={OWNER:"OWNER",MODERATOR:"MODERATOR"};dr(pu),dr(Eu);const Au={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"},vu={...pu,OVERSEER:"OVERSEER"},Tu=dr(vu);function yu(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 Su(e,t="tokenName"){hr(e,t,Cr)}const bu=/^rtmps?:\/\/\S+$/u,Nu=255;function wu(e){if(Su(e.tokenName),!or(e.language))throw Ht("language");if(t=e.language,!or(t)||!/^[a-z]{2}(-[A-Z]{2})?$/.test(t))throw new kt('language must be a valid ISO 639-1 code (e.g., "en", "es", "zh-CN")',"language",wt.INVALID_FORMAT);var t}const ku={STREAM_STARTED:"stream.started",STREAM_STOPPED:"stream.stopped",RECORDING_READY:"recording.ready",SIMULCAST_ERROR:"simulcast.error"};class _u extends zo{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async startStream(e){this.validateTokenName(e,Cr);const t=this.buildEndpoint(U,{tokenName:e}),n=await this.http.post(t,{},this.getJwtHeaders());return this.extractData(n)}async stopStream(e){this.validateTokenName(e,Cr);const t=this.buildEndpoint(F,{tokenName:e});await this.http.post(t,{},this.getJwtHeaders())}async disableStream(e){return this.toggleFeature(e,P,Cr)}async enableStream(e){return this.toggleFeature(e,x,Cr)}async resetStreamKey(e){this.validateTokenName(e,Cr);const t=this.buildEndpoint(B,{tokenName:e}),n=await this.http.post(t,{},this.getJwtHeaders());return this.extractData(n)}async getStreamCredentials(e){this.validateTokenName(e,Cr);const t=this.buildEndpoint(J,{tokenName:e}),n=await this.http.get(t,{},this.getJwtHeaders());return this.extractData(n)}async getRecordings(e){!function(e){Su(e.tokenName)}(e);const t=this.buildEndpoint(G,{tokenName:e.tokenName}),n=await this.http.get(t),r=this.extractData(n);if(!Array.isArray(r))throw Vt("Invalid recordings response: expected an array of recordings");return{recordings:r,tokenName:gn(e.tokenName)}}async getRecordingDownload(e,t){this.validateTokenName(e,Cr),this.validateRequiredString(t,"assetId","Asset ID");const n=this.buildEndpoint($,{tokenName:e,assetId:t}),r=await this.http.get(n,{},this.getJwtHeaders());return this.extractData(r)}async deleteRecording(e,t){this.validateTokenName(e,Cr),this.validateRequiredString(t,"assetId","Asset ID");const n=this.buildEndpoint(K,{tokenName:e,assetId:t});await this.http.delete(n,void 0,this.getJwtHeaders())}async getSimulcastTargets(e){this.validateTokenName(e,Cr);const t=this.buildEndpoint(H,{tokenName:e}),n=await this.http.get(t,void 0,this.getJwtHeaders()),r=this.extractData(n);if(!Array.isArray(r))throw Vt("Invalid simulcast response: expected an array of targets");return{targets:r,tokenName:gn(e)}}async addSimulcastTarget(e){!function(e){if(Su(e.tokenName),!or(e.platform))throw Ht("platform");if(!gu(e.platform))throw new kt("platform must be one of: 'youtube', 'twitch', 'facebook', 'custom'","platform",wt.INVALID_VALUE);if(!or(e.url))throw Ht("url");if(!bu.test(e.url))throw new kt("url must be a valid RTMP or RTMPS URL","url",wt.INVALID_FORMAT);if(e.url.length>2048)throw new kt(`url must not exceed ${String(2048)} characters`,"url",wt.TOO_LONG);if(!or(e.streamKey))throw Ht("streamKey");if(e.streamKey.length>Nu)throw new kt(`streamKey must not exceed ${String(Nu)} characters`,"streamKey",wt.TOO_LONG);if(void 0!==e.passthrough){if("string"!=typeof e.passthrough)throw new kt("passthrough must be a string","passthrough",wt.INVALID_TYPE);if(e.passthrough.length>Nu)throw new kt(`passthrough must not exceed ${String(Nu)} characters`,"passthrough",wt.TOO_LONG)}}(e);const t=this.buildEndpoint(W,{tokenName:e.tokenName}),n=await this.http.post(t,{platform:e.platform,url:e.url,streamKey:e.streamKey,...void 0!==e.passthrough&&{passthrough:e.passthrough}},this.getJwtHeaders());return{target:this.extractData(n),tokenName:gn(e.tokenName)}}async removeSimulcastTarget(e,t){this.validateTokenName(e,Cr),this.validateRequiredString(t,"targetId","Target ID");const n=this.buildEndpoint(V,{tokenName:e,targetId:t});await this.http.delete(n,void 0,this.getJwtHeaders())}async getGlobalStreamingStatus(){const e=await this.http.get(j);return this.extractData(e)}async disableGlobalStreaming(){const e=await this.http.put(q,{},this.getAdminHeaders());return this.extractData(e)}async enableGlobalStreaming(){const e=await this.http.put(z,{},this.getAdminHeaders());return this.extractData(e)}async setNextLiveStream(e){let t;!function(e){if(Su(e.tokenName),null!==e.nextLiveStreamAt){if(!(e.nextLiveStreamAt instanceof Date||or(e.nextLiveStreamAt)))throw new kt("nextLiveStreamAt must be a Date, ISO 8601 string, or null","nextLiveStreamAt",wt.INVALID_TYPE);if("string"==typeof e.nextLiveStreamAt){const t=Date.parse(e.nextLiveStreamAt);if(isNaN(t))throw new kt("nextLiveStreamAt must be a valid ISO 8601 date string","nextLiveStreamAt",wt.INVALID_FORMAT)}}}(e),t=null===e.nextLiveStreamAt?null:e.nextLiveStreamAt instanceof Date?e.nextLiveStreamAt.toISOString():e.nextLiveStreamAt;const n=`/v1/tokens/${e.tokenName.toLowerCase().trim()}`;await this.http.patch(n,{nextLiveStreamAt:t},this.getJwtHeaders())}async clearNextLiveStream(e){this.validateTokenName(e,Cr);const t=`/v1/tokens/${e.toLowerCase().trim()}`;await this.http.patch(t,{nextLiveStreamAt:null},this.getJwtHeaders())}async setStreamLanguage(e){wu(e);const t=`/v1/tokens/${e.tokenName.toLowerCase().trim()}`;await this.http.patch(t,{streamLanguage:e.language},this.getJwtHeaders())}async getStreamRole(e){!function(e){Su(e.tokenName)}(e);const t=this.buildEndpoint(X,{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(Q);return this.extractData(e)}async getTokenAccess(e){!function(e){Su(e.tokenName)}(e);const t=await this.http.get(Y,{tokenName:gn(e.tokenName)},this.getJwtHeaders());return this.extractData(t)}async setNextLiveStreamCountdown(e,t){return this.setNextLiveStream({tokenName:e,nextLiveStreamAt:t})}}const Iu={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"},Du=e=>Cu(e.flagId);function Cu(e){return"string"==typeof e||"number"==typeof e?String(e):void 0}function Ru(e,t){const n=t.map(t=>Cu(e[t]));return n.every(e=>void 0!==e)?n.join("|"):void 0}const Ou={STREAM_STATUS:{},RECORDING_STATUS:{},RECORDINGS_COUNT_UPDATED:{},SIMULCAST_STATUS:{},DOWNLOAD_READY:{},STREAM_COUNTDOWN_UPDATED:{},STREAM_LANGUAGE_UPDATED:{},VIEWER_COUNT:{},STREAM_CONTROL_STATUS_CHANGED:{},STREAM_GLOBAL_STATUS:{token:"none"},ENGAGEMENT_STATS_UPDATED:{},STREAM_CHAT_MESSAGE:{},STREAM_CHAT_SENT:{},STREAM_CHAT_UPDATED:{},STREAM_CHAT_DELETED:{},STREAM_CHAT_PINNED:{},STREAM_CHAT_UNPINNED:{},CHAT_STATUS_CHANGED:{},SLOW_MODE_CHANGED:{},STREAM_CHAT_GLOBAL_STATUS:{token:"none"},USER_TYPING:{},stream_chat_error:{},STREAM_REACTION:{},stream_reaction_error:{},CONTENT_REACTION_ADDED:{},CONTENT_REACTION_REMOVED:{},COMMENT_CREATED:{},COMMENT_UPDATED:{},COMMENT_DELETED:{},TRADE_EXECUTED:{},TRADE_UPDATE_NOTIFY:{token:"none"},BALANCE_UPDATED:{},STATS_UPDATED:{},USER_BANNED:{},USER_UNBANNED:{},BAN_ENFORCEMENT:{},TOKEN_BANNED:{},TOKEN_UNBANNED:{},CONTENT_FLAGGED:{duplicateKey:e=>Cu(e.id)},FLAG_RESOLVED:{duplicateKey:e=>Ru(e,["id","status","reviewedAt"])},AI_MODERATION_COMPLETE:{duplicateKey:Du},AI_MODERATION_FAILED:{duplicateKey:Du},MODERATOR_INVITE_CREATED:{},MODERATOR_ADDED:{},MODERATOR_REMOVED:{},MODERATOR_ROLE_UPDATED:{},OVERSEER_ADDED:{token:"none",duplicateKey:e=>Ru(e,["userAddress","addedAt"])},OVERSEER_REMOVED:{token:"none",duplicateKey:e=>Ru(e,["userAddress","removedAt"])},POOL_CREATED:{duplicateKey:e=>Ru(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 Mu(e){return Ou[e]}const Lu=Object.keys(Ou);const Uu="token:",Fu="comment:",Pu="global:feed",xu="global:events_firehose";function Bu(e){if(e.startsWith(Uu)){const t={tokenName:e.slice(Uu.length)};return{join:{event:Iu.SUBSCRIBE,payload:t},leave:{event:Iu.UNSUBSCRIBE,payload:t}}}if(e.startsWith(Fu)){const t={tokenName:e.slice(8)};return{join:{event:Iu.SUBSCRIBE_COMMENT,payload:t},leave:{event:Iu.UNSUBSCRIBE_COMMENT,payload:t}}}return e===xu?{join:{event:Iu.SUBSCRIBE_EVENTS_FIREHOSE},leave:{event:Iu.UNSUBSCRIBE_EVENTS_FIREHOSE}}:{join:{event:Iu.SUBSCRIBE_GLOBAL_FEED},leave:{event:Iu.UNSUBSCRIBE_GLOBAL_FEED}}}const Gu=new Set(["token_subscribed","room_subscribed","global_feed_subscribed","events_firehose_subscribed"]);const $u={STREAM_CHAT_GLOBAL_STATUS:"chatEnabled",STREAM_GLOBAL_STATUS:"streamingEnabled",COMMENTS_GLOBAL_STATUS:"commentsEnabled",WEBHOOKS_GLOBAL_STATUS:"webhooksEnabled",AI_MODERATION_GLOBAL_STATUS:"aiModerationEnabled"},Ku=["STREAM_STATUS","TRADE_EXECUTED","HOLDER_COUNT_UPDATED","POOL_BADGE_ASSIGNED","VIEWER_COUNT","TOKEN_CONFIG_UPDATED","STATS_UPDATED","POOL_CREATED"],Hu=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"]),Wu=new Set(["COMMENT_CREATED","COMMENT_UPDATED","COMMENT_DELETED"]);const Vu={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"},ju={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"},qu=()=>{};function zu(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Xu(e,t){return t}function Qu(e){return`${Uu}${e}`}function Yu(e){return`${Fu}${e}`}function Ju(e){const t=gn(e);if(""===t)throw Ht("tokenName","Token name");return t}class Zu extends wr{constructor(e,t=!1){if(super(t),this.socket=null,this.disposed=!1,this.epoch=0,this.connectionGeneration=0,this.hasConnected=!1,this.connectAttempt=null,this.reconnectExhausted=!1,this.managerCleanups=[],this.connectionStateListeners=new Set,this.reconnectListeners=new Set,this.subscribers=new Map,this.roomRefs=new Map,this.roomStates=new Map,this.roomWaiters=new Map,this.explicitHolds=new Map,this.recentOccurrences=new Map,this.siteConfig={chatEnabled:void 0,streamingEnabled:void 0,commentsEnabled:void 0,webhooksEnabled:void 0,aiModerationEnabled:void 0},this.authenticated=!1,this.authenticatedToken=null,this.authenticatedGeneration=-1,this.wantsAuthentication=!1,this.lastExplicitToken=null,this.authSequence=0,this.inFlight=null,this.lastEmitted=null,this.pendingAuthenticate=null,""===e.url)throw new Ot("Stream WebSocket URL is required. Set streamWebSocketUrl in SDK config.");this.config={url:e.url,reconnectAttempts:e.reconnectAttempts??5,reconnectDelay:e.reconnectDelay??2e3,reconnectDelayMax:e.reconnectDelayMax,subscriptionTimeout:e.subscriptionTimeout??1e4,tokenProvider:e.tokenProvider,autoConnect:e.autoConnect??!0},this.isSocketIOAvailable="function"==typeof _}register(e,t,n={}){if(this.disposed)return qu;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 qu;let t=!0;return this.acquireRoom(e),this.openIfNeeded(),()=>{t&&(t=!1,this.releaseRoom(e))}}openIfNeeded(){this.config.autoConnect&&!this.disposed&&(null===this.socket||this.reconnectExhausted)&&this.connect().catch(e=>{this.logger.warn(`Stream WebSocket connect failed: ${Ut(e)}`)})}acquireRoom(e){this.roomRefs.set(e,(this.roomRefs.get(e)??0)+1),this.syncRoom(e)}releaseRoom(e){const t=(this.roomRefs.get(e)??1)-1;t<=0?this.roomRefs.delete(e):this.roomRefs.set(e,t),this.syncRoom(e)}syncRoom(e){const t=this.liveSocket();if(null===t)return;const n=(this.roomRefs.get(e)??0)>0,r=this.roomStates.get(e);if(n&&void 0===r){if(function(e){return e===xu}(e)&&!this.authenticated)return;this.joinRoom(t,e)}else n||"joined"!==r?.phase||(t.emit(Bu(e).leave.event,Bu(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=Bu(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(Uu)?e.slice(Uu.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((!zu(t)||!this.isDuplicate(e,t))&&(this.deliver(e,t,zu(t)?function(e,t){const n=Mu(e).token??"payload";if("none"===n)return;if("room"===n){const e=t.room;return"string"==typeof e&&e.startsWith(Uu)?e.slice(Uu.length):void 0}const r=t.tokenName;return"string"==typeof r&&""!==r?r:void 0}(e,t):void 0),zu(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=Mu(e).duplicateKey?.(t);if(void 0===n)return!1;const r=Date.now(),s=`${e}:${n}`,i=this.recentOccurrences.get(s);if(void 0!==i&&r-i<5e3)return!0;if(this.recentOccurrences.set(s,r),this.recentOccurrences.size>256)for(const[e,t]of this.recentOccurrences)r-t>=5e3&&this.recentOccurrences.delete(e);return!1}deliver(e,t,n){const r=this.subscribers.get(e);if(void 0===r)return;const s=void 0===n?void 0:gn(n);for(const n of[...r])n.active&&(void 0!==n.token&&n.token!==s||(void 0===n.filter||this.passes(n,t))&&this.invoke(e,n.deliver,t))}passes(e,t){try{return e.filter?.(t)??!0}catch(t){return this.logger.error(`Error in a ${e.name} filter:`,t),!1}}invoke(e,t,n){try{const r=t(n);r instanceof Promise&&r.catch(t=>{this.logger.error(`Error in a ${e} subscriber:`,t)})}catch(t){this.logger.error(`Error in a ${e} subscriber:`,t)}}applyEffects(e,t){if("authenticated"===e)null!==this.inFlight?this.inFlight.settle(!0):this.adoptLateAuthentication();else if("stream_chat_auth_error"===e)this.authenticated=!1,this.inFlight?.settle(!1);else if("exception"===e)this.inFlight?.settle(!1);else if(function(e){return Gu.has(e)}(e))zu(t)&&"string"==typeof t.room&&this.onRoomAcknowledged(t.room);else{const n=$u[e];void 0!==n&&(this.siteConfig={...this.siteConfig,[n]:eh(t)})}}liveSocket(){return null!==this.socket&&this.socket.connected?this.socket:null}connect(){if(this.disposed)return Promise.reject(new Ot("The stream WebSocket service has been disposed."));if(!this.isSocketIOAvailable)return Promise.reject(new Ot('Socket.IO not available. Install "socket.io-client" package.'));const e=this.socket??this.createSocket();if(e.connected)return Promise.resolve();if(null===this.connectAttempt){let e=()=>{},t=()=>{};const n=new Promise((n,r)=>{e=n,t=r});this.connectAttempt={promise:n,resolve:e,reject:t}}return e.connect(),this.connectAttempt.promise}createSocket(){this.logger.debug(`🔌 Connecting to Stream WebSocket: ${this.config.url}`);const e=_(this.config.url,{transports:["websocket"],reconnection:!0,reconnectionAttempts:this.config.reconnectAttempts,reconnectionDelay:this.config.reconnectDelay,...void 0!==this.config.reconnectDelayMax&&{reconnectionDelayMax:this.config.reconnectDelayMax}});return this.socket=e,this.attachListeners(e),e}attachListeners(e){e.on("connect",()=>{this.onSocketConnect()}),e.on("disconnect",e=>{this.onSocketDisconnect(e)}),e.on("connect_error",e=>{this.logger.error("❌ Stream WebSocket connection error:",e),this.settleConnectWaiters(e)}),e.on("error",e=>{this.logger.error("❌ Stream WebSocket error:",e)});for(const t of Lu)e.on(t,e=>{this.onServerEvent(t,e)});const t=e=>{this.logger.debug(`🔄 Stream WebSocket reconnect attempt ${String(e)}`)},n=()=>{this.reconnectExhausted=!0,this.logger.error("❌ Stream WebSocket max reconnection attempts reached")};e.io.on("reconnect_attempt",t),e.io.on("reconnect_failed",n),this.managerCleanups.push(()=>e.io.off("reconnect_attempt",t),()=>e.io.off("reconnect_failed",n))}onSocketConnect(){this.connectionGeneration+=1;const e=this.connectionGeneration,t=this.hasConnected;this.hasConnected=!0,this.logger.debug(`✅ Stream WebSocket connected: ${String(this.socket?.id)}`),this.reconnectExhausted=!1,this.clearRoomStates(),this.authenticated=!1,this.notifyConnectionState(!0),this.settleConnectWaiters(void 0),this.wantsAuthentication?this.restoreAfterReconnect(e):(this.syncAllRooms(),t&&this.notifyReconnect())}async restoreAfterReconnect(e){try{await this.authenticate()}catch(e){this.logger.warn(`Re-authentication after reconnect failed: ${Ut(e)}`)}e!==this.connectionGeneration||this.disposed||(this.syncAllRooms(),this.notifyReconnect())}onSocketDisconnect(e){this.logger.debug(`🔌 Stream WebSocket disconnected: ${e}`),this.authenticated=!1,this.inFlight?.settle(!1),this.clearRoomStates(),this.notifyConnectionState(!1),"io server disconnect"!==e||null===this.socket||this.disposed||this.socket.connect()}settleConnectWaiters(e){const t=this.connectAttempt;this.connectAttempt=null,null!==t&&(void 0===e?t.resolve():t.reject(e))}notifyConnectionState(e){for(const t of[...this.connectionStateListeners])this.invoke("connection state",t,e)}notifyReconnect(){for(const e of[...this.reconnectListeners])this.invoke("reconnect",e,void 0)}onConnectionStateChange(e){return this.disposed?qu:(this.connectionStateListeners.add(e),()=>{this.connectionStateListeners.delete(e)})}onReconnect(e){return this.disposed?qu:(this.reconnectListeners.add(e),()=>{this.reconnectListeners.delete(e)})}async resolveToken(){const e=this.config.tokenProvider;if(void 0===e)return this.lastExplicitToken;try{const t=await e();return null!==t&&""!==t?t:null}catch(e){return this.logger.warn(`The token provider failed: ${Ut(e)}`),null}}authenticate(e){if(""===e)return Promise.reject(Ht("token","Authentication token"));const t=this.pendingAuthenticate;if(null!==t&&t.token===e&&t.generation===this.connectionGeneration)return t.promise;this.authSequence+=1;const n=this.authSequence,r=this.runAuthenticate(e,n).finally(()=>{this.pendingAuthenticate?.promise===r&&(this.pendingAuthenticate=null)});return this.pendingAuthenticate={token:e,generation:this.connectionGeneration,promise:r},r}async runAuthenticate(e,t){if(this.disposed)return!1;const n=e??await this.resolveToken();if(t!==this.authSequence||null===n)return!1;void 0!==e&&(this.lastExplicitToken=e);try{await this.connect()}catch(e){return this.logger.warn(`Cannot authenticate, the connection failed: ${Ut(e)}`),!1}for(;null!==this.inFlight;)if(await this.inFlight.settled,t!==this.authSequence)return!1;const r=this.liveSocket();if(t!==this.authSequence||null===r)return!1;if(this.authenticated&&this.authenticatedToken===n&&this.authenticatedGeneration===this.connectionGeneration)return!0;const s=this.beginAuthentication(t,n);this.lastEmitted={seq:t,token:n,generation:this.connectionGeneration},this.logger.debug("📡 Authenticating with stream server"),r.emit(Iu.AUTHENTICATE,{token:n});return await s.result&&t===this.authSequence}beginAuthentication(e,t){let n=()=>{};const r=new Promise(e=>{n=e}),s={seq:e,token:t,generation:this.connectionGeneration,result:r,settled:r.then(()=>{}),timer:void 0,settle:e=>{this.finishAuthentication(s,e,n)}};return s.timer=setTimeout(()=>{this.logger.warn("Stream WebSocket authentication timed out"),s.settle(!1)},this.config.subscriptionTimeout),this.inFlight=s,s}finishAuthentication(e,t,n){if(this.inFlight!==e)return;void 0!==e.timer&&clearTimeout(e.timer),this.inFlight=null;const r=e.seq===this.authSequence&&e.generation===this.connectionGeneration;t&&r&&this.markAuthenticated(e.token,e.generation),n(t&&r)}markAuthenticated(e,t){this.authenticated=!0,this.authenticatedToken=e,this.authenticatedGeneration=t,this.wantsAuthentication=!0,this.syncAllRooms()}adoptLateAuthentication(){const e=this.lastEmitted;null===e||this.authenticated||e.seq===this.authSequence&&e.generation===this.connectionGeneration&&this.markAuthenticated(e.token,e.generation)}deauthenticate(){this.authSequence+=1;const e=this.authenticated||null!==this.inFlight;this.inFlight?.settle(!1),this.pendingAuthenticate=null,this.wantsAuthentication=!1,this.lastExplicitToken=null,this.authenticated=!1,this.authenticatedToken=null,this.authenticatedGeneration=-1,e&&null!==this.socket&&!this.disposed&&(this.socket.disconnect(),this.socket.connect())}isAuthenticatedForChat(){return this.authenticated}isConnected(){return this.socket?.connected??!1}requireReady(){const e=this.liveSocket();if(null===e)throw new kt("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(!this.authenticated)throw new kt("Not authenticated. Call authenticate() first.","auth","NOT_AUTHENTICATED");return e}sendChatMessage(e,t){if(""===e)throw Ht("tokenName","Token name");if(""===t)throw Ht("content","Message content");const n=this.requireReady(),r=gn(e);this.logger.debug(`📡 Sending chat message to ${r}: ${t.slice(0,30)}...`),n.emit(Iu.SEND_CHAT,{tokenName:r,content:t})}sendReaction(e,t,n=0){if(""===e)throw Ht("tokenName","Token name");if(""===t)throw Ht("emoji");const r=this.requireReady(),s=gn(e);this.logger.debug(`📡 Sending reaction to ${s}: ${t}`),r.emit(Iu.SEND_REACTION,{tokenName:s,emoji:t,streamTime:n})}sendTypingStart(e){this.sendTypingEvent(e,Iu.TYPING_START)}sendTypingStop(e){this.sendTypingEvent(e,Iu.TYPING_STOP)}sendTypingEvent(e,t){if(""===e)throw Ht("tokenName","Token name");this.requireReady().emit(t,{tokenName:gn(e)})}subscribeToken(e,t,n){const r=Ju(t);return this.register(e,e=>n(Xu(0,e)),{token:r,room:Qu(r)})}joinTokenRoom(e){return this.hold(Qu(Ju(e)))}subscribeComment(e,t,n){const r=Ju(t);return this.register(e,e=>n(Xu(0,e)),{token:r,room:Yu(r)})}subscribeFeed(e,t){return this.register(e,e=>t(Xu(0,e)),{room:Pu})}subscribeEvent(e,t){return this.register(e,e=>t(Xu(0,e)))}subscribeEventsFirehose(e,t){const n=function(e){if(void 0===e)return;const t=e.eventTypes?.map(e=>e.toLowerCase()),n=void 0===e.tokenName?void 0:gn(e.tokenName),r=e.userAddress;return void 0!==t||void 0!==n||void 0!==r?e=>{if(!zu(e))return!1;const s=e.eventType;if(void 0!==t&&("string"!=typeof s||!t.includes(s.toLowerCase())))return!1;const i=e.tokenName;if(void 0!==n&&("string"!=typeof i||gn(i)!==n))return!1;const o=e.userAddress;return void 0===r||"string"==typeof o&&Dn(o,r)}:void 0}(t);return this.register("EVENT",t=>e(Xu(0,t)),{room:xu,...void 0!==n&&{filter:n}})}subscribeFeedTokenEvents(e){const t=Ku.map(t=>this.register(t,n=>e(function(e,t){return{event:e,data:Xu(0,t)}}(t,n)),{room:Pu}));return()=>{for(const e of t)e()}}subscribeToGlobalFeed(e={}){const t=this.registerCallbacks(e,ju,()=>({})),n=this.hold(Pu);return()=>{t(),n()}}addCallbacks(e){return this.registerCallbacks(e,Vu,()=>({}))}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=Ju(e),r=Qu(n),s=this.epoch;if(await this.connect(),s!==this.epoch||this.disposed)throw new Error("WebSocket disconnected");const i=this.registerCallbacks(t,Vu,e=>{return t=e,Hu.has(t)?{token:n}:function(e){return Wu.has(e)}(e)?{token:n,room:Yu(n)}:{};var t}),o=this.hold(r),a={release:()=>{i(),o()}},c=this.explicitHolds.get(n)??[];c.push(a),this.explicitHolds.set(n,c);try{return await this.waitForRoom(r,n)}catch(e){throw this.dropExplicitHold(n,a),e}}waitForRoom(e,t){return"joined"===this.roomStates.get(e)?.phase?Promise.resolve({room:e,tokenName:t}):new Promise((n,r)=>{const s={resolve:n,reject:r,timer:setTimeout(()=>{this.roomWaiters.get(e)?.delete(s),r(new Error(`Subscription to ${t} timed out after ${this.config.subscriptionTimeout}ms`))},this.config.subscriptionTimeout)},i=this.roomWaiters.get(e)??new Set;i.add(s),this.roomWaiters.set(e,i)})}dropExplicitHold(e,t){t.release();const n=(this.explicitHolds.get(e)??[]).filter(e=>e!==t);0===n.length?this.explicitHolds.delete(e):this.explicitHolds.set(e,n)}unsubscribeFromStream(e){const t=gn(e),n=this.explicitHolds.get(t);if(void 0!==n){this.explicitHolds.delete(t);for(const e of n)e.release()}else this.logger.debug(`📡 Not subscribed to ${t} through subscribeToStream, skipping unsubscribe`)}subscribeStreamStatus(e,t){return this.subscribeToken("STREAM_STATUS",e,t)}subscribeViewerCount(e,t){return this.subscribeToken("VIEWER_COUNT",e,t)}subscribeRecordingStatus(e,t){return this.subscribeToken("RECORDING_STATUS",e,t)}subscribeRecordingsCountUpdated(e,t){return this.subscribeToken("RECORDINGS_COUNT_UPDATED",e,t)}subscribeSimulcastStatus(e,t){return this.subscribeToken("SIMULCAST_STATUS",e,t)}subscribeDownloadReady(e,t){return this.subscribeToken("DOWNLOAD_READY",e,t)}subscribeCountdownUpdated(e,t){return this.subscribeToken("STREAM_COUNTDOWN_UPDATED",e,t)}subscribeLanguageUpdated(e,t){return this.subscribeToken("STREAM_LANGUAGE_UPDATED",e,t)}subscribeStreamControlStatusChanged(e,t){return this.subscribeToken("STREAM_CONTROL_STATUS_CHANGED",e,t)}subscribeEngagementStatsUpdated(e,t){return this.subscribeToken("ENGAGEMENT_STATS_UPDATED",e,t)}subscribeChatMessages(e,t){return this.subscribeToken("STREAM_CHAT_MESSAGE",e,t)}subscribeChatSent(e,t){return this.subscribeToken("STREAM_CHAT_SENT",e,t)}subscribeChatUpdated(e,t){return this.subscribeToken("STREAM_CHAT_UPDATED",e,t)}subscribeChatDeleted(e,t){return this.subscribeToken("STREAM_CHAT_DELETED",e,t)}subscribeChatPinned(e,t){return this.subscribeToken("STREAM_CHAT_PINNED",e,t)}subscribeChatUnpinned(e,t){return this.subscribeToken("STREAM_CHAT_UNPINNED",e,t)}subscribeChatStatus(e,t){return this.subscribeToken("CHAT_STATUS_CHANGED",e,t)}subscribeChatSlowMode(e,t){return this.subscribeToken("SLOW_MODE_CHANGED",e,t)}subscribeTypingIndicator(e,t){return this.subscribeToken("USER_TYPING",e,t)}subscribeReactions(e,t){return this.subscribeToken("STREAM_REACTION",e,t)}subscribeContentReactionAdded(e,t){return this.subscribeToken("CONTENT_REACTION_ADDED",e,t)}subscribeContentReactionRemoved(e,t){return this.subscribeToken("CONTENT_REACTION_REMOVED",e,t)}subscribeTradeExecuted(e,t){return this.subscribeToken("TRADE_EXECUTED",e,t)}subscribeBalanceUpdated(e,t){return this.subscribeToken("BALANCE_UPDATED",e,t)}subscribeTokenBanned(e,t){return this.subscribeToken("TOKEN_BANNED",e,t)}subscribeTokenUnbanned(e,t){return this.subscribeToken("TOKEN_UNBANNED",e,t)}subscribeModeratorInviteCreated(e,t){return this.subscribeToken("MODERATOR_INVITE_CREATED",e,t)}subscribeModeratorAdded(e,t){return this.subscribeToken("MODERATOR_ADDED",e,t)}subscribeModeratorRemoved(e,t){return this.subscribeToken("MODERATOR_REMOVED",e,t)}subscribeModeratorRoleUpdated(e,t){return this.subscribeToken("MODERATOR_ROLE_UPDATED",e,t)}subscribePoolMetadataUpdated(e,t){return this.subscribeToken("POOL_METADATA_UPDATED",e,t)}subscribePoolSocialLinksUpdated(e,t){return this.subscribeToken("POOL_SOCIAL_LINKS_UPDATED",e,t)}subscribePoolBadgeAssigned(e,t){return this.subscribeToken("POOL_BADGE_ASSIGNED",e,t)}subscribeHolderCountUpdated(e,t){return this.subscribeToken("HOLDER_COUNT_UPDATED",e,t)}subscribeTokenConfigUpdated(e,t){return this.subscribeToken("TOKEN_CONFIG_UPDATED",e,t)}subscribeCommentCreated(e,t){return this.subscribeComment("COMMENT_CREATED",e,t)}subscribeCommentUpdated(e,t){return this.subscribeComment("COMMENT_UPDATED",e,t)}subscribeCommentDeleted(e,t){return this.subscribeComment("COMMENT_DELETED",e,t)}subscribeStatsUpdated(e){return this.subscribeFeed("STATS_UPDATED",e)}subscribePoolCreated(e){return this.subscribeFeed("POOL_CREATED",e)}subscribeStreamGlobalStatus(e){return this.subscribeFeed("STREAM_GLOBAL_STATUS",e)}subscribeChatGlobalStatus(e){return this.subscribeFeed("STREAM_CHAT_GLOBAL_STATUS",e)}subscribeCommentsGlobalStatus(e){return this.subscribeFeed("COMMENTS_GLOBAL_STATUS",e)}subscribeWebhooksGlobalStatus(e){return this.subscribeFeed("WEBHOOKS_GLOBAL_STATUS",e)}subscribeAIModerationGlobalStatus(e){return this.subscribeFeed("AI_MODERATION_GLOBAL_STATUS",e)}subscribeSiteConfigChanged(e){return this.subscribeFeed("SITE_CONFIG_CHANGED",e)}getSiteConfigState(){return{...this.siteConfig}}subscribeOverseerAdded(e){return this.subscribeEvent("OVERSEER_ADDED",e)}subscribeOverseerRemoved(e){return this.subscribeEvent("OVERSEER_REMOVED",e)}subscribeUserProfileUpdated(e){return this.subscribeEvent("USER_PROFILE_UPDATED",e)}subscribeApiKeyCreated(e){return this.subscribeEvent("API_KEY_CREATED",e)}subscribeApiKeyUpdated(e){return this.subscribeEvent("API_KEY_UPDATED",e)}subscribeApiKeyRevoked(e){return this.subscribeEvent("API_KEY_REVOKED",e)}subscribeGlobalTokenBanned(e){return this.subscribeEvent("TOKEN_BANNED",e)}subscribeGlobalTokenUnbanned(e){return this.subscribeEvent("TOKEN_UNBANNED",e)}subscribeGlobalModeratorAdded(e){return this.subscribeEvent("MODERATOR_ADDED",e)}subscribeGlobalModeratorRemoved(e){return this.subscribeEvent("MODERATOR_REMOVED",e)}subscribeGlobalModeratorRoleUpdated(e){return this.subscribeEvent("MODERATOR_ROLE_UPDATED",e)}subscribeGlobalModeratorInviteCreated(e){return this.subscribeEvent("MODERATOR_INVITE_CREATED",e)}subscribeContentFlagged(e){return this.subscribeEvent("CONTENT_FLAGGED",e)}subscribeFlagResolved(e){return this.subscribeEvent("FLAG_RESOLVED",e)}subscribeAIModerationComplete(e){return this.subscribeEvent("AI_MODERATION_COMPLETE",e)}subscribeAIModerationFailed(e){return this.subscribeEvent("AI_MODERATION_FAILED",e)}subscribeUserBanned(e){return this.subscribeEvent("USER_BANNED",e)}subscribeUserUnbanned(e){return this.subscribeEvent("USER_UNBANNED",e)}subscribeBanEnforcement(e){return this.subscribeEvent("BAN_ENFORCEMENT",e)}subscribeTradeUpdateNotify(e){return this.subscribeEvent("TRADE_UPDATE_NOTIFY",e)}subscribeReactionErrors(e){return this.subscribeEvent("stream_reaction_error",e)}subscribeChatErrors(e){return this.subscribeEvent("stream_chat_error",e)}subscribeException(e){return this.subscribeEvent("exception",e)}getSubscribedTokens(){const e=[];for(const t of this.roomRefs.keys())t.startsWith(Uu)&&e.push(t.slice(Uu.length));return e}isSubscribedToGlobalFeed(){return(this.roomRefs.get(Pu)??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 eh(e){if(!zu(e))return;const t=e.enabled;return"boolean"==typeof t?t:void 0}function th(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 nh(e){return null==e||""===e||"string"==typeof e&&(!vr(e)&&e.length<=Pr.BAN_REASON.MAX_LENGTH)}function rh(e){if(hr(e.tokenName,"tokenName",Ir),!nh(e.reason))throw new kt(`reason must be at most ${Pr.BAN_REASON.MAX_LENGTH} characters`,"reason","TOO_LONG")}function sh(e){hr(e.tokenName,"tokenName",Cr)}function ih(e){lr(0,void 0,Mr,e.pageSize)}function oh(e){hr(e.tokenName,"tokenName",Cr)}class ah extends zo{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async banToken(e){rh(e);const t=We,n={tokenName:gn(e.tokenName)};if(void 0!==e.reason)try{Zn(e.reason,"reason",!0),e.reason.trim().length>0&&(n.reason=e.reason)}catch{}const r=await this.http.post(t,n,this.getDualAuthHeaders());return{ban:this.extractData(r),tokenName:gn(e.tokenName)}}async unbanToken(e){sh(e);const t=this.buildEndpoint(qe,{tokenName:e.tokenName});return sn(await this.http.delete(t,void 0,this.getDualAuthHeaders()),"Failed to unban token",!1),{tokenName:gn(e.tokenName)}}async listTokenBans(e={}){ih(e);const t=Ve,n=this.buildPaginationParams(e,Mr);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){oh(e);const t=this.buildEndpoint(je,{tokenName:e.tokenName}),n=await this.http.get(t,{},this.getDualAuthHeaders()),r=this.extractDataOrNull(n);return{banned:null!==r,...null!==r&&{ban:r},tokenName:gn(e.tokenName)}}async isTokenBanned(e){return this.getTokenBan(e)}}class ch extends wr{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(!or(e))throw Ht("tokenName","Token name");const t=gn(e),n=this.getCacheEntry(t);if(null!==n)return this.cacheHits++,this.updateAccessOrder(t),n.vaultAddress;this.cacheMisses++;const r=await this.poolService.resolveTokenNameToVault(e);if(null!==r&&""!==r){const e=this.parseVaultAddressToTokenClassKey(r);this.setCacheEntry(t,{vaultAddress:r,tokenClassKey:e,cachedAt:Date.now()})}return r}async resolveTokenClassKey(e){if(!or(e))throw Ht("tokenName","Token name");const t=gn(e),n=this.getCacheEntry(t);if(null!==n)return this.cacheHits++,this.updateAccessOrder(t),n.tokenClassKey;this.cacheMisses++;const r=await this.poolService.resolveTokenNameToVault(e);if(null===r||""===r)throw Kt(e);const s=this.parseVaultAddressToTokenClassKey(r);return this.setCacheEntry(t,{vaultAddress:r,tokenClassKey:s,cachedAt:Date.now()}),s}get(e){const t=this.getCacheEntry(gn(e));return t?.vaultAddress??null}getCacheEntry(e){return this.cache.get(e)??null}setCacheEntry(e,t){this.cache.size>=ch.MAX_CACHE_SIZE&&!this.cache.has(e)&&this.evictOldestEntry(),this.cache.set(e,t),this.updateAccessOrder(e)}updateAccessOrder(e){this.accessOrder.delete(e),this.accessOrder.add(e)}evictOldestEntry(){const e=this.accessOrder.values().next().value;void 0!==e&&""!==e&&(this.cache.delete(e),this.accessOrder.delete(e))}set(e,t){const n=gn(e),r=this.parseVaultAddressToTokenClassKey(t);this.setCacheEntry(n,{vaultAddress:t,tokenClassKey:r,cachedAt:Date.now()})}clear(){this.cache.clear(),this.accessOrder=new Set,this.cacheHits=0,this.cacheMisses=0}getStats(){const e=Array.from(this.cache.values()).map(e=>e.cachedAt),t=this.cacheHits+this.cacheMisses;return{size:this.cache.size,keys:Array.from(this.cache.keys()),maxSize:ch.MAX_CACHE_SIZE,hits:this.cacheHits,misses:this.cacheMisses,hitRate:t>0?this.cacheHits/t:0,oldestEntry:e.length>0?Math.min(...e):null,newestEntry:e.length>0?Math.max(...e):null}}getCachedTokenClassKey(e){const t=this.getCacheEntry(gn(e));return t?.tokenClassKey??null}preWarm(e){for(const{tokenName:t,vaultAddress:n}of e)this.set(t,n)}preWarmWithTokenClassKey(e){for(const{tokenName:t,vaultAddress:n,tokenClassKey:r}of e){const e=gn(t);this.setCacheEntry(e,{vaultAddress:n,tokenClassKey:r,cachedAt:Date.now()})}}parseVaultAddressToTokenClassKey(e){try{return Wa(e)}catch(e){if(e instanceof kt)throw Wt("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad","Vault address");throw e}}}ch.MAX_CACHE_SIZE=1e4;class lh extends Nr{constructor(e,t=!1){super(e,t)}async fetchLaunchpadFee(){const e=await cn(()=>this.http.get(lt),{errorContext:"Failed to fetch launchpad fee"});if("number"!=typeof e.feeAmount||!Number.isFinite(e.feeAmount))throw new kt("Failed to fetch launchpad fee: no feeAmount in the response","feeAmount","INVALID_RESPONSE");return e.feeAmount}async fetchSaleDetails(e){return cn(()=>this.http.get(dt,{tokenName:e}),{errorContext:`Failed to fetch sale details for ${e}`})}async getTradeQuote(e){const t={tokenName:e.tokenName,amount:e.amount,type:e.type,method:e.method},{signal:n}=e;return ao(await cn(()=>void 0===n?this.http.get(ut,t):this.http.request({method:"GET",url:ut,params:t,signal:n}),{errorContext:`Failed to get trade quote for ${e.tokenName}`}),`trade quote for ${e.tokenName}`)}async getPremintQuote(e){return ao(await cn(()=>this.http.get(ht,{amount:e}),{errorContext:"Failed to get premint quote"}),"premint quote")}}class dh extends zo{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async emitTradeExecuted(e,t){this.validateTokenName(e,Or);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,Or);const r={action:"balance_updated",userAddress:kn(e,"userAddress"),tokenName:t,payload:n};await this.emitEvent(r)}async emitStreamStatus(e,t,n=!0){this.validateTokenName(e,Or);const r={action:"stream_status",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitViewerCount(e,t,n=!1){this.validateTokenName(e,Or);const r={action:"viewer_count",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitStreamCountdown(e,t,n=!0){this.validateTokenName(e,Or);const r={action:"stream_countdown",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitChatMessage(e,t,n=!1){this.validateTokenName(e,Or);const r={action:"chat_message",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitChatStatus(e,t,n=!1){this.validateTokenName(e,Or);const r={action:"chat_status",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitTypingIndicator(e,t,n=!1){this.validateTokenName(e,Or);const r={action:"typing_indicator",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitTokenBanned(e,t){this.validateTokenName(e,Or);const n={action:"token_banned",tokenName:e,payload:t,broadcast:!0};await this.emitEvent(n)}async emitTokenUnbanned(e,t){this.validateTokenName(e,Or);const n={action:"token_unbanned",tokenName:e,payload:t,broadcast:!0};await this.emitEvent(n)}async emitModeratorAdded(e,t,n=!1){this.validateTokenName(e,Or);const r={action:"moderator_added",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitModeratorRemoved(e,t,n=!1){this.validateTokenName(e,Or);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:kn(e,"userAddress"),payload:t};await this.emitEvent(n)}async emitSiteConfigChanged(e){const t={action:"site_config_changed",payload:e,broadcast:!0};await this.emitEvent(t)}async emitFeatureStatus(e){const t={action:"feature_status",payload:e,broadcast:!0};await this.emitEvent(t)}async emitEvent(e){this.validateRequiredString(e.action,"action","Event Action");const t=this.buildEndpoint("/v1/websocket",{});await this.http.post(t,e,this.getDualAuthHeaders())}async getConnectedClients(e){const t=this.buildEndpoint("/v1/connected-clients",{}),n={};void 0!==e?.room&&""!==e.room&&(n.room=e.room),void 0!==e?.tokenName&&(n.tokenName=e.tokenName),void 0!==e?.userAddress&&(n.userAddress=wn(e.userAddress,"userAddress")),void 0!==e?.userAddresses&&(n.userAddresses=e.userAddresses.split(",").map(e=>wn(e.trim(),"userAddresses")).join(",")),void 0!==e?.authenticated&&(n.authenticated=e.authenticated),void 0!==e?.isOverseer&&(n.isOverseer=e.isOverseer),void 0!==e?.minConnectionSeconds&&(n.minConnectionSeconds=e.minConnectionSeconds),void 0!==e?.offset&&(n.offset=e.offset),void 0!==e?.limit&&(n.limit=e.limit);const r=await this.http.get(t,Object.keys(n).length>0?n:void 0,this.getDualAuthHeaders());return this.extractData(r)}async isUserOnline(e){this.validateRequiredString(e,"userAddress","User Address");const t=await this.getConnectedClients({userAddress:e,limit:1});if(0===t.clients.length)return{online:!1};const n=t.clients[0];return void 0===n?{online:!1}:{online:!0,socketId:n.socketId,rooms:n.rooms,connectedAt:n.connectedAt}}async getOnlineUsers(e){if(!Array.isArray(e)||0===e.length)throw new Ot("userAddresses must be a non-empty array");const t=await this.getConnectedClients({userAddresses:e.join(","),limit:e.length}),n=t.clients.filter(e=>"string"==typeof e.address&&""!==e.address).map(e=>e.address);return{online:n,offline:e.filter(e=>!n.some(t=>Dn(t,e))),clients:t.clients.map(e=>{const t={socketId:e.socketId,rooms:e.rooms};return"string"==typeof e.address&&(t.address=e.address),t})}}async getTokenViewers(e,t){this.validateTokenName(e,Or);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,Or);const n={action:"recording_status",tokenName:e,payload:t};await this.emitEvent(n)}async emitRecordingsCountUpdated(e,t){this.validateTokenName(e,Or);const n={action:"recordings_count_updated",tokenName:e,payload:t};await this.emitEvent(n)}async emitDownloadReady(e,t){this.validateTokenName(e,Or);const n={action:"download_ready",tokenName:e,payload:t};await this.emitEvent(n)}}class uh{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 hh{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 gh extends wr{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 uh({maxAttempts:this.config.reconnectAttempts??5,baseDelayMs:this.config.reconnectDelay??2e3}),this.eventBuffer=new hh(3e4),this.isSocketIOAvailable=this.checkSocketIOAvailability(),gh.instances.add(this)}checkSocketIOAvailability(){try{return"function"==typeof _||(this.logger.warn('⚠️ Socket.IO client not available. Install "socket.io-client" package.'),!1)}catch(e){return this.logger.warn("⚠️ Socket.IO availability check failed:",e),!1}}async connect(){return new Promise((e,t)=>{So(async()=>{if(!this.isSocketIOAvailable){const e=new Error('Socket.IO not available in current environment. Install "socket.io-client" package.');throw this.logger.error("❌ Socket.IO connection failed:",Ut(e)),e}this.logger.debug("🔌 Connecting to Socket.IO server:",this.config.url),this.socket=_(this.config.url,{transports:["websocket"],reconnection:!0,reconnectionAttempts:this.config.reconnectAttempts??5,reconnectionDelay:this.config.reconnectDelay??2e3}),this.socket.on("connect",()=>{this.logger.debug("✅ Socket.IO connected successfully:",this.socket?.id),this.logger.debug("📡 Connected to bundle backend WebSocket:",this.config.url),this.logger.debug("🔗 Ready to monitor transaction updates"),this.reconnectionManager.reset(),e()}),this.socket.on("connect_error",e=>{this.logger.error("❌ Socket.IO connection error:",e),t(e)}),this.socket.on("disconnect",e=>{this.logger.debug(`🔌 Socket.IO disconnected: ${e}`),this.handleReconnect()}),this.socket.on("error",e=>{this.logger.error("❌ Socket.IO error:",e)}),this.socket.onAny((e,...t)=>{if(""!==e&&t.length>0&&"object"==typeof t[0]&&null!==t[0]){const n=t[0],r=n.status??n.Status;"string"==typeof r&&(this.logger.debug(`📡 [Event Buffer] Buffering event for ${e}: ${r}`),this.eventBuffer.size>=this.MAX_BUFFER_SIZE&&this.logger.warn(`📡 [Event Buffer] Buffer approaching limit (${this.eventBuffer.size}/${this.MAX_BUFFER_SIZE})`),this.eventBuffer.set(e,n))}this.debug&&this.logger.debug(`📡 [WebSocket Event] "${e}":`,JSON.stringify(t,null,2))}),this.hasOnAnyListener=!0},"Socket.IO connection failed",this.logger,e=>{this.logger.error("Socket.IO connection failed:",e);const n=Lt(e)?e:new Error(Ut(e));throw t(n),n}).catch(t)})}async monitorTransaction(e,t){this.listeners.set(e,t),this.logger.debug(`📡 Starting to monitor transaction: ${e}`),this.logger.debug(`📡 WebSocket connected: ${String(this.socket?.connected??!1)}`);const n=this.eventBuffer.get(e);null!=n&&(this.logger.debug(`📡 [Event Buffer] Found buffered event for ${e}, delivering immediately`),setImmediate(()=>{this.processTransactionEvent(e,n,t)}),this.eventBuffer.delete(e));const r=this.config.timeout??3e5,s=setTimeout(()=>{if(this.listeners.has(e)){const n=Math.round(r/1e3),s={transactionId:e,status:Do.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:Do.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;or(o)||(o=i===Io.FAILED||i===Io.ERROR?"Transaction failed - check transaction details":i===Io.COMPLETED||i===Io.PROCESSED||i===Io.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===Do.COMPLETED||d.status===Do.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===Do.COMPLETED?t(e):e.status!==Do.FAILED&&e.status!==Do.TIMEOUT||n(new Error(`Transaction ${String(e.status)}: ${e.message}`))})})}mapSocketStatus(e){const t=e?.toUpperCase();return Co[t]??Do.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")),gh.instances.delete(this)}static cleanupAll(e=!1){for(const e of gh.instances)e.disconnect();gh.instances.clear()}isConnected(){return this.socket?.connected??!1}getSocket(){return this.socket}}gh.instances=new Set;class mh 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 kt("limit must be between 1 and 50","limit","INVALID_LIMIT");this.logger.debug("Fetching weekly challenge leaderboard",{limit:t});const n={limit:String(t)},r=await this.http.get(gt.GET_LEADERBOARD,n),s=this.extractData(r);return this.logger.debug("Fetched weekly challenge leaderboard",{count:s.count}),{leaderboard:s}}async getTokenHistory(e){const{vaultAddress:t}=e;if("string"!=typeof t||""===t.trim())throw new kt("vaultAddress is required","vaultAddress","REQUIRED_FIELD");this.logger.debug("Fetching token weekly history",{vaultAddress:t});const n=gt.GET_TOKEN_HISTORY.replace(":vaultAddress",encodeURIComponent(t)),r=await this.http.get(n),s=this.extractData(r);return this.logger.debug("Fetched token weekly history",{count:s.length}),{snapshots:s}}}const fh=["CreateSale","BuyWithNative","BuyExactToken","SellWithNative","SellExactToken"];class ph{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 Eh{constructor(e){this.bundleBaseUrl=_h(e.bundleBaseUrl),this.launchpadBaseUrl=_h(e.launchpadBaseUrl),this.signer=e.signer,this.walletAddress=""===e.walletAddress?"":wn(e.walletAddress,"walletAddress"),this.requestor=e.httpRequestor??fetch.bind(globalThis),this.socketFactory=e.socketFactory??(e=>_(e,{transports:["websocket"]})),this.bundleSocketFactory=e.bundleSocketFactory}attach(e){const{bundleId:t,method:n,uniqueKey:r,tokenName:s}=e;if("string"!=typeof t||""===t)throw vh("bundleId");if(i=n,!fh.some(e=>e===i))throw vh("method");var i;if("string"!=typeof r||""===r)throw vh("uniqueKey");if(void 0!==s&&("string"!=typeof s||""===s))throw vh("tokenName");if("CreateSale"===n&&void 0===s)throw vh("tokenName");const o={method:n,dto:{uniqueKey:r,...void 0===s?{}:{tokenName:s}},stringsInstructions:[]};return new ph({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 Ia)return e;if(g(e)){const t=e instanceof Error?e.message:"The signature was rejected in the wallet.",n=m(e);return new Ia(t,"WALLET_USER_REJECTED",{details:void 0===n?{}:{walletCode:n}})}const t=e instanceof Error?e.message:"Launchpad signing failed.";return new Ia(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 wh(s);if(!s.ok)throw yh(s.status,i,r);const o=function(e){if("string"==typeof e&&""!==e)return e;if(!kh(e))throw new Ia("Bundler returned no bundle id.","INVALID_BUNDLE_RESPONSE");const t=e.data,n=e.bundleId;if("string"==typeof t&&""!==t)return t;if(kh(t)&&"string"==typeof t.bundleId&&""!==t.bundleId)return t.bundleId;if("string"==typeof n&&""!==n)return n;throw new Ia("Bundler returned no bundle id.","INVALID_BUNDLE_RESPONSE")}(i),a=Nh(e.dto,"uniqueKey");return new ph({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(Ah(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(Ah(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 Ia(`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(!kh(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(Th(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=Nh(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 Th(e.data);a("read-failed"===e.kind?e.error:void 0);const c=s-(Date.now()-r);if(c<=0)break;await Ih(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 wh(r);if("CreateSale"===e.method)return r.ok?{kind:"processed",result:{status:"PROCESSED",data:bh(s)}}:404===r.status||202===r.status?{kind:"pending"}:{kind:"read-failed",error:yh(r.status,s,t)};if(!r.ok)return{kind:"read-failed",error:yh(r.status,s,t)};const i=kh(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 Ia(n,"BUNDLE_REQUEST_FAILED",{details:{url:t}})}}}}function Ah(e,t){return new Ia("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 vh(e){return new Ia(`Cannot attach to a launchpad bundle: ${e} is missing or not accepted.`,"INVALID_BUNDLE_ATTACHMENT",{details:{field:e}})}function Th(e){const t=Sh(e)??"Launchpad bundle failed on chain.";return new Ia(t,"BUNDLE_FAILED",{chainMessage:t})}function yh(e,t,n){const r=Sh(t)??`Bundle request failed with HTTP ${e}`;return new Ia(r,"BUNDLE_REQUEST_FAILED",{status:e,chainMessage:r,details:{body:t,url:n}})}function Sh(e){if("string"==typeof e&&""!==e)return e;if(kh(e))for(const t of["chainMessage","message","Message","error"]){const n=e[t];if("string"==typeof n&&""!==n)return n;if(kh(n)){const e=Sh(n);if(void 0!==e)return e}}}function bh(e){return kh(e)?e.data??e.Data??e:e}function Nh(e,t){const n=e[t];if("string"!=typeof n||""===n)throw new Ia(`Missing ${t} in launchpad DTO.`,"INVALID_LAUNCHPAD_DTO");return n}async function wh(e){try{return await e.json()}catch{return e.text()}}function kh(e){return"object"==typeof e&&null!==e}function _h(e){return e.replace(/\/$/u,"")}function Ih(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 Dh(e,t){if(!/^\d+(\.\d+)?$/.test(e))throw new kt(`Quoted reverse bonding curve fee is not a non-negative number: ${e}`,"extraFees","INVALID_QUOTED_FEE");if(!Number.isFinite(t)||t<0)throw new kt(`Fee slippage factor must be a non-negative number, got ${String(t)}`,"maxAcceptableReverseBondingCurveFeeSlippageFactor","INVALID_FEE_SLIPPAGE_FACTOR");return new I(e).multipliedBy(new I(1).plus(new I(String(t)))).decimalPlaces(8,I.ROUND_UP).toFixed()}function Ch(e){return async t=>{const n=t.tokenName??await async function(e,t){const n=Ba(t).type,r=await e.findTokenNameByVault(t,n);if(void 0===r)throw new kt(`Could not find the launchpad token for vault ${t}, so the reverse bonding curve fee ceiling cannot be quoted. Pass tokenName, or pass extraFees.maxAcceptableReverseBondingCurveFee explicitly.`,"tokenName","TOKEN_NOT_FOUND_FOR_VAULT");return r}(e,t.vaultAddress);return Dh((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 Rh={minFeePortion:"0.1",maxFeePortion:"0.5"},Oh=/^(?:\d+\.?\d*|\.\d+)$/u,Mh=/^[0-9A-Z]+$/u,Lh=/^[A-Za-z0-9]+$/u,Uh=new I("0.1"),Fh=new I("0.5");function Ph(e){if("string"!=typeof e||!Oh.test(e))return;const t=new I(e);return t.isFinite()?t.toFixed():void 0}function xh(e){return"string"==typeof e&&""!==e}function Bh(e,t,n){void 0!==n&&"string"!=typeof n&&e.push(`${t} must be a string`)}function Gh(e,t,n){void 0===n||xh(n)||e.push(`${t} must be a non-empty string`)}function $h(e){const t=[];if("object"!=typeof e||null===e)throw new kt("CreateSale input must be an object","data","VALIDATION_ERROR");const n={...e},r=n.tokenName;xh(r)?Lh.test(r)||t.push("Token name can only contain letters and numbers"):t.push("Token name is required");const s=n.tokenSymbol;xh(s)?Mh.test(s.toUpperCase())||t.push("Token symbol can only contain letters and numbers"):t.push("Token symbol is required");const i=n.tokenDescription;xh(i)?i.length>1e3&&t.push("Token description must be at most 1000 characters"):t.push("Token description is required");const o=n.tokenImage;xh(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===Ph(a)&&t.push("preBuyQuantity must be a non-negative decimal number");for(const e of["websiteUrl","telegramUrl","twitterUrl","instagramUrl","facebookUrl","redditUrl","tiktokUrl"])Bh(t,e,n[e]);Gh(t,"tokenCategory",n.tokenCategory),Gh(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??Rh.minFeePortion,s=n.maxFeePortion??Rh.maxFeePortion,i=Ph(r),o=Ph(s);if(void 0===i&&e.push("minFeePortion must be a decimal number"),void 0===o&&e.push("maxFeePortion must be a decimal number"),void 0===i||void 0===o)return;const a=new I(i),c=new I(o);a.isLessThan(Uh)&&e.push("minFeePortion must be greater than or equal to 0.1"),c.isGreaterThan(Fh)&&e.push("maxFeePortion must be less than or equal to 0.5"),a.isGreaterThan(c)&&e.push("minFeePortion must be less than or equal to maxFeePortion")}(t,n.reverseBondingCurveConfiguration),t.length>0)throw new kt(t.join("; "),"data","VALIDATION_ERROR")}class Kh{constructor(e){this.transport=e.transport,this.walletAddress=""===e.walletAddress?"":wn(e.walletAddress,"walletAddress"),this.sellFeeCeiling=e.sellFeeCeiling}createSale(e){$h(e);const t=function(e,t){const n={tokenName:e.tokenName,tokenSymbol:e.tokenSymbol,tokenDescription:e.tokenDescription,tokenImage:e.tokenImage,preBuyQuantity:Ph(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??Hh(t)},r=e.reverseBondingCurveConfiguration;n.reverseBondingCurveConfiguration={minFeePortion:Ph(r?.minFeePortion??Rh.minFeePortion),maxFeePortion:Ph(r?.maxFeePortion??Rh.maxFeePortion)},void 0!==e.saleStartTime&&(n.saleStartTime=e.saleStartTime);return n}(e,this.walletAddress);return this.transport.submit({method:"CreateSale",dto:t,stringsInstructions:$a(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??Hh(this.walletAddress)};return this.transport.submit({method:e,dto:r,stringsInstructions:Ga(t.vaultAddress)})}async defaultExtraFees(e,t){if("BuyWithNative"===e||"BuyExactToken"===e)return{maxAcceptableReverseBondingCurveFee:"0"};if(void 0===this.sellFeeCeiling)throw new kt("A sell needs a reverse bonding curve fee ceiling and no quote source is configured: pass extraFees.maxAcceptableReverseBondingCurveFee.","extraFees","FEE_CEILING_REQUIRED");return{maxAcceptableReverseBondingCurveFee:await this.sellFeeCeiling({method:e,vaultAddress:t.vaultAddress,quantity:t.quantity,...void 0===t.tokenName?{}:{tokenName:t.tokenName}})}}}function Hh(e){return`galaswap-operation-${k()}-${Date.now()}-${e}`}function Wh(e,t=3e4){return D.create({baseURL:e,timeout:t,headers:{"Content-Type":"application/json"}})}const Vh=new Set(["accesstoken","refreshtoken","token","password","privatekey","secret","apikey","api_key","rawkey","authorization","x-api-key","bearer","streamadminapikey","userapikey","signature","signedpayload"]);function jh(e,t=0){if(t>5)return"[...]";if(null==e)return e;if(Array.isArray(e))return e.map(e=>jh(e,t+1));if(e instanceof Map){const n={};for(const[r,s]of e.entries()){const e=String(r);n[e]=Vh.has(e.toLowerCase())?"[REDACTED]":jh(s,t+1)}return n}if("object"==typeof e){const n={};for(const[r,s]of Object.entries(e))n[r]=Vh.has(r.toLowerCase())?"[REDACTED]":jh(s,t+1);return n}return e}class qh{constructor(e,t={},n={signRequests:!0}){this.auth=e,this.signRequests=n.signRequests,this.session=n.session,this.debug=t.debug??!1,this.logger=new En({debug:this.debug,context:"HttpClient"});const r=t.baseUrl??_o("stage").launchpadBaseUrl,s=t.timeout??6e4;this.axios=Wh(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 So(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]":jh(e.data);this.logger.debug("Request:",{method:e.method,url:e.url?.split("?")[0],baseURL:this.axios.defaults.baseURL,params:jh(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:jh(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:kl(e.params)},...void 0!==n&&{headers:{...n}},...void 0!==e.timeout&&{timeout:e.timeout},...void 0!==e.signal&&{signal:e.signal}};if(e.data instanceof FormData){const e=new C(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 So(async()=>{const t=await this.auth.generateCustomSignature(e);return this.logger.debug("Generated custom signature:",{message:e,address:t.address,ethereumAddress:this.auth.getEthereumAddress()}),{signature:t.signature,address:t.address,ethereumAddress:this.auth.getEthereumAddress()}},"Failed to generate custom signature for message",this.logger)}setupInterceptors(){this.requestInterceptorId=this.axios.interceptors.request.use(async e=>{if(e.headers??(e.headers={}),this.signRequests&&this.auth?.hasWallet()){const t=await this.auth.generateSignature();e.headers.Sign=t.signature,this.logger.debug("Added signature header:",{address:t.address,message:t.message,timestamp:t.timestamp})}else this.logger.debug("Skipping signature header (no wallet, or signRequests is off)");return e.data instanceof FormData||(e.headers["Content-Type"]="application/json"),this.logger.debug("Final request header keys being sent:",Object.keys(e.headers)),e},e=>Promise.reject(e instanceof Error?e:new Error(String(e)))),this.responseInterceptorId=this.axios.interceptors.response.use(e=>e,e=>{const t=e;if(void 0!==t.response){const n=t.response.data,r={message:n?.message??Ut(e),...n&&"string"==typeof n.error&&""!==n.error&&{error:n.error},statusCode:t.response.status,...n&&Boolean(n.details)&&{details:n.details},...n&&Boolean(n.timestamp)&&{timestamp:n.timestamp},...n&&Boolean(n.path)&&{path:n.path}};t.launchpadError=r,this.logger.error("Backend error:",r)}else void 0!==t.request?this.logger.error("Network error:",t.message??"Unknown error"):this.logger.error("Request setup error:",t.message??"Unknown error");return Promise.reject(e instanceof Error?e:new Error(String(e)))})}cleanup(){void 0!==this.requestInterceptorId&&(this.axios.interceptors.request.eject(this.requestInterceptorId),this.requestInterceptorId=void 0),void 0!==this.responseInterceptorId&&(this.axios.interceptors.response.eject(this.responseInterceptorId),this.responseInterceptorId=void 0),this.logger.debug("Interceptors cleaned up")}}class zh extends Error{constructor(e,t){super(e),this.cause=t,this.name="WebSocketError"}}class Xh extends zh{constructor(e,t){super(`WebSocket confirmation timeout for transaction ${e} after ${t}ms`),this.name="WebSocketTimeoutError"}}class Qh extends Error{constructor(e,t,n){super(`Transaction ${e} failed with status: ${t}${void 0!==n?` - ${n}`:""}`),this.transactionId=e,this.status=t,this.name="TransactionFailedError"}}function Yh(e,t){if(cr(e))throw new zh(`Invalid WebSocket response received for transaction ${t}: response is null or undefined`);if("object"!=typeof e)throw new zh(`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 zh(`Invalid WebSocket response received for transaction ${t}: missing status field`)}function Jh(e,t,n,r){Yh(e,t);const s=e,i=s.data??{};if(!function(e){if(cr(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 zh(`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 Zh(e){return void 0!==e&&b(e)?new T(e.exportPrivateKey()):void 0}const eg={MUSIC:"$MUSIC",GMUSIC:"$GMUSIC"};function tg(e){if(void 0===e||!("walletAddress"in e))return;const t=e.walletAddress;return"string"==typeof t&&""!==t?t:void 0}const ng=/^(?:eth\||0x)([0-9a-fA-F]{40})$/;function rg(e,t,n){if(void 0===e||void 0===t)return;const r=ng.exec(e)?.[1],s=ng.exec(t)?.[1];if(void 0!==r&&void 0!==s&&r.toLowerCase()!==s.toLowerCase())throw jt(`${n} ${t} is not the identity of the configured signing key (${e}); writes would be signed as the key, not as ${n}.`,n)}class sg{constructor(e){let t,n;this.walletGeneration=0,e.walletProvider?(t=e.walletProvider,n=Zh(e.walletProvider)):e.wallet&&(n=e.wallet,t=S.fromWallet(e.wallet)),this.wallet=n;const r=e.env??"prod",s=_o(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 Fa(n.privateKey):void 0),o=void 0!==n?`eth|${n.address.slice(2)}`:tg(i),a=void 0===e.walletAddress?void 0:wn(e.walletAddress,"walletAddress"),c=void 0===e.galaChainAddress?void 0:wn(e.galaChainAddress,"galaChainAddress");rg(o,a,"walletAddress"),rg(o,c,"galaChainAddress");const l=a??c??(void 0!==n?`eth|${n.address.slice(2)}`:tg(i)),d=i??{signObject:()=>Promise.reject(new Error("A signer is required for token writes.")),signTypedData:()=>Promise.reject(new Error("A signer is required for launchpad writes."))},u=l??"";this.tokenWriter=void 0===n&&void 0!==e.signer&&void 0!==l?{signer:e.signer,walletAddress:l}:void 0;const h=new Eh({bundleBaseUrl:this.config.bundleBaseUrl,launchpadBaseUrl:this.config.baseUrl,signer:d,walletAddress:u,...void 0!==e.httpRequestor&&{httpRequestor:e.httpRequestor},bundleSocketFactory:e.bundleSocketFactory}),g=Ch({getTradeQuote:e=>this.tradingQuotesService.getTradeQuote(e),findTokenNameByVault:(e,t)=>this.findTokenNameByVault(e,t),defaultFeeSlippageFactor:()=>this.maxAcceptableReverseBondingCurveFeeSlippageFactor});this.sellFeeCeiling=g,this.launchpad=new Kh({transport:h,walletAddress:u,sellFeeCeiling:g}),this.logger=new En({debug:this.config.debug??!1,context:"LaunchpadSDK"}),this.validateConfiguration(),this.slippageToleranceFactor=void 0===e.slippageToleranceFactor?sg.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR:this.parseSlippageToleranceFactor(e.slippageToleranceFactor),this.maxAcceptableReverseBondingCurveFeeSlippageFactor=void 0===e.maxAcceptableReverseBondingCurveFeeSlippageFactor?sg.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR:this.parseFeeSlippageFactor(e.maxAcceptableReverseBondingCurveFeeSlippageFactor),this.calculateAmountMode=e.calculateAmountMode??sg.DEFAULT_CALCULATE_AMOUNT_MODE,this.galaChainAddressOverride=c,this.signerWalletAddress=a??(void 0===n?l:void 0),this.auth=new wo({wallet:n,walletProvider:t,messagePrefix:"Create a GalaChain Wallet"});const m=e.session;if(void 0!==m){if(!function(e){if("object"!=typeof e||null===e)return!1;const t=e,n=t.credentials;return"function"==typeof t.accessToken&&"function"==typeof t.onUnauthorized&&(void 0===n||"include"===n||"omit"===n)}(m))throw jt("session must provide accessToken() and onUnauthorized()","session");if(void 0!==e.accessToken&&""!==e.accessToken)throw jt("Pass either session or accessToken, not both: the session owns the token.","accessToken")}if(this.jwtAuth=void 0===m?new To:new yo,void 0!==e.accessToken&&""!==e.accessToken){const t=e.accessTokenExpiresIn??86400;this.jwtAuth.setToken(e.accessToken,t)}this.http=new qh(this.auth,this.config,{signRequests:!0,session:m}),this.sessionAuth=new No(this.http,this.auth,this.jwtAuth,e.debug??!1,m);const f={signRequests:!1};this.galaChainHttp=new qh(this.auth,{...this.config,baseUrl:this.config.gatewayBaseUrl},f),this.bundleHttp=new qh(this.auth,{...this.config,baseUrl:this.config.bundleBaseUrl},f),this.dexApiHttp=new qh(this.auth,{...this.config,baseUrl:this.config.dexApiBaseUrl},f),this.dexBackendHttp=new qh(this.auth,{...this.config,baseUrl:this.config.dexBackendBaseUrl},f),this.galaChainPublicAxios=Wh(this.config.gatewayBaseUrl,this.config.timeout??3e4),this.cache=new _r(e.debug??!1),this.launchpadService=new ed(this.http,this.jwtAuth),this.tokenResolverService=new ch(this.launchpadService.poolService),this.launchpadAPI=new fo(this.http,this.logger,this.bundleHttp,this.calculateAmountMode,this.launchpad),this.galaChainService=new vl(this.galaChainHttp,n,this.tokenResolverService,e.debug??!1,this.galaChainPublicAxios,this.tokenWriter),this.priceService=new yc(this.dexBackendHttp,this.cache,e=>this.galaChainService.fetchTokenDetails(e),e.debug??!1),this.bundleService=this.createBundleService(),this.websocketService=new gh({url:this.config.webSocketUrl},this.config.debug),this.nftCollectionService=new xd(this.galaChainHttp),this.tradingQuotesService=new lh(this.http,e.debug??!1)}createOverrideSdk(e){if(!or(e))throw jt("Invalid privateKey: must be a non-empty string","privateKey");if(!e.match(/^0x[a-fA-F0-9]{64}$/))throw jt('Invalid privateKey format: must be "0x" followed by 64 hexadecimal characters',"privateKey");const t=new T(e),n={...this.config,wallet:t};return new sg(n)}getAddress(){return void 0!==this.galaChainAddressOverride&&""!==this.galaChainAddressOverride?this.galaChainAddressOverride:void 0!==this.signerWalletAddress&&""!==this.signerWalletAddress?this.signerWalletAddress:(this.validateWallet(),this.auth.getAddress())}getEthereumAddress(){return this.validateWallet(),this.wallet.address}validateWallet(){if(!this.wallet)throw Ht("wallet","Wallet");return this.wallet}assertTokenWriter(){if(void 0===this.wallet&&void 0===this.tokenWriter)throw Ht("wallet","Wallet")}setWallet(e){if(null==e||"object"!=typeof e||!("address"in e))throw new kt("Invalid wallet: must be an ethers Wallet instance, received "+typeof e,"wallet","INVALID_WALLET");this.wallet=e,this.auth.setWallet(e),this.onWalletChanged()}onWalletChanged(){this.walletGeneration+=1,this.galaChainAddressOverride=void 0,this.signerWalletAddress=void 0,this.rebuildTokenWrites(),this.bundleService=this.createBundleService(),this._bridgeService=void 0,this._wrapService=void 0,this._galaConnectClient=void 0,this._streamWebSocketService?.deauthenticate()}createBundleService(){return new ec(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 vl(this.galaChainHttp,this.wallet,this.tokenResolverService,this.config.debug??!1,this.galaChainPublicAxios)}setWalletProvider(e){this.auth.setWalletProvider(e),this.wallet=e?Zh(e):void 0,this.onWalletChanged()}getWallet(){return this.wallet}get events(){return this.getEventsBatcherService()}getWalletProvider(){return this.auth.getWalletProvider()}hasWallet(){return this.auth.hasWallet()}getConfig(){const{wallet:e,walletProvider:t,signer:n,httpRequestor:r,streamAdminApiKey:s,userApiKey:i,accessToken:o,headers:a,...c}=this.config;return{...c,...void 0!==s&&{streamAdminApiKey:"[REDACTED]"},...void 0!==i&&{userApiKey:"[REDACTED]"},...void 0!==o&&{accessToken:"[REDACTED]"},...void 0!==a&&{headers:Object.fromEntries(Object.keys(a).map(e=>[e,"[REDACTED]"]))},environment:this.environment,slippageToleranceFactor:this.slippageToleranceFactor,maxAcceptableReverseBondingCurveFeeSlippageFactor:this.maxAcceptableReverseBondingCurveFeeSlippageFactor,calculateAmountMode:this.calculateAmountMode,gasFee:hn.GAS_FEE}}getVersion(){return Ro}getUrlByTokenName(e){const t=this.config.launchpadFrontendUrl;if(void 0===t||""===t)throw jt("launchpadFrontendUrl not configured in SDK","launchpadFrontendUrl");return`${t.replace(/\/$/,"")}/buy-sell/${e}`}async fetchPools(e){const t=await this.launchpadService.fetchPools(e??{});return await this.warmCacheFromPools(t.items),t}async fetchAllPools(e){const t=await this.launchpadService.fetchAllPools(e);return await this.warmCacheFromPools(t.items),t}async fetchTokenDistribution(e){return this.launchpadService.fetchTokenDistribution(e)}async getTopHolders(e,t=10){const n=await this.fetchTokenDistribution(e),r=Math.min(t,100);return n.holders.slice(0,r).map((e,t)=>({...e,rank:t+1}))}async getHolderCount(e){const t=await this.fetchTokenDistribution(e);return{count:t.totalHolders,totalBalance:t.totalSupply}}async getHolderRank(e,t){const n=kn(t,"userAddress"),r=await this.fetchTokenDistribution(e),s=r.holders.findIndex(e=>e.address.toLowerCase()===n);if(-1===s)return null;const i=r.holders[s];return void 0===i?null:{rank:s+1,balance:i.balance,holderCount:r.totalHolders}}async getHoldersByBalance(e,t){const n=await this.fetchTokenDistribution(e),r=t?.minBalance??0,s=t?.maxBalance??1/0,i=Math.min(t?.limit??100,1e3),o=new Map;return n.holders.forEach((e,t)=>{o.set(e.address,t+1)}),n.holders.filter(e=>{const t=parseFloat(e.balance);return t>=r&&t<=s}).map(e=>({...e,rank:o.get(e.address)??0})).slice(0,i)}async getHolderHistory(e,t,n=20){return this.getTrades({tokenName:e,userAddress:t,pageSize:Math.min(n,100)})}async fetchUserHolderContext(e,t){return this.launchpadService.fetchUserHolderContext(e,t)}async fetchTokenPrice(e){const t="object"==typeof e&&null!==e?e:{};if(void 0!==t.tokenId)throw new kt("fetchTokenPrice prices a launchpad token by tokenName; a token by class key is priced by gswap-sdk (gSwap.market.getPrice)","tokenId",wt.INVALID_PARAMETERS);const n=t.tokenName;return this.priceService.fetchLaunchpadTokenSpotPrice("string"==typeof n?n:"",e=>this.launchpadAPI.calculateBuyAmount(e),e=>this.fetchPoolDetails(e))}async fetchTokenDetails(e){return this.galaChainService.fetchTokenDetails(e)}async fetchLaunchTokenFee(){return this.tradingQuotesService.fetchLaunchpadFee()}async fetchTokenClassesWithSupply(e){return this.galaChainService.fetchTokenClassesWithSupply(e)}async fetchPoolDetails(e){const t=await this.launchpadAPI.fetchPoolDetails(e),n=await this.launchpadAPI.fetchPoolDetailsForCalculation(e);return t.currentSupply=n.currentSupply,t.reverseBondingCurveMaxFeeFactor=n.reverseBondingCurveMaxFeeFactor,t.reverseBondingCurveMinFeeFactor=n.reverseBondingCurveMinFeeFactor,t.reverseBondingCurveNetFeeFactor=n.reverseBondingCurveNetFeeFactor,t.tokenName=e,t}async fetchPoolDetailsForCalculation(e){return this.launchpadAPI.fetchPoolDetailsForCalculation(e)}async isTokenGraduated(e){return(await this.fetchPoolDetails(e)).isGraduated}async fetchVolumeData(e){return this.launchpadService.fetchVolumeData(e)}async fetchTrades(e){return this.launchpadService.fetchTrades(e)}async fetchGalaBalance(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Hn}),n=t(e)??this.getAddress();return this.galaChainService.fetchGalaBalance({owner:n,collection:"GALA",category:"Unit",additionalKey:"none",type:"none"})}loadCoreBridge(){const e=this.config.bridge;return void 0===e?Promise.reject(jt("The bridge and wrap methods need gala-core-sdk's ./bridge: create the SDK with `bridge: () => import('@gala-chain/gala-core-sdk/bridge')` (it needs the optional peers ethers, @solana/web3.js and @solana/spl-token).","bridge")):(this.coreBridgeLoad??(this.coreBridgeLoad=Promise.resolve().then(()=>e()).then(e=>{if("object"!=typeof(t=e)||null===t||"function"!=typeof t.BridgeService)throw new Error("the module has no BridgeService export");var t;return e}).catch(e=>{throw this.coreBridgeLoad=void 0,jt(`The bridge and wrap methods use @gala-chain/gala-core-sdk/bridge, which needs its optional peers ethers, @solana/web3.js and @solana/spl-token installed: ${Ut(e)}`,"bridge")})),this.coreBridgeLoad)}async coreBridge(){const e=this.walletGeneration,t=await this.loadCoreBridge();if(e!==this.walletGeneration)throw jt("The wallet changed while this bridge or wrap call was starting; nothing was sent. Call it again.","wallet");return t}getBridgeService(e){if(!this._bridgeService){const t=this.getWallet();if(!t)throw new Error("Bridge operations require a wallet. Configure SDK with a wallet first.");const n=globalThis.process?.env.SOLANA_PRIVATE_KEY;this._bridgeService=new e.BridgeService({galaConnectBaseUrl:this.config.dexApiBaseUrl,galaChainWalletAddress:this.getAddress(),ethereumPrivateKey:t.privateKey,...void 0!==n&&""!==n?{solanaPrivateKey:n}:{},bridgeableTokenService:this.getBridgeableTokenService(e),environment:this.environment,...void 0!==this.config.ethereumRpcUrl&&""!==this.config.ethereumRpcUrl?{ethereumRpcUrl:this.config.ethereumRpcUrl}:{},...void 0!==this.config.solanaRpcUrl&&""!==this.config.solanaRpcUrl?{solanaRpcUrl:this.config.solanaRpcUrl}:{}})}return this._bridgeService}getBridgeableTokenService(e){return this._bridgeableTokenService??(this._bridgeableTokenService=new e.BridgeableTokenService(this.dexApiHttp)),this._bridgeableTokenService}getWrappableTokenService(e){return this._wrappableTokenService??(this._wrappableTokenService=new e.WrappableTokenService(this.dexApiHttp)),this._wrappableTokenService}getGalaConnectClient(e){if(void 0===this._galaConnectClient){const t=this.getAddress();if(void 0===this.config.dexApiBaseUrl||""===this.config.dexApiBaseUrl)throw new Error("DEX API base URL is required for GalaConnectClient. Check SDK configuration.");this._galaConnectClient=new e.GalaConnectClient({baseUrl:this.config.dexApiBaseUrl,...void 0!==this.config.gatewayBaseUrl&&""!==this.config.gatewayBaseUrl?{galachainBaseUrl:this.config.gatewayBaseUrl}:{},walletAddress:t})}return this._galaConnectClient}getWrapService(e){if(!this._wrapService){const t=this.getWallet();this._wrapService=new e.WrapService({galaConnectClient:this.getGalaConnectClient(e),wrappableTokenService:this.getWrappableTokenService(e),...void 0!==t&&{walletAddress:this.getAddress(),signer:new Fa(t.privateKey)}})}return this._wrapService}getStreamingService(){return this._streamingService??(this._streamingService=new _u(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._streamingService}getStreamChatService(){return this._streamChatService??(this._streamChatService=new ou(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._streamChatService}getBanService(){return this._banService??(this._banService=new va(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._banService}getTokenBanService(){return this._tokenBanService??(this._tokenBanService=new ah(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._tokenBanService}getAIModerationService(){return this._aiModerationService??(this._aiModerationService=new Xo(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._aiModerationService}getWeeklyChallengeService(){return this._weeklyChallengeService??(this._weeklyChallengeService=new mh(this.http,this.config.debug??!1)),this._weeklyChallengeService}getOEmbedService(){return this._oembedService??(this._oembedService=new Gd(this.http,this.config.debug??!1)),this._oembedService}getPlatformStatsService(){return this._platformStatsService??(this._platformStatsService=new su(this.http,this.config.debug??!1)),this._platformStatsService}getHealthService(){return this._healthService??(this._healthService=new Tl(this.http,this.config.debug??!1)),this._healthService}getEventsQueryService(){return this._eventsQueryService??(this._eventsQueryService=new Oc(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._eventsQueryService}getNotificationService(){return this._notificationService??(this._notificationService=new Bd(this.http,this.config.debug??!1,this.jwtAuth)),this._notificationService}getClientConfigService(){return this._clientConfigService??(this._clientConfigService=new tc(this.http,this.config.debug??!1)),this._clientConfigService}getApiKeyService(){return this._apiKeyService??(this._apiKeyService=new ca(this.http,this.jwtAuth,this.config.debug??!1)),this._apiKeyService}getModeratorService(){return this._moderatorService??(this._moderatorService=new Cd(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._moderatorService}getFlagService(){return this._flagService??(this._flagService=new fc(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._flagService}getOverseerService(){return this._overseerService??(this._overseerService=new tu(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._overseerService}getWebSocketAdminService(){return this._websocketAdminService??(this._websocketAdminService=new dh(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._websocketAdminService}getContentReactionService(){return this._contentReactionService??(this._contentReactionService=new Ac(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._contentReactionService}buildMessageFetchOptions(e,t){return{type:t,...void 0!==e.tokenName&&{tokenName:e.tokenName},...void 0!==e.userAddress&&{userAddress:e.userAddress},...void 0!==e.cursor&&{cursor:e.cursor},...void 0!==e.pageSize&&{pageSize:e.pageSize}}}resolveReferralAddress(e){return void 0===e||""===e?this.getAddress():wn(e,"address")}getMessagesService(){return this._messagesService??(this._messagesService=new gd(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._messagesService}getRestrictedNamesService(){return this._restrictedNamesService??(this._restrictedNamesService=new iu(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.userApiKey)),this._restrictedNamesService}getPlatformConfigService(){return this._platformConfigService??(this._platformConfigService=new ru(this.http,this.jwtAuth,this.config.debug??!1)),this._platformConfigService}getEventsBatcherService(){return this._eventsBatcherService??(this._eventsBatcherService=new Nc(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 Zu({url:this.config.streamWebSocketUrl,tokenProvider:()=>this.streamSocketToken(),...void 0!==this.config.streamReconnectAttempts&&{reconnectAttempts:this.config.streamReconnectAttempts},...void 0!==this.config.streamReconnectDelay&&{reconnectDelay:this.config.streamReconnectDelay},...void 0!==this.config.streamReconnectDelayMax&&{reconnectDelayMax:this.config.streamReconnectDelayMax}},this.config.debug??!1)}return this._streamWebSocketService}async streamSocketToken(){const e=this.config.session;return void 0!==e?e.accessToken():this.ensureValidToken()}get realtime(){return this.getStreamWebSocketService()}async fetchEthereumWalletTokenBalance(e,t){return this.getBridgeService(await this.coreBridge()).fetchEthereumWalletTokenBalance(e,t)}async fetchEthereumWalletNativeBalance(e){return this.getBridgeService(await this.coreBridge()).fetchEthereumWalletNativeBalance(e)}async fetchSolanaWalletTokenBalance(e,t){return this.getBridgeService(await this.coreBridge()).fetchSolanaWalletTokenBalance(e,t)}async fetchSolanaWalletNativeBalance(e){return this.getBridgeService(await this.coreBridge()).fetchSolanaWalletNativeBalance(e)}async requestSolanaDevnetAirdrop(e,t){return this.getBridgeService(await this.coreBridge()).requestSolanaDevnetAirdrop(e,t)}async getSolanaTransactionStatus(e){return this.getBridgeService(await this.coreBridge()).getSolanaTransactionStatus(e)}async getEthereumTransactionStatus(e){return this.getBridgeService(await this.coreBridge()).getEthereumTransactionStatus(e)}async fetchEthereumWalletAllBalances(e){return this.getBridgeService(await this.coreBridge()).fetchEthereumWalletAllBalances(e)}async fetchSolanaWalletAllBalances(e){return this.getBridgeService(await this.coreBridge()).fetchSolanaWalletAllBalances(e)}async fetchBridgeableTokensByNetwork(e){return this.getBridgeableTokenService(await this.coreBridge()).fetchBridgeableTokensByNetwork(e)}async fetchAllBridgeableTokensByNetwork(e){return this.getBridgeableTokenService(await this.coreBridge()).fetchAllBridgeableTokensByNetwork(e)}async fetchAllTokensBridgeableToEthereum(){return this.getBridgeableTokenService(await this.coreBridge()).fetchAllTokensBridgeableToEthereum()}async fetchAllTokensBridgeableToSolana(){return this.getBridgeableTokenService(await this.coreBridge()).fetchAllTokensBridgeableToSolana()}async isTokenBridgeableToNetwork(e){return this.getBridgeableTokenService(await this.coreBridge()).isTokenBridgeableToNetwork(e)}async isTokenBridgeableToEthereum(e){return this.getBridgeableTokenService(await this.coreBridge()).isTokenBridgeableToEthereum(e)}async isTokenBridgeableToSolana(e){return this.getBridgeableTokenService(await this.coreBridge()).isTokenBridgeableToSolana(e)}async fetchWrappableTokens(e={}){return this.getWrappableTokenService(await this.coreBridge()).fetchWrappableTokens(e)}async fetchAllWrappableTokens(){return this.getWrappableTokenService(await this.coreBridge()).fetchAllWrappableTokens()}async getWrappableToken(e){return this.getWrappableTokenService(await this.coreBridge()).getWrappableToken(e)}async getWrapCounterpart(e){return this.getWrappableTokenService(await this.coreBridge()).getWrapCounterpart(e)}async isTokenWrappable(e){return this.getWrappableTokenService(await this.coreBridge()).isTokenWrappable(e)}async wrapToken(e){return this.getWrapService(await this.coreBridge()).wrapToken(e)}async unwrapToken(e){return this.getWrapService(await this.coreBridge()).unwrapToken(e)}async estimateWrapFee(e,t){return this.getWrapService(await this.coreBridge()).estimateWrapFee(e,t)}async estimateUnwrapFee(e,t){return this.getWrapService(await this.coreBridge()).estimateUnwrapFee(e,t)}async login(){return this.sessionAuth.login()}async loginWithSignature(e){return this.sessionAuth.loginWithSignature(e)}async loginWithDevBypass(e){return this.sessionAuth.loginWithDevBypass(e)}async refreshToken(){return this.sessionAuth.refresh()}async logout(e){return this.sessionAuth.logout(e)}isAuthenticated(){return this.sessionAuth.isAuthenticated()}shouldRefreshToken(e){return this.sessionAuth.shouldRefresh(e)}async getSession(){return this.sessionAuth.getSession()}getAccessToken(){return this.sessionAuth.getAccessToken()}async ensureValidToken(e){return this.sessionAuth.ensureValidToken(e)}async startStream(e){return this.getStreamingService().startStream(e)}async stopStream(e){return this.getStreamingService().stopStream(e)}async disableStream(e){return this.getStreamingService().disableStream(e)}async enableStream(e){return this.getStreamingService().enableStream(e)}async resetStreamKey(e){return this.getStreamingService().resetStreamKey(e)}async getStreamCredentials(e){return this.getStreamingService().getStreamCredentials(e)}async getStreamRecordings(e){return this.getStreamingService().getRecordings(e)}async getRecordingDownload(e,t){return this.getStreamingService().getRecordingDownload(e,t)}async deleteRecording(e,t){return this.getStreamingService().deleteRecording(e,t)}async getSimulcastTargets(e){return this.getStreamingService().getSimulcastTargets(e)}async addSimulcastTarget(e){return this.getStreamingService().addSimulcastTarget(e)}async removeSimulcastTarget(e,t){return this.getStreamingService().removeSimulcastTarget(e,t)}async getGlobalStreamingStatus(){return this.getStreamingService().getGlobalStreamingStatus()}async setNextLiveStreamCountdown(e,t){return this.getStreamingService().setNextLiveStreamCountdown(e,t)}async setGlobalStreamingEnabled(e){const t=this.getStreamingService();return e?t.enableGlobalStreaming():t.disableGlobalStreaming()}async getStreamRole(e){return this.getStreamingService().getStreamRole(e)}async getAvailableRoles(){return this.getStreamingService().getAvailableRoles()}async getTokenAccess(e){return this.getStreamingService().getTokenAccess(e)}async getChatStatus(e){return this.getStreamChatService().getChatStatus(e)}async disableChat(e){return this.getStreamChatService().disableChat(e)}async enableChat(e){return this.getStreamChatService().enableChat(e)}async getPinnedChatMessage(e){const t=this.getMessagesService();return{tokenName:e,pinnedMessage:(await t.getPinnedMessage(e)).message}}async pinChatMessage(e,t){const n=this.getMessagesService();await n.pinMessage(t);return{tokenName:e,pinnedMessage:(await n.getPinnedMessage(e)).message}}async unpinChatMessage(e){const t=this.getMessagesService(),n=await t.getPinnedMessage(e);return n.message?(await t.unpinMessage(n.message.messageId),{tokenName:e,unpinned:!0,unpinnedMessageId:n.message.messageId}):{tokenName:e,unpinned:!1}}async setSlowMode(e,t){return this.getStreamChatService().setSlowMode(e,t)}async createBan(e){return this.getBanService().createBan(e)}async removeBan(e){return this.getBanService().removeBan(e)}async listBans(e){return this.getBanService().listBans(e)}async getBanStatus(e){return this.getBanService().getBanStatus(e)}async getActiveUsers(e){return this.getBanService().getActiveUsers(e)}async createGlobalBan(e){return this.getBanService().createGlobalBan(e)}async removeGlobalBan(e){return this.getBanService().removeGlobalBan(e)}async listGlobalBans(e){return this.getBanService().listGlobalBans(e)}async getGlobalBan(e){return this.getBanService().getGlobalBan(e)}async createApiKey(e){return this.getApiKeyService().create(e)}async listApiKeys(e={}){return this.getApiKeyService().findAll(e)}async getApiKey(e){return this.getApiKeyService().findOne(e)}async updateApiKey(e,t){return this.getApiKeyService().update(e,t)}async revokeApiKey(e){return this.getApiKeyService().revoke(e)}getApiKeyRoles(){return this.getApiKeyService().getRoles()}async createModeratorInvite(e){return this.getModeratorService().createInvite(e)}async claimModeratorInvite(e){return this.getModeratorService().claimInvite(e)}async getModeratedTokens(e){return this.getModeratorService().getModeratedTokens(e)}async listModeratorInvites(e){return this.getModeratorService().listInvites(e)}async getActiveModerators(e){return(await this.listModeratorInvites({tokenName:e,status:"CLAIMED"})).items.filter(e=>null!==e.claimedBy).map(e=>({address:e.claimedBy,role:e.role,joinedAt:e.claimedAt,inviteId:e.id}))}async revokeModeratorInvite(e){return this.getModeratorService().revokeInvite(e)}async updateModeratorInviteRole(e){return this.getModeratorService().updateInviteRole(e)}async updateModeratorInvite(e){return this.getModeratorService().updateInvite(e)}async getModeratorInviteByCode(e){return this.getModeratorService().getInviteByCode(e)}async createFlag(e){return this.getFlagService().createFlag(e)}async listFlags(e){return this.getFlagService().listFlags(e)}async listGlobalFlags(e={}){return this.getFlagService().listGlobalFlags(e)}async dismissFlag(e){return this.getFlagService().dismissFlag(e)}async actionFlag(e){return this.getFlagService().actionFlag(e)}async createOverseerInvite(e={}){return this.getOverseerService().createInvite(e)}async listOverseerInvites(e={}){return this.getOverseerService().listInvites(e)}async getOverseerInviteByCode(e){return this.getOverseerService().getInviteByCode(e)}async claimOverseerInvite(e){return this.getOverseerService().claimInvite(e)}async revokeOverseerInvite(e){return this.getOverseerService().revokeInvite(e)}async listOverseers(e={}){return this.getOverseerService().listOverseers(e)}async createOverseerDirect(e){return this.getOverseerService().createOverseerDirect(e)}async revokeOverseer(e){return this.getOverseerService().revokeOverseer(e)}async getMyOverseerStatus(){return this.getOverseerService().getMyStatus()}async getOverseerSummary(){return this.getOverseerService().getSummary()}async getBanStats(){return this.getOverseerService().getBanStats()}async getTokenBanStats(){return this.getOverseerService().getTokenBanStats()}async getInviteStats(){return this.getOverseerService().getInviteStats()}async getFlagStats(){return this.getOverseerService().getFlagStats()}async getUserStats(){return this.getOverseerService().getUserStats()}async listOverseerUsers(e){return this.getOverseerService().listOverseerUsers(e)}async getOverseerUserSummary(e){return this.getOverseerService().getOverseerUserSummary(e)}async flushCacheByAddress(e){return this.getOverseerService().flushCacheByAddress(e)}async flushCacheByToken(e){return this.getOverseerService().flushCacheByToken(e)}async flushAllCache(e){return this.getOverseerService().flushAllCache(e)}async flushWalletAliasCache(e){return this.getOverseerService().flushWalletAliasCache(e)}async emitWebSocketEvent(e){return this.getWebSocketAdminService().emitEvent(e)}async emitTradeExecuted(e,t){return this.getWebSocketAdminService().emitTradeExecuted(e,t)}async emitBalanceUpdated(e,t,n){return this.getWebSocketAdminService().emitBalanceUpdated(e,t,n)}async emitStreamStatus(e,t){return this.getWebSocketAdminService().emitStreamStatus(e,t)}async emitViewerCount(e,t){return this.getWebSocketAdminService().emitViewerCount(e,t)}async emitStreamCountdown(e,t){return this.getWebSocketAdminService().emitStreamCountdown(e,t)}async emitChatMessage(e,t){return this.getWebSocketAdminService().emitChatMessage(e,t)}async emitChatStatus(e,t){return this.getWebSocketAdminService().emitChatStatus(e,t)}async emitTypingIndicator(e,t){return this.getWebSocketAdminService().emitTypingIndicator(e,t)}async emitTokenBanned(e,t){return this.getWebSocketAdminService().emitTokenBanned(e,t)}async emitTokenUnbanned(e,t){return this.getWebSocketAdminService().emitTokenUnbanned(e,t)}async emitModeratorAdded(e,t){return this.getWebSocketAdminService().emitModeratorAdded(e,t)}async emitModeratorRemoved(e,t){return this.getWebSocketAdminService().emitModeratorRemoved(e,t)}async emitUserProfileUpdated(e,t){return this.getWebSocketAdminService().emitUserProfileUpdated(e,t)}async emitSiteConfigChanged(e){return this.getWebSocketAdminService().emitSiteConfigChanged(e)}async emitFeatureStatus(e){return this.getWebSocketAdminService().emitFeatureStatus(e)}async emitRecordingStatus(e,t){return this.getWebSocketAdminService().emitRecordingStatus(e,t)}async emitRecordingsCountUpdated(e,t){return this.getWebSocketAdminService().emitRecordingsCountUpdated(e,t)}async emitDownloadReady(e,t){return this.getWebSocketAdminService().emitDownloadReady(e,t)}async getConnectedClients(e){return this.getWebSocketAdminService().getConnectedClients(e)}async isUserOnline(e){return this.getWebSocketAdminService().isUserOnline(e)}async getOnlineUsers(e){return this.getWebSocketAdminService().getOnlineUsers(e)}async getTokenViewers(e,t){return this.getWebSocketAdminService().getTokenViewers(e,t)}async getOnlineOverseers(){return this.getWebSocketAdminService().getOnlineOverseers()}async banToken(e){return this.getTokenBanService().banToken(e)}async unbanToken(e){return this.getTokenBanService().unbanToken(e)}async listTokenBans(e={}){return this.getTokenBanService().listTokenBans(e)}async getTokenBan(e){return this.getTokenBanService().getTokenBan(e)}async isTokenBanned(e){return this.getTokenBanService().isTokenBanned(e)}async getAIModerationSettings(){return this.getAIModerationService().getSettings()}async updateAIModerationSettings(e){return this.getAIModerationService().updateSettings(e)}async getAIModeration(e){return this.getAIModerationService().getModeration(e)}async triggerAIModeration(e){return this.getAIModerationService().triggerModeration(e)}async getAIModerationStatus(){return this.getAIModerationService().getStatus()}async getWeeklyChallengeLeaderboard(e={}){return this.getWeeklyChallengeService().getLeaderboard(e)}async getTokenWeeklyHistory(e){return this.getWeeklyChallengeService().getTokenHistory(e)}async getHomeOEmbed(e={}){return this.getOEmbedService().getHomeOEmbedJson(e)}async getPoolOEmbed(e){return this.getOEmbedService().getPoolOEmbedJson(e)}async getProfileOEmbed(e){return this.getOEmbedService().getProfileOEmbedJson(e)}async getPlatformStats(){return this.getPlatformStatsService().getStats()}async getHealth(){return this.getHealthService().getHealth()}async getEventStats(){return this.getEventsQueryService().getEventStats()}async queryEvents(e={}){return this.getEventsQueryService().queryEvents(e)}async registerPushToken(e){return this.getNotificationService().registerPushToken(e)}async unregisterPushToken(e){return this.getNotificationService().unregisterPushToken(e)}async fetchNotificationPreferences(){return this.getNotificationService().getPreferences()}async updateNotificationPreferences(e){return this.getNotificationService().updatePreferences(e)}async fetchClientFlags(){return this.getClientConfigService().getClientFlags()}async addContentReaction(e){return this.getContentReactionService().addContentReaction(e)}async removeContentReaction(e){return this.getContentReactionService().removeContentReaction(e)}async addReactionToChatMessage(e){return this.getContentReactionService().addReactionToChatMessage(e)}async removeReactionFromChatMessage(e){return this.getContentReactionService().removeReactionFromChatMessage(e)}async addReactionToComment(e){return this.getContentReactionService().addReactionToComment(e)}async removeReactionFromComment(e){return this.getContentReactionService().removeReactionFromComment(e)}async getComments(e){const t=this.buildMessageFetchOptions(e,"COMMENT"),n=await this.fetchMessages(t);return{messages:n.messages,pageInfo:n.pageInfo}}async createComment(e){return{comment:(await this.createMessage({type:"COMMENT",tokenName:e.tokenName,content:e.content})).message}}async updateComment(e,t){return{comment:(await this.updateMessage(e,{content:t.content,type:"COMMENT"})).message}}async deleteComment(e){return{success:(await this.deleteMessage(e)).success}}async getChatMessages(e){const t=this.buildMessageFetchOptions(e,"CHAT_MESSAGE"),n=await this.fetchMessages(t);return{messages:n.messages,pageInfo:n.pageInfo}}async sendChatMessage(e){return{message:(await this.createMessage({type:"CHAT_MESSAGE",tokenName:e.tokenName,content:e.content})).message}}async updateChatMessage(e,t){return{message:(await this.updateMessage(e,{content:t.content,type:"CHAT_MESSAGE"})).message}}async deleteChatMessage(e){await this.deleteMessage(e)}async fetchMessages(e){return this.getMessagesService().fetchMessages(e)}async createMessage(e){return this.getMessagesService().createMessage(e)}async updateMessage(e,t){return this.getMessagesService().updateMessage(e,t)}async deleteMessage(e){return this.getMessagesService().deleteMessage(e)}async getPinnedMessage(e){return this.getMessagesService().getPinnedMessage(e)}async pinMessage(e){return this.getMessagesService().pinMessage(e)}async unpinMessage(e){return this.getMessagesService().unpinMessage(e)}async getMessageStats(){return this.getMessagesService().getMessageStats()}async getPlatformConfig(){return this.getPlatformConfigService().getPlatformConfig()}async updatePlatformConfig(e){return this.getPlatformConfigService().updatePlatformConfig(e)}async getRestrictedNames(){return this.getRestrictedNamesService().getRestrictedNames()}async updateRestrictedNames(e){return this.getRestrictedNamesService().updateRestrictedNames(e)}async updateTokenConfig(e,t){return this.launchpadService.poolService.updateTokenConfig(e,t)}async getTokenConfig(e){return this.launchpadService.poolService.getTokenConfig(e)}async getTrades(e){return this.launchpadService.getTrades(e)}async getRecentTrades(e,t=50){return this.getTrades({...void 0!==e&&{tokenName:e},pageSize:Math.min(t,500)})}async getPoolRealtimeState(e){const[t,n,r,s]=await Promise.allSettled([this.getHolderCount(e),this.getTokenConfig(e),this.getRecentTrades(e,10),this.fetchTokenPrice({tokenName:e})]);return{tokenName:e,holderCount:"fulfilled"===t.status?t.value:null,..."rejected"===t.status&&{holderCountError:String(t.reason)},chatConfig:"fulfilled"===n.status?n.value:null,..."rejected"===n.status&&{chatConfigError:String(n.reason)},recentTrades:"fulfilled"===r.status?r.value:null,..."rejected"===r.status&&{recentTradesError:String(r.reason)},price:"fulfilled"===s.status?s.value:null,..."rejected"===s.status&&{priceError:String(s.reason)}}}async fetchLaunchpadFee(){return this.tradingQuotesService.fetchLaunchpadFee()}async fetchSaleDetails(e){return this.tradingQuotesService.fetchSaleDetails(e)}async getTradeQuote(e){return this.tradingQuotesService.getTradeQuote(e)}async getPremintQuote(e){return this.tradingQuotesService.getPremintQuote(e)}async connectStreamWebSocket(e){const t=this.getStreamWebSocketService();await t.connect(),e&&t.addCallbacks(e)}async authenticateStreamWebSocket(e){return this.getStreamWebSocketService().authenticate(e)}deauthenticateStreamWebSocket(){this._streamWebSocketService?.deauthenticate()}async subscribeToStream(e,t){return this.getStreamWebSocketService().subscribeToStream(e,t)}unsubscribeFromStream(e){this.getStreamWebSocketService().unsubscribeFromStream(e)}sendStreamChatViaWebSocket(e,t){this.getStreamWebSocketService().sendChatMessage(e,t)}sendStreamReaction(e,t,n=0){this.getStreamWebSocketService().sendReaction(e,t,n)}sendTypingStart(e){return this.getStreamWebSocketService().sendTypingStart(e)}sendTypingStop(e){return this.getStreamWebSocketService().sendTypingStop(e)}disconnectStreamWebSocket(){this._streamWebSocketService&&this._streamWebSocketService.disconnect()}isStreamWebSocketConnected(){return!!this._streamWebSocketService&&this._streamWebSocketService.isConnected()}onStreamStatusChanged(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_STATUS",e)}onUserBanned(e){return this.getStreamWebSocketService().subscribeEvent("USER_BANNED",e)}onUserUnbanned(e){return this.getStreamWebSocketService().subscribeEvent("USER_UNBANNED",e)}onBanEnforcement(e){return this.getStreamWebSocketService().subscribeEvent("BAN_ENFORCEMENT",e)}watchBanEnforcement(e,t={}){const n=(e,n,r,s)=>(void 0===t.actionType||t.actionType===e)&&(!!(void 0===t.userAddress||null!==n&&Dn(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||Dn(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||Dn(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&&!Dn(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 Hn}),n=t(e.address);if(void 0!==e.tokenId&&""!==e.tokenId){const{normalizeToTokenInstanceKey:t}=await Promise.resolve().then(function(){return Ya}),r=t(e.tokenId),{collection:s,category:i,type:o,additionalKey:a}=r;return this.galaChainService.fetchTokenBalance({owner:n,collection:s,category:i,additionalKey:a,type:o},e.withExpired??!1)}if(void 0!==e.tokenName&&""!==e.tokenName){const t=fn(e.tokenName),r=eg[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:Ka(r)}}throw Ht("tokenId or tokenName","Either tokenId or tokenName")}async fetchLockedBalance(e){const t=await this.fetchTokenBalance(e);if(!t)return null;const n="lockedHolds"in t||"lockedQuantity"in t;return{tokenId:t.tokenId,lockedQuantity:n?t.lockedQuantity??"0":"0",lockedHolds:n?t.lockedHolds??[]:[]}}async fetchAvailableBalance(e){const t=await this.fetchTokenBalance(e);if(!t)return null;const n="availableQuantity"in t;return{tokenId:t.tokenId,availableQuantity:n?t.availableQuantity??String(t.quantity):String(t.quantity),totalQuantity:String(t.quantity)}}async calculateBuyAmount(e){return this.launchpadAPI.calculateBuyAmount(e)}async calculateSellAmount(e){return this.launchpadAPI.calculateSellAmount(e)}async calculateBuyAmountLocal(e){return this.launchpadAPI.calculateBuyAmountLocal(e)}async calculateSellAmountLocal(e){return this.launchpadAPI.calculateSellAmountLocal(e)}async calculateBuyAmountExternal(e){return this.launchpadAPI.calculateBuyAmountExternal(e)}async calculateSellAmountExternal(e){return this.launchpadAPI.calculateSellAmountExternal(e)}async calculateBuyAmountForGraduation(e){return this.launchpadAPI.calculateBuyAmountForGraduation(e)}async graduateToken(e){const{tokenName:t,slippageToleranceFactor:n,maxAcceptableReverseBondingCurveFeeSlippageFactor:r,privateKey:s,calculateAmountMode:i,currentSupply:o}=e;let a=t;void 0===i&&void 0===o||(a={tokenName:t,...void 0!==i&&{calculateAmountMode:i},...void 0!==o&&{currentSupply:o}});const c=await this.calculateBuyAmountForGraduation(a),l={tokenName:t,amount:c.remainingTokens,type:"exact",expectedAmount:c.amount,maxAcceptableReverseBondingCurveFee:c.reverseBondingCurveFee,slippageToleranceFactor:this.slippageToleranceFactor};return void 0!==n&&(l.slippageToleranceFactor=n),void 0!==r&&(l.maxAcceptableReverseBondingCurveFeeSlippageFactor=r),void 0!==s&&(l.privateKey=s),await this.buy(l)}async calculateInitialBuyAmount(e){const t={nativeTokenQuantity:e};return this.launchpadAPI.calculateInitialBuyAmount(t)}async buy(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...r}=e;return t.buy(r)}this.validateWallet(),await this.ensureWebSocketConnection();const t=(await this.bundleService.buyToken(e)).data,n=t?.transactionId;if(void 0===n||""===n)throw qt("No transaction ID returned from buy operation");return this.waitForConfirmation(n,t=>Jh(t,n,"buy",e))}async sell(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...r}=e;return t.sell(r)}this.validateWallet(),await this.ensureWebSocketConnection();const t=(await this.bundleService.sellToken(e)).data,n=t?.transactionId;if(void 0===n||""===n)throw qt("No transaction ID returned from sell operation");return this.waitForConfirmation(n,t=>Jh(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=>{Yh(n,t);const r=n.data??{};if(!function(e){if(cr(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 zh(`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 Hn}),n=t(e)??this.getAddress();return this.launchpadService.fetchProfile(n)}async fetchReferralUrl(){this.validateWallet();const e=this.getAddress();return await this.dexApiHttp.get(O,void 0,{"x-wallet-address":e})}async fetchReferrals(e){const t=this.resolveReferralAddress(e?.address),n=e?.page??1,r=e?.limit??10,s={pageNumber:n,limit:r,sortBy:e?.sortBy??"joined",sortDir:e?.sortDir??"desc"},i=await this.dexApiHttp.get(M,s,{"x-wallet-address":t});if(!Array.isArray(i))throw new Rt("Unexpected API response: expected array, got "+typeof i);return{referrals:i,page:n,limit:r,hasMore:i.length===r}}async fetchAllReferrals(e){const t=await async function(e,t={}){const{maxPages:n=1e4,logger:r,pageSize:s=20,concurrency:i=1,startPage:o=1}=t,a=[];let c=o;const l=o+n-1;let d=!0,u=0;if(i<=1)for(;d&&c<=l;){r&&r.debug(`Auto-pagination: fetching page ${c} with limit ${s}`);const t=await e(c,s);if(null==t||!Array.isArray(t.items)){r&&r.warn("Auto-pagination: received invalid result structure, stopping");break}if(a.push(...t.items),u=t.total,r&&r.debug(`Auto-pagination: page ${c} returned ${t.items.length} items, hasNext: ${String(t.hasNext)}`),0===t.items.length){r&&r.debug(`Auto-pagination: no items returned on page ${c}, exiting loop`);break}d=t.hasNext,c++}else for(r&&r.debug(`Auto-pagination: using concurrent mode with concurrency=${i}`);d&&c<=l;){const t=[];for(let e=0;e<i&&c+e<=l;e++)t.push(c+e);r&&r.debug(`Auto-pagination: fetching pages ${t.join(", ")} concurrently`);const n=t.map(t=>e(t,s).catch(e=>{const n=e,i=n.statusCode??n.response?.status??n.originalError?.response?.status??n.status??n.launchpadError?.statusCode;if(400===i||404===i)return r&&r.debug(`Auto-pagination: page ${t} returned ${i} (end of pagination)`,{statusCode:i}),{items:[],total:0,totalPages:0,page:t,limit:s,hasNext:!1,hasPrevious:!1};throw e})),o=await Promise.all(n);for(const e of o){if(null==e||!Array.isArray(e.items)){r&&r.warn("Auto-pagination: received invalid result structure in batch, stopping"),d=!1;break}if(0===e.items.length){r&&r.debug("Auto-pagination: empty page in batch, reached end of results"),d=!1;break}if(a.push(...e.items),u=e.total,!e.hasNext){d=!1;break}}c+=t.length,r&&r.debug(`Auto-pagination: batch complete, total items so far: ${a.length}`)}return c>l&&r&&r.warn(`Auto-pagination: exceeded maxPages limit of ${n} (maxPage=${l}), stopping iteration`),r&&r.debug(`Auto-pagination: completed with total items: ${a.length}, total count: ${u}`),{items:a,total:u}}((t,n)=>this.fetchReferrals({...e,page:t,limit:n}).then(e=>({items:e.referrals,page:e.page,limit:e.limit,total:0,totalPages:0,hasNext:e.hasMore,hasPrevious:e.page>1})),{maxPages:100,pageSize:100,logger:this.logger});return{referrals:t.items,total:t.items.length}}async fetchReferralsSummary(e){const t=this.resolveReferralAddress(e?.address),n=await this.dexApiHttp.get(L,void 0,{"x-wallet-address":t});if(void 0===n||"number"!=typeof n.referralCount||void 0===n.rewardTotals)throw new Rt(`Unexpected API response: expected { referralCount, rewardTotals }, got ${JSON.stringify(n)}`);return n}async updateProfile(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Hn}),{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 Hn}),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 Hn}),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 Hn}),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 Hn}),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 Hn}),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 Hn});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=$o(r.pageInfo,n);if(void 0===i)return;n=i}}getCacheInfo(){const e={...this.launchpadAPI.getCacheStats()};if(this._bridgeableTokenService){const t=this._bridgeableTokenService.getCacheStats();e.bridgeableTokens={ETHEREUM:t.tokensByNetwork.ETHEREUM,SOLANA:t.tokensByNetwork.SOLANA,total:t.totalTokens}}return this._wrappableTokenService&&(e.wrappableTokens=this._wrappableTokenService.getCacheStats()),e}clearCache(e){this.launchpadAPI.clearCache(e),void 0!==e&&""!==e||(void 0!==this._bridgeableTokenService&&this._bridgeableTokenService.clearCache(),void 0!==this._wrappableTokenService&&this._wrappableTokenService.clearCache())}validateConfiguration(){try{Qn(this.config.timeout,1,3e5,"timeout")}catch{this.logger.warn(`Invalid timeout value: ${this.config.timeout??"undefined"}. Using default 30000ms.`),this.config.timeout=3e4}if(void 0===this.config.baseUrl||""===this.config.baseUrl)throw jt("baseUrl is required in configuration","baseUrl");if(void 0===this.config.webSocketUrl||""===this.config.webSocketUrl)throw jt("webSocketUrl is required in configuration","webSocketUrl");try{new URL(this.config.baseUrl)}catch{throw jt(`Invalid baseUrl format: ${this.config.baseUrl}`,"baseUrl")}try{new URL(this.config.webSocketUrl)}catch{throw jt(`Invalid webSocketUrl format: ${this.config.webSocketUrl}`,"webSocketUrl")}if(void 0!==this.config.gatewayBaseUrl&&""!==this.config.gatewayBaseUrl)try{new URL(this.config.gatewayBaseUrl)}catch{throw jt(`Invalid gatewayBaseUrl format: ${this.config.gatewayBaseUrl}`,"gatewayBaseUrl")}if(void 0!==this.config.bundleBaseUrl&&""!==this.config.bundleBaseUrl)try{new URL(this.config.bundleBaseUrl)}catch{throw jt(`Invalid bundleBaseUrl format: ${this.config.bundleBaseUrl}`,"bundleBaseUrl")}if(void 0!==this.config.launchpadFrontendUrl&&""!==this.config.launchpadFrontendUrl)try{new URL(this.config.launchpadFrontendUrl)}catch{throw jt(`Invalid launchpadFrontendUrl format: ${this.config.launchpadFrontendUrl}`,"launchpadFrontendUrl")}}parseSlippageToleranceFactor(e){const t=Wn("string"==typeof e||"number"==typeof e?e:String(e),sg.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR);return t<0||t>1?(this.logger.warn(`Invalid slippage tolerance factor: ${String(e)}, using default: ${sg.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR}`),sg.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR):t}parseFeeSlippageFactor(e){const t=Wn("string"==typeof e||"number"==typeof e?e:String(e),sg.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: ${sg.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR}`),sg.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!==Do.COMPLETED)throw new Qh(e,n.status,n.message);let r;try{r=t(n)}catch(t){if(t instanceof zh)throw t;throw new zh(`Failed to transform WebSocket response for transaction ${e}`,Lt(t)?t:new Error(Ut(t)))}return this.logger.debug(`Transaction confirmed: ${e}`,r),r}catch(t){if(this.logger.error(`Transaction confirmation failed: ${e}`,t),t instanceof Qh||t instanceof zh)throw t;throw new zh(`WebSocket confirmation failed for transaction ${e}`,Lt(t)?t:new Error(Ut(t)))}}async warmCacheFromPools(e){if(void 0===e||!Array.isArray(e))return;const{extractMetadataFromPoolData:t,isValidPoolForCaching:n}=await Promise.resolve().then(function(){return pf});e.forEach(e=>{if(!n(e))return;const r=t(e,this.logger);r&&this.launchpadAPI.warmCacheFromPoolData(e.tokenName,r)})}connectWebSocket(){this.websocketService.connect()}disconnectWebSocket(){this.websocketService.disconnect()}isWebSocketConnected(){return this.websocketService.isConnected()}subscribeToEvent(e,t){const n=this.websocketService.getSocket();return n?(n.on(e,t),()=>{n.off(e,t),this.logger.debug(`Unsubscribed from event: "${e}"`)}):(this.logger.warn(`⚠️ WebSocket not connected - subscribing to "${e}" without connection`),()=>{})}onLaunchpadTokenCreation(e,t){const n=1e3,r=Math.max(t?.intervalMs??3e4,n);null!=t?.intervalMs&&t.intervalMs<n&&this.logger.warn(`Poll interval ${t.intervalMs}ms is below minimum 1000ms. Using minimum interval instead.`);const s=t?.creatorAddress,i=new Map;let o=!0,a=null;let c=0;const l=async()=>{if(o){try{const t=await this.fetchPools({type:"recent",pageSize:20});c>0&&(this.logger.debug("Successfully recovered from polling errors"),c=0),t.items.forEach(t=>{i.has(t.tokenName)||((e=>{if(i.set(e,!0),i.size>1e3){const e=i.keys().next().value;void 0!==e&&i.delete(e)}})(t.tokenName),void 0!==s&&""!==s&&t.creatorAddress!==s||e(t))})}catch(e){c++;const t=Ut(e);c>=5?this.logger.error(`Polling for new launchpad tokens failed ${c} consecutive times. Last error: ${t}. Continuing to retry...`):c>1?this.logger.warn(`Error polling for new launchpad tokens (attempt ${c}/5): ${t}`):this.logger.debug(`Error polling for new launchpad tokens: ${t}`)}if(o){const e=Math.min(Math.max(c-1,0),2),t=r*Math.pow(2,e);a=setTimeout(()=>{l()},t)}}};return l(),()=>{o=!1,a&&clearTimeout(a),this.logger.debug("Stopped watching for launchpad token creation")}}matchesCreatorFilter(e,t){return void 0===t||""===t||e.creatorAddress===t}subscribeToTokenCreations(e,t){if(this.logger.debug("Subscribing to token creation broadcasts"+(void 0!==t?.creatorFilter&&""!==t.creatorFilter?` (filter: ${t.creatorFilter})`:"")),null===this.websocketService||void 0===this.websocketService)throw jt("WebSocket service not initialized. Ensure websocketUrl is configured and the service is connected.","websocketService");let n=!1,r=null;const s=(n,...r)=>{try{if(r.length>0&&"object"==typeof r[0]&&null!==r[0]){const n=r[0].data;if(void 0!==n?.Data&&null!==n.Data&&"object"==typeof n.Data){const r=n.Data;if("CreateSale"===r.functionName){const n=(e,t="")=>{const n=r[e];return"string"==typeof n&&""!==n?n:t},s={tokenName:n("tokenName"),symbol:n("symbol"),creatorAddress:n("creatorAddress"),description:n("description"),image:n("image"),vaultAddress:n("vaultAddress"),tokenStringKey:n("tokenStringKey"),preBuyQuantity:n("initialBuyQuantity","0"),websiteUrl:n("websiteUrl"),telegramUrl:n("telegramUrl"),twitterUrl:n("twitterUrl"),instagramUrl:n("instagramUrl"),facebookUrl:n("facebookUrl"),redditUrl:n("redditUrl"),tiktokUrl:n("tiktokUrl"),isFinalized:!0===r.isFinalized};this.matchesCreatorFilter(s,t?.creatorFilter)&&e(s)}}}}catch(e){this.logger.warn(`Error processing token creation broadcast: ${Ut(e)}`)}};let i=this.websocketService.getSocket();if(i)i.onAny(s),n=!0,this.logger.debug("Token creation broadcast listener registered");else{this.logger.debug("WebSocket not yet connected, initiating connection..."),this.websocketService.connect().catch(e=>{const n=new Error(`WebSocket connection failed: ${Ut(e)}`);this.logger.warn("Failed to establish WebSocket connection:",e),t?.onError&&t.onError(n)});let e=0;const o=()=>{if(i=this.websocketService.getSocket(),!i&&e<sg.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS)return e++,void(r=setTimeout(()=>o(),sg.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS));if(!i&&e>=sg.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS){const e=new Error(`WebSocket not available after ${sg.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS*sg.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS}ms`);return this.logger.warn("Token creation broadcast subscription timeout:",e.message),void(t?.onError&&t.onError(e))}i&&(i.onAny(s),n=!0,this.logger.debug("Token creation broadcast listener registered"))};o()}return()=>{try{if(null!==r&&(clearTimeout(r),r=null,this.logger.debug("Cleared token creation broadcast polling timeout")),!n)return void this.logger.debug("Cleanup called before listener registration - no action needed");const e=this.websocketService.getSocket();e&&(e.offAny(s),n=!1,this.logger.debug("Stopped listening to token creation broadcasts"))}catch(e){this.logger.warn("Error removing token creation listener:",e)}}}getNftCollectionClaimFee(){return this.nftCollectionService.getCollectionClaimFee()}getNftTokenClassCreateFee(){return this.nftCollectionService.getTokenClassCreateFee()}estimateNftMintFee(e){return this.nftCollectionService.estimateMintFee(e)}estimateNftOperationFees(e){return this.nftCollectionService.estimateNftOperationFees(e)}claimNftCollection(e){return this.nftCollectionService.claimCollection(e)}fetchNftCollections(e){return this.nftCollectionService.fetchUserCollections(e)}isNftCollectionAvailable(e){return this.nftCollectionService.isCollectionAvailable(e)}createNftTokenClass(e){return this.nftCollectionService.createTokenClass(e)}fetchNftTokenClasses(e){return this.nftCollectionService.fetchTokenClasses(e)}mintNft(e){return this.nftCollectionService.mintNft(e)}fetchNftBalances(e,t){return this.nftCollectionService.fetchNftBalances(e,t)}async cleanup(){try{if(this.logger.debug("Starting cleanup..."),void 0!==this._eventsBatcherService)try{await this._eventsBatcherService.shutdown(5e3),this._eventsBatcherService=void 0}catch(e){this.logger.warn("Error during events shutdown:",e)}this.http.cleanup(),null!==this.websocketService&&void 0!==this.websocketService&&this.websocketService.disconnect(),void 0!==this._streamWebSocketService&&(this._streamWebSocketService.dispose(),this._streamWebSocketService=void 0),this.logger.debug("Cleanup completed")}catch(e){this.logger.error("Error during cleanup:",e)}}static cleanupAll(e=!1){const t=new En({debug:e,context:"LaunchpadSDK"});t.debug("Starting global cleanup..."),gh.cleanupAll(e),t.debug("Global cleanup completed")}}function ig(e){cr(e)&&(e={});const{wallet:t,env:n,config:r={},...s}=e,i={...{...s,...r}};delete i.wallet,delete i.env,delete i.config;const o=!cr(i.signer)||!cr(i.walletProvider);let a;if(cr(t))a=o?void 0:new T(f().privateKey);else if("string"==typeof t)a=new T(f(t).privateKey);else{if(!(t instanceof T))throw jt("Invalid wallet input. Expected string (private key or mnemonic) or Wallet instance.","wallet");a=t}const c={...void 0!==a?{wallet:a}:{},...void 0!==n?{env:n}:{},debug:!1,timeout:3e4,...i};return new sg(c)}function og(e){const t=f(e);return{...t,wallet:new T(t.privateKey)}}function ag(){const e=globalThis;return e.process?.env??{}}sg.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR=.15,sg.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR=.01,sg.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY=hn.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY,sg.DEFAULT_CALCULATE_AMOUNT_MODE=Nt.LOCAL,sg.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS=30,sg.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS=100;class cg{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 sg(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 sg(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=Wn(t.quantity,0);s.hasBalance=e>0,s.canTrade=e>=.1,s.canCreateTokens=e>=100,0===e?r.push("Wallet has zero GALA balance - cannot perform transactions"):e<.1?r.push("GALA balance too low for trading (minimum 0.1 GALA)"):e<100&&r.push("GALA balance too low for token creation (minimum 100 GALA)")}else n.push("Failed to fetch GALA balance: No balance returned")}catch(e){n.push(`Balance check error: ${Ut(e)}`)}try{const t=await e.fetchPools({type:"recent",pageSize:1});null!==t.items&&void 0!==t.items&&0!==t.items.length||r.push("Pool listing not accessible - some features may be limited")}catch(e){r.push(`Pool access test failed: ${Ut(e)}`)}return{ready:0===n.length&&s.connectionHealthy,sdk:e,wallet:t??og(),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"===(ag().LAUNCHPAD_ENV??ag().ENVIRONMENT)?"stage":"prod"}static setupWallet(e){if(void 0===e||""===e){const e=ag().PRIVATE_KEY;return void 0!==e&&""!==e?og(e):og()}return"generate"===e?og():og(e)}static buildSdkConfig(e,t,n){const r=e.galaChainAddress??ag().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 _o(e).launchpadBaseUrl}static getDefaultTimeout(e){switch(e){case"prod":return 3e4;case"stage":return 45e3}}static getEnvironmentDefaults(e){const t=_o(e);return{bundleBaseUrl:t.bundleBaseUrl,gatewayBaseUrl:t.gatewayBaseUrl}}}function lg(e,t,n){const r="number"==typeof e?new I(e):e;if(r.isLessThan(0)||r.isGreaterThan(1))throw new Error(`Progress must be between 0 and 1, got: ${r.toString()}`);if(n<t)throw new Error(`maxFee must be >= minFee, got minFee: ${t}, maxFee: ${n}`);const s=n-t;return new I(t).plus(new I(s).multipliedBy(r))}function dg(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 ug(e,t,n=60){const r=Qi(e),s=Qi(t);if(r.isLessThanOrEqualTo(0)||s.isLessThanOrEqualTo(0))throw new Error("Prices must be positive");if(r.isGreaterThanOrEqualTo(s))throw new Error(`minPrice must be < maxPrice, got: ${r.toString()} >= ${s.toString()}`);const i=Math.floor(Ji(r)),o=Math.ceil(Ji(s)),a=Math.floor(i/n)*n,c=Math.ceil(o/n)*n;return{minTick:a,maxTick:c,actualMinPrice:new I(1.0001).pow(a),actualMaxPrice:new I(1.0001).pow(c)}}function hg(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 gg(e,t){if(t<0)throw new Error(`decimals must be >= 0, got: ${t}`);const n=Qi(e),r=new I(10).pow(t);return n.multipliedBy(r).integerValue(I.ROUND_UP).dividedBy(r)}function mg(e,t,n,r="0"){const s=Qi(t);if(Zi(s))return Qi(r);const i=Qi(e).dividedBy(s);if(null!=n){const e=Qi(n);if(e.isLessThan(0))throw new Error(`minimum must be >= 0, got: ${e.toString()}`);if(i.isLessThan(e))return e}return i}function fg(e,t){if(t<=0)throw new Error(`tickSpacing must be > 0, got: ${t}`);return Math.floor(e/t)*t}function pg(e,t){if(t<0)throw new Error(`feeFactor must be >= 0, got: ${t}`);return Qi(e).multipliedBy(t).integerValue(I.ROUND_DOWN)}function Eg(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 Ag(e){if(null==e||"object"!=typeof e)throw new Error("Token must be an object");const t=e,n=(or(t.name)?t.name:void 0)??(or(t.tokenName)?t.tokenName:void 0)??"";if(!or(n))throw new Error("Token name is required and must be a non-empty string");const r=(or(t.symbol)?t.symbol:void 0)??(or(t.tokenSymbol)?t.tokenSymbol:void 0)??"";if(!or(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 or(t.address)&&(i.address=t.address),"boolean"==typeof t.verified&&(i.verified=t.verified),i}function vg(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(or(n))return n;if(null!=n&&""!==n)return n}return n}function Tg(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 yg(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 Sg(e,t){const n={...e};for(const[e,r]of Object.entries(t))void 0!==r&&(n[e]=r);return n}class bg{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 Ng{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 wg{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 kg{constructor(e){this.globalCallbacks=[],this.roomCallbacks=new Map,this.logger=e}registerGlobalCallback(e){this.globalCallbacks.push(e)}registerRoomCallback(e,t){const n=this.roomCallbacks.get(e)??[];n.push(t),this.roomCallbacks.set(e,n)}dispatch(e,t){for(const e of this.globalCallbacks)try{e(t)}catch(e){this.logger?.error(`Error in global callback: ${Ut(e)}`)}const n=this.roomCallbacks.get(e);if(n)for(const r of n)try{r(t)}catch(t){this.logger?.error(`Error in room callback for ${e}: ${Ut(t)}`)}}clear(){this.globalCallbacks=[],this.roomCallbacks.clear()}clearRoom(e){this.roomCallbacks.delete(e)}}class _g{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 Ig{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 Dg{constructor(e={},t){this.events=[],this.timeouts=new Map,this.maxSize=e.maxSize??100,this.defaultTtlMs=e.defaultTtlMs??3e4,this.logger=t}push(e){if(this.events.length>=this.maxSize){const e=0;this.events.shift();const t=this.timeouts.get(e);t&&(clearTimeout(t),this.timeouts.delete(e)),this.logger?.warn(`Buffer full (${this.maxSize}), dropped oldest event`)}this.events.push(e);const t=this.events.length-1,n=setTimeout(()=>{this.events[t]===e&&this.events.splice(t,1),this.timeouts.delete(t)},this.defaultTtlMs);this.timeouts.set(t,n)}getAll(){return[...this.events]}clear(){for(const e of this.timeouts.values())clearTimeout(e);this.events=[],this.timeouts.clear()}get size(){return this.events.length}}class Cg{constructor(e={},t){this.pendingIndicators=new Map,this.activeIndicators=new Set,this.delayMs=e.delayMs??3e3,this.onTyping=e.onTyping,this.onStopTyping=e.onStopTyping}indicate(e,t){const n=`${e}:${t}`,r=this.pendingIndicators.get(n);r&&clearTimeout(r),this.activeIndicators.has(n)||(this.activeIndicators.add(n),this.onTyping?.(e,t));const s=setTimeout(()=>{this.activeIndicators.delete(n),this.pendingIndicators.delete(n),this.onStopTyping?.(e,t)},this.delayMs);this.pendingIndicators.set(n,s)}stopTyping(e,t){const n=`${e}:${t}`,r=this.pendingIndicators.get(n);r&&(clearTimeout(r),this.pendingIndicators.delete(n)),this.activeIndicators.has(n)&&(this.activeIndicators.delete(n),this.onStopTyping?.(e,t))}clear(){for(const e of this.pendingIndicators.values())clearTimeout(e);this.pendingIndicators.clear(),this.activeIndicators.clear()}get activeCount(){return this.activeIndicators.size}}const Rg=5,Og=8,Mg=18,Lg={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"},Ug=5,Fg=5;function Pg(e){const t={};return void 0!==e.cursor&&(t.cursor=e.cursor),void 0!==e.pageSize&&(t.pageSize=e.pageSize),t}function xg(e,t){return Pg({...e,...t})}function Bg(e,t){return void 0===t?e:{...e,cursor:t}}function Gg(e){return"string"==typeof e?e:"number"==typeof e||"boolean"==typeof e||"bigint"==typeof e?String(e):JSON.stringify(e)??""}async function $g(e,t,n,r){const s=r?.logger,i=[];i.length=e.length;let o=0,a=0;s?.debug(`Starting concurrent batch requests: ${e.length} URLs, batch size: ${t}`);for(let r=0;r<e.length;r+=t){const c=e.slice(r,r+t),l=r;try{const t=c.map((t,r)=>{const c=l+r;return(async()=>{try{const r=await n(t);return i[c]=r,o++,s?.debug(`Fetched [${c+1}/${e.length}]: ${t}`),r}catch(n){throw a++,s?.warn(`Failed [${c+1}/${e.length}]: ${t} - ${Ut(n)}`),n}})()}),r=await Promise.allSettled(t);for(let e=0;e<r.length;e++){const t=r[e];"rejected"===t?.status&&s?.debug(`Promise rejected in batch at index ${l+e}`)}}catch(e){s?.error(`Batch processing error at index ${r}: ${Ut(e)}`)}}return s?.debug(`Batch complete: ${o} succeeded, ${a} failed`),i}function Kg(e){const t={page:1,pageSize:20,totalCount:-1,hasMore:!1};if(null==e||"object"!=typeof e)return t;const n=e,r=Vn(Gg(n.page??n.Page??n.current??1),t.page),s=Vn(Gg(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:Vn(Gg(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 Hg(e){if(null==e||"object"!=typeof e)return"";const t=[];for(const[n,r]of Object.entries(e)){if(ar(r))continue;let e;e="string"==typeof r?r:"number"==typeof r||"boolean"==typeof r?String(r):Array.isArray(r)?r.map(e=>Gg(e)).join(","):Gg(r);const s=encodeURIComponent(n),i=encodeURIComponent(e);t.push(`${s}=${i}`)}return t.length>0?`?${t.join("&")}`:""}async function Wg(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=qg(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 Vg(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 jg(e,t,n){const r=n?.logger,s=n?.fetcher??(async e=>{const t=await fetch(e);if(!t.ok)throw new Error(`HTTP ${t.status}`);return t.json()});r?.debug(`Aggregating from ${e.length} endpoints`);const i=e.map(async(t,n)=>{try{const i=await s(t);return r?.debug(`Endpoint [${n+1}/${e.length}] succeeded: ${t}`),i}catch(s){return void r?.warn(`Endpoint [${n+1}/${e.length}] failed: ${t} - ${Ut(s)}`)}}),o=(await Promise.allSettled(i)).map(e=>{if("fulfilled"===e.status)return e.value});return r?.debug(`Aggregating ${o.filter(e=>void 0!==e).length} successful results`),t(o)}function qg(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 zg(e){const t=e.trim().toLowerCase();if(0===t.length)throw new Error("Token name cannot be empty");return t}function Xg(e){if(void 0!==e&&e.length>0&&!/^[a-z0-9]+$/.test(e.toLowerCase()))throw new Error(`Invalid asset extension format: "${e}". Must contain only alphanumeric characters.`)}function Qg(e,t){return`${e.replace(/\/$/,"")}${t}`}function Yg(e,t){const n=zg(e);return Qg(t,`/v1/tokens/${encodeURIComponent(n)}/assets/image`)}function Jg(e,t,n="jpg"){const r=zg(e);Xg(n);return Qg(t,`/v1/tokens/${encodeURIComponent(r)}/assets/thumbnail.${n.toLowerCase()}`)}function Zg(e,t,n="gif"){const r=zg(e);Xg(n);return Qg(t,`/v1/tokens/${encodeURIComponent(r)}/assets/animated.${n.toLowerCase()}`)}function em(e,t){const n=zg(e);return Qg(t,`/v1/tokens/${encodeURIComponent(n)}/assets/poster.jpg`)}function tm(e,t,n="vtt"){const r=zg(e);Xg(n);return Qg(t,`/v1/tokens/${encodeURIComponent(r)}/assets/storyboard.${n.toLowerCase()}`)}function nm(e,t){const n=zg(e);return Qg(t,`/v1/tokens/${encodeURIComponent(n)}/assets/live.m3u8`)}function rm(e,t,n,r){const s=zg(e),i=t.trim().toLowerCase();if(0===i.length)throw new Error("Asset type cannot be empty");Xg(r);const o=void 0!==r&&r.length>0?`.${r.toLowerCase()}`:"";return Qg(n,`/v1/tokens/${encodeURIComponent(s)}/assets/${encodeURIComponent(i)}${o}`)}function sm(e,t,n,r="jpg"){const s=zg(e),i=t.trim();if(0===i.length)throw new Error("Recording ID cannot be empty");Xg(r);return Qg(n,`/v1/tokens/${encodeURIComponent(s)}/recordings/${encodeURIComponent(i)}/assets/thumbnail.${r.toLowerCase()}`)}function im(e,t,n,r="gif"){const s=zg(e),i=t.trim();if(0===i.length)throw new Error("Recording ID cannot be empty");Xg(r);return Qg(n,`/v1/tokens/${encodeURIComponent(s)}/recordings/${encodeURIComponent(i)}/assets/animated.${r.toLowerCase()}`)}function om(e,t,n){const r=zg(e),s=t.trim();if(0===s.length)throw new Error("Recording ID cannot be empty");return Qg(n,`/v1/tokens/${encodeURIComponent(r)}/recordings/${encodeURIComponent(s)}/assets/poster.jpg`)}function am(e,t,n,r="vtt"){const s=zg(e),i=t.trim();if(0===i.length)throw new Error("Recording ID cannot be empty");Xg(r);return Qg(n,`/v1/tokens/${encodeURIComponent(s)}/recordings/${encodeURIComponent(i)}/assets/storyboard.${r.toLowerCase()}`)}function cm(e,t,n){const r=zg(e),s=t.trim();if(0===s.length)throw new Error("Recording ID cannot be empty");return Qg(n,`/v1/tokens/${encodeURIComponent(r)}/recordings/${encodeURIComponent(s)}/assets/stream.m3u8`)}function lm(e,t,n,r,s){const i=zg(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");Xg(s);const c=void 0!==s&&s.length>0?`.${s.toLowerCase()}`:"";return Qg(r,`/v1/tokens/${encodeURIComponent(i)}/recordings/${encodeURIComponent(o)}/assets/${encodeURIComponent(a)}${c}`)}const dm=new Map;function um(e,t){const n=e;return dm.set(n,{createdAt:Date.now(),label:t}),n}function hm(e){const t=e;dm.delete(t)}function gm(){const e=dm.size;return dm.clear(),e}function mm(){const e=Array.from(dm.entries()).map(([e,t])=>({id:e,...t}));return{size:dm.size,entries:e}}class fm extends Nr{constructor(e,t=!1){super(e,t)}async getChart(e){if(null==e)throw Ht("options","Chart options");const{tokenName:t,from:n,to:r,resolution:s}=e;if(null==t||""===t)throw Ht("tokenName","Token name");if(null==n)throw Ht("from","Start timestamp");if(null==r)throw Ht("to","End timestamp");if(null==s)throw Ht("resolution","Data resolution interval");hr(t,"tokenName",Ir);const i=173e6;if("number"!=typeof n||n<i)throw new kt("from must be a valid timestamp (min: 173000000)","from","INVALID_TIMESTAMP");if("number"!=typeof r||r<i)throw new kt("to must be a valid timestamp (min: 173000000)","to","INVALID_TIMESTAMP");if("number"!=typeof s||s<1)throw new kt("resolution must be a number >= 1","resolution","INVALID_RESOLUTION");const{adaptQueryParams:o}=await Promise.resolve().then(function(){return _l}),a=o({tokenName:t,from:n,to:r,resolution:s}),c=await dn(()=>this.http.get(R.CHART,a),{errorContext:"Failed to fetch chart data"}),l=on(c);if(null==l||"object"!=typeof l)throw Vt("Invalid API response: missing or invalid data",c.status??500);const d=l,u=d.data;if(!Array.isArray(u))throw Vt("Invalid API response: expected data array",c.status??500);const h={dataPoints:u.map(e=>{if("object"!=typeof e||null===e)throw Vt("Invalid API response: invalid data point structure",c.status??500);const t=e,n=t.startTime??t.timestamp,r=t.openPrice??t.value,s=t.closePrice??t.value,i=t.lowPrice??t.value,o=t.highPrice??t.value,a=t.volume??"0";return{startTime:"number"==typeof n?n:Number(n),openPrice:String(r),closePrice:String(s),lowPrice:String(i),highPrice:String(o),volume:String(a)}})};return"boolean"==typeof d.isPreviousData&&(h.isPreviousData=d.isPreviousData),h}}const pm={NEW_HOLDER:"NEW_HOLDER",EXITED_HOLDER:"EXITED_HOLDER",BALANCE_CHANGED:"BALANCE_CHANGED"},Em=zi({type:"string",userAddress:"string",balance:"string",rank:"number",previousRank:"optional-number"}),Am=zi({tokenName:"string",userAddress:"string",quantity:"optional-string",percentage:"optional-number",holderTier:"optional-object",isCreator:"boolean",rank:"optional-number"});function vm(e){return"string"==typeof e&&(e===pm.NEW_HOLDER||e===pm.EXITED_HOLDER||e===pm.BALANCE_CHANGED)}Cr.MIN_LENGTH,Cr.MAX_LENGTH,Cr.PATTERN;dr({ENABLED:"ENABLED",DISABLED:"DISABLED",ADMIN_DISABLED:"ADMIN_DISABLED"});function Tm(e){return"global"===e||"token"===e}function ym(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 Sm(e){return ym(e)}function bm(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.message}function Nm(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 wm(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 km(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&wm(t.pinnedMessage)}function _m(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.unpinnedMessageId}function Im(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"boolean"==typeof t.enabled&&(void 0===t.reason||Tm(t.reason))}function Dm(e){return!!or(e)&&(e.length>=Pr.CHAT_MESSAGE.MIN_LENGTH&&e.length<=Pr.CHAT_MESSAGE.MAX_LENGTH)}function Cm(e){return!!or(e)&&Cr.PATTERN.test(e)}function Rm(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 Om(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.message}const Mm=dr({RATE_LIMITED:"RATE_LIMITED",INVALID_EMOJI:"INVALID_EMOJI",NOT_AUTHENTICATED:"NOT_AUTHENTICATED",STREAM_NOT_LIVE:"STREAM_NOT_LIVE"});function Lm(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 Um(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&Array.isArray(t.typingUsers)&&t.typingUsers.every(Lm)}const Fm={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 Pm,xm,Bm,Gm,$m,Km;!function(e){e.PENDING="PENDING",e.PROCESSING="PROCESSING",e.COMPLETED="COMPLETED",e.FAILED="FAILED"}(Pm||(Pm={})),function(e){e.TEXT="TEXT",e.IMAGE="IMAGE",e.VIDEO="VIDEO"}(xm||(xm={})),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"}(Bm||(Bm={})),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"}(Gm||(Gm={})),function(e){e.QUICK="QUICK",e.DETAILED="DETAILED"}($m||($m={})),function(e){e.DISABLED="DISABLED",e.ADVISORY="ADVISORY"}(Km||(Km={}));const Hm={[Pm.PENDING]:"Pending",[Pm.PROCESSING]:"Processing",[Pm.COMPLETED]:"Completed",[Pm.FAILED]:"Failed"},Wm={[Bm.NO_ACTION]:"No Action Needed",[Bm.REVIEW_REQUIRED]:"Human Review Required",[Bm.DELETE_CONTENT]:"Delete Content",[Bm.BAN_USER]:"Ban User",[Bm.DELETE_AND_BAN]:"Delete & Ban"},Vm={[Gm.VIOLENCE]:"Violence",[Gm.HATE_SPEECH]:"Hate Speech",[Gm.SEXUAL_CONTENT]:"Sexual Content",[Gm.HARASSMENT]:"Harassment",[Gm.SPAM]:"Spam",[Gm.SCAM]:"Scam",[Gm.SELF_HARM]:"Self Harm",[Gm.ILLEGAL_ACTIVITY]:"Illegal Activity",[Gm.MISINFORMATION]:"Misinformation",[Gm.COPYRIGHT]:"Copyright",[Gm.SAFE]:"Safe"},jm={[$m.QUICK]:"Quick Scan",[$m.DETAILED]:"Detailed Scan"},qm={[xm.TEXT]:"Text",[xm.IMAGE]:"Image",[xm.VIDEO]:"Video"},zm={[Km.DISABLED]:"Disabled",[Km.ADVISORY]:"Advisory"},Xm=dr(Pm),Qm=dr(xm),Ym=dr(Bm),Jm=dr(Gm),Zm=dr($m),ef=dr(Km),tf=pr([{field:"id",type:"number"},{field:"flagId",type:"number"},{field:"status",type:"string",validator:Xm},{field:"analysisType",type:"string",validator:Qm},{field:"provider",type:"string"}]),nf=pr([{field:"enabled",type:"boolean"},{field:"mode",type:"string",validator:ef},{field:"provider",type:"string"}]);function rf(e){return null!==e.analysisTier}function sf(e){return!0===e.escalatedFromQuick}function of(e,t){if(!rf(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 af(e){if(!(void 0!==e.tokenName&&""!==e.tokenName||void 0!==e.userAddress&&""!==e.userAddress))throw en(["tokenName","userAddress"]);void 0!==e.tokenName&&""!==e.tokenName&&fr(e.tokenName,"tokenName",Ir),lr(0,void 0,Ur,e.pageSize,e.cursor)}function cf(e){if(!or(e.tokenName))throw Ht("tokenName","Token name");fr(e.tokenName,"tokenName",Ir),df(e.content)}function lf(e){df(e.content)}function df(e){if(!or(e))throw Ht("content");if(0===e.trim().length)throw nn("content","Content");if(e.length>Pr.COMMENTS_V1.MAX_LENGTH)throw tn("content",Pr.COMMENTS_V1.MAX_LENGTH,e.length)}function uf(e){if(!(void 0!==e.tokenName&&""!==e.tokenName||void 0!==e.userAddress&&""!==e.userAddress))throw new kt("At least one of tokenName or userAddress is required","options",wt.REQUIRED);td(e.tokenName,e.userAddress),void 0!==e.pageSize&&lr(0,void 0,Ur,e.pageSize)}function hf(e){if(!or(e.tokenName))throw Ht("tokenName");fr(e.tokenName,"tokenName",Ir),mf(e.content)}function gf(e){mf(e.content)}function mf(e){if(!or(e))throw Ht("content");if(0===e.trim().length)throw new kt("content cannot be empty","content",wt.REQUIRED);if(e.length>Pr.CHAT_MESSAGES_V1.MAX_LENGTH)throw new kt(`content must be at most ${Pr.CHAT_MESSAGES_V1.MAX_LENGTH} characters`,"content",wt.TOO_LONG)}function ff(e){if(!or(e))throw Ht("id","Message ID");if(!xr.CHAT_MESSAGE.PATTERN.test(e))throw new kt("Invalid message ID format. Expected: chat-{timestamp}-{uuid}","id",wt.INVALID_FORMAT)}var pf=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=Wn(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=Wn(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{da as ACTIVE_USER_TYPE,Km as AIModerationMode,Bm as AIRecommendation,zm as AI_MODE_LABELS,Wm as AI_RECOMMENDATION_LABELS,ea as ALL_PERMISSIONS,Vm as ANALYSIS_CATEGORY_LABELS,Hm as ANALYSIS_STATUS_LABELS,jm as ANALYSIS_TIER_LABELS,qm as ANALYSIS_TYPE_LABELS,Jo as API_KEY_PERMISSION,Qo as API_KEY_ROLE,Yo as API_KEY_ROLES,oa as API_KEY_ROLE_HIERARCHY,Rn as AddressFormatter,cg as AgentConfig,Gm as AnalysisCategory,Pm as AnalysisStatus,$m as AnalysisTier,xm as AnalysisType,vo as AuthError,Ao as AuthErrorType,la as BAN_DURATIONS,xa as BrowserWalletSigner,ph as BundleSubmission,Eh as BundlerTransport,dl as BurnError,ll as BurnErrorType,Nt as CALCULATION_MODES,pc as CONTENT_REACTION_TYPES,ic as CONTENT_TYPE_LABELS,fm as ChartService,Ot as ConfigurationError,qa as ContentType,Sc as DEFAULT_EVENTS_CONFIG,Ug as DEFAULT_PRICING_CONCURRENCY,Rh as DEFAULT_REVERSE_BONDING_CURVE_CONFIGURATION,Fg as DEFAULT_WEBSOCKET_RECONNECT_ATTEMPTS,ko as ENVIRONMENT_URLS,wt as ERROR_CODES,wc as EVENT_SORT_FIELDS,_c as EVENT_SOURCES,kc as EVENT_TIME_PRESETS,bc as EVENT_TYPES,vu as EXTENDED_STREAM_ROLE,Dg as EventBufferWithAutoCleanup,Nc as EventsBatcherService,Oc as EventsQueryService,sc as FLAG_ACTION_LABELS,oc as FLAG_DETAILS_MAX_LENGTH,nc as FLAG_REASON_LABELS,rc as FLAG_STATUS_LABELS,yl as FileValidationError,Qa as FlagAction,za as FlagReason,Xa as FlagStatus,Og as GALA_DECIMALS,Pa as GalaWalletSigner,kg as GlobalAndRoomCallbackDispatcher,pm as HOLDER_DELTA_TYPES,Tl as HealthService,ys as IMAGE_EXTENSIONS,Ad as INVITE_STATUS,vd as INVITE_STATUSES,po as JWT_CONSTANTS,Mg as LAUNCHPAD_TOKEN_DECIMALS,fh as LAUNCHPAD_WRITE_METHODS,sg as LaunchpadSDK,Ia as LaunchpadSDKError,Kh as LaunchpadWrites,Ig as ListenerCleanupManager,Wc as LockError,Kc as LockErrorType,cl as MAX_BURN_BATCH_SIZE,Rg as MAX_CONCURRENT_POOL_FETCHES,Gc as MAX_LOCK_BATCH_SIZE,$c as MAX_UNLOCK_BATCH_SIZE,rd as MESSAGES_CONSTRAINTS,nd as MESSAGE_TYPES,md as MODERATOR_ROLE,fd as MODERATOR_ROLES,Rd as NFT_FEES,Rt as NetworkError,xd as NftCollectionService,Gd as OEmbedService,Kd as OVERSEER_INVITE_STATUS,Hd as OVERSEER_STATUS,Oo as PAGINATION_DEFAULTS,Zo as PERMISSION,Mo as POOL_FETCH_CONFIG,yt as POOL_FETCH_TYPES,bt as POOL_LIST_MAX_PAGE_SIZE,St as POOL_STREAM_STATUSES,Tt as POOL_TYPES,Ng as PayloadWalkerWithDeduplication,wg as PendingSubscriptionTracker,su as PlatformStatsService,Fa as PrivateKeySigner,Lg as QUERY_FIELD_NAMES,Ec as REACTION_EMOJI_MAP,cu as RECORDING_STATUS,Eu as ROLE_SOURCE,bg as RoomSubscriptionManager,Do as SDKTransactionStatus,Ro as SDK_VERSION,ku as SIMULATE_EVENT_TYPE,du as SIMULCAST_PLATFORM,lu as SIMULCAST_STATUS,Iu as STREAM_EVENTS,Au as STREAM_PERMISSION,pu as STREAM_ROLE,au as STREAM_STATUS,_g as SelectiveEventForwarding,Zu as StreamWebSocketService,Fm as TIME_CONSTANTS,Rr as TOKEN_NAME_AVAILABILITY_CONSTRAINT,Ir as TOKEN_NAME_DTO_CONSTRAINT,Or as TOKEN_NAME_EVENT_CONSTRAINT,Dr as TOKEN_NAME_FILTER_CONSTRAINT,Cr as TOKEN_NAME_PATH_CONSTRAINT,vt as TRADING_TYPES,_t as TokenRestrictedError,lh as TradingQuotesService,Mt as TransactionError,Qh as TransactionFailedError,Cg as TypingIndicatorDebouncer,kt as ValidationError,zh as WebSocketError,Xh as WebSocketTimeoutError,mh as WeeklyChallengeService,Bg as addCursorToPagination,es as addressFormatSchema,jg as aggregateMultipleApiSources,Ps as amountMethodSchema,Fs as amountTypeSchema,$n as assertValidWalletAddress,zr as availabilityTokenNameSchema,kn as backendUserRef,Hl as bidirectionalTokenMatch,bs as browserFileSchema,Ns as bufferFileSchema,$g as buildConcurrentBatchRequests,Hg as buildQueryParametersWithValidation,Pg as buildSafePaginationOptions,Js as buyTokensDataSchema,lg as calculateLinearFeeInterpolation,ii as calculatePreMintDataSchema,pg as calculateScaledFeeAmount,Po as calculateTotalPages,$t as capitalize,Gl as caseInsensitiveTokenComparison,Us as checkPoolOptionsSchema,Er as commonValidators,Sg as conditionalSpreadBuilder,Bl as conditionalTrimAndValidateString,ig as createLaunchpadSDK,ls as createLimitSchema,Ar as createOptionsValidator,zs as createPaginatedResultSchema,Lo as createPaginationQuery,Ys as createTradeDataSchema,gg as decimalRoundingUp,yg as deduplicateByKey,qr as dtoTokenNameSchema,$l as errorMessageCaseNormalization,ts as ethereumAddressSchema,vg as extractFieldWithFallbackPath,Kg as extractPaginationMetadata,Dh as feeCeilingFromQuotedFee,di as fetchGalaBalanceOptionsSchema,oi as fetchPoolDetailsDataSchema,gi as fetchTokenBalanceOptionsSchema,gs as fileSizeSchema,Ss as fileUploadSchema,ms as filenameSchema,ns as flexibleAddressSchema,ws as flexibleFileSchema,zn as formatGalaForDTO,Xn as formatLaunchpadTokenForDTO,Ln as fromBackendAddressFormat,Zr as fullNameSchema,Ga as generateBuySellStringsInstructions,$a as generateCreateSaleStringsInstructions,si as getAmountOptionsSchema,_o as getEnvironmentConfig,mm as getIntervalRegistryStats,Ki as getLaunchTokenDataValidationErrors,Od as getNftFeeAsNumber,im as getRecordingAnimatedUrl,lm as getRecordingAssetUrl,om as getRecordingPosterUrl,am as getRecordingStoryboardUrl,cm as getRecordingStreamUrl,sm as getRecordingThumbnailUrl,of as getTieredModerationSavings,Zg as getTokenAnimatedUrl,rm as getTokenAssetUrl,Yg as getTokenImageUrl,nm as getTokenLiveStreamUrl,em as getTokenPosterUrl,tm as getTokenStoryboardUrl,Jg as getTokenThumbnailUrl,ei as getTradeOptionsSchema,Bs as graduateTokenOptionsSchema,xs as graphDataOptionsSchema,Eg as groupByKey,xo as hasMorePages,Wl as hexStringExtractionAndNormalization,ks as imageExtensionSchema,_s as imageFilenameSchema,fs as imageMimeTypeSchema,Ms as imageUploadOptionsSchema,tf as isAIModerationData,ef as isAIModerationMode,nf as isAIModerationSettings,Ym as isAIRecommendation,ua as isActiveUserType,Jm as isAnalysisCategory,Xm as isAnalysisStatus,Zm as isAnalysisTier,Qm as isAnalysisType,ha as isBanData,fa as isBanEnforcementEvent,ol as isBurnTokenEntry,al as isBurnTokensData,Tm as isChatDisabledReason,Im as isChatStatusResponse,jd as isClaimableInvite,ac as isContentType,ar as isEmptyValue,Tu as isExtendedStreamRole,dc as isFlagAction,uc as isFlagData,cc as isFlagReason,lc as isFlagStatus,Em as isHolderDelta,vm as isHolderDeltaType,Fc as isLockTokenEntry,xc as isLockTokensData,ud as isMessage,hd as isMessageType,Nd as isModeratedToken,rf as isModerationTiered,bd as isModeratorInvite,or as isNonEmptyString,Wd as isOverseerInviteStatus,Vd as isOverseerStatus,wm as isPinnedMessage,wd as isPublicInviteInfo,Mm as isReactionErrorCode,hu as isRecordingStatus,gu as isSimulcastPlatform,Nm as isStreamChatDeletedEvent,bm as isStreamChatErrorEvent,ym as isStreamChatMessage,Sm as isStreamChatMessageEvent,km as isStreamChatPinnedEvent,_m as isStreamChatUnpinnedEvent,Om as isStreamReactionErrorEvent,Rm as isStreamReactionEvent,uu as isStreamStatus,mu as isStreamStatusEvent,yu as isTokenAccessResult,th as isTokenBanData,Um as isTypingIndicatorEvent,Lm as isTypingUser,Pc as isUnlockTokenEntry,Bc as isUnlockTokensData,ga as isUserBannedEvent,Am as isUserHoldingData,Cn as isUserRef,ma as isUserUnbannedEvent,Fn as isValidAddress,ta as isValidApiKeyRole,Ea as isValidBanDuration,pa as isValidBanReason,Dm as isValidChatContent,Cm as isValidChatTokenName,Sd as isValidInviteCode,yd as isValidInviteStatus,$i as isValidLaunchTokenData,Td as isValidModeratorRole,nh as isValidTokenBanReason,mr as isValidTokenName,fu as isViewerCountEvent,ps as isoDateStringSchema,Os as launchTokenDataSchema,xg as mergeSafePaginationOptions,is as nonNegativeDecimalStringSchema,Un as normalizeAddressInput,Tg as normalizeDataWithMapping,Kl as normalizeErrorMessage,Fo as normalizeLimit,mn as normalizeTokenKey,gn as normalizeTokenName,fn as normalizeTokenSymbol,as as optionalUrlSchema,cs as pageNumberSchema,qs as paginationResultMetaSchema,Vg as parseHttpErrorResponse,Ba as parseLaunchpadVaultAddress,hg as percentileIndexCalculation,Ls as poolFetchTypeSchema,Hs as poolPaginationSchema,ss as positiveDecimalStringSchema,ug as priceTickRangeMapping,As as privateKeySchema,um as registerInterval,no as requireNonNegative,to as requirePositive,ro as requirePositiveWithContext,Wg as retryableHttpRequest,Rs as reverseBondingCurveConfigSchema,ai as reverseBondingCurveConfigurationSchema,aa as roleHasSufficientPermission,dg as roundTickBoundaries,fg as roundTickToSpacing,mg as safeDivideWithMinimum,Jr as searchQuerySchema,Zs as sellTokensDataSchema,ds as standardLimitSchema,Gs as standardPaginationSchema,Es as timestampSchema,Mn as toBackendAddressFormat,Kn as toBackendAddressFromEthers,Ds as tokenCategorySchema,Cs as tokenCollectionSchema,Qr as tokenDescriptionSchema,li as tokenListOptionsSchema,jr as tokenNameSchema,Xr as tokenSymbolSchema,Is as tokenUrlsSchema,ri as tradeCalculationMethodSchema,ni as tradeCalculationTypeSchema,hs as tradeLimitSchema,ti as tradeListParamsSchema,Ks as tradePaginationSchema,Vs as tradePaginationWithFiltersSchema,Qs as tradeTypeBackendSchema,Xs as tradeTypeSchema,vs as transactionIdSchema,Ag as transformRawApiTokenToDomainModel,Vl as trimmedLengthValidation,Ts as uniqueKeySchema,gm as unregisterAllIntervals,hm as unregisterInterval,ui as updateProfileDataSchema,hi as uploadProfileImageOptionsSchema,os as urlSchema,us as userLimitSchema,$s as userPaginationSchema,wn as userRef,Yr as userTokenNameSchema,ci as userTokenTypeSchema,Ws as userTokensPaginationSchema,Ai as validateAddress,Ti as validateAmountString,rh as validateBanTokenOptions,Li as validateBuyTokensData,Bi as validateCalculatePreMintData,ff as validateChatMessageId,_i as validateCheckPoolOptions,sr as validateConstrainedEnumVariant,na as validateCreateApiKeyOptions,hf as validateCreateChatMessageOptions,cf as validateCreateCommentOptions,id as validateCreateMessageOptions,_d as validateCreateModeratorInviteOptions,eu as validateCreateOverseerDirectOptions,qd as validateCreateOverseerInviteOptions,Mi as validateCreateTradeData,tr as validateDecimalRangeStrict,nr as validateFeePortionConstraints,Di as validateFetchGalaBalanceOptions,sd as validateFetchMessagesOptions,Gi as validateFetchPoolDetailsData,Oi as validateFetchTokenBalanceOptions,yi as validateFullName,xi as validateGetAmountOptions,uf as validateGetChatMessagesOptions,af as validateGetCommentsOptions,oh as validateGetTokenBanOptions,Fi as validateGetTradeOptions,Fl as validateGetTradesOptions,ki as validateImageUploadOptions,Id as validateInviteCode,Hi as validateLaunchTokenData,ia as validateListApiKeysOptions,Dd as validateListModeratorInvitesOptions,zd as validateListOverseerInvitesOptions,Xd as validateListOverseersOptions,ih as validateListTokenBansOptions,Zd as validateListUsersOptions,ad as validateMessageId,rr as validateMinMaxRelationship,gr as validateOptionalTokenName,Qd as validateOverseerInviteCode,Jd as validateOverseerInviteId,Yd as validateOverseerWalletAddress,Uo as validatePaginationParams,Si as validateSearchQuery,Ui as validateSellTokensData,er as validateSortOrderDirection,Ei as validateTokenDescription,Ii as validateTokenListOptions,fr as validateTokenName,pi as validateTokenSymbol,wi as validateTokenUrls,Pi as validateTradeListParams,sh as validateUnbanTokenOptions,ra as validateUpdateApiKeyOptions,gf as validateUpdateChatMessageOptions,lf as validateUpdateCommentOptions,od as validateUpdateMessageOptions,nu as validateUpdatePlatformConfigOptions,Ci as validateUpdateProfileData,wl as validateUpdateTokenConfigOptions,Ri as validateUploadProfileImageOptions,bi as validateUserTokenName,vi as validateVaultAddress,rs as vaultAddressSchema,sf as wasModerationEscalated};
1
+ import{galaChainUserRef as e,isGalaError as t,GALA_CHAIN_ENVIRONMENTS as n,BrowserWalletSigner as r,generateEIP712Types as s,ethereumAddressOfAccount as i,GalaWalletSigner as o,withGalaWalletIdentity as a,PrivateKeySigner as c,isTokenClassKey as l,withDtoOperation as d,GatewayReads as u,GatewayWrites as h,tokenDetailsOf as g,isWalletUserRejection as m,walletDeclineCode as f,createWallet as p}from"@gala-chain/gala-core-sdk";import{computeAddress as E,getAddress as A,isAddress as v,BrowserProvider as T,Wallet as y}from"ethers";import{z as S}from"zod";import{PrivateKeyProvider as b,isPrivateKeyProvider as N}from"@gala-chain/gala-core-sdk/providers";import{ChainCallDTO as w,TokenClassKey as k}from"@gala-chain/api";import{v4 as _}from"uuid";import{io as I}from"socket.io-client";import D from"bignumber.js";import C,{AxiosHeaders as R}from"axios";const O={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"},M="/v1/users/referrals/url",L="/v1/users/referrals",U="/v1/users/referrals/summary",F="/v1/tokens/:tokenName/start-stream",P="/v1/tokens/:tokenName/stop-stream",x="/v1/tokens/:tokenName/stream/disable",B="/v1/tokens/:tokenName/stream/enable",G="/v1/tokens/:tokenName/reset-key",$="/v1/tokens/:tokenName/recordings",K="/v1/tokens/:tokenName/recordings/:assetId/download",H="/v1/tokens/:tokenName/recordings/:assetId",W="/v1/tokens/:tokenName/simulcasts",V="/v1/tokens/:tokenName/simulcasts",j="/v1/tokens/:tokenName/simulcasts/:targetId",q="/v1/config",z="/v1/config",X="/v1/config",Q="/v1/tokens/:tokenName/role",Y="/v1/roles",J="/v1/permissions",Z="/v1/tokens/:tokenName/credentials",ee="/auth/login",te="/auth/logout",ne="/auth/refresh",re="/auth/session",se="/v1/tokens/:tokenName/bans",ie="/v1/tokens/:tokenName/bans",oe="/v1/tokens/:tokenName/bans/:userAddress",ae="/v1/tokens/:tokenName/bans/:userAddress",ce="/v1/tokens/:tokenName/active-users",le="/v1/user-bans",de="/v1/user-bans",ue="/v1/user-bans/:userAddress",he="/v1/user-bans/:userAddress",ge={CREATE:"/v1/api-keys",LIST:"/v1/api-keys",GET:"/v1/api-keys/:id",UPDATE:"/v1/api-keys/:id",REVOKE:"/v1/api-keys/:id"},me="/v1/moderator-invites",fe="/v1/moderator-invites/claim",pe="/v1/moderated-tokens",Ee="/v1/moderator-invites",Ae="/v1/moderator-invites/:id",ve="/v1/moderator-invites/:id/role",Te="/v1/moderator-invites/:id",ye="/v1/moderator-invites/code/:code",Se={CREATE:"/v1/content-flags",LIST:"/v1/content-flags",DISMISS:"/v1/content-flags/:id/dismiss",ACTION:"/v1/content-flags/:id/action"},be="/v1/overseer-invites",Ne="/v1/overseer-invites",we="/v1/overseer-invites/code/:code",ke="/v1/overseer-invites/claim",_e="/v1/overseer-invites/:id",Ie="/v1/overseers",De="/v1/overseers",Ce="/v1/overseers/:address",Re="/v1/overseers/me",Oe="/v1/overseer-summary",Me="/v1/overseer-summary/bans",Le="/v1/overseer-summary/token-bans",Ue="/v1/overseer-summary/invites",Fe="/v1/overseer-summary/flags",Pe="/v1/overseer-summary/users",xe="/v1/users",Be="/v1/users/:address/summary",Ge="/v1/cache/flush/address/:address",$e="/v1/cache/flush/token/:tokenName",Ke="/v1/cache/flush/all",He="/v1/cache/flush/wallet-aliases/:address",We="/v1/cache/flush/wallet-aliases",Ve="/v1/token-bans",je="/v1/token-bans",qe="/v1/token-bans/:tokenName",ze="/v1/token-bans/:tokenName",Xe="/v1/reactions",Qe="/v1/reactions",Ye="/v1/trades",Je={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"},Ze="/v1/restricted-token-names",et="/v1/restricted-token-names",tt="/live/:tokenName/chat",nt="/live/:tokenName/chat",rt="/live/:tokenName/chat",st="/live/:tokenName/chat/slow-mode",it="/v1/events",ot="/v1/events/stats",at="/health",ct={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"},lt="/v1/stats",dt="/v1/trading/fee",ut="/v1/trading/sale-details",ht="/v1/trading/quote",gt="/v1/trading/premint-quote",mt={GET_LEADERBOARD:"/weekly-challenge",GET_TOKEN_HISTORY:"/weekly-challenge/history/:vaultAddress"},ft="/v1/notifications/register",pt="/v1/notifications/unregister",Et="/v1/notifications/preferences",At="/v1/notifications/preferences",vt="/v1/config/client-flags",Tt={NATIVE:"native",EXACT:"exact"},yt={RECENT:"recent",POPULAR:"popular"},St=["RECENT","POPULAR","RECORDINGS","SECONDS_STREAMED"],bt=["IDLE","ACTIVE","DISABLED"],Nt=100,wt={LOCAL:"local",EXTERNAL:"external"},kt={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 _t extends Error{constructor(e,t,n){super(e),this.field=t,this.code=n,this.name="ValidationError"}}class It extends _t{constructor(e){super(e,"token","TOKEN_RESTRICTED"),this.name="TokenRestrictedError"}}function Dt(e){return"object"==typeof e&&null!==e}function Ct(e){if(null==e||""===e)return{};if(!Dt(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 Rt(e){if(e instanceof Ot)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(!Dt(e))return;const t=Reflect.get(e,"response");return Dt(t)?t:void 0}(e);return void 0===t?{}:Ct(Reflect.get(t,"data"))}class Ot extends Error{constructor(e,t,n,r=Rt(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 Mt extends Error{constructor(e,t){super(e),this.field=t,this.name="ConfigurationError"}}class Lt extends Error{constructor(e,t,n){super(e),this.transactionId=t,this.code=n,this.name="TransactionError"}}function Ut(e){return e instanceof Error}function Ft(e){return Ut(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 Pt(e){return Ut(e)||"object"==typeof e&&null!==e&&"stack"in e&&"string"==typeof e.stack?e.stack:void 0}function xt(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 Bt(e){return"object"==typeof e&&null!==e&&"message"in e&&("response"in e||"request"in e||"config"in e)}function Gt(e,t){if(null==e||"object"!=typeof e)throw new Error(`${t}: No response - expected object, got ${typeof e}`);const n=e;if(!("Status"in n))throw new Error(`${t}: Response missing 'Status' property`);const 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 $t(e,t,n){try{t()}catch(t){if(!function(e){return e instanceof Error&&"ValidationError"===e.name}(t))throw t;{const n=t.message;e.push(n)}}}function Kt(e,t){return void 0!==t?t:e.charAt(0).toUpperCase()+e.slice(1)}function Ht(e,t){return new _t(`Token "${e}" not found. Please verify the token name is correct.`,"tokenName","TOKEN_NOT_FOUND")}function Wt(e,t){const n=Kt(e,t);return new _t(`${n} is required`,e,"REQUIRED")}function Vt(e,t,n){const r=Kt(e,n);return new _t(`${r} must be ${t}`,e,"INVALID_FORMAT")}function jt(e,t,n,r){return new Ot(e,t,n,r)}function qt(e,t){return new Mt(e,t)}function zt(e,t,n){return new Lt(e,t,n)}function Xt(e,t,n,r,s){const i=Kt(e,s);return new _t(`${i} must be between ${t} and ${n}${void 0!==r?`, received: ${r}`:""}`,e,"OUT_OF_RANGE")}function Qt(e,t,n,r){const s=Kt(e,r);return new _t(`${s} must be at least ${t}${void 0!==n?`, received: ${n}`:""}`,e,"TOO_SMALL")}function Yt(e,t,n,r){const s=Kt(e,r);return new _t(`${s} must be at most ${t}${void 0!==n?`, received: ${n}`:""}`,e,"TOO_LARGE")}function Jt(e,t,n,r){const s=Kt(e,r),i=void 0!==n?`, received: ${"object"==typeof n?"object":String(n)}`:"";return new _t(`${s} must be ${t}${i}`,e,"INVALID_TYPE")}function Zt(e,t,n){const r=Kt(e,n);return new _t(`${r} must be a valid number${void 0!==t?`: "${t}"`:""}`,e,"INVALID_NUMBER")}function en(e,t,n,r){const s=Kt(e,r);return new _t(`Invalid ${s}: ${t}. Must be one of: ${n.join(", ")}`,e,"INVALID_ENUM")}function tn(e,t){if(e.length<2)return Wt(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 _t(`At least one of ${n} must be provided`,e[0],"REQUIRED")}function nn(e,t,n,r){const s=Kt(e,r);return new _t(`${s} must be at most ${t} characters${void 0!==n?`, received: ${n}`:""}`,e,"TOO_LONG")}function rn(e,t){const n=Kt(e,t);return new _t(`${n} cannot be empty`,e,"EMPTY_STRING")}function sn(e){return null!=e&&"object"==typeof e&&"data"in e}function on(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 jt(e?.message??t,n,void 0,r?Ct(e):void 0)}}function an(e){if(sn(e))return e.data}function cn(e,t="No data found in response"){if(!sn(e))throw jt(t);const n=e.data;if(null==n)throw jt(t);return n}async function ln(e,t={}){return hn(e,t,e=>{if(void 0===e.data)throw new _t(`${t.errorContext??"Operation failed"}: No data returned from API`,"data","NO_DATA");return e.data})}async function dn(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 un(e,t={}){return hn(e,t,e=>e)}async function hn(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 _t(`${r}: No response from server`,"response","NO_RESPONSE");return on(t,r,!0),i&&s&&s.debug(`${r}: completed successfully`),n(t)}catch(e){throw s&&s.error(r,{error:e}),e}}const gn={BASE_PRICE:1650667151e-14,PRICE_SCALING_FACTOR:1166069e-12,TRADING_FEE_FACTOR:.001,GAS_FEE:"1",DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY:1e7};function mn(e){return e.trim().toLowerCase()}function fn(e){return e.trim().toUpperCase()}function pn(e){return e.trim().toUpperCase()}var En;!function(e){e.DEBUG="DEBUG",e.INFO="INFO",e.WARN="WARN",e.ERROR="ERROR"}(En||(En={}));class An{constructor(e){this.levelPriority={[En.DEBUG]:0,[En.INFO]:1,[En.WARN]:2,[En.ERROR]:3},this.debugEnabled=e.debug,this.context=e.context??"SDK",this.minLevel=e.minLevel??(e.debug?En.DEBUG:En.INFO)}debug(e,t){this.log(En.DEBUG,e,t)}info(e,t){this.log(En.INFO,e,t)}warn(e,t){this.log(En.WARN,e,t)}error(e,t){this.log(En.ERROR,e,t)}log(e,t,n){if(this.levelPriority[e]<this.levelPriority[this.minLevel])return;if(e===En.DEBUG&&!this.debugEnabled)return;const r=`[${(new Date).toISOString()}] [${this.context}] [${e}]`,s=this.getConsoleMethod(e);void 0!==n?Ut(n)?s(`${r} ${t}`,n.message,Pt(n)??""):s(`${r} ${t}`,n):s(`${r} ${t}`)}getConsoleMethod(e){switch(e){case En.DEBUG:return console.debug;case En.INFO:return console.info;case En.WARN:return console.warn;case En.ERROR:return console.error;default:return console.log}}child(e){return new An({debug:this.debugEnabled,context:`${this.context}:${e}`,minLevel:this.minLevel})}isDebugEnabled(){return this.debugEnabled&&this.levelPriority[En.DEBUG]>=this.levelPriority[this.minLevel]}}function vn(e){return"string"==typeof e&&e.trim().length>0}function Tn(e){return null==e||""===e}function yn(e){return null==e}const Sn=new An({debug:!1,context:"DateUtils"});function bn(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())?(Sn.warn(`Invalid date string received: "${e}". Using fallback.`),new Date):t}catch(t){return Sn.warn(`Date parsing error for "${e}":`,t),new Date}}function Nn(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 wn(n,r){if("string"==typeof n&&/^eth\|0[xX]/u.test(n))try{e(n,r)}catch(e){if(t(e)&&"INVALID_ETH_USER_REF_PREFIX"===e.code)return e.message}}function kn(t,n="address"){const r=wn(t,n);if(void 0!==r)throw new _t(r,n,"INVALID_FORMAT");try{return e(t,n)}catch{throw new _t(`${n} must be a GalaChain user address: eth|<40 hex> (\`eth|0x...\` is not a valid form), 0x<40 hex>, <40 hex> or client|<id>, and a mixed-case Ethereum address must carry its EIP-55 checksum (got "${String(t)}")`,n,"INVALID_FORMAT")}}function _n(e,t="address"){return kn(e,t).toLowerCase()}function In(e,t){return Gn(e)??_n(e,t)}function Dn(e){return Rn(e)?_n(e):e.trim().toLowerCase()}function Cn(e,t){const n=e=>Rn(e)?_n(e):e.toLowerCase();return n(e)===n(t)}function Rn(e){try{return kn(e),!0}catch{return!1}}class On{toBackendFormat(e){if(!vn(e))throw new _t("Address is required and must be a string","address","REQUIRED");return kn(e,"address")}toEthereumFormat(e){if(!vn(e))throw new _t("Backend address is required and must be a string","address","REQUIRED");if(!e.match(/^eth\|([0-9a-fA-F]{40})$/i)){const t=wn(e,"address");if(void 0!==t)throw new _t(t,"address","INVALID_FORMAT");throw new _t(`Invalid backend address format. Expected "eth|{40-hex-characters}" (\`eth|0x...\` is not a valid form). Got: "${e}"`,"address","INVALID_FORMAT")}return`0x${e.substring(4)}`}normalizeInput(e){if(void 0!==e&&""!==e)return kn(e,"address")}normalizeForBackend(e){if(void 0!==e&&""!==e)return _n(e,"address")}isValid(e){return Rn(e)}assertValid(e,t="address"){if(!this.isValid(e)){const n=wn(e,t);if(void 0!==n)throw new _t(n,t,"INVALID_FORMAT");throw new _t(`${t} must be a valid wallet address (eth|<40 hex>, 0x<40 hex>, <40 hex> or client|<id>; \`eth|0x...\` is not a valid form; a mixed-case address must carry its EIP-55 checksum)`,t,"INVALID_FORMAT")}}detectFormat(e){return vn(e)&&Rn(e)?e.startsWith("client|")?"client":e.startsWith("eth|")?"backend":"ethereum":null}normalize(e){if(void 0!==e&&""!==e)return e.toLowerCase()}extractHex(e){const t=Rn(e)?kn(e):void 0;if(void 0!==t&&t.startsWith("eth|"))return t.substring(4).toLowerCase();throw new _t(`Cannot extract hex from address: "${e}". Expected Ethereum or backend format.`,"address","INVALID_FORMAT")}}const Mn=new On;function Ln(e){return Mn.toBackendFormat(e)}function Un(e){return Mn.toEthereumFormat(e)}function Fn(e){return Mn.normalizeInput(e)}function Pn(e){return Mn.isValid(e)}const xn=/^(eth\|[a-f0-9]{40}|client\|[a-f0-9]{24})$/;function Bn(e){return void 0!==Gn(e)}function Gn(e){if(!vn(e))return;const t=e.trim(),n=/^[0-9a-fA-F]{24}$/u.test(t)?`client|${t}`:t;if(!Rn(n))return;const r=_n(n);return xn.test(r)?r:void 0}function $n(e,t){if(!Bn(e)){const n=wn(e,t);if(void 0!==n)throw new _t(n,t,"INVALID_FORMAT");throw new _t(`${t} must be a GalaChain user address (eth|<40 hex> (\`eth|0x...\` is not a valid form), 0x<40 hex>, <40 hex> or client|<24 hex>)`,t,"INVALID_FORMAT")}}function Kn(e,t="address"){Mn.assertValid(e,t)}function Hn(e){const t="string"==typeof e?e:e.address;return Mn.toBackendFormat(t)}var Wn=Object.freeze({__proto__:null,AddressFormatter:On,assertBackendUserAddress:$n,assertValidWalletAddress:Kn,backendUserAddress:Gn,backendUserParam:In,backendUserRef:_n,ethZeroXRefusal:wn,fromBackendAddressFormat:Un,isBackendUserAddress:Bn,isUserRef:Rn,isValidAddress:Pn,normalizeAddressInput:Fn,sameUserAddress:Cn,toBackendAddressFormat:Ln,toBackendAddressFromEthers:Hn,userAddressFilter:Dn,userRef:kn});function Vn(e,t=0){if(Tn(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 jn(e,t,n){if(yn(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 qn(e,t=0){if(yn(e))return t;if("number"==typeof e)return isNaN(e)?t:e;return Vn(String(e).replace("%","").trim(),t)}function zn(e,t=18){const n=Vn(e,0);if(0===n)return"0";return n.toFixed(t).replace(/\.?0+$/,"")}function Xn(e){return zn(e,8)}function Qn(e){return zn(e,18)}function Yn(e,t,n,r){if("number"!=typeof e)throw Jt(r,"a number",e,r);if(e<t||e>n)throw Xt(r,t,n,e)}function Jn(e,t,n){if("string"!=typeof e)throw Jt(n,"a string",e,n);if(e.length>t)throw Yt(n,t,e.length)}function Zn(e,t){if("number"!=typeof e)throw Jt(t,"a number",e,t);if(!Number.isInteger(e))throw Jt(t,"an integer",e,t);if(e<=0)throw Qt(t,1,e,t)}function er(e,t,n=!1){if("string"!=typeof e)throw Jt(t,"a string",e,t);if(!n&&0===e.trim().length)throw Wt(t,`${t} (non-empty string)`)}function tr(e,t){if("ASC"!==e&&"DESC"!==e)throw new _t(`${t} must be either 'ASC' or 'DESC'`,t,"INVALID_ENUM_VALUE")}function nr(e,t,n,r){const s="string"==typeof e?parseFloat(e):e;if(!isFinite(s))throw new _t(`${r} must be a valid finite number between ${t} and ${n}`,r,"INVALID_NUMBER");if(s<t||s>n)throw Xt(r,t,n,s,r)}function rr(e,t,n){const r="string"==typeof e?parseFloat(e):e,s="string"==typeof t?parseFloat(t):t;if(!isFinite(r))throw new _t(`${n} minFee must be a valid finite number`,n,"INVALID_FEE_MINIMUM");if(!isFinite(s))throw new _t(`${n} maxFee must be a valid finite number`,n,"INVALID_FEE_MAXIMUM");if(r<.1)throw new _t(`${n} minFee must be >= 0.1, received ${r}`,n,"INVALID_FEE_MINIMUM");if(s>.5)throw new _t(`${n} maxFee must be <= 0.5, received ${s}`,n,"INVALID_FEE_MAXIMUM");if(r>s)throw new _t(`${n} minFee (${r}) must be <= maxFee (${s})`,n,"INVALID_FEE_RANGE")}function sr(e,t,n,r){const s="string"==typeof e?parseFloat(e):e,i="string"==typeof t?parseFloat(t):t;if(!isFinite(s))throw new _t(`${n} must be a valid finite number`,n,"INVALID_MIN_VALUE");if(!isFinite(i))throw new _t(`${r} must be a valid finite number`,r,"INVALID_MAX_VALUE");if(s>i)throw new _t(`${n} (${s}) must be less than or equal to ${r} (${i})`,n,"INVALID_RANGE")}function ir(e,t,n){if(!t.includes(e))throw new _t(`${n} must be one of [${t.map(e=>String(e)).join(", ")}], received "${e}"`,n,"INVALID_ENUM_VALUE")}const or={ETH_ADDRESS:/^0x[0-9a-fA-F]{40}$/,BACKEND_ADDRESS:/^eth\|[0-9a-fA-F]{40}$/},ar=vn,cr=Tn,lr=yn;function dr(e,t,n=100,r,s){if(void 0!==s&&"string"!=typeof s)throw new _t("cursor must be a string","cursor",kt.INVALID_TYPE);const i=r??t,o=void 0!==r?"pageSize":"limit";if(void 0!==i&&(Zn(i,o),i>n))throw new _t(`${o} must be at most ${n}`,o,kt.TOO_LARGE)}function ur(e){const t=Object.values(e);return e=>"string"==typeof e&&t.includes(e)}function hr(e){return Object.values(e)}function gr(e,t,n){if(!ar(e))throw Wt(t);const r=e.trim();if(0===r.length)throw Wt(t);if(r.length<n.MIN_LENGTH)throw Xt(t,n.MIN_LENGTH,n.MAX_LENGTH,r.length,`${t} length`);if(r.length>n.MAX_LENGTH)throw Xt(t,n.MIN_LENGTH,n.MAX_LENGTH,r.length,`${t} length`);if(!n.PATTERN.test(r))throw new _t(`${t} must be ${n.DESCRIPTION}`,t,kt.INVALID_FORMAT)}function mr(e,t,n){if(null==e)return;if("string"!=typeof e)throw Jt(t,"a string",e);const r=e.trim();if(0!==r.length&&!n.PATTERN.test(r))throw new _t(`${t} must be ${n.DESCRIPTION}`,t,kt.INVALID_FORMAT)}function fr(e,t){if("string"!=typeof e)return!1;const n=e.trim();return 0!==n.length&&t.PATTERN.test(n)}function pr(e,t,n){if(null==e)throw Wt(t,t);if("string"!=typeof e)throw Jt(t,"a string",e);const r=e.trim();if(0===r.length)throw Wt(t,t);if(!n.PATTERN.test(r))throw new _t(`${t} must be ${n.DESCRIPTION}`,t,kt.INVALID_FORMAT)}function Er(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 Ar={requiredString:e=>t=>lr(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(!cr(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(!lr(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=>lr(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(!lr(n))return t.includes(n)?void 0:`${e} must be one of: ${t.join(", ")}`},requiredEnumValue:(e,t)=>n=>lr(n)?`${e} is required`:t.includes(n)?void 0:`${e} must be one of: ${t.join(", ")}`,isoDate:e=>t=>{if(!lr(t))return"string"!=typeof t?`${e} must be a string`:Nn(t)?void 0:`${e} must be a valid ISO 8601 date string`},walletAddress:(e,t=!1)=>n=>lr(n)?t?`${e} is required`:void 0:"string"!=typeof n?`${e} must be a string`:Rn(n)?void 0:wn(n,e)??`${e} must be a valid wallet address`};function vr(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(lr(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(!lr(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 Tr(e){return""===e||0===e.trim().length}function yr(e,t,n){if(!lr(e)){if("string"!=typeof e)throw Jt(t,"a string",e,t);if(e.length>n)throw new _t(`${t} must be at most ${n} characters`,t,kt.TOO_LARGE)}}function Sr(e,t){lr(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 Jt(t,"a date",e,t);if(isNaN(n.getTime()))throw new _t(`${t} must be a valid date`,t,kt.INVALID_FORMAT)}(e,t)}function br(e,t,n){try{Zn(e,t)}catch{throw function(e,t,n,r="OPERATION_FAILED"){return new _t(`${e} failed: ${t}`,n,r)}(n,"must be a positive integer",t)}}function Nr(e,t,n="status"){void 0!==e&&function(e,t,n){const r=Object.values(t);if(!r.includes(e))throw new _t(`${n} must be one of: ${r.join(", ")}`,n,kt.INVALID_FORMAT)}(e,t,n)}class wr{constructor(e,t=!1,n){this.http=e,this.logger=new An({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 Mt("JWT authentication required. Call sdk.login() first.")}return this.jwtAuth.getJwtHeaders()}isCalledFromUserCode(){const e=Pt(new Error)??"";return!(!e.includes("expect")&&!e.includes("jest"))||!(!e.includes("tests/")&&!e.includes(".test.ts"))}validatePositiveInteger(e,t,n){br(e,t,n)}}class kr{constructor(e=!1,t){this.logger=t||new An({debug:e,context:this.constructor.name})}}class _r extends kr{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 _r{constructor(e=!1){super(e)}normalizeKey(e){return mn(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??gn.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:${mn(e)}`;return this.cache.get(t)??null}setByTokenId(e,t){const n=`token:${mn(e)}`;this.updateCacheEntry(n,t)}hasByTokenId(e){const t=`token:${mn(e)}`;return this.cache.has(t)}}Ir.MAX_CACHE_SIZE=1e4;const Dr={MIN_LENGTH:1,MAX_LENGTH:25,PATTERN:/^[a-zA-Z0-9]{1,25}$/,DESCRIPTION:"1-25 letters and digits"},Cr={MIN_LENGTH:1,MAX_LENGTH:50,PATTERN:/^[a-zA-Z0-9]{1,50}$/,DESCRIPTION:"1-50 letters and digits"},Rr={MIN_LENGTH:1,MAX_LENGTH:255,PATTERN:/^[a-zA-Z0-9]{1,255}$/,DESCRIPTION:"1-255 letters and digits"},Or={MIN_LENGTH:1,MAX_LENGTH:50,PATTERN:/^[\s\S]{1,50}$/,DESCRIPTION:"1-50 characters"},Mr={MIN_LENGTH:1,MAX_LENGTH:100,PATTERN:/^(?![\s\S]*<[^>]*>)[\s\S]{1,100}$/,DESCRIPTION:"1-100 characters without HTML"},Lr=100,Ur=100,Fr=50,Pr=100,xr={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}},Br={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})$/}},Gr=60,$r=31536e3,Kr={MAX_LENGTH:64,PATTERN:/^(galaswap-operation-|galaconnect-operation-)/},Hr={PATTERN:/^[a-fA-F0-9]{64}$/,MAX_LENGTH:64},Wr=1,Vr=100,jr={FULL_NAME:{MIN_LENGTH:2,MAX_LENGTH:20,ALPHABETS_ONLY_PATTERN:/^[a-zA-Z]+(?: [a-zA-Z]+)?$/}},qr=S.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"),zr=qr.max(25,"Token name must be at most 25 characters"),Xr=S.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"),Qr=S.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"),Yr=S.string({message:"Token description is required"}).min(1,"Token description is required").max(500,"Token description must be at most 500 characters"),Jr=S.string().min(1,"Token name must be at least 1 character").max(50,"Token name must be at most 50 characters"),Zr=S.string().min(1,"Search query must be at least 1 character").max(100,"Search query must be at most 100 characters"),es=S.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"),ts=S.string().regex(or.BACKEND_ADDRESS,"Address must be in format: eth|[40-hex-chars]"),ns=S.string().regex(or.ETH_ADDRESS,"Invalid Ethereum address format"),rs=S.string().refine(e=>Rn(e),{error:e=>wn(e.input,"address")??"Address must be eth|[40-hex], 0x[40-hex], [40-hex] or client|[identifier] (a mixed-case address must carry its EIP-55 checksum)"}).transform(e=>kn(e)),ss=S.string().refine(e=>/^eth\|[0-9a-fA-F]{40}$/.test(e)||/^service\|Token\$Unit\$[A-Z0-9]+\$eth:[0-9a-fA-F]{40}\$launchpad$/.test(e),"Invalid vault address format"),is=S.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>Vn(e,0)>0,"Amount must be greater than zero"),os=S.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>Vn(e,0)>=0,"Amount must be zero or greater"),as=S.string().url("Must be a valid URL").regex(/^https?:\/\//,"URL must start with http:// or https://"),cs=S.string().optional().refine(e=>void 0===e||""===e||/^https?:\/\/.+\..+/.test(e),"Must be a valid URL if provided"),ls=S.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 ds(e=100){return S.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 us=ds(100),hs=ds(20),gs=ds(20),ms=S.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"),fs=S.string().max(255,"Filename must be at most 255 characters"),ps=S.enum(["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"]),Es=S.string().datetime("Must be a valid ISO 8601 date string"),As=S.number().int("Timestamp must be an integer").min(0,"Timestamp must be non-negative"),vs=S.string().regex(/^0x[a-fA-F0-9]{64}$/,"Private key must be format: 0x + 64 hex characters"),Ts=S.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"),ys=S.string().regex(/^galaconnect-operation-[a-z0-9-]+$/,"Unique key must be format: galaconnect-operation-{unique-id}"),Ss=[".png",".jpg",".jpeg",".gif",".webp",".svg"],bs=S.object({file:S.union([S.instanceof(File),S.instanceof(Buffer)]),name:fs,size:ms,type:ps}),Ns=S.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"),ws=S.instanceof(Buffer).refine(e=>e.length>=1&&e.length<=10485760,"Buffer size must be between 1 byte and 10MB"),ks=S.union([Ns,ws]),_s=S.enum([".png",".jpg",".jpeg",".gif",".webp",".svg"]),Is=fs.refine(e=>{const t=e.slice(e.lastIndexOf(".")).toLowerCase();return Ss.includes(t)},`Filename must end with one of: ${Ss.join(", ")}`),Ds=S.object({websiteUrl:cs,telegramUrl:cs,twitterUrl:cs,instagramUrl:cs,facebookUrl:cs,redditUrl:cs,tiktokUrl:cs}).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"),Cs=S.string().min(1,"Token category must not be empty").default("Unit"),Rs=S.string().min(1,"Token collection must not be empty").default("Token"),Os=S.object({minFeePortion:S.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal string").refine(e=>Vn(e,0)>=.1,"Minimum fee must be >= 0.1").refine(e=>Vn(e,0)<=.5,"Minimum fee must be <= 0.5").default("0.1"),maxFeePortion:S.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal string").refine(e=>Vn(e,0)>=.1,"Maximum fee must be >= 0.1").refine(e=>Vn(e,0)<=.5,"Maximum fee must be <= 0.5").default("0.5")}).refine(e=>Vn(e.maxFeePortion,0)>=Vn(e.minFeePortion,0),{message:"Maximum fee must be >= minimum fee",path:["maxFeePortion"]}),Ms=S.object({tokenName:qr,tokenSymbol:Qr,tokenDescription:Yr,tokenImage:S.union([S.instanceof(File),S.instanceof(Buffer),S.string().url("Token image must be a valid URL")]).optional(),preBuyQuantity:os.default("0"),websiteUrl:cs,telegramUrl:cs,twitterUrl:cs,instagramUrl:cs,facebookUrl:cs,redditUrl:cs,tiktokUrl:cs,tokenCategory:Cs,tokenCollection:Rs,reverseBondingCurveConfiguration:Os.optional(),saleStartTime:S.number().int().positive().optional(),privateKey:vs.optional()}),Ls=S.object({file:S.union([S.instanceof(File),S.instanceof(Buffer)]),tokenName:qr}),Us=S.enum(St),Fs=S.object({tokenName:Xr.optional(),symbol:Qr.optional()}).refine(e=>void 0!==e.tokenName||void 0!==e.symbol,"At least one of tokenName or symbol is required"),Ps=S.enum(["NATIVE","MEME"]),xs=S.enum(["IN","OUT"]),Bs=S.object({from:S.number().int("From timestamp must be an integer").min(173e6,"From timestamp must be at least 173000000"),to:S.number().int("To timestamp must be an integer").min(173e6,"To timestamp must be at least 173000000"),resolution:S.number().int("Resolution must be an integer").min(1,"Resolution must be at least 1"),tokenName:zr}),Gs=S.object({tokenName:zr,slippageToleranceFactor:S.number().min(0).max(1).optional(),maxAcceptableReverseBondingCurveFeeSlippageFactor:S.number().min(0).max(1).optional(),privateKey:vs.optional()}),$s=S.object({offset:S.number().int().min(0).default(0),pageSize:S.number().int().min(1).max(100).default(10)}),Ks=S.object({offset:S.number().int().min(0).default(0),pageSize:S.number().int().min(1).max(20).default(10)}),Hs=S.object({offset:S.number().int().min(0).default(0),pageSize:S.number().int().min(1).max(20).default(10)}),Ws=$s.extend({type:S.enum(["RECENT","POPULAR"]).optional(),tokenName:S.string().min(1).max(50).optional(),search:S.string().min(1).max(100).optional()}),Vs=Ks.extend({tokenName:S.string().min(1).max(50).optional(),search:S.string().min(1).max(100).optional()}),js=Hs.extend({tradeType:S.enum(["BUY","SELL"]).optional(),tokenName:S.string().min(1).max(50).optional(),userAddress:S.string().refine(Rn,{error:e=>wn(e.input,"userAddress")??"userAddress must be eth|<40 hex>, 0x<40 hex>, <40 hex> or client|<id> (a mixed-case address must carry its EIP-55 checksum)"}).optional(),startDate:S.string().datetime().optional(),endDate:S.string().datetime().optional(),sortOrder:S.enum(["ASC","DESC"]).default("DESC")}),qs={page:S.number().int().min(1),limit:S.number().int().min(1),total:S.number().int().min(0),totalPages:S.number().int().min(0),hasNext:S.boolean(),hasPrevious:S.boolean()},zs=S.object(qs);function Xs(e){return S.object({data:S.array(e),...qs})}const Qs=S.enum(["buy","sell"]),Ys=S.enum(["BUY","SELL"]),Js=S.object({tradeType:Qs,tokenAmount:is,vaultAddress:ss,userAddress:rs,slippageTolerance:is.optional(),deadline:S.number().int().positive().optional()}),Zs=S.object({tokenSymbol:Qr,nativeTokenQuantity:is,expectedToken:is,maxAcceptableReverseBondingCurveFee:os.default("0").optional()}),ei=S.object({tokenSymbol:Qr,tokenQuantity:is,expectedNativeToken:is,maxAcceptableReverseBondingCurveFee:os.default("0").optional()}),ti=Hs.extend({tokenName:Jr.optional()}),ni=S.object({page:S.number().int().min(1).max(1e3).default(1).optional(),limit:S.number().int().min(1).max(20).default(10).optional()}),ri=S.enum(["NATIVE","MEME"]),si=S.enum(["IN","OUT"]),ii=S.object({type:ri,method:si,vaultAddress:ss,amount:is}),oi=S.object({nativeTokenQuantity:is}),ai=S.object({vaultAddress:ss}),ci=S.object({minFeePortion:is,maxFeePortion:is}),li=S.enum(["both","held","created"]),di=Ks.extend({type:li.optional(),address:rs.optional(),search:Zr.optional(),tokenName:Jr.optional()}),ui=S.object({address:rs.optional(),refresh:S.boolean().optional()}),hi=S.object({profileImage:S.string().nullable().optional(),fullName:es.optional(),address:rs.optional(),privateKey:vs.optional()}),gi=S.object({file:S.union([S.instanceof(File),S.instanceof(Buffer)]),address:rs.optional(),privateKey:vs.optional()}),mi=S.object({address:rs,tokenId:S.union([S.string(),S.object({collection:S.string(),category:S.string(),type:S.string(),additionalKey:S.string()}),S.object({collection:S.string(),category:S.string(),type:S.string(),additionalKey:S.string(),instance:S.string()})]).optional(),tokenName:Jr.optional(),withExpired:S.boolean().optional()}).refine(e=>void 0!==e.tokenId||void 0!==e.tokenName,"At least one token identifier (tokenId or tokenName) is required");function fi(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 pi=fi(qr),Ei=fi(Qr),Ai=fi(Yr),vi=fi(rs),Ti=fi(ss),yi=fi(is),Si=fi(es),bi=fi(Zr),Ni=fi(Jr),wi=fi(Ms),ki=fi(Ds),_i=fi(Ls),Ii=fi(Fs),Di=fi(di),Ci=fi(ui),Ri=fi(hi),Oi=fi(gi),Mi=fi(mi),Li=fi(Js),Ui=fi(Zs),Fi=fi(ei),Pi=fi(ti),xi=fi(ni),Bi=fi(ii),Gi=fi(oi),$i=fi(ai);function Ki(e){return wi(e).success}function Hi(e){const t=wi(e);return t.success?[]:t.errors??["Unknown validation error"]}function Wi(e){const t=Hi(e);if(t.length>0)throw new Error(`LaunchTokenData validation failed:\n${t.map(e=>`- ${e}`).join("\n")}`)}function Vi(e,t){return"string"==typeof e[t]}function ji(e,t){return void 0===e[t]||"string"==typeof e[t]}function qi(e,t){return void 0===e[t]||"number"==typeof e[t]}function zi(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 Xi(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(!zi(n[t],r))return!1}return!0}}ur({BUY:"buy",SELL:"sell"});const Qi=Xi({nativeTokenQuantity:"string"});function Yi(e,t="0"){return function(e,t="0"){if(Tn(e))return new D(t);if(D.isBigNumber(e))return e.isNaN()?new D(t):e;try{const n=new D(e);return n.isNaN()||!n.isFinite()?new D(t):n}catch{return new D(t)}}(e,t)}function Ji(e,t){return void 0!==t?Yi(e).toFixed(t):Yi(e).toFixed()}function Zi(e){const t=Yi(e),n=Math.log(1.0001),r=t.toNumber();return Math.log(r)/n}function eo(e){return Yi(e).isZero()}function to(e,t){return Yi(e).isLessThan(Yi(t))}function no(...e){e.forEach(e=>{if(e.isNaN())throw Zt("value","NaN");if(!e.isFinite())throw Yt("value","finite");if(e.isLessThanOrEqualTo(0))throw Qt("value","0",e.toString())})}function ro(...e){e.forEach(e=>{if(e.isNaN())throw Zt("value","NaN");if(!e.isFinite())throw Yt("value","finite");if(e.isLessThan(0))throw Qt("value","0",e.toString())})}function so(e,t,n){if(e.isNaN())throw Zt(t,"NaN");if(!e.isFinite())throw Yt(t,"finite");if(e.isLessThanOrEqualTo(0))throw Qt(t,"0",e.toString())}function io(e,t,n="0"){const r=Yi(t);return eo(r)?Yi(n):Yi(e).dividedBy(r)}const oo={calculateBuyWithExact(e,t){const n=Vn(e),r=Vn(t),{BASE_PRICE:s,PRICE_SCALING_FACTOR:i,TRADING_FEE_FACTOR:o,GAS_FEE:a}=gn,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=Ji(Yi(c).multipliedBy(o));return{amount:c.toString(),reverseBondingCurveFee:"0",transactionFee:l,gasFee:a}},calculateBuyWithNative(e,t){const n=Vn(e),r=Vn(t),{BASE_PRICE:s,PRICE_SCALING_FACTOR:i,TRADING_FEE_FACTOR:o,GAS_FEE:a}=gn,c=Math.log(n*i/s+Math.exp(r*i))/i-r,l=Ji(Yi(c).multipliedBy(o));return{amount:c.toString(),reverseBondingCurveFee:"0",transactionFee:l,gasFee:a}},calculateSellWithExact(e,t,n,r,s){const i=Vn(e),o=Vn(t),a=Vn(n),{BASE_PRICE:c,PRICE_SCALING_FACTOR:l,TRADING_FEE_FACTOR:d,GAS_FEE:u}=gn,h=c*(Math.exp(o*l)-Math.exp((o-i)*l))/l,g=Yi(h),m=r+o/a*(s-r),f=Ji(g.multipliedBy(m),8),p=Ji(g.multipliedBy(d));return{amount:h.toString(),reverseBondingCurveFee:f,transactionFee:p,gasFee:u}},calculateSellWithNative(e,t,n,r,s){const i=Vn(e),o=Vn(t),a=Vn(n),{BASE_PRICE:c,PRICE_SCALING_FACTOR:l,TRADING_FEE_FACTOR:d,GAS_FEE:u}=gn;if(i>=c*(Math.exp(o*l)-1)/l){const e=Yi(i),t=r+o/a*(s-r),n=Ji(e.multipliedBy(t),8),c=Ji(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=Yi(i),m=r+o/a*(s-r),f=Ji(g.multipliedBy(m),8),p=Ji(g.multipliedBy(d));return{amount:h.toString(),reverseBondingCurveFee:f,transactionFee:p,gasFee:u}}};function ao(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function co(e,t){if(!function(e){if(!ao(e)||"string"!=typeof e.calculatedQuantity)return!1;const t=e.extraFees;return ao(t)&&"string"==typeof t.reverseBondingCurve&&"string"==typeof t.transactionFees}(e))throw jt(`Malformed trade quote from the launchpad backend (${t})`);return{amount:e.calculatedQuantity,reverseBondingCurveFee:e.extraFees.reverseBondingCurve,transactionFee:e.extraFees.transactionFees,gasFee:gn.GAS_FEE}}class lo{validate(e,t={}){const{allowZero:n=!0,minimum:r,maximum:s,maxDecimals:i=lo.MAX_DECIMAL_PLACES,fieldName:o="amount"}=t;if(!ar(e))throw new _t(`${o} cannot be empty or whitespace-only. Provide a valid numeric string.`,o,"INVALID_NUMERIC_STRING");if(/[eE]/.test(e))throw new _t(`${o} cannot use scientific notation. Use standard decimal format (e.g., "1000" instead of "1e3").`,o,"INVALID_NUMERIC_STRING");const a=Vn(e,NaN);if(isNaN(a))throw new _t(`${o} must be a valid numeric string. Received: "${e}"`,o,"INVALID_NUMERIC_STRING");if(!isFinite(a))throw new _t(`${o} must be a finite number. Cannot be Infinity or -Infinity.`,o,"INVALID_NUMERIC_STRING");if(a<0)throw new _t(`${o} must be non-negative. Received: "${e}"`,o,"INVALID_NUMERIC_STRING");if(!n&&0===a)throw new _t(`${o} must be greater than zero. Received: "${e}"`,o,"INVALID_NUMERIC_STRING");const c=Yi(e),l=c.decimalPlaces()??0;if(l>i)throw new _t(`${o} cannot exceed ${i} decimal places. Received: ${l} decimal places`,o,"PRECISION_EXCEEDED");if(void 0!==r&&to(c,r))throw new _t(`${o} must be at least ${r}. Received: "${e}"`,o,"BELOW_MINIMUM");if(void 0!==s&&(d=s,Yi(c).isGreaterThan(Yi(d))))throw new _t(`${o} cannot exceed ${s}. Received: "${e}"`,o,"EXCEEDS_MAXIMUM");var d}parseAmount(e,t="0"){return Yi(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 Ji(e,t)}clampAmount(e,t,n){const r=Yi(e),s=Yi(t),i=Yi(n);return function(e,t,n){const r=Yi(e),s=Yi(t),i=Yi(n);return r.isGreaterThanOrEqualTo(s)&&r.isLessThanOrEqualTo(i)}(r,s,i)?Ji(r):to(r,s)?Ji(s):Ji(i)}}function uo(e,t){throw new _t(e.join("; "),t,"VALIDATION_ERROR")}function ho(e){const t=pi(e);!t.success&&t.errors&&uo(t.errors,"tokenName")}function go(e){const t=Bs.safeParse(e);var n;t.success||uo((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 mo(e,t,n=!0){fo.validate(e,{fieldName:t,allowZero:n})}lo.MAX_DECIMAL_PLACES=18,lo.MIN_POSITIVE="0.00000000000000001";const fo=new lo;class po{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 Vt("options","an options object");const{tokenName:t,amount:n,type:r,currentSupply:s}=e;return"external"===this.validateAmountCalculationInputs(t,n,r,e.mode,[Tt.NATIVE,Tt.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 co(await ln(()=>this.http.get(ht,{...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,[Tt.EXACT,Tt.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(!ar(n))throw Wt("amount","Amount");if(r!==Tt.NATIVE&&r!==Tt.EXACT)throw Jt("type",'"native" or "exact"',r);void 0!==s&&mo(s,"currentSupply");const i=null==s||""===s;if(i&&(null==t||""===t))throw Wt("tokenName","Token name (required when currentSupply is not provided)");null!=t&&""!==t&&ho(t);let o=s;if(i){o=(await this.fetchPoolDetailsForCalculation(t)).currentSupply}return r===Tt.EXACT?oo.calculateBuyWithExact(n,o):oo.calculateBuyWithNative(n,o)}async calculateSellAmountLocal(e){const{tokenName:t,amount:n,type:r,currentSupply:s,maxSupply:i,reverseBondingCurveMaxFeeFactor:o,reverseBondingCurveMinFeeFactor:a}=e;if(!ar(n))throw Wt("amount","Amount");if(r!==Tt.EXACT&&r!==Tt.NATIVE)throw Jt("type",'"exact" or "native"',r);void 0!==s&&mo(s,"currentSupply");const c=null==s||""===s||null==i||""===i||void 0===o||void 0===a;if(c&&(null==t||""===t))throw Wt("tokenName","Token name (required when currentSupply, maxSupply, or fee factors are not provided)");null!=t&&""!==t&&ho(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===Tt.EXACT?oo.calculateSellWithExact(n,l,d,h,u):oo.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 Vi(t,"tokenName")&&function(e){return void 0===e.calculateAmountMode||"local"===e.calculateAmountMode||"external"===e.calculateAmountMode}(t)&&ji(t,"currentSupply")}(e))throw Jt("options","CalculateBuyAmountForGraduationOptions or string (token name)",typeof e);const{tokenName:n,calculateAmountMode:r,currentSupply:s}=t;ho(n);const i=await this.fetchSaleDetails(n),o=s??Ji(Yi(i.maxSupply).minus(i.sellingTokenQuantity)),a=i.sellingTokenQuantity;if("0"===a)throw Wt("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 qt("Bundle backend client not configured. LaunchToken requires bundleHttp client.","bundleHttp");Wi(e);const t=void 0!==e.preBuyQuantity&&""!==e.preBuyQuantity?e.preBuyQuantity:"0",n=Vn(t);if(0===n&&"0"!==t)throw Zt("preBuyQuantity",t,"Pre-buy quantity");if(n<0)throw Zt("preBuyQuantity",t,"Pre-buy quantity");if(e.reverseBondingCurveConfiguration){const{minFeePortion:t,maxFeePortion:n}=e.reverseBondingCurveConfiguration;rr(t,n,"reverseBondingCurve")}throw new Error("Legacy launchToken signing is unavailable; configure the v6 launchpad write transport.")}async calculateInitialBuyAmount(e){if(!Qi(e))throw Vt("data","valid pre-mint calculation data");const t="Failed to calculate initial buy amount";return co(await ln(()=>this.http.get(gt,{amount:e.nativeTokenQuantity}),{errorContext:t}),t)}async fetchPoolDetailsForCalculation(e){const t=await this.fetchSaleDetails(e),n=Ji(Yi(t.maxSupply).minus(t.sellingTokenQuantity)),r=t.sellingTokenQuantity,s=t.maxSupply;let i=.5,o=.1;const a=t.reverseBondingCurveConfiguration;null!=a?.maxFeePortion&&(i=qn(a.maxFeePortion,.5)),null!=a?.minFeePortion&&(o=qn(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){ho(e);const t=await this.fetchSaleDetails(e),n=Ji(Yi(t.maxSupply).minus(t.sellingTokenQuantity)),r=t.maxSupply;return this.metadataCache.set(e,{maxSupply:r}),n}async fetchPoolDetails(e){ho(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:!eo(s)||!eo(i),isGraduated:"Finished"===t.saleStatus}}async fetchSaleDetails(e){return gr(e,"tokenName",Dr),ln(()=>this.http.get(ut,{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 Jt("mode",'"local" or "external"',o);if(!ar(e))throw Wt("tokenName","Token name");if(!ar(t))throw Wt("amount","Amount");if("string"!=typeof n||!s.includes(n))throw Jt("type",i,n);return o}validateExternalAmountInputs(e,t){if("string"!=typeof e||""===e)throw new _t("Token name must be a non-empty string","tokenName","INVALID_TOKEN_NAME");if("string"!=typeof t||""===t)throw new _t("Amount must be a non-empty string","amount","INVALID_AMOUNT")}getAddress(){return this.http.getAddress()}formatAddressForBackend(e){return Ln(e)}validateTokenName(e){return ho(e)}validatePagination(e){void 0!==e.pageSize&&dr(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 Eo={REFRESH_THRESHOLD_MS:3e5,DEFAULT_EXPIRY_S:86400,LOGIN_MESSAGE_PREFIX:"Sign in to Launchpad t:",AUTH_HEADER:"Authorization",BEARER_PREFIX:"Bearer "};class Ao{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 vo;!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"}(vo||(vo={}));class To extends Error{constructor(e,t,n,r){super(t),this.type=e,this.originalError=n,this.statusCode=r,this.name="AuthError"}}class yo{constructor(e,t=Eo.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 Ao,this.refreshThresholdMs=t}setToken(e,t){if(!ar(e))throw new To(vo.SIGNATURE_FAILED,"JWT token must be a non-empty string");if("number"!=typeof t)throw new To(vo.SIGNATURE_FAILED,"Token expiration must be a positive finite number (seconds)");if(!Number.isFinite(t))throw new To(vo.SIGNATURE_FAILED,"Token expiration must be a positive finite number (seconds)");if(t<=0)throw new To(vo.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 To(vo.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:`${Eo.BEARER_PREFIX}${e}`}getJwtHeaders(){const e=this.getAuthorizationHeader();if(null===e||""===e)throw new To(vo.WALLET_NOT_CONNECTED,"No JWT token available. Call login() first.");return{[Eo.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 So extends yo{getJwtHeaders(){return{}}}async function bo(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=(Bt(e)?e.response?.status:void 0)??(e instanceof Ot?e.statusCode:void 0);return jt(`${t}: ${Ft(e)}`,r,Ut(e)?e:void 0)}(e,t,n))}}function No(e,t){return t instanceof To?t:new To(vo.SIGNATURE_FAILED,`${e}: ${Ft(t)}`,Ut(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 wo{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 An({debug:r,context:"SessionAuthService"})}async loginWithSignature(e){const t=kn(e.address,"address");if(!ar(e.message)||!ar(e.signature))throw new To(vo.SIGNATURE_FAILED,"A login needs the signed message and its signature.");const n={address:t,message:e.message,signature:e.signature,...void 0!==e.publicKey&&{publicKey:e.publicKey},...void 0!==this.session&&{cookieSession:!0}};return this.postLogin(n)}async loginWithDevBypass(e){return this.postLogin({address:kn(e,"address"),...void 0!==this.session&&{cookieSession:!0}})}async postLogin(e){try{const t=await this.http.request({method:"POST",url:ee,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 No("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 To(vo.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 bo(async()=>{const e=Date.now(),t=`${Eo.LOGIN_MESSAGE_PREFIX}${e}`;this.logger.debug("Generating login signature",{message:t,timestamp:e});const n=await this.signatureAuth.signMessage(t),r=kn(this.signatureAuth.getAddress(),"address"),s={address:r,message:t,signature:n.signature};this.logger.debug("Sending login request",{address:r,message:t});const i=await this.http.post(ee,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 To)throw e;throw new To(vo.SIGNATURE_FAILED,`Login failed: ${Ft(e)}`,Ut(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 To(vo.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:ne,data:{},withSession:!1});return this.extractLoginData(e)}catch(e){throw No("Token refresh failed",e)}}async performRefresh(){return bo(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(ne,{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(ne,{},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 To)throw e;throw new To(vo.SIGNATURE_FAILED,`Token refresh failed: ${Ft(e)}`,Ut(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:te,data:{allDevices:t},withSession:!1,...null!==n&&""!==n&&{headers:{Authorization:`${Eo.BEARER_PREFIX}${n}`}}})}catch(e){throw No("Logout failed",e)}return}if(t&&this.jwtAuth.hasToken()&&!this.jwtAuth.isExpired())try{await this.http.post(te,{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): ${Ft(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 To(vo.WALLET_NOT_CONNECTED,"Not authenticated. Call login() first.");return bo(async()=>{const e=await this.http.get(re,void 0,this.jwtAuth.getJwtHeaders());return this.extractSessionData(e)},"SessionAuthService.getSession",this.logger,e=>{if(e instanceof To)throw e;throw new To(vo.SIGNATURE_FAILED,`Failed to get session: ${Ft(e)}`,Ut(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 To(vo.WALLET_NOT_CONNECTED,"The app session has no access token.");return e}if(!this.jwtAuth.hasToken())throw new To(vo.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: ${Ft(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 To(vo.SIGNATURE_FAILED,""!==Ft(e)?Ft(e):"Authentication failed");const t=cn(e,"No data in authentication response"),{accessToken:n,expiresIn:r,address:s,refreshToken:i,refreshExpiresIn:o}=t;if(!ar(n))throw new To(vo.SIGNATURE_FAILED,"Invalid access token in response");if("number"!=typeof r||r<=0)throw new To(vo.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 To(vo.SIGNATURE_FAILED,""!==Ft(e)?Ft(e):"Failed to get session");return cn(e,"No data in session response")}}class ko{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{er(e.messagePrefix,"messagePrefix",!1)}catch{throw new To(vo.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=b.fromWallet(this.wallet),this.cachedAddress=this.wallet.address,this.cachedGalaAddress=Ln(this.wallet.address)}catch(e){if(e instanceof To)throw e;if(e instanceof _t&&("INVALID_ADDRESS"===e.code||"INVALID_FORMAT"===e.code||"address"===e.field))throw new To(vo.INVALID_ADDRESS,e.message);if(null!==e&&"object"==typeof e&&"message"in e)throw new To(vo.WALLET_NOT_CONNECTED,e.message);throw e}}setWallet(e){if(void 0!==e){if("object"!=typeof e||!("address"in e))throw new To(vo.WALLET_NOT_CONNECTED,"Invalid wallet: must be an ethers Wallet instance or undefined");if("string"!=typeof e.address||""===e.address)throw new To(vo.INVALID_ADDRESS,"Wallet address is not available");this.walletProvider=b.fromWallet(e),this.cachedAddress=e.address,this.cachedGalaAddress=Ln(e.address)}else this.walletProvider=void 0,this.cachedAddress=void 0,this.cachedGalaAddress=void 0;this.wallet=e}setWalletProvider(e){this.walletProvider=e,this.wallet=void 0;const t=void 0!==e&&N(e)?E(e.exportPrivateKey()):void 0;this.cachedAddress=t,this.cachedGalaAddress=void 0===t?void 0:Ln(t)}getWalletProvider(){return this.walletProvider}async cacheAddress(){this.walletProvider&&(this.cachedAddress=await this.walletProvider.getAddress(),this.cachedGalaAddress=kn(await this.walletProvider.getGalaAddress(),"address"))}async generateSignature(){await this.validateWalletAsync();try{const e=Date.now(),t=`${this.messagePrefix} ${e}`,n=await this.walletProvider.signMessage(t);return{message:t,signature:n,address:await this.walletProvider.getGalaAddress(),timestamp:e}}catch(e){if(e instanceof To)throw e;throw new To(vo.SIGNATURE_FAILED,"Failed to generate signature for authentication",Ut(e)?e:new Error(Ft(e)))}}getAddress(){if(this.validateWallet(),this.cachedGalaAddress)return this.cachedGalaAddress;if(this.wallet)return this.formatAddress(this.wallet.address);throw new To(vo.WALLET_NOT_CONNECTED,"Address not available. For external wallets, call cacheAddress() after connecting.")}async getAddressAsync(){return await this.validateWalletAsync(),kn(await this.walletProvider.getGalaAddress(),"address")}getEthereumAddress(){if(this.validateWallet(),this.cachedAddress)return this.cachedAddress;if(this.wallet)return this.wallet.address;throw new To(vo.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 To(vo.WALLET_NOT_CONNECTED,"Wallet private key not available for @gala-chain signing");return this.wallet.privateKey}if(void 0!==this.walletProvider&&N(this.walletProvider))return this.walletProvider.exportPrivateKey();throw new To(vo.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 To(vo.WALLET_NOT_CONNECTED,"Private key not available with this wallet provider");try{return await this.walletProvider.getPrivateKey()}catch(e){throw new To(vo.WALLET_NOT_CONNECTED,"Private key not available. External wallet providers cannot access private keys. Use PrivateKeyProvider for @gala-chain signing operations.",Ut(e)?e:void 0)}}formatAddress(e){try{return Ln(e)}catch{throw new To(vo.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 To)throw e;throw new To(vo.SIGNATURE_FAILED,Ft(e),Ut(e)?e:new Error(Ft(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 To)throw e;throw new To(vo.SIGNATURE_FAILED,"Failed to generate authentication headers",Ut(e)?e:new Error(Ft(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 To)throw e;throw new To(vo.SIGNATURE_FAILED,"Failed to sign typed data",Ut(e)?e:new Error(Ft(e)))}}async generateCustomSignature(e){if(!ar(e))throw new To(vo.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 To)throw e;throw new To(vo.SIGNATURE_FAILED,"Failed to generate custom message signature",Ut(e)?e:new Error(Ft(e)))}}validateWallet(){if(this.ensureWalletProvider(),!this.walletProvider)throw new To(vo.WALLET_NOT_CONNECTED,"Wallet is required for authentication")}async validateWalletAsync(){if(this.ensureWalletProvider(),!this.walletProvider)throw new To(vo.WALLET_NOT_CONNECTED,"Wallet is required for authentication");if(!this.walletProvider.isConnected())throw new To(vo.WALLET_NOT_CONNECTED,"Wallet is not connected. Call connect() on the wallet provider first.")}}const _o={prod:{...n.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:{...n.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 Io(e){return _o[e]}var Do,Co;!function(e){e.PROCESSED="PROCESSED",e.COMPLETED="COMPLETED",e.SUCCESS="SUCCESS",e.FAILED="FAILED",e.ERROR="ERROR",e.PROCESSING="PROCESSING",e.PENDING="PENDING"}(Do||(Do={})),function(e){e.PENDING="pending",e.PROCESSING="processing",e.COMPLETED="completed",e.FAILED="failed",e.TIMEOUT="timeout"}(Co||(Co={}));const Ro={[Do.PROCESSED]:Co.COMPLETED,[Do.COMPLETED]:Co.COMPLETED,[Do.SUCCESS]:Co.COMPLETED,[Do.FAILED]:Co.FAILED,[Do.ERROR]:Co.FAILED,[Do.PROCESSING]:Co.PROCESSING,[Do.PENDING]:Co.PENDING},Oo="9.1.0-beta.0",Mo={DEFAULT_PAGE_SIZE:50,MAX_PAGE_SIZE:1e3,SAFETY_MAX_PAGES:1e4,DEFAULT_OFFSET:0,DEFAULT_LIMIT:10,BACKEND_MAX_PAGE_SIZE:20},Lo={MAX_CONCURRENT_FETCHES:5,PAGE_SIZE:50,BACKEND_PAGE_SIZE:20};function Uo(e,t=Mo.DEFAULT_LIMIT){if("number"!=typeof e||!Number.isInteger(e)||e<0)throw Jt("offset","a non-negative integer",e);return Zn(t,"limit"),{offset:e,limit:t}}function Fo(e,t,n){if("number"!=typeof e||!Number.isInteger(e)||e<0)throw Jt("offset","a non-negative integer",e);Zn(t,"limit")}function Po(e,t=1,n=Mo.BACKEND_MAX_PAGE_SIZE){return Math.max(t,Math.min(n,Math.ceil(e??t)))}function xo(e,t){if("number"!=typeof e||!Number.isInteger(e))throw Jt("total","a non-negative integer",e);if(e<0)throw Xt("total",0,1/0,e);if("number"!=typeof t||!Number.isInteger(t))throw Jt("limit","a non-negative integer",t);if(t<0)throw Xt("limit",0,1/0,t);return 0===t?1:0===e?0:Math.ceil(e/t)}function Bo(e,t,n){if("number"!=typeof e||!Number.isInteger(e))throw Jt("offset","a non-negative integer",e);if(e<0)throw Xt("offset",0,1/0,e);return e+t<n}function Go(e){return"string"==typeof e||null===e?e:void 0}function $o(e){if("object"!=typeof e||null===e)return{hasNextPage:!1};const t=Reflect.get(e,"hasNextPage"),n=Reflect.get(e,"hasPreviousPage"),r=Go(Reflect.get(e,"endCursor")),s=Go(Reflect.get(e,"startCursor"));return{hasNextPage:!0===t,...void 0===r?{}:{endCursor:r},..."boolean"==typeof n?{hasPreviousPage:n}:{},...void 0===s?{}:{startCursor:s}}}function Ko(e,t){const{hasNextPage:n,endCursor:r}=e;if(n&&"string"==typeof r&&""!==r&&r!==t)return r}function Ho(e){return"string"==typeof e?e:"number"==typeof e||"boolean"==typeof e||"bigint"==typeof e?String(e):JSON.stringify(e)??""}function Wo(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 Vo={tokenName:"lowercase",address:"lowercase",userAddress:"lowercase",assetId:"as given",targetId:"as given",id:"as given",code:"as given"};function jo(e,t){let n=e;for(const[e,r]of Object.entries(t)){const t=Vo[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 qo(e,t,n){for(const r of n){const n=t[r];null!=n&&""!==n&&(e[r]=Ho(n))}return e}const zo="x-api-key";class Xo extends wr{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(!ar(e))throw Wt("tokenName","Token name");const n=mn(e);if(!t.PATTERN.test(n))throw Vt("tokenName",t.DESCRIPTION,"Token name")}(e,t)}validateRequiredString(e,t,n){!function(e,t,n){if(!ar(e))throw Wt(t,n)}(e,t,n)}validateOptionalString(e,t,n,r){!function(e,t,n,r){if(null!=e){if("string"!=typeof e)throw Jt(t,"string",typeof e,n);if(e.length>r)throw Yt(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 Jt(t,"number",typeof e,n);if(e<r||e>s)throw Xt(t,r,s,e,n)}}(e,t,n,r,s)}validateOptionalDate(e,t,n){!function(e,t,n){if(null!=e&&!Nn(e))throw Vt(t,"a valid ISO 8601 date string",n)}(e,t,n)}validatePositiveInteger(e,t,n){br(e,t,n)}validateStatusFilter(e,t,n="status"){Nr(e,t,n)}buildPaginationParams(e,t){return Wo(e,t)}addOptionalFilterParams(e,t,n){return qo(e,t,n)}buildEndpoint(e,t){return jo(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 Mt("Admin API key required for this operation. Set streamAdminApiKey in SDK config.");return{[zo]:this.adminApiKey}}getJwtHeaders(){if(!this.jwtAuth)throw new Mt("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?{[zo]:this.userApiKey}:this.getJwtHeaders()}extractData(e){return on(e,"Backend request failed",!0),cn(e,"No data in backend response")}extractDataOrNull(e){return on(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??mn(e)}}}class Qo extends Xo{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async getSettings(){return{settings:(await this.http.get(ct.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(ct.UPDATE_SETTINGS,t,this.getDualAuthHeaders())).settings}}async getModeration(e){this.validatePositiveInteger(e.flagId,"flagId","Flag ID");const t=ct.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=ct.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(ct.GET_STATUS,{},this.getDualAuthHeaders())).status}}}const Yo={MODERATOR:"MODERATOR",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MANAGER:"MANAGER",OWNER:"OWNER"},Jo=hr(Yo),Zo={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"},ea={MANAGE_COMMUNITY:"MANAGE_COMMUNITY",MANAGE_STREAM:"MANAGE_STREAM",MANAGE_SETTINGS:"MANAGE_SETTINGS",MANAGE_RECORDINGS:"MANAGE_RECORDINGS",VIEW_ANALYTICS:"VIEW_ANALYTICS"},ta=Object.values(ea);function na(e){return Jo.includes(e)}function ra(e){const t=[];return void 0===e.role||null===e.role?t.push("Role is required"):na(e.role)||t.push(`Invalid role. Must be one of: ${Jo.join(", ")}`),ia(e,t),t}function sa(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||na(e.role)||t.push(`Invalid role. Must be one of: ${Jo.join(", ")}`),ia(e,t,!0),t}function ia(e,t,n=!1){const r=t.length;if($t(t,()=>{yr(e.description,"description",255)}),t.length>r&&(t[r]="Description must be 255 characters or less"),void 0!==e.tokenNames){const n=t.length;$t(t,()=>{if(!Array.isArray(e.tokenNames))throw Jt("tokenNames","an array",e.tokenNames);if(!e.tokenNames.every(e=>"string"==typeof e))throw Jt("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;$t(t,()=>{Sr(e.expiresAt,"expiresAt")}),t.length>n&&(t[n]="expiresAt must be a valid ISO 8601 date string")}}function oa(e){if(void 0!==e.pageSize&&("number"!=typeof e.pageSize||e.pageSize<1||e.pageSize>Lr))throw Jt("pageSize",`number between 1 and ${Lr}`,typeof e.pageSize);if(void 0!==e.cursor&&("string"!=typeof e.cursor||""===e.cursor.trim()))throw Jt("cursor","non-empty string",typeof e.cursor)}const aa={[Yo.MODERATOR]:1,[Yo.TECHNICAL_PRODUCER]:1,[Yo.MANAGER]:2,[Yo.OWNER]:3};function ca(e,t){return e===Yo.MANAGER?t!==Yo.OWNER:e===Yo.OWNER||e===t}class la extends wr{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),on(n,"API key operation failed",!0),e.data}validateApiKeyId(e){this.validatePositiveInteger(e,"id","API key ID")}async create(e){const t=ra(e);if(t.length>0)throw new _t(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(ge.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={}){oa(e),this.logger.debug("Listing API keys",e);const t=Wo(e,Lr),n=await this.http.get(ge.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=ge.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=sa(t);if(n.length>0)throw new _t(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=ge.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=ge.REVOKE.replace(":id",String(e));await this.http.delete(t,{},this.getJwtHeaders()),this.logger.debug("API key revoked",{id:e})}getRoles(){return[...Jo]}}const da={ONE_HOUR:3600,ONE_DAY:86400,ONE_WEEK:604800,ONE_MONTH:2592e3},ua={VIEWERS:"viewers",CHAT_PARTICIPANTS:"chat_participants"},ha=ur(ua),ga=Er([{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}]),ma=Er([{field:"tokenName",type:"string",nullable:!0},{field:"isGlobal",type:"boolean"},{field:"isPermanent",type:"boolean"}]),fa=Er([{field:"tokenName",type:"string",nullable:!0},{field:"isGlobal",type:"boolean"}]),pa=Er([{field:"tokenName",type:"string"},{field:"action",type:"string",validator:e=>"CHAT_MESSAGE"===e||"COMMENT"===e||"REACTION"===e}]);function Ea(e){return null==e||""===e||"string"==typeof e&&(!Tr(e)&&e.length<=xr.BAN_REASON.MAX_LENGTH)}function Aa(e){return!!lr(e)||"number"==typeof e&&(e>=Gr&&e<=$r)}function va(e){if(!ar(e.userAddress))throw Wt("userAddress");if(!Ea(e.reason))throw new _t(`reason must be at most ${xr.BAN_REASON.MAX_LENGTH} characters`,"reason","TOO_LONG");if(!Aa(e.durationSeconds))throw new _t(`durationSeconds must be between ${Gr} and ${$r} seconds`,"durationSeconds","OUT_OF_RANGE")}class Ta extends Xo{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async createBan(e){!function(e){gr(e.tokenName,"tokenName",Rr),va(e)}(e);const t=this.buildEndpoint(se,{tokenName:e.tokenName}),n=ya(e),r=await this.http.post(t,n,this.getMultiAuthHeaders());return{ban:this.extractData(r),tokenName:mn(e.tokenName)}}async removeBan(e){!function(e){if(gr(e.tokenName,"tokenName",Rr),!ar(e.userAddress))throw Wt("userAddress")}(e);const t=_n(e.userAddress,"userAddress"),n=this.buildEndpoint(ae,{tokenName:e.tokenName,userAddress:t}),r=await this.http.delete(n,{},this.getMultiAuthHeaders()),s=this.extractDataOrNull(r);return{removed:s?.removed??!0,tokenName:mn(e.tokenName),userAddress:s?.userAddress??t}}async listBans(e){!function(e){gr(e.tokenName,"tokenName",Rr),dr(0,void 0,Lr,e.pageSize)}(e);const t=this.buildEndpoint(ie,{tokenName:e.tokenName}),n=this.buildPaginationParams(e,Lr);this.addOptionalFilterParams(n,e,["search","name","userAddress"]),void 0!==n.userAddress&&(n.userAddress=Dn(n.userAddress));const r=await this.http.get(t,n,this.getMultiAuthHeaders()),s=this.extractData(r);return{items:s.bans,pageInfo:s.pageInfo}}async getBanStatus(e){!function(e){if(gr(e.tokenName,"tokenName",Rr),!ar(e.userAddress))throw Wt("userAddress")}(e);const t=_n(e.userAddress,"userAddress"),n=this.buildEndpoint(oe,{tokenName:e.tokenName,userAddress:t}),r=await this.http.get(n,{},this.getMultiAuthHeaders()),s=this.extractDataOrNull(r);return{banned:null!==s,...null!==s&&{ban:s},tokenName:mn(e.tokenName),userAddress:t}}async getActiveUsers(e){!function(e){if(gr(e.tokenName,"tokenName",Rr),void 0!==e.type&&!ha(e.type))throw new _t(`type must be one of: ${Object.values(ua).join(", ")}`,"type",kt.INVALID_VALUE)}(e);const t=this.buildEndpoint(ce,{tokenName:e.tokenName}),n={};this.addOptionalFilterParams(n,e,["type","search","name","userAddress"]),void 0!==n.userAddress&&(n.userAddress=Dn(n.userAddress));const r=await this.http.get(t,n,this.getMultiAuthHeaders());return this.extractData(r)}async createGlobalBan(e){!function(e){va(e)}(e);const t=ya(e),n=await this.http.post(le,t,this.getDualAuthHeaders());return{ban:this.extractData(n)}}async removeGlobalBan(e){!function(e){if(!ar(e.userAddress))throw Wt("userAddress")}(e);const t=_n(e.userAddress,"userAddress"),n=this.buildEndpoint(he,{userAddress:t}),r=await this.http.delete(n,{},this.getDualAuthHeaders()),s=this.extractDataOrNull(r);return{removed:s?.removed??!0,userAddress:s?.userAddress??t}}async listGlobalBans(e){const t=e??{pageSize:20};!function(e){dr(0,void 0,Lr,e.pageSize)}(t);const n=this.buildPaginationParams(t,Lr);this.addOptionalFilterParams(n,t,["search","name","userAddress"]),void 0!==n.userAddress&&(n.userAddress=Dn(n.userAddress));const r=await this.http.get(de,n,this.getDualAuthHeaders()),s=this.extractData(r);return{items:s.bans,pageInfo:s.pageInfo}}async getGlobalBan(e){!function(e){if(!ar(e.userAddress))throw Wt("userAddress")}(e);const t=_n(e.userAddress,"userAddress"),n=this.buildEndpoint(ue,{userAddress:t}),r=await this.http.get(n,{},this.getDualAuthHeaders()),s=this.extractDataOrNull(r);return{banned:null!==s,...null!==s&&{ban:s},userAddress:t}}}function ya(e){const t={userAddress:_n(e.userAddress,"userAddress")};return void 0!==e.reason&&(t.reason=e.reason),void 0!==e.durationSeconds&&(t.durationSeconds=e.durationSeconds),t}function Sa(e){return{maxAcceptableReverseBondingCurveFee:Xn(e.maxAcceptableReverseBondingCurveFee)}}const ba={BuyNativeDto:class extends w{constructor(e,t,n="0",r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=Xn(t),this.expectedToken=Qn(n),this.extraFees=Sa(r)}},BuyExactDto:class extends w{constructor(e,t,n,r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=Qn(t),this.expectedNativeToken=Xn(n),this.extraFees=Sa(r)}},SellExactDto:class extends w{constructor(e,t,n="0",r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=Qn(t),this.expectedNativeToken=Xn(n),this.extraFees=Sa(r)}},SellNativeDto:class extends w{constructor(e,t,n,r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=Xn(t),this.expectedToken=Qn(n),this.extraFees=Sa(r)}}};function Na(e,t,n){let r;Yn(t,0,1,"slippageToleranceFactor");try{r=function(e,t){if(yn(e)||""===e)throw Wt(t);if(D.isBigNumber(e)){if(e.isNaN())throw Zt(t,"NaN");return e}try{const n=new D(e);if(n.isNaN())throw Zt(t,e);if(!n.isFinite())throw Zt(t,e);return n}catch(n){if(n instanceof _t)throw n;throw Zt(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 Yi(i).isLessThan(0)&&(i=Yi(0)),Ji(i)}function wa(e,t){if(!ar(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 ka(e,t,n,r){const s=e?.split?.(t)??[],i=void 0!==n?` (${n})`:"";return new _t(`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: ${Ft(r)}`,"token",`INVALID_${"|"===t?"PIPE":"DOLLAR"}_DELIMITED_TOKEN`)}function _a(e,t,n){try{const n=wa(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 ka(e,t,n,r)}}function Ia(e){return function(e,t,n){try{const n=wa(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 ka(e,t,n,r)}}(e,"|","pipe-delimited token")}class Da 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 Ca={name:"GalaChain"},Ra={name:"ethereum",chainId:1};function Oa(e){if("string"!=typeof e)throw new Error("Wallet returned an invalid signature");return e}function Ma(e,t){const n=wn(e,t);if(void 0!==n)throw new Da(n,"INVALID_SIGNER_OPTIONS",{details:{[t]:e}});return e}function La(e){const t={};for(const[n,r]of Object.entries(e))void 0!==r&&(t[n]=Ua(r));return t}function Ua(e){return Array.isArray(e)?e.map(Ua):"object"==typeof e&&null!==e?La(e):e}function Fa(e,t,n,r){return{...e,signature:t,types:n,domain:r}}class Pa extends c{constructor(e){super(e),this.typedDataWallet=new y(e),this.walletAddress=`eth|${this.typedDataWallet.address.slice(2)}`}async signTypedData(e,t){const n=La(t),r=s(e,n);return Fa(n,await this.typedDataWallet.signTypedData(Ca,r,n),r,Ca)}}class xa extends o{constructor(e,t={}){const{verifyActiveAccount:n,...r}=t;if(super(Ma(e,"walletAddress"),{...r,...void 0!==r.selectAddress&&{selectAddress:Ma(r.selectAddress,"selectAddress")}}),this.typedDataWallet=t.wallet,!0===n){const e=i(this.walletAddress)??(void 0===this.selectAddress?void 0:i(this.selectAddress));if(void 0===e)throw new Da("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=La(t),r=s(e,n),o={domain:Ra,types:r,message:n,Primary_type:e},c=this.typedDataWallet??function(){const e=globalThis.window,t=e?.gala;if(void 0===t)throw new Error("Gala wallet is not available");return t}();void 0!==this.verifiedKey&&await async function(e,t){let n="address"in e&&"string"==typeof e.address&&""!==e.address?e.address:void 0;if(void 0===n){const t=await e.request({method:"eth_accounts"}),r=Array.isArray(t)?t[0]:void 0;n="string"==typeof r&&""!==r?r:void 0}const r=void 0===n?void 0:i(n);if(void 0===r||r.toLowerCase()!==t.toLowerCase())throw new Da("Your wallet's active account has changed. Please switch back to the connected account or reconnect your wallet.","WALLET_ACCOUNT_CHANGED",{details:{walletAccount:n??null,signerAccount:t}})}(c,this.verifiedKey);const l=await this.typedDataAccount(c);return Fa(n,Oa(await a(c,this.selectAddress??l,()=>c.request({method:"eth_signTypedData",params:[JSON.stringify(o),l]}))),r,Ra)}async typedDataAccount(e){if(v(this.walletAddress))return this.walletAddress;const t=await e.request({method:"eth_accounts"}),n=Array.isArray(t)?t[0]:void 0,r="string"==typeof n?n.replace(/^eth\|/,"0x"):"";if(!v(r))throw new Error("Gala Wallet did not report an Ethereum account to sign typed data with");return r}}class Ba extends r{constructor(e,t,n){super(e,Ma(t,"walletAddress"),n),this.typedDataProvider=e}async signTypedData(e,t){const n=La(t),r=this.typedDataProvider,i=await r.getNetwork(),o={name:i.name,chainId:Number(i.chainId)},a=s(e,n),c=await r.getSigner(),l=A(await c.getAddress());if(v(this.walletAddress)&&l!==A(this.walletAddress))throw new Da(`Wallet account ${l} is not the account this signer was created for (${this.walletAddress}); reconnect before signing.`,"WALLET_ACCOUNT_CHANGED",{details:{walletAccount:l,signerAccount:this.walletAddress}});return Fa(n,Oa(await c.signTypedData(o,a,n)),a,o)}static fromEip1193(e,t,n){const r=new T(e);return new Ba({request:t=>e.request(t),getNetwork:()=>r.getNetwork(),getSigner:()=>r.getSigner()},i(t)??t,n)}}function Ga(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 $a(e){const{collection:t,category:n,type:r}=Ga(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 Ka(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 Ha(e){return`${e.collection}|${e.category}|${e.type}|${e.additionalKey}`}function Wa(e){if("string"==typeof e){if(!ar(t=e)||!t.includes("|"))throw new _t(`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=Ia(n.slice(0,4).join("|")),t=n[4]??"0";return{...e,instance:t.length>0?t:"0"}}return{...Ia(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(!l(e))throw new _t("Invalid tokenId object format. All fields (collection, category, type, additionalKey) must be non-empty strings","tokenId","INVALID_TOKEN_ID_FORMAT");return e}if(!l(e))throw new _t("Invalid tokenId object format. All fields (collection, category, type, additionalKey) are required","tokenId","INVALID_TOKEN_ID_FORMAT");return{...e,instance:"0"}}throw new _t(`Invalid tokenId type: ${typeof e}. Expected string, TokenClassKey, or TokenInstanceKey`,"tokenId","INVALID_TOKEN_ID_TYPE")}function Va(e){return function(e){try{if(!ar(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 _a((n.length>=5&&"launchpad"===n[n.length-1]?n.slice(0,-1):n).join("$"),"$","vault address")}catch(t){throw new _t(`Invalid vault address: "${e}". Expected format: "service|Token$Unit$SYMBOL$additionalKey$launchpad". Error: ${Ft(t)}`,"vaultAddress","INVALID_VAULT_ADDRESS_FORMAT")}}(e)}function ja(e){return{...Va(e),instance:"0"}}function qa(e){const t=Va(e);if("Token"!==t.collection)throw new _t(`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 za,Xa,Qa,Ya,Ja=Object.freeze({__proto__:null,extractTokenSymbolFromVault:qa,normalizeToTokenInstanceKey:Wa,parseVaultAddressToTokenClassKey:Va,parseVaultAddressToTokenInstance:ja});class Za extends kr{constructor(e=!1){super(e)}generateStringsInstructions(e){try{this.logger.debug("🔧 Generating stringsInstructions for:",e);const t=$a(e);return this.logger.debug("✅ Generated stringsInstructions:",t),t}catch(e){this.logger.error("❌ Failed to generate stringsInstructions:",e);const t=Ft(e);throw new _t(`Failed to generate stringsInstructions: ${t}`,"vaultAddress","INVALID_VAULT_ADDRESS")}}createGalaInstance(){const e=new k;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(!ar(e))throw Wt("vaultAddress","Vault address");try{const t=qa(e);return this.logger.debug("🔍 Extracted token symbol:",{vaultAddress:e,tokenSymbol:t}),t}catch(e){if(e instanceof _t)throw Vt("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad");throw e}}validateVaultAddress(e){if(!ar(e))throw Wt("vaultAddress","Vault address");if(!e.startsWith("service|Token$Unit$"))throw Vt("vaultAddress",'starting with "service|Token$Unit$"');if(!e.endsWith("$launchpad"))throw Vt("vaultAddress",'ending with "$launchpad"');const t=function(e){if(!ar(e))return null;const t=e.match(/^service\|Token\$Unit\$([^$]+)\$eth:([a-fA-F0-9]{40})\$launchpad$/);if(!t)return null;const n=t[1],r=t[2];return void 0===n||void 0===r?null:{tokenSymbol:n,creatorAddress:r.toLowerCase()}}(e);if(!t)throw Vt("vaultAddress","valid vault address format (service|Token$Unit$SYMBOL$eth:address$launchpad)");const n=t.tokenSymbol;if(""===n||!/^[A-Za-z]{1,10}$/.test(n))throw Vt("vaultAddress","containing a 1-10 letter token symbol (case insensitive)");return this.logger.debug("✅ Vault address validation passed:",e),!0}generateTokenClassKeyString(e,t,n,r){return`${e}$${t}$${n}$${r}`}parseTokenClassKeyString(e){try{return _a(e,"$","dollar-delimited token")}catch(e){if(e instanceof _t)throw Vt("stringKey","format: collection$category$type$additionalKey (4 parts)");throw e}}}function ec(e){return"object"==typeof e&&null!==e?e:void 0}class tc extends wr{constructor(e,t,n=!1,r,s,o=.05,a=.01,c){if(super(e,n),this.tokenResolver=t,this._walletProvider=r,this.userAddress=s,this.defaultSlippageToleranceFactor=o,this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor=a,this.sellFeeCeiling=c,this.bundleEndpoint="/bundle",null!==this._walletProvider&&void 0!==this._walletProvider&&null!=s){const e=ec(this._walletProvider),t=e?.privateKey;if("string"==typeof t)this.signer=new Pa(t);else if(function(e){const t=ec(e);return"function"==typeof t?.request}(this._walletProvider)&&void 0!==this.userAddress){const e=kn(this.userAddress,"userAddress");this.signer=new Ba(this._walletProvider,i(e)??e)}this.tokenKeyService=new Za(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 dn(()=>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:sn(n),error:n.error}),this.handleBundleResponse(n))}catch(e){if(e instanceof _t)return{success:!1,error:Ft(e)};throw e}}validateBundleData(e){if(null==e)throw Wt("bundleData","Bundle data");if(null===e.signedDto||void 0===e.signedDto)throw Wt("signedDto","Signed DTO");if(!ar(e.method))throw Wt("method","Method name");if(!Array.isArray(e.stringsInstructions))throw Vt("stringsInstructions","an array of resource tracking strings");if(0===e.stringsInstructions.length)throw new _t("stringsInstructions cannot be empty","stringsInstructions","EMPTY_ARRAY");const t=["BuyWithNative","BuyExactToken","SellExactToken","SellWithNative"];if(!t.includes(e.method))throw Vt("method",`one of: ${t.join(", ")}`);e.stringsInstructions.forEach((e,t)=>{if(!ar(e))throw new _t(`stringsInstructions[${t}] must be a non-empty string`,`stringsInstructions[${t}]`,"INVALID_INSTRUCTION");if("string"!=typeof(n=e)||!n.includes("$"))throw new _t(`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=an(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(Bt(e)&&null!==e.response&&void 0!==e.response){const t=an(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 Ft(e)??"Unknown bundle transaction error"}async getBundlerTransactionResult(e){try{if(!ar(e))throw Wt("transactionId","Transaction ID");let t;this.logger.debug("🔍 Checking bundler transaction result:",e);try{t=await dn(()=>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 _t)return{success:!1,error:Ft(e)};throw e}}async cancelTransaction(e){try{if(!ar(e))throw Wt("transactionId","Transaction ID");let t;this.logger.debug("🚫 Cancelling transaction:",e);try{t=await dn(()=>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 _t)return{success:!1,error:Ft(e)};throw e}}async getHealthStatus(){this.logger.debug("🏥 Checking bundle service health");try{const e=await dn(()=>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 _t("expectedAmount is required for native buy operations. Use getBuyTokenAmount() first to calculate expected tokens.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Na(s,i,"buy-native");this.logger.debug("BuyNative slippage applied:",{originalExpectedTokens:s,slippageFactor:i,adjustedMinTokens:e});const t=new ba.BuyNativeDto(a,n,e,{maxAcceptableReverseBondingCurveFee:o});return await this.executeBundleTransaction(t,"BuyWithNative",a)}{if(null==s||""===s)throw new _t("expectedAmount is required for exact buy operations. Use getBuyTokenAmount() first to calculate expected GALA cost.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Na(s,i,"buy-exact");this.logger.debug("BuyExact slippage applied:",{originalExpectedGalaCost:s,slippageFactor:i,adjustedMaxGalaCost:e});const t=new ba.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 _t("expectedAmount is required for exact sell operations. Use getSellTokenAmount() first to calculate expected GALA.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Na(s,i,"sell-exact");this.logger.debug("SellExact slippage applied:",{originalExpectedGala:s,slippageFactor:i,adjustedMinGala:e});const t={maxAcceptableReverseBondingCurveFee:await c()},r=new ba.SellExactDto(a,n,e,t);return await this.executeBundleTransaction(r,"SellExactToken",a)}{if(null==s||""===s)throw new _t("expectedAmount is required for native sell operations. Use getSellTokenAmount() first to calculate tokens to sell.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Na(s,i,"sell-native");this.logger.debug("SellNative slippage applied:",{originalExpectedTokensToSell:s,slippageFactor:i,adjustedMaxTokensToSell:e});const t={maxAcceptableReverseBondingCurveFee:await c()},r=new ba.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 Ht(e);return{effectiveSlippageFactor:s,effectiveMaxFee:i,vaultAddress:o}}async defaultSellFeeCeiling(e,t){if(void 0===this.sellFeeCeiling)throw qt("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=Na(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 qt("Trading services not available. BundleService requires walletProvider and userAddress for trading operations.","walletProvider");if(null===this.userAddress||void 0===this.userAddress)throw Wt("userAddress","User address")}async executeBundleTransaction(e,t,n){this.ensureTradingServicesAvailable();try{e.uniqueKey=`galaswap-operation-${Date.now()}_${_().replace(/-/gu,"").substring(0,26)}`;const r=await this.signer.signObject(t,d("asset/launchpad-contract",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=an(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 Lt("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 nc extends wr{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(vt),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"}(za||(za={})),function(e){e.INAPPROPRIATE_CONTENT="INAPPROPRIATE_CONTENT",e.SPAM="SPAM",e.HARASSMENT="HARASSMENT",e.SCAM="SCAM",e.OTHER="OTHER"}(Xa||(Xa={})),function(e){e.PENDING="PENDING",e.DISMISSED="DISMISSED",e.ACTIONED="ACTIONED"}(Qa||(Qa={})),function(e){e.DELETE_CONTENT="DELETE_CONTENT",e.BAN_USER="BAN_USER",e.DELETE_AND_BAN="DELETE_AND_BAN"}(Ya||(Ya={}));const rc={[Xa.INAPPROPRIATE_CONTENT]:"Inappropriate Content",[Xa.SPAM]:"Spam",[Xa.HARASSMENT]:"Harassment",[Xa.SCAM]:"Scam",[Xa.OTHER]:"Other"},sc={[Qa.PENDING]:"Pending",[Qa.DISMISSED]:"Dismissed",[Qa.ACTIONED]:"Actioned"},ic={[Ya.DELETE_CONTENT]:"Delete Content",[Ya.BAN_USER]:"Ban User",[Ya.DELETE_AND_BAN]:"Delete & Ban"},oc={[za.CHAT_MESSAGE]:"Chat Message",[za.COMMENT]:"Comment",[za.STREAM]:"Stream",[za.RECORDING]:"Recording"},ac=500,cc=ur(za),lc=ur(Xa),dc=ur(Qa),uc=ur(Ya),hc=Er([{field:"id",type:"number"},{field:"tokenName",type:"string"},{field:"contentType",type:"string",validator:cc},{field:"contentId",type:"string"},{field:"reporterAddress",type:"string"},{field:"reportedUserAddress",type:"string"},{field:"status",type:"string",validator:dc}]),gc={TOKEN_NAME:Dr,TOKEN_NAME_FILTER:Cr,CONTENT_ID:xr.CONTENT_ID,DETAILS:xr.FLAG_DETAILS,PAGINATION:{MAX_LIMIT:Lr}};function mc(e,t,n="tokenName"){gr(e,n,t)}function fc(e){if(void 0!==e.contentType&&!cc(e.contentType))throw Vt("contentType",`one of: ${Object.values(za).join(", ")}`,"Content type");if(void 0!==e.status&&!dc(e.status))throw Vt("status",`one of: ${Object.values(Qa).join(", ")}`);if(void 0!==e.reason&&!lc(e.reason))throw Vt("reason",`one of: ${Object.values(Xa).join(", ")}`);if(void 0!==e.reporterAddress&&!ar(e.reporterAddress))throw Jt("reporterAddress","a non-empty string",typeof e.reporterAddress);if(void 0!==e.reporterAddress&&$n(e.reporterAddress,"reporterAddress"),void 0!==e.reportedUserAddress&&!ar(e.reportedUserAddress))throw Jt("reportedUserAddress","a non-empty string",typeof e.reportedUserAddress);void 0!==e.reportedUserAddress&&$n(e.reportedUserAddress,"reportedUserAddress"),dr(0,void 0,gc.PAGINATION.MAX_LIMIT,e.pageSize)}class pc extends Xo{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async createFlag(e){!function(e){if(mc(e.tokenName,gc.TOKEN_NAME),void 0===e.contentType)throw Wt("contentType","Content type");if(!cc(e.contentType))throw Vt("contentType",`one of: ${Object.values(za).join(", ")}`,"Content type");if(!ar(e.contentId))throw Wt("contentId","Content ID");if(e.contentId.length>gc.CONTENT_ID.MAX_LENGTH)throw Yt("contentId",gc.CONTENT_ID.MAX_LENGTH,e.contentId.length,"Content ID");if(!ar(e.reportedUserAddress))throw Wt("reportedUserAddress","Reported user address");if($n(e.reportedUserAddress,"reportedUserAddress"),!(e.contentType!==za.STREAM&&e.contentType!==za.RECORDING||void 0!==e.reason&&null!==e.reason))throw Wt("reason","Reason");if(void 0!==e.reason&&!lc(e.reason))throw Vt("reason",`one of: ${Object.values(Xa).join(", ")}`,"Reason");if(void 0!==e.details&&!ar(e.details))throw Jt("details","a non-empty string",typeof e.details);if(void 0!==e.details&&e.details.length>gc.DETAILS.MAX_LENGTH)throw Yt("details",gc.DETAILS.MAX_LENGTH,e.details.length)}(e);const t={tokenName:e.tokenName,contentType:e.contentType,contentId:e.contentId,reportedUserAddress:In(e.reportedUserAddress,"reportedUserAddress")};null!==e.reason&&void 0!==e.reason&&(t.reason=e.reason),null!==e.details&&void 0!==e.details&&(t.details=e.details);const n=await this.http.post(Se.CREATE,t,this.getMultiAuthHeaders());return{flag:this.extractData(n).flag}}async listFlags(e){return function(e){mc(e.tokenName,gc.TOKEN_NAME_FILTER),fc(e)}(e),this.fetchFlagList(e)}async listGlobalFlags(e={}){return function(e){void 0!==e.tokenName&&mc(e.tokenName,gc.TOKEN_NAME_FILTER),fc(e)}(e),this.fetchFlagList(e)}async dismissFlag(e){!function(e){if(void 0===e.flagId||null===e.flagId)throw Wt("flagId","Flag ID");try{Zn(e.flagId,"flagId")}catch{throw Vt("flagId","a positive integer","Flag ID")}}(e);const t=Se.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 Wt("flagId","Flag ID");try{Zn(e.flagId,"flagId")}catch{throw Vt("flagId","a positive integer","Flag ID")}if(void 0===e.action)throw Wt("action","Action");if(!uc(e.action))throw Vt("action",`one of: ${Object.values(Ya).join(", ")}`,"Action")}(e);const t=Se.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=Wo(e,Lr);qo(t,e,["tokenName","contentType","status","reason","reporterAddress","reportedUserAddress"]);for(const e of["reporterAddress","reportedUserAddress"]){const n=t[e];void 0!==n&&(t[e]=In(n,e))}const n=await this.http.get(Se.LIST,t,this.getMultiAuthHeaders()),r=this.extractData(n);return{items:r.flags,pageInfo:r.pageInfo}}}const Ec=["heart","fire","laugh","wow","thumbs_up"],Ac={heart:"❤️",fire:"🔥",laugh:"😂",wow:"😮",thumbs_up:"👍"};class vc extends Xo{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}validateMessageId(e){if(!ar(e))throw Wt("messageId","Message ID");if(Jn(e,Br.CONTENT_REACTION.MAX_LENGTH,"messageId"),!Br.CONTENT_REACTION.PATTERN.test(e))throw Vt("messageId","msg-{timestamp}-{uuid} or chat-{timestamp}-{uuid} format","Message ID")}validateReactionType(e){if(!ar(e))throw Wt("reactionType","Reaction type");if(!Ec.includes(e))throw Vt("reactionType",`one of: ${Ec.join(", ")}`,"Reaction type")}async addContentReaction(e){this.validateMessageId(e.messageId),this.validateReactionType(e.reactionType);const t=Xe,n={messageId:e.messageId,reactionType:e.reactionType},r=await this.http.post(t,n,this.getMultiAuthHeaders()),s=this.extractData(r),{created:i,...o}=s;return{data:o,created:i}}async removeContentReaction(e){this.validateMessageId(e.messageId),this.validateReactionType(e.reactionType);const t=`${Qe}?${new URLSearchParams({messageId:e.messageId,reactionType:e.reactionType}).toString()}`;return await this.http.delete(t,{},this.getMultiAuthHeaders()),{success:!0}}async addReactionToChatMessage(e){return this.addContentReaction(e)}async removeReactionFromChatMessage(e){return this.removeContentReaction(e)}async addReactionToComment(e){return this.addContentReaction(e)}async removeReactionFromComment(e){return this.removeContentReaction(e)}}const Tc="Token name is required and must be a string";const yc="GALA|Unit|none|none";class Sc extends kr{constructor(e,t,n,r=!1){super(r),this.dexBackendHttp=e,this.cache=t,this.fetchTokenDetails=n}async fetchLaunchpadTokenSpotPrice(e,t,n){if(!ar(e))throw new _t(Tc,"tokenName",kt.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=Ha(t.sellingToken))}catch(t){this.logger.debug(`Could not determine graduation status for ${e}, falling back to bonding curve: ${Ft(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(yc),s=Vn(n.amount,0)/1e18;if(s<=0)throw new _t(`Invalid token amount calculation: ${s}`,"amount","INVALID_CALCULATION");return{symbol:pn(e),price:r.price/s}}catch(t){throw jt(`Failed to calculate launchpad token spot price for ${e}: ${Ft(t)}`,void 0,Ut(t)?t:void 0)}}async resolveAuthoritativeSymbol(e){if(e===yc)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 jt("GalaChainService not available for token metadata fetch",500);n=(await this.fetchTokenDetails(e)).symbol}catch(t){throw jt(`Could not resolve the symbol for ${e} from the token class, and a symbol cannot be derived from the class key: ${Ft(t)}`)}if(""===n)throw jt(`Token class for ${e} has no symbol`);return this.cache?.setByTokenId(e,{symbol:n}),n}async fetchMarketUsdPrice(e){try{const t=function(e){if(!ar(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 jt("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 _t(`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 _t)throw e;throw jt(`Failed to fetch DEX spot price: ${Ft(e)}`)}}}const bc={BATCH_SIZE:20,FLUSH_INTERVAL_MS:3e3,MAX_QUEUE_SIZE:1e3,FLUSH_ON_PAGE_HIDE:!0,FLUSH_ON_PAGE_UNLOAD:!0,DEBUG:!1},Nc={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 wc{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 An({debug:t.debug??!1,context:"EventsBatcherService"}),this.config={batchSize:t.batchSize??bc.BATCH_SIZE,flushIntervalMs:t.flushIntervalMs??bc.FLUSH_INTERVAL_MS,maxQueueSize:t.maxQueueSize??bc.MAX_QUEUE_SIZE,flushOnPageHide:t.flushOnPageHide??bc.FLUSH_ON_PAGE_HIDE,flushOnPageUnload:t.flushOnPageUnload??bc.FLUSH_ON_PAGE_UNLOAD,debug:t.debug??bc.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(n.userAddress,"userAddress")},...void 0!==n?.tokenName&&""!==n.tokenName&&{tokenName:n.tokenName},...void 0!==n?.sessionId&&""!==n.sessionId&&{sessionId:n.sessionId}};this.buffer(r),n?.immediate&&this.scheduleFlush(0)}async flush(){if(0===this.eventBuffer.length)return;this.cancelFlushTimer();const e=this.eventBuffer.splice(0);this.logger.debug(`Flushing ${e.length} events`);try{const t=await this.submitEvents(e);this.totalFlushed+=t.accepted,this.lastFlushTime=Date.now(),this.lastError=void 0,this.logger.debug(`Flush successful, accepted ${t.accepted} events`)}catch(t){throw this.eventBuffer.unshift(...e),this.lastError=t instanceof Error?t.message:String(t),this.logger.error(`Flush failed: ${this.lastError}`),t}}getStats(){const e={bufferedCount:this.eventBuffer.length,totalQueued:this.totalQueued,totalFlushed:this.totalFlushed,totalDropped:this.totalDropped};return void 0!==this.lastFlushTime&&(e.lastFlushTime=this.lastFlushTime),void 0!==this.lastError&&(e.lastError=this.lastError),e}configure(e){void 0!==e.batchSize&&(this.config.batchSize=e.batchSize),void 0!==e.flushIntervalMs&&(this.config.flushIntervalMs=e.flushIntervalMs),void 0!==e.maxQueueSize&&(this.config.maxQueueSize=e.maxQueueSize),void 0!==e.flushOnPageHide&&(this.config.flushOnPageHide=e.flushOnPageHide),void 0!==e.flushOnPageUnload&&(this.config.flushOnPageUnload=e.flushOnPageUnload)}async shutdown(e=5e3){if(this.isShuttingDown=!0,this.removePageLifecycleListeners(),0!==this.eventBuffer.length)try{await Promise.race([this.flush(),new Promise((t,n)=>setTimeout(()=>n(new Error("Flush timeout during shutdown")),e))])}catch(e){this.logger.error(`Shutdown flush failed: ${e instanceof Error?e.message:String(e)}`)}}buffer(e){this.eventBuffer.length>=this.config.maxQueueSize&&(this.eventBuffer.shift(),this.totalDropped++,this.logger.warn("Event buffer full, dropped oldest event")),this.eventBuffer.push(e),this.totalQueued++,this.eventBuffer.length>=this.config.batchSize?this.scheduleFlush(0):this.scheduleFlush(this.config.flushIntervalMs)}scheduleFlush(e){null===this.flushTimer&&(this.flushTimer=setTimeout(()=>{this.flushTimer=null,this.flush().catch(e=>{this.logger.error(`Scheduled flush failed: ${e instanceof Error?e.message:String(e)}`)})},e))}cancelFlushTimer(){null!==this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null)}async submitEvents(e){return await this.httpClient.post("/v1/events",{events:e})}setupPageLifecycleListeners(){"undefined"!=typeof document&&(this.config.flushOnPageHide&&document.addEventListener("visibilitychange",this.handleVisibilityChange),this.config.flushOnPageUnload&&window.addEventListener("beforeunload",this.handleBeforeUnload))}removePageLifecycleListeners(){"undefined"!=typeof document&&(this.config.flushOnPageHide&&document.removeEventListener("visibilitychange",this.handleVisibilityChange),this.config.flushOnPageUnload&&window.removeEventListener("beforeunload",this.handleBeforeUnload))}flushWithBeacon(){if("undefined"==typeof navigator||!navigator.sendBeacon)return;const e=this.eventBuffer.splice(0),t=JSON.stringify({events:e});try{const n=this.getBaseUrl();navigator.sendBeacon(`${n}/v1/events`,t)?(this.totalFlushed+=e.length,this.lastFlushTime=Date.now()):(this.eventBuffer.unshift(...e),this.logger.warn("sendBeacon returned false, events re-buffered"))}catch(t){this.eventBuffer.unshift(...e),this.logger.error(`sendBeacon failed: ${t instanceof Error?t.message:String(t)}`)}}getBaseUrl(){const e=this.httpClient.config;return e?.baseUrl??""}}const kc=["createdAt","eventType","userAddress"],_c=["last_hour","today","yesterday","last_7_days","last_30_days","custom"],Ic=["sdk","frontend","backend","mcp"];function Dc(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Cc(e){return"number"==typeof e&&Number.isFinite(e)}function Rc(e){return Dc(e)&&Cc(e.id)&&"string"==typeof e.eventType&&Dc(e.payload)&&"string"==typeof e.createdAt&&"string"==typeof e.updatedAt}function Oc(e,t,n){if(!t.some(t=>t===e))throw new _t(`${n} must be one of: ${t.join(", ")}`,n,kt.INVALID_VALUE)}class Mc extends Xo{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async getEventStats(){return function(e){if(!(Dc(e)&&Cc(e.totalEvents)&&Cc(e.todayEvents)&&Cc(e.uniqueUsers)&&Cc(e.uniqueTokens)&&Dc(e.eventsByType)))throw jt("Malformed event statistics response");const t={};for(const[n,r]of Object.entries(e.eventsByType)){if(!Cc(r))throw jt("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(ot,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 _t("limit must be an integer from 1 to 100","limit",kt.INVALID_VALUE);if(void 0!==e.page&&(!Number.isInteger(e.page)||e.page<1))throw new _t("page must be a positive integer","page",kt.INVALID_VALUE);void 0!==e.sortBy&&Oc(e.sortBy,kc,"sortBy"),void 0!==e.sortOrder&&Oc(e.sortOrder,["asc","desc"],"sortOrder"),void 0!==e.timePreset&&Oc(e.timePreset,_c,"timePreset"),void 0!==e.source&&Oc(e.source,Ic,"source")}(e);const t={},n=new URLSearchParams;for(const[r,s]of Object.entries(e))if(void 0!==s&&("string"!=typeof s||""!==s)){if(Array.isArray(s)){const e=s.map(String);if(0===e.length)continue;for(const t of 1===e.length?[...e,...e]:e)n.append(r,t);continue}t[r]="userAddress"===r&&"string"==typeof s?_n(s,"userAddress"):s}const r=n.toString(),s=""===r?it:`${it}?${r}`;return function(e){if(!Dc(e)||!Array.isArray(e.data)||!Dc(e.pagination))throw jt("Malformed events response");const t=e.pagination,n=e.data;if(!(Cc(t.page)&&Cc(t.limit)&&Cc(t.total)&&Cc(t.totalPages)&&n.every(Rc)))throw jt("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 Lc(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 Uc=new Set(["GATEWAY_READ_REJECTED","GATEWAY_READ_RESPONSE_INVALID"]);class Fc extends wr{constructor(e,t=!1){super(e,t)}async fetchGalaBalance(e){return this.fetchTokenBalance(e)}async fetchTokenBalance(e,n=!1){const r=kn(e.owner,"owner");try{const{requestor:t}=Lc(async(e,t)=>({data:await this.http.post(e,t)})),s=new u({gatewayBaseUrl:"",httpRequestor:t,requestTimeoutMs:1/0}),{collection:i,category:o,type:a,additionalKey:c}=e,l=await s.fetchTokenBalance({owner:r,tokenClassKey:{collection:i,category:o,type:a,additionalKey:c},includeExpiredHolds:n});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:Ha(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(t(e)&&Uc.has(e.code))return null;throw jt(`Failed to fetch token balance from GalaChain: ${Ft(e)}`,void 0,Ut(e)?e:void 0)}}}function Pc(e){if(null==e||"object"!=typeof e)return!1;const t=e;return ar(t.amount)&&(void 0!==t.tokenId||ar(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 xc(e){if(null==e||"object"!=typeof e)return!1;const t=e;return ar(t.amount)&&(void 0!==t.tokenId||ar(t.tokenName))&&(void 0===t.name||"string"==typeof t.name)}function Bc(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every(Pc)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}function Gc(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every(xc)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}const $c=100,Kc=100;var Hc,Wc;!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"}(Hc||(Hc={}));class Vc 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"}(Wc||(Wc={}));class jc extends Error{constructor(e,t,n){super(e),this.type=t,this.details=n,this.name="TransferError"}}function qc(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 zc(e,t,n,r="[DEBUG] Token resolution (launchpad)"){const s=await t.resolveTokenToVault(e);if(null!==s){const t=ja(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 _t(`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 Xc extends wr{constructor(e,t,n,r=!1,s){super(e,r),this.wallet=t,this.tokenResolver=n,this.writer=s,this.nativeSigner=t?new Pa(t.privateKey):void 0}writeIdentity(){return void 0!==this.wallet&&void 0!==this.nativeSigner?{signer:this.nativeSigner,walletAddress:Ln(this.wallet.address)}:this.writer}}function Qc(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 Yc=new Set(["GATEWAY_WRITE_REJECTED","GATEWAY_RESPONSE_INVALID","GATEWAY_HTTP_ERROR"]);function Jc(e,{signer:t,walletAddress:n}){const{requestor:r,answer:s}=Lc((t,n)=>e.postWithMeta(t,n));return{writes:new h({gatewayBaseUrl:"",signer:t,walletAddress:n,httpRequestor:r,requestTimeoutMs:1/0,uniqueKeyPrefix:"galaconnect-operation-"}),answer:s}}async function Zc(e,n,r){let s;try{s=await n(e.writes)}catch(n){throw function(e){return t(e)&&Yc.has(e.code)}(n)&&r(e.answer(),void 0),n}return r(e.answer(),s)}function el(e){return void 0===e||""===e?{}:{uniqueKey:e}}const tl=100,nl=100;class rl extends Xc{async lockTokens(e){this.validateLockTokensData(e);const t=this.writeIdentity();if(void 0===t)throw new Vc("Wallet required for token lock operations",Hc.WALLET_REQUIRED);return bo(async()=>{const n=Jc(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=Ln(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(Qc(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?Ln(t.lockAuthority):o})}return Zc(n,t=>t.lockTokens({tokens:i,lockAuthority:o,...void 0!==c?.expires&&{expires:c.expires},...void 0!==l?.name&&{name:l.name},...el(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 Vc("Wallet required for token unlock operations",Hc.WALLET_REQUIRED);return bo(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(Qc(e,t.amount)),n.push({tokenClassKey:{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey},quantity:t.amount})}return Zc(Jc(this.http,t),t=>t.unlockTokens({tokens:r,...void 0!==s?.name&&{name:s.name},...el(e.uniqueKey)}),(e,t)=>(this.assertLockAnswer(e,"Token unlock failed"),this.extractUnlockResult(e,t,n)))},"Token unlock failed",this.logger,t=>{throw this.handleLockError(t,"Token unlock failed",e)})}assertLockAnswer(e,t){try{Gt(e,t)}catch(t){const n=function(e){if(null==e||"object"!=typeof e)return"";const t=e.Message;return"string"==typeof t&&t.trim().length>0?` - ${t}`:""}(e);throw new Vc(`${Ft(t)}${n}`,Hc.NETWORK_ERROR)}}validateSharedTokenEntry(e,t,n){if(void 0===e.tokenId&&void 0===e.tokenName)throw new Vc("Must provide either tokenId or tokenName for token identification",Hc.TOKEN_NOT_FOUND);if(void 0!==e.tokenName)try{pr(e.tokenName,"tokenName",Rr)}catch{throw new Vc("Invalid token name format",Hc.TOKEN_NOT_FOUND,{tokenName:e.tokenName})}try{no(Yi(e.amount))}catch{throw new Vc(Vt(t,"a positive number",n).message,Hc.INVALID_AMOUNT,{amount:e.amount})}}validateLockTokensData(e){if(!Bc(e))throw new Vc("Invalid lock data: missing required fields",Hc.VALIDATION_ERROR);if(e.tokens.length>tl)throw new Vc(`Batch size exceeds maximum limit of ${tl} tokens per lock operation`,Hc.VALIDATION_ERROR);for(const t of e.tokens){if(this.validateSharedTokenEntry(t,"lockAmount","Lock amount"),void 0!==t.lockAuthority&&!Pn(t.lockAuthority))throw new Vc("Invalid lock authority address format",Hc.VALIDATION_ERROR,{lockAuthority:t.lockAuthority});if(void 0!==t.expires)try{Zn(t.expires,"expires")}catch{throw new Vc(Vt("expires","a positive integer (epoch milliseconds)","Expires").message,Hc.VALIDATION_ERROR)}}}validateUnlockTokensData(e){if(!Gc(e))throw new Vc("Invalid unlock data: missing required fields",Hc.VALIDATION_ERROR);if(e.tokens.length>nl)throw new Vc(`Batch size exceeds maximum limit of ${nl} tokens per unlock operation`,Hc.VALIDATION_ERROR);for(const t of e.tokens)this.validateSharedTokenEntry(t,"unlockAmount","Unlock amount")}transactionIdOf(e,t){const n=Array.isArray(e.Data)?e.Data[0]:void 0;return t?.transactionId??n?.transactionId??n?.txnId??n?.TxnId??n?.id??void 0}extractLockResult(e,t,n){const r=this.transactionIdOf(e,t),s=t?.blockNumber;return{...void 0!==r&&{transactionId:r},...void 0!==s&&{blockNumber:s},locked:n}}extractUnlockResult(e,t,n){const r=this.transactionIdOf(e,t),s=t?.blockNumber;return{...void 0!==r&&{transactionId:r},...void 0!==s&&{blockNumber:s},unlocked:n}}handleLockError(e,n,r){if(e instanceof Vc)return e;if(t(e)&&"pre_send"===e.phase)return new Vc(`${n}: ${e.message}`,"SIGNING_FAILED"===(s=e.code)?Hc.SIGNATURE_FAILED:"INVALID_TOKEN_REFERENCE"===s?Hc.TOKEN_NOT_FOUND:"INVALID_QUANTITY"===s?Hc.INVALID_AMOUNT:Hc.VALIDATION_ERROR,qc(r));var s;let i=n,o=Hc.NETWORK_ERROR;if(Bt(e)){const t=e.response?.data;if("object"==typeof t&&null!==t){const e=t.Message;"string"==typeof e&&e.length>0&&(i=`${n}: ${e}`);const r="string"==typeof e?e.toLowerCase():"";r.includes("insufficient")||r.includes("balance")?o=Hc.INSUFFICIENT_BALANCE:r.includes("lock")&&r.includes("not found")?o=Hc.LOCK_NOT_FOUND:r.includes("not found")||r.includes("token")?o=Hc.TOKEN_NOT_FOUND:r.includes("authority")?o=Hc.NOT_LOCK_AUTHORITY:r.includes("expired")&&(o=Hc.LOCK_EXPIRED)}}else Ut(e)&&(i=`${n}: ${Ft(e)}`);return new Vc(i,o,qc(r))}async resolveTokenInstance(e){return bo(async()=>zc(e,this.tokenResolver,this.logger),`Failed to resolve token '${e}'`,this.logger,t=>{if(t instanceof jc)throw new Vc(Ft(t),Hc.TOKEN_NOT_FOUND);throw new Vc(`Failed to resolve token '${e}': ${Ft(t)}`,Hc.TOKEN_NOT_FOUND,{tokenName:e})})}async resolveTokenEntry(e){if(void 0!==e.tokenId){const t=Wa(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 Vc("Must provide either tokenId or tokenName for token identification",Hc.TOKEN_NOT_FOUND)}}const sl=new Set(["GATEWAY_READ_REJECTED","GATEWAY_READ_RESPONSE_INVALID","TOKEN_CLASS_NOT_FOUND"]);function il(e){const t=e?.Data;return Array.isArray(t)?t:void 0}class ol extends wr{constructor(e,t=!1,n){super(e,t),this.publicAxios=n}async fetchTokenClassFromChain(e){try{const t="string"==typeof e?Wa(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(Gt(e,a),void 0===il(e)?.[0])throw jt(`Token not found on GalaChain: ${Ha(o)}`,404)},()=>jt(`Token not found on GalaChain: ${Ha(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 Wt("tokenClasses","Token classes array");return await this.readPublic(t=>t.fetchTokenClassesWithSupply(e),e=>{if(Gt(e,"Failed to fetch token classes with supply from GalaChain"),0===(il(e)?.length??0))throw jt("No token supply data found for requested token classes",404)},void 0)}catch(e){return this.handleTokenServiceError(e,"Token supply data not found on GalaChain","Failed to fetch token classes with supply from GalaChain")}}async readPublic(e,n,r){if(!this.publicAxios)throw Wt("publicAxios","Public Axios instance");const s=this.publicAxios,{requestor:i,answer:o}=Lc(async(e,t)=>{const n=await s.post(e,t);return{data:n.data,status:n.status}});try{return await e(new u({gatewayBaseUrl:"",httpRequestor:i,requestTimeoutMs:1/0}))}catch(e){if(t(e)&&sl.has(e.code)&&(n(o()),"TOKEN_CLASS_NOT_FOUND"===e.code&&void 0!==r))throw r();throw e}}handleTokenServiceError(e,t,n){if(e instanceof _t)throw e;if(Bt(e)&&404===e.response?.status)throw jt(t,404,Ut(e)?e:void 0);if(Ut(e)&&"Error"===e.name&&Ft(e).includes("status indicates failure"))throw jt(Ft(e),400,Ut(e)?e:void 0);const r=Ft(e);if(r.includes("Token not found")){if(e instanceof Error)throw e;throw new Error(r)}throw jt(`${n}: ${r}`,void 0,Ut(e)?e:void 0)}}function al(e){if(null==e||"object"!=typeof e)return!1;const t=e;return ar(t.amount)&&(void 0!==t.tokenId||ar(t.tokenName))}function cl(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every(al)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}const ll=50;var dl;!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"}(dl||(dl={}));class ul extends Error{constructor(e,t,n){super(e),this.type=t,this.details=n,this.name="BurnError"}}const hl={validateAmount(e){const t=Yi(e);try{so(t,"amount")}catch(t){throw new jc(t.message,Wc.INVALID_AMOUNT,{amount:e})}},validateUniqueKey(e){if(!lr(e)&&ar(e)){if(e.length>Kr.MAX_LENGTH)throw new _t(`Unique key too long. Maximum length: ${Kr.MAX_LENGTH}`);if(!Kr.PATTERN.test(e))throw new jc('Invalid unique key format. Must start with "galaswap-operation-" or "galaconnect-operation-"',Wc.INVALID_AMOUNT,{uniqueKey:e})}}},gl="gala-transfer-successful",ml="token-transfer-successful",fl="token-locked-successfully",pl="token-unlocked-successfully",El="transfer-successful-no-id",Al=50;class vl extends Xc{async transferGala(e){this.validateTransferGalaData(e);const t=this.writeIdentity();if(void 0===t)throw new jc("Wallet required for GALA transfer operations",Wc.WALLET_REQUIRED);try{const n=Ln(e.recipientAddress),r=Jc(this.http,t);return await Zc(r,t=>t.transferGala({to:n,quantity:e.amount,...el(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 jc("Wallet required for token transfer operations",Wc.WALLET_REQUIRED);try{const n=Ln(e.to),r=await this.tokenInstanceOf(e.tokenId,e.tokenName,()=>new jc("Must provide either tokenId or tokenName for token identification",Wc.TOKEN_NOT_FOUND)),s=Jc(this.http,t);return await Zc(s,t=>t.transferToken({to:n,...Qc(r,e.amount),...el(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 jc)throw t;throw new jc(`Failed to resolve token class key for '${e}': ${Ft(t)}`,Wc.TOKEN_NOT_FOUND,{tokenName:e})}}async burnTokens(e){this.validateBurnTokensData(e);const t=this.writeIdentity();if(void 0===t)throw new ul("Wallet required for token burn operations",dl.WALLET_REQUIRED);try{const n=[];for(const t of e.tokens){const e=await this.tokenInstanceOf(t.tokenId,t.tokenName,()=>new ul("Must provide either tokenId or tokenName for token identification",dl.TOKEN_NOT_FOUND));n.push(Qc(e,t.amount))}const r=Jc(this.http,t);return await Zc(r,t=>t.burnTokens({tokens:n,...el(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 ar(t.recipientAddress)&&ar(t.amount)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)}(e))throw new _t("Invalid GALA transfer data: missing required fields");if(!Pn(e.recipientAddress))throw new jc("Invalid recipient address format",Wc.INVALID_RECIPIENT,{recipientAddress:e.recipientAddress});hl.validateAmount(e.amount),hl.validateUniqueKey(e.uniqueKey)}validateTransferTokenData(e){if(!function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return ar(t.to)&&ar(t.amount)&&(void 0!==t.tokenId||ar(t.tokenName))&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)}(e))throw new _t("Invalid token transfer data: missing required fields");if(!Pn(e.to))throw new jc("Invalid recipient address format",Wc.INVALID_RECIPIENT,{recipientAddress:e.to});if(!(null!==e.tokenId&&void 0!==e.tokenId||null!==e.tokenName&&void 0!==e.tokenName))throw new jc("Must provide either tokenId or tokenName for token identification",Wc.TOKEN_NOT_FOUND);if(null!==e.tokenName&&void 0!==e.tokenName)try{pr(e.tokenName,"tokenName",Rr)}catch{throw new jc("Invalid token name format",Wc.TOKEN_NOT_FOUND,{tokenName:e.tokenName})}hl.validateAmount(e.amount),hl.validateUniqueKey(e.uniqueKey)}validateBurnTokensData(e){if(!cl(e))throw new ul("Invalid burn data: missing required fields",dl.VALIDATION_ERROR);if(e.tokens.length>Al)throw new ul(`Batch size exceeds maximum limit of ${Al} tokens per burn operation`,dl.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 ul("Must provide either tokenId or tokenName for token identification",dl.TOKEN_NOT_FOUND);const e=Yi(t.amount);try{no(e)}catch{throw new ul("Burn amount must be a positive number",dl.INVALID_AMOUNT,{amount:t.amount})}}}async tokenInstanceOf(e,t,n){if(null!=e){const t=Wa(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 zc(e,this.tokenResolver,this.logger,`[DEBUG] Token resolution for '${e}' (launchpad):`)}catch(t){if(t instanceof jc)throw t;throw new jc(`Failed to resolve token '${e}': ${Ft(t)}`,Wc.TOKEN_NOT_FOUND,{tokenName:e})}}extractTransferResult(e,t,n){if(null==e)throw new jc("No response from GalaChain transfer service",Wc.NETWORK_ERROR);const r=t?.blockNumber,s="object"==typeof e&&"Status"in e;s&&Gt(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=El;if(t.Data.length>0)switch(n){case"gala":e=gl;break;case"token":e=ml;break;case"lock":e=fl;break;case"unlock":e=pl}return{transactionId:e,...void 0!==r?{blockNumber:r}:{}}}}throw new jc("Operation succeeded but transaction ID could not be extracted (missing x-transaction-id header and body fields)",Wc.NETWORK_ERROR)}burnResultOf(e,t){if(null==e)throw new ul("No response from GalaChain burn service",dl.NETWORK_ERROR);try{Gt(e,"Token burn operation")}catch(e){throw new Ot(Ft(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,n,r){if(e instanceof jc)return e;if(e instanceof _t)return new jc(Ft(e),Wc.INVALID_AMOUNT);if(t(e)&&"pre_send"===e.phase)return new jc(e.message,"SIGNING_FAILED"===(s=e.code)?Wc.SIGNATURE_FAILED:"INVALID_WALLET_ADDRESS"===s?Wc.INVALID_RECIPIENT:"INVALID_TOKEN_REFERENCE"===s?Wc.TOKEN_NOT_FOUND:Wc.INVALID_AMOUNT);var s;if(Bt(e)&&e.response){const t=e.response.status,n=e.response.data;if(400===t){const e=n?.message;return new jc(("string"==typeof e?e:void 0)??"Invalid transfer request",Wc.INVALID_AMOUNT)}if(403===t)return new jc("Insufficient balance for transfer",Wc.INSUFFICIENT_BALANCE);if(404===t){const e={};return"tokenName"in r&&(e.tokenName=r.tokenName),new jc("Token not found",Wc.TOKEN_NOT_FOUND,e)}}if("object"==typeof e&&null!==e&&"code"in e&&("ECONNABORTED"===xt(e)||"ETIMEDOUT"===xt(e)))return new jc("Transfer request timed out",Wc.NETWORK_ERROR);const i=""!==Ft(e)?Ft(e):n;return new jc(i,Wc.NETWORK_ERROR)}handleBurnError(e,n,r){if(e instanceof ul)return e;if(t(e)&&"pre_send"===e.phase)return new ul(`${n}: ${e.message}`,"SIGNING_FAILED"===(s=e.code)?dl.SIGNATURE_FAILED:"INVALID_TOKEN_REFERENCE"===s?dl.TOKEN_NOT_FOUND:"INVALID_QUANTITY"===s?dl.INVALID_AMOUNT:dl.VALIDATION_ERROR,qc(r));var s;let i=n,o=dl.NETWORK_ERROR;if(Bt(e)){const t=e.response?.data;if("object"==typeof t){const e=t.Message;if("string"==typeof e&&e.length>0){i=`${n}: ${e}`;const t=e.toLowerCase();t.includes("insufficient")||t.includes("balance")?o=dl.INSUFFICIENT_BALANCE:(t.includes("not found")||t.includes("token"))&&(o=dl.TOKEN_NOT_FOUND)}}}else Ut(e)&&(i=`${n}: ${Ft(e)}`);return new ul(i,o,qc(r))}}class Tl extends wr{constructor(e,t,n,r=!1,s,i){super(e,r),this.balanceService=new Fc(e,r),this.tokenService=new ol(e,r,s),this.lockService=new rl(e,t,n,r,i),this.transferService=new vl(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 g(await this.fetchTokenClassFromChain(e))}catch(t){if(Ut(t)&&("NetworkError"===t.name||Ft(t).includes("Token not found")))throw t;throw jt(`Failed to fetch token details from GalaChain for ${"string"==typeof e?e:Ha(e)}: ${Ft(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 yl extends wr{async getHealth(){const e=(await this.http.get(at)).data;if(null==e)throw jt("Health check answered no data");return e}}class Sl extends Error{constructor(e,t,n){super(e),this.filename=t,this.mimeType=n,this.name="FileValidationError"}}function bl(e,t,n){if(null==e)throw new Sl("File is required",t,n);if("undefined"!=typeof File&&e instanceof File){const t=Ns.safeParse(e);if(!t.success){const n=t.error.issues.map(e=>e.message).join("; ");throw new Sl(n,e.name,e.type)}return}if(Buffer.isBuffer(e)){if(void 0===t||""===t)throw new Sl("Filename is required when uploading Buffer objects",t,n);const r=ws.safeParse(e);if(!r.success){const e=r.error.issues.map(e=>e.message).join("; ");throw new Sl(e,t,n)}try{Jn(t,255,"filename")}catch(e){throw new Sl(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 Sl(`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 Sl(`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 Sl(`File extension "${i}" does not match MIME type "${n}"`,t,n);return}throw new Sl("File must be a File object (browser) or Buffer (Node.js)",t,n)}function Nl(e,t="image",n){const r=new FormData;if("undefined"!=typeof File&&e instanceof File)r.append(t,e);else{if(!Buffer.isBuffer(e))throw Vt("file","a File object (browser) or Buffer (Node.js)");{const s=new Blob([e],{type:"image/png"});r.append(t,s,n)}}return r}class wl extends wr{constructor(e,t,n=!1){super(e,n,t)}async uploadImageByTokenName(e){const{tokenName:t,options:n}=e;gr(t,"tokenName",Rr);const r=`${t}.png`;bl(n.file,r,"image/png");try{const e=Nl(n.file,"image",r),s=await ln(()=>this.http.request({method:"POST",url:jo(O.UPLOAD_IMAGE,{tokenName:t}),data:e,headers:this.getJwtHeaders()}),{errorContext:"Image upload failed"});return"string"==typeof s?s:""}catch(e){if(e instanceof Mt)throw e;if(Ut(e)&&Ft(e).includes("FormData"))throw qt("File upload failed: FormData not supported in this environment. Ensure you have proper polyfills for Node.js environments.","FormData");throw e}}}function kl(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 _t("At least one config option must be provided (chatEnabled, commentsEnabled, streamingEnabled, nextLiveStreamAt, streamLanguage, or social URLs)","options",kt.REQUIRED);if(void 0!==e.chatEnabled&&"boolean"!=typeof e.chatEnabled)throw Jt("chatEnabled","boolean");if(void 0!==e.commentsEnabled&&"boolean"!=typeof e.commentsEnabled)throw Jt("commentsEnabled","boolean");if(void 0!==e.streamingEnabled&&"boolean"!=typeof e.streamingEnabled)throw Jt("streamingEnabled","boolean");if(void 0!==e.streamLanguage&&"string"!=typeof e.streamLanguage)throw Jt("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 Jt(n,"string or null")}if(void 0!==e.nextLiveStreamAt&&null!==e.nextLiveStreamAt){if("string"!=typeof e.nextLiveStreamAt)throw Jt("nextLiveStreamAt","string or null");const t=new Date(e.nextLiveStreamAt);if(isNaN(t.getTime()))throw new _t("nextLiveStreamAt must be a valid ISO date string","nextLiveStreamAt",kt.INVALID_FORMAT)}}function _l(e){if(lr(e)||"object"!=typeof e)return{};const t={};for(const[n,r]of Object.entries(e))lr(r)||(ar(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 Il=Object.freeze({__proto__:null,adaptQueryParams:_l});function Dl(e,t){if(null==e)return[];if(Array.isArray(e))return e;const n=e[t];return Array.isArray(n)?n:[]}function Cl(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.owner&&""!==t.owner}function Rl(e){return"string"==typeof e.quantity&&""!==e.quantity}class Ol extends wr{constructor(e,t,n=!1){super(e,n,t)}async fetchPools(e={}){const t=function(e){const t=e.pageSize??Mo.DEFAULT_LIMIT;if(!Number.isInteger(t)||t<1||t>Nt)throw Xt("pageSize",1,Nt,t);const n={pageSize:String(t)};ar(e.cursor)&&(n.cursor=e.cursor);void 0!==e.type&&(n.type=Fl("type",e.type,St));ar(e.tokenName)&&(gr(e.tokenName,"tokenName",Dr),n.tokenName=e.tokenName);if(ar(e.search)){if(e.search.length>Ml)throw nn("search",Ml,e.search.length);n.search=e.search}!0===e.hasUpcomingShows&&(n.hasUpcomingShows="true");if(ar(e.language)){if(!Ul.test(e.language))throw Vt("language",'an ISO 639-1 code such as "en" or "zh-CN"');n.language=e.language}if(void 0!==e.recentlyStreamed){const t=e.recentlyStreamed;if(!Number.isInteger(t)||t<1||t>Ll)throw Xt("recentlyStreamed",1,Ll,t);n.recentlyStreamed=String(t)}!0===e.hasRecordings&&(n.hasRecordings="true");void 0!==e.streamStatus&&(n.streamStatus=Fl("streamStatus",e.streamStatus,bt));if(void 0!==e.isGraduated){if("boolean"!=typeof e.isGraduated)throw Jt("isGraduated","boolean",e.isGraduated);n.isGraduated=e.isGraduated?"true":"false"}void 0!==e.creatorAddress&&(n.creatorAddress=function(e){if("string"!=typeof e)throw Jt("creatorAddress","string",e);return $n(e,"creatorAddress"),Gn(e)??e}(e.creatorAddress));return n}(e),n=an(await un(()=>this.http.get(O.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:$o(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=Ko(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=Ii(e);!t.success&&t.errors&&uo(t.errors,"options")}(e),ar(e.tokenName)&&gr(e.tokenName,"tokenName",Or);try{const t=await this.http.post(O.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===ar(e.symbol)){return!n.symbolAvailable}if(!0===ar(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 Vi(t,"tokenName")&&qi(t,"from")&&qi(t,"to")&&qi(t,"resolution")}(e))throw new _t("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(gr(t,"tokenName",Dr),null==n||null==r||null==s)throw new _t("Graph options (from, to, resolution) are required","options","MISSING_GRAPH_OPTIONS");const i={tokenName:t,from:n,to:r,resolution:s};go(i);const o=_l(i),a=await ln(()=>this.http.get(O.CHART,o),{errorContext:"Failed to fetch graph data"});if(!Array.isArray(a.data)||"boolean"!=typeof a.isPreviousData)throw new Ot("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 Wt("tokenName","Token name");let t;gr(e,"tokenName",Dr);try{t=await un(()=>this.http.get(`${O.GET_TOKEN_DISTRIBUTION}?tokenName=${e}`),{errorContext:"Failed to fetch token distribution"})}catch(t){if(Bt(t)&&500===t.response?.status)throw jt(`Token distribution data temporarily unavailable for ${e}. This is a backend issue - please try again later.`,500,Ut(t)?t:void 0);throw t}return function(e,t,n=Ji){if(!Array.isArray(e))throw jt("Invalid API response: expected array of holders",t);for(const n of e){if(!Cl(n))throw jt("Invalid holder data: missing or invalid owner field",t);if(!Rl(n))throw jt("Invalid holder data: missing or invalid quantity field",t);const e=Vn(n.quantity,NaN);if(isNaN(e)||!isFinite(e))throw jt(`Invalid holder quantity: "${n.quantity}"`,t)}const r=e,s=r.reduce((e,t)=>e.plus(t.quantity),Yi(0));return{holders:r.map(e=>({address:e.owner,balance:e.quantity,percentage:io(Yi(e.quantity),s,Yi(0)).multipliedBy(100).toNumber()})),totalSupply:n(s),totalHolders:r.length,lastUpdated:new Date}}(an(t),t.status,e=>e.toFixed())}async fetchUserHolderContext(e,t){if(""===e||null==e)throw Wt("tokenName","Token name");if(""===t||null==t)throw Wt("userAddress","User address");return gr(e,"tokenName",Dr),ln(()=>this.http.get(`${O.GET_TOKEN_DISTRIBUTION}?tokenName=${e}`,{userAddress:_n(t,"userAddress")}),{errorContext:"Failed to fetch user holder context"})}async resolveTokenNameToVault(e){const t=await this.fetchPools({tokenName:e});if(null!==t.items&&void 0!==t.items&&Array.isArray(t.items)&&t.items.length>0)return t.items[0]?.vaultAddress??null;if(null!==t.items&&void 0!==t.items&&"object"==typeof t.items){const e=t.items.tokens;return e?.vaultAddress??null}return null}async fetchToken(e){if(null==e||"string"!=typeof e||""===e.trim())throw new Error("Token name is required and must be a non-empty string");gr(e,"tokenName",Rr);try{const t=O.GET_TOKEN.replace(":tokenName",e.toLowerCase().trim()),n=an(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 Ot?new Ot(`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&&gr(e.tokenName,"tokenName",Or);try{const t=await this.http.post(O.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(!ar(e))throw Wt("tokenName","Token name");gr(e,"tokenName",Rr);const t=O.TOKEN_STATS.replace(":tokenName",e.toLowerCase().trim());try{const e=an(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 Wt("tokenName","Token name");gr(e,"tokenName",Rr),kl(t);const n=O.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(!ar(e))throw Wt("tokenName","Token name");gr(e,"tokenName",Rr);const t=O.UPDATE_TOKEN_CONFIG.replace(":tokenName",e.toLowerCase().trim()),n=an(await this.http.get(t));if(void 0===n)throw new Error(`Invalid response: missing token config data for "${e}"`);return n}}const Ml=255,Ll=720,Ul=/^[a-z]{2}(-[A-Z]{2})?$/u;function Fl(e,t,n){const r="string"==typeof t?t.toUpperCase():void 0,s=n.find(e=>e===r);if(void 0===s)throw en(e,t,n);return s}function Pl(e){if(void 0!==e.tokenName){if(!ar(e.tokenName))throw Jt("tokenName","a non-empty string",typeof e.tokenName);pr(e.tokenName,"tokenName",Dr)}if(void 0!==e.userAddress){if(!ar(e.userAddress))throw Jt("userAddress","a non-empty string",typeof e.userAddress);if(e.userAddress.length>Pr)throw Yt("userAddress",Pr,e.userAddress.length)}if(void 0!==e.search){if("string"!=typeof e.search)throw Jt("search","a string",typeof e.search);if(e.search.length>256)throw Yt("search",256,e.search.length)}if(dr(0,void 0,Fr,e.pageSize),void 0!==e.txnType&&"BUY"!==e.txnType&&"SELL"!==e.txnType)throw Vt("txnType",'"BUY" or "SELL"');if(void 0!==e.startDate){if(!ar(e.startDate))throw Jt("startDate","a non-empty string",typeof e.startDate);if(isNaN(Date.parse(e.startDate)))throw Vt("startDate","a valid ISO 8601 date")}if(void 0!==e.endDate){if(!ar(e.endDate))throw Jt("endDate","a non-empty string",typeof e.endDate);if(isNaN(Date.parse(e.endDate)))throw Vt("endDate","a valid ISO 8601 date")}if(void 0!==e.minAmount)try{Yn(e.minAmount,0,Number.MAX_SAFE_INTEGER,"minAmount")}catch{throw Vt("minAmount","a non-negative number")}if(void 0!==e.maxAmount)try{Yn(e.maxAmount,0,Number.MAX_SAFE_INTEGER,"maxAmount")}catch{throw Vt("maxAmount","a non-negative number")}void 0!==e.minAmount&&void 0!==e.maxAmount&&function(e,t,n="range"){const r="number"==typeof e?e:Number(e),s="number"==typeof t?t:Number(t);if(isNaN(r)||isNaN(s))throw Jt(n,"numeric values",void 0,n);if(r>s)throw new _t(`Minimum value (${r}) must be less than or equal to maximum value (${s}) for ${n}`,n,kt.INVALID_RANGE)}(e.minAmount,e.maxAmount,"amountRange")}class xl extends wr{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 Vi(t,"tokenName")&&(void 0===t.tradeType||"buy"===t.tradeType||"sell"===t.tradeType)&&ji(t,"userAddress")&&qi(t,"offset")&&qi(t,"pageSize")&&qi(t,"page")&&qi(t,"limit")}(e))throw new _t("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=Mo.DEFAULT_LIMIT}=e;if(!ar(t))throw Wt("tokenName","Token name");const s={pageSize:String(Math.min(r,Ur))};void 0!==n&&(s.cursor=n);const i=await this.http.get(jo(O.GET_TRADES,{tokenName:t}),s);if(null==i)throw new _t("No response from trade service","response","NO_RESPONSE");const o=an(i),a=Dl(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=mn(e.tokenName)),null!==e.userAddress&&void 0!==e.userAddress&&e.userAddress.length>0&&(t.userAddress=_n(e.userAddress,"userAddress")),null!==e.search&&void 0!==e.search&&e.search.length>0&&(t.search=e.search);const n=void 0!==e.pageSize?Po(e.pageSize,1,Fr):Fr;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){Pl(e);const t=this.buildTradesQueryParams(e);return ln(()=>this.http.get(Ye,t),{errorContext:"Failed to fetch trades"})}}Rr.MIN_LENGTH,Rr.MAX_LENGTH;function Bl(e){return ar(e)&&Rn(e)}function Gl(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 $l(e,t){return e.toLowerCase()===t.toLowerCase()}function Kl(e){return e.toLowerCase()}function Hl(e,t){return e.toLowerCase().includes(t.toLowerCase())}function Wl(e,t,n,r){return e===n&&t===r||e===r&&t===n}function Vl(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&&ql(e))return zl(e)}return null}return ql(e)?zl(e):null}function jl(e){return null==e||"string"!=typeof e||0===e.trim().length}function ql(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 zl(e){return e.startsWith("0x")?e.slice(2):e}ur({BOTH:"both",HELD:"held",CREATED:"created"});function Xl(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Ql(e){return"number"==typeof e&&Number.isFinite(e)}function Yl(e){return null===e||"string"==typeof e}function Jl(e){return Array.isArray(e)&&e.every(e=>Xl(e)&&"string"==typeof e.badgeName&&"boolean"==typeof e.isActive)}function Zl(e){return Xl(e)&&"string"==typeof e.address&&Yl(e.fullName)&&Yl(e.profileImage)&&Yl(e.bio)&&function(e){return Xl(e)&&Ql(e.tokensCreated)&&Ql(e.tokensGraduated)&&Ql(e.graduationRate)&&Ql(e.totalTrades)&&"string"==typeof e.totalVolumeGala&&Yl(e.totalVolumeUsd)&&(null===e.holdingsCount||Ql(e.holdingsCount))&&Yl(e.accountCreatedAt)&&Ql(e.accountAgeDays)}(e.stats)&&Jl(e.launchBadge)&&Jl(e.successBadge)&&Jl(e.volumeBadge)&&Jl(e.engagementBadge)&&"boolean"==typeof e.isLiveStreaming&&Yl(e.liveStreamToken)}class ed extends wr{constructor(e,t,n=!1){super(e,n,t)}async fetchProfile(e){const t=e??this.http.getAddress();if(""===t||null==t||!Bl(t))throw Vt("address","eth|[40-hex-chars] or client|[identifier]","Address");if(void 0===e){const e=await ln(()=>this.http.get(O.GET_CURRENT_USER,void 0,this.getJwtHeaders()),{errorContext:"Failed to fetch profile"});if(!(Xl(n=e)&&"string"==typeof n.address&&Yl(n.fullName)&&Yl(n.profileImage)&&"string"==typeof n.bio&&Jl(n.launchBadge)&&Jl(n.successBadge)))throw jt("Malformed profile response");return e}var n;const r=await ln(()=>this.http.get(O.GET_PROFILE.replace(":address",_n(t,"address"))),{errorContext:"Failed to fetch profile"});if(!Zl(r))throw jt("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 ln(()=>this.http.put(O.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=Nl(e.file,"image",t),r=await ln(()=>this.http.request({method:"POST",url:O.UPLOAD_PROFILE_IMAGE,data:n,headers:this.getJwtHeaders()}),{errorContext:"Image upload failed"});return"string"==typeof r?r:""}catch(e){if(e instanceof _t||e instanceof Mt)throw e;if(e instanceof Ot)throw new Ot(`Profile image upload failed: ${Ft(e)}`,e.statusCode,e);throw new _t(`Profile image upload failed: ${Ft(e)}`,"file","UPLOAD_FAILED")}}async fetchTokenList(e){if(void 0!==e.status&&"created"!==e.type)throw new _t("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(O.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 _t("fetchTokensHeld only supports type=held","type","INVALID_TYPE");if(void 0!==e.status)throw new _t("status filters only apply when type=created","status","INVALID_FILTER");return this.buildFetchRequest(O.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 _t("fetchTokensCreated only supports type=created","type","INVALID_TYPE");const o=e?.address??this.http.getAddress();if(null==o||""===o)throw new _t("Wallet address not available - wallet not configured","address","NO_WALLET");const a={type:"created",address:o,pageSize:n??Mo.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,Ur))),ln(()=>this.http.get(O.GET_MANAGED_TOKENS,t,this.getJwtHeaders()),{errorContext:"Failed to fetch managed tokens"})}async getUserGalaBalance(e){if("string"!=typeof e||""===e.trim())throw Wt("address","Address");const t=_n(e.trim(),"address");return ln(()=>this.http.get(jo(O.GET_GALA_BALANCE,{address:t})),{errorContext:"Failed to fetch GALA balance"})}async fetchReferralCode(){return ln(()=>this.http.get(O.GET_REFERRAL_CODE,void 0,this.getJwtHeaders()),{errorContext:"Failed to fetch referral code"})}async buildFetchRequest(e,t,n){this.validateGetTokenListOptions(t);const r=Wo({pageSize:t.pageSize??Mo.DEFAULT_LIMIT,...void 0!==t.cursor&&{cursor:t.cursor}},Ur);qo(r,t,["address","search","tokenName","status"]),n.includeType&&!e.includes("?type=")&&(r.type=n.requestType);let s=e;const i=_n(t.address??this.http.getAddress(),"address");if(void 0!==t.address&&(r.address=i),e.includes(":address")){if(0===i.length)throw Wt("address","User address");s=e.replace(":address",i),delete r.address}const o=an(await un(()=>this.http.get(s,r),{errorContext:n.errorMessage}));return{tokens:Dl(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:$o(o?.pageInfo)}}validateGetTokenListOptions(e){const t=e.pageSize??Mo.DEFAULT_LIMIT;if(t<1||t>Ur)throw new _t(`pageSize must be between 1 and ${Ur}`,"pageSize","OUT_OF_RANGE");if(void 0!==e.address&&!Bl(e.address))throw Vt("address","eth|[40-hex-chars] or client|[identifier]","Address");const n=Gl(e.search);if(null!==n&&!(ar(r=n)&&r.length>=Wr&&r.length<=Vr))throw Xt("search",Wr,Vr,n.length,"Search query");var r;const s=Gl(e.tokenName);if(!(null===s||ar(i=s)&&Rr.PATTERN.test(i)))throw Vt("tokenName",Rr.DESCRIPTION,"Token name");var i}validateUpdateProfileData(e){if(void 0!==e.address&&!Bl(e.address))throw Vt("address","eth|[40-hex-chars] or client|[identifier]","Address");if(void 0===e.fullName&&void 0===e.profileImage)throw new _t("At least one of fullName and profileImage must be provided","options","REQUIRED");if(void 0!==e.fullName&&(t=e.fullName.trim(),!(ar(t)&&t.length>=jr.FULL_NAME.MIN_LENGTH&&t.length<=jr.FULL_NAME.MAX_LENGTH&&jr.FULL_NAME.ALPHABETS_ONLY_PATTERN.test(t))))throw Xt("fullName",jr.FULL_NAME.MIN_LENGTH,jr.FULL_NAME.MAX_LENGTH,e.fullName.trim().length,"Full name");var t;if("string"==typeof e.profileImage&&e.profileImage.trim().length>2048)throw new _t("profileImage must not exceed 2048 characters","profileImage","TOO_LONG")}validateUploadProfileImageOptions(e){if(void 0!==e.address&&!Bl(e.address))throw Vt("address","eth|[40-hex-chars] or client|[identifier]","Address")}}class td{constructor(e,t,n=!1){this.http=e,this.poolService=new Ol(e,t,n),this.tradeService=new xl(e,n),this.userService=new ed(e,t,n),this.imageService=new wl(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 ho(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 nd(e,t){if(void 0!==e){if(!ar(e))throw Jt("tokenName","string");pr(e,"tokenName",Dr)}if(void 0!==t){if(!ar(t))throw Jt("userAddress","string");if(t.length>Pr)throw new _t(`userAddress must be at most ${Pr} characters`,"userAddress",kt.TOO_LONG)}}const rd={CHAT_MESSAGE:"CHAT_MESSAGE",COMMENT:"COMMENT"},sd={PAGINATION:{MAX_LIMIT:Fr},CONTENT:{CHAT_MAX_LENGTH:xr.CHAT_MESSAGES_V1.MAX_LENGTH,COMMENT_MAX_LENGTH:xr.COMMENTS_V1.MAX_LENGTH}};function id(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 tn(["type","tokenName","userAddress"]);if(void 0!==e.type&&e.type!==rd.CHAT_MESSAGE&&e.type!==rd.COMMENT)throw new _t(`type must be one of: ${Object.values(rd).join(", ")}`,"type",kt.INVALID_VALUE);nd(e.tokenName,e.userAddress),void 0!==e.pageSize&&dr(0,void 0,Fr,e.pageSize)}function od(e){if(void 0===e.type||null===e.type)throw Wt("type");if(e.type!==rd.CHAT_MESSAGE&&e.type!==rd.COMMENT)throw new _t(`type must be one of: ${Object.values(rd).join(", ")}`,"type",kt.INVALID_VALUE);if(!ar(e.tokenName))throw Wt("tokenName");if(pr(e.tokenName,"tokenName",Dr),!ar(e.content))throw Wt("content");if(0===e.content.trim().length)throw rn("content","Content");const t=e.type===rd.CHAT_MESSAGE?sd.CONTENT.CHAT_MAX_LENGTH:sd.CONTENT.COMMENT_MAX_LENGTH;if(e.content.length>t)throw nn("content",t,e.content.length)}function ad(e){if(!ar(e.content))throw Wt("content");if(0===e.content.trim().length)throw rn("content","Content");const t=Math.max(sd.CONTENT.CHAT_MAX_LENGTH,sd.CONTENT.COMMENT_MAX_LENGTH);if(e.content.length>t)throw nn("content",t,e.content.length)}function cd(e){if(!ar(e))throw Wt("id","Message ID");const t=Br.CHAT_MESSAGE.PATTERN.test(e),n=/^msg-\d{13}-[a-f0-9]{32}$/.test(e);if(!t&&!n)throw new _t("Invalid message ID format. Expected: chat-{timestamp}-{uuid} or msg-{timestamp}-{uuid}","id",kt.INVALID_FORMAT)}function ld(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function dd(e){return null===e||"string"==typeof e}function ud(e){return ld(e)&&dd(e.fullName)&&dd(e.profileImage)}function hd(e){if(!ld(e))return!1;const t=e.reactions;return"string"==typeof e.id&&"string"==typeof e.messageId&&"string"==typeof e.tokenName&&dd(e.tokenImage)&&"string"==typeof e.userAddress&&ud(e.user)&&ud(e.userProfile)&&"string"==typeof e.content&&"string"==typeof e.createdAt&&dd(e.updatedAt)&&dd(e.deletedAt)&&"number"==typeof e.flagCount&&ld(t)&&ld(t.counts)}function gd(e){return e===rd.CHAT_MESSAGE||e===rd.COMMENT}class md extends Xo{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}validateContent(e,t){if(!ar(e))throw Wt("content","Message content");if(0===e.trim().length)throw Wt("content","Message content");Jn(e,t===rd.CHAT_MESSAGE?xr.CHAT_MESSAGES_V1.MAX_LENGTH:xr.COMMENTS_V1.MAX_LENGTH,"content")}validateMessageId(e){if(!ar(e))throw Wt("id","Message ID");if(e.length<10||e.length>64)throw Vt("id","valid message ID format","Message ID")}validateMessageType(e){if(e!==rd.CHAT_MESSAGE&&e!==rd.COMMENT)throw new _t(`type must be one of: ${Object.values(rd).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,Dr);const r={};void 0!==e.cursor&&(r.cursor=e.cursor),r.pageSize=e.pageSize??Mo.DEFAULT_LIMIT;const s=Wo(r,Fr),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=mn(e.tokenName)),void 0!==e.userAddress&&""!==e.userAddress&&(i.userAddress=_n(e.userAddress,"userAddress")),void 0!==e.search&&""!==e.search&&(i.search=e.search);const o=await this.http.get(Je.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,Dr),this.validateContent(e.content,e.type);const t={type:e.type,tokenName:mn(e.tokenName),content:e.content.trim()},n=await this.http.post(Je.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(Je.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(Je.DELETE_MESSAGE,e);return await this.http.delete(t,void 0,this.getDualAuthHeaders()),{success:!0}}async getPinnedMessage(e){this.validateTokenName(e,Rr);const t=await this.http.get(Je.GET_PINNED,{tokenName:mn(e)});return{message:this.extractDataOrNull(t)}}async pinMessage(e){this.validateMessageId(e);const t=Je.PIN_MESSAGE.replace(":id",e);return await this.http.post(t,{},this.getDualAuthHeaders()),{success:!0}}async unpinMessage(e){this.validateMessageId(e);const t=Je.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 jt("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 jt("Malformed message statistics response");const c={};for(const[e,n]of Object.entries(a)){if(!t(n))throw jt("Malformed message statistics response");c[e]=n}return{totalMessages:r,todayMessages:s,uniqueUsers:i,uniqueTokens:o,messagesByType:c}}(await this.http.get(Je.GET_MESSAGE_STATS,void 0,this.getDualAuthHeaders()))}}const fd={MODERATOR:"MODERATOR",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MANAGER:"MANAGER"},pd=hr(fd),Ed={TOKEN:"TOKEN",ALL_OWNER_TOKENS:"ALL_OWNER_TOKENS"},Ad=hr(Ed),vd={PENDING:"PENDING",CLAIMED:"CLAIMED",REVOKED:"REVOKED",EXPIRED:"EXPIRED"},Td=hr(vd);function yd(e){return pd.includes(e)}function Sd(e){return Td.includes(e)}function bd(e){return Hr.PATTERN.test(e)}const Nd=Er([{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"}]),wd=Er([{field:"tokenName",type:"string"},{field:"tokenSymbol",type:"string"},{field:"role",type:"string"},{field:"inviteScope",type:"string"},{field:"creatorAddress",type:"string"},{field:"claimedAt",type:"string"}]),kd=Er([{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 _d(e){return Ad.includes(e)}function Id(e){const t=[],n=e.inviteScope??Ed.TOKEN;return void 0===e.inviteScope||_d(e.inviteScope)||$t(t,()=>{throw en("inviteScope",e.inviteScope,Ad,"Invite scope")}),n===Ed.TOKEN?$t(t,()=>{gr(e.tokenName??"","tokenName",Dr)}):n===Ed.ALL_OWNER_TOKENS&&void 0!==e.tokenName&&""!==e.tokenName&&t.push("Token name should not be provided for ALL_OWNER_TOKENS scope invites"),yd(e.role)||$t(t,()=>{throw en("role",e.role,pd,"Role")}),void 0!==e.description&&""!==e.description&&$t(t,()=>{Jn(e.description,xr.DESCRIPTION.MAX_LENGTH,"description")}),void 0===e.expiresAt||""===e.expiresAt||Nn(e.expiresAt)||$t(t,()=>{throw function(e,t="a valid date",n){const r=Kt(e,n);return new _t(`${r} must be ${t}`,e,"INVALID_DATE")}("expiresAt","ISO 8601 format")}),t}function Dd(e){const t=[];return ar(e)?bd(e)||t.push("Invalid invite code format"):t.push(Wt("inviteCode","Invite code").message),t}function Cd(e){const t=[];return $t(t,()=>{gr(e.tokenName??"","tokenName",Dr)}),void 0===e.status||Sd(e.status)||$t(t,()=>{throw en("status",e.status,Td,"Status")}),$t(t,()=>{dr(0,void 0,Lr,e.pageSize)}),t}class Rd extends Xo{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}validateRole(e){if(!ar(e))throw Wt("role","Role");if(!yd(e))throw Vt("role",`one of: ${pd.join(", ")}`,"Role")}validateInviteCodeFormat(e){if(!ar(e))throw Wt("inviteCode","Invite code");if(e.length>Hr.MAX_LENGTH)throw Vt("inviteCode",`at most ${String(Hr.MAX_LENGTH)} characters`,"Invite code")}validateInviteScope(e){if(void 0!==e&&!_d(e))throw new _t(`Invalid invite scope. Must be one of: ${Ad.join(", ")}`,"inviteScope","INVALID_VALUE")}async createInvite(e){this.validateInviteScope(e.inviteScope);const t=e.inviteScope??Ed.TOKEN;if(t===Ed.TOKEN){if(void 0===e.tokenName||""===e.tokenName)throw new _t("Token name is required for TOKEN scope invites","tokenName","REQUIRED");this.validateTokenName(e.tokenName,Dr)}else if(t===Ed.ALL_OWNER_TOKENS&&e.tokenName)throw new _t("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",xr.DESCRIPTION.MAX_LENGTH),this.validateOptionalDate(e.expiresAt,"expiresAt","Expiration date");const n=me,r={inviteScope:t,role:e.role};t===Ed.TOKEN&&null!==e.tokenName&&void 0!==e.tokenName&&""!==e.tokenName&&(r.tokenName=mn(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,Dr),this.validateStatusFilter(e.status,vd);const t=Ee,n={...this.buildPaginationParams(e,Fr)};void 0!==e.tokenName&&""!==e.tokenName&&(n.tokenName=mn(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(Ae,{id:String(e)});on(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(ve,{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 _t("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",xr.DESCRIPTION.MAX_LENGTH);const t=this.buildEndpoint(Te,{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=fe,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=pe,n=this.buildPaginationParams(e??{},Fr),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(ye,{code:e}),n=await this.http.get(t,{});return this.extractData(n)}}const Od={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 Md(e){return parseFloat(Od[e])}function Ld(e){return`${e}-${Date.now()}-${Math.random().toString(36).substring(2,11)}`}function Ud(){return Date.now()+6e4}function Fd(e){return""!==e&&"string"==typeof e&&/^[a-zA-Z0-9]{3,50}$/.test(e)}function Pd(e){try{return Math.floor(parseFloat(String(e))??0).toString()}catch{return"0"}}function xd(e){return""!==e&&"string"==typeof e&&Rn(e)}class Bd extends wr{constructor(e){super(e)}getCollectionClaimFee(){return Od.COLLECTION_CLAIM_FEE}getTokenClassCreateFee(){return Od.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(!xd(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=Od.COLLECTION_CLAIM_FEE;n.collectionClaim=e,t=String(BigInt(t)+BigInt(e))}if((e.createTokenClasses??0)>0){const r=Od.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),!Fd(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:Ud(),uniqueKey:Ld("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),!xd(e))throw new Error(`Invalid wallet address format: ${e}`);const t=(await this.allAuthorizations()).filter(t=>t.authorizedUsers.some(t=>Cn(t,e))).map(t=>({authorizedUser:kn(e,"walletAddress"),collection:t.collection}));return this.logger.debug(`Found ${t.length} collections for user`),t}catch(e){throw this.logger.error("Failed to fetch user collections",e),e}}async isCollectionAvailable(e){try{if(this.logger.debug("Checking collection availability",e),!Fd(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(!Fd(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?Pd(e.maxSupply):void 0,maxCapacity:void 0!==e.maxCapacity?Pd(e.maxCapacity):void 0,additionalKey:e.additionalKey,expiresAt:Ud(),uniqueKey:Ld("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),!Fd(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(!xd(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:kn(e.ownerAddress,"ownerAddress"),additionalKey:e.additionalKey??"none",expiresAt:Ud(),uniqueKey:Ld("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:kn(e.ownerAddress,"ownerAddress"),tokenInstances:i,tokenClass:{collection:e.collection,type:e.type,category:e.category}}}catch(e){throw this.logger.error("Failed to mint NFT",e),e}}async fetchNftBalances(e,t){try{if(this.logger.debug("Fetching NFT balances for",{ownerAddress:e,collectionFilter:t}),!xd(e))throw new Error(`Invalid owner address: ${e}`);const n=(await this.reads().fetchNftBalances({owner:kn(e,"ownerAddress"),collection:t})).map(e=>({owner:e.owner,collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey,instanceIds:[...e.instanceIds],totalOwned:e.instanceIds.length}));return this.logger.debug(`Found ${n.length} NFT balances`),n}catch(e){throw this.logger.error("Failed to fetch NFT balances",e),e}}reads(){const{requestor:e}=Lc(async(e,t)=>({data:await this.http.post(e,t)}));return new u({gatewayBaseUrl:"",httpRequestor:e,requestTimeoutMs:1/0})}allAuthorizations(){return this.reads().fetchAllNftCollectionAuthorizations({pageSize:1e3})}}class Gd extends wr{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(ft,{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:pt,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(Et,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(At,e,t),r=this.extractData(n);return this.logger.debug("Updated notification preferences",{tradesEnabled:r.tradesEnabled,streamsEnabled:r.streamsEnabled}),{preferences:r}}}class $d extends wr{constructor(e,t=!1){super(e,t)}async getHomeOEmbedJson(e={}){this.logger.debug("Fetching home oEmbed (JSON)");const t=await this.http.get(O.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(O.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 _t("tokenName is required","tokenName","REQUIRED_FIELD");this.logger.debug("Fetching pool oEmbed (JSON)",{tokenName:t});const n=O.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 _t("tokenName is required","tokenName","REQUIRED_FIELD");this.logger.debug("Fetching pool oEmbed (HTML)",{tokenName:t});const n=O.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 _t("address is required","address","REQUIRED_FIELD");this.logger.debug("Fetching profile oEmbed (JSON)",{address:t});const n=O.OEMBED_PROFILE.replace(":address",encodeURIComponent(_n(t.trim(),"address"))),r=await this.http.get(n,{format:"json"});return this.logger.debug("Fetched profile oEmbed (JSON)",{address:t,title:r.title}),{oembed:r}}async getProfileOEmbedHtml(e){const{address:t}=e;if(null==t||"string"!=typeof t||""===t.trim())throw new _t("address is required","address","REQUIRED_FIELD");this.logger.debug("Fetching profile oEmbed (HTML)",{address:t});const n=O.OEMBED_PROFILE.replace(":address",encodeURIComponent(_n(t.trim(),"address"))),r=await this.http.get(n,{},{responseType:"text"});return this.logger.debug("Fetched profile oEmbed (HTML)",{address:t}),{html:r}}}function Kd(e){if(!ar(e))throw Wt("address","Address");kn(e,"address")}const Hd={PENDING:"PENDING",CLAIMED:"CLAIMED",REVOKED:"REVOKED",EXPIRED:"EXPIRED"},Wd={ACTIVE:"ACTIVE",REVOKED:"REVOKED"},Vd=ur(Hd),jd=ur(Wd);function qd(e){if(e.status!==Hd.PENDING)return!1;if(null!==e.expiresAt&&void 0!==e.expiresAt){if(bn(e.expiresAt)<=new Date)return!1}return!0}function zd(e){try{yr(e.description,"description",255)}catch(e){if(e instanceof _t){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(!ar(e.expiresAt))throw new Error("expiresAt must be a non-empty string");try{Sr(e.expiresAt,"expiresAt")}catch(e){if(e instanceof _t)throw new Error("expiresAt must be a valid ISO 8601 date string");throw e}if(Nn(e.expiresAt)){if(bn(e.expiresAt)<=new Date)throw new Error("expiresAt must be in the future")}}}function Xd(e){if(void 0!==e.status&&!Vd(e.status))throw en("status",e.status,Object.values(Hd),"status");dr(0,void 0,50,e.pageSize,e.cursor)}function Qd(e){if(void 0!==e.status&&!jd(e.status))throw en("status",e.status,Object.values(Wd),"status");dr(0,void 0,50,e.pageSize,e.cursor)}function Yd(e){if(!ar(e))throw new Error("Invite code must be a non-empty string");Jn(e,Hr.MAX_LENGTH,"code")}function Jd(e){if(!ar(e))throw new Error("Address must be a non-empty string");try{Kn(e,"address")}catch{throw new Error("Invalid wallet address format. Must be eth|..., 0x..., or client|... format")}}function Zd(e){try{Zn(e,"id")}catch(e){if(e instanceof _t)throw new Error("Invite ID must be a positive integer");throw e}}function eu(e){if(null==e||"object"!=typeof e)throw new _t("Options are required");if(void 0!==e.search){if("string"!=typeof e.search)throw new _t("Search must be a string");if(0===e.search.length)throw new _t("Search query cannot be empty string")}if(void 0!==e.sortBy){if("string"!=typeof e.sortBy)throw new _t("Sort field must be a string");if(0===e.sortBy.length)throw new _t("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 _t('Sort order must be "asc" or "desc"')}}function tu(e){if(null==e||"object"!=typeof e)throw new _t("Options are required");if(!ar(e.userAddress))throw new _t("userAddress is required and must be a non-empty string");try{Kn(e.userAddress,"userAddress")}catch{throw new _t("Invalid wallet address format. Must be eth|..., 0x..., or client|... format")}if(void 0!==e.description){if("string"!=typeof e.description)throw new _t("description must be a string");if(e.description.length>255)throw new _t("description must be at most 255 characters")}}class nu extends Xo{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}validateInviteCodeFormat(e){if(!ar(e))throw Wt("inviteCode","Invite code");Yd(e)}validateWalletAddressFormat(e){if(!ar(e))throw Wt("address","Address");Jd(e)}async createInvite(e={}){zd(e),this.validateOptionalString(e.description,"description","Description",xr.DESCRIPTION.MAX_LENGTH),this.validateOptionalDate(e.expiresAt,"expiresAt","Expiration date");const t=be,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={}){Xd(e),this.validateStatusFilter(e.status,Hd);const t=Ne,n={...this.buildPaginationParams(e,Fr)};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(we,{code:e}),n=await this.http.get(t,{});return this.extractData(n)}async revokeInvite(e){Zd(e);const t=this.buildEndpoint(_e,{id:String(e)});on(await this.http.delete(t,void 0,this.getDualAuthHeaders()),"Failed to revoke invite")}async claimInvite(e){this.validateInviteCodeFormat(e);const t=ke,n={inviteCode:e},r=await this.http.post(t,n,this.getJwtHeaders());return{invite:this.extractData(r)}}async listOverseers(e={}){Qd(e),this.validateStatusFilter(e.status,Wd);const t=Ie,n={...this.buildPaginationParams(e,Fr)};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){tu(e),this.validateWalletAddressFormat(e.userAddress),this.validateOptionalString(e.description,"description","Description",xr.DESCRIPTION.MAX_LENGTH);const t=De,n={userAddress:_n(e.userAddress,"userAddress")};void 0!==e.description&&(n.description=e.description);const r=await this.http.post(t,n,this.getDualAuthHeaders());return{overseer:this.extractData(r)}}async revokeOverseer(e){this.validateWalletAddressFormat(e);const t=this.buildEndpoint(Ce,{address:_n(e,"address")});on(await this.http.delete(t,void 0,this.getDualAuthHeaders()),"Failed to revoke overseer")}async getMyStatus(){const e=Re,t=await this.http.get(e,{},this.getJwtHeaders());return this.extractData(t)}async getSummary(){const e=Oe,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getBanStats(){const e=Me,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getTokenBanStats(){const e=Le,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getInviteStats(){const e=Ue,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getFlagStats(){const e=Fe,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getUserStats(){const e=Pe,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async listOverseerUsers(e){const t=e??{};Object.keys(t).length>0&&eu(t);const n=xe,r=this.buildPaginationParams(t,Fr);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(!ar(e))throw Wt("address","User address");Jd(e);const t=this.buildEndpoint(Be,{address:_n(e,"address")}),n=await this.http.get(t,{},this.getDualAuthHeaders());return this.extractData(n)}async flushCacheByAddress(e){Kd(e);const t=this.buildEndpoint(Ge,{address:_n(e,"address")}),n=await this.http.delete(t,void 0,this.getDualAuthHeaders());return this.extractData(n)}async flushCacheByToken(e){!function(e){if(!ar(e))throw Wt("tokenName","Token name")}(e);const t=this.buildEndpoint($e,{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 _t("Safety confirmation required: must pass confirm=true to flush all cache","confirm","CONFIRMATION_REQUIRED")}(e);const t=Ke,n=await this.http.delete(t,{confirm:"true"},this.getDualAuthHeaders());return this.extractData(n)}async flushWalletAliasCache(e){if(void 0!==e){Kd(e);const t=this.buildEndpoint(He,{address:_n(e,"address")}),n=await this.http.delete(t,void 0,this.getDualAuthHeaders());return this.extractData(n)}const t=We,n=await this.http.delete(t,{confirm:"true"},this.getDualAuthHeaders());return this.extractData(n)}}function ru(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 su extends wr{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),on(t,"Platform config operation failed",!0),e.data}async getPlatformConfig(){const e=await this.http.get(q);return this.extractData(e)}async updatePlatformConfig(e){const t=ru(e);if(t.length>0)throw new _t(t.join("; "),"options","VALIDATION_FAILED");const n=await this.http.put(z,e,this.getJwtHeaders());return this.extractData(n)}async getAvailableRoles(){const e=await this.http.get(Y);return this.extractData(e)}}class iu extends wr{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(lt),t=this.extractData(e);return this.logger.debug("Fetched platform stats",{totalTokens:t.totalTokens,timestamp:t.timestamp}),{stats:t}}}class ou extends Xo{constructor(e,t,n,r){super(e,t,n,!1,r)}async getRestrictedNames(){try{return{success:!0,data:(await this.http.get(Ze,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 _t("Content is required");return{success:!0,data:(await this.http.put(et,{content:e.content},this.getJwtHeaders())).data}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}}class au extends Xo{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async getChatStatus(e){if(null==e||""===e)throw Wt("tokenName","Token name");return this.validateTokenName(e,Rr),bo(async()=>{const t=this.buildEndpoint(tt,{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 Wt("tokenName","Token name");return this.validateTokenName(e,Rr),bo(async()=>{const t=this.buildEndpoint(rt,{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 Wt("tokenName","Token name");return this.validateTokenName(e,Rr),bo(async()=>{const t=this.buildEndpoint(nt,{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??mn(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 Wt("tokenName","Token name");if(this.validateTokenName(e,Rr),"number"!=typeof t||t<0||t>600)throw new Error("slowModeSeconds must be a number between 0 and 600");return bo(async()=>{const n=this.buildEndpoint(st,{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 cu={IDLE:"IDLE",ACTIVE:"ACTIVE",DISABLED:"DISABLED"},lu={PREPARING:"preparing",READY:"ready",ERRORED:"errored"},du={IDLE:"idle",STARTING:"starting",BROADCASTING:"broadcasting",ERRORED:"errored"},uu={YOUTUBE:"youtube",TWITCH:"twitch",FACEBOOK:"facebook",CUSTOM:"custom"},hu=ur(cu),gu=ur(lu),mu=ur(uu);function fu(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&hu(t.status)&&(null===t.playbackId||"string"==typeof t.playbackId)&&"boolean"==typeof t.isLive}function pu(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"number"==typeof t.viewerCount}const Eu={OWNER:"OWNER",MANAGER:"MANAGER",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MODERATOR:"MODERATOR"},Au={OWNER:"OWNER",MODERATOR:"MODERATOR"};ur(Eu),ur(Au);const vu={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"},Tu={...Eu,OVERSEER:"OVERSEER"},yu=ur(Tu);function Su(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 bu(e,t="tokenName"){gr(e,t,Rr)}const Nu=/^rtmps?:\/\/\S+$/u,wu=255;function ku(e){if(bu(e.tokenName),!ar(e.language))throw Wt("language");if(t=e.language,!ar(t)||!/^[a-z]{2}(-[A-Z]{2})?$/.test(t))throw new _t('language must be a valid ISO 639-1 code (e.g., "en", "es", "zh-CN")',"language",kt.INVALID_FORMAT);var t}const _u={STREAM_STARTED:"stream.started",STREAM_STOPPED:"stream.stopped",RECORDING_READY:"recording.ready",SIMULCAST_ERROR:"simulcast.error"};class Iu extends Xo{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async startStream(e){this.validateTokenName(e,Rr);const t=this.buildEndpoint(F,{tokenName:e}),n=await this.http.post(t,{},this.getJwtHeaders());return this.extractData(n)}async stopStream(e){this.validateTokenName(e,Rr);const t=this.buildEndpoint(P,{tokenName:e});await this.http.post(t,{},this.getJwtHeaders())}async disableStream(e){return this.toggleFeature(e,x,Rr)}async enableStream(e){return this.toggleFeature(e,B,Rr)}async resetStreamKey(e){this.validateTokenName(e,Rr);const t=this.buildEndpoint(G,{tokenName:e}),n=await this.http.post(t,{},this.getJwtHeaders());return this.extractData(n)}async getStreamCredentials(e){this.validateTokenName(e,Rr);const t=this.buildEndpoint(Z,{tokenName:e}),n=await this.http.get(t,{},this.getJwtHeaders());return this.extractData(n)}async getRecordings(e){!function(e){bu(e.tokenName)}(e);const t=this.buildEndpoint($,{tokenName:e.tokenName}),n=await this.http.get(t),r=this.extractData(n);if(!Array.isArray(r))throw jt("Invalid recordings response: expected an array of recordings");return{recordings:r,tokenName:mn(e.tokenName)}}async getRecordingDownload(e,t){this.validateTokenName(e,Rr),this.validateRequiredString(t,"assetId","Asset ID");const n=this.buildEndpoint(K,{tokenName:e,assetId:t}),r=await this.http.get(n,{},this.getJwtHeaders());return this.extractData(r)}async deleteRecording(e,t){this.validateTokenName(e,Rr),this.validateRequiredString(t,"assetId","Asset ID");const n=this.buildEndpoint(H,{tokenName:e,assetId:t});await this.http.delete(n,void 0,this.getJwtHeaders())}async getSimulcastTargets(e){this.validateTokenName(e,Rr);const t=this.buildEndpoint(W,{tokenName:e}),n=await this.http.get(t,void 0,this.getJwtHeaders()),r=this.extractData(n);if(!Array.isArray(r))throw jt("Invalid simulcast response: expected an array of targets");return{targets:r,tokenName:mn(e)}}async addSimulcastTarget(e){!function(e){if(bu(e.tokenName),!ar(e.platform))throw Wt("platform");if(!mu(e.platform))throw new _t("platform must be one of: 'youtube', 'twitch', 'facebook', 'custom'","platform",kt.INVALID_VALUE);if(!ar(e.url))throw Wt("url");if(!Nu.test(e.url))throw new _t("url must be a valid RTMP or RTMPS URL","url",kt.INVALID_FORMAT);if(e.url.length>2048)throw new _t(`url must not exceed ${String(2048)} characters`,"url",kt.TOO_LONG);if(!ar(e.streamKey))throw Wt("streamKey");if(e.streamKey.length>wu)throw new _t(`streamKey must not exceed ${String(wu)} characters`,"streamKey",kt.TOO_LONG);if(void 0!==e.passthrough){if("string"!=typeof e.passthrough)throw new _t("passthrough must be a string","passthrough",kt.INVALID_TYPE);if(e.passthrough.length>wu)throw new _t(`passthrough must not exceed ${String(wu)} characters`,"passthrough",kt.TOO_LONG)}}(e);const t=this.buildEndpoint(V,{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:mn(e.tokenName)}}async removeSimulcastTarget(e,t){this.validateTokenName(e,Rr),this.validateRequiredString(t,"targetId","Target ID");const n=this.buildEndpoint(j,{tokenName:e,targetId:t});await this.http.delete(n,void 0,this.getJwtHeaders())}async getGlobalStreamingStatus(){const e=await this.http.get(q);return this.extractData(e)}async disableGlobalStreaming(){const e=await this.http.put(z,{},this.getAdminHeaders());return this.extractData(e)}async enableGlobalStreaming(){const e=await this.http.put(X,{},this.getAdminHeaders());return this.extractData(e)}async setNextLiveStream(e){let t;!function(e){if(bu(e.tokenName),null!==e.nextLiveStreamAt){if(!(e.nextLiveStreamAt instanceof Date||ar(e.nextLiveStreamAt)))throw new _t("nextLiveStreamAt must be a Date, ISO 8601 string, or null","nextLiveStreamAt",kt.INVALID_TYPE);if("string"==typeof e.nextLiveStreamAt){const t=Date.parse(e.nextLiveStreamAt);if(isNaN(t))throw new _t("nextLiveStreamAt must be a valid ISO 8601 date string","nextLiveStreamAt",kt.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,Rr);const t=`/v1/tokens/${e.toLowerCase().trim()}`;await this.http.patch(t,{nextLiveStreamAt:null},this.getJwtHeaders())}async setStreamLanguage(e){ku(e);const t=`/v1/tokens/${e.tokenName.toLowerCase().trim()}`;await this.http.patch(t,{streamLanguage:e.language},this.getJwtHeaders())}async getStreamRole(e){!function(e){bu(e.tokenName)}(e);const t=this.buildEndpoint(Q,{tokenName:e.tokenName}),n=this.jwtAuth?this.getJwtHeaders():{},r=await this.http.get(t,{},n);return this.extractData(r)}async getAvailableRoles(){const e=await this.http.get(Y);return this.extractData(e)}async getTokenAccess(e){!function(e){bu(e.tokenName)}(e);const t=await this.http.get(J,{tokenName:mn(e.tokenName)},this.getJwtHeaders());return this.extractData(t)}async setNextLiveStreamCountdown(e,t){return this.setNextLiveStream({tokenName:e,nextLiveStreamAt:t})}}const Du={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"},Cu=e=>Ru(e.flagId);function Ru(e){return"string"==typeof e||"number"==typeof e?String(e):void 0}function Ou(e,t){const n=t.map(t=>Ru(e[t]));return n.every(e=>void 0!==e)?n.join("|"):void 0}const Mu={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=>Ru(e.id)},FLAG_RESOLVED:{duplicateKey:e=>Ou(e,["id","status","reviewedAt"])},AI_MODERATION_COMPLETE:{duplicateKey:Cu},AI_MODERATION_FAILED:{duplicateKey:Cu},MODERATOR_INVITE_CREATED:{},MODERATOR_ADDED:{},MODERATOR_REMOVED:{},MODERATOR_ROLE_UPDATED:{},OVERSEER_ADDED:{token:"none",duplicateKey:e=>Ou(e,["userAddress","addedAt"])},OVERSEER_REMOVED:{token:"none",duplicateKey:e=>Ou(e,["userAddress","removedAt"])},POOL_CREATED:{duplicateKey:e=>Ou(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 Lu(e){return Mu[e]}const Uu=Object.keys(Mu);const Fu="token:",Pu="comment:",xu="global:feed",Bu="global:events_firehose";function Gu(e){if(e.startsWith(Fu)){const t={tokenName:e.slice(Fu.length)};return{join:{event:Du.SUBSCRIBE,payload:t},leave:{event:Du.UNSUBSCRIBE,payload:t}}}if(e.startsWith(Pu)){const t={tokenName:e.slice(8)};return{join:{event:Du.SUBSCRIBE_COMMENT,payload:t},leave:{event:Du.UNSUBSCRIBE_COMMENT,payload:t}}}return e===Bu?{join:{event:Du.SUBSCRIBE_EVENTS_FIREHOSE},leave:{event:Du.UNSUBSCRIBE_EVENTS_FIREHOSE}}:{join:{event:Du.SUBSCRIBE_GLOBAL_FEED},leave:{event:Du.UNSUBSCRIBE_GLOBAL_FEED}}}const $u=new Set(["token_subscribed","room_subscribed","global_feed_subscribed","events_firehose_subscribed"]);const Ku={STREAM_CHAT_GLOBAL_STATUS:"chatEnabled",STREAM_GLOBAL_STATUS:"streamingEnabled",COMMENTS_GLOBAL_STATUS:"commentsEnabled",WEBHOOKS_GLOBAL_STATUS:"webhooksEnabled",AI_MODERATION_GLOBAL_STATUS:"aiModerationEnabled"},Hu=["STREAM_STATUS","TRADE_EXECUTED","HOLDER_COUNT_UPDATED","POOL_BADGE_ASSIGNED","VIEWER_COUNT","TOKEN_CONFIG_UPDATED","STATS_UPDATED","POOL_CREATED"],Wu=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"]),Vu=new Set(["COMMENT_CREATED","COMMENT_UPDATED","COMMENT_DELETED"]);const ju={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"},qu={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"},zu=()=>{};function Xu(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Qu(e,t){return t}function Yu(e){return`${Fu}${e}`}function Ju(e){return`${Pu}${e}`}function Zu(e){const t=mn(e);if(""===t)throw Wt("tokenName","Token name");return t}class eh extends kr{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 Mt("Stream WebSocket URL is required. Set streamWebSocketUrl in SDK config.");this.config={url:e.url,reconnectAttempts:e.reconnectAttempts??5,reconnectDelay:e.reconnectDelay??2e3,reconnectDelayMax:e.reconnectDelayMax,subscriptionTimeout:e.subscriptionTimeout??1e4,tokenProvider:e.tokenProvider,autoConnect:e.autoConnect??!0},this.isSocketIOAvailable="function"==typeof I}register(e,t,n={}){if(this.disposed)return zu;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 zu;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: ${Ft(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===Bu}(e)&&!this.authenticated)return;this.joinRoom(t,e)}else n||"joined"!==r?.phase||(t.emit(Gu(e).leave.event,Gu(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=Gu(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(Fu)?e.slice(Fu.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((!Xu(t)||!this.isDuplicate(e,t))&&(this.deliver(e,t,Xu(t)?function(e,t){const n=Lu(e).token??"payload";if("none"===n)return;if("room"===n){const e=t.room;return"string"==typeof e&&e.startsWith(Fu)?e.slice(Fu.length):void 0}const r=t.tokenName;return"string"==typeof r&&""!==r?r:void 0}(e,t):void 0),Xu(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=Lu(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:mn(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 $u.has(e)}(e))Xu(t)&&"string"==typeof t.room&&this.onRoomAcknowledged(t.room);else{const n=Ku[e];void 0!==n&&(this.siteConfig={...this.siteConfig,[n]:th(t)})}}liveSocket(){return null!==this.socket&&this.socket.connected?this.socket:null}connect(){if(this.disposed)return Promise.reject(new Mt("The stream WebSocket service has been disposed."));if(!this.isSocketIOAvailable)return Promise.reject(new Mt('Socket.IO not available. Install "socket.io-client" package.'));const e=this.socket??this.createSocket();if(e.connected)return Promise.resolve();if(null===this.connectAttempt){let e=()=>{},t=()=>{};const n=new Promise((n,r)=>{e=n,t=r});this.connectAttempt={promise:n,resolve:e,reject:t}}return e.connect(),this.connectAttempt.promise}createSocket(){this.logger.debug(`🔌 Connecting to Stream WebSocket: ${this.config.url}`);const e=I(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 Uu)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: ${Ft(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?zu:(this.connectionStateListeners.add(e),()=>{this.connectionStateListeners.delete(e)})}onReconnect(e){return this.disposed?zu:(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: ${Ft(e)}`),null}}authenticate(e){if(""===e)return Promise.reject(Wt("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: ${Ft(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(Du.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 _t("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(!this.authenticated)throw new _t("Not authenticated. Call authenticate() first.","auth","NOT_AUTHENTICATED");return e}sendChatMessage(e,t){if(""===e)throw Wt("tokenName","Token name");if(""===t)throw Wt("content","Message content");const n=this.requireReady(),r=mn(e);this.logger.debug(`📡 Sending chat message to ${r}: ${t.slice(0,30)}...`),n.emit(Du.SEND_CHAT,{tokenName:r,content:t})}sendReaction(e,t,n=0){if(""===e)throw Wt("tokenName","Token name");if(""===t)throw Wt("emoji");const r=this.requireReady(),s=mn(e);this.logger.debug(`📡 Sending reaction to ${s}: ${t}`),r.emit(Du.SEND_REACTION,{tokenName:s,emoji:t,streamTime:n})}sendTypingStart(e){this.sendTypingEvent(e,Du.TYPING_START)}sendTypingStop(e){this.sendTypingEvent(e,Du.TYPING_STOP)}sendTypingEvent(e,t){if(""===e)throw Wt("tokenName","Token name");this.requireReady().emit(t,{tokenName:mn(e)})}subscribeToken(e,t,n){const r=Zu(t);return this.register(e,e=>n(Qu(0,e)),{token:r,room:Yu(r)})}joinTokenRoom(e){return this.hold(Yu(Zu(e)))}subscribeComment(e,t,n){const r=Zu(t);return this.register(e,e=>n(Qu(0,e)),{token:r,room:Ju(r)})}subscribeFeed(e,t){return this.register(e,e=>t(Qu(0,e)),{room:xu})}subscribeEvent(e,t){return this.register(e,e=>t(Qu(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:mn(e.tokenName),r=e.userAddress;return void 0!==t||void 0!==n||void 0!==r?e=>{if(!Xu(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||mn(i)!==n))return!1;const o=e.userAddress;return void 0===r||"string"==typeof o&&Cn(o,r)}:void 0}(t);return this.register("EVENT",t=>e(Qu(0,t)),{room:Bu,...void 0!==n&&{filter:n}})}subscribeFeedTokenEvents(e){const t=Hu.map(t=>this.register(t,n=>e(function(e,t){return{event:e,data:Qu(0,t)}}(t,n)),{room:xu}));return()=>{for(const e of t)e()}}subscribeToGlobalFeed(e={}){const t=this.registerCallbacks(e,qu,()=>({})),n=this.hold(xu);return()=>{t(),n()}}addCallbacks(e){return this.registerCallbacks(e,ju,()=>({}))}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=Zu(e),r=Yu(n),s=this.epoch;if(await this.connect(),s!==this.epoch||this.disposed)throw new Error("WebSocket disconnected");const i=this.registerCallbacks(t,ju,e=>{return t=e,Wu.has(t)?{token:n}:function(e){return Vu.has(e)}(e)?{token:n,room:Ju(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=mn(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(Fu)&&e.push(t.slice(Fu.length));return e}isSubscribedToGlobalFeed(){return(this.roomRefs.get(xu)??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 th(e){if(!Xu(e))return;const t=e.enabled;return"boolean"==typeof t?t:void 0}function nh(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 rh(e){return null==e||""===e||"string"==typeof e&&(!Tr(e)&&e.length<=xr.BAN_REASON.MAX_LENGTH)}function sh(e){if(gr(e.tokenName,"tokenName",Dr),!rh(e.reason))throw new _t(`reason must be at most ${xr.BAN_REASON.MAX_LENGTH} characters`,"reason","TOO_LONG")}function ih(e){gr(e.tokenName,"tokenName",Rr)}function oh(e){dr(0,void 0,Lr,e.pageSize)}function ah(e){gr(e.tokenName,"tokenName",Rr)}class ch extends Xo{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async banToken(e){sh(e);const t=Ve,n={tokenName:mn(e.tokenName)};if(void 0!==e.reason)try{er(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:mn(e.tokenName)}}async unbanToken(e){ih(e);const t=this.buildEndpoint(ze,{tokenName:e.tokenName});return on(await this.http.delete(t,void 0,this.getDualAuthHeaders()),"Failed to unban token",!1),{tokenName:mn(e.tokenName)}}async listTokenBans(e={}){oh(e);const t=je,n=this.buildPaginationParams(e,Lr);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){ah(e);const t=this.buildEndpoint(qe,{tokenName:e.tokenName}),n=await this.http.get(t,{},this.getDualAuthHeaders()),r=this.extractDataOrNull(n);return{banned:null!==r,...null!==r&&{ban:r},tokenName:mn(e.tokenName)}}async isTokenBanned(e){return this.getTokenBan(e)}}class lh extends kr{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(!ar(e))throw Wt("tokenName","Token name");const t=mn(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(!ar(e))throw Wt("tokenName","Token name");const t=mn(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 Ht(e);const s=this.parseVaultAddressToTokenClassKey(r);return this.setCacheEntry(t,{vaultAddress:r,tokenClassKey:s,cachedAt:Date.now()}),s}get(e){const t=this.getCacheEntry(mn(e));return t?.vaultAddress??null}getCacheEntry(e){return this.cache.get(e)??null}setCacheEntry(e,t){this.cache.size>=lh.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=mn(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:lh.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(mn(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=mn(t);this.setCacheEntry(e,{vaultAddress:n,tokenClassKey:r,cachedAt:Date.now()})}}parseVaultAddressToTokenClassKey(e){try{return Va(e)}catch(e){if(e instanceof _t)throw Vt("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad","Vault address");throw e}}}lh.MAX_CACHE_SIZE=1e4;class dh extends wr{constructor(e,t=!1){super(e,t)}async fetchLaunchpadFee(){const e=await ln(()=>this.http.get(dt),{errorContext:"Failed to fetch launchpad fee"});if("number"!=typeof e.feeAmount||!Number.isFinite(e.feeAmount))throw new _t("Failed to fetch launchpad fee: no feeAmount in the response","feeAmount","INVALID_RESPONSE");return e.feeAmount}async fetchSaleDetails(e){return ln(()=>this.http.get(ut,{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 co(await ln(()=>void 0===n?this.http.get(ht,t):this.http.request({method:"GET",url:ht,params:t,signal:n}),{errorContext:`Failed to get trade quote for ${e.tokenName}`}),`trade quote for ${e.tokenName}`)}async getPremintQuote(e){return co(await ln(()=>this.http.get(gt,{amount:e}),{errorContext:"Failed to get premint quote"}),"premint quote")}}class uh extends Xo{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async emitTradeExecuted(e,t){this.validateTokenName(e,Mr);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,Mr);const r={action:"balance_updated",userAddress:_n(e,"userAddress"),tokenName:t,payload:n};await this.emitEvent(r)}async emitStreamStatus(e,t,n=!0){this.validateTokenName(e,Mr);const r={action:"stream_status",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitViewerCount(e,t,n=!1){this.validateTokenName(e,Mr);const r={action:"viewer_count",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitStreamCountdown(e,t,n=!0){this.validateTokenName(e,Mr);const r={action:"stream_countdown",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitChatMessage(e,t,n=!1){this.validateTokenName(e,Mr);const r={action:"chat_message",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitChatStatus(e,t,n=!1){this.validateTokenName(e,Mr);const r={action:"chat_status",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitTypingIndicator(e,t,n=!1){this.validateTokenName(e,Mr);const r={action:"typing_indicator",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitTokenBanned(e,t){this.validateTokenName(e,Mr);const n={action:"token_banned",tokenName:e,payload:t,broadcast:!0};await this.emitEvent(n)}async emitTokenUnbanned(e,t){this.validateTokenName(e,Mr);const n={action:"token_unbanned",tokenName:e,payload:t,broadcast:!0};await this.emitEvent(n)}async emitModeratorAdded(e,t,n=!1){this.validateTokenName(e,Mr);const r={action:"moderator_added",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitModeratorRemoved(e,t,n=!1){this.validateTokenName(e,Mr);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:_n(e,"userAddress"),payload:t};await this.emitEvent(n)}async emitSiteConfigChanged(e){const t={action:"site_config_changed",payload:e,broadcast:!0};await this.emitEvent(t)}async emitFeatureStatus(e){const t={action:"feature_status",payload:e,broadcast:!0};await this.emitEvent(t)}async emitEvent(e){this.validateRequiredString(e.action,"action","Event Action");const t=this.buildEndpoint("/v1/websocket",{});await this.http.post(t,e,this.getDualAuthHeaders())}async getConnectedClients(e){const t=this.buildEndpoint("/v1/connected-clients",{}),n={};void 0!==e?.room&&""!==e.room&&(n.room=e.room),void 0!==e?.tokenName&&(n.tokenName=e.tokenName),void 0!==e?.userAddress&&(n.userAddress=kn(e.userAddress,"userAddress")),void 0!==e?.userAddresses&&(n.userAddresses=e.userAddresses.split(",").map(e=>kn(e.trim(),"userAddresses")).join(",")),void 0!==e?.authenticated&&(n.authenticated=e.authenticated),void 0!==e?.isOverseer&&(n.isOverseer=e.isOverseer),void 0!==e?.minConnectionSeconds&&(n.minConnectionSeconds=e.minConnectionSeconds),void 0!==e?.offset&&(n.offset=e.offset),void 0!==e?.limit&&(n.limit=e.limit);const r=await this.http.get(t,Object.keys(n).length>0?n:void 0,this.getDualAuthHeaders());return this.extractData(r)}async isUserOnline(e){this.validateRequiredString(e,"userAddress","User Address");const t=await this.getConnectedClients({userAddress:e,limit:1});if(0===t.clients.length)return{online:!1};const n=t.clients[0];return void 0===n?{online:!1}:{online:!0,socketId:n.socketId,rooms:n.rooms,connectedAt:n.connectedAt}}async getOnlineUsers(e){if(!Array.isArray(e)||0===e.length)throw new Mt("userAddresses must be a non-empty array");const t=await this.getConnectedClients({userAddresses:e.join(","),limit:e.length}),n=t.clients.filter(e=>"string"==typeof e.address&&""!==e.address).map(e=>e.address);return{online:n,offline:e.filter(e=>!n.some(t=>Cn(t,e))),clients:t.clients.map(e=>{const t={socketId:e.socketId,rooms:e.rooms};return"string"==typeof e.address&&(t.address=e.address),t})}}async getTokenViewers(e,t){this.validateTokenName(e,Mr);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,Mr);const n={action:"recording_status",tokenName:e,payload:t};await this.emitEvent(n)}async emitRecordingsCountUpdated(e,t){this.validateTokenName(e,Mr);const n={action:"recordings_count_updated",tokenName:e,payload:t};await this.emitEvent(n)}async emitDownloadReady(e,t){this.validateTokenName(e,Mr);const n={action:"download_ready",tokenName:e,payload:t};await this.emitEvent(n)}}class hh{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 gh{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 mh extends kr{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 hh({maxAttempts:this.config.reconnectAttempts??5,baseDelayMs:this.config.reconnectDelay??2e3}),this.eventBuffer=new gh(3e4),this.isSocketIOAvailable=this.checkSocketIOAvailability(),mh.instances.add(this)}checkSocketIOAvailability(){try{return"function"==typeof I||(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)=>{bo(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:",Ft(e)),e}this.logger.debug("🔌 Connecting to Socket.IO server:",this.config.url),this.socket=I(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=Ut(e)?e:new Error(Ft(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:Co.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:Co.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;ar(o)||(o=i===Do.FAILED||i===Do.ERROR?"Transaction failed - check transaction details":i===Do.COMPLETED||i===Do.PROCESSED||i===Do.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===Co.COMPLETED||d.status===Co.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===Co.COMPLETED?t(e):e.status!==Co.FAILED&&e.status!==Co.TIMEOUT||n(new Error(`Transaction ${String(e.status)}: ${e.message}`))})})}mapSocketStatus(e){const t=e?.toUpperCase();return Ro[t]??Co.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")),mh.instances.delete(this)}static cleanupAll(e=!1){for(const e of mh.instances)e.disconnect();mh.instances.clear()}isConnected(){return this.socket?.connected??!1}getSocket(){return this.socket}}mh.instances=new Set;class fh extends wr{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 _t("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(mt.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 _t("vaultAddress is required","vaultAddress","REQUIRED_FIELD");this.logger.debug("Fetching token weekly history",{vaultAddress:t});const n=mt.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 ph=["CreateSale","BuyWithNative","BuyExactToken","SellWithNative","SellExactToken"];class Eh{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 Ah{constructor(e){this.bundleBaseUrl=Ih(e.bundleBaseUrl),this.launchpadBaseUrl=Ih(e.launchpadBaseUrl),this.signer=e.signer,this.walletAddress=""===e.walletAddress?"":kn(e.walletAddress,"walletAddress"),this.requestor=e.httpRequestor??fetch.bind(globalThis),this.socketFactory=e.socketFactory??(e=>I(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 Th("bundleId");if(i=n,!ph.some(e=>e===i))throw Th("method");var i;if("string"!=typeof r||""===r)throw Th("uniqueKey");if(void 0!==s&&("string"!=typeof s||""===s))throw Th("tokenName");if("CreateSale"===n&&void 0===s)throw Th("tokenName");const o={method:n,dto:{uniqueKey:r,...void 0===s?{}:{tokenName:s}},stringsInstructions:[]};return new Eh({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,d("asset/launchpad-contract",e.method,e.dto))}catch(e){throw function(e){if(e instanceof Da)return e;if(m(e)){const t=e instanceof Error?e.message:"The signature was rejected in the wallet.",n=f(e);return new Da(t,"WALLET_USER_REJECTED",{details:void 0===n?{}:{walletCode:n}})}const t=e instanceof Error?e.message:"Launchpad signing failed.";return new Da(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 kh(s);if(!s.ok)throw Sh(s.status,i,r);const o=function(e){if("string"==typeof e&&""!==e)return e;if(!_h(e))throw new Da("Bundler returned no bundle id.","INVALID_BUNDLE_RESPONSE");const t=e.data,n=e.bundleId;if("string"==typeof t&&""!==t)return t;if(_h(t)&&"string"==typeof t.bundleId&&""!==t.bundleId)return t.bundleId;if("string"==typeof n&&""!==n)return n;throw new Da("Bundler returned no bundle id.","INVALID_BUNDLE_RESPONSE")}(i),a=wh(e.dto,"uniqueKey");return new Eh({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(vh(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(vh(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 Da(`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(!_h(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(yh(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=wh(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 yh(e.data);a("read-failed"===e.kind?e.error:void 0);const c=s-(Date.now()-r);if(c<=0)break;await Dh(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 kh(r);if("CreateSale"===e.method)return r.ok?{kind:"processed",result:{status:"PROCESSED",data:Nh(s)}}:404===r.status||202===r.status?{kind:"pending"}:{kind:"read-failed",error:Sh(r.status,s,t)};if(!r.ok)return{kind:"read-failed",error:Sh(r.status,s,t)};const i=_h(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 Da(n,"BUNDLE_REQUEST_FAILED",{details:{url:t}})}}}}function vh(e,t){return new Da("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 Th(e){return new Da(`Cannot attach to a launchpad bundle: ${e} is missing or not accepted.`,"INVALID_BUNDLE_ATTACHMENT",{details:{field:e}})}function yh(e){const t=bh(e)??"Launchpad bundle failed on chain.";return new Da(t,"BUNDLE_FAILED",{chainMessage:t})}function Sh(e,t,n){const r=bh(t)??`Bundle request failed with HTTP ${e}`;return new Da(r,"BUNDLE_REQUEST_FAILED",{status:e,chainMessage:r,details:{body:t,url:n}})}function bh(e){if("string"==typeof e&&""!==e)return e;if(_h(e))for(const t of["chainMessage","message","Message","error"]){const n=e[t];if("string"==typeof n&&""!==n)return n;if(_h(n)){const e=bh(n);if(void 0!==e)return e}}}function Nh(e){return _h(e)?e.data??e.Data??e:e}function wh(e,t){const n=e[t];if("string"!=typeof n||""===n)throw new Da(`Missing ${t} in launchpad DTO.`,"INVALID_LAUNCHPAD_DTO");return n}async function kh(e){try{return await e.json()}catch{return e.text()}}function _h(e){return"object"==typeof e&&null!==e}function Ih(e){return e.replace(/\/$/u,"")}function Dh(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 Ch(e,t){if(!/^\d+(\.\d+)?$/.test(e))throw new _t(`Quoted reverse bonding curve fee is not a non-negative number: ${e}`,"extraFees","INVALID_QUOTED_FEE");if(!Number.isFinite(t)||t<0)throw new _t(`Fee slippage factor must be a non-negative number, got ${String(t)}`,"maxAcceptableReverseBondingCurveFeeSlippageFactor","INVALID_FEE_SLIPPAGE_FACTOR");return new D(e).multipliedBy(new D(1).plus(new D(String(t)))).decimalPlaces(8,D.ROUND_UP).toFixed()}function Rh(e){return async t=>{const n=t.tokenName??await async function(e,t){const n=Ga(t).type,r=await e.findTokenNameByVault(t,n);if(void 0===r)throw new _t(`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 Ch((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 Oh={minFeePortion:"0.1",maxFeePortion:"0.5"},Mh=/^(?:\d+\.?\d*|\.\d+)$/u,Lh=/^[0-9A-Z]+$/u,Uh=/^[A-Za-z0-9]+$/u,Fh=new D("0.1"),Ph=new D("0.5");function xh(e){if("string"!=typeof e||!Mh.test(e))return;const t=new D(e);return t.isFinite()?t.toFixed():void 0}function Bh(e){return"string"==typeof e&&""!==e}function Gh(e,t,n){void 0!==n&&"string"!=typeof n&&e.push(`${t} must be a string`)}function $h(e,t,n){void 0===n||Bh(n)||e.push(`${t} must be a non-empty string`)}function Kh(e){const t=[];if("object"!=typeof e||null===e)throw new _t("CreateSale input must be an object","data","VALIDATION_ERROR");const n={...e},r=n.tokenName;Bh(r)?Uh.test(r)||t.push("Token name can only contain letters and numbers"):t.push("Token name is required");const s=n.tokenSymbol;Bh(s)?Lh.test(s.toUpperCase())||t.push("Token symbol can only contain letters and numbers"):t.push("Token symbol is required");const i=n.tokenDescription;Bh(i)?i.length>1e3&&t.push("Token description must be at most 1000 characters"):t.push("Token description is required");const o=n.tokenImage;Bh(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===xh(a)&&t.push("preBuyQuantity must be a non-negative decimal number");for(const e of["websiteUrl","telegramUrl","twitterUrl","instagramUrl","facebookUrl","redditUrl","tiktokUrl"])Gh(t,e,n[e]);$h(t,"tokenCategory",n.tokenCategory),$h(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??Oh.minFeePortion,s=n.maxFeePortion??Oh.maxFeePortion,i=xh(r),o=xh(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 D(i),c=new D(o);a.isLessThan(Fh)&&e.push("minFeePortion must be greater than or equal to 0.1"),c.isGreaterThan(Ph)&&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 _t(t.join("; "),"data","VALIDATION_ERROR")}class Hh{constructor(e){this.transport=e.transport,this.walletAddress=""===e.walletAddress?"":kn(e.walletAddress,"walletAddress"),this.sellFeeCeiling=e.sellFeeCeiling}createSale(e){Kh(e);const t=function(e,t){const n={tokenName:e.tokenName,tokenSymbol:e.tokenSymbol,tokenDescription:e.tokenDescription,tokenImage:e.tokenImage,preBuyQuantity:xh(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??Wh(t)},r=e.reverseBondingCurveConfiguration;n.reverseBondingCurveConfiguration={minFeePortion:xh(r?.minFeePortion??Oh.minFeePortion),maxFeePortion:xh(r?.maxFeePortion??Oh.maxFeePortion)},void 0!==e.saleStartTime&&(n.saleStartTime=e.saleStartTime);return n}(e,this.walletAddress);return this.transport.submit({method:"CreateSale",dto:t,stringsInstructions:Ka(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??Wh(this.walletAddress)};return this.transport.submit({method:e,dto:r,stringsInstructions:$a(t.vaultAddress)})}async defaultExtraFees(e,t){if("BuyWithNative"===e||"BuyExactToken"===e)return{maxAcceptableReverseBondingCurveFee:"0"};if(void 0===this.sellFeeCeiling)throw new _t("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 Wh(e){return`galaswap-operation-${_()}-${Date.now()}-${e}`}function Vh(e,t=3e4){return C.create({baseURL:e,timeout:t,headers:{"Content-Type":"application/json"}})}const jh=new Set(["accesstoken","refreshtoken","token","password","privatekey","secret","apikey","api_key","rawkey","authorization","x-api-key","bearer","streamadminapikey","userapikey","signature","signedpayload"]);function qh(e,t=0){if(t>5)return"[...]";if(null==e)return e;if(Array.isArray(e))return e.map(e=>qh(e,t+1));if(e instanceof Map){const n={};for(const[r,s]of e.entries()){const e=String(r);n[e]=jh.has(e.toLowerCase())?"[REDACTED]":qh(s,t+1)}return n}if("object"==typeof e){const n={};for(const[r,s]of Object.entries(e))n[r]=jh.has(r.toLowerCase())?"[REDACTED]":qh(s,t+1);return n}return e}class zh{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 An({debug:this.debug,context:"HttpClient"});const r=t.baseUrl??Io("stage").launchpadBaseUrl,s=t.timeout??6e4;this.axios=Vh(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 bo(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]":qh(e.data);this.logger.debug("Request:",{method:e.method,url:e.url?.split("?")[0],baseURL:this.axios.defaults.baseURL,params:qh(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:qh(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:_l(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 R(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 bo(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??Ft(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 Xh extends Error{constructor(e,t){super(e),this.cause=t,this.name="WebSocketError"}}class Qh extends Xh{constructor(e,t){super(`WebSocket confirmation timeout for transaction ${e} after ${t}ms`),this.name="WebSocketTimeoutError"}}class Yh 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 Jh(e,t){if(lr(e))throw new Xh(`Invalid WebSocket response received for transaction ${t}: response is null or undefined`);if("object"!=typeof e)throw new Xh(`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 Xh(`Invalid WebSocket response received for transaction ${t}: missing status field`)}function Zh(e,t,n,r){Jh(e,t);const s=e,i=s.data??{};if(!function(e){if(lr(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 Xh(`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 eg(e){return void 0!==e&&N(e)?new y(e.exportPrivateKey()):void 0}const tg={MUSIC:"$MUSIC",GMUSIC:"$GMUSIC"};function ng(e){if(void 0===e||!("walletAddress"in e))return;const t=e.walletAddress;return"string"==typeof t&&""!==t?t:void 0}const rg=/^(?:eth\||0x)([0-9a-fA-F]{40})$/;function sg(e,t,n){if(void 0===e||void 0===t)return;const r=rg.exec(e)?.[1],s=rg.exec(t)?.[1];if(void 0!==r&&void 0!==s&&r.toLowerCase()!==s.toLowerCase())throw qt(`${n} ${t} is not the identity of the configured signing key (${e}); writes would be signed as the key, not as ${n}.`,n)}class ig{constructor(e){let t,n;this.walletGeneration=0,e.walletProvider?(t=e.walletProvider,n=eg(e.walletProvider)):e.wallet&&(n=e.wallet,t=b.fromWallet(e.wallet)),this.wallet=n;const r=e.env??"prod",s=Io(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 Pa(n.privateKey):void 0),o=void 0!==n?`eth|${n.address.slice(2)}`:ng(i),a=void 0===e.walletAddress?void 0:kn(e.walletAddress,"walletAddress"),c=void 0===e.galaChainAddress?void 0:kn(e.galaChainAddress,"galaChainAddress");sg(o,a,"walletAddress"),sg(o,c,"galaChainAddress");const l=a??c??(void 0!==n?`eth|${n.address.slice(2)}`:ng(i)),d=i??{signObject:()=>Promise.reject(new Error("A signer is required for token writes.")),signTypedData:()=>Promise.reject(new Error("A signer is required for launchpad writes."))},u=l??"";this.tokenWriter=void 0===n&&void 0!==e.signer&&void 0!==l?{signer:e.signer,walletAddress:l}:void 0;const h=new Ah({bundleBaseUrl:this.config.bundleBaseUrl,launchpadBaseUrl:this.config.baseUrl,signer:d,walletAddress:u,...void 0!==e.httpRequestor&&{httpRequestor:e.httpRequestor},bundleSocketFactory:e.bundleSocketFactory}),g=Rh({getTradeQuote:e=>this.tradingQuotesService.getTradeQuote(e),findTokenNameByVault:(e,t)=>this.findTokenNameByVault(e,t),defaultFeeSlippageFactor:()=>this.maxAcceptableReverseBondingCurveFeeSlippageFactor});this.sellFeeCeiling=g,this.launchpad=new Hh({transport:h,walletAddress:u,sellFeeCeiling:g}),this.logger=new An({debug:this.config.debug??!1,context:"LaunchpadSDK"}),this.validateConfiguration(),this.slippageToleranceFactor=void 0===e.slippageToleranceFactor?ig.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR:this.parseSlippageToleranceFactor(e.slippageToleranceFactor),this.maxAcceptableReverseBondingCurveFeeSlippageFactor=void 0===e.maxAcceptableReverseBondingCurveFeeSlippageFactor?ig.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR:this.parseFeeSlippageFactor(e.maxAcceptableReverseBondingCurveFeeSlippageFactor),this.calculateAmountMode=e.calculateAmountMode??ig.DEFAULT_CALCULATE_AMOUNT_MODE,this.galaChainAddressOverride=c,this.signerWalletAddress=a??(void 0===n?l:void 0),this.auth=new ko({wallet:n,walletProvider:t,messagePrefix:"Create a GalaChain Wallet"});const m=e.session;if(void 0!==m){if(!function(e){if("object"!=typeof e||null===e)return!1;const t=e,n=t.credentials;return"function"==typeof t.accessToken&&"function"==typeof t.onUnauthorized&&(void 0===n||"include"===n||"omit"===n)}(m))throw qt("session must provide accessToken() and onUnauthorized()","session");if(void 0!==e.accessToken&&""!==e.accessToken)throw qt("Pass either session or accessToken, not both: the session owns the token.","accessToken")}if(this.jwtAuth=void 0===m?new yo:new So,void 0!==e.accessToken&&""!==e.accessToken){const t=e.accessTokenExpiresIn??86400;this.jwtAuth.setToken(e.accessToken,t)}this.http=new zh(this.auth,this.config,{signRequests:!0,session:m}),this.sessionAuth=new wo(this.http,this.auth,this.jwtAuth,e.debug??!1,m);const f={signRequests:!1};this.galaChainHttp=new zh(this.auth,{...this.config,baseUrl:this.config.gatewayBaseUrl},f),this.bundleHttp=new zh(this.auth,{...this.config,baseUrl:this.config.bundleBaseUrl},f),this.dexApiHttp=new zh(this.auth,{...this.config,baseUrl:this.config.dexApiBaseUrl},f),this.dexBackendHttp=new zh(this.auth,{...this.config,baseUrl:this.config.dexBackendBaseUrl},f),this.galaChainPublicAxios=Vh(this.config.gatewayBaseUrl,this.config.timeout??3e4),this.cache=new Ir(e.debug??!1),this.launchpadService=new td(this.http,this.jwtAuth),this.tokenResolverService=new lh(this.launchpadService.poolService),this.launchpadAPI=new po(this.http,this.logger,this.bundleHttp,this.calculateAmountMode,this.launchpad),this.galaChainService=new Tl(this.galaChainHttp,n,this.tokenResolverService,e.debug??!1,this.galaChainPublicAxios,this.tokenWriter),this.priceService=new Sc(this.dexBackendHttp,this.cache,e=>this.galaChainService.fetchTokenDetails(e),e.debug??!1),this.bundleService=this.createBundleService(),this.websocketService=new mh({url:this.config.webSocketUrl},this.config.debug),this.nftCollectionService=new Bd(this.galaChainHttp),this.tradingQuotesService=new dh(this.http,e.debug??!1)}createOverrideSdk(e){if(!ar(e))throw qt("Invalid privateKey: must be a non-empty string","privateKey");if(!e.match(/^0x[a-fA-F0-9]{64}$/))throw qt('Invalid privateKey format: must be "0x" followed by 64 hexadecimal characters',"privateKey");const t=new y(e),n={...this.config,wallet:t};return new ig(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 Wt("wallet","Wallet");return this.wallet}assertTokenWriter(){if(void 0===this.wallet&&void 0===this.tokenWriter)throw Wt("wallet","Wallet")}setWallet(e){if(null==e||"object"!=typeof e||!("address"in e))throw new _t("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 tc(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 Tl(this.galaChainHttp,this.wallet,this.tokenResolverService,this.config.debug??!1,this.galaChainPublicAxios)}setWalletProvider(e){this.auth.setWalletProvider(e),this.wallet=e?eg(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:gn.GAS_FEE}}getVersion(){return Oo}getUrlByTokenName(e){const t=this.config.launchpadFrontendUrl;if(void 0===t||""===t)throw qt("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=_n(t,"userAddress"),r=await this.fetchTokenDistribution(e),s=r.holders.findIndex(e=>e.address.toLowerCase()===n);if(-1===s)return null;const i=r.holders[s];return void 0===i?null:{rank:s+1,balance:i.balance,holderCount:r.totalHolders}}async getHoldersByBalance(e,t){const n=await this.fetchTokenDistribution(e),r=t?.minBalance??0,s=t?.maxBalance??1/0,i=Math.min(t?.limit??100,1e3),o=new Map;return n.holders.forEach((e,t)=>{o.set(e.address,t+1)}),n.holders.filter(e=>{const t=parseFloat(e.balance);return t>=r&&t<=s}).map(e=>({...e,rank:o.get(e.address)??0})).slice(0,i)}async getHolderHistory(e,t,n=20){return this.getTrades({tokenName:e,userAddress:t,pageSize:Math.min(n,100)})}async fetchUserHolderContext(e,t){return this.launchpadService.fetchUserHolderContext(e,t)}async fetchTokenPrice(e){const t="object"==typeof e&&null!==e?e:{};if(void 0!==t.tokenId)throw new _t("fetchTokenPrice prices a launchpad token by tokenName; a token by class key is priced by gswap-sdk (gSwap.market.getPrice)","tokenId",kt.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 Wn}),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(qt("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,qt(`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: ${Ft(e)}`,"bridge")})),this.coreBridgeLoad)}async coreBridge(){const e=this.walletGeneration,t=await this.loadCoreBridge();if(e!==this.walletGeneration)throw qt("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 Pa(t.privateKey)}})}return this._wrapService}getStreamingService(){return this._streamingService??(this._streamingService=new Iu(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._streamingService}getStreamChatService(){return this._streamChatService??(this._streamChatService=new au(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._streamChatService}getBanService(){return this._banService??(this._banService=new Ta(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._banService}getTokenBanService(){return this._tokenBanService??(this._tokenBanService=new ch(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._tokenBanService}getAIModerationService(){return this._aiModerationService??(this._aiModerationService=new Qo(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._aiModerationService}getWeeklyChallengeService(){return this._weeklyChallengeService??(this._weeklyChallengeService=new fh(this.http,this.config.debug??!1)),this._weeklyChallengeService}getOEmbedService(){return this._oembedService??(this._oembedService=new $d(this.http,this.config.debug??!1)),this._oembedService}getPlatformStatsService(){return this._platformStatsService??(this._platformStatsService=new iu(this.http,this.config.debug??!1)),this._platformStatsService}getHealthService(){return this._healthService??(this._healthService=new yl(this.http,this.config.debug??!1)),this._healthService}getEventsQueryService(){return this._eventsQueryService??(this._eventsQueryService=new Mc(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._eventsQueryService}getNotificationService(){return this._notificationService??(this._notificationService=new Gd(this.http,this.config.debug??!1,this.jwtAuth)),this._notificationService}getClientConfigService(){return this._clientConfigService??(this._clientConfigService=new nc(this.http,this.config.debug??!1)),this._clientConfigService}getApiKeyService(){return this._apiKeyService??(this._apiKeyService=new la(this.http,this.jwtAuth,this.config.debug??!1)),this._apiKeyService}getModeratorService(){return this._moderatorService??(this._moderatorService=new Rd(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._moderatorService}getFlagService(){return this._flagService??(this._flagService=new pc(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._flagService}getOverseerService(){return this._overseerService??(this._overseerService=new nu(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._overseerService}getWebSocketAdminService(){return this._websocketAdminService??(this._websocketAdminService=new uh(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._websocketAdminService}getContentReactionService(){return this._contentReactionService??(this._contentReactionService=new vc(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._contentReactionService}buildMessageFetchOptions(e,t){return{type:t,...void 0!==e.tokenName&&{tokenName:e.tokenName},...void 0!==e.userAddress&&{userAddress:e.userAddress},...void 0!==e.cursor&&{cursor:e.cursor},...void 0!==e.pageSize&&{pageSize:e.pageSize}}}resolveReferralAddress(e){return void 0===e||""===e?this.getAddress():kn(e,"address")}getMessagesService(){return this._messagesService??(this._messagesService=new md(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._messagesService}getRestrictedNamesService(){return this._restrictedNamesService??(this._restrictedNamesService=new ou(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.userApiKey)),this._restrictedNamesService}getPlatformConfigService(){return this._platformConfigService??(this._platformConfigService=new su(this.http,this.jwtAuth,this.config.debug??!1)),this._platformConfigService}getEventsBatcherService(){return this._eventsBatcherService??(this._eventsBatcherService=new wc(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 eh({url:this.config.streamWebSocketUrl,tokenProvider:()=>this.streamSocketToken(),...void 0!==this.config.streamReconnectAttempts&&{reconnectAttempts:this.config.streamReconnectAttempts},...void 0!==this.config.streamReconnectDelay&&{reconnectDelay:this.config.streamReconnectDelay},...void 0!==this.config.streamReconnectDelayMax&&{reconnectDelayMax:this.config.streamReconnectDelayMax}},this.config.debug??!1)}return this._streamWebSocketService}async streamSocketToken(){const e=this.config.session;return void 0!==e?e.accessToken():this.ensureValidToken()}get realtime(){return this.getStreamWebSocketService()}async fetchEthereumWalletTokenBalance(e,t){return this.getBridgeService(await this.coreBridge()).fetchEthereumWalletTokenBalance(e,t)}async fetchEthereumWalletNativeBalance(e){return this.getBridgeService(await this.coreBridge()).fetchEthereumWalletNativeBalance(e)}async fetchSolanaWalletTokenBalance(e,t){return this.getBridgeService(await this.coreBridge()).fetchSolanaWalletTokenBalance(e,t)}async fetchSolanaWalletNativeBalance(e){return this.getBridgeService(await this.coreBridge()).fetchSolanaWalletNativeBalance(e)}async requestSolanaDevnetAirdrop(e,t){return this.getBridgeService(await this.coreBridge()).requestSolanaDevnetAirdrop(e,t)}async getSolanaTransactionStatus(e){return this.getBridgeService(await this.coreBridge()).getSolanaTransactionStatus(e)}async getEthereumTransactionStatus(e){return this.getBridgeService(await this.coreBridge()).getEthereumTransactionStatus(e)}async fetchEthereumWalletAllBalances(e){return this.getBridgeService(await this.coreBridge()).fetchEthereumWalletAllBalances(e)}async fetchSolanaWalletAllBalances(e){return this.getBridgeService(await this.coreBridge()).fetchSolanaWalletAllBalances(e)}async fetchBridgeableTokensByNetwork(e){return this.getBridgeableTokenService(await this.coreBridge()).fetchBridgeableTokensByNetwork(e)}async fetchAllBridgeableTokensByNetwork(e){return this.getBridgeableTokenService(await this.coreBridge()).fetchAllBridgeableTokensByNetwork(e)}async fetchAllTokensBridgeableToEthereum(){return this.getBridgeableTokenService(await this.coreBridge()).fetchAllTokensBridgeableToEthereum()}async fetchAllTokensBridgeableToSolana(){return this.getBridgeableTokenService(await this.coreBridge()).fetchAllTokensBridgeableToSolana()}async isTokenBridgeableToNetwork(e){return this.getBridgeableTokenService(await this.coreBridge()).isTokenBridgeableToNetwork(e)}async isTokenBridgeableToEthereum(e){return this.getBridgeableTokenService(await this.coreBridge()).isTokenBridgeableToEthereum(e)}async isTokenBridgeableToSolana(e){return this.getBridgeableTokenService(await this.coreBridge()).isTokenBridgeableToSolana(e)}async fetchWrappableTokens(e={}){return this.getWrappableTokenService(await this.coreBridge()).fetchWrappableTokens(e)}async fetchAllWrappableTokens(){return this.getWrappableTokenService(await this.coreBridge()).fetchAllWrappableTokens()}async getWrappableToken(e){return this.getWrappableTokenService(await this.coreBridge()).getWrappableToken(e)}async getWrapCounterpart(e){return this.getWrappableTokenService(await this.coreBridge()).getWrapCounterpart(e)}async isTokenWrappable(e){return this.getWrappableTokenService(await this.coreBridge()).isTokenWrappable(e)}async wrapToken(e){return this.getWrapService(await this.coreBridge()).wrapToken(e)}async unwrapToken(e){return this.getWrapService(await this.coreBridge()).unwrapToken(e)}async estimateWrapFee(e,t){return this.getWrapService(await this.coreBridge()).estimateWrapFee(e,t)}async estimateUnwrapFee(e,t){return this.getWrapService(await this.coreBridge()).estimateUnwrapFee(e,t)}async login(){return this.sessionAuth.login()}async loginWithSignature(e){return this.sessionAuth.loginWithSignature(e)}async loginWithDevBypass(e){return this.sessionAuth.loginWithDevBypass(e)}async refreshToken(){return this.sessionAuth.refresh()}async logout(e){return this.sessionAuth.logout(e)}isAuthenticated(){return this.sessionAuth.isAuthenticated()}shouldRefreshToken(e){return this.sessionAuth.shouldRefresh(e)}async getSession(){return this.sessionAuth.getSession()}getAccessToken(){return this.sessionAuth.getAccessToken()}async ensureValidToken(e){return this.sessionAuth.ensureValidToken(e)}async startStream(e){return this.getStreamingService().startStream(e)}async stopStream(e){return this.getStreamingService().stopStream(e)}async disableStream(e){return this.getStreamingService().disableStream(e)}async enableStream(e){return this.getStreamingService().enableStream(e)}async resetStreamKey(e){return this.getStreamingService().resetStreamKey(e)}async getStreamCredentials(e){return this.getStreamingService().getStreamCredentials(e)}async getStreamRecordings(e){return this.getStreamingService().getRecordings(e)}async getRecordingDownload(e,t){return this.getStreamingService().getRecordingDownload(e,t)}async deleteRecording(e,t){return this.getStreamingService().deleteRecording(e,t)}async getSimulcastTargets(e){return this.getStreamingService().getSimulcastTargets(e)}async addSimulcastTarget(e){return this.getStreamingService().addSimulcastTarget(e)}async removeSimulcastTarget(e,t){return this.getStreamingService().removeSimulcastTarget(e,t)}async getGlobalStreamingStatus(){return this.getStreamingService().getGlobalStreamingStatus()}async setNextLiveStreamCountdown(e,t){return this.getStreamingService().setNextLiveStreamCountdown(e,t)}async setGlobalStreamingEnabled(e){const t=this.getStreamingService();return e?t.enableGlobalStreaming():t.disableGlobalStreaming()}async getStreamRole(e){return this.getStreamingService().getStreamRole(e)}async getAvailableRoles(){return this.getStreamingService().getAvailableRoles()}async getTokenAccess(e){return this.getStreamingService().getTokenAccess(e)}async getChatStatus(e){return this.getStreamChatService().getChatStatus(e)}async disableChat(e){return this.getStreamChatService().disableChat(e)}async enableChat(e){return this.getStreamChatService().enableChat(e)}async getPinnedChatMessage(e){const t=this.getMessagesService();return{tokenName:e,pinnedMessage:(await t.getPinnedMessage(e)).message}}async pinChatMessage(e,t){const n=this.getMessagesService();await n.pinMessage(t);return{tokenName:e,pinnedMessage:(await n.getPinnedMessage(e)).message}}async unpinChatMessage(e){const t=this.getMessagesService(),n=await t.getPinnedMessage(e);return n.message?(await t.unpinMessage(n.message.messageId),{tokenName:e,unpinned:!0,unpinnedMessageId:n.message.messageId}):{tokenName:e,unpinned:!1}}async setSlowMode(e,t){return this.getStreamChatService().setSlowMode(e,t)}async createBan(e){return this.getBanService().createBan(e)}async removeBan(e){return this.getBanService().removeBan(e)}async listBans(e){return this.getBanService().listBans(e)}async getBanStatus(e){return this.getBanService().getBanStatus(e)}async getActiveUsers(e){return this.getBanService().getActiveUsers(e)}async createGlobalBan(e){return this.getBanService().createGlobalBan(e)}async removeGlobalBan(e){return this.getBanService().removeGlobalBan(e)}async listGlobalBans(e){return this.getBanService().listGlobalBans(e)}async getGlobalBan(e){return this.getBanService().getGlobalBan(e)}async createApiKey(e){return this.getApiKeyService().create(e)}async listApiKeys(e={}){return this.getApiKeyService().findAll(e)}async getApiKey(e){return this.getApiKeyService().findOne(e)}async updateApiKey(e,t){return this.getApiKeyService().update(e,t)}async revokeApiKey(e){return this.getApiKeyService().revoke(e)}getApiKeyRoles(){return this.getApiKeyService().getRoles()}async createModeratorInvite(e){return this.getModeratorService().createInvite(e)}async claimModeratorInvite(e){return this.getModeratorService().claimInvite(e)}async getModeratedTokens(e){return this.getModeratorService().getModeratedTokens(e)}async listModeratorInvites(e){return this.getModeratorService().listInvites(e)}async getActiveModerators(e){return(await this.listModeratorInvites({tokenName:e,status:"CLAIMED"})).items.filter(e=>null!==e.claimedBy).map(e=>({address:e.claimedBy,role:e.role,joinedAt:e.claimedAt,inviteId:e.id}))}async revokeModeratorInvite(e){return this.getModeratorService().revokeInvite(e)}async updateModeratorInviteRole(e){return this.getModeratorService().updateInviteRole(e)}async updateModeratorInvite(e){return this.getModeratorService().updateInvite(e)}async getModeratorInviteByCode(e){return this.getModeratorService().getInviteByCode(e)}async createFlag(e){return this.getFlagService().createFlag(e)}async listFlags(e){return this.getFlagService().listFlags(e)}async listGlobalFlags(e={}){return this.getFlagService().listGlobalFlags(e)}async dismissFlag(e){return this.getFlagService().dismissFlag(e)}async actionFlag(e){return this.getFlagService().actionFlag(e)}async createOverseerInvite(e={}){return this.getOverseerService().createInvite(e)}async listOverseerInvites(e={}){return this.getOverseerService().listInvites(e)}async getOverseerInviteByCode(e){return this.getOverseerService().getInviteByCode(e)}async claimOverseerInvite(e){return this.getOverseerService().claimInvite(e)}async revokeOverseerInvite(e){return this.getOverseerService().revokeInvite(e)}async listOverseers(e={}){return this.getOverseerService().listOverseers(e)}async createOverseerDirect(e){return this.getOverseerService().createOverseerDirect(e)}async revokeOverseer(e){return this.getOverseerService().revokeOverseer(e)}async getMyOverseerStatus(){return this.getOverseerService().getMyStatus()}async getOverseerSummary(){return this.getOverseerService().getSummary()}async getBanStats(){return this.getOverseerService().getBanStats()}async getTokenBanStats(){return this.getOverseerService().getTokenBanStats()}async getInviteStats(){return this.getOverseerService().getInviteStats()}async getFlagStats(){return this.getOverseerService().getFlagStats()}async getUserStats(){return this.getOverseerService().getUserStats()}async listOverseerUsers(e){return this.getOverseerService().listOverseerUsers(e)}async getOverseerUserSummary(e){return this.getOverseerService().getOverseerUserSummary(e)}async flushCacheByAddress(e){return this.getOverseerService().flushCacheByAddress(e)}async flushCacheByToken(e){return this.getOverseerService().flushCacheByToken(e)}async flushAllCache(e){return this.getOverseerService().flushAllCache(e)}async flushWalletAliasCache(e){return this.getOverseerService().flushWalletAliasCache(e)}async emitWebSocketEvent(e){return this.getWebSocketAdminService().emitEvent(e)}async emitTradeExecuted(e,t){return this.getWebSocketAdminService().emitTradeExecuted(e,t)}async emitBalanceUpdated(e,t,n){return this.getWebSocketAdminService().emitBalanceUpdated(e,t,n)}async emitStreamStatus(e,t){return this.getWebSocketAdminService().emitStreamStatus(e,t)}async emitViewerCount(e,t){return this.getWebSocketAdminService().emitViewerCount(e,t)}async emitStreamCountdown(e,t){return this.getWebSocketAdminService().emitStreamCountdown(e,t)}async emitChatMessage(e,t){return this.getWebSocketAdminService().emitChatMessage(e,t)}async emitChatStatus(e,t){return this.getWebSocketAdminService().emitChatStatus(e,t)}async emitTypingIndicator(e,t){return this.getWebSocketAdminService().emitTypingIndicator(e,t)}async emitTokenBanned(e,t){return this.getWebSocketAdminService().emitTokenBanned(e,t)}async emitTokenUnbanned(e,t){return this.getWebSocketAdminService().emitTokenUnbanned(e,t)}async emitModeratorAdded(e,t){return this.getWebSocketAdminService().emitModeratorAdded(e,t)}async emitModeratorRemoved(e,t){return this.getWebSocketAdminService().emitModeratorRemoved(e,t)}async emitUserProfileUpdated(e,t){return this.getWebSocketAdminService().emitUserProfileUpdated(e,t)}async emitSiteConfigChanged(e){return this.getWebSocketAdminService().emitSiteConfigChanged(e)}async emitFeatureStatus(e){return this.getWebSocketAdminService().emitFeatureStatus(e)}async emitRecordingStatus(e,t){return this.getWebSocketAdminService().emitRecordingStatus(e,t)}async emitRecordingsCountUpdated(e,t){return this.getWebSocketAdminService().emitRecordingsCountUpdated(e,t)}async emitDownloadReady(e,t){return this.getWebSocketAdminService().emitDownloadReady(e,t)}async getConnectedClients(e){return this.getWebSocketAdminService().getConnectedClients(e)}async isUserOnline(e){return this.getWebSocketAdminService().isUserOnline(e)}async getOnlineUsers(e){return this.getWebSocketAdminService().getOnlineUsers(e)}async getTokenViewers(e,t){return this.getWebSocketAdminService().getTokenViewers(e,t)}async getOnlineOverseers(){return this.getWebSocketAdminService().getOnlineOverseers()}async banToken(e){return this.getTokenBanService().banToken(e)}async unbanToken(e){return this.getTokenBanService().unbanToken(e)}async listTokenBans(e={}){return this.getTokenBanService().listTokenBans(e)}async getTokenBan(e){return this.getTokenBanService().getTokenBan(e)}async isTokenBanned(e){return this.getTokenBanService().isTokenBanned(e)}async getAIModerationSettings(){return this.getAIModerationService().getSettings()}async updateAIModerationSettings(e){return this.getAIModerationService().updateSettings(e)}async getAIModeration(e){return this.getAIModerationService().getModeration(e)}async triggerAIModeration(e){return this.getAIModerationService().triggerModeration(e)}async getAIModerationStatus(){return this.getAIModerationService().getStatus()}async getWeeklyChallengeLeaderboard(e={}){return this.getWeeklyChallengeService().getLeaderboard(e)}async getTokenWeeklyHistory(e){return this.getWeeklyChallengeService().getTokenHistory(e)}async getHomeOEmbed(e={}){return this.getOEmbedService().getHomeOEmbedJson(e)}async getPoolOEmbed(e){return this.getOEmbedService().getPoolOEmbedJson(e)}async getProfileOEmbed(e){return this.getOEmbedService().getProfileOEmbedJson(e)}async getPlatformStats(){return this.getPlatformStatsService().getStats()}async getHealth(){return this.getHealthService().getHealth()}async getEventStats(){return this.getEventsQueryService().getEventStats()}async queryEvents(e={}){return this.getEventsQueryService().queryEvents(e)}async registerPushToken(e){return this.getNotificationService().registerPushToken(e)}async unregisterPushToken(e){return this.getNotificationService().unregisterPushToken(e)}async fetchNotificationPreferences(){return this.getNotificationService().getPreferences()}async updateNotificationPreferences(e){return this.getNotificationService().updatePreferences(e)}async fetchClientFlags(){return this.getClientConfigService().getClientFlags()}async addContentReaction(e){return this.getContentReactionService().addContentReaction(e)}async removeContentReaction(e){return this.getContentReactionService().removeContentReaction(e)}async addReactionToChatMessage(e){return this.getContentReactionService().addReactionToChatMessage(e)}async removeReactionFromChatMessage(e){return this.getContentReactionService().removeReactionFromChatMessage(e)}async addReactionToComment(e){return this.getContentReactionService().addReactionToComment(e)}async removeReactionFromComment(e){return this.getContentReactionService().removeReactionFromComment(e)}async getComments(e){const t=this.buildMessageFetchOptions(e,"COMMENT"),n=await this.fetchMessages(t);return{messages:n.messages,pageInfo:n.pageInfo}}async createComment(e){return{comment:(await this.createMessage({type:"COMMENT",tokenName:e.tokenName,content:e.content})).message}}async updateComment(e,t){return{comment:(await this.updateMessage(e,{content:t.content,type:"COMMENT"})).message}}async deleteComment(e){return{success:(await this.deleteMessage(e)).success}}async getChatMessages(e){const t=this.buildMessageFetchOptions(e,"CHAT_MESSAGE"),n=await this.fetchMessages(t);return{messages:n.messages,pageInfo:n.pageInfo}}async sendChatMessage(e){return{message:(await this.createMessage({type:"CHAT_MESSAGE",tokenName:e.tokenName,content:e.content})).message}}async updateChatMessage(e,t){return{message:(await this.updateMessage(e,{content:t.content,type:"CHAT_MESSAGE"})).message}}async deleteChatMessage(e){await this.deleteMessage(e)}async fetchMessages(e){return this.getMessagesService().fetchMessages(e)}async createMessage(e){return this.getMessagesService().createMessage(e)}async updateMessage(e,t){return this.getMessagesService().updateMessage(e,t)}async deleteMessage(e){return this.getMessagesService().deleteMessage(e)}async getPinnedMessage(e){return this.getMessagesService().getPinnedMessage(e)}async pinMessage(e){return this.getMessagesService().pinMessage(e)}async unpinMessage(e){return this.getMessagesService().unpinMessage(e)}async getMessageStats(){return this.getMessagesService().getMessageStats()}async getPlatformConfig(){return this.getPlatformConfigService().getPlatformConfig()}async updatePlatformConfig(e){return this.getPlatformConfigService().updatePlatformConfig(e)}async getRestrictedNames(){return this.getRestrictedNamesService().getRestrictedNames()}async updateRestrictedNames(e){return this.getRestrictedNamesService().updateRestrictedNames(e)}async updateTokenConfig(e,t){return this.launchpadService.poolService.updateTokenConfig(e,t)}async getTokenConfig(e){return this.launchpadService.poolService.getTokenConfig(e)}async getTrades(e){return this.launchpadService.getTrades(e)}async getRecentTrades(e,t=50){return this.getTrades({...void 0!==e&&{tokenName:e},pageSize:Math.min(t,500)})}async getPoolRealtimeState(e){const[t,n,r,s]=await Promise.allSettled([this.getHolderCount(e),this.getTokenConfig(e),this.getRecentTrades(e,10),this.fetchTokenPrice({tokenName:e})]);return{tokenName:e,holderCount:"fulfilled"===t.status?t.value:null,..."rejected"===t.status&&{holderCountError:String(t.reason)},chatConfig:"fulfilled"===n.status?n.value:null,..."rejected"===n.status&&{chatConfigError:String(n.reason)},recentTrades:"fulfilled"===r.status?r.value:null,..."rejected"===r.status&&{recentTradesError:String(r.reason)},price:"fulfilled"===s.status?s.value:null,..."rejected"===s.status&&{priceError:String(s.reason)}}}async fetchLaunchpadFee(){return this.tradingQuotesService.fetchLaunchpadFee()}async fetchSaleDetails(e){return this.tradingQuotesService.fetchSaleDetails(e)}async getTradeQuote(e){return this.tradingQuotesService.getTradeQuote(e)}async getPremintQuote(e){return this.tradingQuotesService.getPremintQuote(e)}async connectStreamWebSocket(e){const t=this.getStreamWebSocketService();await t.connect(),e&&t.addCallbacks(e)}async authenticateStreamWebSocket(e){return this.getStreamWebSocketService().authenticate(e)}deauthenticateStreamWebSocket(){this._streamWebSocketService?.deauthenticate()}async subscribeToStream(e,t){return this.getStreamWebSocketService().subscribeToStream(e,t)}unsubscribeFromStream(e){this.getStreamWebSocketService().unsubscribeFromStream(e)}sendStreamChatViaWebSocket(e,t){this.getStreamWebSocketService().sendChatMessage(e,t)}sendStreamReaction(e,t,n=0){this.getStreamWebSocketService().sendReaction(e,t,n)}sendTypingStart(e){return this.getStreamWebSocketService().sendTypingStart(e)}sendTypingStop(e){return this.getStreamWebSocketService().sendTypingStop(e)}disconnectStreamWebSocket(){this._streamWebSocketService&&this._streamWebSocketService.disconnect()}isStreamWebSocketConnected(){return!!this._streamWebSocketService&&this._streamWebSocketService.isConnected()}onStreamStatusChanged(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_STATUS",e)}onUserBanned(e){return this.getStreamWebSocketService().subscribeEvent("USER_BANNED",e)}onUserUnbanned(e){return this.getStreamWebSocketService().subscribeEvent("USER_UNBANNED",e)}onBanEnforcement(e){return this.getStreamWebSocketService().subscribeEvent("BAN_ENFORCEMENT",e)}watchBanEnforcement(e,t={}){const n=(e,n,r,s)=>(void 0===t.actionType||t.actionType===e)&&(!!(void 0===t.userAddress||null!==n&&Cn(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||Cn(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||Cn(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&&!Cn(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 Wn}),n=t(e.address);if(void 0!==e.tokenId&&""!==e.tokenId){const{normalizeToTokenInstanceKey:t}=await Promise.resolve().then(function(){return Ja}),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=pn(e.tokenName),r=tg[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:Ha(r)}}throw Wt("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 zt("No transaction ID returned from buy operation");return this.waitForConfirmation(n,t=>Zh(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 zt("No transaction ID returned from sell operation");return this.waitForConfirmation(n,t=>Zh(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=>{Jh(n,t);const r=n.data??{};if(!function(e){if(lr(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 Xh(`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 Wn}),n=t(e)??this.getAddress();return this.launchpadService.fetchProfile(n)}async fetchReferralUrl(){this.validateWallet();const e=this.getAddress();return await this.dexApiHttp.get(M,void 0,{"x-wallet-address":e})}async fetchReferrals(e){const t=this.resolveReferralAddress(e?.address),n=e?.page??1,r=e?.limit??10,s={pageNumber:n,limit:r,sortBy:e?.sortBy??"joined",sortDir:e?.sortDir??"desc"},i=await this.dexApiHttp.get(L,s,{"x-wallet-address":t});if(!Array.isArray(i))throw new Ot("Unexpected API response: expected array, got "+typeof i);return{referrals:i,page:n,limit:r,hasMore:i.length===r}}async fetchAllReferrals(e){const t=await async function(e,t={}){const{maxPages:n=1e4,logger:r,pageSize:s=20,concurrency:i=1,startPage:o=1}=t,a=[];let c=o;const l=o+n-1;let d=!0,u=0;if(i<=1)for(;d&&c<=l;){r&&r.debug(`Auto-pagination: fetching page ${c} with limit ${s}`);const t=await e(c,s);if(null==t||!Array.isArray(t.items)){r&&r.warn("Auto-pagination: received invalid result structure, stopping");break}if(a.push(...t.items),u=t.total,r&&r.debug(`Auto-pagination: page ${c} returned ${t.items.length} items, hasNext: ${String(t.hasNext)}`),0===t.items.length){r&&r.debug(`Auto-pagination: no items returned on page ${c}, exiting loop`);break}d=t.hasNext,c++}else for(r&&r.debug(`Auto-pagination: using concurrent mode with concurrency=${i}`);d&&c<=l;){const t=[];for(let e=0;e<i&&c+e<=l;e++)t.push(c+e);r&&r.debug(`Auto-pagination: fetching pages ${t.join(", ")} concurrently`);const n=t.map(t=>e(t,s).catch(e=>{const n=e,i=n.statusCode??n.response?.status??n.originalError?.response?.status??n.status??n.launchpadError?.statusCode;if(400===i||404===i)return r&&r.debug(`Auto-pagination: page ${t} returned ${i} (end of pagination)`,{statusCode:i}),{items:[],total:0,totalPages:0,page:t,limit:s,hasNext:!1,hasPrevious:!1};throw e})),o=await Promise.all(n);for(const e of o){if(null==e||!Array.isArray(e.items)){r&&r.warn("Auto-pagination: received invalid result structure in batch, stopping"),d=!1;break}if(0===e.items.length){r&&r.debug("Auto-pagination: empty page in batch, reached end of results"),d=!1;break}if(a.push(...e.items),u=e.total,!e.hasNext){d=!1;break}}c+=t.length,r&&r.debug(`Auto-pagination: batch complete, total items so far: ${a.length}`)}return c>l&&r&&r.warn(`Auto-pagination: exceeded maxPages limit of ${n} (maxPage=${l}), stopping iteration`),r&&r.debug(`Auto-pagination: completed with total items: ${a.length}, total count: ${u}`),{items:a,total:u}}((t,n)=>this.fetchReferrals({...e,page:t,limit:n}).then(e=>({items:e.referrals,page:e.page,limit:e.limit,total:0,totalPages:0,hasNext:e.hasMore,hasPrevious:e.page>1})),{maxPages:100,pageSize:100,logger:this.logger});return{referrals:t.items,total:t.items.length}}async fetchReferralsSummary(e){const t=this.resolveReferralAddress(e?.address),n=await this.dexApiHttp.get(U,void 0,{"x-wallet-address":t});if(void 0===n||"number"!=typeof n.referralCount||void 0===n.rewardTotals)throw new Ot(`Unexpected API response: expected { referralCount, rewardTotals }, got ${JSON.stringify(n)}`);return n}async updateProfile(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Wn}),{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 Wn}),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 Wn}),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 Wn}),n={type:"created",address:t(e?.address)??this.getAddress(),pageSize:e?.pageSize??10};return void 0!==e?.cursor&&(n.cursor=e.cursor),void 0!==e?.tokenName&&""!==e.tokenName&&(n.tokenName=e.tokenName),void 0!==e?.search&&""!==e.search&&(n.search=e.search),void 0!==e?.status&&(n.status=e.status),this.launchpadService.fetchTokenList(n)}async getManagedTokens(e){return this.launchpadService.getManagedTokens(e??{})}async 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 Wn}),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 Wn}),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 Wn});return{...e,lockAuthority:t(e.lockAuthority)}}return e})),n={...e,tokens:t};if(void 0!==n.privateKey&&""!==n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...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=Ko(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{Yn(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 qt("baseUrl is required in configuration","baseUrl");if(void 0===this.config.webSocketUrl||""===this.config.webSocketUrl)throw qt("webSocketUrl is required in configuration","webSocketUrl");try{new URL(this.config.baseUrl)}catch{throw qt(`Invalid baseUrl format: ${this.config.baseUrl}`,"baseUrl")}try{new URL(this.config.webSocketUrl)}catch{throw qt(`Invalid webSocketUrl format: ${this.config.webSocketUrl}`,"webSocketUrl")}if(void 0!==this.config.gatewayBaseUrl&&""!==this.config.gatewayBaseUrl)try{new URL(this.config.gatewayBaseUrl)}catch{throw qt(`Invalid gatewayBaseUrl format: ${this.config.gatewayBaseUrl}`,"gatewayBaseUrl")}if(void 0!==this.config.bundleBaseUrl&&""!==this.config.bundleBaseUrl)try{new URL(this.config.bundleBaseUrl)}catch{throw qt(`Invalid bundleBaseUrl format: ${this.config.bundleBaseUrl}`,"bundleBaseUrl")}if(void 0!==this.config.launchpadFrontendUrl&&""!==this.config.launchpadFrontendUrl)try{new URL(this.config.launchpadFrontendUrl)}catch{throw qt(`Invalid launchpadFrontendUrl format: ${this.config.launchpadFrontendUrl}`,"launchpadFrontendUrl")}}parseSlippageToleranceFactor(e){const t=Vn("string"==typeof e||"number"==typeof e?e:String(e),ig.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR);return t<0||t>1?(this.logger.warn(`Invalid slippage tolerance factor: ${String(e)}, using default: ${ig.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR}`),ig.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR):t}parseFeeSlippageFactor(e){const t=Vn("string"==typeof e||"number"==typeof e?e:String(e),ig.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: ${ig.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR}`),ig.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!==Co.COMPLETED)throw new Yh(e,n.status,n.message);let r;try{r=t(n)}catch(t){if(t instanceof Xh)throw t;throw new Xh(`Failed to transform WebSocket response for transaction ${e}`,Ut(t)?t:new Error(Ft(t)))}return this.logger.debug(`Transaction confirmed: ${e}`,r),r}catch(t){if(this.logger.error(`Transaction confirmation failed: ${e}`,t),t instanceof Yh||t instanceof Xh)throw t;throw new Xh(`WebSocket confirmation failed for transaction ${e}`,Ut(t)?t:new Error(Ft(t)))}}async warmCacheFromPools(e){if(void 0===e||!Array.isArray(e))return;const{extractMetadataFromPoolData:t,isValidPoolForCaching:n}=await Promise.resolve().then(function(){return Ef});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=Ft(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 qt("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: ${Ft(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: ${Ft(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<ig.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS)return e++,void(r=setTimeout(()=>o(),ig.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS));if(!i&&e>=ig.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS){const e=new Error(`WebSocket not available after ${ig.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS*ig.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 An({debug:e,context:"LaunchpadSDK"});t.debug("Starting global cleanup..."),mh.cleanupAll(e),t.debug("Global cleanup completed")}}function og(e){lr(e)&&(e={});const{wallet:t,env:n,config:r={},...s}=e,i={...{...s,...r}};delete i.wallet,delete i.env,delete i.config;const o=!lr(i.signer)||!lr(i.walletProvider);let a;if(lr(t))a=o?void 0:new y(p().privateKey);else if("string"==typeof t)a=new y(p(t).privateKey);else{if(!(t instanceof y))throw qt("Invalid wallet input. Expected string (private key or mnemonic) or Wallet instance.","wallet");a=t}const c={...void 0!==a?{wallet:a}:{},...void 0!==n?{env:n}:{},debug:!1,timeout:3e4,...i};return new ig(c)}function ag(e){const t=p(e);return{...t,wallet:new y(t.privateKey)}}function cg(){const e=globalThis;return e.process?.env??{}}ig.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR=.15,ig.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR=.01,ig.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY=gn.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY,ig.DEFAULT_CALCULATE_AMOUNT_MODE=wt.LOCAL,ig.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS=30,ig.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS=100;class lg{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 ig(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 ig(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=Vn(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: ${Ft(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: ${Ft(e)}`)}return{ready:0===n.length&&s.connectionHealthy,sdk:e,wallet:t??ag(),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"===(cg().LAUNCHPAD_ENV??cg().ENVIRONMENT)?"stage":"prod"}static setupWallet(e){if(void 0===e||""===e){const e=cg().PRIVATE_KEY;return void 0!==e&&""!==e?ag(e):ag()}return"generate"===e?ag():ag(e)}static buildSdkConfig(e,t,n){const r=e.galaChainAddress??cg().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 Io(e).launchpadBaseUrl}static getDefaultTimeout(e){switch(e){case"prod":return 3e4;case"stage":return 45e3}}static getEnvironmentDefaults(e){const t=Io(e);return{bundleBaseUrl:t.bundleBaseUrl,gatewayBaseUrl:t.gatewayBaseUrl}}}function dg(e,t,n){const r="number"==typeof e?new D(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 D(t).plus(new D(s).multipliedBy(r))}function ug(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 hg(e,t,n=60){const r=Yi(e),s=Yi(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(Zi(r)),o=Math.ceil(Zi(s)),a=Math.floor(i/n)*n,c=Math.ceil(o/n)*n;return{minTick:a,maxTick:c,actualMinPrice:new D(1.0001).pow(a),actualMaxPrice:new D(1.0001).pow(c)}}function gg(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 mg(e,t){if(t<0)throw new Error(`decimals must be >= 0, got: ${t}`);const n=Yi(e),r=new D(10).pow(t);return n.multipliedBy(r).integerValue(D.ROUND_UP).dividedBy(r)}function fg(e,t,n,r="0"){const s=Yi(t);if(eo(s))return Yi(r);const i=Yi(e).dividedBy(s);if(null!=n){const e=Yi(n);if(e.isLessThan(0))throw new Error(`minimum must be >= 0, got: ${e.toString()}`);if(i.isLessThan(e))return e}return i}function pg(e,t){if(t<=0)throw new Error(`tickSpacing must be > 0, got: ${t}`);return Math.floor(e/t)*t}function Eg(e,t){if(t<0)throw new Error(`feeFactor must be >= 0, got: ${t}`);return Yi(e).multipliedBy(t).integerValue(D.ROUND_DOWN)}function Ag(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 vg(e){if(null==e||"object"!=typeof e)throw new Error("Token must be an object");const t=e,n=(ar(t.name)?t.name:void 0)??(ar(t.tokenName)?t.tokenName:void 0)??"";if(!ar(n))throw new Error("Token name is required and must be a non-empty string");const r=(ar(t.symbol)?t.symbol:void 0)??(ar(t.tokenSymbol)?t.tokenSymbol:void 0)??"";if(!ar(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 ar(t.address)&&(i.address=t.address),"boolean"==typeof t.verified&&(i.verified=t.verified),i}function Tg(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(ar(n))return n;if(null!=n&&""!==n)return n}return n}function yg(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 Sg(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 bg(e,t){const n={...e};for(const[e,r]of Object.entries(t))void 0!==r&&(n[e]=r);return n}class Ng{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 wg{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 kg{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 _g{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: ${Ft(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}: ${Ft(t)}`)}}clear(){this.globalCallbacks=[],this.roomCallbacks.clear()}clearRoom(e){this.roomCallbacks.delete(e)}}class Ig{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 Dg{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 Cg{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 Rg{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 Og=5,Mg=8,Lg=18,Ug={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"},Fg=5,Pg=5;function xg(e){const t={};return void 0!==e.cursor&&(t.cursor=e.cursor),void 0!==e.pageSize&&(t.pageSize=e.pageSize),t}function Bg(e,t){return xg({...e,...t})}function Gg(e,t){return void 0===t?e:{...e,cursor:t}}function $g(e){return"string"==typeof e?e:"number"==typeof e||"boolean"==typeof e||"bigint"==typeof e?String(e):JSON.stringify(e)??""}async function Kg(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} - ${Ft(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}: ${Ft(e)}`)}}return s?.debug(`Batch complete: ${o} succeeded, ${a} failed`),i}function Hg(e){const t={page:1,pageSize:20,totalCount:-1,hasMore:!1};if(null==e||"object"!=typeof e)return t;const n=e,r=jn($g(n.page??n.Page??n.current??1),t.page),s=jn($g(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:jn($g(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 Wg(e){if(null==e||"object"!=typeof e)return"";const t=[];for(const[n,r]of Object.entries(e)){if(cr(r))continue;let e;e="string"==typeof r?r:"number"==typeof r||"boolean"==typeof r?String(r):Array.isArray(r)?r.map(e=>$g(e)).join(","):$g(r);const s=encodeURIComponent(n),i=encodeURIComponent(e);t.push(`${s}=${i}`)}return t.length>0?`?${t.join("&")}`:""}async function Vg(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=zg(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 jg(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 qg(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} - ${Ft(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 zg(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 Xg(e){const t=e.trim().toLowerCase();if(0===t.length)throw new Error("Token name cannot be empty");return t}function Qg(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 Yg(e,t){return`${e.replace(/\/$/,"")}${t}`}function Jg(e,t){const n=Xg(e);return Yg(t,`/v1/tokens/${encodeURIComponent(n)}/assets/image`)}function Zg(e,t,n="jpg"){const r=Xg(e);Qg(n);return Yg(t,`/v1/tokens/${encodeURIComponent(r)}/assets/thumbnail.${n.toLowerCase()}`)}function em(e,t,n="gif"){const r=Xg(e);Qg(n);return Yg(t,`/v1/tokens/${encodeURIComponent(r)}/assets/animated.${n.toLowerCase()}`)}function tm(e,t){const n=Xg(e);return Yg(t,`/v1/tokens/${encodeURIComponent(n)}/assets/poster.jpg`)}function nm(e,t,n="vtt"){const r=Xg(e);Qg(n);return Yg(t,`/v1/tokens/${encodeURIComponent(r)}/assets/storyboard.${n.toLowerCase()}`)}function rm(e,t){const n=Xg(e);return Yg(t,`/v1/tokens/${encodeURIComponent(n)}/assets/live.m3u8`)}function sm(e,t,n,r){const s=Xg(e),i=t.trim().toLowerCase();if(0===i.length)throw new Error("Asset type cannot be empty");Qg(r);const o=void 0!==r&&r.length>0?`.${r.toLowerCase()}`:"";return Yg(n,`/v1/tokens/${encodeURIComponent(s)}/assets/${encodeURIComponent(i)}${o}`)}function im(e,t,n,r="jpg"){const s=Xg(e),i=t.trim();if(0===i.length)throw new Error("Recording ID cannot be empty");Qg(r);return Yg(n,`/v1/tokens/${encodeURIComponent(s)}/recordings/${encodeURIComponent(i)}/assets/thumbnail.${r.toLowerCase()}`)}function om(e,t,n,r="gif"){const s=Xg(e),i=t.trim();if(0===i.length)throw new Error("Recording ID cannot be empty");Qg(r);return Yg(n,`/v1/tokens/${encodeURIComponent(s)}/recordings/${encodeURIComponent(i)}/assets/animated.${r.toLowerCase()}`)}function am(e,t,n){const r=Xg(e),s=t.trim();if(0===s.length)throw new Error("Recording ID cannot be empty");return Yg(n,`/v1/tokens/${encodeURIComponent(r)}/recordings/${encodeURIComponent(s)}/assets/poster.jpg`)}function cm(e,t,n,r="vtt"){const s=Xg(e),i=t.trim();if(0===i.length)throw new Error("Recording ID cannot be empty");Qg(r);return Yg(n,`/v1/tokens/${encodeURIComponent(s)}/recordings/${encodeURIComponent(i)}/assets/storyboard.${r.toLowerCase()}`)}function lm(e,t,n){const r=Xg(e),s=t.trim();if(0===s.length)throw new Error("Recording ID cannot be empty");return Yg(n,`/v1/tokens/${encodeURIComponent(r)}/recordings/${encodeURIComponent(s)}/assets/stream.m3u8`)}function dm(e,t,n,r,s){const i=Xg(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");Qg(s);const c=void 0!==s&&s.length>0?`.${s.toLowerCase()}`:"";return Yg(r,`/v1/tokens/${encodeURIComponent(i)}/recordings/${encodeURIComponent(o)}/assets/${encodeURIComponent(a)}${c}`)}const um=new Map;function hm(e,t){const n=e;return um.set(n,{createdAt:Date.now(),label:t}),n}function gm(e){const t=e;um.delete(t)}function mm(){const e=um.size;return um.clear(),e}function fm(){const e=Array.from(um.entries()).map(([e,t])=>({id:e,...t}));return{size:um.size,entries:e}}class pm extends wr{constructor(e,t=!1){super(e,t)}async getChart(e){if(null==e)throw Wt("options","Chart options");const{tokenName:t,from:n,to:r,resolution:s}=e;if(null==t||""===t)throw Wt("tokenName","Token name");if(null==n)throw Wt("from","Start timestamp");if(null==r)throw Wt("to","End timestamp");if(null==s)throw Wt("resolution","Data resolution interval");gr(t,"tokenName",Dr);const i=173e6;if("number"!=typeof n||n<i)throw new _t("from must be a valid timestamp (min: 173000000)","from","INVALID_TIMESTAMP");if("number"!=typeof r||r<i)throw new _t("to must be a valid timestamp (min: 173000000)","to","INVALID_TIMESTAMP");if("number"!=typeof s||s<1)throw new _t("resolution must be a number >= 1","resolution","INVALID_RESOLUTION");const{adaptQueryParams:o}=await Promise.resolve().then(function(){return Il}),a=o({tokenName:t,from:n,to:r,resolution:s}),c=await un(()=>this.http.get(O.CHART,a),{errorContext:"Failed to fetch chart data"}),l=an(c);if(null==l||"object"!=typeof l)throw jt("Invalid API response: missing or invalid data",c.status??500);const d=l,u=d.data;if(!Array.isArray(u))throw jt("Invalid API response: expected data array",c.status??500);const h={dataPoints:u.map(e=>{if("object"!=typeof e||null===e)throw jt("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 Em={NEW_HOLDER:"NEW_HOLDER",EXITED_HOLDER:"EXITED_HOLDER",BALANCE_CHANGED:"BALANCE_CHANGED"},Am=Xi({type:"string",userAddress:"string",balance:"string",rank:"number",previousRank:"optional-number"}),vm=Xi({tokenName:"string",userAddress:"string",quantity:"optional-string",percentage:"optional-number",holderTier:"optional-object",isCreator:"boolean",rank:"optional-number"});function Tm(e){return"string"==typeof e&&(e===Em.NEW_HOLDER||e===Em.EXITED_HOLDER||e===Em.BALANCE_CHANGED)}Rr.MIN_LENGTH,Rr.MAX_LENGTH,Rr.PATTERN;ur({ENABLED:"ENABLED",DISABLED:"DISABLED",ADMIN_DISABLED:"ADMIN_DISABLED"});function ym(e){return"global"===e||"token"===e}function Sm(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 bm(e){return Sm(e)}function Nm(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.message}function wm(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 km(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 _m(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&km(t.pinnedMessage)}function Im(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.unpinnedMessageId}function Dm(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"boolean"==typeof t.enabled&&(void 0===t.reason||ym(t.reason))}function Cm(e){return!!ar(e)&&(e.length>=xr.CHAT_MESSAGE.MIN_LENGTH&&e.length<=xr.CHAT_MESSAGE.MAX_LENGTH)}function Rm(e){return!!ar(e)&&Rr.PATTERN.test(e)}function Om(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 Mm(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.message}const Lm=ur({RATE_LIMITED:"RATE_LIMITED",INVALID_EMOJI:"INVALID_EMOJI",NOT_AUTHENTICATED:"NOT_AUTHENTICATED",STREAM_NOT_LIVE:"STREAM_NOT_LIVE"});function Um(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 Fm(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&Array.isArray(t.typingUsers)&&t.typingUsers.every(Um)}const Pm={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 xm,Bm,Gm,$m,Km,Hm;!function(e){e.PENDING="PENDING",e.PROCESSING="PROCESSING",e.COMPLETED="COMPLETED",e.FAILED="FAILED"}(xm||(xm={})),function(e){e.TEXT="TEXT",e.IMAGE="IMAGE",e.VIDEO="VIDEO"}(Bm||(Bm={})),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"}(Gm||(Gm={})),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"}($m||($m={})),function(e){e.QUICK="QUICK",e.DETAILED="DETAILED"}(Km||(Km={})),function(e){e.DISABLED="DISABLED",e.ADVISORY="ADVISORY"}(Hm||(Hm={}));const Wm={[xm.PENDING]:"Pending",[xm.PROCESSING]:"Processing",[xm.COMPLETED]:"Completed",[xm.FAILED]:"Failed"},Vm={[Gm.NO_ACTION]:"No Action Needed",[Gm.REVIEW_REQUIRED]:"Human Review Required",[Gm.DELETE_CONTENT]:"Delete Content",[Gm.BAN_USER]:"Ban User",[Gm.DELETE_AND_BAN]:"Delete & Ban"},jm={[$m.VIOLENCE]:"Violence",[$m.HATE_SPEECH]:"Hate Speech",[$m.SEXUAL_CONTENT]:"Sexual Content",[$m.HARASSMENT]:"Harassment",[$m.SPAM]:"Spam",[$m.SCAM]:"Scam",[$m.SELF_HARM]:"Self Harm",[$m.ILLEGAL_ACTIVITY]:"Illegal Activity",[$m.MISINFORMATION]:"Misinformation",[$m.COPYRIGHT]:"Copyright",[$m.SAFE]:"Safe"},qm={[Km.QUICK]:"Quick Scan",[Km.DETAILED]:"Detailed Scan"},zm={[Bm.TEXT]:"Text",[Bm.IMAGE]:"Image",[Bm.VIDEO]:"Video"},Xm={[Hm.DISABLED]:"Disabled",[Hm.ADVISORY]:"Advisory"},Qm=ur(xm),Ym=ur(Bm),Jm=ur(Gm),Zm=ur($m),ef=ur(Km),tf=ur(Hm),nf=Er([{field:"id",type:"number"},{field:"flagId",type:"number"},{field:"status",type:"string",validator:Qm},{field:"analysisType",type:"string",validator:Ym},{field:"provider",type:"string"}]),rf=Er([{field:"enabled",type:"boolean"},{field:"mode",type:"string",validator:tf},{field:"provider",type:"string"}]);function sf(e){return null!==e.analysisTier}function of(e){return!0===e.escalatedFromQuick}function af(e,t){if(!sf(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 cf(e){if(!(void 0!==e.tokenName&&""!==e.tokenName||void 0!==e.userAddress&&""!==e.userAddress))throw tn(["tokenName","userAddress"]);void 0!==e.tokenName&&""!==e.tokenName&&pr(e.tokenName,"tokenName",Dr),dr(0,void 0,Fr,e.pageSize,e.cursor)}function lf(e){if(!ar(e.tokenName))throw Wt("tokenName","Token name");pr(e.tokenName,"tokenName",Dr),uf(e.content)}function df(e){uf(e.content)}function uf(e){if(!ar(e))throw Wt("content");if(0===e.trim().length)throw rn("content","Content");if(e.length>xr.COMMENTS_V1.MAX_LENGTH)throw nn("content",xr.COMMENTS_V1.MAX_LENGTH,e.length)}function hf(e){if(!(void 0!==e.tokenName&&""!==e.tokenName||void 0!==e.userAddress&&""!==e.userAddress))throw new _t("At least one of tokenName or userAddress is required","options",kt.REQUIRED);nd(e.tokenName,e.userAddress),void 0!==e.pageSize&&dr(0,void 0,Fr,e.pageSize)}function gf(e){if(!ar(e.tokenName))throw Wt("tokenName");pr(e.tokenName,"tokenName",Dr),ff(e.content)}function mf(e){ff(e.content)}function ff(e){if(!ar(e))throw Wt("content");if(0===e.trim().length)throw new _t("content cannot be empty","content",kt.REQUIRED);if(e.length>xr.CHAT_MESSAGES_V1.MAX_LENGTH)throw new _t(`content must be at most ${xr.CHAT_MESSAGES_V1.MAX_LENGTH} characters`,"content",kt.TOO_LONG)}function pf(e){if(!ar(e))throw Wt("id","Message ID");if(!Br.CHAT_MESSAGE.PATTERN.test(e))throw new _t("Invalid message ID format. Expected: chat-{timestamp}-{uuid}","id",kt.INVALID_FORMAT)}var Ef=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=Vn(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=Vn(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{ua as ACTIVE_USER_TYPE,Hm as AIModerationMode,Gm as AIRecommendation,Xm as AI_MODE_LABELS,Vm as AI_RECOMMENDATION_LABELS,ta as ALL_PERMISSIONS,jm as ANALYSIS_CATEGORY_LABELS,Wm as ANALYSIS_STATUS_LABELS,qm as ANALYSIS_TIER_LABELS,zm as ANALYSIS_TYPE_LABELS,Zo as API_KEY_PERMISSION,Yo as API_KEY_ROLE,Jo as API_KEY_ROLES,aa as API_KEY_ROLE_HIERARCHY,On as AddressFormatter,lg as AgentConfig,$m as AnalysisCategory,xm as AnalysisStatus,Km as AnalysisTier,Bm as AnalysisType,To as AuthError,vo as AuthErrorType,da as BAN_DURATIONS,Ba as BrowserWalletSigner,Eh as BundleSubmission,Ah as BundlerTransport,ul as BurnError,dl as BurnErrorType,wt as CALCULATION_MODES,Ec as CONTENT_REACTION_TYPES,oc as CONTENT_TYPE_LABELS,pm as ChartService,Mt as ConfigurationError,za as ContentType,bc as DEFAULT_EVENTS_CONFIG,Fg as DEFAULT_PRICING_CONCURRENCY,Oh as DEFAULT_REVERSE_BONDING_CURVE_CONFIGURATION,Pg as DEFAULT_WEBSOCKET_RECONNECT_ATTEMPTS,_o as ENVIRONMENT_URLS,kt as ERROR_CODES,kc as EVENT_SORT_FIELDS,Ic as EVENT_SOURCES,_c as EVENT_TIME_PRESETS,Nc as EVENT_TYPES,Tu as EXTENDED_STREAM_ROLE,Cg as EventBufferWithAutoCleanup,wc as EventsBatcherService,Mc as EventsQueryService,ic as FLAG_ACTION_LABELS,ac as FLAG_DETAILS_MAX_LENGTH,rc as FLAG_REASON_LABELS,sc as FLAG_STATUS_LABELS,Sl as FileValidationError,Ya as FlagAction,Xa as FlagReason,Qa as FlagStatus,Mg as GALA_DECIMALS,xa as GalaWalletSigner,_g as GlobalAndRoomCallbackDispatcher,Em as HOLDER_DELTA_TYPES,yl as HealthService,Ss as IMAGE_EXTENSIONS,vd as INVITE_STATUS,Td as INVITE_STATUSES,Eo as JWT_CONSTANTS,Lg as LAUNCHPAD_TOKEN_DECIMALS,ph as LAUNCHPAD_WRITE_METHODS,ig as LaunchpadSDK,Da as LaunchpadSDKError,Hh as LaunchpadWrites,Dg as ListenerCleanupManager,Vc as LockError,Hc as LockErrorType,ll as MAX_BURN_BATCH_SIZE,Og as MAX_CONCURRENT_POOL_FETCHES,$c as MAX_LOCK_BATCH_SIZE,Kc as MAX_UNLOCK_BATCH_SIZE,sd as MESSAGES_CONSTRAINTS,rd as MESSAGE_TYPES,fd as MODERATOR_ROLE,pd as MODERATOR_ROLES,Od as NFT_FEES,Ot as NetworkError,Bd as NftCollectionService,$d as OEmbedService,Hd as OVERSEER_INVITE_STATUS,Wd as OVERSEER_STATUS,Mo as PAGINATION_DEFAULTS,ea as PERMISSION,Lo as POOL_FETCH_CONFIG,St as POOL_FETCH_TYPES,Nt as POOL_LIST_MAX_PAGE_SIZE,bt as POOL_STREAM_STATUSES,yt as POOL_TYPES,wg as PayloadWalkerWithDeduplication,kg as PendingSubscriptionTracker,iu as PlatformStatsService,Pa as PrivateKeySigner,Ug as QUERY_FIELD_NAMES,Ac as REACTION_EMOJI_MAP,lu as RECORDING_STATUS,Au as ROLE_SOURCE,Ng as RoomSubscriptionManager,Co as SDKTransactionStatus,Oo as SDK_VERSION,_u as SIMULATE_EVENT_TYPE,uu as SIMULCAST_PLATFORM,du as SIMULCAST_STATUS,Du as STREAM_EVENTS,vu as STREAM_PERMISSION,Eu as STREAM_ROLE,cu as STREAM_STATUS,Ig as SelectiveEventForwarding,eh as StreamWebSocketService,Pm as TIME_CONSTANTS,Or as TOKEN_NAME_AVAILABILITY_CONSTRAINT,Dr as TOKEN_NAME_DTO_CONSTRAINT,Mr as TOKEN_NAME_EVENT_CONSTRAINT,Cr as TOKEN_NAME_FILTER_CONSTRAINT,Rr as TOKEN_NAME_PATH_CONSTRAINT,Tt as TRADING_TYPES,It as TokenRestrictedError,dh as TradingQuotesService,Lt as TransactionError,Yh as TransactionFailedError,Rg as TypingIndicatorDebouncer,_t as ValidationError,Xh as WebSocketError,Qh as WebSocketTimeoutError,fh as WeeklyChallengeService,Gg as addCursorToPagination,ts as addressFormatSchema,qg as aggregateMultipleApiSources,xs as amountMethodSchema,Ps as amountTypeSchema,Kn as assertValidWalletAddress,Xr as availabilityTokenNameSchema,_n as backendUserRef,Wl as bidirectionalTokenMatch,Ns as browserFileSchema,ws as bufferFileSchema,Kg as buildConcurrentBatchRequests,Wg as buildQueryParametersWithValidation,xg as buildSafePaginationOptions,Zs as buyTokensDataSchema,dg as calculateLinearFeeInterpolation,oi as calculatePreMintDataSchema,Eg as calculateScaledFeeAmount,xo as calculateTotalPages,Kt as capitalize,$l as caseInsensitiveTokenComparison,Fs as checkPoolOptionsSchema,Ar as commonValidators,bg as conditionalSpreadBuilder,Gl as conditionalTrimAndValidateString,og as createLaunchpadSDK,ds as createLimitSchema,vr as createOptionsValidator,Xs as createPaginatedResultSchema,Uo as createPaginationQuery,Js as createTradeDataSchema,mg as decimalRoundingUp,Sg as deduplicateByKey,zr as dtoTokenNameSchema,Kl as errorMessageCaseNormalization,ns as ethereumAddressSchema,Tg as extractFieldWithFallbackPath,Hg as extractPaginationMetadata,Ch as feeCeilingFromQuotedFee,ui as fetchGalaBalanceOptionsSchema,ai as fetchPoolDetailsDataSchema,mi as fetchTokenBalanceOptionsSchema,ms as fileSizeSchema,bs as fileUploadSchema,fs as filenameSchema,rs as flexibleAddressSchema,ks as flexibleFileSchema,Xn as formatGalaForDTO,Qn as formatLaunchpadTokenForDTO,Un as fromBackendAddressFormat,es as fullNameSchema,$a as generateBuySellStringsInstructions,Ka as generateCreateSaleStringsInstructions,ii as getAmountOptionsSchema,Io as getEnvironmentConfig,fm as getIntervalRegistryStats,Hi as getLaunchTokenDataValidationErrors,Md as getNftFeeAsNumber,om as getRecordingAnimatedUrl,dm as getRecordingAssetUrl,am as getRecordingPosterUrl,cm as getRecordingStoryboardUrl,lm as getRecordingStreamUrl,im as getRecordingThumbnailUrl,af as getTieredModerationSavings,em as getTokenAnimatedUrl,sm as getTokenAssetUrl,Jg as getTokenImageUrl,rm as getTokenLiveStreamUrl,tm as getTokenPosterUrl,nm as getTokenStoryboardUrl,Zg as getTokenThumbnailUrl,ti as getTradeOptionsSchema,Gs as graduateTokenOptionsSchema,Bs as graphDataOptionsSchema,Ag as groupByKey,Bo as hasMorePages,Vl as hexStringExtractionAndNormalization,_s as imageExtensionSchema,Is as imageFilenameSchema,ps as imageMimeTypeSchema,Ls as imageUploadOptionsSchema,nf as isAIModerationData,tf as isAIModerationMode,rf as isAIModerationSettings,Jm as isAIRecommendation,ha as isActiveUserType,Zm as isAnalysisCategory,Qm as isAnalysisStatus,ef as isAnalysisTier,Ym as isAnalysisType,ga as isBanData,pa as isBanEnforcementEvent,al as isBurnTokenEntry,cl as isBurnTokensData,ym as isChatDisabledReason,Dm as isChatStatusResponse,qd as isClaimableInvite,cc as isContentType,cr as isEmptyValue,yu as isExtendedStreamRole,uc as isFlagAction,hc as isFlagData,lc as isFlagReason,dc as isFlagStatus,Am as isHolderDelta,Tm as isHolderDeltaType,Pc as isLockTokenEntry,Bc as isLockTokensData,hd as isMessage,gd as isMessageType,wd as isModeratedToken,sf as isModerationTiered,Nd as isModeratorInvite,ar as isNonEmptyString,Vd as isOverseerInviteStatus,jd as isOverseerStatus,km as isPinnedMessage,kd as isPublicInviteInfo,Lm as isReactionErrorCode,gu as isRecordingStatus,mu as isSimulcastPlatform,wm as isStreamChatDeletedEvent,Nm as isStreamChatErrorEvent,Sm as isStreamChatMessage,bm as isStreamChatMessageEvent,_m as isStreamChatPinnedEvent,Im as isStreamChatUnpinnedEvent,Mm as isStreamReactionErrorEvent,Om as isStreamReactionEvent,hu as isStreamStatus,fu as isStreamStatusEvent,Su as isTokenAccessResult,nh as isTokenBanData,Fm as isTypingIndicatorEvent,Um as isTypingUser,xc as isUnlockTokenEntry,Gc as isUnlockTokensData,ma as isUserBannedEvent,vm as isUserHoldingData,Rn as isUserRef,fa as isUserUnbannedEvent,Pn as isValidAddress,na as isValidApiKeyRole,Aa as isValidBanDuration,Ea as isValidBanReason,Cm as isValidChatContent,Rm as isValidChatTokenName,bd as isValidInviteCode,Sd as isValidInviteStatus,Ki as isValidLaunchTokenData,yd as isValidModeratorRole,rh as isValidTokenBanReason,fr as isValidTokenName,pu as isViewerCountEvent,Es as isoDateStringSchema,Ms as launchTokenDataSchema,Bg as mergeSafePaginationOptions,os as nonNegativeDecimalStringSchema,Fn as normalizeAddressInput,yg as normalizeDataWithMapping,Hl as normalizeErrorMessage,Po as normalizeLimit,fn as normalizeTokenKey,mn as normalizeTokenName,pn as normalizeTokenSymbol,cs as optionalUrlSchema,ls as pageNumberSchema,zs as paginationResultMetaSchema,jg as parseHttpErrorResponse,Ga as parseLaunchpadVaultAddress,gg as percentileIndexCalculation,Us as poolFetchTypeSchema,Ws as poolPaginationSchema,is as positiveDecimalStringSchema,hg as priceTickRangeMapping,vs as privateKeySchema,hm as registerInterval,ro as requireNonNegative,no as requirePositive,so as requirePositiveWithContext,Vg as retryableHttpRequest,Os as reverseBondingCurveConfigSchema,ci as reverseBondingCurveConfigurationSchema,ca as roleHasSufficientPermission,ug as roundTickBoundaries,pg as roundTickToSpacing,fg as safeDivideWithMinimum,Zr as searchQuerySchema,ei as sellTokensDataSchema,us as standardLimitSchema,$s as standardPaginationSchema,As as timestampSchema,Ln as toBackendAddressFormat,Hn as toBackendAddressFromEthers,Cs as tokenCategorySchema,Rs as tokenCollectionSchema,Yr as tokenDescriptionSchema,di as tokenListOptionsSchema,qr as tokenNameSchema,Qr as tokenSymbolSchema,Ds as tokenUrlsSchema,si as tradeCalculationMethodSchema,ri as tradeCalculationTypeSchema,gs as tradeLimitSchema,ni as tradeListParamsSchema,Hs as tradePaginationSchema,js as tradePaginationWithFiltersSchema,Ys as tradeTypeBackendSchema,Qs as tradeTypeSchema,Ts as transactionIdSchema,vg as transformRawApiTokenToDomainModel,jl as trimmedLengthValidation,ys as uniqueKeySchema,mm as unregisterAllIntervals,gm as unregisterInterval,hi as updateProfileDataSchema,gi as uploadProfileImageOptionsSchema,as as urlSchema,hs as userLimitSchema,Ks as userPaginationSchema,kn as userRef,Jr as userTokenNameSchema,li as userTokenTypeSchema,Vs as userTokensPaginationSchema,vi as validateAddress,yi as validateAmountString,sh as validateBanTokenOptions,Ui as validateBuyTokensData,Gi as validateCalculatePreMintData,pf as validateChatMessageId,Ii as validateCheckPoolOptions,ir as validateConstrainedEnumVariant,ra as validateCreateApiKeyOptions,gf as validateCreateChatMessageOptions,lf as validateCreateCommentOptions,od as validateCreateMessageOptions,Id as validateCreateModeratorInviteOptions,tu as validateCreateOverseerDirectOptions,zd as validateCreateOverseerInviteOptions,Li as validateCreateTradeData,nr as validateDecimalRangeStrict,rr as validateFeePortionConstraints,Ci as validateFetchGalaBalanceOptions,id as validateFetchMessagesOptions,$i as validateFetchPoolDetailsData,Mi as validateFetchTokenBalanceOptions,Si as validateFullName,Bi as validateGetAmountOptions,hf as validateGetChatMessagesOptions,cf as validateGetCommentsOptions,ah as validateGetTokenBanOptions,Pi as validateGetTradeOptions,Pl as validateGetTradesOptions,_i as validateImageUploadOptions,Dd as validateInviteCode,Wi as validateLaunchTokenData,oa as validateListApiKeysOptions,Cd as validateListModeratorInvitesOptions,Xd as validateListOverseerInvitesOptions,Qd as validateListOverseersOptions,oh as validateListTokenBansOptions,eu as validateListUsersOptions,cd as validateMessageId,sr as validateMinMaxRelationship,mr as validateOptionalTokenName,Yd as validateOverseerInviteCode,Zd as validateOverseerInviteId,Jd as validateOverseerWalletAddress,Fo as validatePaginationParams,bi as validateSearchQuery,Fi as validateSellTokensData,tr as validateSortOrderDirection,Ai as validateTokenDescription,Di as validateTokenListOptions,pr as validateTokenName,Ei as validateTokenSymbol,ki as validateTokenUrls,xi as validateTradeListParams,ih as validateUnbanTokenOptions,sa as validateUpdateApiKeyOptions,mf as validateUpdateChatMessageOptions,df as validateUpdateCommentOptions,ad as validateUpdateMessageOptions,ru as validateUpdatePlatformConfigOptions,Ri as validateUpdateProfileData,kl as validateUpdateTokenConfigOptions,Oi as validateUploadProfileImageOptions,Ni as validateUserTokenName,Ti as validateVaultAddress,ss as vaultAddressSchema,of as wasModerationEscalated};