@gala-chain/launchpad-sdk 9.0.0 → 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.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";var e=require("@gala-chain/gala-core-sdk"),t=require("ethers"),n=require("zod"),r=require("@gala-chain/gala-core-sdk/providers"),s=require("@gala-chain/api"),o=require("uuid"),i=require("socket.io-client"),a=require("bignumber.js"),c=require("axios");const l={UPLOAD_IMAGE:"/v1/tokens/:tokenName/image",FETCH_POOLS:"/v1/tokens",GET_TOKEN:"/v1/tokens/:tokenName",GET_TOKEN_DISTRIBUTION:"/v1/holders",CHART:"/v1/chart",GET_TRADES:"/v1/tokens/:tokenName/trades",GET_PROFILE:"/v1/users/:address",UPDATE_PROFILE:"/v1/users/me",GET_CURRENT_USER:"/v1/users/me/profile",UPLOAD_PROFILE_IMAGE:"/v1/users/me/image",GET_TOKEN_LIST:"/v1/users/:address/tokens",GET_TOKENS_HELD:"/v1/users/:address/tokens",GET_GALA_BALANCE:"/v1/users/:address/gala-balance",GET_REFERRAL_CODE:"/v1/connect/users/referrals/code",GET_MANAGED_TOKENS:"/v1/users/me/managed-tokens",VALIDATE_TOKEN:"/v1/utils/validate-token",UPDATE_TOKEN_CONFIG:"/v1/tokens/:tokenName",TOKEN_STATS:"/v1/tokens/:tokenName/stats",OEMBED:"/oembed",OEMBED_BUY_SELL:"/oembed/buy-sell/:tokenName",OEMBED_PROFILE:"/oembed/profile/:address"},d="/v1/users/referrals/url",u="/v1/users/referrals",h="/v1/users/referrals/summary",g="/v1/tokens/:tokenName/start-stream",p="/v1/tokens/:tokenName/stop-stream",m="/v1/tokens/:tokenName/stream/disable",f="/v1/tokens/:tokenName/stream/enable",E="/v1/tokens/:tokenName/reset-key",A="/v1/tokens/:tokenName/recordings",T="/v1/tokens/:tokenName/recordings/:assetId/download",v="/v1/tokens/:tokenName/recordings/:assetId",S="/v1/tokens/:tokenName/simulcasts",y="/v1/tokens/:tokenName/simulcasts",b="/v1/tokens/:tokenName/simulcasts/:targetId",N="/v1/config",k="/v1/config",w="/v1/config",_="/v1/tokens/:tokenName/role",I="/v1/roles",C="/v1/permissions",D="/v1/tokens/:tokenName/credentials",R="/auth/login",O="/auth/logout",x="/auth/refresh",M="/auth/session",L="/v1/tokens/:tokenName/bans",U="/v1/tokens/:tokenName/bans",F="/v1/tokens/:tokenName/bans/:userAddress",P="/v1/tokens/:tokenName/bans/:userAddress",B="/v1/tokens/:tokenName/active-users",G="/v1/user-bans",$="/v1/user-bans",K="/v1/user-bans/:userAddress",H="/v1/user-bans/:userAddress",W={CREATE:"/v1/api-keys",LIST:"/v1/api-keys",GET:"/v1/api-keys/:id",UPDATE:"/v1/api-keys/:id",REVOKE:"/v1/api-keys/:id"},V="/v1/moderator-invites",j="/v1/moderator-invites/claim",q="/v1/moderated-tokens",z="/v1/moderator-invites",Y="/v1/moderator-invites/:id",X="/v1/moderator-invites/:id/role",Q="/v1/moderator-invites/:id",J="/v1/moderator-invites/code/:code",Z={CREATE:"/v1/content-flags",LIST:"/v1/content-flags",DISMISS:"/v1/content-flags/:id/dismiss",ACTION:"/v1/content-flags/:id/action"},ee="/v1/overseer-invites",te="/v1/overseer-invites",ne="/v1/overseer-invites/code/:code",re="/v1/overseer-invites/claim",se="/v1/overseer-invites/:id",oe="/v1/overseers",ie="/v1/overseers",ae="/v1/overseers/:address",ce="/v1/overseers/me",le="/v1/overseer-summary",de="/v1/overseer-summary/bans",ue="/v1/overseer-summary/token-bans",he="/v1/overseer-summary/invites",ge="/v1/overseer-summary/flags",pe="/v1/overseer-summary/users",me="/v1/users",fe="/v1/users/:address/summary",Ee="/v1/cache/flush/address/:address",Ae="/v1/cache/flush/token/:tokenName",Te="/v1/cache/flush/all",ve="/v1/cache/flush/wallet-aliases/:address",Se="/v1/cache/flush/wallet-aliases",ye="/v1/token-bans",be="/v1/token-bans",Ne="/v1/token-bans/:tokenName",ke="/v1/token-bans/:tokenName",we="/v1/reactions",_e="/v1/reactions",Ie="/v1/trades",Ce={GET_MESSAGES:"/v1/messages",CREATE_MESSAGE:"/v1/messages",UPDATE_MESSAGE:"/v1/messages/:id",DELETE_MESSAGE:"/v1/messages/:id",GET_PINNED:"/v1/messages/pinned",PIN_MESSAGE:"/v1/messages/:id/pin",UNPIN_MESSAGE:"/v1/messages/:id/pin",GET_MESSAGE_STATS:"/v1/messages/stats"},De="/v1/restricted-token-names",Re="/v1/restricted-token-names",Oe="/live/:tokenName/chat",xe="/live/:tokenName/chat",Me="/live/:tokenName/chat",Le="/live/:tokenName/chat/slow-mode",Ue="/v1/events",Fe="/v1/events/stats",Pe="/health",Be={GET_SETTINGS:"/v1/ai-moderation/settings",UPDATE_SETTINGS:"/v1/ai-moderation/settings",GET_MODERATION:"/v1/ai-moderation/flags/:flagId",TRIGGER_MODERATION:"/v1/ai-moderation/flags/:flagId/analyze",GET_STATUS:"/v1/ai-moderation/status"},Ge="/v1/stats",$e="/v1/trading/fee",Ke="/v1/trading/sale-details",He="/v1/trading/quote",We="/v1/trading/premint-quote",Ve={GET_LEADERBOARD:"/weekly-challenge",GET_TOKEN_HISTORY:"/weekly-challenge/history/:vaultAddress"},je="/v1/notifications/register",qe="/v1/notifications/unregister",ze="/v1/notifications/preferences",Ye="/v1/notifications/preferences",Xe="/v1/config/client-flags",Qe={NATIVE:"native",EXACT:"exact"},Je=["RECENT","POPULAR","RECORDINGS","SECONDS_STREAMED"],Ze=["IDLE","ACTIVE","DISABLED"],et=100,tt={LOCAL:"local",EXTERNAL:"external"},nt={REQUIRED:"REQUIRED",INVALID_TYPE:"INVALID_TYPE",INVALID_VALUE:"INVALID_VALUE",INVALID_FORMAT:"INVALID_FORMAT",TOO_SHORT:"TOO_SHORT",TOO_LONG:"TOO_LONG",TOO_LARGE:"TOO_LARGE",TOO_SMALL:"TOO_SMALL",EMPTY_ARRAY:"EMPTY_ARRAY",ARRAY_TOO_LARGE:"ARRAY_TOO_LARGE",ZERO_VALUE:"ZERO_VALUE",INVALID_TICK_SPACING:"INVALID_TICK_SPACING",INVALID_FEE_TIER:"INVALID_FEE_TIER",INVALID_RANGE:"INVALID_RANGE",INVALID_PARAMETERS:"INVALID_PARAMETERS",NOT_FOUND:"NOT_FOUND",INVALID_DATA:"INVALID_DATA"};class rt extends Error{constructor(e,t,n){super(e),this.field=t,this.code=n,this.name="ValidationError"}}function st(e){return"object"==typeof e&&null!==e}function ot(e){if(null==e||""===e)return{};if(!st(e)||Array.isArray(e))return{body:e};const t=Reflect.get(e,"message"),n="string"==typeof t?t:Array.isArray(t)&&t.every(e=>"string"==typeof e)?t.join(","):void 0,r=Reflect.get(e,"error"),s=Reflect.get(e,"details");return{...void 0===n?{}:{serverMessage:n},..."string"==typeof r&&""!==r?{serverError:r}:{},...void 0===s?{}:{details:s},body:e}}function it(e){if(e instanceof at)return{...void 0===e.serverMessage?{}:{serverMessage:e.serverMessage},...void 0===e.serverError?{}:{serverError:e.serverError},...void 0===e.details?{}:{details:e.details},...void 0===e.body?{}:{body:e.body}};const t=function(e){if(!st(e))return;const t=Reflect.get(e,"response");return st(t)?t:void 0}(e);return void 0===t?{}:ot(Reflect.get(t,"data"))}class at extends Error{constructor(e,t,n,r=it(n)){super(e),this.name="NetworkError",this.statusCode=t,this.originalError=n,this.serverMessage=r.serverMessage,this.serverError=r.serverError,this.details=r.details,this.body=r.body}}class ct extends Error{constructor(e,t){super(e),this.field=t,this.name="ConfigurationError"}}class lt extends Error{constructor(e,t,n){super(e),this.transactionId=t,this.code=n,this.name="TransactionError"}}function dt(e){return e instanceof Error}function ut(e){return dt(e)||function(e){return"object"==typeof e&&null!==e&&"message"in e&&"string"==typeof e.message}(e)?e.message:"string"==typeof e?e:String(e)}function ht(e){return dt(e)||"object"==typeof e&&null!==e&&"stack"in e&&"string"==typeof e.stack?e.stack:void 0}function gt(e){if(function(e){return"object"==typeof e&&null!==e&&"code"in e&&("string"==typeof e.code||"number"==typeof e.code)}(e))return e.code}function pt(e){return"object"==typeof e&&null!==e&&"message"in e&&("response"in e||"request"in e||"config"in e)}function mt(e,t){if(null==e||"object"!=typeof e)throw new Error(`${t}: No response - expected object, got ${typeof e}`);const n=e;if(!("Status"in n))throw new Error(`${t}: Response missing 'Status' property`);const r=n.Status;if("number"!=typeof r)throw new Error(`${t}: Response Status must be a number, got ${typeof r}`);if(1!==r)throw new Error(`${t}: Response status indicates failure (Status: ${r})`);return n}function ft(e,t,n){try{t()}catch(t){if(!function(e){return e instanceof Error&&"ValidationError"===e.name}(t))throw t;{const n=t.message;e.push(n)}}}function Et(e,t){return void 0!==t?t:e.charAt(0).toUpperCase()+e.slice(1)}function At(e,t){return new rt(`Token "${e}" not found. Please verify the token name is correct.`,"tokenName","TOKEN_NOT_FOUND")}function Tt(e,t){const n=Et(e,t);return new rt(`${n} is required`,e,"REQUIRED")}function vt(e,t,n){const r=Et(e,n);return new rt(`${r} must be ${t}`,e,"INVALID_FORMAT")}function St(e,t,n,r){return new at(e,t,n,r)}function yt(e,t){return new ct(e,t)}function bt(e,t,n){return new lt(e,t,n)}function Nt(e,t,n,r,s){const o=Et(e,s);return new rt(`${o} must be between ${t} and ${n}${void 0!==r?`, received: ${r}`:""}`,e,"OUT_OF_RANGE")}function kt(e,t,n,r){const s=Et(e,r);return new rt(`${s} must be at least ${t}${void 0!==n?`, received: ${n}`:""}`,e,"TOO_SMALL")}function wt(e,t,n,r){const s=Et(e,r);return new rt(`${s} must be at most ${t}${void 0!==n?`, received: ${n}`:""}`,e,"TOO_LARGE")}function _t(e,t,n,r){const s=Et(e,r),o=void 0!==n?`, received: ${"object"==typeof n?"object":String(n)}`:"";return new rt(`${s} must be ${t}${o}`,e,"INVALID_TYPE")}function It(e,t,n){const r=Et(e,n);return new rt(`${r} must be a valid number${void 0!==t?`: "${t}"`:""}`,e,"INVALID_NUMBER")}function Ct(e,t,n,r){const s=Et(e,r);return new rt(`Invalid ${s}: ${t}. Must be one of: ${n.join(", ")}`,e,"INVALID_ENUM")}function Dt(e,t){if(e.length<2)return Tt(void 0!==e[0]&&""!==e[0]?e[0]:"field");let n;if(2===e.length)n=e.join(" or ");else{n=`${e.slice(0,-1).join(", ")} or ${e[e.length-1]??"field"}`}return new rt(`At least one of ${n} must be provided`,e[0],"REQUIRED")}function Rt(e,t,n,r){const s=Et(e,r);return new rt(`${s} must be at most ${t} characters${void 0!==n?`, received: ${n}`:""}`,e,"TOO_LONG")}function Ot(e,t){const n=Et(e,t);return new rt(`${n} cannot be empty`,e,"EMPTY_STRING")}function xt(e){return null!=e&&"object"==typeof e&&"data"in e}function Mt(e,t,n=!1){const r=!0===e.error,s=n&&(null===e.data||void 0===e.data);if(r||s){const n=e?.statusCode??e.status??void 0;throw St(e?.message??t,n,void 0,r?ot(e):void 0)}}function Lt(e){if(xt(e))return e.data}function Ut(e,t="No data found in response"){if(!xt(e))throw St(t);const n=e.data;if(null==n)throw St(t);return n}async function Ft(e,t={}){return Gt(e,t,e=>{if(void 0===e.data)throw new rt(`${t.errorContext??"Operation failed"}: No data returned from API`,"data","NO_DATA");return e.data})}async function Pt(e,t={}){const{errorContext:n="Operation failed",logger:r,debugLogEnabled:s=!1}=t;s&&r&&r.debug(`${n}: starting operation`);try{const t=await e();return s&&r&&r.debug(`${n}: completed successfully`),t}catch(e){throw r&&r.error(n,{error:e}),e}}async function Bt(e,t={}){return Gt(e,t,e=>e)}async function Gt(e,t,n){const{errorContext:r="Operation failed",logger:s,debugLogEnabled:o=!1}=t;o&&s&&s.debug(`${r}: starting operation`);try{const t=await e();if(null==t)throw new rt(`${r}: No response from server`,"response","NO_RESPONSE");return Mt(t,r,!0),o&&s&&s.debug(`${r}: completed successfully`),n(t)}catch(e){throw s&&s.error(r,{error:e}),e}}const $t={BASE_PRICE:1650667151e-14,PRICE_SCALING_FACTOR:1166069e-12,TRADING_FEE_FACTOR:.001,GAS_FEE:"1",DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY:1e7};function Kt(e){return e.trim().toLowerCase()}function Ht(e){return e.trim().toUpperCase()}var Wt;!function(e){e.DEBUG="DEBUG",e.INFO="INFO",e.WARN="WARN",e.ERROR="ERROR"}(Wt||(Wt={}));class Vt{constructor(e){this.levelPriority={[Wt.DEBUG]:0,[Wt.INFO]:1,[Wt.WARN]:2,[Wt.ERROR]:3},this.debugEnabled=e.debug,this.context=e.context??"SDK",this.minLevel=e.minLevel??(e.debug?Wt.DEBUG:Wt.INFO)}debug(e,t){this.log(Wt.DEBUG,e,t)}info(e,t){this.log(Wt.INFO,e,t)}warn(e,t){this.log(Wt.WARN,e,t)}error(e,t){this.log(Wt.ERROR,e,t)}log(e,t,n){if(this.levelPriority[e]<this.levelPriority[this.minLevel])return;if(e===Wt.DEBUG&&!this.debugEnabled)return;const r=`[${(new Date).toISOString()}] [${this.context}] [${e}]`,s=this.getConsoleMethod(e);void 0!==n?dt(n)?s(`${r} ${t}`,n.message,ht(n)??""):s(`${r} ${t}`,n):s(`${r} ${t}`)}getConsoleMethod(e){switch(e){case Wt.DEBUG:return console.debug;case Wt.INFO:return console.info;case Wt.WARN:return console.warn;case Wt.ERROR:return console.error;default:return console.log}}child(e){return new Vt({debug:this.debugEnabled,context:`${this.context}:${e}`,minLevel:this.minLevel})}isDebugEnabled(){return this.debugEnabled&&this.levelPriority[Wt.DEBUG]>=this.levelPriority[this.minLevel]}}function jt(e){return"string"==typeof e&&e.trim().length>0}function qt(e){return null==e||""===e}function zt(e){return null==e}const Yt=new Vt({debug:!1,context:"DateUtils"});function Xt(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())?(Yt.warn(`Invalid date string received: "${e}". Using fallback.`),new Date):t}catch(t){return Yt.warn(`Date parsing error for "${e}":`,t),new Date}}function Qt(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 Jt(t,n){if("string"==typeof t&&/^eth\|0[xX]/u.test(t))try{e.galaChainUserRef(t,n)}catch(t){if(e.isGalaError(t)&&"INVALID_ETH_USER_REF_PREFIX"===t.code)return t.message}}function Zt(t,n="address"){const r=Jt(t,n);if(void 0!==r)throw new rt(r,n,"INVALID_FORMAT");try{return e.galaChainUserRef(t,n)}catch{throw new rt(`${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 en(e,t="address"){return Zt(e,t).toLowerCase()}function tn(e,t){return pn(e)??en(e,t)}function nn(e){return sn(e)?en(e):e.trim().toLowerCase()}function rn(e,t){const n=e=>sn(e)?en(e):e.toLowerCase();return n(e)===n(t)}function sn(e){try{return Zt(e),!0}catch{return!1}}class on{toBackendFormat(e){if(!jt(e))throw new rt("Address is required and must be a string","address","REQUIRED");return Zt(e,"address")}toEthereumFormat(e){if(!jt(e))throw new rt("Backend address is required and must be a string","address","REQUIRED");if(!e.match(/^eth\|([0-9a-fA-F]{40})$/i)){const t=Jt(e,"address");if(void 0!==t)throw new rt(t,"address","INVALID_FORMAT");throw new rt(`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 Zt(e,"address")}normalizeForBackend(e){if(void 0!==e&&""!==e)return en(e,"address")}isValid(e){return sn(e)}assertValid(e,t="address"){if(!this.isValid(e)){const n=Jt(e,t);if(void 0!==n)throw new rt(n,t,"INVALID_FORMAT");throw new rt(`${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 jt(e)&&sn(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=sn(e)?Zt(e):void 0;if(void 0!==t&&t.startsWith("eth|"))return t.substring(4).toLowerCase();throw new rt(`Cannot extract hex from address: "${e}". Expected Ethereum or backend format.`,"address","INVALID_FORMAT")}}const an=new on;function cn(e){return an.toBackendFormat(e)}function ln(e){return an.toEthereumFormat(e)}function dn(e){return an.normalizeInput(e)}function un(e){return an.isValid(e)}const hn=/^(eth\|[a-f0-9]{40}|client\|[a-f0-9]{24})$/;function gn(e){return void 0!==pn(e)}function pn(e){if(!jt(e))return;const t=e.trim(),n=/^[0-9a-fA-F]{24}$/u.test(t)?`client|${t}`:t;if(!sn(n))return;const r=en(n);return hn.test(r)?r:void 0}function mn(e,t){if(!gn(e)){const n=Jt(e,t);if(void 0!==n)throw new rt(n,t,"INVALID_FORMAT");throw new rt(`${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 fn(e,t="address"){an.assertValid(e,t)}function En(e){const t="string"==typeof e?e:e.address;return an.toBackendFormat(t)}var An=Object.freeze({__proto__:null,AddressFormatter:on,assertBackendUserAddress:mn,assertValidWalletAddress:fn,backendUserAddress:pn,backendUserParam:tn,backendUserRef:en,ethZeroXRefusal:Jt,fromBackendAddressFormat:ln,isBackendUserAddress:gn,isUserRef:sn,isValidAddress:un,normalizeAddressInput:dn,sameUserAddress:rn,toBackendAddressFormat:cn,toBackendAddressFromEthers:En,userAddressFilter:nn,userRef:Zt});function Tn(e,t=0){if(qt(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(zt(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 Sn(e,t=0){if(zt(e))return t;if("number"==typeof e)return isNaN(e)?t:e;return Tn(String(e).replace("%","").trim(),t)}function yn(e,t=18){const n=Tn(e,0);if(0===n)return"0";return n.toFixed(t).replace(/\.?0+$/,"")}function bn(e){return yn(e,8)}function Nn(e){return yn(e,18)}function kn(e,t,n,r){if("number"!=typeof e)throw _t(r,"a number",e,r);if(e<t||e>n)throw Nt(r,t,n,e)}function wn(e,t,n){if("string"!=typeof e)throw _t(n,"a string",e,n);if(e.length>t)throw wt(n,t,e.length)}function _n(e,t){if("number"!=typeof e)throw _t(t,"a number",e,t);if(!Number.isInteger(e))throw _t(t,"an integer",e,t);if(e<=0)throw kt(t,1,e,t)}function In(e,t,n=!1){if("string"!=typeof e)throw _t(t,"a string",e,t);if(!n&&0===e.trim().length)throw Tt(t,`${t} (non-empty string)`)}function Cn(e,t,n){const r="string"==typeof e?parseFloat(e):e,s="string"==typeof t?parseFloat(t):t;if(!isFinite(r))throw new rt(`${n} minFee must be a valid finite number`,n,"INVALID_FEE_MINIMUM");if(!isFinite(s))throw new rt(`${n} maxFee must be a valid finite number`,n,"INVALID_FEE_MAXIMUM");if(r<.1)throw new rt(`${n} minFee must be >= 0.1, received ${r}`,n,"INVALID_FEE_MINIMUM");if(s>.5)throw new rt(`${n} maxFee must be <= 0.5, received ${s}`,n,"INVALID_FEE_MAXIMUM");if(r>s)throw new rt(`${n} minFee (${r}) must be <= maxFee (${s})`,n,"INVALID_FEE_RANGE")}const Dn={ETH_ADDRESS:/^0x[0-9a-fA-F]{40}$/,BACKEND_ADDRESS:/^eth\|[0-9a-fA-F]{40}$/},Rn=jt,On=qt,xn=zt;function Mn(e,t,n=100,r,s){if(void 0!==s&&"string"!=typeof s)throw new rt("cursor must be a string","cursor",nt.INVALID_TYPE);const o=r??t,i=void 0!==r?"pageSize":"limit";if(void 0!==o&&(_n(o,i),o>n))throw new rt(`${i} must be at most ${n}`,i,nt.TOO_LARGE)}function Ln(e){const t=Object.values(e);return e=>"string"==typeof e&&t.includes(e)}function Un(e){return Object.values(e)}function Fn(e,t,n){if(!Rn(e))throw Tt(t);const r=e.trim();if(0===r.length)throw Tt(t);if(r.length<n.MIN_LENGTH)throw Nt(t,n.MIN_LENGTH,n.MAX_LENGTH,r.length,`${t} length`);if(r.length>n.MAX_LENGTH)throw Nt(t,n.MIN_LENGTH,n.MAX_LENGTH,r.length,`${t} length`);if(!n.PATTERN.test(r))throw new rt(`${t} must be ${n.DESCRIPTION}`,t,nt.INVALID_FORMAT)}function Pn(e,t,n){if(null==e)throw Tt(t,t);if("string"!=typeof e)throw _t(t,"a string",e);const r=e.trim();if(0===r.length)throw Tt(t,t);if(!n.PATTERN.test(r))throw new rt(`${t} must be ${n.DESCRIPTION}`,t,nt.INVALID_FORMAT)}function Bn(e){return t=>{if(null==t||"object"!=typeof t)return!1;const n=t;for(const{field:t,type:r,nullable:s=!1,optional:o=!1,validator:i}of e){const e=n[t];if((!o||void 0!==e)&&(!s||null!==e)){if(typeof e!==r)return!1;if(i&&!i(e))return!1}}return!0}}const Gn={requiredString:e=>t=>xn(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(!On(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(!xn(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=>xn(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(!xn(n))return t.includes(n)?void 0:`${e} must be one of: ${t.join(", ")}`},requiredEnumValue:(e,t)=>n=>xn(n)?`${e} is required`:t.includes(n)?void 0:`${e} must be one of: ${t.join(", ")}`,isoDate:e=>t=>{if(!xn(t))return"string"!=typeof t?`${e} must be a string`:Qt(t)?void 0:`${e} must be a valid ISO 8601 date string`},walletAddress:(e,t=!1)=>n=>xn(n)?t?`${e} is required`:void 0:"string"!=typeof n?`${e} must be a string`:sn(n)?void 0:Jt(n,e)??`${e} must be a valid wallet address`};function $n(e){return""===e||0===e.trim().length}function Kn(e,t,n){if(!xn(e)){if("string"!=typeof e)throw _t(t,"a string",e,t);if(e.length>n)throw new rt(`${t} must be at most ${n} characters`,t,nt.TOO_LARGE)}}function Hn(e,t){xn(e)||function(e,t){const n=e instanceof Date?e:"string"==typeof e||"number"==typeof e?new Date(e):void 0;if(void 0===n)throw _t(t,"a date",e,t);if(isNaN(n.getTime()))throw new rt(`${t} must be a valid date`,t,nt.INVALID_FORMAT)}(e,t)}function Wn(e,t,n){try{_n(e,t)}catch{throw function(e,t,n,r="OPERATION_FAILED"){return new rt(`${e} failed: ${t}`,n,r)}(n,"must be a positive integer",t)}}function Vn(e,t,n="status"){void 0!==e&&function(e,t,n){const r=Object.values(t);if(!r.includes(e))throw new rt(`${n} must be one of: ${r.join(", ")}`,n,nt.INVALID_FORMAT)}(e,t,n)}class jn{constructor(e,t=!1,n){this.http=e,this.logger=new Vt({debug:t,context:this.constructor.name}),this.jwtAuth=n}setJwtAuth(e){this.jwtAuth=e}getJwtHeaders(){if(!this.jwtAuth){const e=globalThis;if("test"===e.process?.env?.NODE_ENV&&!this.isCalledFromUserCode())return{};throw new ct("JWT authentication required. Call sdk.login() first.")}return this.jwtAuth.getJwtHeaders()}isCalledFromUserCode(){const e=ht(new Error)??"";return!(!e.includes("expect")&&!e.includes("jest"))||!(!e.includes("tests/")&&!e.includes(".test.ts"))}validatePositiveInteger(e,t,n){Wn(e,t,n)}}class qn{constructor(e=!1,t){this.logger=t||new Vt({debug:e,context:this.constructor.name})}}class zn extends qn{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 Yn extends zn{constructor(e=!1){super(e)}normalizeKey(e){return Kt(e).replace(/\s+/g," ").replace(/[\u0000-\u001F\u007F-\u009F\u200B-\u200D\uFEFF]/g,"")}getLRUKey(){return this.cache.keys().next().value??null}updateCacheEntry(e,t){const n=this.cache.get(e);if(this.cache.has(e)&&this.cache.delete(e),this.cache.size>=Yn.MAX_CACHE_SIZE){const e=this.getLRUKey();null!==e&&this.cache.delete(e)}this.cache.set(e,{...n??{},...t,lastUpdated:Date.now()})}warmFromPoolData(e,t){const n=this.normalizeKey(e);this.updateCacheEntry(n,t)}set(e,t){const n=this.normalizeKey(e);this.updateCacheEntry(n,t)}getByName(e){const t=this.normalizeKey(e);return this.cache.get(t)}getMaxSupply(e){const t=this.normalizeKey(e),n=this.cache.get(t);return n?.maxSupply??$t.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY.toString()}has(e){const t=this.normalizeKey(e);return this.cache.has(t)}clear(e){if(void 0!==e&&""!==e){const t=this.normalizeKey(e);this.cache.delete(t)}else super.clear()}dumpAsObject(){const e={};return this.cache.forEach((t,n)=>{e[n]=t}),e}getStats(){const e=this.buildBaseStats(),{cacheSize:t,oldestEntry:n}=this.calculateCacheSizeAndAge();return{...e,totalTokens:e.totalItems,cacheSize:t,oldestEntry:n}}calculateCacheSizeAndAge(){let e=Date.now(),t=0;return this.cache.forEach((n,r)=>{n.lastUpdated<e&&(e=n.lastUpdated);let s=0;s+=2*r.length,void 0!==n.reverseBondingCurveMinFeeFactor&&(s+=8),void 0!==n.reverseBondingCurveMaxFeeFactor&&(s+=8),void 0!==n.reverseBondingCurveNetFeeFactor&&(s+=8),s+=8,void 0!==n.vaultAddress&&""!==n.vaultAddress&&(s+=2*n.vaultAddress.length),void 0!==n.maxSupply&&""!==n.maxSupply&&(s+=2*n.maxSupply.length),void 0!==n.symbol&&""!==n.symbol&&(s+=2*n.symbol.length),s+=32,t+=s}),{cacheSize:t,oldestEntry:this.cache.size>0?e:0}}getByTokenId(e){const t=`token:${Kt(e)}`;return this.cache.get(t)??null}setByTokenId(e,t){const n=`token:${Kt(e)}`;this.updateCacheEntry(n,t)}hasByTokenId(e){const t=`token:${Kt(e)}`;return this.cache.has(t)}}Yn.MAX_CACHE_SIZE=1e4;const Xn={MIN_LENGTH:1,MAX_LENGTH:25,PATTERN:/^[a-zA-Z0-9]{1,25}$/,DESCRIPTION:"1-25 letters and digits"},Qn={MIN_LENGTH:1,MAX_LENGTH:50,PATTERN:/^[a-zA-Z0-9]{1,50}$/,DESCRIPTION:"1-50 letters and digits"},Jn={MIN_LENGTH:1,MAX_LENGTH:255,PATTERN:/^[a-zA-Z0-9]{1,255}$/,DESCRIPTION:"1-255 letters and digits"},Zn={MIN_LENGTH:1,MAX_LENGTH:50,PATTERN:/^[\s\S]{1,50}$/,DESCRIPTION:"1-50 characters"},er={MIN_LENGTH:1,MAX_LENGTH:100,PATTERN:/^(?![\s\S]*<[^>]*>)[\s\S]{1,100}$/,DESCRIPTION:"1-100 characters without HTML"},tr=100,nr=100,rr=50,sr=100,or={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}},ir={CHAT_MESSAGE:{PATTERN:/^chat-\d{13}-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i},CONTENT_REACTION:{MAX_LENGTH:64,PATTERN:/^(msg-\d{13}-[a-f0-9]{32}|chat-\d{13}-[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})$/}},ar=60,cr=31536e3,lr={MAX_LENGTH:64,PATTERN:/^(galaswap-operation-|galaconnect-operation-)/},dr={PATTERN:/^[a-fA-F0-9]{64}$/,MAX_LENGTH:64},ur=1,hr=100,gr={FULL_NAME:{MIN_LENGTH:2,MAX_LENGTH:20,ALPHABETS_ONLY_PATTERN:/^[a-zA-Z]+(?: [a-zA-Z]+)?$/}},pr=n.z.string({message:"Token name is required"}).min(1,"Token name must be at least 1 character").regex(/^[a-zA-Z0-9]+$/,"Token name can only contain letters and numbers"),mr=pr.max(25,"Token name must be at most 25 characters"),fr=n.z.string({message:"Token name is required"}).min(1,"Token name must be at least 1 character").max(50,"Token name must be at most 50 characters"),Er=n.z.string({message:"Token symbol is required"}).min(1,"Token symbol must be at least 1 character").max(8,"Token symbol must be at most 8 characters").regex(/^[A-Z]{1,8}$/,"Token symbol must be uppercase letters only"),Ar=n.z.string({message:"Token description is required"}).min(1,"Token description is required").max(500,"Token description must be at most 500 characters"),Tr=n.z.string().min(1,"Token name must be at least 1 character").max(50,"Token name must be at most 50 characters"),vr=n.z.string().min(1,"Search query must be at least 1 character").max(100,"Search query must be at most 100 characters"),Sr=n.z.string().min(1,"Full name is required").max(100,"Full name must be at most 100 characters").regex(/^[a-zA-Z\s]+$/,"Full name can only contain letters and spaces"),yr=n.z.string().regex(Dn.BACKEND_ADDRESS,"Address must be in format: eth|[40-hex-chars]"),br=n.z.string().regex(Dn.ETH_ADDRESS,"Invalid Ethereum address format"),Nr=n.z.string().refine(e=>sn(e),{error:e=>Jt(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=>Zt(e)),kr=n.z.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"),wr=n.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>Tn(e,0)>0,"Amount must be greater than zero"),_r=n.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>Tn(e,0)>=0,"Amount must be zero or greater"),Ir=n.z.string().url("Must be a valid URL").regex(/^https?:\/\//,"URL must start with http:// or https://"),Cr=n.z.string().optional().refine(e=>void 0===e||""===e||/^https?:\/\/.+\..+/.test(e),"Must be a valid URL if provided"),Dr=n.z.number().int("Page must be an integer").min(1,"Page must be at least 1").max(1e3,"Page must be at most 1000").default(1);function Rr(e=100){return n.z.number().int("Limit must be an integer").min(1,"Limit must be at least 1").max(e,`Limit must be at most ${e}`).default(10)}const Or=Rr(100),xr=Rr(20),Mr=Rr(20),Lr=n.z.number().int("File size must be an integer").min(1,"File must be at least 1 byte").max(10485760,"File must be at most 10MB"),Ur=n.z.string().max(255,"Filename must be at most 255 characters"),Fr=n.z.enum(["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"]),Pr=n.z.string().datetime("Must be a valid ISO 8601 date string"),Br=n.z.number().int("Timestamp must be an integer").min(0,"Timestamp must be non-negative"),Gr=n.z.string().regex(/^0x[a-fA-F0-9]{64}$/,"Private key must be format: 0x + 64 hex characters"),$r=n.z.string().regex(/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/,"Transaction ID must be in UUID format"),Kr=n.z.string().regex(/^galaconnect-operation-[a-z0-9-]+$/,"Unique key must be format: galaconnect-operation-{unique-id}"),Hr=[".png",".jpg",".jpeg",".gif",".webp",".svg"],Wr=n.z.object({file:n.z.union([n.z.instanceof(File),n.z.instanceof(Buffer)]),name:Ur,size:Lr,type:Fr}),Vr=n.z.instanceof(File).refine(e=>e.size>=1&&e.size<=10485760,"File size must be between 1 byte and 10MB").refine(e=>["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"].includes(e.type),"File must be a valid image type (PNG, JPG, JPEG, GIF, WebP, or SVG)").refine(e=>e.name.length<=255,"Filename must be at most 255 characters"),jr=n.z.instanceof(Buffer).refine(e=>e.length>=1&&e.length<=10485760,"Buffer size must be between 1 byte and 10MB"),qr=n.z.union([Vr,jr]),zr=n.z.enum([".png",".jpg",".jpeg",".gif",".webp",".svg"]),Yr=Ur.refine(e=>{const t=e.slice(e.lastIndexOf(".")).toLowerCase();return Hr.includes(t)},`Filename must end with one of: ${Hr.join(", ")}`),Xr=n.z.object({websiteUrl:Cr,telegramUrl:Cr,twitterUrl:Cr,instagramUrl:Cr,facebookUrl:Cr,redditUrl:Cr,tiktokUrl:Cr}).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"),Qr=n.z.string().min(1,"Token category must not be empty").default("Unit"),Jr=n.z.string().min(1,"Token collection must not be empty").default("Token"),Zr=n.z.object({minFeePortion:n.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal string").refine(e=>Tn(e,0)>=.1,"Minimum fee must be >= 0.1").refine(e=>Tn(e,0)<=.5,"Minimum fee must be <= 0.5").default("0.1"),maxFeePortion:n.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal string").refine(e=>Tn(e,0)>=.1,"Maximum fee must be >= 0.1").refine(e=>Tn(e,0)<=.5,"Maximum fee must be <= 0.5").default("0.5")}).refine(e=>Tn(e.maxFeePortion,0)>=Tn(e.minFeePortion,0),{message:"Maximum fee must be >= minimum fee",path:["maxFeePortion"]}),es=n.z.object({tokenName:pr,tokenSymbol:Er,tokenDescription:Ar,tokenImage:n.z.union([n.z.instanceof(File),n.z.instanceof(Buffer),n.z.string().url("Token image must be a valid URL")]).optional(),preBuyQuantity:_r.default("0"),websiteUrl:Cr,telegramUrl:Cr,twitterUrl:Cr,instagramUrl:Cr,facebookUrl:Cr,redditUrl:Cr,tiktokUrl:Cr,tokenCategory:Qr,tokenCollection:Jr,reverseBondingCurveConfiguration:Zr.optional(),saleStartTime:n.z.number().int().positive().optional(),privateKey:Gr.optional()}),ts=n.z.object({file:n.z.union([n.z.instanceof(File),n.z.instanceof(Buffer)]),tokenName:pr}),ns=n.z.enum(Je),rs=n.z.object({tokenName:fr.optional(),symbol:Er.optional()}).refine(e=>void 0!==e.tokenName||void 0!==e.symbol,"At least one of tokenName or symbol is required"),ss=n.z.enum(["NATIVE","MEME"]),os=n.z.enum(["IN","OUT"]),is=n.z.object({from:n.z.number().int("From timestamp must be an integer").min(173e6,"From timestamp must be at least 173000000"),to:n.z.number().int("To timestamp must be an integer").min(173e6,"To timestamp must be at least 173000000"),resolution:n.z.number().int("Resolution must be an integer").min(1,"Resolution must be at least 1"),tokenName:mr}),as=n.z.object({tokenName:mr,slippageToleranceFactor:n.z.number().min(0).max(1).optional(),maxAcceptableReverseBondingCurveFeeSlippageFactor:n.z.number().min(0).max(1).optional(),privateKey:Gr.optional()}),cs=n.z.object({offset:n.z.number().int().min(0).default(0),pageSize:n.z.number().int().min(1).max(100).default(10)}),ls=n.z.object({offset:n.z.number().int().min(0).default(0),pageSize:n.z.number().int().min(1).max(20).default(10)}),ds=n.z.object({offset:n.z.number().int().min(0).default(0),pageSize:n.z.number().int().min(1).max(20).default(10)}),us=cs.extend({type:n.z.enum(["RECENT","POPULAR"]).optional(),tokenName:n.z.string().min(1).max(50).optional(),search:n.z.string().min(1).max(100).optional()}),hs=ls.extend({tokenName:n.z.string().min(1).max(50).optional(),search:n.z.string().min(1).max(100).optional()}),gs=ds.extend({tradeType:n.z.enum(["BUY","SELL"]).optional(),tokenName:n.z.string().min(1).max(50).optional(),userAddress:n.z.string().refine(sn,{error:e=>Jt(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:n.z.string().datetime().optional(),endDate:n.z.string().datetime().optional(),sortOrder:n.z.enum(["ASC","DESC"]).default("DESC")}),ps={page:n.z.number().int().min(1),limit:n.z.number().int().min(1),total:n.z.number().int().min(0),totalPages:n.z.number().int().min(0),hasNext:n.z.boolean(),hasPrevious:n.z.boolean()},ms=n.z.object(ps);const fs=n.z.enum(["buy","sell"]),Es=n.z.enum(["BUY","SELL"]),As=n.z.object({tradeType:fs,tokenAmount:wr,vaultAddress:kr,userAddress:Nr,slippageTolerance:wr.optional(),deadline:n.z.number().int().positive().optional()}),Ts=n.z.object({tokenSymbol:Er,nativeTokenQuantity:wr,expectedToken:wr,maxAcceptableReverseBondingCurveFee:_r.default("0").optional()}),vs=n.z.object({tokenSymbol:Er,tokenQuantity:wr,expectedNativeToken:wr,maxAcceptableReverseBondingCurveFee:_r.default("0").optional()}),Ss=ds.extend({tokenName:Tr.optional()}),ys=n.z.object({page:n.z.number().int().min(1).max(1e3).default(1).optional(),limit:n.z.number().int().min(1).max(20).default(10).optional()}),bs=n.z.enum(["NATIVE","MEME"]),Ns=n.z.enum(["IN","OUT"]),ks=n.z.object({type:bs,method:Ns,vaultAddress:kr,amount:wr}),ws=n.z.object({nativeTokenQuantity:wr}),_s=n.z.object({vaultAddress:kr}),Is=n.z.object({minFeePortion:wr,maxFeePortion:wr}),Cs=n.z.enum(["both","held","created"]),Ds=ls.extend({type:Cs.optional(),address:Nr.optional(),search:vr.optional(),tokenName:Tr.optional()}),Rs=n.z.object({address:Nr.optional(),refresh:n.z.boolean().optional()}),Os=n.z.object({profileImage:n.z.string().nullable().optional(),fullName:Sr.optional(),address:Nr.optional(),privateKey:Gr.optional()}),xs=n.z.object({file:n.z.union([n.z.instanceof(File),n.z.instanceof(Buffer)]),address:Nr.optional(),privateKey:Gr.optional()}),Ms=n.z.object({address:Nr,tokenId:n.z.union([n.z.string(),n.z.object({collection:n.z.string(),category:n.z.string(),type:n.z.string(),additionalKey:n.z.string()}),n.z.object({collection:n.z.string(),category:n.z.string(),type:n.z.string(),additionalKey:n.z.string(),instance:n.z.string()})]).optional(),tokenName:Tr.optional(),withExpired:n.z.boolean().optional()}).refine(e=>void 0!==e.tokenId||void 0!==e.tokenName,"At least one token identifier (tokenId or tokenName) is required");function Ls(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 Us=Ls(pr),Fs=Ls(Er),Ps=Ls(Ar),Bs=Ls(Nr),Gs=Ls(kr),$s=Ls(wr),Ks=Ls(Sr),Hs=Ls(vr),Ws=Ls(Tr),Vs=Ls(es),js=Ls(Xr),qs=Ls(ts),zs=Ls(rs),Ys=Ls(Ds),Xs=Ls(Rs),Qs=Ls(Os),Js=Ls(xs),Zs=Ls(Ms),eo=Ls(As),to=Ls(Ts),no=Ls(vs),ro=Ls(Ss),so=Ls(ys),oo=Ls(ks),io=Ls(ws),ao=Ls(_s);function co(e){const t=Vs(e);return t.success?[]:t.errors??["Unknown validation error"]}function lo(e){const t=co(e);if(t.length>0)throw new Error(`LaunchTokenData validation failed:\n${t.map(e=>`- ${e}`).join("\n")}`)}function uo(e,t){return"string"==typeof e[t]}function ho(e,t){return void 0===e[t]||"string"==typeof e[t]}function go(e,t){return void 0===e[t]||"number"==typeof e[t]}function po(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 mo(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(!po(n[t],r))return!1}return!0}}Ln({BUY:"buy",SELL:"sell"});const fo=mo({nativeTokenQuantity:"string"});function Eo(e,t="0"){return function(e,t="0"){if(qt(e))return new a(t);if(a.isBigNumber(e))return e.isNaN()?new a(t):e;try{const n=new a(e);return n.isNaN()||!n.isFinite()?new a(t):n}catch{return new a(t)}}(e,t)}function Ao(e,t){return void 0!==t?Eo(e).toFixed(t):Eo(e).toFixed()}function To(e){const t=Eo(e),n=Math.log(1.0001),r=t.toNumber();return Math.log(r)/n}function vo(e){return Eo(e).isZero()}function So(e,t){return Eo(e).isLessThan(Eo(t))}function yo(...e){e.forEach(e=>{if(e.isNaN())throw It("value","NaN");if(!e.isFinite())throw wt("value","finite");if(e.isLessThanOrEqualTo(0))throw kt("value","0",e.toString())})}function bo(e,t,n){if(e.isNaN())throw It(t,"NaN");if(!e.isFinite())throw wt(t,"finite");if(e.isLessThanOrEqualTo(0))throw kt(t,"0",e.toString())}function No(e,t,n="0"){const r=Eo(t);return vo(r)?Eo(n):Eo(e).dividedBy(r)}const ko={calculateBuyWithExact(e,t){const n=Tn(e),r=Tn(t),{BASE_PRICE:s,PRICE_SCALING_FACTOR:o,TRADING_FEE_FACTOR:i,GAS_FEE:a}=$t,c=function(e,t){const n=Math.pow(10,t);return Math.ceil(e*n)/n}(s*(Math.exp((r+n)*o)-Math.exp(r*o))/o,8),l=Ao(Eo(c).multipliedBy(i));return{amount:c.toString(),reverseBondingCurveFee:"0",transactionFee:l,gasFee:a}},calculateBuyWithNative(e,t){const n=Tn(e),r=Tn(t),{BASE_PRICE:s,PRICE_SCALING_FACTOR:o,TRADING_FEE_FACTOR:i,GAS_FEE:a}=$t,c=Math.log(n*o/s+Math.exp(r*o))/o-r,l=Ao(Eo(c).multipliedBy(i));return{amount:c.toString(),reverseBondingCurveFee:"0",transactionFee:l,gasFee:a}},calculateSellWithExact(e,t,n,r,s){const o=Tn(e),i=Tn(t),a=Tn(n),{BASE_PRICE:c,PRICE_SCALING_FACTOR:l,TRADING_FEE_FACTOR:d,GAS_FEE:u}=$t,h=c*(Math.exp(i*l)-Math.exp((i-o)*l))/l,g=Eo(h),p=r+i/a*(s-r),m=Ao(g.multipliedBy(p),8),f=Ao(g.multipliedBy(d));return{amount:h.toString(),reverseBondingCurveFee:m,transactionFee:f,gasFee:u}},calculateSellWithNative(e,t,n,r,s){const o=Tn(e),i=Tn(t),a=Tn(n),{BASE_PRICE:c,PRICE_SCALING_FACTOR:l,TRADING_FEE_FACTOR:d,GAS_FEE:u}=$t;if(o>=c*(Math.exp(i*l)-1)/l){const e=Eo(o),t=r+i/a*(s-r),n=Ao(e.multipliedBy(t),8),c=Ao(e.multipliedBy(d));return{amount:i.toString(),reverseBondingCurveFee:n,transactionFee:c,gasFee:u}}const h=i-Math.log(Math.exp(i*l)-o*l/c)/l,g=Eo(o),p=r+i/a*(s-r),m=Ao(g.multipliedBy(p),8),f=Ao(g.multipliedBy(d));return{amount:h.toString(),reverseBondingCurveFee:m,transactionFee:f,gasFee:u}}};function wo(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function _o(e,t){if(!function(e){if(!wo(e)||"string"!=typeof e.calculatedQuantity)return!1;const t=e.extraFees;return wo(t)&&"string"==typeof t.reverseBondingCurve&&"string"==typeof t.transactionFees}(e))throw St(`Malformed trade quote from the launchpad backend (${t})`);return{amount:e.calculatedQuantity,reverseBondingCurveFee:e.extraFees.reverseBondingCurve,transactionFee:e.extraFees.transactionFees,gasFee:$t.GAS_FEE}}class Io{validate(e,t={}){const{allowZero:n=!0,minimum:r,maximum:s,maxDecimals:o=Io.MAX_DECIMAL_PLACES,fieldName:i="amount"}=t;if(!Rn(e))throw new rt(`${i} cannot be empty or whitespace-only. Provide a valid numeric string.`,i,"INVALID_NUMERIC_STRING");if(/[eE]/.test(e))throw new rt(`${i} cannot use scientific notation. Use standard decimal format (e.g., "1000" instead of "1e3").`,i,"INVALID_NUMERIC_STRING");const a=Tn(e,NaN);if(isNaN(a))throw new rt(`${i} must be a valid numeric string. Received: "${e}"`,i,"INVALID_NUMERIC_STRING");if(!isFinite(a))throw new rt(`${i} must be a finite number. Cannot be Infinity or -Infinity.`,i,"INVALID_NUMERIC_STRING");if(a<0)throw new rt(`${i} must be non-negative. Received: "${e}"`,i,"INVALID_NUMERIC_STRING");if(!n&&0===a)throw new rt(`${i} must be greater than zero. Received: "${e}"`,i,"INVALID_NUMERIC_STRING");const c=Eo(e),l=c.decimalPlaces()??0;if(l>o)throw new rt(`${i} cannot exceed ${o} decimal places. Received: ${l} decimal places`,i,"PRECISION_EXCEEDED");if(void 0!==r&&So(c,r))throw new rt(`${i} must be at least ${r}. Received: "${e}"`,i,"BELOW_MINIMUM");if(void 0!==s&&(d=s,Eo(c).isGreaterThan(Eo(d))))throw new rt(`${i} cannot exceed ${s}. Received: "${e}"`,i,"EXCEEDS_MAXIMUM");var d}parseAmount(e,t="0"){return Eo(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 Ao(e,t)}clampAmount(e,t,n){const r=Eo(e),s=Eo(t),o=Eo(n);return function(e,t,n){const r=Eo(e),s=Eo(t),o=Eo(n);return r.isGreaterThanOrEqualTo(s)&&r.isLessThanOrEqualTo(o)}(r,s,o)?Ao(r):So(r,s)?Ao(s):Ao(o)}}function Co(e,t){throw new rt(e.join("; "),t,"VALIDATION_ERROR")}function Do(e){const t=Us(e);!t.success&&t.errors&&Co(t.errors,"tokenName")}function Ro(e){const t=is.safeParse(e);var n;t.success||Co((n=t.error.issues,Array.isArray(n)?n.map(e=>null!=e&&"object"==typeof e&&"message"in e&&"string"==typeof e.message?e.message:String(e)).filter(e=>""!==e):[]),"options")}function Oo(e,t,n=!0){xo.validate(e,{fieldName:t,allowZero:n})}Io.MAX_DECIMAL_PLACES=18,Io.MIN_POSITIVE="0.00000000000000001";const xo=new Io;class Mo{constructor(e,t,n,r="local",s){this.http=e,this.logger=t,this.bundleHttp=n,this.defaultCalculateAmountMode=r,this.launchpadWrites=s,this.metadataCache=new Yn}createSale(e){if(void 0===this.launchpadWrites)throw new Error("Launchpad write transport is not configured.");return this.launchpadWrites.createSale(e)}addIfDefined(e,t,n){return void 0!==n&&(e[t]=n),e}async calculateBuyAmount(e){if(null==e||"object"!=typeof e)throw vt("options","an options object");const{tokenName:t,amount:n,type:r,currentSupply:s}=e;return"external"===this.validateAmountCalculationInputs(t,n,r,e.mode,[Qe.NATIVE,Qe.EXACT],'"native" or "exact"')?this.calculateBuyAmountExternal({tokenName:t,amount:n,type:r}):this.calculateBuyAmountLocal(this.addIfDefined({tokenName:t,amount:n,type:r},"currentSupply",s))}async calculateBuyAmountExternal(e){const{tokenName:t,amount:n,type:r}=e;return this.validateExternalAmountInputs(t,n),"exact"===r?this.fetchBackendQuote({tokenName:t,amount:n,type:"MEME",method:"OUT"},`Failed to calculate buy amount for ${t} (exact tokens)`):this.fetchBackendQuote({tokenName:t,amount:n,type:"NATIVE",method:"IN"},`Failed to calculate buy amount for ${t} (native/GALA budget)`)}async fetchBackendQuote(e,t){return _o(await Ft(()=>this.http.get(He,{...e}),{errorContext:t}),t)}async calculateSellAmount(e){const{tokenName:t,amount:n,type:r,currentSupply:s,maxSupply:o,reverseBondingCurveMaxFeeFactor:i,reverseBondingCurveMinFeeFactor:a}=e;if("external"===this.validateAmountCalculationInputs(t,n,r,e.mode,[Qe.EXACT,Qe.NATIVE],'"exact" or "native"'))return this.calculateSellAmountExternal({tokenName:t,amount:n,type:r});{const e={tokenName:t,amount:n,type:r,...void 0!==s&&{currentSupply:s},...void 0!==o&&{maxSupply:o},...void 0!==i&&{reverseBondingCurveMaxFeeFactor:i},...void 0!==a&&{reverseBondingCurveMinFeeFactor:a}};return this.calculateSellAmountLocal(e)}}async calculateSellAmountExternal(e){const{tokenName:t,amount:n,type:r}=e;return this.validateExternalAmountInputs(t,n),"exact"===r?this.fetchBackendQuote({tokenName:t,amount:n,type:"MEME",method:"IN"},`Failed to calculate sell amount for ${t} (exact tokens)`):this.fetchBackendQuote({tokenName:t,amount:n,type:"NATIVE",method:"OUT"},`Failed to calculate sell amount for ${t} (native/GALA target)`)}async calculateBuyAmountLocal(e){const{tokenName:t,amount:n,type:r,currentSupply:s}=e;if(!Rn(n))throw Tt("amount","Amount");if(r!==Qe.NATIVE&&r!==Qe.EXACT)throw _t("type",'"native" or "exact"',r);void 0!==s&&Oo(s,"currentSupply");const o=null==s||""===s;if(o&&(null==t||""===t))throw Tt("tokenName","Token name (required when currentSupply is not provided)");null!=t&&""!==t&&Do(t);let i=s;if(o){i=(await this.fetchPoolDetailsForCalculation(t)).currentSupply}return r===Qe.EXACT?ko.calculateBuyWithExact(n,i):ko.calculateBuyWithNative(n,i)}async calculateSellAmountLocal(e){const{tokenName:t,amount:n,type:r,currentSupply:s,maxSupply:o,reverseBondingCurveMaxFeeFactor:i,reverseBondingCurveMinFeeFactor:a}=e;if(!Rn(n))throw Tt("amount","Amount");if(r!==Qe.EXACT&&r!==Qe.NATIVE)throw _t("type",'"exact" or "native"',r);void 0!==s&&Oo(s,"currentSupply");const c=null==s||""===s||null==o||""===o||void 0===i||void 0===a;if(c&&(null==t||""===t))throw Tt("tokenName","Token name (required when currentSupply, maxSupply, or fee factors are not provided)");null!=t&&""!==t&&Do(t);let l=s,d=o,u=i,h=a;if(c&&null!=t&&""!==t){const e=this.metadataCache.getByName(t);d=d??this.metadataCache.getMaxSupply(t),u=u??e?.reverseBondingCurveMaxFeeFactor,h=h??e?.reverseBondingCurveMinFeeFactor,null!=l&&""!==l||(l=await this.fetchCurrentSupply(t));if(void 0===u||void 0===h){const e=await this.fetchPoolDetailsForCalculation(t);u=u??e.reverseBondingCurveMaxFeeFactor,h=h??e.reverseBondingCurveMinFeeFactor}}return r===Qe.EXACT?ko.calculateSellWithExact(n,l,d,h,u):ko.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 uo(t,"tokenName")&&function(e){return void 0===e.calculateAmountMode||"local"===e.calculateAmountMode||"external"===e.calculateAmountMode}(t)&&ho(t,"currentSupply")}(e))throw _t("options","CalculateBuyAmountForGraduationOptions or string (token name)",typeof e);const{tokenName:n,calculateAmountMode:r,currentSupply:s}=t;Do(n);const o=await this.fetchSaleDetails(n),i=s??Ao(Eo(o.maxSupply).minus(o.sellingTokenQuantity)),a=o.sellingTokenQuantity;if("0"===a)throw Tt("tokenName",`Token ${n} is already graduated (no tokens remaining in pool)`);const c={tokenName:n,amount:a,type:"exact",currentSupply:i,...void 0!==r&&{mode:r}};return{...await this.calculateBuyAmount(c),remainingTokens:a}}async launchToken(e){if(void 0!==this.launchpadWrites){return(await this.launchpadWrites.createSale(e)).bundleId}if(!this.bundleHttp)throw yt("Bundle backend client not configured. LaunchToken requires bundleHttp client.","bundleHttp");lo(e);const t=void 0!==e.preBuyQuantity&&""!==e.preBuyQuantity?e.preBuyQuantity:"0",n=Tn(t);if(0===n&&"0"!==t)throw It("preBuyQuantity",t,"Pre-buy quantity");if(n<0)throw It("preBuyQuantity",t,"Pre-buy quantity");if(e.reverseBondingCurveConfiguration){const{minFeePortion:t,maxFeePortion:n}=e.reverseBondingCurveConfiguration;Cn(t,n,"reverseBondingCurve")}throw new Error("Legacy launchToken signing is unavailable; configure the v6 launchpad write transport.")}async calculateInitialBuyAmount(e){if(!fo(e))throw vt("data","valid pre-mint calculation data");const t="Failed to calculate initial buy amount";return _o(await Ft(()=>this.http.get(We,{amount:e.nativeTokenQuantity}),{errorContext:t}),t)}async fetchPoolDetailsForCalculation(e){const t=await this.fetchSaleDetails(e),n=Ao(Eo(t.maxSupply).minus(t.sellingTokenQuantity)),r=t.sellingTokenQuantity,s=t.maxSupply;let o=.5,i=.1;const a=t.reverseBondingCurveConfiguration;null!=a?.maxFeePortion&&(o=Sn(a.maxFeePortion,.5)),null!=a?.minFeePortion&&(i=Sn(a.minFeePortion,.1)),void 0===a&&this.logger.debug(`Pool details missing reverse bonding curve configuration for token ${e}, using defaults (min: 0.1, max: 0.5)`);const c=o-i;return this.metadataCache.set(e,{maxSupply:s,reverseBondingCurveMaxFeeFactor:o,reverseBondingCurveMinFeeFactor:i,reverseBondingCurveNetFeeFactor:c}),{currentSupply:n,remainingTokens:r,maxSupply:s,reverseBondingCurveMaxFeeFactor:o,reverseBondingCurveMinFeeFactor:i,reverseBondingCurveNetFeeFactor:c}}async fetchCurrentSupply(e){Do(e);const t=await this.fetchSaleDetails(e),n=Ao(Eo(t.maxSupply).minus(t.sellingTokenQuantity)),r=t.maxSupply;return this.metadataCache.set(e,{maxSupply:r}),n}async fetchPoolDetails(e){Do(e);const t=await this.fetchSaleDetails(e),{reverseBondingCurveConfiguration:n,...r}=t,s=n?.minFeePortion??"0",o=n?.maxFeePortion??"0";return{...r,reverseBondingCurveMinFeePortion:s,reverseBondingCurveMaxFeePortion:o,hasReverseBondingCurveFee:!vo(s)||!vo(o),isGraduated:"Finished"===t.saleStatus}}async fetchSaleDetails(e){return Fn(e,"tokenName",Xn),Ft(()=>this.http.get(Ke,{tokenName:e}),{errorContext:`Failed to fetch sale details for ${e}`})}validateAmountCalculationInputs(e,t,n,r,s,o){const i=r??this.defaultCalculateAmountMode;if("local"!==i&&"external"!==i)throw _t("mode",'"local" or "external"',i);if(!Rn(e))throw Tt("tokenName","Token name");if(!Rn(t))throw Tt("amount","Amount");if("string"!=typeof n||!s.includes(n))throw _t("type",o,n);return i}validateExternalAmountInputs(e,t){if("string"!=typeof e||""===e)throw new rt("Token name must be a non-empty string","tokenName","INVALID_TOKEN_NAME");if("string"!=typeof t||""===t)throw new rt("Amount must be a non-empty string","amount","INVALID_AMOUNT")}getAddress(){return this.http.getAddress()}formatAddressForBackend(e){return cn(e)}validateTokenName(e){return Do(e)}validatePagination(e){void 0!==e.pageSize&&Mn(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 Lo={REFRESH_THRESHOLD_MS:3e5,DEFAULT_EXPIRY_S:86400,LOGIN_MESSAGE_PREFIX:"Sign in to Launchpad t:",AUTH_HEADER:"Authorization",BEARER_PREFIX:"Bearer "};class Uo{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 Fo;exports.AuthErrorType=void 0,(Fo=exports.AuthErrorType||(exports.AuthErrorType={})).WALLET_NOT_CONNECTED="WALLET_NOT_CONNECTED",Fo.SIGNATURE_FAILED="SIGNATURE_FAILED",Fo.INVALID_ADDRESS="INVALID_ADDRESS",Fo.MESSAGE_GENERATION_FAILED="MESSAGE_GENERATION_FAILED";class Po extends Error{constructor(e,t,n,r){super(t),this.type=e,this.originalError=n,this.statusCode=r,this.name="AuthError"}}class Bo{constructor(e,t=Lo.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 Uo,this.refreshThresholdMs=t}setToken(e,t){if(!Rn(e))throw new Po(exports.AuthErrorType.SIGNATURE_FAILED,"JWT token must be a non-empty string");if("number"!=typeof t)throw new Po(exports.AuthErrorType.SIGNATURE_FAILED,"Token expiration must be a positive finite number (seconds)");if(!Number.isFinite(t))throw new Po(exports.AuthErrorType.SIGNATURE_FAILED,"Token expiration must be a positive finite number (seconds)");if(t<=0)throw new Po(exports.AuthErrorType.SIGNATURE_FAILED,"Token expiration must be a positive finite number (seconds)");const n=Date.now();this.tokenState={token:e.trim(),issuedAt:n,expiresAt:n+1e3*t},this.storage.set(this.STORAGE_KEYS.ACCESS_TOKEN,e.trim()),this.storage.set(this.STORAGE_KEYS.ACCESS_EXPIRES,String(this.tokenState.expiresAt))}async setTokens(e,t,n,r){if(this.setToken(e,t),n){const e=Date.now()+1e3*(r??7776e3);if(!this.tokenState)throw new Po(exports.AuthErrorType.SIGNATURE_FAILED,"Access token must be set before refresh token");this.tokenState.refreshToken=n.trim(),this.tokenState.refreshExpiresAt=e,await this.storage.set(this.STORAGE_KEYS.REFRESH_TOKEN,n.trim()),await this.storage.set(this.STORAGE_KEYS.REFRESH_EXPIRES,String(e))}}getToken(){return this.tokenState?.token??null}hasToken(){return null!==this.tokenState}isExpired(){return!this.tokenState||Date.now()>=this.tokenState.expiresAt}shouldRefresh(e){if(!this.tokenState)return!1;const t=e??this.refreshThresholdMs,n=this.tokenState.expiresAt-Date.now();return n>0&&n<=t}getTimeUntilExpiry(){if(!this.tokenState)return 0;const e=this.tokenState.expiresAt-Date.now();return Math.max(0,e)}getExpiresAt(){return this.tokenState?.expiresAt??null}getAuthorizationHeader(){const e=this.getToken();return null===e||""===e?null:`${Lo.BEARER_PREFIX}${e}`}getJwtHeaders(){const e=this.getAuthorizationHeader();if(null===e||""===e)throw new Po(exports.AuthErrorType.WALLET_NOT_CONNECTED,"No JWT token available. Call login() first.");return{[Lo.AUTH_HEADER]:e}}async getRefreshToken(){if(!this.tokenState?.refreshToken){const e=await this.storage.get(this.STORAGE_KEYS.REFRESH_TOKEN),t=await this.storage.get(this.STORAGE_KEYS.REFRESH_EXPIRES);if(e&&t){const n=Number(t);if(Number.isFinite(n)&&Date.now()<n)return e}return null}return null!==this.tokenState.refreshExpiresAt&&void 0!==this.tokenState.refreshExpiresAt&&(!Number.isFinite(this.tokenState.refreshExpiresAt)||Date.now()>=this.tokenState.refreshExpiresAt)?null:this.tokenState.refreshToken??null}async restoreFromStorage(){const e=await this.storage.get(this.STORAGE_KEYS.ACCESS_TOKEN),t=await this.storage.get(this.STORAGE_KEYS.ACCESS_EXPIRES);if(!e||!t)return!1;const n=Number(t);if(!Number.isFinite(n)||Date.now()>=n)return!1;const r=Date.now();this.tokenState={token:e,issuedAt:r,expiresAt:n};const s=await this.storage.get(this.STORAGE_KEYS.REFRESH_TOKEN),o=await this.storage.get(this.STORAGE_KEYS.REFRESH_EXPIRES);if(s&&o){const e=Number(o);Number.isFinite(e)&&Date.now()<e&&(this.tokenState.refreshToken=s,this.tokenState.refreshExpiresAt=e)}return!0}async clear(){this.tokenState=null,await this.storage.remove(this.STORAGE_KEYS.ACCESS_TOKEN),await this.storage.remove(this.STORAGE_KEYS.ACCESS_EXPIRES),await this.storage.remove(this.STORAGE_KEYS.REFRESH_TOKEN),await this.storage.remove(this.STORAGE_KEYS.REFRESH_EXPIRES)}isValid(){return this.hasToken()&&!this.isExpired()}getDebugInfo(){return{hasToken:this.hasToken(),isExpired:this.isExpired(),shouldRefresh:this.shouldRefresh(),timeUntilExpiryMs:this.getTimeUntilExpiry(),expiresAt:this.tokenState?new Date(this.tokenState.expiresAt):null}}}class Go extends Bo{getJwtHeaders(){return{}}}async function $o(e,t,n,r){try{return await e()}catch(e){throw r?(r(e,t,n),new Error("Unreachable after error handler")):(n&&n.error(`${t}:`,e),function(e,t,n){n&&n.error(`${t}:`,e);const r=(pt(e)?e.response?.status:void 0)??(e instanceof at?e.statusCode:void 0);return St(`${t}: ${ut(e)}`,r,dt(e)?e:void 0)}(e,t,n))}}function Ko(e,t){return t instanceof Po?t:new Po(exports.AuthErrorType.SIGNATURE_FAILED,`${e}: ${ut(t)}`,dt(t)?t:void 0,function(e){if("object"==typeof e&&null!==e){if("statusCode"in e&&"number"==typeof e.statusCode)return e.statusCode;if("response"in e&&"object"==typeof e.response&&null!==e.response){const t=e.response;if("status"in t&&"number"==typeof t.status)return t.status}}}(t))}class Ho{constructor(e,t,n,r=!1,s){this.http=e,this.signatureAuth=t,this.jwtAuth=n,this.session=s,this.refreshPromise=null,this.loginPromise=null,this.logger=new Vt({debug:r,context:"SessionAuthService"})}async loginWithSignature(e){const t=Zt(e.address,"address");if(!Rn(e.message)||!Rn(e.signature))throw new Po(exports.AuthErrorType.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:Zt(e,"address"),...void 0!==this.session&&{cookieSession:!0}})}async postLogin(e){try{const t=await this.http.request({method:"POST",url:R,data:e,withSession:!1}),n=this.extractLoginData(t);return void 0===this.session&&await this.jwtAuth.setTokens(n.accessToken,n.expiresIn,n.refreshToken,n.refreshExpiresIn),n}catch(e){throw Ko("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 Po(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Wallet is required for login. Configure privateKey in SDK.");this.loginPromise=this.performLogin();try{return await this.loginPromise}finally{this.loginPromise=null}}async performLogin(){return $o(async()=>{const e=Date.now(),t=`${Lo.LOGIN_MESSAGE_PREFIX}${e}`;this.logger.debug("Generating login signature",{message:t,timestamp:e});const n=await this.signatureAuth.signMessage(t),r=Zt(this.signatureAuth.getAddress(),"address"),s={address:r,message:t,signature:n.signature};this.logger.debug("Sending login request",{address:r,message:t});const o=await this.http.post(R,s),i=this.extractLoginData(o);return await this.jwtAuth.setTokens(i.accessToken,i.expiresIn,i.refreshToken,i.refreshExpiresIn),this.logger.debug("Login successful",{address:i.address,expiresIn:i.expiresIn,hasRefreshToken:!!i.refreshToken}),i},"SessionAuthService.performLogin",this.logger,e=>{if(e instanceof Po)throw e;throw new Po(exports.AuthErrorType.SIGNATURE_FAILED,`Login failed: ${ut(e)}`,dt(e)?e:void 0)})}async refresh(){if(this.refreshPromise)return this.logger.debug("Refresh already in progress, reusing existing promise"),this.refreshPromise;if(void 0!==this.session){this.refreshPromise=this.performCookieRefresh();try{return await this.refreshPromise}finally{this.refreshPromise=null}}if(!this.jwtAuth.hasToken())throw new Po(exports.AuthErrorType.WALLET_NOT_CONNECTED,"No token to refresh. Call login() first.");this.refreshPromise=this.performRefresh();try{return await this.refreshPromise}finally{this.refreshPromise=null}}async performCookieRefresh(){try{const e=await this.http.request({method:"POST",url:x,data:{},withSession:!1});return this.extractLoginData(e)}catch(e){throw Ko("Token refresh failed",e)}}async performRefresh(){return $o(async()=>{this.logger.debug("Refreshing JWT token");const e=await this.jwtAuth.getRefreshToken();if(e){this.logger.debug("Using refresh token flow");const t=await this.http.post(x,{refreshToken:e}),n=this.extractLoginData(t);return await this.jwtAuth.setTokens(n.accessToken,n.expiresIn,n.refreshToken,n.refreshExpiresIn),this.logger.debug("Token refreshed successfully via refresh token",{address:n.address,expiresIn:n.expiresIn,hasNewRefreshToken:!!n.refreshToken}),n}this.logger.debug("Using legacy access token refresh");const t=await this.http.post(x,{},this.jwtAuth.getJwtHeaders()),n=this.extractLoginData(t);return this.jwtAuth.setToken(n.accessToken,n.expiresIn),this.logger.debug("Token refreshed successfully via access token",{address:n.address,expiresIn:n.expiresIn}),n},"SessionAuthService.performRefresh",this.logger,e=>{if(e instanceof Po)throw e;throw new Po(exports.AuthErrorType.SIGNATURE_FAILED,`Token refresh failed: ${ut(e)}`,dt(e)?e:void 0)})}async logout(e){this.logger.debug("Logging out",{allDevices:e?.allDevices});const t=e?.allDevices??!1;if(void 0!==this.session){const n=e?.accessToken??null;try{await this.http.request({method:"POST",url:O,data:{allDevices:t},withSession:!1,...null!==n&&""!==n&&{headers:{Authorization:`${Lo.BEARER_PREFIX}${n}`}}})}catch(e){throw Ko("Logout failed",e)}return}if(t&&this.jwtAuth.hasToken()&&!this.jwtAuth.isExpired())try{await this.http.post(O,{allDevices:!0},this.jwtAuth.getJwtHeaders()),this.logger.debug("Logged out from all devices")}catch(e){this.logger.warn(`Failed to revoke all-device sessions (server-side revocation may be incomplete): ${ut(e)}`)}else t&&this.logger.debug("Skipping server-side revocation: no valid local token available");await this.jwtAuth.clear()}async getSession(){if(!this.jwtAuth.hasToken())throw new Po(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Not authenticated. Call login() first.");return $o(async()=>{const e=await this.http.get(M,void 0,this.jwtAuth.getJwtHeaders());return this.extractSessionData(e)},"SessionAuthService.getSession",this.logger,e=>{if(e instanceof Po)throw e;throw new Po(exports.AuthErrorType.SIGNATURE_FAILED,`Failed to get session: ${ut(e)}`,dt(e)?e:void 0)})}getAccessToken(){return this.jwtAuth.getToken()}isAuthenticated(){return this.jwtAuth.isValid()}shouldRefresh(e){return this.jwtAuth.shouldRefresh(e)}async ensureValidToken(e){if(void 0!==this.session){const e=await this.session.accessToken();if(null===e||""===e)throw new Po(exports.AuthErrorType.WALLET_NOT_CONNECTED,"The app session has no access token.");return e}if(!this.jwtAuth.hasToken())throw new Po(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Not authenticated. Call login() first.");if(this.jwtAuth.isExpired()){if(await this.jwtAuth.getRefreshToken()){this.logger.debug("Token expired - refresh token available, attempting refresh");try{return(await this.refresh()).accessToken}catch(e){this.logger.warn(`Refresh failed after expiry: ${ut(e)} - attempting re-login`)}}else this.logger.debug("Token expired - no refresh token available, attempting re-login");return(await this.login()).accessToken}if(this.jwtAuth.shouldRefresh(e)){this.logger.debug("Token near expiry - refreshing");return(await this.refresh()).accessToken}return this.jwtAuth.getToken()}extractLoginData(e){if(e.error)throw new Po(exports.AuthErrorType.SIGNATURE_FAILED,""!==ut(e)?ut(e):"Authentication failed");const t=Ut(e,"No data in authentication response"),{accessToken:n,expiresIn:r,address:s,refreshToken:o,refreshExpiresIn:i}=t;if(!Rn(n))throw new Po(exports.AuthErrorType.SIGNATURE_FAILED,"Invalid access token in response");if("number"!=typeof r||r<=0)throw new Po(exports.AuthErrorType.SIGNATURE_FAILED,"Invalid expiration in response");return{accessToken:n,expiresIn:r,address:s,...void 0!==o&&{refreshToken:o},...void 0!==i&&{refreshExpiresIn:i}}}extractSessionData(e){if(e.error)throw new Po(exports.AuthErrorType.SIGNATURE_FAILED,""!==ut(e)?ut(e):"Failed to get session");return Ut(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{In(e.messagePrefix,"messagePrefix",!1)}catch{throw new Po(exports.AuthErrorType.SIGNATURE_FAILED,"Message prefix cannot be empty")}}hasWallet(){return void 0!==this.walletProvider||void 0!==this.wallet}ensureWalletProvider(){if(this.wallet&&!this.walletProvider)try{this.walletProvider=r.PrivateKeyProvider.fromWallet(this.wallet),this.cachedAddress=this.wallet.address,this.cachedGalaAddress=cn(this.wallet.address)}catch(e){if(e instanceof Po)throw e;if(e instanceof rt&&("INVALID_ADDRESS"===e.code||"INVALID_FORMAT"===e.code||"address"===e.field))throw new Po(exports.AuthErrorType.INVALID_ADDRESS,e.message);if(null!==e&&"object"==typeof e&&"message"in e)throw new Po(exports.AuthErrorType.WALLET_NOT_CONNECTED,e.message);throw e}}setWallet(e){if(void 0!==e){if("object"!=typeof e||!("address"in e))throw new Po(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Invalid wallet: must be an ethers Wallet instance or undefined");if("string"!=typeof e.address||""===e.address)throw new Po(exports.AuthErrorType.INVALID_ADDRESS,"Wallet address is not available");this.walletProvider=r.PrivateKeyProvider.fromWallet(e),this.cachedAddress=e.address,this.cachedGalaAddress=cn(e.address)}else this.walletProvider=void 0,this.cachedAddress=void 0,this.cachedGalaAddress=void 0;this.wallet=e}setWalletProvider(e){this.walletProvider=e,this.wallet=void 0;const n=void 0!==e&&r.isPrivateKeyProvider(e)?t.computeAddress(e.exportPrivateKey()):void 0;this.cachedAddress=n,this.cachedGalaAddress=void 0===n?void 0:cn(n)}getWalletProvider(){return this.walletProvider}async cacheAddress(){this.walletProvider&&(this.cachedAddress=await this.walletProvider.getAddress(),this.cachedGalaAddress=Zt(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 Po)throw e;throw new Po(exports.AuthErrorType.SIGNATURE_FAILED,"Failed to generate signature for authentication",dt(e)?e:new Error(ut(e)))}}getAddress(){if(this.validateWallet(),this.cachedGalaAddress)return this.cachedGalaAddress;if(this.wallet)return this.formatAddress(this.wallet.address);throw new Po(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Address not available. For external wallets, call cacheAddress() after connecting.")}async getAddressAsync(){return await this.validateWalletAsync(),Zt(await this.walletProvider.getGalaAddress(),"address")}getEthereumAddress(){if(this.validateWallet(),this.cachedAddress)return this.cachedAddress;if(this.wallet)return this.wallet.address;throw new Po(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Address not available. For external wallets, call cacheAddress() after connecting.")}async getEthereumAddressAsync(){return await this.validateWalletAsync(),this.walletProvider.getAddress()}getPrivateKey(){if(this.validateWallet(),this.wallet){if(""===this.wallet.privateKey||null===this.wallet.privateKey||void 0===this.wallet.privateKey)throw new Po(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Wallet private key not available for @gala-chain signing");return this.wallet.privateKey}if(void 0!==this.walletProvider&&r.isPrivateKeyProvider(this.walletProvider))return this.walletProvider.exportPrivateKey();throw new Po(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Private key not available. External wallet providers cannot access private keys. Use PrivateKeyProvider for @gala-chain signing operations.")}async getPrivateKeyAsync(){if(await this.validateWalletAsync(),!this.walletProvider.getPrivateKey)throw new Po(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Private key not available with this wallet provider");try{return await this.walletProvider.getPrivateKey()}catch(e){throw new Po(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Private key not available. External wallet providers cannot access private keys. Use PrivateKeyProvider for @gala-chain signing operations.",dt(e)?e:void 0)}}formatAddress(e){try{return cn(e)}catch{throw new Po(exports.AuthErrorType.INVALID_ADDRESS,`Invalid Ethereum address format: ${e}`)}}async signMessage(e){await this.validateWalletAsync();try{const t=await this.walletProvider.signMessage(e);return{message:e,signature:t,address:await this.walletProvider.getAddress(),timestamp:Date.now()}}catch(e){if(e instanceof Po)throw e;throw new Po(exports.AuthErrorType.SIGNATURE_FAILED,ut(e),dt(e)?e:new Error(ut(e)))}}async generateAuthHeaders(e,t){await this.validateWalletAsync();try{const n=Date.now(),r=`${this.messagePrefix} ${t.toUpperCase()} ${e} ${n}`,s=await this.walletProvider.signMessage(r);return{"x-signature":s,"x-address":await this.walletProvider.getGalaAddress(),"x-message":r,"x-timestamp":n.toString()}}catch(e){if(e instanceof Po)throw e;throw new Po(exports.AuthErrorType.SIGNATURE_FAILED,"Failed to generate authentication headers",dt(e)?e:new Error(ut(e)))}}async signTypedData(e,t,n){await this.validateWalletAsync();try{const r={};for(const[e,n]of Object.entries(t))r[e]=n.map(e=>({name:e.name,type:e.type}));return await this.walletProvider.signTypedData(e,r,n)}catch(e){if(e instanceof Po)throw e;throw new Po(exports.AuthErrorType.SIGNATURE_FAILED,"Failed to sign typed data",dt(e)?e:new Error(ut(e)))}}async generateCustomSignature(e){if(!Rn(e))throw new Po(exports.AuthErrorType.SIGNATURE_FAILED,"Custom message must be a non-empty string");await this.validateWalletAsync();try{const t=await this.walletProvider.signMessage(e);return{message:e,signature:t,address:await this.walletProvider.getGalaAddress(),timestamp:Date.now()}}catch(e){if(e instanceof Po)throw e;throw new Po(exports.AuthErrorType.SIGNATURE_FAILED,"Failed to generate custom message signature",dt(e)?e:new Error(ut(e)))}}validateWallet(){if(this.ensureWalletProvider(),!this.walletProvider)throw new Po(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Wallet is required for authentication")}async validateWalletAsync(){if(this.ensureWalletProvider(),!this.walletProvider)throw new Po(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Wallet is required for authentication");if(!this.walletProvider.isConnected())throw new Po(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Wallet is not connected. Call connect() on the wallet provider first.")}}const Vo={prod:{...e.GALA_CHAIN_ENVIRONMENTS.prod,bundleBaseUrl:"https://bundle-backend-prod1.defi.gala.com",launchpadBaseUrl:"https://lpad-backend-prod1.defi.gala.com",dexBackendBaseUrl:"https://dex-backend-prod1.defi.gala.com",webSocketUrl:"https://bundle-backend-prod1.defi.gala.com",launchpadFrontendUrl:"https://lpad-frontend-prod1.defi.gala.com"},stage:{...e.GALA_CHAIN_ENVIRONMENTS.stage,bundleBaseUrl:"https://bundle-backend.stage.defi.ovh.gala.com",launchpadBaseUrl:"https://lpad-backend.stage.defi.ovh.gala.com",dexBackendBaseUrl:"https://swap-backend.stage.defi.ovh.gala.com",webSocketUrl:"https://bundle-backend.stage.defi.ovh.gala.com",launchpadFrontendUrl:"https://lpad-frontend-test1.defi.gala.com"}};function jo(e){return Vo[e]}var qo,zo;!function(e){e.PROCESSED="PROCESSED",e.COMPLETED="COMPLETED",e.SUCCESS="SUCCESS",e.FAILED="FAILED",e.ERROR="ERROR",e.PROCESSING="PROCESSING",e.PENDING="PENDING"}(qo||(qo={})),exports.SDKTransactionStatus=void 0,(zo=exports.SDKTransactionStatus||(exports.SDKTransactionStatus={})).PENDING="pending",zo.PROCESSING="processing",zo.COMPLETED="completed",zo.FAILED="failed",zo.TIMEOUT="timeout";const Yo={[qo.PROCESSED]:exports.SDKTransactionStatus.COMPLETED,[qo.COMPLETED]:exports.SDKTransactionStatus.COMPLETED,[qo.SUCCESS]:exports.SDKTransactionStatus.COMPLETED,[qo.FAILED]:exports.SDKTransactionStatus.FAILED,[qo.ERROR]:exports.SDKTransactionStatus.FAILED,[qo.PROCESSING]:exports.SDKTransactionStatus.PROCESSING,[qo.PENDING]:exports.SDKTransactionStatus.PENDING},Xo="9.0.0",Qo={DEFAULT_PAGE_SIZE:50,MAX_PAGE_SIZE:1e3,SAFETY_MAX_PAGES:1e4,DEFAULT_OFFSET:0,DEFAULT_LIMIT:10,BACKEND_MAX_PAGE_SIZE:20};function Jo(e,t=1,n=Qo.BACKEND_MAX_PAGE_SIZE){return Math.max(t,Math.min(n,Math.ceil(e??t)))}function Zo(e){return"string"==typeof e||null===e?e:void 0}function ei(e){if("object"!=typeof e||null===e)return{hasNextPage:!1};const t=Reflect.get(e,"hasNextPage"),n=Reflect.get(e,"hasPreviousPage"),r=Zo(Reflect.get(e,"endCursor")),s=Zo(Reflect.get(e,"startCursor"));return{hasNextPage:!0===t,...void 0===r?{}:{endCursor:r},..."boolean"==typeof n?{hasPreviousPage:n}:{},...void 0===s?{}:{startCursor:s}}}function ti(e,t){const{hasNextPage:n,endCursor:r}=e;if(n&&"string"==typeof r&&""!==r&&r!==t)return r}function ni(e){return"string"==typeof e?e:"number"==typeof e||"boolean"==typeof e||"bigint"==typeof e?String(e):JSON.stringify(e)??""}function ri(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 si={tokenName:"lowercase",address:"lowercase",userAddress:"lowercase",assetId:"as given",targetId:"as given",id:"as given",code:"as given"};function oi(e,t){let n=e;for(const[e,r]of Object.entries(t)){const t=si[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 ii(e,t,n){for(const r of n){const n=t[r];null!=n&&""!==n&&(e[r]=ni(n))}return e}const ai="x-api-key";class ci extends jn{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(!Rn(e))throw Tt("tokenName","Token name");const n=Kt(e);if(!t.PATTERN.test(n))throw vt("tokenName",t.DESCRIPTION,"Token name")}(e,t)}validateRequiredString(e,t,n){!function(e,t,n){if(!Rn(e))throw Tt(t,n)}(e,t,n)}validateOptionalString(e,t,n,r){!function(e,t,n,r){if(null!=e){if("string"!=typeof e)throw _t(t,"string",typeof e,n);if(e.length>r)throw wt(t,r,e.length,n)}}(e,t,n,r)}validateOptionalNumber(e,t,n,r,s,o,i){!function(e,t,n,r,s){if(null!=e){if("number"!=typeof e)throw _t(t,"number",typeof e,n);if(e<r||e>s)throw Nt(t,r,s,e,n)}}(e,t,n,r,s)}validateOptionalDate(e,t,n){!function(e,t,n){if(null!=e&&!Qt(e))throw vt(t,"a valid ISO 8601 date string",n)}(e,t,n)}validatePositiveInteger(e,t,n){Wn(e,t,n)}validateStatusFilter(e,t,n="status"){Vn(e,t,n)}buildPaginationParams(e,t){return ri(e,t)}addOptionalFilterParams(e,t,n){return ii(e,t,n)}buildEndpoint(e,t){return oi(e,t)}buildEndpointWithId(e,t){return e.replace(":id",encodeURIComponent(t))}validateAndBuildTokenEndpoint(e,t,n){return this.validateTokenName(e,t),this.buildEndpoint(n,{tokenName:e})}getAdminHeaders(){if(void 0===this.adminApiKey||""===this.adminApiKey)throw new ct("Admin API key required for this operation. Set streamAdminApiKey in SDK config.");return{[ai]:this.adminApiKey}}getJwtHeaders(){if(!this.jwtAuth)throw new ct("JWT authentication required. Call sdk.login() first.");return this.jwtAuth.getJwtHeaders()}hasJwtAuth(){return this.jwtAuth?.isValid()??!1}hasAdminApiKey(){return void 0!==this.adminApiKey&&""!==this.adminApiKey}getDualAuthHeaders(){return void 0!==this.adminApiKey&&""!==this.adminApiKey?this.getAdminHeaders():this.getJwtHeaders()}getMultiAuthHeaders(){return void 0!==this.userApiKey&&""!==this.userApiKey?{[ai]:this.userApiKey}:this.getJwtHeaders()}extractData(e){return Mt(e,"Backend request failed",!0),Ut(e,"No data in backend response")}extractDataOrNull(e){return Mt(e,"Backend request failed",!1),e.data??null}async toggleFeature(e,t,n){this.validateTokenName(e,n);const r=this.buildEndpoint(t,{tokenName:e}),s=await this.http.post(r,{},this.getAdminHeaders()),o=this.extractData(s);return{enabled:o.enabled,tokenName:o.tokenName??Kt(e)}}}class li extends ci{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async getSettings(){return{settings:(await this.http.get(Be.GET_SETTINGS,{},this.getDualAuthHeaders())).settings}}async updateSettings(e){const t={};void 0!==e.enabled&&(t.enabled=e.enabled),void 0!==e.mode&&(t.mode=e.mode),void 0!==e.provider&&(t.provider=e.provider);return{settings:(await this.http.post(Be.UPDATE_SETTINGS,t,this.getDualAuthHeaders())).settings}}async getModeration(e){this.validatePositiveInteger(e.flagId,"flagId","Flag ID");const t=Be.GET_MODERATION.replace(":flagId",String(e.flagId));return{moderation:(await this.http.get(t,{},this.getDualAuthHeaders())).analysis}}async triggerModeration(e){this.validatePositiveInteger(e.flagId,"flagId","Flag ID");const t=Be.TRIGGER_MODERATION.replace(":flagId",String(e.flagId)),n=await this.http.post(t,{},this.getDualAuthHeaders());return{queued:n.queued,message:n.message.length>0?n.message:"Moderation queued successfully"}}async getStatus(){return{status:(await this.http.get(Be.GET_STATUS,{},this.getDualAuthHeaders())).status}}}const di={MODERATOR:"MODERATOR",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MANAGER:"MANAGER",OWNER:"OWNER"},ui=Un(di),hi={MANAGE_COMMUNITY:"MANAGE_COMMUNITY",MANAGE_STREAM:"MANAGE_STREAM",MANAGE_SETTINGS:"MANAGE_SETTINGS",MANAGE_RECORDINGS:"MANAGE_RECORDINGS",VIEW_ANALYTICS:"VIEW_ANALYTICS"},gi=Object.values(hi);function pi(e){return ui.includes(e)}function mi(e){const t=[];return void 0===e.role||null===e.role?t.push("Role is required"):pi(e.role)||t.push(`Invalid role. Must be one of: ${ui.join(", ")}`),Ei(e,t),t}function fi(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||pi(e.role)||t.push(`Invalid role. Must be one of: ${ui.join(", ")}`),Ei(e,t,!0),t}function Ei(e,t,n=!1){const r=t.length;if(ft(t,()=>{Kn(e.description,"description",255)}),t.length>r&&(t[r]="Description must be 255 characters or less"),void 0!==e.tokenNames){const n=t.length;ft(t,()=>{if(!Array.isArray(e.tokenNames))throw _t("tokenNames","an array",e.tokenNames);if(!e.tokenNames.every(e=>"string"==typeof e))throw _t("tokenNames","contain only strings")});for(let e=n;e<t.length;e++){const n=t[e];n?.includes("array")?t[e]="tokenNames must be an array":n?.includes("string")&&(t[e]="tokenNames must contain only strings")}}if(void 0!==e.expiresAt&&(!n||null!==e.expiresAt)){const n=t.length;ft(t,()=>{Hn(e.expiresAt,"expiresAt")}),t.length>n&&(t[n]="expiresAt must be a valid ISO 8601 date string")}}function Ai(e){if(void 0!==e.pageSize&&("number"!=typeof e.pageSize||e.pageSize<1||e.pageSize>tr))throw _t("pageSize",`number between 1 and ${tr}`,typeof e.pageSize);if(void 0!==e.cursor&&("string"!=typeof e.cursor||""===e.cursor.trim()))throw _t("cursor","non-empty string",typeof e.cursor)}const Ti={[di.MODERATOR]:1,[di.TECHNICAL_PRODUCER]:1,[di.MANAGER]:2,[di.OWNER]:3};class vi extends jn{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),Mt(n,"API key operation failed",!0),e.data}validateApiKeyId(e){this.validatePositiveInteger(e,"id","API key ID")}async create(e){const t=mi(e);if(t.length>0)throw new rt(t.join("; "),"options","VALIDATION_FAILED");this.logger.debug("Creating API key",{role:e.role,delegateAllTokens:e.delegateAllTokens});const n={role:e.role};void 0!==e.description&&(n.description=e.description),void 0!==e.delegateAllTokens&&(n.delegateAllTokens=e.delegateAllTokens),void 0!==e.tokenNames&&e.tokenNames.length>0&&(n.tokenNames=e.tokenNames),void 0!==e.expiresAt&&(n.expiresAt=e.expiresAt),void 0!==e.tokenPermissions&&(n.tokenPermissions=e.tokenPermissions);const r=await this.http.post(W.CREATE,n,this.getJwtHeaders()),s=this.extractData(r);return this.logger.debug("API key created",{id:s.id,keyPrefix:s.keyPrefix}),s}async findAll(e={}){Ai(e),this.logger.debug("Listing API keys",e);const t=ri(e,tr),n=await this.http.get(W.LIST,t,this.getJwtHeaders()),r=this.extractData(n);return this.logger.debug("Listed API keys",{count:r.apiKeys.length,total:r.pageInfo.totalCount}),r}async findOne(e){this.validateApiKeyId(e),this.logger.debug("Getting API key",{id:e});const t=W.GET.replace(":id",String(e)),n=await this.http.get(t,{},this.getJwtHeaders()),r=this.extractData(n);return this.logger.debug("Got API key",{id:r.id,keyPrefix:r.keyPrefix}),r}async update(e,t){this.validateApiKeyId(e);const n=fi(t);if(n.length>0)throw new rt(n.join("; "),"options","VALIDATION_FAILED");this.logger.debug("Updating API key",{id:e,options:t});const r={};void 0!==t.role&&(r.role=t.role),void 0!==t.description&&(r.description=t.description),void 0!==t.delegateAllTokens&&(r.delegateAllTokens=t.delegateAllTokens),void 0!==t.tokenNames&&(r.tokenNames=t.tokenNames),void 0!==t.expiresAt&&(r.expiresAt=t.expiresAt),void 0!==t.tokenPermissions&&(r.tokenPermissions=t.tokenPermissions);const s=W.UPDATE.replace(":id",String(e)),o=await this.http.patch(s,r,this.getJwtHeaders()),i=this.extractData(o);return this.logger.debug("Updated API key",{id:i.id,keyPrefix:i.keyPrefix}),i}async revoke(e){this.validateApiKeyId(e),this.logger.debug("Revoking API key",{id:e});const t=W.REVOKE.replace(":id",String(e));await this.http.delete(t,{},this.getJwtHeaders()),this.logger.debug("API key revoked",{id:e})}getRoles(){return[...ui]}}const Si={VIEWERS:"viewers",CHAT_PARTICIPANTS:"chat_participants"},yi=Ln(Si),bi=Bn([{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}]),Ni=Bn([{field:"tokenName",type:"string",nullable:!0},{field:"isGlobal",type:"boolean"},{field:"isPermanent",type:"boolean"}]),ki=Bn([{field:"tokenName",type:"string",nullable:!0},{field:"isGlobal",type:"boolean"}]),wi=Bn([{field:"tokenName",type:"string"},{field:"action",type:"string",validator:e=>"CHAT_MESSAGE"===e||"COMMENT"===e||"REACTION"===e}]);function _i(e){return null==e||""===e||"string"==typeof e&&(!$n(e)&&e.length<=or.BAN_REASON.MAX_LENGTH)}function Ii(e){return!!xn(e)||"number"==typeof e&&(e>=ar&&e<=cr)}function Ci(e){if(!Rn(e.userAddress))throw Tt("userAddress");if(!_i(e.reason))throw new rt(`reason must be at most ${or.BAN_REASON.MAX_LENGTH} characters`,"reason","TOO_LONG");if(!Ii(e.durationSeconds))throw new rt(`durationSeconds must be between ${ar} and ${cr} seconds`,"durationSeconds","OUT_OF_RANGE")}class Di extends ci{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async createBan(e){!function(e){Fn(e.tokenName,"tokenName",Jn),Ci(e)}(e);const t=this.buildEndpoint(L,{tokenName:e.tokenName}),n=Ri(e),r=await this.http.post(t,n,this.getMultiAuthHeaders());return{ban:this.extractData(r),tokenName:Kt(e.tokenName)}}async removeBan(e){!function(e){if(Fn(e.tokenName,"tokenName",Jn),!Rn(e.userAddress))throw Tt("userAddress")}(e);const t=en(e.userAddress,"userAddress"),n=this.buildEndpoint(P,{tokenName:e.tokenName,userAddress:t}),r=await this.http.delete(n,{},this.getMultiAuthHeaders()),s=this.extractDataOrNull(r);return{removed:s?.removed??!0,tokenName:Kt(e.tokenName),userAddress:s?.userAddress??t}}async listBans(e){!function(e){Fn(e.tokenName,"tokenName",Jn),Mn(0,void 0,tr,e.pageSize)}(e);const t=this.buildEndpoint(U,{tokenName:e.tokenName}),n=this.buildPaginationParams(e,tr);this.addOptionalFilterParams(n,e,["search","name","userAddress"]),void 0!==n.userAddress&&(n.userAddress=nn(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(Fn(e.tokenName,"tokenName",Jn),!Rn(e.userAddress))throw Tt("userAddress")}(e);const t=en(e.userAddress,"userAddress"),n=this.buildEndpoint(F,{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:Kt(e.tokenName),userAddress:t}}async getActiveUsers(e){!function(e){if(Fn(e.tokenName,"tokenName",Jn),void 0!==e.type&&!yi(e.type))throw new rt(`type must be one of: ${Object.values(Si).join(", ")}`,"type",nt.INVALID_VALUE)}(e);const t=this.buildEndpoint(B,{tokenName:e.tokenName}),n={};this.addOptionalFilterParams(n,e,["type","search","name","userAddress"]),void 0!==n.userAddress&&(n.userAddress=nn(n.userAddress));const r=await this.http.get(t,n,this.getMultiAuthHeaders());return this.extractData(r)}async createGlobalBan(e){!function(e){Ci(e)}(e);const t=Ri(e),n=await this.http.post(G,t,this.getDualAuthHeaders());return{ban:this.extractData(n)}}async removeGlobalBan(e){!function(e){if(!Rn(e.userAddress))throw Tt("userAddress")}(e);const t=en(e.userAddress,"userAddress"),n=this.buildEndpoint(H,{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){Mn(0,void 0,tr,e.pageSize)}(t);const n=this.buildPaginationParams(t,tr);this.addOptionalFilterParams(n,t,["search","name","userAddress"]),void 0!==n.userAddress&&(n.userAddress=nn(n.userAddress));const r=await this.http.get($,n,this.getDualAuthHeaders()),s=this.extractData(r);return{items:s.bans,pageInfo:s.pageInfo}}async getGlobalBan(e){!function(e){if(!Rn(e.userAddress))throw Tt("userAddress")}(e);const t=en(e.userAddress,"userAddress"),n=this.buildEndpoint(K,{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 Ri(e){const t={userAddress:en(e.userAddress,"userAddress")};return void 0!==e.reason&&(t.reason=e.reason),void 0!==e.durationSeconds&&(t.durationSeconds=e.durationSeconds),t}function Oi(e){return{maxAcceptableReverseBondingCurveFee:bn(e.maxAcceptableReverseBondingCurveFee)}}class xi extends s.ChainCallDTO{constructor(e,t,n="0",r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=bn(t),this.expectedToken=Nn(n),this.extraFees=Oi(r)}}class Mi extends s.ChainCallDTO{constructor(e,t,n,r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=Nn(t),this.expectedNativeToken=bn(n),this.extraFees=Oi(r)}}class Li extends s.ChainCallDTO{constructor(e,t,n="0",r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=Nn(t),this.expectedNativeToken=bn(n),this.extraFees=Oi(r)}}class Ui extends s.ChainCallDTO{constructor(e,t,n,r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=bn(t),this.expectedToken=Nn(n),this.extraFees=Oi(r)}}const Fi={BuyNativeDto:xi,BuyExactDto:Mi,SellExactDto:Li,SellNativeDto:Ui};function Pi(e,t,n){let r;kn(t,0,1,"slippageToleranceFactor");try{r=function(e,t){if(zt(e)||""===e)throw Tt(t);if(a.isBigNumber(e)){if(e.isNaN())throw It(t,"NaN");return e}try{const n=new a(e);if(n.isNaN())throw It(t,e);if(!n.isFinite())throw It(t,e);return n}catch(n){if(n instanceof rt)throw n;throw It(t,e)}}(e,"expectedAmount")}catch{throw new Error(`Invalid expected amount: ${e}. Must be a valid number`)}if(0===t)return e;const s=r.multipliedBy(t);let o;switch(n){case"buy-native":case"sell-exact":o=r.minus(s);break;case"buy-exact":case"sell-native":o=r.plus(s);break;default:throw new Error(`Unknown operation type: ${n}`)}return Eo(o).isLessThan(0)&&(o=Eo(0)),Ao(o)}function Bi(e,t){if(!Rn(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 Gi(e,t,n,r){const s=e?.split?.(t)??[],o=void 0!==n?` (${n})`:"";return new rt(`Invalid ${"|"===t?"pipe":"dollar"}-delimited token: "${e}" (${s.length} parts)${o}. Expected format: "collection${t}category${t}type${t}additionalKey" (4 parts minimum). Received: [${s.map(e=>`"${e}"`).join(", ")}]. Error: ${ut(r)}`,"token",`INVALID_${"|"===t?"PIPE":"DOLLAR"}_DELIMITED_TOKEN`)}function $i(e,t,n){try{const n=Bi(e,t),r=n[n.length-1],s=n[n.length-2],o=n[n.length-3],i=n.slice(0,n.length-3).join(t);if(void 0===i||void 0===o||void 0===s||void 0===r||""===r||""===i||""===o||""===s)throw new Error("All components (collection, category, type, additionalKey) must be non-empty");return{collection:i,category:o,type:s,additionalKey:r}}catch(r){throw Gi(e,t,n,r)}}function Ki(e){return function(e,t,n){try{const n=Bi(e,t),[r,s,o,...i]=n;if(""===r||""===s||""===o)throw new Error("Collection, category, and type must be non-empty");const a=i.join(t);if(void 0===r||void 0===s||void 0===o||""===a)throw new Error("AdditionalKey must be non-empty");return{collection:r,category:s,type:o,additionalKey:a}}catch(r){throw Gi(e,t,n,r)}}(e,"|","pipe-delimited token")}class Hi 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 Wi={name:"GalaChain"},Vi={name:"ethereum",chainId:1};function ji(e){if("string"!=typeof e)throw new Error("Wallet returned an invalid signature");return e}function qi(e,t){const n=Jt(e,t);if(void 0!==n)throw new Hi(n,"INVALID_SIGNER_OPTIONS",{details:{[t]:e}});return e}function zi(e){const t={};for(const[n,r]of Object.entries(e))void 0!==r&&(t[n]=Yi(r));return t}function Yi(e){return Array.isArray(e)?e.map(Yi):"object"==typeof e&&null!==e?zi(e):e}function Xi(e,t,n,r){return{...e,signature:t,types:n,domain:r}}class Qi extends e.PrivateKeySigner{constructor(e){super(e),this.typedDataWallet=new t.Wallet(e),this.walletAddress=`eth|${this.typedDataWallet.address.slice(2)}`}async signTypedData(t,n){const r=zi(n),s=e.generateEIP712Types(t,r);return Xi(r,await this.typedDataWallet.signTypedData(Wi,s,r),s,Wi)}}class Ji extends e.GalaWalletSigner{constructor(t,n={}){const{verifyActiveAccount:r,...s}=n;if(super(qi(t,"walletAddress"),{...s,...void 0!==s.selectAddress&&{selectAddress:qi(s.selectAddress,"selectAddress")}}),this.typedDataWallet=n.wallet,!0===r){const t=e.ethereumAddressOfAccount(this.walletAddress)??(void 0===this.selectAddress?void 0:e.ethereumAddressOfAccount(this.selectAddress));if(void 0===t)throw new Hi("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=t}else this.verifiedKey=void 0}async signTypedData(t,n){const r=zi(n),s=e.generateEIP712Types(t,r),o={domain:Vi,types:s,message:r,Primary_type:t},i=this.typedDataWallet??function(){const e=globalThis.window,t=e?.gala;if(void 0===t)throw new Error("Gala wallet is not available");return t}();void 0!==this.verifiedKey&&await async function(t,n){let r="address"in t&&"string"==typeof t.address&&""!==t.address?t.address:void 0;if(void 0===r){const e=await t.request({method:"eth_accounts"}),n=Array.isArray(e)?e[0]:void 0;r="string"==typeof n&&""!==n?n:void 0}const s=void 0===r?void 0:e.ethereumAddressOfAccount(r);if(void 0===s||s.toLowerCase()!==n.toLowerCase())throw new Hi("Your wallet's active account has changed. Please switch back to the connected account or reconnect your wallet.","WALLET_ACCOUNT_CHANGED",{details:{walletAccount:r??null,signerAccount:n}})}(i,this.verifiedKey);const a=await this.typedDataAccount(i);return Xi(r,ji(await e.withGalaWalletIdentity(i,this.selectAddress??a,()=>i.request({method:"eth_signTypedData",params:[JSON.stringify(o),a]}))),s,Vi)}async typedDataAccount(e){if(t.isAddress(this.walletAddress))return this.walletAddress;const n=await e.request({method:"eth_accounts"}),r=Array.isArray(n)?n[0]:void 0,s="string"==typeof r?r.replace(/^eth\|/,"0x"):"";if(!t.isAddress(s))throw new Error("Gala Wallet did not report an Ethereum account to sign typed data with");return s}}class Zi extends e.BrowserWalletSigner{constructor(e,t,n){super(e,qi(t,"walletAddress"),n),this.typedDataProvider=e}async signTypedData(n,r){const s=zi(r),o=this.typedDataProvider,i=await o.getNetwork(),a={name:i.name,chainId:Number(i.chainId)},c=e.generateEIP712Types(n,s),l=await o.getSigner(),d=t.getAddress(await l.getAddress());if(t.isAddress(this.walletAddress)&&d!==t.getAddress(this.walletAddress))throw new Hi(`Wallet account ${d} is not the account this signer was created for (${this.walletAddress}); reconnect before signing.`,"WALLET_ACCOUNT_CHANGED",{details:{walletAccount:d,signerAccount:this.walletAddress}});return Xi(s,ji(await l.signTypedData(a,c,s)),c,a)}static fromEip1193(n,r,s){const o=new t.BrowserProvider(n);return new Zi({request:e=>n.request(e),getNetwork:()=>o.getNetwork(),getSigner:()=>o.getSigner()},e.ethereumAddressOfAccount(r)??r,s)}}function ea(e){const[t,n]=e.split("|",2);if("service"!==t||void 0===n)throw new Error(`Invalid vaultAddress format (expected service|<collection>$<category>$<type>$<additionalKey>$launchpad): ${e}`);const r=n.split("$"),s=r[r.length-1],o=r.slice(0,-1),i=o.slice(0,-3).join("$"),[a,c,l]=o.slice(-3);if("launchpad"!==s||o.length<4||""===i||void 0===a||void 0===c||void 0===l||""===a||""===c||""===l)throw new Error(`Invalid vaultAddress format (expected service|<collection>$<category>$<type>$<additionalKey>$launchpad): ${e}`);return{collection:i,category:a,type:c,additionalKey:l}}function ta(e){const{collection:t,category:n,type:r}=ea(e),s=`${t}$${n}$${r}$none`,o="GALA$Unit$none$none";return[`$service$${s}$launchpad`,`$tokenBalance$${s}$${e}`,`$tokenBalance$${s}$${e}`,`$tokenBalance$${o}$${e}`,`$tokenBalance$${o}$${e}`]}function na(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 ra(e){return`${e.collection}|${e.category}|${e.type}|${e.additionalKey}`}function sa(t){if("string"==typeof t){if(!Rn(n=t)||!n.includes("|"))throw new rt(`Invalid tokenId string format: "${t}". Expected pipe-delimited format: "collection|category|type|additionalKey" or "collection|category|type|additionalKey|instance"`,"tokenId","INVALID_TOKEN_ID_FORMAT");const e=t.split("|");if(e.length>=5){const t=Ki(e.slice(0,4).join("|")),n=e[4]??"0";return{...t,instance:n.length>0?n:"0"}}return{...Ki(t),instance:"0"}}var n;if("object"==typeof t&&null!==t){if("instance"in t&&void 0!==t.instance&&"string"==typeof t.instance&&t.instance.length>0){if(!e.isTokenClassKey(t))throw new rt("Invalid tokenId object format. All fields (collection, category, type, additionalKey) must be non-empty strings","tokenId","INVALID_TOKEN_ID_FORMAT");return t}if(!e.isTokenClassKey(t))throw new rt("Invalid tokenId object format. All fields (collection, category, type, additionalKey) are required","tokenId","INVALID_TOKEN_ID_FORMAT");return{...t,instance:"0"}}throw new rt(`Invalid tokenId type: ${typeof t}. Expected string, TokenClassKey, or TokenInstanceKey`,"tokenId","INVALID_TOKEN_ID_TYPE")}function oa(e){return function(e){try{if(!Rn(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 $i((n.length>=5&&"launchpad"===n[n.length-1]?n.slice(0,-1):n).join("$"),"$","vault address")}catch(t){throw new rt(`Invalid vault address: "${e}". Expected format: "service|Token$Unit$SYMBOL$additionalKey$launchpad". Error: ${ut(t)}`,"vaultAddress","INVALID_VAULT_ADDRESS_FORMAT")}}(e)}function ia(e){return{...oa(e),instance:"0"}}function aa(e){const t=oa(e);if("Token"!==t.collection)throw new rt(`Cannot extract a token symbol from vault address "${e}": collection "${t.collection}" is not the launchpad "Token" collection, and a symbol cannot be derived from a class key.`,"vaultAddress","SYMBOL_NOT_DERIVABLE_FROM_KEY");return t.type}var ca,la,da,ua,ha=Object.freeze({__proto__:null,extractTokenSymbolFromVault:aa,normalizeToTokenInstanceKey:sa,parseVaultAddressToTokenClassKey:oa,parseVaultAddressToTokenInstance:ia});class ga extends qn{constructor(e=!1){super(e)}generateStringsInstructions(e){try{this.logger.debug("🔧 Generating stringsInstructions for:",e);const t=ta(e);return this.logger.debug("✅ Generated stringsInstructions:",t),t}catch(e){this.logger.error("❌ Failed to generate stringsInstructions:",e);const t=ut(e);throw new rt(`Failed to generate stringsInstructions: ${t}`,"vaultAddress","INVALID_VAULT_ADDRESS")}}createGalaInstance(){const e=new s.TokenClassKey;return e.collection="GALA",e.category="Unit",e.type="none",e.additionalKey="none",this.logger.debug("🟡 Created GALA instance:",{stringKey:e.toStringKey()}),e}extractTokenSymbolFromVault(e){if(!Rn(e))throw Tt("vaultAddress","Vault address");try{const t=aa(e);return this.logger.debug("🔍 Extracted token symbol:",{vaultAddress:e,tokenSymbol:t}),t}catch(e){if(e instanceof rt)throw vt("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad");throw e}}validateVaultAddress(e){if(!Rn(e))throw Tt("vaultAddress","Vault address");if(!e.startsWith("service|Token$Unit$"))throw vt("vaultAddress",'starting with "service|Token$Unit$"');if(!e.endsWith("$launchpad"))throw vt("vaultAddress",'ending with "$launchpad"');const t=function(e){if(!Rn(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 $i(e,"$","dollar-delimited token")}catch(e){if(e instanceof rt)throw vt("stringKey","format: collection$category$type$additionalKey (4 parts)");throw e}}}function pa(e){return"object"==typeof e&&null!==e?e:void 0}class ma extends jn{constructor(t,n,r=!1,s,o,i=.05,a=.01,c){if(super(t,r),this.tokenResolver=n,this._walletProvider=s,this.userAddress=o,this.defaultSlippageToleranceFactor=i,this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor=a,this.sellFeeCeiling=c,this.bundleEndpoint="/bundle",null!==this._walletProvider&&void 0!==this._walletProvider&&null!=o){const t=pa(this._walletProvider),n=t?.privateKey;if("string"==typeof n)this.signer=new Qi(n);else if(function(e){const t=pa(e);return"function"==typeof t?.request}(this._walletProvider)&&void 0!==this.userAddress){const t=Zt(this.userAddress,"userAddress");this.signer=new Zi(this._walletProvider,e.ethereumAddressOfAccount(t)??t)}this.tokenKeyService=new ga(r)}}async submitTransaction(e){try{this.validateBundleData(e),this.logger.debug("📦 Submitting bundle transaction:",{method:e.method,stringsInstructionsCount:e.stringsInstructions.length,signedDtoKeys:Object.keys(e.signedDto)});const t=this.formatBundleRequest(e);this.logger.debug("🚀 Bundle request payload:",{...t,signedDto:"[REDACTED - Contains signature]"});let n=null;try{n=await Pt(()=>this.http.post(this.bundleEndpoint,t),{errorContext:"Bundle transaction submission failed",logger:this.logger})}catch(e){return{success:!1,error:this.formatErrorMessage(e)}}return null==n?{success:!1,error:"No response from bundle API"}:(this.logger.debug("📥 Bundle API response:",{success:n.success,hasData:xt(n),error:n.error}),this.handleBundleResponse(n))}catch(e){if(e instanceof rt)return{success:!1,error:ut(e)};throw e}}validateBundleData(e){if(null==e)throw Tt("bundleData","Bundle data");if(null===e.signedDto||void 0===e.signedDto)throw Tt("signedDto","Signed DTO");if(!Rn(e.method))throw Tt("method","Method name");if(!Array.isArray(e.stringsInstructions))throw vt("stringsInstructions","an array of resource tracking strings");if(0===e.stringsInstructions.length)throw new rt("stringsInstructions cannot be empty","stringsInstructions","EMPTY_ARRAY");const t=["BuyWithNative","BuyExactToken","SellExactToken","SellWithNative"];if(!t.includes(e.method))throw vt("method",`one of: ${t.join(", ")}`);e.stringsInstructions.forEach((e,t)=>{if(!Rn(e))throw new rt(`stringsInstructions[${t}] must be a non-empty string`,`stringsInstructions[${t}]`,"INVALID_INSTRUCTION");if("string"!=typeof(n=e)||!n.includes("$"))throw new rt(`stringsInstructions[${t}] must start with '$': ${e}`,`stringsInstructions[${t}]`,"INVALID_INSTRUCTION_FORMAT");var n}),this.logger.debug("✅ Bundle data validation passed")}formatBundleRequest(e){return{signedDto:e.signedDto,stringsInstructions:e.stringsInstructions,method:e.method}}handleBundleResponse(e){const t=Lt(e);if(null!=t&&!1===e.error)return this.logger.debug("✅ Bundle transaction successful:",t),{success:!0,data:t};const n=("string"==typeof e.error?e.error:e.message)??"Bundle transaction failed";return this.logger.debug("❌ Bundle transaction failed:",n),{success:!1,error:n}}formatErrorMessage(e){if("string"==typeof e)return e;if(pt(e)&&null!==e.response&&void 0!==e.response){const t=Lt(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(!Rn(e))throw Tt("transactionId","Transaction ID");let t;this.logger.debug("🔍 Checking bundler transaction result:",e);try{t=await Pt(()=>this.http.get(`${this.bundleEndpoint}?id=${e}`),{errorContext:"Failed to get bundler transaction result",logger:this.logger})}catch(e){return{success:!1,error:this.formatErrorMessage(e)}}return null==t?{success:!1,error:"No response from bundler transaction query"}:(this.logger.debug("📊 Bundler transaction result:",t),{success:!0,data:t})}catch(e){if(e instanceof rt)return{success:!1,error:ut(e)};throw e}}async cancelTransaction(e){try{if(!Rn(e))throw Tt("transactionId","Transaction ID");let t;this.logger.debug("🚫 Cancelling transaction:",e);try{t=await Pt(()=>this.http.delete(`${this.bundleEndpoint}/${e}`),{errorContext:"Failed to cancel transaction",logger:this.logger})}catch(e){return{success:!1,error:this.formatErrorMessage(e)}}return null==t?{success:!1,error:"No response from transaction cancellation"}:(this.logger.debug("🗑️ Transaction cancellation response:",t),{success:!0,data:t})}catch(e){if(e instanceof rt)return{success:!1,error:ut(e)};throw e}}async getHealthStatus(){this.logger.debug("🏥 Checking bundle service health");try{const e=await Pt(()=>this.http.get(`${this.bundleEndpoint}/health`),{errorContext:"Bundle service health check failed",logger:this.logger});return null==e?{success:!1,error:"No response from bundle service health check"}:(this.logger.debug("💚 Bundle service health:",e),{success:!0,data:e})}catch(e){return{success:!1,error:this.formatErrorMessage(e)}}}async buyToken(e){this.ensureTradingServicesAvailable();const{tokenName:t,amount:n,type:r,expectedAmount:s}=e,{effectiveSlippageFactor:o,effectiveMaxFee:i,vaultAddress:a}=await this.prepareTradingOperation(t,e.maxAcceptableReverseBondingCurveFee,e.maxAcceptableReverseBondingCurveFeeSlippageFactor,e.slippageToleranceFactor);if("native"===r){if(null==s||""===s)throw new rt("expectedAmount is required for native buy operations. Use getBuyTokenAmount() first to calculate expected tokens.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Pi(s,o,"buy-native");this.logger.debug("BuyNative slippage applied:",{originalExpectedTokens:s,slippageFactor:o,adjustedMinTokens:e});const t=new Fi.BuyNativeDto(a,n,e,{maxAcceptableReverseBondingCurveFee:i});return await this.executeBundleTransaction(t,"BuyWithNative",a)}{if(null==s||""===s)throw new rt("expectedAmount is required for exact buy operations. Use getBuyTokenAmount() first to calculate expected GALA cost.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Pi(s,o,"buy-exact");this.logger.debug("BuyExact slippage applied:",{originalExpectedGalaCost:s,slippageFactor:o,adjustedMaxGalaCost:e});const t=new Fi.BuyExactDto(a,n,e,{maxAcceptableReverseBondingCurveFee:i});return await this.executeBundleTransaction(t,"BuyExactToken",a)}}async sellToken(e){this.ensureTradingServicesAvailable();const{tokenName:t,amount:n,type:r,expectedAmount:s}=e,{effectiveSlippageFactor:o,effectiveMaxFee:i,vaultAddress:a}=await this.prepareTradingOperation(t,e.maxAcceptableReverseBondingCurveFee,e.maxAcceptableReverseBondingCurveFeeSlippageFactor,e.slippageToleranceFactor),c=async()=>void 0===e.maxAcceptableReverseBondingCurveFee?this.defaultSellFeeCeiling(e,a):i;if("exact"===r){if(null==s||""===s)throw new rt("expectedAmount is required for exact sell operations. Use getSellTokenAmount() first to calculate expected GALA.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Pi(s,o,"sell-exact");this.logger.debug("SellExact slippage applied:",{originalExpectedGala:s,slippageFactor:o,adjustedMinGala:e});const t={maxAcceptableReverseBondingCurveFee:await c()},r=new Fi.SellExactDto(a,n,e,t);return await this.executeBundleTransaction(r,"SellExactToken",a)}{if(null==s||""===s)throw new rt("expectedAmount is required for native sell operations. Use getSellTokenAmount() first to calculate tokens to sell.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Pi(s,o,"sell-native");this.logger.debug("SellNative slippage applied:",{originalExpectedTokensToSell:s,slippageFactor:o,adjustedMaxTokensToSell:e});const t={maxAcceptableReverseBondingCurveFee:await c()},r=new Fi.SellNativeDto(a,n,e,t);return await this.executeBundleTransaction(r,"SellWithNative",a)}}async prepareTradingOperation(e,t,n,r){const{effectiveSlippageFactor:s,effectiveMaxFee:o}=this.calculateEffectiveSlippage(t,n,r),i=await this.resolveTokenNameToVault(e);if(null==i)throw At(e);return{effectiveSlippageFactor:s,effectiveMaxFee:o,vaultAddress:i}}async defaultSellFeeCeiling(e,t){if(void 0===this.sellFeeCeiling)throw yt("Cannot quote the reverse bonding curve fee for this sell. Pass maxAcceptableReverseBondingCurveFee.","maxAcceptableReverseBondingCurveFee");return this.sellFeeCeiling({method:"exact"===e.type?"SellExactToken":"SellWithNative",vaultAddress:t,quantity:e.amount,tokenName:e.tokenName,feeSlippageFactor:e.maxAcceptableReverseBondingCurveFeeSlippageFactor??this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor})}calculateEffectiveSlippage(e,t,n){const r=n??this.defaultSlippageToleranceFactor,s=t??this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor;let o=e??"0";return null!=e&&(o=Pi(e,s,"buy-exact"),this.logger.debug("Reverse bonding curve fee slippage applied:",{baseFee:e,slippageFactor:s,adjustedMaxFee:o})),{effectiveSlippageFactor:r,effectiveFeeSlippageFactor:s,effectiveMaxFee:o}}ensureTradingServicesAvailable(){if(!this.signer||!this.tokenKeyService)throw yt("Trading services not available. BundleService requires walletProvider and userAddress for trading operations.","walletProvider");if(null===this.userAddress||void 0===this.userAddress)throw Tt("userAddress","User address")}async executeBundleTransaction(e,t,n){this.ensureTradingServicesAvailable();try{e.uniqueKey=`galaswap-operation-${Date.now()}_${o.v4().replace(/-/gu,"").substring(0,26)}`;const r=await this.signer.signObject(t,e),s=this.tokenKeyService.generateStringsInstructions(n),i={stringsInstructions:s,method:t,signedDto:r};this.logger.debug("📦 Bundle transaction data:",{method:t,stringsInstructions:s,dtoKeys:Object.keys(r)});const a=await this.submitTransaction(i);if(a.success){const e=Lt(a);if(null!=e)return this.logger.debug("✅ Bundle transaction submitted:",e),{success:!0,data:{transactionId:e,message:"Transaction submitted successfully. Monitor WebSocket for completion."}}}const c=a.error;throw new lt("string"==typeof c?c:"Bundle transaction failed",void 0,"BUNDLE_FAILED")}catch(e){throw this.logger.error("❌ Bundle transaction error:",e),e}}async resolveTokenNameToVault(e){return await this.tokenResolver.resolveTokenToVault(e)}}class fa extends jn{constructor(e,t=!1){super(e,t)}extractData(e){if(e.error||void 0===e.data){const t=e.message??"Client config operation failed";throw new Error(t)}return e.data}async getClientFlags(){this.logger.debug("Fetching client feature flags");const e=await this.http.get(Xe),t=this.extractData(e);return this.logger.debug("Fetched client feature flags",{flagCount:Object.keys(t.flags).length}),{flags:t.flags}}}exports.ContentType=void 0,(ca=exports.ContentType||(exports.ContentType={})).CHAT_MESSAGE="CHAT_MESSAGE",ca.COMMENT="COMMENT",ca.STREAM="STREAM",ca.RECORDING="RECORDING",exports.FlagReason=void 0,(la=exports.FlagReason||(exports.FlagReason={})).INAPPROPRIATE_CONTENT="INAPPROPRIATE_CONTENT",la.SPAM="SPAM",la.HARASSMENT="HARASSMENT",la.SCAM="SCAM",la.OTHER="OTHER",exports.FlagStatus=void 0,(da=exports.FlagStatus||(exports.FlagStatus={})).PENDING="PENDING",da.DISMISSED="DISMISSED",da.ACTIONED="ACTIONED",exports.FlagAction=void 0,(ua=exports.FlagAction||(exports.FlagAction={})).DELETE_CONTENT="DELETE_CONTENT",ua.BAN_USER="BAN_USER",ua.DELETE_AND_BAN="DELETE_AND_BAN";const Ea={[exports.FlagReason.INAPPROPRIATE_CONTENT]:"Inappropriate Content",[exports.FlagReason.SPAM]:"Spam",[exports.FlagReason.HARASSMENT]:"Harassment",[exports.FlagReason.SCAM]:"Scam",[exports.FlagReason.OTHER]:"Other"},Aa={[exports.FlagStatus.PENDING]:"Pending",[exports.FlagStatus.DISMISSED]:"Dismissed",[exports.FlagStatus.ACTIONED]:"Actioned"},Ta={[exports.FlagAction.DELETE_CONTENT]:"Delete Content",[exports.FlagAction.BAN_USER]:"Ban User",[exports.FlagAction.DELETE_AND_BAN]:"Delete & Ban"},va={[exports.ContentType.CHAT_MESSAGE]:"Chat Message",[exports.ContentType.COMMENT]:"Comment",[exports.ContentType.STREAM]:"Stream",[exports.ContentType.RECORDING]:"Recording"},Sa=Ln(exports.ContentType),ya=Ln(exports.FlagReason),ba=Ln(exports.FlagStatus),Na=Ln(exports.FlagAction),ka=Bn([{field:"id",type:"number"},{field:"tokenName",type:"string"},{field:"contentType",type:"string",validator:Sa},{field:"contentId",type:"string"},{field:"reporterAddress",type:"string"},{field:"reportedUserAddress",type:"string"},{field:"status",type:"string",validator:ba}]),wa={TOKEN_NAME:Xn,TOKEN_NAME_FILTER:Qn,CONTENT_ID:or.CONTENT_ID,DETAILS:or.FLAG_DETAILS,PAGINATION:{MAX_LIMIT:tr}};function _a(e,t,n="tokenName"){Fn(e,n,t)}function Ia(e){if(void 0!==e.contentType&&!Sa(e.contentType))throw vt("contentType",`one of: ${Object.values(exports.ContentType).join(", ")}`,"Content type");if(void 0!==e.status&&!ba(e.status))throw vt("status",`one of: ${Object.values(exports.FlagStatus).join(", ")}`);if(void 0!==e.reason&&!ya(e.reason))throw vt("reason",`one of: ${Object.values(exports.FlagReason).join(", ")}`);if(void 0!==e.reporterAddress&&!Rn(e.reporterAddress))throw _t("reporterAddress","a non-empty string",typeof e.reporterAddress);if(void 0!==e.reporterAddress&&mn(e.reporterAddress,"reporterAddress"),void 0!==e.reportedUserAddress&&!Rn(e.reportedUserAddress))throw _t("reportedUserAddress","a non-empty string",typeof e.reportedUserAddress);void 0!==e.reportedUserAddress&&mn(e.reportedUserAddress,"reportedUserAddress"),Mn(0,void 0,wa.PAGINATION.MAX_LIMIT,e.pageSize)}class Ca extends ci{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async createFlag(e){!function(e){if(_a(e.tokenName,wa.TOKEN_NAME),void 0===e.contentType)throw Tt("contentType","Content type");if(!Sa(e.contentType))throw vt("contentType",`one of: ${Object.values(exports.ContentType).join(", ")}`,"Content type");if(!Rn(e.contentId))throw Tt("contentId","Content ID");if(e.contentId.length>wa.CONTENT_ID.MAX_LENGTH)throw wt("contentId",wa.CONTENT_ID.MAX_LENGTH,e.contentId.length,"Content ID");if(!Rn(e.reportedUserAddress))throw Tt("reportedUserAddress","Reported user address");if(mn(e.reportedUserAddress,"reportedUserAddress"),!(e.contentType!==exports.ContentType.STREAM&&e.contentType!==exports.ContentType.RECORDING||void 0!==e.reason&&null!==e.reason))throw Tt("reason","Reason");if(void 0!==e.reason&&!ya(e.reason))throw vt("reason",`one of: ${Object.values(exports.FlagReason).join(", ")}`,"Reason");if(void 0!==e.details&&!Rn(e.details))throw _t("details","a non-empty string",typeof e.details);if(void 0!==e.details&&e.details.length>wa.DETAILS.MAX_LENGTH)throw wt("details",wa.DETAILS.MAX_LENGTH,e.details.length)}(e);const t={tokenName:e.tokenName,contentType:e.contentType,contentId:e.contentId,reportedUserAddress:tn(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(Z.CREATE,t,this.getMultiAuthHeaders());return{flag:this.extractData(n).flag}}async listFlags(e){return function(e){_a(e.tokenName,wa.TOKEN_NAME_FILTER),Ia(e)}(e),this.fetchFlagList(e)}async listGlobalFlags(e={}){return function(e){void 0!==e.tokenName&&_a(e.tokenName,wa.TOKEN_NAME_FILTER),Ia(e)}(e),this.fetchFlagList(e)}async dismissFlag(e){!function(e){if(void 0===e.flagId||null===e.flagId)throw Tt("flagId","Flag ID");try{_n(e.flagId,"flagId")}catch{throw vt("flagId","a positive integer","Flag ID")}}(e);const t=Z.DISMISS.replace(":id",e.flagId.toString()),n=await this.http.post(t,{},this.getMultiAuthHeaders());return{flag:this.extractData(n).flag}}async actionFlag(e){!function(e){if(void 0===e.flagId||null===e.flagId)throw Tt("flagId","Flag ID");try{_n(e.flagId,"flagId")}catch{throw vt("flagId","a positive integer","Flag ID")}if(void 0===e.action)throw Tt("action","Action");if(!Na(e.action))throw vt("action",`one of: ${Object.values(exports.FlagAction).join(", ")}`,"Action")}(e);const t=Z.ACTION.replace(":id",e.flagId.toString()),n=await this.http.post(t,{action:e.action},this.getMultiAuthHeaders());return{flag:this.extractData(n).flag}}async fetchFlagList(e){const t=ri(e,tr);ii(t,e,["tokenName","contentType","status","reason","reporterAddress","reportedUserAddress"]);for(const e of["reporterAddress","reportedUserAddress"]){const n=t[e];void 0!==n&&(t[e]=tn(n,e))}const n=await this.http.get(Z.LIST,t,this.getMultiAuthHeaders()),r=this.extractData(n);return{items:r.flags,pageInfo:r.pageInfo}}}const Da=["heart","fire","laugh","wow","thumbs_up"];class Ra extends ci{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}validateMessageId(e){if(!Rn(e))throw Tt("messageId","Message ID");if(wn(e,ir.CONTENT_REACTION.MAX_LENGTH,"messageId"),!ir.CONTENT_REACTION.PATTERN.test(e))throw vt("messageId","msg-{timestamp}-{uuid} or chat-{timestamp}-{uuid} format","Message ID")}validateReactionType(e){if(!Rn(e))throw Tt("reactionType","Reaction type");if(!Da.includes(e))throw vt("reactionType",`one of: ${Da.join(", ")}`,"Reaction type")}async addContentReaction(e){this.validateMessageId(e.messageId),this.validateReactionType(e.reactionType);const t=we,n={messageId:e.messageId,reactionType:e.reactionType},r=await this.http.post(t,n,this.getMultiAuthHeaders()),s=this.extractData(r),{created:o,...i}=s;return{data:i,created:o}}async removeContentReaction(e){this.validateMessageId(e.messageId),this.validateReactionType(e.reactionType);const t=`${_e}?${new URLSearchParams({messageId:e.messageId,reactionType:e.reactionType}).toString()}`;return await this.http.delete(t,{},this.getMultiAuthHeaders()),{success:!0}}async addReactionToChatMessage(e){return this.addContentReaction(e)}async removeReactionFromChatMessage(e){return this.removeContentReaction(e)}async addReactionToComment(e){return this.addContentReaction(e)}async removeReactionFromComment(e){return this.removeContentReaction(e)}}const Oa="Token name is required and must be a string";const xa="GALA|Unit|none|none";class Ma extends qn{constructor(e,t,n,r=!1){super(r),this.dexBackendHttp=e,this.cache=t,this.fetchTokenDetails=n}async fetchLaunchpadTokenSpotPrice(e,t,n){if(!Rn(e))throw new rt(Oa,"tokenName",nt.REQUIRED);let r;if(void 0!==n)try{this.logger.debug(`Checking graduation status for token: ${e}`);const t=await n(e);!0===t.isGraduated&&(r=ra(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(xa),s=Tn(n.amount,0)/1e18;if(s<=0)throw new rt(`Invalid token amount calculation: ${s}`,"amount","INVALID_CALCULATION");return{symbol:Ht(e),price:r.price/s}}catch(t){throw St(`Failed to calculate launchpad token spot price for ${e}: ${ut(t)}`,void 0,dt(t)?t:void 0)}}async resolveAuthoritativeSymbol(e){if(e===xa)return"GALA";const t=this.cache?.getByTokenId(e);if(null!=t?.symbol&&""!==t.symbol)return t.symbol;let n;this.logger.debug(`Symbol cache miss for ${e}, reading the token class`);try{if(void 0===this.fetchTokenDetails)throw St("GalaChainService not available for token metadata fetch",500);n=(await this.fetchTokenDetails(e)).symbol}catch(t){throw St(`Could not resolve the symbol for ${e} from the token class, and a symbol cannot be derived from the class key: ${ut(t)}`)}if(""===n)throw St(`Token class for ${e} has no symbol`);return this.cache?.setByTokenId(e,{symbol:n}),n}async fetchMarketUsdPrice(e){try{const t=function(e){if(!Rn(e))throw new Error("Invalid token format: token must be a non-empty string");return e.replace(/\|/g,"$")}(e);if(this.logger.debug(`Fetching swap backend price for token: ${t}`),void 0===this.dexBackendHttp)throw St("DEX Backend API client not configured");const n=await this.resolveAuthoritativeSymbol(e),r=await this.dexBackendHttp.request({method:"GET",url:"/market/price",params:{assetIds:t}}),s=null!==r&&"object"==typeof r?r:{},o=Object.keys(s).find(e=>e.toUpperCase()===n.toUpperCase()),i=void 0!==o?s[o]:1===Object.keys(s).length?Object.values(s)[0]:void 0,a=i?.price;if("number"!=typeof a||!Number.isFinite(a))throw new rt(`Invalid price response: no market price for ${t}`,"data","INVALID_RESPONSE");return this.logger.debug(`Swap backend price for ${n}: $${a}`),{symbol:n,price:a}}catch(e){if(e instanceof rt)throw e;throw St(`Failed to fetch DEX spot price: ${ut(e)}`)}}}const La={BATCH_SIZE:20,FLUSH_INTERVAL_MS:3e3,MAX_QUEUE_SIZE:1e3,FLUSH_ON_PAGE_HIDE:!0,FLUSH_ON_PAGE_UNLOAD:!0,DEBUG:!1};class Ua{constructor(e,t={}){this.eventBuffer=[],this.flushTimer=null,this.isShuttingDown=!1,this.totalQueued=0,this.totalFlushed=0,this.totalDropped=0,this.handleVisibilityChange=()=>{"hidden"===document.visibilityState&&this.eventBuffer.length>0&&this.flushWithBeacon()},this.handleBeforeUnload=()=>{this.eventBuffer.length>0&&this.flushWithBeacon()},this.httpClient=e,this.logger=new Vt({debug:t.debug??!1,context:"EventsBatcherService"}),this.config={batchSize:t.batchSize??La.BATCH_SIZE,flushIntervalMs:t.flushIntervalMs??La.FLUSH_INTERVAL_MS,maxQueueSize:t.maxQueueSize??La.MAX_QUEUE_SIZE,flushOnPageHide:t.flushOnPageHide??La.FLUSH_ON_PAGE_HIDE,flushOnPageUnload:t.flushOnPageUnload??La.FLUSH_ON_PAGE_UNLOAD,debug:t.debug??La.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:en(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 Fa=["createdAt","eventType","userAddress"],Pa=["last_hour","today","yesterday","last_7_days","last_30_days","custom"],Ba=["sdk","frontend","backend","mcp"];function Ga(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function $a(e){return"number"==typeof e&&Number.isFinite(e)}function Ka(e){return Ga(e)&&$a(e.id)&&"string"==typeof e.eventType&&Ga(e.payload)&&"string"==typeof e.createdAt&&"string"==typeof e.updatedAt}function Ha(e,t,n){if(!t.some(t=>t===e))throw new rt(`${n} must be one of: ${t.join(", ")}`,n,nt.INVALID_VALUE)}class Wa extends ci{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async getEventStats(){return function(e){if(!(Ga(e)&&$a(e.totalEvents)&&$a(e.todayEvents)&&$a(e.uniqueUsers)&&$a(e.uniqueTokens)&&Ga(e.eventsByType)))throw St("Malformed event statistics response");const t={};for(const[n,r]of Object.entries(e.eventsByType)){if(!$a(r))throw St("Malformed event statistics response");t[n]=r}return{totalEvents:e.totalEvents,todayEvents:e.todayEvents,uniqueUsers:e.uniqueUsers,uniqueTokens:e.uniqueTokens,eventsByType:t}}(await this.http.get(Fe,void 0,this.getDualAuthHeaders()))}async queryEvents(e={}){!function(e){if(void 0!==e.limit&&(!Number.isInteger(e.limit)||e.limit<1||e.limit>100))throw new rt("limit must be an integer from 1 to 100","limit",nt.INVALID_VALUE);if(void 0!==e.page&&(!Number.isInteger(e.page)||e.page<1))throw new rt("page must be a positive integer","page",nt.INVALID_VALUE);void 0!==e.sortBy&&Ha(e.sortBy,Fa,"sortBy"),void 0!==e.sortOrder&&Ha(e.sortOrder,["asc","desc"],"sortOrder"),void 0!==e.timePreset&&Ha(e.timePreset,Pa,"timePreset"),void 0!==e.source&&Ha(e.source,Ba,"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?en(s,"userAddress"):s}const r=n.toString(),s=""===r?Ue:`${Ue}?${r}`;return function(e){if(!Ga(e)||!Array.isArray(e.data)||!Ga(e.pagination))throw St("Malformed events response");const t=e.pagination,n=e.data;if(!($a(t.page)&&$a(t.limit)&&$a(t.total)&&$a(t.totalPages)&&n.every(Ka)))throw St("Malformed events response");return{data:n,pagination:{page:t.page,limit:t.limit,total:t.total,totalPages:t.totalPages}}}(await this.http.get(s,t,this.getDualAuthHeaders()))}}function Va(e){let t;return{requestor:async(n,r)=>{const s="string"==typeof r?.body?JSON.parse(r.body):void 0,{data:o,status:i,headers:a}=await e(n,s);t=o;const c=void 0===o?"":JSON.stringify(o),l="number"==typeof i?i:200;return{ok:l>=200&&l<300,status:l,json:()=>Promise.resolve(o),text:()=>Promise.resolve(c),headers:a??{}}},answer:()=>t}}const ja=new Set(["GATEWAY_READ_REJECTED","GATEWAY_READ_RESPONSE_INVALID"]);class qa extends jn{constructor(e,t=!1){super(e,t)}async fetchGalaBalance(e){return this.fetchTokenBalance(e)}async fetchTokenBalance(t,n=!1){const r=Zt(t.owner,"owner");try{const{requestor:s}=Va(async(e,t)=>({data:await this.http.post(e,t)})),o=new e.GatewayReads({gatewayBaseUrl:"",httpRequestor:s,requestTimeoutMs:1/0}),{collection:i,category:a,type:c,additionalKey:l}=t,d=await o.fetchTokenBalance({owner:r,tokenClassKey:{collection:i,category:a,type:c,additionalKey:l},includeExpiredHolds:n});return void 0===d?null:function(e){if("0"===e.quantity)return null;const{collection:t,category:n}=e.tokenClassKey,r={quantity:e.quantity,collection:t,category:n,tokenId:ra(e.tokenClassKey)};return e.inUseHolds.length>0&&(r.inUseHolds=[...e.inUseHolds],r.inUseQuantity=e.inUseQuantity),e.lockedHolds.length>0&&(r.lockedHolds=[...e.lockedHolds],r.lockedQuantity=e.lockedQuantity),void 0===r.lockedQuantity&&void 0===r.inUseQuantity||(r.availableQuantity=e.availableQuantity),r}(d)}catch(t){if(e.isGalaError(t)&&ja.has(t.code))return null;throw St(`Failed to fetch token balance from GalaChain: ${ut(t)}`,void 0,dt(t)?t:void 0)}}}function za(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Rn(t.amount)&&(void 0!==t.tokenId||Rn(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 Ya(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Rn(t.amount)&&(void 0!==t.tokenId||Rn(t.tokenName))&&(void 0===t.name||"string"==typeof t.name)}function Xa(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every(za)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}function Qa(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every(Ya)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}var Ja,Za;exports.LockErrorType=void 0,(Ja=exports.LockErrorType||(exports.LockErrorType={})).TOKEN_NOT_FOUND="TOKEN_NOT_FOUND",Ja.INVALID_AMOUNT="INVALID_AMOUNT",Ja.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",Ja.SIGNATURE_FAILED="SIGNATURE_FAILED",Ja.NETWORK_ERROR="NETWORK_ERROR",Ja.WALLET_REQUIRED="WALLET_REQUIRED",Ja.VALIDATION_ERROR="VALIDATION_ERROR",Ja.LOCK_NOT_FOUND="LOCK_NOT_FOUND",Ja.LOCK_EXPIRED="LOCK_EXPIRED",Ja.INSUFFICIENT_LOCKED_BALANCE="INSUFFICIENT_LOCKED_BALANCE",Ja.NOT_LOCK_AUTHORITY="NOT_LOCK_AUTHORITY",Ja.LOCK_NAME_MISMATCH="LOCK_NAME_MISMATCH";class ec 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"}(Za||(Za={}));class tc extends Error{constructor(e,t,n){super(e),this.type=t,this.details=n,this.name="TransferError"}}function nc(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 rc(e,t,n,r="[DEBUG] Token resolution (launchpad)"){const s=await t.resolveTokenToVault(e);if(null!==s){const t=ia(s);return n.debug(r,{tokenName:e,vaultAddress:s,tokenInstance:{collection:t.collection,category:t.category,type:t.type,instance:t.instance}}),t}throw new rt(`Token "${e}" is not a launchpad token (no vault address found), and a token class key cannot be derived from a name. Pass an explicit tokenId (collection|category|type|additionalKey) for standard GalaChain tokens.`,"tokenName","TOKEN_CLASS_KEY_NOT_DERIVABLE")}class sc extends jn{constructor(e,t,n,r=!1,s){super(e,r),this.wallet=t,this.tokenResolver=n,this.writer=s,this.nativeSigner=t?new Qi(t.privateKey):void 0}writeIdentity(){return void 0!==this.wallet&&void 0!==this.nativeSigner?{signer:this.nativeSigner,walletAddress:cn(this.wallet.address)}:this.writer}}function oc(e,t){const{collection:n,category:r,type:s,additionalKey:o,instance:i}=e;return{tokenClassKey:{collection:n,category:r,type:s,additionalKey:o},instance:i,quantity:t}}const ic=new Set(["GATEWAY_WRITE_REJECTED","GATEWAY_RESPONSE_INVALID","GATEWAY_HTTP_ERROR"]);function ac(t,{signer:n,walletAddress:r}){const{requestor:s,answer:o}=Va((e,n)=>t.postWithMeta(e,n));return{writes:new e.GatewayWrites({gatewayBaseUrl:"",signer:n,walletAddress:r,httpRequestor:s,requestTimeoutMs:1/0,uniqueKeyPrefix:"galaconnect-operation-"}),answer:o}}async function cc(t,n,r){let s;try{s=await n(t.writes)}catch(n){throw function(t){return e.isGalaError(t)&&ic.has(t.code)}(n)&&r(t.answer(),void 0),n}return r(t.answer(),s)}function lc(e){return void 0===e||""===e?{}:{uniqueKey:e}}const dc=100,uc=100;class hc extends sc{async lockTokens(e){this.validateLockTokensData(e);const t=this.writeIdentity();if(void 0===t)throw new ec("Wallet required for token lock operations",exports.LockErrorType.WALLET_REQUIRED);return $o(async()=>{const n=ac(this.http,t),r=n.writes.walletAddress,s=[],o=[];let i=r;const a=e.tokens.find(e=>void 0!==e.lockAuthority);void 0!==a?.lockAuthority&&(i=cn(a.lockAuthority));const c=e.tokens.find(e=>void 0!==e.expires),l=e.tokens.find(e=>void 0!==e.name);for(const t of e.tokens){const e=await this.resolveTokenEntry(t);o.push(oc(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?cn(t.lockAuthority):i})}return cc(n,t=>t.lockTokens({tokens:o,lockAuthority:i,...void 0!==c?.expires&&{expires:c.expires},...void 0!==l?.name&&{name:l.name},...lc(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 ec("Wallet required for token unlock operations",exports.LockErrorType.WALLET_REQUIRED);return $o(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(oc(e,t.amount)),n.push({tokenClassKey:{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey},quantity:t.amount})}return cc(ac(this.http,t),t=>t.unlockTokens({tokens:r,...void 0!==s?.name&&{name:s.name},...lc(e.uniqueKey)}),(e,t)=>(this.assertLockAnswer(e,"Token unlock failed"),this.extractUnlockResult(e,t,n)))},"Token unlock failed",this.logger,t=>{throw this.handleLockError(t,"Token unlock failed",e)})}assertLockAnswer(e,t){try{mt(e,t)}catch(t){const n=function(e){if(null==e||"object"!=typeof e)return"";const t=e.Message;return"string"==typeof t&&t.trim().length>0?` - ${t}`:""}(e);throw new ec(`${ut(t)}${n}`,exports.LockErrorType.NETWORK_ERROR)}}validateSharedTokenEntry(e,t,n){if(void 0===e.tokenId&&void 0===e.tokenName)throw new ec("Must provide either tokenId or tokenName for token identification",exports.LockErrorType.TOKEN_NOT_FOUND);if(void 0!==e.tokenName)try{Pn(e.tokenName,"tokenName",Jn)}catch{throw new ec("Invalid token name format",exports.LockErrorType.TOKEN_NOT_FOUND,{tokenName:e.tokenName})}try{yo(Eo(e.amount))}catch{throw new ec(vt(t,"a positive number",n).message,exports.LockErrorType.INVALID_AMOUNT,{amount:e.amount})}}validateLockTokensData(e){if(!Xa(e))throw new ec("Invalid lock data: missing required fields",exports.LockErrorType.VALIDATION_ERROR);if(e.tokens.length>dc)throw new ec(`Batch size exceeds maximum limit of ${dc} tokens per lock operation`,exports.LockErrorType.VALIDATION_ERROR);for(const t of e.tokens){if(this.validateSharedTokenEntry(t,"lockAmount","Lock amount"),void 0!==t.lockAuthority&&!un(t.lockAuthority))throw new ec("Invalid lock authority address format",exports.LockErrorType.VALIDATION_ERROR,{lockAuthority:t.lockAuthority});if(void 0!==t.expires)try{_n(t.expires,"expires")}catch{throw new ec(vt("expires","a positive integer (epoch milliseconds)","Expires").message,exports.LockErrorType.VALIDATION_ERROR)}}}validateUnlockTokensData(e){if(!Qa(e))throw new ec("Invalid unlock data: missing required fields",exports.LockErrorType.VALIDATION_ERROR);if(e.tokens.length>uc)throw new ec(`Batch size exceeds maximum limit of ${uc} tokens per unlock operation`,exports.LockErrorType.VALIDATION_ERROR);for(const t of e.tokens)this.validateSharedTokenEntry(t,"unlockAmount","Unlock amount")}transactionIdOf(e,t){const n=Array.isArray(e.Data)?e.Data[0]:void 0;return t?.transactionId??n?.transactionId??n?.txnId??n?.TxnId??n?.id??void 0}extractLockResult(e,t,n){const r=this.transactionIdOf(e,t),s=t?.blockNumber;return{...void 0!==r&&{transactionId:r},...void 0!==s&&{blockNumber:s},locked:n}}extractUnlockResult(e,t,n){const r=this.transactionIdOf(e,t),s=t?.blockNumber;return{...void 0!==r&&{transactionId:r},...void 0!==s&&{blockNumber:s},unlocked:n}}handleLockError(t,n,r){if(t instanceof ec)return t;if(e.isGalaError(t)&&"pre_send"===t.phase)return new ec(`${n}: ${t.message}`,"SIGNING_FAILED"===(s=t.code)?exports.LockErrorType.SIGNATURE_FAILED:"INVALID_TOKEN_REFERENCE"===s?exports.LockErrorType.TOKEN_NOT_FOUND:"INVALID_QUANTITY"===s?exports.LockErrorType.INVALID_AMOUNT:exports.LockErrorType.VALIDATION_ERROR,nc(r));var s;let o=n,i=exports.LockErrorType.NETWORK_ERROR;if(pt(t)){const e=t.response?.data;if("object"==typeof e&&null!==e){const t=e.Message;"string"==typeof t&&t.length>0&&(o=`${n}: ${t}`);const r="string"==typeof t?t.toLowerCase():"";r.includes("insufficient")||r.includes("balance")?i=exports.LockErrorType.INSUFFICIENT_BALANCE:r.includes("lock")&&r.includes("not found")?i=exports.LockErrorType.LOCK_NOT_FOUND:r.includes("not found")||r.includes("token")?i=exports.LockErrorType.TOKEN_NOT_FOUND:r.includes("authority")?i=exports.LockErrorType.NOT_LOCK_AUTHORITY:r.includes("expired")&&(i=exports.LockErrorType.LOCK_EXPIRED)}}else dt(t)&&(o=`${n}: ${ut(t)}`);return new ec(o,i,nc(r))}async resolveTokenInstance(e){return $o(async()=>rc(e,this.tokenResolver,this.logger),`Failed to resolve token '${e}'`,this.logger,t=>{if(t instanceof tc)throw new ec(ut(t),exports.LockErrorType.TOKEN_NOT_FOUND);throw new ec(`Failed to resolve token '${e}': ${ut(t)}`,exports.LockErrorType.TOKEN_NOT_FOUND,{tokenName:e})})}async resolveTokenEntry(e){if(void 0!==e.tokenId){const t=sa(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 ec("Must provide either tokenId or tokenName for token identification",exports.LockErrorType.TOKEN_NOT_FOUND)}}const gc=new Set(["GATEWAY_READ_REJECTED","GATEWAY_READ_RESPONSE_INVALID","TOKEN_CLASS_NOT_FOUND"]);function pc(e){const t=e?.Data;return Array.isArray(t)?t:void 0}class mc extends jn{constructor(e,t=!1,n){super(e,t),this.publicAxios=n}async fetchTokenClassFromChain(e){try{const t="string"==typeof e?sa(e):e,{collection:n,category:r,type:s,additionalKey:o}=t,i={collection:n,category:r,type:s,additionalKey:o},a="Failed to fetch token class from GalaChain";return await this.readPublic(e=>e.fetchTokenClass(i),e=>{if(mt(e,a),void 0===pc(e)?.[0])throw St(`Token not found on GalaChain: ${ra(i)}`,404)},()=>St(`Token not found on GalaChain: ${ra(i)}`,404))}catch(e){return this.handleTokenServiceError(e,"Token not found on GalaChain","Failed to fetch token class from GalaChain")}}async fetchTokenClassesWithSupply(e){try{if(null==e||0===e.length)throw Tt("tokenClasses","Token classes array");return await this.readPublic(t=>t.fetchTokenClassesWithSupply(e),e=>{if(mt(e,"Failed to fetch token classes with supply from GalaChain"),0===(pc(e)?.length??0))throw St("No token supply data found for requested token classes",404)},void 0)}catch(e){return this.handleTokenServiceError(e,"Token supply data not found on GalaChain","Failed to fetch token classes with supply from GalaChain")}}async readPublic(t,n,r){if(!this.publicAxios)throw Tt("publicAxios","Public Axios instance");const s=this.publicAxios,{requestor:o,answer:i}=Va(async(e,t)=>{const n=await s.post(e,t);return{data:n.data,status:n.status}});try{return await t(new e.GatewayReads({gatewayBaseUrl:"",httpRequestor:o,requestTimeoutMs:1/0}))}catch(t){if(e.isGalaError(t)&&gc.has(t.code)&&(n(i()),"TOKEN_CLASS_NOT_FOUND"===t.code&&void 0!==r))throw r();throw t}}handleTokenServiceError(e,t,n){if(e instanceof rt)throw e;if(pt(e)&&404===e.response?.status)throw St(t,404,dt(e)?e:void 0);if(dt(e)&&"Error"===e.name&&ut(e).includes("status indicates failure"))throw St(ut(e),400,dt(e)?e:void 0);const r=ut(e);if(r.includes("Token not found")){if(e instanceof Error)throw e;throw new Error(r)}throw St(`${n}: ${r}`,void 0,dt(e)?e:void 0)}}function fc(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Rn(t.amount)&&(void 0!==t.tokenId||Rn(t.tokenName))}function Ec(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)}var Ac;exports.BurnErrorType=void 0,(Ac=exports.BurnErrorType||(exports.BurnErrorType={})).TOKEN_NOT_FOUND="TOKEN_NOT_FOUND",Ac.INVALID_AMOUNT="INVALID_AMOUNT",Ac.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",Ac.SIGNATURE_FAILED="SIGNATURE_FAILED",Ac.NETWORK_ERROR="NETWORK_ERROR",Ac.WALLET_REQUIRED="WALLET_REQUIRED",Ac.VALIDATION_ERROR="VALIDATION_ERROR";class Tc extends Error{constructor(e,t,n){super(e),this.type=t,this.details=n,this.name="BurnError"}}const vc={validateAmount(e){const t=Eo(e);try{bo(t,"amount")}catch(t){throw new tc(t.message,Za.INVALID_AMOUNT,{amount:e})}},validateUniqueKey(e){if(!xn(e)&&Rn(e)){if(e.length>lr.MAX_LENGTH)throw new rt(`Unique key too long. Maximum length: ${lr.MAX_LENGTH}`);if(!lr.PATTERN.test(e))throw new tc('Invalid unique key format. Must start with "galaswap-operation-" or "galaconnect-operation-"',Za.INVALID_AMOUNT,{uniqueKey:e})}}},Sc="gala-transfer-successful",yc="token-transfer-successful",bc="token-locked-successfully",Nc="token-unlocked-successfully",kc="transfer-successful-no-id",wc=50;class _c extends sc{async transferGala(e){this.validateTransferGalaData(e);const t=this.writeIdentity();if(void 0===t)throw new tc("Wallet required for GALA transfer operations",Za.WALLET_REQUIRED);try{const n=cn(e.recipientAddress),r=ac(this.http,t);return await cc(r,t=>t.transferGala({to:n,quantity:e.amount,...lc(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 tc("Wallet required for token transfer operations",Za.WALLET_REQUIRED);try{const n=cn(e.to),r=await this.tokenInstanceOf(e.tokenId,e.tokenName,()=>new tc("Must provide either tokenId or tokenName for token identification",Za.TOKEN_NOT_FOUND)),s=ac(this.http,t);return await cc(s,t=>t.transferToken({to:n,...oc(r,e.amount),...lc(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 tc)throw t;throw new tc(`Failed to resolve token class key for '${e}': ${ut(t)}`,Za.TOKEN_NOT_FOUND,{tokenName:e})}}async burnTokens(e){this.validateBurnTokensData(e);const t=this.writeIdentity();if(void 0===t)throw new Tc("Wallet required for token burn operations",exports.BurnErrorType.WALLET_REQUIRED);try{const n=[];for(const t of e.tokens){const e=await this.tokenInstanceOf(t.tokenId,t.tokenName,()=>new Tc("Must provide either tokenId or tokenName for token identification",exports.BurnErrorType.TOKEN_NOT_FOUND));n.push(oc(e,t.amount))}const r=ac(this.http,t);return await cc(r,t=>t.burnTokens({tokens:n,...lc(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 Rn(t.recipientAddress)&&Rn(t.amount)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)}(e))throw new rt("Invalid GALA transfer data: missing required fields");if(!un(e.recipientAddress))throw new tc("Invalid recipient address format",Za.INVALID_RECIPIENT,{recipientAddress:e.recipientAddress});vc.validateAmount(e.amount),vc.validateUniqueKey(e.uniqueKey)}validateTransferTokenData(e){if(!function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Rn(t.to)&&Rn(t.amount)&&(void 0!==t.tokenId||Rn(t.tokenName))&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)}(e))throw new rt("Invalid token transfer data: missing required fields");if(!un(e.to))throw new tc("Invalid recipient address format",Za.INVALID_RECIPIENT,{recipientAddress:e.to});if(!(null!==e.tokenId&&void 0!==e.tokenId||null!==e.tokenName&&void 0!==e.tokenName))throw new tc("Must provide either tokenId or tokenName for token identification",Za.TOKEN_NOT_FOUND);if(null!==e.tokenName&&void 0!==e.tokenName)try{Pn(e.tokenName,"tokenName",Jn)}catch{throw new tc("Invalid token name format",Za.TOKEN_NOT_FOUND,{tokenName:e.tokenName})}vc.validateAmount(e.amount),vc.validateUniqueKey(e.uniqueKey)}validateBurnTokensData(e){if(!Ec(e))throw new Tc("Invalid burn data: missing required fields",exports.BurnErrorType.VALIDATION_ERROR);if(e.tokens.length>wc)throw new Tc(`Batch size exceeds maximum limit of ${wc} tokens per burn operation`,exports.BurnErrorType.VALIDATION_ERROR);for(const t of e.tokens){if(!(null!==t.tokenId&&void 0!==t.tokenId||null!==t.tokenName&&void 0!==t.tokenName))throw new Tc("Must provide either tokenId or tokenName for token identification",exports.BurnErrorType.TOKEN_NOT_FOUND);const e=Eo(t.amount);try{yo(e)}catch{throw new Tc("Burn amount must be a positive number",exports.BurnErrorType.INVALID_AMOUNT,{amount:t.amount})}}}async tokenInstanceOf(e,t,n){if(null!=e){const t=sa(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 rc(e,this.tokenResolver,this.logger,`[DEBUG] Token resolution for '${e}' (launchpad):`)}catch(t){if(t instanceof tc)throw t;throw new tc(`Failed to resolve token '${e}': ${ut(t)}`,Za.TOKEN_NOT_FOUND,{tokenName:e})}}extractTransferResult(e,t,n){if(null==e)throw new tc("No response from GalaChain transfer service",Za.NETWORK_ERROR);const r=t?.blockNumber,s="object"==typeof e&&"Status"in e;s&&mt(e,"Extract transaction ID");const o=s&&"Data"in e,i=t?.transactionId;if(void 0!==i)return{transactionId:i,...void 0!==r?{blockNumber:r}:{}};if(o){const t=e;if(Array.isArray(t.Data)){for(const e of t.Data)if(null!=e&&"object"==typeof e){const t=e;for(const e of["transactionId","txnId","TxnId","id","txId"]){const n=t[e];if("string"==typeof n&&n.length>0)return{transactionId:n,...void 0!==r?{blockNumber:r}:{}}}}let e=kc;if(t.Data.length>0)switch(n){case"gala":e=Sc;break;case"token":e=yc;break;case"lock":e=bc;break;case"unlock":e=Nc}return{transactionId:e,...void 0!==r?{blockNumber:r}:{}}}}throw new tc("Operation succeeded but transaction ID could not be extracted (missing x-transaction-id header and body fields)",Za.NETWORK_ERROR)}burnResultOf(e,t){if(null==e)throw new Tc("No response from GalaChain burn service",exports.BurnErrorType.NETWORK_ERROR);try{mt(e,"Token burn operation")}catch(e){throw new at(ut(e),500)}return this.extractBurnResult(e,t)}extractBurnResult(e,t){const n=[];if(null!==e.Data&&void 0!==e.Data&&Array.isArray(e.Data))for(const t of e.Data)n.push({collection:t.collection??"",category:t.category??"",type:t.type??"",additionalKey:t.additionalKey??"",instance:t.instance??"0",quantity:t.quantity??"0",burnedBy:t.burnedBy??""});const r=Array.isArray(e.Data)?e.Data[0]:void 0,s=t?.transactionId??r?.transactionId??r?.txnId??r?.TxnId??r?.id??void 0,o=t?.blockNumber;return{...void 0!==s&&{transactionId:s},...void 0!==o&&{blockNumber:o},burned:n}}handleTransferError(t,n,r){if(t instanceof tc)return t;if(t instanceof rt)return new tc(ut(t),Za.INVALID_AMOUNT);if(e.isGalaError(t)&&"pre_send"===t.phase)return new tc(t.message,"SIGNING_FAILED"===(s=t.code)?Za.SIGNATURE_FAILED:"INVALID_WALLET_ADDRESS"===s?Za.INVALID_RECIPIENT:"INVALID_TOKEN_REFERENCE"===s?Za.TOKEN_NOT_FOUND:Za.INVALID_AMOUNT);var s;if(pt(t)&&t.response){const e=t.response.status,n=t.response.data;if(400===e){const e=n?.message;return new tc(("string"==typeof e?e:void 0)??"Invalid transfer request",Za.INVALID_AMOUNT)}if(403===e)return new tc("Insufficient balance for transfer",Za.INSUFFICIENT_BALANCE);if(404===e){const e={};return"tokenName"in r&&(e.tokenName=r.tokenName),new tc("Token not found",Za.TOKEN_NOT_FOUND,e)}}if("object"==typeof t&&null!==t&&"code"in t&&("ECONNABORTED"===gt(t)||"ETIMEDOUT"===gt(t)))return new tc("Transfer request timed out",Za.NETWORK_ERROR);const o=""!==ut(t)?ut(t):n;return new tc(o,Za.NETWORK_ERROR)}handleBurnError(t,n,r){if(t instanceof Tc)return t;if(e.isGalaError(t)&&"pre_send"===t.phase)return new Tc(`${n}: ${t.message}`,"SIGNING_FAILED"===(s=t.code)?exports.BurnErrorType.SIGNATURE_FAILED:"INVALID_TOKEN_REFERENCE"===s?exports.BurnErrorType.TOKEN_NOT_FOUND:"INVALID_QUANTITY"===s?exports.BurnErrorType.INVALID_AMOUNT:exports.BurnErrorType.VALIDATION_ERROR,nc(r));var s;let o=n,i=exports.BurnErrorType.NETWORK_ERROR;if(pt(t)){const e=t.response?.data;if("object"==typeof e){const t=e.Message;if("string"==typeof t&&t.length>0){o=`${n}: ${t}`;const e=t.toLowerCase();e.includes("insufficient")||e.includes("balance")?i=exports.BurnErrorType.INSUFFICIENT_BALANCE:(e.includes("not found")||e.includes("token"))&&(i=exports.BurnErrorType.TOKEN_NOT_FOUND)}}}else dt(t)&&(o=`${n}: ${ut(t)}`);return new Tc(o,i,nc(r))}}class Ic extends jn{constructor(e,t,n,r=!1,s,o){super(e,r),this.balanceService=new qa(e,r),this.tokenService=new mc(e,r,s),this.lockService=new hc(e,t,n,r,o),this.transferService=new _c(e,t,n,r,o)}async fetchGalaBalance(e){return this.balanceService.fetchGalaBalance(e)}async fetchTokenBalance(e,t=!1){return this.balanceService.fetchTokenBalance(e,t)}async fetchTokenClassFromChain(e){return this.tokenService.fetchTokenClassFromChain(e)}async fetchTokenDetails(t){try{return e.tokenDetailsOf(await this.fetchTokenClassFromChain(t))}catch(e){if(dt(e)&&("NetworkError"===e.name||ut(e).includes("Token not found")))throw e;throw St(`Failed to fetch token details from GalaChain for ${"string"==typeof t?t:ra(t)}: ${ut(e)}`,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 Cc extends jn{async getHealth(){const e=(await this.http.get(Pe)).data;if(null==e)throw St("Health check answered no data");return e}}class Dc extends Error{constructor(e,t,n){super(e),this.filename=t,this.mimeType=n,this.name="FileValidationError"}}function Rc(e,t,n){if(null==e)throw new Dc("File is required",t,n);if("undefined"!=typeof File&&e instanceof File){const t=Vr.safeParse(e);if(!t.success){const n=t.error.issues.map(e=>e.message).join("; ");throw new Dc(n,e.name,e.type)}return}if(Buffer.isBuffer(e)){if(void 0===t||""===t)throw new Dc("Filename is required when uploading Buffer objects",t,n);const r=jr.safeParse(e);if(!r.success){const e=r.error.issues.map(e=>e.message).join("; ");throw new Dc(e,t,n)}try{wn(t,255,"filename")}catch(e){throw new Dc(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 Dc(`Invalid file type "${n}" is not allowed. Allowed types: ${s.join(", ")}`,t,n);const o=function(e){if(null==e||""===e)return"";const t=e.lastIndexOf(".");if(-1===t)return"";return e.substring(t).toLowerCase()}(t),i=[".png",".jpg",".jpeg",".gif",".webp",".svg"];if(!i.includes(o))throw new Dc(`File extension "${o}" is not allowed. Allowed extensions: ${i.join(", ")}`,t,n);const a=function(e){switch(e.toLowerCase()){case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";case".gif":return"image/gif";case".webp":return"image/webp";case".svg":return"image/svg+xml";default:return"application/octet-stream"}}(o);if(a!==n&&"application/octet-stream"!==a)throw new Dc(`File extension "${o}" does not match MIME type "${n}"`,t,n);return}throw new Dc("File must be a File object (browser) or Buffer (Node.js)",t,n)}function Oc(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 xc extends jn{constructor(e,t,n=!1){super(e,n,t)}async uploadImageByTokenName(e){const{tokenName:t,options:n}=e;Fn(t,"tokenName",Jn);const r=`${t}.png`;Rc(n.file,r,"image/png");try{const e=Oc(n.file,"image",r),s=await Ft(()=>this.http.request({method:"POST",url:oi(l.UPLOAD_IMAGE,{tokenName:t}),data:e,headers:this.getJwtHeaders()}),{errorContext:"Image upload failed"});return"string"==typeof s?s:""}catch(e){if(e instanceof ct)throw e;if(dt(e)&&ut(e).includes("FormData"))throw yt("File upload failed: FormData not supported in this environment. Ensure you have proper polyfills for Node.js environments.","FormData");throw e}}}function Mc(e){if(!!(void 0===e.chatEnabled&&void 0===e.commentsEnabled&&void 0===e.streamingEnabled&&void 0===e.nextLiveStreamAt&&void 0===e.streamLanguage&&void 0===e.websiteUrl&&void 0===e.telegramUrl&&void 0===e.twitterUrl&&void 0===e.instagramUrl&&void 0===e.facebookUrl&&void 0===e.redditUrl&&void 0===e.tiktokUrl))throw new rt("At least one config option must be provided (chatEnabled, commentsEnabled, streamingEnabled, nextLiveStreamAt, streamLanguage, or social URLs)","options",nt.REQUIRED);if(void 0!==e.chatEnabled&&"boolean"!=typeof e.chatEnabled)throw _t("chatEnabled","boolean");if(void 0!==e.commentsEnabled&&"boolean"!=typeof e.commentsEnabled)throw _t("commentsEnabled","boolean");if(void 0!==e.streamingEnabled&&"boolean"!=typeof e.streamingEnabled)throw _t("streamingEnabled","boolean");if(void 0!==e.streamLanguage&&"string"!=typeof e.streamLanguage)throw _t("streamLanguage","string");const t=["websiteUrl","telegramUrl","twitterUrl","instagramUrl","facebookUrl","redditUrl","tiktokUrl"];for(const n of t){const t=e[n];if(null!=t&&"string"!=typeof t)throw _t(n,"string or null")}if(void 0!==e.nextLiveStreamAt&&null!==e.nextLiveStreamAt){if("string"!=typeof e.nextLiveStreamAt)throw _t("nextLiveStreamAt","string or null");const t=new Date(e.nextLiveStreamAt);if(isNaN(t.getTime()))throw new rt("nextLiveStreamAt must be a valid ISO date string","nextLiveStreamAt",nt.INVALID_FORMAT)}}function Lc(e){if(xn(e)||"object"!=typeof e)return{};const t={};for(const[n,r]of Object.entries(e))xn(r)||(Rn(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 Uc=Object.freeze({__proto__:null,adaptQueryParams:Lc});function Fc(e,t){if(null==e)return[];if(Array.isArray(e))return e;const n=e[t];return Array.isArray(n)?n:[]}function Pc(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.owner&&""!==t.owner}function Bc(e){return"string"==typeof e.quantity&&""!==e.quantity}class Gc extends jn{constructor(e,t,n=!1){super(e,n,t)}async fetchPools(e={}){const t=function(e){const t=e.pageSize??Qo.DEFAULT_LIMIT;if(!Number.isInteger(t)||t<1||t>et)throw Nt("pageSize",1,et,t);const n={pageSize:String(t)};Rn(e.cursor)&&(n.cursor=e.cursor);void 0!==e.type&&(n.type=Wc("type",e.type,Je));Rn(e.tokenName)&&(Fn(e.tokenName,"tokenName",Xn),n.tokenName=e.tokenName);if(Rn(e.search)){if(e.search.length>$c)throw Rt("search",$c,e.search.length);n.search=e.search}!0===e.hasUpcomingShows&&(n.hasUpcomingShows="true");if(Rn(e.language)){if(!Hc.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>Kc)throw Nt("recentlyStreamed",1,Kc,t);n.recentlyStreamed=String(t)}!0===e.hasRecordings&&(n.hasRecordings="true");void 0!==e.streamStatus&&(n.streamStatus=Wc("streamStatus",e.streamStatus,Ze));if(void 0!==e.isGraduated){if("boolean"!=typeof e.isGraduated)throw _t("isGraduated","boolean",e.isGraduated);n.isGraduated=e.isGraduated?"true":"false"}void 0!==e.creatorAddress&&(n.creatorAddress=function(e){if("string"!=typeof e)throw _t("creatorAddress","string",e);return mn(e,"creatorAddress"),pn(e)??e}(e.creatorAddress));return n}(e),n=Lt(await Bt(()=>this.http.get(l.FETCH_POOLS,t),{errorContext:"Failed to fetch pools"}));return{items:function(e){if(!e)return[];let t=[];if(e.tokens)if(Array.isArray(e.tokens))t=e.tokens.map(e=>({...e,createdAt:e.created_at??e.createdAt??""}));else{const n=e.tokens;t=[{...n,createdAt:n.created_at??n.createdAt??""}]}else null!==e.pools&&void 0!==e.pools&&Array.isArray(e.pools)&&(t=e.pools.map(e=>({...e,createdAt:e.created_at??e.createdAt??""})));return t}(n),pageInfo:ei(n?.pageInfo)}}async fetchAllPools(e){const t=[];let n;for(;;){const r={...e,pageSize:100,...void 0!==n&&{cursor:n}},s=await this.fetchPools(r);if(t.push(...s.items),0===s.items.length)break;const o=ti(s.pageInfo,n);if(void 0===o)break;n=o}return{items:t,pageInfo:{hasNextPage:!1,totalCount:t.length}}}async checkPool(e){!function(e){const t=zs(e);!t.success&&t.errors&&Co(t.errors,"options")}(e),Rn(e.tokenName)&&Fn(e.tokenName,"tokenName",Zn);try{const t=await this.http.post(l.VALIDATE_TOKEN,{tokenName:e.tokenName,symbol:e.symbol});if(null==t)throw new Error("Invalid response from check pool endpoint");const n=t.data??t;if(null==n)throw new Error("Invalid response from check pool endpoint");if(!0===Rn(e.symbol)){return!n.symbolAvailable}if(!0===Rn(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 uo(t,"tokenName")&&go(t,"from")&&go(t,"to")&&go(t,"resolution")}(e))throw new rt("Invalid options provided. Expected { tokenName: string, from?: number, to?: number, resolution?: number }","options","INVALID_OPTIONS");const{tokenName:t,from:n,to:r,resolution:s}=e;if(Fn(t,"tokenName",Xn),null==n||null==r||null==s)throw new rt("Graph options (from, to, resolution) are required","options","MISSING_GRAPH_OPTIONS");const o={tokenName:t,from:n,to:r,resolution:s};Ro(o);const i=Lc(o),a=await Ft(()=>this.http.get(l.CHART,i),{errorContext:"Failed to fetch graph data"});if(!Array.isArray(a.data)||"boolean"!=typeof a.isPreviousData)throw new at("Invalid chart response: expected { data: candles, isPreviousData }");return{dataPoints:a.data,isPreviousData:a.isPreviousData,..."number"==typeof a.nextTime&&{nextTime:a.nextTime}}}async fetchTokenDistribution(e){if(""===e||null==e)throw Tt("tokenName","Token name");let t;Fn(e,"tokenName",Xn);try{t=await Bt(()=>this.http.get(`${l.GET_TOKEN_DISTRIBUTION}?tokenName=${e}`),{errorContext:"Failed to fetch token distribution"})}catch(t){if(pt(t)&&500===t.response?.status)throw St(`Token distribution data temporarily unavailable for ${e}. This is a backend issue - please try again later.`,500,dt(t)?t:void 0);throw t}return function(e,t,n=Ao){if(!Array.isArray(e))throw St("Invalid API response: expected array of holders",t);for(const n of e){if(!Pc(n))throw St("Invalid holder data: missing or invalid owner field",t);if(!Bc(n))throw St("Invalid holder data: missing or invalid quantity field",t);const e=Tn(n.quantity,NaN);if(isNaN(e)||!isFinite(e))throw St(`Invalid holder quantity: "${n.quantity}"`,t)}const r=e,s=r.reduce((e,t)=>e.plus(t.quantity),Eo(0));return{holders:r.map(e=>({address:e.owner,balance:e.quantity,percentage:No(Eo(e.quantity),s,Eo(0)).multipliedBy(100).toNumber()})),totalSupply:n(s),totalHolders:r.length,lastUpdated:new Date}}(Lt(t),t.status,e=>e.toFixed())}async fetchUserHolderContext(e,t){if(""===e||null==e)throw Tt("tokenName","Token name");if(""===t||null==t)throw Tt("userAddress","User address");return Fn(e,"tokenName",Xn),Ft(()=>this.http.get(`${l.GET_TOKEN_DISTRIBUTION}?tokenName=${e}`,{userAddress:en(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");Fn(e,"tokenName",Jn);try{const t=l.GET_TOKEN.replace(":tokenName",e.toLowerCase().trim()),n=Lt(await this.http.get(t));if(null!=n?.tokens){const t=Array.isArray(n.tokens)?n.tokens[0]:n.tokens;if(null==t)throw new Error(`Token not found: ${e}`);return t}throw new Error(`Invalid response format when fetching token: ${e}`)}catch(t){const n=String(t);if(n.includes("404")||n.includes("not found"))throw t instanceof at?new at(`Token not found: ${e}`,t.statusCode,t):new Error(`Token not found: ${e}`);throw t}}async validateToken(e){if(!(null!==e.tokenName&&void 0!==e.tokenName||null!==e.symbol&&void 0!==e.symbol))throw new Error("At least one of tokenName or symbol is required");if(null!==e.tokenName&&void 0!==e.tokenName&&("string"!=typeof e.tokenName||""===e.tokenName.trim()))throw new Error("tokenName must be a non-empty string");if(null!==e.symbol&&void 0!==e.symbol&&("string"!=typeof e.symbol||""===e.symbol.trim()))throw new Error("symbol must be a non-empty string");null!==e.tokenName&&void 0!==e.tokenName&&Fn(e.tokenName,"tokenName",Zn);try{const t=await this.http.post(l.VALIDATE_TOKEN,{tokenName:e.tokenName?.toLowerCase().trim(),symbol:e.symbol?.toUpperCase().trim()});if(null==t)throw new Error("Invalid response from validation endpoint");const n=t.data??t;if(null==n)throw new Error("Invalid response from validation endpoint");return n}catch(e){throw this.logger.warn(`Token validation failed: ${String(e)}`),e}}async fetchTokenStats(e){if(!Rn(e))throw Tt("tokenName","Token name");Fn(e,"tokenName",Jn);const t=l.TOKEN_STATS.replace(":tokenName",e.toLowerCase().trim());try{const e=Lt(await this.http.get(t));if(!function(e){if("object"!=typeof e||null===e)return!1;const t=new Map(Object.entries(e));return["holdersCount","chatMessageCount","commentCount","roomCount"].every(e=>{const n=t.get(e);return"number"==typeof n&&Number.isFinite(n)})}(e))throw new Error("Invalid response: missing stats data");return{success:!0,data:{holdersCount:e.holdersCount,chatMessageCount:e.chatMessageCount,commentCount:e.commentCount,roomCount:e.roomCount}}}catch(t){throw this.logger.warn(`Failed to fetch token stats for ${e}: ${String(t)}`),t}}async updateTokenConfig(e,t){if(""===e||null==e)throw Tt("tokenName","Token name");Fn(e,"tokenName",Jn),Mc(t);const n=l.UPDATE_TOKEN_CONFIG.replace(":tokenName",e.toLowerCase().trim()),r={};void 0!==t.chatEnabled&&(r.chatEnabled=t.chatEnabled),void 0!==t.commentsEnabled&&(r.commentsEnabled=t.commentsEnabled),void 0!==t.streamingEnabled&&(r.streamingEnabled=t.streamingEnabled),void 0!==t.nextLiveStreamAt&&(r.nextLiveStreamAt=t.nextLiveStreamAt),void 0!==t.streamLanguage&&(r.streamLanguage=t.streamLanguage),void 0!==t.websiteUrl&&(r.websiteUrl=t.websiteUrl),void 0!==t.telegramUrl&&(r.telegramUrl=t.telegramUrl),void 0!==t.twitterUrl&&(r.twitterUrl=t.twitterUrl),void 0!==t.instagramUrl&&(r.instagramUrl=t.instagramUrl),void 0!==t.facebookUrl&&(r.facebookUrl=t.facebookUrl),void 0!==t.redditUrl&&(r.redditUrl=t.redditUrl),void 0!==t.tiktokUrl&&(r.tiktokUrl=t.tiktokUrl),await this.http.patch(n,r,this.getJwtHeaders())}async getTokenConfig(e){if(!Rn(e))throw Tt("tokenName","Token name");Fn(e,"tokenName",Jn);const t=l.UPDATE_TOKEN_CONFIG.replace(":tokenName",e.toLowerCase().trim()),n=Lt(await this.http.get(t));if(void 0===n)throw new Error(`Invalid response: missing token config data for "${e}"`);return n}}const $c=255,Kc=720,Hc=/^[a-z]{2}(-[A-Z]{2})?$/u;function Wc(e,t,n){const r="string"==typeof t?t.toUpperCase():void 0,s=n.find(e=>e===r);if(void 0===s)throw Ct(e,t,n);return s}function Vc(e){if(void 0!==e.tokenName){if(!Rn(e.tokenName))throw _t("tokenName","a non-empty string",typeof e.tokenName);Pn(e.tokenName,"tokenName",Xn)}if(void 0!==e.userAddress){if(!Rn(e.userAddress))throw _t("userAddress","a non-empty string",typeof e.userAddress);if(e.userAddress.length>sr)throw wt("userAddress",sr,e.userAddress.length)}if(void 0!==e.search){if("string"!=typeof e.search)throw _t("search","a string",typeof e.search);if(e.search.length>256)throw wt("search",256,e.search.length)}if(Mn(0,void 0,rr,e.pageSize),void 0!==e.txnType&&"BUY"!==e.txnType&&"SELL"!==e.txnType)throw vt("txnType",'"BUY" or "SELL"');if(void 0!==e.startDate){if(!Rn(e.startDate))throw _t("startDate","a non-empty string",typeof e.startDate);if(isNaN(Date.parse(e.startDate)))throw vt("startDate","a valid ISO 8601 date")}if(void 0!==e.endDate){if(!Rn(e.endDate))throw _t("endDate","a non-empty string",typeof e.endDate);if(isNaN(Date.parse(e.endDate)))throw vt("endDate","a valid ISO 8601 date")}if(void 0!==e.minAmount)try{kn(e.minAmount,0,Number.MAX_SAFE_INTEGER,"minAmount")}catch{throw vt("minAmount","a non-negative number")}if(void 0!==e.maxAmount)try{kn(e.maxAmount,0,Number.MAX_SAFE_INTEGER,"maxAmount")}catch{throw vt("maxAmount","a non-negative number")}void 0!==e.minAmount&&void 0!==e.maxAmount&&function(e,t,n="range"){const r="number"==typeof e?e:Number(e),s="number"==typeof t?t:Number(t);if(isNaN(r)||isNaN(s))throw _t(n,"numeric values",void 0,n);if(r>s)throw new rt(`Minimum value (${r}) must be less than or equal to maximum value (${s}) for ${n}`,n,nt.INVALID_RANGE)}(e.minAmount,e.maxAmount,"amountRange")}class jc extends jn{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 uo(t,"tokenName")&&(void 0===t.tradeType||"buy"===t.tradeType||"sell"===t.tradeType)&&ho(t,"userAddress")&&go(t,"offset")&&go(t,"pageSize")&&go(t,"page")&&go(t,"limit")}(e))throw new rt("Invalid options provided. Expected { tokenName: string, tradeType?: string, userAddress?: string, cursor?: string, pageSize?: number, startDate?: Date, endDate?: Date, sortOrder?: string }","options","INVALID_OPTIONS");const{tokenName:t,cursor:n,pageSize:r=Qo.DEFAULT_LIMIT}=e;if(!Rn(t))throw Tt("tokenName","Token name");const s={pageSize:String(Math.min(r,nr))};void 0!==n&&(s.cursor=n);const o=await this.http.get(oi(l.GET_TRADES,{tokenName:t}),s);if(null==o)throw new rt("No response from trade service","response","NO_RESPONSE");const i=Lt(o),a=Fc(i,"trades"),c=i?.pageInfo;return{items:a,pageInfo:c??{hasNextPage:!1}}}buildTradesQueryParams(e){const t={};null!==e.tokenName&&void 0!==e.tokenName&&e.tokenName.length>0&&(t.tokenName=Kt(e.tokenName)),null!==e.userAddress&&void 0!==e.userAddress&&e.userAddress.length>0&&(t.userAddress=en(e.userAddress,"userAddress")),null!==e.search&&void 0!==e.search&&e.search.length>0&&(t.search=e.search);const n=void 0!==e.pageSize?Jo(e.pageSize,1,rr):rr;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){Vc(e);const t=this.buildTradesQueryParams(e);return Ft(()=>this.http.get(Ie,t),{errorContext:"Failed to fetch trades"})}}Jn.MIN_LENGTH,Jn.MAX_LENGTH;function qc(e){return Rn(e)&&sn(e)}function zc(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 Yc(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 Xc(e){return e.startsWith("0x")?e.slice(2):e}Ln({BOTH:"both",HELD:"held",CREATED:"created"});function Qc(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Jc(e){return"number"==typeof e&&Number.isFinite(e)}function Zc(e){return null===e||"string"==typeof e}function el(e){return Array.isArray(e)&&e.every(e=>Qc(e)&&"string"==typeof e.badgeName&&"boolean"==typeof e.isActive)}function tl(e){return Qc(e)&&"string"==typeof e.address&&Zc(e.fullName)&&Zc(e.profileImage)&&Zc(e.bio)&&function(e){return Qc(e)&&Jc(e.tokensCreated)&&Jc(e.tokensGraduated)&&Jc(e.graduationRate)&&Jc(e.totalTrades)&&"string"==typeof e.totalVolumeGala&&Zc(e.totalVolumeUsd)&&(null===e.holdingsCount||Jc(e.holdingsCount))&&Zc(e.accountCreatedAt)&&Jc(e.accountAgeDays)}(e.stats)&&el(e.launchBadge)&&el(e.successBadge)&&el(e.volumeBadge)&&el(e.engagementBadge)&&"boolean"==typeof e.isLiveStreaming&&Zc(e.liveStreamToken)}class nl extends jn{constructor(e,t,n=!1){super(e,n,t)}async fetchProfile(e){const t=e??this.http.getAddress();if(""===t||null==t||!qc(t))throw vt("address","eth|[40-hex-chars] or client|[identifier]","Address");if(void 0===e){const e=await Ft(()=>this.http.get(l.GET_CURRENT_USER,void 0,this.getJwtHeaders()),{errorContext:"Failed to fetch profile"});if(!(Qc(n=e)&&"string"==typeof n.address&&Zc(n.fullName)&&Zc(n.profileImage)&&"string"==typeof n.bio&&el(n.launchBadge)&&el(n.successBadge)))throw St("Malformed profile response");return e}var n;const r=await Ft(()=>this.http.get(l.GET_PROFILE.replace(":address",en(t,"address"))),{errorContext:"Failed to fetch profile"});if(!tl(r))throw St("Malformed profile response");return r}async updateProfile(e){this.validateUpdateProfileData(e);const t={};void 0!==e.fullName&&(t.fullName=e.fullName.trim()),void 0!==e.profileImage&&(t.profileImage=e.profileImage),await Ft(()=>this.http.put(l.UPDATE_PROFILE,t,this.getJwtHeaders()),{errorContext:"Profile update failed"})}async uploadProfileImage(e){this.validateUploadProfileImageOptions(e);try{const t=void 0===e.address?"profile-image.png":`profile-image-${e.address}.png`,n=Oc(e.file,"image",t),r=await Ft(()=>this.http.request({method:"POST",url:l.UPLOAD_PROFILE_IMAGE,data:n,headers:this.getJwtHeaders()}),{errorContext:"Image upload failed"});return"string"==typeof r?r:""}catch(e){if(e instanceof rt||e instanceof ct)throw e;if(e instanceof at)throw new at(`Profile image upload failed: ${ut(e)}`,e.statusCode,e);throw new rt(`Profile image upload failed: ${ut(e)}`,"file","UPLOAD_FAILED")}}async fetchTokenList(e){if(void 0!==e.status&&"created"!==e.type)throw new rt("status filters only apply when type=created","status","INVALID_FILTER");const t=e.tokenName,n={...e},r="created"===e.type;r&&(delete n.tokenName,void 0!==t&&void 0===n.search&&(n.search=t));const s=await this.buildFetchRequest(l.GET_TOKEN_LIST,n,{includeType:!0,requestType:e.type??"both",responseKey:r?"launches":"token",errorMessage:"Failed to fetch token list"});return r&&void 0!==t?{...s,tokens:s.tokens.filter(e=>e.tokenName===t||e.name===t)}:s}async fetchTokensHeld(e){if(void 0!==e.type&&"held"!==e.type)throw new rt("fetchTokensHeld only supports type=held","type","INVALID_TYPE");if(void 0!==e.status)throw new rt("status filters only apply when type=created","status","INVALID_FILTER");return this.buildFetchRequest(l.GET_TOKENS_HELD,e,{includeType:!0,requestType:"held",responseKey:"token",errorMessage:"Failed to fetch tokens held"})}async fetchTokensCreated(e){const{cursor:t,pageSize:n,search:r,tokenName:s,status:o}=e??{};if(void 0!==e?.type&&"created"!==e.type)throw new rt("fetchTokensCreated only supports type=created","type","INVALID_TYPE");const i=e?.address??this.http.getAddress();if(null==i||""===i)throw new rt("Wallet address not available - wallet not configured","address","NO_WALLET");const a={type:"created",address:i,pageSize:n??Qo.DEFAULT_LIMIT};return void 0!==t&&(a.cursor=t),void 0!==r&&(a.search=r),void 0!==s&&void 0===r&&(a.search=s),void 0!==s&&(a.tokenName=s),void 0!==o&&(a.status=o),this.fetchTokenList(a)}async getManagedTokens(e={}){const t={};return void 0!==e.cursor&&(t.cursor=e.cursor),void 0!==e.pageSize&&(t.pageSize=String(Math.min(e.pageSize,nr))),Ft(()=>this.http.get(l.GET_MANAGED_TOKENS,t,this.getJwtHeaders()),{errorContext:"Failed to fetch managed tokens"})}async getUserGalaBalance(e){if("string"!=typeof e||""===e.trim())throw Tt("address","Address");const t=en(e.trim(),"address");return Ft(()=>this.http.get(oi(l.GET_GALA_BALANCE,{address:t})),{errorContext:"Failed to fetch GALA balance"})}async fetchReferralCode(){return Ft(()=>this.http.get(l.GET_REFERRAL_CODE,void 0,this.getJwtHeaders()),{errorContext:"Failed to fetch referral code"})}async buildFetchRequest(e,t,n){this.validateGetTokenListOptions(t);const r=ri({pageSize:t.pageSize??Qo.DEFAULT_LIMIT,...void 0!==t.cursor&&{cursor:t.cursor}},nr);ii(r,t,["address","search","tokenName","status"]),n.includeType&&!e.includes("?type=")&&(r.type=n.requestType);let s=e;const o=en(t.address??this.http.getAddress(),"address");if(void 0!==t.address&&(r.address=o),e.includes(":address")){if(0===o.length)throw Tt("address","User address");s=e.replace(":address",o),delete r.address}const i=Lt(await Bt(()=>this.http.get(s,r),{errorContext:n.errorMessage}));return{tokens:Fc(i,n.responseKey).map(e=>{const t="string"==typeof e.tokenName?e.tokenName:"",r="string"==typeof e.name?e.name:t,s="string"==typeof e.createdAt?e.createdAt:"",i=e.metadata,a={...e};return delete a.metadata,{...a,id:"string"==typeof e.id?e.id:t,name:r,symbol:"string"==typeof e.symbol?e.symbol:"",type:n.requestType,address:o,balance:"string"==typeof e.balance?e.balance:"string"==typeof e.quantity?e.quantity:"0",decimals:"number"==typeof e.decimals?e.decimals:0,...null!==i&&"object"==typeof i?{metadata:i}:{},createdAt:s,updatedAt:"string"==typeof e.updatedAt?e.updatedAt:s}}),pageInfo:ei(i?.pageInfo)}}validateGetTokenListOptions(e){const t=e.pageSize??Qo.DEFAULT_LIMIT;if(t<1||t>nr)throw new rt(`pageSize must be between 1 and ${nr}`,"pageSize","OUT_OF_RANGE");if(void 0!==e.address&&!qc(e.address))throw vt("address","eth|[40-hex-chars] or client|[identifier]","Address");const n=zc(e.search);if(null!==n&&!(Rn(r=n)&&r.length>=ur&&r.length<=hr))throw Nt("search",ur,hr,n.length,"Search query");var r;const s=zc(e.tokenName);if(!(null===s||Rn(o=s)&&Jn.PATTERN.test(o)))throw vt("tokenName",Jn.DESCRIPTION,"Token name");var o}validateUpdateProfileData(e){if(void 0!==e.address&&!qc(e.address))throw vt("address","eth|[40-hex-chars] or client|[identifier]","Address");if(void 0===e.fullName&&void 0===e.profileImage)throw new rt("At least one of fullName and profileImage must be provided","options","REQUIRED");if(void 0!==e.fullName&&(t=e.fullName.trim(),!(Rn(t)&&t.length>=gr.FULL_NAME.MIN_LENGTH&&t.length<=gr.FULL_NAME.MAX_LENGTH&&gr.FULL_NAME.ALPHABETS_ONLY_PATTERN.test(t))))throw Nt("fullName",gr.FULL_NAME.MIN_LENGTH,gr.FULL_NAME.MAX_LENGTH,e.fullName.trim().length,"Full name");var t;if("string"==typeof e.profileImage&&e.profileImage.trim().length>2048)throw new rt("profileImage must not exceed 2048 characters","profileImage","TOO_LONG")}validateUploadProfileImageOptions(e){if(void 0!==e.address&&!qc(e.address))throw vt("address","eth|[40-hex-chars] or client|[identifier]","Address")}}class rl{constructor(e,t,n=!1){this.http=e,this.poolService=new Gc(e,t,n),this.tradeService=new jc(e,n),this.userService=new nl(e,t,n),this.imageService=new xc(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 Do(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 sl(e,t){if(void 0!==e){if(!Rn(e))throw _t("tokenName","string");Pn(e,"tokenName",Xn)}if(void 0!==t){if(!Rn(t))throw _t("userAddress","string");if(t.length>sr)throw new rt(`userAddress must be at most ${sr} characters`,"userAddress",nt.TOO_LONG)}}const ol={CHAT_MESSAGE:"CHAT_MESSAGE",COMMENT:"COMMENT"},il={PAGINATION:{MAX_LIMIT:rr},CONTENT:{CHAT_MAX_LENGTH:or.CHAT_MESSAGES_V1.MAX_LENGTH,COMMENT_MAX_LENGTH:or.COMMENTS_V1.MAX_LENGTH}};function al(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function cl(e){return null===e||"string"==typeof e}function ll(e){return al(e)&&cl(e.fullName)&&cl(e.profileImage)}class dl extends ci{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}validateContent(e,t){if(!Rn(e))throw Tt("content","Message content");if(0===e.trim().length)throw Tt("content","Message content");wn(e,t===ol.CHAT_MESSAGE?or.CHAT_MESSAGES_V1.MAX_LENGTH:or.COMMENTS_V1.MAX_LENGTH,"content")}validateMessageId(e){if(!Rn(e))throw Tt("id","Message ID");if(e.length<10||e.length>64)throw vt("id","valid message ID format","Message ID")}validateMessageType(e){if(e!==ol.CHAT_MESSAGE&&e!==ol.COMMENT)throw new rt(`type must be one of: ${Object.values(ol).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,Xn);const r={};void 0!==e.cursor&&(r.cursor=e.cursor),r.pageSize=e.pageSize??Qo.DEFAULT_LIMIT;const s=ri(r,rr),o={};void 0!==s.pageSize&&(o.pageSize=s.pageSize),void 0!==s.cursor&&(o.cursor=s.cursor),t&&(o.type=e.type.toUpperCase()),n&&(o.tokenName=Kt(e.tokenName)),void 0!==e.userAddress&&""!==e.userAddress&&(o.userAddress=en(e.userAddress,"userAddress")),void 0!==e.search&&""!==e.search&&(o.search=e.search);const i=await this.http.get(Ce.GET_MESSAGES,o),a=this.extractData(i);return{messages:a.messages,pageInfo:a.pageInfo}}async createMessage(e){this.validateMessageType(e.type),this.validateTokenName(e.tokenName,Xn),this.validateContent(e.content,e.type);const t={type:e.type,tokenName:Kt(e.tokenName),content:e.content.trim()},n=await this.http.post(Ce.CREATE_MESSAGE,t,this.getJwtHeaders());return{message:this.extractData(n)}}async updateMessage(e,t){this.validateMessageId(e),this.validateContent(t.content,t.type);const n=this.buildEndpointWithId(Ce.UPDATE_MESSAGE,e),r={content:t.content.trim()},s=await this.http.put(n,r,this.getJwtHeaders());return{message:this.extractData(s)}}async deleteMessage(e){this.validateMessageId(e);const t=this.buildEndpointWithId(Ce.DELETE_MESSAGE,e);return await this.http.delete(t,void 0,this.getDualAuthHeaders()),{success:!0}}async getPinnedMessage(e){this.validateTokenName(e,Jn);const t=await this.http.get(Ce.GET_PINNED,{tokenName:Kt(e)});return{message:this.extractDataOrNull(t)}}async pinMessage(e){this.validateMessageId(e);const t=Ce.PIN_MESSAGE.replace(":id",e);return await this.http.post(t,{},this.getDualAuthHeaders()),{success:!0}}async unpinMessage(e){this.validateMessageId(e);const t=Ce.UNPIN_MESSAGE.replace(":id",e);return await this.http.delete(t,void 0,this.getDualAuthHeaders()),{success:!0}}async getMessageStats(){return function(e){const t=e=>"number"==typeof e&&Number.isFinite(e),n=e=>"object"==typeof e&&null!==e&&!Array.isArray(e);if(!n(e))throw St("Malformed message statistics response");const r=e.totalMessages,s=e.todayMessages,o=e.uniqueUsers,i=e.uniqueTokens,a=e.messagesByType;if(!(t(r)&&t(s)&&t(o)&&t(i)&&n(a)))throw St("Malformed message statistics response");const c={};for(const[e,n]of Object.entries(a)){if(!t(n))throw St("Malformed message statistics response");c[e]=n}return{totalMessages:r,todayMessages:s,uniqueUsers:o,uniqueTokens:i,messagesByType:c}}(await this.http.get(Ce.GET_MESSAGE_STATS,void 0,this.getDualAuthHeaders()))}}const ul={MODERATOR:"MODERATOR",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MANAGER:"MANAGER"},hl=Un(ul),gl={TOKEN:"TOKEN",ALL_OWNER_TOKENS:"ALL_OWNER_TOKENS"},pl=Un(gl),ml={PENDING:"PENDING",CLAIMED:"CLAIMED",REVOKED:"REVOKED",EXPIRED:"EXPIRED"},fl=Un(ml);function El(e){return hl.includes(e)}function Al(e){return fl.includes(e)}function Tl(e){return dr.PATTERN.test(e)}const vl=Bn([{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"}]),Sl=Bn([{field:"tokenName",type:"string"},{field:"tokenSymbol",type:"string"},{field:"role",type:"string"},{field:"inviteScope",type:"string"},{field:"creatorAddress",type:"string"},{field:"claimedAt",type:"string"}]),yl=Bn([{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 bl(e){return pl.includes(e)}class Nl extends ci{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}validateRole(e){if(!Rn(e))throw Tt("role","Role");if(!El(e))throw vt("role",`one of: ${hl.join(", ")}`,"Role")}validateInviteCodeFormat(e){if(!Rn(e))throw Tt("inviteCode","Invite code");if(e.length>dr.MAX_LENGTH)throw vt("inviteCode",`at most ${String(dr.MAX_LENGTH)} characters`,"Invite code")}validateInviteScope(e){if(void 0!==e&&!bl(e))throw new rt(`Invalid invite scope. Must be one of: ${pl.join(", ")}`,"inviteScope","INVALID_VALUE")}async createInvite(e){this.validateInviteScope(e.inviteScope);const t=e.inviteScope??gl.TOKEN;if(t===gl.TOKEN){if(void 0===e.tokenName||""===e.tokenName)throw new rt("Token name is required for TOKEN scope invites","tokenName","REQUIRED");this.validateTokenName(e.tokenName,Xn)}else if(t===gl.ALL_OWNER_TOKENS&&e.tokenName)throw new rt("Token name should not be provided for ALL_OWNER_TOKENS scope invites","tokenName","INVALID_VALUE");this.validateRole(e.role),this.validateOptionalString(e.description,"description","Description",or.DESCRIPTION.MAX_LENGTH),this.validateOptionalDate(e.expiresAt,"expiresAt","Expiration date");const n=V,r={inviteScope:t,role:e.role};t===gl.TOKEN&&null!==e.tokenName&&void 0!==e.tokenName&&""!==e.tokenName&&(r.tokenName=Kt(e.tokenName)),void 0!==e.description&&(r.description=e.description),void 0!==e.expiresAt&&(r.expiresAt=e.expiresAt);const s=await this.http.post(n,r,this.getMultiAuthHeaders());return{invite:this.extractData(s)}}async listInvites(e){void 0!==e.tokenName&&""!==e.tokenName&&this.validateTokenName(e.tokenName,Xn),this.validateStatusFilter(e.status,ml);const t=z,n={...this.buildPaginationParams(e,rr)};void 0!==e.tokenName&&""!==e.tokenName&&(n.tokenName=Kt(e.tokenName)),void 0!==e.status&&(n.status=e.status);const r=await this.http.get(t,n,this.getMultiAuthHeaders()),s=this.extractData(r);return{items:s.invites,pageInfo:s.pageInfo}}async revokeInvite(e){this.validatePositiveInteger(e,"inviteId","Invite ID");const t=this.buildEndpoint(Y,{id:String(e)});Mt(await this.http.delete(t,void 0,this.getMultiAuthHeaders()),"Failed to revoke invite")}async updateInviteRole(e){this.validatePositiveInteger(e.inviteId,"inviteId","Invite ID"),this.validateRole(e.role);const t=this.buildEndpoint(X,{id:String(e.inviteId)}),n={role:e.role},r=await this.http.patch(t,n,this.getMultiAuthHeaders());return{invite:this.extractData(r)}}async updateInvite(e){if(this.validatePositiveInteger(e.inviteId,"inviteId","Invite ID"),void 0===e.role&&void 0===e.description)throw new rt("At least one of role or description must be provided","options","REQUIRED");void 0!==e.role&&this.validateRole(e.role),void 0!==e.description&&this.validateOptionalString(e.description,"description","Description",or.DESCRIPTION.MAX_LENGTH);const t=this.buildEndpoint(Q,{id:String(e.inviteId)}),n={};void 0!==e.role&&(n.role=e.role),void 0!==e.description&&(n.description=e.description);const r=await this.http.patch(t,n,this.getMultiAuthHeaders());return{invite:this.extractData(r)}}async claimInvite(e){this.validateInviteCodeFormat(e.inviteCode);const t=j,n={inviteCode:e.inviteCode},r=await this.http.post(t,n,this.getMultiAuthHeaders()),s=this.extractData(r);return"tokenName"in s&&void 0!==s.tokenName?{token:s}:{blanketAccess:s}}async getModeratedTokens(e){const t=q,n=this.buildPaginationParams(e??{},rr),r=await this.http.get(t,n,this.getMultiAuthHeaders()),s=this.extractData(r);return{items:s.tokens,pageInfo:s.pageInfo}}async getInviteByCode(e){this.validateInviteCodeFormat(e);const t=this.buildEndpoint(J,{code:e}),n=await this.http.get(t,{});return this.extractData(n)}}const kl={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 wl(e){return`${e}-${Date.now()}-${Math.random().toString(36).substring(2,11)}`}function _l(){return Date.now()+6e4}function Il(e){return""!==e&&"string"==typeof e&&/^[a-zA-Z0-9]{3,50}$/.test(e)}function Cl(e){try{return Math.floor(parseFloat(String(e))??0).toString()}catch{return"0"}}function Dl(e){return""!==e&&"string"==typeof e&&sn(e)}class Rl extends jn{constructor(e){super(e)}getCollectionClaimFee(){return kl.COLLECTION_CLAIM_FEE}getTokenClassCreateFee(){return kl.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(!Dl(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=kl.COLLECTION_CLAIM_FEE;n.collectionClaim=e,t=String(BigInt(t)+BigInt(e))}if((e.createTokenClasses??0)>0){const r=kl.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),!Il(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:_l(),uniqueKey:wl("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),!Dl(e))throw new Error(`Invalid wallet address format: ${e}`);const t=(await this.allAuthorizations()).filter(t=>t.authorizedUsers.some(t=>rn(t,e))).map(t=>({authorizedUser:Zt(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),!Il(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(!Il(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?Cl(e.maxSupply):void 0,maxCapacity:void 0!==e.maxCapacity?Cl(e.maxCapacity):void 0,additionalKey:e.additionalKey,expiresAt:_l(),uniqueKey:wl("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),!Il(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(!Dl(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:Zt(e.ownerAddress,"ownerAddress"),additionalKey:e.additionalKey??"none",expiresAt:_l(),uniqueKey:wl("mint")};this.logger.debug("Built mint DTO",r);const s=`mint-${Date.now()}`,o=Array.from({length:t},(e,t)=>t+1);return{transactionId:s,mintedQuantity:e.quantity,owner:Zt(e.ownerAddress,"ownerAddress"),tokenInstances:o,tokenClass:{collection:e.collection,type:e.type,category:e.category}}}catch(e){throw this.logger.error("Failed to mint NFT",e),e}}async fetchNftBalances(e,t){try{if(this.logger.debug("Fetching NFT balances for",{ownerAddress:e,collectionFilter:t}),!Dl(e))throw new Error(`Invalid owner address: ${e}`);const n=(await this.reads().fetchNftBalances({owner:Zt(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:t}=Va(async(e,t)=>({data:await this.http.post(e,t)}));return new e.GatewayReads({gatewayBaseUrl:"",httpRequestor:t,requestTimeoutMs:1/0})}allAuthorizations(){return this.reads().fetchAllNftCollectionAuthorizations({pageSize:1e3})}}class Ol extends jn{constructor(e,t=!1,n){super(e,t,n)}extractData(e){if(e.error||void 0===e.data){const t=e.message??"Notification operation failed";throw new Error(t)}return e.data}async registerPushToken(e){this.logger.debug("Registering push token",{platform:e.platform});const t=this.getJwtHeaders(),n=await this.http.post(je,{token:e.token,platform:e.platform,...void 0!==e.deviceId?{deviceId:e.deviceId}:{}},t),r=this.extractData(n);return this.logger.debug("Push token registered",{registered:r.registered}),r}async unregisterPushToken(e){this.logger.debug("Unregistering push token");const t=this.getJwtHeaders(),n=await this.http.request({method:"DELETE",url:qe,data:{token:e},headers:t}),r=this.extractData(n);return this.logger.debug("Push token unregistered",{unregistered:r.unregistered}),r}async getPreferences(){this.logger.debug("Fetching notification preferences");const e=this.getJwtHeaders(),t=await this.http.get(ze,void 0,e),n=this.extractData(t);return this.logger.debug("Fetched notification preferences",{tradesEnabled:n.tradesEnabled,streamsEnabled:n.streamsEnabled}),{preferences:n}}async updatePreferences(e){this.logger.debug("Updating notification preferences",e);const t=this.getJwtHeaders(),n=await this.http.put(Ye,e,t),r=this.extractData(n);return this.logger.debug("Updated notification preferences",{tradesEnabled:r.tradesEnabled,streamsEnabled:r.streamsEnabled}),{preferences:r}}}class xl extends jn{constructor(e,t=!1){super(e,t)}async getHomeOEmbedJson(e={}){this.logger.debug("Fetching home oEmbed (JSON)");const t=await this.http.get(l.OEMBED,{format:"json"});return this.logger.debug("Fetched home oEmbed (JSON)",{title:t.title}),{oembed:t}}async getHomeOEmbedHtml(e={}){this.logger.debug("Fetching home oEmbed (HTML)");const t=await this.http.get(l.OEMBED,{},{responseType:"text"});return this.logger.debug("Fetched home oEmbed (HTML)"),{html:t}}async getPoolOEmbedJson(e){const{tokenName:t}=e;if(null==t||"string"!=typeof t||""===t.trim())throw new rt("tokenName is required","tokenName","REQUIRED_FIELD");this.logger.debug("Fetching pool oEmbed (JSON)",{tokenName:t});const n=l.OEMBED_BUY_SELL.replace(":tokenName",t.toLowerCase().trim()),r=await this.http.get(n,{format:"json"});return this.logger.debug("Fetched pool oEmbed (JSON)",{tokenName:t,title:r.title}),{oembed:r}}async getPoolOEmbedHtml(e){const{tokenName:t}=e;if(null==t||"string"!=typeof t||""===t.trim())throw new rt("tokenName is required","tokenName","REQUIRED_FIELD");this.logger.debug("Fetching pool oEmbed (HTML)",{tokenName:t});const n=l.OEMBED_BUY_SELL.replace(":tokenName",t.toLowerCase().trim()),r=await this.http.get(n,{},{responseType:"text"});return this.logger.debug("Fetched pool oEmbed (HTML)",{tokenName:t}),{html:r}}async getProfileOEmbedJson(e){const{address:t}=e;if(null==t||"string"!=typeof t||""===t.trim())throw new rt("address is required","address","REQUIRED_FIELD");this.logger.debug("Fetching profile oEmbed (JSON)",{address:t});const n=l.OEMBED_PROFILE.replace(":address",encodeURIComponent(en(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 rt("address is required","address","REQUIRED_FIELD");this.logger.debug("Fetching profile oEmbed (HTML)",{address:t});const n=l.OEMBED_PROFILE.replace(":address",encodeURIComponent(en(t.trim(),"address"))),r=await this.http.get(n,{},{responseType:"text"});return this.logger.debug("Fetched profile oEmbed (HTML)",{address:t}),{html:r}}}function Ml(e){if(!Rn(e))throw Tt("address","Address");Zt(e,"address")}const Ll={PENDING:"PENDING",CLAIMED:"CLAIMED",REVOKED:"REVOKED",EXPIRED:"EXPIRED"},Ul={ACTIVE:"ACTIVE",REVOKED:"REVOKED"},Fl=Ln(Ll),Pl=Ln(Ul);function Bl(e){try{Kn(e.description,"description",255)}catch(e){if(e instanceof rt){throw e.message.includes("255")?new Error("description must be at most 255 characters"):new Error("description must be a string")}throw e}if(void 0!==e.expiresAt){if(!Rn(e.expiresAt))throw new Error("expiresAt must be a non-empty string");try{Hn(e.expiresAt,"expiresAt")}catch(e){if(e instanceof rt)throw new Error("expiresAt must be a valid ISO 8601 date string");throw e}if(Qt(e.expiresAt)){if(Xt(e.expiresAt)<=new Date)throw new Error("expiresAt must be in the future")}}}function Gl(e){if(void 0!==e.status&&!Fl(e.status))throw Ct("status",e.status,Object.values(Ll),"status");Mn(0,void 0,50,e.pageSize,e.cursor)}function $l(e){if(void 0!==e.status&&!Pl(e.status))throw Ct("status",e.status,Object.values(Ul),"status");Mn(0,void 0,50,e.pageSize,e.cursor)}function Kl(e){if(!Rn(e))throw new Error("Invite code must be a non-empty string");wn(e,dr.MAX_LENGTH,"code")}function Hl(e){if(!Rn(e))throw new Error("Address must be a non-empty string");try{fn(e,"address")}catch{throw new Error("Invalid wallet address format. Must be eth|..., 0x..., or client|... format")}}function Wl(e){try{_n(e,"id")}catch(e){if(e instanceof rt)throw new Error("Invite ID must be a positive integer");throw e}}function Vl(e){if(null==e||"object"!=typeof e)throw new rt("Options are required");if(void 0!==e.search){if("string"!=typeof e.search)throw new rt("Search must be a string");if(0===e.search.length)throw new rt("Search query cannot be empty string")}if(void 0!==e.sortBy){if("string"!=typeof e.sortBy)throw new rt("Sort field must be a string");if(0===e.sortBy.length)throw new rt("Sort field cannot be empty string")}if(void 0!==e.sortOrder){const t="string"==typeof e.sortOrder?e.sortOrder.toLowerCase():"";if("asc"!==t&&"desc"!==t)throw new rt('Sort order must be "asc" or "desc"')}}function jl(e){if(null==e||"object"!=typeof e)throw new rt("Options are required");if(!Rn(e.userAddress))throw new rt("userAddress is required and must be a non-empty string");try{fn(e.userAddress,"userAddress")}catch{throw new rt("Invalid wallet address format. Must be eth|..., 0x..., or client|... format")}if(void 0!==e.description){if("string"!=typeof e.description)throw new rt("description must be a string");if(e.description.length>255)throw new rt("description must be at most 255 characters")}}class ql extends ci{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}validateInviteCodeFormat(e){if(!Rn(e))throw Tt("inviteCode","Invite code");Kl(e)}validateWalletAddressFormat(e){if(!Rn(e))throw Tt("address","Address");Hl(e)}async createInvite(e={}){Bl(e),this.validateOptionalString(e.description,"description","Description",or.DESCRIPTION.MAX_LENGTH),this.validateOptionalDate(e.expiresAt,"expiresAt","Expiration date");const t=ee,n={};void 0!==e.description&&(n.description=e.description),void 0!==e.expiresAt&&(n.expiresAt=e.expiresAt);const r=await this.http.post(t,n,this.getDualAuthHeaders());return{invite:this.extractData(r)}}async listInvites(e={}){Gl(e),this.validateStatusFilter(e.status,Ll);const t=te,n={...this.buildPaginationParams(e,rr)};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){Wl(e);const t=this.buildEndpoint(se,{id:String(e)});Mt(await this.http.delete(t,void 0,this.getDualAuthHeaders()),"Failed to revoke invite")}async claimInvite(e){this.validateInviteCodeFormat(e);const t=re,n={inviteCode:e},r=await this.http.post(t,n,this.getJwtHeaders());return{invite:this.extractData(r)}}async listOverseers(e={}){$l(e),this.validateStatusFilter(e.status,Ul);const t=oe,n={...this.buildPaginationParams(e,rr)};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){jl(e),this.validateWalletAddressFormat(e.userAddress),this.validateOptionalString(e.description,"description","Description",or.DESCRIPTION.MAX_LENGTH);const t=ie,n={userAddress:en(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(ae,{address:en(e,"address")});Mt(await this.http.delete(t,void 0,this.getDualAuthHeaders()),"Failed to revoke overseer")}async getMyStatus(){const e=ce,t=await this.http.get(e,{},this.getJwtHeaders());return this.extractData(t)}async getSummary(){const e=le,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getBanStats(){const e=de,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getTokenBanStats(){const e=ue,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getInviteStats(){const e=he,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getFlagStats(){const e=ge,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getUserStats(){const e=pe,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async listOverseerUsers(e){const t=e??{};Object.keys(t).length>0&&Vl(t);const n=me,r=this.buildPaginationParams(t,rr);void 0!==t.search&&""!==t.search&&(r.search=t.search),void 0!==t.sortBy&&""!==t.sortBy&&(r.sortBy=t.sortBy),void 0!==t.sortOrder&&(r.sortOrder=t.sortOrder);const s=await this.http.get(n,r,this.getDualAuthHeaders()),o=this.extractData(s);return{items:o.users,pageInfo:o.pageInfo}}async getOverseerUserSummary(e){if(!Rn(e))throw Tt("address","User address");Hl(e);const t=this.buildEndpoint(fe,{address:en(e,"address")}),n=await this.http.get(t,{},this.getDualAuthHeaders());return this.extractData(n)}async flushCacheByAddress(e){Ml(e);const t=this.buildEndpoint(Ee,{address:en(e,"address")}),n=await this.http.delete(t,void 0,this.getDualAuthHeaders());return this.extractData(n)}async flushCacheByToken(e){!function(e){if(!Rn(e))throw Tt("tokenName","Token name")}(e);const t=this.buildEndpoint(Ae,{tokenName:e}),n=await this.http.delete(t,void 0,this.getDualAuthHeaders());return this.extractData(n)}async flushAllCache(e){!function(e){if(!0!==e)throw new rt("Safety confirmation required: must pass confirm=true to flush all cache","confirm","CONFIRMATION_REQUIRED")}(e);const t=Te,n=await this.http.delete(t,{confirm:"true"},this.getDualAuthHeaders());return this.extractData(n)}async flushWalletAliasCache(e){if(void 0!==e){Ml(e);const t=this.buildEndpoint(ve,{address:en(e,"address")}),n=await this.http.delete(t,void 0,this.getDualAuthHeaders());return this.extractData(n)}const t=Se,n=await this.http.delete(t,{confirm:"true"},this.getDualAuthHeaders());return this.extractData(n)}}function zl(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 Yl extends jn{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),Mt(t,"Platform config operation failed",!0),e.data}async getPlatformConfig(){const e=await this.http.get(N);return this.extractData(e)}async updatePlatformConfig(e){const t=zl(e);if(t.length>0)throw new rt(t.join("; "),"options","VALIDATION_FAILED");const n=await this.http.put(k,e,this.getJwtHeaders());return this.extractData(n)}async getAvailableRoles(){const e=await this.http.get(I);return this.extractData(e)}}class Xl extends jn{constructor(e,t=!1){super(e,t)}extractData(e){if(e.error||void 0===e.data){const t=e.message??"Platform stats operation failed";throw new Error(t)}return e.data}async getStats(){this.logger.debug("Fetching platform stats");const e=await this.http.get(Ge),t=this.extractData(e);return this.logger.debug("Fetched platform stats",{totalTokens:t.totalTokens,timestamp:t.timestamp}),{stats:t}}}class Ql extends ci{constructor(e,t,n,r){super(e,t,n,!1,r)}async getRestrictedNames(){try{return{success:!0,data:(await this.http.get(De,void 0,this.getJwtHeaders())).data}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}async updateRestrictedNames(e){try{if("string"!=typeof e.content)throw new rt("Content is required");return{success:!0,data:(await this.http.put(Re,{content:e.content},this.getJwtHeaders())).data}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}}class Jl extends ci{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async getChatStatus(e){if(null==e||""===e)throw Tt("tokenName","Token name");return this.validateTokenName(e,Jn),$o(async()=>{const t=this.buildEndpoint(Oe,{tokenName:e}),n=await this.http.get(t);return this.buildChatStatusResponse(e,this.extractData(n))},`Failed to get chat status for token: ${e}`,this.logger)}async disableChat(e){if(null==e||""===e)throw Tt("tokenName","Token name");return this.validateTokenName(e,Jn),$o(async()=>{const t=this.buildEndpoint(Me,{tokenName:e}),n=await this.http.post(t,{enabled:!1},this.getDualAuthHeaders());return this.buildChatStatusResponse(e,this.extractData(n))},`Failed to disable chat for token: ${e}`,this.logger)}async enableChat(e){if(null==e||""===e)throw Tt("tokenName","Token name");return this.validateTokenName(e,Jn),$o(async()=>{const t=this.buildEndpoint(xe,{tokenName:e}),n=await this.http.post(t,{enabled:!0},this.getDualAuthHeaders());return this.buildChatStatusResponse(e,this.extractData(n))},`Failed to enable chat for token: ${e}`,this.logger)}buildChatStatusResponse(e,t){const n={enabled:t.enabled,tokenName:t.tokenName??Kt(e)};return void 0!==t.status&&null!==t.status&&(n.status=t.status),"global"!==t.reason&&"token"!==t.reason||(n.reason=t.reason),"number"==typeof t.slowModeSeconds&&(n.slowModeSeconds=t.slowModeSeconds),n}async setSlowMode(e,t){if(null==e||""===e)throw Tt("tokenName","Token name");if(this.validateTokenName(e,Jn),"number"!=typeof t||t<0||t>600)throw new Error("slowModeSeconds must be a number between 0 and 600");return $o(async()=>{const n=this.buildEndpoint(Le,{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 Zl={IDLE:"IDLE",ACTIVE:"ACTIVE",DISABLED:"DISABLED"},ed={PREPARING:"preparing",READY:"ready",ERRORED:"errored"},td={YOUTUBE:"youtube",TWITCH:"twitch",FACEBOOK:"facebook",CUSTOM:"custom"},nd=Ln(Zl),rd=Ln(ed),sd=Ln(td);const od={OWNER:"OWNER",MANAGER:"MANAGER",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MODERATOR:"MODERATOR"},id={OWNER:"OWNER",MODERATOR:"MODERATOR"};Ln(od),Ln(id);const ad={...od,OVERSEER:"OVERSEER"},cd=Ln(ad);function ld(e,t="tokenName"){Fn(e,t,Jn)}const dd=/^rtmps?:\/\/\S+$/u,ud=255;function hd(e){if(ld(e.tokenName),!Rn(e.language))throw Tt("language");if(t=e.language,!Rn(t)||!/^[a-z]{2}(-[A-Z]{2})?$/.test(t))throw new rt('language must be a valid ISO 639-1 code (e.g., "en", "es", "zh-CN")',"language",nt.INVALID_FORMAT);var t}class gd extends ci{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async startStream(e){this.validateTokenName(e,Jn);const t=this.buildEndpoint(g,{tokenName:e}),n=await this.http.post(t,{},this.getJwtHeaders());return this.extractData(n)}async stopStream(e){this.validateTokenName(e,Jn);const t=this.buildEndpoint(p,{tokenName:e});await this.http.post(t,{},this.getJwtHeaders())}async disableStream(e){return this.toggleFeature(e,m,Jn)}async enableStream(e){return this.toggleFeature(e,f,Jn)}async resetStreamKey(e){this.validateTokenName(e,Jn);const t=this.buildEndpoint(E,{tokenName:e}),n=await this.http.post(t,{},this.getJwtHeaders());return this.extractData(n)}async getStreamCredentials(e){this.validateTokenName(e,Jn);const t=this.buildEndpoint(D,{tokenName:e}),n=await this.http.get(t,{},this.getJwtHeaders());return this.extractData(n)}async getRecordings(e){!function(e){ld(e.tokenName)}(e);const t=this.buildEndpoint(A,{tokenName:e.tokenName}),n=await this.http.get(t),r=this.extractData(n);if(!Array.isArray(r))throw St("Invalid recordings response: expected an array of recordings");return{recordings:r,tokenName:Kt(e.tokenName)}}async getRecordingDownload(e,t){this.validateTokenName(e,Jn),this.validateRequiredString(t,"assetId","Asset ID");const n=this.buildEndpoint(T,{tokenName:e,assetId:t}),r=await this.http.get(n,{},this.getJwtHeaders());return this.extractData(r)}async deleteRecording(e,t){this.validateTokenName(e,Jn),this.validateRequiredString(t,"assetId","Asset ID");const n=this.buildEndpoint(v,{tokenName:e,assetId:t});await this.http.delete(n,void 0,this.getJwtHeaders())}async getSimulcastTargets(e){this.validateTokenName(e,Jn);const t=this.buildEndpoint(S,{tokenName:e}),n=await this.http.get(t,void 0,this.getJwtHeaders()),r=this.extractData(n);if(!Array.isArray(r))throw St("Invalid simulcast response: expected an array of targets");return{targets:r,tokenName:Kt(e)}}async addSimulcastTarget(e){!function(e){if(ld(e.tokenName),!Rn(e.platform))throw Tt("platform");if(!sd(e.platform))throw new rt("platform must be one of: 'youtube', 'twitch', 'facebook', 'custom'","platform",nt.INVALID_VALUE);if(!Rn(e.url))throw Tt("url");if(!dd.test(e.url))throw new rt("url must be a valid RTMP or RTMPS URL","url",nt.INVALID_FORMAT);if(e.url.length>2048)throw new rt(`url must not exceed ${String(2048)} characters`,"url",nt.TOO_LONG);if(!Rn(e.streamKey))throw Tt("streamKey");if(e.streamKey.length>ud)throw new rt(`streamKey must not exceed ${String(ud)} characters`,"streamKey",nt.TOO_LONG);if(void 0!==e.passthrough){if("string"!=typeof e.passthrough)throw new rt("passthrough must be a string","passthrough",nt.INVALID_TYPE);if(e.passthrough.length>ud)throw new rt(`passthrough must not exceed ${String(ud)} characters`,"passthrough",nt.TOO_LONG)}}(e);const t=this.buildEndpoint(y,{tokenName:e.tokenName}),n=await this.http.post(t,{platform:e.platform,url:e.url,streamKey:e.streamKey,...void 0!==e.passthrough&&{passthrough:e.passthrough}},this.getJwtHeaders());return{target:this.extractData(n),tokenName:Kt(e.tokenName)}}async removeSimulcastTarget(e,t){this.validateTokenName(e,Jn),this.validateRequiredString(t,"targetId","Target ID");const n=this.buildEndpoint(b,{tokenName:e,targetId:t});await this.http.delete(n,void 0,this.getJwtHeaders())}async getGlobalStreamingStatus(){const e=await this.http.get(N);return this.extractData(e)}async disableGlobalStreaming(){const e=await this.http.put(k,{},this.getAdminHeaders());return this.extractData(e)}async enableGlobalStreaming(){const e=await this.http.put(w,{},this.getAdminHeaders());return this.extractData(e)}async setNextLiveStream(e){let t;!function(e){if(ld(e.tokenName),null!==e.nextLiveStreamAt){if(!(e.nextLiveStreamAt instanceof Date||Rn(e.nextLiveStreamAt)))throw new rt("nextLiveStreamAt must be a Date, ISO 8601 string, or null","nextLiveStreamAt",nt.INVALID_TYPE);if("string"==typeof e.nextLiveStreamAt){const t=Date.parse(e.nextLiveStreamAt);if(isNaN(t))throw new rt("nextLiveStreamAt must be a valid ISO 8601 date string","nextLiveStreamAt",nt.INVALID_FORMAT)}}}(e),t=null===e.nextLiveStreamAt?null:e.nextLiveStreamAt instanceof Date?e.nextLiveStreamAt.toISOString():e.nextLiveStreamAt;const n=`/v1/tokens/${e.tokenName.toLowerCase().trim()}`;await this.http.patch(n,{nextLiveStreamAt:t},this.getJwtHeaders())}async clearNextLiveStream(e){this.validateTokenName(e,Jn);const t=`/v1/tokens/${e.toLowerCase().trim()}`;await this.http.patch(t,{nextLiveStreamAt:null},this.getJwtHeaders())}async setStreamLanguage(e){hd(e);const t=`/v1/tokens/${e.tokenName.toLowerCase().trim()}`;await this.http.patch(t,{streamLanguage:e.language},this.getJwtHeaders())}async getStreamRole(e){!function(e){ld(e.tokenName)}(e);const t=this.buildEndpoint(_,{tokenName:e.tokenName}),n=this.jwtAuth?this.getJwtHeaders():{},r=await this.http.get(t,{},n);return this.extractData(r)}async getAvailableRoles(){const e=await this.http.get(I);return this.extractData(e)}async getTokenAccess(e){!function(e){ld(e.tokenName)}(e);const t=await this.http.get(C,{tokenName:Kt(e.tokenName)},this.getJwtHeaders());return this.extractData(t)}async setNextLiveStreamCountdown(e,t){return this.setNextLiveStream({tokenName:e,nextLiveStreamAt:t})}}const pd={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"},md=e=>fd(e.flagId);function fd(e){return"string"==typeof e||"number"==typeof e?String(e):void 0}function Ed(e,t){const n=t.map(t=>fd(e[t]));return n.every(e=>void 0!==e)?n.join("|"):void 0}const Ad={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=>fd(e.id)},FLAG_RESOLVED:{duplicateKey:e=>Ed(e,["id","status","reviewedAt"])},AI_MODERATION_COMPLETE:{duplicateKey:md},AI_MODERATION_FAILED:{duplicateKey:md},MODERATOR_INVITE_CREATED:{},MODERATOR_ADDED:{},MODERATOR_REMOVED:{},MODERATOR_ROLE_UPDATED:{},OVERSEER_ADDED:{token:"none",duplicateKey:e=>Ed(e,["userAddress","addedAt"])},OVERSEER_REMOVED:{token:"none",duplicateKey:e=>Ed(e,["userAddress","removedAt"])},POOL_CREATED:{duplicateKey:e=>Ed(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 Td(e){return Ad[e]}const vd=Object.keys(Ad);const Sd="token:",yd="comment:",bd="global:feed",Nd="global:events_firehose";function kd(e){if(e.startsWith(Sd)){const t={tokenName:e.slice(Sd.length)};return{join:{event:pd.SUBSCRIBE,payload:t},leave:{event:pd.UNSUBSCRIBE,payload:t}}}if(e.startsWith(yd)){const t={tokenName:e.slice(8)};return{join:{event:pd.SUBSCRIBE_COMMENT,payload:t},leave:{event:pd.UNSUBSCRIBE_COMMENT,payload:t}}}return e===Nd?{join:{event:pd.SUBSCRIBE_EVENTS_FIREHOSE},leave:{event:pd.UNSUBSCRIBE_EVENTS_FIREHOSE}}:{join:{event:pd.SUBSCRIBE_GLOBAL_FEED},leave:{event:pd.UNSUBSCRIBE_GLOBAL_FEED}}}const wd=new Set(["token_subscribed","room_subscribed","global_feed_subscribed","events_firehose_subscribed"]);const _d={STREAM_CHAT_GLOBAL_STATUS:"chatEnabled",STREAM_GLOBAL_STATUS:"streamingEnabled",COMMENTS_GLOBAL_STATUS:"commentsEnabled",WEBHOOKS_GLOBAL_STATUS:"webhooksEnabled",AI_MODERATION_GLOBAL_STATUS:"aiModerationEnabled"},Id=["STREAM_STATUS","TRADE_EXECUTED","HOLDER_COUNT_UPDATED","POOL_BADGE_ASSIGNED","VIEWER_COUNT","TOKEN_CONFIG_UPDATED","STATS_UPDATED","POOL_CREATED"],Cd=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"]),Dd=new Set(["COMMENT_CREATED","COMMENT_UPDATED","COMMENT_DELETED"]);const Rd={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"},Od={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"},xd=()=>{};function Md(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Ld(e,t){return t}function Ud(e){return`${Sd}${e}`}function Fd(e){return`${yd}${e}`}function Pd(e){const t=Kt(e);if(""===t)throw Tt("tokenName","Token name");return t}class Bd extends qn{constructor(e,t=!1){if(super(t),this.socket=null,this.disposed=!1,this.epoch=0,this.connectionGeneration=0,this.hasConnected=!1,this.connectAttempt=null,this.reconnectExhausted=!1,this.managerCleanups=[],this.connectionStateListeners=new Set,this.reconnectListeners=new Set,this.subscribers=new Map,this.roomRefs=new Map,this.roomStates=new Map,this.roomWaiters=new Map,this.explicitHolds=new Map,this.recentOccurrences=new Map,this.siteConfig={chatEnabled:void 0,streamingEnabled:void 0,commentsEnabled:void 0,webhooksEnabled:void 0,aiModerationEnabled:void 0},this.authenticated=!1,this.authenticatedToken=null,this.authenticatedGeneration=-1,this.wantsAuthentication=!1,this.lastExplicitToken=null,this.authSequence=0,this.inFlight=null,this.lastEmitted=null,this.pendingAuthenticate=null,""===e.url)throw new ct("Stream WebSocket URL is required. Set streamWebSocketUrl in SDK config.");this.config={url:e.url,reconnectAttempts:e.reconnectAttempts??5,reconnectDelay:e.reconnectDelay??2e3,reconnectDelayMax:e.reconnectDelayMax,subscriptionTimeout:e.subscriptionTimeout??1e4,tokenProvider:e.tokenProvider,autoConnect:e.autoConnect??!0},this.isSocketIOAvailable="function"==typeof i.io}register(e,t,n={}){if(this.disposed)return xd;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 xd;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===Nd}(e)&&!this.authenticated)return;this.joinRoom(t,e)}else n||"joined"!==r?.phase||(t.emit(kd(e).leave.event,kd(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=kd(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(Sd)?e.slice(Sd.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((!Md(t)||!this.isDuplicate(e,t))&&(this.deliver(e,t,Md(t)?function(e,t){const n=Td(e).token??"payload";if("none"===n)return;if("room"===n){const e=t.room;return"string"==typeof e&&e.startsWith(Sd)?e.slice(Sd.length):void 0}const r=t.tokenName;return"string"==typeof r&&""!==r?r:void 0}(e,t):void 0),Md(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=Td(e).duplicateKey?.(t);if(void 0===n)return!1;const r=Date.now(),s=`${e}:${n}`,o=this.recentOccurrences.get(s);if(void 0!==o&&r-o<5e3)return!0;if(this.recentOccurrences.set(s,r),this.recentOccurrences.size>256)for(const[e,t]of this.recentOccurrences)r-t>=5e3&&this.recentOccurrences.delete(e);return!1}deliver(e,t,n){const r=this.subscribers.get(e);if(void 0===r)return;const s=void 0===n?void 0:Kt(n);for(const n of[...r])n.active&&(void 0!==n.token&&n.token!==s||(void 0===n.filter||this.passes(n,t))&&this.invoke(e,n.deliver,t))}passes(e,t){try{return e.filter?.(t)??!0}catch(t){return this.logger.error(`Error in a ${e.name} filter:`,t),!1}}invoke(e,t,n){try{const r=t(n);r instanceof Promise&&r.catch(t=>{this.logger.error(`Error in a ${e} subscriber:`,t)})}catch(t){this.logger.error(`Error in a ${e} subscriber:`,t)}}applyEffects(e,t){if("authenticated"===e)null!==this.inFlight?this.inFlight.settle(!0):this.adoptLateAuthentication();else if("stream_chat_auth_error"===e)this.authenticated=!1,this.inFlight?.settle(!1);else if("exception"===e)this.inFlight?.settle(!1);else if(function(e){return wd.has(e)}(e))Md(t)&&"string"==typeof t.room&&this.onRoomAcknowledged(t.room);else{const n=_d[e];void 0!==n&&(this.siteConfig={...this.siteConfig,[n]:Gd(t)})}}liveSocket(){return null!==this.socket&&this.socket.connected?this.socket:null}connect(){if(this.disposed)return Promise.reject(new ct("The stream WebSocket service has been disposed."));if(!this.isSocketIOAvailable)return Promise.reject(new ct('Socket.IO not available. Install "socket.io-client" package.'));const e=this.socket??this.createSocket();if(e.connected)return Promise.resolve();if(null===this.connectAttempt){let e=()=>{},t=()=>{};const n=new Promise((n,r)=>{e=n,t=r});this.connectAttempt={promise:n,resolve:e,reject:t}}return e.connect(),this.connectAttempt.promise}createSocket(){this.logger.debug(`🔌 Connecting to Stream WebSocket: ${this.config.url}`);const e=i.io(this.config.url,{transports:["websocket"],reconnection:!0,reconnectionAttempts:this.config.reconnectAttempts,reconnectionDelay:this.config.reconnectDelay,...void 0!==this.config.reconnectDelayMax&&{reconnectionDelayMax:this.config.reconnectDelayMax}});return this.socket=e,this.attachListeners(e),e}attachListeners(e){e.on("connect",()=>{this.onSocketConnect()}),e.on("disconnect",e=>{this.onSocketDisconnect(e)}),e.on("connect_error",e=>{this.logger.error("❌ Stream WebSocket connection error:",e),this.settleConnectWaiters(e)}),e.on("error",e=>{this.logger.error("❌ Stream WebSocket error:",e)});for(const t of vd)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?xd:(this.connectionStateListeners.add(e),()=>{this.connectionStateListeners.delete(e)})}onReconnect(e){return this.disposed?xd:(this.reconnectListeners.add(e),()=>{this.reconnectListeners.delete(e)})}async resolveToken(){const e=this.config.tokenProvider;if(void 0===e)return this.lastExplicitToken;try{const t=await e();return null!==t&&""!==t?t:null}catch(e){return this.logger.warn(`The token provider failed: ${ut(e)}`),null}}authenticate(e){if(""===e)return Promise.reject(Tt("token","Authentication token"));const t=this.pendingAuthenticate;if(null!==t&&t.token===e&&t.generation===this.connectionGeneration)return t.promise;this.authSequence+=1;const n=this.authSequence,r=this.runAuthenticate(e,n).finally(()=>{this.pendingAuthenticate?.promise===r&&(this.pendingAuthenticate=null)});return this.pendingAuthenticate={token:e,generation:this.connectionGeneration,promise:r},r}async runAuthenticate(e,t){if(this.disposed)return!1;const n=e??await this.resolveToken();if(t!==this.authSequence||null===n)return!1;void 0!==e&&(this.lastExplicitToken=e);try{await this.connect()}catch(e){return this.logger.warn(`Cannot authenticate, the connection failed: ${ut(e)}`),!1}for(;null!==this.inFlight;)if(await this.inFlight.settled,t!==this.authSequence)return!1;const r=this.liveSocket();if(t!==this.authSequence||null===r)return!1;if(this.authenticated&&this.authenticatedToken===n&&this.authenticatedGeneration===this.connectionGeneration)return!0;const s=this.beginAuthentication(t,n);this.lastEmitted={seq:t,token:n,generation:this.connectionGeneration},this.logger.debug("📡 Authenticating with stream server"),r.emit(pd.AUTHENTICATE,{token:n});return await s.result&&t===this.authSequence}beginAuthentication(e,t){let n=()=>{};const r=new Promise(e=>{n=e}),s={seq:e,token:t,generation:this.connectionGeneration,result:r,settled:r.then(()=>{}),timer:void 0,settle:e=>{this.finishAuthentication(s,e,n)}};return s.timer=setTimeout(()=>{this.logger.warn("Stream WebSocket authentication timed out"),s.settle(!1)},this.config.subscriptionTimeout),this.inFlight=s,s}finishAuthentication(e,t,n){if(this.inFlight!==e)return;void 0!==e.timer&&clearTimeout(e.timer),this.inFlight=null;const r=e.seq===this.authSequence&&e.generation===this.connectionGeneration;t&&r&&this.markAuthenticated(e.token,e.generation),n(t&&r)}markAuthenticated(e,t){this.authenticated=!0,this.authenticatedToken=e,this.authenticatedGeneration=t,this.wantsAuthentication=!0,this.syncAllRooms()}adoptLateAuthentication(){const e=this.lastEmitted;null===e||this.authenticated||e.seq===this.authSequence&&e.generation===this.connectionGeneration&&this.markAuthenticated(e.token,e.generation)}deauthenticate(){this.authSequence+=1;const e=this.authenticated||null!==this.inFlight;this.inFlight?.settle(!1),this.pendingAuthenticate=null,this.wantsAuthentication=!1,this.lastExplicitToken=null,this.authenticated=!1,this.authenticatedToken=null,this.authenticatedGeneration=-1,e&&null!==this.socket&&!this.disposed&&(this.socket.disconnect(),this.socket.connect())}isAuthenticatedForChat(){return this.authenticated}isConnected(){return this.socket?.connected??!1}requireReady(){const e=this.liveSocket();if(null===e)throw new rt("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(!this.authenticated)throw new rt("Not authenticated. Call authenticate() first.","auth","NOT_AUTHENTICATED");return e}sendChatMessage(e,t){if(""===e)throw Tt("tokenName","Token name");if(""===t)throw Tt("content","Message content");const n=this.requireReady(),r=Kt(e);this.logger.debug(`📡 Sending chat message to ${r}: ${t.slice(0,30)}...`),n.emit(pd.SEND_CHAT,{tokenName:r,content:t})}sendReaction(e,t,n=0){if(""===e)throw Tt("tokenName","Token name");if(""===t)throw Tt("emoji");const r=this.requireReady(),s=Kt(e);this.logger.debug(`📡 Sending reaction to ${s}: ${t}`),r.emit(pd.SEND_REACTION,{tokenName:s,emoji:t,streamTime:n})}sendTypingStart(e){this.sendTypingEvent(e,pd.TYPING_START)}sendTypingStop(e){this.sendTypingEvent(e,pd.TYPING_STOP)}sendTypingEvent(e,t){if(""===e)throw Tt("tokenName","Token name");this.requireReady().emit(t,{tokenName:Kt(e)})}subscribeToken(e,t,n){const r=Pd(t);return this.register(e,e=>n(Ld(0,e)),{token:r,room:Ud(r)})}joinTokenRoom(e){return this.hold(Ud(Pd(e)))}subscribeComment(e,t,n){const r=Pd(t);return this.register(e,e=>n(Ld(0,e)),{token:r,room:Fd(r)})}subscribeFeed(e,t){return this.register(e,e=>t(Ld(0,e)),{room:bd})}subscribeEvent(e,t){return this.register(e,e=>t(Ld(0,e)))}subscribeEventsFirehose(e,t){const n=function(e){if(void 0===e)return;const t=e.eventTypes?.map(e=>e.toLowerCase()),n=void 0===e.tokenName?void 0:Kt(e.tokenName),r=e.userAddress;return void 0!==t||void 0!==n||void 0!==r?e=>{if(!Md(e))return!1;const s=e.eventType;if(void 0!==t&&("string"!=typeof s||!t.includes(s.toLowerCase())))return!1;const o=e.tokenName;if(void 0!==n&&("string"!=typeof o||Kt(o)!==n))return!1;const i=e.userAddress;return void 0===r||"string"==typeof i&&rn(i,r)}:void 0}(t);return this.register("EVENT",t=>e(Ld(0,t)),{room:Nd,...void 0!==n&&{filter:n}})}subscribeFeedTokenEvents(e){const t=Id.map(t=>this.register(t,n=>e(function(e,t){return{event:e,data:Ld(0,t)}}(t,n)),{room:bd}));return()=>{for(const e of t)e()}}subscribeToGlobalFeed(e={}){const t=this.registerCallbacks(e,Od,()=>({})),n=this.hold(bd);return()=>{t(),n()}}addCallbacks(e){return this.registerCallbacks(e,Rd,()=>({}))}registerCallbacks(e,t,n){const r=[],s={...e};for(const[e,o]of Object.entries(t)){const t=s[e];"function"==typeof t&&r.push(this.register(o,e=>Reflect.apply(t,void 0,[e]),n(o)))}return()=>{for(const e of r)e()}}async subscribeToStream(e,t={}){const n=Pd(e),r=Ud(n),s=this.epoch;if(await this.connect(),s!==this.epoch||this.disposed)throw new Error("WebSocket disconnected");const o=this.registerCallbacks(t,Rd,e=>{return t=e,Cd.has(t)?{token:n}:function(e){return Dd.has(e)}(e)?{token:n,room:Fd(n)}:{};var t}),i=this.hold(r),a={release:()=>{o(),i()}},c=this.explicitHolds.get(n)??[];c.push(a),this.explicitHolds.set(n,c);try{return await this.waitForRoom(r,n)}catch(e){throw this.dropExplicitHold(n,a),e}}waitForRoom(e,t){return"joined"===this.roomStates.get(e)?.phase?Promise.resolve({room:e,tokenName:t}):new Promise((n,r)=>{const s={resolve:n,reject:r,timer:setTimeout(()=>{this.roomWaiters.get(e)?.delete(s),r(new Error(`Subscription to ${t} timed out after ${this.config.subscriptionTimeout}ms`))},this.config.subscriptionTimeout)},o=this.roomWaiters.get(e)??new Set;o.add(s),this.roomWaiters.set(e,o)})}dropExplicitHold(e,t){t.release();const n=(this.explicitHolds.get(e)??[]).filter(e=>e!==t);0===n.length?this.explicitHolds.delete(e):this.explicitHolds.set(e,n)}unsubscribeFromStream(e){const t=Kt(e),n=this.explicitHolds.get(t);if(void 0!==n){this.explicitHolds.delete(t);for(const e of n)e.release()}else this.logger.debug(`📡 Not subscribed to ${t} through subscribeToStream, skipping unsubscribe`)}subscribeStreamStatus(e,t){return this.subscribeToken("STREAM_STATUS",e,t)}subscribeViewerCount(e,t){return this.subscribeToken("VIEWER_COUNT",e,t)}subscribeRecordingStatus(e,t){return this.subscribeToken("RECORDING_STATUS",e,t)}subscribeRecordingsCountUpdated(e,t){return this.subscribeToken("RECORDINGS_COUNT_UPDATED",e,t)}subscribeSimulcastStatus(e,t){return this.subscribeToken("SIMULCAST_STATUS",e,t)}subscribeDownloadReady(e,t){return this.subscribeToken("DOWNLOAD_READY",e,t)}subscribeCountdownUpdated(e,t){return this.subscribeToken("STREAM_COUNTDOWN_UPDATED",e,t)}subscribeLanguageUpdated(e,t){return this.subscribeToken("STREAM_LANGUAGE_UPDATED",e,t)}subscribeStreamControlStatusChanged(e,t){return this.subscribeToken("STREAM_CONTROL_STATUS_CHANGED",e,t)}subscribeEngagementStatsUpdated(e,t){return this.subscribeToken("ENGAGEMENT_STATS_UPDATED",e,t)}subscribeChatMessages(e,t){return this.subscribeToken("STREAM_CHAT_MESSAGE",e,t)}subscribeChatSent(e,t){return this.subscribeToken("STREAM_CHAT_SENT",e,t)}subscribeChatUpdated(e,t){return this.subscribeToken("STREAM_CHAT_UPDATED",e,t)}subscribeChatDeleted(e,t){return this.subscribeToken("STREAM_CHAT_DELETED",e,t)}subscribeChatPinned(e,t){return this.subscribeToken("STREAM_CHAT_PINNED",e,t)}subscribeChatUnpinned(e,t){return this.subscribeToken("STREAM_CHAT_UNPINNED",e,t)}subscribeChatStatus(e,t){return this.subscribeToken("CHAT_STATUS_CHANGED",e,t)}subscribeChatSlowMode(e,t){return this.subscribeToken("SLOW_MODE_CHANGED",e,t)}subscribeTypingIndicator(e,t){return this.subscribeToken("USER_TYPING",e,t)}subscribeReactions(e,t){return this.subscribeToken("STREAM_REACTION",e,t)}subscribeContentReactionAdded(e,t){return this.subscribeToken("CONTENT_REACTION_ADDED",e,t)}subscribeContentReactionRemoved(e,t){return this.subscribeToken("CONTENT_REACTION_REMOVED",e,t)}subscribeTradeExecuted(e,t){return this.subscribeToken("TRADE_EXECUTED",e,t)}subscribeBalanceUpdated(e,t){return this.subscribeToken("BALANCE_UPDATED",e,t)}subscribeTokenBanned(e,t){return this.subscribeToken("TOKEN_BANNED",e,t)}subscribeTokenUnbanned(e,t){return this.subscribeToken("TOKEN_UNBANNED",e,t)}subscribeModeratorInviteCreated(e,t){return this.subscribeToken("MODERATOR_INVITE_CREATED",e,t)}subscribeModeratorAdded(e,t){return this.subscribeToken("MODERATOR_ADDED",e,t)}subscribeModeratorRemoved(e,t){return this.subscribeToken("MODERATOR_REMOVED",e,t)}subscribeModeratorRoleUpdated(e,t){return this.subscribeToken("MODERATOR_ROLE_UPDATED",e,t)}subscribePoolMetadataUpdated(e,t){return this.subscribeToken("POOL_METADATA_UPDATED",e,t)}subscribePoolSocialLinksUpdated(e,t){return this.subscribeToken("POOL_SOCIAL_LINKS_UPDATED",e,t)}subscribePoolBadgeAssigned(e,t){return this.subscribeToken("POOL_BADGE_ASSIGNED",e,t)}subscribeHolderCountUpdated(e,t){return this.subscribeToken("HOLDER_COUNT_UPDATED",e,t)}subscribeTokenConfigUpdated(e,t){return this.subscribeToken("TOKEN_CONFIG_UPDATED",e,t)}subscribeCommentCreated(e,t){return this.subscribeComment("COMMENT_CREATED",e,t)}subscribeCommentUpdated(e,t){return this.subscribeComment("COMMENT_UPDATED",e,t)}subscribeCommentDeleted(e,t){return this.subscribeComment("COMMENT_DELETED",e,t)}subscribeStatsUpdated(e){return this.subscribeFeed("STATS_UPDATED",e)}subscribePoolCreated(e){return this.subscribeFeed("POOL_CREATED",e)}subscribeStreamGlobalStatus(e){return this.subscribeFeed("STREAM_GLOBAL_STATUS",e)}subscribeChatGlobalStatus(e){return this.subscribeFeed("STREAM_CHAT_GLOBAL_STATUS",e)}subscribeCommentsGlobalStatus(e){return this.subscribeFeed("COMMENTS_GLOBAL_STATUS",e)}subscribeWebhooksGlobalStatus(e){return this.subscribeFeed("WEBHOOKS_GLOBAL_STATUS",e)}subscribeAIModerationGlobalStatus(e){return this.subscribeFeed("AI_MODERATION_GLOBAL_STATUS",e)}subscribeSiteConfigChanged(e){return this.subscribeFeed("SITE_CONFIG_CHANGED",e)}getSiteConfigState(){return{...this.siteConfig}}subscribeOverseerAdded(e){return this.subscribeEvent("OVERSEER_ADDED",e)}subscribeOverseerRemoved(e){return this.subscribeEvent("OVERSEER_REMOVED",e)}subscribeUserProfileUpdated(e){return this.subscribeEvent("USER_PROFILE_UPDATED",e)}subscribeApiKeyCreated(e){return this.subscribeEvent("API_KEY_CREATED",e)}subscribeApiKeyUpdated(e){return this.subscribeEvent("API_KEY_UPDATED",e)}subscribeApiKeyRevoked(e){return this.subscribeEvent("API_KEY_REVOKED",e)}subscribeGlobalTokenBanned(e){return this.subscribeEvent("TOKEN_BANNED",e)}subscribeGlobalTokenUnbanned(e){return this.subscribeEvent("TOKEN_UNBANNED",e)}subscribeGlobalModeratorAdded(e){return this.subscribeEvent("MODERATOR_ADDED",e)}subscribeGlobalModeratorRemoved(e){return this.subscribeEvent("MODERATOR_REMOVED",e)}subscribeGlobalModeratorRoleUpdated(e){return this.subscribeEvent("MODERATOR_ROLE_UPDATED",e)}subscribeGlobalModeratorInviteCreated(e){return this.subscribeEvent("MODERATOR_INVITE_CREATED",e)}subscribeContentFlagged(e){return this.subscribeEvent("CONTENT_FLAGGED",e)}subscribeFlagResolved(e){return this.subscribeEvent("FLAG_RESOLVED",e)}subscribeAIModerationComplete(e){return this.subscribeEvent("AI_MODERATION_COMPLETE",e)}subscribeAIModerationFailed(e){return this.subscribeEvent("AI_MODERATION_FAILED",e)}subscribeUserBanned(e){return this.subscribeEvent("USER_BANNED",e)}subscribeUserUnbanned(e){return this.subscribeEvent("USER_UNBANNED",e)}subscribeBanEnforcement(e){return this.subscribeEvent("BAN_ENFORCEMENT",e)}subscribeTradeUpdateNotify(e){return this.subscribeEvent("TRADE_UPDATE_NOTIFY",e)}subscribeReactionErrors(e){return this.subscribeEvent("stream_reaction_error",e)}subscribeChatErrors(e){return this.subscribeEvent("stream_chat_error",e)}subscribeException(e){return this.subscribeEvent("exception",e)}getSubscribedTokens(){const e=[];for(const t of this.roomRefs.keys())t.startsWith(Sd)&&e.push(t.slice(Sd.length));return e}isSubscribedToGlobalFeed(){return(this.roomRefs.get(bd)??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 Gd(e){if(!Md(e))return;const t=e.enabled;return"boolean"==typeof t?t:void 0}function $d(e){return null==e||""===e||"string"==typeof e&&(!$n(e)&&e.length<=or.BAN_REASON.MAX_LENGTH)}function Kd(e){if(Fn(e.tokenName,"tokenName",Xn),!$d(e.reason))throw new rt(`reason must be at most ${or.BAN_REASON.MAX_LENGTH} characters`,"reason","TOO_LONG")}function Hd(e){Fn(e.tokenName,"tokenName",Jn)}function Wd(e){Mn(0,void 0,tr,e.pageSize)}function Vd(e){Fn(e.tokenName,"tokenName",Jn)}class jd extends ci{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async banToken(e){Kd(e);const t=ye,n={tokenName:Kt(e.tokenName)};if(void 0!==e.reason)try{In(e.reason,"reason",!0),e.reason.trim().length>0&&(n.reason=e.reason)}catch{}const r=await this.http.post(t,n,this.getDualAuthHeaders());return{ban:this.extractData(r),tokenName:Kt(e.tokenName)}}async unbanToken(e){Hd(e);const t=this.buildEndpoint(ke,{tokenName:e.tokenName});return Mt(await this.http.delete(t,void 0,this.getDualAuthHeaders()),"Failed to unban token",!1),{tokenName:Kt(e.tokenName)}}async listTokenBans(e={}){Wd(e);const t=be,n=this.buildPaginationParams(e,tr);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){Vd(e);const t=this.buildEndpoint(Ne,{tokenName:e.tokenName}),n=await this.http.get(t,{},this.getDualAuthHeaders()),r=this.extractDataOrNull(n);return{banned:null!==r,...null!==r&&{ban:r},tokenName:Kt(e.tokenName)}}async isTokenBanned(e){return this.getTokenBan(e)}}class qd extends qn{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(!Rn(e))throw Tt("tokenName","Token name");const t=Kt(e),n=this.getCacheEntry(t);if(null!==n)return this.cacheHits++,this.updateAccessOrder(t),n.vaultAddress;this.cacheMisses++;const r=await this.poolService.resolveTokenNameToVault(e);if(null!==r&&""!==r){const e=this.parseVaultAddressToTokenClassKey(r);this.setCacheEntry(t,{vaultAddress:r,tokenClassKey:e,cachedAt:Date.now()})}return r}async resolveTokenClassKey(e){if(!Rn(e))throw Tt("tokenName","Token name");const t=Kt(e),n=this.getCacheEntry(t);if(null!==n)return this.cacheHits++,this.updateAccessOrder(t),n.tokenClassKey;this.cacheMisses++;const r=await this.poolService.resolveTokenNameToVault(e);if(null===r||""===r)throw At(e);const s=this.parseVaultAddressToTokenClassKey(r);return this.setCacheEntry(t,{vaultAddress:r,tokenClassKey:s,cachedAt:Date.now()}),s}get(e){const t=this.getCacheEntry(Kt(e));return t?.vaultAddress??null}getCacheEntry(e){return this.cache.get(e)??null}setCacheEntry(e,t){this.cache.size>=qd.MAX_CACHE_SIZE&&!this.cache.has(e)&&this.evictOldestEntry(),this.cache.set(e,t),this.updateAccessOrder(e)}updateAccessOrder(e){this.accessOrder.delete(e),this.accessOrder.add(e)}evictOldestEntry(){const e=this.accessOrder.values().next().value;void 0!==e&&""!==e&&(this.cache.delete(e),this.accessOrder.delete(e))}set(e,t){const n=Kt(e),r=this.parseVaultAddressToTokenClassKey(t);this.setCacheEntry(n,{vaultAddress:t,tokenClassKey:r,cachedAt:Date.now()})}clear(){this.cache.clear(),this.accessOrder=new Set,this.cacheHits=0,this.cacheMisses=0}getStats(){const e=Array.from(this.cache.values()).map(e=>e.cachedAt),t=this.cacheHits+this.cacheMisses;return{size:this.cache.size,keys:Array.from(this.cache.keys()),maxSize:qd.MAX_CACHE_SIZE,hits:this.cacheHits,misses:this.cacheMisses,hitRate:t>0?this.cacheHits/t:0,oldestEntry:e.length>0?Math.min(...e):null,newestEntry:e.length>0?Math.max(...e):null}}getCachedTokenClassKey(e){const t=this.getCacheEntry(Kt(e));return t?.tokenClassKey??null}preWarm(e){for(const{tokenName:t,vaultAddress:n}of e)this.set(t,n)}preWarmWithTokenClassKey(e){for(const{tokenName:t,vaultAddress:n,tokenClassKey:r}of e){const e=Kt(t);this.setCacheEntry(e,{vaultAddress:n,tokenClassKey:r,cachedAt:Date.now()})}}parseVaultAddressToTokenClassKey(e){try{return oa(e)}catch(e){if(e instanceof rt)throw vt("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad","Vault address");throw e}}}qd.MAX_CACHE_SIZE=1e4;class zd extends jn{constructor(e,t=!1){super(e,t)}async fetchLaunchpadFee(){const e=await Ft(()=>this.http.get($e),{errorContext:"Failed to fetch launchpad fee"});if("number"!=typeof e.feeAmount||!Number.isFinite(e.feeAmount))throw new rt("Failed to fetch launchpad fee: no feeAmount in the response","feeAmount","INVALID_RESPONSE");return e.feeAmount}async fetchSaleDetails(e){return Ft(()=>this.http.get(Ke,{tokenName:e}),{errorContext:`Failed to fetch sale details for ${e}`})}async getTradeQuote(e){const t={tokenName:e.tokenName,amount:e.amount,type:e.type,method:e.method},{signal:n}=e;return _o(await Ft(()=>void 0===n?this.http.get(He,t):this.http.request({method:"GET",url:He,params:t,signal:n}),{errorContext:`Failed to get trade quote for ${e.tokenName}`}),`trade quote for ${e.tokenName}`)}async getPremintQuote(e){return _o(await Ft(()=>this.http.get(We,{amount:e}),{errorContext:"Failed to get premint quote"}),"premint quote")}}class Yd extends ci{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async emitTradeExecuted(e,t){this.validateTokenName(e,er);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,er);const r={action:"balance_updated",userAddress:en(e,"userAddress"),tokenName:t,payload:n};await this.emitEvent(r)}async emitStreamStatus(e,t,n=!0){this.validateTokenName(e,er);const r={action:"stream_status",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitViewerCount(e,t,n=!1){this.validateTokenName(e,er);const r={action:"viewer_count",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitStreamCountdown(e,t,n=!0){this.validateTokenName(e,er);const r={action:"stream_countdown",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitChatMessage(e,t,n=!1){this.validateTokenName(e,er);const r={action:"chat_message",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitChatStatus(e,t,n=!1){this.validateTokenName(e,er);const r={action:"chat_status",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitTypingIndicator(e,t,n=!1){this.validateTokenName(e,er);const r={action:"typing_indicator",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitTokenBanned(e,t){this.validateTokenName(e,er);const n={action:"token_banned",tokenName:e,payload:t,broadcast:!0};await this.emitEvent(n)}async emitTokenUnbanned(e,t){this.validateTokenName(e,er);const n={action:"token_unbanned",tokenName:e,payload:t,broadcast:!0};await this.emitEvent(n)}async emitModeratorAdded(e,t,n=!1){this.validateTokenName(e,er);const r={action:"moderator_added",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitModeratorRemoved(e,t,n=!1){this.validateTokenName(e,er);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:en(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=Zt(e.userAddress,"userAddress")),void 0!==e?.userAddresses&&(n.userAddresses=e.userAddresses.split(",").map(e=>Zt(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 ct("userAddresses must be a non-empty array");const t=await this.getConnectedClients({userAddresses:e.join(","),limit:e.length}),n=t.clients.filter(e=>"string"==typeof e.address&&""!==e.address).map(e=>e.address);return{online:n,offline:e.filter(e=>!n.some(t=>rn(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,er);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,er);const n={action:"recording_status",tokenName:e,payload:t};await this.emitEvent(n)}async emitRecordingsCountUpdated(e,t){this.validateTokenName(e,er);const n={action:"recordings_count_updated",tokenName:e,payload:t};await this.emitEvent(n)}async emitDownloadReady(e,t){this.validateTokenName(e,er);const n={action:"download_ready",tokenName:e,payload:t};await this.emitEvent(n)}}class Xd{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 Qd{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 Jd extends qn{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 Xd({maxAttempts:this.config.reconnectAttempts??5,baseDelayMs:this.config.reconnectDelay??2e3}),this.eventBuffer=new Qd(3e4),this.isSocketIOAvailable=this.checkSocketIOAvailability(),Jd.instances.add(this)}checkSocketIOAvailability(){try{return"function"==typeof i.io||(this.logger.warn('⚠️ Socket.IO client not available. Install "socket.io-client" package.'),!1)}catch(e){return this.logger.warn("⚠️ Socket.IO availability check failed:",e),!1}}async connect(){return new Promise((e,t)=>{$o(async()=>{if(!this.isSocketIOAvailable){const e=new Error('Socket.IO not available in current environment. Install "socket.io-client" package.');throw this.logger.error("❌ Socket.IO connection failed:",ut(e)),e}this.logger.debug("🔌 Connecting to Socket.IO server:",this.config.url),this.socket=i.io(this.config.url,{transports:["websocket"],reconnection:!0,reconnectionAttempts:this.config.reconnectAttempts??5,reconnectionDelay:this.config.reconnectDelay??2e3}),this.socket.on("connect",()=>{this.logger.debug("✅ Socket.IO connected successfully:",this.socket?.id),this.logger.debug("📡 Connected to bundle backend WebSocket:",this.config.url),this.logger.debug("🔗 Ready to monitor transaction updates"),this.reconnectionManager.reset(),e()}),this.socket.on("connect_error",e=>{this.logger.error("❌ Socket.IO connection error:",e),t(e)}),this.socket.on("disconnect",e=>{this.logger.debug(`🔌 Socket.IO disconnected: ${e}`),this.handleReconnect()}),this.socket.on("error",e=>{this.logger.error("❌ Socket.IO error:",e)}),this.socket.onAny((e,...t)=>{if(""!==e&&t.length>0&&"object"==typeof t[0]&&null!==t[0]){const n=t[0],r=n.status??n.Status;"string"==typeof r&&(this.logger.debug(`📡 [Event Buffer] Buffering event for ${e}: ${r}`),this.eventBuffer.size>=this.MAX_BUFFER_SIZE&&this.logger.warn(`📡 [Event Buffer] Buffer approaching limit (${this.eventBuffer.size}/${this.MAX_BUFFER_SIZE})`),this.eventBuffer.set(e,n))}this.debug&&this.logger.debug(`📡 [WebSocket Event] "${e}":`,JSON.stringify(t,null,2))}),this.hasOnAnyListener=!0},"Socket.IO connection failed",this.logger,e=>{this.logger.error("Socket.IO connection failed:",e);const n=dt(e)?e:new Error(ut(e));throw t(n),n}).catch(t)})}async monitorTransaction(e,t){this.listeners.set(e,t),this.logger.debug(`📡 Starting to monitor transaction: ${e}`),this.logger.debug(`📡 WebSocket connected: ${String(this.socket?.connected??!1)}`);const n=this.eventBuffer.get(e);null!=n&&(this.logger.debug(`📡 [Event Buffer] Found buffered event for ${e}, delivering immediately`),setImmediate(()=>{this.processTransactionEvent(e,n,t)}),this.eventBuffer.delete(e));const r=this.config.timeout??3e5,s=setTimeout(()=>{if(this.listeners.has(e)){const n=Math.round(r/1e3),s={transactionId:e,status:exports.SDKTransactionStatus.TIMEOUT,message:`Transaction monitoring timeout - no response after ${n} seconds`,timestamp:Date.now()};this.logger.debug(`📡 Transaction timeout for ${e} (${n}s)`),t(s),this.listeners.delete(e),this.timeouts.delete(e),this.socket?.off(e)}},r);if(this.timeouts.set(e,s),this.socket?.connected)this.socket.off(e),this.logger.debug(`📡 Listening for transaction updates: ${e}`),this.logger.debug(`📡 WebSocket connection ID: ${String(this.socket.id)}`),this.logger.debug(`📡 WebSocket URL: ${this.config.url}`),this.socket.on(e,n=>{this.processTransactionEvent(e,n,t)});else{const n={transactionId:e,status:exports.SDKTransactionStatus.FAILED,message:"WebSocket not connected - cannot monitor transaction",timestamp:Date.now()};t(n),this.listeners.delete(e),this.timeouts.delete(e)}await Promise.resolve()}processTransactionEvent(e,t,n){this.logger.debug(`📡 Socket.IO transaction update for ${e}:`,JSON.stringify(t,null,2));const r=t,s=r?.data,o=r?.status??r?.Status??s?.status??s?.Status;let i=r?.message??r?.Message??s?.message??s?.Message??r?.error??s?.error;Rn(i)||(i=o===qo.FAILED||o===qo.ERROR?"Transaction failed - check transaction details":o===qo.COMPLETED||o===qo.PROCESSED||o===qo.SUCCESS?"Transaction completed successfully":null!=o?`Transaction status: ${String(o)}`:"Unknown transaction status");const a=r?.blockHash??s?.blockHash,c=r?.gasUsed??s?.gasUsed,l=r?.Data??s?.Data,d={transactionId:e,status:this.mapSocketStatus(o),message:"string"==typeof i?i:"Transaction update received",timestamp:Date.now(),...null!=a?{blockHash:a}:{},...null!=c?{gasUsed:c}:{},...null!=l?{data:l}:{}};if(this.logger.debug(`📡 Mapped status for ${e}: ${String(o)} -> ${d.status}`),this.logger.debug(`📡 Final message: "${String(i)}"`),n(d),d.status===exports.SDKTransactionStatus.COMPLETED||d.status===exports.SDKTransactionStatus.FAILED){this.listeners.delete(e);const t=this.timeouts.get(e);t&&(clearTimeout(t),this.timeouts.delete(e)),this.socket?.off(e),this.logger.debug(`📡 Cleaned up listener for ${e} (${d.status})`)}}async waitForTransaction(e){return new Promise((t,n)=>{this.monitorTransaction(e,e=>{e.status===exports.SDKTransactionStatus.COMPLETED?t(e):e.status!==exports.SDKTransactionStatus.FAILED&&e.status!==exports.SDKTransactionStatus.TIMEOUT||n(new Error(`Transaction ${String(e.status)}: ${e.message}`))})})}mapSocketStatus(e){const t=e?.toUpperCase();return Yo[t]??exports.SDKTransactionStatus.PENDING}async handleReconnect(){this.reconnectionManager.shouldRetry()?(this.reconnectionManager.recordAttempt(),this.logger.debug(`🔄 Attempting Socket.IO reconnect ${this.reconnectionManager.getStatusString()}`),setTimeout(()=>{this.socket&&!this.socket.connected&&this.socket.connect()},this.reconnectionManager.getNextDelay())):this.logger.error("❌ Socket.IO max reconnection attempts reached")}disconnect(){this.socket&&(this.listeners.forEach((e,t)=>{this.socket?.off(t)}),this.listeners.clear(),this.timeouts.forEach(e=>{clearTimeout(e)}),this.timeouts.clear(),this.eventBuffer.clear(),this.logger.debug("🧹 Cleared event buffer"),this.hasOnAnyListener&&(this.socket.offAny(),this.hasOnAnyListener=!1,this.logger.debug("🧹 Removed onAny debug listener")),this.socket.disconnect(),this.socket=null,this.logger.debug("🔌 Socket.IO disconnected")),Jd.instances.delete(this)}static cleanupAll(e=!1){for(const e of Jd.instances)e.disconnect();Jd.instances.clear()}isConnected(){return this.socket?.connected??!1}getSocket(){return this.socket}}Jd.instances=new Set;class Zd extends jn{constructor(e,t=!1){super(e,t)}extractData(e){if(e.error||void 0===e.data){const t=e.message??"Weekly challenge operation failed";throw new Error(t)}return e.data}async getLeaderboard(e={}){const{limit:t=10}=e;if(t<1||t>50)throw new rt("limit must be between 1 and 50","limit","INVALID_LIMIT");this.logger.debug("Fetching weekly challenge leaderboard",{limit:t});const n={limit:String(t)},r=await this.http.get(Ve.GET_LEADERBOARD,n),s=this.extractData(r);return this.logger.debug("Fetched weekly challenge leaderboard",{count:s.count}),{leaderboard:s}}async getTokenHistory(e){const{vaultAddress:t}=e;if("string"!=typeof t||""===t.trim())throw new rt("vaultAddress is required","vaultAddress","REQUIRED_FIELD");this.logger.debug("Fetching token weekly history",{vaultAddress:t});const n=Ve.GET_TOKEN_HISTORY.replace(":vaultAddress",encodeURIComponent(t)),r=await this.http.get(n),s=this.extractData(r);return this.logger.debug("Fetched token weekly history",{count:s.length}),{snapshots:s}}}const eu=["CreateSale","BuyWithNative","BuyExactToken","SellWithNative","SellExactToken"];class tu{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 nu{constructor(e){this.bundleBaseUrl=hu(e.bundleBaseUrl),this.launchpadBaseUrl=hu(e.launchpadBaseUrl),this.signer=e.signer,this.walletAddress=""===e.walletAddress?"":Zt(e.walletAddress,"walletAddress"),this.requestor=e.httpRequestor??fetch.bind(globalThis),this.socketFactory=e.socketFactory??(e=>i.io(e,{transports:["websocket"]})),this.bundleSocketFactory=e.bundleSocketFactory}attach(e){const{bundleId:t,method:n,uniqueKey:r,tokenName:s}=e;if("string"!=typeof t||""===t)throw su("bundleId");if(o=n,!eu.some(e=>e===o))throw su("method");var o;if("string"!=typeof r||""===r)throw su("uniqueKey");if(void 0!==s&&("string"!=typeof s||""===s))throw su("tokenName");if("CreateSale"===n&&void 0===s)throw su("tokenName");const i={method:n,dto:{uniqueKey:r,...void 0===s?{}:{tokenName:s}},stringsInstructions:[]};return new tu({bundleId:t,uniqueKey:r,method:n,wait:e=>this.waitForResult(i,t,e)})}async submit(t){let n;try{n=await this.signer.signTypedData(t.method,t.dto)}catch(t){throw function(t){if(t instanceof Hi)return t;if(e.isWalletUserRejection(t)){const n=t instanceof Error?t.message:"The signature was rejected in the wallet.",r=e.walletDeclineCode(t);return new Hi(n,"WALLET_USER_REJECTED",{details:void 0===r?{}:{walletCode:r}})}const n=t instanceof Error?t.message:"Launchpad signing failed.";return new Hi(n,"LAUNCHPAD_SIGNING_FAILED",{chainMessage:n})}(t)}const r=function(e){return Object.fromEntries(Object.entries(e).filter(([e])=>"prefix"!==e))}(n),s=`${this.bundleBaseUrl}/bundle`,o=await this.requestor(s,{method:"POST",headers:{"content-type":"application/json","X-Wallet-Address":this.walletAddress},body:JSON.stringify({stringsInstructions:t.stringsInstructions,method:t.method,signedDto:r})}),i=await du(o);if(!o.ok)throw iu(o.status,i,s);const a=function(e){if("string"==typeof e&&""!==e)return e;if(!uu(e))throw new Hi("Bundler returned no bundle id.","INVALID_BUNDLE_RESPONSE");const t=e.data,n=e.bundleId;if("string"==typeof t&&""!==t)return t;if(uu(t)&&"string"==typeof t.bundleId&&""!==t.bundleId)return t.bundleId;if("string"==typeof n&&""!==n)return n;throw new Hi("Bundler returned no bundle id.","INVALID_BUNDLE_RESPONSE")}(i),c=lu(t.dto,"uniqueKey");return new tu({bundleId:a,uniqueKey:c,method:t.method,wait:e=>this.waitForResult(t,a,e)})}waitForResult(e,t,n={}){const r=n.timeoutMs??6e4,s=n.pollIntervalMs??2500,o=n.signal;return new Promise((n,i)=>{const a=this.confirmationUrl(e,t);if(!0===o?.aborted)return void i(ru(e.method,t));const c=Date.now(),l=new AbortController,d=void 0===this.bundleSocketFactory;let u,h,g,p=!1;const m=()=>{f(()=>i(ru(e.method,t)))},f=e=>{p||(p=!0,clearTimeout(A),o?.removeEventListener("abort",m),l.abort(),void 0!==u&&(void 0!==h&&u.off(t,h),d&&u.disconnect()),e())},E=()=>{f(()=>i(function(e,t){const n="string"==typeof e.dto.uniqueKey?e.dto.uniqueKey:"";return new Hi(`Timed out waiting for bundle ${n}`,"BUNDLE_CONFIRMATION_TIMEOUT",{details:{method:e.method,...void 0===t?{}:{lastReadFailure:{message:t.message,...void 0===t.status?{}:{status:t.status}}}}})}(e,g)))};o?.addEventListener("abort",m,{once:!0});const A=setTimeout(E,r);try{u=(this.bundleSocketFactory??this.socketFactory)(this.bundleBaseUrl),h=e=>{const t=function(e){if(!uu(e))return;const t=e.status;return"PROCESSED"!==t&&"FAILED"!==t?void 0:{status:t,data:e.data}}(e);void 0!==t&&f(()=>{"FAILED"===t.status?i(ou(t.data)):n(t)})},u.on(t,h)}catch{u=void 0,h=void 0}this.pollConfirmation({request:e,confirmationUrl:a,startedAt:c,timeoutMs:r,pollIntervalMs:s,signal:l.signal,onReadFailure:e=>{g=e}}).then(e=>{void 0===e?E():f(()=>n(e))},e=>f(()=>i(e instanceof Error?e:new Error(String(e)))))})}confirmationUrl(e,t){return"CreateSale"===e.method?function(e,t){const n=lu(t,"tokenName");return`${e}/v1/tokens/${encodeURIComponent(n)}`}(this.launchpadBaseUrl,e.dto):`${this.bundleBaseUrl}/bundle?id=${encodeURIComponent(t)}`}async pollConfirmation(e){const{request:t,confirmationUrl:n,startedAt:r,timeoutMs:s,pollIntervalMs:o,signal:i,onReadFailure:a}=e;for(;!i.aborted&&Date.now()-r<=s;){const e=await this.readConfirmation(t,n,i);if(i.aborted)return;if("processed"===e.kind)return e.result;if("failed"===e.kind)throw ou(e.data);a("read-failed"===e.kind?e.error:void 0);const c=s-(Date.now()-r);if(c<=0)break;await gu(Math.min(Math.max(0,o),c),i)}}async readConfirmation(e,t,n){try{const r=await this.requestor(t,{method:"GET",signal:n}),s=await du(r);if("CreateSale"===e.method)return r.ok?{kind:"processed",result:{status:"PROCESSED",data:cu(s)}}:404===r.status||202===r.status?{kind:"pending"}:{kind:"read-failed",error:iu(r.status,s,t)};if(!r.ok)return{kind:"read-failed",error:iu(r.status,s,t)};const o=uu(s)?s.status:void 0;return"COMPLETED"===o||"PROCESSED"===o?{kind:"processed",result:{status:"PROCESSED",data:s}}:"FAILED"===o?{kind:"failed",data:s}:{kind:"pending"}}catch(e){const n=e instanceof Error?e.message:"The bundle confirmation read failed.";return{kind:"read-failed",error:new Hi(n,"BUNDLE_REQUEST_FAILED",{details:{url:t}})}}}}function ru(e,t){return new Hi("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 su(e){return new Hi(`Cannot attach to a launchpad bundle: ${e} is missing or not accepted.`,"INVALID_BUNDLE_ATTACHMENT",{details:{field:e}})}function ou(e){const t=au(e)??"Launchpad bundle failed on chain.";return new Hi(t,"BUNDLE_FAILED",{chainMessage:t})}function iu(e,t,n){const r=au(t)??`Bundle request failed with HTTP ${e}`;return new Hi(r,"BUNDLE_REQUEST_FAILED",{status:e,chainMessage:r,details:{body:t,url:n}})}function au(e){if("string"==typeof e&&""!==e)return e;if(uu(e))for(const t of["chainMessage","message","Message","error"]){const n=e[t];if("string"==typeof n&&""!==n)return n;if(uu(n)){const e=au(n);if(void 0!==e)return e}}}function cu(e){return uu(e)?e.data??e.Data??e:e}function lu(e,t){const n=e[t];if("string"!=typeof n||""===n)throw new Hi(`Missing ${t} in launchpad DTO.`,"INVALID_LAUNCHPAD_DTO");return n}async function du(e){try{return await e.json()}catch{return e.text()}}function uu(e){return"object"==typeof e&&null!==e}function hu(e){return e.replace(/\/$/u,"")}function gu(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 pu(e,t){if(!/^\d+(\.\d+)?$/.test(e))throw new rt(`Quoted reverse bonding curve fee is not a non-negative number: ${e}`,"extraFees","INVALID_QUOTED_FEE");if(!Number.isFinite(t)||t<0)throw new rt(`Fee slippage factor must be a non-negative number, got ${String(t)}`,"maxAcceptableReverseBondingCurveFeeSlippageFactor","INVALID_FEE_SLIPPAGE_FACTOR");return new a(e).multipliedBy(new a(1).plus(new a(String(t)))).decimalPlaces(8,a.ROUND_UP).toFixed()}function mu(e){return async t=>{const n=t.tokenName??await async function(e,t){const n=ea(t).type,r=await e.findTokenNameByVault(t,n);if(void 0===r)throw new rt(`Could not find the launchpad token for vault ${t}, so the reverse bonding curve fee ceiling cannot be quoted. Pass tokenName, or pass extraFees.maxAcceptableReverseBondingCurveFee explicitly.`,"tokenName","TOKEN_NOT_FOUND_FOR_VAULT");return r}(e,t.vaultAddress);return pu((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 fu={minFeePortion:"0.1",maxFeePortion:"0.5"},Eu=/^(?:\d+\.?\d*|\.\d+)$/u,Au=/^[0-9A-Z]+$/u,Tu=/^[A-Za-z0-9]+$/u,vu=new a("0.1"),Su=new a("0.5");function yu(e){if("string"!=typeof e||!Eu.test(e))return;const t=new a(e);return t.isFinite()?t.toFixed():void 0}function bu(e){return"string"==typeof e&&""!==e}function Nu(e,t,n){void 0!==n&&"string"!=typeof n&&e.push(`${t} must be a string`)}function ku(e,t,n){void 0===n||bu(n)||e.push(`${t} must be a non-empty string`)}function wu(e){const t=[];if("object"!=typeof e||null===e)throw new rt("CreateSale input must be an object","data","VALIDATION_ERROR");const n={...e},r=n.tokenName;bu(r)?Tu.test(r)||t.push("Token name can only contain letters and numbers"):t.push("Token name is required");const s=n.tokenSymbol;bu(s)?Au.test(s.toUpperCase())||t.push("Token symbol can only contain letters and numbers"):t.push("Token symbol is required");const o=n.tokenDescription;bu(o)?o.length>1e3&&t.push("Token description must be at most 1000 characters"):t.push("Token description is required");const i=n.tokenImage;bu(i)?i.length>500&&t.push("Token image must be at most 500 characters"):t.push("Token image is required");const c=n.preBuyQuantity;void 0!==c&&void 0===yu(c)&&t.push("preBuyQuantity must be a non-negative decimal number");for(const e of["websiteUrl","telegramUrl","twitterUrl","instagramUrl","facebookUrl","redditUrl","tiktokUrl"])Nu(t,e,n[e]);ku(t,"tokenCategory",n.tokenCategory),ku(t,"tokenCollection",n.tokenCollection);const l=n.saleStartTime;if(void 0===l||Number.isInteger(l)||t.push("saleStartTime must be an integer"),function(e,t){if(void 0!==t&&("object"!=typeof t||null===t))return void e.push("reverseBondingCurveConfiguration must be an object");const n=t??{},r=n.minFeePortion??fu.minFeePortion,s=n.maxFeePortion??fu.maxFeePortion,o=yu(r),i=yu(s);if(void 0===o&&e.push("minFeePortion must be a decimal number"),void 0===i&&e.push("maxFeePortion must be a decimal number"),void 0===o||void 0===i)return;const c=new a(o),l=new a(i);c.isLessThan(vu)&&e.push("minFeePortion must be greater than or equal to 0.1"),l.isGreaterThan(Su)&&e.push("maxFeePortion must be less than or equal to 0.5"),c.isGreaterThan(l)&&e.push("minFeePortion must be less than or equal to maxFeePortion")}(t,n.reverseBondingCurveConfiguration),t.length>0)throw new rt(t.join("; "),"data","VALIDATION_ERROR")}class _u{constructor(e){this.transport=e.transport,this.walletAddress=""===e.walletAddress?"":Zt(e.walletAddress,"walletAddress"),this.sellFeeCeiling=e.sellFeeCeiling}createSale(e){wu(e);const t=function(e,t){const n={tokenName:e.tokenName,tokenSymbol:e.tokenSymbol,tokenDescription:e.tokenDescription,tokenImage:e.tokenImage,preBuyQuantity:yu(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??Iu(t)},r=e.reverseBondingCurveConfiguration;n.reverseBondingCurveConfiguration={minFeePortion:yu(r?.minFeePortion??fu.minFeePortion),maxFeePortion:yu(r?.maxFeePortion??fu.maxFeePortion)},void 0!==e.saleStartTime&&(n.saleStartTime=e.saleStartTime);return n}(e,this.walletAddress);return this.transport.submit({method:"CreateSale",dto:t,stringsInstructions:na(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??Iu(this.walletAddress)};return this.transport.submit({method:e,dto:r,stringsInstructions:ta(t.vaultAddress)})}async defaultExtraFees(e,t){if("BuyWithNative"===e||"BuyExactToken"===e)return{maxAcceptableReverseBondingCurveFee:"0"};if(void 0===this.sellFeeCeiling)throw new rt("A sell needs a reverse bonding curve fee ceiling and no quote source is configured: pass extraFees.maxAcceptableReverseBondingCurveFee.","extraFees","FEE_CEILING_REQUIRED");return{maxAcceptableReverseBondingCurveFee:await this.sellFeeCeiling({method:e,vaultAddress:t.vaultAddress,quantity:t.quantity,...void 0===t.tokenName?{}:{tokenName:t.tokenName}})}}}function Iu(e){return`galaswap-operation-${o.v4()}-${Date.now()}-${e}`}function Cu(e,t=3e4){return c.create({baseURL:e,timeout:t,headers:{"Content-Type":"application/json"}})}const Du=new Set(["accesstoken","refreshtoken","token","password","privatekey","secret","apikey","api_key","rawkey","authorization","x-api-key","bearer","streamadminapikey","userapikey","signature","signedpayload"]);function Ru(e,t=0){if(t>5)return"[...]";if(null==e)return e;if(Array.isArray(e))return e.map(e=>Ru(e,t+1));if(e instanceof Map){const n={};for(const[r,s]of e.entries()){const e=String(r);n[e]=Du.has(e.toLowerCase())?"[REDACTED]":Ru(s,t+1)}return n}if("object"==typeof e){const n={};for(const[r,s]of Object.entries(e))n[r]=Du.has(r.toLowerCase())?"[REDACTED]":Ru(s,t+1);return n}return e}class Ou{constructor(e,t={},n={signRequests:!0}){this.auth=e,this.signRequests=n.signRequests,this.session=n.session,this.debug=t.debug??!1,this.logger=new Vt({debug:this.debug,context:"HttpClient"});const r=t.baseUrl??jo("stage").launchpadBaseUrl,s=t.timeout??6e4;this.axios=Cu(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 $o(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]":Ru(e.data);this.logger.debug("Request:",{method:e.method,url:e.url?.split("?")[0],baseURL:this.axios.defaults.baseURL,params:Ru(r.params),data:s,isFormData:e.data instanceof FormData,contentType:r.headers?.["Content-Type"]??"not set"});const o=await this.sendWithSession(e,r,t,n),i=function(e){const t={};if(null==e||"object"!=typeof e)return t;for(const[n,r]of Object.entries(e))"string"==typeof r?t[n.toLowerCase()]=r:"number"!=typeof r&&"boolean"!=typeof r||(t[n.toLowerCase()]=String(r));return t}(o.headers);return this.logger.debug("Response:",{status:o.status,data:Ru(o.data),transactionId:i["x-transaction-id"],blockNumber:i["x-block-number"]}),{data:o.data,headers:i,status:o.status}},`HTTP ${e.method} ${e.url}`,this.logger)}toAxiosConfig(e,t){const n=null===t?e.headers:{...e.headers,Authorization:`Bearer ${t}`},r={method:e.method,url:e.url,data:e.data,...void 0!==e.params&&{params:Lc(e.params)},...void 0!==n&&{headers:{...n}},...void 0!==e.timeout&&{timeout:e.timeout},...void 0!==e.signal&&{signal:e.signal}};if(e.data instanceof FormData){const e=new c.AxiosHeaders(n);e.set("Content-Type",void 0),r.headers=e,this.logger.debug("FormData detected - clearing the JSON Content-Type default for the multipart upload")}return r}async sendWithSession(e,t,n,r){try{return await this.axios.request(t)}catch(t){if(!n||void 0===this.session||!function(e){if("object"!=typeof e||null===e||!("response"in e))return!1;const t=e.response;return"object"==typeof t&&null!==t&&"status"in t&&401===t.status}(t))throw t;const s=await this.session.onUnauthorized(r);if(null===s)throw t;return this.logger.debug("Retrying once with the refreshed session token"),await this.axios.request(this.toAxiosConfig(e,s))}}async get(e,t,n){return this.request({method:"GET",url:e,...t&&{params:t},...n&&{headers:n}})}async post(e,t,n){return this.request({method:"POST",url:e,data:t,...n&&{headers:n}})}async postWithMeta(e,t,n){return this.requestWithMeta({method:"POST",url:e,data:t,...n&&{headers:n}})}async put(e,t,n){return this.request({method:"PUT",url:e,data:t,...n&&{headers:n}})}async delete(e,t,n){return this.request({method:"DELETE",url:e,...t&&{params:t},...n&&{headers:n}})}async patch(e,t,n){return this.request({method:"PATCH",url:e,data:t,...n&&{headers:n}})}getAddress(){return this.auth.getAddress()}getEthereumAddress(){return this.auth.getEthereumAddress()}async signMessage(e){return(await this.auth.signMessage(e)).signature}async signTypedData(e,t,n){return await this.auth.signTypedData(e,t,n)}async signCustomMessage(e){return $o(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 xu extends Error{constructor(e,t){super(e),this.cause=t,this.name="WebSocketError"}}class Mu 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 Lu(e,t){if(xn(e))throw new xu(`Invalid WebSocket response received for transaction ${t}: response is null or undefined`);if("object"!=typeof e)throw new xu(`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 xu(`Invalid WebSocket response received for transaction ${t}: missing status field`)}function Uu(e,t,n,r){Lu(e,t);const s=e,o=s.data??{};if(!function(e){if(xn(e)||"object"!=typeof e)return!1;const t=e;return!(void 0!==t.inputQuantity&&"string"!=typeof t.inputQuantity||void 0!==t.outputQuantity&&"string"!=typeof t.outputQuantity||void 0!==t.totalFees&&"string"!=typeof t.totalFees||void 0!==t.vaultAddress&&"string"!=typeof t.vaultAddress)}(o))throw new xu(`Invalid trade data received for transaction ${t}`);const i={transactionId:t,type:n,method:"native"===r.type?"native":"exact",inputAmount:o.inputQuantity??r.amount,outputAmount:o.outputQuantity??r.expectedAmount??"0",totalFees:o.totalFees??"0",tokenName:r.tokenName,vaultAddress:o.vaultAddress??"",timestamp:Date.now()};return void 0!==s.blockHash&&(i.blockHash=s.blockHash),void 0!==s.gasUsed&&(i.gasUsed=s.gasUsed),void 0!==r.slippageToleranceFactor&&(i.slippageTolerance=r.slippageToleranceFactor),i}function Fu(e){return void 0!==e&&r.isPrivateKeyProvider(e)?new t.Wallet(e.exportPrivateKey()):void 0}const Pu={MUSIC:"$MUSIC",GMUSIC:"$GMUSIC"};function Bu(e){if(void 0===e||!("walletAddress"in e))return;const t=e.walletAddress;return"string"==typeof t&&""!==t?t:void 0}const Gu=/^(?:eth\||0x)([0-9a-fA-F]{40})$/;function $u(e,t,n){if(void 0===e||void 0===t)return;const r=Gu.exec(e)?.[1],s=Gu.exec(t)?.[1];if(void 0!==r&&void 0!==s&&r.toLowerCase()!==s.toLowerCase())throw yt(`${n} ${t} is not the identity of the configured signing key (${e}); writes would be signed as the key, not as ${n}.`,n)}class Ku{constructor(e){let t,n;this.walletGeneration=0,e.walletProvider?(t=e.walletProvider,n=Fu(e.walletProvider)):e.wallet&&(n=e.wallet,t=r.PrivateKeyProvider.fromWallet(e.wallet)),this.wallet=n;const s=e.env??"prod",o=jo(s);this.environment=s,this.config={baseUrl:e.launchpadBaseUrl??o.launchpadBaseUrl,gatewayBaseUrl:o.gatewayBaseUrl,bundleBaseUrl:o.bundleBaseUrl,webSocketUrl:o.webSocketUrl,dexApiBaseUrl:o.dexApiBaseUrl,dexBackendBaseUrl:o.dexBackendBaseUrl,launchpadFrontendUrl:o.launchpadFrontendUrl,timeout:3e4,debug:!1,...e};const i=e.signer??(void 0!==n?new Qi(n.privateKey):void 0),a=void 0!==n?`eth|${n.address.slice(2)}`:Bu(i),c=void 0===e.walletAddress?void 0:Zt(e.walletAddress,"walletAddress"),l=void 0===e.galaChainAddress?void 0:Zt(e.galaChainAddress,"galaChainAddress");$u(a,c,"walletAddress"),$u(a,l,"galaChainAddress");const d=c??l??(void 0!==n?`eth|${n.address.slice(2)}`:Bu(i)),u=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."))},h=d??"";this.tokenWriter=void 0===n&&void 0!==e.signer&&void 0!==d?{signer:e.signer,walletAddress:d}:void 0;const g=new nu({bundleBaseUrl:this.config.bundleBaseUrl,launchpadBaseUrl:this.config.baseUrl,signer:u,walletAddress:h,...void 0!==e.httpRequestor&&{httpRequestor:e.httpRequestor},bundleSocketFactory:e.bundleSocketFactory}),p=mu({getTradeQuote:e=>this.tradingQuotesService.getTradeQuote(e),findTokenNameByVault:(e,t)=>this.findTokenNameByVault(e,t),defaultFeeSlippageFactor:()=>this.maxAcceptableReverseBondingCurveFeeSlippageFactor});this.sellFeeCeiling=p,this.launchpad=new _u({transport:g,walletAddress:h,sellFeeCeiling:p}),this.logger=new Vt({debug:this.config.debug??!1,context:"LaunchpadSDK"}),this.validateConfiguration(),this.slippageToleranceFactor=void 0===e.slippageToleranceFactor?Ku.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR:this.parseSlippageToleranceFactor(e.slippageToleranceFactor),this.maxAcceptableReverseBondingCurveFeeSlippageFactor=void 0===e.maxAcceptableReverseBondingCurveFeeSlippageFactor?Ku.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR:this.parseFeeSlippageFactor(e.maxAcceptableReverseBondingCurveFeeSlippageFactor),this.calculateAmountMode=e.calculateAmountMode??Ku.DEFAULT_CALCULATE_AMOUNT_MODE,this.galaChainAddressOverride=l,this.signerWalletAddress=c??(void 0===n?d: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 yt("session must provide accessToken() and onUnauthorized()","session");if(void 0!==e.accessToken&&""!==e.accessToken)throw yt("Pass either session or accessToken, not both: the session owns the token.","accessToken")}if(this.jwtAuth=void 0===m?new Bo:new Go,void 0!==e.accessToken&&""!==e.accessToken){const t=e.accessTokenExpiresIn??86400;this.jwtAuth.setToken(e.accessToken,t)}this.http=new Ou(this.auth,this.config,{signRequests:!0,session:m}),this.sessionAuth=new Ho(this.http,this.auth,this.jwtAuth,e.debug??!1,m);const f={signRequests:!1};this.galaChainHttp=new Ou(this.auth,{...this.config,baseUrl:this.config.gatewayBaseUrl},f),this.bundleHttp=new Ou(this.auth,{...this.config,baseUrl:this.config.bundleBaseUrl},f),this.dexApiHttp=new Ou(this.auth,{...this.config,baseUrl:this.config.dexApiBaseUrl},f),this.dexBackendHttp=new Ou(this.auth,{...this.config,baseUrl:this.config.dexBackendBaseUrl},f),this.galaChainPublicAxios=Cu(this.config.gatewayBaseUrl,this.config.timeout??3e4),this.cache=new Yn(e.debug??!1),this.launchpadService=new rl(this.http,this.jwtAuth),this.tokenResolverService=new qd(this.launchpadService.poolService),this.launchpadAPI=new Mo(this.http,this.logger,this.bundleHttp,this.calculateAmountMode,this.launchpad),this.galaChainService=new Ic(this.galaChainHttp,n,this.tokenResolverService,e.debug??!1,this.galaChainPublicAxios,this.tokenWriter),this.priceService=new Ma(this.dexBackendHttp,this.cache,e=>this.galaChainService.fetchTokenDetails(e),e.debug??!1),this.bundleService=this.createBundleService(),this.websocketService=new Jd({url:this.config.webSocketUrl},this.config.debug),this.nftCollectionService=new Rl(this.galaChainHttp),this.tradingQuotesService=new zd(this.http,e.debug??!1)}createOverrideSdk(e){if(!Rn(e))throw yt("Invalid privateKey: must be a non-empty string","privateKey");if(!e.match(/^0x[a-fA-F0-9]{64}$/))throw yt('Invalid privateKey format: must be "0x" followed by 64 hexadecimal characters',"privateKey");const n=new t.Wallet(e),r={...this.config,wallet:n};return new Ku(r)}getAddress(){return void 0!==this.galaChainAddressOverride&&""!==this.galaChainAddressOverride?this.galaChainAddressOverride:void 0!==this.signerWalletAddress&&""!==this.signerWalletAddress?this.signerWalletAddress:(this.validateWallet(),this.auth.getAddress())}getEthereumAddress(){return this.validateWallet(),this.wallet.address}validateWallet(){if(!this.wallet)throw Tt("wallet","Wallet");return this.wallet}assertTokenWriter(){if(void 0===this.wallet&&void 0===this.tokenWriter)throw Tt("wallet","Wallet")}setWallet(e){if(null==e||"object"!=typeof e||!("address"in e))throw new rt("Invalid wallet: must be an ethers Wallet instance, received "+typeof e,"wallet","INVALID_WALLET");this.wallet=e,this.auth.setWallet(e),this.onWalletChanged()}onWalletChanged(){this.walletGeneration+=1,this.galaChainAddressOverride=void 0,this.signerWalletAddress=void 0,this.rebuildTokenWrites(),this.bundleService=this.createBundleService(),this._bridgeService=void 0,this._wrapService=void 0,this._galaConnectClient=void 0,this._streamWebSocketService?.deauthenticate()}createBundleService(){return new ma(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 Ic(this.galaChainHttp,this.wallet,this.tokenResolverService,this.config.debug??!1,this.galaChainPublicAxios)}setWalletProvider(e){this.auth.setWalletProvider(e),this.wallet=e?Fu(e):void 0,this.onWalletChanged()}getWallet(){return this.wallet}get events(){return this.getEventsBatcherService()}getWalletProvider(){return this.auth.getWalletProvider()}hasWallet(){return this.auth.hasWallet()}getConfig(){const{wallet:e,walletProvider:t,signer:n,httpRequestor:r,streamAdminApiKey:s,userApiKey:o,accessToken:i,headers:a,...c}=this.config;return{...c,...void 0!==s&&{streamAdminApiKey:"[REDACTED]"},...void 0!==o&&{userApiKey:"[REDACTED]"},...void 0!==i&&{accessToken:"[REDACTED]"},...void 0!==a&&{headers:Object.fromEntries(Object.keys(a).map(e=>[e,"[REDACTED]"]))},environment:this.environment,slippageToleranceFactor:this.slippageToleranceFactor,maxAcceptableReverseBondingCurveFeeSlippageFactor:this.maxAcceptableReverseBondingCurveFeeSlippageFactor,calculateAmountMode:this.calculateAmountMode,gasFee:$t.GAS_FEE}}getVersion(){return Xo}getUrlByTokenName(e){const t=this.config.launchpadFrontendUrl;if(void 0===t||""===t)throw yt("launchpadFrontendUrl not configured in SDK","launchpadFrontendUrl");return`${t.replace(/\/$/,"")}/buy-sell/${e}`}async fetchPools(e){const t=await this.launchpadService.fetchPools(e??{});return await this.warmCacheFromPools(t.items),t}async fetchAllPools(e){const t=await this.launchpadService.fetchAllPools(e);return await this.warmCacheFromPools(t.items),t}async fetchTokenDistribution(e){return this.launchpadService.fetchTokenDistribution(e)}async getTopHolders(e,t=10){const n=await this.fetchTokenDistribution(e),r=Math.min(t,100);return n.holders.slice(0,r).map((e,t)=>({...e,rank:t+1}))}async getHolderCount(e){const t=await this.fetchTokenDistribution(e);return{count:t.totalHolders,totalBalance:t.totalSupply}}async getHolderRank(e,t){const n=en(t,"userAddress"),r=await this.fetchTokenDistribution(e),s=r.holders.findIndex(e=>e.address.toLowerCase()===n);if(-1===s)return null;const o=r.holders[s];return void 0===o?null:{rank:s+1,balance:o.balance,holderCount:r.totalHolders}}async getHoldersByBalance(e,t){const n=await this.fetchTokenDistribution(e),r=t?.minBalance??0,s=t?.maxBalance??1/0,o=Math.min(t?.limit??100,1e3),i=new Map;return n.holders.forEach((e,t)=>{i.set(e.address,t+1)}),n.holders.filter(e=>{const t=parseFloat(e.balance);return t>=r&&t<=s}).map(e=>({...e,rank:i.get(e.address)??0})).slice(0,o)}async getHolderHistory(e,t,n=20){return this.getTrades({tokenName:e,userAddress:t,pageSize:Math.min(n,100)})}async fetchUserHolderContext(e,t){return this.launchpadService.fetchUserHolderContext(e,t)}async fetchTokenPrice(e){const t="object"==typeof e&&null!==e?e:{};if(void 0!==t.tokenId)throw new rt("fetchTokenPrice prices a launchpad token by tokenName; a token by class key is priced by gswap-sdk (gSwap.market.getPrice)","tokenId",nt.INVALID_PARAMETERS);const n=t.tokenName;return this.priceService.fetchLaunchpadTokenSpotPrice("string"==typeof n?n:"",e=>this.launchpadAPI.calculateBuyAmount(e),e=>this.fetchPoolDetails(e))}async fetchTokenDetails(e){return this.galaChainService.fetchTokenDetails(e)}async fetchLaunchTokenFee(){return this.tradingQuotesService.fetchLaunchpadFee()}async fetchTokenClassesWithSupply(e){return this.galaChainService.fetchTokenClassesWithSupply(e)}async fetchPoolDetails(e){const t=await this.launchpadAPI.fetchPoolDetails(e),n=await this.launchpadAPI.fetchPoolDetailsForCalculation(e);return t.currentSupply=n.currentSupply,t.reverseBondingCurveMaxFeeFactor=n.reverseBondingCurveMaxFeeFactor,t.reverseBondingCurveMinFeeFactor=n.reverseBondingCurveMinFeeFactor,t.reverseBondingCurveNetFeeFactor=n.reverseBondingCurveNetFeeFactor,t.tokenName=e,t}async fetchPoolDetailsForCalculation(e){return this.launchpadAPI.fetchPoolDetailsForCalculation(e)}async isTokenGraduated(e){return(await this.fetchPoolDetails(e)).isGraduated}async fetchVolumeData(e){return this.launchpadService.fetchVolumeData(e)}async fetchTrades(e){return this.launchpadService.fetchTrades(e)}async fetchGalaBalance(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return An}),n=t(e)??this.getAddress();return this.galaChainService.fetchGalaBalance({owner:n,collection:"GALA",category:"Unit",additionalKey:"none",type:"none"})}loadCoreBridge(){const e=this.config.bridge;return void 0===e?Promise.reject(yt("The bridge and wrap methods need gala-core-sdk's ./bridge: create the SDK with `bridge: () => import('@gala-chain/gala-core-sdk/bridge')` (it needs the optional peers ethers, @solana/web3.js and @solana/spl-token).","bridge")):(this.coreBridgeLoad??(this.coreBridgeLoad=Promise.resolve().then(()=>e()).then(e=>{if("object"!=typeof(t=e)||null===t||"function"!=typeof t.BridgeService)throw new Error("the module has no BridgeService export");var t;return e}).catch(e=>{throw this.coreBridgeLoad=void 0,yt(`The bridge and wrap methods use @gala-chain/gala-core-sdk/bridge, which needs its optional peers ethers, @solana/web3.js and @solana/spl-token installed: ${ut(e)}`,"bridge")})),this.coreBridgeLoad)}async coreBridge(){const e=this.walletGeneration,t=await this.loadCoreBridge();if(e!==this.walletGeneration)throw yt("The wallet changed while this bridge or wrap call was starting; nothing was sent. Call it again.","wallet");return t}getBridgeService(e){if(!this._bridgeService){const t=this.getWallet();if(!t)throw new Error("Bridge operations require a wallet. Configure SDK with a wallet first.");const n=globalThis.process?.env.SOLANA_PRIVATE_KEY;this._bridgeService=new e.BridgeService({galaConnectBaseUrl:this.config.dexApiBaseUrl,galaChainWalletAddress:this.getAddress(),ethereumPrivateKey:t.privateKey,...void 0!==n&&""!==n?{solanaPrivateKey:n}:{},bridgeableTokenService:this.getBridgeableTokenService(e),environment:this.environment,...void 0!==this.config.ethereumRpcUrl&&""!==this.config.ethereumRpcUrl?{ethereumRpcUrl:this.config.ethereumRpcUrl}:{},...void 0!==this.config.solanaRpcUrl&&""!==this.config.solanaRpcUrl?{solanaRpcUrl:this.config.solanaRpcUrl}:{}})}return this._bridgeService}getBridgeableTokenService(e){return this._bridgeableTokenService??(this._bridgeableTokenService=new e.BridgeableTokenService(this.dexApiHttp)),this._bridgeableTokenService}getWrappableTokenService(e){return this._wrappableTokenService??(this._wrappableTokenService=new e.WrappableTokenService(this.dexApiHttp)),this._wrappableTokenService}getGalaConnectClient(e){if(void 0===this._galaConnectClient){const t=this.getAddress();if(void 0===this.config.dexApiBaseUrl||""===this.config.dexApiBaseUrl)throw new Error("DEX API base URL is required for GalaConnectClient. Check SDK configuration.");this._galaConnectClient=new e.GalaConnectClient({baseUrl:this.config.dexApiBaseUrl,...void 0!==this.config.gatewayBaseUrl&&""!==this.config.gatewayBaseUrl?{galachainBaseUrl:this.config.gatewayBaseUrl}:{},walletAddress:t})}return this._galaConnectClient}getWrapService(e){if(!this._wrapService){const t=this.getWallet();this._wrapService=new e.WrapService({galaConnectClient:this.getGalaConnectClient(e),wrappableTokenService:this.getWrappableTokenService(e),...void 0!==t&&{walletAddress:this.getAddress(),signer:new Qi(t.privateKey)}})}return this._wrapService}getStreamingService(){return this._streamingService??(this._streamingService=new gd(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._streamingService}getStreamChatService(){return this._streamChatService??(this._streamChatService=new Jl(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._streamChatService}getBanService(){return this._banService??(this._banService=new Di(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._banService}getTokenBanService(){return this._tokenBanService??(this._tokenBanService=new jd(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._tokenBanService}getAIModerationService(){return this._aiModerationService??(this._aiModerationService=new li(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._aiModerationService}getWeeklyChallengeService(){return this._weeklyChallengeService??(this._weeklyChallengeService=new Zd(this.http,this.config.debug??!1)),this._weeklyChallengeService}getOEmbedService(){return this._oembedService??(this._oembedService=new xl(this.http,this.config.debug??!1)),this._oembedService}getPlatformStatsService(){return this._platformStatsService??(this._platformStatsService=new Xl(this.http,this.config.debug??!1)),this._platformStatsService}getHealthService(){return this._healthService??(this._healthService=new Cc(this.http,this.config.debug??!1)),this._healthService}getEventsQueryService(){return this._eventsQueryService??(this._eventsQueryService=new Wa(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._eventsQueryService}getNotificationService(){return this._notificationService??(this._notificationService=new Ol(this.http,this.config.debug??!1,this.jwtAuth)),this._notificationService}getClientConfigService(){return this._clientConfigService??(this._clientConfigService=new fa(this.http,this.config.debug??!1)),this._clientConfigService}getApiKeyService(){return this._apiKeyService??(this._apiKeyService=new vi(this.http,this.jwtAuth,this.config.debug??!1)),this._apiKeyService}getModeratorService(){return this._moderatorService??(this._moderatorService=new Nl(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._moderatorService}getFlagService(){return this._flagService??(this._flagService=new Ca(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._flagService}getOverseerService(){return this._overseerService??(this._overseerService=new ql(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._overseerService}getWebSocketAdminService(){return this._websocketAdminService??(this._websocketAdminService=new Yd(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._websocketAdminService}getContentReactionService(){return this._contentReactionService??(this._contentReactionService=new Ra(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():Zt(e,"address")}getMessagesService(){return this._messagesService??(this._messagesService=new dl(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._messagesService}getRestrictedNamesService(){return this._restrictedNamesService??(this._restrictedNamesService=new Ql(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.userApiKey)),this._restrictedNamesService}getPlatformConfigService(){return this._platformConfigService??(this._platformConfigService=new Yl(this.http,this.jwtAuth,this.config.debug??!1)),this._platformConfigService}getEventsBatcherService(){return this._eventsBatcherService??(this._eventsBatcherService=new Ua(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 Bd({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&&rn(t.userAddress,n))&&((void 0===t.tokenName||t.tokenName===r)&&!!(void 0===t.reason||null!==s&&s.includes(t.reason)))),r=this.onUserBanned(t=>{const r=t.userAddress??null,s=t.reason??null;n("BANNED",r,t.tokenName,s)&&e({actionType:"BANNED",userAddress:r,tokenName:t.tokenName,reason:s,...void 0!==t.expiresAt&&{expiresAt:t.expiresAt}})}),s=this.onUserUnbanned(t=>{const r=t.userAddress??null;n("UNBANNED",r,t.tokenName,null)&&e({actionType:"UNBANNED",userAddress:r,tokenName:t.tokenName,reason:null})}),o=this.onBanEnforcement(t=>{const r=t.reason??null;n("ENFORCEMENT",null,t.tokenName,r)&&e({actionType:"ENFORCEMENT",userAddress:null,tokenName:t.tokenName,reason:r,...void 0!==t.expiresAt&&{expiresAt:t.expiresAt}})});return()=>{r(),s(),o()}}watchTokenRoomEvent(e,t,n,r){const s=r.tokenName;if(void 0===s||""===s)throw new Error(`${e} requires a tokenName filter - these are per-token stream events with no way to watch every token at once.`);return t(s,n)}watchCommentCreated(e,t={}){return this.watchTokenRoomEvent("watchCommentCreated",(e,t)=>this.getStreamWebSocketService().subscribeCommentCreated(e,t),n=>{(void 0===t.authorAddress||rn(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||rn(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&&!rn(t.moderatorAddress,n)),r=this.watchModeratorAdded(t=>{n("ADDED",t.userAddress)&&e({actionType:"ADDED",tokenName:t.tokenName,moderatorAddress:t.userAddress,role:t.role})},t),s=this.watchTokenRoomEvent("watchModeratorRemoved",(e,t)=>this.getStreamWebSocketService().subscribeModeratorRemoved(e,t),t=>{n("REMOVED",t.userAddress)&&e({actionType:"REMOVED",tokenName:t.tokenName,moderatorAddress:t.userAddress})},t),o=this.watchTokenRoomEvent("watchModeratorRoleUpdated",(e,t)=>this.getStreamWebSocketService().subscribeModeratorRoleUpdated(e,t),t=>{n("ROLE_UPDATED",t.userAddress)&&e({actionType:"ROLE_UPDATED",tokenName:t.tokenName,moderatorAddress:t.userAddress,oldRole:t.oldRole,newRole:t.newRole})},t);return()=>{r(),s(),o()}}watchPoolUpdated(e,t={}){const n=e=>void 0===t.updateType||t.updateType===e,r=this.watchPoolMetadataUpdated(t=>{n("METADATA")&&e({updateType:"METADATA",tokenName:t.tokenName,details:t})},t),s=this.watchTokenRoomEvent("watchPoolSocialLinksUpdated",(e,t)=>this.getStreamWebSocketService().subscribePoolSocialLinksUpdated(e,t),t=>{n("SOCIAL_LINKS")&&e({updateType:"SOCIAL_LINKS",tokenName:t.tokenName,details:t})},t),o=this.watchTokenRoomEvent("watchPoolBadgeAssigned",(e,t)=>this.getStreamWebSocketService().subscribePoolBadgeAssigned(e,t),t=>{n("BADGE_ASSIGNED")&&e({updateType:"BADGE_ASSIGNED",tokenName:t.tokenName,details:t})},t);return()=>{r(),s(),o()}}watchTokenBanChanged(e,t={}){const n=e=>void 0===t.banStatus||t.banStatus===e,r=this.watchTokenBanned(t=>{n("BANNED")&&e({banStatus:"BANNED",tokenName:t.tokenName,reason:t.reason})},t),s=this.watchTokenRoomEvent("watchTokenUnbanned",(e,t)=>this.getStreamWebSocketService().subscribeTokenUnbanned(e,t),t=>{n("UNBANNED")&&e({banStatus:"UNBANNED",tokenName:t.tokenName})},t);return()=>{r(),s()}}onContentFlagged(e){return this.getStreamWebSocketService().subscribeEvent("CONTENT_FLAGGED",e)}onFlagResolved(e){return this.getStreamWebSocketService().subscribeEvent("FLAG_RESOLVED",e)}onStreamChatMessage(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_CHAT_MESSAGE",e)}onStreamChatUpdated(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_CHAT_UPDATED",e)}onStreamChatDeleted(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_CHAT_DELETED",e)}onStreamChatPinned(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_CHAT_PINNED",e)}onStreamChatUnpinned(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_CHAT_UNPINNED",e)}onChatStatusChanged(e){return this.getStreamWebSocketService().subscribeEvent("CHAT_STATUS_CHANGED",e)}onViewerCountChanged(e){return this.getStreamWebSocketService().subscribeEvent("VIEWER_COUNT",e)}onRecordingStatusChanged(e){return this.getStreamWebSocketService().subscribeEvent("RECORDING_STATUS",e)}onSimulcastStatusChanged(e){return this.getStreamWebSocketService().subscribeEvent("SIMULCAST_STATUS",e)}onDownloadReady(e){return this.getStreamWebSocketService().subscribeEvent("DOWNLOAD_READY",e)}onRecordingsCountUpdated(e){return this.getStreamWebSocketService().subscribeEvent("RECORDINGS_COUNT_UPDATED",e)}onUserTyping(e){return this.getStreamWebSocketService().subscribeEvent("USER_TYPING",e)}onStreamReaction(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_REACTION",e)}onContentReactionAdded(e){return this.getStreamWebSocketService().subscribeEvent("CONTENT_REACTION_ADDED",e)}onContentReactionRemoved(e){return this.getStreamWebSocketService().subscribeEvent("CONTENT_REACTION_REMOVED",e)}onStreamCountdownUpdated(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_COUNTDOWN_UPDATED",e)}onStreamLanguageUpdated(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_LANGUAGE_UPDATED",e)}onStreamControlStatusChanged(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_CONTROL_STATUS_CHANGED",e)}onConnection(e){return this.getStreamWebSocketService().subscribeEvent("connection",e)}onAuthenticated(e){return this.getStreamWebSocketService().subscribeEvent("authenticated",e)}onTokenSubscribed(e){return this.getStreamWebSocketService().subscribeEvent("token_subscribed",e)}onTokenUnsubscribed(e){return this.getStreamWebSocketService().subscribeEvent("token_unsubscribed",e)}onRoomSubscribed(e){return this.getStreamWebSocketService().subscribeEvent("room_subscribed",e)}onRoomLeft(e){return this.getStreamWebSocketService().subscribeEvent("room_left",e)}onEngagementStatsUpdated(e){return this.getStreamWebSocketService().subscribeEvent("ENGAGEMENT_STATS_UPDATED",e)}async estimateBridgeFee(e){return this.getBridgeService(await this.coreBridge()).estimateBridgeFee(e)}async bridgeOut(e){return this.getBridgeService(await this.coreBridge()).bridgeOut(e)}async bridgeIn(e){return this.getBridgeService(await this.coreBridge()).bridgeIn(e)}async getBridgeStatus(e){return this.getBridgeService(await this.coreBridge()).getBridgeStatus(e)}async getSupportedBridgeTokens(){const e=this.getBridgeService(await this.coreBridge()),t=e.getSupportedBridgeTokens();return{tokens:t,totalCount:t.length,supportedChains:e.getSupportedBridgeChains()}}async fetchTokenBalance(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return An}),n=t(e.address);if(void 0!==e.tokenId&&""!==e.tokenId){const{normalizeToTokenInstanceKey:t}=await Promise.resolve().then(function(){return ha}),r=t(e.tokenId),{collection:s,category:o,type:i,additionalKey:a}=r;return this.galaChainService.fetchTokenBalance({owner:n,collection:s,category:o,additionalKey:a,type:i},e.withExpired??!1)}if(void 0!==e.tokenName&&""!==e.tokenName){const t=Ht(e.tokenName),r=Pu[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:ra(r)}}throw Tt("tokenId or tokenName","Either tokenId or tokenName")}async fetchLockedBalance(e){const t=await this.fetchTokenBalance(e);if(!t)return null;const n="lockedHolds"in t||"lockedQuantity"in t;return{tokenId:t.tokenId,lockedQuantity:n?t.lockedQuantity??"0":"0",lockedHolds:n?t.lockedHolds??[]:[]}}async fetchAvailableBalance(e){const t=await this.fetchTokenBalance(e);if(!t)return null;const n="availableQuantity"in t;return{tokenId:t.tokenId,availableQuantity:n?t.availableQuantity??String(t.quantity):String(t.quantity),totalQuantity:String(t.quantity)}}async calculateBuyAmount(e){return this.launchpadAPI.calculateBuyAmount(e)}async calculateSellAmount(e){return this.launchpadAPI.calculateSellAmount(e)}async calculateBuyAmountLocal(e){return this.launchpadAPI.calculateBuyAmountLocal(e)}async calculateSellAmountLocal(e){return this.launchpadAPI.calculateSellAmountLocal(e)}async calculateBuyAmountExternal(e){return this.launchpadAPI.calculateBuyAmountExternal(e)}async calculateSellAmountExternal(e){return this.launchpadAPI.calculateSellAmountExternal(e)}async calculateBuyAmountForGraduation(e){return this.launchpadAPI.calculateBuyAmountForGraduation(e)}async graduateToken(e){const{tokenName:t,slippageToleranceFactor:n,maxAcceptableReverseBondingCurveFeeSlippageFactor:r,privateKey:s,calculateAmountMode:o,currentSupply:i}=e;let a=t;void 0===o&&void 0===i||(a={tokenName:t,...void 0!==o&&{calculateAmountMode:o},...void 0!==i&&{currentSupply:i}});const c=await this.calculateBuyAmountForGraduation(a),l={tokenName:t,amount:c.remainingTokens,type:"exact",expectedAmount:c.amount,maxAcceptableReverseBondingCurveFee:c.reverseBondingCurveFee,slippageToleranceFactor:this.slippageToleranceFactor};return void 0!==n&&(l.slippageToleranceFactor=n),void 0!==r&&(l.maxAcceptableReverseBondingCurveFeeSlippageFactor=r),void 0!==s&&(l.privateKey=s),await this.buy(l)}async calculateInitialBuyAmount(e){const t={nativeTokenQuantity:e};return this.launchpadAPI.calculateInitialBuyAmount(t)}async buy(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...r}=e;return t.buy(r)}this.validateWallet(),await this.ensureWebSocketConnection();const t=(await this.bundleService.buyToken(e)).data,n=t?.transactionId;if(void 0===n||""===n)throw bt("No transaction ID returned from buy operation");return this.waitForConfirmation(n,t=>Uu(t,n,"buy",e))}async sell(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...r}=e;return t.sell(r)}this.validateWallet(),await this.ensureWebSocketConnection();const t=(await this.bundleService.sellToken(e)).data,n=t?.transactionId;if(void 0===n||""===n)throw bt("No transaction ID returned from sell operation");return this.waitForConfirmation(n,t=>Uu(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=>{Lu(n,t);const r=n.data??{};if(!function(e){if(xn(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 xu(`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 An}),n=t(e)??this.getAddress();return this.launchpadService.fetchProfile(n)}async fetchReferralUrl(){this.validateWallet();const e=this.getAddress();return await this.dexApiHttp.get(d,void 0,{"x-wallet-address":e})}async fetchReferrals(e){const t=this.resolveReferralAddress(e?.address),n=e?.page??1,r=e?.limit??10,s={pageNumber:n,limit:r,sortBy:e?.sortBy??"joined",sortDir:e?.sortDir??"desc"},o=await this.dexApiHttp.get(u,s,{"x-wallet-address":t});if(!Array.isArray(o))throw new at("Unexpected API response: expected array, got "+typeof o);return{referrals:o,page:n,limit:r,hasMore:o.length===r}}async fetchAllReferrals(e){const t=await async function(e,t={}){const{maxPages:n=1e4,logger:r,pageSize:s=20,concurrency:o=1,startPage:i=1}=t,a=[];let c=i;const l=i+n-1;let d=!0,u=0;if(o<=1)for(;d&&c<=l;){r&&r.debug(`Auto-pagination: fetching page ${c} with limit ${s}`);const t=await e(c,s);if(null==t||!Array.isArray(t.items)){r&&r.warn("Auto-pagination: received invalid result structure, stopping");break}if(a.push(...t.items),u=t.total,r&&r.debug(`Auto-pagination: page ${c} returned ${t.items.length} items, hasNext: ${String(t.hasNext)}`),0===t.items.length){r&&r.debug(`Auto-pagination: no items returned on page ${c}, exiting loop`);break}d=t.hasNext,c++}else for(r&&r.debug(`Auto-pagination: using concurrent mode with concurrency=${o}`);d&&c<=l;){const t=[];for(let e=0;e<o&&c+e<=l;e++)t.push(c+e);r&&r.debug(`Auto-pagination: fetching pages ${t.join(", ")} concurrently`);const n=t.map(t=>e(t,s).catch(e=>{const n=e,o=n.statusCode??n.response?.status??n.originalError?.response?.status??n.status??n.launchpadError?.statusCode;if(400===o||404===o)return r&&r.debug(`Auto-pagination: page ${t} returned ${o} (end of pagination)`,{statusCode:o}),{items:[],total:0,totalPages:0,page:t,limit:s,hasNext:!1,hasPrevious:!1};throw e})),i=await Promise.all(n);for(const e of i){if(null==e||!Array.isArray(e.items)){r&&r.warn("Auto-pagination: received invalid result structure in batch, stopping"),d=!1;break}if(0===e.items.length){r&&r.debug("Auto-pagination: empty page in batch, reached end of results"),d=!1;break}if(a.push(...e.items),u=e.total,!e.hasNext){d=!1;break}}c+=t.length,r&&r.debug(`Auto-pagination: batch complete, total items so far: ${a.length}`)}return c>l&&r&&r.warn(`Auto-pagination: exceeded maxPages limit of ${n} (maxPage=${l}), stopping iteration`),r&&r.debug(`Auto-pagination: completed with total items: ${a.length}, total count: ${u}`),{items:a,total:u}}((t,n)=>this.fetchReferrals({...e,page:t,limit:n}).then(e=>({items:e.referrals,page:e.page,limit:e.limit,total:0,totalPages:0,hasNext:e.hasMore,hasPrevious:e.page>1})),{maxPages:100,pageSize:100,logger:this.logger});return{referrals:t.items,total:t.items.length}}async fetchReferralsSummary(e){const t=this.resolveReferralAddress(e?.address),n=await this.dexApiHttp.get(h,void 0,{"x-wallet-address":t});if(void 0===n||"number"!=typeof n.referralCount||void 0===n.rewardTotals)throw new at(`Unexpected API response: expected { referralCount, rewardTotals }, got ${JSON.stringify(n)}`);return n}async updateProfile(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return An}),{address:n,...r}=e,s=void 0===n?void 0:t(n),o={...r,...void 0!==s&&{address:s}};if(void 0!==o.privateKey&&""!==o.privateKey){const e=this.createOverrideSdk(o.privateKey),{privateKey:t,...n}=o;return e.updateProfile(n)}return this.launchpadService.updateProfile(o)}async uploadProfileImage(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return An}),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 An}),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 An}),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 An}),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 An}),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 An});return{...e,lockAuthority:t(e.lockAuthority)}}return e})),n={...e,tokens:t};if(void 0!==n.privateKey&&""!==n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...r}=n;return e.lockTokens(r)}return this.assertTokenWriter(),this.galaChainService.lockTokens(n)}async unlockTokens(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...r}=e;return t.unlockTokens(r)}return this.assertTokenWriter(),this.galaChainService.unlockTokens(e)}async burnTokens(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...r}=e;return t.burnTokens(r)}return this.assertTokenWriter(),this.galaChainService.burnTokens(e)}async resolveVaultAddress(e){return this.tokenResolverService.resolveTokenToVault(e)}async findTokenNameByVault(e,t){let n;for(let r=0;r<10;r+=1){const r=await this.launchpadService.poolService.fetchPools({search:t,pageSize:100,...void 0===n?{}:{cursor:n}}),s=r.items.find(t=>t.vaultAddress===e);if(void 0!==s)return s.tokenName;const o=ti(r.pageInfo,n);if(void 0===o)return;n=o}}getCacheInfo(){const e={...this.launchpadAPI.getCacheStats()};if(this._bridgeableTokenService){const t=this._bridgeableTokenService.getCacheStats();e.bridgeableTokens={ETHEREUM:t.tokensByNetwork.ETHEREUM,SOLANA:t.tokensByNetwork.SOLANA,total:t.totalTokens}}return this._wrappableTokenService&&(e.wrappableTokens=this._wrappableTokenService.getCacheStats()),e}clearCache(e){this.launchpadAPI.clearCache(e),void 0!==e&&""!==e||(void 0!==this._bridgeableTokenService&&this._bridgeableTokenService.clearCache(),void 0!==this._wrappableTokenService&&this._wrappableTokenService.clearCache())}validateConfiguration(){try{kn(this.config.timeout,1,3e5,"timeout")}catch{this.logger.warn(`Invalid timeout value: ${this.config.timeout??"undefined"}. Using default 30000ms.`),this.config.timeout=3e4}if(void 0===this.config.baseUrl||""===this.config.baseUrl)throw yt("baseUrl is required in configuration","baseUrl");if(void 0===this.config.webSocketUrl||""===this.config.webSocketUrl)throw yt("webSocketUrl is required in configuration","webSocketUrl");try{new URL(this.config.baseUrl)}catch{throw yt(`Invalid baseUrl format: ${this.config.baseUrl}`,"baseUrl")}try{new URL(this.config.webSocketUrl)}catch{throw yt(`Invalid webSocketUrl format: ${this.config.webSocketUrl}`,"webSocketUrl")}if(void 0!==this.config.gatewayBaseUrl&&""!==this.config.gatewayBaseUrl)try{new URL(this.config.gatewayBaseUrl)}catch{throw yt(`Invalid gatewayBaseUrl format: ${this.config.gatewayBaseUrl}`,"gatewayBaseUrl")}if(void 0!==this.config.bundleBaseUrl&&""!==this.config.bundleBaseUrl)try{new URL(this.config.bundleBaseUrl)}catch{throw yt(`Invalid bundleBaseUrl format: ${this.config.bundleBaseUrl}`,"bundleBaseUrl")}if(void 0!==this.config.launchpadFrontendUrl&&""!==this.config.launchpadFrontendUrl)try{new URL(this.config.launchpadFrontendUrl)}catch{throw yt(`Invalid launchpadFrontendUrl format: ${this.config.launchpadFrontendUrl}`,"launchpadFrontendUrl")}}parseSlippageToleranceFactor(e){const t=Tn("string"==typeof e||"number"==typeof e?e:String(e),Ku.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR);return t<0||t>1?(this.logger.warn(`Invalid slippage tolerance factor: ${String(e)}, using default: ${Ku.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR}`),Ku.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR):t}parseFeeSlippageFactor(e){const t=Tn("string"==typeof e||"number"==typeof e?e:String(e),Ku.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: ${Ku.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR}`),Ku.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR):t}async ensureWebSocketConnection(){this.websocketService.isConnected()||(await this.websocketService.connect(),this.logger.debug("WebSocket connection established"))}async waitForConfirmation(e,t){this.logger.debug(`Waiting for confirmation of transaction: ${e}`);try{const n=await this.websocketService.waitForTransaction(e);if(n.status!==exports.SDKTransactionStatus.COMPLETED)throw new Mu(e,n.status,n.message);let r;try{r=t(n)}catch(t){if(t instanceof xu)throw t;throw new xu(`Failed to transform WebSocket response for transaction ${e}`,dt(t)?t:new Error(ut(t)))}return this.logger.debug(`Transaction confirmed: ${e}`,r),r}catch(t){if(this.logger.error(`Transaction confirmation failed: ${e}`,t),t instanceof Mu||t instanceof xu)throw t;throw new xu(`WebSocket confirmation failed for transaction ${e}`,dt(t)?t:new Error(ut(t)))}}async warmCacheFromPools(e){if(void 0===e||!Array.isArray(e))return;const{extractMetadataFromPoolData:t,isValidPoolForCaching:n}=await Promise.resolve().then(function(){return Ch});e.forEach(e=>{if(!n(e))return;const r=t(e,this.logger);r&&this.launchpadAPI.warmCacheFromPoolData(e.tokenName,r)})}connectWebSocket(){this.websocketService.connect()}disconnectWebSocket(){this.websocketService.disconnect()}isWebSocketConnected(){return this.websocketService.isConnected()}subscribeToEvent(e,t){const n=this.websocketService.getSocket();return n?(n.on(e,t),()=>{n.off(e,t),this.logger.debug(`Unsubscribed from event: "${e}"`)}):(this.logger.warn(`⚠️ WebSocket not connected - subscribing to "${e}" without connection`),()=>{})}onLaunchpadTokenCreation(e,t){const n=1e3,r=Math.max(t?.intervalMs??3e4,n);null!=t?.intervalMs&&t.intervalMs<n&&this.logger.warn(`Poll interval ${t.intervalMs}ms is below minimum 1000ms. Using minimum interval instead.`);const s=t?.creatorAddress,o=new Map;let i=!0,a=null;let c=0;const l=async()=>{if(i){try{const t=await this.fetchPools({type:"recent",pageSize:20});c>0&&(this.logger.debug("Successfully recovered from polling errors"),c=0),t.items.forEach(t=>{o.has(t.tokenName)||((e=>{if(o.set(e,!0),o.size>1e3){const e=o.keys().next().value;void 0!==e&&o.delete(e)}})(t.tokenName),void 0!==s&&""!==s&&t.creatorAddress!==s||e(t))})}catch(e){c++;const t=ut(e);c>=5?this.logger.error(`Polling for new launchpad tokens failed ${c} consecutive times. Last error: ${t}. Continuing to retry...`):c>1?this.logger.warn(`Error polling for new launchpad tokens (attempt ${c}/5): ${t}`):this.logger.debug(`Error polling for new launchpad tokens: ${t}`)}if(i){const e=Math.min(Math.max(c-1,0),2),t=r*Math.pow(2,e);a=setTimeout(()=>{l()},t)}}};return l(),()=>{i=!1,a&&clearTimeout(a),this.logger.debug("Stopped watching for launchpad token creation")}}matchesCreatorFilter(e,t){return void 0===t||""===t||e.creatorAddress===t}subscribeToTokenCreations(e,t){if(this.logger.debug("Subscribing to token creation broadcasts"+(void 0!==t?.creatorFilter&&""!==t.creatorFilter?` (filter: ${t.creatorFilter})`:"")),null===this.websocketService||void 0===this.websocketService)throw yt("WebSocket service not initialized. Ensure websocketUrl is configured and the service is connected.","websocketService");let n=!1,r=null;const s=(n,...r)=>{try{if(r.length>0&&"object"==typeof r[0]&&null!==r[0]){const n=r[0].data;if(void 0!==n?.Data&&null!==n.Data&&"object"==typeof n.Data){const r=n.Data;if("CreateSale"===r.functionName){const n=(e,t="")=>{const n=r[e];return"string"==typeof n&&""!==n?n:t},s={tokenName:n("tokenName"),symbol:n("symbol"),creatorAddress:n("creatorAddress"),description:n("description"),image:n("image"),vaultAddress:n("vaultAddress"),tokenStringKey:n("tokenStringKey"),preBuyQuantity:n("initialBuyQuantity","0"),websiteUrl:n("websiteUrl"),telegramUrl:n("telegramUrl"),twitterUrl:n("twitterUrl"),instagramUrl:n("instagramUrl"),facebookUrl:n("facebookUrl"),redditUrl:n("redditUrl"),tiktokUrl:n("tiktokUrl"),isFinalized:!0===r.isFinalized};this.matchesCreatorFilter(s,t?.creatorFilter)&&e(s)}}}}catch(e){this.logger.warn(`Error processing token creation broadcast: ${ut(e)}`)}};let o=this.websocketService.getSocket();if(o)o.onAny(s),n=!0,this.logger.debug("Token creation broadcast listener registered");else{this.logger.debug("WebSocket not yet connected, initiating connection..."),this.websocketService.connect().catch(e=>{const n=new Error(`WebSocket connection failed: ${ut(e)}`);this.logger.warn("Failed to establish WebSocket connection:",e),t?.onError&&t.onError(n)});let e=0;const i=()=>{if(o=this.websocketService.getSocket(),!o&&e<Ku.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS)return e++,void(r=setTimeout(()=>i(),Ku.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS));if(!o&&e>=Ku.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS){const e=new Error(`WebSocket not available after ${Ku.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS*Ku.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS}ms`);return this.logger.warn("Token creation broadcast subscription timeout:",e.message),void(t?.onError&&t.onError(e))}o&&(o.onAny(s),n=!0,this.logger.debug("Token creation broadcast listener registered"))};i()}return()=>{try{if(null!==r&&(clearTimeout(r),r=null,this.logger.debug("Cleared token creation broadcast polling timeout")),!n)return void this.logger.debug("Cleanup called before listener registration - no action needed");const e=this.websocketService.getSocket();e&&(e.offAny(s),n=!1,this.logger.debug("Stopped listening to token creation broadcasts"))}catch(e){this.logger.warn("Error removing token creation listener:",e)}}}getNftCollectionClaimFee(){return this.nftCollectionService.getCollectionClaimFee()}getNftTokenClassCreateFee(){return this.nftCollectionService.getTokenClassCreateFee()}estimateNftMintFee(e){return this.nftCollectionService.estimateMintFee(e)}estimateNftOperationFees(e){return this.nftCollectionService.estimateNftOperationFees(e)}claimNftCollection(e){return this.nftCollectionService.claimCollection(e)}fetchNftCollections(e){return this.nftCollectionService.fetchUserCollections(e)}isNftCollectionAvailable(e){return this.nftCollectionService.isCollectionAvailable(e)}createNftTokenClass(e){return this.nftCollectionService.createTokenClass(e)}fetchNftTokenClasses(e){return this.nftCollectionService.fetchTokenClasses(e)}mintNft(e){return this.nftCollectionService.mintNft(e)}fetchNftBalances(e,t){return this.nftCollectionService.fetchNftBalances(e,t)}async cleanup(){try{if(this.logger.debug("Starting cleanup..."),void 0!==this._eventsBatcherService)try{await this._eventsBatcherService.shutdown(5e3),this._eventsBatcherService=void 0}catch(e){this.logger.warn("Error during events shutdown:",e)}this.http.cleanup(),null!==this.websocketService&&void 0!==this.websocketService&&this.websocketService.disconnect(),void 0!==this._streamWebSocketService&&(this._streamWebSocketService.dispose(),this._streamWebSocketService=void 0),this.logger.debug("Cleanup completed")}catch(e){this.logger.error("Error during cleanup:",e)}}static cleanupAll(e=!1){const t=new Vt({debug:e,context:"LaunchpadSDK"});t.debug("Starting global cleanup..."),Jd.cleanupAll(e),t.debug("Global cleanup completed")}}function Hu(n){const r=e.createWallet(n);return{...r,wallet:new t.Wallet(r.privateKey)}}function Wu(){const e=globalThis;return e.process?.env??{}}Ku.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR=.15,Ku.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR=.01,Ku.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY=$t.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY,Ku.DEFAULT_CALCULATE_AMOUNT_MODE=tt.LOCAL,Ku.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS=30,Ku.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS=100;function Vu(e){const t={};return void 0!==e.cursor&&(t.cursor=e.cursor),void 0!==e.pageSize&&(t.pageSize=e.pageSize),t}function ju(e){return"string"==typeof e?e:"number"==typeof e||"boolean"==typeof e||"bigint"==typeof e?String(e):JSON.stringify(e)??""}function qu(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 zu(e){const t=e.trim().toLowerCase();if(0===t.length)throw new Error("Token name cannot be empty");return t}function Yu(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 Xu(e,t){return`${e.replace(/\/$/,"")}${t}`}const Qu=new Map;const Ju={NEW_HOLDER:"NEW_HOLDER",EXITED_HOLDER:"EXITED_HOLDER",BALANCE_CHANGED:"BALANCE_CHANGED"},Zu=mo({type:"string",userAddress:"string",balance:"string",rank:"number",previousRank:"optional-number"}),eh=mo({tokenName:"string",userAddress:"string",quantity:"optional-string",percentage:"optional-number",holderTier:"optional-object",isCreator:"boolean",rank:"optional-number"});Jn.MIN_LENGTH,Jn.MAX_LENGTH,Jn.PATTERN;Ln({ENABLED:"ENABLED",DISABLED:"DISABLED",ADMIN_DISABLED:"ADMIN_DISABLED"});function th(e){return"global"===e||"token"===e}function nh(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 rh(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.messageId&&"string"==typeof t.content&&"string"==typeof t.userAddress&&"string"==typeof t.pinnedBy&&"string"==typeof t.pinnedAt}const sh=Ln({RATE_LIMITED:"RATE_LIMITED",INVALID_EMOJI:"INVALID_EMOJI",NOT_AUTHENTICATED:"NOT_AUTHENTICATED",STREAM_NOT_LIVE:"STREAM_NOT_LIVE"});function oh(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.userAddress&&"string"==typeof t.fullName&&(void 0===t.profileImage||"string"==typeof t.profileImage)}var ih,ah,ch,lh,dh,uh;exports.AnalysisStatus=void 0,(ih=exports.AnalysisStatus||(exports.AnalysisStatus={})).PENDING="PENDING",ih.PROCESSING="PROCESSING",ih.COMPLETED="COMPLETED",ih.FAILED="FAILED",exports.AnalysisType=void 0,(ah=exports.AnalysisType||(exports.AnalysisType={})).TEXT="TEXT",ah.IMAGE="IMAGE",ah.VIDEO="VIDEO",exports.AIRecommendation=void 0,(ch=exports.AIRecommendation||(exports.AIRecommendation={})).NO_ACTION="NO_ACTION",ch.REVIEW_REQUIRED="REVIEW_REQUIRED",ch.DELETE_CONTENT="DELETE_CONTENT",ch.BAN_USER="BAN_USER",ch.DELETE_AND_BAN="DELETE_AND_BAN",exports.AnalysisCategory=void 0,(lh=exports.AnalysisCategory||(exports.AnalysisCategory={})).VIOLENCE="VIOLENCE",lh.HATE_SPEECH="HATE_SPEECH",lh.SEXUAL_CONTENT="SEXUAL_CONTENT",lh.HARASSMENT="HARASSMENT",lh.SPAM="SPAM",lh.SCAM="SCAM",lh.SELF_HARM="SELF_HARM",lh.ILLEGAL_ACTIVITY="ILLEGAL_ACTIVITY",lh.MISINFORMATION="MISINFORMATION",lh.COPYRIGHT="COPYRIGHT",lh.SAFE="SAFE",exports.AnalysisTier=void 0,(dh=exports.AnalysisTier||(exports.AnalysisTier={})).QUICK="QUICK",dh.DETAILED="DETAILED",exports.AIModerationMode=void 0,(uh=exports.AIModerationMode||(exports.AIModerationMode={})).DISABLED="DISABLED",uh.ADVISORY="ADVISORY";const hh={[exports.AnalysisStatus.PENDING]:"Pending",[exports.AnalysisStatus.PROCESSING]:"Processing",[exports.AnalysisStatus.COMPLETED]:"Completed",[exports.AnalysisStatus.FAILED]:"Failed"},gh={[exports.AIRecommendation.NO_ACTION]:"No Action Needed",[exports.AIRecommendation.REVIEW_REQUIRED]:"Human Review Required",[exports.AIRecommendation.DELETE_CONTENT]:"Delete Content",[exports.AIRecommendation.BAN_USER]:"Ban User",[exports.AIRecommendation.DELETE_AND_BAN]:"Delete & Ban"},ph={[exports.AnalysisCategory.VIOLENCE]:"Violence",[exports.AnalysisCategory.HATE_SPEECH]:"Hate Speech",[exports.AnalysisCategory.SEXUAL_CONTENT]:"Sexual Content",[exports.AnalysisCategory.HARASSMENT]:"Harassment",[exports.AnalysisCategory.SPAM]:"Spam",[exports.AnalysisCategory.SCAM]:"Scam",[exports.AnalysisCategory.SELF_HARM]:"Self Harm",[exports.AnalysisCategory.ILLEGAL_ACTIVITY]:"Illegal Activity",[exports.AnalysisCategory.MISINFORMATION]:"Misinformation",[exports.AnalysisCategory.COPYRIGHT]:"Copyright",[exports.AnalysisCategory.SAFE]:"Safe"},mh={[exports.AnalysisTier.QUICK]:"Quick Scan",[exports.AnalysisTier.DETAILED]:"Detailed Scan"},fh={[exports.AnalysisType.TEXT]:"Text",[exports.AnalysisType.IMAGE]:"Image",[exports.AnalysisType.VIDEO]:"Video"},Eh={[exports.AIModerationMode.DISABLED]:"Disabled",[exports.AIModerationMode.ADVISORY]:"Advisory"},Ah=Ln(exports.AnalysisStatus),Th=Ln(exports.AnalysisType),vh=Ln(exports.AIRecommendation),Sh=Ln(exports.AnalysisCategory),yh=Ln(exports.AnalysisTier),bh=Ln(exports.AIModerationMode),Nh=Bn([{field:"id",type:"number"},{field:"flagId",type:"number"},{field:"status",type:"string",validator:Ah},{field:"analysisType",type:"string",validator:Th},{field:"provider",type:"string"}]),kh=Bn([{field:"enabled",type:"boolean"},{field:"mode",type:"string",validator:bh},{field:"provider",type:"string"}]);function wh(e){return null!==e.analysisTier}function _h(e){if(!Rn(e))throw Tt("content");if(0===e.trim().length)throw Ot("content","Content");if(e.length>or.COMMENTS_V1.MAX_LENGTH)throw Rt("content",or.COMMENTS_V1.MAX_LENGTH,e.length)}function Ih(e){if(!Rn(e))throw Tt("content");if(0===e.trim().length)throw new rt("content cannot be empty","content",nt.REQUIRED);if(e.length>or.CHAT_MESSAGES_V1.MAX_LENGTH)throw new rt(`content must be at most ${or.CHAT_MESSAGES_V1.MAX_LENGTH} characters`,"content",nt.TOO_LONG)}var Ch=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=Tn(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=Tn(e.reverseBondingCurveMaxFeePortion,NaN);isNaN(r)?t&&t.debug(`Skipping invalid reverseBondingCurveMaxFeePortion for ${e.tokenName}: "${e.reverseBondingCurveMaxFeePortion}"`):n.reverseBondingCurveMaxFeeFactor=r}return void 0!==n.reverseBondingCurveMaxFeeFactor&&void 0!==n.reverseBondingCurveMinFeeFactor&&(n.reverseBondingCurveNetFeeFactor=n.reverseBondingCurveMaxFeeFactor-n.reverseBondingCurveMinFeeFactor),Object.keys(n).length>0?n:null},isValidPoolForCaching:function(e){if(null===e||"object"!=typeof e)return!1;const t=e;return"tokenName"in t&&"string"==typeof t.tokenName&&t.tokenName.length>0}});exports.ACTIVE_USER_TYPE=Si,exports.AI_MODE_LABELS=Eh,exports.AI_RECOMMENDATION_LABELS=gh,exports.ALL_PERMISSIONS=gi,exports.ANALYSIS_CATEGORY_LABELS=ph,exports.ANALYSIS_STATUS_LABELS=hh,exports.ANALYSIS_TIER_LABELS=mh,exports.ANALYSIS_TYPE_LABELS=fh,exports.API_KEY_PERMISSION={MANAGE_COMMENTS:"MANAGE_COMMENTS",MANAGE_CHAT:"MANAGE_CHAT",BAN_USERS:"BAN_USERS",UNBAN_USERS:"UNBAN_USERS",MANAGE_SIMULCAST:"MANAGE_SIMULCAST",GET_STREAM_KEY:"GET_STREAM_KEY",STOP_STREAM:"STOP_STREAM",RESET_STREAM_KEY:"RESET_STREAM_KEY",START_STREAM:"START_STREAM",DELETE_RECORDINGS:"DELETE_RECORDINGS",MANAGE_STREAM_SETTINGS:"MANAGE_STREAM_SETTINGS"},exports.API_KEY_ROLE=di,exports.API_KEY_ROLES=ui,exports.API_KEY_ROLE_HIERARCHY=Ti,exports.AddressFormatter=on,exports.AgentConfig=class{constructor(){this.utilityInstance=!0,this.utilityInstance}static async quickSetup(e={}){const t=e.environment??this.detectEnvironment(),n=this.setupWallet(e.privateKey),r=this.buildSdkConfig(e,t,n),s=new Ku(r),o={sdk:s,wallet:n,config:r};if(!1!==e.autoValidate){const e=await this.validateSetup(s,n);return{...o,validation:e}}return o}static readOnlySetup(e={}){const t=e.environment??this.detectEnvironment(),n=this.buildSdkConfig(e,t),r=new Ku(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=Tn(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??Hu(),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"===(Wu().LAUNCHPAD_ENV??Wu().ENVIRONMENT)?"stage":"prod"}static setupWallet(e){if(void 0===e||""===e){const e=Wu().PRIVATE_KEY;return void 0!==e&&""!==e?Hu(e):Hu()}return"generate"===e?Hu():Hu(e)}static buildSdkConfig(e,t,n){const r=e.galaChainAddress??Wu().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 jo(e).launchpadBaseUrl}static getDefaultTimeout(e){switch(e){case"prod":return 3e4;case"stage":return 45e3}}static getEnvironmentDefaults(e){const t=jo(e);return{bundleBaseUrl:t.bundleBaseUrl,gatewayBaseUrl:t.gatewayBaseUrl}}},exports.AuthError=Po,exports.BAN_DURATIONS={ONE_HOUR:3600,ONE_DAY:86400,ONE_WEEK:604800,ONE_MONTH:2592e3},exports.BrowserWalletSigner=Zi,exports.BundleSubmission=tu,exports.BundlerTransport=nu,exports.BurnError=Tc,exports.CALCULATION_MODES=tt,exports.CONTENT_REACTION_TYPES=Da,exports.CONTENT_TYPE_LABELS=va,exports.ChartService=class extends jn{constructor(e,t=!1){super(e,t)}async getChart(e){if(null==e)throw Tt("options","Chart options");const{tokenName:t,from:n,to:r,resolution:s}=e;if(null==t||""===t)throw Tt("tokenName","Token name");if(null==n)throw Tt("from","Start timestamp");if(null==r)throw Tt("to","End timestamp");if(null==s)throw Tt("resolution","Data resolution interval");Fn(t,"tokenName",Xn);const o=173e6;if("number"!=typeof n||n<o)throw new rt("from must be a valid timestamp (min: 173000000)","from","INVALID_TIMESTAMP");if("number"!=typeof r||r<o)throw new rt("to must be a valid timestamp (min: 173000000)","to","INVALID_TIMESTAMP");if("number"!=typeof s||s<1)throw new rt("resolution must be a number >= 1","resolution","INVALID_RESOLUTION");const{adaptQueryParams:i}=await Promise.resolve().then(function(){return Uc}),a=i({tokenName:t,from:n,to:r,resolution:s}),c=await Bt(()=>this.http.get(l.CHART,a),{errorContext:"Failed to fetch chart data"}),d=Lt(c);if(null==d||"object"!=typeof d)throw St("Invalid API response: missing or invalid data",c.status??500);const u=d,h=u.data;if(!Array.isArray(h))throw St("Invalid API response: expected data array",c.status??500);const g={dataPoints:h.map(e=>{if("object"!=typeof e||null===e)throw St("Invalid API response: invalid data point structure",c.status??500);const t=e,n=t.startTime??t.timestamp,r=t.openPrice??t.value,s=t.closePrice??t.value,o=t.lowPrice??t.value,i=t.highPrice??t.value,a=t.volume??"0";return{startTime:"number"==typeof n?n:Number(n),openPrice:String(r),closePrice:String(s),lowPrice:String(o),highPrice:String(i),volume:String(a)}})};return"boolean"==typeof u.isPreviousData&&(g.isPreviousData=u.isPreviousData),g}},exports.ConfigurationError=ct,exports.DEFAULT_EVENTS_CONFIG=La,exports.DEFAULT_PRICING_CONCURRENCY=5,exports.DEFAULT_REVERSE_BONDING_CURVE_CONFIGURATION=fu,exports.DEFAULT_WEBSOCKET_RECONNECT_ATTEMPTS=5,exports.ENVIRONMENT_URLS=Vo,exports.ERROR_CODES=nt,exports.EVENT_SORT_FIELDS=Fa,exports.EVENT_SOURCES=Ba,exports.EVENT_TIME_PRESETS=Pa,exports.EVENT_TYPES={LOGIN:"login",LOGOUT:"logout",TOKEN_BUY:"token_buy",TOKEN_SELL:"token_sell",TOKEN_SWAP:"token_swap",TOKEN_CREATED:"token_created",TOKEN_GRADUATED:"token_graduated",PAGE_VIEW:"page_view",PAGE_LEAVE:"page_leave",STREAM_START:"stream_start",STREAM_END:"stream_end",STREAM_VIEWERS_CHANGED:"stream_viewers_changed",CHAT_MESSAGE_SENT:"chat_message_sent",CHAT_MESSAGE_RECEIVED:"chat_message_received",LIQUIDITY_ADDED:"liquidity_added",LIQUIDITY_REMOVED:"liquidity_removed",BRIDGE_DEPOSIT:"bridge_deposit",BRIDGE_WITHDRAW:"bridge_withdraw",PROFILE_UPDATED:"profile_updated",BALANCE_CHANGED:"balance_changed",ERROR_OCCURRED:"error_occurred"},exports.EXTENDED_STREAM_ROLE=ad,exports.EventBufferWithAutoCleanup=class{constructor(e={},t){this.events=[],this.timeouts=new Map,this.maxSize=e.maxSize??100,this.defaultTtlMs=e.defaultTtlMs??3e4,this.logger=t}push(e){if(this.events.length>=this.maxSize){const e=0;this.events.shift();const t=this.timeouts.get(e);t&&(clearTimeout(t),this.timeouts.delete(e)),this.logger?.warn(`Buffer full (${this.maxSize}), dropped oldest event`)}this.events.push(e);const t=this.events.length-1,n=setTimeout(()=>{this.events[t]===e&&this.events.splice(t,1),this.timeouts.delete(t)},this.defaultTtlMs);this.timeouts.set(t,n)}getAll(){return[...this.events]}clear(){for(const e of this.timeouts.values())clearTimeout(e);this.events=[],this.timeouts.clear()}get size(){return this.events.length}},exports.EventsBatcherService=Ua,exports.EventsQueryService=Wa,exports.FLAG_ACTION_LABELS=Ta,exports.FLAG_DETAILS_MAX_LENGTH=500,exports.FLAG_REASON_LABELS=Ea,exports.FLAG_STATUS_LABELS=Aa,exports.FileValidationError=Dc,exports.GALA_DECIMALS=8,exports.GalaWalletSigner=Ji,exports.GlobalAndRoomCallbackDispatcher=class{constructor(e){this.globalCallbacks=[],this.roomCallbacks=new Map,this.logger=e}registerGlobalCallback(e){this.globalCallbacks.push(e)}registerRoomCallback(e,t){const n=this.roomCallbacks.get(e)??[];n.push(t),this.roomCallbacks.set(e,n)}dispatch(e,t){for(const e of this.globalCallbacks)try{e(t)}catch(e){this.logger?.error(`Error in global callback: ${ut(e)}`)}const n=this.roomCallbacks.get(e);if(n)for(const r of n)try{r(t)}catch(t){this.logger?.error(`Error in room callback for ${e}: ${ut(t)}`)}}clear(){this.globalCallbacks=[],this.roomCallbacks.clear()}clearRoom(e){this.roomCallbacks.delete(e)}},exports.HOLDER_DELTA_TYPES=Ju,exports.HealthService=Cc,exports.IMAGE_EXTENSIONS=Hr,exports.INVITE_STATUS=ml,exports.INVITE_STATUSES=fl,exports.JWT_CONSTANTS=Lo,exports.LAUNCHPAD_TOKEN_DECIMALS=18,exports.LAUNCHPAD_WRITE_METHODS=eu,exports.LaunchpadSDK=Ku,exports.LaunchpadSDKError=Hi,exports.LaunchpadWrites=_u,exports.ListenerCleanupManager=class{constructor(e){this.listeners=[],this.logger=e}register(e,t){this.listeners.push({id:e,cleanup:t})}async cleanup(){const e=[];for(let t=this.listeners.length-1;t>=0;t--){const n=this.listeners[t];if(void 0===n)continue;const{id:r,cleanup:s}=n;try{await s()}catch(t){const n=t instanceof Error?t:new Error(String(t));e.push(n),this.logger?.error(`Cleanup error for listener ${r}:`,n)}}return this.listeners=[],e}clear(){this.listeners=[]}get size(){return this.listeners.length}},exports.LockError=ec,exports.MAX_BURN_BATCH_SIZE=50,exports.MAX_CONCURRENT_POOL_FETCHES=5,exports.MAX_LOCK_BATCH_SIZE=100,exports.MAX_UNLOCK_BATCH_SIZE=100,exports.MESSAGES_CONSTRAINTS=il,exports.MESSAGE_TYPES=ol,exports.MODERATOR_ROLE=ul,exports.MODERATOR_ROLES=hl,exports.NFT_FEES=kl,exports.NetworkError=at,exports.NftCollectionService=Rl,exports.OEmbedService=xl,exports.OVERSEER_INVITE_STATUS=Ll,exports.OVERSEER_STATUS=Ul,exports.PAGINATION_DEFAULTS=Qo,exports.PERMISSION=hi,exports.POOL_FETCH_CONFIG={MAX_CONCURRENT_FETCHES:5,PAGE_SIZE:50,BACKEND_PAGE_SIZE:20},exports.POOL_FETCH_TYPES=Je,exports.POOL_LIST_MAX_PAGE_SIZE=et,exports.POOL_STREAM_STATUSES=Ze,exports.POOL_TYPES={RECENT:"recent",POPULAR:"popular"},exports.PayloadWalkerWithDeduplication=class{constructor(e,t,n=50){this.seen=new Set,this.extractor=e,this.dedupeKeyFn=t,this.maxDepth=n}walk(e){const t=[],n=new WeakSet,r=(e,s=0)=>{if(s>this.maxDepth)return;if(null==e||"object"!=typeof e)return;if(n.has(e))return;n.add(e);const o=this.extractor(e);if(null!==o){const e=this.dedupeKeyFn(o);this.seen.has(e)||(this.seen.add(e),t.push(o))}for(const t of Object.values(e))r(t,s+1)};return r(e,0),t}reset(){this.seen.clear()}getSeenCount(){return this.seen.size}},exports.PendingSubscriptionTracker=class{constructor(){this.pending=new Map}addPending(e,t){this.removePending(e);const n=setTimeout(()=>{this.pending.delete(e)},t);this.pending.set(e,{timeoutId:n,addedAt:Date.now()})}removePending(e){const t=this.pending.get(e);t&&(clearTimeout(t.timeoutId),this.pending.delete(e))}isPending(e){return this.pending.has(e)}getPendingCount(){return this.pending.size}clearExpired(){for(const[e,t]of this.pending.entries())null==t&&this.pending.delete(e)}clear(){for(const e of this.pending.values())clearTimeout(e.timeoutId);this.pending.clear()}},exports.PlatformStatsService=Xl,exports.PrivateKeySigner=Qi,exports.QUERY_FIELD_NAMES={PAGE:"page",LIMIT:"limit",TOKEN_NAME:"tokenName",VAULT_ADDRESS:"vaultAddress",USER_ADDRESS:"userAddress",TRADE_TYPE:"tradeType",POOL_TYPE:"type",SEARCH:"search",SORT_ORDER:"sortOrder",START_DATE:"startDate",END_DATE:"endDate"},exports.REACTION_EMOJI_MAP={heart:"❤️",fire:"🔥",laugh:"😂",wow:"😮",thumbs_up:"👍"},exports.RECORDING_STATUS=ed,exports.ROLE_SOURCE=id,exports.RoomSubscriptionManager=class{constructor(){this.rooms=new Set}addRoom(e){this.rooms.add(e)}removeRoom(e){this.rooms.delete(e)}getRooms(){return Array.from(this.rooms)}isSubscribedTo(e){return this.rooms.has(e)}clear(){this.rooms.clear()}get size(){return this.rooms.size}},exports.SDK_VERSION=Xo,exports.SIMULATE_EVENT_TYPE={STREAM_STARTED:"stream.started",STREAM_STOPPED:"stream.stopped",RECORDING_READY:"recording.ready",SIMULCAST_ERROR:"simulcast.error"},exports.SIMULCAST_PLATFORM=td,exports.SIMULCAST_STATUS={IDLE:"idle",STARTING:"starting",BROADCASTING:"broadcasting",ERRORED:"errored"},exports.STREAM_EVENTS=pd,exports.STREAM_PERMISSION={MANAGE_COMMENTS:"MANAGE_COMMENTS",MANAGE_CHAT:"MANAGE_CHAT",BAN_USERS:"BAN_USERS",UNBAN_USERS:"UNBAN_USERS",MANAGE_SIMULCAST:"MANAGE_SIMULCAST",GET_STREAM_KEY:"GET_STREAM_KEY",STOP_STREAM:"STOP_STREAM",RESET_STREAM_KEY:"RESET_STREAM_KEY",START_STREAM:"START_STREAM",DELETE_RECORDINGS:"DELETE_RECORDINGS",MANAGE_STREAM_SETTINGS:"MANAGE_STREAM_SETTINGS"},exports.STREAM_ROLE=od,exports.STREAM_STATUS=Zl,exports.SelectiveEventForwarding=class{constructor(){this.filters=[]}addFilter(e){return this.filters.push(e),this}forward(e){for(const t of this.filters)if(!t(e))return!1;return!0}clearFilters(){this.filters=[]}get filterCount(){return this.filters.length}},exports.StreamWebSocketService=Bd,exports.TIME_CONSTANTS={ONE_SECOND_MS:1e3,ONE_MINUTE_MS:6e4,ONE_HOUR_MS:36e5,ONE_DAY_MS:864e5,ONE_WEEK_MS:6048e5,ONE_MONTH_MS:2592e6},exports.TOKEN_NAME_AVAILABILITY_CONSTRAINT=Zn,exports.TOKEN_NAME_DTO_CONSTRAINT=Xn,exports.TOKEN_NAME_EVENT_CONSTRAINT=er,exports.TOKEN_NAME_FILTER_CONSTRAINT=Qn,exports.TOKEN_NAME_PATH_CONSTRAINT=Jn,exports.TRADING_TYPES=Qe,exports.TokenRestrictedError=class extends rt{constructor(e){super(e,"token","TOKEN_RESTRICTED"),this.name="TokenRestrictedError"}},exports.TradingQuotesService=zd,exports.TransactionError=lt,exports.TransactionFailedError=Mu,exports.TypingIndicatorDebouncer=class{constructor(e={},t){this.pendingIndicators=new Map,this.activeIndicators=new Set,this.delayMs=e.delayMs??3e3,this.onTyping=e.onTyping,this.onStopTyping=e.onStopTyping}indicate(e,t){const n=`${e}:${t}`,r=this.pendingIndicators.get(n);r&&clearTimeout(r),this.activeIndicators.has(n)||(this.activeIndicators.add(n),this.onTyping?.(e,t));const s=setTimeout(()=>{this.activeIndicators.delete(n),this.pendingIndicators.delete(n),this.onStopTyping?.(e,t)},this.delayMs);this.pendingIndicators.set(n,s)}stopTyping(e,t){const n=`${e}:${t}`,r=this.pendingIndicators.get(n);r&&(clearTimeout(r),this.pendingIndicators.delete(n)),this.activeIndicators.has(n)&&(this.activeIndicators.delete(n),this.onStopTyping?.(e,t))}clear(){for(const e of this.pendingIndicators.values())clearTimeout(e);this.pendingIndicators.clear(),this.activeIndicators.clear()}get activeCount(){return this.activeIndicators.size}},exports.ValidationError=rt,exports.WebSocketError=xu,exports.WebSocketTimeoutError=class extends xu{constructor(e,t){super(`WebSocket confirmation timeout for transaction ${e} after ${t}ms`),this.name="WebSocketTimeoutError"}},exports.WeeklyChallengeService=Zd,exports.addCursorToPagination=function(e,t){return void 0===t?e:{...e,cursor:t}},exports.addressFormatSchema=yr,exports.aggregateMultipleApiSources=async function(e,t,n){const r=n?.logger,s=n?.fetcher??(async e=>{const t=await fetch(e);if(!t.ok)throw new Error(`HTTP ${t.status}`);return t.json()});r?.debug(`Aggregating from ${e.length} endpoints`);const o=e.map(async(t,n)=>{try{const o=await s(t);return r?.debug(`Endpoint [${n+1}/${e.length}] succeeded: ${t}`),o}catch(s){return void r?.warn(`Endpoint [${n+1}/${e.length}] failed: ${t} - ${ut(s)}`)}}),i=(await Promise.allSettled(o)).map(e=>{if("fulfilled"===e.status)return e.value});return r?.debug(`Aggregating ${i.filter(e=>void 0!==e).length} successful results`),t(i)},exports.amountMethodSchema=os,exports.amountTypeSchema=ss,exports.assertValidWalletAddress=fn,exports.availabilityTokenNameSchema=fr,exports.backendUserRef=en,exports.bidirectionalTokenMatch=function(e,t,n,r){return e===n&&t===r||e===r&&t===n},exports.browserFileSchema=Vr,exports.bufferFileSchema=jr,exports.buildConcurrentBatchRequests=async function(e,t,n,r){const s=r?.logger,o=[];o.length=e.length;let i=0,a=0;s?.debug(`Starting concurrent batch requests: ${e.length} URLs, batch size: ${t}`);for(let r=0;r<e.length;r+=t){const c=e.slice(r,r+t),l=r;try{const t=c.map((t,r)=>{const c=l+r;return(async()=>{try{const r=await n(t);return o[c]=r,i++,s?.debug(`Fetched [${c+1}/${e.length}]: ${t}`),r}catch(n){throw a++,s?.warn(`Failed [${c+1}/${e.length}]: ${t} - ${ut(n)}`),n}})()}),r=await Promise.allSettled(t);for(let e=0;e<r.length;e++){const t=r[e];"rejected"===t?.status&&s?.debug(`Promise rejected in batch at index ${l+e}`)}}catch(e){s?.error(`Batch processing error at index ${r}: ${ut(e)}`)}}return s?.debug(`Batch complete: ${i} succeeded, ${a} failed`),o},exports.buildQueryParametersWithValidation=function(e){if(null==e||"object"!=typeof e)return"";const t=[];for(const[n,r]of Object.entries(e)){if(On(r))continue;let e;e="string"==typeof r?r:"number"==typeof r||"boolean"==typeof r?String(r):Array.isArray(r)?r.map(e=>ju(e)).join(","):ju(r);const s=encodeURIComponent(n),o=encodeURIComponent(e);t.push(`${s}=${o}`)}return t.length>0?`?${t.join("&")}`:""},exports.buildSafePaginationOptions=Vu,exports.buyTokensDataSchema=Ts,exports.calculateLinearFeeInterpolation=function(e,t,n){const r="number"==typeof e?new a(e):e;if(r.isLessThan(0)||r.isGreaterThan(1))throw new Error(`Progress must be between 0 and 1, got: ${r.toString()}`);if(n<t)throw new Error(`maxFee must be >= minFee, got minFee: ${t}, maxFee: ${n}`);const s=n-t;return new a(t).plus(new a(s).multipliedBy(r))},exports.calculatePreMintDataSchema=ws,exports.calculateScaledFeeAmount=function(e,t){if(t<0)throw new Error(`feeFactor must be >= 0, got: ${t}`);return Eo(e).multipliedBy(t).integerValue(a.ROUND_DOWN)},exports.calculateTotalPages=function(e,t){if("number"!=typeof e||!Number.isInteger(e))throw _t("total","a non-negative integer",e);if(e<0)throw Nt("total",0,1/0,e);if("number"!=typeof t||!Number.isInteger(t))throw _t("limit","a non-negative integer",t);if(t<0)throw Nt("limit",0,1/0,t);return 0===t?1:0===e?0:Math.ceil(e/t)},exports.capitalize=Et,exports.caseInsensitiveTokenComparison=function(e,t){return e.toLowerCase()===t.toLowerCase()},exports.checkPoolOptionsSchema=rs,exports.commonValidators=Gn,exports.conditionalSpreadBuilder=function(e,t){const n={...e};for(const[e,r]of Object.entries(t))void 0!==r&&(n[e]=r);return n},exports.conditionalTrimAndValidateString=zc,exports.createLaunchpadSDK=function(n){xn(n)&&(n={});const{wallet:r,env:s,config:o={},...i}=n,a={...{...i,...o}};delete a.wallet,delete a.env,delete a.config;const c=!xn(a.signer)||!xn(a.walletProvider);let l;if(xn(r))l=c?void 0:new t.Wallet(e.createWallet().privateKey);else if("string"==typeof r)l=new t.Wallet(e.createWallet(r).privateKey);else{if(!(r instanceof t.Wallet))throw yt("Invalid wallet input. Expected string (private key or mnemonic) or Wallet instance.","wallet");l=r}const d={...void 0!==l?{wallet:l}:{},...void 0!==s?{env:s}:{},debug:!1,timeout:3e4,...a};return new Ku(d)},exports.createLimitSchema=Rr,exports.createOptionsValidator=function(e){return t=>{const n=[],r=t;for(const t of e){const{field:e,required:s,type:o,validator:i}=t,a=r[e];if(s){if(xn(a)){n.push(`${e} is required`);continue}if("string"===o){if("string"!=typeof a){n.push(`${e} must be a string`);continue}if(0===a.trim().length){n.push(`${e} is required`);continue}}}if(!xn(a))if(void 0===o||typeof a===o){if(void 0!==i){const e=i(a,r);null!=e&&""!==e&&n.push(e)}}else n.push(`${e} must be a ${o}`)}return n}},exports.createPaginatedResultSchema=function(e){return n.z.object({data:n.z.array(e),...ps})},exports.createPaginationQuery=function(e,t=Qo.DEFAULT_LIMIT){if("number"!=typeof e||!Number.isInteger(e)||e<0)throw _t("offset","a non-negative integer",e);return _n(t,"limit"),{offset:e,limit:t}},exports.createTradeDataSchema=As,exports.decimalRoundingUp=function(e,t){if(t<0)throw new Error(`decimals must be >= 0, got: ${t}`);const n=Eo(e),r=new a(10).pow(t);return n.multipliedBy(r).integerValue(a.ROUND_UP).dividedBy(r)},exports.deduplicateByKey=function(e,t,n=!0){const r=new Map;if(e.forEach((e,n)=>{const s=t(e);r.set(s,n)}),n){const n=new Set;return e.filter(e=>{const r=t(e);return!n.has(r)&&(n.add(r),!0)})}return e.filter((e,n)=>{const s=t(e);return r.get(s)===n})},exports.dtoTokenNameSchema=mr,exports.errorMessageCaseNormalization=function(e){return e.toLowerCase()},exports.ethereumAddressSchema=br,exports.extractFieldWithFallbackPath=function(e,t,n=null){if(null==e||"object"!=typeof e)return n;const r=e;for(const e of t){const t=e.split(".");let n=r;for(const e of t){if(null==n||"object"!=typeof n){n=null;break}n=n[e]}if(Rn(n))return n;if(null!=n&&""!==n)return n}return n},exports.extractPaginationMetadata=function(e){const t={page:1,pageSize:20,totalCount:-1,hasMore:!1};if(null==e||"object"!=typeof e)return t;const n=e,r=vn(ju(n.page??n.Page??n.current??1),t.page),s=vn(ju(n.pageSize??n.limit??n.size??t.pageSize),t.pageSize),o=n.data,i=o?.meta;let a;a="number"==typeof n.totalCount?n.totalCount:"number"==typeof n.total?n.total:"number"==typeof i?.totalItems?i.totalItems:"number"==typeof o?.count?o.count:vn(ju(n.totalCount??n.total??-1),t.totalCount);let c=t.hasMore;return"boolean"==typeof n.hasMore?c=n.hasMore:"boolean"==typeof n.has_more?c=n.has_more:"boolean"==typeof i?.hasMore&&(c=i.hasMore),{page:r,pageSize:s,totalCount:a,hasMore:c}},exports.feeCeilingFromQuotedFee=pu,exports.fetchGalaBalanceOptionsSchema=Rs,exports.fetchPoolDetailsDataSchema=_s,exports.fetchTokenBalanceOptionsSchema=Ms,exports.fileSizeSchema=Lr,exports.fileUploadSchema=Wr,exports.filenameSchema=Ur,exports.flexibleAddressSchema=Nr,exports.flexibleFileSchema=qr,exports.formatGalaForDTO=bn,exports.formatLaunchpadTokenForDTO=Nn,exports.fromBackendAddressFormat=ln,exports.fullNameSchema=Sr,exports.generateBuySellStringsInstructions=ta,exports.generateCreateSaleStringsInstructions=na,exports.getAmountOptionsSchema=ks,exports.getEnvironmentConfig=jo,exports.getIntervalRegistryStats=function(){const e=Array.from(Qu.entries()).map(([e,t])=>({id:e,...t}));return{size:Qu.size,entries:e}},exports.getLaunchTokenDataValidationErrors=co,exports.getNftFeeAsNumber=function(e){return parseFloat(kl[e])},exports.getRecordingAnimatedUrl=function(e,t,n,r="gif"){const s=zu(e),o=t.trim();if(0===o.length)throw new Error("Recording ID cannot be empty");return Yu(r),Xu(n,`/v1/tokens/${encodeURIComponent(s)}/recordings/${encodeURIComponent(o)}/assets/animated.${r.toLowerCase()}`)},exports.getRecordingAssetUrl=function(e,t,n,r,s){const o=zu(e),i=t.trim(),a=n.trim().toLowerCase();if(0===i.length)throw new Error("Recording ID cannot be empty");if(0===a.length)throw new Error("Asset type cannot be empty");Yu(s);const c=void 0!==s&&s.length>0?`.${s.toLowerCase()}`:"";return Xu(r,`/v1/tokens/${encodeURIComponent(o)}/recordings/${encodeURIComponent(i)}/assets/${encodeURIComponent(a)}${c}`)},exports.getRecordingPosterUrl=function(e,t,n){const r=zu(e),s=t.trim();if(0===s.length)throw new Error("Recording ID cannot be empty");return Xu(n,`/v1/tokens/${encodeURIComponent(r)}/recordings/${encodeURIComponent(s)}/assets/poster.jpg`)},exports.getRecordingStoryboardUrl=function(e,t,n,r="vtt"){const s=zu(e),o=t.trim();if(0===o.length)throw new Error("Recording ID cannot be empty");return Yu(r),Xu(n,`/v1/tokens/${encodeURIComponent(s)}/recordings/${encodeURIComponent(o)}/assets/storyboard.${r.toLowerCase()}`)},exports.getRecordingStreamUrl=function(e,t,n){const r=zu(e),s=t.trim();if(0===s.length)throw new Error("Recording ID cannot be empty");return Xu(n,`/v1/tokens/${encodeURIComponent(r)}/recordings/${encodeURIComponent(s)}/assets/stream.m3u8`)},exports.getRecordingThumbnailUrl=function(e,t,n,r="jpg"){const s=zu(e),o=t.trim();if(0===o.length)throw new Error("Recording ID cannot be empty");return Yu(r),Xu(n,`/v1/tokens/${encodeURIComponent(s)}/recordings/${encodeURIComponent(o)}/assets/thumbnail.${r.toLowerCase()}`)},exports.getTieredModerationSavings=function(e,t){if(!wh(e)||null===e.tokensUsed)return 0;const n=1500*t.maxFrames;if(0===n)return 0;const r=(n-e.tokensUsed)/n*100;return Math.max(0,Math.round(r))},exports.getTokenAnimatedUrl=function(e,t,n="gif"){const r=zu(e);return Yu(n),Xu(t,`/v1/tokens/${encodeURIComponent(r)}/assets/animated.${n.toLowerCase()}`)},exports.getTokenAssetUrl=function(e,t,n,r){const s=zu(e),o=t.trim().toLowerCase();if(0===o.length)throw new Error("Asset type cannot be empty");Yu(r);const i=void 0!==r&&r.length>0?`.${r.toLowerCase()}`:"";return Xu(n,`/v1/tokens/${encodeURIComponent(s)}/assets/${encodeURIComponent(o)}${i}`)},exports.getTokenImageUrl=function(e,t){const n=zu(e);return Xu(t,`/v1/tokens/${encodeURIComponent(n)}/assets/image`)},exports.getTokenLiveStreamUrl=function(e,t){const n=zu(e);return Xu(t,`/v1/tokens/${encodeURIComponent(n)}/assets/live.m3u8`)},exports.getTokenPosterUrl=function(e,t){const n=zu(e);return Xu(t,`/v1/tokens/${encodeURIComponent(n)}/assets/poster.jpg`)},exports.getTokenStoryboardUrl=function(e,t,n="vtt"){const r=zu(e);return Yu(n),Xu(t,`/v1/tokens/${encodeURIComponent(r)}/assets/storyboard.${n.toLowerCase()}`)},exports.getTokenThumbnailUrl=function(e,t,n="jpg"){const r=zu(e);return Yu(n),Xu(t,`/v1/tokens/${encodeURIComponent(r)}/assets/thumbnail.${n.toLowerCase()}`)},exports.getTradeOptionsSchema=Ss,exports.graduateTokenOptionsSchema=as,exports.graphDataOptionsSchema=is,exports.groupByKey=function(e,t){const n=new Map;for(const r of e){const e=t(r);n.has(e)||n.set(e,[]),n.get(e).push(r)}return n},exports.hasMorePages=function(e,t,n){if("number"!=typeof e||!Number.isInteger(e))throw _t("offset","a non-negative integer",e);if(e<0)throw Nt("offset",0,1/0,e);return e+t<n},exports.hexStringExtractionAndNormalization=function(e){if(""===e||"string"!=typeof e)return null;if(e.includes("|")){const t=e.split("|");if(t.length>=2){const e=t[1];if(void 0!==e&&Yc(e))return Xc(e)}return null}return Yc(e)?Xc(e):null},exports.imageExtensionSchema=zr,exports.imageFilenameSchema=Yr,exports.imageMimeTypeSchema=Fr,exports.imageUploadOptionsSchema=ts,exports.isAIModerationData=Nh,exports.isAIModerationMode=bh,exports.isAIModerationSettings=kh,exports.isAIRecommendation=vh,exports.isActiveUserType=yi,exports.isAnalysisCategory=Sh,exports.isAnalysisStatus=Ah,exports.isAnalysisTier=yh,exports.isAnalysisType=Th,exports.isBanData=bi,exports.isBanEnforcementEvent=wi,exports.isBurnTokenEntry=fc,exports.isBurnTokensData=Ec,exports.isChatDisabledReason=th,exports.isChatStatusResponse=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"boolean"==typeof t.enabled&&(void 0===t.reason||th(t.reason))},exports.isClaimableInvite=function(e){if(e.status!==Ll.PENDING)return!1;if(null!==e.expiresAt&&void 0!==e.expiresAt){if(Xt(e.expiresAt)<=new Date)return!1}return!0},exports.isContentType=Sa,exports.isEmptyValue=On,exports.isExtendedStreamRole=cd,exports.isFlagAction=Na,exports.isFlagData=ka,exports.isFlagReason=ya,exports.isFlagStatus=ba,exports.isHolderDelta=Zu,exports.isHolderDeltaType=function(e){return"string"==typeof e&&(e===Ju.NEW_HOLDER||e===Ju.EXITED_HOLDER||e===Ju.BALANCE_CHANGED)},exports.isLockTokenEntry=za,exports.isLockTokensData=Xa,exports.isMessage=function(e){if(!al(e))return!1;const t=e.reactions;return"string"==typeof e.id&&"string"==typeof e.messageId&&"string"==typeof e.tokenName&&cl(e.tokenImage)&&"string"==typeof e.userAddress&&ll(e.user)&&ll(e.userProfile)&&"string"==typeof e.content&&"string"==typeof e.createdAt&&cl(e.updatedAt)&&cl(e.deletedAt)&&"number"==typeof e.flagCount&&al(t)&&al(t.counts)},exports.isMessageType=function(e){return e===ol.CHAT_MESSAGE||e===ol.COMMENT},exports.isModeratedToken=Sl,exports.isModerationTiered=wh,exports.isModeratorInvite=vl,exports.isNonEmptyString=Rn,exports.isOverseerInviteStatus=Fl,exports.isOverseerStatus=Pl,exports.isPinnedMessage=rh,exports.isPublicInviteInfo=yl,exports.isReactionErrorCode=sh,exports.isRecordingStatus=rd,exports.isSimulcastPlatform=sd,exports.isStreamChatDeletedEvent=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.messageId&&"string"==typeof t.deletedAt},exports.isStreamChatErrorEvent=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.message},exports.isStreamChatMessage=nh,exports.isStreamChatMessageEvent=function(e){return nh(e)},exports.isStreamChatPinnedEvent=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&rh(t.pinnedMessage)},exports.isStreamChatUnpinnedEvent=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.unpinnedMessageId},exports.isStreamReactionErrorEvent=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.message},exports.isStreamReactionEvent=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.emoji&&"number"==typeof t.timestamp&&"number"==typeof t.streamTime},exports.isStreamStatus=nd,exports.isStreamStatusEvent=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&nd(t.status)&&(null===t.playbackId||"string"==typeof t.playbackId)&&"boolean"==typeof t.isLive},exports.isTokenAccessResult=function(e){if(null==e||"object"!=typeof e)return!1;const t=e,n=t.permissions;return Array.isArray(n)&&n.every(e=>"string"==typeof e)&&(null===t.source||"owner"===t.source||"moderator_invite"===t.source||"api_key"===t.source||"overseer"===t.source)&&(void 0===t.matchedPreset||null===t.matchedPreset||"MODERATOR"===t.matchedPreset||"TECHNICAL_PRODUCER"===t.matchedPreset||"MANAGER"===t.matchedPreset)&&"boolean"==typeof t.isOwner&&"boolean"==typeof t.isOverseer},exports.isTokenBanData=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"number"==typeof t.id&&"string"==typeof t.tokenName&&"string"==typeof t.bannedBy&&"string"==typeof t.createdAt&&(null===t.reason||"string"==typeof t.reason)},exports.isTypingIndicatorEvent=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&Array.isArray(t.typingUsers)&&t.typingUsers.every(oh)},exports.isTypingUser=oh,exports.isUnlockTokenEntry=Ya,exports.isUnlockTokensData=Qa,exports.isUserBannedEvent=Ni,exports.isUserHoldingData=eh,exports.isUserRef=sn,exports.isUserUnbannedEvent=ki,exports.isValidAddress=un,exports.isValidApiKeyRole=pi,exports.isValidBanDuration=Ii,exports.isValidBanReason=_i,exports.isValidChatContent=function(e){return!!Rn(e)&&(e.length>=or.CHAT_MESSAGE.MIN_LENGTH&&e.length<=or.CHAT_MESSAGE.MAX_LENGTH)},exports.isValidChatTokenName=function(e){return!!Rn(e)&&Jn.PATTERN.test(e)},exports.isValidInviteCode=Tl,exports.isValidInviteStatus=Al,exports.isValidLaunchTokenData=function(e){return Vs(e).success},exports.isValidModeratorRole=El,exports.isValidTokenBanReason=$d,exports.isValidTokenName=function(e,t){if("string"!=typeof e)return!1;const n=e.trim();return 0!==n.length&&t.PATTERN.test(n)},exports.isViewerCountEvent=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"number"==typeof t.viewerCount},exports.isoDateStringSchema=Pr,exports.launchTokenDataSchema=es,exports.mergeSafePaginationOptions=function(e,t){return Vu({...e,...t})},exports.nonNegativeDecimalStringSchema=_r,exports.normalizeAddressInput=dn,exports.normalizeDataWithMapping=function(e,t){return e.map(e=>{const n={};for(const[r,s]of Object.entries(t)){const t=s(e);void 0!==t&&(n[r]=t)}return n})},exports.normalizeErrorMessage=function(e,t){return e.toLowerCase().includes(t.toLowerCase())},exports.normalizeLimit=Jo,exports.normalizeTokenKey=function(e){return e.trim().toUpperCase()},exports.normalizeTokenName=Kt,exports.normalizeTokenSymbol=Ht,exports.optionalUrlSchema=Cr,exports.pageNumberSchema=Dr,exports.paginationResultMetaSchema=ms,exports.parseHttpErrorResponse=function(e){const t={statusCode:0,errorMessage:"Unknown error",raw:e};if(null==e)return t;const n=e;let r=t.statusCode;"number"==typeof n.status?r=n.status:"number"==typeof n.statusCode?r=n.statusCode:"number"==typeof n.code&&(r=n.code);let s,o=t.errorMessage;"string"==typeof n.message?o=n.message:"string"==typeof n.error?o=n.error:e instanceof Error?o=e.message:"string"==typeof e&&(o=e);const i=n.response;if(i){const e=i.data;if("object"==typeof e&&null!==e){s=e;const t=e;"string"==typeof t.message?o=t.message:"string"==typeof t.error&&(o=t.error)}}const a={statusCode:r,errorMessage:o,raw:e};return null!=s&&(a.errorData=s),a},exports.parseLaunchpadVaultAddress=ea,exports.percentileIndexCalculation=function(e,t){if(0===e.length)return-1;if(t<0||t>100)throw new Error(`Percentile must be between 0 and 100, got: ${t}`);const n=(e.length-1)*(t/100),r=Math.floor(n);return Math.min(r,e.length-1)},exports.poolFetchTypeSchema=ns,exports.poolPaginationSchema=us,exports.positiveDecimalStringSchema=wr,exports.priceTickRangeMapping=function(e,t,n=60){const r=Eo(e),s=Eo(t);if(r.isLessThanOrEqualTo(0)||s.isLessThanOrEqualTo(0))throw new Error("Prices must be positive");if(r.isGreaterThanOrEqualTo(s))throw new Error(`minPrice must be < maxPrice, got: ${r.toString()} >= ${s.toString()}`);const o=Math.floor(To(r)),i=Math.ceil(To(s)),c=Math.floor(o/n)*n,l=Math.ceil(i/n)*n;return{minTick:c,maxTick:l,actualMinPrice:new a(1.0001).pow(c),actualMaxPrice:new a(1.0001).pow(l)}},exports.privateKeySchema=Gr,exports.registerInterval=function(e,t){const n=e;return Qu.set(n,{createdAt:Date.now(),label:t}),n},exports.requireNonNegative=function(...e){e.forEach(e=>{if(e.isNaN())throw It("value","NaN");if(!e.isFinite())throw wt("value","finite");if(e.isLessThan(0))throw kt("value","0",e.toString())})},exports.requirePositive=yo,exports.requirePositiveWithContext=bo,exports.retryableHttpRequest=async function(e,t){const n=t?.maxRetries??3,r=t?.backoffMs??100,s=t?.retryableStatus??[429,503,504];let o,i=0;for(;i<=n;)try{return await e()}catch(e){o=e,i++;const t=qu(e),a=s.includes(t);if(i>n||!a)throw e;const c=r*Math.pow(2,i-1);await new Promise(e=>setTimeout(e,c))}throw o},exports.reverseBondingCurveConfigSchema=Zr,exports.reverseBondingCurveConfigurationSchema=Is,exports.roleHasSufficientPermission=function(e,t){return e===di.MANAGER?t!==di.OWNER:e===di.OWNER||e===t},exports.roundTickBoundaries=function(e,t,n){if(e>=t)throw new Error(`tickLower must be < tickUpper, got: ${e} >= ${t}`);if(n<=0)throw new Error(`tickSpacing must be > 0, got: ${n}`);return{tickLower:Math.floor(e/n)*n,tickUpper:Math.ceil(t/n)*n}},exports.roundTickToSpacing=function(e,t){if(t<=0)throw new Error(`tickSpacing must be > 0, got: ${t}`);return Math.floor(e/t)*t},exports.safeDivideWithMinimum=function(e,t,n,r="0"){const s=Eo(t);if(vo(s))return Eo(r);const o=Eo(e).dividedBy(s);if(null!=n){const e=Eo(n);if(e.isLessThan(0))throw new Error(`minimum must be >= 0, got: ${e.toString()}`);if(o.isLessThan(e))return e}return o},exports.searchQuerySchema=vr,exports.sellTokensDataSchema=vs,exports.standardLimitSchema=Or,exports.standardPaginationSchema=cs,exports.timestampSchema=Br,exports.toBackendAddressFormat=cn,exports.toBackendAddressFromEthers=En,exports.tokenCategorySchema=Qr,exports.tokenCollectionSchema=Jr,exports.tokenDescriptionSchema=Ar,exports.tokenListOptionsSchema=Ds,exports.tokenNameSchema=pr,exports.tokenSymbolSchema=Er,exports.tokenUrlsSchema=Xr,exports.tradeCalculationMethodSchema=Ns,exports.tradeCalculationTypeSchema=bs,exports.tradeLimitSchema=Mr,exports.tradeListParamsSchema=ys,exports.tradePaginationSchema=ds,exports.tradePaginationWithFiltersSchema=gs,exports.tradeTypeBackendSchema=Es,exports.tradeTypeSchema=fs,exports.transactionIdSchema=$r,exports.transformRawApiTokenToDomainModel=function(e){if(null==e||"object"!=typeof e)throw new Error("Token must be an object");const t=e,n=(Rn(t.name)?t.name:void 0)??(Rn(t.tokenName)?t.tokenName:void 0)??"";if(!Rn(n))throw new Error("Token name is required and must be a non-empty string");const r=(Rn(t.symbol)?t.symbol:void 0)??(Rn(t.tokenSymbol)?t.tokenSymbol:void 0)??"";if(!Rn(r))throw new Error("Token symbol is required and must be a non-empty string");let s=8;"number"==typeof t.decimals&&t.decimals>=0&&(s=Math.floor(t.decimals));const o={name:n,symbol:r,decimals:s};return Rn(t.address)&&(o.address=t.address),"boolean"==typeof t.verified&&(o.verified=t.verified),o},exports.trimmedLengthValidation=function(e){return null==e||"string"!=typeof e||0===e.trim().length},exports.uniqueKeySchema=Kr,exports.unregisterAllIntervals=function(){const e=Qu.size;return Qu.clear(),e},exports.unregisterInterval=function(e){const t=e;Qu.delete(t)},exports.updateProfileDataSchema=Os,exports.uploadProfileImageOptionsSchema=xs,exports.urlSchema=Ir,exports.userLimitSchema=xr,exports.userPaginationSchema=ls,exports.userRef=Zt,exports.userTokenNameSchema=Tr,exports.userTokenTypeSchema=Cs,exports.userTokensPaginationSchema=hs,exports.validateAddress=Bs,exports.validateAmountString=$s,exports.validateBanTokenOptions=Kd,exports.validateBuyTokensData=to,exports.validateCalculatePreMintData=io,exports.validateChatMessageId=function(e){if(!Rn(e))throw Tt("id","Message ID");if(!ir.CHAT_MESSAGE.PATTERN.test(e))throw new rt("Invalid message ID format. Expected: chat-{timestamp}-{uuid}","id",nt.INVALID_FORMAT)},exports.validateCheckPoolOptions=zs,exports.validateConstrainedEnumVariant=function(e,t,n){if(!t.includes(e))throw new rt(`${n} must be one of [${t.map(e=>String(e)).join(", ")}], received "${e}"`,n,"INVALID_ENUM_VALUE")},exports.validateCreateApiKeyOptions=mi,exports.validateCreateChatMessageOptions=function(e){if(!Rn(e.tokenName))throw Tt("tokenName");Pn(e.tokenName,"tokenName",Xn),Ih(e.content)},exports.validateCreateCommentOptions=function(e){if(!Rn(e.tokenName))throw Tt("tokenName","Token name");Pn(e.tokenName,"tokenName",Xn),_h(e.content)},exports.validateCreateMessageOptions=function(e){if(void 0===e.type||null===e.type)throw Tt("type");if(e.type!==ol.CHAT_MESSAGE&&e.type!==ol.COMMENT)throw new rt(`type must be one of: ${Object.values(ol).join(", ")}`,"type",nt.INVALID_VALUE);if(!Rn(e.tokenName))throw Tt("tokenName");if(Pn(e.tokenName,"tokenName",Xn),!Rn(e.content))throw Tt("content");if(0===e.content.trim().length)throw Ot("content","Content");const t=e.type===ol.CHAT_MESSAGE?il.CONTENT.CHAT_MAX_LENGTH:il.CONTENT.COMMENT_MAX_LENGTH;if(e.content.length>t)throw Rt("content",t,e.content.length)},exports.validateCreateModeratorInviteOptions=function(e){const t=[],n=e.inviteScope??gl.TOKEN;return void 0===e.inviteScope||bl(e.inviteScope)||ft(t,()=>{throw Ct("inviteScope",e.inviteScope,pl,"Invite scope")}),n===gl.TOKEN?ft(t,()=>{Fn(e.tokenName??"","tokenName",Xn)}):n===gl.ALL_OWNER_TOKENS&&void 0!==e.tokenName&&""!==e.tokenName&&t.push("Token name should not be provided for ALL_OWNER_TOKENS scope invites"),El(e.role)||ft(t,()=>{throw Ct("role",e.role,hl,"Role")}),void 0!==e.description&&""!==e.description&&ft(t,()=>{wn(e.description,or.DESCRIPTION.MAX_LENGTH,"description")}),void 0===e.expiresAt||""===e.expiresAt||Qt(e.expiresAt)||ft(t,()=>{throw function(e,t="a valid date",n){const r=Et(e,n);return new rt(`${r} must be ${t}`,e,"INVALID_DATE")}("expiresAt","ISO 8601 format")}),t},exports.validateCreateOverseerDirectOptions=jl,exports.validateCreateOverseerInviteOptions=Bl,exports.validateCreateTradeData=eo,exports.validateDecimalRangeStrict=function(e,t,n,r){const s="string"==typeof e?parseFloat(e):e;if(!isFinite(s))throw new rt(`${r} must be a valid finite number between ${t} and ${n}`,r,"INVALID_NUMBER");if(s<t||s>n)throw Nt(r,t,n,s,r)},exports.validateFeePortionConstraints=Cn,exports.validateFetchGalaBalanceOptions=Xs,exports.validateFetchMessagesOptions=function(e){const t=void 0!==e.type,n=void 0!==e.tokenName&&""!==e.tokenName,r=void 0!==e.userAddress&&""!==e.userAddress;if(!t&&!n&&!r)throw Dt(["type","tokenName","userAddress"]);if(void 0!==e.type&&e.type!==ol.CHAT_MESSAGE&&e.type!==ol.COMMENT)throw new rt(`type must be one of: ${Object.values(ol).join(", ")}`,"type",nt.INVALID_VALUE);sl(e.tokenName,e.userAddress),void 0!==e.pageSize&&Mn(0,void 0,rr,e.pageSize)},exports.validateFetchPoolDetailsData=ao,exports.validateFetchTokenBalanceOptions=Zs,exports.validateFullName=Ks,exports.validateGetAmountOptions=oo,exports.validateGetChatMessagesOptions=function(e){if(!(void 0!==e.tokenName&&""!==e.tokenName||void 0!==e.userAddress&&""!==e.userAddress))throw new rt("At least one of tokenName or userAddress is required","options",nt.REQUIRED);sl(e.tokenName,e.userAddress),void 0!==e.pageSize&&Mn(0,void 0,rr,e.pageSize)},exports.validateGetCommentsOptions=function(e){if(!(void 0!==e.tokenName&&""!==e.tokenName||void 0!==e.userAddress&&""!==e.userAddress))throw Dt(["tokenName","userAddress"]);void 0!==e.tokenName&&""!==e.tokenName&&Pn(e.tokenName,"tokenName",Xn),Mn(0,void 0,rr,e.pageSize,e.cursor)},exports.validateGetTokenBanOptions=Vd,exports.validateGetTradeOptions=ro,exports.validateGetTradesOptions=Vc,exports.validateImageUploadOptions=qs,exports.validateInviteCode=function(e){const t=[];return Rn(e)?Tl(e)||t.push("Invalid invite code format"):t.push(Tt("inviteCode","Invite code").message),t},exports.validateLaunchTokenData=lo,exports.validateListApiKeysOptions=Ai,exports.validateListModeratorInvitesOptions=function(e){const t=[];return ft(t,()=>{Fn(e.tokenName??"","tokenName",Xn)}),void 0===e.status||Al(e.status)||ft(t,()=>{throw Ct("status",e.status,fl,"Status")}),ft(t,()=>{Mn(0,void 0,tr,e.pageSize)}),t},exports.validateListOverseerInvitesOptions=Gl,exports.validateListOverseersOptions=$l,exports.validateListTokenBansOptions=Wd,exports.validateListUsersOptions=Vl,exports.validateMessageId=function(e){if(!Rn(e))throw Tt("id","Message ID");const t=ir.CHAT_MESSAGE.PATTERN.test(e),n=/^msg-\d{13}-[a-f0-9]{32}$/.test(e);if(!t&&!n)throw new rt("Invalid message ID format. Expected: chat-{timestamp}-{uuid} or msg-{timestamp}-{uuid}","id",nt.INVALID_FORMAT)},exports.validateMinMaxRelationship=function(e,t,n,r){const s="string"==typeof e?parseFloat(e):e,o="string"==typeof t?parseFloat(t):t;if(!isFinite(s))throw new rt(`${n} must be a valid finite number`,n,"INVALID_MIN_VALUE");if(!isFinite(o))throw new rt(`${r} must be a valid finite number`,r,"INVALID_MAX_VALUE");if(s>o)throw new rt(`${n} (${s}) must be less than or equal to ${r} (${o})`,n,"INVALID_RANGE")},exports.validateOptionalTokenName=function(e,t,n){if(null==e)return;if("string"!=typeof e)throw _t(t,"a string",e);const r=e.trim();if(0!==r.length&&!n.PATTERN.test(r))throw new rt(`${t} must be ${n.DESCRIPTION}`,t,nt.INVALID_FORMAT)},exports.validateOverseerInviteCode=Kl,exports.validateOverseerInviteId=Wl,exports.validateOverseerWalletAddress=Hl,exports.validatePaginationParams=function(e,t,n){if("number"!=typeof e||!Number.isInteger(e)||e<0)throw _t("offset","a non-negative integer",e);_n(t,"limit")},exports.validateSearchQuery=Hs,exports.validateSellTokensData=no,exports.validateSortOrderDirection=function(e,t){if("ASC"!==e&&"DESC"!==e)throw new rt(`${t} must be either 'ASC' or 'DESC'`,t,"INVALID_ENUM_VALUE")},exports.validateTokenDescription=Ps,exports.validateTokenListOptions=Ys,exports.validateTokenName=Pn,exports.validateTokenSymbol=Fs,exports.validateTokenUrls=js,exports.validateTradeListParams=so,exports.validateUnbanTokenOptions=Hd,exports.validateUpdateApiKeyOptions=fi,exports.validateUpdateChatMessageOptions=function(e){Ih(e.content)},exports.validateUpdateCommentOptions=function(e){_h(e.content)},exports.validateUpdateMessageOptions=function(e){if(!Rn(e.content))throw Tt("content");if(0===e.content.trim().length)throw Ot("content","Content");const t=Math.max(il.CONTENT.CHAT_MAX_LENGTH,il.CONTENT.COMMENT_MAX_LENGTH);if(e.content.length>t)throw Rt("content",t,e.content.length)},exports.validateUpdatePlatformConfigOptions=zl,exports.validateUpdateProfileData=Qs,exports.validateUpdateTokenConfigOptions=Mc,exports.validateUploadProfileImageOptions=Js,exports.validateUserTokenName=Ws,exports.validateVaultAddress=Gs,exports.vaultAddressSchema=kr,exports.wasModerationEscalated=function(e){return!0===e.escalatedFromQuick};
1
+ "use strict";var e=require("@gala-chain/gala-core-sdk"),t=require("ethers"),n=require("zod"),r=require("@gala-chain/gala-core-sdk/providers"),s=require("@gala-chain/api"),o=require("uuid"),i=require("socket.io-client"),a=require("bignumber.js"),c=require("axios");const l={UPLOAD_IMAGE:"/v1/tokens/:tokenName/image",FETCH_POOLS:"/v1/tokens",GET_TOKEN:"/v1/tokens/:tokenName",GET_TOKEN_DISTRIBUTION:"/v1/holders",CHART:"/v1/chart",GET_TRADES:"/v1/tokens/:tokenName/trades",GET_PROFILE:"/v1/users/:address",UPDATE_PROFILE:"/v1/users/me",GET_CURRENT_USER:"/v1/users/me/profile",UPLOAD_PROFILE_IMAGE:"/v1/users/me/image",GET_TOKEN_LIST:"/v1/users/:address/tokens",GET_TOKENS_HELD:"/v1/users/:address/tokens",GET_GALA_BALANCE:"/v1/users/:address/gala-balance",GET_REFERRAL_CODE:"/v1/connect/users/referrals/code",GET_MANAGED_TOKENS:"/v1/users/me/managed-tokens",VALIDATE_TOKEN:"/v1/utils/validate-token",UPDATE_TOKEN_CONFIG:"/v1/tokens/:tokenName",TOKEN_STATS:"/v1/tokens/:tokenName/stats",OEMBED:"/oembed",OEMBED_BUY_SELL:"/oembed/buy-sell/:tokenName",OEMBED_PROFILE:"/oembed/profile/:address"},d="/v1/users/referrals/url",u="/v1/users/referrals",h="/v1/users/referrals/summary",g="/v1/tokens/:tokenName/start-stream",p="/v1/tokens/:tokenName/stop-stream",m="/v1/tokens/:tokenName/stream/disable",f="/v1/tokens/:tokenName/stream/enable",E="/v1/tokens/:tokenName/reset-key",A="/v1/tokens/:tokenName/recordings",T="/v1/tokens/:tokenName/recordings/:assetId/download",v="/v1/tokens/:tokenName/recordings/:assetId",S="/v1/tokens/:tokenName/simulcasts",y="/v1/tokens/:tokenName/simulcasts",b="/v1/tokens/:tokenName/simulcasts/:targetId",N="/v1/config",k="/v1/config",w="/v1/config",_="/v1/tokens/:tokenName/role",I="/v1/roles",C="/v1/permissions",D="/v1/tokens/:tokenName/credentials",R="/auth/login",O="/auth/logout",x="/auth/refresh",M="/auth/session",L="/v1/tokens/:tokenName/bans",U="/v1/tokens/:tokenName/bans",F="/v1/tokens/:tokenName/bans/:userAddress",P="/v1/tokens/:tokenName/bans/:userAddress",B="/v1/tokens/:tokenName/active-users",G="/v1/user-bans",$="/v1/user-bans",K="/v1/user-bans/:userAddress",H="/v1/user-bans/:userAddress",W={CREATE:"/v1/api-keys",LIST:"/v1/api-keys",GET:"/v1/api-keys/:id",UPDATE:"/v1/api-keys/:id",REVOKE:"/v1/api-keys/:id"},V="/v1/moderator-invites",j="/v1/moderator-invites/claim",q="/v1/moderated-tokens",z="/v1/moderator-invites",Y="/v1/moderator-invites/:id",X="/v1/moderator-invites/:id/role",Q="/v1/moderator-invites/:id",J="/v1/moderator-invites/code/:code",Z={CREATE:"/v1/content-flags",LIST:"/v1/content-flags",DISMISS:"/v1/content-flags/:id/dismiss",ACTION:"/v1/content-flags/:id/action"},ee="/v1/overseer-invites",te="/v1/overseer-invites",ne="/v1/overseer-invites/code/:code",re="/v1/overseer-invites/claim",se="/v1/overseer-invites/:id",oe="/v1/overseers",ie="/v1/overseers",ae="/v1/overseers/:address",ce="/v1/overseers/me",le="/v1/overseer-summary",de="/v1/overseer-summary/bans",ue="/v1/overseer-summary/token-bans",he="/v1/overseer-summary/invites",ge="/v1/overseer-summary/flags",pe="/v1/overseer-summary/users",me="/v1/users",fe="/v1/users/:address/summary",Ee="/v1/cache/flush/address/:address",Ae="/v1/cache/flush/token/:tokenName",Te="/v1/cache/flush/all",ve="/v1/cache/flush/wallet-aliases/:address",Se="/v1/cache/flush/wallet-aliases",ye="/v1/token-bans",be="/v1/token-bans",Ne="/v1/token-bans/:tokenName",ke="/v1/token-bans/:tokenName",we="/v1/reactions",_e="/v1/reactions",Ie="/v1/trades",Ce={GET_MESSAGES:"/v1/messages",CREATE_MESSAGE:"/v1/messages",UPDATE_MESSAGE:"/v1/messages/:id",DELETE_MESSAGE:"/v1/messages/:id",GET_PINNED:"/v1/messages/pinned",PIN_MESSAGE:"/v1/messages/:id/pin",UNPIN_MESSAGE:"/v1/messages/:id/pin",GET_MESSAGE_STATS:"/v1/messages/stats"},De="/v1/restricted-token-names",Re="/v1/restricted-token-names",Oe="/live/:tokenName/chat",xe="/live/:tokenName/chat",Me="/live/:tokenName/chat",Le="/live/:tokenName/chat/slow-mode",Ue="/v1/events",Fe="/v1/events/stats",Pe="/health",Be={GET_SETTINGS:"/v1/ai-moderation/settings",UPDATE_SETTINGS:"/v1/ai-moderation/settings",GET_MODERATION:"/v1/ai-moderation/flags/:flagId",TRIGGER_MODERATION:"/v1/ai-moderation/flags/:flagId/analyze",GET_STATUS:"/v1/ai-moderation/status"},Ge="/v1/stats",$e="/v1/trading/fee",Ke="/v1/trading/sale-details",He="/v1/trading/quote",We="/v1/trading/premint-quote",Ve={GET_LEADERBOARD:"/weekly-challenge",GET_TOKEN_HISTORY:"/weekly-challenge/history/:vaultAddress"},je="/v1/notifications/register",qe="/v1/notifications/unregister",ze="/v1/notifications/preferences",Ye="/v1/notifications/preferences",Xe="/v1/config/client-flags",Qe={NATIVE:"native",EXACT:"exact"},Je=["RECENT","POPULAR","RECORDINGS","SECONDS_STREAMED"],Ze=["IDLE","ACTIVE","DISABLED"],et=100,tt={LOCAL:"local",EXTERNAL:"external"},nt={REQUIRED:"REQUIRED",INVALID_TYPE:"INVALID_TYPE",INVALID_VALUE:"INVALID_VALUE",INVALID_FORMAT:"INVALID_FORMAT",TOO_SHORT:"TOO_SHORT",TOO_LONG:"TOO_LONG",TOO_LARGE:"TOO_LARGE",TOO_SMALL:"TOO_SMALL",EMPTY_ARRAY:"EMPTY_ARRAY",ARRAY_TOO_LARGE:"ARRAY_TOO_LARGE",ZERO_VALUE:"ZERO_VALUE",INVALID_TICK_SPACING:"INVALID_TICK_SPACING",INVALID_FEE_TIER:"INVALID_FEE_TIER",INVALID_RANGE:"INVALID_RANGE",INVALID_PARAMETERS:"INVALID_PARAMETERS",NOT_FOUND:"NOT_FOUND",INVALID_DATA:"INVALID_DATA"};class rt extends Error{constructor(e,t,n){super(e),this.field=t,this.code=n,this.name="ValidationError"}}function st(e){return"object"==typeof e&&null!==e}function ot(e){if(null==e||""===e)return{};if(!st(e)||Array.isArray(e))return{body:e};const t=Reflect.get(e,"message"),n="string"==typeof t?t:Array.isArray(t)&&t.every(e=>"string"==typeof e)?t.join(","):void 0,r=Reflect.get(e,"error"),s=Reflect.get(e,"details");return{...void 0===n?{}:{serverMessage:n},..."string"==typeof r&&""!==r?{serverError:r}:{},...void 0===s?{}:{details:s},body:e}}function it(e){if(e instanceof at)return{...void 0===e.serverMessage?{}:{serverMessage:e.serverMessage},...void 0===e.serverError?{}:{serverError:e.serverError},...void 0===e.details?{}:{details:e.details},...void 0===e.body?{}:{body:e.body}};const t=function(e){if(!st(e))return;const t=Reflect.get(e,"response");return st(t)?t:void 0}(e);return void 0===t?{}:ot(Reflect.get(t,"data"))}class at extends Error{constructor(e,t,n,r=it(n)){super(e),this.name="NetworkError",this.statusCode=t,this.originalError=n,this.serverMessage=r.serverMessage,this.serverError=r.serverError,this.details=r.details,this.body=r.body}}class ct extends Error{constructor(e,t){super(e),this.field=t,this.name="ConfigurationError"}}class lt extends Error{constructor(e,t,n){super(e),this.transactionId=t,this.code=n,this.name="TransactionError"}}function dt(e){return e instanceof Error}function ut(e){return dt(e)||function(e){return"object"==typeof e&&null!==e&&"message"in e&&"string"==typeof e.message}(e)?e.message:"string"==typeof e?e:String(e)}function ht(e){return dt(e)||"object"==typeof e&&null!==e&&"stack"in e&&"string"==typeof e.stack?e.stack:void 0}function gt(e){if(function(e){return"object"==typeof e&&null!==e&&"code"in e&&("string"==typeof e.code||"number"==typeof e.code)}(e))return e.code}function pt(e){return"object"==typeof e&&null!==e&&"message"in e&&("response"in e||"request"in e||"config"in e)}function mt(e,t){if(null==e||"object"!=typeof e)throw new Error(`${t}: No response - expected object, got ${typeof e}`);const n=e;if(!("Status"in n))throw new Error(`${t}: Response missing 'Status' property`);const r=n.Status;if("number"!=typeof r)throw new Error(`${t}: Response Status must be a number, got ${typeof r}`);if(1!==r)throw new Error(`${t}: Response status indicates failure (Status: ${r})`);return n}function ft(e,t,n){try{t()}catch(t){if(!function(e){return e instanceof Error&&"ValidationError"===e.name}(t))throw t;{const n=t.message;e.push(n)}}}function Et(e,t){return void 0!==t?t:e.charAt(0).toUpperCase()+e.slice(1)}function At(e,t){return new rt(`Token "${e}" not found. Please verify the token name is correct.`,"tokenName","TOKEN_NOT_FOUND")}function Tt(e,t){const n=Et(e,t);return new rt(`${n} is required`,e,"REQUIRED")}function vt(e,t,n){const r=Et(e,n);return new rt(`${r} must be ${t}`,e,"INVALID_FORMAT")}function St(e,t,n,r){return new at(e,t,n,r)}function yt(e,t){return new ct(e,t)}function bt(e,t,n){return new lt(e,t,n)}function Nt(e,t,n,r,s){const o=Et(e,s);return new rt(`${o} must be between ${t} and ${n}${void 0!==r?`, received: ${r}`:""}`,e,"OUT_OF_RANGE")}function kt(e,t,n,r){const s=Et(e,r);return new rt(`${s} must be at least ${t}${void 0!==n?`, received: ${n}`:""}`,e,"TOO_SMALL")}function wt(e,t,n,r){const s=Et(e,r);return new rt(`${s} must be at most ${t}${void 0!==n?`, received: ${n}`:""}`,e,"TOO_LARGE")}function _t(e,t,n,r){const s=Et(e,r),o=void 0!==n?`, received: ${"object"==typeof n?"object":String(n)}`:"";return new rt(`${s} must be ${t}${o}`,e,"INVALID_TYPE")}function It(e,t,n){const r=Et(e,n);return new rt(`${r} must be a valid number${void 0!==t?`: "${t}"`:""}`,e,"INVALID_NUMBER")}function Ct(e,t,n,r){const s=Et(e,r);return new rt(`Invalid ${s}: ${t}. Must be one of: ${n.join(", ")}`,e,"INVALID_ENUM")}function Dt(e,t){if(e.length<2)return Tt(void 0!==e[0]&&""!==e[0]?e[0]:"field");let n;if(2===e.length)n=e.join(" or ");else{n=`${e.slice(0,-1).join(", ")} or ${e[e.length-1]??"field"}`}return new rt(`At least one of ${n} must be provided`,e[0],"REQUIRED")}function Rt(e,t,n,r){const s=Et(e,r);return new rt(`${s} must be at most ${t} characters${void 0!==n?`, received: ${n}`:""}`,e,"TOO_LONG")}function Ot(e,t){const n=Et(e,t);return new rt(`${n} cannot be empty`,e,"EMPTY_STRING")}function xt(e){return null!=e&&"object"==typeof e&&"data"in e}function Mt(e,t,n=!1){const r=!0===e.error,s=n&&(null===e.data||void 0===e.data);if(r||s){const n=e?.statusCode??e.status??void 0;throw St(e?.message??t,n,void 0,r?ot(e):void 0)}}function Lt(e){if(xt(e))return e.data}function Ut(e,t="No data found in response"){if(!xt(e))throw St(t);const n=e.data;if(null==n)throw St(t);return n}async function Ft(e,t={}){return Gt(e,t,e=>{if(void 0===e.data)throw new rt(`${t.errorContext??"Operation failed"}: No data returned from API`,"data","NO_DATA");return e.data})}async function Pt(e,t={}){const{errorContext:n="Operation failed",logger:r,debugLogEnabled:s=!1}=t;s&&r&&r.debug(`${n}: starting operation`);try{const t=await e();return s&&r&&r.debug(`${n}: completed successfully`),t}catch(e){throw r&&r.error(n,{error:e}),e}}async function Bt(e,t={}){return Gt(e,t,e=>e)}async function Gt(e,t,n){const{errorContext:r="Operation failed",logger:s,debugLogEnabled:o=!1}=t;o&&s&&s.debug(`${r}: starting operation`);try{const t=await e();if(null==t)throw new rt(`${r}: No response from server`,"response","NO_RESPONSE");return Mt(t,r,!0),o&&s&&s.debug(`${r}: completed successfully`),n(t)}catch(e){throw s&&s.error(r,{error:e}),e}}const $t={BASE_PRICE:1650667151e-14,PRICE_SCALING_FACTOR:1166069e-12,TRADING_FEE_FACTOR:.001,GAS_FEE:"1",DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY:1e7};function Kt(e){return e.trim().toLowerCase()}function Ht(e){return e.trim().toUpperCase()}var Wt;!function(e){e.DEBUG="DEBUG",e.INFO="INFO",e.WARN="WARN",e.ERROR="ERROR"}(Wt||(Wt={}));class Vt{constructor(e){this.levelPriority={[Wt.DEBUG]:0,[Wt.INFO]:1,[Wt.WARN]:2,[Wt.ERROR]:3},this.debugEnabled=e.debug,this.context=e.context??"SDK",this.minLevel=e.minLevel??(e.debug?Wt.DEBUG:Wt.INFO)}debug(e,t){this.log(Wt.DEBUG,e,t)}info(e,t){this.log(Wt.INFO,e,t)}warn(e,t){this.log(Wt.WARN,e,t)}error(e,t){this.log(Wt.ERROR,e,t)}log(e,t,n){if(this.levelPriority[e]<this.levelPriority[this.minLevel])return;if(e===Wt.DEBUG&&!this.debugEnabled)return;const r=`[${(new Date).toISOString()}] [${this.context}] [${e}]`,s=this.getConsoleMethod(e);void 0!==n?dt(n)?s(`${r} ${t}`,n.message,ht(n)??""):s(`${r} ${t}`,n):s(`${r} ${t}`)}getConsoleMethod(e){switch(e){case Wt.DEBUG:return console.debug;case Wt.INFO:return console.info;case Wt.WARN:return console.warn;case Wt.ERROR:return console.error;default:return console.log}}child(e){return new Vt({debug:this.debugEnabled,context:`${this.context}:${e}`,minLevel:this.minLevel})}isDebugEnabled(){return this.debugEnabled&&this.levelPriority[Wt.DEBUG]>=this.levelPriority[this.minLevel]}}function jt(e){return"string"==typeof e&&e.trim().length>0}function qt(e){return null==e||""===e}function zt(e){return null==e}const Yt=new Vt({debug:!1,context:"DateUtils"});function Xt(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())?(Yt.warn(`Invalid date string received: "${e}". Using fallback.`),new Date):t}catch(t){return Yt.warn(`Date parsing error for "${e}":`,t),new Date}}function Qt(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 Jt(t,n){if("string"==typeof t&&/^eth\|0[xX]/u.test(t))try{e.galaChainUserRef(t,n)}catch(t){if(e.isGalaError(t)&&"INVALID_ETH_USER_REF_PREFIX"===t.code)return t.message}}function Zt(t,n="address"){const r=Jt(t,n);if(void 0!==r)throw new rt(r,n,"INVALID_FORMAT");try{return e.galaChainUserRef(t,n)}catch{throw new rt(`${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 en(e,t="address"){return Zt(e,t).toLowerCase()}function tn(e,t){return pn(e)??en(e,t)}function nn(e){return sn(e)?en(e):e.trim().toLowerCase()}function rn(e,t){const n=e=>sn(e)?en(e):e.toLowerCase();return n(e)===n(t)}function sn(e){try{return Zt(e),!0}catch{return!1}}class on{toBackendFormat(e){if(!jt(e))throw new rt("Address is required and must be a string","address","REQUIRED");return Zt(e,"address")}toEthereumFormat(e){if(!jt(e))throw new rt("Backend address is required and must be a string","address","REQUIRED");if(!e.match(/^eth\|([0-9a-fA-F]{40})$/i)){const t=Jt(e,"address");if(void 0!==t)throw new rt(t,"address","INVALID_FORMAT");throw new rt(`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 Zt(e,"address")}normalizeForBackend(e){if(void 0!==e&&""!==e)return en(e,"address")}isValid(e){return sn(e)}assertValid(e,t="address"){if(!this.isValid(e)){const n=Jt(e,t);if(void 0!==n)throw new rt(n,t,"INVALID_FORMAT");throw new rt(`${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 jt(e)&&sn(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=sn(e)?Zt(e):void 0;if(void 0!==t&&t.startsWith("eth|"))return t.substring(4).toLowerCase();throw new rt(`Cannot extract hex from address: "${e}". Expected Ethereum or backend format.`,"address","INVALID_FORMAT")}}const an=new on;function cn(e){return an.toBackendFormat(e)}function ln(e){return an.toEthereumFormat(e)}function dn(e){return an.normalizeInput(e)}function un(e){return an.isValid(e)}const hn=/^(eth\|[a-f0-9]{40}|client\|[a-f0-9]{24})$/;function gn(e){return void 0!==pn(e)}function pn(e){if(!jt(e))return;const t=e.trim(),n=/^[0-9a-fA-F]{24}$/u.test(t)?`client|${t}`:t;if(!sn(n))return;const r=en(n);return hn.test(r)?r:void 0}function mn(e,t){if(!gn(e)){const n=Jt(e,t);if(void 0!==n)throw new rt(n,t,"INVALID_FORMAT");throw new rt(`${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 fn(e,t="address"){an.assertValid(e,t)}function En(e){const t="string"==typeof e?e:e.address;return an.toBackendFormat(t)}var An=Object.freeze({__proto__:null,AddressFormatter:on,assertBackendUserAddress:mn,assertValidWalletAddress:fn,backendUserAddress:pn,backendUserParam:tn,backendUserRef:en,ethZeroXRefusal:Jt,fromBackendAddressFormat:ln,isBackendUserAddress:gn,isUserRef:sn,isValidAddress:un,normalizeAddressInput:dn,sameUserAddress:rn,toBackendAddressFormat:cn,toBackendAddressFromEthers:En,userAddressFilter:nn,userRef:Zt});function Tn(e,t=0){if(qt(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(zt(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 Sn(e,t=0){if(zt(e))return t;if("number"==typeof e)return isNaN(e)?t:e;return Tn(String(e).replace("%","").trim(),t)}function yn(e,t=18){const n=Tn(e,0);if(0===n)return"0";return n.toFixed(t).replace(/\.?0+$/,"")}function bn(e){return yn(e,8)}function Nn(e){return yn(e,18)}function kn(e,t,n,r){if("number"!=typeof e)throw _t(r,"a number",e,r);if(e<t||e>n)throw Nt(r,t,n,e)}function wn(e,t,n){if("string"!=typeof e)throw _t(n,"a string",e,n);if(e.length>t)throw wt(n,t,e.length)}function _n(e,t){if("number"!=typeof e)throw _t(t,"a number",e,t);if(!Number.isInteger(e))throw _t(t,"an integer",e,t);if(e<=0)throw kt(t,1,e,t)}function In(e,t,n=!1){if("string"!=typeof e)throw _t(t,"a string",e,t);if(!n&&0===e.trim().length)throw Tt(t,`${t} (non-empty string)`)}function Cn(e,t,n){const r="string"==typeof e?parseFloat(e):e,s="string"==typeof t?parseFloat(t):t;if(!isFinite(r))throw new rt(`${n} minFee must be a valid finite number`,n,"INVALID_FEE_MINIMUM");if(!isFinite(s))throw new rt(`${n} maxFee must be a valid finite number`,n,"INVALID_FEE_MAXIMUM");if(r<.1)throw new rt(`${n} minFee must be >= 0.1, received ${r}`,n,"INVALID_FEE_MINIMUM");if(s>.5)throw new rt(`${n} maxFee must be <= 0.5, received ${s}`,n,"INVALID_FEE_MAXIMUM");if(r>s)throw new rt(`${n} minFee (${r}) must be <= maxFee (${s})`,n,"INVALID_FEE_RANGE")}const Dn={ETH_ADDRESS:/^0x[0-9a-fA-F]{40}$/,BACKEND_ADDRESS:/^eth\|[0-9a-fA-F]{40}$/},Rn=jt,On=qt,xn=zt;function Mn(e,t,n=100,r,s){if(void 0!==s&&"string"!=typeof s)throw new rt("cursor must be a string","cursor",nt.INVALID_TYPE);const o=r??t,i=void 0!==r?"pageSize":"limit";if(void 0!==o&&(_n(o,i),o>n))throw new rt(`${i} must be at most ${n}`,i,nt.TOO_LARGE)}function Ln(e){const t=Object.values(e);return e=>"string"==typeof e&&t.includes(e)}function Un(e){return Object.values(e)}function Fn(e,t,n){if(!Rn(e))throw Tt(t);const r=e.trim();if(0===r.length)throw Tt(t);if(r.length<n.MIN_LENGTH)throw Nt(t,n.MIN_LENGTH,n.MAX_LENGTH,r.length,`${t} length`);if(r.length>n.MAX_LENGTH)throw Nt(t,n.MIN_LENGTH,n.MAX_LENGTH,r.length,`${t} length`);if(!n.PATTERN.test(r))throw new rt(`${t} must be ${n.DESCRIPTION}`,t,nt.INVALID_FORMAT)}function Pn(e,t,n){if(null==e)throw Tt(t,t);if("string"!=typeof e)throw _t(t,"a string",e);const r=e.trim();if(0===r.length)throw Tt(t,t);if(!n.PATTERN.test(r))throw new rt(`${t} must be ${n.DESCRIPTION}`,t,nt.INVALID_FORMAT)}function Bn(e){return t=>{if(null==t||"object"!=typeof t)return!1;const n=t;for(const{field:t,type:r,nullable:s=!1,optional:o=!1,validator:i}of e){const e=n[t];if((!o||void 0!==e)&&(!s||null!==e)){if(typeof e!==r)return!1;if(i&&!i(e))return!1}}return!0}}const Gn={requiredString:e=>t=>xn(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(!On(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(!xn(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=>xn(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(!xn(n))return t.includes(n)?void 0:`${e} must be one of: ${t.join(", ")}`},requiredEnumValue:(e,t)=>n=>xn(n)?`${e} is required`:t.includes(n)?void 0:`${e} must be one of: ${t.join(", ")}`,isoDate:e=>t=>{if(!xn(t))return"string"!=typeof t?`${e} must be a string`:Qt(t)?void 0:`${e} must be a valid ISO 8601 date string`},walletAddress:(e,t=!1)=>n=>xn(n)?t?`${e} is required`:void 0:"string"!=typeof n?`${e} must be a string`:sn(n)?void 0:Jt(n,e)??`${e} must be a valid wallet address`};function $n(e){return""===e||0===e.trim().length}function Kn(e,t,n){if(!xn(e)){if("string"!=typeof e)throw _t(t,"a string",e,t);if(e.length>n)throw new rt(`${t} must be at most ${n} characters`,t,nt.TOO_LARGE)}}function Hn(e,t){xn(e)||function(e,t){const n=e instanceof Date?e:"string"==typeof e||"number"==typeof e?new Date(e):void 0;if(void 0===n)throw _t(t,"a date",e,t);if(isNaN(n.getTime()))throw new rt(`${t} must be a valid date`,t,nt.INVALID_FORMAT)}(e,t)}function Wn(e,t,n){try{_n(e,t)}catch{throw function(e,t,n,r="OPERATION_FAILED"){return new rt(`${e} failed: ${t}`,n,r)}(n,"must be a positive integer",t)}}function Vn(e,t,n="status"){void 0!==e&&function(e,t,n){const r=Object.values(t);if(!r.includes(e))throw new rt(`${n} must be one of: ${r.join(", ")}`,n,nt.INVALID_FORMAT)}(e,t,n)}class jn{constructor(e,t=!1,n){this.http=e,this.logger=new Vt({debug:t,context:this.constructor.name}),this.jwtAuth=n}setJwtAuth(e){this.jwtAuth=e}getJwtHeaders(){if(!this.jwtAuth){const e=globalThis;if("test"===e.process?.env?.NODE_ENV&&!this.isCalledFromUserCode())return{};throw new ct("JWT authentication required. Call sdk.login() first.")}return this.jwtAuth.getJwtHeaders()}isCalledFromUserCode(){const e=ht(new Error)??"";return!(!e.includes("expect")&&!e.includes("jest"))||!(!e.includes("tests/")&&!e.includes(".test.ts"))}validatePositiveInteger(e,t,n){Wn(e,t,n)}}class qn{constructor(e=!1,t){this.logger=t||new Vt({debug:e,context:this.constructor.name})}}class zn extends qn{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 Yn extends zn{constructor(e=!1){super(e)}normalizeKey(e){return Kt(e).replace(/\s+/g," ").replace(/[\u0000-\u001F\u007F-\u009F\u200B-\u200D\uFEFF]/g,"")}getLRUKey(){return this.cache.keys().next().value??null}updateCacheEntry(e,t){const n=this.cache.get(e);if(this.cache.has(e)&&this.cache.delete(e),this.cache.size>=Yn.MAX_CACHE_SIZE){const e=this.getLRUKey();null!==e&&this.cache.delete(e)}this.cache.set(e,{...n??{},...t,lastUpdated:Date.now()})}warmFromPoolData(e,t){const n=this.normalizeKey(e);this.updateCacheEntry(n,t)}set(e,t){const n=this.normalizeKey(e);this.updateCacheEntry(n,t)}getByName(e){const t=this.normalizeKey(e);return this.cache.get(t)}getMaxSupply(e){const t=this.normalizeKey(e),n=this.cache.get(t);return n?.maxSupply??$t.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY.toString()}has(e){const t=this.normalizeKey(e);return this.cache.has(t)}clear(e){if(void 0!==e&&""!==e){const t=this.normalizeKey(e);this.cache.delete(t)}else super.clear()}dumpAsObject(){const e={};return this.cache.forEach((t,n)=>{e[n]=t}),e}getStats(){const e=this.buildBaseStats(),{cacheSize:t,oldestEntry:n}=this.calculateCacheSizeAndAge();return{...e,totalTokens:e.totalItems,cacheSize:t,oldestEntry:n}}calculateCacheSizeAndAge(){let e=Date.now(),t=0;return this.cache.forEach((n,r)=>{n.lastUpdated<e&&(e=n.lastUpdated);let s=0;s+=2*r.length,void 0!==n.reverseBondingCurveMinFeeFactor&&(s+=8),void 0!==n.reverseBondingCurveMaxFeeFactor&&(s+=8),void 0!==n.reverseBondingCurveNetFeeFactor&&(s+=8),s+=8,void 0!==n.vaultAddress&&""!==n.vaultAddress&&(s+=2*n.vaultAddress.length),void 0!==n.maxSupply&&""!==n.maxSupply&&(s+=2*n.maxSupply.length),void 0!==n.symbol&&""!==n.symbol&&(s+=2*n.symbol.length),s+=32,t+=s}),{cacheSize:t,oldestEntry:this.cache.size>0?e:0}}getByTokenId(e){const t=`token:${Kt(e)}`;return this.cache.get(t)??null}setByTokenId(e,t){const n=`token:${Kt(e)}`;this.updateCacheEntry(n,t)}hasByTokenId(e){const t=`token:${Kt(e)}`;return this.cache.has(t)}}Yn.MAX_CACHE_SIZE=1e4;const Xn={MIN_LENGTH:1,MAX_LENGTH:25,PATTERN:/^[a-zA-Z0-9]{1,25}$/,DESCRIPTION:"1-25 letters and digits"},Qn={MIN_LENGTH:1,MAX_LENGTH:50,PATTERN:/^[a-zA-Z0-9]{1,50}$/,DESCRIPTION:"1-50 letters and digits"},Jn={MIN_LENGTH:1,MAX_LENGTH:255,PATTERN:/^[a-zA-Z0-9]{1,255}$/,DESCRIPTION:"1-255 letters and digits"},Zn={MIN_LENGTH:1,MAX_LENGTH:50,PATTERN:/^[\s\S]{1,50}$/,DESCRIPTION:"1-50 characters"},er={MIN_LENGTH:1,MAX_LENGTH:100,PATTERN:/^(?![\s\S]*<[^>]*>)[\s\S]{1,100}$/,DESCRIPTION:"1-100 characters without HTML"},tr=100,nr=100,rr=50,sr=100,or={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}},ir={CHAT_MESSAGE:{PATTERN:/^chat-\d{13}-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i},CONTENT_REACTION:{MAX_LENGTH:64,PATTERN:/^(msg-\d{13}-[a-f0-9]{32}|chat-\d{13}-[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})$/}},ar=60,cr=31536e3,lr={MAX_LENGTH:64,PATTERN:/^(galaswap-operation-|galaconnect-operation-)/},dr={PATTERN:/^[a-fA-F0-9]{64}$/,MAX_LENGTH:64},ur=1,hr=100,gr={FULL_NAME:{MIN_LENGTH:2,MAX_LENGTH:20,ALPHABETS_ONLY_PATTERN:/^[a-zA-Z]+(?: [a-zA-Z]+)?$/}},pr=n.z.string({message:"Token name is required"}).min(1,"Token name must be at least 1 character").regex(/^[a-zA-Z0-9]+$/,"Token name can only contain letters and numbers"),mr=pr.max(25,"Token name must be at most 25 characters"),fr=n.z.string({message:"Token name is required"}).min(1,"Token name must be at least 1 character").max(50,"Token name must be at most 50 characters"),Er=n.z.string({message:"Token symbol is required"}).min(1,"Token symbol must be at least 1 character").max(8,"Token symbol must be at most 8 characters").regex(/^[A-Z]{1,8}$/,"Token symbol must be uppercase letters only"),Ar=n.z.string({message:"Token description is required"}).min(1,"Token description is required").max(500,"Token description must be at most 500 characters"),Tr=n.z.string().min(1,"Token name must be at least 1 character").max(50,"Token name must be at most 50 characters"),vr=n.z.string().min(1,"Search query must be at least 1 character").max(100,"Search query must be at most 100 characters"),Sr=n.z.string().min(1,"Full name is required").max(100,"Full name must be at most 100 characters").regex(/^[a-zA-Z\s]+$/,"Full name can only contain letters and spaces"),yr=n.z.string().regex(Dn.BACKEND_ADDRESS,"Address must be in format: eth|[40-hex-chars]"),br=n.z.string().regex(Dn.ETH_ADDRESS,"Invalid Ethereum address format"),Nr=n.z.string().refine(e=>sn(e),{error:e=>Jt(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=>Zt(e)),kr=n.z.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"),wr=n.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>Tn(e,0)>0,"Amount must be greater than zero"),_r=n.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>Tn(e,0)>=0,"Amount must be zero or greater"),Ir=n.z.string().url("Must be a valid URL").regex(/^https?:\/\//,"URL must start with http:// or https://"),Cr=n.z.string().optional().refine(e=>void 0===e||""===e||/^https?:\/\/.+\..+/.test(e),"Must be a valid URL if provided"),Dr=n.z.number().int("Page must be an integer").min(1,"Page must be at least 1").max(1e3,"Page must be at most 1000").default(1);function Rr(e=100){return n.z.number().int("Limit must be an integer").min(1,"Limit must be at least 1").max(e,`Limit must be at most ${e}`).default(10)}const Or=Rr(100),xr=Rr(20),Mr=Rr(20),Lr=n.z.number().int("File size must be an integer").min(1,"File must be at least 1 byte").max(10485760,"File must be at most 10MB"),Ur=n.z.string().max(255,"Filename must be at most 255 characters"),Fr=n.z.enum(["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"]),Pr=n.z.string().datetime("Must be a valid ISO 8601 date string"),Br=n.z.number().int("Timestamp must be an integer").min(0,"Timestamp must be non-negative"),Gr=n.z.string().regex(/^0x[a-fA-F0-9]{64}$/,"Private key must be format: 0x + 64 hex characters"),$r=n.z.string().regex(/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/,"Transaction ID must be in UUID format"),Kr=n.z.string().regex(/^galaconnect-operation-[a-z0-9-]+$/,"Unique key must be format: galaconnect-operation-{unique-id}"),Hr=[".png",".jpg",".jpeg",".gif",".webp",".svg"],Wr=n.z.object({file:n.z.union([n.z.instanceof(File),n.z.instanceof(Buffer)]),name:Ur,size:Lr,type:Fr}),Vr=n.z.instanceof(File).refine(e=>e.size>=1&&e.size<=10485760,"File size must be between 1 byte and 10MB").refine(e=>["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"].includes(e.type),"File must be a valid image type (PNG, JPG, JPEG, GIF, WebP, or SVG)").refine(e=>e.name.length<=255,"Filename must be at most 255 characters"),jr=n.z.instanceof(Buffer).refine(e=>e.length>=1&&e.length<=10485760,"Buffer size must be between 1 byte and 10MB"),qr=n.z.union([Vr,jr]),zr=n.z.enum([".png",".jpg",".jpeg",".gif",".webp",".svg"]),Yr=Ur.refine(e=>{const t=e.slice(e.lastIndexOf(".")).toLowerCase();return Hr.includes(t)},`Filename must end with one of: ${Hr.join(", ")}`),Xr=n.z.object({websiteUrl:Cr,telegramUrl:Cr,twitterUrl:Cr,instagramUrl:Cr,facebookUrl:Cr,redditUrl:Cr,tiktokUrl:Cr}).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"),Qr=n.z.string().min(1,"Token category must not be empty").default("Unit"),Jr=n.z.string().min(1,"Token collection must not be empty").default("Token"),Zr=n.z.object({minFeePortion:n.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal string").refine(e=>Tn(e,0)>=.1,"Minimum fee must be >= 0.1").refine(e=>Tn(e,0)<=.5,"Minimum fee must be <= 0.5").default("0.1"),maxFeePortion:n.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal string").refine(e=>Tn(e,0)>=.1,"Maximum fee must be >= 0.1").refine(e=>Tn(e,0)<=.5,"Maximum fee must be <= 0.5").default("0.5")}).refine(e=>Tn(e.maxFeePortion,0)>=Tn(e.minFeePortion,0),{message:"Maximum fee must be >= minimum fee",path:["maxFeePortion"]}),es=n.z.object({tokenName:pr,tokenSymbol:Er,tokenDescription:Ar,tokenImage:n.z.union([n.z.instanceof(File),n.z.instanceof(Buffer),n.z.string().url("Token image must be a valid URL")]).optional(),preBuyQuantity:_r.default("0"),websiteUrl:Cr,telegramUrl:Cr,twitterUrl:Cr,instagramUrl:Cr,facebookUrl:Cr,redditUrl:Cr,tiktokUrl:Cr,tokenCategory:Qr,tokenCollection:Jr,reverseBondingCurveConfiguration:Zr.optional(),saleStartTime:n.z.number().int().positive().optional(),privateKey:Gr.optional()}),ts=n.z.object({file:n.z.union([n.z.instanceof(File),n.z.instanceof(Buffer)]),tokenName:pr}),ns=n.z.enum(Je),rs=n.z.object({tokenName:fr.optional(),symbol:Er.optional()}).refine(e=>void 0!==e.tokenName||void 0!==e.symbol,"At least one of tokenName or symbol is required"),ss=n.z.enum(["NATIVE","MEME"]),os=n.z.enum(["IN","OUT"]),is=n.z.object({from:n.z.number().int("From timestamp must be an integer").min(173e6,"From timestamp must be at least 173000000"),to:n.z.number().int("To timestamp must be an integer").min(173e6,"To timestamp must be at least 173000000"),resolution:n.z.number().int("Resolution must be an integer").min(1,"Resolution must be at least 1"),tokenName:mr}),as=n.z.object({tokenName:mr,slippageToleranceFactor:n.z.number().min(0).max(1).optional(),maxAcceptableReverseBondingCurveFeeSlippageFactor:n.z.number().min(0).max(1).optional(),privateKey:Gr.optional()}),cs=n.z.object({offset:n.z.number().int().min(0).default(0),pageSize:n.z.number().int().min(1).max(100).default(10)}),ls=n.z.object({offset:n.z.number().int().min(0).default(0),pageSize:n.z.number().int().min(1).max(20).default(10)}),ds=n.z.object({offset:n.z.number().int().min(0).default(0),pageSize:n.z.number().int().min(1).max(20).default(10)}),us=cs.extend({type:n.z.enum(["RECENT","POPULAR"]).optional(),tokenName:n.z.string().min(1).max(50).optional(),search:n.z.string().min(1).max(100).optional()}),hs=ls.extend({tokenName:n.z.string().min(1).max(50).optional(),search:n.z.string().min(1).max(100).optional()}),gs=ds.extend({tradeType:n.z.enum(["BUY","SELL"]).optional(),tokenName:n.z.string().min(1).max(50).optional(),userAddress:n.z.string().refine(sn,{error:e=>Jt(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:n.z.string().datetime().optional(),endDate:n.z.string().datetime().optional(),sortOrder:n.z.enum(["ASC","DESC"]).default("DESC")}),ps={page:n.z.number().int().min(1),limit:n.z.number().int().min(1),total:n.z.number().int().min(0),totalPages:n.z.number().int().min(0),hasNext:n.z.boolean(),hasPrevious:n.z.boolean()},ms=n.z.object(ps);const fs=n.z.enum(["buy","sell"]),Es=n.z.enum(["BUY","SELL"]),As=n.z.object({tradeType:fs,tokenAmount:wr,vaultAddress:kr,userAddress:Nr,slippageTolerance:wr.optional(),deadline:n.z.number().int().positive().optional()}),Ts=n.z.object({tokenSymbol:Er,nativeTokenQuantity:wr,expectedToken:wr,maxAcceptableReverseBondingCurveFee:_r.default("0").optional()}),vs=n.z.object({tokenSymbol:Er,tokenQuantity:wr,expectedNativeToken:wr,maxAcceptableReverseBondingCurveFee:_r.default("0").optional()}),Ss=ds.extend({tokenName:Tr.optional()}),ys=n.z.object({page:n.z.number().int().min(1).max(1e3).default(1).optional(),limit:n.z.number().int().min(1).max(20).default(10).optional()}),bs=n.z.enum(["NATIVE","MEME"]),Ns=n.z.enum(["IN","OUT"]),ks=n.z.object({type:bs,method:Ns,vaultAddress:kr,amount:wr}),ws=n.z.object({nativeTokenQuantity:wr}),_s=n.z.object({vaultAddress:kr}),Is=n.z.object({minFeePortion:wr,maxFeePortion:wr}),Cs=n.z.enum(["both","held","created"]),Ds=ls.extend({type:Cs.optional(),address:Nr.optional(),search:vr.optional(),tokenName:Tr.optional()}),Rs=n.z.object({address:Nr.optional(),refresh:n.z.boolean().optional()}),Os=n.z.object({profileImage:n.z.string().nullable().optional(),fullName:Sr.optional(),address:Nr.optional(),privateKey:Gr.optional()}),xs=n.z.object({file:n.z.union([n.z.instanceof(File),n.z.instanceof(Buffer)]),address:Nr.optional(),privateKey:Gr.optional()}),Ms=n.z.object({address:Nr,tokenId:n.z.union([n.z.string(),n.z.object({collection:n.z.string(),category:n.z.string(),type:n.z.string(),additionalKey:n.z.string()}),n.z.object({collection:n.z.string(),category:n.z.string(),type:n.z.string(),additionalKey:n.z.string(),instance:n.z.string()})]).optional(),tokenName:Tr.optional(),withExpired:n.z.boolean().optional()}).refine(e=>void 0!==e.tokenId||void 0!==e.tokenName,"At least one token identifier (tokenId or tokenName) is required");function Ls(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 Us=Ls(pr),Fs=Ls(Er),Ps=Ls(Ar),Bs=Ls(Nr),Gs=Ls(kr),$s=Ls(wr),Ks=Ls(Sr),Hs=Ls(vr),Ws=Ls(Tr),Vs=Ls(es),js=Ls(Xr),qs=Ls(ts),zs=Ls(rs),Ys=Ls(Ds),Xs=Ls(Rs),Qs=Ls(Os),Js=Ls(xs),Zs=Ls(Ms),eo=Ls(As),to=Ls(Ts),no=Ls(vs),ro=Ls(Ss),so=Ls(ys),oo=Ls(ks),io=Ls(ws),ao=Ls(_s);function co(e){const t=Vs(e);return t.success?[]:t.errors??["Unknown validation error"]}function lo(e){const t=co(e);if(t.length>0)throw new Error(`LaunchTokenData validation failed:\n${t.map(e=>`- ${e}`).join("\n")}`)}function uo(e,t){return"string"==typeof e[t]}function ho(e,t){return void 0===e[t]||"string"==typeof e[t]}function go(e,t){return void 0===e[t]||"number"==typeof e[t]}function po(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 mo(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(!po(n[t],r))return!1}return!0}}Ln({BUY:"buy",SELL:"sell"});const fo=mo({nativeTokenQuantity:"string"});function Eo(e,t="0"){return function(e,t="0"){if(qt(e))return new a(t);if(a.isBigNumber(e))return e.isNaN()?new a(t):e;try{const n=new a(e);return n.isNaN()||!n.isFinite()?new a(t):n}catch{return new a(t)}}(e,t)}function Ao(e,t){return void 0!==t?Eo(e).toFixed(t):Eo(e).toFixed()}function To(e){const t=Eo(e),n=Math.log(1.0001),r=t.toNumber();return Math.log(r)/n}function vo(e){return Eo(e).isZero()}function So(e,t){return Eo(e).isLessThan(Eo(t))}function yo(...e){e.forEach(e=>{if(e.isNaN())throw It("value","NaN");if(!e.isFinite())throw wt("value","finite");if(e.isLessThanOrEqualTo(0))throw kt("value","0",e.toString())})}function bo(e,t,n){if(e.isNaN())throw It(t,"NaN");if(!e.isFinite())throw wt(t,"finite");if(e.isLessThanOrEqualTo(0))throw kt(t,"0",e.toString())}function No(e,t,n="0"){const r=Eo(t);return vo(r)?Eo(n):Eo(e).dividedBy(r)}const ko={calculateBuyWithExact(e,t){const n=Tn(e),r=Tn(t),{BASE_PRICE:s,PRICE_SCALING_FACTOR:o,TRADING_FEE_FACTOR:i,GAS_FEE:a}=$t,c=function(e,t){const n=Math.pow(10,t);return Math.ceil(e*n)/n}(s*(Math.exp((r+n)*o)-Math.exp(r*o))/o,8),l=Ao(Eo(c).multipliedBy(i));return{amount:c.toString(),reverseBondingCurveFee:"0",transactionFee:l,gasFee:a}},calculateBuyWithNative(e,t){const n=Tn(e),r=Tn(t),{BASE_PRICE:s,PRICE_SCALING_FACTOR:o,TRADING_FEE_FACTOR:i,GAS_FEE:a}=$t,c=Math.log(n*o/s+Math.exp(r*o))/o-r,l=Ao(Eo(c).multipliedBy(i));return{amount:c.toString(),reverseBondingCurveFee:"0",transactionFee:l,gasFee:a}},calculateSellWithExact(e,t,n,r,s){const o=Tn(e),i=Tn(t),a=Tn(n),{BASE_PRICE:c,PRICE_SCALING_FACTOR:l,TRADING_FEE_FACTOR:d,GAS_FEE:u}=$t,h=c*(Math.exp(i*l)-Math.exp((i-o)*l))/l,g=Eo(h),p=r+i/a*(s-r),m=Ao(g.multipliedBy(p),8),f=Ao(g.multipliedBy(d));return{amount:h.toString(),reverseBondingCurveFee:m,transactionFee:f,gasFee:u}},calculateSellWithNative(e,t,n,r,s){const o=Tn(e),i=Tn(t),a=Tn(n),{BASE_PRICE:c,PRICE_SCALING_FACTOR:l,TRADING_FEE_FACTOR:d,GAS_FEE:u}=$t;if(o>=c*(Math.exp(i*l)-1)/l){const e=Eo(o),t=r+i/a*(s-r),n=Ao(e.multipliedBy(t),8),c=Ao(e.multipliedBy(d));return{amount:i.toString(),reverseBondingCurveFee:n,transactionFee:c,gasFee:u}}const h=i-Math.log(Math.exp(i*l)-o*l/c)/l,g=Eo(o),p=r+i/a*(s-r),m=Ao(g.multipliedBy(p),8),f=Ao(g.multipliedBy(d));return{amount:h.toString(),reverseBondingCurveFee:m,transactionFee:f,gasFee:u}}};function wo(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function _o(e,t){if(!function(e){if(!wo(e)||"string"!=typeof e.calculatedQuantity)return!1;const t=e.extraFees;return wo(t)&&"string"==typeof t.reverseBondingCurve&&"string"==typeof t.transactionFees}(e))throw St(`Malformed trade quote from the launchpad backend (${t})`);return{amount:e.calculatedQuantity,reverseBondingCurveFee:e.extraFees.reverseBondingCurve,transactionFee:e.extraFees.transactionFees,gasFee:$t.GAS_FEE}}class Io{validate(e,t={}){const{allowZero:n=!0,minimum:r,maximum:s,maxDecimals:o=Io.MAX_DECIMAL_PLACES,fieldName:i="amount"}=t;if(!Rn(e))throw new rt(`${i} cannot be empty or whitespace-only. Provide a valid numeric string.`,i,"INVALID_NUMERIC_STRING");if(/[eE]/.test(e))throw new rt(`${i} cannot use scientific notation. Use standard decimal format (e.g., "1000" instead of "1e3").`,i,"INVALID_NUMERIC_STRING");const a=Tn(e,NaN);if(isNaN(a))throw new rt(`${i} must be a valid numeric string. Received: "${e}"`,i,"INVALID_NUMERIC_STRING");if(!isFinite(a))throw new rt(`${i} must be a finite number. Cannot be Infinity or -Infinity.`,i,"INVALID_NUMERIC_STRING");if(a<0)throw new rt(`${i} must be non-negative. Received: "${e}"`,i,"INVALID_NUMERIC_STRING");if(!n&&0===a)throw new rt(`${i} must be greater than zero. Received: "${e}"`,i,"INVALID_NUMERIC_STRING");const c=Eo(e),l=c.decimalPlaces()??0;if(l>o)throw new rt(`${i} cannot exceed ${o} decimal places. Received: ${l} decimal places`,i,"PRECISION_EXCEEDED");if(void 0!==r&&So(c,r))throw new rt(`${i} must be at least ${r}. Received: "${e}"`,i,"BELOW_MINIMUM");if(void 0!==s&&(d=s,Eo(c).isGreaterThan(Eo(d))))throw new rt(`${i} cannot exceed ${s}. Received: "${e}"`,i,"EXCEEDS_MAXIMUM");var d}parseAmount(e,t="0"){return Eo(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 Ao(e,t)}clampAmount(e,t,n){const r=Eo(e),s=Eo(t),o=Eo(n);return function(e,t,n){const r=Eo(e),s=Eo(t),o=Eo(n);return r.isGreaterThanOrEqualTo(s)&&r.isLessThanOrEqualTo(o)}(r,s,o)?Ao(r):So(r,s)?Ao(s):Ao(o)}}function Co(e,t){throw new rt(e.join("; "),t,"VALIDATION_ERROR")}function Do(e){const t=Us(e);!t.success&&t.errors&&Co(t.errors,"tokenName")}function Ro(e){const t=is.safeParse(e);var n;t.success||Co((n=t.error.issues,Array.isArray(n)?n.map(e=>null!=e&&"object"==typeof e&&"message"in e&&"string"==typeof e.message?e.message:String(e)).filter(e=>""!==e):[]),"options")}function Oo(e,t,n=!0){xo.validate(e,{fieldName:t,allowZero:n})}Io.MAX_DECIMAL_PLACES=18,Io.MIN_POSITIVE="0.00000000000000001";const xo=new Io;class Mo{constructor(e,t,n,r="local",s){this.http=e,this.logger=t,this.bundleHttp=n,this.defaultCalculateAmountMode=r,this.launchpadWrites=s,this.metadataCache=new Yn}createSale(e){if(void 0===this.launchpadWrites)throw new Error("Launchpad write transport is not configured.");return this.launchpadWrites.createSale(e)}addIfDefined(e,t,n){return void 0!==n&&(e[t]=n),e}async calculateBuyAmount(e){if(null==e||"object"!=typeof e)throw vt("options","an options object");const{tokenName:t,amount:n,type:r,currentSupply:s}=e;return"external"===this.validateAmountCalculationInputs(t,n,r,e.mode,[Qe.NATIVE,Qe.EXACT],'"native" or "exact"')?this.calculateBuyAmountExternal({tokenName:t,amount:n,type:r}):this.calculateBuyAmountLocal(this.addIfDefined({tokenName:t,amount:n,type:r},"currentSupply",s))}async calculateBuyAmountExternal(e){const{tokenName:t,amount:n,type:r}=e;return this.validateExternalAmountInputs(t,n),"exact"===r?this.fetchBackendQuote({tokenName:t,amount:n,type:"MEME",method:"OUT"},`Failed to calculate buy amount for ${t} (exact tokens)`):this.fetchBackendQuote({tokenName:t,amount:n,type:"NATIVE",method:"IN"},`Failed to calculate buy amount for ${t} (native/GALA budget)`)}async fetchBackendQuote(e,t){return _o(await Ft(()=>this.http.get(He,{...e}),{errorContext:t}),t)}async calculateSellAmount(e){const{tokenName:t,amount:n,type:r,currentSupply:s,maxSupply:o,reverseBondingCurveMaxFeeFactor:i,reverseBondingCurveMinFeeFactor:a}=e;if("external"===this.validateAmountCalculationInputs(t,n,r,e.mode,[Qe.EXACT,Qe.NATIVE],'"exact" or "native"'))return this.calculateSellAmountExternal({tokenName:t,amount:n,type:r});{const e={tokenName:t,amount:n,type:r,...void 0!==s&&{currentSupply:s},...void 0!==o&&{maxSupply:o},...void 0!==i&&{reverseBondingCurveMaxFeeFactor:i},...void 0!==a&&{reverseBondingCurveMinFeeFactor:a}};return this.calculateSellAmountLocal(e)}}async calculateSellAmountExternal(e){const{tokenName:t,amount:n,type:r}=e;return this.validateExternalAmountInputs(t,n),"exact"===r?this.fetchBackendQuote({tokenName:t,amount:n,type:"MEME",method:"IN"},`Failed to calculate sell amount for ${t} (exact tokens)`):this.fetchBackendQuote({tokenName:t,amount:n,type:"NATIVE",method:"OUT"},`Failed to calculate sell amount for ${t} (native/GALA target)`)}async calculateBuyAmountLocal(e){const{tokenName:t,amount:n,type:r,currentSupply:s}=e;if(!Rn(n))throw Tt("amount","Amount");if(r!==Qe.NATIVE&&r!==Qe.EXACT)throw _t("type",'"native" or "exact"',r);void 0!==s&&Oo(s,"currentSupply");const o=null==s||""===s;if(o&&(null==t||""===t))throw Tt("tokenName","Token name (required when currentSupply is not provided)");null!=t&&""!==t&&Do(t);let i=s;if(o){i=(await this.fetchPoolDetailsForCalculation(t)).currentSupply}return r===Qe.EXACT?ko.calculateBuyWithExact(n,i):ko.calculateBuyWithNative(n,i)}async calculateSellAmountLocal(e){const{tokenName:t,amount:n,type:r,currentSupply:s,maxSupply:o,reverseBondingCurveMaxFeeFactor:i,reverseBondingCurveMinFeeFactor:a}=e;if(!Rn(n))throw Tt("amount","Amount");if(r!==Qe.EXACT&&r!==Qe.NATIVE)throw _t("type",'"exact" or "native"',r);void 0!==s&&Oo(s,"currentSupply");const c=null==s||""===s||null==o||""===o||void 0===i||void 0===a;if(c&&(null==t||""===t))throw Tt("tokenName","Token name (required when currentSupply, maxSupply, or fee factors are not provided)");null!=t&&""!==t&&Do(t);let l=s,d=o,u=i,h=a;if(c&&null!=t&&""!==t){const e=this.metadataCache.getByName(t);d=d??this.metadataCache.getMaxSupply(t),u=u??e?.reverseBondingCurveMaxFeeFactor,h=h??e?.reverseBondingCurveMinFeeFactor,null!=l&&""!==l||(l=await this.fetchCurrentSupply(t));if(void 0===u||void 0===h){const e=await this.fetchPoolDetailsForCalculation(t);u=u??e.reverseBondingCurveMaxFeeFactor,h=h??e.reverseBondingCurveMinFeeFactor}}return r===Qe.EXACT?ko.calculateSellWithExact(n,l,d,h,u):ko.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 uo(t,"tokenName")&&function(e){return void 0===e.calculateAmountMode||"local"===e.calculateAmountMode||"external"===e.calculateAmountMode}(t)&&ho(t,"currentSupply")}(e))throw _t("options","CalculateBuyAmountForGraduationOptions or string (token name)",typeof e);const{tokenName:n,calculateAmountMode:r,currentSupply:s}=t;Do(n);const o=await this.fetchSaleDetails(n),i=s??Ao(Eo(o.maxSupply).minus(o.sellingTokenQuantity)),a=o.sellingTokenQuantity;if("0"===a)throw Tt("tokenName",`Token ${n} is already graduated (no tokens remaining in pool)`);const c={tokenName:n,amount:a,type:"exact",currentSupply:i,...void 0!==r&&{mode:r}};return{...await this.calculateBuyAmount(c),remainingTokens:a}}async launchToken(e){if(void 0!==this.launchpadWrites){return(await this.launchpadWrites.createSale(e)).bundleId}if(!this.bundleHttp)throw yt("Bundle backend client not configured. LaunchToken requires bundleHttp client.","bundleHttp");lo(e);const t=void 0!==e.preBuyQuantity&&""!==e.preBuyQuantity?e.preBuyQuantity:"0",n=Tn(t);if(0===n&&"0"!==t)throw It("preBuyQuantity",t,"Pre-buy quantity");if(n<0)throw It("preBuyQuantity",t,"Pre-buy quantity");if(e.reverseBondingCurveConfiguration){const{minFeePortion:t,maxFeePortion:n}=e.reverseBondingCurveConfiguration;Cn(t,n,"reverseBondingCurve")}throw new Error("Legacy launchToken signing is unavailable; configure the v6 launchpad write transport.")}async calculateInitialBuyAmount(e){if(!fo(e))throw vt("data","valid pre-mint calculation data");const t="Failed to calculate initial buy amount";return _o(await Ft(()=>this.http.get(We,{amount:e.nativeTokenQuantity}),{errorContext:t}),t)}async fetchPoolDetailsForCalculation(e){const t=await this.fetchSaleDetails(e),n=Ao(Eo(t.maxSupply).minus(t.sellingTokenQuantity)),r=t.sellingTokenQuantity,s=t.maxSupply;let o=.5,i=.1;const a=t.reverseBondingCurveConfiguration;null!=a?.maxFeePortion&&(o=Sn(a.maxFeePortion,.5)),null!=a?.minFeePortion&&(i=Sn(a.minFeePortion,.1)),void 0===a&&this.logger.debug(`Pool details missing reverse bonding curve configuration for token ${e}, using defaults (min: 0.1, max: 0.5)`);const c=o-i;return this.metadataCache.set(e,{maxSupply:s,reverseBondingCurveMaxFeeFactor:o,reverseBondingCurveMinFeeFactor:i,reverseBondingCurveNetFeeFactor:c}),{currentSupply:n,remainingTokens:r,maxSupply:s,reverseBondingCurveMaxFeeFactor:o,reverseBondingCurveMinFeeFactor:i,reverseBondingCurveNetFeeFactor:c}}async fetchCurrentSupply(e){Do(e);const t=await this.fetchSaleDetails(e),n=Ao(Eo(t.maxSupply).minus(t.sellingTokenQuantity)),r=t.maxSupply;return this.metadataCache.set(e,{maxSupply:r}),n}async fetchPoolDetails(e){Do(e);const t=await this.fetchSaleDetails(e),{reverseBondingCurveConfiguration:n,...r}=t,s=n?.minFeePortion??"0",o=n?.maxFeePortion??"0";return{...r,reverseBondingCurveMinFeePortion:s,reverseBondingCurveMaxFeePortion:o,hasReverseBondingCurveFee:!vo(s)||!vo(o),isGraduated:"Finished"===t.saleStatus}}async fetchSaleDetails(e){return Fn(e,"tokenName",Xn),Ft(()=>this.http.get(Ke,{tokenName:e}),{errorContext:`Failed to fetch sale details for ${e}`})}validateAmountCalculationInputs(e,t,n,r,s,o){const i=r??this.defaultCalculateAmountMode;if("local"!==i&&"external"!==i)throw _t("mode",'"local" or "external"',i);if(!Rn(e))throw Tt("tokenName","Token name");if(!Rn(t))throw Tt("amount","Amount");if("string"!=typeof n||!s.includes(n))throw _t("type",o,n);return i}validateExternalAmountInputs(e,t){if("string"!=typeof e||""===e)throw new rt("Token name must be a non-empty string","tokenName","INVALID_TOKEN_NAME");if("string"!=typeof t||""===t)throw new rt("Amount must be a non-empty string","amount","INVALID_AMOUNT")}getAddress(){return this.http.getAddress()}formatAddressForBackend(e){return cn(e)}validateTokenName(e){return Do(e)}validatePagination(e){void 0!==e.pageSize&&Mn(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 Lo={REFRESH_THRESHOLD_MS:3e5,DEFAULT_EXPIRY_S:86400,LOGIN_MESSAGE_PREFIX:"Sign in to Launchpad t:",AUTH_HEADER:"Authorization",BEARER_PREFIX:"Bearer "};class Uo{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 Fo;exports.AuthErrorType=void 0,(Fo=exports.AuthErrorType||(exports.AuthErrorType={})).WALLET_NOT_CONNECTED="WALLET_NOT_CONNECTED",Fo.SIGNATURE_FAILED="SIGNATURE_FAILED",Fo.INVALID_ADDRESS="INVALID_ADDRESS",Fo.MESSAGE_GENERATION_FAILED="MESSAGE_GENERATION_FAILED";class Po extends Error{constructor(e,t,n,r){super(t),this.type=e,this.originalError=n,this.statusCode=r,this.name="AuthError"}}class Bo{constructor(e,t=Lo.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 Uo,this.refreshThresholdMs=t}setToken(e,t){if(!Rn(e))throw new Po(exports.AuthErrorType.SIGNATURE_FAILED,"JWT token must be a non-empty string");if("number"!=typeof t)throw new Po(exports.AuthErrorType.SIGNATURE_FAILED,"Token expiration must be a positive finite number (seconds)");if(!Number.isFinite(t))throw new Po(exports.AuthErrorType.SIGNATURE_FAILED,"Token expiration must be a positive finite number (seconds)");if(t<=0)throw new Po(exports.AuthErrorType.SIGNATURE_FAILED,"Token expiration must be a positive finite number (seconds)");const n=Date.now();this.tokenState={token:e.trim(),issuedAt:n,expiresAt:n+1e3*t},this.storage.set(this.STORAGE_KEYS.ACCESS_TOKEN,e.trim()),this.storage.set(this.STORAGE_KEYS.ACCESS_EXPIRES,String(this.tokenState.expiresAt))}async setTokens(e,t,n,r){if(this.setToken(e,t),n){const e=Date.now()+1e3*(r??7776e3);if(!this.tokenState)throw new Po(exports.AuthErrorType.SIGNATURE_FAILED,"Access token must be set before refresh token");this.tokenState.refreshToken=n.trim(),this.tokenState.refreshExpiresAt=e,await this.storage.set(this.STORAGE_KEYS.REFRESH_TOKEN,n.trim()),await this.storage.set(this.STORAGE_KEYS.REFRESH_EXPIRES,String(e))}}getToken(){return this.tokenState?.token??null}hasToken(){return null!==this.tokenState}isExpired(){return!this.tokenState||Date.now()>=this.tokenState.expiresAt}shouldRefresh(e){if(!this.tokenState)return!1;const t=e??this.refreshThresholdMs,n=this.tokenState.expiresAt-Date.now();return n>0&&n<=t}getTimeUntilExpiry(){if(!this.tokenState)return 0;const e=this.tokenState.expiresAt-Date.now();return Math.max(0,e)}getExpiresAt(){return this.tokenState?.expiresAt??null}getAuthorizationHeader(){const e=this.getToken();return null===e||""===e?null:`${Lo.BEARER_PREFIX}${e}`}getJwtHeaders(){const e=this.getAuthorizationHeader();if(null===e||""===e)throw new Po(exports.AuthErrorType.WALLET_NOT_CONNECTED,"No JWT token available. Call login() first.");return{[Lo.AUTH_HEADER]:e}}async getRefreshToken(){if(!this.tokenState?.refreshToken){const e=await this.storage.get(this.STORAGE_KEYS.REFRESH_TOKEN),t=await this.storage.get(this.STORAGE_KEYS.REFRESH_EXPIRES);if(e&&t){const n=Number(t);if(Number.isFinite(n)&&Date.now()<n)return e}return null}return null!==this.tokenState.refreshExpiresAt&&void 0!==this.tokenState.refreshExpiresAt&&(!Number.isFinite(this.tokenState.refreshExpiresAt)||Date.now()>=this.tokenState.refreshExpiresAt)?null:this.tokenState.refreshToken??null}async restoreFromStorage(){const e=await this.storage.get(this.STORAGE_KEYS.ACCESS_TOKEN),t=await this.storage.get(this.STORAGE_KEYS.ACCESS_EXPIRES);if(!e||!t)return!1;const n=Number(t);if(!Number.isFinite(n)||Date.now()>=n)return!1;const r=Date.now();this.tokenState={token:e,issuedAt:r,expiresAt:n};const s=await this.storage.get(this.STORAGE_KEYS.REFRESH_TOKEN),o=await this.storage.get(this.STORAGE_KEYS.REFRESH_EXPIRES);if(s&&o){const e=Number(o);Number.isFinite(e)&&Date.now()<e&&(this.tokenState.refreshToken=s,this.tokenState.refreshExpiresAt=e)}return!0}async clear(){this.tokenState=null,await this.storage.remove(this.STORAGE_KEYS.ACCESS_TOKEN),await this.storage.remove(this.STORAGE_KEYS.ACCESS_EXPIRES),await this.storage.remove(this.STORAGE_KEYS.REFRESH_TOKEN),await this.storage.remove(this.STORAGE_KEYS.REFRESH_EXPIRES)}isValid(){return this.hasToken()&&!this.isExpired()}getDebugInfo(){return{hasToken:this.hasToken(),isExpired:this.isExpired(),shouldRefresh:this.shouldRefresh(),timeUntilExpiryMs:this.getTimeUntilExpiry(),expiresAt:this.tokenState?new Date(this.tokenState.expiresAt):null}}}class Go extends Bo{getJwtHeaders(){return{}}}async function $o(e,t,n,r){try{return await e()}catch(e){throw r?(r(e,t,n),new Error("Unreachable after error handler")):(n&&n.error(`${t}:`,e),function(e,t,n){n&&n.error(`${t}:`,e);const r=(pt(e)?e.response?.status:void 0)??(e instanceof at?e.statusCode:void 0);return St(`${t}: ${ut(e)}`,r,dt(e)?e:void 0)}(e,t,n))}}function Ko(e,t){return t instanceof Po?t:new Po(exports.AuthErrorType.SIGNATURE_FAILED,`${e}: ${ut(t)}`,dt(t)?t:void 0,function(e){if("object"==typeof e&&null!==e){if("statusCode"in e&&"number"==typeof e.statusCode)return e.statusCode;if("response"in e&&"object"==typeof e.response&&null!==e.response){const t=e.response;if("status"in t&&"number"==typeof t.status)return t.status}}}(t))}class Ho{constructor(e,t,n,r=!1,s){this.http=e,this.signatureAuth=t,this.jwtAuth=n,this.session=s,this.refreshPromise=null,this.loginPromise=null,this.logger=new Vt({debug:r,context:"SessionAuthService"})}async loginWithSignature(e){const t=Zt(e.address,"address");if(!Rn(e.message)||!Rn(e.signature))throw new Po(exports.AuthErrorType.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:Zt(e,"address"),...void 0!==this.session&&{cookieSession:!0}})}async postLogin(e){try{const t=await this.http.request({method:"POST",url:R,data:e,withSession:!1}),n=this.extractLoginData(t);return void 0===this.session&&await this.jwtAuth.setTokens(n.accessToken,n.expiresIn,n.refreshToken,n.refreshExpiresIn),n}catch(e){throw Ko("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 Po(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Wallet is required for login. Configure privateKey in SDK.");this.loginPromise=this.performLogin();try{return await this.loginPromise}finally{this.loginPromise=null}}async performLogin(){return $o(async()=>{const e=Date.now(),t=`${Lo.LOGIN_MESSAGE_PREFIX}${e}`;this.logger.debug("Generating login signature",{message:t,timestamp:e});const n=await this.signatureAuth.signMessage(t),r=Zt(this.signatureAuth.getAddress(),"address"),s={address:r,message:t,signature:n.signature};this.logger.debug("Sending login request",{address:r,message:t});const o=await this.http.post(R,s),i=this.extractLoginData(o);return await this.jwtAuth.setTokens(i.accessToken,i.expiresIn,i.refreshToken,i.refreshExpiresIn),this.logger.debug("Login successful",{address:i.address,expiresIn:i.expiresIn,hasRefreshToken:!!i.refreshToken}),i},"SessionAuthService.performLogin",this.logger,e=>{if(e instanceof Po)throw e;throw new Po(exports.AuthErrorType.SIGNATURE_FAILED,`Login failed: ${ut(e)}`,dt(e)?e:void 0)})}async refresh(){if(this.refreshPromise)return this.logger.debug("Refresh already in progress, reusing existing promise"),this.refreshPromise;if(void 0!==this.session){this.refreshPromise=this.performCookieRefresh();try{return await this.refreshPromise}finally{this.refreshPromise=null}}if(!this.jwtAuth.hasToken())throw new Po(exports.AuthErrorType.WALLET_NOT_CONNECTED,"No token to refresh. Call login() first.");this.refreshPromise=this.performRefresh();try{return await this.refreshPromise}finally{this.refreshPromise=null}}async performCookieRefresh(){try{const e=await this.http.request({method:"POST",url:x,data:{},withSession:!1});return this.extractLoginData(e)}catch(e){throw Ko("Token refresh failed",e)}}async performRefresh(){return $o(async()=>{this.logger.debug("Refreshing JWT token");const e=await this.jwtAuth.getRefreshToken();if(e){this.logger.debug("Using refresh token flow");const t=await this.http.post(x,{refreshToken:e}),n=this.extractLoginData(t);return await this.jwtAuth.setTokens(n.accessToken,n.expiresIn,n.refreshToken,n.refreshExpiresIn),this.logger.debug("Token refreshed successfully via refresh token",{address:n.address,expiresIn:n.expiresIn,hasNewRefreshToken:!!n.refreshToken}),n}this.logger.debug("Using legacy access token refresh");const t=await this.http.post(x,{},this.jwtAuth.getJwtHeaders()),n=this.extractLoginData(t);return this.jwtAuth.setToken(n.accessToken,n.expiresIn),this.logger.debug("Token refreshed successfully via access token",{address:n.address,expiresIn:n.expiresIn}),n},"SessionAuthService.performRefresh",this.logger,e=>{if(e instanceof Po)throw e;throw new Po(exports.AuthErrorType.SIGNATURE_FAILED,`Token refresh failed: ${ut(e)}`,dt(e)?e:void 0)})}async logout(e){this.logger.debug("Logging out",{allDevices:e?.allDevices});const t=e?.allDevices??!1;if(void 0!==this.session){const n=e?.accessToken??null;try{await this.http.request({method:"POST",url:O,data:{allDevices:t},withSession:!1,...null!==n&&""!==n&&{headers:{Authorization:`${Lo.BEARER_PREFIX}${n}`}}})}catch(e){throw Ko("Logout failed",e)}return}if(t&&this.jwtAuth.hasToken()&&!this.jwtAuth.isExpired())try{await this.http.post(O,{allDevices:!0},this.jwtAuth.getJwtHeaders()),this.logger.debug("Logged out from all devices")}catch(e){this.logger.warn(`Failed to revoke all-device sessions (server-side revocation may be incomplete): ${ut(e)}`)}else t&&this.logger.debug("Skipping server-side revocation: no valid local token available");await this.jwtAuth.clear()}async getSession(){if(!this.jwtAuth.hasToken())throw new Po(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Not authenticated. Call login() first.");return $o(async()=>{const e=await this.http.get(M,void 0,this.jwtAuth.getJwtHeaders());return this.extractSessionData(e)},"SessionAuthService.getSession",this.logger,e=>{if(e instanceof Po)throw e;throw new Po(exports.AuthErrorType.SIGNATURE_FAILED,`Failed to get session: ${ut(e)}`,dt(e)?e:void 0)})}getAccessToken(){return this.jwtAuth.getToken()}isAuthenticated(){return this.jwtAuth.isValid()}shouldRefresh(e){return this.jwtAuth.shouldRefresh(e)}async ensureValidToken(e){if(void 0!==this.session){const e=await this.session.accessToken();if(null===e||""===e)throw new Po(exports.AuthErrorType.WALLET_NOT_CONNECTED,"The app session has no access token.");return e}if(!this.jwtAuth.hasToken())throw new Po(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Not authenticated. Call login() first.");if(this.jwtAuth.isExpired()){if(await this.jwtAuth.getRefreshToken()){this.logger.debug("Token expired - refresh token available, attempting refresh");try{return(await this.refresh()).accessToken}catch(e){this.logger.warn(`Refresh failed after expiry: ${ut(e)} - attempting re-login`)}}else this.logger.debug("Token expired - no refresh token available, attempting re-login");return(await this.login()).accessToken}if(this.jwtAuth.shouldRefresh(e)){this.logger.debug("Token near expiry - refreshing");return(await this.refresh()).accessToken}return this.jwtAuth.getToken()}extractLoginData(e){if(e.error)throw new Po(exports.AuthErrorType.SIGNATURE_FAILED,""!==ut(e)?ut(e):"Authentication failed");const t=Ut(e,"No data in authentication response"),{accessToken:n,expiresIn:r,address:s,refreshToken:o,refreshExpiresIn:i}=t;if(!Rn(n))throw new Po(exports.AuthErrorType.SIGNATURE_FAILED,"Invalid access token in response");if("number"!=typeof r||r<=0)throw new Po(exports.AuthErrorType.SIGNATURE_FAILED,"Invalid expiration in response");return{accessToken:n,expiresIn:r,address:s,...void 0!==o&&{refreshToken:o},...void 0!==i&&{refreshExpiresIn:i}}}extractSessionData(e){if(e.error)throw new Po(exports.AuthErrorType.SIGNATURE_FAILED,""!==ut(e)?ut(e):"Failed to get session");return Ut(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{In(e.messagePrefix,"messagePrefix",!1)}catch{throw new Po(exports.AuthErrorType.SIGNATURE_FAILED,"Message prefix cannot be empty")}}hasWallet(){return void 0!==this.walletProvider||void 0!==this.wallet}ensureWalletProvider(){if(this.wallet&&!this.walletProvider)try{this.walletProvider=r.PrivateKeyProvider.fromWallet(this.wallet),this.cachedAddress=this.wallet.address,this.cachedGalaAddress=cn(this.wallet.address)}catch(e){if(e instanceof Po)throw e;if(e instanceof rt&&("INVALID_ADDRESS"===e.code||"INVALID_FORMAT"===e.code||"address"===e.field))throw new Po(exports.AuthErrorType.INVALID_ADDRESS,e.message);if(null!==e&&"object"==typeof e&&"message"in e)throw new Po(exports.AuthErrorType.WALLET_NOT_CONNECTED,e.message);throw e}}setWallet(e){if(void 0!==e){if("object"!=typeof e||!("address"in e))throw new Po(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Invalid wallet: must be an ethers Wallet instance or undefined");if("string"!=typeof e.address||""===e.address)throw new Po(exports.AuthErrorType.INVALID_ADDRESS,"Wallet address is not available");this.walletProvider=r.PrivateKeyProvider.fromWallet(e),this.cachedAddress=e.address,this.cachedGalaAddress=cn(e.address)}else this.walletProvider=void 0,this.cachedAddress=void 0,this.cachedGalaAddress=void 0;this.wallet=e}setWalletProvider(e){this.walletProvider=e,this.wallet=void 0;const n=void 0!==e&&r.isPrivateKeyProvider(e)?t.computeAddress(e.exportPrivateKey()):void 0;this.cachedAddress=n,this.cachedGalaAddress=void 0===n?void 0:cn(n)}getWalletProvider(){return this.walletProvider}async cacheAddress(){this.walletProvider&&(this.cachedAddress=await this.walletProvider.getAddress(),this.cachedGalaAddress=Zt(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 Po)throw e;throw new Po(exports.AuthErrorType.SIGNATURE_FAILED,"Failed to generate signature for authentication",dt(e)?e:new Error(ut(e)))}}getAddress(){if(this.validateWallet(),this.cachedGalaAddress)return this.cachedGalaAddress;if(this.wallet)return this.formatAddress(this.wallet.address);throw new Po(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Address not available. For external wallets, call cacheAddress() after connecting.")}async getAddressAsync(){return await this.validateWalletAsync(),Zt(await this.walletProvider.getGalaAddress(),"address")}getEthereumAddress(){if(this.validateWallet(),this.cachedAddress)return this.cachedAddress;if(this.wallet)return this.wallet.address;throw new Po(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Address not available. For external wallets, call cacheAddress() after connecting.")}async getEthereumAddressAsync(){return await this.validateWalletAsync(),this.walletProvider.getAddress()}getPrivateKey(){if(this.validateWallet(),this.wallet){if(""===this.wallet.privateKey||null===this.wallet.privateKey||void 0===this.wallet.privateKey)throw new Po(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Wallet private key not available for @gala-chain signing");return this.wallet.privateKey}if(void 0!==this.walletProvider&&r.isPrivateKeyProvider(this.walletProvider))return this.walletProvider.exportPrivateKey();throw new Po(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Private key not available. External wallet providers cannot access private keys. Use PrivateKeyProvider for @gala-chain signing operations.")}async getPrivateKeyAsync(){if(await this.validateWalletAsync(),!this.walletProvider.getPrivateKey)throw new Po(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Private key not available with this wallet provider");try{return await this.walletProvider.getPrivateKey()}catch(e){throw new Po(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Private key not available. External wallet providers cannot access private keys. Use PrivateKeyProvider for @gala-chain signing operations.",dt(e)?e:void 0)}}formatAddress(e){try{return cn(e)}catch{throw new Po(exports.AuthErrorType.INVALID_ADDRESS,`Invalid Ethereum address format: ${e}`)}}async signMessage(e){await this.validateWalletAsync();try{const t=await this.walletProvider.signMessage(e);return{message:e,signature:t,address:await this.walletProvider.getAddress(),timestamp:Date.now()}}catch(e){if(e instanceof Po)throw e;throw new Po(exports.AuthErrorType.SIGNATURE_FAILED,ut(e),dt(e)?e:new Error(ut(e)))}}async generateAuthHeaders(e,t){await this.validateWalletAsync();try{const n=Date.now(),r=`${this.messagePrefix} ${t.toUpperCase()} ${e} ${n}`,s=await this.walletProvider.signMessage(r);return{"x-signature":s,"x-address":await this.walletProvider.getGalaAddress(),"x-message":r,"x-timestamp":n.toString()}}catch(e){if(e instanceof Po)throw e;throw new Po(exports.AuthErrorType.SIGNATURE_FAILED,"Failed to generate authentication headers",dt(e)?e:new Error(ut(e)))}}async signTypedData(e,t,n){await this.validateWalletAsync();try{const r={};for(const[e,n]of Object.entries(t))r[e]=n.map(e=>({name:e.name,type:e.type}));return await this.walletProvider.signTypedData(e,r,n)}catch(e){if(e instanceof Po)throw e;throw new Po(exports.AuthErrorType.SIGNATURE_FAILED,"Failed to sign typed data",dt(e)?e:new Error(ut(e)))}}async generateCustomSignature(e){if(!Rn(e))throw new Po(exports.AuthErrorType.SIGNATURE_FAILED,"Custom message must be a non-empty string");await this.validateWalletAsync();try{const t=await this.walletProvider.signMessage(e);return{message:e,signature:t,address:await this.walletProvider.getGalaAddress(),timestamp:Date.now()}}catch(e){if(e instanceof Po)throw e;throw new Po(exports.AuthErrorType.SIGNATURE_FAILED,"Failed to generate custom message signature",dt(e)?e:new Error(ut(e)))}}validateWallet(){if(this.ensureWalletProvider(),!this.walletProvider)throw new Po(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Wallet is required for authentication")}async validateWalletAsync(){if(this.ensureWalletProvider(),!this.walletProvider)throw new Po(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Wallet is required for authentication");if(!this.walletProvider.isConnected())throw new Po(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Wallet is not connected. Call connect() on the wallet provider first.")}}const Vo={prod:{...e.GALA_CHAIN_ENVIRONMENTS.prod,bundleBaseUrl:"https://bundle-backend-prod1.defi.gala.com",launchpadBaseUrl:"https://lpad-backend-prod1.defi.gala.com",dexBackendBaseUrl:"https://dex-backend-prod1.defi.gala.com",webSocketUrl:"https://bundle-backend-prod1.defi.gala.com",launchpadFrontendUrl:"https://lpad-frontend-prod1.defi.gala.com"},stage:{...e.GALA_CHAIN_ENVIRONMENTS.stage,bundleBaseUrl:"https://bundle-backend.stage.defi.ovh.gala.com",launchpadBaseUrl:"https://lpad-backend.stage.defi.ovh.gala.com",dexBackendBaseUrl:"https://swap-backend.stage.defi.ovh.gala.com",webSocketUrl:"https://bundle-backend.stage.defi.ovh.gala.com",launchpadFrontendUrl:"https://lpad-frontend-test1.defi.gala.com"}};function jo(e){return Vo[e]}var qo,zo;!function(e){e.PROCESSED="PROCESSED",e.COMPLETED="COMPLETED",e.SUCCESS="SUCCESS",e.FAILED="FAILED",e.ERROR="ERROR",e.PROCESSING="PROCESSING",e.PENDING="PENDING"}(qo||(qo={})),exports.SDKTransactionStatus=void 0,(zo=exports.SDKTransactionStatus||(exports.SDKTransactionStatus={})).PENDING="pending",zo.PROCESSING="processing",zo.COMPLETED="completed",zo.FAILED="failed",zo.TIMEOUT="timeout";const Yo={[qo.PROCESSED]:exports.SDKTransactionStatus.COMPLETED,[qo.COMPLETED]:exports.SDKTransactionStatus.COMPLETED,[qo.SUCCESS]:exports.SDKTransactionStatus.COMPLETED,[qo.FAILED]:exports.SDKTransactionStatus.FAILED,[qo.ERROR]:exports.SDKTransactionStatus.FAILED,[qo.PROCESSING]:exports.SDKTransactionStatus.PROCESSING,[qo.PENDING]:exports.SDKTransactionStatus.PENDING},Xo="9.1.0-beta.0",Qo={DEFAULT_PAGE_SIZE:50,MAX_PAGE_SIZE:1e3,SAFETY_MAX_PAGES:1e4,DEFAULT_OFFSET:0,DEFAULT_LIMIT:10,BACKEND_MAX_PAGE_SIZE:20};function Jo(e,t=1,n=Qo.BACKEND_MAX_PAGE_SIZE){return Math.max(t,Math.min(n,Math.ceil(e??t)))}function Zo(e){return"string"==typeof e||null===e?e:void 0}function ei(e){if("object"!=typeof e||null===e)return{hasNextPage:!1};const t=Reflect.get(e,"hasNextPage"),n=Reflect.get(e,"hasPreviousPage"),r=Zo(Reflect.get(e,"endCursor")),s=Zo(Reflect.get(e,"startCursor"));return{hasNextPage:!0===t,...void 0===r?{}:{endCursor:r},..."boolean"==typeof n?{hasPreviousPage:n}:{},...void 0===s?{}:{startCursor:s}}}function ti(e,t){const{hasNextPage:n,endCursor:r}=e;if(n&&"string"==typeof r&&""!==r&&r!==t)return r}function ni(e){return"string"==typeof e?e:"number"==typeof e||"boolean"==typeof e||"bigint"==typeof e?String(e):JSON.stringify(e)??""}function ri(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 si={tokenName:"lowercase",address:"lowercase",userAddress:"lowercase",assetId:"as given",targetId:"as given",id:"as given",code:"as given"};function oi(e,t){let n=e;for(const[e,r]of Object.entries(t)){const t=si[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 ii(e,t,n){for(const r of n){const n=t[r];null!=n&&""!==n&&(e[r]=ni(n))}return e}const ai="x-api-key";class ci extends jn{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(!Rn(e))throw Tt("tokenName","Token name");const n=Kt(e);if(!t.PATTERN.test(n))throw vt("tokenName",t.DESCRIPTION,"Token name")}(e,t)}validateRequiredString(e,t,n){!function(e,t,n){if(!Rn(e))throw Tt(t,n)}(e,t,n)}validateOptionalString(e,t,n,r){!function(e,t,n,r){if(null!=e){if("string"!=typeof e)throw _t(t,"string",typeof e,n);if(e.length>r)throw wt(t,r,e.length,n)}}(e,t,n,r)}validateOptionalNumber(e,t,n,r,s,o,i){!function(e,t,n,r,s){if(null!=e){if("number"!=typeof e)throw _t(t,"number",typeof e,n);if(e<r||e>s)throw Nt(t,r,s,e,n)}}(e,t,n,r,s)}validateOptionalDate(e,t,n){!function(e,t,n){if(null!=e&&!Qt(e))throw vt(t,"a valid ISO 8601 date string",n)}(e,t,n)}validatePositiveInteger(e,t,n){Wn(e,t,n)}validateStatusFilter(e,t,n="status"){Vn(e,t,n)}buildPaginationParams(e,t){return ri(e,t)}addOptionalFilterParams(e,t,n){return ii(e,t,n)}buildEndpoint(e,t){return oi(e,t)}buildEndpointWithId(e,t){return e.replace(":id",encodeURIComponent(t))}validateAndBuildTokenEndpoint(e,t,n){return this.validateTokenName(e,t),this.buildEndpoint(n,{tokenName:e})}getAdminHeaders(){if(void 0===this.adminApiKey||""===this.adminApiKey)throw new ct("Admin API key required for this operation. Set streamAdminApiKey in SDK config.");return{[ai]:this.adminApiKey}}getJwtHeaders(){if(!this.jwtAuth)throw new ct("JWT authentication required. Call sdk.login() first.");return this.jwtAuth.getJwtHeaders()}hasJwtAuth(){return this.jwtAuth?.isValid()??!1}hasAdminApiKey(){return void 0!==this.adminApiKey&&""!==this.adminApiKey}getDualAuthHeaders(){return void 0!==this.adminApiKey&&""!==this.adminApiKey?this.getAdminHeaders():this.getJwtHeaders()}getMultiAuthHeaders(){return void 0!==this.userApiKey&&""!==this.userApiKey?{[ai]:this.userApiKey}:this.getJwtHeaders()}extractData(e){return Mt(e,"Backend request failed",!0),Ut(e,"No data in backend response")}extractDataOrNull(e){return Mt(e,"Backend request failed",!1),e.data??null}async toggleFeature(e,t,n){this.validateTokenName(e,n);const r=this.buildEndpoint(t,{tokenName:e}),s=await this.http.post(r,{},this.getAdminHeaders()),o=this.extractData(s);return{enabled:o.enabled,tokenName:o.tokenName??Kt(e)}}}class li extends ci{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async getSettings(){return{settings:(await this.http.get(Be.GET_SETTINGS,{},this.getDualAuthHeaders())).settings}}async updateSettings(e){const t={};void 0!==e.enabled&&(t.enabled=e.enabled),void 0!==e.mode&&(t.mode=e.mode),void 0!==e.provider&&(t.provider=e.provider);return{settings:(await this.http.post(Be.UPDATE_SETTINGS,t,this.getDualAuthHeaders())).settings}}async getModeration(e){this.validatePositiveInteger(e.flagId,"flagId","Flag ID");const t=Be.GET_MODERATION.replace(":flagId",String(e.flagId));return{moderation:(await this.http.get(t,{},this.getDualAuthHeaders())).analysis}}async triggerModeration(e){this.validatePositiveInteger(e.flagId,"flagId","Flag ID");const t=Be.TRIGGER_MODERATION.replace(":flagId",String(e.flagId)),n=await this.http.post(t,{},this.getDualAuthHeaders());return{queued:n.queued,message:n.message.length>0?n.message:"Moderation queued successfully"}}async getStatus(){return{status:(await this.http.get(Be.GET_STATUS,{},this.getDualAuthHeaders())).status}}}const di={MODERATOR:"MODERATOR",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MANAGER:"MANAGER",OWNER:"OWNER"},ui=Un(di),hi={MANAGE_COMMUNITY:"MANAGE_COMMUNITY",MANAGE_STREAM:"MANAGE_STREAM",MANAGE_SETTINGS:"MANAGE_SETTINGS",MANAGE_RECORDINGS:"MANAGE_RECORDINGS",VIEW_ANALYTICS:"VIEW_ANALYTICS"},gi=Object.values(hi);function pi(e){return ui.includes(e)}function mi(e){const t=[];return void 0===e.role||null===e.role?t.push("Role is required"):pi(e.role)||t.push(`Invalid role. Must be one of: ${ui.join(", ")}`),Ei(e,t),t}function fi(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||pi(e.role)||t.push(`Invalid role. Must be one of: ${ui.join(", ")}`),Ei(e,t,!0),t}function Ei(e,t,n=!1){const r=t.length;if(ft(t,()=>{Kn(e.description,"description",255)}),t.length>r&&(t[r]="Description must be 255 characters or less"),void 0!==e.tokenNames){const n=t.length;ft(t,()=>{if(!Array.isArray(e.tokenNames))throw _t("tokenNames","an array",e.tokenNames);if(!e.tokenNames.every(e=>"string"==typeof e))throw _t("tokenNames","contain only strings")});for(let e=n;e<t.length;e++){const n=t[e];n?.includes("array")?t[e]="tokenNames must be an array":n?.includes("string")&&(t[e]="tokenNames must contain only strings")}}if(void 0!==e.expiresAt&&(!n||null!==e.expiresAt)){const n=t.length;ft(t,()=>{Hn(e.expiresAt,"expiresAt")}),t.length>n&&(t[n]="expiresAt must be a valid ISO 8601 date string")}}function Ai(e){if(void 0!==e.pageSize&&("number"!=typeof e.pageSize||e.pageSize<1||e.pageSize>tr))throw _t("pageSize",`number between 1 and ${tr}`,typeof e.pageSize);if(void 0!==e.cursor&&("string"!=typeof e.cursor||""===e.cursor.trim()))throw _t("cursor","non-empty string",typeof e.cursor)}const Ti={[di.MODERATOR]:1,[di.TECHNICAL_PRODUCER]:1,[di.MANAGER]:2,[di.OWNER]:3};class vi extends jn{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),Mt(n,"API key operation failed",!0),e.data}validateApiKeyId(e){this.validatePositiveInteger(e,"id","API key ID")}async create(e){const t=mi(e);if(t.length>0)throw new rt(t.join("; "),"options","VALIDATION_FAILED");this.logger.debug("Creating API key",{role:e.role,delegateAllTokens:e.delegateAllTokens});const n={role:e.role};void 0!==e.description&&(n.description=e.description),void 0!==e.delegateAllTokens&&(n.delegateAllTokens=e.delegateAllTokens),void 0!==e.tokenNames&&e.tokenNames.length>0&&(n.tokenNames=e.tokenNames),void 0!==e.expiresAt&&(n.expiresAt=e.expiresAt),void 0!==e.tokenPermissions&&(n.tokenPermissions=e.tokenPermissions);const r=await this.http.post(W.CREATE,n,this.getJwtHeaders()),s=this.extractData(r);return this.logger.debug("API key created",{id:s.id,keyPrefix:s.keyPrefix}),s}async findAll(e={}){Ai(e),this.logger.debug("Listing API keys",e);const t=ri(e,tr),n=await this.http.get(W.LIST,t,this.getJwtHeaders()),r=this.extractData(n);return this.logger.debug("Listed API keys",{count:r.apiKeys.length,total:r.pageInfo.totalCount}),r}async findOne(e){this.validateApiKeyId(e),this.logger.debug("Getting API key",{id:e});const t=W.GET.replace(":id",String(e)),n=await this.http.get(t,{},this.getJwtHeaders()),r=this.extractData(n);return this.logger.debug("Got API key",{id:r.id,keyPrefix:r.keyPrefix}),r}async update(e,t){this.validateApiKeyId(e);const n=fi(t);if(n.length>0)throw new rt(n.join("; "),"options","VALIDATION_FAILED");this.logger.debug("Updating API key",{id:e,options:t});const r={};void 0!==t.role&&(r.role=t.role),void 0!==t.description&&(r.description=t.description),void 0!==t.delegateAllTokens&&(r.delegateAllTokens=t.delegateAllTokens),void 0!==t.tokenNames&&(r.tokenNames=t.tokenNames),void 0!==t.expiresAt&&(r.expiresAt=t.expiresAt),void 0!==t.tokenPermissions&&(r.tokenPermissions=t.tokenPermissions);const s=W.UPDATE.replace(":id",String(e)),o=await this.http.patch(s,r,this.getJwtHeaders()),i=this.extractData(o);return this.logger.debug("Updated API key",{id:i.id,keyPrefix:i.keyPrefix}),i}async revoke(e){this.validateApiKeyId(e),this.logger.debug("Revoking API key",{id:e});const t=W.REVOKE.replace(":id",String(e));await this.http.delete(t,{},this.getJwtHeaders()),this.logger.debug("API key revoked",{id:e})}getRoles(){return[...ui]}}const Si={VIEWERS:"viewers",CHAT_PARTICIPANTS:"chat_participants"},yi=Ln(Si),bi=Bn([{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}]),Ni=Bn([{field:"tokenName",type:"string",nullable:!0},{field:"isGlobal",type:"boolean"},{field:"isPermanent",type:"boolean"}]),ki=Bn([{field:"tokenName",type:"string",nullable:!0},{field:"isGlobal",type:"boolean"}]),wi=Bn([{field:"tokenName",type:"string"},{field:"action",type:"string",validator:e=>"CHAT_MESSAGE"===e||"COMMENT"===e||"REACTION"===e}]);function _i(e){return null==e||""===e||"string"==typeof e&&(!$n(e)&&e.length<=or.BAN_REASON.MAX_LENGTH)}function Ii(e){return!!xn(e)||"number"==typeof e&&(e>=ar&&e<=cr)}function Ci(e){if(!Rn(e.userAddress))throw Tt("userAddress");if(!_i(e.reason))throw new rt(`reason must be at most ${or.BAN_REASON.MAX_LENGTH} characters`,"reason","TOO_LONG");if(!Ii(e.durationSeconds))throw new rt(`durationSeconds must be between ${ar} and ${cr} seconds`,"durationSeconds","OUT_OF_RANGE")}class Di extends ci{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async createBan(e){!function(e){Fn(e.tokenName,"tokenName",Jn),Ci(e)}(e);const t=this.buildEndpoint(L,{tokenName:e.tokenName}),n=Ri(e),r=await this.http.post(t,n,this.getMultiAuthHeaders());return{ban:this.extractData(r),tokenName:Kt(e.tokenName)}}async removeBan(e){!function(e){if(Fn(e.tokenName,"tokenName",Jn),!Rn(e.userAddress))throw Tt("userAddress")}(e);const t=en(e.userAddress,"userAddress"),n=this.buildEndpoint(P,{tokenName:e.tokenName,userAddress:t}),r=await this.http.delete(n,{},this.getMultiAuthHeaders()),s=this.extractDataOrNull(r);return{removed:s?.removed??!0,tokenName:Kt(e.tokenName),userAddress:s?.userAddress??t}}async listBans(e){!function(e){Fn(e.tokenName,"tokenName",Jn),Mn(0,void 0,tr,e.pageSize)}(e);const t=this.buildEndpoint(U,{tokenName:e.tokenName}),n=this.buildPaginationParams(e,tr);this.addOptionalFilterParams(n,e,["search","name","userAddress"]),void 0!==n.userAddress&&(n.userAddress=nn(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(Fn(e.tokenName,"tokenName",Jn),!Rn(e.userAddress))throw Tt("userAddress")}(e);const t=en(e.userAddress,"userAddress"),n=this.buildEndpoint(F,{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:Kt(e.tokenName),userAddress:t}}async getActiveUsers(e){!function(e){if(Fn(e.tokenName,"tokenName",Jn),void 0!==e.type&&!yi(e.type))throw new rt(`type must be one of: ${Object.values(Si).join(", ")}`,"type",nt.INVALID_VALUE)}(e);const t=this.buildEndpoint(B,{tokenName:e.tokenName}),n={};this.addOptionalFilterParams(n,e,["type","search","name","userAddress"]),void 0!==n.userAddress&&(n.userAddress=nn(n.userAddress));const r=await this.http.get(t,n,this.getMultiAuthHeaders());return this.extractData(r)}async createGlobalBan(e){!function(e){Ci(e)}(e);const t=Ri(e),n=await this.http.post(G,t,this.getDualAuthHeaders());return{ban:this.extractData(n)}}async removeGlobalBan(e){!function(e){if(!Rn(e.userAddress))throw Tt("userAddress")}(e);const t=en(e.userAddress,"userAddress"),n=this.buildEndpoint(H,{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){Mn(0,void 0,tr,e.pageSize)}(t);const n=this.buildPaginationParams(t,tr);this.addOptionalFilterParams(n,t,["search","name","userAddress"]),void 0!==n.userAddress&&(n.userAddress=nn(n.userAddress));const r=await this.http.get($,n,this.getDualAuthHeaders()),s=this.extractData(r);return{items:s.bans,pageInfo:s.pageInfo}}async getGlobalBan(e){!function(e){if(!Rn(e.userAddress))throw Tt("userAddress")}(e);const t=en(e.userAddress,"userAddress"),n=this.buildEndpoint(K,{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 Ri(e){const t={userAddress:en(e.userAddress,"userAddress")};return void 0!==e.reason&&(t.reason=e.reason),void 0!==e.durationSeconds&&(t.durationSeconds=e.durationSeconds),t}function Oi(e){return{maxAcceptableReverseBondingCurveFee:bn(e.maxAcceptableReverseBondingCurveFee)}}class xi extends s.ChainCallDTO{constructor(e,t,n="0",r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=bn(t),this.expectedToken=Nn(n),this.extraFees=Oi(r)}}class Mi extends s.ChainCallDTO{constructor(e,t,n,r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=Nn(t),this.expectedNativeToken=bn(n),this.extraFees=Oi(r)}}class Li extends s.ChainCallDTO{constructor(e,t,n="0",r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=Nn(t),this.expectedNativeToken=bn(n),this.extraFees=Oi(r)}}class Ui extends s.ChainCallDTO{constructor(e,t,n,r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=bn(t),this.expectedToken=Nn(n),this.extraFees=Oi(r)}}const Fi={BuyNativeDto:xi,BuyExactDto:Mi,SellExactDto:Li,SellNativeDto:Ui};function Pi(e,t,n){let r;kn(t,0,1,"slippageToleranceFactor");try{r=function(e,t){if(zt(e)||""===e)throw Tt(t);if(a.isBigNumber(e)){if(e.isNaN())throw It(t,"NaN");return e}try{const n=new a(e);if(n.isNaN())throw It(t,e);if(!n.isFinite())throw It(t,e);return n}catch(n){if(n instanceof rt)throw n;throw It(t,e)}}(e,"expectedAmount")}catch{throw new Error(`Invalid expected amount: ${e}. Must be a valid number`)}if(0===t)return e;const s=r.multipliedBy(t);let o;switch(n){case"buy-native":case"sell-exact":o=r.minus(s);break;case"buy-exact":case"sell-native":o=r.plus(s);break;default:throw new Error(`Unknown operation type: ${n}`)}return Eo(o).isLessThan(0)&&(o=Eo(0)),Ao(o)}function Bi(e,t){if(!Rn(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 Gi(e,t,n,r){const s=e?.split?.(t)??[],o=void 0!==n?` (${n})`:"";return new rt(`Invalid ${"|"===t?"pipe":"dollar"}-delimited token: "${e}" (${s.length} parts)${o}. Expected format: "collection${t}category${t}type${t}additionalKey" (4 parts minimum). Received: [${s.map(e=>`"${e}"`).join(", ")}]. Error: ${ut(r)}`,"token",`INVALID_${"|"===t?"PIPE":"DOLLAR"}_DELIMITED_TOKEN`)}function $i(e,t,n){try{const n=Bi(e,t),r=n[n.length-1],s=n[n.length-2],o=n[n.length-3],i=n.slice(0,n.length-3).join(t);if(void 0===i||void 0===o||void 0===s||void 0===r||""===r||""===i||""===o||""===s)throw new Error("All components (collection, category, type, additionalKey) must be non-empty");return{collection:i,category:o,type:s,additionalKey:r}}catch(r){throw Gi(e,t,n,r)}}function Ki(e){return function(e,t,n){try{const n=Bi(e,t),[r,s,o,...i]=n;if(""===r||""===s||""===o)throw new Error("Collection, category, and type must be non-empty");const a=i.join(t);if(void 0===r||void 0===s||void 0===o||""===a)throw new Error("AdditionalKey must be non-empty");return{collection:r,category:s,type:o,additionalKey:a}}catch(r){throw Gi(e,t,n,r)}}(e,"|","pipe-delimited token")}class Hi 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 Wi={name:"GalaChain"},Vi={name:"ethereum",chainId:1};function ji(e){if("string"!=typeof e)throw new Error("Wallet returned an invalid signature");return e}function qi(e,t){const n=Jt(e,t);if(void 0!==n)throw new Hi(n,"INVALID_SIGNER_OPTIONS",{details:{[t]:e}});return e}function zi(e){const t={};for(const[n,r]of Object.entries(e))void 0!==r&&(t[n]=Yi(r));return t}function Yi(e){return Array.isArray(e)?e.map(Yi):"object"==typeof e&&null!==e?zi(e):e}function Xi(e,t,n,r){return{...e,signature:t,types:n,domain:r}}class Qi extends e.PrivateKeySigner{constructor(e){super(e),this.typedDataWallet=new t.Wallet(e),this.walletAddress=`eth|${this.typedDataWallet.address.slice(2)}`}async signTypedData(t,n){const r=zi(n),s=e.generateEIP712Types(t,r);return Xi(r,await this.typedDataWallet.signTypedData(Wi,s,r),s,Wi)}}class Ji extends e.GalaWalletSigner{constructor(t,n={}){const{verifyActiveAccount:r,...s}=n;if(super(qi(t,"walletAddress"),{...s,...void 0!==s.selectAddress&&{selectAddress:qi(s.selectAddress,"selectAddress")}}),this.typedDataWallet=n.wallet,!0===r){const t=e.ethereumAddressOfAccount(this.walletAddress)??(void 0===this.selectAddress?void 0:e.ethereumAddressOfAccount(this.selectAddress));if(void 0===t)throw new Hi("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=t}else this.verifiedKey=void 0}async signTypedData(t,n){const r=zi(n),s=e.generateEIP712Types(t,r),o={domain:Vi,types:s,message:r,Primary_type:t},i=this.typedDataWallet??function(){const e=globalThis.window,t=e?.gala;if(void 0===t)throw new Error("Gala wallet is not available");return t}();void 0!==this.verifiedKey&&await async function(t,n){let r="address"in t&&"string"==typeof t.address&&""!==t.address?t.address:void 0;if(void 0===r){const e=await t.request({method:"eth_accounts"}),n=Array.isArray(e)?e[0]:void 0;r="string"==typeof n&&""!==n?n:void 0}const s=void 0===r?void 0:e.ethereumAddressOfAccount(r);if(void 0===s||s.toLowerCase()!==n.toLowerCase())throw new Hi("Your wallet's active account has changed. Please switch back to the connected account or reconnect your wallet.","WALLET_ACCOUNT_CHANGED",{details:{walletAccount:r??null,signerAccount:n}})}(i,this.verifiedKey);const a=await this.typedDataAccount(i);return Xi(r,ji(await e.withGalaWalletIdentity(i,this.selectAddress??a,()=>i.request({method:"eth_signTypedData",params:[JSON.stringify(o),a]}))),s,Vi)}async typedDataAccount(e){if(t.isAddress(this.walletAddress))return this.walletAddress;const n=await e.request({method:"eth_accounts"}),r=Array.isArray(n)?n[0]:void 0,s="string"==typeof r?r.replace(/^eth\|/,"0x"):"";if(!t.isAddress(s))throw new Error("Gala Wallet did not report an Ethereum account to sign typed data with");return s}}class Zi extends e.BrowserWalletSigner{constructor(e,t,n){super(e,qi(t,"walletAddress"),n),this.typedDataProvider=e}async signTypedData(n,r){const s=zi(r),o=this.typedDataProvider,i=await o.getNetwork(),a={name:i.name,chainId:Number(i.chainId)},c=e.generateEIP712Types(n,s),l=await o.getSigner(),d=t.getAddress(await l.getAddress());if(t.isAddress(this.walletAddress)&&d!==t.getAddress(this.walletAddress))throw new Hi(`Wallet account ${d} is not the account this signer was created for (${this.walletAddress}); reconnect before signing.`,"WALLET_ACCOUNT_CHANGED",{details:{walletAccount:d,signerAccount:this.walletAddress}});return Xi(s,ji(await l.signTypedData(a,c,s)),c,a)}static fromEip1193(n,r,s){const o=new t.BrowserProvider(n);return new Zi({request:e=>n.request(e),getNetwork:()=>o.getNetwork(),getSigner:()=>o.getSigner()},e.ethereumAddressOfAccount(r)??r,s)}}function ea(e){const[t,n]=e.split("|",2);if("service"!==t||void 0===n)throw new Error(`Invalid vaultAddress format (expected service|<collection>$<category>$<type>$<additionalKey>$launchpad): ${e}`);const r=n.split("$"),s=r[r.length-1],o=r.slice(0,-1),i=o.slice(0,-3).join("$"),[a,c,l]=o.slice(-3);if("launchpad"!==s||o.length<4||""===i||void 0===a||void 0===c||void 0===l||""===a||""===c||""===l)throw new Error(`Invalid vaultAddress format (expected service|<collection>$<category>$<type>$<additionalKey>$launchpad): ${e}`);return{collection:i,category:a,type:c,additionalKey:l}}function ta(e){const{collection:t,category:n,type:r}=ea(e),s=`${t}$${n}$${r}$none`,o="GALA$Unit$none$none";return[`$service$${s}$launchpad`,`$tokenBalance$${s}$${e}`,`$tokenBalance$${s}$${e}`,`$tokenBalance$${o}$${e}`,`$tokenBalance$${o}$${e}`]}function na(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 ra(e){return`${e.collection}|${e.category}|${e.type}|${e.additionalKey}`}function sa(t){if("string"==typeof t){if(!Rn(n=t)||!n.includes("|"))throw new rt(`Invalid tokenId string format: "${t}". Expected pipe-delimited format: "collection|category|type|additionalKey" or "collection|category|type|additionalKey|instance"`,"tokenId","INVALID_TOKEN_ID_FORMAT");const e=t.split("|");if(e.length>=5){const t=Ki(e.slice(0,4).join("|")),n=e[4]??"0";return{...t,instance:n.length>0?n:"0"}}return{...Ki(t),instance:"0"}}var n;if("object"==typeof t&&null!==t){if("instance"in t&&void 0!==t.instance&&"string"==typeof t.instance&&t.instance.length>0){if(!e.isTokenClassKey(t))throw new rt("Invalid tokenId object format. All fields (collection, category, type, additionalKey) must be non-empty strings","tokenId","INVALID_TOKEN_ID_FORMAT");return t}if(!e.isTokenClassKey(t))throw new rt("Invalid tokenId object format. All fields (collection, category, type, additionalKey) are required","tokenId","INVALID_TOKEN_ID_FORMAT");return{...t,instance:"0"}}throw new rt(`Invalid tokenId type: ${typeof t}. Expected string, TokenClassKey, or TokenInstanceKey`,"tokenId","INVALID_TOKEN_ID_TYPE")}function oa(e){return function(e){try{if(!Rn(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 $i((n.length>=5&&"launchpad"===n[n.length-1]?n.slice(0,-1):n).join("$"),"$","vault address")}catch(t){throw new rt(`Invalid vault address: "${e}". Expected format: "service|Token$Unit$SYMBOL$additionalKey$launchpad". Error: ${ut(t)}`,"vaultAddress","INVALID_VAULT_ADDRESS_FORMAT")}}(e)}function ia(e){return{...oa(e),instance:"0"}}function aa(e){const t=oa(e);if("Token"!==t.collection)throw new rt(`Cannot extract a token symbol from vault address "${e}": collection "${t.collection}" is not the launchpad "Token" collection, and a symbol cannot be derived from a class key.`,"vaultAddress","SYMBOL_NOT_DERIVABLE_FROM_KEY");return t.type}var ca,la,da,ua,ha=Object.freeze({__proto__:null,extractTokenSymbolFromVault:aa,normalizeToTokenInstanceKey:sa,parseVaultAddressToTokenClassKey:oa,parseVaultAddressToTokenInstance:ia});class ga extends qn{constructor(e=!1){super(e)}generateStringsInstructions(e){try{this.logger.debug("🔧 Generating stringsInstructions for:",e);const t=ta(e);return this.logger.debug("✅ Generated stringsInstructions:",t),t}catch(e){this.logger.error("❌ Failed to generate stringsInstructions:",e);const t=ut(e);throw new rt(`Failed to generate stringsInstructions: ${t}`,"vaultAddress","INVALID_VAULT_ADDRESS")}}createGalaInstance(){const e=new s.TokenClassKey;return e.collection="GALA",e.category="Unit",e.type="none",e.additionalKey="none",this.logger.debug("🟡 Created GALA instance:",{stringKey:e.toStringKey()}),e}extractTokenSymbolFromVault(e){if(!Rn(e))throw Tt("vaultAddress","Vault address");try{const t=aa(e);return this.logger.debug("🔍 Extracted token symbol:",{vaultAddress:e,tokenSymbol:t}),t}catch(e){if(e instanceof rt)throw vt("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad");throw e}}validateVaultAddress(e){if(!Rn(e))throw Tt("vaultAddress","Vault address");if(!e.startsWith("service|Token$Unit$"))throw vt("vaultAddress",'starting with "service|Token$Unit$"');if(!e.endsWith("$launchpad"))throw vt("vaultAddress",'ending with "$launchpad"');const t=function(e){if(!Rn(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 $i(e,"$","dollar-delimited token")}catch(e){if(e instanceof rt)throw vt("stringKey","format: collection$category$type$additionalKey (4 parts)");throw e}}}function pa(e){return"object"==typeof e&&null!==e?e:void 0}class ma extends jn{constructor(t,n,r=!1,s,o,i=.05,a=.01,c){if(super(t,r),this.tokenResolver=n,this._walletProvider=s,this.userAddress=o,this.defaultSlippageToleranceFactor=i,this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor=a,this.sellFeeCeiling=c,this.bundleEndpoint="/bundle",null!==this._walletProvider&&void 0!==this._walletProvider&&null!=o){const t=pa(this._walletProvider),n=t?.privateKey;if("string"==typeof n)this.signer=new Qi(n);else if(function(e){const t=pa(e);return"function"==typeof t?.request}(this._walletProvider)&&void 0!==this.userAddress){const t=Zt(this.userAddress,"userAddress");this.signer=new Zi(this._walletProvider,e.ethereumAddressOfAccount(t)??t)}this.tokenKeyService=new ga(r)}}async submitTransaction(e){try{this.validateBundleData(e),this.logger.debug("📦 Submitting bundle transaction:",{method:e.method,stringsInstructionsCount:e.stringsInstructions.length,signedDtoKeys:Object.keys(e.signedDto)});const t=this.formatBundleRequest(e);this.logger.debug("🚀 Bundle request payload:",{...t,signedDto:"[REDACTED - Contains signature]"});let n=null;try{n=await Pt(()=>this.http.post(this.bundleEndpoint,t),{errorContext:"Bundle transaction submission failed",logger:this.logger})}catch(e){return{success:!1,error:this.formatErrorMessage(e)}}return null==n?{success:!1,error:"No response from bundle API"}:(this.logger.debug("📥 Bundle API response:",{success:n.success,hasData:xt(n),error:n.error}),this.handleBundleResponse(n))}catch(e){if(e instanceof rt)return{success:!1,error:ut(e)};throw e}}validateBundleData(e){if(null==e)throw Tt("bundleData","Bundle data");if(null===e.signedDto||void 0===e.signedDto)throw Tt("signedDto","Signed DTO");if(!Rn(e.method))throw Tt("method","Method name");if(!Array.isArray(e.stringsInstructions))throw vt("stringsInstructions","an array of resource tracking strings");if(0===e.stringsInstructions.length)throw new rt("stringsInstructions cannot be empty","stringsInstructions","EMPTY_ARRAY");const t=["BuyWithNative","BuyExactToken","SellExactToken","SellWithNative"];if(!t.includes(e.method))throw vt("method",`one of: ${t.join(", ")}`);e.stringsInstructions.forEach((e,t)=>{if(!Rn(e))throw new rt(`stringsInstructions[${t}] must be a non-empty string`,`stringsInstructions[${t}]`,"INVALID_INSTRUCTION");if("string"!=typeof(n=e)||!n.includes("$"))throw new rt(`stringsInstructions[${t}] must start with '$': ${e}`,`stringsInstructions[${t}]`,"INVALID_INSTRUCTION_FORMAT");var n}),this.logger.debug("✅ Bundle data validation passed")}formatBundleRequest(e){return{signedDto:e.signedDto,stringsInstructions:e.stringsInstructions,method:e.method}}handleBundleResponse(e){const t=Lt(e);if(null!=t&&!1===e.error)return this.logger.debug("✅ Bundle transaction successful:",t),{success:!0,data:t};const n=("string"==typeof e.error?e.error:e.message)??"Bundle transaction failed";return this.logger.debug("❌ Bundle transaction failed:",n),{success:!1,error:n}}formatErrorMessage(e){if("string"==typeof e)return e;if(pt(e)&&null!==e.response&&void 0!==e.response){const t=Lt(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(!Rn(e))throw Tt("transactionId","Transaction ID");let t;this.logger.debug("🔍 Checking bundler transaction result:",e);try{t=await Pt(()=>this.http.get(`${this.bundleEndpoint}?id=${e}`),{errorContext:"Failed to get bundler transaction result",logger:this.logger})}catch(e){return{success:!1,error:this.formatErrorMessage(e)}}return null==t?{success:!1,error:"No response from bundler transaction query"}:(this.logger.debug("📊 Bundler transaction result:",t),{success:!0,data:t})}catch(e){if(e instanceof rt)return{success:!1,error:ut(e)};throw e}}async cancelTransaction(e){try{if(!Rn(e))throw Tt("transactionId","Transaction ID");let t;this.logger.debug("🚫 Cancelling transaction:",e);try{t=await Pt(()=>this.http.delete(`${this.bundleEndpoint}/${e}`),{errorContext:"Failed to cancel transaction",logger:this.logger})}catch(e){return{success:!1,error:this.formatErrorMessage(e)}}return null==t?{success:!1,error:"No response from transaction cancellation"}:(this.logger.debug("🗑️ Transaction cancellation response:",t),{success:!0,data:t})}catch(e){if(e instanceof rt)return{success:!1,error:ut(e)};throw e}}async getHealthStatus(){this.logger.debug("🏥 Checking bundle service health");try{const e=await Pt(()=>this.http.get(`${this.bundleEndpoint}/health`),{errorContext:"Bundle service health check failed",logger:this.logger});return null==e?{success:!1,error:"No response from bundle service health check"}:(this.logger.debug("💚 Bundle service health:",e),{success:!0,data:e})}catch(e){return{success:!1,error:this.formatErrorMessage(e)}}}async buyToken(e){this.ensureTradingServicesAvailable();const{tokenName:t,amount:n,type:r,expectedAmount:s}=e,{effectiveSlippageFactor:o,effectiveMaxFee:i,vaultAddress:a}=await this.prepareTradingOperation(t,e.maxAcceptableReverseBondingCurveFee,e.maxAcceptableReverseBondingCurveFeeSlippageFactor,e.slippageToleranceFactor);if("native"===r){if(null==s||""===s)throw new rt("expectedAmount is required for native buy operations. Use getBuyTokenAmount() first to calculate expected tokens.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Pi(s,o,"buy-native");this.logger.debug("BuyNative slippage applied:",{originalExpectedTokens:s,slippageFactor:o,adjustedMinTokens:e});const t=new Fi.BuyNativeDto(a,n,e,{maxAcceptableReverseBondingCurveFee:i});return await this.executeBundleTransaction(t,"BuyWithNative",a)}{if(null==s||""===s)throw new rt("expectedAmount is required for exact buy operations. Use getBuyTokenAmount() first to calculate expected GALA cost.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Pi(s,o,"buy-exact");this.logger.debug("BuyExact slippage applied:",{originalExpectedGalaCost:s,slippageFactor:o,adjustedMaxGalaCost:e});const t=new Fi.BuyExactDto(a,n,e,{maxAcceptableReverseBondingCurveFee:i});return await this.executeBundleTransaction(t,"BuyExactToken",a)}}async sellToken(e){this.ensureTradingServicesAvailable();const{tokenName:t,amount:n,type:r,expectedAmount:s}=e,{effectiveSlippageFactor:o,effectiveMaxFee:i,vaultAddress:a}=await this.prepareTradingOperation(t,e.maxAcceptableReverseBondingCurveFee,e.maxAcceptableReverseBondingCurveFeeSlippageFactor,e.slippageToleranceFactor),c=async()=>void 0===e.maxAcceptableReverseBondingCurveFee?this.defaultSellFeeCeiling(e,a):i;if("exact"===r){if(null==s||""===s)throw new rt("expectedAmount is required for exact sell operations. Use getSellTokenAmount() first to calculate expected GALA.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Pi(s,o,"sell-exact");this.logger.debug("SellExact slippage applied:",{originalExpectedGala:s,slippageFactor:o,adjustedMinGala:e});const t={maxAcceptableReverseBondingCurveFee:await c()},r=new Fi.SellExactDto(a,n,e,t);return await this.executeBundleTransaction(r,"SellExactToken",a)}{if(null==s||""===s)throw new rt("expectedAmount is required for native sell operations. Use getSellTokenAmount() first to calculate tokens to sell.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Pi(s,o,"sell-native");this.logger.debug("SellNative slippage applied:",{originalExpectedTokensToSell:s,slippageFactor:o,adjustedMaxTokensToSell:e});const t={maxAcceptableReverseBondingCurveFee:await c()},r=new Fi.SellNativeDto(a,n,e,t);return await this.executeBundleTransaction(r,"SellWithNative",a)}}async prepareTradingOperation(e,t,n,r){const{effectiveSlippageFactor:s,effectiveMaxFee:o}=this.calculateEffectiveSlippage(t,n,r),i=await this.resolveTokenNameToVault(e);if(null==i)throw At(e);return{effectiveSlippageFactor:s,effectiveMaxFee:o,vaultAddress:i}}async defaultSellFeeCeiling(e,t){if(void 0===this.sellFeeCeiling)throw yt("Cannot quote the reverse bonding curve fee for this sell. Pass maxAcceptableReverseBondingCurveFee.","maxAcceptableReverseBondingCurveFee");return this.sellFeeCeiling({method:"exact"===e.type?"SellExactToken":"SellWithNative",vaultAddress:t,quantity:e.amount,tokenName:e.tokenName,feeSlippageFactor:e.maxAcceptableReverseBondingCurveFeeSlippageFactor??this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor})}calculateEffectiveSlippage(e,t,n){const r=n??this.defaultSlippageToleranceFactor,s=t??this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor;let o=e??"0";return null!=e&&(o=Pi(e,s,"buy-exact"),this.logger.debug("Reverse bonding curve fee slippage applied:",{baseFee:e,slippageFactor:s,adjustedMaxFee:o})),{effectiveSlippageFactor:r,effectiveFeeSlippageFactor:s,effectiveMaxFee:o}}ensureTradingServicesAvailable(){if(!this.signer||!this.tokenKeyService)throw yt("Trading services not available. BundleService requires walletProvider and userAddress for trading operations.","walletProvider");if(null===this.userAddress||void 0===this.userAddress)throw Tt("userAddress","User address")}async executeBundleTransaction(t,n,r){this.ensureTradingServicesAvailable();try{t.uniqueKey=`galaswap-operation-${Date.now()}_${o.v4().replace(/-/gu,"").substring(0,26)}`;const s=await this.signer.signObject(n,e.withDtoOperation("asset/launchpad-contract",n,t)),i=this.tokenKeyService.generateStringsInstructions(r),a={stringsInstructions:i,method:n,signedDto:s};this.logger.debug("📦 Bundle transaction data:",{method:n,stringsInstructions:i,dtoKeys:Object.keys(s)});const c=await this.submitTransaction(a);if(c.success){const e=Lt(c);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 l=c.error;throw new lt("string"==typeof l?l:"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 fa extends jn{constructor(e,t=!1){super(e,t)}extractData(e){if(e.error||void 0===e.data){const t=e.message??"Client config operation failed";throw new Error(t)}return e.data}async getClientFlags(){this.logger.debug("Fetching client feature flags");const e=await this.http.get(Xe),t=this.extractData(e);return this.logger.debug("Fetched client feature flags",{flagCount:Object.keys(t.flags).length}),{flags:t.flags}}}exports.ContentType=void 0,(ca=exports.ContentType||(exports.ContentType={})).CHAT_MESSAGE="CHAT_MESSAGE",ca.COMMENT="COMMENT",ca.STREAM="STREAM",ca.RECORDING="RECORDING",exports.FlagReason=void 0,(la=exports.FlagReason||(exports.FlagReason={})).INAPPROPRIATE_CONTENT="INAPPROPRIATE_CONTENT",la.SPAM="SPAM",la.HARASSMENT="HARASSMENT",la.SCAM="SCAM",la.OTHER="OTHER",exports.FlagStatus=void 0,(da=exports.FlagStatus||(exports.FlagStatus={})).PENDING="PENDING",da.DISMISSED="DISMISSED",da.ACTIONED="ACTIONED",exports.FlagAction=void 0,(ua=exports.FlagAction||(exports.FlagAction={})).DELETE_CONTENT="DELETE_CONTENT",ua.BAN_USER="BAN_USER",ua.DELETE_AND_BAN="DELETE_AND_BAN";const Ea={[exports.FlagReason.INAPPROPRIATE_CONTENT]:"Inappropriate Content",[exports.FlagReason.SPAM]:"Spam",[exports.FlagReason.HARASSMENT]:"Harassment",[exports.FlagReason.SCAM]:"Scam",[exports.FlagReason.OTHER]:"Other"},Aa={[exports.FlagStatus.PENDING]:"Pending",[exports.FlagStatus.DISMISSED]:"Dismissed",[exports.FlagStatus.ACTIONED]:"Actioned"},Ta={[exports.FlagAction.DELETE_CONTENT]:"Delete Content",[exports.FlagAction.BAN_USER]:"Ban User",[exports.FlagAction.DELETE_AND_BAN]:"Delete & Ban"},va={[exports.ContentType.CHAT_MESSAGE]:"Chat Message",[exports.ContentType.COMMENT]:"Comment",[exports.ContentType.STREAM]:"Stream",[exports.ContentType.RECORDING]:"Recording"},Sa=Ln(exports.ContentType),ya=Ln(exports.FlagReason),ba=Ln(exports.FlagStatus),Na=Ln(exports.FlagAction),ka=Bn([{field:"id",type:"number"},{field:"tokenName",type:"string"},{field:"contentType",type:"string",validator:Sa},{field:"contentId",type:"string"},{field:"reporterAddress",type:"string"},{field:"reportedUserAddress",type:"string"},{field:"status",type:"string",validator:ba}]),wa={TOKEN_NAME:Xn,TOKEN_NAME_FILTER:Qn,CONTENT_ID:or.CONTENT_ID,DETAILS:or.FLAG_DETAILS,PAGINATION:{MAX_LIMIT:tr}};function _a(e,t,n="tokenName"){Fn(e,n,t)}function Ia(e){if(void 0!==e.contentType&&!Sa(e.contentType))throw vt("contentType",`one of: ${Object.values(exports.ContentType).join(", ")}`,"Content type");if(void 0!==e.status&&!ba(e.status))throw vt("status",`one of: ${Object.values(exports.FlagStatus).join(", ")}`);if(void 0!==e.reason&&!ya(e.reason))throw vt("reason",`one of: ${Object.values(exports.FlagReason).join(", ")}`);if(void 0!==e.reporterAddress&&!Rn(e.reporterAddress))throw _t("reporterAddress","a non-empty string",typeof e.reporterAddress);if(void 0!==e.reporterAddress&&mn(e.reporterAddress,"reporterAddress"),void 0!==e.reportedUserAddress&&!Rn(e.reportedUserAddress))throw _t("reportedUserAddress","a non-empty string",typeof e.reportedUserAddress);void 0!==e.reportedUserAddress&&mn(e.reportedUserAddress,"reportedUserAddress"),Mn(0,void 0,wa.PAGINATION.MAX_LIMIT,e.pageSize)}class Ca extends ci{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async createFlag(e){!function(e){if(_a(e.tokenName,wa.TOKEN_NAME),void 0===e.contentType)throw Tt("contentType","Content type");if(!Sa(e.contentType))throw vt("contentType",`one of: ${Object.values(exports.ContentType).join(", ")}`,"Content type");if(!Rn(e.contentId))throw Tt("contentId","Content ID");if(e.contentId.length>wa.CONTENT_ID.MAX_LENGTH)throw wt("contentId",wa.CONTENT_ID.MAX_LENGTH,e.contentId.length,"Content ID");if(!Rn(e.reportedUserAddress))throw Tt("reportedUserAddress","Reported user address");if(mn(e.reportedUserAddress,"reportedUserAddress"),!(e.contentType!==exports.ContentType.STREAM&&e.contentType!==exports.ContentType.RECORDING||void 0!==e.reason&&null!==e.reason))throw Tt("reason","Reason");if(void 0!==e.reason&&!ya(e.reason))throw vt("reason",`one of: ${Object.values(exports.FlagReason).join(", ")}`,"Reason");if(void 0!==e.details&&!Rn(e.details))throw _t("details","a non-empty string",typeof e.details);if(void 0!==e.details&&e.details.length>wa.DETAILS.MAX_LENGTH)throw wt("details",wa.DETAILS.MAX_LENGTH,e.details.length)}(e);const t={tokenName:e.tokenName,contentType:e.contentType,contentId:e.contentId,reportedUserAddress:tn(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(Z.CREATE,t,this.getMultiAuthHeaders());return{flag:this.extractData(n).flag}}async listFlags(e){return function(e){_a(e.tokenName,wa.TOKEN_NAME_FILTER),Ia(e)}(e),this.fetchFlagList(e)}async listGlobalFlags(e={}){return function(e){void 0!==e.tokenName&&_a(e.tokenName,wa.TOKEN_NAME_FILTER),Ia(e)}(e),this.fetchFlagList(e)}async dismissFlag(e){!function(e){if(void 0===e.flagId||null===e.flagId)throw Tt("flagId","Flag ID");try{_n(e.flagId,"flagId")}catch{throw vt("flagId","a positive integer","Flag ID")}}(e);const t=Z.DISMISS.replace(":id",e.flagId.toString()),n=await this.http.post(t,{},this.getMultiAuthHeaders());return{flag:this.extractData(n).flag}}async actionFlag(e){!function(e){if(void 0===e.flagId||null===e.flagId)throw Tt("flagId","Flag ID");try{_n(e.flagId,"flagId")}catch{throw vt("flagId","a positive integer","Flag ID")}if(void 0===e.action)throw Tt("action","Action");if(!Na(e.action))throw vt("action",`one of: ${Object.values(exports.FlagAction).join(", ")}`,"Action")}(e);const t=Z.ACTION.replace(":id",e.flagId.toString()),n=await this.http.post(t,{action:e.action},this.getMultiAuthHeaders());return{flag:this.extractData(n).flag}}async fetchFlagList(e){const t=ri(e,tr);ii(t,e,["tokenName","contentType","status","reason","reporterAddress","reportedUserAddress"]);for(const e of["reporterAddress","reportedUserAddress"]){const n=t[e];void 0!==n&&(t[e]=tn(n,e))}const n=await this.http.get(Z.LIST,t,this.getMultiAuthHeaders()),r=this.extractData(n);return{items:r.flags,pageInfo:r.pageInfo}}}const Da=["heart","fire","laugh","wow","thumbs_up"];class Ra extends ci{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}validateMessageId(e){if(!Rn(e))throw Tt("messageId","Message ID");if(wn(e,ir.CONTENT_REACTION.MAX_LENGTH,"messageId"),!ir.CONTENT_REACTION.PATTERN.test(e))throw vt("messageId","msg-{timestamp}-{uuid} or chat-{timestamp}-{uuid} format","Message ID")}validateReactionType(e){if(!Rn(e))throw Tt("reactionType","Reaction type");if(!Da.includes(e))throw vt("reactionType",`one of: ${Da.join(", ")}`,"Reaction type")}async addContentReaction(e){this.validateMessageId(e.messageId),this.validateReactionType(e.reactionType);const t=we,n={messageId:e.messageId,reactionType:e.reactionType},r=await this.http.post(t,n,this.getMultiAuthHeaders()),s=this.extractData(r),{created:o,...i}=s;return{data:i,created:o}}async removeContentReaction(e){this.validateMessageId(e.messageId),this.validateReactionType(e.reactionType);const t=`${_e}?${new URLSearchParams({messageId:e.messageId,reactionType:e.reactionType}).toString()}`;return await this.http.delete(t,{},this.getMultiAuthHeaders()),{success:!0}}async addReactionToChatMessage(e){return this.addContentReaction(e)}async removeReactionFromChatMessage(e){return this.removeContentReaction(e)}async addReactionToComment(e){return this.addContentReaction(e)}async removeReactionFromComment(e){return this.removeContentReaction(e)}}const Oa="Token name is required and must be a string";const xa="GALA|Unit|none|none";class Ma extends qn{constructor(e,t,n,r=!1){super(r),this.dexBackendHttp=e,this.cache=t,this.fetchTokenDetails=n}async fetchLaunchpadTokenSpotPrice(e,t,n){if(!Rn(e))throw new rt(Oa,"tokenName",nt.REQUIRED);let r;if(void 0!==n)try{this.logger.debug(`Checking graduation status for token: ${e}`);const t=await n(e);!0===t.isGraduated&&(r=ra(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(xa),s=Tn(n.amount,0)/1e18;if(s<=0)throw new rt(`Invalid token amount calculation: ${s}`,"amount","INVALID_CALCULATION");return{symbol:Ht(e),price:r.price/s}}catch(t){throw St(`Failed to calculate launchpad token spot price for ${e}: ${ut(t)}`,void 0,dt(t)?t:void 0)}}async resolveAuthoritativeSymbol(e){if(e===xa)return"GALA";const t=this.cache?.getByTokenId(e);if(null!=t?.symbol&&""!==t.symbol)return t.symbol;let n;this.logger.debug(`Symbol cache miss for ${e}, reading the token class`);try{if(void 0===this.fetchTokenDetails)throw St("GalaChainService not available for token metadata fetch",500);n=(await this.fetchTokenDetails(e)).symbol}catch(t){throw St(`Could not resolve the symbol for ${e} from the token class, and a symbol cannot be derived from the class key: ${ut(t)}`)}if(""===n)throw St(`Token class for ${e} has no symbol`);return this.cache?.setByTokenId(e,{symbol:n}),n}async fetchMarketUsdPrice(e){try{const t=function(e){if(!Rn(e))throw new Error("Invalid token format: token must be a non-empty string");return e.replace(/\|/g,"$")}(e);if(this.logger.debug(`Fetching swap backend price for token: ${t}`),void 0===this.dexBackendHttp)throw St("DEX Backend API client not configured");const n=await this.resolveAuthoritativeSymbol(e),r=await this.dexBackendHttp.request({method:"GET",url:"/market/price",params:{assetIds:t}}),s=null!==r&&"object"==typeof r?r:{},o=Object.keys(s).find(e=>e.toUpperCase()===n.toUpperCase()),i=void 0!==o?s[o]:1===Object.keys(s).length?Object.values(s)[0]:void 0,a=i?.price;if("number"!=typeof a||!Number.isFinite(a))throw new rt(`Invalid price response: no market price for ${t}`,"data","INVALID_RESPONSE");return this.logger.debug(`Swap backend price for ${n}: $${a}`),{symbol:n,price:a}}catch(e){if(e instanceof rt)throw e;throw St(`Failed to fetch DEX spot price: ${ut(e)}`)}}}const La={BATCH_SIZE:20,FLUSH_INTERVAL_MS:3e3,MAX_QUEUE_SIZE:1e3,FLUSH_ON_PAGE_HIDE:!0,FLUSH_ON_PAGE_UNLOAD:!0,DEBUG:!1};class Ua{constructor(e,t={}){this.eventBuffer=[],this.flushTimer=null,this.isShuttingDown=!1,this.totalQueued=0,this.totalFlushed=0,this.totalDropped=0,this.handleVisibilityChange=()=>{"hidden"===document.visibilityState&&this.eventBuffer.length>0&&this.flushWithBeacon()},this.handleBeforeUnload=()=>{this.eventBuffer.length>0&&this.flushWithBeacon()},this.httpClient=e,this.logger=new Vt({debug:t.debug??!1,context:"EventsBatcherService"}),this.config={batchSize:t.batchSize??La.BATCH_SIZE,flushIntervalMs:t.flushIntervalMs??La.FLUSH_INTERVAL_MS,maxQueueSize:t.maxQueueSize??La.MAX_QUEUE_SIZE,flushOnPageHide:t.flushOnPageHide??La.FLUSH_ON_PAGE_HIDE,flushOnPageUnload:t.flushOnPageUnload??La.FLUSH_ON_PAGE_UNLOAD,debug:t.debug??La.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:en(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 Fa=["createdAt","eventType","userAddress"],Pa=["last_hour","today","yesterday","last_7_days","last_30_days","custom"],Ba=["sdk","frontend","backend","mcp"];function Ga(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function $a(e){return"number"==typeof e&&Number.isFinite(e)}function Ka(e){return Ga(e)&&$a(e.id)&&"string"==typeof e.eventType&&Ga(e.payload)&&"string"==typeof e.createdAt&&"string"==typeof e.updatedAt}function Ha(e,t,n){if(!t.some(t=>t===e))throw new rt(`${n} must be one of: ${t.join(", ")}`,n,nt.INVALID_VALUE)}class Wa extends ci{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async getEventStats(){return function(e){if(!(Ga(e)&&$a(e.totalEvents)&&$a(e.todayEvents)&&$a(e.uniqueUsers)&&$a(e.uniqueTokens)&&Ga(e.eventsByType)))throw St("Malformed event statistics response");const t={};for(const[n,r]of Object.entries(e.eventsByType)){if(!$a(r))throw St("Malformed event statistics response");t[n]=r}return{totalEvents:e.totalEvents,todayEvents:e.todayEvents,uniqueUsers:e.uniqueUsers,uniqueTokens:e.uniqueTokens,eventsByType:t}}(await this.http.get(Fe,void 0,this.getDualAuthHeaders()))}async queryEvents(e={}){!function(e){if(void 0!==e.limit&&(!Number.isInteger(e.limit)||e.limit<1||e.limit>100))throw new rt("limit must be an integer from 1 to 100","limit",nt.INVALID_VALUE);if(void 0!==e.page&&(!Number.isInteger(e.page)||e.page<1))throw new rt("page must be a positive integer","page",nt.INVALID_VALUE);void 0!==e.sortBy&&Ha(e.sortBy,Fa,"sortBy"),void 0!==e.sortOrder&&Ha(e.sortOrder,["asc","desc"],"sortOrder"),void 0!==e.timePreset&&Ha(e.timePreset,Pa,"timePreset"),void 0!==e.source&&Ha(e.source,Ba,"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?en(s,"userAddress"):s}const r=n.toString(),s=""===r?Ue:`${Ue}?${r}`;return function(e){if(!Ga(e)||!Array.isArray(e.data)||!Ga(e.pagination))throw St("Malformed events response");const t=e.pagination,n=e.data;if(!($a(t.page)&&$a(t.limit)&&$a(t.total)&&$a(t.totalPages)&&n.every(Ka)))throw St("Malformed events response");return{data:n,pagination:{page:t.page,limit:t.limit,total:t.total,totalPages:t.totalPages}}}(await this.http.get(s,t,this.getDualAuthHeaders()))}}function Va(e){let t;return{requestor:async(n,r)=>{const s="string"==typeof r?.body?JSON.parse(r.body):void 0,{data:o,status:i,headers:a}=await e(n,s);t=o;const c=void 0===o?"":JSON.stringify(o),l="number"==typeof i?i:200;return{ok:l>=200&&l<300,status:l,json:()=>Promise.resolve(o),text:()=>Promise.resolve(c),headers:a??{}}},answer:()=>t}}const ja=new Set(["GATEWAY_READ_REJECTED","GATEWAY_READ_RESPONSE_INVALID"]);class qa extends jn{constructor(e,t=!1){super(e,t)}async fetchGalaBalance(e){return this.fetchTokenBalance(e)}async fetchTokenBalance(t,n=!1){const r=Zt(t.owner,"owner");try{const{requestor:s}=Va(async(e,t)=>({data:await this.http.post(e,t)})),o=new e.GatewayReads({gatewayBaseUrl:"",httpRequestor:s,requestTimeoutMs:1/0}),{collection:i,category:a,type:c,additionalKey:l}=t,d=await o.fetchTokenBalance({owner:r,tokenClassKey:{collection:i,category:a,type:c,additionalKey:l},includeExpiredHolds:n});return void 0===d?null:function(e){if("0"===e.quantity)return null;const{collection:t,category:n}=e.tokenClassKey,r={quantity:e.quantity,collection:t,category:n,tokenId:ra(e.tokenClassKey)};return e.inUseHolds.length>0&&(r.inUseHolds=[...e.inUseHolds],r.inUseQuantity=e.inUseQuantity),e.lockedHolds.length>0&&(r.lockedHolds=[...e.lockedHolds],r.lockedQuantity=e.lockedQuantity),void 0===r.lockedQuantity&&void 0===r.inUseQuantity||(r.availableQuantity=e.availableQuantity),r}(d)}catch(t){if(e.isGalaError(t)&&ja.has(t.code))return null;throw St(`Failed to fetch token balance from GalaChain: ${ut(t)}`,void 0,dt(t)?t:void 0)}}}function za(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Rn(t.amount)&&(void 0!==t.tokenId||Rn(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 Ya(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Rn(t.amount)&&(void 0!==t.tokenId||Rn(t.tokenName))&&(void 0===t.name||"string"==typeof t.name)}function Xa(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every(za)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}function Qa(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every(Ya)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}var Ja,Za;exports.LockErrorType=void 0,(Ja=exports.LockErrorType||(exports.LockErrorType={})).TOKEN_NOT_FOUND="TOKEN_NOT_FOUND",Ja.INVALID_AMOUNT="INVALID_AMOUNT",Ja.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",Ja.SIGNATURE_FAILED="SIGNATURE_FAILED",Ja.NETWORK_ERROR="NETWORK_ERROR",Ja.WALLET_REQUIRED="WALLET_REQUIRED",Ja.VALIDATION_ERROR="VALIDATION_ERROR",Ja.LOCK_NOT_FOUND="LOCK_NOT_FOUND",Ja.LOCK_EXPIRED="LOCK_EXPIRED",Ja.INSUFFICIENT_LOCKED_BALANCE="INSUFFICIENT_LOCKED_BALANCE",Ja.NOT_LOCK_AUTHORITY="NOT_LOCK_AUTHORITY",Ja.LOCK_NAME_MISMATCH="LOCK_NAME_MISMATCH";class ec 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"}(Za||(Za={}));class tc extends Error{constructor(e,t,n){super(e),this.type=t,this.details=n,this.name="TransferError"}}function nc(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 rc(e,t,n,r="[DEBUG] Token resolution (launchpad)"){const s=await t.resolveTokenToVault(e);if(null!==s){const t=ia(s);return n.debug(r,{tokenName:e,vaultAddress:s,tokenInstance:{collection:t.collection,category:t.category,type:t.type,instance:t.instance}}),t}throw new rt(`Token "${e}" is not a launchpad token (no vault address found), and a token class key cannot be derived from a name. Pass an explicit tokenId (collection|category|type|additionalKey) for standard GalaChain tokens.`,"tokenName","TOKEN_CLASS_KEY_NOT_DERIVABLE")}class sc extends jn{constructor(e,t,n,r=!1,s){super(e,r),this.wallet=t,this.tokenResolver=n,this.writer=s,this.nativeSigner=t?new Qi(t.privateKey):void 0}writeIdentity(){return void 0!==this.wallet&&void 0!==this.nativeSigner?{signer:this.nativeSigner,walletAddress:cn(this.wallet.address)}:this.writer}}function oc(e,t){const{collection:n,category:r,type:s,additionalKey:o,instance:i}=e;return{tokenClassKey:{collection:n,category:r,type:s,additionalKey:o},instance:i,quantity:t}}const ic=new Set(["GATEWAY_WRITE_REJECTED","GATEWAY_RESPONSE_INVALID","GATEWAY_HTTP_ERROR"]);function ac(t,{signer:n,walletAddress:r}){const{requestor:s,answer:o}=Va((e,n)=>t.postWithMeta(e,n));return{writes:new e.GatewayWrites({gatewayBaseUrl:"",signer:n,walletAddress:r,httpRequestor:s,requestTimeoutMs:1/0,uniqueKeyPrefix:"galaconnect-operation-"}),answer:o}}async function cc(t,n,r){let s;try{s=await n(t.writes)}catch(n){throw function(t){return e.isGalaError(t)&&ic.has(t.code)}(n)&&r(t.answer(),void 0),n}return r(t.answer(),s)}function lc(e){return void 0===e||""===e?{}:{uniqueKey:e}}const dc=100,uc=100;class hc extends sc{async lockTokens(e){this.validateLockTokensData(e);const t=this.writeIdentity();if(void 0===t)throw new ec("Wallet required for token lock operations",exports.LockErrorType.WALLET_REQUIRED);return $o(async()=>{const n=ac(this.http,t),r=n.writes.walletAddress,s=[],o=[];let i=r;const a=e.tokens.find(e=>void 0!==e.lockAuthority);void 0!==a?.lockAuthority&&(i=cn(a.lockAuthority));const c=e.tokens.find(e=>void 0!==e.expires),l=e.tokens.find(e=>void 0!==e.name);for(const t of e.tokens){const e=await this.resolveTokenEntry(t);o.push(oc(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?cn(t.lockAuthority):i})}return cc(n,t=>t.lockTokens({tokens:o,lockAuthority:i,...void 0!==c?.expires&&{expires:c.expires},...void 0!==l?.name&&{name:l.name},...lc(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 ec("Wallet required for token unlock operations",exports.LockErrorType.WALLET_REQUIRED);return $o(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(oc(e,t.amount)),n.push({tokenClassKey:{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey},quantity:t.amount})}return cc(ac(this.http,t),t=>t.unlockTokens({tokens:r,...void 0!==s?.name&&{name:s.name},...lc(e.uniqueKey)}),(e,t)=>(this.assertLockAnswer(e,"Token unlock failed"),this.extractUnlockResult(e,t,n)))},"Token unlock failed",this.logger,t=>{throw this.handleLockError(t,"Token unlock failed",e)})}assertLockAnswer(e,t){try{mt(e,t)}catch(t){const n=function(e){if(null==e||"object"!=typeof e)return"";const t=e.Message;return"string"==typeof t&&t.trim().length>0?` - ${t}`:""}(e);throw new ec(`${ut(t)}${n}`,exports.LockErrorType.NETWORK_ERROR)}}validateSharedTokenEntry(e,t,n){if(void 0===e.tokenId&&void 0===e.tokenName)throw new ec("Must provide either tokenId or tokenName for token identification",exports.LockErrorType.TOKEN_NOT_FOUND);if(void 0!==e.tokenName)try{Pn(e.tokenName,"tokenName",Jn)}catch{throw new ec("Invalid token name format",exports.LockErrorType.TOKEN_NOT_FOUND,{tokenName:e.tokenName})}try{yo(Eo(e.amount))}catch{throw new ec(vt(t,"a positive number",n).message,exports.LockErrorType.INVALID_AMOUNT,{amount:e.amount})}}validateLockTokensData(e){if(!Xa(e))throw new ec("Invalid lock data: missing required fields",exports.LockErrorType.VALIDATION_ERROR);if(e.tokens.length>dc)throw new ec(`Batch size exceeds maximum limit of ${dc} tokens per lock operation`,exports.LockErrorType.VALIDATION_ERROR);for(const t of e.tokens){if(this.validateSharedTokenEntry(t,"lockAmount","Lock amount"),void 0!==t.lockAuthority&&!un(t.lockAuthority))throw new ec("Invalid lock authority address format",exports.LockErrorType.VALIDATION_ERROR,{lockAuthority:t.lockAuthority});if(void 0!==t.expires)try{_n(t.expires,"expires")}catch{throw new ec(vt("expires","a positive integer (epoch milliseconds)","Expires").message,exports.LockErrorType.VALIDATION_ERROR)}}}validateUnlockTokensData(e){if(!Qa(e))throw new ec("Invalid unlock data: missing required fields",exports.LockErrorType.VALIDATION_ERROR);if(e.tokens.length>uc)throw new ec(`Batch size exceeds maximum limit of ${uc} tokens per unlock operation`,exports.LockErrorType.VALIDATION_ERROR);for(const t of e.tokens)this.validateSharedTokenEntry(t,"unlockAmount","Unlock amount")}transactionIdOf(e,t){const n=Array.isArray(e.Data)?e.Data[0]:void 0;return t?.transactionId??n?.transactionId??n?.txnId??n?.TxnId??n?.id??void 0}extractLockResult(e,t,n){const r=this.transactionIdOf(e,t),s=t?.blockNumber;return{...void 0!==r&&{transactionId:r},...void 0!==s&&{blockNumber:s},locked:n}}extractUnlockResult(e,t,n){const r=this.transactionIdOf(e,t),s=t?.blockNumber;return{...void 0!==r&&{transactionId:r},...void 0!==s&&{blockNumber:s},unlocked:n}}handleLockError(t,n,r){if(t instanceof ec)return t;if(e.isGalaError(t)&&"pre_send"===t.phase)return new ec(`${n}: ${t.message}`,"SIGNING_FAILED"===(s=t.code)?exports.LockErrorType.SIGNATURE_FAILED:"INVALID_TOKEN_REFERENCE"===s?exports.LockErrorType.TOKEN_NOT_FOUND:"INVALID_QUANTITY"===s?exports.LockErrorType.INVALID_AMOUNT:exports.LockErrorType.VALIDATION_ERROR,nc(r));var s;let o=n,i=exports.LockErrorType.NETWORK_ERROR;if(pt(t)){const e=t.response?.data;if("object"==typeof e&&null!==e){const t=e.Message;"string"==typeof t&&t.length>0&&(o=`${n}: ${t}`);const r="string"==typeof t?t.toLowerCase():"";r.includes("insufficient")||r.includes("balance")?i=exports.LockErrorType.INSUFFICIENT_BALANCE:r.includes("lock")&&r.includes("not found")?i=exports.LockErrorType.LOCK_NOT_FOUND:r.includes("not found")||r.includes("token")?i=exports.LockErrorType.TOKEN_NOT_FOUND:r.includes("authority")?i=exports.LockErrorType.NOT_LOCK_AUTHORITY:r.includes("expired")&&(i=exports.LockErrorType.LOCK_EXPIRED)}}else dt(t)&&(o=`${n}: ${ut(t)}`);return new ec(o,i,nc(r))}async resolveTokenInstance(e){return $o(async()=>rc(e,this.tokenResolver,this.logger),`Failed to resolve token '${e}'`,this.logger,t=>{if(t instanceof tc)throw new ec(ut(t),exports.LockErrorType.TOKEN_NOT_FOUND);throw new ec(`Failed to resolve token '${e}': ${ut(t)}`,exports.LockErrorType.TOKEN_NOT_FOUND,{tokenName:e})})}async resolveTokenEntry(e){if(void 0!==e.tokenId){const t=sa(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 ec("Must provide either tokenId or tokenName for token identification",exports.LockErrorType.TOKEN_NOT_FOUND)}}const gc=new Set(["GATEWAY_READ_REJECTED","GATEWAY_READ_RESPONSE_INVALID","TOKEN_CLASS_NOT_FOUND"]);function pc(e){const t=e?.Data;return Array.isArray(t)?t:void 0}class mc extends jn{constructor(e,t=!1,n){super(e,t),this.publicAxios=n}async fetchTokenClassFromChain(e){try{const t="string"==typeof e?sa(e):e,{collection:n,category:r,type:s,additionalKey:o}=t,i={collection:n,category:r,type:s,additionalKey:o},a="Failed to fetch token class from GalaChain";return await this.readPublic(e=>e.fetchTokenClass(i),e=>{if(mt(e,a),void 0===pc(e)?.[0])throw St(`Token not found on GalaChain: ${ra(i)}`,404)},()=>St(`Token not found on GalaChain: ${ra(i)}`,404))}catch(e){return this.handleTokenServiceError(e,"Token not found on GalaChain","Failed to fetch token class from GalaChain")}}async fetchTokenClassesWithSupply(e){try{if(null==e||0===e.length)throw Tt("tokenClasses","Token classes array");return await this.readPublic(t=>t.fetchTokenClassesWithSupply(e),e=>{if(mt(e,"Failed to fetch token classes with supply from GalaChain"),0===(pc(e)?.length??0))throw St("No token supply data found for requested token classes",404)},void 0)}catch(e){return this.handleTokenServiceError(e,"Token supply data not found on GalaChain","Failed to fetch token classes with supply from GalaChain")}}async readPublic(t,n,r){if(!this.publicAxios)throw Tt("publicAxios","Public Axios instance");const s=this.publicAxios,{requestor:o,answer:i}=Va(async(e,t)=>{const n=await s.post(e,t);return{data:n.data,status:n.status}});try{return await t(new e.GatewayReads({gatewayBaseUrl:"",httpRequestor:o,requestTimeoutMs:1/0}))}catch(t){if(e.isGalaError(t)&&gc.has(t.code)&&(n(i()),"TOKEN_CLASS_NOT_FOUND"===t.code&&void 0!==r))throw r();throw t}}handleTokenServiceError(e,t,n){if(e instanceof rt)throw e;if(pt(e)&&404===e.response?.status)throw St(t,404,dt(e)?e:void 0);if(dt(e)&&"Error"===e.name&&ut(e).includes("status indicates failure"))throw St(ut(e),400,dt(e)?e:void 0);const r=ut(e);if(r.includes("Token not found")){if(e instanceof Error)throw e;throw new Error(r)}throw St(`${n}: ${r}`,void 0,dt(e)?e:void 0)}}function fc(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Rn(t.amount)&&(void 0!==t.tokenId||Rn(t.tokenName))}function Ec(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)}var Ac;exports.BurnErrorType=void 0,(Ac=exports.BurnErrorType||(exports.BurnErrorType={})).TOKEN_NOT_FOUND="TOKEN_NOT_FOUND",Ac.INVALID_AMOUNT="INVALID_AMOUNT",Ac.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",Ac.SIGNATURE_FAILED="SIGNATURE_FAILED",Ac.NETWORK_ERROR="NETWORK_ERROR",Ac.WALLET_REQUIRED="WALLET_REQUIRED",Ac.VALIDATION_ERROR="VALIDATION_ERROR";class Tc extends Error{constructor(e,t,n){super(e),this.type=t,this.details=n,this.name="BurnError"}}const vc={validateAmount(e){const t=Eo(e);try{bo(t,"amount")}catch(t){throw new tc(t.message,Za.INVALID_AMOUNT,{amount:e})}},validateUniqueKey(e){if(!xn(e)&&Rn(e)){if(e.length>lr.MAX_LENGTH)throw new rt(`Unique key too long. Maximum length: ${lr.MAX_LENGTH}`);if(!lr.PATTERN.test(e))throw new tc('Invalid unique key format. Must start with "galaswap-operation-" or "galaconnect-operation-"',Za.INVALID_AMOUNT,{uniqueKey:e})}}},Sc="gala-transfer-successful",yc="token-transfer-successful",bc="token-locked-successfully",Nc="token-unlocked-successfully",kc="transfer-successful-no-id",wc=50;class _c extends sc{async transferGala(e){this.validateTransferGalaData(e);const t=this.writeIdentity();if(void 0===t)throw new tc("Wallet required for GALA transfer operations",Za.WALLET_REQUIRED);try{const n=cn(e.recipientAddress),r=ac(this.http,t);return await cc(r,t=>t.transferGala({to:n,quantity:e.amount,...lc(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 tc("Wallet required for token transfer operations",Za.WALLET_REQUIRED);try{const n=cn(e.to),r=await this.tokenInstanceOf(e.tokenId,e.tokenName,()=>new tc("Must provide either tokenId or tokenName for token identification",Za.TOKEN_NOT_FOUND)),s=ac(this.http,t);return await cc(s,t=>t.transferToken({to:n,...oc(r,e.amount),...lc(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 tc)throw t;throw new tc(`Failed to resolve token class key for '${e}': ${ut(t)}`,Za.TOKEN_NOT_FOUND,{tokenName:e})}}async burnTokens(e){this.validateBurnTokensData(e);const t=this.writeIdentity();if(void 0===t)throw new Tc("Wallet required for token burn operations",exports.BurnErrorType.WALLET_REQUIRED);try{const n=[];for(const t of e.tokens){const e=await this.tokenInstanceOf(t.tokenId,t.tokenName,()=>new Tc("Must provide either tokenId or tokenName for token identification",exports.BurnErrorType.TOKEN_NOT_FOUND));n.push(oc(e,t.amount))}const r=ac(this.http,t);return await cc(r,t=>t.burnTokens({tokens:n,...lc(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 Rn(t.recipientAddress)&&Rn(t.amount)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)}(e))throw new rt("Invalid GALA transfer data: missing required fields");if(!un(e.recipientAddress))throw new tc("Invalid recipient address format",Za.INVALID_RECIPIENT,{recipientAddress:e.recipientAddress});vc.validateAmount(e.amount),vc.validateUniqueKey(e.uniqueKey)}validateTransferTokenData(e){if(!function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Rn(t.to)&&Rn(t.amount)&&(void 0!==t.tokenId||Rn(t.tokenName))&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)}(e))throw new rt("Invalid token transfer data: missing required fields");if(!un(e.to))throw new tc("Invalid recipient address format",Za.INVALID_RECIPIENT,{recipientAddress:e.to});if(!(null!==e.tokenId&&void 0!==e.tokenId||null!==e.tokenName&&void 0!==e.tokenName))throw new tc("Must provide either tokenId or tokenName for token identification",Za.TOKEN_NOT_FOUND);if(null!==e.tokenName&&void 0!==e.tokenName)try{Pn(e.tokenName,"tokenName",Jn)}catch{throw new tc("Invalid token name format",Za.TOKEN_NOT_FOUND,{tokenName:e.tokenName})}vc.validateAmount(e.amount),vc.validateUniqueKey(e.uniqueKey)}validateBurnTokensData(e){if(!Ec(e))throw new Tc("Invalid burn data: missing required fields",exports.BurnErrorType.VALIDATION_ERROR);if(e.tokens.length>wc)throw new Tc(`Batch size exceeds maximum limit of ${wc} tokens per burn operation`,exports.BurnErrorType.VALIDATION_ERROR);for(const t of e.tokens){if(!(null!==t.tokenId&&void 0!==t.tokenId||null!==t.tokenName&&void 0!==t.tokenName))throw new Tc("Must provide either tokenId or tokenName for token identification",exports.BurnErrorType.TOKEN_NOT_FOUND);const e=Eo(t.amount);try{yo(e)}catch{throw new Tc("Burn amount must be a positive number",exports.BurnErrorType.INVALID_AMOUNT,{amount:t.amount})}}}async tokenInstanceOf(e,t,n){if(null!=e){const t=sa(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 rc(e,this.tokenResolver,this.logger,`[DEBUG] Token resolution for '${e}' (launchpad):`)}catch(t){if(t instanceof tc)throw t;throw new tc(`Failed to resolve token '${e}': ${ut(t)}`,Za.TOKEN_NOT_FOUND,{tokenName:e})}}extractTransferResult(e,t,n){if(null==e)throw new tc("No response from GalaChain transfer service",Za.NETWORK_ERROR);const r=t?.blockNumber,s="object"==typeof e&&"Status"in e;s&&mt(e,"Extract transaction ID");const o=s&&"Data"in e,i=t?.transactionId;if(void 0!==i)return{transactionId:i,...void 0!==r?{blockNumber:r}:{}};if(o){const t=e;if(Array.isArray(t.Data)){for(const e of t.Data)if(null!=e&&"object"==typeof e){const t=e;for(const e of["transactionId","txnId","TxnId","id","txId"]){const n=t[e];if("string"==typeof n&&n.length>0)return{transactionId:n,...void 0!==r?{blockNumber:r}:{}}}}let e=kc;if(t.Data.length>0)switch(n){case"gala":e=Sc;break;case"token":e=yc;break;case"lock":e=bc;break;case"unlock":e=Nc}return{transactionId:e,...void 0!==r?{blockNumber:r}:{}}}}throw new tc("Operation succeeded but transaction ID could not be extracted (missing x-transaction-id header and body fields)",Za.NETWORK_ERROR)}burnResultOf(e,t){if(null==e)throw new Tc("No response from GalaChain burn service",exports.BurnErrorType.NETWORK_ERROR);try{mt(e,"Token burn operation")}catch(e){throw new at(ut(e),500)}return this.extractBurnResult(e,t)}extractBurnResult(e,t){const n=[];if(null!==e.Data&&void 0!==e.Data&&Array.isArray(e.Data))for(const t of e.Data)n.push({collection:t.collection??"",category:t.category??"",type:t.type??"",additionalKey:t.additionalKey??"",instance:t.instance??"0",quantity:t.quantity??"0",burnedBy:t.burnedBy??""});const r=Array.isArray(e.Data)?e.Data[0]:void 0,s=t?.transactionId??r?.transactionId??r?.txnId??r?.TxnId??r?.id??void 0,o=t?.blockNumber;return{...void 0!==s&&{transactionId:s},...void 0!==o&&{blockNumber:o},burned:n}}handleTransferError(t,n,r){if(t instanceof tc)return t;if(t instanceof rt)return new tc(ut(t),Za.INVALID_AMOUNT);if(e.isGalaError(t)&&"pre_send"===t.phase)return new tc(t.message,"SIGNING_FAILED"===(s=t.code)?Za.SIGNATURE_FAILED:"INVALID_WALLET_ADDRESS"===s?Za.INVALID_RECIPIENT:"INVALID_TOKEN_REFERENCE"===s?Za.TOKEN_NOT_FOUND:Za.INVALID_AMOUNT);var s;if(pt(t)&&t.response){const e=t.response.status,n=t.response.data;if(400===e){const e=n?.message;return new tc(("string"==typeof e?e:void 0)??"Invalid transfer request",Za.INVALID_AMOUNT)}if(403===e)return new tc("Insufficient balance for transfer",Za.INSUFFICIENT_BALANCE);if(404===e){const e={};return"tokenName"in r&&(e.tokenName=r.tokenName),new tc("Token not found",Za.TOKEN_NOT_FOUND,e)}}if("object"==typeof t&&null!==t&&"code"in t&&("ECONNABORTED"===gt(t)||"ETIMEDOUT"===gt(t)))return new tc("Transfer request timed out",Za.NETWORK_ERROR);const o=""!==ut(t)?ut(t):n;return new tc(o,Za.NETWORK_ERROR)}handleBurnError(t,n,r){if(t instanceof Tc)return t;if(e.isGalaError(t)&&"pre_send"===t.phase)return new Tc(`${n}: ${t.message}`,"SIGNING_FAILED"===(s=t.code)?exports.BurnErrorType.SIGNATURE_FAILED:"INVALID_TOKEN_REFERENCE"===s?exports.BurnErrorType.TOKEN_NOT_FOUND:"INVALID_QUANTITY"===s?exports.BurnErrorType.INVALID_AMOUNT:exports.BurnErrorType.VALIDATION_ERROR,nc(r));var s;let o=n,i=exports.BurnErrorType.NETWORK_ERROR;if(pt(t)){const e=t.response?.data;if("object"==typeof e){const t=e.Message;if("string"==typeof t&&t.length>0){o=`${n}: ${t}`;const e=t.toLowerCase();e.includes("insufficient")||e.includes("balance")?i=exports.BurnErrorType.INSUFFICIENT_BALANCE:(e.includes("not found")||e.includes("token"))&&(i=exports.BurnErrorType.TOKEN_NOT_FOUND)}}}else dt(t)&&(o=`${n}: ${ut(t)}`);return new Tc(o,i,nc(r))}}class Ic extends jn{constructor(e,t,n,r=!1,s,o){super(e,r),this.balanceService=new qa(e,r),this.tokenService=new mc(e,r,s),this.lockService=new hc(e,t,n,r,o),this.transferService=new _c(e,t,n,r,o)}async fetchGalaBalance(e){return this.balanceService.fetchGalaBalance(e)}async fetchTokenBalance(e,t=!1){return this.balanceService.fetchTokenBalance(e,t)}async fetchTokenClassFromChain(e){return this.tokenService.fetchTokenClassFromChain(e)}async fetchTokenDetails(t){try{return e.tokenDetailsOf(await this.fetchTokenClassFromChain(t))}catch(e){if(dt(e)&&("NetworkError"===e.name||ut(e).includes("Token not found")))throw e;throw St(`Failed to fetch token details from GalaChain for ${"string"==typeof t?t:ra(t)}: ${ut(e)}`,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 Cc extends jn{async getHealth(){const e=(await this.http.get(Pe)).data;if(null==e)throw St("Health check answered no data");return e}}class Dc extends Error{constructor(e,t,n){super(e),this.filename=t,this.mimeType=n,this.name="FileValidationError"}}function Rc(e,t,n){if(null==e)throw new Dc("File is required",t,n);if("undefined"!=typeof File&&e instanceof File){const t=Vr.safeParse(e);if(!t.success){const n=t.error.issues.map(e=>e.message).join("; ");throw new Dc(n,e.name,e.type)}return}if(Buffer.isBuffer(e)){if(void 0===t||""===t)throw new Dc("Filename is required when uploading Buffer objects",t,n);const r=jr.safeParse(e);if(!r.success){const e=r.error.issues.map(e=>e.message).join("; ");throw new Dc(e,t,n)}try{wn(t,255,"filename")}catch(e){throw new Dc(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 Dc(`Invalid file type "${n}" is not allowed. Allowed types: ${s.join(", ")}`,t,n);const o=function(e){if(null==e||""===e)return"";const t=e.lastIndexOf(".");if(-1===t)return"";return e.substring(t).toLowerCase()}(t),i=[".png",".jpg",".jpeg",".gif",".webp",".svg"];if(!i.includes(o))throw new Dc(`File extension "${o}" is not allowed. Allowed extensions: ${i.join(", ")}`,t,n);const a=function(e){switch(e.toLowerCase()){case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";case".gif":return"image/gif";case".webp":return"image/webp";case".svg":return"image/svg+xml";default:return"application/octet-stream"}}(o);if(a!==n&&"application/octet-stream"!==a)throw new Dc(`File extension "${o}" does not match MIME type "${n}"`,t,n);return}throw new Dc("File must be a File object (browser) or Buffer (Node.js)",t,n)}function Oc(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 xc extends jn{constructor(e,t,n=!1){super(e,n,t)}async uploadImageByTokenName(e){const{tokenName:t,options:n}=e;Fn(t,"tokenName",Jn);const r=`${t}.png`;Rc(n.file,r,"image/png");try{const e=Oc(n.file,"image",r),s=await Ft(()=>this.http.request({method:"POST",url:oi(l.UPLOAD_IMAGE,{tokenName:t}),data:e,headers:this.getJwtHeaders()}),{errorContext:"Image upload failed"});return"string"==typeof s?s:""}catch(e){if(e instanceof ct)throw e;if(dt(e)&&ut(e).includes("FormData"))throw yt("File upload failed: FormData not supported in this environment. Ensure you have proper polyfills for Node.js environments.","FormData");throw e}}}function Mc(e){if(!!(void 0===e.chatEnabled&&void 0===e.commentsEnabled&&void 0===e.streamingEnabled&&void 0===e.nextLiveStreamAt&&void 0===e.streamLanguage&&void 0===e.websiteUrl&&void 0===e.telegramUrl&&void 0===e.twitterUrl&&void 0===e.instagramUrl&&void 0===e.facebookUrl&&void 0===e.redditUrl&&void 0===e.tiktokUrl))throw new rt("At least one config option must be provided (chatEnabled, commentsEnabled, streamingEnabled, nextLiveStreamAt, streamLanguage, or social URLs)","options",nt.REQUIRED);if(void 0!==e.chatEnabled&&"boolean"!=typeof e.chatEnabled)throw _t("chatEnabled","boolean");if(void 0!==e.commentsEnabled&&"boolean"!=typeof e.commentsEnabled)throw _t("commentsEnabled","boolean");if(void 0!==e.streamingEnabled&&"boolean"!=typeof e.streamingEnabled)throw _t("streamingEnabled","boolean");if(void 0!==e.streamLanguage&&"string"!=typeof e.streamLanguage)throw _t("streamLanguage","string");const t=["websiteUrl","telegramUrl","twitterUrl","instagramUrl","facebookUrl","redditUrl","tiktokUrl"];for(const n of t){const t=e[n];if(null!=t&&"string"!=typeof t)throw _t(n,"string or null")}if(void 0!==e.nextLiveStreamAt&&null!==e.nextLiveStreamAt){if("string"!=typeof e.nextLiveStreamAt)throw _t("nextLiveStreamAt","string or null");const t=new Date(e.nextLiveStreamAt);if(isNaN(t.getTime()))throw new rt("nextLiveStreamAt must be a valid ISO date string","nextLiveStreamAt",nt.INVALID_FORMAT)}}function Lc(e){if(xn(e)||"object"!=typeof e)return{};const t={};for(const[n,r]of Object.entries(e))xn(r)||(Rn(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 Uc=Object.freeze({__proto__:null,adaptQueryParams:Lc});function Fc(e,t){if(null==e)return[];if(Array.isArray(e))return e;const n=e[t];return Array.isArray(n)?n:[]}function Pc(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.owner&&""!==t.owner}function Bc(e){return"string"==typeof e.quantity&&""!==e.quantity}class Gc extends jn{constructor(e,t,n=!1){super(e,n,t)}async fetchPools(e={}){const t=function(e){const t=e.pageSize??Qo.DEFAULT_LIMIT;if(!Number.isInteger(t)||t<1||t>et)throw Nt("pageSize",1,et,t);const n={pageSize:String(t)};Rn(e.cursor)&&(n.cursor=e.cursor);void 0!==e.type&&(n.type=Wc("type",e.type,Je));Rn(e.tokenName)&&(Fn(e.tokenName,"tokenName",Xn),n.tokenName=e.tokenName);if(Rn(e.search)){if(e.search.length>$c)throw Rt("search",$c,e.search.length);n.search=e.search}!0===e.hasUpcomingShows&&(n.hasUpcomingShows="true");if(Rn(e.language)){if(!Hc.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>Kc)throw Nt("recentlyStreamed",1,Kc,t);n.recentlyStreamed=String(t)}!0===e.hasRecordings&&(n.hasRecordings="true");void 0!==e.streamStatus&&(n.streamStatus=Wc("streamStatus",e.streamStatus,Ze));if(void 0!==e.isGraduated){if("boolean"!=typeof e.isGraduated)throw _t("isGraduated","boolean",e.isGraduated);n.isGraduated=e.isGraduated?"true":"false"}void 0!==e.creatorAddress&&(n.creatorAddress=function(e){if("string"!=typeof e)throw _t("creatorAddress","string",e);return mn(e,"creatorAddress"),pn(e)??e}(e.creatorAddress));return n}(e),n=Lt(await Bt(()=>this.http.get(l.FETCH_POOLS,t),{errorContext:"Failed to fetch pools"}));return{items:function(e){if(!e)return[];let t=[];if(e.tokens)if(Array.isArray(e.tokens))t=e.tokens.map(e=>({...e,createdAt:e.created_at??e.createdAt??""}));else{const n=e.tokens;t=[{...n,createdAt:n.created_at??n.createdAt??""}]}else null!==e.pools&&void 0!==e.pools&&Array.isArray(e.pools)&&(t=e.pools.map(e=>({...e,createdAt:e.created_at??e.createdAt??""})));return t}(n),pageInfo:ei(n?.pageInfo)}}async fetchAllPools(e){const t=[];let n;for(;;){const r={...e,pageSize:100,...void 0!==n&&{cursor:n}},s=await this.fetchPools(r);if(t.push(...s.items),0===s.items.length)break;const o=ti(s.pageInfo,n);if(void 0===o)break;n=o}return{items:t,pageInfo:{hasNextPage:!1,totalCount:t.length}}}async checkPool(e){!function(e){const t=zs(e);!t.success&&t.errors&&Co(t.errors,"options")}(e),Rn(e.tokenName)&&Fn(e.tokenName,"tokenName",Zn);try{const t=await this.http.post(l.VALIDATE_TOKEN,{tokenName:e.tokenName,symbol:e.symbol});if(null==t)throw new Error("Invalid response from check pool endpoint");const n=t.data??t;if(null==n)throw new Error("Invalid response from check pool endpoint");if(!0===Rn(e.symbol)){return!n.symbolAvailable}if(!0===Rn(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 uo(t,"tokenName")&&go(t,"from")&&go(t,"to")&&go(t,"resolution")}(e))throw new rt("Invalid options provided. Expected { tokenName: string, from?: number, to?: number, resolution?: number }","options","INVALID_OPTIONS");const{tokenName:t,from:n,to:r,resolution:s}=e;if(Fn(t,"tokenName",Xn),null==n||null==r||null==s)throw new rt("Graph options (from, to, resolution) are required","options","MISSING_GRAPH_OPTIONS");const o={tokenName:t,from:n,to:r,resolution:s};Ro(o);const i=Lc(o),a=await Ft(()=>this.http.get(l.CHART,i),{errorContext:"Failed to fetch graph data"});if(!Array.isArray(a.data)||"boolean"!=typeof a.isPreviousData)throw new at("Invalid chart response: expected { data: candles, isPreviousData }");return{dataPoints:a.data,isPreviousData:a.isPreviousData,..."number"==typeof a.nextTime&&{nextTime:a.nextTime}}}async fetchTokenDistribution(e){if(""===e||null==e)throw Tt("tokenName","Token name");let t;Fn(e,"tokenName",Xn);try{t=await Bt(()=>this.http.get(`${l.GET_TOKEN_DISTRIBUTION}?tokenName=${e}`),{errorContext:"Failed to fetch token distribution"})}catch(t){if(pt(t)&&500===t.response?.status)throw St(`Token distribution data temporarily unavailable for ${e}. This is a backend issue - please try again later.`,500,dt(t)?t:void 0);throw t}return function(e,t,n=Ao){if(!Array.isArray(e))throw St("Invalid API response: expected array of holders",t);for(const n of e){if(!Pc(n))throw St("Invalid holder data: missing or invalid owner field",t);if(!Bc(n))throw St("Invalid holder data: missing or invalid quantity field",t);const e=Tn(n.quantity,NaN);if(isNaN(e)||!isFinite(e))throw St(`Invalid holder quantity: "${n.quantity}"`,t)}const r=e,s=r.reduce((e,t)=>e.plus(t.quantity),Eo(0));return{holders:r.map(e=>({address:e.owner,balance:e.quantity,percentage:No(Eo(e.quantity),s,Eo(0)).multipliedBy(100).toNumber()})),totalSupply:n(s),totalHolders:r.length,lastUpdated:new Date}}(Lt(t),t.status,e=>e.toFixed())}async fetchUserHolderContext(e,t){if(""===e||null==e)throw Tt("tokenName","Token name");if(""===t||null==t)throw Tt("userAddress","User address");return Fn(e,"tokenName",Xn),Ft(()=>this.http.get(`${l.GET_TOKEN_DISTRIBUTION}?tokenName=${e}`,{userAddress:en(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");Fn(e,"tokenName",Jn);try{const t=l.GET_TOKEN.replace(":tokenName",e.toLowerCase().trim()),n=Lt(await this.http.get(t));if(null!=n?.tokens){const t=Array.isArray(n.tokens)?n.tokens[0]:n.tokens;if(null==t)throw new Error(`Token not found: ${e}`);return t}throw new Error(`Invalid response format when fetching token: ${e}`)}catch(t){const n=String(t);if(n.includes("404")||n.includes("not found"))throw t instanceof at?new at(`Token not found: ${e}`,t.statusCode,t):new Error(`Token not found: ${e}`);throw t}}async validateToken(e){if(!(null!==e.tokenName&&void 0!==e.tokenName||null!==e.symbol&&void 0!==e.symbol))throw new Error("At least one of tokenName or symbol is required");if(null!==e.tokenName&&void 0!==e.tokenName&&("string"!=typeof e.tokenName||""===e.tokenName.trim()))throw new Error("tokenName must be a non-empty string");if(null!==e.symbol&&void 0!==e.symbol&&("string"!=typeof e.symbol||""===e.symbol.trim()))throw new Error("symbol must be a non-empty string");null!==e.tokenName&&void 0!==e.tokenName&&Fn(e.tokenName,"tokenName",Zn);try{const t=await this.http.post(l.VALIDATE_TOKEN,{tokenName:e.tokenName?.toLowerCase().trim(),symbol:e.symbol?.toUpperCase().trim()});if(null==t)throw new Error("Invalid response from validation endpoint");const n=t.data??t;if(null==n)throw new Error("Invalid response from validation endpoint");return n}catch(e){throw this.logger.warn(`Token validation failed: ${String(e)}`),e}}async fetchTokenStats(e){if(!Rn(e))throw Tt("tokenName","Token name");Fn(e,"tokenName",Jn);const t=l.TOKEN_STATS.replace(":tokenName",e.toLowerCase().trim());try{const e=Lt(await this.http.get(t));if(!function(e){if("object"!=typeof e||null===e)return!1;const t=new Map(Object.entries(e));return["holdersCount","chatMessageCount","commentCount","roomCount"].every(e=>{const n=t.get(e);return"number"==typeof n&&Number.isFinite(n)})}(e))throw new Error("Invalid response: missing stats data");return{success:!0,data:{holdersCount:e.holdersCount,chatMessageCount:e.chatMessageCount,commentCount:e.commentCount,roomCount:e.roomCount}}}catch(t){throw this.logger.warn(`Failed to fetch token stats for ${e}: ${String(t)}`),t}}async updateTokenConfig(e,t){if(""===e||null==e)throw Tt("tokenName","Token name");Fn(e,"tokenName",Jn),Mc(t);const n=l.UPDATE_TOKEN_CONFIG.replace(":tokenName",e.toLowerCase().trim()),r={};void 0!==t.chatEnabled&&(r.chatEnabled=t.chatEnabled),void 0!==t.commentsEnabled&&(r.commentsEnabled=t.commentsEnabled),void 0!==t.streamingEnabled&&(r.streamingEnabled=t.streamingEnabled),void 0!==t.nextLiveStreamAt&&(r.nextLiveStreamAt=t.nextLiveStreamAt),void 0!==t.streamLanguage&&(r.streamLanguage=t.streamLanguage),void 0!==t.websiteUrl&&(r.websiteUrl=t.websiteUrl),void 0!==t.telegramUrl&&(r.telegramUrl=t.telegramUrl),void 0!==t.twitterUrl&&(r.twitterUrl=t.twitterUrl),void 0!==t.instagramUrl&&(r.instagramUrl=t.instagramUrl),void 0!==t.facebookUrl&&(r.facebookUrl=t.facebookUrl),void 0!==t.redditUrl&&(r.redditUrl=t.redditUrl),void 0!==t.tiktokUrl&&(r.tiktokUrl=t.tiktokUrl),await this.http.patch(n,r,this.getJwtHeaders())}async getTokenConfig(e){if(!Rn(e))throw Tt("tokenName","Token name");Fn(e,"tokenName",Jn);const t=l.UPDATE_TOKEN_CONFIG.replace(":tokenName",e.toLowerCase().trim()),n=Lt(await this.http.get(t));if(void 0===n)throw new Error(`Invalid response: missing token config data for "${e}"`);return n}}const $c=255,Kc=720,Hc=/^[a-z]{2}(-[A-Z]{2})?$/u;function Wc(e,t,n){const r="string"==typeof t?t.toUpperCase():void 0,s=n.find(e=>e===r);if(void 0===s)throw Ct(e,t,n);return s}function Vc(e){if(void 0!==e.tokenName){if(!Rn(e.tokenName))throw _t("tokenName","a non-empty string",typeof e.tokenName);Pn(e.tokenName,"tokenName",Xn)}if(void 0!==e.userAddress){if(!Rn(e.userAddress))throw _t("userAddress","a non-empty string",typeof e.userAddress);if(e.userAddress.length>sr)throw wt("userAddress",sr,e.userAddress.length)}if(void 0!==e.search){if("string"!=typeof e.search)throw _t("search","a string",typeof e.search);if(e.search.length>256)throw wt("search",256,e.search.length)}if(Mn(0,void 0,rr,e.pageSize),void 0!==e.txnType&&"BUY"!==e.txnType&&"SELL"!==e.txnType)throw vt("txnType",'"BUY" or "SELL"');if(void 0!==e.startDate){if(!Rn(e.startDate))throw _t("startDate","a non-empty string",typeof e.startDate);if(isNaN(Date.parse(e.startDate)))throw vt("startDate","a valid ISO 8601 date")}if(void 0!==e.endDate){if(!Rn(e.endDate))throw _t("endDate","a non-empty string",typeof e.endDate);if(isNaN(Date.parse(e.endDate)))throw vt("endDate","a valid ISO 8601 date")}if(void 0!==e.minAmount)try{kn(e.minAmount,0,Number.MAX_SAFE_INTEGER,"minAmount")}catch{throw vt("minAmount","a non-negative number")}if(void 0!==e.maxAmount)try{kn(e.maxAmount,0,Number.MAX_SAFE_INTEGER,"maxAmount")}catch{throw vt("maxAmount","a non-negative number")}void 0!==e.minAmount&&void 0!==e.maxAmount&&function(e,t,n="range"){const r="number"==typeof e?e:Number(e),s="number"==typeof t?t:Number(t);if(isNaN(r)||isNaN(s))throw _t(n,"numeric values",void 0,n);if(r>s)throw new rt(`Minimum value (${r}) must be less than or equal to maximum value (${s}) for ${n}`,n,nt.INVALID_RANGE)}(e.minAmount,e.maxAmount,"amountRange")}class jc extends jn{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 uo(t,"tokenName")&&(void 0===t.tradeType||"buy"===t.tradeType||"sell"===t.tradeType)&&ho(t,"userAddress")&&go(t,"offset")&&go(t,"pageSize")&&go(t,"page")&&go(t,"limit")}(e))throw new rt("Invalid options provided. Expected { tokenName: string, tradeType?: string, userAddress?: string, cursor?: string, pageSize?: number, startDate?: Date, endDate?: Date, sortOrder?: string }","options","INVALID_OPTIONS");const{tokenName:t,cursor:n,pageSize:r=Qo.DEFAULT_LIMIT}=e;if(!Rn(t))throw Tt("tokenName","Token name");const s={pageSize:String(Math.min(r,nr))};void 0!==n&&(s.cursor=n);const o=await this.http.get(oi(l.GET_TRADES,{tokenName:t}),s);if(null==o)throw new rt("No response from trade service","response","NO_RESPONSE");const i=Lt(o),a=Fc(i,"trades"),c=i?.pageInfo;return{items:a,pageInfo:c??{hasNextPage:!1}}}buildTradesQueryParams(e){const t={};null!==e.tokenName&&void 0!==e.tokenName&&e.tokenName.length>0&&(t.tokenName=Kt(e.tokenName)),null!==e.userAddress&&void 0!==e.userAddress&&e.userAddress.length>0&&(t.userAddress=en(e.userAddress,"userAddress")),null!==e.search&&void 0!==e.search&&e.search.length>0&&(t.search=e.search);const n=void 0!==e.pageSize?Jo(e.pageSize,1,rr):rr;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){Vc(e);const t=this.buildTradesQueryParams(e);return Ft(()=>this.http.get(Ie,t),{errorContext:"Failed to fetch trades"})}}Jn.MIN_LENGTH,Jn.MAX_LENGTH;function qc(e){return Rn(e)&&sn(e)}function zc(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 Yc(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 Xc(e){return e.startsWith("0x")?e.slice(2):e}Ln({BOTH:"both",HELD:"held",CREATED:"created"});function Qc(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Jc(e){return"number"==typeof e&&Number.isFinite(e)}function Zc(e){return null===e||"string"==typeof e}function el(e){return Array.isArray(e)&&e.every(e=>Qc(e)&&"string"==typeof e.badgeName&&"boolean"==typeof e.isActive)}function tl(e){return Qc(e)&&"string"==typeof e.address&&Zc(e.fullName)&&Zc(e.profileImage)&&Zc(e.bio)&&function(e){return Qc(e)&&Jc(e.tokensCreated)&&Jc(e.tokensGraduated)&&Jc(e.graduationRate)&&Jc(e.totalTrades)&&"string"==typeof e.totalVolumeGala&&Zc(e.totalVolumeUsd)&&(null===e.holdingsCount||Jc(e.holdingsCount))&&Zc(e.accountCreatedAt)&&Jc(e.accountAgeDays)}(e.stats)&&el(e.launchBadge)&&el(e.successBadge)&&el(e.volumeBadge)&&el(e.engagementBadge)&&"boolean"==typeof e.isLiveStreaming&&Zc(e.liveStreamToken)}class nl extends jn{constructor(e,t,n=!1){super(e,n,t)}async fetchProfile(e){const t=e??this.http.getAddress();if(""===t||null==t||!qc(t))throw vt("address","eth|[40-hex-chars] or client|[identifier]","Address");if(void 0===e){const e=await Ft(()=>this.http.get(l.GET_CURRENT_USER,void 0,this.getJwtHeaders()),{errorContext:"Failed to fetch profile"});if(!(Qc(n=e)&&"string"==typeof n.address&&Zc(n.fullName)&&Zc(n.profileImage)&&"string"==typeof n.bio&&el(n.launchBadge)&&el(n.successBadge)))throw St("Malformed profile response");return e}var n;const r=await Ft(()=>this.http.get(l.GET_PROFILE.replace(":address",en(t,"address"))),{errorContext:"Failed to fetch profile"});if(!tl(r))throw St("Malformed profile response");return r}async updateProfile(e){this.validateUpdateProfileData(e);const t={};void 0!==e.fullName&&(t.fullName=e.fullName.trim()),void 0!==e.profileImage&&(t.profileImage=e.profileImage),await Ft(()=>this.http.put(l.UPDATE_PROFILE,t,this.getJwtHeaders()),{errorContext:"Profile update failed"})}async uploadProfileImage(e){this.validateUploadProfileImageOptions(e);try{const t=void 0===e.address?"profile-image.png":`profile-image-${e.address}.png`,n=Oc(e.file,"image",t),r=await Ft(()=>this.http.request({method:"POST",url:l.UPLOAD_PROFILE_IMAGE,data:n,headers:this.getJwtHeaders()}),{errorContext:"Image upload failed"});return"string"==typeof r?r:""}catch(e){if(e instanceof rt||e instanceof ct)throw e;if(e instanceof at)throw new at(`Profile image upload failed: ${ut(e)}`,e.statusCode,e);throw new rt(`Profile image upload failed: ${ut(e)}`,"file","UPLOAD_FAILED")}}async fetchTokenList(e){if(void 0!==e.status&&"created"!==e.type)throw new rt("status filters only apply when type=created","status","INVALID_FILTER");const t=e.tokenName,n={...e},r="created"===e.type;r&&(delete n.tokenName,void 0!==t&&void 0===n.search&&(n.search=t));const s=await this.buildFetchRequest(l.GET_TOKEN_LIST,n,{includeType:!0,requestType:e.type??"both",responseKey:r?"launches":"token",errorMessage:"Failed to fetch token list"});return r&&void 0!==t?{...s,tokens:s.tokens.filter(e=>e.tokenName===t||e.name===t)}:s}async fetchTokensHeld(e){if(void 0!==e.type&&"held"!==e.type)throw new rt("fetchTokensHeld only supports type=held","type","INVALID_TYPE");if(void 0!==e.status)throw new rt("status filters only apply when type=created","status","INVALID_FILTER");return this.buildFetchRequest(l.GET_TOKENS_HELD,e,{includeType:!0,requestType:"held",responseKey:"token",errorMessage:"Failed to fetch tokens held"})}async fetchTokensCreated(e){const{cursor:t,pageSize:n,search:r,tokenName:s,status:o}=e??{};if(void 0!==e?.type&&"created"!==e.type)throw new rt("fetchTokensCreated only supports type=created","type","INVALID_TYPE");const i=e?.address??this.http.getAddress();if(null==i||""===i)throw new rt("Wallet address not available - wallet not configured","address","NO_WALLET");const a={type:"created",address:i,pageSize:n??Qo.DEFAULT_LIMIT};return void 0!==t&&(a.cursor=t),void 0!==r&&(a.search=r),void 0!==s&&void 0===r&&(a.search=s),void 0!==s&&(a.tokenName=s),void 0!==o&&(a.status=o),this.fetchTokenList(a)}async getManagedTokens(e={}){const t={};return void 0!==e.cursor&&(t.cursor=e.cursor),void 0!==e.pageSize&&(t.pageSize=String(Math.min(e.pageSize,nr))),Ft(()=>this.http.get(l.GET_MANAGED_TOKENS,t,this.getJwtHeaders()),{errorContext:"Failed to fetch managed tokens"})}async getUserGalaBalance(e){if("string"!=typeof e||""===e.trim())throw Tt("address","Address");const t=en(e.trim(),"address");return Ft(()=>this.http.get(oi(l.GET_GALA_BALANCE,{address:t})),{errorContext:"Failed to fetch GALA balance"})}async fetchReferralCode(){return Ft(()=>this.http.get(l.GET_REFERRAL_CODE,void 0,this.getJwtHeaders()),{errorContext:"Failed to fetch referral code"})}async buildFetchRequest(e,t,n){this.validateGetTokenListOptions(t);const r=ri({pageSize:t.pageSize??Qo.DEFAULT_LIMIT,...void 0!==t.cursor&&{cursor:t.cursor}},nr);ii(r,t,["address","search","tokenName","status"]),n.includeType&&!e.includes("?type=")&&(r.type=n.requestType);let s=e;const o=en(t.address??this.http.getAddress(),"address");if(void 0!==t.address&&(r.address=o),e.includes(":address")){if(0===o.length)throw Tt("address","User address");s=e.replace(":address",o),delete r.address}const i=Lt(await Bt(()=>this.http.get(s,r),{errorContext:n.errorMessage}));return{tokens:Fc(i,n.responseKey).map(e=>{const t="string"==typeof e.tokenName?e.tokenName:"",r="string"==typeof e.name?e.name:t,s="string"==typeof e.createdAt?e.createdAt:"",i=e.metadata,a={...e};return delete a.metadata,{...a,id:"string"==typeof e.id?e.id:t,name:r,symbol:"string"==typeof e.symbol?e.symbol:"",type:n.requestType,address:o,balance:"string"==typeof e.balance?e.balance:"string"==typeof e.quantity?e.quantity:"0",decimals:"number"==typeof e.decimals?e.decimals:0,...null!==i&&"object"==typeof i?{metadata:i}:{},createdAt:s,updatedAt:"string"==typeof e.updatedAt?e.updatedAt:s}}),pageInfo:ei(i?.pageInfo)}}validateGetTokenListOptions(e){const t=e.pageSize??Qo.DEFAULT_LIMIT;if(t<1||t>nr)throw new rt(`pageSize must be between 1 and ${nr}`,"pageSize","OUT_OF_RANGE");if(void 0!==e.address&&!qc(e.address))throw vt("address","eth|[40-hex-chars] or client|[identifier]","Address");const n=zc(e.search);if(null!==n&&!(Rn(r=n)&&r.length>=ur&&r.length<=hr))throw Nt("search",ur,hr,n.length,"Search query");var r;const s=zc(e.tokenName);if(!(null===s||Rn(o=s)&&Jn.PATTERN.test(o)))throw vt("tokenName",Jn.DESCRIPTION,"Token name");var o}validateUpdateProfileData(e){if(void 0!==e.address&&!qc(e.address))throw vt("address","eth|[40-hex-chars] or client|[identifier]","Address");if(void 0===e.fullName&&void 0===e.profileImage)throw new rt("At least one of fullName and profileImage must be provided","options","REQUIRED");if(void 0!==e.fullName&&(t=e.fullName.trim(),!(Rn(t)&&t.length>=gr.FULL_NAME.MIN_LENGTH&&t.length<=gr.FULL_NAME.MAX_LENGTH&&gr.FULL_NAME.ALPHABETS_ONLY_PATTERN.test(t))))throw Nt("fullName",gr.FULL_NAME.MIN_LENGTH,gr.FULL_NAME.MAX_LENGTH,e.fullName.trim().length,"Full name");var t;if("string"==typeof e.profileImage&&e.profileImage.trim().length>2048)throw new rt("profileImage must not exceed 2048 characters","profileImage","TOO_LONG")}validateUploadProfileImageOptions(e){if(void 0!==e.address&&!qc(e.address))throw vt("address","eth|[40-hex-chars] or client|[identifier]","Address")}}class rl{constructor(e,t,n=!1){this.http=e,this.poolService=new Gc(e,t,n),this.tradeService=new jc(e,n),this.userService=new nl(e,t,n),this.imageService=new xc(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 Do(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 sl(e,t){if(void 0!==e){if(!Rn(e))throw _t("tokenName","string");Pn(e,"tokenName",Xn)}if(void 0!==t){if(!Rn(t))throw _t("userAddress","string");if(t.length>sr)throw new rt(`userAddress must be at most ${sr} characters`,"userAddress",nt.TOO_LONG)}}const ol={CHAT_MESSAGE:"CHAT_MESSAGE",COMMENT:"COMMENT"},il={PAGINATION:{MAX_LIMIT:rr},CONTENT:{CHAT_MAX_LENGTH:or.CHAT_MESSAGES_V1.MAX_LENGTH,COMMENT_MAX_LENGTH:or.COMMENTS_V1.MAX_LENGTH}};function al(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function cl(e){return null===e||"string"==typeof e}function ll(e){return al(e)&&cl(e.fullName)&&cl(e.profileImage)}class dl extends ci{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}validateContent(e,t){if(!Rn(e))throw Tt("content","Message content");if(0===e.trim().length)throw Tt("content","Message content");wn(e,t===ol.CHAT_MESSAGE?or.CHAT_MESSAGES_V1.MAX_LENGTH:or.COMMENTS_V1.MAX_LENGTH,"content")}validateMessageId(e){if(!Rn(e))throw Tt("id","Message ID");if(e.length<10||e.length>64)throw vt("id","valid message ID format","Message ID")}validateMessageType(e){if(e!==ol.CHAT_MESSAGE&&e!==ol.COMMENT)throw new rt(`type must be one of: ${Object.values(ol).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,Xn);const r={};void 0!==e.cursor&&(r.cursor=e.cursor),r.pageSize=e.pageSize??Qo.DEFAULT_LIMIT;const s=ri(r,rr),o={};void 0!==s.pageSize&&(o.pageSize=s.pageSize),void 0!==s.cursor&&(o.cursor=s.cursor),t&&(o.type=e.type.toUpperCase()),n&&(o.tokenName=Kt(e.tokenName)),void 0!==e.userAddress&&""!==e.userAddress&&(o.userAddress=en(e.userAddress,"userAddress")),void 0!==e.search&&""!==e.search&&(o.search=e.search);const i=await this.http.get(Ce.GET_MESSAGES,o),a=this.extractData(i);return{messages:a.messages,pageInfo:a.pageInfo}}async createMessage(e){this.validateMessageType(e.type),this.validateTokenName(e.tokenName,Xn),this.validateContent(e.content,e.type);const t={type:e.type,tokenName:Kt(e.tokenName),content:e.content.trim()},n=await this.http.post(Ce.CREATE_MESSAGE,t,this.getJwtHeaders());return{message:this.extractData(n)}}async updateMessage(e,t){this.validateMessageId(e),this.validateContent(t.content,t.type);const n=this.buildEndpointWithId(Ce.UPDATE_MESSAGE,e),r={content:t.content.trim()},s=await this.http.put(n,r,this.getJwtHeaders());return{message:this.extractData(s)}}async deleteMessage(e){this.validateMessageId(e);const t=this.buildEndpointWithId(Ce.DELETE_MESSAGE,e);return await this.http.delete(t,void 0,this.getDualAuthHeaders()),{success:!0}}async getPinnedMessage(e){this.validateTokenName(e,Jn);const t=await this.http.get(Ce.GET_PINNED,{tokenName:Kt(e)});return{message:this.extractDataOrNull(t)}}async pinMessage(e){this.validateMessageId(e);const t=Ce.PIN_MESSAGE.replace(":id",e);return await this.http.post(t,{},this.getDualAuthHeaders()),{success:!0}}async unpinMessage(e){this.validateMessageId(e);const t=Ce.UNPIN_MESSAGE.replace(":id",e);return await this.http.delete(t,void 0,this.getDualAuthHeaders()),{success:!0}}async getMessageStats(){return function(e){const t=e=>"number"==typeof e&&Number.isFinite(e),n=e=>"object"==typeof e&&null!==e&&!Array.isArray(e);if(!n(e))throw St("Malformed message statistics response");const r=e.totalMessages,s=e.todayMessages,o=e.uniqueUsers,i=e.uniqueTokens,a=e.messagesByType;if(!(t(r)&&t(s)&&t(o)&&t(i)&&n(a)))throw St("Malformed message statistics response");const c={};for(const[e,n]of Object.entries(a)){if(!t(n))throw St("Malformed message statistics response");c[e]=n}return{totalMessages:r,todayMessages:s,uniqueUsers:o,uniqueTokens:i,messagesByType:c}}(await this.http.get(Ce.GET_MESSAGE_STATS,void 0,this.getDualAuthHeaders()))}}const ul={MODERATOR:"MODERATOR",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MANAGER:"MANAGER"},hl=Un(ul),gl={TOKEN:"TOKEN",ALL_OWNER_TOKENS:"ALL_OWNER_TOKENS"},pl=Un(gl),ml={PENDING:"PENDING",CLAIMED:"CLAIMED",REVOKED:"REVOKED",EXPIRED:"EXPIRED"},fl=Un(ml);function El(e){return hl.includes(e)}function Al(e){return fl.includes(e)}function Tl(e){return dr.PATTERN.test(e)}const vl=Bn([{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"}]),Sl=Bn([{field:"tokenName",type:"string"},{field:"tokenSymbol",type:"string"},{field:"role",type:"string"},{field:"inviteScope",type:"string"},{field:"creatorAddress",type:"string"},{field:"claimedAt",type:"string"}]),yl=Bn([{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 bl(e){return pl.includes(e)}class Nl extends ci{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}validateRole(e){if(!Rn(e))throw Tt("role","Role");if(!El(e))throw vt("role",`one of: ${hl.join(", ")}`,"Role")}validateInviteCodeFormat(e){if(!Rn(e))throw Tt("inviteCode","Invite code");if(e.length>dr.MAX_LENGTH)throw vt("inviteCode",`at most ${String(dr.MAX_LENGTH)} characters`,"Invite code")}validateInviteScope(e){if(void 0!==e&&!bl(e))throw new rt(`Invalid invite scope. Must be one of: ${pl.join(", ")}`,"inviteScope","INVALID_VALUE")}async createInvite(e){this.validateInviteScope(e.inviteScope);const t=e.inviteScope??gl.TOKEN;if(t===gl.TOKEN){if(void 0===e.tokenName||""===e.tokenName)throw new rt("Token name is required for TOKEN scope invites","tokenName","REQUIRED");this.validateTokenName(e.tokenName,Xn)}else if(t===gl.ALL_OWNER_TOKENS&&e.tokenName)throw new rt("Token name should not be provided for ALL_OWNER_TOKENS scope invites","tokenName","INVALID_VALUE");this.validateRole(e.role),this.validateOptionalString(e.description,"description","Description",or.DESCRIPTION.MAX_LENGTH),this.validateOptionalDate(e.expiresAt,"expiresAt","Expiration date");const n=V,r={inviteScope:t,role:e.role};t===gl.TOKEN&&null!==e.tokenName&&void 0!==e.tokenName&&""!==e.tokenName&&(r.tokenName=Kt(e.tokenName)),void 0!==e.description&&(r.description=e.description),void 0!==e.expiresAt&&(r.expiresAt=e.expiresAt);const s=await this.http.post(n,r,this.getMultiAuthHeaders());return{invite:this.extractData(s)}}async listInvites(e){void 0!==e.tokenName&&""!==e.tokenName&&this.validateTokenName(e.tokenName,Xn),this.validateStatusFilter(e.status,ml);const t=z,n={...this.buildPaginationParams(e,rr)};void 0!==e.tokenName&&""!==e.tokenName&&(n.tokenName=Kt(e.tokenName)),void 0!==e.status&&(n.status=e.status);const r=await this.http.get(t,n,this.getMultiAuthHeaders()),s=this.extractData(r);return{items:s.invites,pageInfo:s.pageInfo}}async revokeInvite(e){this.validatePositiveInteger(e,"inviteId","Invite ID");const t=this.buildEndpoint(Y,{id:String(e)});Mt(await this.http.delete(t,void 0,this.getMultiAuthHeaders()),"Failed to revoke invite")}async updateInviteRole(e){this.validatePositiveInteger(e.inviteId,"inviteId","Invite ID"),this.validateRole(e.role);const t=this.buildEndpoint(X,{id:String(e.inviteId)}),n={role:e.role},r=await this.http.patch(t,n,this.getMultiAuthHeaders());return{invite:this.extractData(r)}}async updateInvite(e){if(this.validatePositiveInteger(e.inviteId,"inviteId","Invite ID"),void 0===e.role&&void 0===e.description)throw new rt("At least one of role or description must be provided","options","REQUIRED");void 0!==e.role&&this.validateRole(e.role),void 0!==e.description&&this.validateOptionalString(e.description,"description","Description",or.DESCRIPTION.MAX_LENGTH);const t=this.buildEndpoint(Q,{id:String(e.inviteId)}),n={};void 0!==e.role&&(n.role=e.role),void 0!==e.description&&(n.description=e.description);const r=await this.http.patch(t,n,this.getMultiAuthHeaders());return{invite:this.extractData(r)}}async claimInvite(e){this.validateInviteCodeFormat(e.inviteCode);const t=j,n={inviteCode:e.inviteCode},r=await this.http.post(t,n,this.getMultiAuthHeaders()),s=this.extractData(r);return"tokenName"in s&&void 0!==s.tokenName?{token:s}:{blanketAccess:s}}async getModeratedTokens(e){const t=q,n=this.buildPaginationParams(e??{},rr),r=await this.http.get(t,n,this.getMultiAuthHeaders()),s=this.extractData(r);return{items:s.tokens,pageInfo:s.pageInfo}}async getInviteByCode(e){this.validateInviteCodeFormat(e);const t=this.buildEndpoint(J,{code:e}),n=await this.http.get(t,{});return this.extractData(n)}}const kl={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 wl(e){return`${e}-${Date.now()}-${Math.random().toString(36).substring(2,11)}`}function _l(){return Date.now()+6e4}function Il(e){return""!==e&&"string"==typeof e&&/^[a-zA-Z0-9]{3,50}$/.test(e)}function Cl(e){try{return Math.floor(parseFloat(String(e))??0).toString()}catch{return"0"}}function Dl(e){return""!==e&&"string"==typeof e&&sn(e)}class Rl extends jn{constructor(e){super(e)}getCollectionClaimFee(){return kl.COLLECTION_CLAIM_FEE}getTokenClassCreateFee(){return kl.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(!Dl(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=kl.COLLECTION_CLAIM_FEE;n.collectionClaim=e,t=String(BigInt(t)+BigInt(e))}if((e.createTokenClasses??0)>0){const r=kl.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),!Il(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:_l(),uniqueKey:wl("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),!Dl(e))throw new Error(`Invalid wallet address format: ${e}`);const t=(await this.allAuthorizations()).filter(t=>t.authorizedUsers.some(t=>rn(t,e))).map(t=>({authorizedUser:Zt(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),!Il(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(!Il(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?Cl(e.maxSupply):void 0,maxCapacity:void 0!==e.maxCapacity?Cl(e.maxCapacity):void 0,additionalKey:e.additionalKey,expiresAt:_l(),uniqueKey:wl("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),!Il(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(!Dl(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:Zt(e.ownerAddress,"ownerAddress"),additionalKey:e.additionalKey??"none",expiresAt:_l(),uniqueKey:wl("mint")};this.logger.debug("Built mint DTO",r);const s=`mint-${Date.now()}`,o=Array.from({length:t},(e,t)=>t+1);return{transactionId:s,mintedQuantity:e.quantity,owner:Zt(e.ownerAddress,"ownerAddress"),tokenInstances:o,tokenClass:{collection:e.collection,type:e.type,category:e.category}}}catch(e){throw this.logger.error("Failed to mint NFT",e),e}}async fetchNftBalances(e,t){try{if(this.logger.debug("Fetching NFT balances for",{ownerAddress:e,collectionFilter:t}),!Dl(e))throw new Error(`Invalid owner address: ${e}`);const n=(await this.reads().fetchNftBalances({owner:Zt(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:t}=Va(async(e,t)=>({data:await this.http.post(e,t)}));return new e.GatewayReads({gatewayBaseUrl:"",httpRequestor:t,requestTimeoutMs:1/0})}allAuthorizations(){return this.reads().fetchAllNftCollectionAuthorizations({pageSize:1e3})}}class Ol extends jn{constructor(e,t=!1,n){super(e,t,n)}extractData(e){if(e.error||void 0===e.data){const t=e.message??"Notification operation failed";throw new Error(t)}return e.data}async registerPushToken(e){this.logger.debug("Registering push token",{platform:e.platform});const t=this.getJwtHeaders(),n=await this.http.post(je,{token:e.token,platform:e.platform,...void 0!==e.deviceId?{deviceId:e.deviceId}:{}},t),r=this.extractData(n);return this.logger.debug("Push token registered",{registered:r.registered}),r}async unregisterPushToken(e){this.logger.debug("Unregistering push token");const t=this.getJwtHeaders(),n=await this.http.request({method:"DELETE",url:qe,data:{token:e},headers:t}),r=this.extractData(n);return this.logger.debug("Push token unregistered",{unregistered:r.unregistered}),r}async getPreferences(){this.logger.debug("Fetching notification preferences");const e=this.getJwtHeaders(),t=await this.http.get(ze,void 0,e),n=this.extractData(t);return this.logger.debug("Fetched notification preferences",{tradesEnabled:n.tradesEnabled,streamsEnabled:n.streamsEnabled}),{preferences:n}}async updatePreferences(e){this.logger.debug("Updating notification preferences",e);const t=this.getJwtHeaders(),n=await this.http.put(Ye,e,t),r=this.extractData(n);return this.logger.debug("Updated notification preferences",{tradesEnabled:r.tradesEnabled,streamsEnabled:r.streamsEnabled}),{preferences:r}}}class xl extends jn{constructor(e,t=!1){super(e,t)}async getHomeOEmbedJson(e={}){this.logger.debug("Fetching home oEmbed (JSON)");const t=await this.http.get(l.OEMBED,{format:"json"});return this.logger.debug("Fetched home oEmbed (JSON)",{title:t.title}),{oembed:t}}async getHomeOEmbedHtml(e={}){this.logger.debug("Fetching home oEmbed (HTML)");const t=await this.http.get(l.OEMBED,{},{responseType:"text"});return this.logger.debug("Fetched home oEmbed (HTML)"),{html:t}}async getPoolOEmbedJson(e){const{tokenName:t}=e;if(null==t||"string"!=typeof t||""===t.trim())throw new rt("tokenName is required","tokenName","REQUIRED_FIELD");this.logger.debug("Fetching pool oEmbed (JSON)",{tokenName:t});const n=l.OEMBED_BUY_SELL.replace(":tokenName",t.toLowerCase().trim()),r=await this.http.get(n,{format:"json"});return this.logger.debug("Fetched pool oEmbed (JSON)",{tokenName:t,title:r.title}),{oembed:r}}async getPoolOEmbedHtml(e){const{tokenName:t}=e;if(null==t||"string"!=typeof t||""===t.trim())throw new rt("tokenName is required","tokenName","REQUIRED_FIELD");this.logger.debug("Fetching pool oEmbed (HTML)",{tokenName:t});const n=l.OEMBED_BUY_SELL.replace(":tokenName",t.toLowerCase().trim()),r=await this.http.get(n,{},{responseType:"text"});return this.logger.debug("Fetched pool oEmbed (HTML)",{tokenName:t}),{html:r}}async getProfileOEmbedJson(e){const{address:t}=e;if(null==t||"string"!=typeof t||""===t.trim())throw new rt("address is required","address","REQUIRED_FIELD");this.logger.debug("Fetching profile oEmbed (JSON)",{address:t});const n=l.OEMBED_PROFILE.replace(":address",encodeURIComponent(en(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 rt("address is required","address","REQUIRED_FIELD");this.logger.debug("Fetching profile oEmbed (HTML)",{address:t});const n=l.OEMBED_PROFILE.replace(":address",encodeURIComponent(en(t.trim(),"address"))),r=await this.http.get(n,{},{responseType:"text"});return this.logger.debug("Fetched profile oEmbed (HTML)",{address:t}),{html:r}}}function Ml(e){if(!Rn(e))throw Tt("address","Address");Zt(e,"address")}const Ll={PENDING:"PENDING",CLAIMED:"CLAIMED",REVOKED:"REVOKED",EXPIRED:"EXPIRED"},Ul={ACTIVE:"ACTIVE",REVOKED:"REVOKED"},Fl=Ln(Ll),Pl=Ln(Ul);function Bl(e){try{Kn(e.description,"description",255)}catch(e){if(e instanceof rt){throw e.message.includes("255")?new Error("description must be at most 255 characters"):new Error("description must be a string")}throw e}if(void 0!==e.expiresAt){if(!Rn(e.expiresAt))throw new Error("expiresAt must be a non-empty string");try{Hn(e.expiresAt,"expiresAt")}catch(e){if(e instanceof rt)throw new Error("expiresAt must be a valid ISO 8601 date string");throw e}if(Qt(e.expiresAt)){if(Xt(e.expiresAt)<=new Date)throw new Error("expiresAt must be in the future")}}}function Gl(e){if(void 0!==e.status&&!Fl(e.status))throw Ct("status",e.status,Object.values(Ll),"status");Mn(0,void 0,50,e.pageSize,e.cursor)}function $l(e){if(void 0!==e.status&&!Pl(e.status))throw Ct("status",e.status,Object.values(Ul),"status");Mn(0,void 0,50,e.pageSize,e.cursor)}function Kl(e){if(!Rn(e))throw new Error("Invite code must be a non-empty string");wn(e,dr.MAX_LENGTH,"code")}function Hl(e){if(!Rn(e))throw new Error("Address must be a non-empty string");try{fn(e,"address")}catch{throw new Error("Invalid wallet address format. Must be eth|..., 0x..., or client|... format")}}function Wl(e){try{_n(e,"id")}catch(e){if(e instanceof rt)throw new Error("Invite ID must be a positive integer");throw e}}function Vl(e){if(null==e||"object"!=typeof e)throw new rt("Options are required");if(void 0!==e.search){if("string"!=typeof e.search)throw new rt("Search must be a string");if(0===e.search.length)throw new rt("Search query cannot be empty string")}if(void 0!==e.sortBy){if("string"!=typeof e.sortBy)throw new rt("Sort field must be a string");if(0===e.sortBy.length)throw new rt("Sort field cannot be empty string")}if(void 0!==e.sortOrder){const t="string"==typeof e.sortOrder?e.sortOrder.toLowerCase():"";if("asc"!==t&&"desc"!==t)throw new rt('Sort order must be "asc" or "desc"')}}function jl(e){if(null==e||"object"!=typeof e)throw new rt("Options are required");if(!Rn(e.userAddress))throw new rt("userAddress is required and must be a non-empty string");try{fn(e.userAddress,"userAddress")}catch{throw new rt("Invalid wallet address format. Must be eth|..., 0x..., or client|... format")}if(void 0!==e.description){if("string"!=typeof e.description)throw new rt("description must be a string");if(e.description.length>255)throw new rt("description must be at most 255 characters")}}class ql extends ci{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}validateInviteCodeFormat(e){if(!Rn(e))throw Tt("inviteCode","Invite code");Kl(e)}validateWalletAddressFormat(e){if(!Rn(e))throw Tt("address","Address");Hl(e)}async createInvite(e={}){Bl(e),this.validateOptionalString(e.description,"description","Description",or.DESCRIPTION.MAX_LENGTH),this.validateOptionalDate(e.expiresAt,"expiresAt","Expiration date");const t=ee,n={};void 0!==e.description&&(n.description=e.description),void 0!==e.expiresAt&&(n.expiresAt=e.expiresAt);const r=await this.http.post(t,n,this.getDualAuthHeaders());return{invite:this.extractData(r)}}async listInvites(e={}){Gl(e),this.validateStatusFilter(e.status,Ll);const t=te,n={...this.buildPaginationParams(e,rr)};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){Wl(e);const t=this.buildEndpoint(se,{id:String(e)});Mt(await this.http.delete(t,void 0,this.getDualAuthHeaders()),"Failed to revoke invite")}async claimInvite(e){this.validateInviteCodeFormat(e);const t=re,n={inviteCode:e},r=await this.http.post(t,n,this.getJwtHeaders());return{invite:this.extractData(r)}}async listOverseers(e={}){$l(e),this.validateStatusFilter(e.status,Ul);const t=oe,n={...this.buildPaginationParams(e,rr)};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){jl(e),this.validateWalletAddressFormat(e.userAddress),this.validateOptionalString(e.description,"description","Description",or.DESCRIPTION.MAX_LENGTH);const t=ie,n={userAddress:en(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(ae,{address:en(e,"address")});Mt(await this.http.delete(t,void 0,this.getDualAuthHeaders()),"Failed to revoke overseer")}async getMyStatus(){const e=ce,t=await this.http.get(e,{},this.getJwtHeaders());return this.extractData(t)}async getSummary(){const e=le,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getBanStats(){const e=de,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getTokenBanStats(){const e=ue,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getInviteStats(){const e=he,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getFlagStats(){const e=ge,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getUserStats(){const e=pe,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async listOverseerUsers(e){const t=e??{};Object.keys(t).length>0&&Vl(t);const n=me,r=this.buildPaginationParams(t,rr);void 0!==t.search&&""!==t.search&&(r.search=t.search),void 0!==t.sortBy&&""!==t.sortBy&&(r.sortBy=t.sortBy),void 0!==t.sortOrder&&(r.sortOrder=t.sortOrder);const s=await this.http.get(n,r,this.getDualAuthHeaders()),o=this.extractData(s);return{items:o.users,pageInfo:o.pageInfo}}async getOverseerUserSummary(e){if(!Rn(e))throw Tt("address","User address");Hl(e);const t=this.buildEndpoint(fe,{address:en(e,"address")}),n=await this.http.get(t,{},this.getDualAuthHeaders());return this.extractData(n)}async flushCacheByAddress(e){Ml(e);const t=this.buildEndpoint(Ee,{address:en(e,"address")}),n=await this.http.delete(t,void 0,this.getDualAuthHeaders());return this.extractData(n)}async flushCacheByToken(e){!function(e){if(!Rn(e))throw Tt("tokenName","Token name")}(e);const t=this.buildEndpoint(Ae,{tokenName:e}),n=await this.http.delete(t,void 0,this.getDualAuthHeaders());return this.extractData(n)}async flushAllCache(e){!function(e){if(!0!==e)throw new rt("Safety confirmation required: must pass confirm=true to flush all cache","confirm","CONFIRMATION_REQUIRED")}(e);const t=Te,n=await this.http.delete(t,{confirm:"true"},this.getDualAuthHeaders());return this.extractData(n)}async flushWalletAliasCache(e){if(void 0!==e){Ml(e);const t=this.buildEndpoint(ve,{address:en(e,"address")}),n=await this.http.delete(t,void 0,this.getDualAuthHeaders());return this.extractData(n)}const t=Se,n=await this.http.delete(t,{confirm:"true"},this.getDualAuthHeaders());return this.extractData(n)}}function zl(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 Yl extends jn{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),Mt(t,"Platform config operation failed",!0),e.data}async getPlatformConfig(){const e=await this.http.get(N);return this.extractData(e)}async updatePlatformConfig(e){const t=zl(e);if(t.length>0)throw new rt(t.join("; "),"options","VALIDATION_FAILED");const n=await this.http.put(k,e,this.getJwtHeaders());return this.extractData(n)}async getAvailableRoles(){const e=await this.http.get(I);return this.extractData(e)}}class Xl extends jn{constructor(e,t=!1){super(e,t)}extractData(e){if(e.error||void 0===e.data){const t=e.message??"Platform stats operation failed";throw new Error(t)}return e.data}async getStats(){this.logger.debug("Fetching platform stats");const e=await this.http.get(Ge),t=this.extractData(e);return this.logger.debug("Fetched platform stats",{totalTokens:t.totalTokens,timestamp:t.timestamp}),{stats:t}}}class Ql extends ci{constructor(e,t,n,r){super(e,t,n,!1,r)}async getRestrictedNames(){try{return{success:!0,data:(await this.http.get(De,void 0,this.getJwtHeaders())).data}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}async updateRestrictedNames(e){try{if("string"!=typeof e.content)throw new rt("Content is required");return{success:!0,data:(await this.http.put(Re,{content:e.content},this.getJwtHeaders())).data}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}}class Jl extends ci{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async getChatStatus(e){if(null==e||""===e)throw Tt("tokenName","Token name");return this.validateTokenName(e,Jn),$o(async()=>{const t=this.buildEndpoint(Oe,{tokenName:e}),n=await this.http.get(t);return this.buildChatStatusResponse(e,this.extractData(n))},`Failed to get chat status for token: ${e}`,this.logger)}async disableChat(e){if(null==e||""===e)throw Tt("tokenName","Token name");return this.validateTokenName(e,Jn),$o(async()=>{const t=this.buildEndpoint(Me,{tokenName:e}),n=await this.http.post(t,{enabled:!1},this.getDualAuthHeaders());return this.buildChatStatusResponse(e,this.extractData(n))},`Failed to disable chat for token: ${e}`,this.logger)}async enableChat(e){if(null==e||""===e)throw Tt("tokenName","Token name");return this.validateTokenName(e,Jn),$o(async()=>{const t=this.buildEndpoint(xe,{tokenName:e}),n=await this.http.post(t,{enabled:!0},this.getDualAuthHeaders());return this.buildChatStatusResponse(e,this.extractData(n))},`Failed to enable chat for token: ${e}`,this.logger)}buildChatStatusResponse(e,t){const n={enabled:t.enabled,tokenName:t.tokenName??Kt(e)};return void 0!==t.status&&null!==t.status&&(n.status=t.status),"global"!==t.reason&&"token"!==t.reason||(n.reason=t.reason),"number"==typeof t.slowModeSeconds&&(n.slowModeSeconds=t.slowModeSeconds),n}async setSlowMode(e,t){if(null==e||""===e)throw Tt("tokenName","Token name");if(this.validateTokenName(e,Jn),"number"!=typeof t||t<0||t>600)throw new Error("slowModeSeconds must be a number between 0 and 600");return $o(async()=>{const n=this.buildEndpoint(Le,{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 Zl={IDLE:"IDLE",ACTIVE:"ACTIVE",DISABLED:"DISABLED"},ed={PREPARING:"preparing",READY:"ready",ERRORED:"errored"},td={YOUTUBE:"youtube",TWITCH:"twitch",FACEBOOK:"facebook",CUSTOM:"custom"},nd=Ln(Zl),rd=Ln(ed),sd=Ln(td);const od={OWNER:"OWNER",MANAGER:"MANAGER",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MODERATOR:"MODERATOR"},id={OWNER:"OWNER",MODERATOR:"MODERATOR"};Ln(od),Ln(id);const ad={...od,OVERSEER:"OVERSEER"},cd=Ln(ad);function ld(e,t="tokenName"){Fn(e,t,Jn)}const dd=/^rtmps?:\/\/\S+$/u,ud=255;function hd(e){if(ld(e.tokenName),!Rn(e.language))throw Tt("language");if(t=e.language,!Rn(t)||!/^[a-z]{2}(-[A-Z]{2})?$/.test(t))throw new rt('language must be a valid ISO 639-1 code (e.g., "en", "es", "zh-CN")',"language",nt.INVALID_FORMAT);var t}class gd extends ci{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async startStream(e){this.validateTokenName(e,Jn);const t=this.buildEndpoint(g,{tokenName:e}),n=await this.http.post(t,{},this.getJwtHeaders());return this.extractData(n)}async stopStream(e){this.validateTokenName(e,Jn);const t=this.buildEndpoint(p,{tokenName:e});await this.http.post(t,{},this.getJwtHeaders())}async disableStream(e){return this.toggleFeature(e,m,Jn)}async enableStream(e){return this.toggleFeature(e,f,Jn)}async resetStreamKey(e){this.validateTokenName(e,Jn);const t=this.buildEndpoint(E,{tokenName:e}),n=await this.http.post(t,{},this.getJwtHeaders());return this.extractData(n)}async getStreamCredentials(e){this.validateTokenName(e,Jn);const t=this.buildEndpoint(D,{tokenName:e}),n=await this.http.get(t,{},this.getJwtHeaders());return this.extractData(n)}async getRecordings(e){!function(e){ld(e.tokenName)}(e);const t=this.buildEndpoint(A,{tokenName:e.tokenName}),n=await this.http.get(t),r=this.extractData(n);if(!Array.isArray(r))throw St("Invalid recordings response: expected an array of recordings");return{recordings:r,tokenName:Kt(e.tokenName)}}async getRecordingDownload(e,t){this.validateTokenName(e,Jn),this.validateRequiredString(t,"assetId","Asset ID");const n=this.buildEndpoint(T,{tokenName:e,assetId:t}),r=await this.http.get(n,{},this.getJwtHeaders());return this.extractData(r)}async deleteRecording(e,t){this.validateTokenName(e,Jn),this.validateRequiredString(t,"assetId","Asset ID");const n=this.buildEndpoint(v,{tokenName:e,assetId:t});await this.http.delete(n,void 0,this.getJwtHeaders())}async getSimulcastTargets(e){this.validateTokenName(e,Jn);const t=this.buildEndpoint(S,{tokenName:e}),n=await this.http.get(t,void 0,this.getJwtHeaders()),r=this.extractData(n);if(!Array.isArray(r))throw St("Invalid simulcast response: expected an array of targets");return{targets:r,tokenName:Kt(e)}}async addSimulcastTarget(e){!function(e){if(ld(e.tokenName),!Rn(e.platform))throw Tt("platform");if(!sd(e.platform))throw new rt("platform must be one of: 'youtube', 'twitch', 'facebook', 'custom'","platform",nt.INVALID_VALUE);if(!Rn(e.url))throw Tt("url");if(!dd.test(e.url))throw new rt("url must be a valid RTMP or RTMPS URL","url",nt.INVALID_FORMAT);if(e.url.length>2048)throw new rt(`url must not exceed ${String(2048)} characters`,"url",nt.TOO_LONG);if(!Rn(e.streamKey))throw Tt("streamKey");if(e.streamKey.length>ud)throw new rt(`streamKey must not exceed ${String(ud)} characters`,"streamKey",nt.TOO_LONG);if(void 0!==e.passthrough){if("string"!=typeof e.passthrough)throw new rt("passthrough must be a string","passthrough",nt.INVALID_TYPE);if(e.passthrough.length>ud)throw new rt(`passthrough must not exceed ${String(ud)} characters`,"passthrough",nt.TOO_LONG)}}(e);const t=this.buildEndpoint(y,{tokenName:e.tokenName}),n=await this.http.post(t,{platform:e.platform,url:e.url,streamKey:e.streamKey,...void 0!==e.passthrough&&{passthrough:e.passthrough}},this.getJwtHeaders());return{target:this.extractData(n),tokenName:Kt(e.tokenName)}}async removeSimulcastTarget(e,t){this.validateTokenName(e,Jn),this.validateRequiredString(t,"targetId","Target ID");const n=this.buildEndpoint(b,{tokenName:e,targetId:t});await this.http.delete(n,void 0,this.getJwtHeaders())}async getGlobalStreamingStatus(){const e=await this.http.get(N);return this.extractData(e)}async disableGlobalStreaming(){const e=await this.http.put(k,{},this.getAdminHeaders());return this.extractData(e)}async enableGlobalStreaming(){const e=await this.http.put(w,{},this.getAdminHeaders());return this.extractData(e)}async setNextLiveStream(e){let t;!function(e){if(ld(e.tokenName),null!==e.nextLiveStreamAt){if(!(e.nextLiveStreamAt instanceof Date||Rn(e.nextLiveStreamAt)))throw new rt("nextLiveStreamAt must be a Date, ISO 8601 string, or null","nextLiveStreamAt",nt.INVALID_TYPE);if("string"==typeof e.nextLiveStreamAt){const t=Date.parse(e.nextLiveStreamAt);if(isNaN(t))throw new rt("nextLiveStreamAt must be a valid ISO 8601 date string","nextLiveStreamAt",nt.INVALID_FORMAT)}}}(e),t=null===e.nextLiveStreamAt?null:e.nextLiveStreamAt instanceof Date?e.nextLiveStreamAt.toISOString():e.nextLiveStreamAt;const n=`/v1/tokens/${e.tokenName.toLowerCase().trim()}`;await this.http.patch(n,{nextLiveStreamAt:t},this.getJwtHeaders())}async clearNextLiveStream(e){this.validateTokenName(e,Jn);const t=`/v1/tokens/${e.toLowerCase().trim()}`;await this.http.patch(t,{nextLiveStreamAt:null},this.getJwtHeaders())}async setStreamLanguage(e){hd(e);const t=`/v1/tokens/${e.tokenName.toLowerCase().trim()}`;await this.http.patch(t,{streamLanguage:e.language},this.getJwtHeaders())}async getStreamRole(e){!function(e){ld(e.tokenName)}(e);const t=this.buildEndpoint(_,{tokenName:e.tokenName}),n=this.jwtAuth?this.getJwtHeaders():{},r=await this.http.get(t,{},n);return this.extractData(r)}async getAvailableRoles(){const e=await this.http.get(I);return this.extractData(e)}async getTokenAccess(e){!function(e){ld(e.tokenName)}(e);const t=await this.http.get(C,{tokenName:Kt(e.tokenName)},this.getJwtHeaders());return this.extractData(t)}async setNextLiveStreamCountdown(e,t){return this.setNextLiveStream({tokenName:e,nextLiveStreamAt:t})}}const pd={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"},md=e=>fd(e.flagId);function fd(e){return"string"==typeof e||"number"==typeof e?String(e):void 0}function Ed(e,t){const n=t.map(t=>fd(e[t]));return n.every(e=>void 0!==e)?n.join("|"):void 0}const Ad={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=>fd(e.id)},FLAG_RESOLVED:{duplicateKey:e=>Ed(e,["id","status","reviewedAt"])},AI_MODERATION_COMPLETE:{duplicateKey:md},AI_MODERATION_FAILED:{duplicateKey:md},MODERATOR_INVITE_CREATED:{},MODERATOR_ADDED:{},MODERATOR_REMOVED:{},MODERATOR_ROLE_UPDATED:{},OVERSEER_ADDED:{token:"none",duplicateKey:e=>Ed(e,["userAddress","addedAt"])},OVERSEER_REMOVED:{token:"none",duplicateKey:e=>Ed(e,["userAddress","removedAt"])},POOL_CREATED:{duplicateKey:e=>Ed(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 Td(e){return Ad[e]}const vd=Object.keys(Ad);const Sd="token:",yd="comment:",bd="global:feed",Nd="global:events_firehose";function kd(e){if(e.startsWith(Sd)){const t={tokenName:e.slice(Sd.length)};return{join:{event:pd.SUBSCRIBE,payload:t},leave:{event:pd.UNSUBSCRIBE,payload:t}}}if(e.startsWith(yd)){const t={tokenName:e.slice(8)};return{join:{event:pd.SUBSCRIBE_COMMENT,payload:t},leave:{event:pd.UNSUBSCRIBE_COMMENT,payload:t}}}return e===Nd?{join:{event:pd.SUBSCRIBE_EVENTS_FIREHOSE},leave:{event:pd.UNSUBSCRIBE_EVENTS_FIREHOSE}}:{join:{event:pd.SUBSCRIBE_GLOBAL_FEED},leave:{event:pd.UNSUBSCRIBE_GLOBAL_FEED}}}const wd=new Set(["token_subscribed","room_subscribed","global_feed_subscribed","events_firehose_subscribed"]);const _d={STREAM_CHAT_GLOBAL_STATUS:"chatEnabled",STREAM_GLOBAL_STATUS:"streamingEnabled",COMMENTS_GLOBAL_STATUS:"commentsEnabled",WEBHOOKS_GLOBAL_STATUS:"webhooksEnabled",AI_MODERATION_GLOBAL_STATUS:"aiModerationEnabled"},Id=["STREAM_STATUS","TRADE_EXECUTED","HOLDER_COUNT_UPDATED","POOL_BADGE_ASSIGNED","VIEWER_COUNT","TOKEN_CONFIG_UPDATED","STATS_UPDATED","POOL_CREATED"],Cd=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"]),Dd=new Set(["COMMENT_CREATED","COMMENT_UPDATED","COMMENT_DELETED"]);const Rd={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"},Od={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"},xd=()=>{};function Md(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Ld(e,t){return t}function Ud(e){return`${Sd}${e}`}function Fd(e){return`${yd}${e}`}function Pd(e){const t=Kt(e);if(""===t)throw Tt("tokenName","Token name");return t}class Bd extends qn{constructor(e,t=!1){if(super(t),this.socket=null,this.disposed=!1,this.epoch=0,this.connectionGeneration=0,this.hasConnected=!1,this.connectAttempt=null,this.reconnectExhausted=!1,this.managerCleanups=[],this.connectionStateListeners=new Set,this.reconnectListeners=new Set,this.subscribers=new Map,this.roomRefs=new Map,this.roomStates=new Map,this.roomWaiters=new Map,this.explicitHolds=new Map,this.recentOccurrences=new Map,this.siteConfig={chatEnabled:void 0,streamingEnabled:void 0,commentsEnabled:void 0,webhooksEnabled:void 0,aiModerationEnabled:void 0},this.authenticated=!1,this.authenticatedToken=null,this.authenticatedGeneration=-1,this.wantsAuthentication=!1,this.lastExplicitToken=null,this.authSequence=0,this.inFlight=null,this.lastEmitted=null,this.pendingAuthenticate=null,""===e.url)throw new ct("Stream WebSocket URL is required. Set streamWebSocketUrl in SDK config.");this.config={url:e.url,reconnectAttempts:e.reconnectAttempts??5,reconnectDelay:e.reconnectDelay??2e3,reconnectDelayMax:e.reconnectDelayMax,subscriptionTimeout:e.subscriptionTimeout??1e4,tokenProvider:e.tokenProvider,autoConnect:e.autoConnect??!0},this.isSocketIOAvailable="function"==typeof i.io}register(e,t,n={}){if(this.disposed)return xd;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 xd;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===Nd}(e)&&!this.authenticated)return;this.joinRoom(t,e)}else n||"joined"!==r?.phase||(t.emit(kd(e).leave.event,kd(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=kd(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(Sd)?e.slice(Sd.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((!Md(t)||!this.isDuplicate(e,t))&&(this.deliver(e,t,Md(t)?function(e,t){const n=Td(e).token??"payload";if("none"===n)return;if("room"===n){const e=t.room;return"string"==typeof e&&e.startsWith(Sd)?e.slice(Sd.length):void 0}const r=t.tokenName;return"string"==typeof r&&""!==r?r:void 0}(e,t):void 0),Md(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=Td(e).duplicateKey?.(t);if(void 0===n)return!1;const r=Date.now(),s=`${e}:${n}`,o=this.recentOccurrences.get(s);if(void 0!==o&&r-o<5e3)return!0;if(this.recentOccurrences.set(s,r),this.recentOccurrences.size>256)for(const[e,t]of this.recentOccurrences)r-t>=5e3&&this.recentOccurrences.delete(e);return!1}deliver(e,t,n){const r=this.subscribers.get(e);if(void 0===r)return;const s=void 0===n?void 0:Kt(n);for(const n of[...r])n.active&&(void 0!==n.token&&n.token!==s||(void 0===n.filter||this.passes(n,t))&&this.invoke(e,n.deliver,t))}passes(e,t){try{return e.filter?.(t)??!0}catch(t){return this.logger.error(`Error in a ${e.name} filter:`,t),!1}}invoke(e,t,n){try{const r=t(n);r instanceof Promise&&r.catch(t=>{this.logger.error(`Error in a ${e} subscriber:`,t)})}catch(t){this.logger.error(`Error in a ${e} subscriber:`,t)}}applyEffects(e,t){if("authenticated"===e)null!==this.inFlight?this.inFlight.settle(!0):this.adoptLateAuthentication();else if("stream_chat_auth_error"===e)this.authenticated=!1,this.inFlight?.settle(!1);else if("exception"===e)this.inFlight?.settle(!1);else if(function(e){return wd.has(e)}(e))Md(t)&&"string"==typeof t.room&&this.onRoomAcknowledged(t.room);else{const n=_d[e];void 0!==n&&(this.siteConfig={...this.siteConfig,[n]:Gd(t)})}}liveSocket(){return null!==this.socket&&this.socket.connected?this.socket:null}connect(){if(this.disposed)return Promise.reject(new ct("The stream WebSocket service has been disposed."));if(!this.isSocketIOAvailable)return Promise.reject(new ct('Socket.IO not available. Install "socket.io-client" package.'));const e=this.socket??this.createSocket();if(e.connected)return Promise.resolve();if(null===this.connectAttempt){let e=()=>{},t=()=>{};const n=new Promise((n,r)=>{e=n,t=r});this.connectAttempt={promise:n,resolve:e,reject:t}}return e.connect(),this.connectAttempt.promise}createSocket(){this.logger.debug(`🔌 Connecting to Stream WebSocket: ${this.config.url}`);const e=i.io(this.config.url,{transports:["websocket"],reconnection:!0,reconnectionAttempts:this.config.reconnectAttempts,reconnectionDelay:this.config.reconnectDelay,...void 0!==this.config.reconnectDelayMax&&{reconnectionDelayMax:this.config.reconnectDelayMax}});return this.socket=e,this.attachListeners(e),e}attachListeners(e){e.on("connect",()=>{this.onSocketConnect()}),e.on("disconnect",e=>{this.onSocketDisconnect(e)}),e.on("connect_error",e=>{this.logger.error("❌ Stream WebSocket connection error:",e),this.settleConnectWaiters(e)}),e.on("error",e=>{this.logger.error("❌ Stream WebSocket error:",e)});for(const t of vd)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?xd:(this.connectionStateListeners.add(e),()=>{this.connectionStateListeners.delete(e)})}onReconnect(e){return this.disposed?xd:(this.reconnectListeners.add(e),()=>{this.reconnectListeners.delete(e)})}async resolveToken(){const e=this.config.tokenProvider;if(void 0===e)return this.lastExplicitToken;try{const t=await e();return null!==t&&""!==t?t:null}catch(e){return this.logger.warn(`The token provider failed: ${ut(e)}`),null}}authenticate(e){if(""===e)return Promise.reject(Tt("token","Authentication token"));const t=this.pendingAuthenticate;if(null!==t&&t.token===e&&t.generation===this.connectionGeneration)return t.promise;this.authSequence+=1;const n=this.authSequence,r=this.runAuthenticate(e,n).finally(()=>{this.pendingAuthenticate?.promise===r&&(this.pendingAuthenticate=null)});return this.pendingAuthenticate={token:e,generation:this.connectionGeneration,promise:r},r}async runAuthenticate(e,t){if(this.disposed)return!1;const n=e??await this.resolveToken();if(t!==this.authSequence||null===n)return!1;void 0!==e&&(this.lastExplicitToken=e);try{await this.connect()}catch(e){return this.logger.warn(`Cannot authenticate, the connection failed: ${ut(e)}`),!1}for(;null!==this.inFlight;)if(await this.inFlight.settled,t!==this.authSequence)return!1;const r=this.liveSocket();if(t!==this.authSequence||null===r)return!1;if(this.authenticated&&this.authenticatedToken===n&&this.authenticatedGeneration===this.connectionGeneration)return!0;const s=this.beginAuthentication(t,n);this.lastEmitted={seq:t,token:n,generation:this.connectionGeneration},this.logger.debug("📡 Authenticating with stream server"),r.emit(pd.AUTHENTICATE,{token:n});return await s.result&&t===this.authSequence}beginAuthentication(e,t){let n=()=>{};const r=new Promise(e=>{n=e}),s={seq:e,token:t,generation:this.connectionGeneration,result:r,settled:r.then(()=>{}),timer:void 0,settle:e=>{this.finishAuthentication(s,e,n)}};return s.timer=setTimeout(()=>{this.logger.warn("Stream WebSocket authentication timed out"),s.settle(!1)},this.config.subscriptionTimeout),this.inFlight=s,s}finishAuthentication(e,t,n){if(this.inFlight!==e)return;void 0!==e.timer&&clearTimeout(e.timer),this.inFlight=null;const r=e.seq===this.authSequence&&e.generation===this.connectionGeneration;t&&r&&this.markAuthenticated(e.token,e.generation),n(t&&r)}markAuthenticated(e,t){this.authenticated=!0,this.authenticatedToken=e,this.authenticatedGeneration=t,this.wantsAuthentication=!0,this.syncAllRooms()}adoptLateAuthentication(){const e=this.lastEmitted;null===e||this.authenticated||e.seq===this.authSequence&&e.generation===this.connectionGeneration&&this.markAuthenticated(e.token,e.generation)}deauthenticate(){this.authSequence+=1;const e=this.authenticated||null!==this.inFlight;this.inFlight?.settle(!1),this.pendingAuthenticate=null,this.wantsAuthentication=!1,this.lastExplicitToken=null,this.authenticated=!1,this.authenticatedToken=null,this.authenticatedGeneration=-1,e&&null!==this.socket&&!this.disposed&&(this.socket.disconnect(),this.socket.connect())}isAuthenticatedForChat(){return this.authenticated}isConnected(){return this.socket?.connected??!1}requireReady(){const e=this.liveSocket();if(null===e)throw new rt("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(!this.authenticated)throw new rt("Not authenticated. Call authenticate() first.","auth","NOT_AUTHENTICATED");return e}sendChatMessage(e,t){if(""===e)throw Tt("tokenName","Token name");if(""===t)throw Tt("content","Message content");const n=this.requireReady(),r=Kt(e);this.logger.debug(`📡 Sending chat message to ${r}: ${t.slice(0,30)}...`),n.emit(pd.SEND_CHAT,{tokenName:r,content:t})}sendReaction(e,t,n=0){if(""===e)throw Tt("tokenName","Token name");if(""===t)throw Tt("emoji");const r=this.requireReady(),s=Kt(e);this.logger.debug(`📡 Sending reaction to ${s}: ${t}`),r.emit(pd.SEND_REACTION,{tokenName:s,emoji:t,streamTime:n})}sendTypingStart(e){this.sendTypingEvent(e,pd.TYPING_START)}sendTypingStop(e){this.sendTypingEvent(e,pd.TYPING_STOP)}sendTypingEvent(e,t){if(""===e)throw Tt("tokenName","Token name");this.requireReady().emit(t,{tokenName:Kt(e)})}subscribeToken(e,t,n){const r=Pd(t);return this.register(e,e=>n(Ld(0,e)),{token:r,room:Ud(r)})}joinTokenRoom(e){return this.hold(Ud(Pd(e)))}subscribeComment(e,t,n){const r=Pd(t);return this.register(e,e=>n(Ld(0,e)),{token:r,room:Fd(r)})}subscribeFeed(e,t){return this.register(e,e=>t(Ld(0,e)),{room:bd})}subscribeEvent(e,t){return this.register(e,e=>t(Ld(0,e)))}subscribeEventsFirehose(e,t){const n=function(e){if(void 0===e)return;const t=e.eventTypes?.map(e=>e.toLowerCase()),n=void 0===e.tokenName?void 0:Kt(e.tokenName),r=e.userAddress;return void 0!==t||void 0!==n||void 0!==r?e=>{if(!Md(e))return!1;const s=e.eventType;if(void 0!==t&&("string"!=typeof s||!t.includes(s.toLowerCase())))return!1;const o=e.tokenName;if(void 0!==n&&("string"!=typeof o||Kt(o)!==n))return!1;const i=e.userAddress;return void 0===r||"string"==typeof i&&rn(i,r)}:void 0}(t);return this.register("EVENT",t=>e(Ld(0,t)),{room:Nd,...void 0!==n&&{filter:n}})}subscribeFeedTokenEvents(e){const t=Id.map(t=>this.register(t,n=>e(function(e,t){return{event:e,data:Ld(0,t)}}(t,n)),{room:bd}));return()=>{for(const e of t)e()}}subscribeToGlobalFeed(e={}){const t=this.registerCallbacks(e,Od,()=>({})),n=this.hold(bd);return()=>{t(),n()}}addCallbacks(e){return this.registerCallbacks(e,Rd,()=>({}))}registerCallbacks(e,t,n){const r=[],s={...e};for(const[e,o]of Object.entries(t)){const t=s[e];"function"==typeof t&&r.push(this.register(o,e=>Reflect.apply(t,void 0,[e]),n(o)))}return()=>{for(const e of r)e()}}async subscribeToStream(e,t={}){const n=Pd(e),r=Ud(n),s=this.epoch;if(await this.connect(),s!==this.epoch||this.disposed)throw new Error("WebSocket disconnected");const o=this.registerCallbacks(t,Rd,e=>{return t=e,Cd.has(t)?{token:n}:function(e){return Dd.has(e)}(e)?{token:n,room:Fd(n)}:{};var t}),i=this.hold(r),a={release:()=>{o(),i()}},c=this.explicitHolds.get(n)??[];c.push(a),this.explicitHolds.set(n,c);try{return await this.waitForRoom(r,n)}catch(e){throw this.dropExplicitHold(n,a),e}}waitForRoom(e,t){return"joined"===this.roomStates.get(e)?.phase?Promise.resolve({room:e,tokenName:t}):new Promise((n,r)=>{const s={resolve:n,reject:r,timer:setTimeout(()=>{this.roomWaiters.get(e)?.delete(s),r(new Error(`Subscription to ${t} timed out after ${this.config.subscriptionTimeout}ms`))},this.config.subscriptionTimeout)},o=this.roomWaiters.get(e)??new Set;o.add(s),this.roomWaiters.set(e,o)})}dropExplicitHold(e,t){t.release();const n=(this.explicitHolds.get(e)??[]).filter(e=>e!==t);0===n.length?this.explicitHolds.delete(e):this.explicitHolds.set(e,n)}unsubscribeFromStream(e){const t=Kt(e),n=this.explicitHolds.get(t);if(void 0!==n){this.explicitHolds.delete(t);for(const e of n)e.release()}else this.logger.debug(`📡 Not subscribed to ${t} through subscribeToStream, skipping unsubscribe`)}subscribeStreamStatus(e,t){return this.subscribeToken("STREAM_STATUS",e,t)}subscribeViewerCount(e,t){return this.subscribeToken("VIEWER_COUNT",e,t)}subscribeRecordingStatus(e,t){return this.subscribeToken("RECORDING_STATUS",e,t)}subscribeRecordingsCountUpdated(e,t){return this.subscribeToken("RECORDINGS_COUNT_UPDATED",e,t)}subscribeSimulcastStatus(e,t){return this.subscribeToken("SIMULCAST_STATUS",e,t)}subscribeDownloadReady(e,t){return this.subscribeToken("DOWNLOAD_READY",e,t)}subscribeCountdownUpdated(e,t){return this.subscribeToken("STREAM_COUNTDOWN_UPDATED",e,t)}subscribeLanguageUpdated(e,t){return this.subscribeToken("STREAM_LANGUAGE_UPDATED",e,t)}subscribeStreamControlStatusChanged(e,t){return this.subscribeToken("STREAM_CONTROL_STATUS_CHANGED",e,t)}subscribeEngagementStatsUpdated(e,t){return this.subscribeToken("ENGAGEMENT_STATS_UPDATED",e,t)}subscribeChatMessages(e,t){return this.subscribeToken("STREAM_CHAT_MESSAGE",e,t)}subscribeChatSent(e,t){return this.subscribeToken("STREAM_CHAT_SENT",e,t)}subscribeChatUpdated(e,t){return this.subscribeToken("STREAM_CHAT_UPDATED",e,t)}subscribeChatDeleted(e,t){return this.subscribeToken("STREAM_CHAT_DELETED",e,t)}subscribeChatPinned(e,t){return this.subscribeToken("STREAM_CHAT_PINNED",e,t)}subscribeChatUnpinned(e,t){return this.subscribeToken("STREAM_CHAT_UNPINNED",e,t)}subscribeChatStatus(e,t){return this.subscribeToken("CHAT_STATUS_CHANGED",e,t)}subscribeChatSlowMode(e,t){return this.subscribeToken("SLOW_MODE_CHANGED",e,t)}subscribeTypingIndicator(e,t){return this.subscribeToken("USER_TYPING",e,t)}subscribeReactions(e,t){return this.subscribeToken("STREAM_REACTION",e,t)}subscribeContentReactionAdded(e,t){return this.subscribeToken("CONTENT_REACTION_ADDED",e,t)}subscribeContentReactionRemoved(e,t){return this.subscribeToken("CONTENT_REACTION_REMOVED",e,t)}subscribeTradeExecuted(e,t){return this.subscribeToken("TRADE_EXECUTED",e,t)}subscribeBalanceUpdated(e,t){return this.subscribeToken("BALANCE_UPDATED",e,t)}subscribeTokenBanned(e,t){return this.subscribeToken("TOKEN_BANNED",e,t)}subscribeTokenUnbanned(e,t){return this.subscribeToken("TOKEN_UNBANNED",e,t)}subscribeModeratorInviteCreated(e,t){return this.subscribeToken("MODERATOR_INVITE_CREATED",e,t)}subscribeModeratorAdded(e,t){return this.subscribeToken("MODERATOR_ADDED",e,t)}subscribeModeratorRemoved(e,t){return this.subscribeToken("MODERATOR_REMOVED",e,t)}subscribeModeratorRoleUpdated(e,t){return this.subscribeToken("MODERATOR_ROLE_UPDATED",e,t)}subscribePoolMetadataUpdated(e,t){return this.subscribeToken("POOL_METADATA_UPDATED",e,t)}subscribePoolSocialLinksUpdated(e,t){return this.subscribeToken("POOL_SOCIAL_LINKS_UPDATED",e,t)}subscribePoolBadgeAssigned(e,t){return this.subscribeToken("POOL_BADGE_ASSIGNED",e,t)}subscribeHolderCountUpdated(e,t){return this.subscribeToken("HOLDER_COUNT_UPDATED",e,t)}subscribeTokenConfigUpdated(e,t){return this.subscribeToken("TOKEN_CONFIG_UPDATED",e,t)}subscribeCommentCreated(e,t){return this.subscribeComment("COMMENT_CREATED",e,t)}subscribeCommentUpdated(e,t){return this.subscribeComment("COMMENT_UPDATED",e,t)}subscribeCommentDeleted(e,t){return this.subscribeComment("COMMENT_DELETED",e,t)}subscribeStatsUpdated(e){return this.subscribeFeed("STATS_UPDATED",e)}subscribePoolCreated(e){return this.subscribeFeed("POOL_CREATED",e)}subscribeStreamGlobalStatus(e){return this.subscribeFeed("STREAM_GLOBAL_STATUS",e)}subscribeChatGlobalStatus(e){return this.subscribeFeed("STREAM_CHAT_GLOBAL_STATUS",e)}subscribeCommentsGlobalStatus(e){return this.subscribeFeed("COMMENTS_GLOBAL_STATUS",e)}subscribeWebhooksGlobalStatus(e){return this.subscribeFeed("WEBHOOKS_GLOBAL_STATUS",e)}subscribeAIModerationGlobalStatus(e){return this.subscribeFeed("AI_MODERATION_GLOBAL_STATUS",e)}subscribeSiteConfigChanged(e){return this.subscribeFeed("SITE_CONFIG_CHANGED",e)}getSiteConfigState(){return{...this.siteConfig}}subscribeOverseerAdded(e){return this.subscribeEvent("OVERSEER_ADDED",e)}subscribeOverseerRemoved(e){return this.subscribeEvent("OVERSEER_REMOVED",e)}subscribeUserProfileUpdated(e){return this.subscribeEvent("USER_PROFILE_UPDATED",e)}subscribeApiKeyCreated(e){return this.subscribeEvent("API_KEY_CREATED",e)}subscribeApiKeyUpdated(e){return this.subscribeEvent("API_KEY_UPDATED",e)}subscribeApiKeyRevoked(e){return this.subscribeEvent("API_KEY_REVOKED",e)}subscribeGlobalTokenBanned(e){return this.subscribeEvent("TOKEN_BANNED",e)}subscribeGlobalTokenUnbanned(e){return this.subscribeEvent("TOKEN_UNBANNED",e)}subscribeGlobalModeratorAdded(e){return this.subscribeEvent("MODERATOR_ADDED",e)}subscribeGlobalModeratorRemoved(e){return this.subscribeEvent("MODERATOR_REMOVED",e)}subscribeGlobalModeratorRoleUpdated(e){return this.subscribeEvent("MODERATOR_ROLE_UPDATED",e)}subscribeGlobalModeratorInviteCreated(e){return this.subscribeEvent("MODERATOR_INVITE_CREATED",e)}subscribeContentFlagged(e){return this.subscribeEvent("CONTENT_FLAGGED",e)}subscribeFlagResolved(e){return this.subscribeEvent("FLAG_RESOLVED",e)}subscribeAIModerationComplete(e){return this.subscribeEvent("AI_MODERATION_COMPLETE",e)}subscribeAIModerationFailed(e){return this.subscribeEvent("AI_MODERATION_FAILED",e)}subscribeUserBanned(e){return this.subscribeEvent("USER_BANNED",e)}subscribeUserUnbanned(e){return this.subscribeEvent("USER_UNBANNED",e)}subscribeBanEnforcement(e){return this.subscribeEvent("BAN_ENFORCEMENT",e)}subscribeTradeUpdateNotify(e){return this.subscribeEvent("TRADE_UPDATE_NOTIFY",e)}subscribeReactionErrors(e){return this.subscribeEvent("stream_reaction_error",e)}subscribeChatErrors(e){return this.subscribeEvent("stream_chat_error",e)}subscribeException(e){return this.subscribeEvent("exception",e)}getSubscribedTokens(){const e=[];for(const t of this.roomRefs.keys())t.startsWith(Sd)&&e.push(t.slice(Sd.length));return e}isSubscribedToGlobalFeed(){return(this.roomRefs.get(bd)??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 Gd(e){if(!Md(e))return;const t=e.enabled;return"boolean"==typeof t?t:void 0}function $d(e){return null==e||""===e||"string"==typeof e&&(!$n(e)&&e.length<=or.BAN_REASON.MAX_LENGTH)}function Kd(e){if(Fn(e.tokenName,"tokenName",Xn),!$d(e.reason))throw new rt(`reason must be at most ${or.BAN_REASON.MAX_LENGTH} characters`,"reason","TOO_LONG")}function Hd(e){Fn(e.tokenName,"tokenName",Jn)}function Wd(e){Mn(0,void 0,tr,e.pageSize)}function Vd(e){Fn(e.tokenName,"tokenName",Jn)}class jd extends ci{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async banToken(e){Kd(e);const t=ye,n={tokenName:Kt(e.tokenName)};if(void 0!==e.reason)try{In(e.reason,"reason",!0),e.reason.trim().length>0&&(n.reason=e.reason)}catch{}const r=await this.http.post(t,n,this.getDualAuthHeaders());return{ban:this.extractData(r),tokenName:Kt(e.tokenName)}}async unbanToken(e){Hd(e);const t=this.buildEndpoint(ke,{tokenName:e.tokenName});return Mt(await this.http.delete(t,void 0,this.getDualAuthHeaders()),"Failed to unban token",!1),{tokenName:Kt(e.tokenName)}}async listTokenBans(e={}){Wd(e);const t=be,n=this.buildPaginationParams(e,tr);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){Vd(e);const t=this.buildEndpoint(Ne,{tokenName:e.tokenName}),n=await this.http.get(t,{},this.getDualAuthHeaders()),r=this.extractDataOrNull(n);return{banned:null!==r,...null!==r&&{ban:r},tokenName:Kt(e.tokenName)}}async isTokenBanned(e){return this.getTokenBan(e)}}class qd extends qn{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(!Rn(e))throw Tt("tokenName","Token name");const t=Kt(e),n=this.getCacheEntry(t);if(null!==n)return this.cacheHits++,this.updateAccessOrder(t),n.vaultAddress;this.cacheMisses++;const r=await this.poolService.resolveTokenNameToVault(e);if(null!==r&&""!==r){const e=this.parseVaultAddressToTokenClassKey(r);this.setCacheEntry(t,{vaultAddress:r,tokenClassKey:e,cachedAt:Date.now()})}return r}async resolveTokenClassKey(e){if(!Rn(e))throw Tt("tokenName","Token name");const t=Kt(e),n=this.getCacheEntry(t);if(null!==n)return this.cacheHits++,this.updateAccessOrder(t),n.tokenClassKey;this.cacheMisses++;const r=await this.poolService.resolveTokenNameToVault(e);if(null===r||""===r)throw At(e);const s=this.parseVaultAddressToTokenClassKey(r);return this.setCacheEntry(t,{vaultAddress:r,tokenClassKey:s,cachedAt:Date.now()}),s}get(e){const t=this.getCacheEntry(Kt(e));return t?.vaultAddress??null}getCacheEntry(e){return this.cache.get(e)??null}setCacheEntry(e,t){this.cache.size>=qd.MAX_CACHE_SIZE&&!this.cache.has(e)&&this.evictOldestEntry(),this.cache.set(e,t),this.updateAccessOrder(e)}updateAccessOrder(e){this.accessOrder.delete(e),this.accessOrder.add(e)}evictOldestEntry(){const e=this.accessOrder.values().next().value;void 0!==e&&""!==e&&(this.cache.delete(e),this.accessOrder.delete(e))}set(e,t){const n=Kt(e),r=this.parseVaultAddressToTokenClassKey(t);this.setCacheEntry(n,{vaultAddress:t,tokenClassKey:r,cachedAt:Date.now()})}clear(){this.cache.clear(),this.accessOrder=new Set,this.cacheHits=0,this.cacheMisses=0}getStats(){const e=Array.from(this.cache.values()).map(e=>e.cachedAt),t=this.cacheHits+this.cacheMisses;return{size:this.cache.size,keys:Array.from(this.cache.keys()),maxSize:qd.MAX_CACHE_SIZE,hits:this.cacheHits,misses:this.cacheMisses,hitRate:t>0?this.cacheHits/t:0,oldestEntry:e.length>0?Math.min(...e):null,newestEntry:e.length>0?Math.max(...e):null}}getCachedTokenClassKey(e){const t=this.getCacheEntry(Kt(e));return t?.tokenClassKey??null}preWarm(e){for(const{tokenName:t,vaultAddress:n}of e)this.set(t,n)}preWarmWithTokenClassKey(e){for(const{tokenName:t,vaultAddress:n,tokenClassKey:r}of e){const e=Kt(t);this.setCacheEntry(e,{vaultAddress:n,tokenClassKey:r,cachedAt:Date.now()})}}parseVaultAddressToTokenClassKey(e){try{return oa(e)}catch(e){if(e instanceof rt)throw vt("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad","Vault address");throw e}}}qd.MAX_CACHE_SIZE=1e4;class zd extends jn{constructor(e,t=!1){super(e,t)}async fetchLaunchpadFee(){const e=await Ft(()=>this.http.get($e),{errorContext:"Failed to fetch launchpad fee"});if("number"!=typeof e.feeAmount||!Number.isFinite(e.feeAmount))throw new rt("Failed to fetch launchpad fee: no feeAmount in the response","feeAmount","INVALID_RESPONSE");return e.feeAmount}async fetchSaleDetails(e){return Ft(()=>this.http.get(Ke,{tokenName:e}),{errorContext:`Failed to fetch sale details for ${e}`})}async getTradeQuote(e){const t={tokenName:e.tokenName,amount:e.amount,type:e.type,method:e.method},{signal:n}=e;return _o(await Ft(()=>void 0===n?this.http.get(He,t):this.http.request({method:"GET",url:He,params:t,signal:n}),{errorContext:`Failed to get trade quote for ${e.tokenName}`}),`trade quote for ${e.tokenName}`)}async getPremintQuote(e){return _o(await Ft(()=>this.http.get(We,{amount:e}),{errorContext:"Failed to get premint quote"}),"premint quote")}}class Yd extends ci{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async emitTradeExecuted(e,t){this.validateTokenName(e,er);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,er);const r={action:"balance_updated",userAddress:en(e,"userAddress"),tokenName:t,payload:n};await this.emitEvent(r)}async emitStreamStatus(e,t,n=!0){this.validateTokenName(e,er);const r={action:"stream_status",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitViewerCount(e,t,n=!1){this.validateTokenName(e,er);const r={action:"viewer_count",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitStreamCountdown(e,t,n=!0){this.validateTokenName(e,er);const r={action:"stream_countdown",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitChatMessage(e,t,n=!1){this.validateTokenName(e,er);const r={action:"chat_message",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitChatStatus(e,t,n=!1){this.validateTokenName(e,er);const r={action:"chat_status",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitTypingIndicator(e,t,n=!1){this.validateTokenName(e,er);const r={action:"typing_indicator",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitTokenBanned(e,t){this.validateTokenName(e,er);const n={action:"token_banned",tokenName:e,payload:t,broadcast:!0};await this.emitEvent(n)}async emitTokenUnbanned(e,t){this.validateTokenName(e,er);const n={action:"token_unbanned",tokenName:e,payload:t,broadcast:!0};await this.emitEvent(n)}async emitModeratorAdded(e,t,n=!1){this.validateTokenName(e,er);const r={action:"moderator_added",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitModeratorRemoved(e,t,n=!1){this.validateTokenName(e,er);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:en(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=Zt(e.userAddress,"userAddress")),void 0!==e?.userAddresses&&(n.userAddresses=e.userAddresses.split(",").map(e=>Zt(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 ct("userAddresses must be a non-empty array");const t=await this.getConnectedClients({userAddresses:e.join(","),limit:e.length}),n=t.clients.filter(e=>"string"==typeof e.address&&""!==e.address).map(e=>e.address);return{online:n,offline:e.filter(e=>!n.some(t=>rn(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,er);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,er);const n={action:"recording_status",tokenName:e,payload:t};await this.emitEvent(n)}async emitRecordingsCountUpdated(e,t){this.validateTokenName(e,er);const n={action:"recordings_count_updated",tokenName:e,payload:t};await this.emitEvent(n)}async emitDownloadReady(e,t){this.validateTokenName(e,er);const n={action:"download_ready",tokenName:e,payload:t};await this.emitEvent(n)}}class Xd{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 Qd{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 Jd extends qn{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 Xd({maxAttempts:this.config.reconnectAttempts??5,baseDelayMs:this.config.reconnectDelay??2e3}),this.eventBuffer=new Qd(3e4),this.isSocketIOAvailable=this.checkSocketIOAvailability(),Jd.instances.add(this)}checkSocketIOAvailability(){try{return"function"==typeof i.io||(this.logger.warn('⚠️ Socket.IO client not available. Install "socket.io-client" package.'),!1)}catch(e){return this.logger.warn("⚠️ Socket.IO availability check failed:",e),!1}}async connect(){return new Promise((e,t)=>{$o(async()=>{if(!this.isSocketIOAvailable){const e=new Error('Socket.IO not available in current environment. Install "socket.io-client" package.');throw this.logger.error("❌ Socket.IO connection failed:",ut(e)),e}this.logger.debug("🔌 Connecting to Socket.IO server:",this.config.url),this.socket=i.io(this.config.url,{transports:["websocket"],reconnection:!0,reconnectionAttempts:this.config.reconnectAttempts??5,reconnectionDelay:this.config.reconnectDelay??2e3}),this.socket.on("connect",()=>{this.logger.debug("✅ Socket.IO connected successfully:",this.socket?.id),this.logger.debug("📡 Connected to bundle backend WebSocket:",this.config.url),this.logger.debug("🔗 Ready to monitor transaction updates"),this.reconnectionManager.reset(),e()}),this.socket.on("connect_error",e=>{this.logger.error("❌ Socket.IO connection error:",e),t(e)}),this.socket.on("disconnect",e=>{this.logger.debug(`🔌 Socket.IO disconnected: ${e}`),this.handleReconnect()}),this.socket.on("error",e=>{this.logger.error("❌ Socket.IO error:",e)}),this.socket.onAny((e,...t)=>{if(""!==e&&t.length>0&&"object"==typeof t[0]&&null!==t[0]){const n=t[0],r=n.status??n.Status;"string"==typeof r&&(this.logger.debug(`📡 [Event Buffer] Buffering event for ${e}: ${r}`),this.eventBuffer.size>=this.MAX_BUFFER_SIZE&&this.logger.warn(`📡 [Event Buffer] Buffer approaching limit (${this.eventBuffer.size}/${this.MAX_BUFFER_SIZE})`),this.eventBuffer.set(e,n))}this.debug&&this.logger.debug(`📡 [WebSocket Event] "${e}":`,JSON.stringify(t,null,2))}),this.hasOnAnyListener=!0},"Socket.IO connection failed",this.logger,e=>{this.logger.error("Socket.IO connection failed:",e);const n=dt(e)?e:new Error(ut(e));throw t(n),n}).catch(t)})}async monitorTransaction(e,t){this.listeners.set(e,t),this.logger.debug(`📡 Starting to monitor transaction: ${e}`),this.logger.debug(`📡 WebSocket connected: ${String(this.socket?.connected??!1)}`);const n=this.eventBuffer.get(e);null!=n&&(this.logger.debug(`📡 [Event Buffer] Found buffered event for ${e}, delivering immediately`),setImmediate(()=>{this.processTransactionEvent(e,n,t)}),this.eventBuffer.delete(e));const r=this.config.timeout??3e5,s=setTimeout(()=>{if(this.listeners.has(e)){const n=Math.round(r/1e3),s={transactionId:e,status:exports.SDKTransactionStatus.TIMEOUT,message:`Transaction monitoring timeout - no response after ${n} seconds`,timestamp:Date.now()};this.logger.debug(`📡 Transaction timeout for ${e} (${n}s)`),t(s),this.listeners.delete(e),this.timeouts.delete(e),this.socket?.off(e)}},r);if(this.timeouts.set(e,s),this.socket?.connected)this.socket.off(e),this.logger.debug(`📡 Listening for transaction updates: ${e}`),this.logger.debug(`📡 WebSocket connection ID: ${String(this.socket.id)}`),this.logger.debug(`📡 WebSocket URL: ${this.config.url}`),this.socket.on(e,n=>{this.processTransactionEvent(e,n,t)});else{const n={transactionId:e,status:exports.SDKTransactionStatus.FAILED,message:"WebSocket not connected - cannot monitor transaction",timestamp:Date.now()};t(n),this.listeners.delete(e),this.timeouts.delete(e)}await Promise.resolve()}processTransactionEvent(e,t,n){this.logger.debug(`📡 Socket.IO transaction update for ${e}:`,JSON.stringify(t,null,2));const r=t,s=r?.data,o=r?.status??r?.Status??s?.status??s?.Status;let i=r?.message??r?.Message??s?.message??s?.Message??r?.error??s?.error;Rn(i)||(i=o===qo.FAILED||o===qo.ERROR?"Transaction failed - check transaction details":o===qo.COMPLETED||o===qo.PROCESSED||o===qo.SUCCESS?"Transaction completed successfully":null!=o?`Transaction status: ${String(o)}`:"Unknown transaction status");const a=r?.blockHash??s?.blockHash,c=r?.gasUsed??s?.gasUsed,l=r?.Data??s?.Data,d={transactionId:e,status:this.mapSocketStatus(o),message:"string"==typeof i?i:"Transaction update received",timestamp:Date.now(),...null!=a?{blockHash:a}:{},...null!=c?{gasUsed:c}:{},...null!=l?{data:l}:{}};if(this.logger.debug(`📡 Mapped status for ${e}: ${String(o)} -> ${d.status}`),this.logger.debug(`📡 Final message: "${String(i)}"`),n(d),d.status===exports.SDKTransactionStatus.COMPLETED||d.status===exports.SDKTransactionStatus.FAILED){this.listeners.delete(e);const t=this.timeouts.get(e);t&&(clearTimeout(t),this.timeouts.delete(e)),this.socket?.off(e),this.logger.debug(`📡 Cleaned up listener for ${e} (${d.status})`)}}async waitForTransaction(e){return new Promise((t,n)=>{this.monitorTransaction(e,e=>{e.status===exports.SDKTransactionStatus.COMPLETED?t(e):e.status!==exports.SDKTransactionStatus.FAILED&&e.status!==exports.SDKTransactionStatus.TIMEOUT||n(new Error(`Transaction ${String(e.status)}: ${e.message}`))})})}mapSocketStatus(e){const t=e?.toUpperCase();return Yo[t]??exports.SDKTransactionStatus.PENDING}async handleReconnect(){this.reconnectionManager.shouldRetry()?(this.reconnectionManager.recordAttempt(),this.logger.debug(`🔄 Attempting Socket.IO reconnect ${this.reconnectionManager.getStatusString()}`),setTimeout(()=>{this.socket&&!this.socket.connected&&this.socket.connect()},this.reconnectionManager.getNextDelay())):this.logger.error("❌ Socket.IO max reconnection attempts reached")}disconnect(){this.socket&&(this.listeners.forEach((e,t)=>{this.socket?.off(t)}),this.listeners.clear(),this.timeouts.forEach(e=>{clearTimeout(e)}),this.timeouts.clear(),this.eventBuffer.clear(),this.logger.debug("🧹 Cleared event buffer"),this.hasOnAnyListener&&(this.socket.offAny(),this.hasOnAnyListener=!1,this.logger.debug("🧹 Removed onAny debug listener")),this.socket.disconnect(),this.socket=null,this.logger.debug("🔌 Socket.IO disconnected")),Jd.instances.delete(this)}static cleanupAll(e=!1){for(const e of Jd.instances)e.disconnect();Jd.instances.clear()}isConnected(){return this.socket?.connected??!1}getSocket(){return this.socket}}Jd.instances=new Set;class Zd extends jn{constructor(e,t=!1){super(e,t)}extractData(e){if(e.error||void 0===e.data){const t=e.message??"Weekly challenge operation failed";throw new Error(t)}return e.data}async getLeaderboard(e={}){const{limit:t=10}=e;if(t<1||t>50)throw new rt("limit must be between 1 and 50","limit","INVALID_LIMIT");this.logger.debug("Fetching weekly challenge leaderboard",{limit:t});const n={limit:String(t)},r=await this.http.get(Ve.GET_LEADERBOARD,n),s=this.extractData(r);return this.logger.debug("Fetched weekly challenge leaderboard",{count:s.count}),{leaderboard:s}}async getTokenHistory(e){const{vaultAddress:t}=e;if("string"!=typeof t||""===t.trim())throw new rt("vaultAddress is required","vaultAddress","REQUIRED_FIELD");this.logger.debug("Fetching token weekly history",{vaultAddress:t});const n=Ve.GET_TOKEN_HISTORY.replace(":vaultAddress",encodeURIComponent(t)),r=await this.http.get(n),s=this.extractData(r);return this.logger.debug("Fetched token weekly history",{count:s.length}),{snapshots:s}}}const eu=["CreateSale","BuyWithNative","BuyExactToken","SellWithNative","SellExactToken"];class tu{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 nu{constructor(e){this.bundleBaseUrl=hu(e.bundleBaseUrl),this.launchpadBaseUrl=hu(e.launchpadBaseUrl),this.signer=e.signer,this.walletAddress=""===e.walletAddress?"":Zt(e.walletAddress,"walletAddress"),this.requestor=e.httpRequestor??fetch.bind(globalThis),this.socketFactory=e.socketFactory??(e=>i.io(e,{transports:["websocket"]})),this.bundleSocketFactory=e.bundleSocketFactory}attach(e){const{bundleId:t,method:n,uniqueKey:r,tokenName:s}=e;if("string"!=typeof t||""===t)throw su("bundleId");if(o=n,!eu.some(e=>e===o))throw su("method");var o;if("string"!=typeof r||""===r)throw su("uniqueKey");if(void 0!==s&&("string"!=typeof s||""===s))throw su("tokenName");if("CreateSale"===n&&void 0===s)throw su("tokenName");const i={method:n,dto:{uniqueKey:r,...void 0===s?{}:{tokenName:s}},stringsInstructions:[]};return new tu({bundleId:t,uniqueKey:r,method:n,wait:e=>this.waitForResult(i,t,e)})}async submit(t){let n;try{n=await this.signer.signTypedData(t.method,e.withDtoOperation("asset/launchpad-contract",t.method,t.dto))}catch(t){throw function(t){if(t instanceof Hi)return t;if(e.isWalletUserRejection(t)){const n=t instanceof Error?t.message:"The signature was rejected in the wallet.",r=e.walletDeclineCode(t);return new Hi(n,"WALLET_USER_REJECTED",{details:void 0===r?{}:{walletCode:r}})}const n=t instanceof Error?t.message:"Launchpad signing failed.";return new Hi(n,"LAUNCHPAD_SIGNING_FAILED",{chainMessage:n})}(t)}const r=function(e){return Object.fromEntries(Object.entries(e).filter(([e])=>"prefix"!==e))}(n),s=`${this.bundleBaseUrl}/bundle`,o=await this.requestor(s,{method:"POST",headers:{"content-type":"application/json","X-Wallet-Address":this.walletAddress},body:JSON.stringify({stringsInstructions:t.stringsInstructions,method:t.method,signedDto:r})}),i=await du(o);if(!o.ok)throw iu(o.status,i,s);const a=function(e){if("string"==typeof e&&""!==e)return e;if(!uu(e))throw new Hi("Bundler returned no bundle id.","INVALID_BUNDLE_RESPONSE");const t=e.data,n=e.bundleId;if("string"==typeof t&&""!==t)return t;if(uu(t)&&"string"==typeof t.bundleId&&""!==t.bundleId)return t.bundleId;if("string"==typeof n&&""!==n)return n;throw new Hi("Bundler returned no bundle id.","INVALID_BUNDLE_RESPONSE")}(i),c=lu(t.dto,"uniqueKey");return new tu({bundleId:a,uniqueKey:c,method:t.method,wait:e=>this.waitForResult(t,a,e)})}waitForResult(e,t,n={}){const r=n.timeoutMs??6e4,s=n.pollIntervalMs??2500,o=n.signal;return new Promise((n,i)=>{const a=this.confirmationUrl(e,t);if(!0===o?.aborted)return void i(ru(e.method,t));const c=Date.now(),l=new AbortController,d=void 0===this.bundleSocketFactory;let u,h,g,p=!1;const m=()=>{f(()=>i(ru(e.method,t)))},f=e=>{p||(p=!0,clearTimeout(A),o?.removeEventListener("abort",m),l.abort(),void 0!==u&&(void 0!==h&&u.off(t,h),d&&u.disconnect()),e())},E=()=>{f(()=>i(function(e,t){const n="string"==typeof e.dto.uniqueKey?e.dto.uniqueKey:"";return new Hi(`Timed out waiting for bundle ${n}`,"BUNDLE_CONFIRMATION_TIMEOUT",{details:{method:e.method,...void 0===t?{}:{lastReadFailure:{message:t.message,...void 0===t.status?{}:{status:t.status}}}}})}(e,g)))};o?.addEventListener("abort",m,{once:!0});const A=setTimeout(E,r);try{u=(this.bundleSocketFactory??this.socketFactory)(this.bundleBaseUrl),h=e=>{const t=function(e){if(!uu(e))return;const t=e.status;return"PROCESSED"!==t&&"FAILED"!==t?void 0:{status:t,data:e.data}}(e);void 0!==t&&f(()=>{"FAILED"===t.status?i(ou(t.data)):n(t)})},u.on(t,h)}catch{u=void 0,h=void 0}this.pollConfirmation({request:e,confirmationUrl:a,startedAt:c,timeoutMs:r,pollIntervalMs:s,signal:l.signal,onReadFailure:e=>{g=e}}).then(e=>{void 0===e?E():f(()=>n(e))},e=>f(()=>i(e instanceof Error?e:new Error(String(e)))))})}confirmationUrl(e,t){return"CreateSale"===e.method?function(e,t){const n=lu(t,"tokenName");return`${e}/v1/tokens/${encodeURIComponent(n)}`}(this.launchpadBaseUrl,e.dto):`${this.bundleBaseUrl}/bundle?id=${encodeURIComponent(t)}`}async pollConfirmation(e){const{request:t,confirmationUrl:n,startedAt:r,timeoutMs:s,pollIntervalMs:o,signal:i,onReadFailure:a}=e;for(;!i.aborted&&Date.now()-r<=s;){const e=await this.readConfirmation(t,n,i);if(i.aborted)return;if("processed"===e.kind)return e.result;if("failed"===e.kind)throw ou(e.data);a("read-failed"===e.kind?e.error:void 0);const c=s-(Date.now()-r);if(c<=0)break;await gu(Math.min(Math.max(0,o),c),i)}}async readConfirmation(e,t,n){try{const r=await this.requestor(t,{method:"GET",signal:n}),s=await du(r);if("CreateSale"===e.method)return r.ok?{kind:"processed",result:{status:"PROCESSED",data:cu(s)}}:404===r.status||202===r.status?{kind:"pending"}:{kind:"read-failed",error:iu(r.status,s,t)};if(!r.ok)return{kind:"read-failed",error:iu(r.status,s,t)};const o=uu(s)?s.status:void 0;return"COMPLETED"===o||"PROCESSED"===o?{kind:"processed",result:{status:"PROCESSED",data:s}}:"FAILED"===o?{kind:"failed",data:s}:{kind:"pending"}}catch(e){const n=e instanceof Error?e.message:"The bundle confirmation read failed.";return{kind:"read-failed",error:new Hi(n,"BUNDLE_REQUEST_FAILED",{details:{url:t}})}}}}function ru(e,t){return new Hi("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 su(e){return new Hi(`Cannot attach to a launchpad bundle: ${e} is missing or not accepted.`,"INVALID_BUNDLE_ATTACHMENT",{details:{field:e}})}function ou(e){const t=au(e)??"Launchpad bundle failed on chain.";return new Hi(t,"BUNDLE_FAILED",{chainMessage:t})}function iu(e,t,n){const r=au(t)??`Bundle request failed with HTTP ${e}`;return new Hi(r,"BUNDLE_REQUEST_FAILED",{status:e,chainMessage:r,details:{body:t,url:n}})}function au(e){if("string"==typeof e&&""!==e)return e;if(uu(e))for(const t of["chainMessage","message","Message","error"]){const n=e[t];if("string"==typeof n&&""!==n)return n;if(uu(n)){const e=au(n);if(void 0!==e)return e}}}function cu(e){return uu(e)?e.data??e.Data??e:e}function lu(e,t){const n=e[t];if("string"!=typeof n||""===n)throw new Hi(`Missing ${t} in launchpad DTO.`,"INVALID_LAUNCHPAD_DTO");return n}async function du(e){try{return await e.json()}catch{return e.text()}}function uu(e){return"object"==typeof e&&null!==e}function hu(e){return e.replace(/\/$/u,"")}function gu(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 pu(e,t){if(!/^\d+(\.\d+)?$/.test(e))throw new rt(`Quoted reverse bonding curve fee is not a non-negative number: ${e}`,"extraFees","INVALID_QUOTED_FEE");if(!Number.isFinite(t)||t<0)throw new rt(`Fee slippage factor must be a non-negative number, got ${String(t)}`,"maxAcceptableReverseBondingCurveFeeSlippageFactor","INVALID_FEE_SLIPPAGE_FACTOR");return new a(e).multipliedBy(new a(1).plus(new a(String(t)))).decimalPlaces(8,a.ROUND_UP).toFixed()}function mu(e){return async t=>{const n=t.tokenName??await async function(e,t){const n=ea(t).type,r=await e.findTokenNameByVault(t,n);if(void 0===r)throw new rt(`Could not find the launchpad token for vault ${t}, so the reverse bonding curve fee ceiling cannot be quoted. Pass tokenName, or pass extraFees.maxAcceptableReverseBondingCurveFee explicitly.`,"tokenName","TOKEN_NOT_FOUND_FOR_VAULT");return r}(e,t.vaultAddress);return pu((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 fu={minFeePortion:"0.1",maxFeePortion:"0.5"},Eu=/^(?:\d+\.?\d*|\.\d+)$/u,Au=/^[0-9A-Z]+$/u,Tu=/^[A-Za-z0-9]+$/u,vu=new a("0.1"),Su=new a("0.5");function yu(e){if("string"!=typeof e||!Eu.test(e))return;const t=new a(e);return t.isFinite()?t.toFixed():void 0}function bu(e){return"string"==typeof e&&""!==e}function Nu(e,t,n){void 0!==n&&"string"!=typeof n&&e.push(`${t} must be a string`)}function ku(e,t,n){void 0===n||bu(n)||e.push(`${t} must be a non-empty string`)}function wu(e){const t=[];if("object"!=typeof e||null===e)throw new rt("CreateSale input must be an object","data","VALIDATION_ERROR");const n={...e},r=n.tokenName;bu(r)?Tu.test(r)||t.push("Token name can only contain letters and numbers"):t.push("Token name is required");const s=n.tokenSymbol;bu(s)?Au.test(s.toUpperCase())||t.push("Token symbol can only contain letters and numbers"):t.push("Token symbol is required");const o=n.tokenDescription;bu(o)?o.length>1e3&&t.push("Token description must be at most 1000 characters"):t.push("Token description is required");const i=n.tokenImage;bu(i)?i.length>500&&t.push("Token image must be at most 500 characters"):t.push("Token image is required");const c=n.preBuyQuantity;void 0!==c&&void 0===yu(c)&&t.push("preBuyQuantity must be a non-negative decimal number");for(const e of["websiteUrl","telegramUrl","twitterUrl","instagramUrl","facebookUrl","redditUrl","tiktokUrl"])Nu(t,e,n[e]);ku(t,"tokenCategory",n.tokenCategory),ku(t,"tokenCollection",n.tokenCollection);const l=n.saleStartTime;if(void 0===l||Number.isInteger(l)||t.push("saleStartTime must be an integer"),function(e,t){if(void 0!==t&&("object"!=typeof t||null===t))return void e.push("reverseBondingCurveConfiguration must be an object");const n=t??{},r=n.minFeePortion??fu.minFeePortion,s=n.maxFeePortion??fu.maxFeePortion,o=yu(r),i=yu(s);if(void 0===o&&e.push("minFeePortion must be a decimal number"),void 0===i&&e.push("maxFeePortion must be a decimal number"),void 0===o||void 0===i)return;const c=new a(o),l=new a(i);c.isLessThan(vu)&&e.push("minFeePortion must be greater than or equal to 0.1"),l.isGreaterThan(Su)&&e.push("maxFeePortion must be less than or equal to 0.5"),c.isGreaterThan(l)&&e.push("minFeePortion must be less than or equal to maxFeePortion")}(t,n.reverseBondingCurveConfiguration),t.length>0)throw new rt(t.join("; "),"data","VALIDATION_ERROR")}class _u{constructor(e){this.transport=e.transport,this.walletAddress=""===e.walletAddress?"":Zt(e.walletAddress,"walletAddress"),this.sellFeeCeiling=e.sellFeeCeiling}createSale(e){wu(e);const t=function(e,t){const n={tokenName:e.tokenName,tokenSymbol:e.tokenSymbol,tokenDescription:e.tokenDescription,tokenImage:e.tokenImage,preBuyQuantity:yu(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??Iu(t)},r=e.reverseBondingCurveConfiguration;n.reverseBondingCurveConfiguration={minFeePortion:yu(r?.minFeePortion??fu.minFeePortion),maxFeePortion:yu(r?.maxFeePortion??fu.maxFeePortion)},void 0!==e.saleStartTime&&(n.saleStartTime=e.saleStartTime);return n}(e,this.walletAddress);return this.transport.submit({method:"CreateSale",dto:t,stringsInstructions:na(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??Iu(this.walletAddress)};return this.transport.submit({method:e,dto:r,stringsInstructions:ta(t.vaultAddress)})}async defaultExtraFees(e,t){if("BuyWithNative"===e||"BuyExactToken"===e)return{maxAcceptableReverseBondingCurveFee:"0"};if(void 0===this.sellFeeCeiling)throw new rt("A sell needs a reverse bonding curve fee ceiling and no quote source is configured: pass extraFees.maxAcceptableReverseBondingCurveFee.","extraFees","FEE_CEILING_REQUIRED");return{maxAcceptableReverseBondingCurveFee:await this.sellFeeCeiling({method:e,vaultAddress:t.vaultAddress,quantity:t.quantity,...void 0===t.tokenName?{}:{tokenName:t.tokenName}})}}}function Iu(e){return`galaswap-operation-${o.v4()}-${Date.now()}-${e}`}function Cu(e,t=3e4){return c.create({baseURL:e,timeout:t,headers:{"Content-Type":"application/json"}})}const Du=new Set(["accesstoken","refreshtoken","token","password","privatekey","secret","apikey","api_key","rawkey","authorization","x-api-key","bearer","streamadminapikey","userapikey","signature","signedpayload"]);function Ru(e,t=0){if(t>5)return"[...]";if(null==e)return e;if(Array.isArray(e))return e.map(e=>Ru(e,t+1));if(e instanceof Map){const n={};for(const[r,s]of e.entries()){const e=String(r);n[e]=Du.has(e.toLowerCase())?"[REDACTED]":Ru(s,t+1)}return n}if("object"==typeof e){const n={};for(const[r,s]of Object.entries(e))n[r]=Du.has(r.toLowerCase())?"[REDACTED]":Ru(s,t+1);return n}return e}class Ou{constructor(e,t={},n={signRequests:!0}){this.auth=e,this.signRequests=n.signRequests,this.session=n.session,this.debug=t.debug??!1,this.logger=new Vt({debug:this.debug,context:"HttpClient"});const r=t.baseUrl??jo("stage").launchpadBaseUrl,s=t.timeout??6e4;this.axios=Cu(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 $o(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]":Ru(e.data);this.logger.debug("Request:",{method:e.method,url:e.url?.split("?")[0],baseURL:this.axios.defaults.baseURL,params:Ru(r.params),data:s,isFormData:e.data instanceof FormData,contentType:r.headers?.["Content-Type"]??"not set"});const o=await this.sendWithSession(e,r,t,n),i=function(e){const t={};if(null==e||"object"!=typeof e)return t;for(const[n,r]of Object.entries(e))"string"==typeof r?t[n.toLowerCase()]=r:"number"!=typeof r&&"boolean"!=typeof r||(t[n.toLowerCase()]=String(r));return t}(o.headers);return this.logger.debug("Response:",{status:o.status,data:Ru(o.data),transactionId:i["x-transaction-id"],blockNumber:i["x-block-number"]}),{data:o.data,headers:i,status:o.status}},`HTTP ${e.method} ${e.url}`,this.logger)}toAxiosConfig(e,t){const n=null===t?e.headers:{...e.headers,Authorization:`Bearer ${t}`},r={method:e.method,url:e.url,data:e.data,...void 0!==e.params&&{params:Lc(e.params)},...void 0!==n&&{headers:{...n}},...void 0!==e.timeout&&{timeout:e.timeout},...void 0!==e.signal&&{signal:e.signal}};if(e.data instanceof FormData){const e=new c.AxiosHeaders(n);e.set("Content-Type",void 0),r.headers=e,this.logger.debug("FormData detected - clearing the JSON Content-Type default for the multipart upload")}return r}async sendWithSession(e,t,n,r){try{return await this.axios.request(t)}catch(t){if(!n||void 0===this.session||!function(e){if("object"!=typeof e||null===e||!("response"in e))return!1;const t=e.response;return"object"==typeof t&&null!==t&&"status"in t&&401===t.status}(t))throw t;const s=await this.session.onUnauthorized(r);if(null===s)throw t;return this.logger.debug("Retrying once with the refreshed session token"),await this.axios.request(this.toAxiosConfig(e,s))}}async get(e,t,n){return this.request({method:"GET",url:e,...t&&{params:t},...n&&{headers:n}})}async post(e,t,n){return this.request({method:"POST",url:e,data:t,...n&&{headers:n}})}async postWithMeta(e,t,n){return this.requestWithMeta({method:"POST",url:e,data:t,...n&&{headers:n}})}async put(e,t,n){return this.request({method:"PUT",url:e,data:t,...n&&{headers:n}})}async delete(e,t,n){return this.request({method:"DELETE",url:e,...t&&{params:t},...n&&{headers:n}})}async patch(e,t,n){return this.request({method:"PATCH",url:e,data:t,...n&&{headers:n}})}getAddress(){return this.auth.getAddress()}getEthereumAddress(){return this.auth.getEthereumAddress()}async signMessage(e){return(await this.auth.signMessage(e)).signature}async signTypedData(e,t,n){return await this.auth.signTypedData(e,t,n)}async signCustomMessage(e){return $o(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 xu extends Error{constructor(e,t){super(e),this.cause=t,this.name="WebSocketError"}}class Mu 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 Lu(e,t){if(xn(e))throw new xu(`Invalid WebSocket response received for transaction ${t}: response is null or undefined`);if("object"!=typeof e)throw new xu(`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 xu(`Invalid WebSocket response received for transaction ${t}: missing status field`)}function Uu(e,t,n,r){Lu(e,t);const s=e,o=s.data??{};if(!function(e){if(xn(e)||"object"!=typeof e)return!1;const t=e;return!(void 0!==t.inputQuantity&&"string"!=typeof t.inputQuantity||void 0!==t.outputQuantity&&"string"!=typeof t.outputQuantity||void 0!==t.totalFees&&"string"!=typeof t.totalFees||void 0!==t.vaultAddress&&"string"!=typeof t.vaultAddress)}(o))throw new xu(`Invalid trade data received for transaction ${t}`);const i={transactionId:t,type:n,method:"native"===r.type?"native":"exact",inputAmount:o.inputQuantity??r.amount,outputAmount:o.outputQuantity??r.expectedAmount??"0",totalFees:o.totalFees??"0",tokenName:r.tokenName,vaultAddress:o.vaultAddress??"",timestamp:Date.now()};return void 0!==s.blockHash&&(i.blockHash=s.blockHash),void 0!==s.gasUsed&&(i.gasUsed=s.gasUsed),void 0!==r.slippageToleranceFactor&&(i.slippageTolerance=r.slippageToleranceFactor),i}function Fu(e){return void 0!==e&&r.isPrivateKeyProvider(e)?new t.Wallet(e.exportPrivateKey()):void 0}const Pu={MUSIC:"$MUSIC",GMUSIC:"$GMUSIC"};function Bu(e){if(void 0===e||!("walletAddress"in e))return;const t=e.walletAddress;return"string"==typeof t&&""!==t?t:void 0}const Gu=/^(?:eth\||0x)([0-9a-fA-F]{40})$/;function $u(e,t,n){if(void 0===e||void 0===t)return;const r=Gu.exec(e)?.[1],s=Gu.exec(t)?.[1];if(void 0!==r&&void 0!==s&&r.toLowerCase()!==s.toLowerCase())throw yt(`${n} ${t} is not the identity of the configured signing key (${e}); writes would be signed as the key, not as ${n}.`,n)}class Ku{constructor(e){let t,n;this.walletGeneration=0,e.walletProvider?(t=e.walletProvider,n=Fu(e.walletProvider)):e.wallet&&(n=e.wallet,t=r.PrivateKeyProvider.fromWallet(e.wallet)),this.wallet=n;const s=e.env??"prod",o=jo(s);this.environment=s,this.config={baseUrl:e.launchpadBaseUrl??o.launchpadBaseUrl,gatewayBaseUrl:o.gatewayBaseUrl,bundleBaseUrl:o.bundleBaseUrl,webSocketUrl:o.webSocketUrl,dexApiBaseUrl:o.dexApiBaseUrl,dexBackendBaseUrl:o.dexBackendBaseUrl,launchpadFrontendUrl:o.launchpadFrontendUrl,timeout:3e4,debug:!1,...e};const i=e.signer??(void 0!==n?new Qi(n.privateKey):void 0),a=void 0!==n?`eth|${n.address.slice(2)}`:Bu(i),c=void 0===e.walletAddress?void 0:Zt(e.walletAddress,"walletAddress"),l=void 0===e.galaChainAddress?void 0:Zt(e.galaChainAddress,"galaChainAddress");$u(a,c,"walletAddress"),$u(a,l,"galaChainAddress");const d=c??l??(void 0!==n?`eth|${n.address.slice(2)}`:Bu(i)),u=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."))},h=d??"";this.tokenWriter=void 0===n&&void 0!==e.signer&&void 0!==d?{signer:e.signer,walletAddress:d}:void 0;const g=new nu({bundleBaseUrl:this.config.bundleBaseUrl,launchpadBaseUrl:this.config.baseUrl,signer:u,walletAddress:h,...void 0!==e.httpRequestor&&{httpRequestor:e.httpRequestor},bundleSocketFactory:e.bundleSocketFactory}),p=mu({getTradeQuote:e=>this.tradingQuotesService.getTradeQuote(e),findTokenNameByVault:(e,t)=>this.findTokenNameByVault(e,t),defaultFeeSlippageFactor:()=>this.maxAcceptableReverseBondingCurveFeeSlippageFactor});this.sellFeeCeiling=p,this.launchpad=new _u({transport:g,walletAddress:h,sellFeeCeiling:p}),this.logger=new Vt({debug:this.config.debug??!1,context:"LaunchpadSDK"}),this.validateConfiguration(),this.slippageToleranceFactor=void 0===e.slippageToleranceFactor?Ku.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR:this.parseSlippageToleranceFactor(e.slippageToleranceFactor),this.maxAcceptableReverseBondingCurveFeeSlippageFactor=void 0===e.maxAcceptableReverseBondingCurveFeeSlippageFactor?Ku.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR:this.parseFeeSlippageFactor(e.maxAcceptableReverseBondingCurveFeeSlippageFactor),this.calculateAmountMode=e.calculateAmountMode??Ku.DEFAULT_CALCULATE_AMOUNT_MODE,this.galaChainAddressOverride=l,this.signerWalletAddress=c??(void 0===n?d: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 yt("session must provide accessToken() and onUnauthorized()","session");if(void 0!==e.accessToken&&""!==e.accessToken)throw yt("Pass either session or accessToken, not both: the session owns the token.","accessToken")}if(this.jwtAuth=void 0===m?new Bo:new Go,void 0!==e.accessToken&&""!==e.accessToken){const t=e.accessTokenExpiresIn??86400;this.jwtAuth.setToken(e.accessToken,t)}this.http=new Ou(this.auth,this.config,{signRequests:!0,session:m}),this.sessionAuth=new Ho(this.http,this.auth,this.jwtAuth,e.debug??!1,m);const f={signRequests:!1};this.galaChainHttp=new Ou(this.auth,{...this.config,baseUrl:this.config.gatewayBaseUrl},f),this.bundleHttp=new Ou(this.auth,{...this.config,baseUrl:this.config.bundleBaseUrl},f),this.dexApiHttp=new Ou(this.auth,{...this.config,baseUrl:this.config.dexApiBaseUrl},f),this.dexBackendHttp=new Ou(this.auth,{...this.config,baseUrl:this.config.dexBackendBaseUrl},f),this.galaChainPublicAxios=Cu(this.config.gatewayBaseUrl,this.config.timeout??3e4),this.cache=new Yn(e.debug??!1),this.launchpadService=new rl(this.http,this.jwtAuth),this.tokenResolverService=new qd(this.launchpadService.poolService),this.launchpadAPI=new Mo(this.http,this.logger,this.bundleHttp,this.calculateAmountMode,this.launchpad),this.galaChainService=new Ic(this.galaChainHttp,n,this.tokenResolverService,e.debug??!1,this.galaChainPublicAxios,this.tokenWriter),this.priceService=new Ma(this.dexBackendHttp,this.cache,e=>this.galaChainService.fetchTokenDetails(e),e.debug??!1),this.bundleService=this.createBundleService(),this.websocketService=new Jd({url:this.config.webSocketUrl},this.config.debug),this.nftCollectionService=new Rl(this.galaChainHttp),this.tradingQuotesService=new zd(this.http,e.debug??!1)}createOverrideSdk(e){if(!Rn(e))throw yt("Invalid privateKey: must be a non-empty string","privateKey");if(!e.match(/^0x[a-fA-F0-9]{64}$/))throw yt('Invalid privateKey format: must be "0x" followed by 64 hexadecimal characters',"privateKey");const n=new t.Wallet(e),r={...this.config,wallet:n};return new Ku(r)}getAddress(){return void 0!==this.galaChainAddressOverride&&""!==this.galaChainAddressOverride?this.galaChainAddressOverride:void 0!==this.signerWalletAddress&&""!==this.signerWalletAddress?this.signerWalletAddress:(this.validateWallet(),this.auth.getAddress())}getEthereumAddress(){return this.validateWallet(),this.wallet.address}validateWallet(){if(!this.wallet)throw Tt("wallet","Wallet");return this.wallet}assertTokenWriter(){if(void 0===this.wallet&&void 0===this.tokenWriter)throw Tt("wallet","Wallet")}setWallet(e){if(null==e||"object"!=typeof e||!("address"in e))throw new rt("Invalid wallet: must be an ethers Wallet instance, received "+typeof e,"wallet","INVALID_WALLET");this.wallet=e,this.auth.setWallet(e),this.onWalletChanged()}onWalletChanged(){this.walletGeneration+=1,this.galaChainAddressOverride=void 0,this.signerWalletAddress=void 0,this.rebuildTokenWrites(),this.bundleService=this.createBundleService(),this._bridgeService=void 0,this._wrapService=void 0,this._galaConnectClient=void 0,this._streamWebSocketService?.deauthenticate()}createBundleService(){return new ma(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 Ic(this.galaChainHttp,this.wallet,this.tokenResolverService,this.config.debug??!1,this.galaChainPublicAxios)}setWalletProvider(e){this.auth.setWalletProvider(e),this.wallet=e?Fu(e):void 0,this.onWalletChanged()}getWallet(){return this.wallet}get events(){return this.getEventsBatcherService()}getWalletProvider(){return this.auth.getWalletProvider()}hasWallet(){return this.auth.hasWallet()}getConfig(){const{wallet:e,walletProvider:t,signer:n,httpRequestor:r,streamAdminApiKey:s,userApiKey:o,accessToken:i,headers:a,...c}=this.config;return{...c,...void 0!==s&&{streamAdminApiKey:"[REDACTED]"},...void 0!==o&&{userApiKey:"[REDACTED]"},...void 0!==i&&{accessToken:"[REDACTED]"},...void 0!==a&&{headers:Object.fromEntries(Object.keys(a).map(e=>[e,"[REDACTED]"]))},environment:this.environment,slippageToleranceFactor:this.slippageToleranceFactor,maxAcceptableReverseBondingCurveFeeSlippageFactor:this.maxAcceptableReverseBondingCurveFeeSlippageFactor,calculateAmountMode:this.calculateAmountMode,gasFee:$t.GAS_FEE}}getVersion(){return Xo}getUrlByTokenName(e){const t=this.config.launchpadFrontendUrl;if(void 0===t||""===t)throw yt("launchpadFrontendUrl not configured in SDK","launchpadFrontendUrl");return`${t.replace(/\/$/,"")}/buy-sell/${e}`}async fetchPools(e){const t=await this.launchpadService.fetchPools(e??{});return await this.warmCacheFromPools(t.items),t}async fetchAllPools(e){const t=await this.launchpadService.fetchAllPools(e);return await this.warmCacheFromPools(t.items),t}async fetchTokenDistribution(e){return this.launchpadService.fetchTokenDistribution(e)}async getTopHolders(e,t=10){const n=await this.fetchTokenDistribution(e),r=Math.min(t,100);return n.holders.slice(0,r).map((e,t)=>({...e,rank:t+1}))}async getHolderCount(e){const t=await this.fetchTokenDistribution(e);return{count:t.totalHolders,totalBalance:t.totalSupply}}async getHolderRank(e,t){const n=en(t,"userAddress"),r=await this.fetchTokenDistribution(e),s=r.holders.findIndex(e=>e.address.toLowerCase()===n);if(-1===s)return null;const o=r.holders[s];return void 0===o?null:{rank:s+1,balance:o.balance,holderCount:r.totalHolders}}async getHoldersByBalance(e,t){const n=await this.fetchTokenDistribution(e),r=t?.minBalance??0,s=t?.maxBalance??1/0,o=Math.min(t?.limit??100,1e3),i=new Map;return n.holders.forEach((e,t)=>{i.set(e.address,t+1)}),n.holders.filter(e=>{const t=parseFloat(e.balance);return t>=r&&t<=s}).map(e=>({...e,rank:i.get(e.address)??0})).slice(0,o)}async getHolderHistory(e,t,n=20){return this.getTrades({tokenName:e,userAddress:t,pageSize:Math.min(n,100)})}async fetchUserHolderContext(e,t){return this.launchpadService.fetchUserHolderContext(e,t)}async fetchTokenPrice(e){const t="object"==typeof e&&null!==e?e:{};if(void 0!==t.tokenId)throw new rt("fetchTokenPrice prices a launchpad token by tokenName; a token by class key is priced by gswap-sdk (gSwap.market.getPrice)","tokenId",nt.INVALID_PARAMETERS);const n=t.tokenName;return this.priceService.fetchLaunchpadTokenSpotPrice("string"==typeof n?n:"",e=>this.launchpadAPI.calculateBuyAmount(e),e=>this.fetchPoolDetails(e))}async fetchTokenDetails(e){return this.galaChainService.fetchTokenDetails(e)}async fetchLaunchTokenFee(){return this.tradingQuotesService.fetchLaunchpadFee()}async fetchTokenClassesWithSupply(e){return this.galaChainService.fetchTokenClassesWithSupply(e)}async fetchPoolDetails(e){const t=await this.launchpadAPI.fetchPoolDetails(e),n=await this.launchpadAPI.fetchPoolDetailsForCalculation(e);return t.currentSupply=n.currentSupply,t.reverseBondingCurveMaxFeeFactor=n.reverseBondingCurveMaxFeeFactor,t.reverseBondingCurveMinFeeFactor=n.reverseBondingCurveMinFeeFactor,t.reverseBondingCurveNetFeeFactor=n.reverseBondingCurveNetFeeFactor,t.tokenName=e,t}async fetchPoolDetailsForCalculation(e){return this.launchpadAPI.fetchPoolDetailsForCalculation(e)}async isTokenGraduated(e){return(await this.fetchPoolDetails(e)).isGraduated}async fetchVolumeData(e){return this.launchpadService.fetchVolumeData(e)}async fetchTrades(e){return this.launchpadService.fetchTrades(e)}async fetchGalaBalance(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return An}),n=t(e)??this.getAddress();return this.galaChainService.fetchGalaBalance({owner:n,collection:"GALA",category:"Unit",additionalKey:"none",type:"none"})}loadCoreBridge(){const e=this.config.bridge;return void 0===e?Promise.reject(yt("The bridge and wrap methods need gala-core-sdk's ./bridge: create the SDK with `bridge: () => import('@gala-chain/gala-core-sdk/bridge')` (it needs the optional peers ethers, @solana/web3.js and @solana/spl-token).","bridge")):(this.coreBridgeLoad??(this.coreBridgeLoad=Promise.resolve().then(()=>e()).then(e=>{if("object"!=typeof(t=e)||null===t||"function"!=typeof t.BridgeService)throw new Error("the module has no BridgeService export");var t;return e}).catch(e=>{throw this.coreBridgeLoad=void 0,yt(`The bridge and wrap methods use @gala-chain/gala-core-sdk/bridge, which needs its optional peers ethers, @solana/web3.js and @solana/spl-token installed: ${ut(e)}`,"bridge")})),this.coreBridgeLoad)}async coreBridge(){const e=this.walletGeneration,t=await this.loadCoreBridge();if(e!==this.walletGeneration)throw yt("The wallet changed while this bridge or wrap call was starting; nothing was sent. Call it again.","wallet");return t}getBridgeService(e){if(!this._bridgeService){const t=this.getWallet();if(!t)throw new Error("Bridge operations require a wallet. Configure SDK with a wallet first.");const n=globalThis.process?.env.SOLANA_PRIVATE_KEY;this._bridgeService=new e.BridgeService({galaConnectBaseUrl:this.config.dexApiBaseUrl,galaChainWalletAddress:this.getAddress(),ethereumPrivateKey:t.privateKey,...void 0!==n&&""!==n?{solanaPrivateKey:n}:{},bridgeableTokenService:this.getBridgeableTokenService(e),environment:this.environment,...void 0!==this.config.ethereumRpcUrl&&""!==this.config.ethereumRpcUrl?{ethereumRpcUrl:this.config.ethereumRpcUrl}:{},...void 0!==this.config.solanaRpcUrl&&""!==this.config.solanaRpcUrl?{solanaRpcUrl:this.config.solanaRpcUrl}:{}})}return this._bridgeService}getBridgeableTokenService(e){return this._bridgeableTokenService??(this._bridgeableTokenService=new e.BridgeableTokenService(this.dexApiHttp)),this._bridgeableTokenService}getWrappableTokenService(e){return this._wrappableTokenService??(this._wrappableTokenService=new e.WrappableTokenService(this.dexApiHttp)),this._wrappableTokenService}getGalaConnectClient(e){if(void 0===this._galaConnectClient){const t=this.getAddress();if(void 0===this.config.dexApiBaseUrl||""===this.config.dexApiBaseUrl)throw new Error("DEX API base URL is required for GalaConnectClient. Check SDK configuration.");this._galaConnectClient=new e.GalaConnectClient({baseUrl:this.config.dexApiBaseUrl,...void 0!==this.config.gatewayBaseUrl&&""!==this.config.gatewayBaseUrl?{galachainBaseUrl:this.config.gatewayBaseUrl}:{},walletAddress:t})}return this._galaConnectClient}getWrapService(e){if(!this._wrapService){const t=this.getWallet();this._wrapService=new e.WrapService({galaConnectClient:this.getGalaConnectClient(e),wrappableTokenService:this.getWrappableTokenService(e),...void 0!==t&&{walletAddress:this.getAddress(),signer:new Qi(t.privateKey)}})}return this._wrapService}getStreamingService(){return this._streamingService??(this._streamingService=new gd(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._streamingService}getStreamChatService(){return this._streamChatService??(this._streamChatService=new Jl(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._streamChatService}getBanService(){return this._banService??(this._banService=new Di(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._banService}getTokenBanService(){return this._tokenBanService??(this._tokenBanService=new jd(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._tokenBanService}getAIModerationService(){return this._aiModerationService??(this._aiModerationService=new li(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._aiModerationService}getWeeklyChallengeService(){return this._weeklyChallengeService??(this._weeklyChallengeService=new Zd(this.http,this.config.debug??!1)),this._weeklyChallengeService}getOEmbedService(){return this._oembedService??(this._oembedService=new xl(this.http,this.config.debug??!1)),this._oembedService}getPlatformStatsService(){return this._platformStatsService??(this._platformStatsService=new Xl(this.http,this.config.debug??!1)),this._platformStatsService}getHealthService(){return this._healthService??(this._healthService=new Cc(this.http,this.config.debug??!1)),this._healthService}getEventsQueryService(){return this._eventsQueryService??(this._eventsQueryService=new Wa(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._eventsQueryService}getNotificationService(){return this._notificationService??(this._notificationService=new Ol(this.http,this.config.debug??!1,this.jwtAuth)),this._notificationService}getClientConfigService(){return this._clientConfigService??(this._clientConfigService=new fa(this.http,this.config.debug??!1)),this._clientConfigService}getApiKeyService(){return this._apiKeyService??(this._apiKeyService=new vi(this.http,this.jwtAuth,this.config.debug??!1)),this._apiKeyService}getModeratorService(){return this._moderatorService??(this._moderatorService=new Nl(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._moderatorService}getFlagService(){return this._flagService??(this._flagService=new Ca(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._flagService}getOverseerService(){return this._overseerService??(this._overseerService=new ql(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._overseerService}getWebSocketAdminService(){return this._websocketAdminService??(this._websocketAdminService=new Yd(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._websocketAdminService}getContentReactionService(){return this._contentReactionService??(this._contentReactionService=new Ra(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():Zt(e,"address")}getMessagesService(){return this._messagesService??(this._messagesService=new dl(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._messagesService}getRestrictedNamesService(){return this._restrictedNamesService??(this._restrictedNamesService=new Ql(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.userApiKey)),this._restrictedNamesService}getPlatformConfigService(){return this._platformConfigService??(this._platformConfigService=new Yl(this.http,this.jwtAuth,this.config.debug??!1)),this._platformConfigService}getEventsBatcherService(){return this._eventsBatcherService??(this._eventsBatcherService=new Ua(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 Bd({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&&rn(t.userAddress,n))&&((void 0===t.tokenName||t.tokenName===r)&&!!(void 0===t.reason||null!==s&&s.includes(t.reason)))),r=this.onUserBanned(t=>{const r=t.userAddress??null,s=t.reason??null;n("BANNED",r,t.tokenName,s)&&e({actionType:"BANNED",userAddress:r,tokenName:t.tokenName,reason:s,...void 0!==t.expiresAt&&{expiresAt:t.expiresAt}})}),s=this.onUserUnbanned(t=>{const r=t.userAddress??null;n("UNBANNED",r,t.tokenName,null)&&e({actionType:"UNBANNED",userAddress:r,tokenName:t.tokenName,reason:null})}),o=this.onBanEnforcement(t=>{const r=t.reason??null;n("ENFORCEMENT",null,t.tokenName,r)&&e({actionType:"ENFORCEMENT",userAddress:null,tokenName:t.tokenName,reason:r,...void 0!==t.expiresAt&&{expiresAt:t.expiresAt}})});return()=>{r(),s(),o()}}watchTokenRoomEvent(e,t,n,r){const s=r.tokenName;if(void 0===s||""===s)throw new Error(`${e} requires a tokenName filter - these are per-token stream events with no way to watch every token at once.`);return t(s,n)}watchCommentCreated(e,t={}){return this.watchTokenRoomEvent("watchCommentCreated",(e,t)=>this.getStreamWebSocketService().subscribeCommentCreated(e,t),n=>{(void 0===t.authorAddress||rn(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||rn(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&&!rn(t.moderatorAddress,n)),r=this.watchModeratorAdded(t=>{n("ADDED",t.userAddress)&&e({actionType:"ADDED",tokenName:t.tokenName,moderatorAddress:t.userAddress,role:t.role})},t),s=this.watchTokenRoomEvent("watchModeratorRemoved",(e,t)=>this.getStreamWebSocketService().subscribeModeratorRemoved(e,t),t=>{n("REMOVED",t.userAddress)&&e({actionType:"REMOVED",tokenName:t.tokenName,moderatorAddress:t.userAddress})},t),o=this.watchTokenRoomEvent("watchModeratorRoleUpdated",(e,t)=>this.getStreamWebSocketService().subscribeModeratorRoleUpdated(e,t),t=>{n("ROLE_UPDATED",t.userAddress)&&e({actionType:"ROLE_UPDATED",tokenName:t.tokenName,moderatorAddress:t.userAddress,oldRole:t.oldRole,newRole:t.newRole})},t);return()=>{r(),s(),o()}}watchPoolUpdated(e,t={}){const n=e=>void 0===t.updateType||t.updateType===e,r=this.watchPoolMetadataUpdated(t=>{n("METADATA")&&e({updateType:"METADATA",tokenName:t.tokenName,details:t})},t),s=this.watchTokenRoomEvent("watchPoolSocialLinksUpdated",(e,t)=>this.getStreamWebSocketService().subscribePoolSocialLinksUpdated(e,t),t=>{n("SOCIAL_LINKS")&&e({updateType:"SOCIAL_LINKS",tokenName:t.tokenName,details:t})},t),o=this.watchTokenRoomEvent("watchPoolBadgeAssigned",(e,t)=>this.getStreamWebSocketService().subscribePoolBadgeAssigned(e,t),t=>{n("BADGE_ASSIGNED")&&e({updateType:"BADGE_ASSIGNED",tokenName:t.tokenName,details:t})},t);return()=>{r(),s(),o()}}watchTokenBanChanged(e,t={}){const n=e=>void 0===t.banStatus||t.banStatus===e,r=this.watchTokenBanned(t=>{n("BANNED")&&e({banStatus:"BANNED",tokenName:t.tokenName,reason:t.reason})},t),s=this.watchTokenRoomEvent("watchTokenUnbanned",(e,t)=>this.getStreamWebSocketService().subscribeTokenUnbanned(e,t),t=>{n("UNBANNED")&&e({banStatus:"UNBANNED",tokenName:t.tokenName})},t);return()=>{r(),s()}}onContentFlagged(e){return this.getStreamWebSocketService().subscribeEvent("CONTENT_FLAGGED",e)}onFlagResolved(e){return this.getStreamWebSocketService().subscribeEvent("FLAG_RESOLVED",e)}onStreamChatMessage(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_CHAT_MESSAGE",e)}onStreamChatUpdated(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_CHAT_UPDATED",e)}onStreamChatDeleted(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_CHAT_DELETED",e)}onStreamChatPinned(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_CHAT_PINNED",e)}onStreamChatUnpinned(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_CHAT_UNPINNED",e)}onChatStatusChanged(e){return this.getStreamWebSocketService().subscribeEvent("CHAT_STATUS_CHANGED",e)}onViewerCountChanged(e){return this.getStreamWebSocketService().subscribeEvent("VIEWER_COUNT",e)}onRecordingStatusChanged(e){return this.getStreamWebSocketService().subscribeEvent("RECORDING_STATUS",e)}onSimulcastStatusChanged(e){return this.getStreamWebSocketService().subscribeEvent("SIMULCAST_STATUS",e)}onDownloadReady(e){return this.getStreamWebSocketService().subscribeEvent("DOWNLOAD_READY",e)}onRecordingsCountUpdated(e){return this.getStreamWebSocketService().subscribeEvent("RECORDINGS_COUNT_UPDATED",e)}onUserTyping(e){return this.getStreamWebSocketService().subscribeEvent("USER_TYPING",e)}onStreamReaction(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_REACTION",e)}onContentReactionAdded(e){return this.getStreamWebSocketService().subscribeEvent("CONTENT_REACTION_ADDED",e)}onContentReactionRemoved(e){return this.getStreamWebSocketService().subscribeEvent("CONTENT_REACTION_REMOVED",e)}onStreamCountdownUpdated(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_COUNTDOWN_UPDATED",e)}onStreamLanguageUpdated(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_LANGUAGE_UPDATED",e)}onStreamControlStatusChanged(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_CONTROL_STATUS_CHANGED",e)}onConnection(e){return this.getStreamWebSocketService().subscribeEvent("connection",e)}onAuthenticated(e){return this.getStreamWebSocketService().subscribeEvent("authenticated",e)}onTokenSubscribed(e){return this.getStreamWebSocketService().subscribeEvent("token_subscribed",e)}onTokenUnsubscribed(e){return this.getStreamWebSocketService().subscribeEvent("token_unsubscribed",e)}onRoomSubscribed(e){return this.getStreamWebSocketService().subscribeEvent("room_subscribed",e)}onRoomLeft(e){return this.getStreamWebSocketService().subscribeEvent("room_left",e)}onEngagementStatsUpdated(e){return this.getStreamWebSocketService().subscribeEvent("ENGAGEMENT_STATS_UPDATED",e)}async estimateBridgeFee(e){return this.getBridgeService(await this.coreBridge()).estimateBridgeFee(e)}async bridgeOut(e){return this.getBridgeService(await this.coreBridge()).bridgeOut(e)}async bridgeIn(e){return this.getBridgeService(await this.coreBridge()).bridgeIn(e)}async getBridgeStatus(e){return this.getBridgeService(await this.coreBridge()).getBridgeStatus(e)}async getSupportedBridgeTokens(){const e=this.getBridgeService(await this.coreBridge()),t=e.getSupportedBridgeTokens();return{tokens:t,totalCount:t.length,supportedChains:e.getSupportedBridgeChains()}}async fetchTokenBalance(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return An}),n=t(e.address);if(void 0!==e.tokenId&&""!==e.tokenId){const{normalizeToTokenInstanceKey:t}=await Promise.resolve().then(function(){return ha}),r=t(e.tokenId),{collection:s,category:o,type:i,additionalKey:a}=r;return this.galaChainService.fetchTokenBalance({owner:n,collection:s,category:o,additionalKey:a,type:i},e.withExpired??!1)}if(void 0!==e.tokenName&&""!==e.tokenName){const t=Ht(e.tokenName),r=Pu[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:ra(r)}}throw Tt("tokenId or tokenName","Either tokenId or tokenName")}async fetchLockedBalance(e){const t=await this.fetchTokenBalance(e);if(!t)return null;const n="lockedHolds"in t||"lockedQuantity"in t;return{tokenId:t.tokenId,lockedQuantity:n?t.lockedQuantity??"0":"0",lockedHolds:n?t.lockedHolds??[]:[]}}async fetchAvailableBalance(e){const t=await this.fetchTokenBalance(e);if(!t)return null;const n="availableQuantity"in t;return{tokenId:t.tokenId,availableQuantity:n?t.availableQuantity??String(t.quantity):String(t.quantity),totalQuantity:String(t.quantity)}}async calculateBuyAmount(e){return this.launchpadAPI.calculateBuyAmount(e)}async calculateSellAmount(e){return this.launchpadAPI.calculateSellAmount(e)}async calculateBuyAmountLocal(e){return this.launchpadAPI.calculateBuyAmountLocal(e)}async calculateSellAmountLocal(e){return this.launchpadAPI.calculateSellAmountLocal(e)}async calculateBuyAmountExternal(e){return this.launchpadAPI.calculateBuyAmountExternal(e)}async calculateSellAmountExternal(e){return this.launchpadAPI.calculateSellAmountExternal(e)}async calculateBuyAmountForGraduation(e){return this.launchpadAPI.calculateBuyAmountForGraduation(e)}async graduateToken(e){const{tokenName:t,slippageToleranceFactor:n,maxAcceptableReverseBondingCurveFeeSlippageFactor:r,privateKey:s,calculateAmountMode:o,currentSupply:i}=e;let a=t;void 0===o&&void 0===i||(a={tokenName:t,...void 0!==o&&{calculateAmountMode:o},...void 0!==i&&{currentSupply:i}});const c=await this.calculateBuyAmountForGraduation(a),l={tokenName:t,amount:c.remainingTokens,type:"exact",expectedAmount:c.amount,maxAcceptableReverseBondingCurveFee:c.reverseBondingCurveFee,slippageToleranceFactor:this.slippageToleranceFactor};return void 0!==n&&(l.slippageToleranceFactor=n),void 0!==r&&(l.maxAcceptableReverseBondingCurveFeeSlippageFactor=r),void 0!==s&&(l.privateKey=s),await this.buy(l)}async calculateInitialBuyAmount(e){const t={nativeTokenQuantity:e};return this.launchpadAPI.calculateInitialBuyAmount(t)}async buy(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...r}=e;return t.buy(r)}this.validateWallet(),await this.ensureWebSocketConnection();const t=(await this.bundleService.buyToken(e)).data,n=t?.transactionId;if(void 0===n||""===n)throw bt("No transaction ID returned from buy operation");return this.waitForConfirmation(n,t=>Uu(t,n,"buy",e))}async sell(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...r}=e;return t.sell(r)}this.validateWallet(),await this.ensureWebSocketConnection();const t=(await this.bundleService.sellToken(e)).data,n=t?.transactionId;if(void 0===n||""===n)throw bt("No transaction ID returned from sell operation");return this.waitForConfirmation(n,t=>Uu(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=>{Lu(n,t);const r=n.data??{};if(!function(e){if(xn(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 xu(`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 An}),n=t(e)??this.getAddress();return this.launchpadService.fetchProfile(n)}async fetchReferralUrl(){this.validateWallet();const e=this.getAddress();return await this.dexApiHttp.get(d,void 0,{"x-wallet-address":e})}async fetchReferrals(e){const t=this.resolveReferralAddress(e?.address),n=e?.page??1,r=e?.limit??10,s={pageNumber:n,limit:r,sortBy:e?.sortBy??"joined",sortDir:e?.sortDir??"desc"},o=await this.dexApiHttp.get(u,s,{"x-wallet-address":t});if(!Array.isArray(o))throw new at("Unexpected API response: expected array, got "+typeof o);return{referrals:o,page:n,limit:r,hasMore:o.length===r}}async fetchAllReferrals(e){const t=await async function(e,t={}){const{maxPages:n=1e4,logger:r,pageSize:s=20,concurrency:o=1,startPage:i=1}=t,a=[];let c=i;const l=i+n-1;let d=!0,u=0;if(o<=1)for(;d&&c<=l;){r&&r.debug(`Auto-pagination: fetching page ${c} with limit ${s}`);const t=await e(c,s);if(null==t||!Array.isArray(t.items)){r&&r.warn("Auto-pagination: received invalid result structure, stopping");break}if(a.push(...t.items),u=t.total,r&&r.debug(`Auto-pagination: page ${c} returned ${t.items.length} items, hasNext: ${String(t.hasNext)}`),0===t.items.length){r&&r.debug(`Auto-pagination: no items returned on page ${c}, exiting loop`);break}d=t.hasNext,c++}else for(r&&r.debug(`Auto-pagination: using concurrent mode with concurrency=${o}`);d&&c<=l;){const t=[];for(let e=0;e<o&&c+e<=l;e++)t.push(c+e);r&&r.debug(`Auto-pagination: fetching pages ${t.join(", ")} concurrently`);const n=t.map(t=>e(t,s).catch(e=>{const n=e,o=n.statusCode??n.response?.status??n.originalError?.response?.status??n.status??n.launchpadError?.statusCode;if(400===o||404===o)return r&&r.debug(`Auto-pagination: page ${t} returned ${o} (end of pagination)`,{statusCode:o}),{items:[],total:0,totalPages:0,page:t,limit:s,hasNext:!1,hasPrevious:!1};throw e})),i=await Promise.all(n);for(const e of i){if(null==e||!Array.isArray(e.items)){r&&r.warn("Auto-pagination: received invalid result structure in batch, stopping"),d=!1;break}if(0===e.items.length){r&&r.debug("Auto-pagination: empty page in batch, reached end of results"),d=!1;break}if(a.push(...e.items),u=e.total,!e.hasNext){d=!1;break}}c+=t.length,r&&r.debug(`Auto-pagination: batch complete, total items so far: ${a.length}`)}return c>l&&r&&r.warn(`Auto-pagination: exceeded maxPages limit of ${n} (maxPage=${l}), stopping iteration`),r&&r.debug(`Auto-pagination: completed with total items: ${a.length}, total count: ${u}`),{items:a,total:u}}((t,n)=>this.fetchReferrals({...e,page:t,limit:n}).then(e=>({items:e.referrals,page:e.page,limit:e.limit,total:0,totalPages:0,hasNext:e.hasMore,hasPrevious:e.page>1})),{maxPages:100,pageSize:100,logger:this.logger});return{referrals:t.items,total:t.items.length}}async fetchReferralsSummary(e){const t=this.resolveReferralAddress(e?.address),n=await this.dexApiHttp.get(h,void 0,{"x-wallet-address":t});if(void 0===n||"number"!=typeof n.referralCount||void 0===n.rewardTotals)throw new at(`Unexpected API response: expected { referralCount, rewardTotals }, got ${JSON.stringify(n)}`);return n}async updateProfile(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return An}),{address:n,...r}=e,s=void 0===n?void 0:t(n),o={...r,...void 0!==s&&{address:s}};if(void 0!==o.privateKey&&""!==o.privateKey){const e=this.createOverrideSdk(o.privateKey),{privateKey:t,...n}=o;return e.updateProfile(n)}return this.launchpadService.updateProfile(o)}async uploadProfileImage(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return An}),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 An}),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 An}),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 An}),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 An}),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 An});return{...e,lockAuthority:t(e.lockAuthority)}}return e})),n={...e,tokens:t};if(void 0!==n.privateKey&&""!==n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...r}=n;return e.lockTokens(r)}return this.assertTokenWriter(),this.galaChainService.lockTokens(n)}async unlockTokens(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...r}=e;return t.unlockTokens(r)}return this.assertTokenWriter(),this.galaChainService.unlockTokens(e)}async burnTokens(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...r}=e;return t.burnTokens(r)}return this.assertTokenWriter(),this.galaChainService.burnTokens(e)}async resolveVaultAddress(e){return this.tokenResolverService.resolveTokenToVault(e)}async findTokenNameByVault(e,t){let n;for(let r=0;r<10;r+=1){const r=await this.launchpadService.poolService.fetchPools({search:t,pageSize:100,...void 0===n?{}:{cursor:n}}),s=r.items.find(t=>t.vaultAddress===e);if(void 0!==s)return s.tokenName;const o=ti(r.pageInfo,n);if(void 0===o)return;n=o}}getCacheInfo(){const e={...this.launchpadAPI.getCacheStats()};if(this._bridgeableTokenService){const t=this._bridgeableTokenService.getCacheStats();e.bridgeableTokens={ETHEREUM:t.tokensByNetwork.ETHEREUM,SOLANA:t.tokensByNetwork.SOLANA,total:t.totalTokens}}return this._wrappableTokenService&&(e.wrappableTokens=this._wrappableTokenService.getCacheStats()),e}clearCache(e){this.launchpadAPI.clearCache(e),void 0!==e&&""!==e||(void 0!==this._bridgeableTokenService&&this._bridgeableTokenService.clearCache(),void 0!==this._wrappableTokenService&&this._wrappableTokenService.clearCache())}validateConfiguration(){try{kn(this.config.timeout,1,3e5,"timeout")}catch{this.logger.warn(`Invalid timeout value: ${this.config.timeout??"undefined"}. Using default 30000ms.`),this.config.timeout=3e4}if(void 0===this.config.baseUrl||""===this.config.baseUrl)throw yt("baseUrl is required in configuration","baseUrl");if(void 0===this.config.webSocketUrl||""===this.config.webSocketUrl)throw yt("webSocketUrl is required in configuration","webSocketUrl");try{new URL(this.config.baseUrl)}catch{throw yt(`Invalid baseUrl format: ${this.config.baseUrl}`,"baseUrl")}try{new URL(this.config.webSocketUrl)}catch{throw yt(`Invalid webSocketUrl format: ${this.config.webSocketUrl}`,"webSocketUrl")}if(void 0!==this.config.gatewayBaseUrl&&""!==this.config.gatewayBaseUrl)try{new URL(this.config.gatewayBaseUrl)}catch{throw yt(`Invalid gatewayBaseUrl format: ${this.config.gatewayBaseUrl}`,"gatewayBaseUrl")}if(void 0!==this.config.bundleBaseUrl&&""!==this.config.bundleBaseUrl)try{new URL(this.config.bundleBaseUrl)}catch{throw yt(`Invalid bundleBaseUrl format: ${this.config.bundleBaseUrl}`,"bundleBaseUrl")}if(void 0!==this.config.launchpadFrontendUrl&&""!==this.config.launchpadFrontendUrl)try{new URL(this.config.launchpadFrontendUrl)}catch{throw yt(`Invalid launchpadFrontendUrl format: ${this.config.launchpadFrontendUrl}`,"launchpadFrontendUrl")}}parseSlippageToleranceFactor(e){const t=Tn("string"==typeof e||"number"==typeof e?e:String(e),Ku.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR);return t<0||t>1?(this.logger.warn(`Invalid slippage tolerance factor: ${String(e)}, using default: ${Ku.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR}`),Ku.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR):t}parseFeeSlippageFactor(e){const t=Tn("string"==typeof e||"number"==typeof e?e:String(e),Ku.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: ${Ku.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR}`),Ku.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR):t}async ensureWebSocketConnection(){this.websocketService.isConnected()||(await this.websocketService.connect(),this.logger.debug("WebSocket connection established"))}async waitForConfirmation(e,t){this.logger.debug(`Waiting for confirmation of transaction: ${e}`);try{const n=await this.websocketService.waitForTransaction(e);if(n.status!==exports.SDKTransactionStatus.COMPLETED)throw new Mu(e,n.status,n.message);let r;try{r=t(n)}catch(t){if(t instanceof xu)throw t;throw new xu(`Failed to transform WebSocket response for transaction ${e}`,dt(t)?t:new Error(ut(t)))}return this.logger.debug(`Transaction confirmed: ${e}`,r),r}catch(t){if(this.logger.error(`Transaction confirmation failed: ${e}`,t),t instanceof Mu||t instanceof xu)throw t;throw new xu(`WebSocket confirmation failed for transaction ${e}`,dt(t)?t:new Error(ut(t)))}}async warmCacheFromPools(e){if(void 0===e||!Array.isArray(e))return;const{extractMetadataFromPoolData:t,isValidPoolForCaching:n}=await Promise.resolve().then(function(){return Ch});e.forEach(e=>{if(!n(e))return;const r=t(e,this.logger);r&&this.launchpadAPI.warmCacheFromPoolData(e.tokenName,r)})}connectWebSocket(){this.websocketService.connect()}disconnectWebSocket(){this.websocketService.disconnect()}isWebSocketConnected(){return this.websocketService.isConnected()}subscribeToEvent(e,t){const n=this.websocketService.getSocket();return n?(n.on(e,t),()=>{n.off(e,t),this.logger.debug(`Unsubscribed from event: "${e}"`)}):(this.logger.warn(`⚠️ WebSocket not connected - subscribing to "${e}" without connection`),()=>{})}onLaunchpadTokenCreation(e,t){const n=1e3,r=Math.max(t?.intervalMs??3e4,n);null!=t?.intervalMs&&t.intervalMs<n&&this.logger.warn(`Poll interval ${t.intervalMs}ms is below minimum 1000ms. Using minimum interval instead.`);const s=t?.creatorAddress,o=new Map;let i=!0,a=null;let c=0;const l=async()=>{if(i){try{const t=await this.fetchPools({type:"recent",pageSize:20});c>0&&(this.logger.debug("Successfully recovered from polling errors"),c=0),t.items.forEach(t=>{o.has(t.tokenName)||((e=>{if(o.set(e,!0),o.size>1e3){const e=o.keys().next().value;void 0!==e&&o.delete(e)}})(t.tokenName),void 0!==s&&""!==s&&t.creatorAddress!==s||e(t))})}catch(e){c++;const t=ut(e);c>=5?this.logger.error(`Polling for new launchpad tokens failed ${c} consecutive times. Last error: ${t}. Continuing to retry...`):c>1?this.logger.warn(`Error polling for new launchpad tokens (attempt ${c}/5): ${t}`):this.logger.debug(`Error polling for new launchpad tokens: ${t}`)}if(i){const e=Math.min(Math.max(c-1,0),2),t=r*Math.pow(2,e);a=setTimeout(()=>{l()},t)}}};return l(),()=>{i=!1,a&&clearTimeout(a),this.logger.debug("Stopped watching for launchpad token creation")}}matchesCreatorFilter(e,t){return void 0===t||""===t||e.creatorAddress===t}subscribeToTokenCreations(e,t){if(this.logger.debug("Subscribing to token creation broadcasts"+(void 0!==t?.creatorFilter&&""!==t.creatorFilter?` (filter: ${t.creatorFilter})`:"")),null===this.websocketService||void 0===this.websocketService)throw yt("WebSocket service not initialized. Ensure websocketUrl is configured and the service is connected.","websocketService");let n=!1,r=null;const s=(n,...r)=>{try{if(r.length>0&&"object"==typeof r[0]&&null!==r[0]){const n=r[0].data;if(void 0!==n?.Data&&null!==n.Data&&"object"==typeof n.Data){const r=n.Data;if("CreateSale"===r.functionName){const n=(e,t="")=>{const n=r[e];return"string"==typeof n&&""!==n?n:t},s={tokenName:n("tokenName"),symbol:n("symbol"),creatorAddress:n("creatorAddress"),description:n("description"),image:n("image"),vaultAddress:n("vaultAddress"),tokenStringKey:n("tokenStringKey"),preBuyQuantity:n("initialBuyQuantity","0"),websiteUrl:n("websiteUrl"),telegramUrl:n("telegramUrl"),twitterUrl:n("twitterUrl"),instagramUrl:n("instagramUrl"),facebookUrl:n("facebookUrl"),redditUrl:n("redditUrl"),tiktokUrl:n("tiktokUrl"),isFinalized:!0===r.isFinalized};this.matchesCreatorFilter(s,t?.creatorFilter)&&e(s)}}}}catch(e){this.logger.warn(`Error processing token creation broadcast: ${ut(e)}`)}};let o=this.websocketService.getSocket();if(o)o.onAny(s),n=!0,this.logger.debug("Token creation broadcast listener registered");else{this.logger.debug("WebSocket not yet connected, initiating connection..."),this.websocketService.connect().catch(e=>{const n=new Error(`WebSocket connection failed: ${ut(e)}`);this.logger.warn("Failed to establish WebSocket connection:",e),t?.onError&&t.onError(n)});let e=0;const i=()=>{if(o=this.websocketService.getSocket(),!o&&e<Ku.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS)return e++,void(r=setTimeout(()=>i(),Ku.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS));if(!o&&e>=Ku.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS){const e=new Error(`WebSocket not available after ${Ku.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS*Ku.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS}ms`);return this.logger.warn("Token creation broadcast subscription timeout:",e.message),void(t?.onError&&t.onError(e))}o&&(o.onAny(s),n=!0,this.logger.debug("Token creation broadcast listener registered"))};i()}return()=>{try{if(null!==r&&(clearTimeout(r),r=null,this.logger.debug("Cleared token creation broadcast polling timeout")),!n)return void this.logger.debug("Cleanup called before listener registration - no action needed");const e=this.websocketService.getSocket();e&&(e.offAny(s),n=!1,this.logger.debug("Stopped listening to token creation broadcasts"))}catch(e){this.logger.warn("Error removing token creation listener:",e)}}}getNftCollectionClaimFee(){return this.nftCollectionService.getCollectionClaimFee()}getNftTokenClassCreateFee(){return this.nftCollectionService.getTokenClassCreateFee()}estimateNftMintFee(e){return this.nftCollectionService.estimateMintFee(e)}estimateNftOperationFees(e){return this.nftCollectionService.estimateNftOperationFees(e)}claimNftCollection(e){return this.nftCollectionService.claimCollection(e)}fetchNftCollections(e){return this.nftCollectionService.fetchUserCollections(e)}isNftCollectionAvailable(e){return this.nftCollectionService.isCollectionAvailable(e)}createNftTokenClass(e){return this.nftCollectionService.createTokenClass(e)}fetchNftTokenClasses(e){return this.nftCollectionService.fetchTokenClasses(e)}mintNft(e){return this.nftCollectionService.mintNft(e)}fetchNftBalances(e,t){return this.nftCollectionService.fetchNftBalances(e,t)}async cleanup(){try{if(this.logger.debug("Starting cleanup..."),void 0!==this._eventsBatcherService)try{await this._eventsBatcherService.shutdown(5e3),this._eventsBatcherService=void 0}catch(e){this.logger.warn("Error during events shutdown:",e)}this.http.cleanup(),null!==this.websocketService&&void 0!==this.websocketService&&this.websocketService.disconnect(),void 0!==this._streamWebSocketService&&(this._streamWebSocketService.dispose(),this._streamWebSocketService=void 0),this.logger.debug("Cleanup completed")}catch(e){this.logger.error("Error during cleanup:",e)}}static cleanupAll(e=!1){const t=new Vt({debug:e,context:"LaunchpadSDK"});t.debug("Starting global cleanup..."),Jd.cleanupAll(e),t.debug("Global cleanup completed")}}function Hu(n){const r=e.createWallet(n);return{...r,wallet:new t.Wallet(r.privateKey)}}function Wu(){const e=globalThis;return e.process?.env??{}}Ku.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR=.15,Ku.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR=.01,Ku.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY=$t.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY,Ku.DEFAULT_CALCULATE_AMOUNT_MODE=tt.LOCAL,Ku.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS=30,Ku.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS=100;function Vu(e){const t={};return void 0!==e.cursor&&(t.cursor=e.cursor),void 0!==e.pageSize&&(t.pageSize=e.pageSize),t}function ju(e){return"string"==typeof e?e:"number"==typeof e||"boolean"==typeof e||"bigint"==typeof e?String(e):JSON.stringify(e)??""}function qu(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 zu(e){const t=e.trim().toLowerCase();if(0===t.length)throw new Error("Token name cannot be empty");return t}function Yu(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 Xu(e,t){return`${e.replace(/\/$/,"")}${t}`}const Qu=new Map;const Ju={NEW_HOLDER:"NEW_HOLDER",EXITED_HOLDER:"EXITED_HOLDER",BALANCE_CHANGED:"BALANCE_CHANGED"},Zu=mo({type:"string",userAddress:"string",balance:"string",rank:"number",previousRank:"optional-number"}),eh=mo({tokenName:"string",userAddress:"string",quantity:"optional-string",percentage:"optional-number",holderTier:"optional-object",isCreator:"boolean",rank:"optional-number"});Jn.MIN_LENGTH,Jn.MAX_LENGTH,Jn.PATTERN;Ln({ENABLED:"ENABLED",DISABLED:"DISABLED",ADMIN_DISABLED:"ADMIN_DISABLED"});function th(e){return"global"===e||"token"===e}function nh(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 rh(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.messageId&&"string"==typeof t.content&&"string"==typeof t.userAddress&&"string"==typeof t.pinnedBy&&"string"==typeof t.pinnedAt}const sh=Ln({RATE_LIMITED:"RATE_LIMITED",INVALID_EMOJI:"INVALID_EMOJI",NOT_AUTHENTICATED:"NOT_AUTHENTICATED",STREAM_NOT_LIVE:"STREAM_NOT_LIVE"});function oh(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.userAddress&&"string"==typeof t.fullName&&(void 0===t.profileImage||"string"==typeof t.profileImage)}var ih,ah,ch,lh,dh,uh;exports.AnalysisStatus=void 0,(ih=exports.AnalysisStatus||(exports.AnalysisStatus={})).PENDING="PENDING",ih.PROCESSING="PROCESSING",ih.COMPLETED="COMPLETED",ih.FAILED="FAILED",exports.AnalysisType=void 0,(ah=exports.AnalysisType||(exports.AnalysisType={})).TEXT="TEXT",ah.IMAGE="IMAGE",ah.VIDEO="VIDEO",exports.AIRecommendation=void 0,(ch=exports.AIRecommendation||(exports.AIRecommendation={})).NO_ACTION="NO_ACTION",ch.REVIEW_REQUIRED="REVIEW_REQUIRED",ch.DELETE_CONTENT="DELETE_CONTENT",ch.BAN_USER="BAN_USER",ch.DELETE_AND_BAN="DELETE_AND_BAN",exports.AnalysisCategory=void 0,(lh=exports.AnalysisCategory||(exports.AnalysisCategory={})).VIOLENCE="VIOLENCE",lh.HATE_SPEECH="HATE_SPEECH",lh.SEXUAL_CONTENT="SEXUAL_CONTENT",lh.HARASSMENT="HARASSMENT",lh.SPAM="SPAM",lh.SCAM="SCAM",lh.SELF_HARM="SELF_HARM",lh.ILLEGAL_ACTIVITY="ILLEGAL_ACTIVITY",lh.MISINFORMATION="MISINFORMATION",lh.COPYRIGHT="COPYRIGHT",lh.SAFE="SAFE",exports.AnalysisTier=void 0,(dh=exports.AnalysisTier||(exports.AnalysisTier={})).QUICK="QUICK",dh.DETAILED="DETAILED",exports.AIModerationMode=void 0,(uh=exports.AIModerationMode||(exports.AIModerationMode={})).DISABLED="DISABLED",uh.ADVISORY="ADVISORY";const hh={[exports.AnalysisStatus.PENDING]:"Pending",[exports.AnalysisStatus.PROCESSING]:"Processing",[exports.AnalysisStatus.COMPLETED]:"Completed",[exports.AnalysisStatus.FAILED]:"Failed"},gh={[exports.AIRecommendation.NO_ACTION]:"No Action Needed",[exports.AIRecommendation.REVIEW_REQUIRED]:"Human Review Required",[exports.AIRecommendation.DELETE_CONTENT]:"Delete Content",[exports.AIRecommendation.BAN_USER]:"Ban User",[exports.AIRecommendation.DELETE_AND_BAN]:"Delete & Ban"},ph={[exports.AnalysisCategory.VIOLENCE]:"Violence",[exports.AnalysisCategory.HATE_SPEECH]:"Hate Speech",[exports.AnalysisCategory.SEXUAL_CONTENT]:"Sexual Content",[exports.AnalysisCategory.HARASSMENT]:"Harassment",[exports.AnalysisCategory.SPAM]:"Spam",[exports.AnalysisCategory.SCAM]:"Scam",[exports.AnalysisCategory.SELF_HARM]:"Self Harm",[exports.AnalysisCategory.ILLEGAL_ACTIVITY]:"Illegal Activity",[exports.AnalysisCategory.MISINFORMATION]:"Misinformation",[exports.AnalysisCategory.COPYRIGHT]:"Copyright",[exports.AnalysisCategory.SAFE]:"Safe"},mh={[exports.AnalysisTier.QUICK]:"Quick Scan",[exports.AnalysisTier.DETAILED]:"Detailed Scan"},fh={[exports.AnalysisType.TEXT]:"Text",[exports.AnalysisType.IMAGE]:"Image",[exports.AnalysisType.VIDEO]:"Video"},Eh={[exports.AIModerationMode.DISABLED]:"Disabled",[exports.AIModerationMode.ADVISORY]:"Advisory"},Ah=Ln(exports.AnalysisStatus),Th=Ln(exports.AnalysisType),vh=Ln(exports.AIRecommendation),Sh=Ln(exports.AnalysisCategory),yh=Ln(exports.AnalysisTier),bh=Ln(exports.AIModerationMode),Nh=Bn([{field:"id",type:"number"},{field:"flagId",type:"number"},{field:"status",type:"string",validator:Ah},{field:"analysisType",type:"string",validator:Th},{field:"provider",type:"string"}]),kh=Bn([{field:"enabled",type:"boolean"},{field:"mode",type:"string",validator:bh},{field:"provider",type:"string"}]);function wh(e){return null!==e.analysisTier}function _h(e){if(!Rn(e))throw Tt("content");if(0===e.trim().length)throw Ot("content","Content");if(e.length>or.COMMENTS_V1.MAX_LENGTH)throw Rt("content",or.COMMENTS_V1.MAX_LENGTH,e.length)}function Ih(e){if(!Rn(e))throw Tt("content");if(0===e.trim().length)throw new rt("content cannot be empty","content",nt.REQUIRED);if(e.length>or.CHAT_MESSAGES_V1.MAX_LENGTH)throw new rt(`content must be at most ${or.CHAT_MESSAGES_V1.MAX_LENGTH} characters`,"content",nt.TOO_LONG)}var Ch=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=Tn(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=Tn(e.reverseBondingCurveMaxFeePortion,NaN);isNaN(r)?t&&t.debug(`Skipping invalid reverseBondingCurveMaxFeePortion for ${e.tokenName}: "${e.reverseBondingCurveMaxFeePortion}"`):n.reverseBondingCurveMaxFeeFactor=r}return void 0!==n.reverseBondingCurveMaxFeeFactor&&void 0!==n.reverseBondingCurveMinFeeFactor&&(n.reverseBondingCurveNetFeeFactor=n.reverseBondingCurveMaxFeeFactor-n.reverseBondingCurveMinFeeFactor),Object.keys(n).length>0?n:null},isValidPoolForCaching:function(e){if(null===e||"object"!=typeof e)return!1;const t=e;return"tokenName"in t&&"string"==typeof t.tokenName&&t.tokenName.length>0}});exports.ACTIVE_USER_TYPE=Si,exports.AI_MODE_LABELS=Eh,exports.AI_RECOMMENDATION_LABELS=gh,exports.ALL_PERMISSIONS=gi,exports.ANALYSIS_CATEGORY_LABELS=ph,exports.ANALYSIS_STATUS_LABELS=hh,exports.ANALYSIS_TIER_LABELS=mh,exports.ANALYSIS_TYPE_LABELS=fh,exports.API_KEY_PERMISSION={MANAGE_COMMENTS:"MANAGE_COMMENTS",MANAGE_CHAT:"MANAGE_CHAT",BAN_USERS:"BAN_USERS",UNBAN_USERS:"UNBAN_USERS",MANAGE_SIMULCAST:"MANAGE_SIMULCAST",GET_STREAM_KEY:"GET_STREAM_KEY",STOP_STREAM:"STOP_STREAM",RESET_STREAM_KEY:"RESET_STREAM_KEY",START_STREAM:"START_STREAM",DELETE_RECORDINGS:"DELETE_RECORDINGS",MANAGE_STREAM_SETTINGS:"MANAGE_STREAM_SETTINGS"},exports.API_KEY_ROLE=di,exports.API_KEY_ROLES=ui,exports.API_KEY_ROLE_HIERARCHY=Ti,exports.AddressFormatter=on,exports.AgentConfig=class{constructor(){this.utilityInstance=!0,this.utilityInstance}static async quickSetup(e={}){const t=e.environment??this.detectEnvironment(),n=this.setupWallet(e.privateKey),r=this.buildSdkConfig(e,t,n),s=new Ku(r),o={sdk:s,wallet:n,config:r};if(!1!==e.autoValidate){const e=await this.validateSetup(s,n);return{...o,validation:e}}return o}static readOnlySetup(e={}){const t=e.environment??this.detectEnvironment(),n=this.buildSdkConfig(e,t),r=new Ku(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=Tn(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??Hu(),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"===(Wu().LAUNCHPAD_ENV??Wu().ENVIRONMENT)?"stage":"prod"}static setupWallet(e){if(void 0===e||""===e){const e=Wu().PRIVATE_KEY;return void 0!==e&&""!==e?Hu(e):Hu()}return"generate"===e?Hu():Hu(e)}static buildSdkConfig(e,t,n){const r=e.galaChainAddress??Wu().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 jo(e).launchpadBaseUrl}static getDefaultTimeout(e){switch(e){case"prod":return 3e4;case"stage":return 45e3}}static getEnvironmentDefaults(e){const t=jo(e);return{bundleBaseUrl:t.bundleBaseUrl,gatewayBaseUrl:t.gatewayBaseUrl}}},exports.AuthError=Po,exports.BAN_DURATIONS={ONE_HOUR:3600,ONE_DAY:86400,ONE_WEEK:604800,ONE_MONTH:2592e3},exports.BrowserWalletSigner=Zi,exports.BundleSubmission=tu,exports.BundlerTransport=nu,exports.BurnError=Tc,exports.CALCULATION_MODES=tt,exports.CONTENT_REACTION_TYPES=Da,exports.CONTENT_TYPE_LABELS=va,exports.ChartService=class extends jn{constructor(e,t=!1){super(e,t)}async getChart(e){if(null==e)throw Tt("options","Chart options");const{tokenName:t,from:n,to:r,resolution:s}=e;if(null==t||""===t)throw Tt("tokenName","Token name");if(null==n)throw Tt("from","Start timestamp");if(null==r)throw Tt("to","End timestamp");if(null==s)throw Tt("resolution","Data resolution interval");Fn(t,"tokenName",Xn);const o=173e6;if("number"!=typeof n||n<o)throw new rt("from must be a valid timestamp (min: 173000000)","from","INVALID_TIMESTAMP");if("number"!=typeof r||r<o)throw new rt("to must be a valid timestamp (min: 173000000)","to","INVALID_TIMESTAMP");if("number"!=typeof s||s<1)throw new rt("resolution must be a number >= 1","resolution","INVALID_RESOLUTION");const{adaptQueryParams:i}=await Promise.resolve().then(function(){return Uc}),a=i({tokenName:t,from:n,to:r,resolution:s}),c=await Bt(()=>this.http.get(l.CHART,a),{errorContext:"Failed to fetch chart data"}),d=Lt(c);if(null==d||"object"!=typeof d)throw St("Invalid API response: missing or invalid data",c.status??500);const u=d,h=u.data;if(!Array.isArray(h))throw St("Invalid API response: expected data array",c.status??500);const g={dataPoints:h.map(e=>{if("object"!=typeof e||null===e)throw St("Invalid API response: invalid data point structure",c.status??500);const t=e,n=t.startTime??t.timestamp,r=t.openPrice??t.value,s=t.closePrice??t.value,o=t.lowPrice??t.value,i=t.highPrice??t.value,a=t.volume??"0";return{startTime:"number"==typeof n?n:Number(n),openPrice:String(r),closePrice:String(s),lowPrice:String(o),highPrice:String(i),volume:String(a)}})};return"boolean"==typeof u.isPreviousData&&(g.isPreviousData=u.isPreviousData),g}},exports.ConfigurationError=ct,exports.DEFAULT_EVENTS_CONFIG=La,exports.DEFAULT_PRICING_CONCURRENCY=5,exports.DEFAULT_REVERSE_BONDING_CURVE_CONFIGURATION=fu,exports.DEFAULT_WEBSOCKET_RECONNECT_ATTEMPTS=5,exports.ENVIRONMENT_URLS=Vo,exports.ERROR_CODES=nt,exports.EVENT_SORT_FIELDS=Fa,exports.EVENT_SOURCES=Ba,exports.EVENT_TIME_PRESETS=Pa,exports.EVENT_TYPES={LOGIN:"login",LOGOUT:"logout",TOKEN_BUY:"token_buy",TOKEN_SELL:"token_sell",TOKEN_SWAP:"token_swap",TOKEN_CREATED:"token_created",TOKEN_GRADUATED:"token_graduated",PAGE_VIEW:"page_view",PAGE_LEAVE:"page_leave",STREAM_START:"stream_start",STREAM_END:"stream_end",STREAM_VIEWERS_CHANGED:"stream_viewers_changed",CHAT_MESSAGE_SENT:"chat_message_sent",CHAT_MESSAGE_RECEIVED:"chat_message_received",LIQUIDITY_ADDED:"liquidity_added",LIQUIDITY_REMOVED:"liquidity_removed",BRIDGE_DEPOSIT:"bridge_deposit",BRIDGE_WITHDRAW:"bridge_withdraw",PROFILE_UPDATED:"profile_updated",BALANCE_CHANGED:"balance_changed",ERROR_OCCURRED:"error_occurred"},exports.EXTENDED_STREAM_ROLE=ad,exports.EventBufferWithAutoCleanup=class{constructor(e={},t){this.events=[],this.timeouts=new Map,this.maxSize=e.maxSize??100,this.defaultTtlMs=e.defaultTtlMs??3e4,this.logger=t}push(e){if(this.events.length>=this.maxSize){const e=0;this.events.shift();const t=this.timeouts.get(e);t&&(clearTimeout(t),this.timeouts.delete(e)),this.logger?.warn(`Buffer full (${this.maxSize}), dropped oldest event`)}this.events.push(e);const t=this.events.length-1,n=setTimeout(()=>{this.events[t]===e&&this.events.splice(t,1),this.timeouts.delete(t)},this.defaultTtlMs);this.timeouts.set(t,n)}getAll(){return[...this.events]}clear(){for(const e of this.timeouts.values())clearTimeout(e);this.events=[],this.timeouts.clear()}get size(){return this.events.length}},exports.EventsBatcherService=Ua,exports.EventsQueryService=Wa,exports.FLAG_ACTION_LABELS=Ta,exports.FLAG_DETAILS_MAX_LENGTH=500,exports.FLAG_REASON_LABELS=Ea,exports.FLAG_STATUS_LABELS=Aa,exports.FileValidationError=Dc,exports.GALA_DECIMALS=8,exports.GalaWalletSigner=Ji,exports.GlobalAndRoomCallbackDispatcher=class{constructor(e){this.globalCallbacks=[],this.roomCallbacks=new Map,this.logger=e}registerGlobalCallback(e){this.globalCallbacks.push(e)}registerRoomCallback(e,t){const n=this.roomCallbacks.get(e)??[];n.push(t),this.roomCallbacks.set(e,n)}dispatch(e,t){for(const e of this.globalCallbacks)try{e(t)}catch(e){this.logger?.error(`Error in global callback: ${ut(e)}`)}const n=this.roomCallbacks.get(e);if(n)for(const r of n)try{r(t)}catch(t){this.logger?.error(`Error in room callback for ${e}: ${ut(t)}`)}}clear(){this.globalCallbacks=[],this.roomCallbacks.clear()}clearRoom(e){this.roomCallbacks.delete(e)}},exports.HOLDER_DELTA_TYPES=Ju,exports.HealthService=Cc,exports.IMAGE_EXTENSIONS=Hr,exports.INVITE_STATUS=ml,exports.INVITE_STATUSES=fl,exports.JWT_CONSTANTS=Lo,exports.LAUNCHPAD_TOKEN_DECIMALS=18,exports.LAUNCHPAD_WRITE_METHODS=eu,exports.LaunchpadSDK=Ku,exports.LaunchpadSDKError=Hi,exports.LaunchpadWrites=_u,exports.ListenerCleanupManager=class{constructor(e){this.listeners=[],this.logger=e}register(e,t){this.listeners.push({id:e,cleanup:t})}async cleanup(){const e=[];for(let t=this.listeners.length-1;t>=0;t--){const n=this.listeners[t];if(void 0===n)continue;const{id:r,cleanup:s}=n;try{await s()}catch(t){const n=t instanceof Error?t:new Error(String(t));e.push(n),this.logger?.error(`Cleanup error for listener ${r}:`,n)}}return this.listeners=[],e}clear(){this.listeners=[]}get size(){return this.listeners.length}},exports.LockError=ec,exports.MAX_BURN_BATCH_SIZE=50,exports.MAX_CONCURRENT_POOL_FETCHES=5,exports.MAX_LOCK_BATCH_SIZE=100,exports.MAX_UNLOCK_BATCH_SIZE=100,exports.MESSAGES_CONSTRAINTS=il,exports.MESSAGE_TYPES=ol,exports.MODERATOR_ROLE=ul,exports.MODERATOR_ROLES=hl,exports.NFT_FEES=kl,exports.NetworkError=at,exports.NftCollectionService=Rl,exports.OEmbedService=xl,exports.OVERSEER_INVITE_STATUS=Ll,exports.OVERSEER_STATUS=Ul,exports.PAGINATION_DEFAULTS=Qo,exports.PERMISSION=hi,exports.POOL_FETCH_CONFIG={MAX_CONCURRENT_FETCHES:5,PAGE_SIZE:50,BACKEND_PAGE_SIZE:20},exports.POOL_FETCH_TYPES=Je,exports.POOL_LIST_MAX_PAGE_SIZE=et,exports.POOL_STREAM_STATUSES=Ze,exports.POOL_TYPES={RECENT:"recent",POPULAR:"popular"},exports.PayloadWalkerWithDeduplication=class{constructor(e,t,n=50){this.seen=new Set,this.extractor=e,this.dedupeKeyFn=t,this.maxDepth=n}walk(e){const t=[],n=new WeakSet,r=(e,s=0)=>{if(s>this.maxDepth)return;if(null==e||"object"!=typeof e)return;if(n.has(e))return;n.add(e);const o=this.extractor(e);if(null!==o){const e=this.dedupeKeyFn(o);this.seen.has(e)||(this.seen.add(e),t.push(o))}for(const t of Object.values(e))r(t,s+1)};return r(e,0),t}reset(){this.seen.clear()}getSeenCount(){return this.seen.size}},exports.PendingSubscriptionTracker=class{constructor(){this.pending=new Map}addPending(e,t){this.removePending(e);const n=setTimeout(()=>{this.pending.delete(e)},t);this.pending.set(e,{timeoutId:n,addedAt:Date.now()})}removePending(e){const t=this.pending.get(e);t&&(clearTimeout(t.timeoutId),this.pending.delete(e))}isPending(e){return this.pending.has(e)}getPendingCount(){return this.pending.size}clearExpired(){for(const[e,t]of this.pending.entries())null==t&&this.pending.delete(e)}clear(){for(const e of this.pending.values())clearTimeout(e.timeoutId);this.pending.clear()}},exports.PlatformStatsService=Xl,exports.PrivateKeySigner=Qi,exports.QUERY_FIELD_NAMES={PAGE:"page",LIMIT:"limit",TOKEN_NAME:"tokenName",VAULT_ADDRESS:"vaultAddress",USER_ADDRESS:"userAddress",TRADE_TYPE:"tradeType",POOL_TYPE:"type",SEARCH:"search",SORT_ORDER:"sortOrder",START_DATE:"startDate",END_DATE:"endDate"},exports.REACTION_EMOJI_MAP={heart:"❤️",fire:"🔥",laugh:"😂",wow:"😮",thumbs_up:"👍"},exports.RECORDING_STATUS=ed,exports.ROLE_SOURCE=id,exports.RoomSubscriptionManager=class{constructor(){this.rooms=new Set}addRoom(e){this.rooms.add(e)}removeRoom(e){this.rooms.delete(e)}getRooms(){return Array.from(this.rooms)}isSubscribedTo(e){return this.rooms.has(e)}clear(){this.rooms.clear()}get size(){return this.rooms.size}},exports.SDK_VERSION=Xo,exports.SIMULATE_EVENT_TYPE={STREAM_STARTED:"stream.started",STREAM_STOPPED:"stream.stopped",RECORDING_READY:"recording.ready",SIMULCAST_ERROR:"simulcast.error"},exports.SIMULCAST_PLATFORM=td,exports.SIMULCAST_STATUS={IDLE:"idle",STARTING:"starting",BROADCASTING:"broadcasting",ERRORED:"errored"},exports.STREAM_EVENTS=pd,exports.STREAM_PERMISSION={MANAGE_COMMENTS:"MANAGE_COMMENTS",MANAGE_CHAT:"MANAGE_CHAT",BAN_USERS:"BAN_USERS",UNBAN_USERS:"UNBAN_USERS",MANAGE_SIMULCAST:"MANAGE_SIMULCAST",GET_STREAM_KEY:"GET_STREAM_KEY",STOP_STREAM:"STOP_STREAM",RESET_STREAM_KEY:"RESET_STREAM_KEY",START_STREAM:"START_STREAM",DELETE_RECORDINGS:"DELETE_RECORDINGS",MANAGE_STREAM_SETTINGS:"MANAGE_STREAM_SETTINGS"},exports.STREAM_ROLE=od,exports.STREAM_STATUS=Zl,exports.SelectiveEventForwarding=class{constructor(){this.filters=[]}addFilter(e){return this.filters.push(e),this}forward(e){for(const t of this.filters)if(!t(e))return!1;return!0}clearFilters(){this.filters=[]}get filterCount(){return this.filters.length}},exports.StreamWebSocketService=Bd,exports.TIME_CONSTANTS={ONE_SECOND_MS:1e3,ONE_MINUTE_MS:6e4,ONE_HOUR_MS:36e5,ONE_DAY_MS:864e5,ONE_WEEK_MS:6048e5,ONE_MONTH_MS:2592e6},exports.TOKEN_NAME_AVAILABILITY_CONSTRAINT=Zn,exports.TOKEN_NAME_DTO_CONSTRAINT=Xn,exports.TOKEN_NAME_EVENT_CONSTRAINT=er,exports.TOKEN_NAME_FILTER_CONSTRAINT=Qn,exports.TOKEN_NAME_PATH_CONSTRAINT=Jn,exports.TRADING_TYPES=Qe,exports.TokenRestrictedError=class extends rt{constructor(e){super(e,"token","TOKEN_RESTRICTED"),this.name="TokenRestrictedError"}},exports.TradingQuotesService=zd,exports.TransactionError=lt,exports.TransactionFailedError=Mu,exports.TypingIndicatorDebouncer=class{constructor(e={},t){this.pendingIndicators=new Map,this.activeIndicators=new Set,this.delayMs=e.delayMs??3e3,this.onTyping=e.onTyping,this.onStopTyping=e.onStopTyping}indicate(e,t){const n=`${e}:${t}`,r=this.pendingIndicators.get(n);r&&clearTimeout(r),this.activeIndicators.has(n)||(this.activeIndicators.add(n),this.onTyping?.(e,t));const s=setTimeout(()=>{this.activeIndicators.delete(n),this.pendingIndicators.delete(n),this.onStopTyping?.(e,t)},this.delayMs);this.pendingIndicators.set(n,s)}stopTyping(e,t){const n=`${e}:${t}`,r=this.pendingIndicators.get(n);r&&(clearTimeout(r),this.pendingIndicators.delete(n)),this.activeIndicators.has(n)&&(this.activeIndicators.delete(n),this.onStopTyping?.(e,t))}clear(){for(const e of this.pendingIndicators.values())clearTimeout(e);this.pendingIndicators.clear(),this.activeIndicators.clear()}get activeCount(){return this.activeIndicators.size}},exports.ValidationError=rt,exports.WebSocketError=xu,exports.WebSocketTimeoutError=class extends xu{constructor(e,t){super(`WebSocket confirmation timeout for transaction ${e} after ${t}ms`),this.name="WebSocketTimeoutError"}},exports.WeeklyChallengeService=Zd,exports.addCursorToPagination=function(e,t){return void 0===t?e:{...e,cursor:t}},exports.addressFormatSchema=yr,exports.aggregateMultipleApiSources=async function(e,t,n){const r=n?.logger,s=n?.fetcher??(async e=>{const t=await fetch(e);if(!t.ok)throw new Error(`HTTP ${t.status}`);return t.json()});r?.debug(`Aggregating from ${e.length} endpoints`);const o=e.map(async(t,n)=>{try{const o=await s(t);return r?.debug(`Endpoint [${n+1}/${e.length}] succeeded: ${t}`),o}catch(s){return void r?.warn(`Endpoint [${n+1}/${e.length}] failed: ${t} - ${ut(s)}`)}}),i=(await Promise.allSettled(o)).map(e=>{if("fulfilled"===e.status)return e.value});return r?.debug(`Aggregating ${i.filter(e=>void 0!==e).length} successful results`),t(i)},exports.amountMethodSchema=os,exports.amountTypeSchema=ss,exports.assertValidWalletAddress=fn,exports.availabilityTokenNameSchema=fr,exports.backendUserRef=en,exports.bidirectionalTokenMatch=function(e,t,n,r){return e===n&&t===r||e===r&&t===n},exports.browserFileSchema=Vr,exports.bufferFileSchema=jr,exports.buildConcurrentBatchRequests=async function(e,t,n,r){const s=r?.logger,o=[];o.length=e.length;let i=0,a=0;s?.debug(`Starting concurrent batch requests: ${e.length} URLs, batch size: ${t}`);for(let r=0;r<e.length;r+=t){const c=e.slice(r,r+t),l=r;try{const t=c.map((t,r)=>{const c=l+r;return(async()=>{try{const r=await n(t);return o[c]=r,i++,s?.debug(`Fetched [${c+1}/${e.length}]: ${t}`),r}catch(n){throw a++,s?.warn(`Failed [${c+1}/${e.length}]: ${t} - ${ut(n)}`),n}})()}),r=await Promise.allSettled(t);for(let e=0;e<r.length;e++){const t=r[e];"rejected"===t?.status&&s?.debug(`Promise rejected in batch at index ${l+e}`)}}catch(e){s?.error(`Batch processing error at index ${r}: ${ut(e)}`)}}return s?.debug(`Batch complete: ${i} succeeded, ${a} failed`),o},exports.buildQueryParametersWithValidation=function(e){if(null==e||"object"!=typeof e)return"";const t=[];for(const[n,r]of Object.entries(e)){if(On(r))continue;let e;e="string"==typeof r?r:"number"==typeof r||"boolean"==typeof r?String(r):Array.isArray(r)?r.map(e=>ju(e)).join(","):ju(r);const s=encodeURIComponent(n),o=encodeURIComponent(e);t.push(`${s}=${o}`)}return t.length>0?`?${t.join("&")}`:""},exports.buildSafePaginationOptions=Vu,exports.buyTokensDataSchema=Ts,exports.calculateLinearFeeInterpolation=function(e,t,n){const r="number"==typeof e?new a(e):e;if(r.isLessThan(0)||r.isGreaterThan(1))throw new Error(`Progress must be between 0 and 1, got: ${r.toString()}`);if(n<t)throw new Error(`maxFee must be >= minFee, got minFee: ${t}, maxFee: ${n}`);const s=n-t;return new a(t).plus(new a(s).multipliedBy(r))},exports.calculatePreMintDataSchema=ws,exports.calculateScaledFeeAmount=function(e,t){if(t<0)throw new Error(`feeFactor must be >= 0, got: ${t}`);return Eo(e).multipliedBy(t).integerValue(a.ROUND_DOWN)},exports.calculateTotalPages=function(e,t){if("number"!=typeof e||!Number.isInteger(e))throw _t("total","a non-negative integer",e);if(e<0)throw Nt("total",0,1/0,e);if("number"!=typeof t||!Number.isInteger(t))throw _t("limit","a non-negative integer",t);if(t<0)throw Nt("limit",0,1/0,t);return 0===t?1:0===e?0:Math.ceil(e/t)},exports.capitalize=Et,exports.caseInsensitiveTokenComparison=function(e,t){return e.toLowerCase()===t.toLowerCase()},exports.checkPoolOptionsSchema=rs,exports.commonValidators=Gn,exports.conditionalSpreadBuilder=function(e,t){const n={...e};for(const[e,r]of Object.entries(t))void 0!==r&&(n[e]=r);return n},exports.conditionalTrimAndValidateString=zc,exports.createLaunchpadSDK=function(n){xn(n)&&(n={});const{wallet:r,env:s,config:o={},...i}=n,a={...{...i,...o}};delete a.wallet,delete a.env,delete a.config;const c=!xn(a.signer)||!xn(a.walletProvider);let l;if(xn(r))l=c?void 0:new t.Wallet(e.createWallet().privateKey);else if("string"==typeof r)l=new t.Wallet(e.createWallet(r).privateKey);else{if(!(r instanceof t.Wallet))throw yt("Invalid wallet input. Expected string (private key or mnemonic) or Wallet instance.","wallet");l=r}const d={...void 0!==l?{wallet:l}:{},...void 0!==s?{env:s}:{},debug:!1,timeout:3e4,...a};return new Ku(d)},exports.createLimitSchema=Rr,exports.createOptionsValidator=function(e){return t=>{const n=[],r=t;for(const t of e){const{field:e,required:s,type:o,validator:i}=t,a=r[e];if(s){if(xn(a)){n.push(`${e} is required`);continue}if("string"===o){if("string"!=typeof a){n.push(`${e} must be a string`);continue}if(0===a.trim().length){n.push(`${e} is required`);continue}}}if(!xn(a))if(void 0===o||typeof a===o){if(void 0!==i){const e=i(a,r);null!=e&&""!==e&&n.push(e)}}else n.push(`${e} must be a ${o}`)}return n}},exports.createPaginatedResultSchema=function(e){return n.z.object({data:n.z.array(e),...ps})},exports.createPaginationQuery=function(e,t=Qo.DEFAULT_LIMIT){if("number"!=typeof e||!Number.isInteger(e)||e<0)throw _t("offset","a non-negative integer",e);return _n(t,"limit"),{offset:e,limit:t}},exports.createTradeDataSchema=As,exports.decimalRoundingUp=function(e,t){if(t<0)throw new Error(`decimals must be >= 0, got: ${t}`);const n=Eo(e),r=new a(10).pow(t);return n.multipliedBy(r).integerValue(a.ROUND_UP).dividedBy(r)},exports.deduplicateByKey=function(e,t,n=!0){const r=new Map;if(e.forEach((e,n)=>{const s=t(e);r.set(s,n)}),n){const n=new Set;return e.filter(e=>{const r=t(e);return!n.has(r)&&(n.add(r),!0)})}return e.filter((e,n)=>{const s=t(e);return r.get(s)===n})},exports.dtoTokenNameSchema=mr,exports.errorMessageCaseNormalization=function(e){return e.toLowerCase()},exports.ethereumAddressSchema=br,exports.extractFieldWithFallbackPath=function(e,t,n=null){if(null==e||"object"!=typeof e)return n;const r=e;for(const e of t){const t=e.split(".");let n=r;for(const e of t){if(null==n||"object"!=typeof n){n=null;break}n=n[e]}if(Rn(n))return n;if(null!=n&&""!==n)return n}return n},exports.extractPaginationMetadata=function(e){const t={page:1,pageSize:20,totalCount:-1,hasMore:!1};if(null==e||"object"!=typeof e)return t;const n=e,r=vn(ju(n.page??n.Page??n.current??1),t.page),s=vn(ju(n.pageSize??n.limit??n.size??t.pageSize),t.pageSize),o=n.data,i=o?.meta;let a;a="number"==typeof n.totalCount?n.totalCount:"number"==typeof n.total?n.total:"number"==typeof i?.totalItems?i.totalItems:"number"==typeof o?.count?o.count:vn(ju(n.totalCount??n.total??-1),t.totalCount);let c=t.hasMore;return"boolean"==typeof n.hasMore?c=n.hasMore:"boolean"==typeof n.has_more?c=n.has_more:"boolean"==typeof i?.hasMore&&(c=i.hasMore),{page:r,pageSize:s,totalCount:a,hasMore:c}},exports.feeCeilingFromQuotedFee=pu,exports.fetchGalaBalanceOptionsSchema=Rs,exports.fetchPoolDetailsDataSchema=_s,exports.fetchTokenBalanceOptionsSchema=Ms,exports.fileSizeSchema=Lr,exports.fileUploadSchema=Wr,exports.filenameSchema=Ur,exports.flexibleAddressSchema=Nr,exports.flexibleFileSchema=qr,exports.formatGalaForDTO=bn,exports.formatLaunchpadTokenForDTO=Nn,exports.fromBackendAddressFormat=ln,exports.fullNameSchema=Sr,exports.generateBuySellStringsInstructions=ta,exports.generateCreateSaleStringsInstructions=na,exports.getAmountOptionsSchema=ks,exports.getEnvironmentConfig=jo,exports.getIntervalRegistryStats=function(){const e=Array.from(Qu.entries()).map(([e,t])=>({id:e,...t}));return{size:Qu.size,entries:e}},exports.getLaunchTokenDataValidationErrors=co,exports.getNftFeeAsNumber=function(e){return parseFloat(kl[e])},exports.getRecordingAnimatedUrl=function(e,t,n,r="gif"){const s=zu(e),o=t.trim();if(0===o.length)throw new Error("Recording ID cannot be empty");return Yu(r),Xu(n,`/v1/tokens/${encodeURIComponent(s)}/recordings/${encodeURIComponent(o)}/assets/animated.${r.toLowerCase()}`)},exports.getRecordingAssetUrl=function(e,t,n,r,s){const o=zu(e),i=t.trim(),a=n.trim().toLowerCase();if(0===i.length)throw new Error("Recording ID cannot be empty");if(0===a.length)throw new Error("Asset type cannot be empty");Yu(s);const c=void 0!==s&&s.length>0?`.${s.toLowerCase()}`:"";return Xu(r,`/v1/tokens/${encodeURIComponent(o)}/recordings/${encodeURIComponent(i)}/assets/${encodeURIComponent(a)}${c}`)},exports.getRecordingPosterUrl=function(e,t,n){const r=zu(e),s=t.trim();if(0===s.length)throw new Error("Recording ID cannot be empty");return Xu(n,`/v1/tokens/${encodeURIComponent(r)}/recordings/${encodeURIComponent(s)}/assets/poster.jpg`)},exports.getRecordingStoryboardUrl=function(e,t,n,r="vtt"){const s=zu(e),o=t.trim();if(0===o.length)throw new Error("Recording ID cannot be empty");return Yu(r),Xu(n,`/v1/tokens/${encodeURIComponent(s)}/recordings/${encodeURIComponent(o)}/assets/storyboard.${r.toLowerCase()}`)},exports.getRecordingStreamUrl=function(e,t,n){const r=zu(e),s=t.trim();if(0===s.length)throw new Error("Recording ID cannot be empty");return Xu(n,`/v1/tokens/${encodeURIComponent(r)}/recordings/${encodeURIComponent(s)}/assets/stream.m3u8`)},exports.getRecordingThumbnailUrl=function(e,t,n,r="jpg"){const s=zu(e),o=t.trim();if(0===o.length)throw new Error("Recording ID cannot be empty");return Yu(r),Xu(n,`/v1/tokens/${encodeURIComponent(s)}/recordings/${encodeURIComponent(o)}/assets/thumbnail.${r.toLowerCase()}`)},exports.getTieredModerationSavings=function(e,t){if(!wh(e)||null===e.tokensUsed)return 0;const n=1500*t.maxFrames;if(0===n)return 0;const r=(n-e.tokensUsed)/n*100;return Math.max(0,Math.round(r))},exports.getTokenAnimatedUrl=function(e,t,n="gif"){const r=zu(e);return Yu(n),Xu(t,`/v1/tokens/${encodeURIComponent(r)}/assets/animated.${n.toLowerCase()}`)},exports.getTokenAssetUrl=function(e,t,n,r){const s=zu(e),o=t.trim().toLowerCase();if(0===o.length)throw new Error("Asset type cannot be empty");Yu(r);const i=void 0!==r&&r.length>0?`.${r.toLowerCase()}`:"";return Xu(n,`/v1/tokens/${encodeURIComponent(s)}/assets/${encodeURIComponent(o)}${i}`)},exports.getTokenImageUrl=function(e,t){const n=zu(e);return Xu(t,`/v1/tokens/${encodeURIComponent(n)}/assets/image`)},exports.getTokenLiveStreamUrl=function(e,t){const n=zu(e);return Xu(t,`/v1/tokens/${encodeURIComponent(n)}/assets/live.m3u8`)},exports.getTokenPosterUrl=function(e,t){const n=zu(e);return Xu(t,`/v1/tokens/${encodeURIComponent(n)}/assets/poster.jpg`)},exports.getTokenStoryboardUrl=function(e,t,n="vtt"){const r=zu(e);return Yu(n),Xu(t,`/v1/tokens/${encodeURIComponent(r)}/assets/storyboard.${n.toLowerCase()}`)},exports.getTokenThumbnailUrl=function(e,t,n="jpg"){const r=zu(e);return Yu(n),Xu(t,`/v1/tokens/${encodeURIComponent(r)}/assets/thumbnail.${n.toLowerCase()}`)},exports.getTradeOptionsSchema=Ss,exports.graduateTokenOptionsSchema=as,exports.graphDataOptionsSchema=is,exports.groupByKey=function(e,t){const n=new Map;for(const r of e){const e=t(r);n.has(e)||n.set(e,[]),n.get(e).push(r)}return n},exports.hasMorePages=function(e,t,n){if("number"!=typeof e||!Number.isInteger(e))throw _t("offset","a non-negative integer",e);if(e<0)throw Nt("offset",0,1/0,e);return e+t<n},exports.hexStringExtractionAndNormalization=function(e){if(""===e||"string"!=typeof e)return null;if(e.includes("|")){const t=e.split("|");if(t.length>=2){const e=t[1];if(void 0!==e&&Yc(e))return Xc(e)}return null}return Yc(e)?Xc(e):null},exports.imageExtensionSchema=zr,exports.imageFilenameSchema=Yr,exports.imageMimeTypeSchema=Fr,exports.imageUploadOptionsSchema=ts,exports.isAIModerationData=Nh,exports.isAIModerationMode=bh,exports.isAIModerationSettings=kh,exports.isAIRecommendation=vh,exports.isActiveUserType=yi,exports.isAnalysisCategory=Sh,exports.isAnalysisStatus=Ah,exports.isAnalysisTier=yh,exports.isAnalysisType=Th,exports.isBanData=bi,exports.isBanEnforcementEvent=wi,exports.isBurnTokenEntry=fc,exports.isBurnTokensData=Ec,exports.isChatDisabledReason=th,exports.isChatStatusResponse=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"boolean"==typeof t.enabled&&(void 0===t.reason||th(t.reason))},exports.isClaimableInvite=function(e){if(e.status!==Ll.PENDING)return!1;if(null!==e.expiresAt&&void 0!==e.expiresAt){if(Xt(e.expiresAt)<=new Date)return!1}return!0},exports.isContentType=Sa,exports.isEmptyValue=On,exports.isExtendedStreamRole=cd,exports.isFlagAction=Na,exports.isFlagData=ka,exports.isFlagReason=ya,exports.isFlagStatus=ba,exports.isHolderDelta=Zu,exports.isHolderDeltaType=function(e){return"string"==typeof e&&(e===Ju.NEW_HOLDER||e===Ju.EXITED_HOLDER||e===Ju.BALANCE_CHANGED)},exports.isLockTokenEntry=za,exports.isLockTokensData=Xa,exports.isMessage=function(e){if(!al(e))return!1;const t=e.reactions;return"string"==typeof e.id&&"string"==typeof e.messageId&&"string"==typeof e.tokenName&&cl(e.tokenImage)&&"string"==typeof e.userAddress&&ll(e.user)&&ll(e.userProfile)&&"string"==typeof e.content&&"string"==typeof e.createdAt&&cl(e.updatedAt)&&cl(e.deletedAt)&&"number"==typeof e.flagCount&&al(t)&&al(t.counts)},exports.isMessageType=function(e){return e===ol.CHAT_MESSAGE||e===ol.COMMENT},exports.isModeratedToken=Sl,exports.isModerationTiered=wh,exports.isModeratorInvite=vl,exports.isNonEmptyString=Rn,exports.isOverseerInviteStatus=Fl,exports.isOverseerStatus=Pl,exports.isPinnedMessage=rh,exports.isPublicInviteInfo=yl,exports.isReactionErrorCode=sh,exports.isRecordingStatus=rd,exports.isSimulcastPlatform=sd,exports.isStreamChatDeletedEvent=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.messageId&&"string"==typeof t.deletedAt},exports.isStreamChatErrorEvent=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.message},exports.isStreamChatMessage=nh,exports.isStreamChatMessageEvent=function(e){return nh(e)},exports.isStreamChatPinnedEvent=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&rh(t.pinnedMessage)},exports.isStreamChatUnpinnedEvent=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.unpinnedMessageId},exports.isStreamReactionErrorEvent=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.message},exports.isStreamReactionEvent=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.emoji&&"number"==typeof t.timestamp&&"number"==typeof t.streamTime},exports.isStreamStatus=nd,exports.isStreamStatusEvent=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&nd(t.status)&&(null===t.playbackId||"string"==typeof t.playbackId)&&"boolean"==typeof t.isLive},exports.isTokenAccessResult=function(e){if(null==e||"object"!=typeof e)return!1;const t=e,n=t.permissions;return Array.isArray(n)&&n.every(e=>"string"==typeof e)&&(null===t.source||"owner"===t.source||"moderator_invite"===t.source||"api_key"===t.source||"overseer"===t.source)&&(void 0===t.matchedPreset||null===t.matchedPreset||"MODERATOR"===t.matchedPreset||"TECHNICAL_PRODUCER"===t.matchedPreset||"MANAGER"===t.matchedPreset)&&"boolean"==typeof t.isOwner&&"boolean"==typeof t.isOverseer},exports.isTokenBanData=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"number"==typeof t.id&&"string"==typeof t.tokenName&&"string"==typeof t.bannedBy&&"string"==typeof t.createdAt&&(null===t.reason||"string"==typeof t.reason)},exports.isTypingIndicatorEvent=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&Array.isArray(t.typingUsers)&&t.typingUsers.every(oh)},exports.isTypingUser=oh,exports.isUnlockTokenEntry=Ya,exports.isUnlockTokensData=Qa,exports.isUserBannedEvent=Ni,exports.isUserHoldingData=eh,exports.isUserRef=sn,exports.isUserUnbannedEvent=ki,exports.isValidAddress=un,exports.isValidApiKeyRole=pi,exports.isValidBanDuration=Ii,exports.isValidBanReason=_i,exports.isValidChatContent=function(e){return!!Rn(e)&&(e.length>=or.CHAT_MESSAGE.MIN_LENGTH&&e.length<=or.CHAT_MESSAGE.MAX_LENGTH)},exports.isValidChatTokenName=function(e){return!!Rn(e)&&Jn.PATTERN.test(e)},exports.isValidInviteCode=Tl,exports.isValidInviteStatus=Al,exports.isValidLaunchTokenData=function(e){return Vs(e).success},exports.isValidModeratorRole=El,exports.isValidTokenBanReason=$d,exports.isValidTokenName=function(e,t){if("string"!=typeof e)return!1;const n=e.trim();return 0!==n.length&&t.PATTERN.test(n)},exports.isViewerCountEvent=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"number"==typeof t.viewerCount},exports.isoDateStringSchema=Pr,exports.launchTokenDataSchema=es,exports.mergeSafePaginationOptions=function(e,t){return Vu({...e,...t})},exports.nonNegativeDecimalStringSchema=_r,exports.normalizeAddressInput=dn,exports.normalizeDataWithMapping=function(e,t){return e.map(e=>{const n={};for(const[r,s]of Object.entries(t)){const t=s(e);void 0!==t&&(n[r]=t)}return n})},exports.normalizeErrorMessage=function(e,t){return e.toLowerCase().includes(t.toLowerCase())},exports.normalizeLimit=Jo,exports.normalizeTokenKey=function(e){return e.trim().toUpperCase()},exports.normalizeTokenName=Kt,exports.normalizeTokenSymbol=Ht,exports.optionalUrlSchema=Cr,exports.pageNumberSchema=Dr,exports.paginationResultMetaSchema=ms,exports.parseHttpErrorResponse=function(e){const t={statusCode:0,errorMessage:"Unknown error",raw:e};if(null==e)return t;const n=e;let r=t.statusCode;"number"==typeof n.status?r=n.status:"number"==typeof n.statusCode?r=n.statusCode:"number"==typeof n.code&&(r=n.code);let s,o=t.errorMessage;"string"==typeof n.message?o=n.message:"string"==typeof n.error?o=n.error:e instanceof Error?o=e.message:"string"==typeof e&&(o=e);const i=n.response;if(i){const e=i.data;if("object"==typeof e&&null!==e){s=e;const t=e;"string"==typeof t.message?o=t.message:"string"==typeof t.error&&(o=t.error)}}const a={statusCode:r,errorMessage:o,raw:e};return null!=s&&(a.errorData=s),a},exports.parseLaunchpadVaultAddress=ea,exports.percentileIndexCalculation=function(e,t){if(0===e.length)return-1;if(t<0||t>100)throw new Error(`Percentile must be between 0 and 100, got: ${t}`);const n=(e.length-1)*(t/100),r=Math.floor(n);return Math.min(r,e.length-1)},exports.poolFetchTypeSchema=ns,exports.poolPaginationSchema=us,exports.positiveDecimalStringSchema=wr,exports.priceTickRangeMapping=function(e,t,n=60){const r=Eo(e),s=Eo(t);if(r.isLessThanOrEqualTo(0)||s.isLessThanOrEqualTo(0))throw new Error("Prices must be positive");if(r.isGreaterThanOrEqualTo(s))throw new Error(`minPrice must be < maxPrice, got: ${r.toString()} >= ${s.toString()}`);const o=Math.floor(To(r)),i=Math.ceil(To(s)),c=Math.floor(o/n)*n,l=Math.ceil(i/n)*n;return{minTick:c,maxTick:l,actualMinPrice:new a(1.0001).pow(c),actualMaxPrice:new a(1.0001).pow(l)}},exports.privateKeySchema=Gr,exports.registerInterval=function(e,t){const n=e;return Qu.set(n,{createdAt:Date.now(),label:t}),n},exports.requireNonNegative=function(...e){e.forEach(e=>{if(e.isNaN())throw It("value","NaN");if(!e.isFinite())throw wt("value","finite");if(e.isLessThan(0))throw kt("value","0",e.toString())})},exports.requirePositive=yo,exports.requirePositiveWithContext=bo,exports.retryableHttpRequest=async function(e,t){const n=t?.maxRetries??3,r=t?.backoffMs??100,s=t?.retryableStatus??[429,503,504];let o,i=0;for(;i<=n;)try{return await e()}catch(e){o=e,i++;const t=qu(e),a=s.includes(t);if(i>n||!a)throw e;const c=r*Math.pow(2,i-1);await new Promise(e=>setTimeout(e,c))}throw o},exports.reverseBondingCurveConfigSchema=Zr,exports.reverseBondingCurveConfigurationSchema=Is,exports.roleHasSufficientPermission=function(e,t){return e===di.MANAGER?t!==di.OWNER:e===di.OWNER||e===t},exports.roundTickBoundaries=function(e,t,n){if(e>=t)throw new Error(`tickLower must be < tickUpper, got: ${e} >= ${t}`);if(n<=0)throw new Error(`tickSpacing must be > 0, got: ${n}`);return{tickLower:Math.floor(e/n)*n,tickUpper:Math.ceil(t/n)*n}},exports.roundTickToSpacing=function(e,t){if(t<=0)throw new Error(`tickSpacing must be > 0, got: ${t}`);return Math.floor(e/t)*t},exports.safeDivideWithMinimum=function(e,t,n,r="0"){const s=Eo(t);if(vo(s))return Eo(r);const o=Eo(e).dividedBy(s);if(null!=n){const e=Eo(n);if(e.isLessThan(0))throw new Error(`minimum must be >= 0, got: ${e.toString()}`);if(o.isLessThan(e))return e}return o},exports.searchQuerySchema=vr,exports.sellTokensDataSchema=vs,exports.standardLimitSchema=Or,exports.standardPaginationSchema=cs,exports.timestampSchema=Br,exports.toBackendAddressFormat=cn,exports.toBackendAddressFromEthers=En,exports.tokenCategorySchema=Qr,exports.tokenCollectionSchema=Jr,exports.tokenDescriptionSchema=Ar,exports.tokenListOptionsSchema=Ds,exports.tokenNameSchema=pr,exports.tokenSymbolSchema=Er,exports.tokenUrlsSchema=Xr,exports.tradeCalculationMethodSchema=Ns,exports.tradeCalculationTypeSchema=bs,exports.tradeLimitSchema=Mr,exports.tradeListParamsSchema=ys,exports.tradePaginationSchema=ds,exports.tradePaginationWithFiltersSchema=gs,exports.tradeTypeBackendSchema=Es,exports.tradeTypeSchema=fs,exports.transactionIdSchema=$r,exports.transformRawApiTokenToDomainModel=function(e){if(null==e||"object"!=typeof e)throw new Error("Token must be an object");const t=e,n=(Rn(t.name)?t.name:void 0)??(Rn(t.tokenName)?t.tokenName:void 0)??"";if(!Rn(n))throw new Error("Token name is required and must be a non-empty string");const r=(Rn(t.symbol)?t.symbol:void 0)??(Rn(t.tokenSymbol)?t.tokenSymbol:void 0)??"";if(!Rn(r))throw new Error("Token symbol is required and must be a non-empty string");let s=8;"number"==typeof t.decimals&&t.decimals>=0&&(s=Math.floor(t.decimals));const o={name:n,symbol:r,decimals:s};return Rn(t.address)&&(o.address=t.address),"boolean"==typeof t.verified&&(o.verified=t.verified),o},exports.trimmedLengthValidation=function(e){return null==e||"string"!=typeof e||0===e.trim().length},exports.uniqueKeySchema=Kr,exports.unregisterAllIntervals=function(){const e=Qu.size;return Qu.clear(),e},exports.unregisterInterval=function(e){const t=e;Qu.delete(t)},exports.updateProfileDataSchema=Os,exports.uploadProfileImageOptionsSchema=xs,exports.urlSchema=Ir,exports.userLimitSchema=xr,exports.userPaginationSchema=ls,exports.userRef=Zt,exports.userTokenNameSchema=Tr,exports.userTokenTypeSchema=Cs,exports.userTokensPaginationSchema=hs,exports.validateAddress=Bs,exports.validateAmountString=$s,exports.validateBanTokenOptions=Kd,exports.validateBuyTokensData=to,exports.validateCalculatePreMintData=io,exports.validateChatMessageId=function(e){if(!Rn(e))throw Tt("id","Message ID");if(!ir.CHAT_MESSAGE.PATTERN.test(e))throw new rt("Invalid message ID format. Expected: chat-{timestamp}-{uuid}","id",nt.INVALID_FORMAT)},exports.validateCheckPoolOptions=zs,exports.validateConstrainedEnumVariant=function(e,t,n){if(!t.includes(e))throw new rt(`${n} must be one of [${t.map(e=>String(e)).join(", ")}], received "${e}"`,n,"INVALID_ENUM_VALUE")},exports.validateCreateApiKeyOptions=mi,exports.validateCreateChatMessageOptions=function(e){if(!Rn(e.tokenName))throw Tt("tokenName");Pn(e.tokenName,"tokenName",Xn),Ih(e.content)},exports.validateCreateCommentOptions=function(e){if(!Rn(e.tokenName))throw Tt("tokenName","Token name");Pn(e.tokenName,"tokenName",Xn),_h(e.content)},exports.validateCreateMessageOptions=function(e){if(void 0===e.type||null===e.type)throw Tt("type");if(e.type!==ol.CHAT_MESSAGE&&e.type!==ol.COMMENT)throw new rt(`type must be one of: ${Object.values(ol).join(", ")}`,"type",nt.INVALID_VALUE);if(!Rn(e.tokenName))throw Tt("tokenName");if(Pn(e.tokenName,"tokenName",Xn),!Rn(e.content))throw Tt("content");if(0===e.content.trim().length)throw Ot("content","Content");const t=e.type===ol.CHAT_MESSAGE?il.CONTENT.CHAT_MAX_LENGTH:il.CONTENT.COMMENT_MAX_LENGTH;if(e.content.length>t)throw Rt("content",t,e.content.length)},exports.validateCreateModeratorInviteOptions=function(e){const t=[],n=e.inviteScope??gl.TOKEN;return void 0===e.inviteScope||bl(e.inviteScope)||ft(t,()=>{throw Ct("inviteScope",e.inviteScope,pl,"Invite scope")}),n===gl.TOKEN?ft(t,()=>{Fn(e.tokenName??"","tokenName",Xn)}):n===gl.ALL_OWNER_TOKENS&&void 0!==e.tokenName&&""!==e.tokenName&&t.push("Token name should not be provided for ALL_OWNER_TOKENS scope invites"),El(e.role)||ft(t,()=>{throw Ct("role",e.role,hl,"Role")}),void 0!==e.description&&""!==e.description&&ft(t,()=>{wn(e.description,or.DESCRIPTION.MAX_LENGTH,"description")}),void 0===e.expiresAt||""===e.expiresAt||Qt(e.expiresAt)||ft(t,()=>{throw function(e,t="a valid date",n){const r=Et(e,n);return new rt(`${r} must be ${t}`,e,"INVALID_DATE")}("expiresAt","ISO 8601 format")}),t},exports.validateCreateOverseerDirectOptions=jl,exports.validateCreateOverseerInviteOptions=Bl,exports.validateCreateTradeData=eo,exports.validateDecimalRangeStrict=function(e,t,n,r){const s="string"==typeof e?parseFloat(e):e;if(!isFinite(s))throw new rt(`${r} must be a valid finite number between ${t} and ${n}`,r,"INVALID_NUMBER");if(s<t||s>n)throw Nt(r,t,n,s,r)},exports.validateFeePortionConstraints=Cn,exports.validateFetchGalaBalanceOptions=Xs,exports.validateFetchMessagesOptions=function(e){const t=void 0!==e.type,n=void 0!==e.tokenName&&""!==e.tokenName,r=void 0!==e.userAddress&&""!==e.userAddress;if(!t&&!n&&!r)throw Dt(["type","tokenName","userAddress"]);if(void 0!==e.type&&e.type!==ol.CHAT_MESSAGE&&e.type!==ol.COMMENT)throw new rt(`type must be one of: ${Object.values(ol).join(", ")}`,"type",nt.INVALID_VALUE);sl(e.tokenName,e.userAddress),void 0!==e.pageSize&&Mn(0,void 0,rr,e.pageSize)},exports.validateFetchPoolDetailsData=ao,exports.validateFetchTokenBalanceOptions=Zs,exports.validateFullName=Ks,exports.validateGetAmountOptions=oo,exports.validateGetChatMessagesOptions=function(e){if(!(void 0!==e.tokenName&&""!==e.tokenName||void 0!==e.userAddress&&""!==e.userAddress))throw new rt("At least one of tokenName or userAddress is required","options",nt.REQUIRED);sl(e.tokenName,e.userAddress),void 0!==e.pageSize&&Mn(0,void 0,rr,e.pageSize)},exports.validateGetCommentsOptions=function(e){if(!(void 0!==e.tokenName&&""!==e.tokenName||void 0!==e.userAddress&&""!==e.userAddress))throw Dt(["tokenName","userAddress"]);void 0!==e.tokenName&&""!==e.tokenName&&Pn(e.tokenName,"tokenName",Xn),Mn(0,void 0,rr,e.pageSize,e.cursor)},exports.validateGetTokenBanOptions=Vd,exports.validateGetTradeOptions=ro,exports.validateGetTradesOptions=Vc,exports.validateImageUploadOptions=qs,exports.validateInviteCode=function(e){const t=[];return Rn(e)?Tl(e)||t.push("Invalid invite code format"):t.push(Tt("inviteCode","Invite code").message),t},exports.validateLaunchTokenData=lo,exports.validateListApiKeysOptions=Ai,exports.validateListModeratorInvitesOptions=function(e){const t=[];return ft(t,()=>{Fn(e.tokenName??"","tokenName",Xn)}),void 0===e.status||Al(e.status)||ft(t,()=>{throw Ct("status",e.status,fl,"Status")}),ft(t,()=>{Mn(0,void 0,tr,e.pageSize)}),t},exports.validateListOverseerInvitesOptions=Gl,exports.validateListOverseersOptions=$l,exports.validateListTokenBansOptions=Wd,exports.validateListUsersOptions=Vl,exports.validateMessageId=function(e){if(!Rn(e))throw Tt("id","Message ID");const t=ir.CHAT_MESSAGE.PATTERN.test(e),n=/^msg-\d{13}-[a-f0-9]{32}$/.test(e);if(!t&&!n)throw new rt("Invalid message ID format. Expected: chat-{timestamp}-{uuid} or msg-{timestamp}-{uuid}","id",nt.INVALID_FORMAT)},exports.validateMinMaxRelationship=function(e,t,n,r){const s="string"==typeof e?parseFloat(e):e,o="string"==typeof t?parseFloat(t):t;if(!isFinite(s))throw new rt(`${n} must be a valid finite number`,n,"INVALID_MIN_VALUE");if(!isFinite(o))throw new rt(`${r} must be a valid finite number`,r,"INVALID_MAX_VALUE");if(s>o)throw new rt(`${n} (${s}) must be less than or equal to ${r} (${o})`,n,"INVALID_RANGE")},exports.validateOptionalTokenName=function(e,t,n){if(null==e)return;if("string"!=typeof e)throw _t(t,"a string",e);const r=e.trim();if(0!==r.length&&!n.PATTERN.test(r))throw new rt(`${t} must be ${n.DESCRIPTION}`,t,nt.INVALID_FORMAT)},exports.validateOverseerInviteCode=Kl,exports.validateOverseerInviteId=Wl,exports.validateOverseerWalletAddress=Hl,exports.validatePaginationParams=function(e,t,n){if("number"!=typeof e||!Number.isInteger(e)||e<0)throw _t("offset","a non-negative integer",e);_n(t,"limit")},exports.validateSearchQuery=Hs,exports.validateSellTokensData=no,exports.validateSortOrderDirection=function(e,t){if("ASC"!==e&&"DESC"!==e)throw new rt(`${t} must be either 'ASC' or 'DESC'`,t,"INVALID_ENUM_VALUE")},exports.validateTokenDescription=Ps,exports.validateTokenListOptions=Ys,exports.validateTokenName=Pn,exports.validateTokenSymbol=Fs,exports.validateTokenUrls=js,exports.validateTradeListParams=so,exports.validateUnbanTokenOptions=Hd,exports.validateUpdateApiKeyOptions=fi,exports.validateUpdateChatMessageOptions=function(e){Ih(e.content)},exports.validateUpdateCommentOptions=function(e){_h(e.content)},exports.validateUpdateMessageOptions=function(e){if(!Rn(e.content))throw Tt("content");if(0===e.content.trim().length)throw Ot("content","Content");const t=Math.max(il.CONTENT.CHAT_MAX_LENGTH,il.CONTENT.COMMENT_MAX_LENGTH);if(e.content.length>t)throw Rt("content",t,e.content.length)},exports.validateUpdatePlatformConfigOptions=zl,exports.validateUpdateProfileData=Qs,exports.validateUpdateTokenConfigOptions=Mc,exports.validateUploadProfileImageOptions=Js,exports.validateUserTokenName=Ws,exports.validateVaultAddress=Gs,exports.vaultAddressSchema=kr,exports.wasModerationEscalated=function(e){return!0===e.escalatedFromQuick};