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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/EXAMPLES.md +3 -3
  3. package/MIGRATING-TO-9.0.md +1 -1
  4. package/dist/LaunchpadSDK.d.ts +15 -15
  5. package/dist/constants/version.generated.d.ts +1 -1
  6. package/dist/index.browser.esm.js +1 -1
  7. package/dist/index.cjs +1 -1
  8. package/dist/index.esm.js +1 -1
  9. package/dist/index.js +1 -1
  10. package/dist/native.cjs +1 -1
  11. package/dist/native.esm.js +1 -1
  12. package/dist/schemas/pagination.d.ts.map +1 -1
  13. package/dist/schemas/primitives.d.ts.map +1 -1
  14. package/dist/services/GalaChainLockService.d.ts +2 -2
  15. package/dist/services/GalaChainService.d.ts +1 -1
  16. package/dist/services/HolderService.d.ts +3 -3
  17. package/dist/services/MessagesService.d.ts +1 -1
  18. package/dist/services/OEmbedService.d.ts +3 -3
  19. package/dist/services/OverseerService.d.ts +1 -1
  20. package/dist/services/TradeService.d.ts +1 -1
  21. package/dist/services/WebSocketAdminService.d.ts +12 -12
  22. package/dist/services/WeeklyChallengeService.d.ts +2 -2
  23. package/dist/signing/signers.d.ts +1 -1
  24. package/dist/signing/signers.d.ts.map +1 -1
  25. package/dist/types/constraints.d.ts +1 -1
  26. package/dist/types/constraints.d.ts.map +1 -1
  27. package/dist/types/messages.dto.d.ts +1 -1
  28. package/dist/types/overseer.dto.d.ts +1 -1
  29. package/dist/types/session-auth.dto.d.ts +1 -1
  30. package/dist/types/session-auth.dto.d.ts.map +1 -1
  31. package/dist/types/trade.dto.d.ts +1 -1
  32. package/dist/types/trade.dto.d.ts.map +1 -1
  33. package/dist/types/user.dto.d.ts +1 -1
  34. package/dist/utils/address-formatter.d.ts +14 -2
  35. package/dist/utils/address-formatter.d.ts.map +1 -1
  36. package/dist/utils/string-patterns.d.ts +4 -4
  37. package/package.json +3 -3
@@ -1 +1 @@
1
- import{z as e}from"zod";import{computeAddress as t,getAddress as n,isAddress as s,BrowserProvider as r,Wallet as i}from"ethers";import{galaChainUserRef as a,GALA_CHAIN_ENVIRONMENTS as o,BrowserWalletSigner as c,generateEIP712Types as l,ethereumAddressOfAccount as d,GalaWalletSigner as u,withGalaWalletIdentity as h,PrivateKeySigner as g,isTokenClassKey as m,GatewayReads as f,isGalaError as p,GatewayWrites as v,tokenDetailsOf as A,isWalletUserRejection as E,walletDeclineCode as y,createWallet as T}from"@gala-chain/gala-core-sdk";import{PrivateKeyProvider as S,isPrivateKeyProvider as b}from"@gala-chain/gala-core-sdk/providers";import{ChainCallDTO as k,TokenClassKey as w}from"@gala-chain/api";import{v4 as N}from"uuid";import{io as _}from"socket.io-client";import I from"bignumber.js";import C,{AxiosHeaders as D}from"axios";const R={UPLOAD_IMAGE:"/v1/tokens/:tokenName/image",FETCH_POOLS:"/v1/tokens",GET_TOKEN:"/v1/tokens/:tokenName",GET_TOKEN_DISTRIBUTION:"/v1/holders",CHART:"/v1/chart",GET_TRADES:"/v1/tokens/:tokenName/trades",GET_PROFILE:"/v1/users/:address",UPDATE_PROFILE:"/v1/users/me",GET_CURRENT_USER:"/v1/users/me/profile",UPLOAD_PROFILE_IMAGE:"/v1/users/me/image",GET_TOKEN_LIST:"/v1/users/:address/tokens",GET_TOKENS_HELD:"/v1/users/:address/tokens",GET_GALA_BALANCE:"/v1/users/:address/gala-balance",GET_REFERRAL_CODE:"/v1/connect/users/referrals/code",GET_MANAGED_TOKENS:"/v1/users/me/managed-tokens",VALIDATE_TOKEN:"/v1/utils/validate-token",UPDATE_TOKEN_CONFIG:"/v1/tokens/:tokenName",TOKEN_STATS:"/v1/tokens/:tokenName/stats",OEMBED:"/oembed",OEMBED_BUY_SELL:"/oembed/buy-sell/:tokenName",OEMBED_PROFILE:"/oembed/profile/:address"},O="/v1/users/referrals/url",U="/v1/users/referrals",M="/v1/users/referrals/summary",F="/v1/tokens/:tokenName/start-stream",L="/v1/tokens/:tokenName/stop-stream",x="/v1/tokens/:tokenName/stream/disable",P="/v1/tokens/:tokenName/stream/enable",B="/v1/tokens/:tokenName/reset-key",$="/v1/tokens/:tokenName/recordings",G="/v1/tokens/:tokenName/recordings/:assetId/download",K="/v1/tokens/:tokenName/recordings/:assetId",W="/v1/tokens/:tokenName/simulcasts",H="/v1/tokens/:tokenName/simulcasts",j="/v1/tokens/:tokenName/simulcasts/:targetId",q="/v1/config",V="/v1/config",z="/v1/config",Q="/v1/tokens/:tokenName/role",X="/v1/roles",J="/v1/permissions",Y="/v1/tokens/:tokenName/credentials",Z="/auth/login",ee="/auth/logout",te="/auth/refresh",ne="/auth/session",se="/v1/tokens/:tokenName/bans",re="/v1/tokens/:tokenName/bans",ie="/v1/tokens/:tokenName/bans/:userAddress",ae="/v1/tokens/:tokenName/bans/:userAddress",oe="/v1/tokens/:tokenName/active-users",ce="/v1/user-bans",le="/v1/user-bans",de="/v1/user-bans/:userAddress",ue="/v1/user-bans/:userAddress",he={CREATE:"/v1/api-keys",LIST:"/v1/api-keys",GET:"/v1/api-keys/:id",UPDATE:"/v1/api-keys/:id",REVOKE:"/v1/api-keys/:id"},ge="/v1/moderator-invites",me="/v1/moderator-invites/claim",fe="/v1/moderated-tokens",pe="/v1/moderator-invites",ve="/v1/moderator-invites/:id",Ae="/v1/moderator-invites/:id/role",Ee="/v1/moderator-invites/:id",ye="/v1/moderator-invites/code/:code",Te={CREATE:"/v1/content-flags",LIST:"/v1/content-flags",DISMISS:"/v1/content-flags/:id/dismiss",ACTION:"/v1/content-flags/:id/action"},Se="/v1/overseer-invites",be="/v1/overseer-invites",ke="/v1/overseer-invites/code/:code",we="/v1/overseer-invites/claim",Ne="/v1/overseer-invites/:id",_e="/v1/overseers",Ie="/v1/overseers",Ce="/v1/overseers/:address",De="/v1/overseers/me",Re="/v1/overseer-summary",Oe="/v1/overseer-summary/bans",Ue="/v1/overseer-summary/token-bans",Me="/v1/overseer-summary/invites",Fe="/v1/overseer-summary/flags",Le="/v1/overseer-summary/users",xe="/v1/users",Pe="/v1/users/:address/summary",Be="/v1/cache/flush/address/:address",$e="/v1/cache/flush/token/:tokenName",Ge="/v1/cache/flush/all",Ke="/v1/cache/flush/wallet-aliases/:address",We="/v1/cache/flush/wallet-aliases",He="/v1/token-bans",je="/v1/token-bans",qe="/v1/token-bans/:tokenName",Ve="/v1/token-bans/:tokenName",ze="/v1/reactions",Qe="/v1/reactions",Xe="/v1/trades",Je={GET_MESSAGES:"/v1/messages",CREATE_MESSAGE:"/v1/messages",UPDATE_MESSAGE:"/v1/messages/:id",DELETE_MESSAGE:"/v1/messages/:id",GET_PINNED:"/v1/messages/pinned",PIN_MESSAGE:"/v1/messages/:id/pin",UNPIN_MESSAGE:"/v1/messages/:id/pin",GET_MESSAGE_STATS:"/v1/messages/stats"},Ye="/v1/restricted-token-names",Ze="/v1/restricted-token-names",et="/live/:tokenName/chat",tt="/live/:tokenName/chat",nt="/live/:tokenName/chat",st="/live/:tokenName/chat/slow-mode",rt="/v1/events",it="/v1/events/stats",at="/health",ot={GET_SETTINGS:"/v1/ai-moderation/settings",UPDATE_SETTINGS:"/v1/ai-moderation/settings",GET_MODERATION:"/v1/ai-moderation/flags/:flagId",TRIGGER_MODERATION:"/v1/ai-moderation/flags/:flagId/analyze",GET_STATUS:"/v1/ai-moderation/status"},ct="/v1/stats",lt="/v1/trading/fee",dt="/v1/trading/sale-details",ut="/v1/trading/quote",ht="/v1/trading/premint-quote",gt={GET_LEADERBOARD:"/weekly-challenge",GET_TOKEN_HISTORY:"/weekly-challenge/history/:vaultAddress"},mt="/v1/notifications/register",ft="/v1/notifications/unregister",pt="/v1/notifications/preferences",vt="/v1/notifications/preferences",At="/v1/config/client-flags",Et="native",yt="exact",Tt=["RECENT","POPULAR","RECORDINGS","SECONDS_STREAMED"],St=["IDLE","ACTIVE","DISABLED"],bt=100,kt="REQUIRED",wt="INVALID_TYPE",Nt="INVALID_VALUE",_t="INVALID_FORMAT",It="TOO_LONG",Ct="TOO_LARGE",Dt="INVALID_RANGE",Rt="INVALID_PARAMETERS";class Ot extends Error{constructor(e,t,n){super(e),this.field=t,this.code=n,this.name="ValidationError"}}function Ut(e){return"object"==typeof e&&null!==e}function Mt(e){if(null==e||""===e)return{};if(!Ut(e)||Array.isArray(e))return{body:e};const t=Reflect.get(e,"message"),n="string"==typeof t?t:Array.isArray(t)&&t.every(e=>"string"==typeof e)?t.join(","):void 0,s=Reflect.get(e,"error"),r=Reflect.get(e,"details");return{...void 0===n?{}:{serverMessage:n},..."string"==typeof s&&""!==s?{serverError:s}:{},...void 0===r?{}:{details:r},body:e}}function Ft(e){if(e instanceof Lt)return{...void 0===e.serverMessage?{}:{serverMessage:e.serverMessage},...void 0===e.serverError?{}:{serverError:e.serverError},...void 0===e.details?{}:{details:e.details},...void 0===e.body?{}:{body:e.body}};const t=function(e){if(!Ut(e))return;const t=Reflect.get(e,"response");return Ut(t)?t:void 0}(e);return void 0===t?{}:Mt(Reflect.get(t,"data"))}class Lt extends Error{constructor(e,t,n,s=Ft(n)){super(e),this.name="NetworkError",this.statusCode=t,this.originalError=n,this.serverMessage=s.serverMessage,this.serverError=s.serverError,this.details=s.details,this.body=s.body}}class xt extends Error{constructor(e,t){super(e),this.field=t,this.name="ConfigurationError"}}class Pt extends Error{constructor(e,t,n){super(e),this.transactionId=t,this.code=n,this.name="TransactionError"}}function Bt(e){return e instanceof Error}function $t(e){return Bt(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 Gt(e){return Bt(e)||"object"==typeof e&&null!==e&&"stack"in e&&"string"==typeof e.stack?e.stack:void 0}function Kt(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 Wt(e){return"object"==typeof e&&null!==e&&"message"in e&&("response"in e||"request"in e||"config"in e)}function Ht(e,t){if(null==e||"object"!=typeof e)throw new Error(`${t}: No response - expected object, got ${typeof e}`);const n=e;if(!("Status"in n))throw new Error(`${t}: Response missing 'Status' property`);const s=n.Status;if("number"!=typeof s)throw new Error(`${t}: Response Status must be a number, got ${typeof s}`);if(1!==s)throw new Error(`${t}: Response status indicates failure (Status: ${s})`);return n}function jt(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 qt(e,t){return void 0!==t?t:e.charAt(0).toUpperCase()+e.slice(1)}function Vt(e,t){return new Ot(`Token "${e}" not found. Please verify the token name is correct.`,"tokenName","TOKEN_NOT_FOUND")}function zt(e,t){const n=qt(e,t);return new Ot(`${n} is required`,e,"REQUIRED")}function Qt(e,t,n){const s=qt(e,n);return new Ot(`${s} must be ${t}`,e,"INVALID_FORMAT")}function Xt(e,t,n,s){return new Lt(e,t,n,s)}function Jt(e,t){return new xt(e,t)}function Yt(e,t,n){return new Pt(e,t,n)}function Zt(e,t,n,s,r){const i=qt(e,r);return new Ot(`${i} must be between ${t} and ${n}${void 0!==s?`, received: ${s}`:""}`,e,"OUT_OF_RANGE")}function en(e,t,n,s){const r=qt(e,s);return new Ot(`${r} must be at least ${t}${void 0!==n?`, received: ${n}`:""}`,e,"TOO_SMALL")}function tn(e,t,n,s){const r=qt(e,s);return new Ot(`${r} must be at most ${t}${void 0!==n?`, received: ${n}`:""}`,e,"TOO_LARGE")}function nn(e,t,n,s){const r=qt(e,s),i=void 0!==n?`, received: ${"object"==typeof n?"object":String(n)}`:"";return new Ot(`${r} must be ${t}${i}`,e,"INVALID_TYPE")}function sn(e,t,n){const s=qt(e,n);return new Ot(`${s} must be a valid number${void 0!==t?`: "${t}"`:""}`,e,"INVALID_NUMBER")}function rn(e,t,n,s){const r=qt(e,s);return new Ot(`Invalid ${r}: ${t}. Must be one of: ${n.join(", ")}`,e,"INVALID_ENUM")}function an(e){return null!=e&&"object"==typeof e&&"data"in e}function on(e,t,n=!1){const s=!0===e.error,r=n&&(null===e.data||void 0===e.data);if(s||r){const n=e?.statusCode??e.status??void 0;throw Xt(e?.message??t,n,void 0,s?Mt(e):void 0)}}function cn(e){if(an(e))return e.data}function ln(e,t="No data found in response"){if(!an(e))throw Xt(t);const n=e.data;if(null==n)throw Xt(t);return n}async function dn(e,t={}){return gn(e,t,e=>{if(void 0===e.data)throw new Ot(`${t.errorContext??"Operation failed"}: No data returned from API`,"data","NO_DATA");return e.data})}async function un(e,t={}){const{errorContext:n="Operation failed",logger:s,debugLogEnabled:r=!1}=t;r&&s&&s.debug(`${n}: starting operation`);try{const t=await e();return r&&s&&s.debug(`${n}: completed successfully`),t}catch(e){throw s&&s.error(n,{error:e}),e}}async function hn(e,t={}){return gn(e,t,e=>e)}async function gn(e,t,n){const{errorContext:s="Operation failed",logger:r,debugLogEnabled:i=!1}=t;i&&r&&r.debug(`${s}: starting operation`);try{const t=await e();if(null==t)throw new Ot(`${s}: No response from server`,"response","NO_RESPONSE");return on(t,s,!0),i&&r&&r.debug(`${s}: completed successfully`),n(t)}catch(e){throw r&&r.error(s,{error:e}),e}}const mn={BASE_PRICE:1650667151e-14,PRICE_SCALING_FACTOR:1166069e-12,TRADING_FEE_FACTOR:.001,GAS_FEE:"1",DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY:1e7};function fn(e){return e.trim().toLowerCase()}function pn(e){return e.trim().toUpperCase()}var vn;!function(e){e.DEBUG="DEBUG",e.INFO="INFO",e.WARN="WARN",e.ERROR="ERROR"}(vn||(vn={}));class An{constructor(e){this.levelPriority={[vn.DEBUG]:0,[vn.INFO]:1,[vn.WARN]:2,[vn.ERROR]:3},this.debugEnabled=e.debug,this.context=e.context??"SDK",this.minLevel=e.minLevel??(e.debug?vn.DEBUG:vn.INFO)}debug(e,t){this.log(vn.DEBUG,e,t)}info(e,t){this.log(vn.INFO,e,t)}warn(e,t){this.log(vn.WARN,e,t)}error(e,t){this.log(vn.ERROR,e,t)}log(e,t,n){if(this.levelPriority[e]<this.levelPriority[this.minLevel])return;if(e===vn.DEBUG&&!this.debugEnabled)return;const s=`[${(new Date).toISOString()}] [${this.context}] [${e}]`,r=this.getConsoleMethod(e);void 0!==n?Bt(n)?r(`${s} ${t}`,n.message,Gt(n)??""):r(`${s} ${t}`,n):r(`${s} ${t}`)}getConsoleMethod(e){switch(e){case vn.DEBUG:return console.debug;case vn.INFO:return console.info;case vn.WARN:return console.warn;case vn.ERROR:return console.error;default:return console.log}}child(e){return new An({debug:this.debugEnabled,context:`${this.context}:${e}`,minLevel:this.minLevel})}isDebugEnabled(){return this.debugEnabled&&this.levelPriority[vn.DEBUG]>=this.levelPriority[this.minLevel]}}function En(e){return"string"==typeof e&&e.trim().length>0}function yn(e){return null==e||""===e}function Tn(e){return null==e}const Sn=new An({debug:!1,context:"DateUtils"});function bn(e){if(null==e)return!1;if(e instanceof Date)return!isNaN(e.getTime());if("string"!=typeof e)return!1;const t=new Date(e);return!isNaN(t.getTime())}function kn(e,t="address"){try{if("string"==typeof e&&/^eth\|0x/iu.test(e))throw new Error("eth|0x is not an address form");return a(e,t)}catch{throw new Ot(`${t} 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(e)}")`,t,"INVALID_FORMAT")}}function wn(e,t="address"){return kn(e,t).toLowerCase()}function Nn(e,t){return Ln(e)??wn(e,t)}function _n(e){return Cn(e)?wn(e):e.trim().toLowerCase()}function In(e,t){const n=e=>Cn(e)?wn(e):e.toLowerCase();return n(e)===n(t)}function Cn(e){try{return kn(e),!0}catch{return!1}}class Dn{toBackendFormat(e){if(!En(e))throw new Ot("Address is required and must be a string","address","REQUIRED");return kn(e,"address")}toEthereumFormat(e){if(!En(e))throw new Ot("Backend address is required and must be a string","address","REQUIRED");if(!e.match(/^eth\|([0-9a-fA-F]{40})$/i))throw new Ot(`Invalid backend address format. Expected "eth|{40-hex-characters}" (\`eth|0x...\` is not a valid form). Got: "${e}"`,"address","INVALID_FORMAT");return`0x${e.substring(4)}`}normalizeInput(e){if(void 0!==e&&""!==e)return kn(e,"address")}normalizeForBackend(e){if(void 0!==e&&""!==e)return wn(e,"address")}isValid(e){return Cn(e)}assertValid(e,t="address"){if(!this.isValid(e))throw new Ot(`${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 En(e)&&Cn(e)?e.startsWith("client|")?"client":e.startsWith("eth|")?"backend":"ethereum":null}normalize(e){if(void 0!==e&&""!==e)return e.toLowerCase()}extractHex(e){const t=Cn(e)?kn(e):void 0;if(void 0!==t&&t.startsWith("eth|"))return t.substring(4).toLowerCase();throw new Ot(`Cannot extract hex from address: "${e}". Expected Ethereum or backend format.`,"address","INVALID_FORMAT")}}const Rn=new Dn;function On(e){return Rn.toBackendFormat(e)}function Un(e){return Rn.isValid(e)}const Mn=/^(eth\|[a-f0-9]{40}|client\|[a-f0-9]{24})$/;function Fn(e){return void 0!==Ln(e)}function Ln(e){if(!En(e))return;const t=e.trim(),n=/^[0-9a-fA-F]{24}$/u.test(t)?`client|${t}`:t;if(!Cn(n))return;const s=wn(n);return Mn.test(s)?s:void 0}function xn(e,t){if(!Fn(e))throw new Ot(`${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 Pn(e,t="address"){Rn.assertValid(e,t)}var Bn=Object.freeze({__proto__:null,AddressFormatter:Dn,assertBackendUserAddress:xn,assertValidWalletAddress:Pn,backendUserAddress:Ln,backendUserParam:Nn,backendUserRef:wn,isBackendUserAddress:Fn,isUserRef:Cn,isValidAddress:Un,normalizeAddressInput:function(e){return Rn.normalizeInput(e)},sameUserAddress:In,toBackendAddressFormat:On,userAddressFilter:_n,userRef:kn});function $n(e,t=0){if(yn(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 Gn(e,t=0){if(Tn(e))return t;if("number"==typeof e)return isNaN(e)?t:e;return $n(String(e).replace("%","").trim(),t)}function Kn(e,t=18){const n=$n(e,0);if(0===n)return"0";return n.toFixed(t).replace(/\.?0+$/,"")}function Wn(e){return Kn(e,8)}function Hn(e){return Kn(e,18)}function jn(e,t,n,s){if("number"!=typeof e)throw nn(s,"a number",e,s);if(e<t||e>n)throw Zt(s,t,n,e)}function qn(e,t,n){if("string"!=typeof e)throw nn(n,"a string",e,n);if(e.length>t)throw tn(n,t,e.length)}function Vn(e,t){if("number"!=typeof e)throw nn(t,"a number",e,t);if(!Number.isInteger(e))throw nn(t,"an integer",e,t);if(e<=0)throw en(t,1,e,t)}function zn(e,t,n=!1){if("string"!=typeof e)throw nn(t,"a string",e,t);if(!n&&0===e.trim().length)throw zt(t,`${t} (non-empty string)`)}const Qn={ETH_ADDRESS:/^0x[0-9a-fA-F]{40}$/,BACKEND_ADDRESS:/^eth\|[0-9a-fA-F]{40}$/},Xn=En,Jn=Tn;function Yn(e,t,n=100,s,r){if(void 0!==r&&"string"!=typeof r)throw new Ot("cursor must be a string","cursor",wt);const i=s??t,a=void 0!==s?"pageSize":"limit";if(void 0!==i&&(Vn(i,a),i>n))throw new Ot(`${a} must be at most ${n}`,a,Ct)}function Zn(e){const t=Object.values(e);return e=>"string"==typeof e&&t.includes(e)}function es(e){return Object.values(e)}function ts(e,t,n){if(!Xn(e))throw zt(t);const s=e.trim();if(0===s.length)throw zt(t);if(s.length<n.MIN_LENGTH)throw Zt(t,n.MIN_LENGTH,n.MAX_LENGTH,s.length,`${t} length`);if(s.length>n.MAX_LENGTH)throw Zt(t,n.MIN_LENGTH,n.MAX_LENGTH,s.length,`${t} length`);if(!n.PATTERN.test(s))throw new Ot(`${t} must be ${n.DESCRIPTION}`,t,_t)}function ns(e,t,n){if(null==e)throw zt(t,t);if("string"!=typeof e)throw nn(t,"a string",e);const s=e.trim();if(0===s.length)throw zt(t,t);if(!n.PATTERN.test(s))throw new Ot(`${t} must be ${n.DESCRIPTION}`,t,_t)}function ss(e){return""===e||0===e.trim().length}function rs(e,t,n){if(!Jn(e)){if("string"!=typeof e)throw nn(t,"a string",e,t);if(e.length>n)throw new Ot(`${t} must be at most ${n} characters`,t,Ct)}}function is(e,t){Jn(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 nn(t,"a date",e,t);if(isNaN(n.getTime()))throw new Ot(`${t} must be a valid date`,t,_t)}(e,t)}function as(e,t,n){try{Vn(e,t)}catch{throw function(e,t,n,s="OPERATION_FAILED"){return new Ot(`${e} failed: ${t}`,n,s)}(n,"must be a positive integer",t)}}function os(e,t,n="status"){void 0!==e&&function(e,t,n){const s=Object.values(t);if(!s.includes(e))throw new Ot(`${n} must be one of: ${s.join(", ")}`,n,_t)}(e,t,n)}class cs{constructor(e,t=!1,n){this.http=e,this.logger=new An({debug:t,context:this.constructor.name}),this.jwtAuth=n}setJwtAuth(e){this.jwtAuth=e}getJwtHeaders(){if(!this.jwtAuth){const e=globalThis;if("test"===e.process?.env?.NODE_ENV&&!this.isCalledFromUserCode())return{};throw new xt("JWT authentication required. Call sdk.login() first.")}return this.jwtAuth.getJwtHeaders()}isCalledFromUserCode(){const e=Gt(new Error)??"";return!(!e.includes("expect")&&!e.includes("jest"))||!(!e.includes("tests/")&&!e.includes(".test.ts"))}validatePositiveInteger(e,t,n){as(e,t,n)}}class ls{constructor(e=!1,t){this.logger=t||new An({debug:e,context:this.constructor.name})}}class ds extends ls{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 us extends ds{constructor(e=!1){super(e)}normalizeKey(e){return fn(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>=us.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??mn.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY.toString()}has(e){const t=this.normalizeKey(e);return this.cache.has(t)}clear(e){if(void 0!==e&&""!==e){const t=this.normalizeKey(e);this.cache.delete(t)}else super.clear()}dumpAsObject(){const e={};return this.cache.forEach((t,n)=>{e[n]=t}),e}getStats(){const e=this.buildBaseStats(),{cacheSize:t,oldestEntry:n}=this.calculateCacheSizeAndAge();return{...e,totalTokens:e.totalItems,cacheSize:t,oldestEntry:n}}calculateCacheSizeAndAge(){let e=Date.now(),t=0;return this.cache.forEach((n,s)=>{n.lastUpdated<e&&(e=n.lastUpdated);let r=0;r+=2*s.length,void 0!==n.reverseBondingCurveMinFeeFactor&&(r+=8),void 0!==n.reverseBondingCurveMaxFeeFactor&&(r+=8),void 0!==n.reverseBondingCurveNetFeeFactor&&(r+=8),r+=8,void 0!==n.vaultAddress&&""!==n.vaultAddress&&(r+=2*n.vaultAddress.length),void 0!==n.maxSupply&&""!==n.maxSupply&&(r+=2*n.maxSupply.length),void 0!==n.symbol&&""!==n.symbol&&(r+=2*n.symbol.length),r+=32,t+=r}),{cacheSize:t,oldestEntry:this.cache.size>0?e:0}}getByTokenId(e){const t=`token:${fn(e)}`;return this.cache.get(t)??null}setByTokenId(e,t){const n=`token:${fn(e)}`;this.updateCacheEntry(n,t)}hasByTokenId(e){const t=`token:${fn(e)}`;return this.cache.has(t)}}us.MAX_CACHE_SIZE=1e4;const hs={MIN_LENGTH:1,MAX_LENGTH:25,PATTERN:/^[a-zA-Z0-9]{1,25}$/,DESCRIPTION:"1-25 letters and digits"},gs={MIN_LENGTH:1,MAX_LENGTH:255,PATTERN:/^[a-zA-Z0-9]{1,255}$/,DESCRIPTION:"1-255 letters and digits"},ms={MIN_LENGTH:1,MAX_LENGTH:50,PATTERN:/^[\s\S]{1,50}$/,DESCRIPTION:"1-50 characters"},fs={MIN_LENGTH:1,MAX_LENGTH:100,PATTERN:/^(?![\s\S]*<[^>]*>)[\s\S]{1,100}$/,DESCRIPTION:"1-100 characters without HTML"},ps=100,vs=100,As=50,Es=100,ys={COMMENTS_V1:{MAX_LENGTH:2e3},CHAT_MESSAGES_V1:{MAX_LENGTH:500},BAN_REASON:{MAX_LENGTH:500},DESCRIPTION:{MAX_LENGTH:255},FLAG_DETAILS:{MAX_LENGTH:1e3},CONTENT_ID:{MAX_LENGTH:100}},Ts={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})$/}},Ss=60,bs=31536e3,ks={MAX_LENGTH:64,PATTERN:/^(galaswap-operation-|galaconnect-operation-)/},ws=64,Ns=1,_s=100,Is={FULL_NAME:{MIN_LENGTH:2,MAX_LENGTH:20,ALPHABETS_ONLY_PATTERN:/^[a-zA-Z]+(?: [a-zA-Z]+)?$/}},Cs=e.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"),Ds=Cs.max(25,"Token name must be at most 25 characters"),Rs=e.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"),Os=e.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"),Us=e.string({message:"Token description is required"}).min(1,"Token description is required").max(500,"Token description must be at most 500 characters"),Ms=e.string().min(1,"Token name must be at least 1 character").max(50,"Token name must be at most 50 characters"),Fs=e.string().min(1,"Search query must be at least 1 character").max(100,"Search query must be at most 100 characters"),Ls=e.string().min(1,"Full name is required").max(100,"Full name must be at most 100 characters").regex(/^[a-zA-Z\s]+$/,"Full name can only contain letters and spaces");e.string().regex(Qn.BACKEND_ADDRESS,"Address must be in format: eth|[40-hex-chars]"),e.string().regex(Qn.ETH_ADDRESS,"Invalid Ethereum address format");const xs=e.string().refine(e=>Cn(e),"Address must be eth|[40-hex], 0x[40-hex], [40-hex] or client|[identifier] (eth|0x... is not a valid form; a mixed-case address must carry its EIP-55 checksum)").transform(e=>kn(e)),Ps=e.string().refine(e=>/^eth\|(0x)?[0-9a-fA-F]{40}$/.test(e)||/^service\|Token\$Unit\$[A-Z0-9]+\$eth:[0-9a-fA-F]{40}\$launchpad$/.test(e),"Invalid vault address format"),Bs=e.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>$n(e,0)>0,"Amount must be greater than zero"),$s=e.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>$n(e,0)>=0,"Amount must be zero or greater");e.string().url("Must be a valid URL").regex(/^https?:\/\//,"URL must start with http:// or https://");const Gs=e.string().optional().refine(e=>void 0===e||""===e||/^https?:\/\/.+\..+/.test(e),"Must be a valid URL if provided");function Ks(t=100){return e.number().int("Limit must be an integer").min(1,"Limit must be at least 1").max(t,`Limit must be at most ${t}`).default(10)}e.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),Ks(100),Ks(20),Ks(20);const Ws=e.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"),Hs=e.string().max(255,"Filename must be at most 255 characters"),js=e.enum(["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"]);e.string().datetime("Must be a valid ISO 8601 date string"),e.number().int("Timestamp must be an integer").min(0,"Timestamp must be non-negative");const qs=e.string().regex(/^0x[a-fA-F0-9]{64}$/,"Private key must be format: 0x + 64 hex characters");e.string().regex(/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/,"Transaction ID must be in UUID format"),e.string().regex(/^galaconnect-operation-[a-z0-9-]+$/,"Unique key must be format: galaconnect-operation-{unique-id}");const Vs=[".png",".jpg",".jpeg",".gif",".webp",".svg"];e.object({file:e.union([e.instanceof(File),e.instanceof(Buffer)]),name:Hs,size:Ws,type:js});const zs=e.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"),Qs=e.instanceof(Buffer).refine(e=>e.length>=1&&e.length<=10485760,"Buffer size must be between 1 byte and 10MB");e.union([zs,Qs]),e.enum([".png",".jpg",".jpeg",".gif",".webp",".svg"]),Hs.refine(e=>{const t=e.slice(e.lastIndexOf(".")).toLowerCase();return Vs.includes(t)},`Filename must end with one of: ${Vs.join(", ")}`),e.object({websiteUrl:Gs,telegramUrl:Gs,twitterUrl:Gs,instagramUrl:Gs,facebookUrl:Gs,redditUrl:Gs,tiktokUrl:Gs}).refine(e=>void 0!==e.websiteUrl||void 0!==e.telegramUrl||void 0!==e.twitterUrl||void 0!==e.instagramUrl||void 0!==e.facebookUrl||void 0!==e.redditUrl||void 0!==e.tiktokUrl,"At least one social URL (website, telegram, twitter, instagram, facebook, reddit, or tiktok) is required");const Xs=e.string().min(1,"Token category must not be empty").default("Unit"),Js=e.string().min(1,"Token collection must not be empty").default("Token"),Ys=e.object({minFeePortion:e.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal string").refine(e=>$n(e,0)>=.1,"Minimum fee must be >= 0.1").refine(e=>$n(e,0)<=.5,"Minimum fee must be <= 0.5").default("0.1"),maxFeePortion:e.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal string").refine(e=>$n(e,0)>=.1,"Maximum fee must be >= 0.1").refine(e=>$n(e,0)<=.5,"Maximum fee must be <= 0.5").default("0.5")}).refine(e=>$n(e.maxFeePortion,0)>=$n(e.minFeePortion,0),{message:"Maximum fee must be >= minimum fee",path:["maxFeePortion"]}),Zs=e.object({tokenName:Cs,tokenSymbol:Os,tokenDescription:Us,tokenImage:e.union([e.instanceof(File),e.instanceof(Buffer),e.string().url("Token image must be a valid URL")]).optional(),preBuyQuantity:$s.default("0"),websiteUrl:Gs,telegramUrl:Gs,twitterUrl:Gs,instagramUrl:Gs,facebookUrl:Gs,redditUrl:Gs,tiktokUrl:Gs,tokenCategory:Xs,tokenCollection:Js,reverseBondingCurveConfiguration:Ys.optional(),saleStartTime:e.number().int().positive().optional(),privateKey:qs.optional()});e.object({file:e.union([e.instanceof(File),e.instanceof(Buffer)]),tokenName:Cs}),e.enum(Tt);const er=e.object({tokenName:Rs.optional(),symbol:Os.optional()}).refine(e=>void 0!==e.tokenName||void 0!==e.symbol,"At least one of tokenName or symbol is required");e.enum(["NATIVE","MEME"]),e.enum(["IN","OUT"]);const tr=e.object({from:e.number().int("From timestamp must be an integer").min(173e6,"From timestamp must be at least 173000000"),to:e.number().int("To timestamp must be an integer").min(173e6,"To timestamp must be at least 173000000"),resolution:e.number().int("Resolution must be an integer").min(1,"Resolution must be at least 1"),tokenName:Ds});e.object({tokenName:Ds,slippageToleranceFactor:e.number().min(0).max(1).optional(),maxAcceptableReverseBondingCurveFeeSlippageFactor:e.number().min(0).max(1).optional(),privateKey:qs.optional()});const nr=e.object({offset:e.number().int().min(0).default(0),pageSize:e.number().int().min(1).max(100).default(10)}),sr=e.object({offset:e.number().int().min(0).default(0),pageSize:e.number().int().min(1).max(20).default(10)}),rr=e.object({offset:e.number().int().min(0).default(0),pageSize:e.number().int().min(1).max(20).default(10)});nr.extend({type:e.enum(["RECENT","POPULAR"]).optional(),tokenName:e.string().min(1).max(50).optional(),search:e.string().min(1).max(100).optional()}),sr.extend({tokenName:e.string().min(1).max(50).optional(),search:e.string().min(1).max(100).optional()}),rr.extend({tradeType:e.enum(["BUY","SELL"]).optional(),tokenName:e.string().min(1).max(50).optional(),userAddress:e.string().refine(Cn,"userAddress must be eth|<40 hex>, 0x<40 hex>, <40 hex> or client|<id> (eth|0x... is not a valid form; a mixed-case address must carry its EIP-55 checksum)").optional(),startDate:e.string().datetime().optional(),endDate:e.string().datetime().optional(),sortOrder:e.enum(["ASC","DESC"]).default("DESC")});const ir={page:e.number().int().min(1),limit:e.number().int().min(1),total:e.number().int().min(0),totalPages:e.number().int().min(0),hasNext:e.boolean(),hasPrevious:e.boolean()};e.object(ir);const ar=e.enum(["buy","sell"]);e.enum(["BUY","SELL"]),e.object({tradeType:ar,tokenAmount:Bs,vaultAddress:Ps,userAddress:xs,slippageTolerance:Bs.optional(),deadline:e.number().int().positive().optional()}),e.object({tokenSymbol:Os,nativeTokenQuantity:Bs,expectedToken:Bs,maxAcceptableReverseBondingCurveFee:$s.default("0").optional()}),e.object({tokenSymbol:Os,tokenQuantity:Bs,expectedNativeToken:Bs,maxAcceptableReverseBondingCurveFee:$s.default("0").optional()}),rr.extend({tokenName:Ms.optional()}),e.object({page:e.number().int().min(1).max(1e3).default(1).optional(),limit:e.number().int().min(1).max(20).default(10).optional()});const or=e.enum(["NATIVE","MEME"]),cr=e.enum(["IN","OUT"]);e.object({type:or,method:cr,vaultAddress:Ps,amount:Bs}),e.object({nativeTokenQuantity:Bs}),e.object({vaultAddress:Ps}),e.object({minFeePortion:Bs,maxFeePortion:Bs});const lr=e.enum(["both","held","created"]);function dr(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)}}}sr.extend({type:lr.optional(),address:xs.optional(),search:Fs.optional(),tokenName:Ms.optional()}),e.object({address:xs.optional(),refresh:e.boolean().optional()}),e.object({profileImage:e.string().nullable().optional(),fullName:Ls.optional(),address:xs.optional(),privateKey:qs.optional()}),e.object({file:e.union([e.instanceof(File),e.instanceof(Buffer)]),address:xs.optional(),privateKey:qs.optional()}),e.object({address:xs,tokenId:e.union([e.string(),e.object({collection:e.string(),category:e.string(),type:e.string(),additionalKey:e.string()}),e.object({collection:e.string(),category:e.string(),type:e.string(),additionalKey:e.string(),instance:e.string()})]).optional(),tokenName:Ms.optional(),withExpired:e.boolean().optional()}).refine(e=>void 0!==e.tokenId||void 0!==e.tokenName,"At least one token identifier (tokenId or tokenName) is required");const ur=dr(Cs),hr=dr(Zs),gr=dr(er);function mr(e){const t=function(e){const t=hr(e);return t.success?[]:t.errors??["Unknown validation error"]}(e);if(t.length>0)throw new Error(`LaunchTokenData validation failed:\n${t.map(e=>`- ${e}`).join("\n")}`)}function fr(e,t){return"string"==typeof e[t]}function pr(e,t){return void 0===e[t]||"string"==typeof e[t]}function vr(e,t){return void 0===e[t]||"number"==typeof e[t]}function Ar(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}}Zn({BUY:"buy",SELL:"sell"});const Er=(yr={nativeTokenQuantity:"string"},e=>{if(null==e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;for(const[e,n]of Object.entries(yr))if(!Ar(t[e],n))return!1;return!0});var yr;function Tr(e,t="0"){return function(e,t="0"){if(yn(e))return new I(t);if(I.isBigNumber(e))return e.isNaN()?new I(t):e;try{const n=new I(e);return n.isNaN()||!n.isFinite()?new I(t):n}catch{return new I(t)}}(e,t)}function Sr(e,t){return void 0!==t?Tr(e).toFixed(t):Tr(e).toFixed()}function br(e){return Tr(e).isZero()}function kr(e,t){return Tr(e).isLessThan(Tr(t))}function wr(...e){e.forEach(e=>{if(e.isNaN())throw sn("value","NaN");if(!e.isFinite())throw tn("value","finite");if(e.isLessThanOrEqualTo(0))throw en("value","0",e.toString())})}function Nr(e,t,n="0"){const s=Tr(t);return br(s)?Tr(n):Tr(e).dividedBy(s)}const _r={calculateBuyWithExact(e,t){const n=$n(e),s=$n(t),{BASE_PRICE:r,PRICE_SCALING_FACTOR:i,TRADING_FEE_FACTOR:a,GAS_FEE:o}=mn,c=function(e,t){const n=Math.pow(10,t);return Math.ceil(e*n)/n}(r*(Math.exp((s+n)*i)-Math.exp(s*i))/i,8),l=Sr(Tr(c).multipliedBy(a));return{amount:c.toString(),reverseBondingCurveFee:"0",transactionFee:l,gasFee:o}},calculateBuyWithNative(e,t){const n=$n(e),s=$n(t),{BASE_PRICE:r,PRICE_SCALING_FACTOR:i,TRADING_FEE_FACTOR:a,GAS_FEE:o}=mn,c=Math.log(n*i/r+Math.exp(s*i))/i-s,l=Sr(Tr(c).multipliedBy(a));return{amount:c.toString(),reverseBondingCurveFee:"0",transactionFee:l,gasFee:o}},calculateSellWithExact(e,t,n,s,r){const i=$n(e),a=$n(t),o=$n(n),{BASE_PRICE:c,PRICE_SCALING_FACTOR:l,TRADING_FEE_FACTOR:d,GAS_FEE:u}=mn,h=c*(Math.exp(a*l)-Math.exp((a-i)*l))/l,g=Tr(h),m=s+a/o*(r-s),f=Sr(g.multipliedBy(m),8),p=Sr(g.multipliedBy(d));return{amount:h.toString(),reverseBondingCurveFee:f,transactionFee:p,gasFee:u}},calculateSellWithNative(e,t,n,s,r){const i=$n(e),a=$n(t),o=$n(n),{BASE_PRICE:c,PRICE_SCALING_FACTOR:l,TRADING_FEE_FACTOR:d,GAS_FEE:u}=mn;if(i>=c*(Math.exp(a*l)-1)/l){const e=Tr(i),t=s+a/o*(r-s),n=Sr(e.multipliedBy(t),8),c=Sr(e.multipliedBy(d));return{amount:a.toString(),reverseBondingCurveFee:n,transactionFee:c,gasFee:u}}const h=a-Math.log(Math.exp(a*l)-i*l/c)/l,g=Tr(i),m=s+a/o*(r-s),f=Sr(g.multipliedBy(m),8),p=Sr(g.multipliedBy(d));return{amount:h.toString(),reverseBondingCurveFee:f,transactionFee:p,gasFee:u}}};function Ir(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Cr(e,t){if(!function(e){if(!Ir(e)||"string"!=typeof e.calculatedQuantity)return!1;const t=e.extraFees;return Ir(t)&&"string"==typeof t.reverseBondingCurve&&"string"==typeof t.transactionFees}(e))throw Xt(`Malformed trade quote from the launchpad backend (${t})`);return{amount:e.calculatedQuantity,reverseBondingCurveFee:e.extraFees.reverseBondingCurve,transactionFee:e.extraFees.transactionFees,gasFee:mn.GAS_FEE}}class Dr{validate(e,t={}){const{allowZero:n=!0,minimum:s,maximum:r,maxDecimals:i=Dr.MAX_DECIMAL_PLACES,fieldName:a="amount"}=t;if(!Xn(e))throw new Ot(`${a} cannot be empty or whitespace-only. Provide a valid numeric string.`,a,"INVALID_NUMERIC_STRING");if(/[eE]/.test(e))throw new Ot(`${a} cannot use scientific notation. Use standard decimal format (e.g., "1000" instead of "1e3").`,a,"INVALID_NUMERIC_STRING");const o=$n(e,NaN);if(isNaN(o))throw new Ot(`${a} must be a valid numeric string. Received: "${e}"`,a,"INVALID_NUMERIC_STRING");if(!isFinite(o))throw new Ot(`${a} must be a finite number. Cannot be Infinity or -Infinity.`,a,"INVALID_NUMERIC_STRING");if(o<0)throw new Ot(`${a} must be non-negative. Received: "${e}"`,a,"INVALID_NUMERIC_STRING");if(!n&&0===o)throw new Ot(`${a} must be greater than zero. Received: "${e}"`,a,"INVALID_NUMERIC_STRING");const c=Tr(e),l=c.decimalPlaces()??0;if(l>i)throw new Ot(`${a} cannot exceed ${i} decimal places. Received: ${l} decimal places`,a,"PRECISION_EXCEEDED");if(void 0!==s&&kr(c,s))throw new Ot(`${a} must be at least ${s}. Received: "${e}"`,a,"BELOW_MINIMUM");if(void 0!==r&&(d=r,Tr(c).isGreaterThan(Tr(d))))throw new Ot(`${a} cannot exceed ${r}. Received: "${e}"`,a,"EXCEEDS_MAXIMUM");var d}parseAmount(e,t="0"){return Tr(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 Sr(e,t)}clampAmount(e,t,n){const s=Tr(e),r=Tr(t),i=Tr(n);return function(e,t,n){const s=Tr(e),r=Tr(t),i=Tr(n);return s.isGreaterThanOrEqualTo(r)&&s.isLessThanOrEqualTo(i)}(s,r,i)?Sr(s):kr(s,r)?Sr(r):Sr(i)}}function Rr(e,t){throw new Ot(e.join("; "),t,"VALIDATION_ERROR")}function Or(e){const t=ur(e);!t.success&&t.errors&&Rr(t.errors,"tokenName")}function Ur(e){const t=tr.safeParse(e);var n;t.success||Rr((n=t.error.issues,Array.isArray(n)?n.map(e=>null!=e&&"object"==typeof e&&"message"in e&&"string"==typeof e.message?e.message:String(e)).filter(e=>""!==e):[]),"options")}function Mr(e,t,n=!0){Fr.validate(e,{fieldName:t,allowZero:n})}Dr.MAX_DECIMAL_PLACES=18,Dr.MIN_POSITIVE="0.00000000000000001";const Fr=new Dr;class Lr{constructor(e,t,n,s="local",r){this.http=e,this.logger=t,this.bundleHttp=n,this.defaultCalculateAmountMode=s,this.launchpadWrites=r,this.metadataCache=new us}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 Qt("options","an options object");const{tokenName:t,amount:n,type:s,currentSupply:r}=e;return"external"===this.validateAmountCalculationInputs(t,n,s,e.mode,[Et,yt],'"native" or "exact"')?this.calculateBuyAmountExternal({tokenName:t,amount:n,type:s}):this.calculateBuyAmountLocal(this.addIfDefined({tokenName:t,amount:n,type:s},"currentSupply",r))}async calculateBuyAmountExternal(e){const{tokenName:t,amount:n,type:s}=e;return this.validateExternalAmountInputs(t,n),"exact"===s?this.fetchBackendQuote({tokenName:t,amount:n,type:"MEME",method:"OUT"},`Failed to calculate buy amount for ${t} (exact tokens)`):this.fetchBackendQuote({tokenName:t,amount:n,type:"NATIVE",method:"IN"},`Failed to calculate buy amount for ${t} (native/GALA budget)`)}async fetchBackendQuote(e,t){return Cr(await dn(()=>this.http.get(ut,{...e}),{errorContext:t}),t)}async calculateSellAmount(e){const{tokenName:t,amount:n,type:s,currentSupply:r,maxSupply:i,reverseBondingCurveMaxFeeFactor:a,reverseBondingCurveMinFeeFactor:o}=e;if("external"===this.validateAmountCalculationInputs(t,n,s,e.mode,[yt,Et],'"exact" or "native"'))return this.calculateSellAmountExternal({tokenName:t,amount:n,type:s});{const e={tokenName:t,amount:n,type:s,...void 0!==r&&{currentSupply:r},...void 0!==i&&{maxSupply:i},...void 0!==a&&{reverseBondingCurveMaxFeeFactor:a},...void 0!==o&&{reverseBondingCurveMinFeeFactor:o}};return this.calculateSellAmountLocal(e)}}async calculateSellAmountExternal(e){const{tokenName:t,amount:n,type:s}=e;return this.validateExternalAmountInputs(t,n),"exact"===s?this.fetchBackendQuote({tokenName:t,amount:n,type:"MEME",method:"IN"},`Failed to calculate sell amount for ${t} (exact tokens)`):this.fetchBackendQuote({tokenName:t,amount:n,type:"NATIVE",method:"OUT"},`Failed to calculate sell amount for ${t} (native/GALA target)`)}async calculateBuyAmountLocal(e){const{tokenName:t,amount:n,type:s,currentSupply:r}=e;if(!Xn(n))throw zt("amount","Amount");if(s!==Et&&s!==yt)throw nn("type",'"native" or "exact"',s);void 0!==r&&Mr(r,"currentSupply");const i=null==r||""===r;if(i&&(null==t||""===t))throw zt("tokenName","Token name (required when currentSupply is not provided)");null!=t&&""!==t&&Or(t);let a=r;if(i){a=(await this.fetchPoolDetailsForCalculation(t)).currentSupply}return s===yt?_r.calculateBuyWithExact(n,a):_r.calculateBuyWithNative(n,a)}async calculateSellAmountLocal(e){const{tokenName:t,amount:n,type:s,currentSupply:r,maxSupply:i,reverseBondingCurveMaxFeeFactor:a,reverseBondingCurveMinFeeFactor:o}=e;if(!Xn(n))throw zt("amount","Amount");if(s!==yt&&s!==Et)throw nn("type",'"exact" or "native"',s);void 0!==r&&Mr(r,"currentSupply");const c=null==r||""===r||null==i||""===i||void 0===a||void 0===o;if(c&&(null==t||""===t))throw zt("tokenName","Token name (required when currentSupply, maxSupply, or fee factors are not provided)");null!=t&&""!==t&&Or(t);let l=r,d=i,u=a,h=o;if(c&&null!=t&&""!==t){const e=this.metadataCache.getByName(t);d=d??this.metadataCache.getMaxSupply(t),u=u??e?.reverseBondingCurveMaxFeeFactor,h=h??e?.reverseBondingCurveMinFeeFactor,null!=l&&""!==l||(l=await this.fetchCurrentSupply(t));if(void 0===u||void 0===h){const e=await this.fetchPoolDetailsForCalculation(t);u=u??e.reverseBondingCurveMaxFeeFactor,h=h??e.reverseBondingCurveMinFeeFactor}}return s===yt?_r.calculateSellWithExact(n,l,d,h,u):_r.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 fr(t,"tokenName")&&function(e){return void 0===e.calculateAmountMode||"local"===e.calculateAmountMode||"external"===e.calculateAmountMode}(t)&&pr(t,"currentSupply")}(e))throw nn("options","CalculateBuyAmountForGraduationOptions or string (token name)",typeof e);const{tokenName:n,calculateAmountMode:s,currentSupply:r}=t;Or(n);const i=await this.fetchSaleDetails(n),a=r??Sr(Tr(i.maxSupply).minus(i.sellingTokenQuantity)),o=i.sellingTokenQuantity;if("0"===o)throw zt("tokenName",`Token ${n} is already graduated (no tokens remaining in pool)`);const c={tokenName:n,amount:o,type:"exact",currentSupply:a,...void 0!==s&&{mode:s}};return{...await this.calculateBuyAmount(c),remainingTokens:o}}async launchToken(e){if(void 0!==this.launchpadWrites){return(await this.launchpadWrites.createSale(e)).bundleId}if(!this.bundleHttp)throw Jt("Bundle backend client not configured. LaunchToken requires bundleHttp client.","bundleHttp");mr(e);const t=void 0!==e.preBuyQuantity&&""!==e.preBuyQuantity?e.preBuyQuantity:"0",n=$n(t);if(0===n&&"0"!==t)throw sn("preBuyQuantity",t,"Pre-buy quantity");if(n<0)throw sn("preBuyQuantity",t,"Pre-buy quantity");if(e.reverseBondingCurveConfiguration){const{minFeePortion:t,maxFeePortion:n}=e.reverseBondingCurveConfiguration;!function(e,t,n){const s="string"==typeof e?parseFloat(e):e,r="string"==typeof t?parseFloat(t):t;if(!isFinite(s))throw new Ot(`${n} minFee must be a valid finite number`,n,"INVALID_FEE_MINIMUM");if(!isFinite(r))throw new Ot(`${n} maxFee must be a valid finite number`,n,"INVALID_FEE_MAXIMUM");if(s<.1)throw new Ot(`${n} minFee must be >= 0.1, received ${s}`,n,"INVALID_FEE_MINIMUM");if(r>.5)throw new Ot(`${n} maxFee must be <= 0.5, received ${r}`,n,"INVALID_FEE_MAXIMUM");if(s>r)throw new Ot(`${n} minFee (${s}) must be <= maxFee (${r})`,n,"INVALID_FEE_RANGE")}(t,n,"reverseBondingCurve")}throw new Error("Legacy launchToken signing is unavailable; configure the v6 launchpad write transport.")}async calculateInitialBuyAmount(e){if(!Er(e))throw Qt("data","valid pre-mint calculation data");const t="Failed to calculate initial buy amount";return Cr(await dn(()=>this.http.get(ht,{amount:e.nativeTokenQuantity}),{errorContext:t}),t)}async fetchPoolDetailsForCalculation(e){const t=await this.fetchSaleDetails(e),n=Sr(Tr(t.maxSupply).minus(t.sellingTokenQuantity)),s=t.sellingTokenQuantity,r=t.maxSupply;let i=.5,a=.1;const o=t.reverseBondingCurveConfiguration;null!=o?.maxFeePortion&&(i=Gn(o.maxFeePortion,.5)),null!=o?.minFeePortion&&(a=Gn(o.minFeePortion,.1)),void 0===o&&this.logger.debug(`Pool details missing reverse bonding curve configuration for token ${e}, using defaults (min: 0.1, max: 0.5)`);const c=i-a;return this.metadataCache.set(e,{maxSupply:r,reverseBondingCurveMaxFeeFactor:i,reverseBondingCurveMinFeeFactor:a,reverseBondingCurveNetFeeFactor:c}),{currentSupply:n,remainingTokens:s,maxSupply:r,reverseBondingCurveMaxFeeFactor:i,reverseBondingCurveMinFeeFactor:a,reverseBondingCurveNetFeeFactor:c}}async fetchCurrentSupply(e){Or(e);const t=await this.fetchSaleDetails(e),n=Sr(Tr(t.maxSupply).minus(t.sellingTokenQuantity)),s=t.maxSupply;return this.metadataCache.set(e,{maxSupply:s}),n}async fetchPoolDetails(e){Or(e);const t=await this.fetchSaleDetails(e),{reverseBondingCurveConfiguration:n,...s}=t,r=n?.minFeePortion??"0",i=n?.maxFeePortion??"0";return{...s,reverseBondingCurveMinFeePortion:r,reverseBondingCurveMaxFeePortion:i,hasReverseBondingCurveFee:!br(r)||!br(i),isGraduated:"Finished"===t.saleStatus}}async fetchSaleDetails(e){return ts(e,"tokenName",hs),dn(()=>this.http.get(dt,{tokenName:e}),{errorContext:`Failed to fetch sale details for ${e}`})}validateAmountCalculationInputs(e,t,n,s,r,i){const a=s??this.defaultCalculateAmountMode;if("local"!==a&&"external"!==a)throw nn("mode",'"local" or "external"',a);if(!Xn(e))throw zt("tokenName","Token name");if(!Xn(t))throw zt("amount","Amount");if("string"!=typeof n||!r.includes(n))throw nn("type",i,n);return a}validateExternalAmountInputs(e,t){if("string"!=typeof e||""===e)throw new Ot("Token name must be a non-empty string","tokenName","INVALID_TOKEN_NAME");if("string"!=typeof t||""===t)throw new Ot("Amount must be a non-empty string","amount","INVALID_AMOUNT")}getAddress(){return this.http.getAddress()}formatAddressForBackend(e){return On(e)}validateTokenName(e){return Or(e)}validatePagination(e){void 0!==e.pageSize&&Yn(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 xr=3e5,Pr="Sign in to Launchpad t:",Br="Authorization",$r="Bearer ";class Gr{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 Kr;!function(e){e.WALLET_NOT_CONNECTED="WALLET_NOT_CONNECTED",e.SIGNATURE_FAILED="SIGNATURE_FAILED",e.INVALID_ADDRESS="INVALID_ADDRESS",e.MESSAGE_GENERATION_FAILED="MESSAGE_GENERATION_FAILED"}(Kr||(Kr={}));class Wr extends Error{constructor(e,t,n,s){super(t),this.type=e,this.originalError=n,this.statusCode=s,this.name="AuthError"}}class Hr{constructor(e,t=xr){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 Gr,this.refreshThresholdMs=t}setToken(e,t){if(!Xn(e))throw new Wr(Kr.SIGNATURE_FAILED,"JWT token must be a non-empty string");if("number"!=typeof t)throw new Wr(Kr.SIGNATURE_FAILED,"Token expiration must be a positive finite number (seconds)");if(!Number.isFinite(t))throw new Wr(Kr.SIGNATURE_FAILED,"Token expiration must be a positive finite number (seconds)");if(t<=0)throw new Wr(Kr.SIGNATURE_FAILED,"Token expiration must be a positive finite number (seconds)");const n=Date.now();this.tokenState={token:e.trim(),issuedAt:n,expiresAt:n+1e3*t},this.storage.set(this.STORAGE_KEYS.ACCESS_TOKEN,e.trim()),this.storage.set(this.STORAGE_KEYS.ACCESS_EXPIRES,String(this.tokenState.expiresAt))}async setTokens(e,t,n,s){if(this.setToken(e,t),n){const e=Date.now()+1e3*(s??7776e3);if(!this.tokenState)throw new Wr(Kr.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:`${$r}${e}`}getJwtHeaders(){const e=this.getAuthorizationHeader();if(null===e||""===e)throw new Wr(Kr.WALLET_NOT_CONNECTED,"No JWT token available. Call login() first.");return{[Br]:e}}async getRefreshToken(){if(!this.tokenState?.refreshToken){const e=await this.storage.get(this.STORAGE_KEYS.REFRESH_TOKEN),t=await this.storage.get(this.STORAGE_KEYS.REFRESH_EXPIRES);if(e&&t){const n=Number(t);if(Number.isFinite(n)&&Date.now()<n)return e}return null}return null!==this.tokenState.refreshExpiresAt&&void 0!==this.tokenState.refreshExpiresAt&&(!Number.isFinite(this.tokenState.refreshExpiresAt)||Date.now()>=this.tokenState.refreshExpiresAt)?null:this.tokenState.refreshToken??null}async restoreFromStorage(){const e=await this.storage.get(this.STORAGE_KEYS.ACCESS_TOKEN),t=await this.storage.get(this.STORAGE_KEYS.ACCESS_EXPIRES);if(!e||!t)return!1;const n=Number(t);if(!Number.isFinite(n)||Date.now()>=n)return!1;const s=Date.now();this.tokenState={token:e,issuedAt:s,expiresAt:n};const r=await this.storage.get(this.STORAGE_KEYS.REFRESH_TOKEN),i=await this.storage.get(this.STORAGE_KEYS.REFRESH_EXPIRES);if(r&&i){const e=Number(i);Number.isFinite(e)&&Date.now()<e&&(this.tokenState.refreshToken=r,this.tokenState.refreshExpiresAt=e)}return!0}async clear(){this.tokenState=null,await this.storage.remove(this.STORAGE_KEYS.ACCESS_TOKEN),await this.storage.remove(this.STORAGE_KEYS.ACCESS_EXPIRES),await this.storage.remove(this.STORAGE_KEYS.REFRESH_TOKEN),await this.storage.remove(this.STORAGE_KEYS.REFRESH_EXPIRES)}isValid(){return this.hasToken()&&!this.isExpired()}getDebugInfo(){return{hasToken:this.hasToken(),isExpired:this.isExpired(),shouldRefresh:this.shouldRefresh(),timeUntilExpiryMs:this.getTimeUntilExpiry(),expiresAt:this.tokenState?new Date(this.tokenState.expiresAt):null}}}class jr extends Hr{getJwtHeaders(){return{}}}async function qr(e,t,n,s){try{return await e()}catch(e){throw s?(s(e,t,n),new Error("Unreachable after error handler")):(n&&n.error(`${t}:`,e),function(e,t,n){n&&n.error(`${t}:`,e);const s=(Wt(e)?e.response?.status:void 0)??(e instanceof Lt?e.statusCode:void 0);return Xt(`${t}: ${$t(e)}`,s,Bt(e)?e:void 0)}(e,t,n))}}function Vr(e,t){return t instanceof Wr?t:new Wr(Kr.SIGNATURE_FAILED,`${e}: ${$t(t)}`,Bt(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 zr{constructor(e,t,n,s=!1,r){this.http=e,this.signatureAuth=t,this.jwtAuth=n,this.session=r,this.refreshPromise=null,this.loginPromise=null,this.logger=new An({debug:s,context:"SessionAuthService"})}async loginWithSignature(e){const t=kn(e.address,"address");if(!Xn(e.message)||!Xn(e.signature))throw new Wr(Kr.SIGNATURE_FAILED,"A login needs the signed message and its signature.");const n={address:t,message:e.message,signature:e.signature,...void 0!==e.publicKey&&{publicKey:e.publicKey},...void 0!==this.session&&{cookieSession:!0}};return this.postLogin(n)}async loginWithDevBypass(e){return this.postLogin({address:kn(e,"address"),...void 0!==this.session&&{cookieSession:!0}})}async postLogin(e){try{const t=await this.http.request({method:"POST",url:Z,data:e,withSession:!1}),n=this.extractLoginData(t);return void 0===this.session&&await this.jwtAuth.setTokens(n.accessToken,n.expiresIn,n.refreshToken,n.refreshExpiresIn),n}catch(e){throw Vr("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 Wr(Kr.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 qr(async()=>{const e=Date.now(),t=`${Pr}${e}`;this.logger.debug("Generating login signature",{message:t,timestamp:e});const n=await this.signatureAuth.signMessage(t),s=kn(this.signatureAuth.getAddress(),"address"),r={address:s,message:t,signature:n.signature};this.logger.debug("Sending login request",{address:s,message:t});const i=await this.http.post(Z,r),a=this.extractLoginData(i);return await this.jwtAuth.setTokens(a.accessToken,a.expiresIn,a.refreshToken,a.refreshExpiresIn),this.logger.debug("Login successful",{address:a.address,expiresIn:a.expiresIn,hasRefreshToken:!!a.refreshToken}),a},"SessionAuthService.performLogin",this.logger,e=>{if(e instanceof Wr)throw e;throw new Wr(Kr.SIGNATURE_FAILED,`Login failed: ${$t(e)}`,Bt(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 Wr(Kr.WALLET_NOT_CONNECTED,"No token to refresh. Call login() first.");this.refreshPromise=this.performRefresh();try{return await this.refreshPromise}finally{this.refreshPromise=null}}async performCookieRefresh(){try{const e=await this.http.request({method:"POST",url:te,data:{},withSession:!1});return this.extractLoginData(e)}catch(e){throw Vr("Token refresh failed",e)}}async performRefresh(){return qr(async()=>{this.logger.debug("Refreshing JWT token");const e=await this.jwtAuth.getRefreshToken();if(e){this.logger.debug("Using refresh token flow");const t=await this.http.post(te,{refreshToken:e}),n=this.extractLoginData(t);return await this.jwtAuth.setTokens(n.accessToken,n.expiresIn,n.refreshToken,n.refreshExpiresIn),this.logger.debug("Token refreshed successfully via refresh token",{address:n.address,expiresIn:n.expiresIn,hasNewRefreshToken:!!n.refreshToken}),n}this.logger.debug("Using legacy access token refresh");const t=await this.http.post(te,{},this.jwtAuth.getJwtHeaders()),n=this.extractLoginData(t);return this.jwtAuth.setToken(n.accessToken,n.expiresIn),this.logger.debug("Token refreshed successfully via access token",{address:n.address,expiresIn:n.expiresIn}),n},"SessionAuthService.performRefresh",this.logger,e=>{if(e instanceof Wr)throw e;throw new Wr(Kr.SIGNATURE_FAILED,`Token refresh failed: ${$t(e)}`,Bt(e)?e:void 0)})}async logout(e){this.logger.debug("Logging out",{allDevices:e?.allDevices});const t=e?.allDevices??!1;if(void 0!==this.session){const n=e?.accessToken??null;try{await this.http.request({method:"POST",url:ee,data:{allDevices:t},withSession:!1,...null!==n&&""!==n&&{headers:{Authorization:`${$r}${n}`}}})}catch(e){throw Vr("Logout failed",e)}return}if(t&&this.jwtAuth.hasToken()&&!this.jwtAuth.isExpired())try{await this.http.post(ee,{allDevices:!0},this.jwtAuth.getJwtHeaders()),this.logger.debug("Logged out from all devices")}catch(e){this.logger.warn(`Failed to revoke all-device sessions (server-side revocation may be incomplete): ${$t(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 Wr(Kr.WALLET_NOT_CONNECTED,"Not authenticated. Call login() first.");return qr(async()=>{const e=await this.http.get(ne,void 0,this.jwtAuth.getJwtHeaders());return this.extractSessionData(e)},"SessionAuthService.getSession",this.logger,e=>{if(e instanceof Wr)throw e;throw new Wr(Kr.SIGNATURE_FAILED,`Failed to get session: ${$t(e)}`,Bt(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 Wr(Kr.WALLET_NOT_CONNECTED,"The app session has no access token.");return e}if(!this.jwtAuth.hasToken())throw new Wr(Kr.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: ${$t(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 Wr(Kr.SIGNATURE_FAILED,""!==$t(e)?$t(e):"Authentication failed");const t=ln(e,"No data in authentication response"),{accessToken:n,expiresIn:s,address:r,refreshToken:i,refreshExpiresIn:a}=t;if(!Xn(n))throw new Wr(Kr.SIGNATURE_FAILED,"Invalid access token in response");if("number"!=typeof s||s<=0)throw new Wr(Kr.SIGNATURE_FAILED,"Invalid expiration in response");return{accessToken:n,expiresIn:s,address:r,...void 0!==i&&{refreshToken:i},...void 0!==a&&{refreshExpiresIn:a}}}extractSessionData(e){if(e.error)throw new Wr(Kr.SIGNATURE_FAILED,""!==$t(e)?$t(e):"Failed to get session");return ln(e,"No data in session response")}}class Qr{constructor(e){if(this.wallet=e.wallet,e.walletProvider?this.walletProvider=e.walletProvider:e.wallet,this.messagePrefix=e.messagePrefix??"Create a GalaChain Wallet",void 0!==e.messagePrefix)try{zn(e.messagePrefix,"messagePrefix",!1)}catch{throw new Wr(Kr.SIGNATURE_FAILED,"Message prefix cannot be empty")}}hasWallet(){return void 0!==this.walletProvider||void 0!==this.wallet}ensureWalletProvider(){if(this.wallet&&!this.walletProvider)try{this.walletProvider=S.fromWallet(this.wallet),this.cachedAddress=this.wallet.address,this.cachedGalaAddress=On(this.wallet.address)}catch(e){if(e instanceof Wr)throw e;if(e instanceof Ot&&("INVALID_ADDRESS"===e.code||"INVALID_FORMAT"===e.code||"address"===e.field))throw new Wr(Kr.INVALID_ADDRESS,e.message);if(null!==e&&"object"==typeof e&&"message"in e)throw new Wr(Kr.WALLET_NOT_CONNECTED,e.message);throw e}}setWallet(e){if(void 0!==e){if("object"!=typeof e||!("address"in e))throw new Wr(Kr.WALLET_NOT_CONNECTED,"Invalid wallet: must be an ethers Wallet instance or undefined");if("string"!=typeof e.address||""===e.address)throw new Wr(Kr.INVALID_ADDRESS,"Wallet address is not available");this.walletProvider=S.fromWallet(e),this.cachedAddress=e.address,this.cachedGalaAddress=On(e.address)}else this.walletProvider=void 0,this.cachedAddress=void 0,this.cachedGalaAddress=void 0;this.wallet=e}setWalletProvider(e){this.walletProvider=e,this.wallet=void 0;const n=void 0!==e&&b(e)?t(e.exportPrivateKey()):void 0;this.cachedAddress=n,this.cachedGalaAddress=void 0===n?void 0:On(n)}getWalletProvider(){return this.walletProvider}async cacheAddress(){this.walletProvider&&(this.cachedAddress=await this.walletProvider.getAddress(),this.cachedGalaAddress=kn(await this.walletProvider.getGalaAddress(),"address"))}async generateSignature(){await this.validateWalletAsync();try{const e=Date.now(),t=`${this.messagePrefix} ${e}`,n=await this.walletProvider.signMessage(t);return{message:t,signature:n,address:await this.walletProvider.getGalaAddress(),timestamp:e}}catch(e){if(e instanceof Wr)throw e;throw new Wr(Kr.SIGNATURE_FAILED,"Failed to generate signature for authentication",Bt(e)?e:new Error($t(e)))}}getAddress(){if(this.validateWallet(),this.cachedGalaAddress)return this.cachedGalaAddress;if(this.wallet)return this.formatAddress(this.wallet.address);throw new Wr(Kr.WALLET_NOT_CONNECTED,"Address not available. For external wallets, call cacheAddress() after connecting.")}async getAddressAsync(){return await this.validateWalletAsync(),kn(await this.walletProvider.getGalaAddress(),"address")}getEthereumAddress(){if(this.validateWallet(),this.cachedAddress)return this.cachedAddress;if(this.wallet)return this.wallet.address;throw new Wr(Kr.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 Wr(Kr.WALLET_NOT_CONNECTED,"Wallet private key not available for @gala-chain signing");return this.wallet.privateKey}if(void 0!==this.walletProvider&&b(this.walletProvider))return this.walletProvider.exportPrivateKey();throw new Wr(Kr.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 Wr(Kr.WALLET_NOT_CONNECTED,"Private key not available with this wallet provider");try{return await this.walletProvider.getPrivateKey()}catch(e){throw new Wr(Kr.WALLET_NOT_CONNECTED,"Private key not available. External wallet providers cannot access private keys. Use PrivateKeyProvider for @gala-chain signing operations.",Bt(e)?e:void 0)}}formatAddress(e){try{return On(e)}catch{throw new Wr(Kr.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 Wr)throw e;throw new Wr(Kr.SIGNATURE_FAILED,$t(e),Bt(e)?e:new Error($t(e)))}}async generateAuthHeaders(e,t){await this.validateWalletAsync();try{const n=Date.now(),s=`${this.messagePrefix} ${t.toUpperCase()} ${e} ${n}`,r=await this.walletProvider.signMessage(s);return{"x-signature":r,"x-address":await this.walletProvider.getGalaAddress(),"x-message":s,"x-timestamp":n.toString()}}catch(e){if(e instanceof Wr)throw e;throw new Wr(Kr.SIGNATURE_FAILED,"Failed to generate authentication headers",Bt(e)?e:new Error($t(e)))}}async signTypedData(e,t,n){await this.validateWalletAsync();try{const s={};for(const[e,n]of Object.entries(t))s[e]=n.map(e=>({name:e.name,type:e.type}));return await this.walletProvider.signTypedData(e,s,n)}catch(e){if(e instanceof Wr)throw e;throw new Wr(Kr.SIGNATURE_FAILED,"Failed to sign typed data",Bt(e)?e:new Error($t(e)))}}async generateCustomSignature(e){if(!Xn(e))throw new Wr(Kr.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 Wr)throw e;throw new Wr(Kr.SIGNATURE_FAILED,"Failed to generate custom message signature",Bt(e)?e:new Error($t(e)))}}validateWallet(){if(this.ensureWalletProvider(),!this.walletProvider)throw new Wr(Kr.WALLET_NOT_CONNECTED,"Wallet is required for authentication")}async validateWalletAsync(){if(this.ensureWalletProvider(),!this.walletProvider)throw new Wr(Kr.WALLET_NOT_CONNECTED,"Wallet is required for authentication");if(!this.walletProvider.isConnected())throw new Wr(Kr.WALLET_NOT_CONNECTED,"Wallet is not connected. Call connect() on the wallet provider first.")}}const Xr={prod:{...o.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:{...o.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 Jr(e){return Xr[e]}var Yr,Zr;!function(e){e.PROCESSED="PROCESSED",e.COMPLETED="COMPLETED",e.SUCCESS="SUCCESS",e.FAILED="FAILED",e.ERROR="ERROR",e.PROCESSING="PROCESSING",e.PENDING="PENDING"}(Yr||(Yr={})),function(e){e.PENDING="pending",e.PROCESSING="processing",e.COMPLETED="completed",e.FAILED="failed",e.TIMEOUT="timeout"}(Zr||(Zr={}));const ei={[Yr.PROCESSED]:Zr.COMPLETED,[Yr.COMPLETED]:Zr.COMPLETED,[Yr.SUCCESS]:Zr.COMPLETED,[Yr.FAILED]:Zr.FAILED,[Yr.ERROR]:Zr.FAILED,[Yr.PROCESSING]:Zr.PROCESSING,[Yr.PENDING]:Zr.PENDING},ti="9.0.0-rc.3",ni={DEFAULT_LIMIT:10,BACKEND_MAX_PAGE_SIZE:20};function si(e){return"string"==typeof e||null===e?e:void 0}function ri(e){if("object"!=typeof e||null===e)return{hasNextPage:!1};const t=Reflect.get(e,"hasNextPage"),n=Reflect.get(e,"hasPreviousPage"),s=si(Reflect.get(e,"endCursor")),r=si(Reflect.get(e,"startCursor"));return{hasNextPage:!0===t,...void 0===s?{}:{endCursor:s},..."boolean"==typeof n?{hasPreviousPage:n}:{},...void 0===r?{}:{startCursor:r}}}function ii(e,t){const{hasNextPage:n,endCursor:s}=e;if(n&&"string"==typeof s&&""!==s&&s!==t)return s}function ai(e){return"string"==typeof e?e:"number"==typeof e||"boolean"==typeof e||"bigint"==typeof e?String(e):JSON.stringify(e)??""}function oi(e,t){const n={};void 0!==e.cursor&&(n.cursor=e.cursor);const s=void 0!==e.pageSize?Math.min(e.pageSize,t):t;return n.pageSize=String(s),n}const ci={tokenName:"lowercase",address:"lowercase",userAddress:"lowercase",assetId:"as given",targetId:"as given",id:"as given",code:"as given"};function li(e,t){let n=e;for(const[e,s]of Object.entries(t)){const t=ci[e];if(void 0===t)throw new Error(`buildEndpoint: path parameter :${e} has no casing in PATH_PARAM_CASING`);n=n.replace(`:${e}`,encodeURIComponent("lowercase"===t?s.toLowerCase():s))}return n}function di(e,t,n){for(const s of n){const n=t[s];null!=n&&""!==n&&(e[s]=ai(n))}return e}const ui="x-api-key";class hi extends cs{constructor(e,t,n,s=!1,r){super(e,s),this.adminApiKey=t??void 0,this.jwtAuth=n,this.userApiKey=r??void 0}setJwtAuth(e){this.jwtAuth=e}validateTokenName(e,t){!function(e,t){if(!Xn(e))throw zt("tokenName","Token name");const n=fn(e);if(!t.PATTERN.test(n))throw Qt("tokenName",t.DESCRIPTION,"Token name")}(e,t)}validateRequiredString(e,t,n){!function(e,t,n){if(!Xn(e))throw zt(t,n)}(e,t,n)}validateOptionalString(e,t,n,s){!function(e,t,n,s){if(null!=e){if("string"!=typeof e)throw nn(t,"string",typeof e,n);if(e.length>s)throw tn(t,s,e.length,n)}}(e,t,n,s)}validateOptionalNumber(e,t,n,s,r,i,a){!function(e,t,n,s,r){if(null!=e){if("number"!=typeof e)throw nn(t,"number",typeof e,n);if(e<s||e>r)throw Zt(t,s,r,e,n)}}(e,t,n,s,r)}validateOptionalDate(e,t,n){!function(e,t,n){if(null!=e&&!bn(e))throw Qt(t,"a valid ISO 8601 date string",n)}(e,t,n)}validatePositiveInteger(e,t,n){as(e,t,n)}validateStatusFilter(e,t,n="status"){os(e,t,n)}buildPaginationParams(e,t){return oi(e,t)}addOptionalFilterParams(e,t,n){return di(e,t,n)}buildEndpoint(e,t){return li(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 xt("Admin API key required for this operation. Set streamAdminApiKey in SDK config.");return{[ui]:this.adminApiKey}}getJwtHeaders(){if(!this.jwtAuth)throw new xt("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?{[ui]:this.userApiKey}:this.getJwtHeaders()}extractData(e){return on(e,"Backend request failed",!0),ln(e,"No data in backend response")}extractDataOrNull(e){return on(e,"Backend request failed",!1),e.data??null}async toggleFeature(e,t,n){this.validateTokenName(e,n);const s=this.buildEndpoint(t,{tokenName:e}),r=await this.http.post(s,{},this.getAdminHeaders()),i=this.extractData(r);return{enabled:i.enabled,tokenName:i.tokenName??fn(e)}}}class gi extends hi{constructor(e,t,n,s=!1,r){super(e,t,n,s,r)}async getSettings(){return{settings:(await this.http.get(ot.GET_SETTINGS,{},this.getDualAuthHeaders())).settings}}async updateSettings(e){const t={};void 0!==e.enabled&&(t.enabled=e.enabled),void 0!==e.mode&&(t.mode=e.mode),void 0!==e.provider&&(t.provider=e.provider);return{settings:(await this.http.post(ot.UPDATE_SETTINGS,t,this.getDualAuthHeaders())).settings}}async getModeration(e){this.validatePositiveInteger(e.flagId,"flagId","Flag ID");const t=ot.GET_MODERATION.replace(":flagId",String(e.flagId));return{moderation:(await this.http.get(t,{},this.getDualAuthHeaders())).analysis}}async triggerModeration(e){this.validatePositiveInteger(e.flagId,"flagId","Flag ID");const t=ot.TRIGGER_MODERATION.replace(":flagId",String(e.flagId)),n=await this.http.post(t,{},this.getDualAuthHeaders());return{queued:n.queued,message:n.message.length>0?n.message:"Moderation queued successfully"}}async getStatus(){return{status:(await this.http.get(ot.GET_STATUS,{},this.getDualAuthHeaders())).status}}}const mi=es({MODERATOR:"MODERATOR",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MANAGER:"MANAGER",OWNER:"OWNER"});function fi(e){return mi.includes(e)}function pi(e,t,n=!1){const s=t.length;if(jt(t,()=>{rs(e.description,"description",255)}),t.length>s&&(t[s]="Description must be 255 characters or less"),void 0!==e.tokenNames){const n=t.length;jt(t,()=>{if(!Array.isArray(e.tokenNames))throw nn("tokenNames","an array",e.tokenNames);if(!e.tokenNames.every(e=>"string"==typeof e))throw nn("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;jt(t,()=>{is(e.expiresAt,"expiresAt")}),t.length>n&&(t[n]="expiresAt must be a valid ISO 8601 date string")}}class vi extends cs{constructor(e,t,n=!1){super(e,n,t)}extractData(e){let t;t="error"in e?e.error:"success"in e&&!e.success;const n={status:200,error:t,data:e.data};return void 0!==e.message&&(n.message=e.message),on(n,"API key operation failed",!0),e.data}validateApiKeyId(e){this.validatePositiveInteger(e,"id","API key ID")}async create(e){const t=function(e){const t=[];return void 0===e.role||null===e.role?t.push("Role is required"):fi(e.role)||t.push(`Invalid role. Must be one of: ${mi.join(", ")}`),pi(e,t),t}(e);if(t.length>0)throw new Ot(t.join("; "),"options","VALIDATION_FAILED");this.logger.debug("Creating API key",{role:e.role,delegateAllTokens:e.delegateAllTokens});const n={role:e.role};void 0!==e.description&&(n.description=e.description),void 0!==e.delegateAllTokens&&(n.delegateAllTokens=e.delegateAllTokens),void 0!==e.tokenNames&&e.tokenNames.length>0&&(n.tokenNames=e.tokenNames),void 0!==e.expiresAt&&(n.expiresAt=e.expiresAt),void 0!==e.tokenPermissions&&(n.tokenPermissions=e.tokenPermissions);const s=await this.http.post(he.CREATE,n,this.getJwtHeaders()),r=this.extractData(s);return this.logger.debug("API key created",{id:r.id,keyPrefix:r.keyPrefix}),r}async findAll(e={}){!function(e){if(void 0!==e.pageSize&&("number"!=typeof e.pageSize||e.pageSize<1||e.pageSize>ps))throw nn("pageSize",`number between 1 and ${ps}`,typeof e.pageSize);if(void 0!==e.cursor&&("string"!=typeof e.cursor||""===e.cursor.trim()))throw nn("cursor","non-empty string",typeof e.cursor)}(e),this.logger.debug("Listing API keys",e);const t=oi(e,ps),n=await this.http.get(he.LIST,t,this.getJwtHeaders()),s=this.extractData(n);return this.logger.debug("Listed API keys",{count:s.apiKeys.length,total:s.pageInfo.totalCount}),s}async findOne(e){this.validateApiKeyId(e),this.logger.debug("Getting API key",{id:e});const t=he.GET.replace(":id",String(e)),n=await this.http.get(t,{},this.getJwtHeaders()),s=this.extractData(n);return this.logger.debug("Got API key",{id:s.id,keyPrefix:s.keyPrefix}),s}async update(e,t){this.validateApiKeyId(e);const n=function(e){const t=[];return["role","description","delegateAllTokens","tokenNames","expiresAt","tokenPermissions"].some(t=>void 0!==e[t])||t.push("At least one field must be provided for update"),void 0===e.role||fi(e.role)||t.push(`Invalid role. Must be one of: ${mi.join(", ")}`),pi(e,t,!0),t}(t);if(n.length>0)throw new Ot(n.join("; "),"options","VALIDATION_FAILED");this.logger.debug("Updating API key",{id:e,options:t});const s={};void 0!==t.role&&(s.role=t.role),void 0!==t.description&&(s.description=t.description),void 0!==t.delegateAllTokens&&(s.delegateAllTokens=t.delegateAllTokens),void 0!==t.tokenNames&&(s.tokenNames=t.tokenNames),void 0!==t.expiresAt&&(s.expiresAt=t.expiresAt),void 0!==t.tokenPermissions&&(s.tokenPermissions=t.tokenPermissions);const r=he.UPDATE.replace(":id",String(e)),i=await this.http.patch(r,s,this.getJwtHeaders()),a=this.extractData(i);return this.logger.debug("Updated API key",{id:a.id,keyPrefix:a.keyPrefix}),a}async revoke(e){this.validateApiKeyId(e),this.logger.debug("Revoking API key",{id:e});const t=he.REVOKE.replace(":id",String(e));await this.http.delete(t,{},this.getJwtHeaders()),this.logger.debug("API key revoked",{id:e})}getRoles(){return[...mi]}}const Ai={VIEWERS:"viewers",CHAT_PARTICIPANTS:"chat_participants"},Ei=Zn(Ai);function yi(e){if(!Xn(e.userAddress))throw zt("userAddress");if(!(null==(t=e.reason)||""===t||"string"==typeof t&&!ss(t)&&t.length<=ys.BAN_REASON.MAX_LENGTH))throw new Ot(`reason must be at most ${ys.BAN_REASON.MAX_LENGTH} characters`,"reason","TOO_LONG");var t,n;if(n=e.durationSeconds,!(Jn(n)||"number"==typeof n&&n>=Ss&&n<=bs))throw new Ot(`durationSeconds must be between ${Ss} and ${bs} seconds`,"durationSeconds","OUT_OF_RANGE")}class Ti extends hi{constructor(e,t,n,s=!1,r){super(e,t,n,s,r)}async createBan(e){!function(e){ts(e.tokenName,"tokenName",gs),yi(e)}(e);const t=this.buildEndpoint(se,{tokenName:e.tokenName}),n=Si(e),s=await this.http.post(t,n,this.getMultiAuthHeaders());return{ban:this.extractData(s),tokenName:fn(e.tokenName)}}async removeBan(e){!function(e){if(ts(e.tokenName,"tokenName",gs),!Xn(e.userAddress))throw zt("userAddress")}(e);const t=wn(e.userAddress,"userAddress"),n=this.buildEndpoint(ae,{tokenName:e.tokenName,userAddress:t}),s=await this.http.delete(n,{},this.getMultiAuthHeaders()),r=this.extractDataOrNull(s);return{removed:r?.removed??!0,tokenName:fn(e.tokenName),userAddress:r?.userAddress??t}}async listBans(e){!function(e){ts(e.tokenName,"tokenName",gs),Yn(0,void 0,ps,e.pageSize)}(e);const t=this.buildEndpoint(re,{tokenName:e.tokenName}),n=this.buildPaginationParams(e,ps);this.addOptionalFilterParams(n,e,["search","name","userAddress"]),void 0!==n.userAddress&&(n.userAddress=_n(n.userAddress));const s=await this.http.get(t,n,this.getMultiAuthHeaders()),r=this.extractData(s);return{items:r.bans,pageInfo:r.pageInfo}}async getBanStatus(e){!function(e){if(ts(e.tokenName,"tokenName",gs),!Xn(e.userAddress))throw zt("userAddress")}(e);const t=wn(e.userAddress,"userAddress"),n=this.buildEndpoint(ie,{tokenName:e.tokenName,userAddress:t}),s=await this.http.get(n,{},this.getMultiAuthHeaders()),r=this.extractDataOrNull(s);return{banned:null!==r,...null!==r&&{ban:r},tokenName:fn(e.tokenName),userAddress:t}}async getActiveUsers(e){!function(e){if(ts(e.tokenName,"tokenName",gs),void 0!==e.type&&!Ei(e.type))throw new Ot(`type must be one of: ${Object.values(Ai).join(", ")}`,"type",Nt)}(e);const t=this.buildEndpoint(oe,{tokenName:e.tokenName}),n={};this.addOptionalFilterParams(n,e,["type","search","name","userAddress"]),void 0!==n.userAddress&&(n.userAddress=_n(n.userAddress));const s=await this.http.get(t,n,this.getMultiAuthHeaders());return this.extractData(s)}async createGlobalBan(e){!function(e){yi(e)}(e);const t=Si(e),n=await this.http.post(ce,t,this.getDualAuthHeaders());return{ban:this.extractData(n)}}async removeGlobalBan(e){!function(e){if(!Xn(e.userAddress))throw zt("userAddress")}(e);const t=wn(e.userAddress,"userAddress"),n=this.buildEndpoint(ue,{userAddress:t}),s=await this.http.delete(n,{},this.getDualAuthHeaders()),r=this.extractDataOrNull(s);return{removed:r?.removed??!0,userAddress:r?.userAddress??t}}async listGlobalBans(e){const t=e??{pageSize:20};!function(e){Yn(0,void 0,ps,e.pageSize)}(t);const n=this.buildPaginationParams(t,ps);this.addOptionalFilterParams(n,t,["search","name","userAddress"]),void 0!==n.userAddress&&(n.userAddress=_n(n.userAddress));const s=await this.http.get(le,n,this.getDualAuthHeaders()),r=this.extractData(s);return{items:r.bans,pageInfo:r.pageInfo}}async getGlobalBan(e){!function(e){if(!Xn(e.userAddress))throw zt("userAddress")}(e);const t=wn(e.userAddress,"userAddress"),n=this.buildEndpoint(de,{userAddress:t}),s=await this.http.get(n,{},this.getDualAuthHeaders()),r=this.extractDataOrNull(s);return{banned:null!==r,...null!==r&&{ban:r},userAddress:t}}}function Si(e){const t={userAddress:wn(e.userAddress,"userAddress")};return void 0!==e.reason&&(t.reason=e.reason),void 0!==e.durationSeconds&&(t.durationSeconds=e.durationSeconds),t}function bi(e){return{maxAcceptableReverseBondingCurveFee:Wn(e.maxAcceptableReverseBondingCurveFee)}}const ki={BuyNativeDto:class extends k{constructor(e,t,n="0",s={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=Wn(t),this.expectedToken=Hn(n),this.extraFees=bi(s)}},BuyExactDto:class extends k{constructor(e,t,n,s={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=Hn(t),this.expectedNativeToken=Wn(n),this.extraFees=bi(s)}},SellExactDto:class extends k{constructor(e,t,n="0",s={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=Hn(t),this.expectedNativeToken=Wn(n),this.extraFees=bi(s)}},SellNativeDto:class extends k{constructor(e,t,n,s={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=Wn(t),this.expectedToken=Hn(n),this.extraFees=bi(s)}}};function wi(e,t,n){let s;jn(t,0,1,"slippageToleranceFactor");try{s=function(e,t){if(Tn(e)||""===e)throw zt(t);if(I.isBigNumber(e)){if(e.isNaN())throw sn(t,"NaN");return e}try{const n=new I(e);if(n.isNaN())throw sn(t,e);if(!n.isFinite())throw sn(t,e);return n}catch(n){if(n instanceof Ot)throw n;throw sn(t,e)}}(e,"expectedAmount")}catch{throw new Error(`Invalid expected amount: ${e}. Must be a valid number`)}if(0===t)return e;const r=s.multipliedBy(t);let i;switch(n){case"buy-native":case"sell-exact":i=s.minus(r);break;case"buy-exact":case"sell-native":i=s.plus(r);break;default:throw new Error(`Unknown operation type: ${n}`)}return Tr(i).isLessThan(0)&&(i=Tr(0)),Sr(i)}function Ni(e,t){if(!Xn(e))throw new Error("Input must be a non-empty string");const n=e.split(t);if(n.length<4)throw new Error(`Invalid ${"|"===t?"pipe":"dollar"}-delimited token format. Expected 4+ parts separated by ${t}, got ${n.length}`);return n}function _i(e,t,n,s){const r=e?.split?.(t)??[],i=void 0!==n?` (${n})`:"";return new Ot(`Invalid ${"|"===t?"pipe":"dollar"}-delimited token: "${e}" (${r.length} parts)${i}. Expected format: "collection${t}category${t}type${t}additionalKey" (4 parts minimum). Received: [${r.map(e=>`"${e}"`).join(", ")}]. Error: ${$t(s)}`,"token",`INVALID_${"|"===t?"PIPE":"DOLLAR"}_DELIMITED_TOKEN`)}function Ii(e,t,n){try{const n=Ni(e,t),s=n[n.length-1],r=n[n.length-2],i=n[n.length-3],a=n.slice(0,n.length-3).join(t);if(void 0===a||void 0===i||void 0===r||void 0===s||""===s||""===a||""===i||""===r)throw new Error("All components (collection, category, type, additionalKey) must be non-empty");return{collection:a,category:i,type:r,additionalKey:s}}catch(s){throw _i(e,t,n,s)}}function Ci(e){return function(e,t,n){try{const n=Ni(e,t),[s,r,i,...a]=n;if(""===s||""===r||""===i)throw new Error("Collection, category, and type must be non-empty");const o=a.join(t);if(void 0===s||void 0===r||void 0===i||""===o)throw new Error("AdditionalKey must be non-empty");return{collection:s,category:r,type:i,additionalKey:o}}catch(s){throw _i(e,t,n,s)}}(e,"|","pipe-delimited token")}class Di 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 Ri={name:"GalaChain"},Oi={name:"ethereum",chainId:1};function Ui(e){if("string"!=typeof e)throw new Error("Wallet returned an invalid signature");return e}function Mi(e,t){if(/^eth\|0x/iu.test(e))throw new Di(`${t} must not be written eth|0x...: use eth|<40 hex>, 0x<40 hex> or client|<id>`,"INVALID_SIGNER_OPTIONS",{details:{[t]:e}});return e}function Fi(e){const t={};for(const[n,s]of Object.entries(e))void 0!==s&&(t[n]=Li(s));return t}function Li(e){return Array.isArray(e)?e.map(Li):"object"==typeof e&&null!==e?Fi(e):e}function xi(e,t,n,s){return{...e,signature:t,types:n,domain:s}}class Pi extends g{constructor(e){super(e),this.typedDataWallet=new i(e),this.walletAddress=`eth|${this.typedDataWallet.address.slice(2)}`}async signTypedData(e,t){const n=Fi(t),s=l(e,n);return xi(n,await this.typedDataWallet.signTypedData(Ri,s,n),s,Ri)}}class Bi extends u{constructor(e,t={}){const{verifyActiveAccount:n,...s}=t;if(super(Mi(e,"walletAddress"),{...s,...void 0!==s.selectAddress&&{selectAddress:Mi(s.selectAddress,"selectAddress")}}),this.typedDataWallet=t.wallet,!0===n){const e=d(this.walletAddress)??(void 0===this.selectAddress?void 0:d(this.selectAddress));if(void 0===e)throw new Di("verifyActiveAccount needs the Ethereum account of the key (walletAddress or selectAddress as 0x... / eth|...); a client| alias names no key.","INVALID_SIGNER_OPTIONS",{details:{walletAddress:this.walletAddress,selectAddress:this.selectAddress}});this.verifiedKey=e}else this.verifiedKey=void 0}async signTypedData(e,t){const n=Fi(t),s=l(e,n),r={domain:Oi,types:s,message:n,Primary_type:e},i=this.typedDataWallet??function(){const e=globalThis.window,t=e?.gala;if(void 0===t)throw new Error("Gala wallet is not available");return t}();void 0!==this.verifiedKey&&await async function(e,t){let n="address"in e&&"string"==typeof e.address&&""!==e.address?e.address:void 0;if(void 0===n){const t=await e.request({method:"eth_accounts"}),s=Array.isArray(t)?t[0]:void 0;n="string"==typeof s&&""!==s?s:void 0}const s=void 0===n?void 0:d(n);if(void 0===s||s.toLowerCase()!==t.toLowerCase())throw new Di("Your wallet's active account has changed. Please switch back to the connected account or reconnect your wallet.","WALLET_ACCOUNT_CHANGED",{details:{walletAccount:n??null,signerAccount:t}})}(i,this.verifiedKey);const a=await this.typedDataAccount(i);return xi(n,Ui(await h(i,this.selectAddress??a,()=>i.request({method:"eth_signTypedData",params:[JSON.stringify(r),a]}))),s,Oi)}async typedDataAccount(e){if(s(this.walletAddress))return this.walletAddress;const t=await e.request({method:"eth_accounts"}),n=Array.isArray(t)?t[0]:void 0,r="string"==typeof n?n.replace(/^eth\|/,"0x"):"";if(!s(r))throw new Error("Gala Wallet did not report an Ethereum account to sign typed data with");return r}}class $i extends c{constructor(e,t,n){super(e,Mi(t,"walletAddress"),n),this.typedDataProvider=e}async signTypedData(e,t){const r=Fi(t),i=this.typedDataProvider,a=await i.getNetwork(),o={name:a.name,chainId:Number(a.chainId)},c=l(e,r),d=await i.getSigner(),u=n(await d.getAddress());if(s(this.walletAddress)&&u!==n(this.walletAddress))throw new Di(`Wallet account ${u} is not the account this signer was created for (${this.walletAddress}); reconnect before signing.`,"WALLET_ACCOUNT_CHANGED",{details:{walletAccount:u,signerAccount:this.walletAddress}});return xi(r,Ui(await d.signTypedData(o,c,r)),c,o)}static fromEip1193(e,t,n){const s=new r(e);return new $i({request:t=>e.request(t),getNetwork:()=>s.getNetwork(),getSigner:()=>s.getSigner()},d(t)??t,n)}}function Gi(e){const[t,n]=e.split("|",2);if("service"!==t||void 0===n)throw new Error(`Invalid vaultAddress format (expected service|<collection>$<category>$<type>$<additionalKey>$launchpad): ${e}`);const s=n.split("$"),r=s[s.length-1],i=s.slice(0,-1),a=i.slice(0,-3).join("$"),[o,c,l]=i.slice(-3);if("launchpad"!==r||i.length<4||""===a||void 0===o||void 0===c||void 0===l||""===o||""===c||""===l)throw new Error(`Invalid vaultAddress format (expected service|<collection>$<category>$<type>$<additionalKey>$launchpad): ${e}`);return{collection:a,category:o,type:c,additionalKey:l}}function Ki(e){const{collection:t,category:n,type:s}=Gi(e),r=`${t}$${n}$${s}$none`,i="GALA$Unit$none$none";return[`$service$${r}$launchpad`,`$tokenBalance$${r}$${e}`,`$tokenBalance$${r}$${e}`,`$tokenBalance$${i}$${e}`,`$tokenBalance$${i}$${e}`]}function Wi(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 Hi(e){return`${e.collection}|${e.category}|${e.type}|${e.additionalKey}`}function ji(e){if("string"==typeof e){if(!Xn(t=e)||!t.includes("|"))throw new Ot(`Invalid tokenId string format: "${e}". Expected pipe-delimited format: "collection|category|type|additionalKey" or "collection|category|type|additionalKey|instance"`,"tokenId","INVALID_TOKEN_ID_FORMAT");const n=e.split("|");if(n.length>=5){const e=Ci(n.slice(0,4).join("|")),t=n[4]??"0";return{...e,instance:t.length>0?t:"0"}}return{...Ci(e),instance:"0"}}var t;if("object"==typeof e&&null!==e){if("instance"in e&&void 0!==e.instance&&"string"==typeof e.instance&&e.instance.length>0){if(!m(e))throw new Ot("Invalid tokenId object format. All fields (collection, category, type, additionalKey) must be non-empty strings","tokenId","INVALID_TOKEN_ID_FORMAT");return e}if(!m(e))throw new Ot("Invalid tokenId object format. All fields (collection, category, type, additionalKey) are required","tokenId","INVALID_TOKEN_ID_FORMAT");return{...e,instance:"0"}}throw new Ot(`Invalid tokenId type: ${typeof e}. Expected string, TokenClassKey, or TokenInstanceKey`,"tokenId","INVALID_TOKEN_ID_TYPE")}function qi(e){return function(e){try{if(!Xn(e))throw new Error("Vault address must be a non-empty string");const t=e.split("|")[1];if(""===t||void 0===t)throw new Error("Missing token part after service prefix");const n=t.split("$");return Ii((n.length>=5&&"launchpad"===n[n.length-1]?n.slice(0,-1):n).join("$"),"$","vault address")}catch(t){throw new Ot(`Invalid vault address: "${e}". Expected format: "service|Token$Unit$SYMBOL$additionalKey$launchpad". Error: ${$t(t)}`,"vaultAddress","INVALID_VAULT_ADDRESS_FORMAT")}}(e)}function Vi(e){return{...qi(e),instance:"0"}}function zi(e){const t=qi(e);if("Token"!==t.collection)throw new Ot(`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 Qi,Xi,Ji,Yi,Zi=Object.freeze({__proto__:null,extractTokenSymbolFromVault:zi,normalizeToTokenInstanceKey:ji,parseVaultAddressToTokenClassKey:qi,parseVaultAddressToTokenInstance:Vi});class ea extends ls{constructor(e=!1){super(e)}generateStringsInstructions(e){try{this.logger.debug("🔧 Generating stringsInstructions for:",e);const t=Ki(e);return this.logger.debug("✅ Generated stringsInstructions:",t),t}catch(e){this.logger.error("❌ Failed to generate stringsInstructions:",e);const t=$t(e);throw new Ot(`Failed to generate stringsInstructions: ${t}`,"vaultAddress","INVALID_VAULT_ADDRESS")}}createGalaInstance(){const e=new w;return e.collection="GALA",e.category="Unit",e.type="none",e.additionalKey="none",this.logger.debug("🟡 Created GALA instance:",{stringKey:e.toStringKey()}),e}extractTokenSymbolFromVault(e){if(!Xn(e))throw zt("vaultAddress","Vault address");try{const t=zi(e);return this.logger.debug("🔍 Extracted token symbol:",{vaultAddress:e,tokenSymbol:t}),t}catch(e){if(e instanceof Ot)throw Qt("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad");throw e}}validateVaultAddress(e){if(!Xn(e))throw zt("vaultAddress","Vault address");if(!e.startsWith("service|Token$Unit$"))throw Qt("vaultAddress",'starting with "service|Token$Unit$"');if(!e.endsWith("$launchpad"))throw Qt("vaultAddress",'ending with "$launchpad"');const t=function(e){if(!Xn(e))return null;const t=e.match(/^service\|Token\$Unit\$([^$]+)\$eth:([a-fA-F0-9]{40})\$launchpad$/);if(!t)return null;const n=t[1],s=t[2];return void 0===n||void 0===s?null:{tokenSymbol:n,creatorAddress:s.toLowerCase()}}(e);if(!t)throw Qt("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 Qt("vaultAddress","containing a 1-10 letter token symbol (case insensitive)");return this.logger.debug("✅ Vault address validation passed:",e),!0}generateTokenClassKeyString(e,t,n,s){return`${e}$${t}$${n}$${s}`}parseTokenClassKeyString(e){try{return Ii(e,"$","dollar-delimited token")}catch(e){if(e instanceof Ot)throw Qt("stringKey","format: collection$category$type$additionalKey (4 parts)");throw e}}}function ta(e){return"object"==typeof e&&null!==e?e:void 0}class na extends cs{constructor(e,t,n=!1,s,r,i=.05,a=.01,o){if(super(e,n),this.tokenResolver=t,this._walletProvider=s,this.userAddress=r,this.defaultSlippageToleranceFactor=i,this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor=a,this.sellFeeCeiling=o,this.bundleEndpoint="/bundle",null!==this._walletProvider&&void 0!==this._walletProvider&&null!=r){const e=ta(this._walletProvider),t=e?.privateKey;if("string"==typeof t)this.signer=new Pi(t);else if(function(e){const t=ta(e);return"function"==typeof t?.request}(this._walletProvider)&&void 0!==this.userAddress){const e=kn(this.userAddress,"userAddress");this.signer=new $i(this._walletProvider,d(e)??e)}this.tokenKeyService=new ea(n)}}async submitTransaction(e){try{this.validateBundleData(e),this.logger.debug("📦 Submitting bundle transaction:",{method:e.method,stringsInstructionsCount:e.stringsInstructions.length,signedDtoKeys:Object.keys(e.signedDto)});const t=this.formatBundleRequest(e);this.logger.debug("🚀 Bundle request payload:",{...t,signedDto:"[REDACTED - Contains signature]"});let n=null;try{n=await un(()=>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:an(n),error:n.error}),this.handleBundleResponse(n))}catch(e){if(e instanceof Ot)return{success:!1,error:$t(e)};throw e}}validateBundleData(e){if(null==e)throw zt("bundleData","Bundle data");if(null===e.signedDto||void 0===e.signedDto)throw zt("signedDto","Signed DTO");if(!Xn(e.method))throw zt("method","Method name");if(!Array.isArray(e.stringsInstructions))throw Qt("stringsInstructions","an array of resource tracking strings");if(0===e.stringsInstructions.length)throw new Ot("stringsInstructions cannot be empty","stringsInstructions","EMPTY_ARRAY");const t=["BuyWithNative","BuyExactToken","SellExactToken","SellWithNative"];if(!t.includes(e.method))throw Qt("method",`one of: ${t.join(", ")}`);e.stringsInstructions.forEach((e,t)=>{if(!Xn(e))throw new Ot(`stringsInstructions[${t}] must be a non-empty string`,`stringsInstructions[${t}]`,"INVALID_INSTRUCTION");if("string"!=typeof(n=e)||!n.includes("$"))throw new Ot(`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=cn(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(Wt(e)&&null!==e.response&&void 0!==e.response){const t=cn(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 $t(e)??"Unknown bundle transaction error"}async getBundlerTransactionResult(e){try{if(!Xn(e))throw zt("transactionId","Transaction ID");let t;this.logger.debug("🔍 Checking bundler transaction result:",e);try{t=await un(()=>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 Ot)return{success:!1,error:$t(e)};throw e}}async cancelTransaction(e){try{if(!Xn(e))throw zt("transactionId","Transaction ID");let t;this.logger.debug("🚫 Cancelling transaction:",e);try{t=await un(()=>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 Ot)return{success:!1,error:$t(e)};throw e}}async getHealthStatus(){this.logger.debug("🏥 Checking bundle service health");try{const e=await un(()=>this.http.get(`${this.bundleEndpoint}/health`),{errorContext:"Bundle service health check failed",logger:this.logger});return null==e?{success:!1,error:"No response from bundle service health check"}:(this.logger.debug("💚 Bundle service health:",e),{success:!0,data:e})}catch(e){return{success:!1,error:this.formatErrorMessage(e)}}}async buyToken(e){this.ensureTradingServicesAvailable();const{tokenName:t,amount:n,type:s,expectedAmount:r}=e,{effectiveSlippageFactor:i,effectiveMaxFee:a,vaultAddress:o}=await this.prepareTradingOperation(t,e.maxAcceptableReverseBondingCurveFee,e.maxAcceptableReverseBondingCurveFeeSlippageFactor,e.slippageToleranceFactor);if("native"===s){if(null==r||""===r)throw new Ot("expectedAmount is required for native buy operations. Use getBuyTokenAmount() first to calculate expected tokens.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=wi(r,i,"buy-native");this.logger.debug("BuyNative slippage applied:",{originalExpectedTokens:r,slippageFactor:i,adjustedMinTokens:e});const t=new ki.BuyNativeDto(o,n,e,{maxAcceptableReverseBondingCurveFee:a});return await this.executeBundleTransaction(t,"BuyWithNative",o)}{if(null==r||""===r)throw new Ot("expectedAmount is required for exact buy operations. Use getBuyTokenAmount() first to calculate expected GALA cost.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=wi(r,i,"buy-exact");this.logger.debug("BuyExact slippage applied:",{originalExpectedGalaCost:r,slippageFactor:i,adjustedMaxGalaCost:e});const t=new ki.BuyExactDto(o,n,e,{maxAcceptableReverseBondingCurveFee:a});return await this.executeBundleTransaction(t,"BuyExactToken",o)}}async sellToken(e){this.ensureTradingServicesAvailable();const{tokenName:t,amount:n,type:s,expectedAmount:r}=e,{effectiveSlippageFactor:i,effectiveMaxFee:a,vaultAddress:o}=await this.prepareTradingOperation(t,e.maxAcceptableReverseBondingCurveFee,e.maxAcceptableReverseBondingCurveFeeSlippageFactor,e.slippageToleranceFactor),c=async()=>void 0===e.maxAcceptableReverseBondingCurveFee?this.defaultSellFeeCeiling(e,o):a;if("exact"===s){if(null==r||""===r)throw new Ot("expectedAmount is required for exact sell operations. Use getSellTokenAmount() first to calculate expected GALA.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=wi(r,i,"sell-exact");this.logger.debug("SellExact slippage applied:",{originalExpectedGala:r,slippageFactor:i,adjustedMinGala:e});const t={maxAcceptableReverseBondingCurveFee:await c()},s=new ki.SellExactDto(o,n,e,t);return await this.executeBundleTransaction(s,"SellExactToken",o)}{if(null==r||""===r)throw new Ot("expectedAmount is required for native sell operations. Use getSellTokenAmount() first to calculate tokens to sell.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=wi(r,i,"sell-native");this.logger.debug("SellNative slippage applied:",{originalExpectedTokensToSell:r,slippageFactor:i,adjustedMaxTokensToSell:e});const t={maxAcceptableReverseBondingCurveFee:await c()},s=new ki.SellNativeDto(o,n,e,t);return await this.executeBundleTransaction(s,"SellWithNative",o)}}async prepareTradingOperation(e,t,n,s){const{effectiveSlippageFactor:r,effectiveMaxFee:i}=this.calculateEffectiveSlippage(t,n,s),a=await this.resolveTokenNameToVault(e);if(null==a)throw Vt(e);return{effectiveSlippageFactor:r,effectiveMaxFee:i,vaultAddress:a}}async defaultSellFeeCeiling(e,t){if(void 0===this.sellFeeCeiling)throw Jt("Cannot quote the reverse bonding curve fee for this sell. Pass maxAcceptableReverseBondingCurveFee.","maxAcceptableReverseBondingCurveFee");return this.sellFeeCeiling({method:"exact"===e.type?"SellExactToken":"SellWithNative",vaultAddress:t,quantity:e.amount,tokenName:e.tokenName,feeSlippageFactor:e.maxAcceptableReverseBondingCurveFeeSlippageFactor??this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor})}calculateEffectiveSlippage(e,t,n){const s=n??this.defaultSlippageToleranceFactor,r=t??this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor;let i=e??"0";return null!=e&&(i=wi(e,r,"buy-exact"),this.logger.debug("Reverse bonding curve fee slippage applied:",{baseFee:e,slippageFactor:r,adjustedMaxFee:i})),{effectiveSlippageFactor:s,effectiveFeeSlippageFactor:r,effectiveMaxFee:i}}ensureTradingServicesAvailable(){if(!this.signer||!this.tokenKeyService)throw Jt("Trading services not available. BundleService requires walletProvider and userAddress for trading operations.","walletProvider");if(null===this.userAddress||void 0===this.userAddress)throw zt("userAddress","User address")}async executeBundleTransaction(e,t,n){this.ensureTradingServicesAvailable();try{e.uniqueKey=`galaswap-operation-${Date.now()}_${N().replace(/-/gu,"").substring(0,26)}`;const s=await this.signer.signObject(t,e),r=this.tokenKeyService.generateStringsInstructions(n),i={stringsInstructions:r,method:t,signedDto:s};this.logger.debug("📦 Bundle transaction data:",{method:t,stringsInstructions:r,dtoKeys:Object.keys(s)});const a=await this.submitTransaction(i);if(a.success){const e=cn(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 o=a.error;throw new Pt("string"==typeof o?o:"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 sa extends cs{constructor(e,t=!1){super(e,t)}extractData(e){if(e.error||void 0===e.data){const t=e.message??"Client config operation failed";throw new Error(t)}return e.data}async getClientFlags(){this.logger.debug("Fetching client feature flags");const e=await this.http.get(At),t=this.extractData(e);return this.logger.debug("Fetched client feature flags",{flagCount:Object.keys(t.flags).length}),{flags:t.flags}}}!function(e){e.CHAT_MESSAGE="CHAT_MESSAGE",e.COMMENT="COMMENT",e.STREAM="STREAM",e.RECORDING="RECORDING"}(Qi||(Qi={})),function(e){e.INAPPROPRIATE_CONTENT="INAPPROPRIATE_CONTENT",e.SPAM="SPAM",e.HARASSMENT="HARASSMENT",e.SCAM="SCAM",e.OTHER="OTHER"}(Xi||(Xi={})),function(e){e.PENDING="PENDING",e.DISMISSED="DISMISSED",e.ACTIONED="ACTIONED"}(Ji||(Ji={})),function(e){e.DELETE_CONTENT="DELETE_CONTENT",e.BAN_USER="BAN_USER",e.DELETE_AND_BAN="DELETE_AND_BAN"}(Yi||(Yi={})),Xi.INAPPROPRIATE_CONTENT,Xi.SPAM,Xi.HARASSMENT,Xi.SCAM,Xi.OTHER,Ji.PENDING,Ji.DISMISSED,Ji.ACTIONED,Yi.DELETE_CONTENT,Yi.BAN_USER,Yi.DELETE_AND_BAN,Qi.CHAT_MESSAGE,Qi.COMMENT,Qi.STREAM,Qi.RECORDING;const ra=Zn(Qi),ia=Zn(Xi),aa=Zn(Ji),oa=Zn(Yi),ca={TOKEN_NAME:hs,TOKEN_NAME_FILTER:{MIN_LENGTH:1,MAX_LENGTH:50,PATTERN:/^[a-zA-Z0-9]{1,50}$/,DESCRIPTION:"1-50 letters and digits"},CONTENT_ID:ys.CONTENT_ID,DETAILS:ys.FLAG_DETAILS,PAGINATION:{MAX_LIMIT:ps}};function la(e,t,n="tokenName"){ts(e,n,t)}function da(e){if(void 0!==e.contentType&&!ra(e.contentType))throw Qt("contentType",`one of: ${Object.values(Qi).join(", ")}`,"Content type");if(void 0!==e.status&&!aa(e.status))throw Qt("status",`one of: ${Object.values(Ji).join(", ")}`);if(void 0!==e.reason&&!ia(e.reason))throw Qt("reason",`one of: ${Object.values(Xi).join(", ")}`);if(void 0!==e.reporterAddress&&!Xn(e.reporterAddress))throw nn("reporterAddress","a non-empty string",typeof e.reporterAddress);if(void 0!==e.reporterAddress&&xn(e.reporterAddress,"reporterAddress"),void 0!==e.reportedUserAddress&&!Xn(e.reportedUserAddress))throw nn("reportedUserAddress","a non-empty string",typeof e.reportedUserAddress);void 0!==e.reportedUserAddress&&xn(e.reportedUserAddress,"reportedUserAddress"),Yn(0,void 0,ca.PAGINATION.MAX_LIMIT,e.pageSize)}class ua extends hi{constructor(e,t,n,s=!1,r){super(e,t,n,s,r)}async createFlag(e){!function(e){if(la(e.tokenName,ca.TOKEN_NAME),void 0===e.contentType)throw zt("contentType","Content type");if(!ra(e.contentType))throw Qt("contentType",`one of: ${Object.values(Qi).join(", ")}`,"Content type");if(!Xn(e.contentId))throw zt("contentId","Content ID");if(e.contentId.length>ca.CONTENT_ID.MAX_LENGTH)throw tn("contentId",ca.CONTENT_ID.MAX_LENGTH,e.contentId.length,"Content ID");if(!Xn(e.reportedUserAddress))throw zt("reportedUserAddress","Reported user address");if(xn(e.reportedUserAddress,"reportedUserAddress"),!(e.contentType!==Qi.STREAM&&e.contentType!==Qi.RECORDING||void 0!==e.reason&&null!==e.reason))throw zt("reason","Reason");if(void 0!==e.reason&&!ia(e.reason))throw Qt("reason",`one of: ${Object.values(Xi).join(", ")}`,"Reason");if(void 0!==e.details&&!Xn(e.details))throw nn("details","a non-empty string",typeof e.details);if(void 0!==e.details&&e.details.length>ca.DETAILS.MAX_LENGTH)throw tn("details",ca.DETAILS.MAX_LENGTH,e.details.length)}(e);const t={tokenName:e.tokenName,contentType:e.contentType,contentId:e.contentId,reportedUserAddress:Nn(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(Te.CREATE,t,this.getMultiAuthHeaders());return{flag:this.extractData(n).flag}}async listFlags(e){return function(e){la(e.tokenName,ca.TOKEN_NAME_FILTER),da(e)}(e),this.fetchFlagList(e)}async listGlobalFlags(e={}){return function(e){void 0!==e.tokenName&&la(e.tokenName,ca.TOKEN_NAME_FILTER),da(e)}(e),this.fetchFlagList(e)}async dismissFlag(e){!function(e){if(void 0===e.flagId||null===e.flagId)throw zt("flagId","Flag ID");try{Vn(e.flagId,"flagId")}catch{throw Qt("flagId","a positive integer","Flag ID")}}(e);const t=Te.DISMISS.replace(":id",e.flagId.toString()),n=await this.http.post(t,{},this.getMultiAuthHeaders());return{flag:this.extractData(n).flag}}async actionFlag(e){!function(e){if(void 0===e.flagId||null===e.flagId)throw zt("flagId","Flag ID");try{Vn(e.flagId,"flagId")}catch{throw Qt("flagId","a positive integer","Flag ID")}if(void 0===e.action)throw zt("action","Action");if(!oa(e.action))throw Qt("action",`one of: ${Object.values(Yi).join(", ")}`,"Action")}(e);const t=Te.ACTION.replace(":id",e.flagId.toString()),n=await this.http.post(t,{action:e.action},this.getMultiAuthHeaders());return{flag:this.extractData(n).flag}}async fetchFlagList(e){const t=oi(e,ps);di(t,e,["tokenName","contentType","status","reason","reporterAddress","reportedUserAddress"]);for(const e of["reporterAddress","reportedUserAddress"]){const n=t[e];void 0!==n&&(t[e]=Nn(n,e))}const n=await this.http.get(Te.LIST,t,this.getMultiAuthHeaders()),s=this.extractData(n);return{items:s.flags,pageInfo:s.pageInfo}}}const ha=["heart","fire","laugh","wow","thumbs_up"];class ga extends hi{constructor(e,t,n,s=!1,r){super(e,t,n,s,r)}validateMessageId(e){if(!Xn(e))throw zt("messageId","Message ID");if(qn(e,Ts.CONTENT_REACTION.MAX_LENGTH,"messageId"),!Ts.CONTENT_REACTION.PATTERN.test(e))throw Qt("messageId","msg-{timestamp}-{uuid} or chat-{timestamp}-{uuid} format","Message ID")}validateReactionType(e){if(!Xn(e))throw zt("reactionType","Reaction type");if(!ha.includes(e))throw Qt("reactionType",`one of: ${ha.join(", ")}`,"Reaction type")}async addContentReaction(e){this.validateMessageId(e.messageId),this.validateReactionType(e.reactionType);const t=ze,n={messageId:e.messageId,reactionType:e.reactionType},s=await this.http.post(t,n,this.getMultiAuthHeaders()),r=this.extractData(s),{created:i,...a}=r;return{data:a,created:i}}async removeContentReaction(e){this.validateMessageId(e.messageId),this.validateReactionType(e.reactionType);const t=`${Qe}?${new URLSearchParams({messageId:e.messageId,reactionType:e.reactionType}).toString()}`;return await this.http.delete(t,{},this.getMultiAuthHeaders()),{success:!0}}async addReactionToChatMessage(e){return this.addContentReaction(e)}async removeReactionFromChatMessage(e){return this.removeContentReaction(e)}async addReactionToComment(e){return this.addContentReaction(e)}async removeReactionFromComment(e){return this.removeContentReaction(e)}}const ma="Token name is required and must be a string";const fa="GALA|Unit|none|none";class pa extends ls{constructor(e,t,n,s=!1){super(s),this.dexBackendHttp=e,this.cache=t,this.fetchTokenDetails=n}async fetchLaunchpadTokenSpotPrice(e,t,n){if(!Xn(e))throw new Ot(ma,"tokenName",kt);let s;if(void 0!==n)try{this.logger.debug(`Checking graduation status for token: ${e}`);const t=await n(e);!0===t.isGraduated&&(s=Hi(t.sellingToken))}catch(t){this.logger.debug(`Could not determine graduation status for ${e}, falling back to bonding curve: ${$t(t)}`)}if(void 0!==s)return this.logger.debug(`Token ${e} is graduated, using its swap backend price`),this.fetchMarketUsdPrice(s);try{this.logger.debug(`Using bonding curve calculation for token: ${e}`);const n=await t({tokenName:e,amount:"1",type:"native"}),s=await this.fetchMarketUsdPrice(fa),r=$n(n.amount,0)/1e18;if(r<=0)throw new Ot(`Invalid token amount calculation: ${r}`,"amount","INVALID_CALCULATION");return{symbol:pn(e),price:s.price/r}}catch(t){throw Xt(`Failed to calculate launchpad token spot price for ${e}: ${$t(t)}`,void 0,Bt(t)?t:void 0)}}async resolveAuthoritativeSymbol(e){if(e===fa)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 Xt("GalaChainService not available for token metadata fetch",500);n=(await this.fetchTokenDetails(e)).symbol}catch(t){throw Xt(`Could not resolve the symbol for ${e} from the token class, and a symbol cannot be derived from the class key: ${$t(t)}`)}if(""===n)throw Xt(`Token class for ${e} has no symbol`);return this.cache?.setByTokenId(e,{symbol:n}),n}async fetchMarketUsdPrice(e){try{const t=function(e){if(!Xn(e))throw new Error("Invalid token format: token must be a non-empty string");return e.replace(/\|/g,"$")}(e);if(this.logger.debug(`Fetching swap backend price for token: ${t}`),void 0===this.dexBackendHttp)throw Xt("DEX Backend API client not configured");const n=await this.resolveAuthoritativeSymbol(e),s=await this.dexBackendHttp.request({method:"GET",url:"/market/price",params:{assetIds:t}}),r=null!==s&&"object"==typeof s?s:{},i=Object.keys(r).find(e=>e.toUpperCase()===n.toUpperCase()),a=void 0!==i?r[i]:1===Object.keys(r).length?Object.values(r)[0]:void 0,o=a?.price;if("number"!=typeof o||!Number.isFinite(o))throw new Ot(`Invalid price response: no market price for ${t}`,"data","INVALID_RESPONSE");return this.logger.debug(`Swap backend price for ${n}: $${o}`),{symbol:n,price:o}}catch(e){if(e instanceof Ot)throw e;throw Xt(`Failed to fetch DEX spot price: ${$t(e)}`)}}}const va=20,Aa=3e3,Ea=1e3,ya=!0,Ta=!0,Sa=!1,ba={LOGIN:"login",LOGOUT:"logout",TOKEN_BUY:"token_buy",TOKEN_SELL:"token_sell",TOKEN_SWAP:"token_swap",TOKEN_CREATED:"token_created",TOKEN_GRADUATED:"token_graduated",PAGE_VIEW:"page_view",PAGE_LEAVE:"page_leave",STREAM_START:"stream_start",STREAM_END:"stream_end",STREAM_VIEWERS_CHANGED:"stream_viewers_changed",CHAT_MESSAGE_SENT:"chat_message_sent",CHAT_MESSAGE_RECEIVED:"chat_message_received",LIQUIDITY_ADDED:"liquidity_added",LIQUIDITY_REMOVED:"liquidity_removed",BRIDGE_DEPOSIT:"bridge_deposit",BRIDGE_WITHDRAW:"bridge_withdraw",PROFILE_UPDATED:"profile_updated",BALANCE_CHANGED:"balance_changed",ERROR_OCCURRED:"error_occurred"};class ka{constructor(e,t={}){this.eventBuffer=[],this.flushTimer=null,this.isShuttingDown=!1,this.totalQueued=0,this.totalFlushed=0,this.totalDropped=0,this.handleVisibilityChange=()=>{"hidden"===document.visibilityState&&this.eventBuffer.length>0&&this.flushWithBeacon()},this.handleBeforeUnload=()=>{this.eventBuffer.length>0&&this.flushWithBeacon()},this.httpClient=e,this.logger=new An({debug:t.debug??!1,context:"EventsBatcherService"}),this.config={batchSize:t.batchSize??va,flushIntervalMs:t.flushIntervalMs??Aa,maxQueueSize:t.maxQueueSize??Ea,flushOnPageHide:t.flushOnPageHide??ya,flushOnPageUnload:t.flushOnPageUnload??Ta,debug:t.debug??Sa},this.setupPageLifecycleListeners()}track(e,t,n){if(this.isShuttingDown)return void this.logger.warn("EventsBatcher is shutting down, ignoring track call");const s={eventType:e,payload:t,clientTimestamp:(new Date).toISOString(),...void 0!==n?.userAddress&&""!==n.userAddress&&{userAddress:wn(n.userAddress,"userAddress")},...void 0!==n?.tokenName&&""!==n.tokenName&&{tokenName:n.tokenName},...void 0!==n?.sessionId&&""!==n.sessionId&&{sessionId:n.sessionId}};this.buffer(s),n?.immediate&&this.scheduleFlush(0)}async flush(){if(0===this.eventBuffer.length)return;this.cancelFlushTimer();const e=this.eventBuffer.splice(0);this.logger.debug(`Flushing ${e.length} events`);try{const t=await this.submitEvents(e);this.totalFlushed+=t.accepted,this.lastFlushTime=Date.now(),this.lastError=void 0,this.logger.debug(`Flush successful, accepted ${t.accepted} events`)}catch(t){throw this.eventBuffer.unshift(...e),this.lastError=t instanceof Error?t.message:String(t),this.logger.error(`Flush failed: ${this.lastError}`),t}}getStats(){const e={bufferedCount:this.eventBuffer.length,totalQueued:this.totalQueued,totalFlushed:this.totalFlushed,totalDropped:this.totalDropped};return void 0!==this.lastFlushTime&&(e.lastFlushTime=this.lastFlushTime),void 0!==this.lastError&&(e.lastError=this.lastError),e}configure(e){void 0!==e.batchSize&&(this.config.batchSize=e.batchSize),void 0!==e.flushIntervalMs&&(this.config.flushIntervalMs=e.flushIntervalMs),void 0!==e.maxQueueSize&&(this.config.maxQueueSize=e.maxQueueSize),void 0!==e.flushOnPageHide&&(this.config.flushOnPageHide=e.flushOnPageHide),void 0!==e.flushOnPageUnload&&(this.config.flushOnPageUnload=e.flushOnPageUnload)}async shutdown(e=5e3){if(this.isShuttingDown=!0,this.removePageLifecycleListeners(),0!==this.eventBuffer.length)try{await Promise.race([this.flush(),new Promise((t,n)=>setTimeout(()=>n(new Error("Flush timeout during shutdown")),e))])}catch(e){this.logger.error(`Shutdown flush failed: ${e instanceof Error?e.message:String(e)}`)}}buffer(e){this.eventBuffer.length>=this.config.maxQueueSize&&(this.eventBuffer.shift(),this.totalDropped++,this.logger.warn("Event buffer full, dropped oldest event")),this.eventBuffer.push(e),this.totalQueued++,this.eventBuffer.length>=this.config.batchSize?this.scheduleFlush(0):this.scheduleFlush(this.config.flushIntervalMs)}scheduleFlush(e){null===this.flushTimer&&(this.flushTimer=setTimeout(()=>{this.flushTimer=null,this.flush().catch(e=>{this.logger.error(`Scheduled flush failed: ${e instanceof Error?e.message:String(e)}`)})},e))}cancelFlushTimer(){null!==this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null)}async submitEvents(e){return await this.httpClient.post("/v1/events",{events:e})}setupPageLifecycleListeners(){"undefined"!=typeof document&&(this.config.flushOnPageHide&&document.addEventListener("visibilitychange",this.handleVisibilityChange),this.config.flushOnPageUnload&&window.addEventListener("beforeunload",this.handleBeforeUnload))}removePageLifecycleListeners(){"undefined"!=typeof document&&(this.config.flushOnPageHide&&document.removeEventListener("visibilitychange",this.handleVisibilityChange),this.config.flushOnPageUnload&&window.removeEventListener("beforeunload",this.handleBeforeUnload))}flushWithBeacon(){if("undefined"==typeof navigator||!navigator.sendBeacon)return;const e=this.eventBuffer.splice(0),t=JSON.stringify({events:e});try{const n=this.getBaseUrl();navigator.sendBeacon(`${n}/v1/events`,t)?(this.totalFlushed+=e.length,this.lastFlushTime=Date.now()):(this.eventBuffer.unshift(...e),this.logger.warn("sendBeacon returned false, events re-buffered"))}catch(t){this.eventBuffer.unshift(...e),this.logger.error(`sendBeacon failed: ${t instanceof Error?t.message:String(t)}`)}}getBaseUrl(){const e=this.httpClient.config;return e?.baseUrl??""}}const wa=["createdAt","eventType","userAddress"],Na=["last_hour","today","yesterday","last_7_days","last_30_days","custom"],_a=["sdk","frontend","backend","mcp"];function Ia(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Ca(e){return"number"==typeof e&&Number.isFinite(e)}function Da(e){return Ia(e)&&Ca(e.id)&&"string"==typeof e.eventType&&Ia(e.payload)&&"string"==typeof e.createdAt&&"string"==typeof e.updatedAt}function Ra(e,t,n){if(!t.some(t=>t===e))throw new Ot(`${n} must be one of: ${t.join(", ")}`,n,Nt)}class Oa extends hi{constructor(e,t,n,s=!1,r){super(e,t,n,s,r)}async getEventStats(){return function(e){if(!(Ia(e)&&Ca(e.totalEvents)&&Ca(e.todayEvents)&&Ca(e.uniqueUsers)&&Ca(e.uniqueTokens)&&Ia(e.eventsByType)))throw Xt("Malformed event statistics response");const t={};for(const[n,s]of Object.entries(e.eventsByType)){if(!Ca(s))throw Xt("Malformed event statistics response");t[n]=s}return{totalEvents:e.totalEvents,todayEvents:e.todayEvents,uniqueUsers:e.uniqueUsers,uniqueTokens:e.uniqueTokens,eventsByType:t}}(await this.http.get(it,void 0,this.getDualAuthHeaders()))}async queryEvents(e={}){!function(e){if(void 0!==e.limit&&(!Number.isInteger(e.limit)||e.limit<1||e.limit>100))throw new Ot("limit must be an integer from 1 to 100","limit",Nt);if(void 0!==e.page&&(!Number.isInteger(e.page)||e.page<1))throw new Ot("page must be a positive integer","page",Nt);void 0!==e.sortBy&&Ra(e.sortBy,wa,"sortBy"),void 0!==e.sortOrder&&Ra(e.sortOrder,["asc","desc"],"sortOrder"),void 0!==e.timePreset&&Ra(e.timePreset,Na,"timePreset"),void 0!==e.source&&Ra(e.source,_a,"source")}(e);const t={},n=new URLSearchParams;for(const[s,r]of Object.entries(e))if(void 0!==r&&("string"!=typeof r||""!==r)){if(Array.isArray(r)){const e=r.map(String);if(0===e.length)continue;for(const t of 1===e.length?[...e,...e]:e)n.append(s,t);continue}t[s]="userAddress"===s&&"string"==typeof r?wn(r,"userAddress"):r}const s=n.toString(),r=""===s?rt:`${rt}?${s}`;return function(e){if(!Ia(e)||!Array.isArray(e.data)||!Ia(e.pagination))throw Xt("Malformed events response");const t=e.pagination,n=e.data;if(!(Ca(t.page)&&Ca(t.limit)&&Ca(t.total)&&Ca(t.totalPages)&&n.every(Da)))throw Xt("Malformed events response");return{data:n,pagination:{page:t.page,limit:t.limit,total:t.total,totalPages:t.totalPages}}}(await this.http.get(r,t,this.getDualAuthHeaders()))}}function Ua(e){let t;return{requestor:async(n,s)=>{const r="string"==typeof s?.body?JSON.parse(s.body):void 0,{data:i,status:a,headers:o}=await e(n,r);t=i;const c=void 0===i?"":JSON.stringify(i),l="number"==typeof a?a:200;return{ok:l>=200&&l<300,status:l,json:()=>Promise.resolve(i),text:()=>Promise.resolve(c),headers:o??{}}},answer:()=>t}}const Ma=new Set(["GATEWAY_READ_REJECTED","GATEWAY_READ_RESPONSE_INVALID"]);class Fa extends cs{constructor(e,t=!1){super(e,t)}async fetchGalaBalance(e){return this.fetchTokenBalance(e)}async fetchTokenBalance(e,t=!1){const n=kn(e.owner,"owner");try{const{requestor:s}=Ua(async(e,t)=>({data:await this.http.post(e,t)})),r=new f({gatewayBaseUrl:"",httpRequestor:s,requestTimeoutMs:1/0}),{collection:i,category:a,type:o,additionalKey:c}=e,l=await r.fetchTokenBalance({owner:n,tokenClassKey:{collection:i,category:a,type:o,additionalKey:c},includeExpiredHolds:t});return void 0===l?null:function(e){if("0"===e.quantity)return null;const{collection:t,category:n}=e.tokenClassKey,s={quantity:e.quantity,collection:t,category:n,tokenId:Hi(e.tokenClassKey)};return e.inUseHolds.length>0&&(s.inUseHolds=[...e.inUseHolds],s.inUseQuantity=e.inUseQuantity),e.lockedHolds.length>0&&(s.lockedHolds=[...e.lockedHolds],s.lockedQuantity=e.lockedQuantity),void 0===s.lockedQuantity&&void 0===s.inUseQuantity||(s.availableQuantity=e.availableQuantity),s}(l)}catch(e){if(p(e)&&Ma.has(e.code))return null;throw Xt(`Failed to fetch token balance from GalaChain: ${$t(e)}`,void 0,Bt(e)?e:void 0)}}}function La(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Xn(t.amount)&&(void 0!==t.tokenId||Xn(t.tokenName))&&(void 0===t.lockAuthority||"string"==typeof t.lockAuthority)&&(void 0===t.expires||"number"==typeof t.expires)&&(void 0===t.name||"string"==typeof t.name)}function xa(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Xn(t.amount)&&(void 0!==t.tokenId||Xn(t.tokenName))&&(void 0===t.name||"string"==typeof t.name)}var Pa,Ba;!function(e){e.TOKEN_NOT_FOUND="TOKEN_NOT_FOUND",e.INVALID_AMOUNT="INVALID_AMOUNT",e.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",e.SIGNATURE_FAILED="SIGNATURE_FAILED",e.NETWORK_ERROR="NETWORK_ERROR",e.WALLET_REQUIRED="WALLET_REQUIRED",e.VALIDATION_ERROR="VALIDATION_ERROR",e.LOCK_NOT_FOUND="LOCK_NOT_FOUND",e.LOCK_EXPIRED="LOCK_EXPIRED",e.INSUFFICIENT_LOCKED_BALANCE="INSUFFICIENT_LOCKED_BALANCE",e.NOT_LOCK_AUTHORITY="NOT_LOCK_AUTHORITY",e.LOCK_NAME_MISMATCH="LOCK_NAME_MISMATCH"}(Pa||(Pa={}));class $a 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"}(Ba||(Ba={}));class Ga extends Error{constructor(e,t,n){super(e),this.type=t,this.details=n,this.name="TransferError"}}function Ka(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 Wa(e,t,n,s="[DEBUG] Token resolution (launchpad)"){const r=await t.resolveTokenToVault(e);if(null!==r){const t=Vi(r);return n.debug(s,{tokenName:e,vaultAddress:r,tokenInstance:{collection:t.collection,category:t.category,type:t.type,instance:t.instance}}),t}throw new Ot(`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 Ha extends cs{constructor(e,t,n,s=!1,r){super(e,s),this.wallet=t,this.tokenResolver=n,this.writer=r,this.nativeSigner=t?new Pi(t.privateKey):void 0}writeIdentity(){return void 0!==this.wallet&&void 0!==this.nativeSigner?{signer:this.nativeSigner,walletAddress:On(this.wallet.address)}:this.writer}}function ja(e,t){const{collection:n,category:s,type:r,additionalKey:i,instance:a}=e;return{tokenClassKey:{collection:n,category:s,type:r,additionalKey:i},instance:a,quantity:t}}const qa=new Set(["GATEWAY_WRITE_REJECTED","GATEWAY_RESPONSE_INVALID","GATEWAY_HTTP_ERROR"]);function Va(e,{signer:t,walletAddress:n}){const{requestor:s,answer:r}=Ua((t,n)=>e.postWithMeta(t,n));return{writes:new v({gatewayBaseUrl:"",signer:t,walletAddress:n,httpRequestor:s,requestTimeoutMs:1/0,uniqueKeyPrefix:"galaconnect-operation-"}),answer:r}}async function za(e,t,n){let s;try{s=await t(e.writes)}catch(t){throw function(e){return p(e)&&qa.has(e.code)}(t)&&n(e.answer(),void 0),t}return n(e.answer(),s)}function Qa(e){return void 0===e||""===e?{}:{uniqueKey:e}}const Xa=100,Ja=100;class Ya extends Ha{async lockTokens(e){this.validateLockTokensData(e);const t=this.writeIdentity();if(void 0===t)throw new $a("Wallet required for token lock operations",Pa.WALLET_REQUIRED);return qr(async()=>{const n=Va(this.http,t),s=n.writes.walletAddress,r=[],i=[];let a=s;const o=e.tokens.find(e=>void 0!==e.lockAuthority);void 0!==o?.lockAuthority&&(a=On(o.lockAuthority));const c=e.tokens.find(e=>void 0!==e.expires),l=e.tokens.find(e=>void 0!==e.name);for(const t of e.tokens){const e=await this.resolveTokenEntry(t);i.push(ja(e,t.amount)),r.push({tokenClassKey:{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey},quantity:t.amount,lockAuthority:void 0!==t.lockAuthority?On(t.lockAuthority):a})}return za(n,t=>t.lockTokens({tokens:i,lockAuthority:a,...void 0!==c?.expires&&{expires:c.expires},...void 0!==l?.name&&{name:l.name},...Qa(e.uniqueKey)}),(e,t)=>(this.assertLockAnswer(e,"Token lock failed"),this.extractLockResult(e,t,r)))},"Token lock failed",this.logger,t=>{throw this.handleLockError(t,"Token lock failed",e)})}async unlockTokens(e){this.validateUnlockTokensData(e);const t=this.writeIdentity();if(void 0===t)throw new $a("Wallet required for token unlock operations",Pa.WALLET_REQUIRED);return qr(async()=>{const n=[],s=[],r=e.tokens.find(e=>void 0!==e.name);for(const t of e.tokens){const e=await this.resolveTokenEntry(t);s.push(ja(e,t.amount)),n.push({tokenClassKey:{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey},quantity:t.amount})}return za(Va(this.http,t),t=>t.unlockTokens({tokens:s,...void 0!==r?.name&&{name:r.name},...Qa(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{Ht(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 $a(`${$t(t)}${n}`,Pa.NETWORK_ERROR)}}validateSharedTokenEntry(e,t,n){if(void 0===e.tokenId&&void 0===e.tokenName)throw new $a("Must provide either tokenId or tokenName for token identification",Pa.TOKEN_NOT_FOUND);if(void 0!==e.tokenName)try{ns(e.tokenName,"tokenName",gs)}catch{throw new $a("Invalid token name format",Pa.TOKEN_NOT_FOUND,{tokenName:e.tokenName})}try{wr(Tr(e.amount))}catch{throw new $a(Qt(t,"a positive number",n).message,Pa.INVALID_AMOUNT,{amount:e.amount})}}validateLockTokensData(e){if(!function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every(La)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}(e))throw new $a("Invalid lock data: missing required fields",Pa.VALIDATION_ERROR);if(e.tokens.length>Xa)throw new $a(`Batch size exceeds maximum limit of ${Xa} tokens per lock operation`,Pa.VALIDATION_ERROR);for(const t of e.tokens){if(this.validateSharedTokenEntry(t,"lockAmount","Lock amount"),void 0!==t.lockAuthority&&!Un(t.lockAuthority))throw new $a("Invalid lock authority address format",Pa.VALIDATION_ERROR,{lockAuthority:t.lockAuthority});if(void 0!==t.expires)try{Vn(t.expires,"expires")}catch{throw new $a(Qt("expires","a positive integer (epoch milliseconds)","Expires").message,Pa.VALIDATION_ERROR)}}}validateUnlockTokensData(e){if(!function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every(xa)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}(e))throw new $a("Invalid unlock data: missing required fields",Pa.VALIDATION_ERROR);if(e.tokens.length>Ja)throw new $a(`Batch size exceeds maximum limit of ${Ja} tokens per unlock operation`,Pa.VALIDATION_ERROR);for(const t of e.tokens)this.validateSharedTokenEntry(t,"unlockAmount","Unlock amount")}transactionIdOf(e,t){const n=Array.isArray(e.Data)?e.Data[0]:void 0;return t?.transactionId??n?.transactionId??n?.txnId??n?.TxnId??n?.id??void 0}extractLockResult(e,t,n){const s=this.transactionIdOf(e,t),r=t?.blockNumber;return{...void 0!==s&&{transactionId:s},...void 0!==r&&{blockNumber:r},locked:n}}extractUnlockResult(e,t,n){const s=this.transactionIdOf(e,t),r=t?.blockNumber;return{...void 0!==s&&{transactionId:s},...void 0!==r&&{blockNumber:r},unlocked:n}}handleLockError(e,t,n){if(e instanceof $a)return e;if(p(e)&&"pre_send"===e.phase)return new $a(`${t}: ${e.message}`,"SIGNING_FAILED"===(s=e.code)?Pa.SIGNATURE_FAILED:"INVALID_TOKEN_REFERENCE"===s?Pa.TOKEN_NOT_FOUND:"INVALID_QUANTITY"===s?Pa.INVALID_AMOUNT:Pa.VALIDATION_ERROR,Ka(n));var s;let r=t,i=Pa.NETWORK_ERROR;if(Wt(e)){const n=e.response?.data;if("object"==typeof n&&null!==n){const e=n.Message;"string"==typeof e&&e.length>0&&(r=`${t}: ${e}`);const s="string"==typeof e?e.toLowerCase():"";s.includes("insufficient")||s.includes("balance")?i=Pa.INSUFFICIENT_BALANCE:s.includes("lock")&&s.includes("not found")?i=Pa.LOCK_NOT_FOUND:s.includes("not found")||s.includes("token")?i=Pa.TOKEN_NOT_FOUND:s.includes("authority")?i=Pa.NOT_LOCK_AUTHORITY:s.includes("expired")&&(i=Pa.LOCK_EXPIRED)}}else Bt(e)&&(r=`${t}: ${$t(e)}`);return new $a(r,i,Ka(n))}async resolveTokenInstance(e){return qr(async()=>Wa(e,this.tokenResolver,this.logger),`Failed to resolve token '${e}'`,this.logger,t=>{if(t instanceof Ga)throw new $a($t(t),Pa.TOKEN_NOT_FOUND);throw new $a(`Failed to resolve token '${e}': ${$t(t)}`,Pa.TOKEN_NOT_FOUND,{tokenName:e})})}async resolveTokenEntry(e){if(void 0!==e.tokenId){const t=ji(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 $a("Must provide either tokenId or tokenName for token identification",Pa.TOKEN_NOT_FOUND)}}const Za=new Set(["GATEWAY_READ_REJECTED","GATEWAY_READ_RESPONSE_INVALID","TOKEN_CLASS_NOT_FOUND"]);function eo(e){const t=e?.Data;return Array.isArray(t)?t:void 0}class to extends cs{constructor(e,t=!1,n){super(e,t),this.publicAxios=n}async fetchTokenClassFromChain(e){try{const t="string"==typeof e?ji(e):e,{collection:n,category:s,type:r,additionalKey:i}=t,a={collection:n,category:s,type:r,additionalKey:i},o="Failed to fetch token class from GalaChain";return await this.readPublic(e=>e.fetchTokenClass(a),e=>{if(Ht(e,o),void 0===eo(e)?.[0])throw Xt(`Token not found on GalaChain: ${Hi(a)}`,404)},()=>Xt(`Token not found on GalaChain: ${Hi(a)}`,404))}catch(e){return this.handleTokenServiceError(e,"Token not found on GalaChain","Failed to fetch token class from GalaChain")}}async fetchTokenClassesWithSupply(e){try{if(null==e||0===e.length)throw zt("tokenClasses","Token classes array");return await this.readPublic(t=>t.fetchTokenClassesWithSupply(e),e=>{if(Ht(e,"Failed to fetch token classes with supply from GalaChain"),0===(eo(e)?.length??0))throw Xt("No token supply data found for requested token classes",404)},void 0)}catch(e){return this.handleTokenServiceError(e,"Token supply data not found on GalaChain","Failed to fetch token classes with supply from GalaChain")}}async readPublic(e,t,n){if(!this.publicAxios)throw zt("publicAxios","Public Axios instance");const s=this.publicAxios,{requestor:r,answer:i}=Ua(async(e,t)=>{const n=await s.post(e,t);return{data:n.data,status:n.status}});try{return await e(new f({gatewayBaseUrl:"",httpRequestor:r,requestTimeoutMs:1/0}))}catch(e){if(p(e)&&Za.has(e.code)&&(t(i()),"TOKEN_CLASS_NOT_FOUND"===e.code&&void 0!==n))throw n();throw e}}handleTokenServiceError(e,t,n){if(e instanceof Ot)throw e;if(Wt(e)&&404===e.response?.status)throw Xt(t,404,Bt(e)?e:void 0);if(Bt(e)&&"Error"===e.name&&$t(e).includes("status indicates failure"))throw Xt($t(e),400,Bt(e)?e:void 0);const s=$t(e);if(s.includes("Token not found")){if(e instanceof Error)throw e;throw new Error(s)}throw Xt(`${n}: ${s}`,void 0,Bt(e)?e:void 0)}}function no(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Xn(t.amount)&&(void 0!==t.tokenId||Xn(t.tokenName))}var so;!function(e){e.TOKEN_NOT_FOUND="TOKEN_NOT_FOUND",e.INVALID_AMOUNT="INVALID_AMOUNT",e.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",e.SIGNATURE_FAILED="SIGNATURE_FAILED",e.NETWORK_ERROR="NETWORK_ERROR",e.WALLET_REQUIRED="WALLET_REQUIRED",e.VALIDATION_ERROR="VALIDATION_ERROR"}(so||(so={}));class ro extends Error{constructor(e,t,n){super(e),this.type=t,this.details=n,this.name="BurnError"}}const io={validateAmount(e){const t=Tr(e);try{!function(e,t){if(e.isNaN())throw sn(t,"NaN");if(!e.isFinite())throw tn(t,"finite");if(e.isLessThanOrEqualTo(0))throw en(t,"0",e.toString())}(t,"amount")}catch(t){throw new Ga(t.message,Ba.INVALID_AMOUNT,{amount:e})}},validateUniqueKey(e){if(!Jn(e)&&Xn(e)){if(e.length>ks.MAX_LENGTH)throw new Ot(`Unique key too long. Maximum length: ${ks.MAX_LENGTH}`);if(!ks.PATTERN.test(e))throw new Ga('Invalid unique key format. Must start with "galaswap-operation-" or "galaconnect-operation-"',Ba.INVALID_AMOUNT,{uniqueKey:e})}}},ao="gala-transfer-successful",oo="token-transfer-successful",co="token-locked-successfully",lo="token-unlocked-successfully",uo="transfer-successful-no-id",ho=50;class go extends Ha{async transferGala(e){this.validateTransferGalaData(e);const t=this.writeIdentity();if(void 0===t)throw new Ga("Wallet required for GALA transfer operations",Ba.WALLET_REQUIRED);try{const n=On(e.recipientAddress),s=Va(this.http,t);return await za(s,t=>t.transferGala({to:n,quantity:e.amount,...Qa(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 Ga("Wallet required for token transfer operations",Ba.WALLET_REQUIRED);try{const n=On(e.to),s=await this.tokenInstanceOf(e.tokenId,e.tokenName,()=>new Ga("Must provide either tokenId or tokenName for token identification",Ba.TOKEN_NOT_FOUND)),r=Va(this.http,t);return await za(r,t=>t.transferToken({to:n,...ja(s,e.amount),...Qa(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 Ga)throw t;throw new Ga(`Failed to resolve token class key for '${e}': ${$t(t)}`,Ba.TOKEN_NOT_FOUND,{tokenName:e})}}async burnTokens(e){this.validateBurnTokensData(e);const t=this.writeIdentity();if(void 0===t)throw new ro("Wallet required for token burn operations",so.WALLET_REQUIRED);try{const n=[];for(const t of e.tokens){const e=await this.tokenInstanceOf(t.tokenId,t.tokenName,()=>new ro("Must provide either tokenId or tokenName for token identification",so.TOKEN_NOT_FOUND));n.push(ja(e,t.amount))}const s=Va(this.http,t);return await za(s,t=>t.burnTokens({tokens:n,...Qa(e.uniqueKey)}),(e,t)=>this.burnResultOf(e,t))}catch(t){throw this.handleBurnError(t,"Token burn failed",e)}}validateTransferGalaData(e){if(!function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Xn(t.recipientAddress)&&Xn(t.amount)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)}(e))throw new Ot("Invalid GALA transfer data: missing required fields");if(!Un(e.recipientAddress))throw new Ga("Invalid recipient address format",Ba.INVALID_RECIPIENT,{recipientAddress:e.recipientAddress});io.validateAmount(e.amount),io.validateUniqueKey(e.uniqueKey)}validateTransferTokenData(e){if(!function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Xn(t.to)&&Xn(t.amount)&&(void 0!==t.tokenId||Xn(t.tokenName))&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)}(e))throw new Ot("Invalid token transfer data: missing required fields");if(!Un(e.to))throw new Ga("Invalid recipient address format",Ba.INVALID_RECIPIENT,{recipientAddress:e.to});if(!(null!==e.tokenId&&void 0!==e.tokenId||null!==e.tokenName&&void 0!==e.tokenName))throw new Ga("Must provide either tokenId or tokenName for token identification",Ba.TOKEN_NOT_FOUND);if(null!==e.tokenName&&void 0!==e.tokenName)try{ns(e.tokenName,"tokenName",gs)}catch{throw new Ga("Invalid token name format",Ba.TOKEN_NOT_FOUND,{tokenName:e.tokenName})}io.validateAmount(e.amount),io.validateUniqueKey(e.uniqueKey)}validateBurnTokensData(e){if(!function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every(no)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}(e))throw new ro("Invalid burn data: missing required fields",so.VALIDATION_ERROR);if(e.tokens.length>ho)throw new ro(`Batch size exceeds maximum limit of ${ho} tokens per burn operation`,so.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 ro("Must provide either tokenId or tokenName for token identification",so.TOKEN_NOT_FOUND);const e=Tr(t.amount);try{wr(e)}catch{throw new ro("Burn amount must be a positive number",so.INVALID_AMOUNT,{amount:t.amount})}}}async tokenInstanceOf(e,t,n){if(null!=e){const t=ji(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 Wa(e,this.tokenResolver,this.logger,`[DEBUG] Token resolution for '${e}' (launchpad):`)}catch(t){if(t instanceof Ga)throw t;throw new Ga(`Failed to resolve token '${e}': ${$t(t)}`,Ba.TOKEN_NOT_FOUND,{tokenName:e})}}extractTransferResult(e,t,n){if(null==e)throw new Ga("No response from GalaChain transfer service",Ba.NETWORK_ERROR);const s=t?.blockNumber,r="object"==typeof e&&"Status"in e;r&&Ht(e,"Extract transaction ID");const i=r&&"Data"in e,a=t?.transactionId;if(void 0!==a)return{transactionId:a,...void 0!==s?{blockNumber:s}:{}};if(i){const t=e;if(Array.isArray(t.Data)){for(const e of t.Data)if(null!=e&&"object"==typeof e){const t=e;for(const e of["transactionId","txnId","TxnId","id","txId"]){const n=t[e];if("string"==typeof n&&n.length>0)return{transactionId:n,...void 0!==s?{blockNumber:s}:{}}}}let e=uo;if(t.Data.length>0)switch(n){case"gala":e=ao;break;case"token":e=oo;break;case"lock":e=co;break;case"unlock":e=lo}return{transactionId:e,...void 0!==s?{blockNumber:s}:{}}}}throw new Ga("Operation succeeded but transaction ID could not be extracted (missing x-transaction-id header and body fields)",Ba.NETWORK_ERROR)}burnResultOf(e,t){if(null==e)throw new ro("No response from GalaChain burn service",so.NETWORK_ERROR);try{Ht(e,"Token burn operation")}catch(e){throw new Lt($t(e),500)}return this.extractBurnResult(e,t)}extractBurnResult(e,t){const n=[];if(null!==e.Data&&void 0!==e.Data&&Array.isArray(e.Data))for(const t of e.Data)n.push({collection:t.collection??"",category:t.category??"",type:t.type??"",additionalKey:t.additionalKey??"",instance:t.instance??"0",quantity:t.quantity??"0",burnedBy:t.burnedBy??""});const s=Array.isArray(e.Data)?e.Data[0]:void 0,r=t?.transactionId??s?.transactionId??s?.txnId??s?.TxnId??s?.id??void 0,i=t?.blockNumber;return{...void 0!==r&&{transactionId:r},...void 0!==i&&{blockNumber:i},burned:n}}handleTransferError(e,t,n){if(e instanceof Ga)return e;if(e instanceof Ot)return new Ga($t(e),Ba.INVALID_AMOUNT);if(p(e)&&"pre_send"===e.phase)return new Ga(e.message,"SIGNING_FAILED"===(s=e.code)?Ba.SIGNATURE_FAILED:"INVALID_WALLET_ADDRESS"===s?Ba.INVALID_RECIPIENT:"INVALID_TOKEN_REFERENCE"===s?Ba.TOKEN_NOT_FOUND:Ba.INVALID_AMOUNT);var s;if(Wt(e)&&e.response){const t=e.response.status,s=e.response.data;if(400===t){const e=s?.message;return new Ga(("string"==typeof e?e:void 0)??"Invalid transfer request",Ba.INVALID_AMOUNT)}if(403===t)return new Ga("Insufficient balance for transfer",Ba.INSUFFICIENT_BALANCE);if(404===t){const e={};return"tokenName"in n&&(e.tokenName=n.tokenName),new Ga("Token not found",Ba.TOKEN_NOT_FOUND,e)}}if("object"==typeof e&&null!==e&&"code"in e&&("ECONNABORTED"===Kt(e)||"ETIMEDOUT"===Kt(e)))return new Ga("Transfer request timed out",Ba.NETWORK_ERROR);const r=""!==$t(e)?$t(e):t;return new Ga(r,Ba.NETWORK_ERROR)}handleBurnError(e,t,n){if(e instanceof ro)return e;if(p(e)&&"pre_send"===e.phase)return new ro(`${t}: ${e.message}`,"SIGNING_FAILED"===(s=e.code)?so.SIGNATURE_FAILED:"INVALID_TOKEN_REFERENCE"===s?so.TOKEN_NOT_FOUND:"INVALID_QUANTITY"===s?so.INVALID_AMOUNT:so.VALIDATION_ERROR,Ka(n));var s;let r=t,i=so.NETWORK_ERROR;if(Wt(e)){const n=e.response?.data;if("object"==typeof n){const e=n.Message;if("string"==typeof e&&e.length>0){r=`${t}: ${e}`;const n=e.toLowerCase();n.includes("insufficient")||n.includes("balance")?i=so.INSUFFICIENT_BALANCE:(n.includes("not found")||n.includes("token"))&&(i=so.TOKEN_NOT_FOUND)}}}else Bt(e)&&(r=`${t}: ${$t(e)}`);return new ro(r,i,Ka(n))}}class mo extends cs{constructor(e,t,n,s=!1,r,i){super(e,s),this.balanceService=new Fa(e,s),this.tokenService=new to(e,s,r),this.lockService=new Ya(e,t,n,s,i),this.transferService=new go(e,t,n,s,i)}async fetchGalaBalance(e){return this.balanceService.fetchGalaBalance(e)}async fetchTokenBalance(e,t=!1){return this.balanceService.fetchTokenBalance(e,t)}async fetchTokenClassFromChain(e){return this.tokenService.fetchTokenClassFromChain(e)}async fetchTokenDetails(e){try{return A(await this.fetchTokenClassFromChain(e))}catch(t){if(Bt(t)&&("NetworkError"===t.name||$t(t).includes("Token not found")))throw t;throw Xt(`Failed to fetch token details from GalaChain for ${"string"==typeof e?e:Hi(e)}: ${$t(t)}`,500)}}async fetchTokenClassesWithSupply(e){return this.tokenService.fetchTokenClassesWithSupply(e)}async transferGala(e){return this.transferService.transferGala(e)}async transferToken(e){return this.transferService.transferToken(e)}async resolveTokenClassKey(e){return this.transferService.resolveTokenClassKey(e)}async lockTokens(e){return this.lockService.lockTokens(e)}async unlockTokens(e){return this.lockService.unlockTokens(e)}async burnTokens(e){return this.transferService.burnTokens(e)}}class fo extends cs{async getHealth(){const e=(await this.http.get(at)).data;if(null==e)throw Xt("Health check answered no data");return e}}class po extends Error{constructor(e,t,n){super(e),this.filename=t,this.mimeType=n,this.name="FileValidationError"}}function vo(e,t,n){if(null==e)throw new po("File is required",t,n);if("undefined"!=typeof File&&e instanceof File){const t=zs.safeParse(e);if(!t.success){const n=t.error.issues.map(e=>e.message).join("; ");throw new po(n,e.name,e.type)}return}if(Buffer.isBuffer(e)){if(void 0===t||""===t)throw new po("Filename is required when uploading Buffer objects",t,n);const s=Qs.safeParse(e);if(!s.success){const e=s.error.issues.map(e=>e.message).join("; ");throw new po(e,t,n)}try{qn(t,255,"filename")}catch(e){throw new po(e.message,t,n)}const r=["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"];if(!r.includes(n))throw new po(`Invalid file type "${n}" is not allowed. Allowed types: ${r.join(", ")}`,t,n);const i=function(e){if(null==e||""===e)return"";const t=e.lastIndexOf(".");if(-1===t)return"";return e.substring(t).toLowerCase()}(t),a=[".png",".jpg",".jpeg",".gif",".webp",".svg"];if(!a.includes(i))throw new po(`File extension "${i}" is not allowed. Allowed extensions: ${a.join(", ")}`,t,n);const o=function(e){switch(e.toLowerCase()){case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";case".gif":return"image/gif";case".webp":return"image/webp";case".svg":return"image/svg+xml";default:return"application/octet-stream"}}(i);if(o!==n&&"application/octet-stream"!==o)throw new po(`File extension "${i}" does not match MIME type "${n}"`,t,n);return}throw new po("File must be a File object (browser) or Buffer (Node.js)",t,n)}function Ao(e,t="image",n){const s=new FormData;if("undefined"!=typeof File&&e instanceof File)s.append(t,e);else{if(!Buffer.isBuffer(e))throw Qt("file","a File object (browser) or Buffer (Node.js)");{const r=new Blob([e],{type:"image/png"});s.append(t,r,n)}}return s}class Eo extends cs{constructor(e,t,n=!1){super(e,n,t)}async uploadImageByTokenName(e){const{tokenName:t,options:n}=e;ts(t,"tokenName",gs);const s=`${t}.png`;vo(n.file,s,"image/png");try{const e=Ao(n.file,"image",s),r=await dn(()=>this.http.request({method:"POST",url:li(R.UPLOAD_IMAGE,{tokenName:t}),data:e,headers:this.getJwtHeaders()}),{errorContext:"Image upload failed"});return"string"==typeof r?r:""}catch(e){if(e instanceof xt)throw e;if(Bt(e)&&$t(e).includes("FormData"))throw Jt("File upload failed: FormData not supported in this environment. Ensure you have proper polyfills for Node.js environments.","FormData");throw e}}}function yo(e){if(Jn(e)||"object"!=typeof e)return{};const t={};for(const[n,s]of Object.entries(e))Jn(s)||(Xn(s)?t[n]=s:"number"==typeof s||"boolean"==typeof s?t[n]=s.toString():Array.isArray(s)?t[n]=s.join(","):t[n]="object"==typeof s?JSON.stringify(s):String(s));return t}function To(e,t){if(null==e)return[];if(Array.isArray(e))return e;const n=e[t];return Array.isArray(n)?n:[]}function So(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.owner&&""!==t.owner}function bo(e){return"string"==typeof e.quantity&&""!==e.quantity}class ko extends cs{constructor(e,t,n=!1){super(e,n,t)}async fetchPools(e={}){const t=function(e){const t=e.pageSize??ni.DEFAULT_LIMIT;if(!Number.isInteger(t)||t<1||t>bt)throw Zt("pageSize",1,bt,t);const n={pageSize:String(t)};Xn(e.cursor)&&(n.cursor=e.cursor);void 0!==e.type&&(n.type=Io("type",e.type,Tt));Xn(e.tokenName)&&(ts(e.tokenName,"tokenName",hs),n.tokenName=e.tokenName);if(Xn(e.search)){if(e.search.length>wo)throw function(e,t,n,s){const r=qt(e,s);return new Ot(`${r} must be at most ${t} characters${void 0!==n?`, received: ${n}`:""}`,e,"TOO_LONG")}("search",wo,e.search.length);n.search=e.search}!0===e.hasUpcomingShows&&(n.hasUpcomingShows="true");if(Xn(e.language)){if(!_o.test(e.language))throw Qt("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>No)throw Zt("recentlyStreamed",1,No,t);n.recentlyStreamed=String(t)}!0===e.hasRecordings&&(n.hasRecordings="true");void 0!==e.streamStatus&&(n.streamStatus=Io("streamStatus",e.streamStatus,St));if(void 0!==e.isGraduated){if("boolean"!=typeof e.isGraduated)throw nn("isGraduated","boolean",e.isGraduated);n.isGraduated=e.isGraduated?"true":"false"}void 0!==e.creatorAddress&&(n.creatorAddress=function(e){if("string"!=typeof e)throw nn("creatorAddress","string",e);return xn(e,"creatorAddress"),Ln(e)??e}(e.creatorAddress));return n}(e),n=cn(await hn(()=>this.http.get(R.FETCH_POOLS,t),{errorContext:"Failed to fetch pools"}));return{items:function(e){if(!e)return[];let t=[];if(e.tokens)if(Array.isArray(e.tokens))t=e.tokens.map(e=>({...e,createdAt:e.created_at??e.createdAt??""}));else{const n=e.tokens;t=[{...n,createdAt:n.created_at??n.createdAt??""}]}else null!==e.pools&&void 0!==e.pools&&Array.isArray(e.pools)&&(t=e.pools.map(e=>({...e,createdAt:e.created_at??e.createdAt??""})));return t}(n),pageInfo:ri(n?.pageInfo)}}async fetchAllPools(e){const t=[];let n;for(;;){const s={...e,pageSize:100,...void 0!==n&&{cursor:n}},r=await this.fetchPools(s);if(t.push(...r.items),0===r.items.length)break;const i=ii(r.pageInfo,n);if(void 0===i)break;n=i}return{items:t,pageInfo:{hasNextPage:!1,totalCount:t.length}}}async checkPool(e){!function(e){const t=gr(e);!t.success&&t.errors&&Rr(t.errors,"options")}(e),Xn(e.tokenName)&&ts(e.tokenName,"tokenName",ms);try{const t=await this.http.post(R.VALIDATE_TOKEN,{tokenName:e.tokenName,symbol:e.symbol});if(null==t)throw new Error("Invalid response from check pool endpoint");const n=t.data??t;if(null==n)throw new Error("Invalid response from check pool endpoint");if(!0===Xn(e.symbol)){return!n.symbolAvailable}if(!0===Xn(e.tokenName)){return!n.nameAvailable}return!1}catch(e){const t=String(e),n=e,s="string"==typeof n.message?n.message:"";if(t.includes("404")||t.includes("Pool not found")||s.includes("404")||s.includes("Pool not found"))return!1;const r="number"==typeof n.statusCode?n.statusCode:null;if(404===r)return!1;if(t.includes("400")||t.includes("Missing required pool identifier")||s.includes("400")||s.includes("Missing required pool identifier"))return!1;if(400===r&&s.includes("Missing required pool identifier"))return!1;throw e}}async isTokenNameAvailable(e){try{return!await this.checkPool({tokenName:e})}catch{return!1}}async isTokenSymbolAvailable(e){try{return!await this.checkPool({symbol:e})}catch{return!1}}async fetchVolumeData(e){if(!function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return fr(t,"tokenName")&&vr(t,"from")&&vr(t,"to")&&vr(t,"resolution")}(e))throw new Ot("Invalid options provided. Expected { tokenName: string, from?: number, to?: number, resolution?: number }","options","INVALID_OPTIONS");const{tokenName:t,from:n,to:s,resolution:r}=e;if(ts(t,"tokenName",hs),null==n||null==s||null==r)throw new Ot("Graph options (from, to, resolution) are required","options","MISSING_GRAPH_OPTIONS");const i={tokenName:t,from:n,to:s,resolution:r};Ur(i);const a=yo(i),o=await dn(()=>this.http.get(R.CHART,a),{errorContext:"Failed to fetch graph data"});if(!Array.isArray(o.data)||"boolean"!=typeof o.isPreviousData)throw new Lt("Invalid chart response: expected { data: candles, isPreviousData }");return{dataPoints:o.data,isPreviousData:o.isPreviousData,..."number"==typeof o.nextTime&&{nextTime:o.nextTime}}}async fetchTokenDistribution(e){if(""===e||null==e)throw zt("tokenName","Token name");let t;ts(e,"tokenName",hs);try{t=await hn(()=>this.http.get(`${R.GET_TOKEN_DISTRIBUTION}?tokenName=${e}`),{errorContext:"Failed to fetch token distribution"})}catch(t){if(Wt(t)&&500===t.response?.status)throw Xt(`Token distribution data temporarily unavailable for ${e}. This is a backend issue - please try again later.`,500,Bt(t)?t:void 0);throw t}return function(e,t,n=Sr){if(!Array.isArray(e))throw Xt("Invalid API response: expected array of holders",t);for(const n of e){if(!So(n))throw Xt("Invalid holder data: missing or invalid owner field",t);if(!bo(n))throw Xt("Invalid holder data: missing or invalid quantity field",t);const e=$n(n.quantity,NaN);if(isNaN(e)||!isFinite(e))throw Xt(`Invalid holder quantity: "${n.quantity}"`,t)}const s=e,r=s.reduce((e,t)=>e.plus(t.quantity),Tr(0));return{holders:s.map(e=>({address:e.owner,balance:e.quantity,percentage:Nr(Tr(e.quantity),r,Tr(0)).multipliedBy(100).toNumber()})),totalSupply:n(r),totalHolders:s.length,lastUpdated:new Date}}(cn(t),t.status,e=>e.toFixed())}async fetchUserHolderContext(e,t){if(""===e||null==e)throw zt("tokenName","Token name");if(""===t||null==t)throw zt("userAddress","User address");return ts(e,"tokenName",hs),dn(()=>this.http.get(`${R.GET_TOKEN_DISTRIBUTION}?tokenName=${e}`,{userAddress:wn(t,"userAddress")}),{errorContext:"Failed to fetch user holder context"})}async resolveTokenNameToVault(e){const t=await this.fetchPools({tokenName:e});if(null!==t.items&&void 0!==t.items&&Array.isArray(t.items)&&t.items.length>0)return t.items[0]?.vaultAddress??null;if(null!==t.items&&void 0!==t.items&&"object"==typeof t.items){const e=t.items.tokens;return e?.vaultAddress??null}return null}async fetchToken(e){if(null==e||"string"!=typeof e||""===e.trim())throw new Error("Token name is required and must be a non-empty string");ts(e,"tokenName",gs);try{const t=R.GET_TOKEN.replace(":tokenName",e.toLowerCase().trim()),n=cn(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 Lt?new Lt(`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&&ts(e.tokenName,"tokenName",ms);try{const t=await this.http.post(R.VALIDATE_TOKEN,{tokenName:e.tokenName?.toLowerCase().trim(),symbol:e.symbol?.toUpperCase().trim()});if(null==t)throw new Error("Invalid response from validation endpoint");const n=t.data??t;if(null==n)throw new Error("Invalid response from validation endpoint");return n}catch(e){throw this.logger.warn(`Token validation failed: ${String(e)}`),e}}async fetchTokenStats(e){if(!Xn(e))throw zt("tokenName","Token name");ts(e,"tokenName",gs);const t=R.TOKEN_STATS.replace(":tokenName",e.toLowerCase().trim());try{const e=cn(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 zt("tokenName","Token name");ts(e,"tokenName",gs),function(e){if(void 0===e.chatEnabled&&void 0===e.commentsEnabled&&void 0===e.streamingEnabled&&void 0===e.nextLiveStreamAt&&void 0===e.streamLanguage&&void 0===e.websiteUrl&&void 0===e.telegramUrl&&void 0===e.twitterUrl&&void 0===e.instagramUrl&&void 0===e.facebookUrl&&void 0===e.redditUrl&&void 0===e.tiktokUrl)throw new Ot("At least one config option must be provided (chatEnabled, commentsEnabled, streamingEnabled, nextLiveStreamAt, streamLanguage, or social URLs)","options",kt);if(void 0!==e.chatEnabled&&"boolean"!=typeof e.chatEnabled)throw nn("chatEnabled","boolean");if(void 0!==e.commentsEnabled&&"boolean"!=typeof e.commentsEnabled)throw nn("commentsEnabled","boolean");if(void 0!==e.streamingEnabled&&"boolean"!=typeof e.streamingEnabled)throw nn("streamingEnabled","boolean");if(void 0!==e.streamLanguage&&"string"!=typeof e.streamLanguage)throw nn("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 nn(n,"string or null")}if(void 0!==e.nextLiveStreamAt&&null!==e.nextLiveStreamAt){if("string"!=typeof e.nextLiveStreamAt)throw nn("nextLiveStreamAt","string or null");const t=new Date(e.nextLiveStreamAt);if(isNaN(t.getTime()))throw new Ot("nextLiveStreamAt must be a valid ISO date string","nextLiveStreamAt",_t)}}(t);const n=R.UPDATE_TOKEN_CONFIG.replace(":tokenName",e.toLowerCase().trim()),s={};void 0!==t.chatEnabled&&(s.chatEnabled=t.chatEnabled),void 0!==t.commentsEnabled&&(s.commentsEnabled=t.commentsEnabled),void 0!==t.streamingEnabled&&(s.streamingEnabled=t.streamingEnabled),void 0!==t.nextLiveStreamAt&&(s.nextLiveStreamAt=t.nextLiveStreamAt),void 0!==t.streamLanguage&&(s.streamLanguage=t.streamLanguage),void 0!==t.websiteUrl&&(s.websiteUrl=t.websiteUrl),void 0!==t.telegramUrl&&(s.telegramUrl=t.telegramUrl),void 0!==t.twitterUrl&&(s.twitterUrl=t.twitterUrl),void 0!==t.instagramUrl&&(s.instagramUrl=t.instagramUrl),void 0!==t.facebookUrl&&(s.facebookUrl=t.facebookUrl),void 0!==t.redditUrl&&(s.redditUrl=t.redditUrl),void 0!==t.tiktokUrl&&(s.tiktokUrl=t.tiktokUrl),await this.http.patch(n,s,this.getJwtHeaders())}async getTokenConfig(e){if(!Xn(e))throw zt("tokenName","Token name");ts(e,"tokenName",gs);const t=R.UPDATE_TOKEN_CONFIG.replace(":tokenName",e.toLowerCase().trim()),n=cn(await this.http.get(t));if(void 0===n)throw new Error(`Invalid response: missing token config data for "${e}"`);return n}}const wo=255,No=720,_o=/^[a-z]{2}(-[A-Z]{2})?$/u;function Io(e,t,n){const s="string"==typeof t?t.toUpperCase():void 0,r=n.find(e=>e===s);if(void 0===r)throw rn(e,t,n);return r}function Co(e){if(void 0!==e.tokenName){if(!Xn(e.tokenName))throw nn("tokenName","a non-empty string",typeof e.tokenName);ns(e.tokenName,"tokenName",hs)}if(void 0!==e.userAddress){if(!Xn(e.userAddress))throw nn("userAddress","a non-empty string",typeof e.userAddress);if(e.userAddress.length>Es)throw tn("userAddress",Es,e.userAddress.length)}if(void 0!==e.search){if("string"!=typeof e.search)throw nn("search","a string",typeof e.search);if(e.search.length>256)throw tn("search",256,e.search.length)}if(Yn(0,void 0,As,e.pageSize),void 0!==e.txnType&&"BUY"!==e.txnType&&"SELL"!==e.txnType)throw Qt("txnType",'"BUY" or "SELL"');if(void 0!==e.startDate){if(!Xn(e.startDate))throw nn("startDate","a non-empty string",typeof e.startDate);if(isNaN(Date.parse(e.startDate)))throw Qt("startDate","a valid ISO 8601 date")}if(void 0!==e.endDate){if(!Xn(e.endDate))throw nn("endDate","a non-empty string",typeof e.endDate);if(isNaN(Date.parse(e.endDate)))throw Qt("endDate","a valid ISO 8601 date")}if(void 0!==e.minAmount)try{jn(e.minAmount,0,Number.MAX_SAFE_INTEGER,"minAmount")}catch{throw Qt("minAmount","a non-negative number")}if(void 0!==e.maxAmount)try{jn(e.maxAmount,0,Number.MAX_SAFE_INTEGER,"maxAmount")}catch{throw Qt("maxAmount","a non-negative number")}void 0!==e.minAmount&&void 0!==e.maxAmount&&function(e,t,n="range"){const s="number"==typeof e?e:Number(e),r="number"==typeof t?t:Number(t);if(isNaN(s)||isNaN(r))throw nn(n,"numeric values",void 0,n);if(s>r)throw new Ot(`Minimum value (${s}) must be less than or equal to maximum value (${r}) for ${n}`,n,Dt)}(e.minAmount,e.maxAmount,"amountRange")}class Do extends cs{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 fr(t,"tokenName")&&(void 0===t.tradeType||"buy"===t.tradeType||"sell"===t.tradeType)&&pr(t,"userAddress")&&vr(t,"offset")&&vr(t,"pageSize")&&vr(t,"page")&&vr(t,"limit")}(e))throw new Ot("Invalid options provided. Expected { tokenName: string, tradeType?: string, userAddress?: string, cursor?: string, pageSize?: number, startDate?: Date, endDate?: Date, sortOrder?: string }","options","INVALID_OPTIONS");const{tokenName:t,cursor:n,pageSize:s=ni.DEFAULT_LIMIT}=e;if(!Xn(t))throw zt("tokenName","Token name");const r={pageSize:String(Math.min(s,vs))};void 0!==n&&(r.cursor=n);const i=await this.http.get(li(R.GET_TRADES,{tokenName:t}),r);if(null==i)throw new Ot("No response from trade service","response","NO_RESPONSE");const a=cn(i),o=To(a,"trades"),c=a?.pageInfo;return{items:o,pageInfo:c??{hasNextPage:!1}}}buildTradesQueryParams(e){const t={};null!==e.tokenName&&void 0!==e.tokenName&&e.tokenName.length>0&&(t.tokenName=fn(e.tokenName)),null!==e.userAddress&&void 0!==e.userAddress&&e.userAddress.length>0&&(t.userAddress=wn(e.userAddress,"userAddress")),null!==e.search&&void 0!==e.search&&e.search.length>0&&(t.search=e.search);const n=void 0!==e.pageSize?function(e,t=1,n=ni.BACKEND_MAX_PAGE_SIZE){return Math.max(t,Math.min(n,Math.ceil(e??t)))}(e.pageSize,1,As):As;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){Co(e);const t=this.buildTradesQueryParams(e);return dn(()=>this.http.get(Xe,t),{errorContext:"Failed to fetch trades"})}}gs.MIN_LENGTH,gs.MAX_LENGTH;function Ro(e){return Xn(e)&&Cn(e)}function Oo(e,t,n=1){if(null==e||""===e)return null;if("string"!=typeof e)return null;const s=e.trim();return s.length<n?null:s}Zn({BOTH:"both",HELD:"held",CREATED:"created"});function Uo(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Mo(e){return"number"==typeof e&&Number.isFinite(e)}function Fo(e){return null===e||"string"==typeof e}function Lo(e){return Array.isArray(e)&&e.every(e=>Uo(e)&&"string"==typeof e.badgeName&&"boolean"==typeof e.isActive)}function xo(e){return Uo(e)&&"string"==typeof e.address&&Fo(e.fullName)&&Fo(e.profileImage)&&Fo(e.bio)&&function(e){return Uo(e)&&Mo(e.tokensCreated)&&Mo(e.tokensGraduated)&&Mo(e.graduationRate)&&Mo(e.totalTrades)&&"string"==typeof e.totalVolumeGala&&Fo(e.totalVolumeUsd)&&(null===e.holdingsCount||Mo(e.holdingsCount))&&Fo(e.accountCreatedAt)&&Mo(e.accountAgeDays)}(e.stats)&&Lo(e.launchBadge)&&Lo(e.successBadge)&&Lo(e.volumeBadge)&&Lo(e.engagementBadge)&&"boolean"==typeof e.isLiveStreaming&&Fo(e.liveStreamToken)}class Po extends cs{constructor(e,t,n=!1){super(e,n,t)}async fetchProfile(e){const t=e??this.http.getAddress();if(""===t||null==t||!Ro(t))throw Qt("address","eth|[40-hex-chars] or client|[identifier]","Address");if(void 0===e){const e=await dn(()=>this.http.get(R.GET_CURRENT_USER,void 0,this.getJwtHeaders()),{errorContext:"Failed to fetch profile"});if(!(Uo(n=e)&&"string"==typeof n.address&&Fo(n.fullName)&&Fo(n.profileImage)&&"string"==typeof n.bio&&Lo(n.launchBadge)&&Lo(n.successBadge)))throw Xt("Malformed profile response");return e}var n;const s=await dn(()=>this.http.get(R.GET_PROFILE.replace(":address",wn(t,"address"))),{errorContext:"Failed to fetch profile"});if(!xo(s))throw Xt("Malformed profile response");return s}async updateProfile(e){this.validateUpdateProfileData(e);const t={};void 0!==e.fullName&&(t.fullName=e.fullName.trim()),void 0!==e.profileImage&&(t.profileImage=e.profileImage),await dn(()=>this.http.put(R.UPDATE_PROFILE,t,this.getJwtHeaders()),{errorContext:"Profile update failed"})}async uploadProfileImage(e){this.validateUploadProfileImageOptions(e);try{const t=void 0===e.address?"profile-image.png":`profile-image-${e.address}.png`,n=Ao(e.file,"image",t),s=await dn(()=>this.http.request({method:"POST",url:R.UPLOAD_PROFILE_IMAGE,data:n,headers:this.getJwtHeaders()}),{errorContext:"Image upload failed"});return"string"==typeof s?s:""}catch(e){if(e instanceof Ot||e instanceof xt)throw e;if(e instanceof Lt)throw new Lt(`Profile image upload failed: ${$t(e)}`,e.statusCode,e);throw new Ot(`Profile image upload failed: ${$t(e)}`,"file","UPLOAD_FAILED")}}async fetchTokenList(e){if(void 0!==e.status&&"created"!==e.type)throw new Ot("status filters only apply when type=created","status","INVALID_FILTER");const t=e.tokenName,n={...e},s="created"===e.type;s&&(delete n.tokenName,void 0!==t&&void 0===n.search&&(n.search=t));const r=await this.buildFetchRequest(R.GET_TOKEN_LIST,n,{includeType:!0,requestType:e.type??"both",responseKey:s?"launches":"token",errorMessage:"Failed to fetch token list"});return s&&void 0!==t?{...r,tokens:r.tokens.filter(e=>e.tokenName===t||e.name===t)}:r}async fetchTokensHeld(e){if(void 0!==e.type&&"held"!==e.type)throw new Ot("fetchTokensHeld only supports type=held","type","INVALID_TYPE");if(void 0!==e.status)throw new Ot("status filters only apply when type=created","status","INVALID_FILTER");return this.buildFetchRequest(R.GET_TOKENS_HELD,e,{includeType:!0,requestType:"held",responseKey:"token",errorMessage:"Failed to fetch tokens held"})}async fetchTokensCreated(e){const{cursor:t,pageSize:n,search:s,tokenName:r,status:i}=e??{};if(void 0!==e?.type&&"created"!==e.type)throw new Ot("fetchTokensCreated only supports type=created","type","INVALID_TYPE");const a=e?.address??this.http.getAddress();if(null==a||""===a)throw new Ot("Wallet address not available - wallet not configured","address","NO_WALLET");const o={type:"created",address:a,pageSize:n??ni.DEFAULT_LIMIT};return void 0!==t&&(o.cursor=t),void 0!==s&&(o.search=s),void 0!==r&&void 0===s&&(o.search=r),void 0!==r&&(o.tokenName=r),void 0!==i&&(o.status=i),this.fetchTokenList(o)}async getManagedTokens(e={}){const t={};return void 0!==e.cursor&&(t.cursor=e.cursor),void 0!==e.pageSize&&(t.pageSize=String(Math.min(e.pageSize,vs))),dn(()=>this.http.get(R.GET_MANAGED_TOKENS,t,this.getJwtHeaders()),{errorContext:"Failed to fetch managed tokens"})}async getUserGalaBalance(e){if("string"!=typeof e||""===e.trim())throw zt("address","Address");const t=wn(e.trim(),"address");return dn(()=>this.http.get(li(R.GET_GALA_BALANCE,{address:t})),{errorContext:"Failed to fetch GALA balance"})}async fetchReferralCode(){return dn(()=>this.http.get(R.GET_REFERRAL_CODE,void 0,this.getJwtHeaders()),{errorContext:"Failed to fetch referral code"})}async buildFetchRequest(e,t,n){this.validateGetTokenListOptions(t);const s=oi({pageSize:t.pageSize??ni.DEFAULT_LIMIT,...void 0!==t.cursor&&{cursor:t.cursor}},vs);di(s,t,["address","search","tokenName","status"]),n.includeType&&!e.includes("?type=")&&(s.type=n.requestType);let r=e;const i=wn(t.address??this.http.getAddress(),"address");if(void 0!==t.address&&(s.address=i),e.includes(":address")){if(0===i.length)throw zt("address","User address");r=e.replace(":address",i),delete s.address}const a=cn(await hn(()=>this.http.get(r,s),{errorContext:n.errorMessage}));return{tokens:To(a,n.responseKey).map(e=>{const t="string"==typeof e.tokenName?e.tokenName:"",s="string"==typeof e.name?e.name:t,r="string"==typeof e.createdAt?e.createdAt:"",a=e.metadata,o={...e};return delete o.metadata,{...o,id:"string"==typeof e.id?e.id:t,name:s,symbol:"string"==typeof e.symbol?e.symbol:"",type:n.requestType,address:i,balance:"string"==typeof e.balance?e.balance:"string"==typeof e.quantity?e.quantity:"0",decimals:"number"==typeof e.decimals?e.decimals:0,...null!==a&&"object"==typeof a?{metadata:a}:{},createdAt:r,updatedAt:"string"==typeof e.updatedAt?e.updatedAt:r}}),pageInfo:ri(a?.pageInfo)}}validateGetTokenListOptions(e){const t=e.pageSize??ni.DEFAULT_LIMIT;if(t<1||t>vs)throw new Ot(`pageSize must be between 1 and ${vs}`,"pageSize","OUT_OF_RANGE");if(void 0!==e.address&&!Ro(e.address))throw Qt("address","eth|[40-hex-chars] or client|[identifier]","Address");const n=Oo(e.search);if(null!==n&&!(Xn(s=n)&&s.length>=Ns&&s.length<=_s))throw Zt("search",Ns,_s,n.length,"Search query");var s;const r=Oo(e.tokenName);if(!(null===r||Xn(i=r)&&gs.PATTERN.test(i)))throw Qt("tokenName",gs.DESCRIPTION,"Token name");var i}validateUpdateProfileData(e){if(void 0!==e.address&&!Ro(e.address))throw Qt("address","eth|[40-hex-chars] or client|[identifier]","Address");if(void 0===e.fullName&&void 0===e.profileImage)throw new Ot("At least one of fullName and profileImage must be provided","options","REQUIRED");if(void 0!==e.fullName&&(t=e.fullName.trim(),!(Xn(t)&&t.length>=Is.FULL_NAME.MIN_LENGTH&&t.length<=Is.FULL_NAME.MAX_LENGTH&&Is.FULL_NAME.ALPHABETS_ONLY_PATTERN.test(t))))throw Zt("fullName",Is.FULL_NAME.MIN_LENGTH,Is.FULL_NAME.MAX_LENGTH,e.fullName.trim().length,"Full name");var t;if("string"==typeof e.profileImage&&e.profileImage.trim().length>2048)throw new Ot("profileImage must not exceed 2048 characters","profileImage","TOO_LONG")}validateUploadProfileImageOptions(e){if(void 0!==e.address&&!Ro(e.address))throw Qt("address","eth|[40-hex-chars] or client|[identifier]","Address")}}class Bo{constructor(e,t,n=!1){this.http=e,this.poolService=new ko(e,t,n),this.tradeService=new Do(e,n),this.userService=new Po(e,t,n),this.imageService=new Eo(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 Or(e)}async fetchToken(e){return this.poolService.fetchToken(e)}async validateToken(e){return this.poolService.validateToken(e)}async fetchTokenStats(e){return this.poolService.fetchTokenStats(e)}async updateTokenConfig(e,t){return this.poolService.updateTokenConfig(e,t)}async getTokenConfig(e){return this.poolService.getTokenConfig(e)}}const $o={CHAT_MESSAGE:"CHAT_MESSAGE",COMMENT:"COMMENT"};class Go extends hi{constructor(e,t,n,s=!1,r){super(e,t,n,s,r)}validateContent(e,t){if(!Xn(e))throw zt("content","Message content");if(0===e.trim().length)throw zt("content","Message content");qn(e,t===$o.CHAT_MESSAGE?ys.CHAT_MESSAGES_V1.MAX_LENGTH:ys.COMMENTS_V1.MAX_LENGTH,"content")}validateMessageId(e){if(!Xn(e))throw zt("id","Message ID");if(e.length<10||e.length>64)throw Qt("id","valid message ID format","Message ID")}validateMessageType(e){if(e!==$o.CHAT_MESSAGE&&e!==$o.COMMENT)throw new Ot(`type must be one of: ${Object.values($o).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,hs);const s={};void 0!==e.cursor&&(s.cursor=e.cursor),s.pageSize=e.pageSize??ni.DEFAULT_LIMIT;const r=oi(s,As),i={};void 0!==r.pageSize&&(i.pageSize=r.pageSize),void 0!==r.cursor&&(i.cursor=r.cursor),t&&(i.type=e.type.toUpperCase()),n&&(i.tokenName=fn(e.tokenName)),void 0!==e.userAddress&&""!==e.userAddress&&(i.userAddress=wn(e.userAddress,"userAddress")),void 0!==e.search&&""!==e.search&&(i.search=e.search);const a=await this.http.get(Je.GET_MESSAGES,i),o=this.extractData(a);return{messages:o.messages,pageInfo:o.pageInfo}}async createMessage(e){this.validateMessageType(e.type),this.validateTokenName(e.tokenName,hs),this.validateContent(e.content,e.type);const t={type:e.type,tokenName:fn(e.tokenName),content:e.content.trim()},n=await this.http.post(Je.CREATE_MESSAGE,t,this.getJwtHeaders());return{message:this.extractData(n)}}async updateMessage(e,t){this.validateMessageId(e),this.validateContent(t.content,t.type);const n=this.buildEndpointWithId(Je.UPDATE_MESSAGE,e),s={content:t.content.trim()},r=await this.http.put(n,s,this.getJwtHeaders());return{message:this.extractData(r)}}async deleteMessage(e){this.validateMessageId(e);const t=this.buildEndpointWithId(Je.DELETE_MESSAGE,e);return await this.http.delete(t,void 0,this.getDualAuthHeaders()),{success:!0}}async getPinnedMessage(e){this.validateTokenName(e,gs);const t=await this.http.get(Je.GET_PINNED,{tokenName:fn(e)});return{message:this.extractDataOrNull(t)}}async pinMessage(e){this.validateMessageId(e);const t=Je.PIN_MESSAGE.replace(":id",e);return await this.http.post(t,{},this.getDualAuthHeaders()),{success:!0}}async unpinMessage(e){this.validateMessageId(e);const t=Je.UNPIN_MESSAGE.replace(":id",e);return await this.http.delete(t,void 0,this.getDualAuthHeaders()),{success:!0}}async getMessageStats(){return function(e){const t=e=>"number"==typeof e&&Number.isFinite(e),n=e=>"object"==typeof e&&null!==e&&!Array.isArray(e);if(!n(e))throw Xt("Malformed message statistics response");const s=e.totalMessages,r=e.todayMessages,i=e.uniqueUsers,a=e.uniqueTokens,o=e.messagesByType;if(!(t(s)&&t(r)&&t(i)&&t(a)&&n(o)))throw Xt("Malformed message statistics response");const c={};for(const[e,n]of Object.entries(o)){if(!t(n))throw Xt("Malformed message statistics response");c[e]=n}return{totalMessages:s,todayMessages:r,uniqueUsers:i,uniqueTokens:a,messagesByType:c}}(await this.http.get(Je.GET_MESSAGE_STATS,void 0,this.getDualAuthHeaders()))}}const Ko=es({MODERATOR:"MODERATOR",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MANAGER:"MANAGER"}),Wo={TOKEN:"TOKEN",ALL_OWNER_TOKENS:"ALL_OWNER_TOKENS"},Ho=es(Wo),jo={PENDING:"PENDING",CLAIMED:"CLAIMED",REVOKED:"REVOKED",EXPIRED:"EXPIRED"};es(jo);class qo extends hi{constructor(e,t,n,s=!1,r){super(e,t,n,s,r)}validateRole(e){if(!Xn(e))throw zt("role","Role");if(!function(e){return Ko.includes(e)}(e))throw Qt("role",`one of: ${Ko.join(", ")}`,"Role")}validateInviteCodeFormat(e){if(!Xn(e))throw zt("inviteCode","Invite code");if(e.length>ws)throw Qt("inviteCode",`at most ${String(ws)} characters`,"Invite code")}validateInviteScope(e){if(void 0!==e&&(t=e,!Ho.includes(t)))throw new Ot(`Invalid invite scope. Must be one of: ${Ho.join(", ")}`,"inviteScope","INVALID_VALUE");var t}async createInvite(e){this.validateInviteScope(e.inviteScope);const t=e.inviteScope??Wo.TOKEN;if(t===Wo.TOKEN){if(void 0===e.tokenName||""===e.tokenName)throw new Ot("Token name is required for TOKEN scope invites","tokenName","REQUIRED");this.validateTokenName(e.tokenName,hs)}else if(t===Wo.ALL_OWNER_TOKENS&&e.tokenName)throw new Ot("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",ys.DESCRIPTION.MAX_LENGTH),this.validateOptionalDate(e.expiresAt,"expiresAt","Expiration date");const n=ge,s={inviteScope:t,role:e.role};t===Wo.TOKEN&&null!==e.tokenName&&void 0!==e.tokenName&&""!==e.tokenName&&(s.tokenName=fn(e.tokenName)),void 0!==e.description&&(s.description=e.description),void 0!==e.expiresAt&&(s.expiresAt=e.expiresAt);const r=await this.http.post(n,s,this.getMultiAuthHeaders());return{invite:this.extractData(r)}}async listInvites(e){void 0!==e.tokenName&&""!==e.tokenName&&this.validateTokenName(e.tokenName,hs),this.validateStatusFilter(e.status,jo);const t=pe,n={...this.buildPaginationParams(e,As)};void 0!==e.tokenName&&""!==e.tokenName&&(n.tokenName=fn(e.tokenName)),void 0!==e.status&&(n.status=e.status);const s=await this.http.get(t,n,this.getMultiAuthHeaders()),r=this.extractData(s);return{items:r.invites,pageInfo:r.pageInfo}}async revokeInvite(e){this.validatePositiveInteger(e,"inviteId","Invite ID");const t=this.buildEndpoint(ve,{id:String(e)});on(await this.http.delete(t,void 0,this.getMultiAuthHeaders()),"Failed to revoke invite")}async updateInviteRole(e){this.validatePositiveInteger(e.inviteId,"inviteId","Invite ID"),this.validateRole(e.role);const t=this.buildEndpoint(Ae,{id:String(e.inviteId)}),n={role:e.role},s=await this.http.patch(t,n,this.getMultiAuthHeaders());return{invite:this.extractData(s)}}async updateInvite(e){if(this.validatePositiveInteger(e.inviteId,"inviteId","Invite ID"),void 0===e.role&&void 0===e.description)throw new Ot("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",ys.DESCRIPTION.MAX_LENGTH);const t=this.buildEndpoint(Ee,{id:String(e.inviteId)}),n={};void 0!==e.role&&(n.role=e.role),void 0!==e.description&&(n.description=e.description);const s=await this.http.patch(t,n,this.getMultiAuthHeaders());return{invite:this.extractData(s)}}async claimInvite(e){this.validateInviteCodeFormat(e.inviteCode);const t=me,n={inviteCode:e.inviteCode},s=await this.http.post(t,n,this.getMultiAuthHeaders()),r=this.extractData(s);return"tokenName"in r&&void 0!==r.tokenName?{token:r}:{blanketAccess:r}}async getModeratedTokens(e){const t=fe,n=this.buildPaginationParams(e??{},As),s=await this.http.get(t,n,this.getMultiAuthHeaders()),r=this.extractData(s);return{items:r.tokens,pageInfo:r.pageInfo}}async getInviteByCode(e){this.validateInviteCodeFormat(e);const t=this.buildEndpoint(ye,{code:e}),n=await this.http.get(t,{});return this.extractData(n)}}const Vo="10000",zo="1000";function Qo(e){return`${e}-${Date.now()}-${Math.random().toString(36).substring(2,11)}`}function Xo(){return Date.now()+6e4}function Jo(e){return""!==e&&"string"==typeof e&&/^[a-zA-Z0-9]{3,50}$/.test(e)}function Yo(e){try{return Math.floor(parseFloat(String(e))??0).toString()}catch{return"0"}}function Zo(e){return""!==e&&"string"==typeof e&&Cn(e)}class ec extends cs{constructor(e){super(e)}getCollectionClaimFee(){return Vo}getTokenClassCreateFee(){return zo}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(!Zo(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=Vo;n.collectionClaim=e,t=String(BigInt(t)+BigInt(e))}if((e.createTokenClasses??0)>0){const s=zo,r=String(BigInt(s)*BigInt(e.createTokenClasses));n.tokenClassCreate=s,n.tokenClassCount=e.createTokenClasses,t=String(BigInt(t)+BigInt(r))}return{totalFee:t,breakdown:n}}async claimCollection(e){try{if(this.logger.debug("Claiming NFT collection",e.collectionName),!Jo(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:Xo(),uniqueKey:Qo("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),!Zo(e))throw new Error(`Invalid wallet address format: ${e}`);const t=(await this.allAuthorizations()).filter(t=>t.authorizedUsers.some(t=>In(t,e))).map(t=>({authorizedUser:kn(e,"walletAddress"),collection:t.collection}));return this.logger.debug(`Found ${t.length} collections for user`),t}catch(e){throw this.logger.error("Failed to fetch user collections",e),e}}async isCollectionAvailable(e){try{if(this.logger.debug("Checking collection availability",e),!Jo(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(!Jo(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?Yo(e.maxSupply):void 0,maxCapacity:void 0!==e.maxCapacity?Yo(e.maxCapacity):void 0,additionalKey:e.additionalKey,expiresAt:Xo(),uniqueKey:Qo("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),!Jo(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(!Zo(e.ownerAddress))throw new Error(`Invalid owner address: ${e.ownerAddress}`);const n=this.estimateMintFee({collection:e.collection,type:e.type,category:e.category,quantity:e.quantity,ownerAddress:e.ownerAddress});this.logger.debug("Estimated mint fee:",n);const s={collection:e.collection,type:e.type,category:e.category,quantity:e.quantity,owner:kn(e.ownerAddress,"ownerAddress"),additionalKey:e.additionalKey??"none",expiresAt:Xo(),uniqueKey:Qo("mint")};this.logger.debug("Built mint DTO",s);const r=`mint-${Date.now()}`,i=Array.from({length:t},(e,t)=>t+1);return{transactionId:r,mintedQuantity:e.quantity,owner:kn(e.ownerAddress,"ownerAddress"),tokenInstances:i,tokenClass:{collection:e.collection,type:e.type,category:e.category}}}catch(e){throw this.logger.error("Failed to mint NFT",e),e}}async fetchNftBalances(e,t){try{if(this.logger.debug("Fetching NFT balances for",{ownerAddress:e,collectionFilter:t}),!Zo(e))throw new Error(`Invalid owner address: ${e}`);const n=(await this.reads().fetchNftBalances({owner:kn(e,"ownerAddress"),collection:t})).map(e=>({owner:e.owner,collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey,instanceIds:[...e.instanceIds],totalOwned:e.instanceIds.length}));return this.logger.debug(`Found ${n.length} NFT balances`),n}catch(e){throw this.logger.error("Failed to fetch NFT balances",e),e}}reads(){const{requestor:e}=Ua(async(e,t)=>({data:await this.http.post(e,t)}));return new f({gatewayBaseUrl:"",httpRequestor:e,requestTimeoutMs:1/0})}allAuthorizations(){return this.reads().fetchAllNftCollectionAuthorizations({pageSize:1e3})}}class tc extends cs{constructor(e,t=!1,n){super(e,t,n)}extractData(e){if(e.error||void 0===e.data){const t=e.message??"Notification operation failed";throw new Error(t)}return e.data}async registerPushToken(e){this.logger.debug("Registering push token",{platform:e.platform});const t=this.getJwtHeaders(),n=await this.http.post(mt,{token:e.token,platform:e.platform,...void 0!==e.deviceId?{deviceId:e.deviceId}:{}},t),s=this.extractData(n);return this.logger.debug("Push token registered",{registered:s.registered}),s}async unregisterPushToken(e){this.logger.debug("Unregistering push token");const t=this.getJwtHeaders(),n=await this.http.request({method:"DELETE",url:ft,data:{token:e},headers:t}),s=this.extractData(n);return this.logger.debug("Push token unregistered",{unregistered:s.unregistered}),s}async getPreferences(){this.logger.debug("Fetching notification preferences");const e=this.getJwtHeaders(),t=await this.http.get(pt,void 0,e),n=this.extractData(t);return this.logger.debug("Fetched notification preferences",{tradesEnabled:n.tradesEnabled,streamsEnabled:n.streamsEnabled}),{preferences:n}}async updatePreferences(e){this.logger.debug("Updating notification preferences",e);const t=this.getJwtHeaders(),n=await this.http.put(vt,e,t),s=this.extractData(n);return this.logger.debug("Updated notification preferences",{tradesEnabled:s.tradesEnabled,streamsEnabled:s.streamsEnabled}),{preferences:s}}}class nc extends cs{constructor(e,t=!1){super(e,t)}async getHomeOEmbedJson(e={}){this.logger.debug("Fetching home oEmbed (JSON)");const t=await this.http.get(R.OEMBED,{format:"json"});return this.logger.debug("Fetched home oEmbed (JSON)",{title:t.title}),{oembed:t}}async getHomeOEmbedHtml(e={}){this.logger.debug("Fetching home oEmbed (HTML)");const t=await this.http.get(R.OEMBED,{},{responseType:"text"});return this.logger.debug("Fetched home oEmbed (HTML)"),{html:t}}async getPoolOEmbedJson(e){const{tokenName:t}=e;if(null==t||"string"!=typeof t||""===t.trim())throw new Ot("tokenName is required","tokenName","REQUIRED_FIELD");this.logger.debug("Fetching pool oEmbed (JSON)",{tokenName:t});const n=R.OEMBED_BUY_SELL.replace(":tokenName",t.toLowerCase().trim()),s=await this.http.get(n,{format:"json"});return this.logger.debug("Fetched pool oEmbed (JSON)",{tokenName:t,title:s.title}),{oembed:s}}async getPoolOEmbedHtml(e){const{tokenName:t}=e;if(null==t||"string"!=typeof t||""===t.trim())throw new Ot("tokenName is required","tokenName","REQUIRED_FIELD");this.logger.debug("Fetching pool oEmbed (HTML)",{tokenName:t});const n=R.OEMBED_BUY_SELL.replace(":tokenName",t.toLowerCase().trim()),s=await this.http.get(n,{},{responseType:"text"});return this.logger.debug("Fetched pool oEmbed (HTML)",{tokenName:t}),{html:s}}async getProfileOEmbedJson(e){const{address:t}=e;if(null==t||"string"!=typeof t||""===t.trim())throw new Ot("address is required","address","REQUIRED_FIELD");this.logger.debug("Fetching profile oEmbed (JSON)",{address:t});const n=R.OEMBED_PROFILE.replace(":address",encodeURIComponent(wn(t.trim(),"address"))),s=await this.http.get(n,{format:"json"});return this.logger.debug("Fetched profile oEmbed (JSON)",{address:t,title:s.title}),{oembed:s}}async getProfileOEmbedHtml(e){const{address:t}=e;if(null==t||"string"!=typeof t||""===t.trim())throw new Ot("address is required","address","REQUIRED_FIELD");this.logger.debug("Fetching profile oEmbed (HTML)",{address:t});const n=R.OEMBED_PROFILE.replace(":address",encodeURIComponent(wn(t.trim(),"address"))),s=await this.http.get(n,{},{responseType:"text"});return this.logger.debug("Fetched profile oEmbed (HTML)",{address:t}),{html:s}}}function sc(e){if(!Xn(e))throw zt("address","Address");kn(e,"address")}const rc={PENDING:"PENDING",CLAIMED:"CLAIMED",REVOKED:"REVOKED",EXPIRED:"EXPIRED"},ic={ACTIVE:"ACTIVE",REVOKED:"REVOKED"},ac=Zn(rc),oc=Zn(ic);function cc(e){try{rs(e.description,"description",255)}catch(e){if(e instanceof Ot){throw e.message.includes("255")?new Error("description must be at most 255 characters"):new Error("description must be a string")}throw e}if(void 0!==e.expiresAt){if(!Xn(e.expiresAt))throw new Error("expiresAt must be a non-empty string");try{is(e.expiresAt,"expiresAt")}catch(e){if(e instanceof Ot)throw new Error("expiresAt must be a valid ISO 8601 date string");throw e}if(bn(e.expiresAt)){if(function(e){if(null==e)return new Date;if(e instanceof Date)return isNaN(e.getTime())?new Date:e;try{const t=new Date(e);return isNaN(t.getTime())?(Sn.warn(`Invalid date string received: "${e}". Using fallback.`),new Date):t}catch(t){return Sn.warn(`Date parsing error for "${e}":`,t),new Date}}(e.expiresAt)<=new Date)throw new Error("expiresAt must be in the future")}}}function lc(e){if(!Xn(e))throw new Error("Address must be a non-empty string");try{Pn(e,"address")}catch{throw new Error("Invalid wallet address format. Must be eth|..., 0x..., or client|... format")}}function dc(e){try{Vn(e,"id")}catch(e){if(e instanceof Ot)throw new Error("Invite ID must be a positive integer");throw e}}class uc extends hi{constructor(e,t,n,s=!1,r){super(e,t,n,s,r)}validateInviteCodeFormat(e){if(!Xn(e))throw zt("inviteCode","Invite code");!function(e){if(!Xn(e))throw new Error("Invite code must be a non-empty string");qn(e,ws,"code")}(e)}validateWalletAddressFormat(e){if(!Xn(e))throw zt("address","Address");lc(e)}async createInvite(e={}){cc(e),this.validateOptionalString(e.description,"description","Description",ys.DESCRIPTION.MAX_LENGTH),this.validateOptionalDate(e.expiresAt,"expiresAt","Expiration date");const t=Se,n={};void 0!==e.description&&(n.description=e.description),void 0!==e.expiresAt&&(n.expiresAt=e.expiresAt);const s=await this.http.post(t,n,this.getDualAuthHeaders());return{invite:this.extractData(s)}}async listInvites(e={}){!function(e){if(void 0!==e.status&&!ac(e.status))throw rn("status",e.status,Object.values(rc),"status");Yn(0,void 0,50,e.pageSize,e.cursor)}(e),this.validateStatusFilter(e.status,rc);const t=be,n={...this.buildPaginationParams(e,As)};void 0!==e.status&&(n.status=e.status);const s=await this.http.get(t,n,this.getDualAuthHeaders()),r=this.extractData(s);return{items:r.invites,pageInfo:r.pageInfo}}async getInviteByCode(e){this.validateInviteCodeFormat(e);const t=this.buildEndpoint(ke,{code:e}),n=await this.http.get(t,{});return this.extractData(n)}async revokeInvite(e){dc(e);const t=this.buildEndpoint(Ne,{id:String(e)});on(await this.http.delete(t,void 0,this.getDualAuthHeaders()),"Failed to revoke invite")}async claimInvite(e){this.validateInviteCodeFormat(e);const t=we,n={inviteCode:e},s=await this.http.post(t,n,this.getJwtHeaders());return{invite:this.extractData(s)}}async listOverseers(e={}){!function(e){if(void 0!==e.status&&!oc(e.status))throw rn("status",e.status,Object.values(ic),"status");Yn(0,void 0,50,e.pageSize,e.cursor)}(e),this.validateStatusFilter(e.status,ic);const t=_e,n={...this.buildPaginationParams(e,As)};void 0!==e.status&&(n.status=e.status);const s=await this.http.get(t,n,this.getDualAuthHeaders()),r=this.extractData(s);return{items:r.overseers,pageInfo:r.pageInfo}}async createOverseerDirect(e){!function(e){if(null==e||"object"!=typeof e)throw new Ot("Options are required");if(!Xn(e.userAddress))throw new Ot("userAddress is required and must be a non-empty string");try{Pn(e.userAddress,"userAddress")}catch{throw new Ot("Invalid wallet address format. Must be eth|..., 0x..., or client|... format")}if(void 0!==e.description){if("string"!=typeof e.description)throw new Ot("description must be a string");if(e.description.length>255)throw new Ot("description must be at most 255 characters")}}(e),this.validateWalletAddressFormat(e.userAddress),this.validateOptionalString(e.description,"description","Description",ys.DESCRIPTION.MAX_LENGTH);const t=Ie,n={userAddress:wn(e.userAddress,"userAddress")};void 0!==e.description&&(n.description=e.description);const s=await this.http.post(t,n,this.getDualAuthHeaders());return{overseer:this.extractData(s)}}async revokeOverseer(e){this.validateWalletAddressFormat(e);const t=this.buildEndpoint(Ce,{address:wn(e,"address")});on(await this.http.delete(t,void 0,this.getDualAuthHeaders()),"Failed to revoke overseer")}async getMyStatus(){const e=De,t=await this.http.get(e,{},this.getJwtHeaders());return this.extractData(t)}async getSummary(){const e=Re,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getBanStats(){const e=Oe,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getTokenBanStats(){const e=Ue,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getInviteStats(){const e=Me,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getFlagStats(){const e=Fe,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getUserStats(){const e=Le,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async listOverseerUsers(e){const t=e??{};Object.keys(t).length>0&&function(e){if(null==e||"object"!=typeof e)throw new Ot("Options are required");if(void 0!==e.search){if("string"!=typeof e.search)throw new Ot("Search must be a string");if(0===e.search.length)throw new Ot("Search query cannot be empty string")}if(void 0!==e.sortBy){if("string"!=typeof e.sortBy)throw new Ot("Sort field must be a string");if(0===e.sortBy.length)throw new Ot("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 Ot('Sort order must be "asc" or "desc"')}}(t);const n=xe,s=this.buildPaginationParams(t,As);void 0!==t.search&&""!==t.search&&(s.search=t.search),void 0!==t.sortBy&&""!==t.sortBy&&(s.sortBy=t.sortBy),void 0!==t.sortOrder&&(s.sortOrder=t.sortOrder);const r=await this.http.get(n,s,this.getDualAuthHeaders()),i=this.extractData(r);return{items:i.users,pageInfo:i.pageInfo}}async getOverseerUserSummary(e){if(!Xn(e))throw zt("address","User address");lc(e);const t=this.buildEndpoint(Pe,{address:wn(e,"address")}),n=await this.http.get(t,{},this.getDualAuthHeaders());return this.extractData(n)}async flushCacheByAddress(e){sc(e);const t=this.buildEndpoint(Be,{address:wn(e,"address")}),n=await this.http.delete(t,void 0,this.getDualAuthHeaders());return this.extractData(n)}async flushCacheByToken(e){!function(e){if(!Xn(e))throw zt("tokenName","Token name")}(e);const t=this.buildEndpoint($e,{tokenName:e}),n=await this.http.delete(t,void 0,this.getDualAuthHeaders());return this.extractData(n)}async flushAllCache(e){!function(e){if(!0!==e)throw new Ot("Safety confirmation required: must pass confirm=true to flush all cache","confirm","CONFIRMATION_REQUIRED")}(e);const t=Ge,n=await this.http.delete(t,{confirm:"true"},this.getDualAuthHeaders());return this.extractData(n)}async flushWalletAliasCache(e){if(void 0!==e){sc(e);const t=this.buildEndpoint(Ke,{address:wn(e,"address")}),n=await this.http.delete(t,void 0,this.getDualAuthHeaders());return this.extractData(n)}const t=We,n=await this.http.delete(t,{confirm:"true"},this.getDualAuthHeaders());return this.extractData(n)}}class hc extends cs{constructor(e,t,n=!1){super(e,n,t)}extractData(e){const t={status:200,error:"error"in e?e.error:"success"in e?!e.success:!("data"in e),data:e.data};return void 0!==e.message&&(t.message=e.message),on(t,"Platform config operation failed",!0),e.data}async getPlatformConfig(){const e=await this.http.get(q);return this.extractData(e)}async updatePlatformConfig(e){const t=function(e){const t=[];return 0===Object.keys(e).length&&t.push("At least one field (streamingEnabled, chatEnabled, commentsEnabled, webhooksEnabled, aiModerationEnabled) must be provided"),void 0!==e.streamingEnabled&&"boolean"!=typeof e.streamingEnabled&&t.push("streamingEnabled must be a boolean"),void 0!==e.chatEnabled&&"boolean"!=typeof e.chatEnabled&&t.push("chatEnabled must be a boolean"),void 0!==e.commentsEnabled&&"boolean"!=typeof e.commentsEnabled&&t.push("commentsEnabled must be a boolean"),void 0!==e.webhooksEnabled&&"boolean"!=typeof e.webhooksEnabled&&t.push("webhooksEnabled must be a boolean"),void 0!==e.aiModerationEnabled&&"boolean"!=typeof e.aiModerationEnabled&&t.push("aiModerationEnabled must be a boolean"),t}(e);if(t.length>0)throw new Ot(t.join("; "),"options","VALIDATION_FAILED");const n=await this.http.put(V,e,this.getJwtHeaders());return this.extractData(n)}async getAvailableRoles(){const e=await this.http.get(X);return this.extractData(e)}}class gc extends cs{constructor(e,t=!1){super(e,t)}extractData(e){if(e.error||void 0===e.data){const t=e.message??"Platform stats operation failed";throw new Error(t)}return e.data}async getStats(){this.logger.debug("Fetching platform stats");const e=await this.http.get(ct),t=this.extractData(e);return this.logger.debug("Fetched platform stats",{totalTokens:t.totalTokens,timestamp:t.timestamp}),{stats:t}}}class mc extends hi{constructor(e,t,n,s){super(e,t,n,!1,s)}async getRestrictedNames(){try{return{success:!0,data:(await this.http.get(Ye,void 0,this.getJwtHeaders())).data}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}async updateRestrictedNames(e){try{if("string"!=typeof e.content)throw new Ot("Content is required");return{success:!0,data:(await this.http.put(Ze,{content:e.content},this.getJwtHeaders())).data}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}}class fc extends hi{constructor(e,t,n,s=!1,r){super(e,t,n,s,r)}async getChatStatus(e){if(null==e||""===e)throw zt("tokenName","Token name");return this.validateTokenName(e,gs),qr(async()=>{const t=this.buildEndpoint(et,{tokenName:e}),n=await this.http.get(t);return this.buildChatStatusResponse(e,this.extractData(n))},`Failed to get chat status for token: ${e}`,this.logger)}async disableChat(e){if(null==e||""===e)throw zt("tokenName","Token name");return this.validateTokenName(e,gs),qr(async()=>{const t=this.buildEndpoint(nt,{tokenName:e}),n=await this.http.post(t,{enabled:!1},this.getDualAuthHeaders());return this.buildChatStatusResponse(e,this.extractData(n))},`Failed to disable chat for token: ${e}`,this.logger)}async enableChat(e){if(null==e||""===e)throw zt("tokenName","Token name");return this.validateTokenName(e,gs),qr(async()=>{const t=this.buildEndpoint(tt,{tokenName:e}),n=await this.http.post(t,{enabled:!0},this.getDualAuthHeaders());return this.buildChatStatusResponse(e,this.extractData(n))},`Failed to enable chat for token: ${e}`,this.logger)}buildChatStatusResponse(e,t){const n={enabled:t.enabled,tokenName:t.tokenName??fn(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 zt("tokenName","Token name");if(this.validateTokenName(e,gs),"number"!=typeof t||t<0||t>600)throw new Error("slowModeSeconds must be a number between 0 and 600");return qr(async()=>{const n=this.buildEndpoint(st,{tokenName:e}),s=await this.http.patch(n,{slowModeSeconds:t},this.getDualAuthHeaders());return this.extractData(s)},`Failed to set slow mode for token: ${e}`,this.logger)}}Zn({IDLE:"IDLE",ACTIVE:"ACTIVE",DISABLED:"DISABLED"}),Zn({PREPARING:"preparing",READY:"ready",ERRORED:"errored"});const pc=Zn({YOUTUBE:"youtube",TWITCH:"twitch",FACEBOOK:"facebook",CUSTOM:"custom"});const vc={OWNER:"OWNER",MANAGER:"MANAGER",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MODERATOR:"MODERATOR"};Zn(vc),Zn({OWNER:"OWNER",MODERATOR:"MODERATOR"});function Ac(e,t="tokenName"){ts(e,t,gs)}Zn({...vc,OVERSEER:"OVERSEER"});const Ec=/^rtmps?:\/\/\S+$/u,yc=255;function Tc(e){if(Ac(e.tokenName),!Xn(e.language))throw zt("language");if(t=e.language,!Xn(t)||!/^[a-z]{2}(-[A-Z]{2})?$/.test(t))throw new Ot('language must be a valid ISO 639-1 code (e.g., "en", "es", "zh-CN")',"language",_t);var t}class Sc extends hi{constructor(e,t,n,s=!1,r){super(e,t,n,s,r)}async startStream(e){this.validateTokenName(e,gs);const t=this.buildEndpoint(F,{tokenName:e}),n=await this.http.post(t,{},this.getJwtHeaders());return this.extractData(n)}async stopStream(e){this.validateTokenName(e,gs);const t=this.buildEndpoint(L,{tokenName:e});await this.http.post(t,{},this.getJwtHeaders())}async disableStream(e){return this.toggleFeature(e,x,gs)}async enableStream(e){return this.toggleFeature(e,P,gs)}async resetStreamKey(e){this.validateTokenName(e,gs);const t=this.buildEndpoint(B,{tokenName:e}),n=await this.http.post(t,{},this.getJwtHeaders());return this.extractData(n)}async getStreamCredentials(e){this.validateTokenName(e,gs);const t=this.buildEndpoint(Y,{tokenName:e}),n=await this.http.get(t,{},this.getJwtHeaders());return this.extractData(n)}async getRecordings(e){!function(e){Ac(e.tokenName)}(e);const t=this.buildEndpoint($,{tokenName:e.tokenName}),n=await this.http.get(t),s=this.extractData(n);if(!Array.isArray(s))throw Xt("Invalid recordings response: expected an array of recordings");return{recordings:s,tokenName:fn(e.tokenName)}}async getRecordingDownload(e,t){this.validateTokenName(e,gs),this.validateRequiredString(t,"assetId","Asset ID");const n=this.buildEndpoint(G,{tokenName:e,assetId:t}),s=await this.http.get(n,{},this.getJwtHeaders());return this.extractData(s)}async deleteRecording(e,t){this.validateTokenName(e,gs),this.validateRequiredString(t,"assetId","Asset ID");const n=this.buildEndpoint(K,{tokenName:e,assetId:t});await this.http.delete(n,void 0,this.getJwtHeaders())}async getSimulcastTargets(e){this.validateTokenName(e,gs);const t=this.buildEndpoint(W,{tokenName:e}),n=await this.http.get(t,void 0,this.getJwtHeaders()),s=this.extractData(n);if(!Array.isArray(s))throw Xt("Invalid simulcast response: expected an array of targets");return{targets:s,tokenName:fn(e)}}async addSimulcastTarget(e){!function(e){if(Ac(e.tokenName),!Xn(e.platform))throw zt("platform");if(!pc(e.platform))throw new Ot("platform must be one of: 'youtube', 'twitch', 'facebook', 'custom'","platform",Nt);if(!Xn(e.url))throw zt("url");if(!Ec.test(e.url))throw new Ot("url must be a valid RTMP or RTMPS URL","url",_t);if(e.url.length>2048)throw new Ot(`url must not exceed ${String(2048)} characters`,"url",It);if(!Xn(e.streamKey))throw zt("streamKey");if(e.streamKey.length>yc)throw new Ot(`streamKey must not exceed ${String(yc)} characters`,"streamKey",It);if(void 0!==e.passthrough){if("string"!=typeof e.passthrough)throw new Ot("passthrough must be a string","passthrough",wt);if(e.passthrough.length>yc)throw new Ot(`passthrough must not exceed ${String(yc)} characters`,"passthrough",It)}}(e);const t=this.buildEndpoint(H,{tokenName:e.tokenName}),n=await this.http.post(t,{platform:e.platform,url:e.url,streamKey:e.streamKey,...void 0!==e.passthrough&&{passthrough:e.passthrough}},this.getJwtHeaders());return{target:this.extractData(n),tokenName:fn(e.tokenName)}}async removeSimulcastTarget(e,t){this.validateTokenName(e,gs),this.validateRequiredString(t,"targetId","Target ID");const n=this.buildEndpoint(j,{tokenName:e,targetId:t});await this.http.delete(n,void 0,this.getJwtHeaders())}async getGlobalStreamingStatus(){const e=await this.http.get(q);return this.extractData(e)}async disableGlobalStreaming(){const e=await this.http.put(V,{},this.getAdminHeaders());return this.extractData(e)}async enableGlobalStreaming(){const e=await this.http.put(z,{},this.getAdminHeaders());return this.extractData(e)}async setNextLiveStream(e){let t;!function(e){if(Ac(e.tokenName),null!==e.nextLiveStreamAt){if(!(e.nextLiveStreamAt instanceof Date||Xn(e.nextLiveStreamAt)))throw new Ot("nextLiveStreamAt must be a Date, ISO 8601 string, or null","nextLiveStreamAt",wt);if("string"==typeof e.nextLiveStreamAt){const t=Date.parse(e.nextLiveStreamAt);if(isNaN(t))throw new Ot("nextLiveStreamAt must be a valid ISO 8601 date string","nextLiveStreamAt",_t)}}}(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,gs);const t=`/v1/tokens/${e.toLowerCase().trim()}`;await this.http.patch(t,{nextLiveStreamAt:null},this.getJwtHeaders())}async setStreamLanguage(e){Tc(e);const t=`/v1/tokens/${e.tokenName.toLowerCase().trim()}`;await this.http.patch(t,{streamLanguage:e.language},this.getJwtHeaders())}async getStreamRole(e){!function(e){Ac(e.tokenName)}(e);const t=this.buildEndpoint(Q,{tokenName:e.tokenName}),n=this.jwtAuth?this.getJwtHeaders():{},s=await this.http.get(t,{},n);return this.extractData(s)}async getAvailableRoles(){const e=await this.http.get(X);return this.extractData(e)}async getTokenAccess(e){!function(e){Ac(e.tokenName)}(e);const t=await this.http.get(J,{tokenName:fn(e.tokenName)},this.getJwtHeaders());return this.extractData(t)}async setNextLiveStreamCountdown(e,t){return this.setNextLiveStream({tokenName:e,nextLiveStreamAt:t})}}const bc="subscribe_token",kc="unsubscribe_token",wc="subscribe_comment",Nc="unsubscribe_comment",_c="subscribe_global_feed",Ic="unsubscribe_global_feed",Cc="subscribe_events_firehose",Dc="unsubscribe_events_firehose",Rc="authenticate",Oc="send_stream_chat",Uc="SEND_STREAM_REACTION",Mc="typing_start",Fc="typing_stop",Lc=e=>xc(e.flagId);function xc(e){return"string"==typeof e||"number"==typeof e?String(e):void 0}function Pc(e,t){const n=t.map(t=>xc(e[t]));return n.every(e=>void 0!==e)?n.join("|"):void 0}const Bc={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=>xc(e.id)},FLAG_RESOLVED:{duplicateKey:e=>Pc(e,["id","status","reviewedAt"])},AI_MODERATION_COMPLETE:{duplicateKey:Lc},AI_MODERATION_FAILED:{duplicateKey:Lc},MODERATOR_INVITE_CREATED:{},MODERATOR_ADDED:{},MODERATOR_REMOVED:{},MODERATOR_ROLE_UPDATED:{},OVERSEER_ADDED:{token:"none",duplicateKey:e=>Pc(e,["userAddress","addedAt"])},OVERSEER_REMOVED:{token:"none",duplicateKey:e=>Pc(e,["userAddress","removedAt"])},POOL_CREATED:{duplicateKey:e=>Pc(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 $c(e){return Bc[e]}const Gc=Object.keys(Bc);const Kc="token:",Wc="comment:",Hc="global:feed",jc="global:events_firehose";function qc(e){if(e.startsWith(Kc)){const t={tokenName:e.slice(Kc.length)};return{join:{event:bc,payload:t},leave:{event:kc,payload:t}}}if(e.startsWith(Wc)){const t={tokenName:e.slice(8)};return{join:{event:wc,payload:t},leave:{event:Nc,payload:t}}}return e===jc?{join:{event:Cc},leave:{event:Dc}}:{join:{event:_c},leave:{event:Ic}}}const Vc=new Set(["token_subscribed","room_subscribed","global_feed_subscribed","events_firehose_subscribed"]);const zc={STREAM_CHAT_GLOBAL_STATUS:"chatEnabled",STREAM_GLOBAL_STATUS:"streamingEnabled",COMMENTS_GLOBAL_STATUS:"commentsEnabled",WEBHOOKS_GLOBAL_STATUS:"webhooksEnabled",AI_MODERATION_GLOBAL_STATUS:"aiModerationEnabled"},Qc=["STREAM_STATUS","TRADE_EXECUTED","HOLDER_COUNT_UPDATED","POOL_BADGE_ASSIGNED","VIEWER_COUNT","TOKEN_CONFIG_UPDATED","STATS_UPDATED","POOL_CREATED"],Xc=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"]),Jc=new Set(["COMMENT_CREATED","COMMENT_UPDATED","COMMENT_DELETED"]);const Yc={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"},Zc={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"},el=()=>{};function tl(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function nl(e,t){return t}function sl(e){return`${Kc}${e}`}function rl(e){return`${Wc}${e}`}function il(e){const t=fn(e);if(""===t)throw zt("tokenName","Token name");return t}class al extends ls{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 xt("Stream WebSocket URL is required. Set streamWebSocketUrl in SDK config.");this.config={url:e.url,reconnectAttempts:e.reconnectAttempts??5,reconnectDelay:e.reconnectDelay??2e3,reconnectDelayMax:e.reconnectDelayMax,subscriptionTimeout:e.subscriptionTimeout??1e4,tokenProvider:e.tokenProvider,autoConnect:e.autoConnect??!0},this.isSocketIOAvailable="function"==typeof _}register(e,t,n={}){if(this.disposed)return el;const s={name:e,deliver:t,token:n.token,filter:n.filter,room:n.room,active:!0};let r=this.subscribers.get(e);return void 0===r&&(r=new Set,this.subscribers.set(e,r)),r.add(s),void 0!==n.room&&this.acquireRoom(n.room),this.openIfNeeded(),()=>{this.release(s)}}release(e){if(!e.active)return;e.active=!1;const t=this.subscribers.get(e.name);t?.delete(e),0===t?.size&&this.subscribers.delete(e.name),void 0!==e.room&&this.releaseRoom(e.room)}hold(e){if(this.disposed)return el;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: ${$t(e)}`)})}acquireRoom(e){this.roomRefs.set(e,(this.roomRefs.get(e)??0)+1),this.syncRoom(e)}releaseRoom(e){const t=(this.roomRefs.get(e)??1)-1;t<=0?this.roomRefs.delete(e):this.roomRefs.set(e,t),this.syncRoom(e)}syncRoom(e){const t=this.liveSocket();if(null===t)return;const n=(this.roomRefs.get(e)??0)>0,s=this.roomStates.get(e);if(n&&void 0===s){if(function(e){return e===jc}(e)&&!this.authenticated)return;this.joinRoom(t,e)}else n||"joined"!==s?.phase||(t.emit(qc(e).leave.event,qc(e).leave.payload),this.roomStates.delete(e))}syncAllRooms(){for(const e of new Set([...this.roomRefs.keys(),...this.roomStates.keys()]))this.syncRoom(e)}joinRoom(e,t){const n=setTimeout(()=>{const e=this.roomStates.get(t);"joining"===e?.phase&&(this.roomStates.delete(t),this.rejectWaiters(t,new Error(`Subscription to ${t} timed out after ${this.config.subscriptionTimeout}ms`)))},this.config.subscriptionTimeout);this.roomStates.set(t,{phase:"joining",timer:n});const s=qc(t).join;e.emit(s.event,s.payload)}onRoomAcknowledged(e){const t=this.roomStates.get(e);void 0!==t?.timer&&clearTimeout(t.timer),this.roomStates.set(e,{phase:"joined",timer:void 0});const n=this.roomWaiters.get(e);if(void 0!==n){this.roomWaiters.delete(e);const t=e.startsWith(Kc)?e.slice(Kc.length):e;for(const s of n)clearTimeout(s.timer),s.resolve({room:e,tokenName:t})}this.syncRoom(e)}rejectWaiters(e,t){const n=this.roomWaiters.get(e);if(void 0!==n){this.roomWaiters.delete(e);for(const e of n)clearTimeout(e.timer),e.reject(t)}}clearRoomStates(){for(const e of this.roomStates.values())void 0!==e.timer&&clearTimeout(e.timer);this.roomStates.clear()}onServerEvent(e,t){try{this.applyEffects(e,t)}catch(t){this.logger.error(`Error handling ${e}:`,t)}if((!tl(t)||!this.isDuplicate(e,t))&&(this.deliver(e,t,tl(t)?function(e,t){const n=$c(e).token??"payload";if("none"===n)return;if("room"===n){const e=t.room;return"string"==typeof e&&e.startsWith(Kc)?e.slice(Kc.length):void 0}const s=t.tokenName;return"string"==typeof s&&""!==s?s:void 0}(e,t):void 0),tl(t)))for(const n of function(e,t){if("TOKEN_CONFIG_UPDATED"!==e)return[];const n=t.tokenName;if("string"!=typeof n)return[];const s=[];if("nextLiveStreamAt"in t){const e=t.nextLiveStreamAt;s.push({name:"STREAM_COUNTDOWN_UPDATED",payload:{tokenName:n,nextLiveStreamAt:"string"==typeof e?e:null}})}const r=t.streamLanguage;return"string"==typeof r&&s.push({name:"STREAM_LANGUAGE_UPDATED",payload:{tokenName:n,language:r}}),s}(e,t))this.deliver(n.name,n.payload,n.payload.tokenName)}isDuplicate(e,t){const n=$c(e).duplicateKey?.(t);if(void 0===n)return!1;const s=Date.now(),r=`${e}:${n}`,i=this.recentOccurrences.get(r);if(void 0!==i&&s-i<5e3)return!0;if(this.recentOccurrences.set(r,s),this.recentOccurrences.size>256)for(const[e,t]of this.recentOccurrences)s-t>=5e3&&this.recentOccurrences.delete(e);return!1}deliver(e,t,n){const s=this.subscribers.get(e);if(void 0===s)return;const r=void 0===n?void 0:fn(n);for(const n of[...s])n.active&&(void 0!==n.token&&n.token!==r||(void 0===n.filter||this.passes(n,t))&&this.invoke(e,n.deliver,t))}passes(e,t){try{return e.filter?.(t)??!0}catch(t){return this.logger.error(`Error in a ${e.name} filter:`,t),!1}}invoke(e,t,n){try{const s=t(n);s instanceof Promise&&s.catch(t=>{this.logger.error(`Error in a ${e} subscriber:`,t)})}catch(t){this.logger.error(`Error in a ${e} subscriber:`,t)}}applyEffects(e,t){if("authenticated"===e)null!==this.inFlight?this.inFlight.settle(!0):this.adoptLateAuthentication();else if("stream_chat_auth_error"===e)this.authenticated=!1,this.inFlight?.settle(!1);else if("exception"===e)this.inFlight?.settle(!1);else if(function(e){return Vc.has(e)}(e))tl(t)&&"string"==typeof t.room&&this.onRoomAcknowledged(t.room);else{const n=zc[e];void 0!==n&&(this.siteConfig={...this.siteConfig,[n]:ol(t)})}}liveSocket(){return null!==this.socket&&this.socket.connected?this.socket:null}connect(){if(this.disposed)return Promise.reject(new xt("The stream WebSocket service has been disposed."));if(!this.isSocketIOAvailable)return Promise.reject(new xt('Socket.IO not available. Install "socket.io-client" package.'));const e=this.socket??this.createSocket();if(e.connected)return Promise.resolve();if(null===this.connectAttempt){let e=()=>{},t=()=>{};const n=new Promise((n,s)=>{e=n,t=s});this.connectAttempt={promise:n,resolve:e,reject:t}}return e.connect(),this.connectAttempt.promise}createSocket(){this.logger.debug(`🔌 Connecting to Stream WebSocket: ${this.config.url}`);const e=_(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 Gc)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: ${$t(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?el:(this.connectionStateListeners.add(e),()=>{this.connectionStateListeners.delete(e)})}onReconnect(e){return this.disposed?el:(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: ${$t(e)}`),null}}authenticate(e){if(""===e)return Promise.reject(zt("token","Authentication token"));const t=this.pendingAuthenticate;if(null!==t&&t.token===e&&t.generation===this.connectionGeneration)return t.promise;this.authSequence+=1;const n=this.authSequence,s=this.runAuthenticate(e,n).finally(()=>{this.pendingAuthenticate?.promise===s&&(this.pendingAuthenticate=null)});return this.pendingAuthenticate={token:e,generation:this.connectionGeneration,promise:s},s}async runAuthenticate(e,t){if(this.disposed)return!1;const n=e??await this.resolveToken();if(t!==this.authSequence||null===n)return!1;void 0!==e&&(this.lastExplicitToken=e);try{await this.connect()}catch(e){return this.logger.warn(`Cannot authenticate, the connection failed: ${$t(e)}`),!1}for(;null!==this.inFlight;)if(await this.inFlight.settled,t!==this.authSequence)return!1;const s=this.liveSocket();if(t!==this.authSequence||null===s)return!1;if(this.authenticated&&this.authenticatedToken===n&&this.authenticatedGeneration===this.connectionGeneration)return!0;const r=this.beginAuthentication(t,n);this.lastEmitted={seq:t,token:n,generation:this.connectionGeneration},this.logger.debug("📡 Authenticating with stream server"),s.emit(Rc,{token:n});return await r.result&&t===this.authSequence}beginAuthentication(e,t){let n=()=>{};const s=new Promise(e=>{n=e}),r={seq:e,token:t,generation:this.connectionGeneration,result:s,settled:s.then(()=>{}),timer:void 0,settle:e=>{this.finishAuthentication(r,e,n)}};return r.timer=setTimeout(()=>{this.logger.warn("Stream WebSocket authentication timed out"),r.settle(!1)},this.config.subscriptionTimeout),this.inFlight=r,r}finishAuthentication(e,t,n){if(this.inFlight!==e)return;void 0!==e.timer&&clearTimeout(e.timer),this.inFlight=null;const s=e.seq===this.authSequence&&e.generation===this.connectionGeneration;t&&s&&this.markAuthenticated(e.token,e.generation),n(t&&s)}markAuthenticated(e,t){this.authenticated=!0,this.authenticatedToken=e,this.authenticatedGeneration=t,this.wantsAuthentication=!0,this.syncAllRooms()}adoptLateAuthentication(){const e=this.lastEmitted;null===e||this.authenticated||e.seq===this.authSequence&&e.generation===this.connectionGeneration&&this.markAuthenticated(e.token,e.generation)}deauthenticate(){this.authSequence+=1;const e=this.authenticated||null!==this.inFlight;this.inFlight?.settle(!1),this.pendingAuthenticate=null,this.wantsAuthentication=!1,this.lastExplicitToken=null,this.authenticated=!1,this.authenticatedToken=null,this.authenticatedGeneration=-1,e&&null!==this.socket&&!this.disposed&&(this.socket.disconnect(),this.socket.connect())}isAuthenticatedForChat(){return this.authenticated}isConnected(){return this.socket?.connected??!1}requireReady(){const e=this.liveSocket();if(null===e)throw new Ot("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(!this.authenticated)throw new Ot("Not authenticated. Call authenticate() first.","auth","NOT_AUTHENTICATED");return e}sendChatMessage(e,t){if(""===e)throw zt("tokenName","Token name");if(""===t)throw zt("content","Message content");const n=this.requireReady(),s=fn(e);this.logger.debug(`📡 Sending chat message to ${s}: ${t.slice(0,30)}...`),n.emit(Oc,{tokenName:s,content:t})}sendReaction(e,t,n=0){if(""===e)throw zt("tokenName","Token name");if(""===t)throw zt("emoji");const s=this.requireReady(),r=fn(e);this.logger.debug(`📡 Sending reaction to ${r}: ${t}`),s.emit(Uc,{tokenName:r,emoji:t,streamTime:n})}sendTypingStart(e){this.sendTypingEvent(e,Mc)}sendTypingStop(e){this.sendTypingEvent(e,Fc)}sendTypingEvent(e,t){if(""===e)throw zt("tokenName","Token name");this.requireReady().emit(t,{tokenName:fn(e)})}subscribeToken(e,t,n){const s=il(t);return this.register(e,e=>n(nl(0,e)),{token:s,room:sl(s)})}joinTokenRoom(e){return this.hold(sl(il(e)))}subscribeComment(e,t,n){const s=il(t);return this.register(e,e=>n(nl(0,e)),{token:s,room:rl(s)})}subscribeFeed(e,t){return this.register(e,e=>t(nl(0,e)),{room:Hc})}subscribeEvent(e,t){return this.register(e,e=>t(nl(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:fn(e.tokenName),s=e.userAddress;return void 0!==t||void 0!==n||void 0!==s?e=>{if(!tl(e))return!1;const r=e.eventType;if(void 0!==t&&("string"!=typeof r||!t.includes(r.toLowerCase())))return!1;const i=e.tokenName;if(void 0!==n&&("string"!=typeof i||fn(i)!==n))return!1;const a=e.userAddress;return void 0===s||"string"==typeof a&&In(a,s)}:void 0}(t);return this.register("EVENT",t=>e(nl(0,t)),{room:jc,...void 0!==n&&{filter:n}})}subscribeFeedTokenEvents(e){const t=Qc.map(t=>this.register(t,n=>e(function(e,t){return{event:e,data:nl(0,t)}}(t,n)),{room:Hc}));return()=>{for(const e of t)e()}}subscribeToGlobalFeed(e={}){const t=this.registerCallbacks(e,Zc,()=>({})),n=this.hold(Hc);return()=>{t(),n()}}addCallbacks(e){return this.registerCallbacks(e,Yc,()=>({}))}registerCallbacks(e,t,n){const s=[],r={...e};for(const[e,i]of Object.entries(t)){const t=r[e];"function"==typeof t&&s.push(this.register(i,e=>Reflect.apply(t,void 0,[e]),n(i)))}return()=>{for(const e of s)e()}}async subscribeToStream(e,t={}){const n=il(e),s=sl(n),r=this.epoch;if(await this.connect(),r!==this.epoch||this.disposed)throw new Error("WebSocket disconnected");const i=this.registerCallbacks(t,Yc,e=>{return t=e,Xc.has(t)?{token:n}:function(e){return Jc.has(e)}(e)?{token:n,room:rl(n)}:{};var t}),a=this.hold(s),o={release:()=>{i(),a()}},c=this.explicitHolds.get(n)??[];c.push(o),this.explicitHolds.set(n,c);try{return await this.waitForRoom(s,n)}catch(e){throw this.dropExplicitHold(n,o),e}}waitForRoom(e,t){return"joined"===this.roomStates.get(e)?.phase?Promise.resolve({room:e,tokenName:t}):new Promise((n,s)=>{const r={resolve:n,reject:s,timer:setTimeout(()=>{this.roomWaiters.get(e)?.delete(r),s(new Error(`Subscription to ${t} timed out after ${this.config.subscriptionTimeout}ms`))},this.config.subscriptionTimeout)},i=this.roomWaiters.get(e)??new Set;i.add(r),this.roomWaiters.set(e,i)})}dropExplicitHold(e,t){t.release();const n=(this.explicitHolds.get(e)??[]).filter(e=>e!==t);0===n.length?this.explicitHolds.delete(e):this.explicitHolds.set(e,n)}unsubscribeFromStream(e){const t=fn(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(Kc)&&e.push(t.slice(Kc.length));return e}isSubscribedToGlobalFeed(){return(this.roomRefs.get(Hc)??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 ol(e){if(!tl(e))return;const t=e.enabled;return"boolean"==typeof t?t:void 0}function cl(e){if(ts(e.tokenName,"tokenName",hs),!(null==(t=e.reason)||""===t||"string"==typeof t&&!ss(t)&&t.length<=ys.BAN_REASON.MAX_LENGTH))throw new Ot(`reason must be at most ${ys.BAN_REASON.MAX_LENGTH} characters`,"reason","TOO_LONG");var t}class ll extends hi{constructor(e,t,n,s=!1,r){super(e,t,n,s,r)}async banToken(e){cl(e);const t=He,n={tokenName:fn(e.tokenName)};if(void 0!==e.reason)try{zn(e.reason,"reason",!0),e.reason.trim().length>0&&(n.reason=e.reason)}catch{}const s=await this.http.post(t,n,this.getDualAuthHeaders());return{ban:this.extractData(s),tokenName:fn(e.tokenName)}}async unbanToken(e){!function(e){ts(e.tokenName,"tokenName",gs)}(e);const t=this.buildEndpoint(Ve,{tokenName:e.tokenName});return on(await this.http.delete(t,void 0,this.getDualAuthHeaders()),"Failed to unban token",!1),{tokenName:fn(e.tokenName)}}async listTokenBans(e={}){!function(e){Yn(0,void 0,ps,e.pageSize)}(e);const t=je,n=this.buildPaginationParams(e,ps);this.addOptionalFilterParams(n,e,["search"]);const s=await this.http.get(t,n,this.getDualAuthHeaders()),r=this.extractData(s);return{items:r.bans,pageInfo:r.pageInfo}}async getTokenBan(e){!function(e){ts(e.tokenName,"tokenName",gs)}(e);const t=this.buildEndpoint(qe,{tokenName:e.tokenName}),n=await this.http.get(t,{},this.getDualAuthHeaders()),s=this.extractDataOrNull(n);return{banned:null!==s,...null!==s&&{ban:s},tokenName:fn(e.tokenName)}}async isTokenBanned(e){return this.getTokenBan(e)}}class dl extends ls{constructor(e,t=!1){super(t),this.poolService=e,this.cache=new Map,this.accessOrder=new Set,this.cacheHits=0,this.cacheMisses=0}async resolveTokenToVault(e){if(!Xn(e))throw zt("tokenName","Token name");const t=fn(e),n=this.getCacheEntry(t);if(null!==n)return this.cacheHits++,this.updateAccessOrder(t),n.vaultAddress;this.cacheMisses++;const s=await this.poolService.resolveTokenNameToVault(e);if(null!==s&&""!==s){const e=this.parseVaultAddressToTokenClassKey(s);this.setCacheEntry(t,{vaultAddress:s,tokenClassKey:e,cachedAt:Date.now()})}return s}async resolveTokenClassKey(e){if(!Xn(e))throw zt("tokenName","Token name");const t=fn(e),n=this.getCacheEntry(t);if(null!==n)return this.cacheHits++,this.updateAccessOrder(t),n.tokenClassKey;this.cacheMisses++;const s=await this.poolService.resolveTokenNameToVault(e);if(null===s||""===s)throw Vt(e);const r=this.parseVaultAddressToTokenClassKey(s);return this.setCacheEntry(t,{vaultAddress:s,tokenClassKey:r,cachedAt:Date.now()}),r}get(e){const t=this.getCacheEntry(fn(e));return t?.vaultAddress??null}getCacheEntry(e){return this.cache.get(e)??null}setCacheEntry(e,t){this.cache.size>=dl.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=fn(e),s=this.parseVaultAddressToTokenClassKey(t);this.setCacheEntry(n,{vaultAddress:t,tokenClassKey:s,cachedAt:Date.now()})}clear(){this.cache.clear(),this.accessOrder=new Set,this.cacheHits=0,this.cacheMisses=0}getStats(){const e=Array.from(this.cache.values()).map(e=>e.cachedAt),t=this.cacheHits+this.cacheMisses;return{size:this.cache.size,keys:Array.from(this.cache.keys()),maxSize:dl.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(fn(e));return t?.tokenClassKey??null}preWarm(e){for(const{tokenName:t,vaultAddress:n}of e)this.set(t,n)}preWarmWithTokenClassKey(e){for(const{tokenName:t,vaultAddress:n,tokenClassKey:s}of e){const e=fn(t);this.setCacheEntry(e,{vaultAddress:n,tokenClassKey:s,cachedAt:Date.now()})}}parseVaultAddressToTokenClassKey(e){try{return qi(e)}catch(e){if(e instanceof Ot)throw Qt("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad","Vault address");throw e}}}dl.MAX_CACHE_SIZE=1e4;class ul extends cs{constructor(e,t=!1){super(e,t)}async fetchLaunchpadFee(){const e=await dn(()=>this.http.get(lt),{errorContext:"Failed to fetch launchpad fee"});if("number"!=typeof e.feeAmount||!Number.isFinite(e.feeAmount))throw new Ot("Failed to fetch launchpad fee: no feeAmount in the response","feeAmount","INVALID_RESPONSE");return e.feeAmount}async fetchSaleDetails(e){return dn(()=>this.http.get(dt,{tokenName:e}),{errorContext:`Failed to fetch sale details for ${e}`})}async getTradeQuote(e){const t={tokenName:e.tokenName,amount:e.amount,type:e.type,method:e.method},{signal:n}=e;return Cr(await dn(()=>void 0===n?this.http.get(ut,t):this.http.request({method:"GET",url:ut,params:t,signal:n}),{errorContext:`Failed to get trade quote for ${e.tokenName}`}),`trade quote for ${e.tokenName}`)}async getPremintQuote(e){return Cr(await dn(()=>this.http.get(ht,{amount:e}),{errorContext:"Failed to get premint quote"}),"premint quote")}}class hl extends hi{constructor(e,t,n,s=!1,r){super(e,t,n,s,r)}async emitTradeExecuted(e,t){this.validateTokenName(e,fs);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,fs);const s={action:"balance_updated",userAddress:wn(e,"userAddress"),tokenName:t,payload:n};await this.emitEvent(s)}async emitStreamStatus(e,t,n=!0){this.validateTokenName(e,fs);const s={action:"stream_status",tokenName:e,payload:t,broadcast:n};await this.emitEvent(s)}async emitViewerCount(e,t,n=!1){this.validateTokenName(e,fs);const s={action:"viewer_count",tokenName:e,payload:t,broadcast:n};await this.emitEvent(s)}async emitStreamCountdown(e,t,n=!0){this.validateTokenName(e,fs);const s={action:"stream_countdown",tokenName:e,payload:t,broadcast:n};await this.emitEvent(s)}async emitChatMessage(e,t,n=!1){this.validateTokenName(e,fs);const s={action:"chat_message",tokenName:e,payload:t,broadcast:n};await this.emitEvent(s)}async emitChatStatus(e,t,n=!1){this.validateTokenName(e,fs);const s={action:"chat_status",tokenName:e,payload:t,broadcast:n};await this.emitEvent(s)}async emitTypingIndicator(e,t,n=!1){this.validateTokenName(e,fs);const s={action:"typing_indicator",tokenName:e,payload:t,broadcast:n};await this.emitEvent(s)}async emitTokenBanned(e,t){this.validateTokenName(e,fs);const n={action:"token_banned",tokenName:e,payload:t,broadcast:!0};await this.emitEvent(n)}async emitTokenUnbanned(e,t){this.validateTokenName(e,fs);const n={action:"token_unbanned",tokenName:e,payload:t,broadcast:!0};await this.emitEvent(n)}async emitModeratorAdded(e,t,n=!1){this.validateTokenName(e,fs);const s={action:"moderator_added",tokenName:e,payload:t,broadcast:n};await this.emitEvent(s)}async emitModeratorRemoved(e,t,n=!1){this.validateTokenName(e,fs);const s={action:"moderator_removed",tokenName:e,payload:t,broadcast:n};await this.emitEvent(s)}async emitUserProfileUpdated(e,t){this.validateRequiredString(e,"userAddress","User Address");const n={action:"user_profile_updated",userAddress:wn(e,"userAddress"),payload:t};await this.emitEvent(n)}async emitSiteConfigChanged(e){const t={action:"site_config_changed",payload:e,broadcast:!0};await this.emitEvent(t)}async emitFeatureStatus(e){const t={action:"feature_status",payload:e,broadcast:!0};await this.emitEvent(t)}async emitEvent(e){this.validateRequiredString(e.action,"action","Event Action");const t=this.buildEndpoint("/v1/websocket",{});await this.http.post(t,e,this.getDualAuthHeaders())}async getConnectedClients(e){const t=this.buildEndpoint("/v1/connected-clients",{}),n={};void 0!==e?.room&&""!==e.room&&(n.room=e.room),void 0!==e?.tokenName&&(n.tokenName=e.tokenName),void 0!==e?.userAddress&&(n.userAddress=kn(e.userAddress,"userAddress")),void 0!==e?.userAddresses&&(n.userAddresses=e.userAddresses.split(",").map(e=>kn(e.trim(),"userAddresses")).join(",")),void 0!==e?.authenticated&&(n.authenticated=e.authenticated),void 0!==e?.isOverseer&&(n.isOverseer=e.isOverseer),void 0!==e?.minConnectionSeconds&&(n.minConnectionSeconds=e.minConnectionSeconds),void 0!==e?.offset&&(n.offset=e.offset),void 0!==e?.limit&&(n.limit=e.limit);const s=await this.http.get(t,Object.keys(n).length>0?n:void 0,this.getDualAuthHeaders());return this.extractData(s)}async isUserOnline(e){this.validateRequiredString(e,"userAddress","User Address");const t=await this.getConnectedClients({userAddress:e,limit:1});if(0===t.clients.length)return{online:!1};const n=t.clients[0];return void 0===n?{online:!1}:{online:!0,socketId:n.socketId,rooms:n.rooms,connectedAt:n.connectedAt}}async getOnlineUsers(e){if(!Array.isArray(e)||0===e.length)throw new xt("userAddresses must be a non-empty array");const t=await this.getConnectedClients({userAddresses:e.join(","),limit:e.length}),n=t.clients.filter(e=>"string"==typeof e.address&&""!==e.address).map(e=>e.address);return{online:n,offline:e.filter(e=>!n.some(t=>In(t,e))),clients:t.clients.map(e=>{const t={socketId:e.socketId,rooms:e.rooms};return"string"==typeof e.address&&(t.address=e.address),t})}}async getTokenViewers(e,t){this.validateTokenName(e,fs);const n={tokenName:e};void 0!==t?.authenticated&&(n.authenticated=t.authenticated),void 0!==t?.limit&&(n.limit=t.limit);const s=await this.getConnectedClients(n);return{clients:s.clients,count:s.summary.totalConnected,authenticatedCount:s.summary.authenticatedCount}}async getOnlineOverseers(){const e=await this.getConnectedClients({isOverseer:!0});return{clients:e.clients,count:e.summary.totalConnected}}async emitRecordingStatus(e,t){this.validateTokenName(e,fs);const n={action:"recording_status",tokenName:e,payload:t};await this.emitEvent(n)}async emitRecordingsCountUpdated(e,t){this.validateTokenName(e,fs);const n={action:"recordings_count_updated",tokenName:e,payload:t};await this.emitEvent(n)}async emitDownloadReady(e,t){this.validateTokenName(e,fs);const n={action:"download_ready",tokenName:e,payload:t};await this.emitEvent(n)}}class gl{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 ml{constructor(e=0){this.defaultTtlMs=e,this.cache=new Map}get(e){const t=this.cache.get(e);if(t){if(!(void 0!==t.expiresAt&&Date.now()>t.expiresAt))return t.value;this.cache.delete(e)}}set(e,t,n){const s=n??this.defaultTtlMs,r={value:t};s>0&&(r.expiresAt=Date.now()+s),this.cache.set(e,r)}has(e){return void 0!==this.get(e)}delete(e){this.cache.delete(e)}clear(){this.cache.clear()}get size(){return this.cache.size}}class fl extends ls{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 gl({maxAttempts:this.config.reconnectAttempts??5,baseDelayMs:this.config.reconnectDelay??2e3}),this.eventBuffer=new ml(3e4),this.isSocketIOAvailable=this.checkSocketIOAvailability(),fl.instances.add(this)}checkSocketIOAvailability(){try{return"function"==typeof _||(this.logger.warn('⚠️ Socket.IO client not available. Install "socket.io-client" package.'),!1)}catch(e){return this.logger.warn("⚠️ Socket.IO availability check failed:",e),!1}}async connect(){return new Promise((e,t)=>{qr(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:",$t(e)),e}this.logger.debug("🔌 Connecting to Socket.IO server:",this.config.url),this.socket=_(this.config.url,{transports:["websocket"],reconnection:!0,reconnectionAttempts:this.config.reconnectAttempts??5,reconnectionDelay:this.config.reconnectDelay??2e3}),this.socket.on("connect",()=>{this.logger.debug("✅ Socket.IO connected successfully:",this.socket?.id),this.logger.debug("📡 Connected to bundle backend WebSocket:",this.config.url),this.logger.debug("🔗 Ready to monitor transaction updates"),this.reconnectionManager.reset(),e()}),this.socket.on("connect_error",e=>{this.logger.error("❌ Socket.IO connection error:",e),t(e)}),this.socket.on("disconnect",e=>{this.logger.debug(`🔌 Socket.IO disconnected: ${e}`),this.handleReconnect()}),this.socket.on("error",e=>{this.logger.error("❌ Socket.IO error:",e)}),this.socket.onAny((e,...t)=>{if(""!==e&&t.length>0&&"object"==typeof t[0]&&null!==t[0]){const n=t[0],s=n.status??n.Status;"string"==typeof s&&(this.logger.debug(`📡 [Event Buffer] Buffering event for ${e}: ${s}`),this.eventBuffer.size>=this.MAX_BUFFER_SIZE&&this.logger.warn(`📡 [Event Buffer] Buffer approaching limit (${this.eventBuffer.size}/${this.MAX_BUFFER_SIZE})`),this.eventBuffer.set(e,n))}this.debug&&this.logger.debug(`📡 [WebSocket Event] "${e}":`,JSON.stringify(t,null,2))}),this.hasOnAnyListener=!0},"Socket.IO connection failed",this.logger,e=>{this.logger.error("Socket.IO connection failed:",e);const n=Bt(e)?e:new Error($t(e));throw t(n),n}).catch(t)})}async monitorTransaction(e,t){this.listeners.set(e,t),this.logger.debug(`📡 Starting to monitor transaction: ${e}`),this.logger.debug(`📡 WebSocket connected: ${String(this.socket?.connected??!1)}`);const n=this.eventBuffer.get(e);null!=n&&(this.logger.debug(`📡 [Event Buffer] Found buffered event for ${e}, delivering immediately`),setImmediate(()=>{this.processTransactionEvent(e,n,t)}),this.eventBuffer.delete(e));const s=this.config.timeout??3e5,r=setTimeout(()=>{if(this.listeners.has(e)){const n=Math.round(s/1e3),r={transactionId:e,status:Zr.TIMEOUT,message:`Transaction monitoring timeout - no response after ${n} seconds`,timestamp:Date.now()};this.logger.debug(`📡 Transaction timeout for ${e} (${n}s)`),t(r),this.listeners.delete(e),this.timeouts.delete(e),this.socket?.off(e)}},s);if(this.timeouts.set(e,r),this.socket?.connected)this.socket.off(e),this.logger.debug(`📡 Listening for transaction updates: ${e}`),this.logger.debug(`📡 WebSocket connection ID: ${String(this.socket.id)}`),this.logger.debug(`📡 WebSocket URL: ${this.config.url}`),this.socket.on(e,n=>{this.processTransactionEvent(e,n,t)});else{const n={transactionId:e,status:Zr.FAILED,message:"WebSocket not connected - cannot monitor transaction",timestamp:Date.now()};t(n),this.listeners.delete(e),this.timeouts.delete(e)}await Promise.resolve()}processTransactionEvent(e,t,n){this.logger.debug(`📡 Socket.IO transaction update for ${e}:`,JSON.stringify(t,null,2));const s=t,r=s?.data,i=s?.status??s?.Status??r?.status??r?.Status;let a=s?.message??s?.Message??r?.message??r?.Message??s?.error??r?.error;Xn(a)||(a=i===Yr.FAILED||i===Yr.ERROR?"Transaction failed - check transaction details":i===Yr.COMPLETED||i===Yr.PROCESSED||i===Yr.SUCCESS?"Transaction completed successfully":null!=i?`Transaction status: ${String(i)}`:"Unknown transaction status");const o=s?.blockHash??r?.blockHash,c=s?.gasUsed??r?.gasUsed,l=s?.Data??r?.Data,d={transactionId:e,status:this.mapSocketStatus(i),message:"string"==typeof a?a:"Transaction update received",timestamp:Date.now(),...null!=o?{blockHash:o}:{},...null!=c?{gasUsed:c}:{},...null!=l?{data:l}:{}};if(this.logger.debug(`📡 Mapped status for ${e}: ${String(i)} -> ${d.status}`),this.logger.debug(`📡 Final message: "${String(a)}"`),n(d),d.status===Zr.COMPLETED||d.status===Zr.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===Zr.COMPLETED?t(e):e.status!==Zr.FAILED&&e.status!==Zr.TIMEOUT||n(new Error(`Transaction ${String(e.status)}: ${e.message}`))})})}mapSocketStatus(e){const t=e?.toUpperCase();return ei[t]??Zr.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")),fl.instances.delete(this)}static cleanupAll(e=!1){for(const e of fl.instances)e.disconnect();fl.instances.clear()}isConnected(){return this.socket?.connected??!1}getSocket(){return this.socket}}fl.instances=new Set;class pl extends cs{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 Ot("limit must be between 1 and 50","limit","INVALID_LIMIT");this.logger.debug("Fetching weekly challenge leaderboard",{limit:t});const n={limit:String(t)},s=await this.http.get(gt.GET_LEADERBOARD,n),r=this.extractData(s);return this.logger.debug("Fetched weekly challenge leaderboard",{count:r.count}),{leaderboard:r}}async getTokenHistory(e){const{vaultAddress:t}=e;if("string"!=typeof t||""===t.trim())throw new Ot("vaultAddress is required","vaultAddress","REQUIRED_FIELD");this.logger.debug("Fetching token weekly history",{vaultAddress:t});const n=gt.GET_TOKEN_HISTORY.replace(":vaultAddress",encodeURIComponent(t)),s=await this.http.get(n),r=this.extractData(s);return this.logger.debug("Fetched token weekly history",{count:r.length}),{snapshots:r}}}const vl=["CreateSale","BuyWithNative","BuyExactToken","SellWithNative","SellExactToken"];class Al{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 El{constructor(e){this.bundleBaseUrl=Cl(e.bundleBaseUrl),this.launchpadBaseUrl=Cl(e.launchpadBaseUrl),this.signer=e.signer,this.walletAddress=""===e.walletAddress?"":kn(e.walletAddress,"walletAddress"),this.requestor=e.httpRequestor??fetch.bind(globalThis),this.socketFactory=e.socketFactory??(e=>_(e,{transports:["websocket"]})),this.bundleSocketFactory=e.bundleSocketFactory}attach(e){const{bundleId:t,method:n,uniqueKey:s,tokenName:r}=e;if("string"!=typeof t||""===t)throw Tl("bundleId");if(i=n,!vl.some(e=>e===i))throw Tl("method");var i;if("string"!=typeof s||""===s)throw Tl("uniqueKey");if(void 0!==r&&("string"!=typeof r||""===r))throw Tl("tokenName");if("CreateSale"===n&&void 0===r)throw Tl("tokenName");const a={method:n,dto:{uniqueKey:s,...void 0===r?{}:{tokenName:r}},stringsInstructions:[]};return new Al({bundleId:t,uniqueKey:s,method:n,wait:e=>this.waitForResult(a,t,e)})}async submit(e){let t;try{t=await this.signer.signTypedData(e.method,e.dto)}catch(e){throw function(e){if(e instanceof Di)return e;if(E(e)){const t=e instanceof Error?e.message:"The signature was rejected in the wallet.",n=y(e);return new Di(t,"WALLET_USER_REJECTED",{details:void 0===n?{}:{walletCode:n}})}const t=e instanceof Error?e.message:"Launchpad signing failed.";return new Di(t,"LAUNCHPAD_SIGNING_FAILED",{chainMessage:t})}(e)}const n=function(e){return Object.fromEntries(Object.entries(e).filter(([e])=>"prefix"!==e))}(t),s=`${this.bundleBaseUrl}/bundle`,r=await this.requestor(s,{method:"POST",headers:{"content-type":"application/json","X-Wallet-Address":this.walletAddress},body:JSON.stringify({stringsInstructions:e.stringsInstructions,method:e.method,signedDto:n})}),i=await _l(r);if(!r.ok)throw bl(r.status,i,s);const a=function(e){if("string"==typeof e&&""!==e)return e;if(!Il(e))throw new Di("Bundler returned no bundle id.","INVALID_BUNDLE_RESPONSE");const t=e.data,n=e.bundleId;if("string"==typeof t&&""!==t)return t;if(Il(t)&&"string"==typeof t.bundleId&&""!==t.bundleId)return t.bundleId;if("string"==typeof n&&""!==n)return n;throw new Di("Bundler returned no bundle id.","INVALID_BUNDLE_RESPONSE")}(i),o=Nl(e.dto,"uniqueKey");return new Al({bundleId:a,uniqueKey:o,method:e.method,wait:t=>this.waitForResult(e,a,t)})}waitForResult(e,t,n={}){const s=n.timeoutMs??6e4,r=n.pollIntervalMs??2500,i=n.signal;return new Promise((n,a)=>{const o=this.confirmationUrl(e,t);if(!0===i?.aborted)return void a(yl(e.method,t));const c=Date.now(),l=new AbortController,d=void 0===this.bundleSocketFactory;let u,h,g,m=!1;const f=()=>{p(()=>a(yl(e.method,t)))},p=e=>{m||(m=!0,clearTimeout(A),i?.removeEventListener("abort",f),l.abort(),void 0!==u&&(void 0!==h&&u.off(t,h),d&&u.disconnect()),e())},v=()=>{p(()=>a(function(e,t){const n="string"==typeof e.dto.uniqueKey?e.dto.uniqueKey:"";return new Di(`Timed out waiting for bundle ${n}`,"BUNDLE_CONFIRMATION_TIMEOUT",{details:{method:e.method,...void 0===t?{}:{lastReadFailure:{message:t.message,...void 0===t.status?{}:{status:t.status}}}}})}(e,g)))};i?.addEventListener("abort",f,{once:!0});const A=setTimeout(v,s);try{u=(this.bundleSocketFactory??this.socketFactory)(this.bundleBaseUrl),h=e=>{const t=function(e){if(!Il(e))return;const t=e.status;return"PROCESSED"!==t&&"FAILED"!==t?void 0:{status:t,data:e.data}}(e);void 0!==t&&p(()=>{"FAILED"===t.status?a(Sl(t.data)):n(t)})},u.on(t,h)}catch{u=void 0,h=void 0}this.pollConfirmation({request:e,confirmationUrl:o,startedAt:c,timeoutMs:s,pollIntervalMs:r,signal:l.signal,onReadFailure:e=>{g=e}}).then(e=>{void 0===e?v():p(()=>n(e))},e=>p(()=>a(e instanceof Error?e:new Error(String(e)))))})}confirmationUrl(e,t){return"CreateSale"===e.method?function(e,t){const n=Nl(t,"tokenName");return`${e}/v1/tokens/${encodeURIComponent(n)}`}(this.launchpadBaseUrl,e.dto):`${this.bundleBaseUrl}/bundle?id=${encodeURIComponent(t)}`}async pollConfirmation(e){const{request:t,confirmationUrl:n,startedAt:s,timeoutMs:r,pollIntervalMs:i,signal:a,onReadFailure:o}=e;for(;!a.aborted&&Date.now()-s<=r;){const e=await this.readConfirmation(t,n,a);if(a.aborted)return;if("processed"===e.kind)return e.result;if("failed"===e.kind)throw Sl(e.data);o("read-failed"===e.kind?e.error:void 0);const c=r-(Date.now()-s);if(c<=0)break;await Dl(Math.min(Math.max(0,i),c),a)}}async readConfirmation(e,t,n){try{const s=await this.requestor(t,{method:"GET",signal:n}),r=await _l(s);if("CreateSale"===e.method)return s.ok?{kind:"processed",result:{status:"PROCESSED",data:wl(r)}}:404===s.status||202===s.status?{kind:"pending"}:{kind:"read-failed",error:bl(s.status,r,t)};if(!s.ok)return{kind:"read-failed",error:bl(s.status,r,t)};const i=Il(r)?r.status:void 0;return"COMPLETED"===i||"PROCESSED"===i?{kind:"processed",result:{status:"PROCESSED",data:r}}:"FAILED"===i?{kind:"failed",data:r}:{kind:"pending"}}catch(e){const n=e instanceof Error?e.message:"The bundle confirmation read failed.";return{kind:"read-failed",error:new Di(n,"BUNDLE_REQUEST_FAILED",{details:{url:t}})}}}}function yl(e,t){return new Di("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 Tl(e){return new Di(`Cannot attach to a launchpad bundle: ${e} is missing or not accepted.`,"INVALID_BUNDLE_ATTACHMENT",{details:{field:e}})}function Sl(e){const t=kl(e)??"Launchpad bundle failed on chain.";return new Di(t,"BUNDLE_FAILED",{chainMessage:t})}function bl(e,t,n){const s=kl(t)??`Bundle request failed with HTTP ${e}`;return new Di(s,"BUNDLE_REQUEST_FAILED",{status:e,chainMessage:s,details:{body:t,url:n}})}function kl(e){if("string"==typeof e&&""!==e)return e;if(Il(e))for(const t of["chainMessage","message","Message","error"]){const n=e[t];if("string"==typeof n&&""!==n)return n;if(Il(n)){const e=kl(n);if(void 0!==e)return e}}}function wl(e){return Il(e)?e.data??e.Data??e:e}function Nl(e,t){const n=e[t];if("string"!=typeof n||""===n)throw new Di(`Missing ${t} in launchpad DTO.`,"INVALID_LAUNCHPAD_DTO");return n}async function _l(e){try{return await e.json()}catch{return e.text()}}function Il(e){return"object"==typeof e&&null!==e}function Cl(e){return e.replace(/\/$/u,"")}function Dl(e,t){return new Promise(n=>{if(t.aborted)return void n();const s=()=>{clearTimeout(r),n()},r=setTimeout(()=>{t.removeEventListener("abort",s),n()},e);t.addEventListener("abort",s,{once:!0})})}function Rl(e){return async t=>{const n=t.tokenName??await async function(e,t){const n=Gi(t).type,s=await e.findTokenNameByVault(t,n);if(void 0===s)throw new Ot(`Could not find the launchpad token for vault ${t}, so the reverse bonding curve fee ceiling cannot be quoted. Pass tokenName, or pass extraFees.maxAcceptableReverseBondingCurveFee explicitly.`,"tokenName","TOKEN_NOT_FOUND_FOR_VAULT");return s}(e,t.vaultAddress);return function(e,t){if(!/^\d+(\.\d+)?$/.test(e))throw new Ot(`Quoted reverse bonding curve fee is not a non-negative number: ${e}`,"extraFees","INVALID_QUOTED_FEE");if(!Number.isFinite(t)||t<0)throw new Ot(`Fee slippage factor must be a non-negative number, got ${String(t)}`,"maxAcceptableReverseBondingCurveFeeSlippageFactor","INVALID_FEE_SLIPPAGE_FACTOR");return new I(e).multipliedBy(new I(1).plus(new I(String(t)))).decimalPlaces(8,I.ROUND_UP).toFixed()}((await e.getTradeQuote("SellExactToken"===t.method?{tokenName:n,amount:t.quantity,type:"MEME",method:"IN"}:{tokenName:n,amount:t.quantity,type:"NATIVE",method:"OUT"})).reverseBondingCurveFee,t.feeSlippageFactor??e.defaultFeeSlippageFactor())}}const Ol="0.1",Ul="0.5",Ml=/^(?:\d+\.?\d*|\.\d+)$/u,Fl=/^[0-9A-Z]+$/u,Ll=/^[A-Za-z0-9]+$/u,xl=new I("0.1"),Pl=new I("0.5");function Bl(e){if("string"!=typeof e||!Ml.test(e))return;const t=new I(e);return t.isFinite()?t.toFixed():void 0}function $l(e){return"string"==typeof e&&""!==e}function Gl(e,t,n){void 0!==n&&"string"!=typeof n&&e.push(`${t} must be a string`)}function Kl(e,t,n){void 0===n||$l(n)||e.push(`${t} must be a non-empty string`)}function Wl(e){const t=[];if("object"!=typeof e||null===e)throw new Ot("CreateSale input must be an object","data","VALIDATION_ERROR");const n={...e},s=n.tokenName;$l(s)?Ll.test(s)||t.push("Token name can only contain letters and numbers"):t.push("Token name is required");const r=n.tokenSymbol;$l(r)?Fl.test(r.toUpperCase())||t.push("Token symbol can only contain letters and numbers"):t.push("Token symbol is required");const i=n.tokenDescription;$l(i)?i.length>1e3&&t.push("Token description must be at most 1000 characters"):t.push("Token description is required");const a=n.tokenImage;$l(a)?a.length>500&&t.push("Token image must be at most 500 characters"):t.push("Token image is required");const o=n.preBuyQuantity;void 0!==o&&void 0===Bl(o)&&t.push("preBuyQuantity must be a non-negative decimal number");for(const e of["websiteUrl","telegramUrl","twitterUrl","instagramUrl","facebookUrl","redditUrl","tiktokUrl"])Gl(t,e,n[e]);Kl(t,"tokenCategory",n.tokenCategory),Kl(t,"tokenCollection",n.tokenCollection);const c=n.saleStartTime;if(void 0===c||Number.isInteger(c)||t.push("saleStartTime must be an integer"),function(e,t){if(void 0!==t&&("object"!=typeof t||null===t))return void e.push("reverseBondingCurveConfiguration must be an object");const n=t??{},s=n.minFeePortion??Ol,r=n.maxFeePortion??Ul,i=Bl(s),a=Bl(r);if(void 0===i&&e.push("minFeePortion must be a decimal number"),void 0===a&&e.push("maxFeePortion must be a decimal number"),void 0===i||void 0===a)return;const o=new I(i),c=new I(a);o.isLessThan(xl)&&e.push("minFeePortion must be greater than or equal to 0.1"),c.isGreaterThan(Pl)&&e.push("maxFeePortion must be less than or equal to 0.5"),o.isGreaterThan(c)&&e.push("minFeePortion must be less than or equal to maxFeePortion")}(t,n.reverseBondingCurveConfiguration),t.length>0)throw new Ot(t.join("; "),"data","VALIDATION_ERROR")}class Hl{constructor(e){this.transport=e.transport,this.walletAddress=""===e.walletAddress?"":kn(e.walletAddress,"walletAddress"),this.sellFeeCeiling=e.sellFeeCeiling}createSale(e){Wl(e);const t=function(e,t){const n={tokenName:e.tokenName,tokenSymbol:e.tokenSymbol,tokenDescription:e.tokenDescription,tokenImage:e.tokenImage,preBuyQuantity:Bl(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??jl(t)},s=e.reverseBondingCurveConfiguration;n.reverseBondingCurveConfiguration={minFeePortion:Bl(s?.minFeePortion??Ol),maxFeePortion:Bl(s?.maxFeePortion??Ul)},void 0!==e.saleStartTime&&(n.saleStartTime=e.saleStartTime);return n}(e,this.walletAddress);return this.transport.submit({method:"CreateSale",dto:t,stringsInstructions:Wi(e)})}attach(e){return this.transport.attach(e)}buyWithNative(e){return this.submitTrade("BuyWithNative",e,{nativeTokenQuantity:e.quantity,expectedToken:e.expectedAmount})}buyExactToken(e){return this.submitTrade("BuyExactToken",e,{tokenQuantity:e.quantity,expectedNativeToken:e.expectedAmount})}sellWithNative(e){return this.submitTrade("SellWithNative",e,{nativeTokenQuantity:e.quantity,expectedToken:e.expectedAmount})}sellExactToken(e){return this.submitTrade("SellExactToken",e,{tokenQuantity:e.quantity,expectedNativeToken:e.expectedAmount})}async submitTrade(e,t,n){const s={vaultAddress:t.vaultAddress,...n,extraFees:t.extraFees??await this.defaultExtraFees(e,t),uniqueKey:t.uniqueKey??jl(this.walletAddress)};return this.transport.submit({method:e,dto:s,stringsInstructions:Ki(t.vaultAddress)})}async defaultExtraFees(e,t){if("BuyWithNative"===e||"BuyExactToken"===e)return{maxAcceptableReverseBondingCurveFee:"0"};if(void 0===this.sellFeeCeiling)throw new Ot("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 jl(e){return`galaswap-operation-${N()}-${Date.now()}-${e}`}function ql(e,t=3e4){return C.create({baseURL:e,timeout:t,headers:{"Content-Type":"application/json"}})}const Vl=new Set(["accesstoken","refreshtoken","token","password","privatekey","secret","apikey","api_key","rawkey","authorization","x-api-key","bearer","streamadminapikey","userapikey","signature","signedpayload"]);function zl(e,t=0){if(t>5)return"[...]";if(null==e)return e;if(Array.isArray(e))return e.map(e=>zl(e,t+1));if(e instanceof Map){const n={};for(const[s,r]of e.entries()){const e=String(s);n[e]=Vl.has(e.toLowerCase())?"[REDACTED]":zl(r,t+1)}return n}if("object"==typeof e){const n={};for(const[s,r]of Object.entries(e))n[s]=Vl.has(s.toLowerCase())?"[REDACTED]":zl(r,t+1);return n}return e}class Ql{constructor(e,t={},n={signRequests:!0}){this.auth=e,this.signRequests=n.signRequests,this.session=n.session,this.debug=t.debug??!1,this.logger=new An({debug:this.debug,context:"HttpClient"});const s=t.baseUrl??Jr("stage").launchpadBaseUrl,r=t.timeout??6e4;this.axios=ql(s,r),t.headers&&(this.axios.defaults.headers.common={...this.axios.defaults.headers.common,...t.headers}),void 0!==this.session&&"omit"!==this.session.credentials&&(this.axios.defaults.withCredentials=!0),this.setupInterceptors()}async request(e){return(await this.requestWithMeta(e)).data}async requestWithMeta(e){return qr(async()=>{const t=void 0!==this.session&&!1!==e.withSession&&!function(e){return void 0!==e&&Object.keys(e).some(e=>"authorization"===e.toLowerCase())}(e.headers),n=t&&void 0!==this.session?await this.session.accessToken():null,s=this.toAxiosConfig(e,n);e.headers&&this.logger.debug("Custom headers provided:",Object.keys(s.headers??{}));const r=e.data instanceof FormData?"[FormData object - multipart/form-data]":zl(e.data);this.logger.debug("Request:",{method:e.method,url:e.url?.split("?")[0],baseURL:this.axios.defaults.baseURL,params:zl(s.params),data:r,isFormData:e.data instanceof FormData,contentType:s.headers?.["Content-Type"]??"not set"});const i=await this.sendWithSession(e,s,t,n),a=function(e){const t={};if(null==e||"object"!=typeof e)return t;for(const[n,s]of Object.entries(e))"string"==typeof s?t[n.toLowerCase()]=s:"number"!=typeof s&&"boolean"!=typeof s||(t[n.toLowerCase()]=String(s));return t}(i.headers);return this.logger.debug("Response:",{status:i.status,data:zl(i.data),transactionId:a["x-transaction-id"],blockNumber:a["x-block-number"]}),{data:i.data,headers:a,status:i.status}},`HTTP ${e.method} ${e.url}`,this.logger)}toAxiosConfig(e,t){const n=null===t?e.headers:{...e.headers,Authorization:`Bearer ${t}`},s={method:e.method,url:e.url,data:e.data,...void 0!==e.params&&{params:yo(e.params)},...void 0!==n&&{headers:{...n}},...void 0!==e.timeout&&{timeout:e.timeout},...void 0!==e.signal&&{signal:e.signal}};if(e.data instanceof FormData){const e=new D(n);e.set("Content-Type",void 0),s.headers=e,this.logger.debug("FormData detected - clearing the JSON Content-Type default for the multipart upload")}return s}async sendWithSession(e,t,n,s){try{return await this.axios.request(t)}catch(t){if(!n||void 0===this.session||!function(e){if("object"!=typeof e||null===e||!("response"in e))return!1;const t=e.response;return"object"==typeof t&&null!==t&&"status"in t&&401===t.status}(t))throw t;const r=await this.session.onUnauthorized(s);if(null===r)throw t;return this.logger.debug("Retrying once with the refreshed session token"),await this.axios.request(this.toAxiosConfig(e,r))}}async get(e,t,n){return this.request({method:"GET",url:e,...t&&{params:t},...n&&{headers:n}})}async post(e,t,n){return this.request({method:"POST",url:e,data:t,...n&&{headers:n}})}async postWithMeta(e,t,n){return this.requestWithMeta({method:"POST",url:e,data:t,...n&&{headers:n}})}async put(e,t,n){return this.request({method:"PUT",url:e,data:t,...n&&{headers:n}})}async delete(e,t,n){return this.request({method:"DELETE",url:e,...t&&{params:t},...n&&{headers:n}})}async patch(e,t,n){return this.request({method:"PATCH",url:e,data:t,...n&&{headers:n}})}getAddress(){return this.auth.getAddress()}getEthereumAddress(){return this.auth.getEthereumAddress()}async signMessage(e){return(await this.auth.signMessage(e)).signature}async signTypedData(e,t,n){return await this.auth.signTypedData(e,t,n)}async signCustomMessage(e){return qr(async()=>{const t=await this.auth.generateCustomSignature(e);return this.logger.debug("Generated custom signature:",{message:e,address:t.address,ethereumAddress:this.auth.getEthereumAddress()}),{signature:t.signature,address:t.address,ethereumAddress:this.auth.getEthereumAddress()}},"Failed to generate custom signature for message",this.logger)}setupInterceptors(){this.requestInterceptorId=this.axios.interceptors.request.use(async e=>{if(e.headers??(e.headers={}),this.signRequests&&this.auth?.hasWallet()){const t=await this.auth.generateSignature();e.headers.Sign=t.signature,this.logger.debug("Added signature header:",{address:t.address,message:t.message,timestamp:t.timestamp})}else this.logger.debug("Skipping signature header (no wallet, or signRequests is off)");return e.data instanceof FormData||(e.headers["Content-Type"]="application/json"),this.logger.debug("Final request header keys being sent:",Object.keys(e.headers)),e},e=>Promise.reject(e instanceof Error?e:new Error(String(e)))),this.responseInterceptorId=this.axios.interceptors.response.use(e=>e,e=>{const t=e;if(void 0!==t.response){const n=t.response.data,s={message:n?.message??$t(e),...n&&"string"==typeof n.error&&""!==n.error&&{error:n.error},statusCode:t.response.status,...n&&Boolean(n.details)&&{details:n.details},...n&&Boolean(n.timestamp)&&{timestamp:n.timestamp},...n&&Boolean(n.path)&&{path:n.path}};t.launchpadError=s,this.logger.error("Backend error:",s)}else void 0!==t.request?this.logger.error("Network error:",t.message??"Unknown error"):this.logger.error("Request setup error:",t.message??"Unknown error");return Promise.reject(e instanceof Error?e:new Error(String(e)))})}cleanup(){void 0!==this.requestInterceptorId&&(this.axios.interceptors.request.eject(this.requestInterceptorId),this.requestInterceptorId=void 0),void 0!==this.responseInterceptorId&&(this.axios.interceptors.response.eject(this.responseInterceptorId),this.responseInterceptorId=void 0),this.logger.debug("Interceptors cleaned up")}}class Xl extends Error{constructor(e,t){super(e),this.cause=t,this.name="WebSocketError"}}class Jl extends Xl{constructor(e,t){super(`WebSocket confirmation timeout for transaction ${e} after ${t}ms`),this.name="WebSocketTimeoutError"}}class Yl 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 Zl(e,t){if(Jn(e))throw new Xl(`Invalid WebSocket response received for transaction ${t}: response is null or undefined`);if("object"!=typeof e)throw new Xl(`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 Xl(`Invalid WebSocket response received for transaction ${t}: missing status field`)}function ed(e,t,n,s){Zl(e,t);const r=e,i=r.data??{};if(!function(e){if(Jn(e)||"object"!=typeof e)return!1;const t=e;return!(void 0!==t.inputQuantity&&"string"!=typeof t.inputQuantity||void 0!==t.outputQuantity&&"string"!=typeof t.outputQuantity||void 0!==t.totalFees&&"string"!=typeof t.totalFees||void 0!==t.vaultAddress&&"string"!=typeof t.vaultAddress)}(i))throw new Xl(`Invalid trade data received for transaction ${t}`);const a={transactionId:t,type:n,method:"native"===s.type?"native":"exact",inputAmount:i.inputQuantity??s.amount,outputAmount:i.outputQuantity??s.expectedAmount??"0",totalFees:i.totalFees??"0",tokenName:s.tokenName,vaultAddress:i.vaultAddress??"",timestamp:Date.now()};return void 0!==r.blockHash&&(a.blockHash=r.blockHash),void 0!==r.gasUsed&&(a.gasUsed=r.gasUsed),void 0!==s.slippageToleranceFactor&&(a.slippageTolerance=s.slippageToleranceFactor),a}function td(e){return void 0!==e&&b(e)?new i(e.exportPrivateKey()):void 0}const nd={MUSIC:"$MUSIC",GMUSIC:"$GMUSIC"};function sd(e){if(void 0===e||!("walletAddress"in e))return;const t=e.walletAddress;return"string"==typeof t&&""!==t?t:void 0}const rd=/^(?:eth\||0x)([0-9a-fA-F]{40})$/;function id(e,t,n){if(void 0===e||void 0===t)return;const s=rd.exec(e)?.[1],r=rd.exec(t)?.[1];if(void 0!==s&&void 0!==r&&s.toLowerCase()!==r.toLowerCase())throw Jt(`${n} ${t} is not the identity of the configured signing key (${e}); writes would be signed as the key, not as ${n}.`,n)}class ad{constructor(e){let t,n;this.walletGeneration=0,e.walletProvider?(t=e.walletProvider,n=td(e.walletProvider)):e.wallet&&(n=e.wallet,t=S.fromWallet(e.wallet)),this.wallet=n;const s=e.env??"prod",r=Jr(s);this.environment=s,this.config={baseUrl:e.launchpadBaseUrl??r.launchpadBaseUrl,gatewayBaseUrl:r.gatewayBaseUrl,bundleBaseUrl:r.bundleBaseUrl,webSocketUrl:r.webSocketUrl,dexApiBaseUrl:r.dexApiBaseUrl,dexBackendBaseUrl:r.dexBackendBaseUrl,launchpadFrontendUrl:r.launchpadFrontendUrl,timeout:3e4,debug:!1,...e};const i=e.signer??(void 0!==n?new Pi(n.privateKey):void 0),a=void 0!==n?`eth|${n.address.slice(2)}`:sd(i),o=void 0===e.walletAddress?void 0:kn(e.walletAddress,"walletAddress"),c=void 0===e.galaChainAddress?void 0:kn(e.galaChainAddress,"galaChainAddress");id(a,o,"walletAddress"),id(a,c,"galaChainAddress");const l=o??c??(void 0!==n?`eth|${n.address.slice(2)}`:sd(i)),d=i??{signObject:()=>Promise.reject(new Error("A signer is required for token writes.")),signTypedData:()=>Promise.reject(new Error("A signer is required for launchpad writes."))},u=l??"";this.tokenWriter=void 0===n&&void 0!==e.signer&&void 0!==l?{signer:e.signer,walletAddress:l}:void 0;const h=new El({bundleBaseUrl:this.config.bundleBaseUrl,launchpadBaseUrl:this.config.baseUrl,signer:d,walletAddress:u,...void 0!==e.httpRequestor&&{httpRequestor:e.httpRequestor},bundleSocketFactory:e.bundleSocketFactory}),g=Rl({getTradeQuote:e=>this.tradingQuotesService.getTradeQuote(e),findTokenNameByVault:(e,t)=>this.findTokenNameByVault(e,t),defaultFeeSlippageFactor:()=>this.maxAcceptableReverseBondingCurveFeeSlippageFactor});this.sellFeeCeiling=g,this.launchpad=new Hl({transport:h,walletAddress:u,sellFeeCeiling:g}),this.logger=new An({debug:this.config.debug??!1,context:"LaunchpadSDK"}),this.validateConfiguration(),this.slippageToleranceFactor=void 0===e.slippageToleranceFactor?ad.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR:this.parseSlippageToleranceFactor(e.slippageToleranceFactor),this.maxAcceptableReverseBondingCurveFeeSlippageFactor=void 0===e.maxAcceptableReverseBondingCurveFeeSlippageFactor?ad.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR:this.parseFeeSlippageFactor(e.maxAcceptableReverseBondingCurveFeeSlippageFactor),this.calculateAmountMode=e.calculateAmountMode??ad.DEFAULT_CALCULATE_AMOUNT_MODE,this.galaChainAddressOverride=c,this.signerWalletAddress=o??(void 0===n?l:void 0),this.auth=new Qr({wallet:n,walletProvider:t,messagePrefix:"Create a GalaChain Wallet"});const m=e.session;if(void 0!==m){if(!function(e){if("object"!=typeof e||null===e)return!1;const t=e,n=t.credentials;return"function"==typeof t.accessToken&&"function"==typeof t.onUnauthorized&&(void 0===n||"include"===n||"omit"===n)}(m))throw Jt("session must provide accessToken() and onUnauthorized()","session");if(void 0!==e.accessToken&&""!==e.accessToken)throw Jt("Pass either session or accessToken, not both: the session owns the token.","accessToken")}if(this.jwtAuth=void 0===m?new Hr:new jr,void 0!==e.accessToken&&""!==e.accessToken){const t=e.accessTokenExpiresIn??86400;this.jwtAuth.setToken(e.accessToken,t)}this.http=new Ql(this.auth,this.config,{signRequests:!0,session:m}),this.sessionAuth=new zr(this.http,this.auth,this.jwtAuth,e.debug??!1,m);const f={signRequests:!1};this.galaChainHttp=new Ql(this.auth,{...this.config,baseUrl:this.config.gatewayBaseUrl},f),this.bundleHttp=new Ql(this.auth,{...this.config,baseUrl:this.config.bundleBaseUrl},f),this.dexApiHttp=new Ql(this.auth,{...this.config,baseUrl:this.config.dexApiBaseUrl},f),this.dexBackendHttp=new Ql(this.auth,{...this.config,baseUrl:this.config.dexBackendBaseUrl},f),this.galaChainPublicAxios=ql(this.config.gatewayBaseUrl,this.config.timeout??3e4),this.cache=new us(e.debug??!1),this.launchpadService=new Bo(this.http,this.jwtAuth),this.tokenResolverService=new dl(this.launchpadService.poolService),this.launchpadAPI=new Lr(this.http,this.logger,this.bundleHttp,this.calculateAmountMode,this.launchpad),this.galaChainService=new mo(this.galaChainHttp,n,this.tokenResolverService,e.debug??!1,this.galaChainPublicAxios,this.tokenWriter),this.priceService=new pa(this.dexBackendHttp,this.cache,e=>this.galaChainService.fetchTokenDetails(e),e.debug??!1),this.bundleService=this.createBundleService(),this.websocketService=new fl({url:this.config.webSocketUrl},this.config.debug),this.nftCollectionService=new ec(this.galaChainHttp),this.tradingQuotesService=new ul(this.http,e.debug??!1)}createOverrideSdk(e){if(!Xn(e))throw Jt("Invalid privateKey: must be a non-empty string","privateKey");if(!e.match(/^0x[a-fA-F0-9]{64}$/))throw Jt('Invalid privateKey format: must be "0x" followed by 64 hexadecimal characters',"privateKey");const t=new i(e),n={...this.config,wallet:t};return new ad(n)}getAddress(){return void 0!==this.galaChainAddressOverride&&""!==this.galaChainAddressOverride?this.galaChainAddressOverride:void 0!==this.signerWalletAddress&&""!==this.signerWalletAddress?this.signerWalletAddress:(this.validateWallet(),this.auth.getAddress())}getEthereumAddress(){return this.validateWallet(),this.wallet.address}validateWallet(){if(!this.wallet)throw zt("wallet","Wallet");return this.wallet}assertTokenWriter(){if(void 0===this.wallet&&void 0===this.tokenWriter)throw zt("wallet","Wallet")}setWallet(e){if(null==e||"object"!=typeof e||!("address"in e))throw new Ot("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 na(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 mo(this.galaChainHttp,this.wallet,this.tokenResolverService,this.config.debug??!1,this.galaChainPublicAxios)}setWalletProvider(e){this.auth.setWalletProvider(e),this.wallet=e?td(e):void 0,this.onWalletChanged()}getWallet(){return this.wallet}get events(){return this.getEventsBatcherService()}getWalletProvider(){return this.auth.getWalletProvider()}hasWallet(){return this.auth.hasWallet()}getConfig(){const{wallet:e,walletProvider:t,signer:n,httpRequestor:s,streamAdminApiKey:r,userApiKey:i,accessToken:a,headers:o,...c}=this.config;return{...c,...void 0!==r&&{streamAdminApiKey:"[REDACTED]"},...void 0!==i&&{userApiKey:"[REDACTED]"},...void 0!==a&&{accessToken:"[REDACTED]"},...void 0!==o&&{headers:Object.fromEntries(Object.keys(o).map(e=>[e,"[REDACTED]"]))},environment:this.environment,slippageToleranceFactor:this.slippageToleranceFactor,maxAcceptableReverseBondingCurveFeeSlippageFactor:this.maxAcceptableReverseBondingCurveFeeSlippageFactor,calculateAmountMode:this.calculateAmountMode,gasFee:mn.GAS_FEE}}getVersion(){return ti}getUrlByTokenName(e){const t=this.config.launchpadFrontendUrl;if(void 0===t||""===t)throw Jt("launchpadFrontendUrl not configured in SDK","launchpadFrontendUrl");return`${t.replace(/\/$/,"")}/buy-sell/${e}`}async fetchPools(e){const t=await this.launchpadService.fetchPools(e??{});return await this.warmCacheFromPools(t.items),t}async fetchAllPools(e){const t=await this.launchpadService.fetchAllPools(e);return await this.warmCacheFromPools(t.items),t}async fetchTokenDistribution(e){return this.launchpadService.fetchTokenDistribution(e)}async getTopHolders(e,t=10){const n=await this.fetchTokenDistribution(e),s=Math.min(t,100);return n.holders.slice(0,s).map((e,t)=>({...e,rank:t+1}))}async getHolderCount(e){const t=await this.fetchTokenDistribution(e);return{count:t.totalHolders,totalBalance:t.totalSupply}}async getHolderRank(e,t){const n=wn(t,"userAddress"),s=await this.fetchTokenDistribution(e),r=s.holders.findIndex(e=>e.address.toLowerCase()===n);if(-1===r)return null;const i=s.holders[r];return void 0===i?null:{rank:r+1,balance:i.balance,holderCount:s.totalHolders}}async getHoldersByBalance(e,t){const n=await this.fetchTokenDistribution(e),s=t?.minBalance??0,r=t?.maxBalance??1/0,i=Math.min(t?.limit??100,1e3),a=new Map;return n.holders.forEach((e,t)=>{a.set(e.address,t+1)}),n.holders.filter(e=>{const t=parseFloat(e.balance);return t>=s&&t<=r}).map(e=>({...e,rank:a.get(e.address)??0})).slice(0,i)}async getHolderHistory(e,t,n=20){return this.getTrades({tokenName:e,userAddress:t,pageSize:Math.min(n,100)})}async fetchUserHolderContext(e,t){return this.launchpadService.fetchUserHolderContext(e,t)}async fetchTokenPrice(e){const t="object"==typeof e&&null!==e?e:{};if(void 0!==t.tokenId)throw new Ot("fetchTokenPrice prices a launchpad token by tokenName; a token by class key is priced by gswap-sdk (gSwap.market.getPrice)","tokenId",Rt);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 Bn}),n=t(e)??this.getAddress();return this.galaChainService.fetchGalaBalance({owner:n,collection:"GALA",category:"Unit",additionalKey:"none",type:"none"})}loadCoreBridge(){const e=this.config.bridge;return void 0===e?Promise.reject(Jt("The bridge and wrap methods need gala-core-sdk's ./bridge: create the SDK with `bridge: () => import('@gala-chain/gala-core-sdk/bridge')` (it needs the optional peers ethers, @solana/web3.js and @solana/spl-token).","bridge")):(this.coreBridgeLoad??(this.coreBridgeLoad=Promise.resolve().then(()=>e()).then(e=>{if("object"!=typeof(t=e)||null===t||"function"!=typeof t.BridgeService)throw new Error("the module has no BridgeService export");var t;return e}).catch(e=>{throw this.coreBridgeLoad=void 0,Jt(`The bridge and wrap methods use @gala-chain/gala-core-sdk/bridge, which needs its optional peers ethers, @solana/web3.js and @solana/spl-token installed: ${$t(e)}`,"bridge")})),this.coreBridgeLoad)}async coreBridge(){const e=this.walletGeneration,t=await this.loadCoreBridge();if(e!==this.walletGeneration)throw Jt("The wallet changed while this bridge or wrap call was starting; nothing was sent. Call it again.","wallet");return t}getBridgeService(e){if(!this._bridgeService){const t=this.getWallet();if(!t)throw new Error("Bridge operations require a wallet. Configure SDK with a wallet first.");const n=globalThis.process?.env.SOLANA_PRIVATE_KEY;this._bridgeService=new e.BridgeService({galaConnectBaseUrl:this.config.dexApiBaseUrl,galaChainWalletAddress:this.getAddress(),ethereumPrivateKey:t.privateKey,...void 0!==n&&""!==n?{solanaPrivateKey:n}:{},bridgeableTokenService:this.getBridgeableTokenService(e),environment:this.environment,...void 0!==this.config.ethereumRpcUrl&&""!==this.config.ethereumRpcUrl?{ethereumRpcUrl:this.config.ethereumRpcUrl}:{},...void 0!==this.config.solanaRpcUrl&&""!==this.config.solanaRpcUrl?{solanaRpcUrl:this.config.solanaRpcUrl}:{}})}return this._bridgeService}getBridgeableTokenService(e){return this._bridgeableTokenService??(this._bridgeableTokenService=new e.BridgeableTokenService(this.dexApiHttp)),this._bridgeableTokenService}getWrappableTokenService(e){return this._wrappableTokenService??(this._wrappableTokenService=new e.WrappableTokenService(this.dexApiHttp)),this._wrappableTokenService}getGalaConnectClient(e){if(void 0===this._galaConnectClient){const t=this.getAddress();if(void 0===this.config.dexApiBaseUrl||""===this.config.dexApiBaseUrl)throw new Error("DEX API base URL is required for GalaConnectClient. Check SDK configuration.");this._galaConnectClient=new e.GalaConnectClient({baseUrl:this.config.dexApiBaseUrl,...void 0!==this.config.gatewayBaseUrl&&""!==this.config.gatewayBaseUrl?{galachainBaseUrl:this.config.gatewayBaseUrl}:{},walletAddress:t})}return this._galaConnectClient}getWrapService(e){if(!this._wrapService){const t=this.getWallet();this._wrapService=new e.WrapService({galaConnectClient:this.getGalaConnectClient(e),wrappableTokenService:this.getWrappableTokenService(e),...void 0!==t&&{walletAddress:this.getAddress(),signer:new Pi(t.privateKey)}})}return this._wrapService}getStreamingService(){return this._streamingService??(this._streamingService=new Sc(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._streamingService}getStreamChatService(){return this._streamChatService??(this._streamChatService=new fc(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._streamChatService}getBanService(){return this._banService??(this._banService=new Ti(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._banService}getTokenBanService(){return this._tokenBanService??(this._tokenBanService=new ll(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._tokenBanService}getAIModerationService(){return this._aiModerationService??(this._aiModerationService=new gi(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._aiModerationService}getWeeklyChallengeService(){return this._weeklyChallengeService??(this._weeklyChallengeService=new pl(this.http,this.config.debug??!1)),this._weeklyChallengeService}getOEmbedService(){return this._oembedService??(this._oembedService=new nc(this.http,this.config.debug??!1)),this._oembedService}getPlatformStatsService(){return this._platformStatsService??(this._platformStatsService=new gc(this.http,this.config.debug??!1)),this._platformStatsService}getHealthService(){return this._healthService??(this._healthService=new fo(this.http,this.config.debug??!1)),this._healthService}getEventsQueryService(){return this._eventsQueryService??(this._eventsQueryService=new Oa(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._eventsQueryService}getNotificationService(){return this._notificationService??(this._notificationService=new tc(this.http,this.config.debug??!1,this.jwtAuth)),this._notificationService}getClientConfigService(){return this._clientConfigService??(this._clientConfigService=new sa(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 qo(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._moderatorService}getFlagService(){return this._flagService??(this._flagService=new ua(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._flagService}getOverseerService(){return this._overseerService??(this._overseerService=new uc(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._overseerService}getWebSocketAdminService(){return this._websocketAdminService??(this._websocketAdminService=new hl(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._websocketAdminService}getContentReactionService(){return this._contentReactionService??(this._contentReactionService=new ga(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._contentReactionService}buildMessageFetchOptions(e,t){return{type:t,...void 0!==e.tokenName&&{tokenName:e.tokenName},...void 0!==e.userAddress&&{userAddress:e.userAddress},...void 0!==e.cursor&&{cursor:e.cursor},...void 0!==e.pageSize&&{pageSize:e.pageSize}}}resolveReferralAddress(e){return void 0===e||""===e?this.getAddress():kn(e,"address")}getMessagesService(){return this._messagesService??(this._messagesService=new Go(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._messagesService}getRestrictedNamesService(){return this._restrictedNamesService??(this._restrictedNamesService=new mc(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.userApiKey)),this._restrictedNamesService}getPlatformConfigService(){return this._platformConfigService??(this._platformConfigService=new hc(this.http,this.jwtAuth,this.config.debug??!1)),this._platformConfigService}getEventsBatcherService(){return this._eventsBatcherService??(this._eventsBatcherService=new ka(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 al({url:this.config.streamWebSocketUrl,tokenProvider:()=>this.streamSocketToken(),...void 0!==this.config.streamReconnectAttempts&&{reconnectAttempts:this.config.streamReconnectAttempts},...void 0!==this.config.streamReconnectDelay&&{reconnectDelay:this.config.streamReconnectDelay},...void 0!==this.config.streamReconnectDelayMax&&{reconnectDelayMax:this.config.streamReconnectDelayMax}},this.config.debug??!1)}return this._streamWebSocketService}async streamSocketToken(){const e=this.config.session;return void 0!==e?e.accessToken():this.ensureValidToken()}get realtime(){return this.getStreamWebSocketService()}async fetchEthereumWalletTokenBalance(e,t){return this.getBridgeService(await this.coreBridge()).fetchEthereumWalletTokenBalance(e,t)}async fetchEthereumWalletNativeBalance(e){return this.getBridgeService(await this.coreBridge()).fetchEthereumWalletNativeBalance(e)}async fetchSolanaWalletTokenBalance(e,t){return this.getBridgeService(await this.coreBridge()).fetchSolanaWalletTokenBalance(e,t)}async fetchSolanaWalletNativeBalance(e){return this.getBridgeService(await this.coreBridge()).fetchSolanaWalletNativeBalance(e)}async requestSolanaDevnetAirdrop(e,t){return this.getBridgeService(await this.coreBridge()).requestSolanaDevnetAirdrop(e,t)}async getSolanaTransactionStatus(e){return this.getBridgeService(await this.coreBridge()).getSolanaTransactionStatus(e)}async getEthereumTransactionStatus(e){return this.getBridgeService(await this.coreBridge()).getEthereumTransactionStatus(e)}async fetchEthereumWalletAllBalances(e){return this.getBridgeService(await this.coreBridge()).fetchEthereumWalletAllBalances(e)}async fetchSolanaWalletAllBalances(e){return this.getBridgeService(await this.coreBridge()).fetchSolanaWalletAllBalances(e)}async fetchBridgeableTokensByNetwork(e){return this.getBridgeableTokenService(await this.coreBridge()).fetchBridgeableTokensByNetwork(e)}async fetchAllBridgeableTokensByNetwork(e){return this.getBridgeableTokenService(await this.coreBridge()).fetchAllBridgeableTokensByNetwork(e)}async fetchAllTokensBridgeableToEthereum(){return this.getBridgeableTokenService(await this.coreBridge()).fetchAllTokensBridgeableToEthereum()}async fetchAllTokensBridgeableToSolana(){return this.getBridgeableTokenService(await this.coreBridge()).fetchAllTokensBridgeableToSolana()}async isTokenBridgeableToNetwork(e){return this.getBridgeableTokenService(await this.coreBridge()).isTokenBridgeableToNetwork(e)}async isTokenBridgeableToEthereum(e){return this.getBridgeableTokenService(await this.coreBridge()).isTokenBridgeableToEthereum(e)}async isTokenBridgeableToSolana(e){return this.getBridgeableTokenService(await this.coreBridge()).isTokenBridgeableToSolana(e)}async fetchWrappableTokens(e={}){return this.getWrappableTokenService(await this.coreBridge()).fetchWrappableTokens(e)}async fetchAllWrappableTokens(){return this.getWrappableTokenService(await this.coreBridge()).fetchAllWrappableTokens()}async getWrappableToken(e){return this.getWrappableTokenService(await this.coreBridge()).getWrappableToken(e)}async getWrapCounterpart(e){return this.getWrappableTokenService(await this.coreBridge()).getWrapCounterpart(e)}async isTokenWrappable(e){return this.getWrappableTokenService(await this.coreBridge()).isTokenWrappable(e)}async wrapToken(e){return this.getWrapService(await this.coreBridge()).wrapToken(e)}async unwrapToken(e){return this.getWrapService(await this.coreBridge()).unwrapToken(e)}async estimateWrapFee(e,t){return this.getWrapService(await this.coreBridge()).estimateWrapFee(e,t)}async estimateUnwrapFee(e,t){return this.getWrapService(await this.coreBridge()).estimateUnwrapFee(e,t)}async login(){return this.sessionAuth.login()}async loginWithSignature(e){return this.sessionAuth.loginWithSignature(e)}async loginWithDevBypass(e){return this.sessionAuth.loginWithDevBypass(e)}async refreshToken(){return this.sessionAuth.refresh()}async logout(e){return this.sessionAuth.logout(e)}isAuthenticated(){return this.sessionAuth.isAuthenticated()}shouldRefreshToken(e){return this.sessionAuth.shouldRefresh(e)}async getSession(){return this.sessionAuth.getSession()}getAccessToken(){return this.sessionAuth.getAccessToken()}async ensureValidToken(e){return this.sessionAuth.ensureValidToken(e)}async startStream(e){return this.getStreamingService().startStream(e)}async stopStream(e){return this.getStreamingService().stopStream(e)}async disableStream(e){return this.getStreamingService().disableStream(e)}async enableStream(e){return this.getStreamingService().enableStream(e)}async resetStreamKey(e){return this.getStreamingService().resetStreamKey(e)}async getStreamCredentials(e){return this.getStreamingService().getStreamCredentials(e)}async getStreamRecordings(e){return this.getStreamingService().getRecordings(e)}async getRecordingDownload(e,t){return this.getStreamingService().getRecordingDownload(e,t)}async deleteRecording(e,t){return this.getStreamingService().deleteRecording(e,t)}async getSimulcastTargets(e){return this.getStreamingService().getSimulcastTargets(e)}async addSimulcastTarget(e){return this.getStreamingService().addSimulcastTarget(e)}async removeSimulcastTarget(e,t){return this.getStreamingService().removeSimulcastTarget(e,t)}async getGlobalStreamingStatus(){return this.getStreamingService().getGlobalStreamingStatus()}async setNextLiveStreamCountdown(e,t){return this.getStreamingService().setNextLiveStreamCountdown(e,t)}async setGlobalStreamingEnabled(e){const t=this.getStreamingService();return e?t.enableGlobalStreaming():t.disableGlobalStreaming()}async getStreamRole(e){return this.getStreamingService().getStreamRole(e)}async getAvailableRoles(){return this.getStreamingService().getAvailableRoles()}async getTokenAccess(e){return this.getStreamingService().getTokenAccess(e)}async getChatStatus(e){return this.getStreamChatService().getChatStatus(e)}async disableChat(e){return this.getStreamChatService().disableChat(e)}async enableChat(e){return this.getStreamChatService().enableChat(e)}async getPinnedChatMessage(e){const t=this.getMessagesService();return{tokenName:e,pinnedMessage:(await t.getPinnedMessage(e)).message}}async pinChatMessage(e,t){const n=this.getMessagesService();await n.pinMessage(t);return{tokenName:e,pinnedMessage:(await n.getPinnedMessage(e)).message}}async unpinChatMessage(e){const t=this.getMessagesService(),n=await t.getPinnedMessage(e);return n.message?(await t.unpinMessage(n.message.messageId),{tokenName:e,unpinned:!0,unpinnedMessageId:n.message.messageId}):{tokenName:e,unpinned:!1}}async setSlowMode(e,t){return this.getStreamChatService().setSlowMode(e,t)}async createBan(e){return this.getBanService().createBan(e)}async removeBan(e){return this.getBanService().removeBan(e)}async listBans(e){return this.getBanService().listBans(e)}async getBanStatus(e){return this.getBanService().getBanStatus(e)}async getActiveUsers(e){return this.getBanService().getActiveUsers(e)}async createGlobalBan(e){return this.getBanService().createGlobalBan(e)}async removeGlobalBan(e){return this.getBanService().removeGlobalBan(e)}async listGlobalBans(e){return this.getBanService().listGlobalBans(e)}async getGlobalBan(e){return this.getBanService().getGlobalBan(e)}async createApiKey(e){return this.getApiKeyService().create(e)}async listApiKeys(e={}){return this.getApiKeyService().findAll(e)}async getApiKey(e){return this.getApiKeyService().findOne(e)}async updateApiKey(e,t){return this.getApiKeyService().update(e,t)}async revokeApiKey(e){return this.getApiKeyService().revoke(e)}getApiKeyRoles(){return this.getApiKeyService().getRoles()}async createModeratorInvite(e){return this.getModeratorService().createInvite(e)}async claimModeratorInvite(e){return this.getModeratorService().claimInvite(e)}async getModeratedTokens(e){return this.getModeratorService().getModeratedTokens(e)}async listModeratorInvites(e){return this.getModeratorService().listInvites(e)}async getActiveModerators(e){return(await this.listModeratorInvites({tokenName:e,status:"CLAIMED"})).items.filter(e=>null!==e.claimedBy).map(e=>({address:e.claimedBy,role:e.role,joinedAt:e.claimedAt,inviteId:e.id}))}async revokeModeratorInvite(e){return this.getModeratorService().revokeInvite(e)}async updateModeratorInviteRole(e){return this.getModeratorService().updateInviteRole(e)}async updateModeratorInvite(e){return this.getModeratorService().updateInvite(e)}async getModeratorInviteByCode(e){return this.getModeratorService().getInviteByCode(e)}async createFlag(e){return this.getFlagService().createFlag(e)}async listFlags(e){return this.getFlagService().listFlags(e)}async listGlobalFlags(e={}){return this.getFlagService().listGlobalFlags(e)}async dismissFlag(e){return this.getFlagService().dismissFlag(e)}async actionFlag(e){return this.getFlagService().actionFlag(e)}async createOverseerInvite(e={}){return this.getOverseerService().createInvite(e)}async listOverseerInvites(e={}){return this.getOverseerService().listInvites(e)}async getOverseerInviteByCode(e){return this.getOverseerService().getInviteByCode(e)}async claimOverseerInvite(e){return this.getOverseerService().claimInvite(e)}async revokeOverseerInvite(e){return this.getOverseerService().revokeInvite(e)}async listOverseers(e={}){return this.getOverseerService().listOverseers(e)}async createOverseerDirect(e){return this.getOverseerService().createOverseerDirect(e)}async revokeOverseer(e){return this.getOverseerService().revokeOverseer(e)}async getMyOverseerStatus(){return this.getOverseerService().getMyStatus()}async getOverseerSummary(){return this.getOverseerService().getSummary()}async getBanStats(){return this.getOverseerService().getBanStats()}async getTokenBanStats(){return this.getOverseerService().getTokenBanStats()}async getInviteStats(){return this.getOverseerService().getInviteStats()}async getFlagStats(){return this.getOverseerService().getFlagStats()}async getUserStats(){return this.getOverseerService().getUserStats()}async listOverseerUsers(e){return this.getOverseerService().listOverseerUsers(e)}async getOverseerUserSummary(e){return this.getOverseerService().getOverseerUserSummary(e)}async flushCacheByAddress(e){return this.getOverseerService().flushCacheByAddress(e)}async flushCacheByToken(e){return this.getOverseerService().flushCacheByToken(e)}async flushAllCache(e){return this.getOverseerService().flushAllCache(e)}async flushWalletAliasCache(e){return this.getOverseerService().flushWalletAliasCache(e)}async emitWebSocketEvent(e){return this.getWebSocketAdminService().emitEvent(e)}async emitTradeExecuted(e,t){return this.getWebSocketAdminService().emitTradeExecuted(e,t)}async emitBalanceUpdated(e,t,n){return this.getWebSocketAdminService().emitBalanceUpdated(e,t,n)}async emitStreamStatus(e,t){return this.getWebSocketAdminService().emitStreamStatus(e,t)}async emitViewerCount(e,t){return this.getWebSocketAdminService().emitViewerCount(e,t)}async emitStreamCountdown(e,t){return this.getWebSocketAdminService().emitStreamCountdown(e,t)}async emitChatMessage(e,t){return this.getWebSocketAdminService().emitChatMessage(e,t)}async emitChatStatus(e,t){return this.getWebSocketAdminService().emitChatStatus(e,t)}async emitTypingIndicator(e,t){return this.getWebSocketAdminService().emitTypingIndicator(e,t)}async emitTokenBanned(e,t){return this.getWebSocketAdminService().emitTokenBanned(e,t)}async emitTokenUnbanned(e,t){return this.getWebSocketAdminService().emitTokenUnbanned(e,t)}async emitModeratorAdded(e,t){return this.getWebSocketAdminService().emitModeratorAdded(e,t)}async emitModeratorRemoved(e,t){return this.getWebSocketAdminService().emitModeratorRemoved(e,t)}async emitUserProfileUpdated(e,t){return this.getWebSocketAdminService().emitUserProfileUpdated(e,t)}async emitSiteConfigChanged(e){return this.getWebSocketAdminService().emitSiteConfigChanged(e)}async emitFeatureStatus(e){return this.getWebSocketAdminService().emitFeatureStatus(e)}async emitRecordingStatus(e,t){return this.getWebSocketAdminService().emitRecordingStatus(e,t)}async emitRecordingsCountUpdated(e,t){return this.getWebSocketAdminService().emitRecordingsCountUpdated(e,t)}async emitDownloadReady(e,t){return this.getWebSocketAdminService().emitDownloadReady(e,t)}async getConnectedClients(e){return this.getWebSocketAdminService().getConnectedClients(e)}async isUserOnline(e){return this.getWebSocketAdminService().isUserOnline(e)}async getOnlineUsers(e){return this.getWebSocketAdminService().getOnlineUsers(e)}async getTokenViewers(e,t){return this.getWebSocketAdminService().getTokenViewers(e,t)}async getOnlineOverseers(){return this.getWebSocketAdminService().getOnlineOverseers()}async banToken(e){return this.getTokenBanService().banToken(e)}async unbanToken(e){return this.getTokenBanService().unbanToken(e)}async listTokenBans(e={}){return this.getTokenBanService().listTokenBans(e)}async getTokenBan(e){return this.getTokenBanService().getTokenBan(e)}async isTokenBanned(e){return this.getTokenBanService().isTokenBanned(e)}async getAIModerationSettings(){return this.getAIModerationService().getSettings()}async updateAIModerationSettings(e){return this.getAIModerationService().updateSettings(e)}async getAIModeration(e){return this.getAIModerationService().getModeration(e)}async triggerAIModeration(e){return this.getAIModerationService().triggerModeration(e)}async getAIModerationStatus(){return this.getAIModerationService().getStatus()}async getWeeklyChallengeLeaderboard(e={}){return this.getWeeklyChallengeService().getLeaderboard(e)}async getTokenWeeklyHistory(e){return this.getWeeklyChallengeService().getTokenHistory(e)}async getHomeOEmbed(e={}){return this.getOEmbedService().getHomeOEmbedJson(e)}async getPoolOEmbed(e){return this.getOEmbedService().getPoolOEmbedJson(e)}async getProfileOEmbed(e){return this.getOEmbedService().getProfileOEmbedJson(e)}async getPlatformStats(){return this.getPlatformStatsService().getStats()}async getHealth(){return this.getHealthService().getHealth()}async getEventStats(){return this.getEventsQueryService().getEventStats()}async queryEvents(e={}){return this.getEventsQueryService().queryEvents(e)}async registerPushToken(e){return this.getNotificationService().registerPushToken(e)}async unregisterPushToken(e){return this.getNotificationService().unregisterPushToken(e)}async fetchNotificationPreferences(){return this.getNotificationService().getPreferences()}async updateNotificationPreferences(e){return this.getNotificationService().updatePreferences(e)}async fetchClientFlags(){return this.getClientConfigService().getClientFlags()}async addContentReaction(e){return this.getContentReactionService().addContentReaction(e)}async removeContentReaction(e){return this.getContentReactionService().removeContentReaction(e)}async addReactionToChatMessage(e){return this.getContentReactionService().addReactionToChatMessage(e)}async removeReactionFromChatMessage(e){return this.getContentReactionService().removeReactionFromChatMessage(e)}async addReactionToComment(e){return this.getContentReactionService().addReactionToComment(e)}async removeReactionFromComment(e){return this.getContentReactionService().removeReactionFromComment(e)}async getComments(e){const t=this.buildMessageFetchOptions(e,"COMMENT"),n=await this.fetchMessages(t);return{messages:n.messages,pageInfo:n.pageInfo}}async createComment(e){return{comment:(await this.createMessage({type:"COMMENT",tokenName:e.tokenName,content:e.content})).message}}async updateComment(e,t){return{comment:(await this.updateMessage(e,{content:t.content,type:"COMMENT"})).message}}async deleteComment(e){return{success:(await this.deleteMessage(e)).success}}async getChatMessages(e){const t=this.buildMessageFetchOptions(e,"CHAT_MESSAGE"),n=await this.fetchMessages(t);return{messages:n.messages,pageInfo:n.pageInfo}}async sendChatMessage(e){return{message:(await this.createMessage({type:"CHAT_MESSAGE",tokenName:e.tokenName,content:e.content})).message}}async updateChatMessage(e,t){return{message:(await this.updateMessage(e,{content:t.content,type:"CHAT_MESSAGE"})).message}}async deleteChatMessage(e){await this.deleteMessage(e)}async fetchMessages(e){return this.getMessagesService().fetchMessages(e)}async createMessage(e){return this.getMessagesService().createMessage(e)}async updateMessage(e,t){return this.getMessagesService().updateMessage(e,t)}async deleteMessage(e){return this.getMessagesService().deleteMessage(e)}async getPinnedMessage(e){return this.getMessagesService().getPinnedMessage(e)}async pinMessage(e){return this.getMessagesService().pinMessage(e)}async unpinMessage(e){return this.getMessagesService().unpinMessage(e)}async getMessageStats(){return this.getMessagesService().getMessageStats()}async getPlatformConfig(){return this.getPlatformConfigService().getPlatformConfig()}async updatePlatformConfig(e){return this.getPlatformConfigService().updatePlatformConfig(e)}async getRestrictedNames(){return this.getRestrictedNamesService().getRestrictedNames()}async updateRestrictedNames(e){return this.getRestrictedNamesService().updateRestrictedNames(e)}async updateTokenConfig(e,t){return this.launchpadService.poolService.updateTokenConfig(e,t)}async getTokenConfig(e){return this.launchpadService.poolService.getTokenConfig(e)}async getTrades(e){return this.launchpadService.getTrades(e)}async getRecentTrades(e,t=50){return this.getTrades({...void 0!==e&&{tokenName:e},pageSize:Math.min(t,500)})}async getPoolRealtimeState(e){const[t,n,s,r]=await Promise.allSettled([this.getHolderCount(e),this.getTokenConfig(e),this.getRecentTrades(e,10),this.fetchTokenPrice({tokenName:e})]);return{tokenName:e,holderCount:"fulfilled"===t.status?t.value:null,..."rejected"===t.status&&{holderCountError:String(t.reason)},chatConfig:"fulfilled"===n.status?n.value:null,..."rejected"===n.status&&{chatConfigError:String(n.reason)},recentTrades:"fulfilled"===s.status?s.value:null,..."rejected"===s.status&&{recentTradesError:String(s.reason)},price:"fulfilled"===r.status?r.value:null,..."rejected"===r.status&&{priceError:String(r.reason)}}}async fetchLaunchpadFee(){return this.tradingQuotesService.fetchLaunchpadFee()}async fetchSaleDetails(e){return this.tradingQuotesService.fetchSaleDetails(e)}async getTradeQuote(e){return this.tradingQuotesService.getTradeQuote(e)}async getPremintQuote(e){return this.tradingQuotesService.getPremintQuote(e)}async connectStreamWebSocket(e){const t=this.getStreamWebSocketService();await t.connect(),e&&t.addCallbacks(e)}async authenticateStreamWebSocket(e){return this.getStreamWebSocketService().authenticate(e)}deauthenticateStreamWebSocket(){this._streamWebSocketService?.deauthenticate()}async subscribeToStream(e,t){return this.getStreamWebSocketService().subscribeToStream(e,t)}unsubscribeFromStream(e){this.getStreamWebSocketService().unsubscribeFromStream(e)}sendStreamChatViaWebSocket(e,t){this.getStreamWebSocketService().sendChatMessage(e,t)}sendStreamReaction(e,t,n=0){this.getStreamWebSocketService().sendReaction(e,t,n)}sendTypingStart(e){return this.getStreamWebSocketService().sendTypingStart(e)}sendTypingStop(e){return this.getStreamWebSocketService().sendTypingStop(e)}disconnectStreamWebSocket(){this._streamWebSocketService&&this._streamWebSocketService.disconnect()}isStreamWebSocketConnected(){return!!this._streamWebSocketService&&this._streamWebSocketService.isConnected()}onStreamStatusChanged(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_STATUS",e)}onUserBanned(e){return this.getStreamWebSocketService().subscribeEvent("USER_BANNED",e)}onUserUnbanned(e){return this.getStreamWebSocketService().subscribeEvent("USER_UNBANNED",e)}onBanEnforcement(e){return this.getStreamWebSocketService().subscribeEvent("BAN_ENFORCEMENT",e)}watchBanEnforcement(e,t={}){const n=(e,n,s,r)=>(void 0===t.actionType||t.actionType===e)&&(!!(void 0===t.userAddress||null!==n&&In(t.userAddress,n))&&((void 0===t.tokenName||t.tokenName===s)&&!!(void 0===t.reason||null!==r&&r.includes(t.reason)))),s=this.onUserBanned(t=>{const s=t.userAddress??null,r=t.reason??null;n("BANNED",s,t.tokenName,r)&&e({actionType:"BANNED",userAddress:s,tokenName:t.tokenName,reason:r,...void 0!==t.expiresAt&&{expiresAt:t.expiresAt}})}),r=this.onUserUnbanned(t=>{const s=t.userAddress??null;n("UNBANNED",s,t.tokenName,null)&&e({actionType:"UNBANNED",userAddress:s,tokenName:t.tokenName,reason:null})}),i=this.onBanEnforcement(t=>{const s=t.reason??null;n("ENFORCEMENT",null,t.tokenName,s)&&e({actionType:"ENFORCEMENT",userAddress:null,tokenName:t.tokenName,reason:s,...void 0!==t.expiresAt&&{expiresAt:t.expiresAt}})});return()=>{s(),r(),i()}}watchTokenRoomEvent(e,t,n,s){const r=s.tokenName;if(void 0===r||""===r)throw new Error(`${e} requires a tokenName filter - these are per-token stream events with no way to watch every token at once.`);return t(r,n)}watchCommentCreated(e,t={}){return this.watchTokenRoomEvent("watchCommentCreated",(e,t)=>this.getStreamWebSocketService().subscribeCommentCreated(e,t),n=>{(void 0===t.authorAddress||In(t.authorAddress,n.userAddress))&&(void 0!==t.minLength&&n.content.length<t.minLength||e(n))},t)}watchHolderCountUpdated(e,t={}){return this.watchTokenRoomEvent("watchHolderCountUpdated",(e,t)=>this.getStreamWebSocketService().subscribeHolderCountUpdated(e,t),n=>{void 0!==t.minThreshold&&Math.abs(n.change??0)<t.minThreshold||e(n)},t)}watchModeratorAdded(e,t={}){return this.watchTokenRoomEvent("watchModeratorAdded",(e,t)=>this.getStreamWebSocketService().subscribeModeratorAdded(e,t),e,t)}watchPoolMetadataUpdated(e,t={}){return this.watchTokenRoomEvent("watchPoolMetadataUpdated",(e,t)=>this.getStreamWebSocketService().subscribePoolMetadataUpdated(e,t),e,t)}watchTradeExecuted(e,t={}){return this.watchTokenRoomEvent("watchTradeExecuted",(e,t)=>this.getStreamWebSocketService().subscribeTradeExecuted(e,t),n=>{void 0!==t.tradeType&&t.tradeType!==n.tradeType||(void 0===t.userAddress||In(t.userAddress,n.userAddress))&&(void 0!==t.minAmount&&Number(n.inputAmount)<t.minAmount||e(n))},t)}watchTokenBanned(e,t={}){return this.watchTokenRoomEvent("watchTokenBanned",(e,t)=>this.getStreamWebSocketService().subscribeTokenBanned(e,t),e,t)}watchModeratorChanged(e,t={}){const n=(e,n)=>(void 0===t.eventType||t.eventType===e)&&!(void 0!==t.moderatorAddress&&!In(t.moderatorAddress,n)),s=this.watchModeratorAdded(t=>{n("ADDED",t.userAddress)&&e({actionType:"ADDED",tokenName:t.tokenName,moderatorAddress:t.userAddress,role:t.role})},t),r=this.watchTokenRoomEvent("watchModeratorRemoved",(e,t)=>this.getStreamWebSocketService().subscribeModeratorRemoved(e,t),t=>{n("REMOVED",t.userAddress)&&e({actionType:"REMOVED",tokenName:t.tokenName,moderatorAddress:t.userAddress})},t),i=this.watchTokenRoomEvent("watchModeratorRoleUpdated",(e,t)=>this.getStreamWebSocketService().subscribeModeratorRoleUpdated(e,t),t=>{n("ROLE_UPDATED",t.userAddress)&&e({actionType:"ROLE_UPDATED",tokenName:t.tokenName,moderatorAddress:t.userAddress,oldRole:t.oldRole,newRole:t.newRole})},t);return()=>{s(),r(),i()}}watchPoolUpdated(e,t={}){const n=e=>void 0===t.updateType||t.updateType===e,s=this.watchPoolMetadataUpdated(t=>{n("METADATA")&&e({updateType:"METADATA",tokenName:t.tokenName,details:t})},t),r=this.watchTokenRoomEvent("watchPoolSocialLinksUpdated",(e,t)=>this.getStreamWebSocketService().subscribePoolSocialLinksUpdated(e,t),t=>{n("SOCIAL_LINKS")&&e({updateType:"SOCIAL_LINKS",tokenName:t.tokenName,details:t})},t),i=this.watchTokenRoomEvent("watchPoolBadgeAssigned",(e,t)=>this.getStreamWebSocketService().subscribePoolBadgeAssigned(e,t),t=>{n("BADGE_ASSIGNED")&&e({updateType:"BADGE_ASSIGNED",tokenName:t.tokenName,details:t})},t);return()=>{s(),r(),i()}}watchTokenBanChanged(e,t={}){const n=e=>void 0===t.banStatus||t.banStatus===e,s=this.watchTokenBanned(t=>{n("BANNED")&&e({banStatus:"BANNED",tokenName:t.tokenName,reason:t.reason})},t),r=this.watchTokenRoomEvent("watchTokenUnbanned",(e,t)=>this.getStreamWebSocketService().subscribeTokenUnbanned(e,t),t=>{n("UNBANNED")&&e({banStatus:"UNBANNED",tokenName:t.tokenName})},t);return()=>{s(),r()}}onContentFlagged(e){return this.getStreamWebSocketService().subscribeEvent("CONTENT_FLAGGED",e)}onFlagResolved(e){return this.getStreamWebSocketService().subscribeEvent("FLAG_RESOLVED",e)}onStreamChatMessage(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_CHAT_MESSAGE",e)}onStreamChatUpdated(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_CHAT_UPDATED",e)}onStreamChatDeleted(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_CHAT_DELETED",e)}onStreamChatPinned(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_CHAT_PINNED",e)}onStreamChatUnpinned(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_CHAT_UNPINNED",e)}onChatStatusChanged(e){return this.getStreamWebSocketService().subscribeEvent("CHAT_STATUS_CHANGED",e)}onViewerCountChanged(e){return this.getStreamWebSocketService().subscribeEvent("VIEWER_COUNT",e)}onRecordingStatusChanged(e){return this.getStreamWebSocketService().subscribeEvent("RECORDING_STATUS",e)}onSimulcastStatusChanged(e){return this.getStreamWebSocketService().subscribeEvent("SIMULCAST_STATUS",e)}onDownloadReady(e){return this.getStreamWebSocketService().subscribeEvent("DOWNLOAD_READY",e)}onRecordingsCountUpdated(e){return this.getStreamWebSocketService().subscribeEvent("RECORDINGS_COUNT_UPDATED",e)}onUserTyping(e){return this.getStreamWebSocketService().subscribeEvent("USER_TYPING",e)}onStreamReaction(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_REACTION",e)}onContentReactionAdded(e){return this.getStreamWebSocketService().subscribeEvent("CONTENT_REACTION_ADDED",e)}onContentReactionRemoved(e){return this.getStreamWebSocketService().subscribeEvent("CONTENT_REACTION_REMOVED",e)}onStreamCountdownUpdated(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_COUNTDOWN_UPDATED",e)}onStreamLanguageUpdated(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_LANGUAGE_UPDATED",e)}onStreamControlStatusChanged(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_CONTROL_STATUS_CHANGED",e)}onConnection(e){return this.getStreamWebSocketService().subscribeEvent("connection",e)}onAuthenticated(e){return this.getStreamWebSocketService().subscribeEvent("authenticated",e)}onTokenSubscribed(e){return this.getStreamWebSocketService().subscribeEvent("token_subscribed",e)}onTokenUnsubscribed(e){return this.getStreamWebSocketService().subscribeEvent("token_unsubscribed",e)}onRoomSubscribed(e){return this.getStreamWebSocketService().subscribeEvent("room_subscribed",e)}onRoomLeft(e){return this.getStreamWebSocketService().subscribeEvent("room_left",e)}onEngagementStatsUpdated(e){return this.getStreamWebSocketService().subscribeEvent("ENGAGEMENT_STATS_UPDATED",e)}async estimateBridgeFee(e){return this.getBridgeService(await this.coreBridge()).estimateBridgeFee(e)}async bridgeOut(e){return this.getBridgeService(await this.coreBridge()).bridgeOut(e)}async bridgeIn(e){return this.getBridgeService(await this.coreBridge()).bridgeIn(e)}async getBridgeStatus(e){return this.getBridgeService(await this.coreBridge()).getBridgeStatus(e)}async getSupportedBridgeTokens(){const e=this.getBridgeService(await this.coreBridge()),t=e.getSupportedBridgeTokens();return{tokens:t,totalCount:t.length,supportedChains:e.getSupportedBridgeChains()}}async fetchTokenBalance(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Bn}),n=t(e.address);if(void 0!==e.tokenId&&""!==e.tokenId){const{normalizeToTokenInstanceKey:t}=await Promise.resolve().then(function(){return Zi}),s=t(e.tokenId),{collection:r,category:i,type:a,additionalKey:o}=s;return this.galaChainService.fetchTokenBalance({owner:n,collection:r,category:i,additionalKey:o,type:a},e.withExpired??!1)}if(void 0!==e.tokenName&&""!==e.tokenName){const t=pn(e.tokenName),s=nd[t];if(void 0!==s)return this.galaChainService.fetchTokenBalance({owner:n,collection:s,category:"Unit",additionalKey:"none",type:"none"},e.withExpired??!1)}if(void 0!==e.tokenName&&""!==e.tokenName){const t=(await this.fetchTokensHeld({tokenName:e.tokenName,pageSize:1,...void 0!==n?{address:n}:{}})).tokens[0];if(void 0===t)return null;const s=await this.resolveTokenClassKey(e.tokenName);return{quantity:t.balance,collection:s.collection,category:s.category,tokenId:Hi(s)}}throw zt("tokenId or tokenName","Either tokenId or tokenName")}async fetchLockedBalance(e){const t=await this.fetchTokenBalance(e);if(!t)return null;const n="lockedHolds"in t||"lockedQuantity"in t;return{tokenId:t.tokenId,lockedQuantity:n?t.lockedQuantity??"0":"0",lockedHolds:n?t.lockedHolds??[]:[]}}async fetchAvailableBalance(e){const t=await this.fetchTokenBalance(e);if(!t)return null;const n="availableQuantity"in t;return{tokenId:t.tokenId,availableQuantity:n?t.availableQuantity??String(t.quantity):String(t.quantity),totalQuantity:String(t.quantity)}}async calculateBuyAmount(e){return this.launchpadAPI.calculateBuyAmount(e)}async calculateSellAmount(e){return this.launchpadAPI.calculateSellAmount(e)}async calculateBuyAmountLocal(e){return this.launchpadAPI.calculateBuyAmountLocal(e)}async calculateSellAmountLocal(e){return this.launchpadAPI.calculateSellAmountLocal(e)}async calculateBuyAmountExternal(e){return this.launchpadAPI.calculateBuyAmountExternal(e)}async calculateSellAmountExternal(e){return this.launchpadAPI.calculateSellAmountExternal(e)}async calculateBuyAmountForGraduation(e){return this.launchpadAPI.calculateBuyAmountForGraduation(e)}async graduateToken(e){const{tokenName:t,slippageToleranceFactor:n,maxAcceptableReverseBondingCurveFeeSlippageFactor:s,privateKey:r,calculateAmountMode:i,currentSupply:a}=e;let o=t;void 0===i&&void 0===a||(o={tokenName:t,...void 0!==i&&{calculateAmountMode:i},...void 0!==a&&{currentSupply:a}});const c=await this.calculateBuyAmountForGraduation(o),l={tokenName:t,amount:c.remainingTokens,type:"exact",expectedAmount:c.amount,maxAcceptableReverseBondingCurveFee:c.reverseBondingCurveFee,slippageToleranceFactor:this.slippageToleranceFactor};return void 0!==n&&(l.slippageToleranceFactor=n),void 0!==s&&(l.maxAcceptableReverseBondingCurveFeeSlippageFactor=s),void 0!==r&&(l.privateKey=r),await this.buy(l)}async calculateInitialBuyAmount(e){const t={nativeTokenQuantity:e};return this.launchpadAPI.calculateInitialBuyAmount(t)}async buy(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...s}=e;return t.buy(s)}this.validateWallet(),await this.ensureWebSocketConnection();const t=(await this.bundleService.buyToken(e)).data,n=t?.transactionId;if(void 0===n||""===n)throw Yt("No transaction ID returned from buy operation");return this.waitForConfirmation(n,t=>ed(t,n,"buy",e))}async sell(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...s}=e;return t.sell(s)}this.validateWallet(),await this.ensureWebSocketConnection();const t=(await this.bundleService.sellToken(e)).data,n=t?.transactionId;if(void 0===n||""===n)throw Yt("No transaction ID returned from sell operation");return this.waitForConfirmation(n,t=>ed(t,n,"sell",e))}async getBundlerTransactionResult(e){return this.bundleService.getBundlerTransactionResult(e)}async launchToken(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...s}=e;return t.launchToken(s)}this.validateWallet(),await this.ensureWebSocketConnection();const t=await this.launchpadAPI.launchToken(e);return this.waitForConfirmation(t,n=>{Zl(n,t);const s=n.data??{};if(!function(e){if(Jn(e)||"object"!=typeof e)return!1;const t=e;return!(void 0!==t.vaultAddress&&"string"!=typeof t.vaultAddress||void 0!==t.tokenStringKey&&"string"!=typeof t.tokenStringKey||void 0!==t.creatorAddress&&"string"!=typeof t.creatorAddress)}(s))throw new Xl(`Invalid launch data received for transaction ${t}`);const r={transactionId:t,vaultAddress:s.vaultAddress??"",tokenStringKey:s.tokenStringKey??"",tokenName:e.tokenName,tokenSymbol:e.tokenSymbol,creatorAddress:s.creatorAddress??this.getAddress(),timestamp:Date.now(),...void 0!==n.blockHash&&""!==n.blockHash?{blockHash:n.blockHash}:{},...void 0!==n.gasUsed?{gasUsed:n.gasUsed}:{}};return"string"==typeof e.tokenImage&&(r.tokenImage=e.tokenImage),void 0!==e.preBuyQuantity&&(r.preBuyQuantity=e.preBuyQuantity),""!==r.vaultAddress&&this.tokenResolverService.set(e.tokenName,r.vaultAddress),r})}async uploadTokenImage(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...s}=e;return t.uploadTokenImage(s)}return this.launchpadService.uploadImageByTokenName(e)}async checkPoolExists(e,t){return this.launchpadService.checkPoolExists(e,t)}async isTokenNameAvailable(e){return this.launchpadService.isTokenNameAvailable(e)}async isTokenSymbolAvailable(e){return this.launchpadService.isTokenSymbolAvailable(e)}async fetchToken(e){return this.launchpadService.fetchToken(e)}async validateToken(e){return this.launchpadService.validateToken(e)}async fetchTokenStats(e){return this.launchpadService.fetchTokenStats(e)}async fetchProfile(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Bn}),n=t(e)??this.getAddress();return this.launchpadService.fetchProfile(n)}async fetchReferralUrl(){this.validateWallet();const e=this.getAddress();return await this.dexApiHttp.get(O,void 0,{"x-wallet-address":e})}async fetchReferrals(e){const t=this.resolveReferralAddress(e?.address),n=e?.page??1,s=e?.limit??10,r={pageNumber:n,limit:s,sortBy:e?.sortBy??"joined",sortDir:e?.sortDir??"desc"},i=await this.dexApiHttp.get(U,r,{"x-wallet-address":t});if(!Array.isArray(i))throw new Lt("Unexpected API response: expected array, got "+typeof i);return{referrals:i,page:n,limit:s,hasMore:i.length===s}}async fetchAllReferrals(e){const t=await async function(e,t={}){const{maxPages:n=1e4,logger:s,pageSize:r=20,concurrency:i=1,startPage:a=1}=t,o=[];let c=a;const l=a+n-1;let d=!0,u=0;if(i<=1)for(;d&&c<=l;){s&&s.debug(`Auto-pagination: fetching page ${c} with limit ${r}`);const t=await e(c,r);if(null==t||!Array.isArray(t.items)){s&&s.warn("Auto-pagination: received invalid result structure, stopping");break}if(o.push(...t.items),u=t.total,s&&s.debug(`Auto-pagination: page ${c} returned ${t.items.length} items, hasNext: ${String(t.hasNext)}`),0===t.items.length){s&&s.debug(`Auto-pagination: no items returned on page ${c}, exiting loop`);break}d=t.hasNext,c++}else for(s&&s.debug(`Auto-pagination: using concurrent mode with concurrency=${i}`);d&&c<=l;){const t=[];for(let e=0;e<i&&c+e<=l;e++)t.push(c+e);s&&s.debug(`Auto-pagination: fetching pages ${t.join(", ")} concurrently`);const n=t.map(t=>e(t,r).catch(e=>{const n=e,i=n.statusCode??n.response?.status??n.originalError?.response?.status??n.status??n.launchpadError?.statusCode;if(400===i||404===i)return s&&s.debug(`Auto-pagination: page ${t} returned ${i} (end of pagination)`,{statusCode:i}),{items:[],total:0,totalPages:0,page:t,limit:r,hasNext:!1,hasPrevious:!1};throw e})),a=await Promise.all(n);for(const e of a){if(null==e||!Array.isArray(e.items)){s&&s.warn("Auto-pagination: received invalid result structure in batch, stopping"),d=!1;break}if(0===e.items.length){s&&s.debug("Auto-pagination: empty page in batch, reached end of results"),d=!1;break}if(o.push(...e.items),u=e.total,!e.hasNext){d=!1;break}}c+=t.length,s&&s.debug(`Auto-pagination: batch complete, total items so far: ${o.length}`)}return c>l&&s&&s.warn(`Auto-pagination: exceeded maxPages limit of ${n} (maxPage=${l}), stopping iteration`),s&&s.debug(`Auto-pagination: completed with total items: ${o.length}, total count: ${u}`),{items:o,total:u}}((t,n)=>this.fetchReferrals({...e,page:t,limit:n}).then(e=>({items:e.referrals,page:e.page,limit:e.limit,total:0,totalPages:0,hasNext:e.hasMore,hasPrevious:e.page>1})),{maxPages:100,pageSize:100,logger:this.logger});return{referrals:t.items,total:t.items.length}}async fetchReferralsSummary(e){const t=this.resolveReferralAddress(e?.address),n=await this.dexApiHttp.get(M,void 0,{"x-wallet-address":t});if(void 0===n||"number"!=typeof n.referralCount||void 0===n.rewardTotals)throw new Lt(`Unexpected API response: expected { referralCount, rewardTotals }, got ${JSON.stringify(n)}`);return n}async updateProfile(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Bn}),{address:n,...s}=e,r=void 0===n?void 0:t(n),i={...s,...void 0!==r&&{address:r}};if(void 0!==i.privateKey&&""!==i.privateKey){const e=this.createOverrideSdk(i.privateKey),{privateKey:t,...n}=i;return e.updateProfile(n)}return this.launchpadService.updateProfile(i)}async uploadProfileImage(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Bn}),n=void 0===e.address?void 0:t(e.address)??e.address,s={...e,...void 0!==n&&{address:n}};if(void 0!==s.privateKey&&""!==s.privateKey){const e=this.createOverrideSdk(s.privateKey),{privateKey:t,...n}=s;return e.uploadProfileImage(n)}return this.launchpadService.uploadProfileImage(s)}async fetchTokensHeld(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Bn}),n=t(e?.address)??this.getAddress(),s={pageSize:e?.pageSize??10,address:n,...void 0!==e?.cursor?{cursor:e.cursor}:{}};return void 0!==e?.tokenName&&""!==e.tokenName&&(s.tokenName=e.tokenName),void 0!==e?.search&&""!==e.search&&(s.search=e.search),this.launchpadService.fetchTokensHeld(s)}async fetchTokensCreated(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Bn}),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 Bn}),n={...e,recipientAddress:t(e.recipientAddress)};if(void 0!==n.privateKey&&""!==n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...s}=n;return e.transferGala(s)}return this.assertTokenWriter(),this.galaChainService.transferGala(n)}async transferToken(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Bn}),n={...e,to:t(e.to)};if(void 0!==n.privateKey&&""!==n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...s}=n;return e.transferToken(s)}return this.assertTokenWriter(),this.galaChainService.transferToken(n)}async resolveTokenClassKey(e){return this.galaChainService.resolveTokenClassKey(e)}async convertTokenNameToTokenClassKey(e){return this.resolveTokenClassKey(e)}async lockTokens(e){const t=await Promise.all(e.tokens.map(async e=>{if(void 0!==e.lockAuthority&&""!==e.lockAuthority){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Bn});return{...e,lockAuthority:t(e.lockAuthority)}}return e})),n={...e,tokens:t};if(void 0!==n.privateKey&&""!==n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...s}=n;return e.lockTokens(s)}return this.assertTokenWriter(),this.galaChainService.lockTokens(n)}async unlockTokens(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...s}=e;return t.unlockTokens(s)}return this.assertTokenWriter(),this.galaChainService.unlockTokens(e)}async burnTokens(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...s}=e;return t.burnTokens(s)}return this.assertTokenWriter(),this.galaChainService.burnTokens(e)}async resolveVaultAddress(e){return this.tokenResolverService.resolveTokenToVault(e)}async findTokenNameByVault(e,t){let n;for(let s=0;s<10;s+=1){const s=await this.launchpadService.poolService.fetchPools({search:t,pageSize:100,...void 0===n?{}:{cursor:n}}),r=s.items.find(t=>t.vaultAddress===e);if(void 0!==r)return r.tokenName;const i=ii(s.pageInfo,n);if(void 0===i)return;n=i}}getCacheInfo(){const e={...this.launchpadAPI.getCacheStats()};if(this._bridgeableTokenService){const t=this._bridgeableTokenService.getCacheStats();e.bridgeableTokens={ETHEREUM:t.tokensByNetwork.ETHEREUM,SOLANA:t.tokensByNetwork.SOLANA,total:t.totalTokens}}return this._wrappableTokenService&&(e.wrappableTokens=this._wrappableTokenService.getCacheStats()),e}clearCache(e){this.launchpadAPI.clearCache(e),void 0!==e&&""!==e||(void 0!==this._bridgeableTokenService&&this._bridgeableTokenService.clearCache(),void 0!==this._wrappableTokenService&&this._wrappableTokenService.clearCache())}validateConfiguration(){try{jn(this.config.timeout,1,3e5,"timeout")}catch{this.logger.warn(`Invalid timeout value: ${this.config.timeout??"undefined"}. Using default 30000ms.`),this.config.timeout=3e4}if(void 0===this.config.baseUrl||""===this.config.baseUrl)throw Jt("baseUrl is required in configuration","baseUrl");if(void 0===this.config.webSocketUrl||""===this.config.webSocketUrl)throw Jt("webSocketUrl is required in configuration","webSocketUrl");try{new URL(this.config.baseUrl)}catch{throw Jt(`Invalid baseUrl format: ${this.config.baseUrl}`,"baseUrl")}try{new URL(this.config.webSocketUrl)}catch{throw Jt(`Invalid webSocketUrl format: ${this.config.webSocketUrl}`,"webSocketUrl")}if(void 0!==this.config.gatewayBaseUrl&&""!==this.config.gatewayBaseUrl)try{new URL(this.config.gatewayBaseUrl)}catch{throw Jt(`Invalid gatewayBaseUrl format: ${this.config.gatewayBaseUrl}`,"gatewayBaseUrl")}if(void 0!==this.config.bundleBaseUrl&&""!==this.config.bundleBaseUrl)try{new URL(this.config.bundleBaseUrl)}catch{throw Jt(`Invalid bundleBaseUrl format: ${this.config.bundleBaseUrl}`,"bundleBaseUrl")}if(void 0!==this.config.launchpadFrontendUrl&&""!==this.config.launchpadFrontendUrl)try{new URL(this.config.launchpadFrontendUrl)}catch{throw Jt(`Invalid launchpadFrontendUrl format: ${this.config.launchpadFrontendUrl}`,"launchpadFrontendUrl")}}parseSlippageToleranceFactor(e){const t=$n("string"==typeof e||"number"==typeof e?e:String(e),ad.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR);return t<0||t>1?(this.logger.warn(`Invalid slippage tolerance factor: ${String(e)}, using default: ${ad.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR}`),ad.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR):t}parseFeeSlippageFactor(e){const t=$n("string"==typeof e||"number"==typeof e?e:String(e),ad.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: ${ad.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR}`),ad.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!==Zr.COMPLETED)throw new Yl(e,n.status,n.message);let s;try{s=t(n)}catch(t){if(t instanceof Xl)throw t;throw new Xl(`Failed to transform WebSocket response for transaction ${e}`,Bt(t)?t:new Error($t(t)))}return this.logger.debug(`Transaction confirmed: ${e}`,s),s}catch(t){if(this.logger.error(`Transaction confirmation failed: ${e}`,t),t instanceof Yl||t instanceof Xl)throw t;throw new Xl(`WebSocket confirmation failed for transaction ${e}`,Bt(t)?t:new Error($t(t)))}}async warmCacheFromPools(e){if(void 0===e||!Array.isArray(e))return;const{extractMetadataFromPoolData:t,isValidPoolForCaching:n}=await Promise.resolve().then(function(){return cd});e.forEach(e=>{if(!n(e))return;const s=t(e,this.logger);s&&this.launchpadAPI.warmCacheFromPoolData(e.tokenName,s)})}connectWebSocket(){this.websocketService.connect()}disconnectWebSocket(){this.websocketService.disconnect()}isWebSocketConnected(){return this.websocketService.isConnected()}subscribeToEvent(e,t){const n=this.websocketService.getSocket();return n?(n.on(e,t),()=>{n.off(e,t),this.logger.debug(`Unsubscribed from event: "${e}"`)}):(this.logger.warn(`⚠️ WebSocket not connected - subscribing to "${e}" without connection`),()=>{})}onLaunchpadTokenCreation(e,t){const n=1e3,s=Math.max(t?.intervalMs??3e4,n);null!=t?.intervalMs&&t.intervalMs<n&&this.logger.warn(`Poll interval ${t.intervalMs}ms is below minimum 1000ms. Using minimum interval instead.`);const r=t?.creatorAddress,i=new Map;let a=!0,o=null;let c=0;const l=async()=>{if(a){try{const t=await this.fetchPools({type:"recent",pageSize:20});c>0&&(this.logger.debug("Successfully recovered from polling errors"),c=0),t.items.forEach(t=>{i.has(t.tokenName)||((e=>{if(i.set(e,!0),i.size>1e3){const e=i.keys().next().value;void 0!==e&&i.delete(e)}})(t.tokenName),void 0!==r&&""!==r&&t.creatorAddress!==r||e(t))})}catch(e){c++;const t=$t(e);c>=5?this.logger.error(`Polling for new launchpad tokens failed ${c} consecutive times. Last error: ${t}. Continuing to retry...`):c>1?this.logger.warn(`Error polling for new launchpad tokens (attempt ${c}/5): ${t}`):this.logger.debug(`Error polling for new launchpad tokens: ${t}`)}if(a){const e=Math.min(Math.max(c-1,0),2),t=s*Math.pow(2,e);o=setTimeout(()=>{l()},t)}}};return l(),()=>{a=!1,o&&clearTimeout(o),this.logger.debug("Stopped watching for launchpad token creation")}}matchesCreatorFilter(e,t){return void 0===t||""===t||e.creatorAddress===t}subscribeToTokenCreations(e,t){if(this.logger.debug("Subscribing to token creation broadcasts"+(void 0!==t?.creatorFilter&&""!==t.creatorFilter?` (filter: ${t.creatorFilter})`:"")),null===this.websocketService||void 0===this.websocketService)throw Jt("WebSocket service not initialized. Ensure websocketUrl is configured and the service is connected.","websocketService");let n=!1,s=null;const r=(n,...s)=>{try{if(s.length>0&&"object"==typeof s[0]&&null!==s[0]){const n=s[0].data;if(void 0!==n?.Data&&null!==n.Data&&"object"==typeof n.Data){const s=n.Data;if("CreateSale"===s.functionName){const n=(e,t="")=>{const n=s[e];return"string"==typeof n&&""!==n?n:t},r={tokenName:n("tokenName"),symbol:n("symbol"),creatorAddress:n("creatorAddress"),description:n("description"),image:n("image"),vaultAddress:n("vaultAddress"),tokenStringKey:n("tokenStringKey"),preBuyQuantity:n("initialBuyQuantity","0"),websiteUrl:n("websiteUrl"),telegramUrl:n("telegramUrl"),twitterUrl:n("twitterUrl"),instagramUrl:n("instagramUrl"),facebookUrl:n("facebookUrl"),redditUrl:n("redditUrl"),tiktokUrl:n("tiktokUrl"),isFinalized:!0===s.isFinalized};this.matchesCreatorFilter(r,t?.creatorFilter)&&e(r)}}}}catch(e){this.logger.warn(`Error processing token creation broadcast: ${$t(e)}`)}};let i=this.websocketService.getSocket();if(i)i.onAny(r),n=!0,this.logger.debug("Token creation broadcast listener registered");else{this.logger.debug("WebSocket not yet connected, initiating connection..."),this.websocketService.connect().catch(e=>{const n=new Error(`WebSocket connection failed: ${$t(e)}`);this.logger.warn("Failed to establish WebSocket connection:",e),t?.onError&&t.onError(n)});let e=0;const a=()=>{if(i=this.websocketService.getSocket(),!i&&e<ad.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS)return e++,void(s=setTimeout(()=>a(),ad.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS));if(!i&&e>=ad.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS){const e=new Error(`WebSocket not available after ${ad.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS*ad.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS}ms`);return this.logger.warn("Token creation broadcast subscription timeout:",e.message),void(t?.onError&&t.onError(e))}i&&(i.onAny(r),n=!0,this.logger.debug("Token creation broadcast listener registered"))};a()}return()=>{try{if(null!==s&&(clearTimeout(s),s=null,this.logger.debug("Cleared token creation broadcast polling timeout")),!n)return void this.logger.debug("Cleanup called before listener registration - no action needed");const e=this.websocketService.getSocket();e&&(e.offAny(r),n=!1,this.logger.debug("Stopped listening to token creation broadcasts"))}catch(e){this.logger.warn("Error removing token creation listener:",e)}}}getNftCollectionClaimFee(){return this.nftCollectionService.getCollectionClaimFee()}getNftTokenClassCreateFee(){return this.nftCollectionService.getTokenClassCreateFee()}estimateNftMintFee(e){return this.nftCollectionService.estimateMintFee(e)}estimateNftOperationFees(e){return this.nftCollectionService.estimateNftOperationFees(e)}claimNftCollection(e){return this.nftCollectionService.claimCollection(e)}fetchNftCollections(e){return this.nftCollectionService.fetchUserCollections(e)}isNftCollectionAvailable(e){return this.nftCollectionService.isCollectionAvailable(e)}createNftTokenClass(e){return this.nftCollectionService.createTokenClass(e)}fetchNftTokenClasses(e){return this.nftCollectionService.fetchTokenClasses(e)}mintNft(e){return this.nftCollectionService.mintNft(e)}fetchNftBalances(e,t){return this.nftCollectionService.fetchNftBalances(e,t)}async cleanup(){try{if(this.logger.debug("Starting cleanup..."),void 0!==this._eventsBatcherService)try{await this._eventsBatcherService.shutdown(5e3),this._eventsBatcherService=void 0}catch(e){this.logger.warn("Error during events shutdown:",e)}this.http.cleanup(),null!==this.websocketService&&void 0!==this.websocketService&&this.websocketService.disconnect(),void 0!==this._streamWebSocketService&&(this._streamWebSocketService.dispose(),this._streamWebSocketService=void 0),this.logger.debug("Cleanup completed")}catch(e){this.logger.error("Error during cleanup:",e)}}static cleanupAll(e=!1){const t=new An({debug:e,context:"LaunchpadSDK"});t.debug("Starting global cleanup..."),fl.cleanupAll(e),t.debug("Global cleanup completed")}}function od(e){Jn(e)&&(e={});const{wallet:t,env:n,config:s={},...r}=e,a={...{...r,...s}};delete a.wallet,delete a.env,delete a.config;const o=!Jn(a.signer)||!Jn(a.walletProvider);let c;if(Jn(t))c=o?void 0:new i(T().privateKey);else if("string"==typeof t)c=new i(T(t).privateKey);else{if(!(t instanceof i))throw Jt("Invalid wallet input. Expected string (private key or mnemonic) or Wallet instance.","wallet");c=t}const l={...void 0!==c?{wallet:c}:{},...void 0!==n?{env:n}:{},debug:!1,timeout:3e4,...a};return new ad(l)}ad.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR=.15,ad.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR=.01,ad.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY=mn.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY,ad.DEFAULT_CALCULATE_AMOUNT_MODE="local",ad.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS=30,ad.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS=100;var cd=Object.freeze({__proto__:null,extractMetadataFromPoolData:function(e,t){const n={};if(void 0!==e.vaultAddress&&(n.vaultAddress=e.vaultAddress),void 0!==e.reverseBondingCurveMinFeePortion){const s=$n(e.reverseBondingCurveMinFeePortion,NaN);isNaN(s)?t&&t.debug(`Skipping invalid reverseBondingCurveMinFeePortion for ${e.tokenName}: "${e.reverseBondingCurveMinFeePortion}"`):n.reverseBondingCurveMinFeeFactor=s}if(void 0!==e.reverseBondingCurveMaxFeePortion){const s=$n(e.reverseBondingCurveMaxFeePortion,NaN);isNaN(s)?t&&t.debug(`Skipping invalid reverseBondingCurveMaxFeePortion for ${e.tokenName}: "${e.reverseBondingCurveMaxFeePortion}"`):n.reverseBondingCurveMaxFeeFactor=s}return void 0!==n.reverseBondingCurveMaxFeeFactor&&void 0!==n.reverseBondingCurveMinFeeFactor&&(n.reverseBondingCurveNetFeeFactor=n.reverseBondingCurveMaxFeeFactor-n.reverseBondingCurveMinFeeFactor),Object.keys(n).length>0?n:null},isValidPoolForCaching:function(e){if(null===e||"object"!=typeof e)return!1;const t=e;return"tokenName"in t&&"string"==typeof t.tokenName&&t.tokenName.length>0}});export{$i as BrowserWalletSigner,ba as EVENT_TYPES,Bi as GalaWalletSigner,ad as LaunchpadSDK,Di as LaunchpadSDKError,Pi as PrivateKeySigner,ti as SDK_VERSION,Yl as TransactionFailedError,Xl as WebSocketError,Jl as WebSocketTimeoutError,od as createLaunchpadSDK};
1
+ import{z as e}from"zod";import{computeAddress as t,getAddress as n,isAddress as s,BrowserProvider as r,Wallet as i}from"ethers";import{galaChainUserRef as a,isGalaError as o,GALA_CHAIN_ENVIRONMENTS as c,BrowserWalletSigner as l,generateEIP712Types as d,ethereumAddressOfAccount as u,GalaWalletSigner as h,withGalaWalletIdentity as g,PrivateKeySigner as m,isTokenClassKey as f,GatewayReads as p,GatewayWrites as v,tokenDetailsOf as A,isWalletUserRejection as E,walletDeclineCode as y,createWallet as T}from"@gala-chain/gala-core-sdk";import{PrivateKeyProvider as S,isPrivateKeyProvider as b}from"@gala-chain/gala-core-sdk/providers";import{ChainCallDTO as k,TokenClassKey as w}from"@gala-chain/api";import{v4 as N}from"uuid";import{io as I}from"socket.io-client";import _ from"bignumber.js";import C,{AxiosHeaders as D}from"axios";const R={UPLOAD_IMAGE:"/v1/tokens/:tokenName/image",FETCH_POOLS:"/v1/tokens",GET_TOKEN:"/v1/tokens/:tokenName",GET_TOKEN_DISTRIBUTION:"/v1/holders",CHART:"/v1/chart",GET_TRADES:"/v1/tokens/:tokenName/trades",GET_PROFILE:"/v1/users/:address",UPDATE_PROFILE:"/v1/users/me",GET_CURRENT_USER:"/v1/users/me/profile",UPLOAD_PROFILE_IMAGE:"/v1/users/me/image",GET_TOKEN_LIST:"/v1/users/:address/tokens",GET_TOKENS_HELD:"/v1/users/:address/tokens",GET_GALA_BALANCE:"/v1/users/:address/gala-balance",GET_REFERRAL_CODE:"/v1/connect/users/referrals/code",GET_MANAGED_TOKENS:"/v1/users/me/managed-tokens",VALIDATE_TOKEN:"/v1/utils/validate-token",UPDATE_TOKEN_CONFIG:"/v1/tokens/:tokenName",TOKEN_STATS:"/v1/tokens/:tokenName/stats",OEMBED:"/oembed",OEMBED_BUY_SELL:"/oembed/buy-sell/:tokenName",OEMBED_PROFILE:"/oembed/profile/:address"},O="/v1/users/referrals/url",M="/v1/users/referrals",U="/v1/users/referrals/summary",F="/v1/tokens/:tokenName/start-stream",L="/v1/tokens/:tokenName/stop-stream",x="/v1/tokens/:tokenName/stream/disable",P="/v1/tokens/:tokenName/stream/enable",B="/v1/tokens/:tokenName/reset-key",$="/v1/tokens/:tokenName/recordings",G="/v1/tokens/:tokenName/recordings/:assetId/download",K="/v1/tokens/:tokenName/recordings/:assetId",W="/v1/tokens/:tokenName/simulcasts",H="/v1/tokens/:tokenName/simulcasts",j="/v1/tokens/:tokenName/simulcasts/:targetId",q="/v1/config",V="/v1/config",z="/v1/config",Q="/v1/tokens/:tokenName/role",X="/v1/roles",J="/v1/permissions",Y="/v1/tokens/:tokenName/credentials",Z="/auth/login",ee="/auth/logout",te="/auth/refresh",ne="/auth/session",se="/v1/tokens/:tokenName/bans",re="/v1/tokens/:tokenName/bans",ie="/v1/tokens/:tokenName/bans/:userAddress",ae="/v1/tokens/:tokenName/bans/:userAddress",oe="/v1/tokens/:tokenName/active-users",ce="/v1/user-bans",le="/v1/user-bans",de="/v1/user-bans/:userAddress",ue="/v1/user-bans/:userAddress",he={CREATE:"/v1/api-keys",LIST:"/v1/api-keys",GET:"/v1/api-keys/:id",UPDATE:"/v1/api-keys/:id",REVOKE:"/v1/api-keys/:id"},ge="/v1/moderator-invites",me="/v1/moderator-invites/claim",fe="/v1/moderated-tokens",pe="/v1/moderator-invites",ve="/v1/moderator-invites/:id",Ae="/v1/moderator-invites/:id/role",Ee="/v1/moderator-invites/:id",ye="/v1/moderator-invites/code/:code",Te={CREATE:"/v1/content-flags",LIST:"/v1/content-flags",DISMISS:"/v1/content-flags/:id/dismiss",ACTION:"/v1/content-flags/:id/action"},Se="/v1/overseer-invites",be="/v1/overseer-invites",ke="/v1/overseer-invites/code/:code",we="/v1/overseer-invites/claim",Ne="/v1/overseer-invites/:id",Ie="/v1/overseers",_e="/v1/overseers",Ce="/v1/overseers/:address",De="/v1/overseers/me",Re="/v1/overseer-summary",Oe="/v1/overseer-summary/bans",Me="/v1/overseer-summary/token-bans",Ue="/v1/overseer-summary/invites",Fe="/v1/overseer-summary/flags",Le="/v1/overseer-summary/users",xe="/v1/users",Pe="/v1/users/:address/summary",Be="/v1/cache/flush/address/:address",$e="/v1/cache/flush/token/:tokenName",Ge="/v1/cache/flush/all",Ke="/v1/cache/flush/wallet-aliases/:address",We="/v1/cache/flush/wallet-aliases",He="/v1/token-bans",je="/v1/token-bans",qe="/v1/token-bans/:tokenName",Ve="/v1/token-bans/:tokenName",ze="/v1/reactions",Qe="/v1/reactions",Xe="/v1/trades",Je={GET_MESSAGES:"/v1/messages",CREATE_MESSAGE:"/v1/messages",UPDATE_MESSAGE:"/v1/messages/:id",DELETE_MESSAGE:"/v1/messages/:id",GET_PINNED:"/v1/messages/pinned",PIN_MESSAGE:"/v1/messages/:id/pin",UNPIN_MESSAGE:"/v1/messages/:id/pin",GET_MESSAGE_STATS:"/v1/messages/stats"},Ye="/v1/restricted-token-names",Ze="/v1/restricted-token-names",et="/live/:tokenName/chat",tt="/live/:tokenName/chat",nt="/live/:tokenName/chat",st="/live/:tokenName/chat/slow-mode",rt="/v1/events",it="/v1/events/stats",at="/health",ot={GET_SETTINGS:"/v1/ai-moderation/settings",UPDATE_SETTINGS:"/v1/ai-moderation/settings",GET_MODERATION:"/v1/ai-moderation/flags/:flagId",TRIGGER_MODERATION:"/v1/ai-moderation/flags/:flagId/analyze",GET_STATUS:"/v1/ai-moderation/status"},ct="/v1/stats",lt="/v1/trading/fee",dt="/v1/trading/sale-details",ut="/v1/trading/quote",ht="/v1/trading/premint-quote",gt={GET_LEADERBOARD:"/weekly-challenge",GET_TOKEN_HISTORY:"/weekly-challenge/history/:vaultAddress"},mt="/v1/notifications/register",ft="/v1/notifications/unregister",pt="/v1/notifications/preferences",vt="/v1/notifications/preferences",At="/v1/config/client-flags",Et="native",yt="exact",Tt=["RECENT","POPULAR","RECORDINGS","SECONDS_STREAMED"],St=["IDLE","ACTIVE","DISABLED"],bt=100,kt="REQUIRED",wt="INVALID_TYPE",Nt="INVALID_VALUE",It="INVALID_FORMAT",_t="TOO_LONG",Ct="TOO_LARGE",Dt="INVALID_RANGE",Rt="INVALID_PARAMETERS";class Ot extends Error{constructor(e,t,n){super(e),this.field=t,this.code=n,this.name="ValidationError"}}function Mt(e){return"object"==typeof e&&null!==e}function Ut(e){if(null==e||""===e)return{};if(!Mt(e)||Array.isArray(e))return{body:e};const t=Reflect.get(e,"message"),n="string"==typeof t?t:Array.isArray(t)&&t.every(e=>"string"==typeof e)?t.join(","):void 0,s=Reflect.get(e,"error"),r=Reflect.get(e,"details");return{...void 0===n?{}:{serverMessage:n},..."string"==typeof s&&""!==s?{serverError:s}:{},...void 0===r?{}:{details:r},body:e}}function Ft(e){if(e instanceof Lt)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(!Mt(e))return;const t=Reflect.get(e,"response");return Mt(t)?t:void 0}(e);return void 0===t?{}:Ut(Reflect.get(t,"data"))}class Lt extends Error{constructor(e,t,n,s=Ft(n)){super(e),this.name="NetworkError",this.statusCode=t,this.originalError=n,this.serverMessage=s.serverMessage,this.serverError=s.serverError,this.details=s.details,this.body=s.body}}class xt extends Error{constructor(e,t){super(e),this.field=t,this.name="ConfigurationError"}}class Pt extends Error{constructor(e,t,n){super(e),this.transactionId=t,this.code=n,this.name="TransactionError"}}function Bt(e){return e instanceof Error}function $t(e){return Bt(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 Gt(e){return Bt(e)||"object"==typeof e&&null!==e&&"stack"in e&&"string"==typeof e.stack?e.stack:void 0}function Kt(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 Wt(e){return"object"==typeof e&&null!==e&&"message"in e&&("response"in e||"request"in e||"config"in e)}function Ht(e,t){if(null==e||"object"!=typeof e)throw new Error(`${t}: No response - expected object, got ${typeof e}`);const n=e;if(!("Status"in n))throw new Error(`${t}: Response missing 'Status' property`);const s=n.Status;if("number"!=typeof s)throw new Error(`${t}: Response Status must be a number, got ${typeof s}`);if(1!==s)throw new Error(`${t}: Response status indicates failure (Status: ${s})`);return n}function jt(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 qt(e,t){return void 0!==t?t:e.charAt(0).toUpperCase()+e.slice(1)}function Vt(e,t){return new Ot(`Token "${e}" not found. Please verify the token name is correct.`,"tokenName","TOKEN_NOT_FOUND")}function zt(e,t){const n=qt(e,t);return new Ot(`${n} is required`,e,"REQUIRED")}function Qt(e,t,n){const s=qt(e,n);return new Ot(`${s} must be ${t}`,e,"INVALID_FORMAT")}function Xt(e,t,n,s){return new Lt(e,t,n,s)}function Jt(e,t){return new xt(e,t)}function Yt(e,t,n){return new Pt(e,t,n)}function Zt(e,t,n,s,r){const i=qt(e,r);return new Ot(`${i} must be between ${t} and ${n}${void 0!==s?`, received: ${s}`:""}`,e,"OUT_OF_RANGE")}function en(e,t,n,s){const r=qt(e,s);return new Ot(`${r} must be at least ${t}${void 0!==n?`, received: ${n}`:""}`,e,"TOO_SMALL")}function tn(e,t,n,s){const r=qt(e,s);return new Ot(`${r} must be at most ${t}${void 0!==n?`, received: ${n}`:""}`,e,"TOO_LARGE")}function nn(e,t,n,s){const r=qt(e,s),i=void 0!==n?`, received: ${"object"==typeof n?"object":String(n)}`:"";return new Ot(`${r} must be ${t}${i}`,e,"INVALID_TYPE")}function sn(e,t,n){const s=qt(e,n);return new Ot(`${s} must be a valid number${void 0!==t?`: "${t}"`:""}`,e,"INVALID_NUMBER")}function rn(e,t,n,s){const r=qt(e,s);return new Ot(`Invalid ${r}: ${t}. Must be one of: ${n.join(", ")}`,e,"INVALID_ENUM")}function an(e){return null!=e&&"object"==typeof e&&"data"in e}function on(e,t,n=!1){const s=!0===e.error,r=n&&(null===e.data||void 0===e.data);if(s||r){const n=e?.statusCode??e.status??void 0;throw Xt(e?.message??t,n,void 0,s?Ut(e):void 0)}}function cn(e){if(an(e))return e.data}function ln(e,t="No data found in response"){if(!an(e))throw Xt(t);const n=e.data;if(null==n)throw Xt(t);return n}async function dn(e,t={}){return gn(e,t,e=>{if(void 0===e.data)throw new Ot(`${t.errorContext??"Operation failed"}: No data returned from API`,"data","NO_DATA");return e.data})}async function un(e,t={}){const{errorContext:n="Operation failed",logger:s,debugLogEnabled:r=!1}=t;r&&s&&s.debug(`${n}: starting operation`);try{const t=await e();return r&&s&&s.debug(`${n}: completed successfully`),t}catch(e){throw s&&s.error(n,{error:e}),e}}async function hn(e,t={}){return gn(e,t,e=>e)}async function gn(e,t,n){const{errorContext:s="Operation failed",logger:r,debugLogEnabled:i=!1}=t;i&&r&&r.debug(`${s}: starting operation`);try{const t=await e();if(null==t)throw new Ot(`${s}: No response from server`,"response","NO_RESPONSE");return on(t,s,!0),i&&r&&r.debug(`${s}: completed successfully`),n(t)}catch(e){throw r&&r.error(s,{error:e}),e}}const mn={BASE_PRICE:1650667151e-14,PRICE_SCALING_FACTOR:1166069e-12,TRADING_FEE_FACTOR:.001,GAS_FEE:"1",DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY:1e7};function fn(e){return e.trim().toLowerCase()}function pn(e){return e.trim().toUpperCase()}var vn;!function(e){e.DEBUG="DEBUG",e.INFO="INFO",e.WARN="WARN",e.ERROR="ERROR"}(vn||(vn={}));class An{constructor(e){this.levelPriority={[vn.DEBUG]:0,[vn.INFO]:1,[vn.WARN]:2,[vn.ERROR]:3},this.debugEnabled=e.debug,this.context=e.context??"SDK",this.minLevel=e.minLevel??(e.debug?vn.DEBUG:vn.INFO)}debug(e,t){this.log(vn.DEBUG,e,t)}info(e,t){this.log(vn.INFO,e,t)}warn(e,t){this.log(vn.WARN,e,t)}error(e,t){this.log(vn.ERROR,e,t)}log(e,t,n){if(this.levelPriority[e]<this.levelPriority[this.minLevel])return;if(e===vn.DEBUG&&!this.debugEnabled)return;const s=`[${(new Date).toISOString()}] [${this.context}] [${e}]`,r=this.getConsoleMethod(e);void 0!==n?Bt(n)?r(`${s} ${t}`,n.message,Gt(n)??""):r(`${s} ${t}`,n):r(`${s} ${t}`)}getConsoleMethod(e){switch(e){case vn.DEBUG:return console.debug;case vn.INFO:return console.info;case vn.WARN:return console.warn;case vn.ERROR:return console.error;default:return console.log}}child(e){return new An({debug:this.debugEnabled,context:`${this.context}:${e}`,minLevel:this.minLevel})}isDebugEnabled(){return this.debugEnabled&&this.levelPriority[vn.DEBUG]>=this.levelPriority[this.minLevel]}}function En(e){return"string"==typeof e&&e.trim().length>0}function yn(e){return null==e||""===e}function Tn(e){return null==e}const Sn=new An({debug:!1,context:"DateUtils"});function bn(e){if(null==e)return!1;if(e instanceof Date)return!isNaN(e.getTime());if("string"!=typeof e)return!1;const t=new Date(e);return!isNaN(t.getTime())}function kn(e,t){if("string"==typeof e&&/^eth\|0[xX]/u.test(e))try{a(e,t)}catch(e){if(o(e)&&"INVALID_ETH_USER_REF_PREFIX"===e.code)return e.message}}function wn(e,t="address"){const n=kn(e,t);if(void 0!==n)throw new Ot(n,t,"INVALID_FORMAT");try{return a(e,t)}catch{throw new Ot(`${t} 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(e)}")`,t,"INVALID_FORMAT")}}function Nn(e,t="address"){return wn(e,t).toLowerCase()}function In(e,t){return xn(e)??Nn(e,t)}function _n(e){return Dn(e)?Nn(e):e.trim().toLowerCase()}function Cn(e,t){const n=e=>Dn(e)?Nn(e):e.toLowerCase();return n(e)===n(t)}function Dn(e){try{return wn(e),!0}catch{return!1}}class Rn{toBackendFormat(e){if(!En(e))throw new Ot("Address is required and must be a string","address","REQUIRED");return wn(e,"address")}toEthereumFormat(e){if(!En(e))throw new Ot("Backend address is required and must be a string","address","REQUIRED");if(!e.match(/^eth\|([0-9a-fA-F]{40})$/i)){const t=kn(e,"address");if(void 0!==t)throw new Ot(t,"address","INVALID_FORMAT");throw new Ot(`Invalid backend address format. Expected "eth|{40-hex-characters}" (\`eth|0x...\` is not a valid form). Got: "${e}"`,"address","INVALID_FORMAT")}return`0x${e.substring(4)}`}normalizeInput(e){if(void 0!==e&&""!==e)return wn(e,"address")}normalizeForBackend(e){if(void 0!==e&&""!==e)return Nn(e,"address")}isValid(e){return Dn(e)}assertValid(e,t="address"){if(!this.isValid(e)){const n=kn(e,t);if(void 0!==n)throw new Ot(n,t,"INVALID_FORMAT");throw new Ot(`${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 En(e)&&Dn(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=Dn(e)?wn(e):void 0;if(void 0!==t&&t.startsWith("eth|"))return t.substring(4).toLowerCase();throw new Ot(`Cannot extract hex from address: "${e}". Expected Ethereum or backend format.`,"address","INVALID_FORMAT")}}const On=new Rn;function Mn(e){return On.toBackendFormat(e)}function Un(e){return On.isValid(e)}const Fn=/^(eth\|[a-f0-9]{40}|client\|[a-f0-9]{24})$/;function Ln(e){return void 0!==xn(e)}function xn(e){if(!En(e))return;const t=e.trim(),n=/^[0-9a-fA-F]{24}$/u.test(t)?`client|${t}`:t;if(!Dn(n))return;const s=Nn(n);return Fn.test(s)?s:void 0}function Pn(e,t){if(!Ln(e)){const n=kn(e,t);if(void 0!==n)throw new Ot(n,t,"INVALID_FORMAT");throw new Ot(`${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 Bn(e,t="address"){On.assertValid(e,t)}var $n=Object.freeze({__proto__:null,AddressFormatter:Rn,assertBackendUserAddress:Pn,assertValidWalletAddress:Bn,backendUserAddress:xn,backendUserParam:In,backendUserRef:Nn,ethZeroXRefusal:kn,isBackendUserAddress:Ln,isUserRef:Dn,isValidAddress:Un,normalizeAddressInput:function(e){return On.normalizeInput(e)},sameUserAddress:Cn,toBackendAddressFormat:Mn,userAddressFilter:_n,userRef:wn});function Gn(e,t=0){if(yn(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 Kn(e,t=0){if(Tn(e))return t;if("number"==typeof e)return isNaN(e)?t:e;return Gn(String(e).replace("%","").trim(),t)}function Wn(e,t=18){const n=Gn(e,0);if(0===n)return"0";return n.toFixed(t).replace(/\.?0+$/,"")}function Hn(e){return Wn(e,8)}function jn(e){return Wn(e,18)}function qn(e,t,n,s){if("number"!=typeof e)throw nn(s,"a number",e,s);if(e<t||e>n)throw Zt(s,t,n,e)}function Vn(e,t,n){if("string"!=typeof e)throw nn(n,"a string",e,n);if(e.length>t)throw tn(n,t,e.length)}function zn(e,t){if("number"!=typeof e)throw nn(t,"a number",e,t);if(!Number.isInteger(e))throw nn(t,"an integer",e,t);if(e<=0)throw en(t,1,e,t)}function Qn(e,t,n=!1){if("string"!=typeof e)throw nn(t,"a string",e,t);if(!n&&0===e.trim().length)throw zt(t,`${t} (non-empty string)`)}const Xn={ETH_ADDRESS:/^0x[0-9a-fA-F]{40}$/,BACKEND_ADDRESS:/^eth\|[0-9a-fA-F]{40}$/},Jn=En,Yn=Tn;function Zn(e,t,n=100,s,r){if(void 0!==r&&"string"!=typeof r)throw new Ot("cursor must be a string","cursor",wt);const i=s??t,a=void 0!==s?"pageSize":"limit";if(void 0!==i&&(zn(i,a),i>n))throw new Ot(`${a} must be at most ${n}`,a,Ct)}function es(e){const t=Object.values(e);return e=>"string"==typeof e&&t.includes(e)}function ts(e){return Object.values(e)}function ns(e,t,n){if(!Jn(e))throw zt(t);const s=e.trim();if(0===s.length)throw zt(t);if(s.length<n.MIN_LENGTH)throw Zt(t,n.MIN_LENGTH,n.MAX_LENGTH,s.length,`${t} length`);if(s.length>n.MAX_LENGTH)throw Zt(t,n.MIN_LENGTH,n.MAX_LENGTH,s.length,`${t} length`);if(!n.PATTERN.test(s))throw new Ot(`${t} must be ${n.DESCRIPTION}`,t,It)}function ss(e,t,n){if(null==e)throw zt(t,t);if("string"!=typeof e)throw nn(t,"a string",e);const s=e.trim();if(0===s.length)throw zt(t,t);if(!n.PATTERN.test(s))throw new Ot(`${t} must be ${n.DESCRIPTION}`,t,It)}function rs(e){return""===e||0===e.trim().length}function is(e,t,n){if(!Yn(e)){if("string"!=typeof e)throw nn(t,"a string",e,t);if(e.length>n)throw new Ot(`${t} must be at most ${n} characters`,t,Ct)}}function as(e,t){Yn(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 nn(t,"a date",e,t);if(isNaN(n.getTime()))throw new Ot(`${t} must be a valid date`,t,It)}(e,t)}function os(e,t,n){try{zn(e,t)}catch{throw function(e,t,n,s="OPERATION_FAILED"){return new Ot(`${e} failed: ${t}`,n,s)}(n,"must be a positive integer",t)}}function cs(e,t,n="status"){void 0!==e&&function(e,t,n){const s=Object.values(t);if(!s.includes(e))throw new Ot(`${n} must be one of: ${s.join(", ")}`,n,It)}(e,t,n)}class ls{constructor(e,t=!1,n){this.http=e,this.logger=new An({debug:t,context:this.constructor.name}),this.jwtAuth=n}setJwtAuth(e){this.jwtAuth=e}getJwtHeaders(){if(!this.jwtAuth){const e=globalThis;if("test"===e.process?.env?.NODE_ENV&&!this.isCalledFromUserCode())return{};throw new xt("JWT authentication required. Call sdk.login() first.")}return this.jwtAuth.getJwtHeaders()}isCalledFromUserCode(){const e=Gt(new Error)??"";return!(!e.includes("expect")&&!e.includes("jest"))||!(!e.includes("tests/")&&!e.includes(".test.ts"))}validatePositiveInteger(e,t,n){os(e,t,n)}}class ds{constructor(e=!1,t){this.logger=t||new An({debug:e,context:this.constructor.name})}}class us extends ds{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 hs extends us{constructor(e=!1){super(e)}normalizeKey(e){return fn(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>=hs.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??mn.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY.toString()}has(e){const t=this.normalizeKey(e);return this.cache.has(t)}clear(e){if(void 0!==e&&""!==e){const t=this.normalizeKey(e);this.cache.delete(t)}else super.clear()}dumpAsObject(){const e={};return this.cache.forEach((t,n)=>{e[n]=t}),e}getStats(){const e=this.buildBaseStats(),{cacheSize:t,oldestEntry:n}=this.calculateCacheSizeAndAge();return{...e,totalTokens:e.totalItems,cacheSize:t,oldestEntry:n}}calculateCacheSizeAndAge(){let e=Date.now(),t=0;return this.cache.forEach((n,s)=>{n.lastUpdated<e&&(e=n.lastUpdated);let r=0;r+=2*s.length,void 0!==n.reverseBondingCurveMinFeeFactor&&(r+=8),void 0!==n.reverseBondingCurveMaxFeeFactor&&(r+=8),void 0!==n.reverseBondingCurveNetFeeFactor&&(r+=8),r+=8,void 0!==n.vaultAddress&&""!==n.vaultAddress&&(r+=2*n.vaultAddress.length),void 0!==n.maxSupply&&""!==n.maxSupply&&(r+=2*n.maxSupply.length),void 0!==n.symbol&&""!==n.symbol&&(r+=2*n.symbol.length),r+=32,t+=r}),{cacheSize:t,oldestEntry:this.cache.size>0?e:0}}getByTokenId(e){const t=`token:${fn(e)}`;return this.cache.get(t)??null}setByTokenId(e,t){const n=`token:${fn(e)}`;this.updateCacheEntry(n,t)}hasByTokenId(e){const t=`token:${fn(e)}`;return this.cache.has(t)}}hs.MAX_CACHE_SIZE=1e4;const gs={MIN_LENGTH:1,MAX_LENGTH:25,PATTERN:/^[a-zA-Z0-9]{1,25}$/,DESCRIPTION:"1-25 letters and digits"},ms={MIN_LENGTH:1,MAX_LENGTH:255,PATTERN:/^[a-zA-Z0-9]{1,255}$/,DESCRIPTION:"1-255 letters and digits"},fs={MIN_LENGTH:1,MAX_LENGTH:50,PATTERN:/^[\s\S]{1,50}$/,DESCRIPTION:"1-50 characters"},ps={MIN_LENGTH:1,MAX_LENGTH:100,PATTERN:/^(?![\s\S]*<[^>]*>)[\s\S]{1,100}$/,DESCRIPTION:"1-100 characters without HTML"},vs=100,As=100,Es=50,ys=100,Ts={COMMENTS_V1:{MAX_LENGTH:2e3},CHAT_MESSAGES_V1:{MAX_LENGTH:500},BAN_REASON:{MAX_LENGTH:500},DESCRIPTION:{MAX_LENGTH:255},FLAG_DETAILS:{MAX_LENGTH:1e3},CONTENT_ID:{MAX_LENGTH:100}},Ss={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})$/}},bs=60,ks=31536e3,ws={MAX_LENGTH:64,PATTERN:/^(galaswap-operation-|galaconnect-operation-)/},Ns=64,Is=1,_s=100,Cs={FULL_NAME:{MIN_LENGTH:2,MAX_LENGTH:20,ALPHABETS_ONLY_PATTERN:/^[a-zA-Z]+(?: [a-zA-Z]+)?$/}},Ds=e.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"),Rs=Ds.max(25,"Token name must be at most 25 characters"),Os=e.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"),Ms=e.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"),Us=e.string({message:"Token description is required"}).min(1,"Token description is required").max(500,"Token description must be at most 500 characters"),Fs=e.string().min(1,"Token name must be at least 1 character").max(50,"Token name must be at most 50 characters"),Ls=e.string().min(1,"Search query must be at least 1 character").max(100,"Search query must be at most 100 characters"),xs=e.string().min(1,"Full name is required").max(100,"Full name must be at most 100 characters").regex(/^[a-zA-Z\s]+$/,"Full name can only contain letters and spaces");e.string().regex(Xn.BACKEND_ADDRESS,"Address must be in format: eth|[40-hex-chars]"),e.string().regex(Xn.ETH_ADDRESS,"Invalid Ethereum address format");const Ps=e.string().refine(e=>Dn(e),{error:e=>kn(e.input,"address")??"Address must be eth|[40-hex], 0x[40-hex], [40-hex] or client|[identifier] (a mixed-case address must carry its EIP-55 checksum)"}).transform(e=>wn(e)),Bs=e.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"),$s=e.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>Gn(e,0)>0,"Amount must be greater than zero"),Gs=e.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>Gn(e,0)>=0,"Amount must be zero or greater");e.string().url("Must be a valid URL").regex(/^https?:\/\//,"URL must start with http:// or https://");const Ks=e.string().optional().refine(e=>void 0===e||""===e||/^https?:\/\/.+\..+/.test(e),"Must be a valid URL if provided");function Ws(t=100){return e.number().int("Limit must be an integer").min(1,"Limit must be at least 1").max(t,`Limit must be at most ${t}`).default(10)}e.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),Ws(100),Ws(20),Ws(20);const Hs=e.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"),js=e.string().max(255,"Filename must be at most 255 characters"),qs=e.enum(["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"]);e.string().datetime("Must be a valid ISO 8601 date string"),e.number().int("Timestamp must be an integer").min(0,"Timestamp must be non-negative");const Vs=e.string().regex(/^0x[a-fA-F0-9]{64}$/,"Private key must be format: 0x + 64 hex characters");e.string().regex(/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/,"Transaction ID must be in UUID format"),e.string().regex(/^galaconnect-operation-[a-z0-9-]+$/,"Unique key must be format: galaconnect-operation-{unique-id}");const zs=[".png",".jpg",".jpeg",".gif",".webp",".svg"];e.object({file:e.union([e.instanceof(File),e.instanceof(Buffer)]),name:js,size:Hs,type:qs});const Qs=e.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"),Xs=e.instanceof(Buffer).refine(e=>e.length>=1&&e.length<=10485760,"Buffer size must be between 1 byte and 10MB");e.union([Qs,Xs]),e.enum([".png",".jpg",".jpeg",".gif",".webp",".svg"]),js.refine(e=>{const t=e.slice(e.lastIndexOf(".")).toLowerCase();return zs.includes(t)},`Filename must end with one of: ${zs.join(", ")}`),e.object({websiteUrl:Ks,telegramUrl:Ks,twitterUrl:Ks,instagramUrl:Ks,facebookUrl:Ks,redditUrl:Ks,tiktokUrl:Ks}).refine(e=>void 0!==e.websiteUrl||void 0!==e.telegramUrl||void 0!==e.twitterUrl||void 0!==e.instagramUrl||void 0!==e.facebookUrl||void 0!==e.redditUrl||void 0!==e.tiktokUrl,"At least one social URL (website, telegram, twitter, instagram, facebook, reddit, or tiktok) is required");const Js=e.string().min(1,"Token category must not be empty").default("Unit"),Ys=e.string().min(1,"Token collection must not be empty").default("Token"),Zs=e.object({minFeePortion:e.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal string").refine(e=>Gn(e,0)>=.1,"Minimum fee must be >= 0.1").refine(e=>Gn(e,0)<=.5,"Minimum fee must be <= 0.5").default("0.1"),maxFeePortion:e.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal string").refine(e=>Gn(e,0)>=.1,"Maximum fee must be >= 0.1").refine(e=>Gn(e,0)<=.5,"Maximum fee must be <= 0.5").default("0.5")}).refine(e=>Gn(e.maxFeePortion,0)>=Gn(e.minFeePortion,0),{message:"Maximum fee must be >= minimum fee",path:["maxFeePortion"]}),er=e.object({tokenName:Ds,tokenSymbol:Ms,tokenDescription:Us,tokenImage:e.union([e.instanceof(File),e.instanceof(Buffer),e.string().url("Token image must be a valid URL")]).optional(),preBuyQuantity:Gs.default("0"),websiteUrl:Ks,telegramUrl:Ks,twitterUrl:Ks,instagramUrl:Ks,facebookUrl:Ks,redditUrl:Ks,tiktokUrl:Ks,tokenCategory:Js,tokenCollection:Ys,reverseBondingCurveConfiguration:Zs.optional(),saleStartTime:e.number().int().positive().optional(),privateKey:Vs.optional()});e.object({file:e.union([e.instanceof(File),e.instanceof(Buffer)]),tokenName:Ds}),e.enum(Tt);const tr=e.object({tokenName:Os.optional(),symbol:Ms.optional()}).refine(e=>void 0!==e.tokenName||void 0!==e.symbol,"At least one of tokenName or symbol is required");e.enum(["NATIVE","MEME"]),e.enum(["IN","OUT"]);const nr=e.object({from:e.number().int("From timestamp must be an integer").min(173e6,"From timestamp must be at least 173000000"),to:e.number().int("To timestamp must be an integer").min(173e6,"To timestamp must be at least 173000000"),resolution:e.number().int("Resolution must be an integer").min(1,"Resolution must be at least 1"),tokenName:Rs});e.object({tokenName:Rs,slippageToleranceFactor:e.number().min(0).max(1).optional(),maxAcceptableReverseBondingCurveFeeSlippageFactor:e.number().min(0).max(1).optional(),privateKey:Vs.optional()});const sr=e.object({offset:e.number().int().min(0).default(0),pageSize:e.number().int().min(1).max(100).default(10)}),rr=e.object({offset:e.number().int().min(0).default(0),pageSize:e.number().int().min(1).max(20).default(10)}),ir=e.object({offset:e.number().int().min(0).default(0),pageSize:e.number().int().min(1).max(20).default(10)});sr.extend({type:e.enum(["RECENT","POPULAR"]).optional(),tokenName:e.string().min(1).max(50).optional(),search:e.string().min(1).max(100).optional()}),rr.extend({tokenName:e.string().min(1).max(50).optional(),search:e.string().min(1).max(100).optional()}),ir.extend({tradeType:e.enum(["BUY","SELL"]).optional(),tokenName:e.string().min(1).max(50).optional(),userAddress:e.string().refine(Dn,{error:e=>kn(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:e.string().datetime().optional(),endDate:e.string().datetime().optional(),sortOrder:e.enum(["ASC","DESC"]).default("DESC")});const ar={page:e.number().int().min(1),limit:e.number().int().min(1),total:e.number().int().min(0),totalPages:e.number().int().min(0),hasNext:e.boolean(),hasPrevious:e.boolean()};e.object(ar);const or=e.enum(["buy","sell"]);e.enum(["BUY","SELL"]),e.object({tradeType:or,tokenAmount:$s,vaultAddress:Bs,userAddress:Ps,slippageTolerance:$s.optional(),deadline:e.number().int().positive().optional()}),e.object({tokenSymbol:Ms,nativeTokenQuantity:$s,expectedToken:$s,maxAcceptableReverseBondingCurveFee:Gs.default("0").optional()}),e.object({tokenSymbol:Ms,tokenQuantity:$s,expectedNativeToken:$s,maxAcceptableReverseBondingCurveFee:Gs.default("0").optional()}),ir.extend({tokenName:Fs.optional()}),e.object({page:e.number().int().min(1).max(1e3).default(1).optional(),limit:e.number().int().min(1).max(20).default(10).optional()});const cr=e.enum(["NATIVE","MEME"]),lr=e.enum(["IN","OUT"]);e.object({type:cr,method:lr,vaultAddress:Bs,amount:$s}),e.object({nativeTokenQuantity:$s}),e.object({vaultAddress:Bs}),e.object({minFeePortion:$s,maxFeePortion:$s});const dr=e.enum(["both","held","created"]);function ur(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)}}}rr.extend({type:dr.optional(),address:Ps.optional(),search:Ls.optional(),tokenName:Fs.optional()}),e.object({address:Ps.optional(),refresh:e.boolean().optional()}),e.object({profileImage:e.string().nullable().optional(),fullName:xs.optional(),address:Ps.optional(),privateKey:Vs.optional()}),e.object({file:e.union([e.instanceof(File),e.instanceof(Buffer)]),address:Ps.optional(),privateKey:Vs.optional()}),e.object({address:Ps,tokenId:e.union([e.string(),e.object({collection:e.string(),category:e.string(),type:e.string(),additionalKey:e.string()}),e.object({collection:e.string(),category:e.string(),type:e.string(),additionalKey:e.string(),instance:e.string()})]).optional(),tokenName:Fs.optional(),withExpired:e.boolean().optional()}).refine(e=>void 0!==e.tokenId||void 0!==e.tokenName,"At least one token identifier (tokenId or tokenName) is required");const hr=ur(Ds),gr=ur(er),mr=ur(tr);function fr(e){const t=function(e){const t=gr(e);return t.success?[]:t.errors??["Unknown validation error"]}(e);if(t.length>0)throw new Error(`LaunchTokenData validation failed:\n${t.map(e=>`- ${e}`).join("\n")}`)}function pr(e,t){return"string"==typeof e[t]}function vr(e,t){return void 0===e[t]||"string"==typeof e[t]}function Ar(e,t){return void 0===e[t]||"number"==typeof e[t]}function Er(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}}es({BUY:"buy",SELL:"sell"});const yr=(Tr={nativeTokenQuantity:"string"},e=>{if(null==e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;for(const[e,n]of Object.entries(Tr))if(!Er(t[e],n))return!1;return!0});var Tr;function Sr(e,t="0"){return function(e,t="0"){if(yn(e))return new _(t);if(_.isBigNumber(e))return e.isNaN()?new _(t):e;try{const n=new _(e);return n.isNaN()||!n.isFinite()?new _(t):n}catch{return new _(t)}}(e,t)}function br(e,t){return void 0!==t?Sr(e).toFixed(t):Sr(e).toFixed()}function kr(e){return Sr(e).isZero()}function wr(e,t){return Sr(e).isLessThan(Sr(t))}function Nr(...e){e.forEach(e=>{if(e.isNaN())throw sn("value","NaN");if(!e.isFinite())throw tn("value","finite");if(e.isLessThanOrEqualTo(0))throw en("value","0",e.toString())})}function Ir(e,t,n="0"){const s=Sr(t);return kr(s)?Sr(n):Sr(e).dividedBy(s)}const _r={calculateBuyWithExact(e,t){const n=Gn(e),s=Gn(t),{BASE_PRICE:r,PRICE_SCALING_FACTOR:i,TRADING_FEE_FACTOR:a,GAS_FEE:o}=mn,c=function(e,t){const n=Math.pow(10,t);return Math.ceil(e*n)/n}(r*(Math.exp((s+n)*i)-Math.exp(s*i))/i,8),l=br(Sr(c).multipliedBy(a));return{amount:c.toString(),reverseBondingCurveFee:"0",transactionFee:l,gasFee:o}},calculateBuyWithNative(e,t){const n=Gn(e),s=Gn(t),{BASE_PRICE:r,PRICE_SCALING_FACTOR:i,TRADING_FEE_FACTOR:a,GAS_FEE:o}=mn,c=Math.log(n*i/r+Math.exp(s*i))/i-s,l=br(Sr(c).multipliedBy(a));return{amount:c.toString(),reverseBondingCurveFee:"0",transactionFee:l,gasFee:o}},calculateSellWithExact(e,t,n,s,r){const i=Gn(e),a=Gn(t),o=Gn(n),{BASE_PRICE:c,PRICE_SCALING_FACTOR:l,TRADING_FEE_FACTOR:d,GAS_FEE:u}=mn,h=c*(Math.exp(a*l)-Math.exp((a-i)*l))/l,g=Sr(h),m=s+a/o*(r-s),f=br(g.multipliedBy(m),8),p=br(g.multipliedBy(d));return{amount:h.toString(),reverseBondingCurveFee:f,transactionFee:p,gasFee:u}},calculateSellWithNative(e,t,n,s,r){const i=Gn(e),a=Gn(t),o=Gn(n),{BASE_PRICE:c,PRICE_SCALING_FACTOR:l,TRADING_FEE_FACTOR:d,GAS_FEE:u}=mn;if(i>=c*(Math.exp(a*l)-1)/l){const e=Sr(i),t=s+a/o*(r-s),n=br(e.multipliedBy(t),8),c=br(e.multipliedBy(d));return{amount:a.toString(),reverseBondingCurveFee:n,transactionFee:c,gasFee:u}}const h=a-Math.log(Math.exp(a*l)-i*l/c)/l,g=Sr(i),m=s+a/o*(r-s),f=br(g.multipliedBy(m),8),p=br(g.multipliedBy(d));return{amount:h.toString(),reverseBondingCurveFee:f,transactionFee:p,gasFee:u}}};function Cr(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Dr(e,t){if(!function(e){if(!Cr(e)||"string"!=typeof e.calculatedQuantity)return!1;const t=e.extraFees;return Cr(t)&&"string"==typeof t.reverseBondingCurve&&"string"==typeof t.transactionFees}(e))throw Xt(`Malformed trade quote from the launchpad backend (${t})`);return{amount:e.calculatedQuantity,reverseBondingCurveFee:e.extraFees.reverseBondingCurve,transactionFee:e.extraFees.transactionFees,gasFee:mn.GAS_FEE}}class Rr{validate(e,t={}){const{allowZero:n=!0,minimum:s,maximum:r,maxDecimals:i=Rr.MAX_DECIMAL_PLACES,fieldName:a="amount"}=t;if(!Jn(e))throw new Ot(`${a} cannot be empty or whitespace-only. Provide a valid numeric string.`,a,"INVALID_NUMERIC_STRING");if(/[eE]/.test(e))throw new Ot(`${a} cannot use scientific notation. Use standard decimal format (e.g., "1000" instead of "1e3").`,a,"INVALID_NUMERIC_STRING");const o=Gn(e,NaN);if(isNaN(o))throw new Ot(`${a} must be a valid numeric string. Received: "${e}"`,a,"INVALID_NUMERIC_STRING");if(!isFinite(o))throw new Ot(`${a} must be a finite number. Cannot be Infinity or -Infinity.`,a,"INVALID_NUMERIC_STRING");if(o<0)throw new Ot(`${a} must be non-negative. Received: "${e}"`,a,"INVALID_NUMERIC_STRING");if(!n&&0===o)throw new Ot(`${a} must be greater than zero. Received: "${e}"`,a,"INVALID_NUMERIC_STRING");const c=Sr(e),l=c.decimalPlaces()??0;if(l>i)throw new Ot(`${a} cannot exceed ${i} decimal places. Received: ${l} decimal places`,a,"PRECISION_EXCEEDED");if(void 0!==s&&wr(c,s))throw new Ot(`${a} must be at least ${s}. Received: "${e}"`,a,"BELOW_MINIMUM");if(void 0!==r&&(d=r,Sr(c).isGreaterThan(Sr(d))))throw new Ot(`${a} cannot exceed ${r}. Received: "${e}"`,a,"EXCEEDS_MAXIMUM");var d}parseAmount(e,t="0"){return Sr(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 br(e,t)}clampAmount(e,t,n){const s=Sr(e),r=Sr(t),i=Sr(n);return function(e,t,n){const s=Sr(e),r=Sr(t),i=Sr(n);return s.isGreaterThanOrEqualTo(r)&&s.isLessThanOrEqualTo(i)}(s,r,i)?br(s):wr(s,r)?br(r):br(i)}}function Or(e,t){throw new Ot(e.join("; "),t,"VALIDATION_ERROR")}function Mr(e){const t=hr(e);!t.success&&t.errors&&Or(t.errors,"tokenName")}function Ur(e){const t=nr.safeParse(e);var n;t.success||Or((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 Fr(e,t,n=!0){Lr.validate(e,{fieldName:t,allowZero:n})}Rr.MAX_DECIMAL_PLACES=18,Rr.MIN_POSITIVE="0.00000000000000001";const Lr=new Rr;class xr{constructor(e,t,n,s="local",r){this.http=e,this.logger=t,this.bundleHttp=n,this.defaultCalculateAmountMode=s,this.launchpadWrites=r,this.metadataCache=new hs}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 Qt("options","an options object");const{tokenName:t,amount:n,type:s,currentSupply:r}=e;return"external"===this.validateAmountCalculationInputs(t,n,s,e.mode,[Et,yt],'"native" or "exact"')?this.calculateBuyAmountExternal({tokenName:t,amount:n,type:s}):this.calculateBuyAmountLocal(this.addIfDefined({tokenName:t,amount:n,type:s},"currentSupply",r))}async calculateBuyAmountExternal(e){const{tokenName:t,amount:n,type:s}=e;return this.validateExternalAmountInputs(t,n),"exact"===s?this.fetchBackendQuote({tokenName:t,amount:n,type:"MEME",method:"OUT"},`Failed to calculate buy amount for ${t} (exact tokens)`):this.fetchBackendQuote({tokenName:t,amount:n,type:"NATIVE",method:"IN"},`Failed to calculate buy amount for ${t} (native/GALA budget)`)}async fetchBackendQuote(e,t){return Dr(await dn(()=>this.http.get(ut,{...e}),{errorContext:t}),t)}async calculateSellAmount(e){const{tokenName:t,amount:n,type:s,currentSupply:r,maxSupply:i,reverseBondingCurveMaxFeeFactor:a,reverseBondingCurveMinFeeFactor:o}=e;if("external"===this.validateAmountCalculationInputs(t,n,s,e.mode,[yt,Et],'"exact" or "native"'))return this.calculateSellAmountExternal({tokenName:t,amount:n,type:s});{const e={tokenName:t,amount:n,type:s,...void 0!==r&&{currentSupply:r},...void 0!==i&&{maxSupply:i},...void 0!==a&&{reverseBondingCurveMaxFeeFactor:a},...void 0!==o&&{reverseBondingCurveMinFeeFactor:o}};return this.calculateSellAmountLocal(e)}}async calculateSellAmountExternal(e){const{tokenName:t,amount:n,type:s}=e;return this.validateExternalAmountInputs(t,n),"exact"===s?this.fetchBackendQuote({tokenName:t,amount:n,type:"MEME",method:"IN"},`Failed to calculate sell amount for ${t} (exact tokens)`):this.fetchBackendQuote({tokenName:t,amount:n,type:"NATIVE",method:"OUT"},`Failed to calculate sell amount for ${t} (native/GALA target)`)}async calculateBuyAmountLocal(e){const{tokenName:t,amount:n,type:s,currentSupply:r}=e;if(!Jn(n))throw zt("amount","Amount");if(s!==Et&&s!==yt)throw nn("type",'"native" or "exact"',s);void 0!==r&&Fr(r,"currentSupply");const i=null==r||""===r;if(i&&(null==t||""===t))throw zt("tokenName","Token name (required when currentSupply is not provided)");null!=t&&""!==t&&Mr(t);let a=r;if(i){a=(await this.fetchPoolDetailsForCalculation(t)).currentSupply}return s===yt?_r.calculateBuyWithExact(n,a):_r.calculateBuyWithNative(n,a)}async calculateSellAmountLocal(e){const{tokenName:t,amount:n,type:s,currentSupply:r,maxSupply:i,reverseBondingCurveMaxFeeFactor:a,reverseBondingCurveMinFeeFactor:o}=e;if(!Jn(n))throw zt("amount","Amount");if(s!==yt&&s!==Et)throw nn("type",'"exact" or "native"',s);void 0!==r&&Fr(r,"currentSupply");const c=null==r||""===r||null==i||""===i||void 0===a||void 0===o;if(c&&(null==t||""===t))throw zt("tokenName","Token name (required when currentSupply, maxSupply, or fee factors are not provided)");null!=t&&""!==t&&Mr(t);let l=r,d=i,u=a,h=o;if(c&&null!=t&&""!==t){const e=this.metadataCache.getByName(t);d=d??this.metadataCache.getMaxSupply(t),u=u??e?.reverseBondingCurveMaxFeeFactor,h=h??e?.reverseBondingCurveMinFeeFactor,null!=l&&""!==l||(l=await this.fetchCurrentSupply(t));if(void 0===u||void 0===h){const e=await this.fetchPoolDetailsForCalculation(t);u=u??e.reverseBondingCurveMaxFeeFactor,h=h??e.reverseBondingCurveMinFeeFactor}}return s===yt?_r.calculateSellWithExact(n,l,d,h,u):_r.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 pr(t,"tokenName")&&function(e){return void 0===e.calculateAmountMode||"local"===e.calculateAmountMode||"external"===e.calculateAmountMode}(t)&&vr(t,"currentSupply")}(e))throw nn("options","CalculateBuyAmountForGraduationOptions or string (token name)",typeof e);const{tokenName:n,calculateAmountMode:s,currentSupply:r}=t;Mr(n);const i=await this.fetchSaleDetails(n),a=r??br(Sr(i.maxSupply).minus(i.sellingTokenQuantity)),o=i.sellingTokenQuantity;if("0"===o)throw zt("tokenName",`Token ${n} is already graduated (no tokens remaining in pool)`);const c={tokenName:n,amount:o,type:"exact",currentSupply:a,...void 0!==s&&{mode:s}};return{...await this.calculateBuyAmount(c),remainingTokens:o}}async launchToken(e){if(void 0!==this.launchpadWrites){return(await this.launchpadWrites.createSale(e)).bundleId}if(!this.bundleHttp)throw Jt("Bundle backend client not configured. LaunchToken requires bundleHttp client.","bundleHttp");fr(e);const t=void 0!==e.preBuyQuantity&&""!==e.preBuyQuantity?e.preBuyQuantity:"0",n=Gn(t);if(0===n&&"0"!==t)throw sn("preBuyQuantity",t,"Pre-buy quantity");if(n<0)throw sn("preBuyQuantity",t,"Pre-buy quantity");if(e.reverseBondingCurveConfiguration){const{minFeePortion:t,maxFeePortion:n}=e.reverseBondingCurveConfiguration;!function(e,t,n){const s="string"==typeof e?parseFloat(e):e,r="string"==typeof t?parseFloat(t):t;if(!isFinite(s))throw new Ot(`${n} minFee must be a valid finite number`,n,"INVALID_FEE_MINIMUM");if(!isFinite(r))throw new Ot(`${n} maxFee must be a valid finite number`,n,"INVALID_FEE_MAXIMUM");if(s<.1)throw new Ot(`${n} minFee must be >= 0.1, received ${s}`,n,"INVALID_FEE_MINIMUM");if(r>.5)throw new Ot(`${n} maxFee must be <= 0.5, received ${r}`,n,"INVALID_FEE_MAXIMUM");if(s>r)throw new Ot(`${n} minFee (${s}) must be <= maxFee (${r})`,n,"INVALID_FEE_RANGE")}(t,n,"reverseBondingCurve")}throw new Error("Legacy launchToken signing is unavailable; configure the v6 launchpad write transport.")}async calculateInitialBuyAmount(e){if(!yr(e))throw Qt("data","valid pre-mint calculation data");const t="Failed to calculate initial buy amount";return Dr(await dn(()=>this.http.get(ht,{amount:e.nativeTokenQuantity}),{errorContext:t}),t)}async fetchPoolDetailsForCalculation(e){const t=await this.fetchSaleDetails(e),n=br(Sr(t.maxSupply).minus(t.sellingTokenQuantity)),s=t.sellingTokenQuantity,r=t.maxSupply;let i=.5,a=.1;const o=t.reverseBondingCurveConfiguration;null!=o?.maxFeePortion&&(i=Kn(o.maxFeePortion,.5)),null!=o?.minFeePortion&&(a=Kn(o.minFeePortion,.1)),void 0===o&&this.logger.debug(`Pool details missing reverse bonding curve configuration for token ${e}, using defaults (min: 0.1, max: 0.5)`);const c=i-a;return this.metadataCache.set(e,{maxSupply:r,reverseBondingCurveMaxFeeFactor:i,reverseBondingCurveMinFeeFactor:a,reverseBondingCurveNetFeeFactor:c}),{currentSupply:n,remainingTokens:s,maxSupply:r,reverseBondingCurveMaxFeeFactor:i,reverseBondingCurveMinFeeFactor:a,reverseBondingCurveNetFeeFactor:c}}async fetchCurrentSupply(e){Mr(e);const t=await this.fetchSaleDetails(e),n=br(Sr(t.maxSupply).minus(t.sellingTokenQuantity)),s=t.maxSupply;return this.metadataCache.set(e,{maxSupply:s}),n}async fetchPoolDetails(e){Mr(e);const t=await this.fetchSaleDetails(e),{reverseBondingCurveConfiguration:n,...s}=t,r=n?.minFeePortion??"0",i=n?.maxFeePortion??"0";return{...s,reverseBondingCurveMinFeePortion:r,reverseBondingCurveMaxFeePortion:i,hasReverseBondingCurveFee:!kr(r)||!kr(i),isGraduated:"Finished"===t.saleStatus}}async fetchSaleDetails(e){return ns(e,"tokenName",gs),dn(()=>this.http.get(dt,{tokenName:e}),{errorContext:`Failed to fetch sale details for ${e}`})}validateAmountCalculationInputs(e,t,n,s,r,i){const a=s??this.defaultCalculateAmountMode;if("local"!==a&&"external"!==a)throw nn("mode",'"local" or "external"',a);if(!Jn(e))throw zt("tokenName","Token name");if(!Jn(t))throw zt("amount","Amount");if("string"!=typeof n||!r.includes(n))throw nn("type",i,n);return a}validateExternalAmountInputs(e,t){if("string"!=typeof e||""===e)throw new Ot("Token name must be a non-empty string","tokenName","INVALID_TOKEN_NAME");if("string"!=typeof t||""===t)throw new Ot("Amount must be a non-empty string","amount","INVALID_AMOUNT")}getAddress(){return this.http.getAddress()}formatAddressForBackend(e){return Mn(e)}validateTokenName(e){return Mr(e)}validatePagination(e){void 0!==e.pageSize&&Zn(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 Pr=3e5,Br="Sign in to Launchpad t:",$r="Authorization",Gr="Bearer ";class Kr{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 Wr;!function(e){e.WALLET_NOT_CONNECTED="WALLET_NOT_CONNECTED",e.SIGNATURE_FAILED="SIGNATURE_FAILED",e.INVALID_ADDRESS="INVALID_ADDRESS",e.MESSAGE_GENERATION_FAILED="MESSAGE_GENERATION_FAILED"}(Wr||(Wr={}));class Hr extends Error{constructor(e,t,n,s){super(t),this.type=e,this.originalError=n,this.statusCode=s,this.name="AuthError"}}class jr{constructor(e,t=Pr){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 Kr,this.refreshThresholdMs=t}setToken(e,t){if(!Jn(e))throw new Hr(Wr.SIGNATURE_FAILED,"JWT token must be a non-empty string");if("number"!=typeof t)throw new Hr(Wr.SIGNATURE_FAILED,"Token expiration must be a positive finite number (seconds)");if(!Number.isFinite(t))throw new Hr(Wr.SIGNATURE_FAILED,"Token expiration must be a positive finite number (seconds)");if(t<=0)throw new Hr(Wr.SIGNATURE_FAILED,"Token expiration must be a positive finite number (seconds)");const n=Date.now();this.tokenState={token:e.trim(),issuedAt:n,expiresAt:n+1e3*t},this.storage.set(this.STORAGE_KEYS.ACCESS_TOKEN,e.trim()),this.storage.set(this.STORAGE_KEYS.ACCESS_EXPIRES,String(this.tokenState.expiresAt))}async setTokens(e,t,n,s){if(this.setToken(e,t),n){const e=Date.now()+1e3*(s??7776e3);if(!this.tokenState)throw new Hr(Wr.SIGNATURE_FAILED,"Access token must be set before refresh token");this.tokenState.refreshToken=n.trim(),this.tokenState.refreshExpiresAt=e,await this.storage.set(this.STORAGE_KEYS.REFRESH_TOKEN,n.trim()),await this.storage.set(this.STORAGE_KEYS.REFRESH_EXPIRES,String(e))}}getToken(){return this.tokenState?.token??null}hasToken(){return null!==this.tokenState}isExpired(){return!this.tokenState||Date.now()>=this.tokenState.expiresAt}shouldRefresh(e){if(!this.tokenState)return!1;const t=e??this.refreshThresholdMs,n=this.tokenState.expiresAt-Date.now();return n>0&&n<=t}getTimeUntilExpiry(){if(!this.tokenState)return 0;const e=this.tokenState.expiresAt-Date.now();return Math.max(0,e)}getExpiresAt(){return this.tokenState?.expiresAt??null}getAuthorizationHeader(){const e=this.getToken();return null===e||""===e?null:`${Gr}${e}`}getJwtHeaders(){const e=this.getAuthorizationHeader();if(null===e||""===e)throw new Hr(Wr.WALLET_NOT_CONNECTED,"No JWT token available. Call login() first.");return{[$r]:e}}async getRefreshToken(){if(!this.tokenState?.refreshToken){const e=await this.storage.get(this.STORAGE_KEYS.REFRESH_TOKEN),t=await this.storage.get(this.STORAGE_KEYS.REFRESH_EXPIRES);if(e&&t){const n=Number(t);if(Number.isFinite(n)&&Date.now()<n)return e}return null}return null!==this.tokenState.refreshExpiresAt&&void 0!==this.tokenState.refreshExpiresAt&&(!Number.isFinite(this.tokenState.refreshExpiresAt)||Date.now()>=this.tokenState.refreshExpiresAt)?null:this.tokenState.refreshToken??null}async restoreFromStorage(){const e=await this.storage.get(this.STORAGE_KEYS.ACCESS_TOKEN),t=await this.storage.get(this.STORAGE_KEYS.ACCESS_EXPIRES);if(!e||!t)return!1;const n=Number(t);if(!Number.isFinite(n)||Date.now()>=n)return!1;const s=Date.now();this.tokenState={token:e,issuedAt:s,expiresAt:n};const r=await this.storage.get(this.STORAGE_KEYS.REFRESH_TOKEN),i=await this.storage.get(this.STORAGE_KEYS.REFRESH_EXPIRES);if(r&&i){const e=Number(i);Number.isFinite(e)&&Date.now()<e&&(this.tokenState.refreshToken=r,this.tokenState.refreshExpiresAt=e)}return!0}async clear(){this.tokenState=null,await this.storage.remove(this.STORAGE_KEYS.ACCESS_TOKEN),await this.storage.remove(this.STORAGE_KEYS.ACCESS_EXPIRES),await this.storage.remove(this.STORAGE_KEYS.REFRESH_TOKEN),await this.storage.remove(this.STORAGE_KEYS.REFRESH_EXPIRES)}isValid(){return this.hasToken()&&!this.isExpired()}getDebugInfo(){return{hasToken:this.hasToken(),isExpired:this.isExpired(),shouldRefresh:this.shouldRefresh(),timeUntilExpiryMs:this.getTimeUntilExpiry(),expiresAt:this.tokenState?new Date(this.tokenState.expiresAt):null}}}class qr extends jr{getJwtHeaders(){return{}}}async function Vr(e,t,n,s){try{return await e()}catch(e){throw s?(s(e,t,n),new Error("Unreachable after error handler")):(n&&n.error(`${t}:`,e),function(e,t,n){n&&n.error(`${t}:`,e);const s=(Wt(e)?e.response?.status:void 0)??(e instanceof Lt?e.statusCode:void 0);return Xt(`${t}: ${$t(e)}`,s,Bt(e)?e:void 0)}(e,t,n))}}function zr(e,t){return t instanceof Hr?t:new Hr(Wr.SIGNATURE_FAILED,`${e}: ${$t(t)}`,Bt(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 Qr{constructor(e,t,n,s=!1,r){this.http=e,this.signatureAuth=t,this.jwtAuth=n,this.session=r,this.refreshPromise=null,this.loginPromise=null,this.logger=new An({debug:s,context:"SessionAuthService"})}async loginWithSignature(e){const t=wn(e.address,"address");if(!Jn(e.message)||!Jn(e.signature))throw new Hr(Wr.SIGNATURE_FAILED,"A login needs the signed message and its signature.");const n={address:t,message:e.message,signature:e.signature,...void 0!==e.publicKey&&{publicKey:e.publicKey},...void 0!==this.session&&{cookieSession:!0}};return this.postLogin(n)}async loginWithDevBypass(e){return this.postLogin({address:wn(e,"address"),...void 0!==this.session&&{cookieSession:!0}})}async postLogin(e){try{const t=await this.http.request({method:"POST",url:Z,data:e,withSession:!1}),n=this.extractLoginData(t);return void 0===this.session&&await this.jwtAuth.setTokens(n.accessToken,n.expiresIn,n.refreshToken,n.refreshExpiresIn),n}catch(e){throw zr("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 Hr(Wr.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 Vr(async()=>{const e=Date.now(),t=`${Br}${e}`;this.logger.debug("Generating login signature",{message:t,timestamp:e});const n=await this.signatureAuth.signMessage(t),s=wn(this.signatureAuth.getAddress(),"address"),r={address:s,message:t,signature:n.signature};this.logger.debug("Sending login request",{address:s,message:t});const i=await this.http.post(Z,r),a=this.extractLoginData(i);return await this.jwtAuth.setTokens(a.accessToken,a.expiresIn,a.refreshToken,a.refreshExpiresIn),this.logger.debug("Login successful",{address:a.address,expiresIn:a.expiresIn,hasRefreshToken:!!a.refreshToken}),a},"SessionAuthService.performLogin",this.logger,e=>{if(e instanceof Hr)throw e;throw new Hr(Wr.SIGNATURE_FAILED,`Login failed: ${$t(e)}`,Bt(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 Hr(Wr.WALLET_NOT_CONNECTED,"No token to refresh. Call login() first.");this.refreshPromise=this.performRefresh();try{return await this.refreshPromise}finally{this.refreshPromise=null}}async performCookieRefresh(){try{const e=await this.http.request({method:"POST",url:te,data:{},withSession:!1});return this.extractLoginData(e)}catch(e){throw zr("Token refresh failed",e)}}async performRefresh(){return Vr(async()=>{this.logger.debug("Refreshing JWT token");const e=await this.jwtAuth.getRefreshToken();if(e){this.logger.debug("Using refresh token flow");const t=await this.http.post(te,{refreshToken:e}),n=this.extractLoginData(t);return await this.jwtAuth.setTokens(n.accessToken,n.expiresIn,n.refreshToken,n.refreshExpiresIn),this.logger.debug("Token refreshed successfully via refresh token",{address:n.address,expiresIn:n.expiresIn,hasNewRefreshToken:!!n.refreshToken}),n}this.logger.debug("Using legacy access token refresh");const t=await this.http.post(te,{},this.jwtAuth.getJwtHeaders()),n=this.extractLoginData(t);return this.jwtAuth.setToken(n.accessToken,n.expiresIn),this.logger.debug("Token refreshed successfully via access token",{address:n.address,expiresIn:n.expiresIn}),n},"SessionAuthService.performRefresh",this.logger,e=>{if(e instanceof Hr)throw e;throw new Hr(Wr.SIGNATURE_FAILED,`Token refresh failed: ${$t(e)}`,Bt(e)?e:void 0)})}async logout(e){this.logger.debug("Logging out",{allDevices:e?.allDevices});const t=e?.allDevices??!1;if(void 0!==this.session){const n=e?.accessToken??null;try{await this.http.request({method:"POST",url:ee,data:{allDevices:t},withSession:!1,...null!==n&&""!==n&&{headers:{Authorization:`${Gr}${n}`}}})}catch(e){throw zr("Logout failed",e)}return}if(t&&this.jwtAuth.hasToken()&&!this.jwtAuth.isExpired())try{await this.http.post(ee,{allDevices:!0},this.jwtAuth.getJwtHeaders()),this.logger.debug("Logged out from all devices")}catch(e){this.logger.warn(`Failed to revoke all-device sessions (server-side revocation may be incomplete): ${$t(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 Hr(Wr.WALLET_NOT_CONNECTED,"Not authenticated. Call login() first.");return Vr(async()=>{const e=await this.http.get(ne,void 0,this.jwtAuth.getJwtHeaders());return this.extractSessionData(e)},"SessionAuthService.getSession",this.logger,e=>{if(e instanceof Hr)throw e;throw new Hr(Wr.SIGNATURE_FAILED,`Failed to get session: ${$t(e)}`,Bt(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 Hr(Wr.WALLET_NOT_CONNECTED,"The app session has no access token.");return e}if(!this.jwtAuth.hasToken())throw new Hr(Wr.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: ${$t(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 Hr(Wr.SIGNATURE_FAILED,""!==$t(e)?$t(e):"Authentication failed");const t=ln(e,"No data in authentication response"),{accessToken:n,expiresIn:s,address:r,refreshToken:i,refreshExpiresIn:a}=t;if(!Jn(n))throw new Hr(Wr.SIGNATURE_FAILED,"Invalid access token in response");if("number"!=typeof s||s<=0)throw new Hr(Wr.SIGNATURE_FAILED,"Invalid expiration in response");return{accessToken:n,expiresIn:s,address:r,...void 0!==i&&{refreshToken:i},...void 0!==a&&{refreshExpiresIn:a}}}extractSessionData(e){if(e.error)throw new Hr(Wr.SIGNATURE_FAILED,""!==$t(e)?$t(e):"Failed to get session");return ln(e,"No data in session response")}}class Xr{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{Qn(e.messagePrefix,"messagePrefix",!1)}catch{throw new Hr(Wr.SIGNATURE_FAILED,"Message prefix cannot be empty")}}hasWallet(){return void 0!==this.walletProvider||void 0!==this.wallet}ensureWalletProvider(){if(this.wallet&&!this.walletProvider)try{this.walletProvider=S.fromWallet(this.wallet),this.cachedAddress=this.wallet.address,this.cachedGalaAddress=Mn(this.wallet.address)}catch(e){if(e instanceof Hr)throw e;if(e instanceof Ot&&("INVALID_ADDRESS"===e.code||"INVALID_FORMAT"===e.code||"address"===e.field))throw new Hr(Wr.INVALID_ADDRESS,e.message);if(null!==e&&"object"==typeof e&&"message"in e)throw new Hr(Wr.WALLET_NOT_CONNECTED,e.message);throw e}}setWallet(e){if(void 0!==e){if("object"!=typeof e||!("address"in e))throw new Hr(Wr.WALLET_NOT_CONNECTED,"Invalid wallet: must be an ethers Wallet instance or undefined");if("string"!=typeof e.address||""===e.address)throw new Hr(Wr.INVALID_ADDRESS,"Wallet address is not available");this.walletProvider=S.fromWallet(e),this.cachedAddress=e.address,this.cachedGalaAddress=Mn(e.address)}else this.walletProvider=void 0,this.cachedAddress=void 0,this.cachedGalaAddress=void 0;this.wallet=e}setWalletProvider(e){this.walletProvider=e,this.wallet=void 0;const n=void 0!==e&&b(e)?t(e.exportPrivateKey()):void 0;this.cachedAddress=n,this.cachedGalaAddress=void 0===n?void 0:Mn(n)}getWalletProvider(){return this.walletProvider}async cacheAddress(){this.walletProvider&&(this.cachedAddress=await this.walletProvider.getAddress(),this.cachedGalaAddress=wn(await this.walletProvider.getGalaAddress(),"address"))}async generateSignature(){await this.validateWalletAsync();try{const e=Date.now(),t=`${this.messagePrefix} ${e}`,n=await this.walletProvider.signMessage(t);return{message:t,signature:n,address:await this.walletProvider.getGalaAddress(),timestamp:e}}catch(e){if(e instanceof Hr)throw e;throw new Hr(Wr.SIGNATURE_FAILED,"Failed to generate signature for authentication",Bt(e)?e:new Error($t(e)))}}getAddress(){if(this.validateWallet(),this.cachedGalaAddress)return this.cachedGalaAddress;if(this.wallet)return this.formatAddress(this.wallet.address);throw new Hr(Wr.WALLET_NOT_CONNECTED,"Address not available. For external wallets, call cacheAddress() after connecting.")}async getAddressAsync(){return await this.validateWalletAsync(),wn(await this.walletProvider.getGalaAddress(),"address")}getEthereumAddress(){if(this.validateWallet(),this.cachedAddress)return this.cachedAddress;if(this.wallet)return this.wallet.address;throw new Hr(Wr.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 Hr(Wr.WALLET_NOT_CONNECTED,"Wallet private key not available for @gala-chain signing");return this.wallet.privateKey}if(void 0!==this.walletProvider&&b(this.walletProvider))return this.walletProvider.exportPrivateKey();throw new Hr(Wr.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 Hr(Wr.WALLET_NOT_CONNECTED,"Private key not available with this wallet provider");try{return await this.walletProvider.getPrivateKey()}catch(e){throw new Hr(Wr.WALLET_NOT_CONNECTED,"Private key not available. External wallet providers cannot access private keys. Use PrivateKeyProvider for @gala-chain signing operations.",Bt(e)?e:void 0)}}formatAddress(e){try{return Mn(e)}catch{throw new Hr(Wr.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 Hr)throw e;throw new Hr(Wr.SIGNATURE_FAILED,$t(e),Bt(e)?e:new Error($t(e)))}}async generateAuthHeaders(e,t){await this.validateWalletAsync();try{const n=Date.now(),s=`${this.messagePrefix} ${t.toUpperCase()} ${e} ${n}`,r=await this.walletProvider.signMessage(s);return{"x-signature":r,"x-address":await this.walletProvider.getGalaAddress(),"x-message":s,"x-timestamp":n.toString()}}catch(e){if(e instanceof Hr)throw e;throw new Hr(Wr.SIGNATURE_FAILED,"Failed to generate authentication headers",Bt(e)?e:new Error($t(e)))}}async signTypedData(e,t,n){await this.validateWalletAsync();try{const s={};for(const[e,n]of Object.entries(t))s[e]=n.map(e=>({name:e.name,type:e.type}));return await this.walletProvider.signTypedData(e,s,n)}catch(e){if(e instanceof Hr)throw e;throw new Hr(Wr.SIGNATURE_FAILED,"Failed to sign typed data",Bt(e)?e:new Error($t(e)))}}async generateCustomSignature(e){if(!Jn(e))throw new Hr(Wr.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 Hr)throw e;throw new Hr(Wr.SIGNATURE_FAILED,"Failed to generate custom message signature",Bt(e)?e:new Error($t(e)))}}validateWallet(){if(this.ensureWalletProvider(),!this.walletProvider)throw new Hr(Wr.WALLET_NOT_CONNECTED,"Wallet is required for authentication")}async validateWalletAsync(){if(this.ensureWalletProvider(),!this.walletProvider)throw new Hr(Wr.WALLET_NOT_CONNECTED,"Wallet is required for authentication");if(!this.walletProvider.isConnected())throw new Hr(Wr.WALLET_NOT_CONNECTED,"Wallet is not connected. Call connect() on the wallet provider first.")}}const Jr={prod:{...c.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:{...c.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 Yr(e){return Jr[e]}var Zr,ei;!function(e){e.PROCESSED="PROCESSED",e.COMPLETED="COMPLETED",e.SUCCESS="SUCCESS",e.FAILED="FAILED",e.ERROR="ERROR",e.PROCESSING="PROCESSING",e.PENDING="PENDING"}(Zr||(Zr={})),function(e){e.PENDING="pending",e.PROCESSING="processing",e.COMPLETED="completed",e.FAILED="failed",e.TIMEOUT="timeout"}(ei||(ei={}));const ti={[Zr.PROCESSED]:ei.COMPLETED,[Zr.COMPLETED]:ei.COMPLETED,[Zr.SUCCESS]:ei.COMPLETED,[Zr.FAILED]:ei.FAILED,[Zr.ERROR]:ei.FAILED,[Zr.PROCESSING]:ei.PROCESSING,[Zr.PENDING]:ei.PENDING},ni="9.0.0-rc.4",si={DEFAULT_LIMIT:10,BACKEND_MAX_PAGE_SIZE:20};function ri(e){return"string"==typeof e||null===e?e:void 0}function ii(e){if("object"!=typeof e||null===e)return{hasNextPage:!1};const t=Reflect.get(e,"hasNextPage"),n=Reflect.get(e,"hasPreviousPage"),s=ri(Reflect.get(e,"endCursor")),r=ri(Reflect.get(e,"startCursor"));return{hasNextPage:!0===t,...void 0===s?{}:{endCursor:s},..."boolean"==typeof n?{hasPreviousPage:n}:{},...void 0===r?{}:{startCursor:r}}}function ai(e,t){const{hasNextPage:n,endCursor:s}=e;if(n&&"string"==typeof s&&""!==s&&s!==t)return s}function oi(e){return"string"==typeof e?e:"number"==typeof e||"boolean"==typeof e||"bigint"==typeof e?String(e):JSON.stringify(e)??""}function ci(e,t){const n={};void 0!==e.cursor&&(n.cursor=e.cursor);const s=void 0!==e.pageSize?Math.min(e.pageSize,t):t;return n.pageSize=String(s),n}const li={tokenName:"lowercase",address:"lowercase",userAddress:"lowercase",assetId:"as given",targetId:"as given",id:"as given",code:"as given"};function di(e,t){let n=e;for(const[e,s]of Object.entries(t)){const t=li[e];if(void 0===t)throw new Error(`buildEndpoint: path parameter :${e} has no casing in PATH_PARAM_CASING`);n=n.replace(`:${e}`,encodeURIComponent("lowercase"===t?s.toLowerCase():s))}return n}function ui(e,t,n){for(const s of n){const n=t[s];null!=n&&""!==n&&(e[s]=oi(n))}return e}const hi="x-api-key";class gi extends ls{constructor(e,t,n,s=!1,r){super(e,s),this.adminApiKey=t??void 0,this.jwtAuth=n,this.userApiKey=r??void 0}setJwtAuth(e){this.jwtAuth=e}validateTokenName(e,t){!function(e,t){if(!Jn(e))throw zt("tokenName","Token name");const n=fn(e);if(!t.PATTERN.test(n))throw Qt("tokenName",t.DESCRIPTION,"Token name")}(e,t)}validateRequiredString(e,t,n){!function(e,t,n){if(!Jn(e))throw zt(t,n)}(e,t,n)}validateOptionalString(e,t,n,s){!function(e,t,n,s){if(null!=e){if("string"!=typeof e)throw nn(t,"string",typeof e,n);if(e.length>s)throw tn(t,s,e.length,n)}}(e,t,n,s)}validateOptionalNumber(e,t,n,s,r,i,a){!function(e,t,n,s,r){if(null!=e){if("number"!=typeof e)throw nn(t,"number",typeof e,n);if(e<s||e>r)throw Zt(t,s,r,e,n)}}(e,t,n,s,r)}validateOptionalDate(e,t,n){!function(e,t,n){if(null!=e&&!bn(e))throw Qt(t,"a valid ISO 8601 date string",n)}(e,t,n)}validatePositiveInteger(e,t,n){os(e,t,n)}validateStatusFilter(e,t,n="status"){cs(e,t,n)}buildPaginationParams(e,t){return ci(e,t)}addOptionalFilterParams(e,t,n){return ui(e,t,n)}buildEndpoint(e,t){return di(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 xt("Admin API key required for this operation. Set streamAdminApiKey in SDK config.");return{[hi]:this.adminApiKey}}getJwtHeaders(){if(!this.jwtAuth)throw new xt("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?{[hi]:this.userApiKey}:this.getJwtHeaders()}extractData(e){return on(e,"Backend request failed",!0),ln(e,"No data in backend response")}extractDataOrNull(e){return on(e,"Backend request failed",!1),e.data??null}async toggleFeature(e,t,n){this.validateTokenName(e,n);const s=this.buildEndpoint(t,{tokenName:e}),r=await this.http.post(s,{},this.getAdminHeaders()),i=this.extractData(r);return{enabled:i.enabled,tokenName:i.tokenName??fn(e)}}}class mi extends gi{constructor(e,t,n,s=!1,r){super(e,t,n,s,r)}async getSettings(){return{settings:(await this.http.get(ot.GET_SETTINGS,{},this.getDualAuthHeaders())).settings}}async updateSettings(e){const t={};void 0!==e.enabled&&(t.enabled=e.enabled),void 0!==e.mode&&(t.mode=e.mode),void 0!==e.provider&&(t.provider=e.provider);return{settings:(await this.http.post(ot.UPDATE_SETTINGS,t,this.getDualAuthHeaders())).settings}}async getModeration(e){this.validatePositiveInteger(e.flagId,"flagId","Flag ID");const t=ot.GET_MODERATION.replace(":flagId",String(e.flagId));return{moderation:(await this.http.get(t,{},this.getDualAuthHeaders())).analysis}}async triggerModeration(e){this.validatePositiveInteger(e.flagId,"flagId","Flag ID");const t=ot.TRIGGER_MODERATION.replace(":flagId",String(e.flagId)),n=await this.http.post(t,{},this.getDualAuthHeaders());return{queued:n.queued,message:n.message.length>0?n.message:"Moderation queued successfully"}}async getStatus(){return{status:(await this.http.get(ot.GET_STATUS,{},this.getDualAuthHeaders())).status}}}const fi=ts({MODERATOR:"MODERATOR",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MANAGER:"MANAGER",OWNER:"OWNER"});function pi(e){return fi.includes(e)}function vi(e,t,n=!1){const s=t.length;if(jt(t,()=>{is(e.description,"description",255)}),t.length>s&&(t[s]="Description must be 255 characters or less"),void 0!==e.tokenNames){const n=t.length;jt(t,()=>{if(!Array.isArray(e.tokenNames))throw nn("tokenNames","an array",e.tokenNames);if(!e.tokenNames.every(e=>"string"==typeof e))throw nn("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;jt(t,()=>{as(e.expiresAt,"expiresAt")}),t.length>n&&(t[n]="expiresAt must be a valid ISO 8601 date string")}}class Ai extends ls{constructor(e,t,n=!1){super(e,n,t)}extractData(e){let t;t="error"in e?e.error:"success"in e&&!e.success;const n={status:200,error:t,data:e.data};return void 0!==e.message&&(n.message=e.message),on(n,"API key operation failed",!0),e.data}validateApiKeyId(e){this.validatePositiveInteger(e,"id","API key ID")}async create(e){const t=function(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: ${fi.join(", ")}`),vi(e,t),t}(e);if(t.length>0)throw new Ot(t.join("; "),"options","VALIDATION_FAILED");this.logger.debug("Creating API key",{role:e.role,delegateAllTokens:e.delegateAllTokens});const n={role:e.role};void 0!==e.description&&(n.description=e.description),void 0!==e.delegateAllTokens&&(n.delegateAllTokens=e.delegateAllTokens),void 0!==e.tokenNames&&e.tokenNames.length>0&&(n.tokenNames=e.tokenNames),void 0!==e.expiresAt&&(n.expiresAt=e.expiresAt),void 0!==e.tokenPermissions&&(n.tokenPermissions=e.tokenPermissions);const s=await this.http.post(he.CREATE,n,this.getJwtHeaders()),r=this.extractData(s);return this.logger.debug("API key created",{id:r.id,keyPrefix:r.keyPrefix}),r}async findAll(e={}){!function(e){if(void 0!==e.pageSize&&("number"!=typeof e.pageSize||e.pageSize<1||e.pageSize>vs))throw nn("pageSize",`number between 1 and ${vs}`,typeof e.pageSize);if(void 0!==e.cursor&&("string"!=typeof e.cursor||""===e.cursor.trim()))throw nn("cursor","non-empty string",typeof e.cursor)}(e),this.logger.debug("Listing API keys",e);const t=ci(e,vs),n=await this.http.get(he.LIST,t,this.getJwtHeaders()),s=this.extractData(n);return this.logger.debug("Listed API keys",{count:s.apiKeys.length,total:s.pageInfo.totalCount}),s}async findOne(e){this.validateApiKeyId(e),this.logger.debug("Getting API key",{id:e});const t=he.GET.replace(":id",String(e)),n=await this.http.get(t,{},this.getJwtHeaders()),s=this.extractData(n);return this.logger.debug("Got API key",{id:s.id,keyPrefix:s.keyPrefix}),s}async update(e,t){this.validateApiKeyId(e);const n=function(e){const t=[];return["role","description","delegateAllTokens","tokenNames","expiresAt","tokenPermissions"].some(t=>void 0!==e[t])||t.push("At least one field must be provided for update"),void 0===e.role||pi(e.role)||t.push(`Invalid role. Must be one of: ${fi.join(", ")}`),vi(e,t,!0),t}(t);if(n.length>0)throw new Ot(n.join("; "),"options","VALIDATION_FAILED");this.logger.debug("Updating API key",{id:e,options:t});const s={};void 0!==t.role&&(s.role=t.role),void 0!==t.description&&(s.description=t.description),void 0!==t.delegateAllTokens&&(s.delegateAllTokens=t.delegateAllTokens),void 0!==t.tokenNames&&(s.tokenNames=t.tokenNames),void 0!==t.expiresAt&&(s.expiresAt=t.expiresAt),void 0!==t.tokenPermissions&&(s.tokenPermissions=t.tokenPermissions);const r=he.UPDATE.replace(":id",String(e)),i=await this.http.patch(r,s,this.getJwtHeaders()),a=this.extractData(i);return this.logger.debug("Updated API key",{id:a.id,keyPrefix:a.keyPrefix}),a}async revoke(e){this.validateApiKeyId(e),this.logger.debug("Revoking API key",{id:e});const t=he.REVOKE.replace(":id",String(e));await this.http.delete(t,{},this.getJwtHeaders()),this.logger.debug("API key revoked",{id:e})}getRoles(){return[...fi]}}const Ei={VIEWERS:"viewers",CHAT_PARTICIPANTS:"chat_participants"},yi=es(Ei);function Ti(e){if(!Jn(e.userAddress))throw zt("userAddress");if(!(null==(t=e.reason)||""===t||"string"==typeof t&&!rs(t)&&t.length<=Ts.BAN_REASON.MAX_LENGTH))throw new Ot(`reason must be at most ${Ts.BAN_REASON.MAX_LENGTH} characters`,"reason","TOO_LONG");var t,n;if(n=e.durationSeconds,!(Yn(n)||"number"==typeof n&&n>=bs&&n<=ks))throw new Ot(`durationSeconds must be between ${bs} and ${ks} seconds`,"durationSeconds","OUT_OF_RANGE")}class Si extends gi{constructor(e,t,n,s=!1,r){super(e,t,n,s,r)}async createBan(e){!function(e){ns(e.tokenName,"tokenName",ms),Ti(e)}(e);const t=this.buildEndpoint(se,{tokenName:e.tokenName}),n=bi(e),s=await this.http.post(t,n,this.getMultiAuthHeaders());return{ban:this.extractData(s),tokenName:fn(e.tokenName)}}async removeBan(e){!function(e){if(ns(e.tokenName,"tokenName",ms),!Jn(e.userAddress))throw zt("userAddress")}(e);const t=Nn(e.userAddress,"userAddress"),n=this.buildEndpoint(ae,{tokenName:e.tokenName,userAddress:t}),s=await this.http.delete(n,{},this.getMultiAuthHeaders()),r=this.extractDataOrNull(s);return{removed:r?.removed??!0,tokenName:fn(e.tokenName),userAddress:r?.userAddress??t}}async listBans(e){!function(e){ns(e.tokenName,"tokenName",ms),Zn(0,void 0,vs,e.pageSize)}(e);const t=this.buildEndpoint(re,{tokenName:e.tokenName}),n=this.buildPaginationParams(e,vs);this.addOptionalFilterParams(n,e,["search","name","userAddress"]),void 0!==n.userAddress&&(n.userAddress=_n(n.userAddress));const s=await this.http.get(t,n,this.getMultiAuthHeaders()),r=this.extractData(s);return{items:r.bans,pageInfo:r.pageInfo}}async getBanStatus(e){!function(e){if(ns(e.tokenName,"tokenName",ms),!Jn(e.userAddress))throw zt("userAddress")}(e);const t=Nn(e.userAddress,"userAddress"),n=this.buildEndpoint(ie,{tokenName:e.tokenName,userAddress:t}),s=await this.http.get(n,{},this.getMultiAuthHeaders()),r=this.extractDataOrNull(s);return{banned:null!==r,...null!==r&&{ban:r},tokenName:fn(e.tokenName),userAddress:t}}async getActiveUsers(e){!function(e){if(ns(e.tokenName,"tokenName",ms),void 0!==e.type&&!yi(e.type))throw new Ot(`type must be one of: ${Object.values(Ei).join(", ")}`,"type",Nt)}(e);const t=this.buildEndpoint(oe,{tokenName:e.tokenName}),n={};this.addOptionalFilterParams(n,e,["type","search","name","userAddress"]),void 0!==n.userAddress&&(n.userAddress=_n(n.userAddress));const s=await this.http.get(t,n,this.getMultiAuthHeaders());return this.extractData(s)}async createGlobalBan(e){!function(e){Ti(e)}(e);const t=bi(e),n=await this.http.post(ce,t,this.getDualAuthHeaders());return{ban:this.extractData(n)}}async removeGlobalBan(e){!function(e){if(!Jn(e.userAddress))throw zt("userAddress")}(e);const t=Nn(e.userAddress,"userAddress"),n=this.buildEndpoint(ue,{userAddress:t}),s=await this.http.delete(n,{},this.getDualAuthHeaders()),r=this.extractDataOrNull(s);return{removed:r?.removed??!0,userAddress:r?.userAddress??t}}async listGlobalBans(e){const t=e??{pageSize:20};!function(e){Zn(0,void 0,vs,e.pageSize)}(t);const n=this.buildPaginationParams(t,vs);this.addOptionalFilterParams(n,t,["search","name","userAddress"]),void 0!==n.userAddress&&(n.userAddress=_n(n.userAddress));const s=await this.http.get(le,n,this.getDualAuthHeaders()),r=this.extractData(s);return{items:r.bans,pageInfo:r.pageInfo}}async getGlobalBan(e){!function(e){if(!Jn(e.userAddress))throw zt("userAddress")}(e);const t=Nn(e.userAddress,"userAddress"),n=this.buildEndpoint(de,{userAddress:t}),s=await this.http.get(n,{},this.getDualAuthHeaders()),r=this.extractDataOrNull(s);return{banned:null!==r,...null!==r&&{ban:r},userAddress:t}}}function bi(e){const t={userAddress:Nn(e.userAddress,"userAddress")};return void 0!==e.reason&&(t.reason=e.reason),void 0!==e.durationSeconds&&(t.durationSeconds=e.durationSeconds),t}function ki(e){return{maxAcceptableReverseBondingCurveFee:Hn(e.maxAcceptableReverseBondingCurveFee)}}const wi={BuyNativeDto:class extends k{constructor(e,t,n="0",s={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=Hn(t),this.expectedToken=jn(n),this.extraFees=ki(s)}},BuyExactDto:class extends k{constructor(e,t,n,s={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=jn(t),this.expectedNativeToken=Hn(n),this.extraFees=ki(s)}},SellExactDto:class extends k{constructor(e,t,n="0",s={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=jn(t),this.expectedNativeToken=Hn(n),this.extraFees=ki(s)}},SellNativeDto:class extends k{constructor(e,t,n,s={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=Hn(t),this.expectedToken=jn(n),this.extraFees=ki(s)}}};function Ni(e,t,n){let s;qn(t,0,1,"slippageToleranceFactor");try{s=function(e,t){if(Tn(e)||""===e)throw zt(t);if(_.isBigNumber(e)){if(e.isNaN())throw sn(t,"NaN");return e}try{const n=new _(e);if(n.isNaN())throw sn(t,e);if(!n.isFinite())throw sn(t,e);return n}catch(n){if(n instanceof Ot)throw n;throw sn(t,e)}}(e,"expectedAmount")}catch{throw new Error(`Invalid expected amount: ${e}. Must be a valid number`)}if(0===t)return e;const r=s.multipliedBy(t);let i;switch(n){case"buy-native":case"sell-exact":i=s.minus(r);break;case"buy-exact":case"sell-native":i=s.plus(r);break;default:throw new Error(`Unknown operation type: ${n}`)}return Sr(i).isLessThan(0)&&(i=Sr(0)),br(i)}function Ii(e,t){if(!Jn(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 _i(e,t,n,s){const r=e?.split?.(t)??[],i=void 0!==n?` (${n})`:"";return new Ot(`Invalid ${"|"===t?"pipe":"dollar"}-delimited token: "${e}" (${r.length} parts)${i}. Expected format: "collection${t}category${t}type${t}additionalKey" (4 parts minimum). Received: [${r.map(e=>`"${e}"`).join(", ")}]. Error: ${$t(s)}`,"token",`INVALID_${"|"===t?"PIPE":"DOLLAR"}_DELIMITED_TOKEN`)}function Ci(e,t,n){try{const n=Ii(e,t),s=n[n.length-1],r=n[n.length-2],i=n[n.length-3],a=n.slice(0,n.length-3).join(t);if(void 0===a||void 0===i||void 0===r||void 0===s||""===s||""===a||""===i||""===r)throw new Error("All components (collection, category, type, additionalKey) must be non-empty");return{collection:a,category:i,type:r,additionalKey:s}}catch(s){throw _i(e,t,n,s)}}function Di(e){return function(e,t,n){try{const n=Ii(e,t),[s,r,i,...a]=n;if(""===s||""===r||""===i)throw new Error("Collection, category, and type must be non-empty");const o=a.join(t);if(void 0===s||void 0===r||void 0===i||""===o)throw new Error("AdditionalKey must be non-empty");return{collection:s,category:r,type:i,additionalKey:o}}catch(s){throw _i(e,t,n,s)}}(e,"|","pipe-delimited token")}class Ri 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 Oi={name:"GalaChain"},Mi={name:"ethereum",chainId:1};function Ui(e){if("string"!=typeof e)throw new Error("Wallet returned an invalid signature");return e}function Fi(e,t){const n=kn(e,t);if(void 0!==n)throw new Ri(n,"INVALID_SIGNER_OPTIONS",{details:{[t]:e}});return e}function Li(e){const t={};for(const[n,s]of Object.entries(e))void 0!==s&&(t[n]=xi(s));return t}function xi(e){return Array.isArray(e)?e.map(xi):"object"==typeof e&&null!==e?Li(e):e}function Pi(e,t,n,s){return{...e,signature:t,types:n,domain:s}}class Bi extends m{constructor(e){super(e),this.typedDataWallet=new i(e),this.walletAddress=`eth|${this.typedDataWallet.address.slice(2)}`}async signTypedData(e,t){const n=Li(t),s=d(e,n);return Pi(n,await this.typedDataWallet.signTypedData(Oi,s,n),s,Oi)}}class $i extends h{constructor(e,t={}){const{verifyActiveAccount:n,...s}=t;if(super(Fi(e,"walletAddress"),{...s,...void 0!==s.selectAddress&&{selectAddress:Fi(s.selectAddress,"selectAddress")}}),this.typedDataWallet=t.wallet,!0===n){const e=u(this.walletAddress)??(void 0===this.selectAddress?void 0:u(this.selectAddress));if(void 0===e)throw new Ri("verifyActiveAccount needs the Ethereum account of the key (walletAddress or selectAddress as 0x... / eth|...); a client| alias names no key.","INVALID_SIGNER_OPTIONS",{details:{walletAddress:this.walletAddress,selectAddress:this.selectAddress}});this.verifiedKey=e}else this.verifiedKey=void 0}async signTypedData(e,t){const n=Li(t),s=d(e,n),r={domain:Mi,types:s,message:n,Primary_type:e},i=this.typedDataWallet??function(){const e=globalThis.window,t=e?.gala;if(void 0===t)throw new Error("Gala wallet is not available");return t}();void 0!==this.verifiedKey&&await async function(e,t){let n="address"in e&&"string"==typeof e.address&&""!==e.address?e.address:void 0;if(void 0===n){const t=await e.request({method:"eth_accounts"}),s=Array.isArray(t)?t[0]:void 0;n="string"==typeof s&&""!==s?s:void 0}const s=void 0===n?void 0:u(n);if(void 0===s||s.toLowerCase()!==t.toLowerCase())throw new Ri("Your wallet's active account has changed. Please switch back to the connected account or reconnect your wallet.","WALLET_ACCOUNT_CHANGED",{details:{walletAccount:n??null,signerAccount:t}})}(i,this.verifiedKey);const a=await this.typedDataAccount(i);return Pi(n,Ui(await g(i,this.selectAddress??a,()=>i.request({method:"eth_signTypedData",params:[JSON.stringify(r),a]}))),s,Mi)}async typedDataAccount(e){if(s(this.walletAddress))return this.walletAddress;const t=await e.request({method:"eth_accounts"}),n=Array.isArray(t)?t[0]:void 0,r="string"==typeof n?n.replace(/^eth\|/,"0x"):"";if(!s(r))throw new Error("Gala Wallet did not report an Ethereum account to sign typed data with");return r}}class Gi extends l{constructor(e,t,n){super(e,Fi(t,"walletAddress"),n),this.typedDataProvider=e}async signTypedData(e,t){const r=Li(t),i=this.typedDataProvider,a=await i.getNetwork(),o={name:a.name,chainId:Number(a.chainId)},c=d(e,r),l=await i.getSigner(),u=n(await l.getAddress());if(s(this.walletAddress)&&u!==n(this.walletAddress))throw new Ri(`Wallet account ${u} is not the account this signer was created for (${this.walletAddress}); reconnect before signing.`,"WALLET_ACCOUNT_CHANGED",{details:{walletAccount:u,signerAccount:this.walletAddress}});return Pi(r,Ui(await l.signTypedData(o,c,r)),c,o)}static fromEip1193(e,t,n){const s=new r(e);return new Gi({request:t=>e.request(t),getNetwork:()=>s.getNetwork(),getSigner:()=>s.getSigner()},u(t)??t,n)}}function Ki(e){const[t,n]=e.split("|",2);if("service"!==t||void 0===n)throw new Error(`Invalid vaultAddress format (expected service|<collection>$<category>$<type>$<additionalKey>$launchpad): ${e}`);const s=n.split("$"),r=s[s.length-1],i=s.slice(0,-1),a=i.slice(0,-3).join("$"),[o,c,l]=i.slice(-3);if("launchpad"!==r||i.length<4||""===a||void 0===o||void 0===c||void 0===l||""===o||""===c||""===l)throw new Error(`Invalid vaultAddress format (expected service|<collection>$<category>$<type>$<additionalKey>$launchpad): ${e}`);return{collection:a,category:o,type:c,additionalKey:l}}function Wi(e){const{collection:t,category:n,type:s}=Ki(e),r=`${t}$${n}$${s}$none`,i="GALA$Unit$none$none";return[`$service$${r}$launchpad`,`$tokenBalance$${r}$${e}`,`$tokenBalance$${r}$${e}`,`$tokenBalance$${i}$${e}`,`$tokenBalance$${i}$${e}`]}function Hi(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 ji(e){return`${e.collection}|${e.category}|${e.type}|${e.additionalKey}`}function qi(e){if("string"==typeof e){if(!Jn(t=e)||!t.includes("|"))throw new Ot(`Invalid tokenId string format: "${e}". Expected pipe-delimited format: "collection|category|type|additionalKey" or "collection|category|type|additionalKey|instance"`,"tokenId","INVALID_TOKEN_ID_FORMAT");const n=e.split("|");if(n.length>=5){const e=Di(n.slice(0,4).join("|")),t=n[4]??"0";return{...e,instance:t.length>0?t:"0"}}return{...Di(e),instance:"0"}}var t;if("object"==typeof e&&null!==e){if("instance"in e&&void 0!==e.instance&&"string"==typeof e.instance&&e.instance.length>0){if(!f(e))throw new Ot("Invalid tokenId object format. All fields (collection, category, type, additionalKey) must be non-empty strings","tokenId","INVALID_TOKEN_ID_FORMAT");return e}if(!f(e))throw new Ot("Invalid tokenId object format. All fields (collection, category, type, additionalKey) are required","tokenId","INVALID_TOKEN_ID_FORMAT");return{...e,instance:"0"}}throw new Ot(`Invalid tokenId type: ${typeof e}. Expected string, TokenClassKey, or TokenInstanceKey`,"tokenId","INVALID_TOKEN_ID_TYPE")}function Vi(e){return function(e){try{if(!Jn(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 Ci((n.length>=5&&"launchpad"===n[n.length-1]?n.slice(0,-1):n).join("$"),"$","vault address")}catch(t){throw new Ot(`Invalid vault address: "${e}". Expected format: "service|Token$Unit$SYMBOL$additionalKey$launchpad". Error: ${$t(t)}`,"vaultAddress","INVALID_VAULT_ADDRESS_FORMAT")}}(e)}function zi(e){return{...Vi(e),instance:"0"}}function Qi(e){const t=Vi(e);if("Token"!==t.collection)throw new Ot(`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 Xi,Ji,Yi,Zi,ea=Object.freeze({__proto__:null,extractTokenSymbolFromVault:Qi,normalizeToTokenInstanceKey:qi,parseVaultAddressToTokenClassKey:Vi,parseVaultAddressToTokenInstance:zi});class ta extends ds{constructor(e=!1){super(e)}generateStringsInstructions(e){try{this.logger.debug("🔧 Generating stringsInstructions for:",e);const t=Wi(e);return this.logger.debug("✅ Generated stringsInstructions:",t),t}catch(e){this.logger.error("❌ Failed to generate stringsInstructions:",e);const t=$t(e);throw new Ot(`Failed to generate stringsInstructions: ${t}`,"vaultAddress","INVALID_VAULT_ADDRESS")}}createGalaInstance(){const e=new w;return e.collection="GALA",e.category="Unit",e.type="none",e.additionalKey="none",this.logger.debug("🟡 Created GALA instance:",{stringKey:e.toStringKey()}),e}extractTokenSymbolFromVault(e){if(!Jn(e))throw zt("vaultAddress","Vault address");try{const t=Qi(e);return this.logger.debug("🔍 Extracted token symbol:",{vaultAddress:e,tokenSymbol:t}),t}catch(e){if(e instanceof Ot)throw Qt("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad");throw e}}validateVaultAddress(e){if(!Jn(e))throw zt("vaultAddress","Vault address");if(!e.startsWith("service|Token$Unit$"))throw Qt("vaultAddress",'starting with "service|Token$Unit$"');if(!e.endsWith("$launchpad"))throw Qt("vaultAddress",'ending with "$launchpad"');const t=function(e){if(!Jn(e))return null;const t=e.match(/^service\|Token\$Unit\$([^$]+)\$eth:([a-fA-F0-9]{40})\$launchpad$/);if(!t)return null;const n=t[1],s=t[2];return void 0===n||void 0===s?null:{tokenSymbol:n,creatorAddress:s.toLowerCase()}}(e);if(!t)throw Qt("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 Qt("vaultAddress","containing a 1-10 letter token symbol (case insensitive)");return this.logger.debug("✅ Vault address validation passed:",e),!0}generateTokenClassKeyString(e,t,n,s){return`${e}$${t}$${n}$${s}`}parseTokenClassKeyString(e){try{return Ci(e,"$","dollar-delimited token")}catch(e){if(e instanceof Ot)throw Qt("stringKey","format: collection$category$type$additionalKey (4 parts)");throw e}}}function na(e){return"object"==typeof e&&null!==e?e:void 0}class sa extends ls{constructor(e,t,n=!1,s,r,i=.05,a=.01,o){if(super(e,n),this.tokenResolver=t,this._walletProvider=s,this.userAddress=r,this.defaultSlippageToleranceFactor=i,this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor=a,this.sellFeeCeiling=o,this.bundleEndpoint="/bundle",null!==this._walletProvider&&void 0!==this._walletProvider&&null!=r){const e=na(this._walletProvider),t=e?.privateKey;if("string"==typeof t)this.signer=new Bi(t);else if(function(e){const t=na(e);return"function"==typeof t?.request}(this._walletProvider)&&void 0!==this.userAddress){const e=wn(this.userAddress,"userAddress");this.signer=new Gi(this._walletProvider,u(e)??e)}this.tokenKeyService=new ta(n)}}async submitTransaction(e){try{this.validateBundleData(e),this.logger.debug("📦 Submitting bundle transaction:",{method:e.method,stringsInstructionsCount:e.stringsInstructions.length,signedDtoKeys:Object.keys(e.signedDto)});const t=this.formatBundleRequest(e);this.logger.debug("🚀 Bundle request payload:",{...t,signedDto:"[REDACTED - Contains signature]"});let n=null;try{n=await un(()=>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:an(n),error:n.error}),this.handleBundleResponse(n))}catch(e){if(e instanceof Ot)return{success:!1,error:$t(e)};throw e}}validateBundleData(e){if(null==e)throw zt("bundleData","Bundle data");if(null===e.signedDto||void 0===e.signedDto)throw zt("signedDto","Signed DTO");if(!Jn(e.method))throw zt("method","Method name");if(!Array.isArray(e.stringsInstructions))throw Qt("stringsInstructions","an array of resource tracking strings");if(0===e.stringsInstructions.length)throw new Ot("stringsInstructions cannot be empty","stringsInstructions","EMPTY_ARRAY");const t=["BuyWithNative","BuyExactToken","SellExactToken","SellWithNative"];if(!t.includes(e.method))throw Qt("method",`one of: ${t.join(", ")}`);e.stringsInstructions.forEach((e,t)=>{if(!Jn(e))throw new Ot(`stringsInstructions[${t}] must be a non-empty string`,`stringsInstructions[${t}]`,"INVALID_INSTRUCTION");if("string"!=typeof(n=e)||!n.includes("$"))throw new Ot(`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=cn(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(Wt(e)&&null!==e.response&&void 0!==e.response){const t=cn(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 $t(e)??"Unknown bundle transaction error"}async getBundlerTransactionResult(e){try{if(!Jn(e))throw zt("transactionId","Transaction ID");let t;this.logger.debug("🔍 Checking bundler transaction result:",e);try{t=await un(()=>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 Ot)return{success:!1,error:$t(e)};throw e}}async cancelTransaction(e){try{if(!Jn(e))throw zt("transactionId","Transaction ID");let t;this.logger.debug("🚫 Cancelling transaction:",e);try{t=await un(()=>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 Ot)return{success:!1,error:$t(e)};throw e}}async getHealthStatus(){this.logger.debug("🏥 Checking bundle service health");try{const e=await un(()=>this.http.get(`${this.bundleEndpoint}/health`),{errorContext:"Bundle service health check failed",logger:this.logger});return null==e?{success:!1,error:"No response from bundle service health check"}:(this.logger.debug("💚 Bundle service health:",e),{success:!0,data:e})}catch(e){return{success:!1,error:this.formatErrorMessage(e)}}}async buyToken(e){this.ensureTradingServicesAvailable();const{tokenName:t,amount:n,type:s,expectedAmount:r}=e,{effectiveSlippageFactor:i,effectiveMaxFee:a,vaultAddress:o}=await this.prepareTradingOperation(t,e.maxAcceptableReverseBondingCurveFee,e.maxAcceptableReverseBondingCurveFeeSlippageFactor,e.slippageToleranceFactor);if("native"===s){if(null==r||""===r)throw new Ot("expectedAmount is required for native buy operations. Use getBuyTokenAmount() first to calculate expected tokens.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Ni(r,i,"buy-native");this.logger.debug("BuyNative slippage applied:",{originalExpectedTokens:r,slippageFactor:i,adjustedMinTokens:e});const t=new wi.BuyNativeDto(o,n,e,{maxAcceptableReverseBondingCurveFee:a});return await this.executeBundleTransaction(t,"BuyWithNative",o)}{if(null==r||""===r)throw new Ot("expectedAmount is required for exact buy operations. Use getBuyTokenAmount() first to calculate expected GALA cost.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Ni(r,i,"buy-exact");this.logger.debug("BuyExact slippage applied:",{originalExpectedGalaCost:r,slippageFactor:i,adjustedMaxGalaCost:e});const t=new wi.BuyExactDto(o,n,e,{maxAcceptableReverseBondingCurveFee:a});return await this.executeBundleTransaction(t,"BuyExactToken",o)}}async sellToken(e){this.ensureTradingServicesAvailable();const{tokenName:t,amount:n,type:s,expectedAmount:r}=e,{effectiveSlippageFactor:i,effectiveMaxFee:a,vaultAddress:o}=await this.prepareTradingOperation(t,e.maxAcceptableReverseBondingCurveFee,e.maxAcceptableReverseBondingCurveFeeSlippageFactor,e.slippageToleranceFactor),c=async()=>void 0===e.maxAcceptableReverseBondingCurveFee?this.defaultSellFeeCeiling(e,o):a;if("exact"===s){if(null==r||""===r)throw new Ot("expectedAmount is required for exact sell operations. Use getSellTokenAmount() first to calculate expected GALA.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Ni(r,i,"sell-exact");this.logger.debug("SellExact slippage applied:",{originalExpectedGala:r,slippageFactor:i,adjustedMinGala:e});const t={maxAcceptableReverseBondingCurveFee:await c()},s=new wi.SellExactDto(o,n,e,t);return await this.executeBundleTransaction(s,"SellExactToken",o)}{if(null==r||""===r)throw new Ot("expectedAmount is required for native sell operations. Use getSellTokenAmount() first to calculate tokens to sell.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Ni(r,i,"sell-native");this.logger.debug("SellNative slippage applied:",{originalExpectedTokensToSell:r,slippageFactor:i,adjustedMaxTokensToSell:e});const t={maxAcceptableReverseBondingCurveFee:await c()},s=new wi.SellNativeDto(o,n,e,t);return await this.executeBundleTransaction(s,"SellWithNative",o)}}async prepareTradingOperation(e,t,n,s){const{effectiveSlippageFactor:r,effectiveMaxFee:i}=this.calculateEffectiveSlippage(t,n,s),a=await this.resolveTokenNameToVault(e);if(null==a)throw Vt(e);return{effectiveSlippageFactor:r,effectiveMaxFee:i,vaultAddress:a}}async defaultSellFeeCeiling(e,t){if(void 0===this.sellFeeCeiling)throw Jt("Cannot quote the reverse bonding curve fee for this sell. Pass maxAcceptableReverseBondingCurveFee.","maxAcceptableReverseBondingCurveFee");return this.sellFeeCeiling({method:"exact"===e.type?"SellExactToken":"SellWithNative",vaultAddress:t,quantity:e.amount,tokenName:e.tokenName,feeSlippageFactor:e.maxAcceptableReverseBondingCurveFeeSlippageFactor??this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor})}calculateEffectiveSlippage(e,t,n){const s=n??this.defaultSlippageToleranceFactor,r=t??this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor;let i=e??"0";return null!=e&&(i=Ni(e,r,"buy-exact"),this.logger.debug("Reverse bonding curve fee slippage applied:",{baseFee:e,slippageFactor:r,adjustedMaxFee:i})),{effectiveSlippageFactor:s,effectiveFeeSlippageFactor:r,effectiveMaxFee:i}}ensureTradingServicesAvailable(){if(!this.signer||!this.tokenKeyService)throw Jt("Trading services not available. BundleService requires walletProvider and userAddress for trading operations.","walletProvider");if(null===this.userAddress||void 0===this.userAddress)throw zt("userAddress","User address")}async executeBundleTransaction(e,t,n){this.ensureTradingServicesAvailable();try{e.uniqueKey=`galaswap-operation-${Date.now()}_${N().replace(/-/gu,"").substring(0,26)}`;const s=await this.signer.signObject(t,e),r=this.tokenKeyService.generateStringsInstructions(n),i={stringsInstructions:r,method:t,signedDto:s};this.logger.debug("📦 Bundle transaction data:",{method:t,stringsInstructions:r,dtoKeys:Object.keys(s)});const a=await this.submitTransaction(i);if(a.success){const e=cn(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 o=a.error;throw new Pt("string"==typeof o?o:"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 ra extends ls{constructor(e,t=!1){super(e,t)}extractData(e){if(e.error||void 0===e.data){const t=e.message??"Client config operation failed";throw new Error(t)}return e.data}async getClientFlags(){this.logger.debug("Fetching client feature flags");const e=await this.http.get(At),t=this.extractData(e);return this.logger.debug("Fetched client feature flags",{flagCount:Object.keys(t.flags).length}),{flags:t.flags}}}!function(e){e.CHAT_MESSAGE="CHAT_MESSAGE",e.COMMENT="COMMENT",e.STREAM="STREAM",e.RECORDING="RECORDING"}(Xi||(Xi={})),function(e){e.INAPPROPRIATE_CONTENT="INAPPROPRIATE_CONTENT",e.SPAM="SPAM",e.HARASSMENT="HARASSMENT",e.SCAM="SCAM",e.OTHER="OTHER"}(Ji||(Ji={})),function(e){e.PENDING="PENDING",e.DISMISSED="DISMISSED",e.ACTIONED="ACTIONED"}(Yi||(Yi={})),function(e){e.DELETE_CONTENT="DELETE_CONTENT",e.BAN_USER="BAN_USER",e.DELETE_AND_BAN="DELETE_AND_BAN"}(Zi||(Zi={})),Ji.INAPPROPRIATE_CONTENT,Ji.SPAM,Ji.HARASSMENT,Ji.SCAM,Ji.OTHER,Yi.PENDING,Yi.DISMISSED,Yi.ACTIONED,Zi.DELETE_CONTENT,Zi.BAN_USER,Zi.DELETE_AND_BAN,Xi.CHAT_MESSAGE,Xi.COMMENT,Xi.STREAM,Xi.RECORDING;const ia=es(Xi),aa=es(Ji),oa=es(Yi),ca=es(Zi),la={TOKEN_NAME:gs,TOKEN_NAME_FILTER:{MIN_LENGTH:1,MAX_LENGTH:50,PATTERN:/^[a-zA-Z0-9]{1,50}$/,DESCRIPTION:"1-50 letters and digits"},CONTENT_ID:Ts.CONTENT_ID,DETAILS:Ts.FLAG_DETAILS,PAGINATION:{MAX_LIMIT:vs}};function da(e,t,n="tokenName"){ns(e,n,t)}function ua(e){if(void 0!==e.contentType&&!ia(e.contentType))throw Qt("contentType",`one of: ${Object.values(Xi).join(", ")}`,"Content type");if(void 0!==e.status&&!oa(e.status))throw Qt("status",`one of: ${Object.values(Yi).join(", ")}`);if(void 0!==e.reason&&!aa(e.reason))throw Qt("reason",`one of: ${Object.values(Ji).join(", ")}`);if(void 0!==e.reporterAddress&&!Jn(e.reporterAddress))throw nn("reporterAddress","a non-empty string",typeof e.reporterAddress);if(void 0!==e.reporterAddress&&Pn(e.reporterAddress,"reporterAddress"),void 0!==e.reportedUserAddress&&!Jn(e.reportedUserAddress))throw nn("reportedUserAddress","a non-empty string",typeof e.reportedUserAddress);void 0!==e.reportedUserAddress&&Pn(e.reportedUserAddress,"reportedUserAddress"),Zn(0,void 0,la.PAGINATION.MAX_LIMIT,e.pageSize)}class ha extends gi{constructor(e,t,n,s=!1,r){super(e,t,n,s,r)}async createFlag(e){!function(e){if(da(e.tokenName,la.TOKEN_NAME),void 0===e.contentType)throw zt("contentType","Content type");if(!ia(e.contentType))throw Qt("contentType",`one of: ${Object.values(Xi).join(", ")}`,"Content type");if(!Jn(e.contentId))throw zt("contentId","Content ID");if(e.contentId.length>la.CONTENT_ID.MAX_LENGTH)throw tn("contentId",la.CONTENT_ID.MAX_LENGTH,e.contentId.length,"Content ID");if(!Jn(e.reportedUserAddress))throw zt("reportedUserAddress","Reported user address");if(Pn(e.reportedUserAddress,"reportedUserAddress"),!(e.contentType!==Xi.STREAM&&e.contentType!==Xi.RECORDING||void 0!==e.reason&&null!==e.reason))throw zt("reason","Reason");if(void 0!==e.reason&&!aa(e.reason))throw Qt("reason",`one of: ${Object.values(Ji).join(", ")}`,"Reason");if(void 0!==e.details&&!Jn(e.details))throw nn("details","a non-empty string",typeof e.details);if(void 0!==e.details&&e.details.length>la.DETAILS.MAX_LENGTH)throw tn("details",la.DETAILS.MAX_LENGTH,e.details.length)}(e);const t={tokenName:e.tokenName,contentType:e.contentType,contentId:e.contentId,reportedUserAddress:In(e.reportedUserAddress,"reportedUserAddress")};null!==e.reason&&void 0!==e.reason&&(t.reason=e.reason),null!==e.details&&void 0!==e.details&&(t.details=e.details);const n=await this.http.post(Te.CREATE,t,this.getMultiAuthHeaders());return{flag:this.extractData(n).flag}}async listFlags(e){return function(e){da(e.tokenName,la.TOKEN_NAME_FILTER),ua(e)}(e),this.fetchFlagList(e)}async listGlobalFlags(e={}){return function(e){void 0!==e.tokenName&&da(e.tokenName,la.TOKEN_NAME_FILTER),ua(e)}(e),this.fetchFlagList(e)}async dismissFlag(e){!function(e){if(void 0===e.flagId||null===e.flagId)throw zt("flagId","Flag ID");try{zn(e.flagId,"flagId")}catch{throw Qt("flagId","a positive integer","Flag ID")}}(e);const t=Te.DISMISS.replace(":id",e.flagId.toString()),n=await this.http.post(t,{},this.getMultiAuthHeaders());return{flag:this.extractData(n).flag}}async actionFlag(e){!function(e){if(void 0===e.flagId||null===e.flagId)throw zt("flagId","Flag ID");try{zn(e.flagId,"flagId")}catch{throw Qt("flagId","a positive integer","Flag ID")}if(void 0===e.action)throw zt("action","Action");if(!ca(e.action))throw Qt("action",`one of: ${Object.values(Zi).join(", ")}`,"Action")}(e);const t=Te.ACTION.replace(":id",e.flagId.toString()),n=await this.http.post(t,{action:e.action},this.getMultiAuthHeaders());return{flag:this.extractData(n).flag}}async fetchFlagList(e){const t=ci(e,vs);ui(t,e,["tokenName","contentType","status","reason","reporterAddress","reportedUserAddress"]);for(const e of["reporterAddress","reportedUserAddress"]){const n=t[e];void 0!==n&&(t[e]=In(n,e))}const n=await this.http.get(Te.LIST,t,this.getMultiAuthHeaders()),s=this.extractData(n);return{items:s.flags,pageInfo:s.pageInfo}}}const ga=["heart","fire","laugh","wow","thumbs_up"];class ma extends gi{constructor(e,t,n,s=!1,r){super(e,t,n,s,r)}validateMessageId(e){if(!Jn(e))throw zt("messageId","Message ID");if(Vn(e,Ss.CONTENT_REACTION.MAX_LENGTH,"messageId"),!Ss.CONTENT_REACTION.PATTERN.test(e))throw Qt("messageId","msg-{timestamp}-{uuid} or chat-{timestamp}-{uuid} format","Message ID")}validateReactionType(e){if(!Jn(e))throw zt("reactionType","Reaction type");if(!ga.includes(e))throw Qt("reactionType",`one of: ${ga.join(", ")}`,"Reaction type")}async addContentReaction(e){this.validateMessageId(e.messageId),this.validateReactionType(e.reactionType);const t=ze,n={messageId:e.messageId,reactionType:e.reactionType},s=await this.http.post(t,n,this.getMultiAuthHeaders()),r=this.extractData(s),{created:i,...a}=r;return{data:a,created:i}}async removeContentReaction(e){this.validateMessageId(e.messageId),this.validateReactionType(e.reactionType);const t=`${Qe}?${new URLSearchParams({messageId:e.messageId,reactionType:e.reactionType}).toString()}`;return await this.http.delete(t,{},this.getMultiAuthHeaders()),{success:!0}}async addReactionToChatMessage(e){return this.addContentReaction(e)}async removeReactionFromChatMessage(e){return this.removeContentReaction(e)}async addReactionToComment(e){return this.addContentReaction(e)}async removeReactionFromComment(e){return this.removeContentReaction(e)}}const fa="Token name is required and must be a string";const pa="GALA|Unit|none|none";class va extends ds{constructor(e,t,n,s=!1){super(s),this.dexBackendHttp=e,this.cache=t,this.fetchTokenDetails=n}async fetchLaunchpadTokenSpotPrice(e,t,n){if(!Jn(e))throw new Ot(fa,"tokenName",kt);let s;if(void 0!==n)try{this.logger.debug(`Checking graduation status for token: ${e}`);const t=await n(e);!0===t.isGraduated&&(s=ji(t.sellingToken))}catch(t){this.logger.debug(`Could not determine graduation status for ${e}, falling back to bonding curve: ${$t(t)}`)}if(void 0!==s)return this.logger.debug(`Token ${e} is graduated, using its swap backend price`),this.fetchMarketUsdPrice(s);try{this.logger.debug(`Using bonding curve calculation for token: ${e}`);const n=await t({tokenName:e,amount:"1",type:"native"}),s=await this.fetchMarketUsdPrice(pa),r=Gn(n.amount,0)/1e18;if(r<=0)throw new Ot(`Invalid token amount calculation: ${r}`,"amount","INVALID_CALCULATION");return{symbol:pn(e),price:s.price/r}}catch(t){throw Xt(`Failed to calculate launchpad token spot price for ${e}: ${$t(t)}`,void 0,Bt(t)?t:void 0)}}async resolveAuthoritativeSymbol(e){if(e===pa)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 Xt("GalaChainService not available for token metadata fetch",500);n=(await this.fetchTokenDetails(e)).symbol}catch(t){throw Xt(`Could not resolve the symbol for ${e} from the token class, and a symbol cannot be derived from the class key: ${$t(t)}`)}if(""===n)throw Xt(`Token class for ${e} has no symbol`);return this.cache?.setByTokenId(e,{symbol:n}),n}async fetchMarketUsdPrice(e){try{const t=function(e){if(!Jn(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 Xt("DEX Backend API client not configured");const n=await this.resolveAuthoritativeSymbol(e),s=await this.dexBackendHttp.request({method:"GET",url:"/market/price",params:{assetIds:t}}),r=null!==s&&"object"==typeof s?s:{},i=Object.keys(r).find(e=>e.toUpperCase()===n.toUpperCase()),a=void 0!==i?r[i]:1===Object.keys(r).length?Object.values(r)[0]:void 0,o=a?.price;if("number"!=typeof o||!Number.isFinite(o))throw new Ot(`Invalid price response: no market price for ${t}`,"data","INVALID_RESPONSE");return this.logger.debug(`Swap backend price for ${n}: $${o}`),{symbol:n,price:o}}catch(e){if(e instanceof Ot)throw e;throw Xt(`Failed to fetch DEX spot price: ${$t(e)}`)}}}const Aa=20,Ea=3e3,ya=1e3,Ta=!0,Sa=!0,ba=!1,ka={LOGIN:"login",LOGOUT:"logout",TOKEN_BUY:"token_buy",TOKEN_SELL:"token_sell",TOKEN_SWAP:"token_swap",TOKEN_CREATED:"token_created",TOKEN_GRADUATED:"token_graduated",PAGE_VIEW:"page_view",PAGE_LEAVE:"page_leave",STREAM_START:"stream_start",STREAM_END:"stream_end",STREAM_VIEWERS_CHANGED:"stream_viewers_changed",CHAT_MESSAGE_SENT:"chat_message_sent",CHAT_MESSAGE_RECEIVED:"chat_message_received",LIQUIDITY_ADDED:"liquidity_added",LIQUIDITY_REMOVED:"liquidity_removed",BRIDGE_DEPOSIT:"bridge_deposit",BRIDGE_WITHDRAW:"bridge_withdraw",PROFILE_UPDATED:"profile_updated",BALANCE_CHANGED:"balance_changed",ERROR_OCCURRED:"error_occurred"};class wa{constructor(e,t={}){this.eventBuffer=[],this.flushTimer=null,this.isShuttingDown=!1,this.totalQueued=0,this.totalFlushed=0,this.totalDropped=0,this.handleVisibilityChange=()=>{"hidden"===document.visibilityState&&this.eventBuffer.length>0&&this.flushWithBeacon()},this.handleBeforeUnload=()=>{this.eventBuffer.length>0&&this.flushWithBeacon()},this.httpClient=e,this.logger=new An({debug:t.debug??!1,context:"EventsBatcherService"}),this.config={batchSize:t.batchSize??Aa,flushIntervalMs:t.flushIntervalMs??Ea,maxQueueSize:t.maxQueueSize??ya,flushOnPageHide:t.flushOnPageHide??Ta,flushOnPageUnload:t.flushOnPageUnload??Sa,debug:t.debug??ba},this.setupPageLifecycleListeners()}track(e,t,n){if(this.isShuttingDown)return void this.logger.warn("EventsBatcher is shutting down, ignoring track call");const s={eventType:e,payload:t,clientTimestamp:(new Date).toISOString(),...void 0!==n?.userAddress&&""!==n.userAddress&&{userAddress:Nn(n.userAddress,"userAddress")},...void 0!==n?.tokenName&&""!==n.tokenName&&{tokenName:n.tokenName},...void 0!==n?.sessionId&&""!==n.sessionId&&{sessionId:n.sessionId}};this.buffer(s),n?.immediate&&this.scheduleFlush(0)}async flush(){if(0===this.eventBuffer.length)return;this.cancelFlushTimer();const e=this.eventBuffer.splice(0);this.logger.debug(`Flushing ${e.length} events`);try{const t=await this.submitEvents(e);this.totalFlushed+=t.accepted,this.lastFlushTime=Date.now(),this.lastError=void 0,this.logger.debug(`Flush successful, accepted ${t.accepted} events`)}catch(t){throw this.eventBuffer.unshift(...e),this.lastError=t instanceof Error?t.message:String(t),this.logger.error(`Flush failed: ${this.lastError}`),t}}getStats(){const e={bufferedCount:this.eventBuffer.length,totalQueued:this.totalQueued,totalFlushed:this.totalFlushed,totalDropped:this.totalDropped};return void 0!==this.lastFlushTime&&(e.lastFlushTime=this.lastFlushTime),void 0!==this.lastError&&(e.lastError=this.lastError),e}configure(e){void 0!==e.batchSize&&(this.config.batchSize=e.batchSize),void 0!==e.flushIntervalMs&&(this.config.flushIntervalMs=e.flushIntervalMs),void 0!==e.maxQueueSize&&(this.config.maxQueueSize=e.maxQueueSize),void 0!==e.flushOnPageHide&&(this.config.flushOnPageHide=e.flushOnPageHide),void 0!==e.flushOnPageUnload&&(this.config.flushOnPageUnload=e.flushOnPageUnload)}async shutdown(e=5e3){if(this.isShuttingDown=!0,this.removePageLifecycleListeners(),0!==this.eventBuffer.length)try{await Promise.race([this.flush(),new Promise((t,n)=>setTimeout(()=>n(new Error("Flush timeout during shutdown")),e))])}catch(e){this.logger.error(`Shutdown flush failed: ${e instanceof Error?e.message:String(e)}`)}}buffer(e){this.eventBuffer.length>=this.config.maxQueueSize&&(this.eventBuffer.shift(),this.totalDropped++,this.logger.warn("Event buffer full, dropped oldest event")),this.eventBuffer.push(e),this.totalQueued++,this.eventBuffer.length>=this.config.batchSize?this.scheduleFlush(0):this.scheduleFlush(this.config.flushIntervalMs)}scheduleFlush(e){null===this.flushTimer&&(this.flushTimer=setTimeout(()=>{this.flushTimer=null,this.flush().catch(e=>{this.logger.error(`Scheduled flush failed: ${e instanceof Error?e.message:String(e)}`)})},e))}cancelFlushTimer(){null!==this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null)}async submitEvents(e){return await this.httpClient.post("/v1/events",{events:e})}setupPageLifecycleListeners(){"undefined"!=typeof document&&(this.config.flushOnPageHide&&document.addEventListener("visibilitychange",this.handleVisibilityChange),this.config.flushOnPageUnload&&window.addEventListener("beforeunload",this.handleBeforeUnload))}removePageLifecycleListeners(){"undefined"!=typeof document&&(this.config.flushOnPageHide&&document.removeEventListener("visibilitychange",this.handleVisibilityChange),this.config.flushOnPageUnload&&window.removeEventListener("beforeunload",this.handleBeforeUnload))}flushWithBeacon(){if("undefined"==typeof navigator||!navigator.sendBeacon)return;const e=this.eventBuffer.splice(0),t=JSON.stringify({events:e});try{const n=this.getBaseUrl();navigator.sendBeacon(`${n}/v1/events`,t)?(this.totalFlushed+=e.length,this.lastFlushTime=Date.now()):(this.eventBuffer.unshift(...e),this.logger.warn("sendBeacon returned false, events re-buffered"))}catch(t){this.eventBuffer.unshift(...e),this.logger.error(`sendBeacon failed: ${t instanceof Error?t.message:String(t)}`)}}getBaseUrl(){const e=this.httpClient.config;return e?.baseUrl??""}}const Na=["createdAt","eventType","userAddress"],Ia=["last_hour","today","yesterday","last_7_days","last_30_days","custom"],_a=["sdk","frontend","backend","mcp"];function Ca(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Da(e){return"number"==typeof e&&Number.isFinite(e)}function Ra(e){return Ca(e)&&Da(e.id)&&"string"==typeof e.eventType&&Ca(e.payload)&&"string"==typeof e.createdAt&&"string"==typeof e.updatedAt}function Oa(e,t,n){if(!t.some(t=>t===e))throw new Ot(`${n} must be one of: ${t.join(", ")}`,n,Nt)}class Ma extends gi{constructor(e,t,n,s=!1,r){super(e,t,n,s,r)}async getEventStats(){return function(e){if(!(Ca(e)&&Da(e.totalEvents)&&Da(e.todayEvents)&&Da(e.uniqueUsers)&&Da(e.uniqueTokens)&&Ca(e.eventsByType)))throw Xt("Malformed event statistics response");const t={};for(const[n,s]of Object.entries(e.eventsByType)){if(!Da(s))throw Xt("Malformed event statistics response");t[n]=s}return{totalEvents:e.totalEvents,todayEvents:e.todayEvents,uniqueUsers:e.uniqueUsers,uniqueTokens:e.uniqueTokens,eventsByType:t}}(await this.http.get(it,void 0,this.getDualAuthHeaders()))}async queryEvents(e={}){!function(e){if(void 0!==e.limit&&(!Number.isInteger(e.limit)||e.limit<1||e.limit>100))throw new Ot("limit must be an integer from 1 to 100","limit",Nt);if(void 0!==e.page&&(!Number.isInteger(e.page)||e.page<1))throw new Ot("page must be a positive integer","page",Nt);void 0!==e.sortBy&&Oa(e.sortBy,Na,"sortBy"),void 0!==e.sortOrder&&Oa(e.sortOrder,["asc","desc"],"sortOrder"),void 0!==e.timePreset&&Oa(e.timePreset,Ia,"timePreset"),void 0!==e.source&&Oa(e.source,_a,"source")}(e);const t={},n=new URLSearchParams;for(const[s,r]of Object.entries(e))if(void 0!==r&&("string"!=typeof r||""!==r)){if(Array.isArray(r)){const e=r.map(String);if(0===e.length)continue;for(const t of 1===e.length?[...e,...e]:e)n.append(s,t);continue}t[s]="userAddress"===s&&"string"==typeof r?Nn(r,"userAddress"):r}const s=n.toString(),r=""===s?rt:`${rt}?${s}`;return function(e){if(!Ca(e)||!Array.isArray(e.data)||!Ca(e.pagination))throw Xt("Malformed events response");const t=e.pagination,n=e.data;if(!(Da(t.page)&&Da(t.limit)&&Da(t.total)&&Da(t.totalPages)&&n.every(Ra)))throw Xt("Malformed events response");return{data:n,pagination:{page:t.page,limit:t.limit,total:t.total,totalPages:t.totalPages}}}(await this.http.get(r,t,this.getDualAuthHeaders()))}}function Ua(e){let t;return{requestor:async(n,s)=>{const r="string"==typeof s?.body?JSON.parse(s.body):void 0,{data:i,status:a,headers:o}=await e(n,r);t=i;const c=void 0===i?"":JSON.stringify(i),l="number"==typeof a?a:200;return{ok:l>=200&&l<300,status:l,json:()=>Promise.resolve(i),text:()=>Promise.resolve(c),headers:o??{}}},answer:()=>t}}const Fa=new Set(["GATEWAY_READ_REJECTED","GATEWAY_READ_RESPONSE_INVALID"]);class La extends ls{constructor(e,t=!1){super(e,t)}async fetchGalaBalance(e){return this.fetchTokenBalance(e)}async fetchTokenBalance(e,t=!1){const n=wn(e.owner,"owner");try{const{requestor:s}=Ua(async(e,t)=>({data:await this.http.post(e,t)})),r=new p({gatewayBaseUrl:"",httpRequestor:s,requestTimeoutMs:1/0}),{collection:i,category:a,type:o,additionalKey:c}=e,l=await r.fetchTokenBalance({owner:n,tokenClassKey:{collection:i,category:a,type:o,additionalKey:c},includeExpiredHolds:t});return void 0===l?null:function(e){if("0"===e.quantity)return null;const{collection:t,category:n}=e.tokenClassKey,s={quantity:e.quantity,collection:t,category:n,tokenId:ji(e.tokenClassKey)};return e.inUseHolds.length>0&&(s.inUseHolds=[...e.inUseHolds],s.inUseQuantity=e.inUseQuantity),e.lockedHolds.length>0&&(s.lockedHolds=[...e.lockedHolds],s.lockedQuantity=e.lockedQuantity),void 0===s.lockedQuantity&&void 0===s.inUseQuantity||(s.availableQuantity=e.availableQuantity),s}(l)}catch(e){if(o(e)&&Fa.has(e.code))return null;throw Xt(`Failed to fetch token balance from GalaChain: ${$t(e)}`,void 0,Bt(e)?e:void 0)}}}function xa(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Jn(t.amount)&&(void 0!==t.tokenId||Jn(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 Pa(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Jn(t.amount)&&(void 0!==t.tokenId||Jn(t.tokenName))&&(void 0===t.name||"string"==typeof t.name)}var Ba,$a;!function(e){e.TOKEN_NOT_FOUND="TOKEN_NOT_FOUND",e.INVALID_AMOUNT="INVALID_AMOUNT",e.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",e.SIGNATURE_FAILED="SIGNATURE_FAILED",e.NETWORK_ERROR="NETWORK_ERROR",e.WALLET_REQUIRED="WALLET_REQUIRED",e.VALIDATION_ERROR="VALIDATION_ERROR",e.LOCK_NOT_FOUND="LOCK_NOT_FOUND",e.LOCK_EXPIRED="LOCK_EXPIRED",e.INSUFFICIENT_LOCKED_BALANCE="INSUFFICIENT_LOCKED_BALANCE",e.NOT_LOCK_AUTHORITY="NOT_LOCK_AUTHORITY",e.LOCK_NAME_MISMATCH="LOCK_NAME_MISMATCH"}(Ba||(Ba={}));class Ga 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"}($a||($a={}));class Ka extends Error{constructor(e,t,n){super(e),this.type=t,this.details=n,this.name="TransferError"}}function Wa(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 Ha(e,t,n,s="[DEBUG] Token resolution (launchpad)"){const r=await t.resolveTokenToVault(e);if(null!==r){const t=zi(r);return n.debug(s,{tokenName:e,vaultAddress:r,tokenInstance:{collection:t.collection,category:t.category,type:t.type,instance:t.instance}}),t}throw new Ot(`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 ja extends ls{constructor(e,t,n,s=!1,r){super(e,s),this.wallet=t,this.tokenResolver=n,this.writer=r,this.nativeSigner=t?new Bi(t.privateKey):void 0}writeIdentity(){return void 0!==this.wallet&&void 0!==this.nativeSigner?{signer:this.nativeSigner,walletAddress:Mn(this.wallet.address)}:this.writer}}function qa(e,t){const{collection:n,category:s,type:r,additionalKey:i,instance:a}=e;return{tokenClassKey:{collection:n,category:s,type:r,additionalKey:i},instance:a,quantity:t}}const Va=new Set(["GATEWAY_WRITE_REJECTED","GATEWAY_RESPONSE_INVALID","GATEWAY_HTTP_ERROR"]);function za(e,{signer:t,walletAddress:n}){const{requestor:s,answer:r}=Ua((t,n)=>e.postWithMeta(t,n));return{writes:new v({gatewayBaseUrl:"",signer:t,walletAddress:n,httpRequestor:s,requestTimeoutMs:1/0,uniqueKeyPrefix:"galaconnect-operation-"}),answer:r}}async function Qa(e,t,n){let s;try{s=await t(e.writes)}catch(t){throw function(e){return o(e)&&Va.has(e.code)}(t)&&n(e.answer(),void 0),t}return n(e.answer(),s)}function Xa(e){return void 0===e||""===e?{}:{uniqueKey:e}}const Ja=100,Ya=100;class Za extends ja{async lockTokens(e){this.validateLockTokensData(e);const t=this.writeIdentity();if(void 0===t)throw new Ga("Wallet required for token lock operations",Ba.WALLET_REQUIRED);return Vr(async()=>{const n=za(this.http,t),s=n.writes.walletAddress,r=[],i=[];let a=s;const o=e.tokens.find(e=>void 0!==e.lockAuthority);void 0!==o?.lockAuthority&&(a=Mn(o.lockAuthority));const c=e.tokens.find(e=>void 0!==e.expires),l=e.tokens.find(e=>void 0!==e.name);for(const t of e.tokens){const e=await this.resolveTokenEntry(t);i.push(qa(e,t.amount)),r.push({tokenClassKey:{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey},quantity:t.amount,lockAuthority:void 0!==t.lockAuthority?Mn(t.lockAuthority):a})}return Qa(n,t=>t.lockTokens({tokens:i,lockAuthority:a,...void 0!==c?.expires&&{expires:c.expires},...void 0!==l?.name&&{name:l.name},...Xa(e.uniqueKey)}),(e,t)=>(this.assertLockAnswer(e,"Token lock failed"),this.extractLockResult(e,t,r)))},"Token lock failed",this.logger,t=>{throw this.handleLockError(t,"Token lock failed",e)})}async unlockTokens(e){this.validateUnlockTokensData(e);const t=this.writeIdentity();if(void 0===t)throw new Ga("Wallet required for token unlock operations",Ba.WALLET_REQUIRED);return Vr(async()=>{const n=[],s=[],r=e.tokens.find(e=>void 0!==e.name);for(const t of e.tokens){const e=await this.resolveTokenEntry(t);s.push(qa(e,t.amount)),n.push({tokenClassKey:{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey},quantity:t.amount})}return Qa(za(this.http,t),t=>t.unlockTokens({tokens:s,...void 0!==r?.name&&{name:r.name},...Xa(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{Ht(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 Ga(`${$t(t)}${n}`,Ba.NETWORK_ERROR)}}validateSharedTokenEntry(e,t,n){if(void 0===e.tokenId&&void 0===e.tokenName)throw new Ga("Must provide either tokenId or tokenName for token identification",Ba.TOKEN_NOT_FOUND);if(void 0!==e.tokenName)try{ss(e.tokenName,"tokenName",ms)}catch{throw new Ga("Invalid token name format",Ba.TOKEN_NOT_FOUND,{tokenName:e.tokenName})}try{Nr(Sr(e.amount))}catch{throw new Ga(Qt(t,"a positive number",n).message,Ba.INVALID_AMOUNT,{amount:e.amount})}}validateLockTokensData(e){if(!function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every(xa)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}(e))throw new Ga("Invalid lock data: missing required fields",Ba.VALIDATION_ERROR);if(e.tokens.length>Ja)throw new Ga(`Batch size exceeds maximum limit of ${Ja} tokens per lock operation`,Ba.VALIDATION_ERROR);for(const t of e.tokens){if(this.validateSharedTokenEntry(t,"lockAmount","Lock amount"),void 0!==t.lockAuthority&&!Un(t.lockAuthority))throw new Ga("Invalid lock authority address format",Ba.VALIDATION_ERROR,{lockAuthority:t.lockAuthority});if(void 0!==t.expires)try{zn(t.expires,"expires")}catch{throw new Ga(Qt("expires","a positive integer (epoch milliseconds)","Expires").message,Ba.VALIDATION_ERROR)}}}validateUnlockTokensData(e){if(!function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every(Pa)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}(e))throw new Ga("Invalid unlock data: missing required fields",Ba.VALIDATION_ERROR);if(e.tokens.length>Ya)throw new Ga(`Batch size exceeds maximum limit of ${Ya} tokens per unlock operation`,Ba.VALIDATION_ERROR);for(const t of e.tokens)this.validateSharedTokenEntry(t,"unlockAmount","Unlock amount")}transactionIdOf(e,t){const n=Array.isArray(e.Data)?e.Data[0]:void 0;return t?.transactionId??n?.transactionId??n?.txnId??n?.TxnId??n?.id??void 0}extractLockResult(e,t,n){const s=this.transactionIdOf(e,t),r=t?.blockNumber;return{...void 0!==s&&{transactionId:s},...void 0!==r&&{blockNumber:r},locked:n}}extractUnlockResult(e,t,n){const s=this.transactionIdOf(e,t),r=t?.blockNumber;return{...void 0!==s&&{transactionId:s},...void 0!==r&&{blockNumber:r},unlocked:n}}handleLockError(e,t,n){if(e instanceof Ga)return e;if(o(e)&&"pre_send"===e.phase)return new Ga(`${t}: ${e.message}`,"SIGNING_FAILED"===(s=e.code)?Ba.SIGNATURE_FAILED:"INVALID_TOKEN_REFERENCE"===s?Ba.TOKEN_NOT_FOUND:"INVALID_QUANTITY"===s?Ba.INVALID_AMOUNT:Ba.VALIDATION_ERROR,Wa(n));var s;let r=t,i=Ba.NETWORK_ERROR;if(Wt(e)){const n=e.response?.data;if("object"==typeof n&&null!==n){const e=n.Message;"string"==typeof e&&e.length>0&&(r=`${t}: ${e}`);const s="string"==typeof e?e.toLowerCase():"";s.includes("insufficient")||s.includes("balance")?i=Ba.INSUFFICIENT_BALANCE:s.includes("lock")&&s.includes("not found")?i=Ba.LOCK_NOT_FOUND:s.includes("not found")||s.includes("token")?i=Ba.TOKEN_NOT_FOUND:s.includes("authority")?i=Ba.NOT_LOCK_AUTHORITY:s.includes("expired")&&(i=Ba.LOCK_EXPIRED)}}else Bt(e)&&(r=`${t}: ${$t(e)}`);return new Ga(r,i,Wa(n))}async resolveTokenInstance(e){return Vr(async()=>Ha(e,this.tokenResolver,this.logger),`Failed to resolve token '${e}'`,this.logger,t=>{if(t instanceof Ka)throw new Ga($t(t),Ba.TOKEN_NOT_FOUND);throw new Ga(`Failed to resolve token '${e}': ${$t(t)}`,Ba.TOKEN_NOT_FOUND,{tokenName:e})})}async resolveTokenEntry(e){if(void 0!==e.tokenId){const t=qi(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 Ga("Must provide either tokenId or tokenName for token identification",Ba.TOKEN_NOT_FOUND)}}const eo=new Set(["GATEWAY_READ_REJECTED","GATEWAY_READ_RESPONSE_INVALID","TOKEN_CLASS_NOT_FOUND"]);function to(e){const t=e?.Data;return Array.isArray(t)?t:void 0}class no extends ls{constructor(e,t=!1,n){super(e,t),this.publicAxios=n}async fetchTokenClassFromChain(e){try{const t="string"==typeof e?qi(e):e,{collection:n,category:s,type:r,additionalKey:i}=t,a={collection:n,category:s,type:r,additionalKey:i},o="Failed to fetch token class from GalaChain";return await this.readPublic(e=>e.fetchTokenClass(a),e=>{if(Ht(e,o),void 0===to(e)?.[0])throw Xt(`Token not found on GalaChain: ${ji(a)}`,404)},()=>Xt(`Token not found on GalaChain: ${ji(a)}`,404))}catch(e){return this.handleTokenServiceError(e,"Token not found on GalaChain","Failed to fetch token class from GalaChain")}}async fetchTokenClassesWithSupply(e){try{if(null==e||0===e.length)throw zt("tokenClasses","Token classes array");return await this.readPublic(t=>t.fetchTokenClassesWithSupply(e),e=>{if(Ht(e,"Failed to fetch token classes with supply from GalaChain"),0===(to(e)?.length??0))throw Xt("No token supply data found for requested token classes",404)},void 0)}catch(e){return this.handleTokenServiceError(e,"Token supply data not found on GalaChain","Failed to fetch token classes with supply from GalaChain")}}async readPublic(e,t,n){if(!this.publicAxios)throw zt("publicAxios","Public Axios instance");const s=this.publicAxios,{requestor:r,answer:i}=Ua(async(e,t)=>{const n=await s.post(e,t);return{data:n.data,status:n.status}});try{return await e(new p({gatewayBaseUrl:"",httpRequestor:r,requestTimeoutMs:1/0}))}catch(e){if(o(e)&&eo.has(e.code)&&(t(i()),"TOKEN_CLASS_NOT_FOUND"===e.code&&void 0!==n))throw n();throw e}}handleTokenServiceError(e,t,n){if(e instanceof Ot)throw e;if(Wt(e)&&404===e.response?.status)throw Xt(t,404,Bt(e)?e:void 0);if(Bt(e)&&"Error"===e.name&&$t(e).includes("status indicates failure"))throw Xt($t(e),400,Bt(e)?e:void 0);const s=$t(e);if(s.includes("Token not found")){if(e instanceof Error)throw e;throw new Error(s)}throw Xt(`${n}: ${s}`,void 0,Bt(e)?e:void 0)}}function so(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Jn(t.amount)&&(void 0!==t.tokenId||Jn(t.tokenName))}var ro;!function(e){e.TOKEN_NOT_FOUND="TOKEN_NOT_FOUND",e.INVALID_AMOUNT="INVALID_AMOUNT",e.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",e.SIGNATURE_FAILED="SIGNATURE_FAILED",e.NETWORK_ERROR="NETWORK_ERROR",e.WALLET_REQUIRED="WALLET_REQUIRED",e.VALIDATION_ERROR="VALIDATION_ERROR"}(ro||(ro={}));class io extends Error{constructor(e,t,n){super(e),this.type=t,this.details=n,this.name="BurnError"}}const ao={validateAmount(e){const t=Sr(e);try{!function(e,t){if(e.isNaN())throw sn(t,"NaN");if(!e.isFinite())throw tn(t,"finite");if(e.isLessThanOrEqualTo(0))throw en(t,"0",e.toString())}(t,"amount")}catch(t){throw new Ka(t.message,$a.INVALID_AMOUNT,{amount:e})}},validateUniqueKey(e){if(!Yn(e)&&Jn(e)){if(e.length>ws.MAX_LENGTH)throw new Ot(`Unique key too long. Maximum length: ${ws.MAX_LENGTH}`);if(!ws.PATTERN.test(e))throw new Ka('Invalid unique key format. Must start with "galaswap-operation-" or "galaconnect-operation-"',$a.INVALID_AMOUNT,{uniqueKey:e})}}},oo="gala-transfer-successful",co="token-transfer-successful",lo="token-locked-successfully",uo="token-unlocked-successfully",ho="transfer-successful-no-id",go=50;class mo extends ja{async transferGala(e){this.validateTransferGalaData(e);const t=this.writeIdentity();if(void 0===t)throw new Ka("Wallet required for GALA transfer operations",$a.WALLET_REQUIRED);try{const n=Mn(e.recipientAddress),s=za(this.http,t);return await Qa(s,t=>t.transferGala({to:n,quantity:e.amount,...Xa(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 Ka("Wallet required for token transfer operations",$a.WALLET_REQUIRED);try{const n=Mn(e.to),s=await this.tokenInstanceOf(e.tokenId,e.tokenName,()=>new Ka("Must provide either tokenId or tokenName for token identification",$a.TOKEN_NOT_FOUND)),r=za(this.http,t);return await Qa(r,t=>t.transferToken({to:n,...qa(s,e.amount),...Xa(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 Ka)throw t;throw new Ka(`Failed to resolve token class key for '${e}': ${$t(t)}`,$a.TOKEN_NOT_FOUND,{tokenName:e})}}async burnTokens(e){this.validateBurnTokensData(e);const t=this.writeIdentity();if(void 0===t)throw new io("Wallet required for token burn operations",ro.WALLET_REQUIRED);try{const n=[];for(const t of e.tokens){const e=await this.tokenInstanceOf(t.tokenId,t.tokenName,()=>new io("Must provide either tokenId or tokenName for token identification",ro.TOKEN_NOT_FOUND));n.push(qa(e,t.amount))}const s=za(this.http,t);return await Qa(s,t=>t.burnTokens({tokens:n,...Xa(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 Jn(t.recipientAddress)&&Jn(t.amount)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)}(e))throw new Ot("Invalid GALA transfer data: missing required fields");if(!Un(e.recipientAddress))throw new Ka("Invalid recipient address format",$a.INVALID_RECIPIENT,{recipientAddress:e.recipientAddress});ao.validateAmount(e.amount),ao.validateUniqueKey(e.uniqueKey)}validateTransferTokenData(e){if(!function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Jn(t.to)&&Jn(t.amount)&&(void 0!==t.tokenId||Jn(t.tokenName))&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)}(e))throw new Ot("Invalid token transfer data: missing required fields");if(!Un(e.to))throw new Ka("Invalid recipient address format",$a.INVALID_RECIPIENT,{recipientAddress:e.to});if(!(null!==e.tokenId&&void 0!==e.tokenId||null!==e.tokenName&&void 0!==e.tokenName))throw new Ka("Must provide either tokenId or tokenName for token identification",$a.TOKEN_NOT_FOUND);if(null!==e.tokenName&&void 0!==e.tokenName)try{ss(e.tokenName,"tokenName",ms)}catch{throw new Ka("Invalid token name format",$a.TOKEN_NOT_FOUND,{tokenName:e.tokenName})}ao.validateAmount(e.amount),ao.validateUniqueKey(e.uniqueKey)}validateBurnTokensData(e){if(!function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every(so)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}(e))throw new io("Invalid burn data: missing required fields",ro.VALIDATION_ERROR);if(e.tokens.length>go)throw new io(`Batch size exceeds maximum limit of ${go} tokens per burn operation`,ro.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 io("Must provide either tokenId or tokenName for token identification",ro.TOKEN_NOT_FOUND);const e=Sr(t.amount);try{Nr(e)}catch{throw new io("Burn amount must be a positive number",ro.INVALID_AMOUNT,{amount:t.amount})}}}async tokenInstanceOf(e,t,n){if(null!=e){const t=qi(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 Ha(e,this.tokenResolver,this.logger,`[DEBUG] Token resolution for '${e}' (launchpad):`)}catch(t){if(t instanceof Ka)throw t;throw new Ka(`Failed to resolve token '${e}': ${$t(t)}`,$a.TOKEN_NOT_FOUND,{tokenName:e})}}extractTransferResult(e,t,n){if(null==e)throw new Ka("No response from GalaChain transfer service",$a.NETWORK_ERROR);const s=t?.blockNumber,r="object"==typeof e&&"Status"in e;r&&Ht(e,"Extract transaction ID");const i=r&&"Data"in e,a=t?.transactionId;if(void 0!==a)return{transactionId:a,...void 0!==s?{blockNumber:s}:{}};if(i){const t=e;if(Array.isArray(t.Data)){for(const e of t.Data)if(null!=e&&"object"==typeof e){const t=e;for(const e of["transactionId","txnId","TxnId","id","txId"]){const n=t[e];if("string"==typeof n&&n.length>0)return{transactionId:n,...void 0!==s?{blockNumber:s}:{}}}}let e=ho;if(t.Data.length>0)switch(n){case"gala":e=oo;break;case"token":e=co;break;case"lock":e=lo;break;case"unlock":e=uo}return{transactionId:e,...void 0!==s?{blockNumber:s}:{}}}}throw new Ka("Operation succeeded but transaction ID could not be extracted (missing x-transaction-id header and body fields)",$a.NETWORK_ERROR)}burnResultOf(e,t){if(null==e)throw new io("No response from GalaChain burn service",ro.NETWORK_ERROR);try{Ht(e,"Token burn operation")}catch(e){throw new Lt($t(e),500)}return this.extractBurnResult(e,t)}extractBurnResult(e,t){const n=[];if(null!==e.Data&&void 0!==e.Data&&Array.isArray(e.Data))for(const t of e.Data)n.push({collection:t.collection??"",category:t.category??"",type:t.type??"",additionalKey:t.additionalKey??"",instance:t.instance??"0",quantity:t.quantity??"0",burnedBy:t.burnedBy??""});const s=Array.isArray(e.Data)?e.Data[0]:void 0,r=t?.transactionId??s?.transactionId??s?.txnId??s?.TxnId??s?.id??void 0,i=t?.blockNumber;return{...void 0!==r&&{transactionId:r},...void 0!==i&&{blockNumber:i},burned:n}}handleTransferError(e,t,n){if(e instanceof Ka)return e;if(e instanceof Ot)return new Ka($t(e),$a.INVALID_AMOUNT);if(o(e)&&"pre_send"===e.phase)return new Ka(e.message,"SIGNING_FAILED"===(s=e.code)?$a.SIGNATURE_FAILED:"INVALID_WALLET_ADDRESS"===s?$a.INVALID_RECIPIENT:"INVALID_TOKEN_REFERENCE"===s?$a.TOKEN_NOT_FOUND:$a.INVALID_AMOUNT);var s;if(Wt(e)&&e.response){const t=e.response.status,s=e.response.data;if(400===t){const e=s?.message;return new Ka(("string"==typeof e?e:void 0)??"Invalid transfer request",$a.INVALID_AMOUNT)}if(403===t)return new Ka("Insufficient balance for transfer",$a.INSUFFICIENT_BALANCE);if(404===t){const e={};return"tokenName"in n&&(e.tokenName=n.tokenName),new Ka("Token not found",$a.TOKEN_NOT_FOUND,e)}}if("object"==typeof e&&null!==e&&"code"in e&&("ECONNABORTED"===Kt(e)||"ETIMEDOUT"===Kt(e)))return new Ka("Transfer request timed out",$a.NETWORK_ERROR);const r=""!==$t(e)?$t(e):t;return new Ka(r,$a.NETWORK_ERROR)}handleBurnError(e,t,n){if(e instanceof io)return e;if(o(e)&&"pre_send"===e.phase)return new io(`${t}: ${e.message}`,"SIGNING_FAILED"===(s=e.code)?ro.SIGNATURE_FAILED:"INVALID_TOKEN_REFERENCE"===s?ro.TOKEN_NOT_FOUND:"INVALID_QUANTITY"===s?ro.INVALID_AMOUNT:ro.VALIDATION_ERROR,Wa(n));var s;let r=t,i=ro.NETWORK_ERROR;if(Wt(e)){const n=e.response?.data;if("object"==typeof n){const e=n.Message;if("string"==typeof e&&e.length>0){r=`${t}: ${e}`;const n=e.toLowerCase();n.includes("insufficient")||n.includes("balance")?i=ro.INSUFFICIENT_BALANCE:(n.includes("not found")||n.includes("token"))&&(i=ro.TOKEN_NOT_FOUND)}}}else Bt(e)&&(r=`${t}: ${$t(e)}`);return new io(r,i,Wa(n))}}class fo extends ls{constructor(e,t,n,s=!1,r,i){super(e,s),this.balanceService=new La(e,s),this.tokenService=new no(e,s,r),this.lockService=new Za(e,t,n,s,i),this.transferService=new mo(e,t,n,s,i)}async fetchGalaBalance(e){return this.balanceService.fetchGalaBalance(e)}async fetchTokenBalance(e,t=!1){return this.balanceService.fetchTokenBalance(e,t)}async fetchTokenClassFromChain(e){return this.tokenService.fetchTokenClassFromChain(e)}async fetchTokenDetails(e){try{return A(await this.fetchTokenClassFromChain(e))}catch(t){if(Bt(t)&&("NetworkError"===t.name||$t(t).includes("Token not found")))throw t;throw Xt(`Failed to fetch token details from GalaChain for ${"string"==typeof e?e:ji(e)}: ${$t(t)}`,500)}}async fetchTokenClassesWithSupply(e){return this.tokenService.fetchTokenClassesWithSupply(e)}async transferGala(e){return this.transferService.transferGala(e)}async transferToken(e){return this.transferService.transferToken(e)}async resolveTokenClassKey(e){return this.transferService.resolveTokenClassKey(e)}async lockTokens(e){return this.lockService.lockTokens(e)}async unlockTokens(e){return this.lockService.unlockTokens(e)}async burnTokens(e){return this.transferService.burnTokens(e)}}class po extends ls{async getHealth(){const e=(await this.http.get(at)).data;if(null==e)throw Xt("Health check answered no data");return e}}class vo extends Error{constructor(e,t,n){super(e),this.filename=t,this.mimeType=n,this.name="FileValidationError"}}function Ao(e,t,n){if(null==e)throw new vo("File is required",t,n);if("undefined"!=typeof File&&e instanceof File){const t=Qs.safeParse(e);if(!t.success){const n=t.error.issues.map(e=>e.message).join("; ");throw new vo(n,e.name,e.type)}return}if(Buffer.isBuffer(e)){if(void 0===t||""===t)throw new vo("Filename is required when uploading Buffer objects",t,n);const s=Xs.safeParse(e);if(!s.success){const e=s.error.issues.map(e=>e.message).join("; ");throw new vo(e,t,n)}try{Vn(t,255,"filename")}catch(e){throw new vo(e.message,t,n)}const r=["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"];if(!r.includes(n))throw new vo(`Invalid file type "${n}" is not allowed. Allowed types: ${r.join(", ")}`,t,n);const i=function(e){if(null==e||""===e)return"";const t=e.lastIndexOf(".");if(-1===t)return"";return e.substring(t).toLowerCase()}(t),a=[".png",".jpg",".jpeg",".gif",".webp",".svg"];if(!a.includes(i))throw new vo(`File extension "${i}" is not allowed. Allowed extensions: ${a.join(", ")}`,t,n);const o=function(e){switch(e.toLowerCase()){case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";case".gif":return"image/gif";case".webp":return"image/webp";case".svg":return"image/svg+xml";default:return"application/octet-stream"}}(i);if(o!==n&&"application/octet-stream"!==o)throw new vo(`File extension "${i}" does not match MIME type "${n}"`,t,n);return}throw new vo("File must be a File object (browser) or Buffer (Node.js)",t,n)}function Eo(e,t="image",n){const s=new FormData;if("undefined"!=typeof File&&e instanceof File)s.append(t,e);else{if(!Buffer.isBuffer(e))throw Qt("file","a File object (browser) or Buffer (Node.js)");{const r=new Blob([e],{type:"image/png"});s.append(t,r,n)}}return s}class yo extends ls{constructor(e,t,n=!1){super(e,n,t)}async uploadImageByTokenName(e){const{tokenName:t,options:n}=e;ns(t,"tokenName",ms);const s=`${t}.png`;Ao(n.file,s,"image/png");try{const e=Eo(n.file,"image",s),r=await dn(()=>this.http.request({method:"POST",url:di(R.UPLOAD_IMAGE,{tokenName:t}),data:e,headers:this.getJwtHeaders()}),{errorContext:"Image upload failed"});return"string"==typeof r?r:""}catch(e){if(e instanceof xt)throw e;if(Bt(e)&&$t(e).includes("FormData"))throw Jt("File upload failed: FormData not supported in this environment. Ensure you have proper polyfills for Node.js environments.","FormData");throw e}}}function To(e){if(Yn(e)||"object"!=typeof e)return{};const t={};for(const[n,s]of Object.entries(e))Yn(s)||(Jn(s)?t[n]=s:"number"==typeof s||"boolean"==typeof s?t[n]=s.toString():Array.isArray(s)?t[n]=s.join(","):t[n]="object"==typeof s?JSON.stringify(s):String(s));return t}function So(e,t){if(null==e)return[];if(Array.isArray(e))return e;const n=e[t];return Array.isArray(n)?n:[]}function bo(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.owner&&""!==t.owner}function ko(e){return"string"==typeof e.quantity&&""!==e.quantity}class wo extends ls{constructor(e,t,n=!1){super(e,n,t)}async fetchPools(e={}){const t=function(e){const t=e.pageSize??si.DEFAULT_LIMIT;if(!Number.isInteger(t)||t<1||t>bt)throw Zt("pageSize",1,bt,t);const n={pageSize:String(t)};Jn(e.cursor)&&(n.cursor=e.cursor);void 0!==e.type&&(n.type=Co("type",e.type,Tt));Jn(e.tokenName)&&(ns(e.tokenName,"tokenName",gs),n.tokenName=e.tokenName);if(Jn(e.search)){if(e.search.length>No)throw function(e,t,n,s){const r=qt(e,s);return new Ot(`${r} must be at most ${t} characters${void 0!==n?`, received: ${n}`:""}`,e,"TOO_LONG")}("search",No,e.search.length);n.search=e.search}!0===e.hasUpcomingShows&&(n.hasUpcomingShows="true");if(Jn(e.language)){if(!_o.test(e.language))throw Qt("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>Io)throw Zt("recentlyStreamed",1,Io,t);n.recentlyStreamed=String(t)}!0===e.hasRecordings&&(n.hasRecordings="true");void 0!==e.streamStatus&&(n.streamStatus=Co("streamStatus",e.streamStatus,St));if(void 0!==e.isGraduated){if("boolean"!=typeof e.isGraduated)throw nn("isGraduated","boolean",e.isGraduated);n.isGraduated=e.isGraduated?"true":"false"}void 0!==e.creatorAddress&&(n.creatorAddress=function(e){if("string"!=typeof e)throw nn("creatorAddress","string",e);return Pn(e,"creatorAddress"),xn(e)??e}(e.creatorAddress));return n}(e),n=cn(await hn(()=>this.http.get(R.FETCH_POOLS,t),{errorContext:"Failed to fetch pools"}));return{items:function(e){if(!e)return[];let t=[];if(e.tokens)if(Array.isArray(e.tokens))t=e.tokens.map(e=>({...e,createdAt:e.created_at??e.createdAt??""}));else{const n=e.tokens;t=[{...n,createdAt:n.created_at??n.createdAt??""}]}else null!==e.pools&&void 0!==e.pools&&Array.isArray(e.pools)&&(t=e.pools.map(e=>({...e,createdAt:e.created_at??e.createdAt??""})));return t}(n),pageInfo:ii(n?.pageInfo)}}async fetchAllPools(e){const t=[];let n;for(;;){const s={...e,pageSize:100,...void 0!==n&&{cursor:n}},r=await this.fetchPools(s);if(t.push(...r.items),0===r.items.length)break;const i=ai(r.pageInfo,n);if(void 0===i)break;n=i}return{items:t,pageInfo:{hasNextPage:!1,totalCount:t.length}}}async checkPool(e){!function(e){const t=mr(e);!t.success&&t.errors&&Or(t.errors,"options")}(e),Jn(e.tokenName)&&ns(e.tokenName,"tokenName",fs);try{const t=await this.http.post(R.VALIDATE_TOKEN,{tokenName:e.tokenName,symbol:e.symbol});if(null==t)throw new Error("Invalid response from check pool endpoint");const n=t.data??t;if(null==n)throw new Error("Invalid response from check pool endpoint");if(!0===Jn(e.symbol)){return!n.symbolAvailable}if(!0===Jn(e.tokenName)){return!n.nameAvailable}return!1}catch(e){const t=String(e),n=e,s="string"==typeof n.message?n.message:"";if(t.includes("404")||t.includes("Pool not found")||s.includes("404")||s.includes("Pool not found"))return!1;const r="number"==typeof n.statusCode?n.statusCode:null;if(404===r)return!1;if(t.includes("400")||t.includes("Missing required pool identifier")||s.includes("400")||s.includes("Missing required pool identifier"))return!1;if(400===r&&s.includes("Missing required pool identifier"))return!1;throw e}}async isTokenNameAvailable(e){try{return!await this.checkPool({tokenName:e})}catch{return!1}}async isTokenSymbolAvailable(e){try{return!await this.checkPool({symbol:e})}catch{return!1}}async fetchVolumeData(e){if(!function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return pr(t,"tokenName")&&Ar(t,"from")&&Ar(t,"to")&&Ar(t,"resolution")}(e))throw new Ot("Invalid options provided. Expected { tokenName: string, from?: number, to?: number, resolution?: number }","options","INVALID_OPTIONS");const{tokenName:t,from:n,to:s,resolution:r}=e;if(ns(t,"tokenName",gs),null==n||null==s||null==r)throw new Ot("Graph options (from, to, resolution) are required","options","MISSING_GRAPH_OPTIONS");const i={tokenName:t,from:n,to:s,resolution:r};Ur(i);const a=To(i),o=await dn(()=>this.http.get(R.CHART,a),{errorContext:"Failed to fetch graph data"});if(!Array.isArray(o.data)||"boolean"!=typeof o.isPreviousData)throw new Lt("Invalid chart response: expected { data: candles, isPreviousData }");return{dataPoints:o.data,isPreviousData:o.isPreviousData,..."number"==typeof o.nextTime&&{nextTime:o.nextTime}}}async fetchTokenDistribution(e){if(""===e||null==e)throw zt("tokenName","Token name");let t;ns(e,"tokenName",gs);try{t=await hn(()=>this.http.get(`${R.GET_TOKEN_DISTRIBUTION}?tokenName=${e}`),{errorContext:"Failed to fetch token distribution"})}catch(t){if(Wt(t)&&500===t.response?.status)throw Xt(`Token distribution data temporarily unavailable for ${e}. This is a backend issue - please try again later.`,500,Bt(t)?t:void 0);throw t}return function(e,t,n=br){if(!Array.isArray(e))throw Xt("Invalid API response: expected array of holders",t);for(const n of e){if(!bo(n))throw Xt("Invalid holder data: missing or invalid owner field",t);if(!ko(n))throw Xt("Invalid holder data: missing or invalid quantity field",t);const e=Gn(n.quantity,NaN);if(isNaN(e)||!isFinite(e))throw Xt(`Invalid holder quantity: "${n.quantity}"`,t)}const s=e,r=s.reduce((e,t)=>e.plus(t.quantity),Sr(0));return{holders:s.map(e=>({address:e.owner,balance:e.quantity,percentage:Ir(Sr(e.quantity),r,Sr(0)).multipliedBy(100).toNumber()})),totalSupply:n(r),totalHolders:s.length,lastUpdated:new Date}}(cn(t),t.status,e=>e.toFixed())}async fetchUserHolderContext(e,t){if(""===e||null==e)throw zt("tokenName","Token name");if(""===t||null==t)throw zt("userAddress","User address");return ns(e,"tokenName",gs),dn(()=>this.http.get(`${R.GET_TOKEN_DISTRIBUTION}?tokenName=${e}`,{userAddress:Nn(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");ns(e,"tokenName",ms);try{const t=R.GET_TOKEN.replace(":tokenName",e.toLowerCase().trim()),n=cn(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 Lt?new Lt(`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&&ns(e.tokenName,"tokenName",fs);try{const t=await this.http.post(R.VALIDATE_TOKEN,{tokenName:e.tokenName?.toLowerCase().trim(),symbol:e.symbol?.toUpperCase().trim()});if(null==t)throw new Error("Invalid response from validation endpoint");const n=t.data??t;if(null==n)throw new Error("Invalid response from validation endpoint");return n}catch(e){throw this.logger.warn(`Token validation failed: ${String(e)}`),e}}async fetchTokenStats(e){if(!Jn(e))throw zt("tokenName","Token name");ns(e,"tokenName",ms);const t=R.TOKEN_STATS.replace(":tokenName",e.toLowerCase().trim());try{const e=cn(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 zt("tokenName","Token name");ns(e,"tokenName",ms),function(e){if(void 0===e.chatEnabled&&void 0===e.commentsEnabled&&void 0===e.streamingEnabled&&void 0===e.nextLiveStreamAt&&void 0===e.streamLanguage&&void 0===e.websiteUrl&&void 0===e.telegramUrl&&void 0===e.twitterUrl&&void 0===e.instagramUrl&&void 0===e.facebookUrl&&void 0===e.redditUrl&&void 0===e.tiktokUrl)throw new Ot("At least one config option must be provided (chatEnabled, commentsEnabled, streamingEnabled, nextLiveStreamAt, streamLanguage, or social URLs)","options",kt);if(void 0!==e.chatEnabled&&"boolean"!=typeof e.chatEnabled)throw nn("chatEnabled","boolean");if(void 0!==e.commentsEnabled&&"boolean"!=typeof e.commentsEnabled)throw nn("commentsEnabled","boolean");if(void 0!==e.streamingEnabled&&"boolean"!=typeof e.streamingEnabled)throw nn("streamingEnabled","boolean");if(void 0!==e.streamLanguage&&"string"!=typeof e.streamLanguage)throw nn("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 nn(n,"string or null")}if(void 0!==e.nextLiveStreamAt&&null!==e.nextLiveStreamAt){if("string"!=typeof e.nextLiveStreamAt)throw nn("nextLiveStreamAt","string or null");const t=new Date(e.nextLiveStreamAt);if(isNaN(t.getTime()))throw new Ot("nextLiveStreamAt must be a valid ISO date string","nextLiveStreamAt",It)}}(t);const n=R.UPDATE_TOKEN_CONFIG.replace(":tokenName",e.toLowerCase().trim()),s={};void 0!==t.chatEnabled&&(s.chatEnabled=t.chatEnabled),void 0!==t.commentsEnabled&&(s.commentsEnabled=t.commentsEnabled),void 0!==t.streamingEnabled&&(s.streamingEnabled=t.streamingEnabled),void 0!==t.nextLiveStreamAt&&(s.nextLiveStreamAt=t.nextLiveStreamAt),void 0!==t.streamLanguage&&(s.streamLanguage=t.streamLanguage),void 0!==t.websiteUrl&&(s.websiteUrl=t.websiteUrl),void 0!==t.telegramUrl&&(s.telegramUrl=t.telegramUrl),void 0!==t.twitterUrl&&(s.twitterUrl=t.twitterUrl),void 0!==t.instagramUrl&&(s.instagramUrl=t.instagramUrl),void 0!==t.facebookUrl&&(s.facebookUrl=t.facebookUrl),void 0!==t.redditUrl&&(s.redditUrl=t.redditUrl),void 0!==t.tiktokUrl&&(s.tiktokUrl=t.tiktokUrl),await this.http.patch(n,s,this.getJwtHeaders())}async getTokenConfig(e){if(!Jn(e))throw zt("tokenName","Token name");ns(e,"tokenName",ms);const t=R.UPDATE_TOKEN_CONFIG.replace(":tokenName",e.toLowerCase().trim()),n=cn(await this.http.get(t));if(void 0===n)throw new Error(`Invalid response: missing token config data for "${e}"`);return n}}const No=255,Io=720,_o=/^[a-z]{2}(-[A-Z]{2})?$/u;function Co(e,t,n){const s="string"==typeof t?t.toUpperCase():void 0,r=n.find(e=>e===s);if(void 0===r)throw rn(e,t,n);return r}function Do(e){if(void 0!==e.tokenName){if(!Jn(e.tokenName))throw nn("tokenName","a non-empty string",typeof e.tokenName);ss(e.tokenName,"tokenName",gs)}if(void 0!==e.userAddress){if(!Jn(e.userAddress))throw nn("userAddress","a non-empty string",typeof e.userAddress);if(e.userAddress.length>ys)throw tn("userAddress",ys,e.userAddress.length)}if(void 0!==e.search){if("string"!=typeof e.search)throw nn("search","a string",typeof e.search);if(e.search.length>256)throw tn("search",256,e.search.length)}if(Zn(0,void 0,Es,e.pageSize),void 0!==e.txnType&&"BUY"!==e.txnType&&"SELL"!==e.txnType)throw Qt("txnType",'"BUY" or "SELL"');if(void 0!==e.startDate){if(!Jn(e.startDate))throw nn("startDate","a non-empty string",typeof e.startDate);if(isNaN(Date.parse(e.startDate)))throw Qt("startDate","a valid ISO 8601 date")}if(void 0!==e.endDate){if(!Jn(e.endDate))throw nn("endDate","a non-empty string",typeof e.endDate);if(isNaN(Date.parse(e.endDate)))throw Qt("endDate","a valid ISO 8601 date")}if(void 0!==e.minAmount)try{qn(e.minAmount,0,Number.MAX_SAFE_INTEGER,"minAmount")}catch{throw Qt("minAmount","a non-negative number")}if(void 0!==e.maxAmount)try{qn(e.maxAmount,0,Number.MAX_SAFE_INTEGER,"maxAmount")}catch{throw Qt("maxAmount","a non-negative number")}void 0!==e.minAmount&&void 0!==e.maxAmount&&function(e,t,n="range"){const s="number"==typeof e?e:Number(e),r="number"==typeof t?t:Number(t);if(isNaN(s)||isNaN(r))throw nn(n,"numeric values",void 0,n);if(s>r)throw new Ot(`Minimum value (${s}) must be less than or equal to maximum value (${r}) for ${n}`,n,Dt)}(e.minAmount,e.maxAmount,"amountRange")}class Ro extends ls{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 pr(t,"tokenName")&&(void 0===t.tradeType||"buy"===t.tradeType||"sell"===t.tradeType)&&vr(t,"userAddress")&&Ar(t,"offset")&&Ar(t,"pageSize")&&Ar(t,"page")&&Ar(t,"limit")}(e))throw new Ot("Invalid options provided. Expected { tokenName: string, tradeType?: string, userAddress?: string, cursor?: string, pageSize?: number, startDate?: Date, endDate?: Date, sortOrder?: string }","options","INVALID_OPTIONS");const{tokenName:t,cursor:n,pageSize:s=si.DEFAULT_LIMIT}=e;if(!Jn(t))throw zt("tokenName","Token name");const r={pageSize:String(Math.min(s,As))};void 0!==n&&(r.cursor=n);const i=await this.http.get(di(R.GET_TRADES,{tokenName:t}),r);if(null==i)throw new Ot("No response from trade service","response","NO_RESPONSE");const a=cn(i),o=So(a,"trades"),c=a?.pageInfo;return{items:o,pageInfo:c??{hasNextPage:!1}}}buildTradesQueryParams(e){const t={};null!==e.tokenName&&void 0!==e.tokenName&&e.tokenName.length>0&&(t.tokenName=fn(e.tokenName)),null!==e.userAddress&&void 0!==e.userAddress&&e.userAddress.length>0&&(t.userAddress=Nn(e.userAddress,"userAddress")),null!==e.search&&void 0!==e.search&&e.search.length>0&&(t.search=e.search);const n=void 0!==e.pageSize?function(e,t=1,n=si.BACKEND_MAX_PAGE_SIZE){return Math.max(t,Math.min(n,Math.ceil(e??t)))}(e.pageSize,1,Es):Es;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){Do(e);const t=this.buildTradesQueryParams(e);return dn(()=>this.http.get(Xe,t),{errorContext:"Failed to fetch trades"})}}ms.MIN_LENGTH,ms.MAX_LENGTH;function Oo(e){return Jn(e)&&Dn(e)}function Mo(e,t,n=1){if(null==e||""===e)return null;if("string"!=typeof e)return null;const s=e.trim();return s.length<n?null:s}es({BOTH:"both",HELD:"held",CREATED:"created"});function Uo(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Fo(e){return"number"==typeof e&&Number.isFinite(e)}function Lo(e){return null===e||"string"==typeof e}function xo(e){return Array.isArray(e)&&e.every(e=>Uo(e)&&"string"==typeof e.badgeName&&"boolean"==typeof e.isActive)}function Po(e){return Uo(e)&&"string"==typeof e.address&&Lo(e.fullName)&&Lo(e.profileImage)&&Lo(e.bio)&&function(e){return Uo(e)&&Fo(e.tokensCreated)&&Fo(e.tokensGraduated)&&Fo(e.graduationRate)&&Fo(e.totalTrades)&&"string"==typeof e.totalVolumeGala&&Lo(e.totalVolumeUsd)&&(null===e.holdingsCount||Fo(e.holdingsCount))&&Lo(e.accountCreatedAt)&&Fo(e.accountAgeDays)}(e.stats)&&xo(e.launchBadge)&&xo(e.successBadge)&&xo(e.volumeBadge)&&xo(e.engagementBadge)&&"boolean"==typeof e.isLiveStreaming&&Lo(e.liveStreamToken)}class Bo extends ls{constructor(e,t,n=!1){super(e,n,t)}async fetchProfile(e){const t=e??this.http.getAddress();if(""===t||null==t||!Oo(t))throw Qt("address","eth|[40-hex-chars] or client|[identifier]","Address");if(void 0===e){const e=await dn(()=>this.http.get(R.GET_CURRENT_USER,void 0,this.getJwtHeaders()),{errorContext:"Failed to fetch profile"});if(!(Uo(n=e)&&"string"==typeof n.address&&Lo(n.fullName)&&Lo(n.profileImage)&&"string"==typeof n.bio&&xo(n.launchBadge)&&xo(n.successBadge)))throw Xt("Malformed profile response");return e}var n;const s=await dn(()=>this.http.get(R.GET_PROFILE.replace(":address",Nn(t,"address"))),{errorContext:"Failed to fetch profile"});if(!Po(s))throw Xt("Malformed profile response");return s}async updateProfile(e){this.validateUpdateProfileData(e);const t={};void 0!==e.fullName&&(t.fullName=e.fullName.trim()),void 0!==e.profileImage&&(t.profileImage=e.profileImage),await dn(()=>this.http.put(R.UPDATE_PROFILE,t,this.getJwtHeaders()),{errorContext:"Profile update failed"})}async uploadProfileImage(e){this.validateUploadProfileImageOptions(e);try{const t=void 0===e.address?"profile-image.png":`profile-image-${e.address}.png`,n=Eo(e.file,"image",t),s=await dn(()=>this.http.request({method:"POST",url:R.UPLOAD_PROFILE_IMAGE,data:n,headers:this.getJwtHeaders()}),{errorContext:"Image upload failed"});return"string"==typeof s?s:""}catch(e){if(e instanceof Ot||e instanceof xt)throw e;if(e instanceof Lt)throw new Lt(`Profile image upload failed: ${$t(e)}`,e.statusCode,e);throw new Ot(`Profile image upload failed: ${$t(e)}`,"file","UPLOAD_FAILED")}}async fetchTokenList(e){if(void 0!==e.status&&"created"!==e.type)throw new Ot("status filters only apply when type=created","status","INVALID_FILTER");const t=e.tokenName,n={...e},s="created"===e.type;s&&(delete n.tokenName,void 0!==t&&void 0===n.search&&(n.search=t));const r=await this.buildFetchRequest(R.GET_TOKEN_LIST,n,{includeType:!0,requestType:e.type??"both",responseKey:s?"launches":"token",errorMessage:"Failed to fetch token list"});return s&&void 0!==t?{...r,tokens:r.tokens.filter(e=>e.tokenName===t||e.name===t)}:r}async fetchTokensHeld(e){if(void 0!==e.type&&"held"!==e.type)throw new Ot("fetchTokensHeld only supports type=held","type","INVALID_TYPE");if(void 0!==e.status)throw new Ot("status filters only apply when type=created","status","INVALID_FILTER");return this.buildFetchRequest(R.GET_TOKENS_HELD,e,{includeType:!0,requestType:"held",responseKey:"token",errorMessage:"Failed to fetch tokens held"})}async fetchTokensCreated(e){const{cursor:t,pageSize:n,search:s,tokenName:r,status:i}=e??{};if(void 0!==e?.type&&"created"!==e.type)throw new Ot("fetchTokensCreated only supports type=created","type","INVALID_TYPE");const a=e?.address??this.http.getAddress();if(null==a||""===a)throw new Ot("Wallet address not available - wallet not configured","address","NO_WALLET");const o={type:"created",address:a,pageSize:n??si.DEFAULT_LIMIT};return void 0!==t&&(o.cursor=t),void 0!==s&&(o.search=s),void 0!==r&&void 0===s&&(o.search=r),void 0!==r&&(o.tokenName=r),void 0!==i&&(o.status=i),this.fetchTokenList(o)}async getManagedTokens(e={}){const t={};return void 0!==e.cursor&&(t.cursor=e.cursor),void 0!==e.pageSize&&(t.pageSize=String(Math.min(e.pageSize,As))),dn(()=>this.http.get(R.GET_MANAGED_TOKENS,t,this.getJwtHeaders()),{errorContext:"Failed to fetch managed tokens"})}async getUserGalaBalance(e){if("string"!=typeof e||""===e.trim())throw zt("address","Address");const t=Nn(e.trim(),"address");return dn(()=>this.http.get(di(R.GET_GALA_BALANCE,{address:t})),{errorContext:"Failed to fetch GALA balance"})}async fetchReferralCode(){return dn(()=>this.http.get(R.GET_REFERRAL_CODE,void 0,this.getJwtHeaders()),{errorContext:"Failed to fetch referral code"})}async buildFetchRequest(e,t,n){this.validateGetTokenListOptions(t);const s=ci({pageSize:t.pageSize??si.DEFAULT_LIMIT,...void 0!==t.cursor&&{cursor:t.cursor}},As);ui(s,t,["address","search","tokenName","status"]),n.includeType&&!e.includes("?type=")&&(s.type=n.requestType);let r=e;const i=Nn(t.address??this.http.getAddress(),"address");if(void 0!==t.address&&(s.address=i),e.includes(":address")){if(0===i.length)throw zt("address","User address");r=e.replace(":address",i),delete s.address}const a=cn(await hn(()=>this.http.get(r,s),{errorContext:n.errorMessage}));return{tokens:So(a,n.responseKey).map(e=>{const t="string"==typeof e.tokenName?e.tokenName:"",s="string"==typeof e.name?e.name:t,r="string"==typeof e.createdAt?e.createdAt:"",a=e.metadata,o={...e};return delete o.metadata,{...o,id:"string"==typeof e.id?e.id:t,name:s,symbol:"string"==typeof e.symbol?e.symbol:"",type:n.requestType,address:i,balance:"string"==typeof e.balance?e.balance:"string"==typeof e.quantity?e.quantity:"0",decimals:"number"==typeof e.decimals?e.decimals:0,...null!==a&&"object"==typeof a?{metadata:a}:{},createdAt:r,updatedAt:"string"==typeof e.updatedAt?e.updatedAt:r}}),pageInfo:ii(a?.pageInfo)}}validateGetTokenListOptions(e){const t=e.pageSize??si.DEFAULT_LIMIT;if(t<1||t>As)throw new Ot(`pageSize must be between 1 and ${As}`,"pageSize","OUT_OF_RANGE");if(void 0!==e.address&&!Oo(e.address))throw Qt("address","eth|[40-hex-chars] or client|[identifier]","Address");const n=Mo(e.search);if(null!==n&&!(Jn(s=n)&&s.length>=Is&&s.length<=_s))throw Zt("search",Is,_s,n.length,"Search query");var s;const r=Mo(e.tokenName);if(!(null===r||Jn(i=r)&&ms.PATTERN.test(i)))throw Qt("tokenName",ms.DESCRIPTION,"Token name");var i}validateUpdateProfileData(e){if(void 0!==e.address&&!Oo(e.address))throw Qt("address","eth|[40-hex-chars] or client|[identifier]","Address");if(void 0===e.fullName&&void 0===e.profileImage)throw new Ot("At least one of fullName and profileImage must be provided","options","REQUIRED");if(void 0!==e.fullName&&(t=e.fullName.trim(),!(Jn(t)&&t.length>=Cs.FULL_NAME.MIN_LENGTH&&t.length<=Cs.FULL_NAME.MAX_LENGTH&&Cs.FULL_NAME.ALPHABETS_ONLY_PATTERN.test(t))))throw Zt("fullName",Cs.FULL_NAME.MIN_LENGTH,Cs.FULL_NAME.MAX_LENGTH,e.fullName.trim().length,"Full name");var t;if("string"==typeof e.profileImage&&e.profileImage.trim().length>2048)throw new Ot("profileImage must not exceed 2048 characters","profileImage","TOO_LONG")}validateUploadProfileImageOptions(e){if(void 0!==e.address&&!Oo(e.address))throw Qt("address","eth|[40-hex-chars] or client|[identifier]","Address")}}class $o{constructor(e,t,n=!1){this.http=e,this.poolService=new wo(e,t,n),this.tradeService=new Ro(e,n),this.userService=new Bo(e,t,n),this.imageService=new yo(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 Mr(e)}async fetchToken(e){return this.poolService.fetchToken(e)}async validateToken(e){return this.poolService.validateToken(e)}async fetchTokenStats(e){return this.poolService.fetchTokenStats(e)}async updateTokenConfig(e,t){return this.poolService.updateTokenConfig(e,t)}async getTokenConfig(e){return this.poolService.getTokenConfig(e)}}const Go={CHAT_MESSAGE:"CHAT_MESSAGE",COMMENT:"COMMENT"};class Ko extends gi{constructor(e,t,n,s=!1,r){super(e,t,n,s,r)}validateContent(e,t){if(!Jn(e))throw zt("content","Message content");if(0===e.trim().length)throw zt("content","Message content");Vn(e,t===Go.CHAT_MESSAGE?Ts.CHAT_MESSAGES_V1.MAX_LENGTH:Ts.COMMENTS_V1.MAX_LENGTH,"content")}validateMessageId(e){if(!Jn(e))throw zt("id","Message ID");if(e.length<10||e.length>64)throw Qt("id","valid message ID format","Message ID")}validateMessageType(e){if(e!==Go.CHAT_MESSAGE&&e!==Go.COMMENT)throw new Ot(`type must be one of: ${Object.values(Go).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,gs);const s={};void 0!==e.cursor&&(s.cursor=e.cursor),s.pageSize=e.pageSize??si.DEFAULT_LIMIT;const r=ci(s,Es),i={};void 0!==r.pageSize&&(i.pageSize=r.pageSize),void 0!==r.cursor&&(i.cursor=r.cursor),t&&(i.type=e.type.toUpperCase()),n&&(i.tokenName=fn(e.tokenName)),void 0!==e.userAddress&&""!==e.userAddress&&(i.userAddress=Nn(e.userAddress,"userAddress")),void 0!==e.search&&""!==e.search&&(i.search=e.search);const a=await this.http.get(Je.GET_MESSAGES,i),o=this.extractData(a);return{messages:o.messages,pageInfo:o.pageInfo}}async createMessage(e){this.validateMessageType(e.type),this.validateTokenName(e.tokenName,gs),this.validateContent(e.content,e.type);const t={type:e.type,tokenName:fn(e.tokenName),content:e.content.trim()},n=await this.http.post(Je.CREATE_MESSAGE,t,this.getJwtHeaders());return{message:this.extractData(n)}}async updateMessage(e,t){this.validateMessageId(e),this.validateContent(t.content,t.type);const n=this.buildEndpointWithId(Je.UPDATE_MESSAGE,e),s={content:t.content.trim()},r=await this.http.put(n,s,this.getJwtHeaders());return{message:this.extractData(r)}}async deleteMessage(e){this.validateMessageId(e);const t=this.buildEndpointWithId(Je.DELETE_MESSAGE,e);return await this.http.delete(t,void 0,this.getDualAuthHeaders()),{success:!0}}async getPinnedMessage(e){this.validateTokenName(e,ms);const t=await this.http.get(Je.GET_PINNED,{tokenName:fn(e)});return{message:this.extractDataOrNull(t)}}async pinMessage(e){this.validateMessageId(e);const t=Je.PIN_MESSAGE.replace(":id",e);return await this.http.post(t,{},this.getDualAuthHeaders()),{success:!0}}async unpinMessage(e){this.validateMessageId(e);const t=Je.UNPIN_MESSAGE.replace(":id",e);return await this.http.delete(t,void 0,this.getDualAuthHeaders()),{success:!0}}async getMessageStats(){return function(e){const t=e=>"number"==typeof e&&Number.isFinite(e),n=e=>"object"==typeof e&&null!==e&&!Array.isArray(e);if(!n(e))throw Xt("Malformed message statistics response");const s=e.totalMessages,r=e.todayMessages,i=e.uniqueUsers,a=e.uniqueTokens,o=e.messagesByType;if(!(t(s)&&t(r)&&t(i)&&t(a)&&n(o)))throw Xt("Malformed message statistics response");const c={};for(const[e,n]of Object.entries(o)){if(!t(n))throw Xt("Malformed message statistics response");c[e]=n}return{totalMessages:s,todayMessages:r,uniqueUsers:i,uniqueTokens:a,messagesByType:c}}(await this.http.get(Je.GET_MESSAGE_STATS,void 0,this.getDualAuthHeaders()))}}const Wo=ts({MODERATOR:"MODERATOR",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MANAGER:"MANAGER"}),Ho={TOKEN:"TOKEN",ALL_OWNER_TOKENS:"ALL_OWNER_TOKENS"},jo=ts(Ho),qo={PENDING:"PENDING",CLAIMED:"CLAIMED",REVOKED:"REVOKED",EXPIRED:"EXPIRED"};ts(qo);class Vo extends gi{constructor(e,t,n,s=!1,r){super(e,t,n,s,r)}validateRole(e){if(!Jn(e))throw zt("role","Role");if(!function(e){return Wo.includes(e)}(e))throw Qt("role",`one of: ${Wo.join(", ")}`,"Role")}validateInviteCodeFormat(e){if(!Jn(e))throw zt("inviteCode","Invite code");if(e.length>Ns)throw Qt("inviteCode",`at most ${String(Ns)} characters`,"Invite code")}validateInviteScope(e){if(void 0!==e&&(t=e,!jo.includes(t)))throw new Ot(`Invalid invite scope. Must be one of: ${jo.join(", ")}`,"inviteScope","INVALID_VALUE");var t}async createInvite(e){this.validateInviteScope(e.inviteScope);const t=e.inviteScope??Ho.TOKEN;if(t===Ho.TOKEN){if(void 0===e.tokenName||""===e.tokenName)throw new Ot("Token name is required for TOKEN scope invites","tokenName","REQUIRED");this.validateTokenName(e.tokenName,gs)}else if(t===Ho.ALL_OWNER_TOKENS&&e.tokenName)throw new Ot("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",Ts.DESCRIPTION.MAX_LENGTH),this.validateOptionalDate(e.expiresAt,"expiresAt","Expiration date");const n=ge,s={inviteScope:t,role:e.role};t===Ho.TOKEN&&null!==e.tokenName&&void 0!==e.tokenName&&""!==e.tokenName&&(s.tokenName=fn(e.tokenName)),void 0!==e.description&&(s.description=e.description),void 0!==e.expiresAt&&(s.expiresAt=e.expiresAt);const r=await this.http.post(n,s,this.getMultiAuthHeaders());return{invite:this.extractData(r)}}async listInvites(e){void 0!==e.tokenName&&""!==e.tokenName&&this.validateTokenName(e.tokenName,gs),this.validateStatusFilter(e.status,qo);const t=pe,n={...this.buildPaginationParams(e,Es)};void 0!==e.tokenName&&""!==e.tokenName&&(n.tokenName=fn(e.tokenName)),void 0!==e.status&&(n.status=e.status);const s=await this.http.get(t,n,this.getMultiAuthHeaders()),r=this.extractData(s);return{items:r.invites,pageInfo:r.pageInfo}}async revokeInvite(e){this.validatePositiveInteger(e,"inviteId","Invite ID");const t=this.buildEndpoint(ve,{id:String(e)});on(await this.http.delete(t,void 0,this.getMultiAuthHeaders()),"Failed to revoke invite")}async updateInviteRole(e){this.validatePositiveInteger(e.inviteId,"inviteId","Invite ID"),this.validateRole(e.role);const t=this.buildEndpoint(Ae,{id:String(e.inviteId)}),n={role:e.role},s=await this.http.patch(t,n,this.getMultiAuthHeaders());return{invite:this.extractData(s)}}async updateInvite(e){if(this.validatePositiveInteger(e.inviteId,"inviteId","Invite ID"),void 0===e.role&&void 0===e.description)throw new Ot("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",Ts.DESCRIPTION.MAX_LENGTH);const t=this.buildEndpoint(Ee,{id:String(e.inviteId)}),n={};void 0!==e.role&&(n.role=e.role),void 0!==e.description&&(n.description=e.description);const s=await this.http.patch(t,n,this.getMultiAuthHeaders());return{invite:this.extractData(s)}}async claimInvite(e){this.validateInviteCodeFormat(e.inviteCode);const t=me,n={inviteCode:e.inviteCode},s=await this.http.post(t,n,this.getMultiAuthHeaders()),r=this.extractData(s);return"tokenName"in r&&void 0!==r.tokenName?{token:r}:{blanketAccess:r}}async getModeratedTokens(e){const t=fe,n=this.buildPaginationParams(e??{},Es),s=await this.http.get(t,n,this.getMultiAuthHeaders()),r=this.extractData(s);return{items:r.tokens,pageInfo:r.pageInfo}}async getInviteByCode(e){this.validateInviteCodeFormat(e);const t=this.buildEndpoint(ye,{code:e}),n=await this.http.get(t,{});return this.extractData(n)}}const zo="10000",Qo="1000";function Xo(e){return`${e}-${Date.now()}-${Math.random().toString(36).substring(2,11)}`}function Jo(){return Date.now()+6e4}function Yo(e){return""!==e&&"string"==typeof e&&/^[a-zA-Z0-9]{3,50}$/.test(e)}function Zo(e){try{return Math.floor(parseFloat(String(e))??0).toString()}catch{return"0"}}function ec(e){return""!==e&&"string"==typeof e&&Dn(e)}class tc extends ls{constructor(e){super(e)}getCollectionClaimFee(){return zo}getTokenClassCreateFee(){return Qo}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(!ec(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=zo;n.collectionClaim=e,t=String(BigInt(t)+BigInt(e))}if((e.createTokenClasses??0)>0){const s=Qo,r=String(BigInt(s)*BigInt(e.createTokenClasses));n.tokenClassCreate=s,n.tokenClassCount=e.createTokenClasses,t=String(BigInt(t)+BigInt(r))}return{totalFee:t,breakdown:n}}async claimCollection(e){try{if(this.logger.debug("Claiming NFT collection",e.collectionName),!Yo(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:Jo(),uniqueKey:Xo("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),!ec(e))throw new Error(`Invalid wallet address format: ${e}`);const t=(await this.allAuthorizations()).filter(t=>t.authorizedUsers.some(t=>Cn(t,e))).map(t=>({authorizedUser:wn(e,"walletAddress"),collection:t.collection}));return this.logger.debug(`Found ${t.length} collections for user`),t}catch(e){throw this.logger.error("Failed to fetch user collections",e),e}}async isCollectionAvailable(e){try{if(this.logger.debug("Checking collection availability",e),!Yo(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(!Yo(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?Zo(e.maxSupply):void 0,maxCapacity:void 0!==e.maxCapacity?Zo(e.maxCapacity):void 0,additionalKey:e.additionalKey,expiresAt:Jo(),uniqueKey:Xo("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),!Yo(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(!ec(e.ownerAddress))throw new Error(`Invalid owner address: ${e.ownerAddress}`);const n=this.estimateMintFee({collection:e.collection,type:e.type,category:e.category,quantity:e.quantity,ownerAddress:e.ownerAddress});this.logger.debug("Estimated mint fee:",n);const s={collection:e.collection,type:e.type,category:e.category,quantity:e.quantity,owner:wn(e.ownerAddress,"ownerAddress"),additionalKey:e.additionalKey??"none",expiresAt:Jo(),uniqueKey:Xo("mint")};this.logger.debug("Built mint DTO",s);const r=`mint-${Date.now()}`,i=Array.from({length:t},(e,t)=>t+1);return{transactionId:r,mintedQuantity:e.quantity,owner:wn(e.ownerAddress,"ownerAddress"),tokenInstances:i,tokenClass:{collection:e.collection,type:e.type,category:e.category}}}catch(e){throw this.logger.error("Failed to mint NFT",e),e}}async fetchNftBalances(e,t){try{if(this.logger.debug("Fetching NFT balances for",{ownerAddress:e,collectionFilter:t}),!ec(e))throw new Error(`Invalid owner address: ${e}`);const n=(await this.reads().fetchNftBalances({owner:wn(e,"ownerAddress"),collection:t})).map(e=>({owner:e.owner,collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey,instanceIds:[...e.instanceIds],totalOwned:e.instanceIds.length}));return this.logger.debug(`Found ${n.length} NFT balances`),n}catch(e){throw this.logger.error("Failed to fetch NFT balances",e),e}}reads(){const{requestor:e}=Ua(async(e,t)=>({data:await this.http.post(e,t)}));return new p({gatewayBaseUrl:"",httpRequestor:e,requestTimeoutMs:1/0})}allAuthorizations(){return this.reads().fetchAllNftCollectionAuthorizations({pageSize:1e3})}}class nc extends ls{constructor(e,t=!1,n){super(e,t,n)}extractData(e){if(e.error||void 0===e.data){const t=e.message??"Notification operation failed";throw new Error(t)}return e.data}async registerPushToken(e){this.logger.debug("Registering push token",{platform:e.platform});const t=this.getJwtHeaders(),n=await this.http.post(mt,{token:e.token,platform:e.platform,...void 0!==e.deviceId?{deviceId:e.deviceId}:{}},t),s=this.extractData(n);return this.logger.debug("Push token registered",{registered:s.registered}),s}async unregisterPushToken(e){this.logger.debug("Unregistering push token");const t=this.getJwtHeaders(),n=await this.http.request({method:"DELETE",url:ft,data:{token:e},headers:t}),s=this.extractData(n);return this.logger.debug("Push token unregistered",{unregistered:s.unregistered}),s}async getPreferences(){this.logger.debug("Fetching notification preferences");const e=this.getJwtHeaders(),t=await this.http.get(pt,void 0,e),n=this.extractData(t);return this.logger.debug("Fetched notification preferences",{tradesEnabled:n.tradesEnabled,streamsEnabled:n.streamsEnabled}),{preferences:n}}async updatePreferences(e){this.logger.debug("Updating notification preferences",e);const t=this.getJwtHeaders(),n=await this.http.put(vt,e,t),s=this.extractData(n);return this.logger.debug("Updated notification preferences",{tradesEnabled:s.tradesEnabled,streamsEnabled:s.streamsEnabled}),{preferences:s}}}class sc extends ls{constructor(e,t=!1){super(e,t)}async getHomeOEmbedJson(e={}){this.logger.debug("Fetching home oEmbed (JSON)");const t=await this.http.get(R.OEMBED,{format:"json"});return this.logger.debug("Fetched home oEmbed (JSON)",{title:t.title}),{oembed:t}}async getHomeOEmbedHtml(e={}){this.logger.debug("Fetching home oEmbed (HTML)");const t=await this.http.get(R.OEMBED,{},{responseType:"text"});return this.logger.debug("Fetched home oEmbed (HTML)"),{html:t}}async getPoolOEmbedJson(e){const{tokenName:t}=e;if(null==t||"string"!=typeof t||""===t.trim())throw new Ot("tokenName is required","tokenName","REQUIRED_FIELD");this.logger.debug("Fetching pool oEmbed (JSON)",{tokenName:t});const n=R.OEMBED_BUY_SELL.replace(":tokenName",t.toLowerCase().trim()),s=await this.http.get(n,{format:"json"});return this.logger.debug("Fetched pool oEmbed (JSON)",{tokenName:t,title:s.title}),{oembed:s}}async getPoolOEmbedHtml(e){const{tokenName:t}=e;if(null==t||"string"!=typeof t||""===t.trim())throw new Ot("tokenName is required","tokenName","REQUIRED_FIELD");this.logger.debug("Fetching pool oEmbed (HTML)",{tokenName:t});const n=R.OEMBED_BUY_SELL.replace(":tokenName",t.toLowerCase().trim()),s=await this.http.get(n,{},{responseType:"text"});return this.logger.debug("Fetched pool oEmbed (HTML)",{tokenName:t}),{html:s}}async getProfileOEmbedJson(e){const{address:t}=e;if(null==t||"string"!=typeof t||""===t.trim())throw new Ot("address is required","address","REQUIRED_FIELD");this.logger.debug("Fetching profile oEmbed (JSON)",{address:t});const n=R.OEMBED_PROFILE.replace(":address",encodeURIComponent(Nn(t.trim(),"address"))),s=await this.http.get(n,{format:"json"});return this.logger.debug("Fetched profile oEmbed (JSON)",{address:t,title:s.title}),{oembed:s}}async getProfileOEmbedHtml(e){const{address:t}=e;if(null==t||"string"!=typeof t||""===t.trim())throw new Ot("address is required","address","REQUIRED_FIELD");this.logger.debug("Fetching profile oEmbed (HTML)",{address:t});const n=R.OEMBED_PROFILE.replace(":address",encodeURIComponent(Nn(t.trim(),"address"))),s=await this.http.get(n,{},{responseType:"text"});return this.logger.debug("Fetched profile oEmbed (HTML)",{address:t}),{html:s}}}function rc(e){if(!Jn(e))throw zt("address","Address");wn(e,"address")}const ic={PENDING:"PENDING",CLAIMED:"CLAIMED",REVOKED:"REVOKED",EXPIRED:"EXPIRED"},ac={ACTIVE:"ACTIVE",REVOKED:"REVOKED"},oc=es(ic),cc=es(ac);function lc(e){try{is(e.description,"description",255)}catch(e){if(e instanceof Ot){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(!Jn(e.expiresAt))throw new Error("expiresAt must be a non-empty string");try{as(e.expiresAt,"expiresAt")}catch(e){if(e instanceof Ot)throw new Error("expiresAt must be a valid ISO 8601 date string");throw e}if(bn(e.expiresAt)){if(function(e){if(null==e)return new Date;if(e instanceof Date)return isNaN(e.getTime())?new Date:e;try{const t=new Date(e);return isNaN(t.getTime())?(Sn.warn(`Invalid date string received: "${e}". Using fallback.`),new Date):t}catch(t){return Sn.warn(`Date parsing error for "${e}":`,t),new Date}}(e.expiresAt)<=new Date)throw new Error("expiresAt must be in the future")}}}function dc(e){if(!Jn(e))throw new Error("Address must be a non-empty string");try{Bn(e,"address")}catch{throw new Error("Invalid wallet address format. Must be eth|..., 0x..., or client|... format")}}function uc(e){try{zn(e,"id")}catch(e){if(e instanceof Ot)throw new Error("Invite ID must be a positive integer");throw e}}class hc extends gi{constructor(e,t,n,s=!1,r){super(e,t,n,s,r)}validateInviteCodeFormat(e){if(!Jn(e))throw zt("inviteCode","Invite code");!function(e){if(!Jn(e))throw new Error("Invite code must be a non-empty string");Vn(e,Ns,"code")}(e)}validateWalletAddressFormat(e){if(!Jn(e))throw zt("address","Address");dc(e)}async createInvite(e={}){lc(e),this.validateOptionalString(e.description,"description","Description",Ts.DESCRIPTION.MAX_LENGTH),this.validateOptionalDate(e.expiresAt,"expiresAt","Expiration date");const t=Se,n={};void 0!==e.description&&(n.description=e.description),void 0!==e.expiresAt&&(n.expiresAt=e.expiresAt);const s=await this.http.post(t,n,this.getDualAuthHeaders());return{invite:this.extractData(s)}}async listInvites(e={}){!function(e){if(void 0!==e.status&&!oc(e.status))throw rn("status",e.status,Object.values(ic),"status");Zn(0,void 0,50,e.pageSize,e.cursor)}(e),this.validateStatusFilter(e.status,ic);const t=be,n={...this.buildPaginationParams(e,Es)};void 0!==e.status&&(n.status=e.status);const s=await this.http.get(t,n,this.getDualAuthHeaders()),r=this.extractData(s);return{items:r.invites,pageInfo:r.pageInfo}}async getInviteByCode(e){this.validateInviteCodeFormat(e);const t=this.buildEndpoint(ke,{code:e}),n=await this.http.get(t,{});return this.extractData(n)}async revokeInvite(e){uc(e);const t=this.buildEndpoint(Ne,{id:String(e)});on(await this.http.delete(t,void 0,this.getDualAuthHeaders()),"Failed to revoke invite")}async claimInvite(e){this.validateInviteCodeFormat(e);const t=we,n={inviteCode:e},s=await this.http.post(t,n,this.getJwtHeaders());return{invite:this.extractData(s)}}async listOverseers(e={}){!function(e){if(void 0!==e.status&&!cc(e.status))throw rn("status",e.status,Object.values(ac),"status");Zn(0,void 0,50,e.pageSize,e.cursor)}(e),this.validateStatusFilter(e.status,ac);const t=Ie,n={...this.buildPaginationParams(e,Es)};void 0!==e.status&&(n.status=e.status);const s=await this.http.get(t,n,this.getDualAuthHeaders()),r=this.extractData(s);return{items:r.overseers,pageInfo:r.pageInfo}}async createOverseerDirect(e){!function(e){if(null==e||"object"!=typeof e)throw new Ot("Options are required");if(!Jn(e.userAddress))throw new Ot("userAddress is required and must be a non-empty string");try{Bn(e.userAddress,"userAddress")}catch{throw new Ot("Invalid wallet address format. Must be eth|..., 0x..., or client|... format")}if(void 0!==e.description){if("string"!=typeof e.description)throw new Ot("description must be a string");if(e.description.length>255)throw new Ot("description must be at most 255 characters")}}(e),this.validateWalletAddressFormat(e.userAddress),this.validateOptionalString(e.description,"description","Description",Ts.DESCRIPTION.MAX_LENGTH);const t=_e,n={userAddress:Nn(e.userAddress,"userAddress")};void 0!==e.description&&(n.description=e.description);const s=await this.http.post(t,n,this.getDualAuthHeaders());return{overseer:this.extractData(s)}}async revokeOverseer(e){this.validateWalletAddressFormat(e);const t=this.buildEndpoint(Ce,{address:Nn(e,"address")});on(await this.http.delete(t,void 0,this.getDualAuthHeaders()),"Failed to revoke overseer")}async getMyStatus(){const e=De,t=await this.http.get(e,{},this.getJwtHeaders());return this.extractData(t)}async getSummary(){const e=Re,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getBanStats(){const e=Oe,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getTokenBanStats(){const e=Me,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getInviteStats(){const e=Ue,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getFlagStats(){const e=Fe,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getUserStats(){const e=Le,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async listOverseerUsers(e){const t=e??{};Object.keys(t).length>0&&function(e){if(null==e||"object"!=typeof e)throw new Ot("Options are required");if(void 0!==e.search){if("string"!=typeof e.search)throw new Ot("Search must be a string");if(0===e.search.length)throw new Ot("Search query cannot be empty string")}if(void 0!==e.sortBy){if("string"!=typeof e.sortBy)throw new Ot("Sort field must be a string");if(0===e.sortBy.length)throw new Ot("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 Ot('Sort order must be "asc" or "desc"')}}(t);const n=xe,s=this.buildPaginationParams(t,Es);void 0!==t.search&&""!==t.search&&(s.search=t.search),void 0!==t.sortBy&&""!==t.sortBy&&(s.sortBy=t.sortBy),void 0!==t.sortOrder&&(s.sortOrder=t.sortOrder);const r=await this.http.get(n,s,this.getDualAuthHeaders()),i=this.extractData(r);return{items:i.users,pageInfo:i.pageInfo}}async getOverseerUserSummary(e){if(!Jn(e))throw zt("address","User address");dc(e);const t=this.buildEndpoint(Pe,{address:Nn(e,"address")}),n=await this.http.get(t,{},this.getDualAuthHeaders());return this.extractData(n)}async flushCacheByAddress(e){rc(e);const t=this.buildEndpoint(Be,{address:Nn(e,"address")}),n=await this.http.delete(t,void 0,this.getDualAuthHeaders());return this.extractData(n)}async flushCacheByToken(e){!function(e){if(!Jn(e))throw zt("tokenName","Token name")}(e);const t=this.buildEndpoint($e,{tokenName:e}),n=await this.http.delete(t,void 0,this.getDualAuthHeaders());return this.extractData(n)}async flushAllCache(e){!function(e){if(!0!==e)throw new Ot("Safety confirmation required: must pass confirm=true to flush all cache","confirm","CONFIRMATION_REQUIRED")}(e);const t=Ge,n=await this.http.delete(t,{confirm:"true"},this.getDualAuthHeaders());return this.extractData(n)}async flushWalletAliasCache(e){if(void 0!==e){rc(e);const t=this.buildEndpoint(Ke,{address:Nn(e,"address")}),n=await this.http.delete(t,void 0,this.getDualAuthHeaders());return this.extractData(n)}const t=We,n=await this.http.delete(t,{confirm:"true"},this.getDualAuthHeaders());return this.extractData(n)}}class gc extends ls{constructor(e,t,n=!1){super(e,n,t)}extractData(e){const t={status:200,error:"error"in e?e.error:"success"in e?!e.success:!("data"in e),data:e.data};return void 0!==e.message&&(t.message=e.message),on(t,"Platform config operation failed",!0),e.data}async getPlatformConfig(){const e=await this.http.get(q);return this.extractData(e)}async updatePlatformConfig(e){const t=function(e){const t=[];return 0===Object.keys(e).length&&t.push("At least one field (streamingEnabled, chatEnabled, commentsEnabled, webhooksEnabled, aiModerationEnabled) must be provided"),void 0!==e.streamingEnabled&&"boolean"!=typeof e.streamingEnabled&&t.push("streamingEnabled must be a boolean"),void 0!==e.chatEnabled&&"boolean"!=typeof e.chatEnabled&&t.push("chatEnabled must be a boolean"),void 0!==e.commentsEnabled&&"boolean"!=typeof e.commentsEnabled&&t.push("commentsEnabled must be a boolean"),void 0!==e.webhooksEnabled&&"boolean"!=typeof e.webhooksEnabled&&t.push("webhooksEnabled must be a boolean"),void 0!==e.aiModerationEnabled&&"boolean"!=typeof e.aiModerationEnabled&&t.push("aiModerationEnabled must be a boolean"),t}(e);if(t.length>0)throw new Ot(t.join("; "),"options","VALIDATION_FAILED");const n=await this.http.put(V,e,this.getJwtHeaders());return this.extractData(n)}async getAvailableRoles(){const e=await this.http.get(X);return this.extractData(e)}}class mc extends ls{constructor(e,t=!1){super(e,t)}extractData(e){if(e.error||void 0===e.data){const t=e.message??"Platform stats operation failed";throw new Error(t)}return e.data}async getStats(){this.logger.debug("Fetching platform stats");const e=await this.http.get(ct),t=this.extractData(e);return this.logger.debug("Fetched platform stats",{totalTokens:t.totalTokens,timestamp:t.timestamp}),{stats:t}}}class fc extends gi{constructor(e,t,n,s){super(e,t,n,!1,s)}async getRestrictedNames(){try{return{success:!0,data:(await this.http.get(Ye,void 0,this.getJwtHeaders())).data}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}async updateRestrictedNames(e){try{if("string"!=typeof e.content)throw new Ot("Content is required");return{success:!0,data:(await this.http.put(Ze,{content:e.content},this.getJwtHeaders())).data}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}}class pc extends gi{constructor(e,t,n,s=!1,r){super(e,t,n,s,r)}async getChatStatus(e){if(null==e||""===e)throw zt("tokenName","Token name");return this.validateTokenName(e,ms),Vr(async()=>{const t=this.buildEndpoint(et,{tokenName:e}),n=await this.http.get(t);return this.buildChatStatusResponse(e,this.extractData(n))},`Failed to get chat status for token: ${e}`,this.logger)}async disableChat(e){if(null==e||""===e)throw zt("tokenName","Token name");return this.validateTokenName(e,ms),Vr(async()=>{const t=this.buildEndpoint(nt,{tokenName:e}),n=await this.http.post(t,{enabled:!1},this.getDualAuthHeaders());return this.buildChatStatusResponse(e,this.extractData(n))},`Failed to disable chat for token: ${e}`,this.logger)}async enableChat(e){if(null==e||""===e)throw zt("tokenName","Token name");return this.validateTokenName(e,ms),Vr(async()=>{const t=this.buildEndpoint(tt,{tokenName:e}),n=await this.http.post(t,{enabled:!0},this.getDualAuthHeaders());return this.buildChatStatusResponse(e,this.extractData(n))},`Failed to enable chat for token: ${e}`,this.logger)}buildChatStatusResponse(e,t){const n={enabled:t.enabled,tokenName:t.tokenName??fn(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 zt("tokenName","Token name");if(this.validateTokenName(e,ms),"number"!=typeof t||t<0||t>600)throw new Error("slowModeSeconds must be a number between 0 and 600");return Vr(async()=>{const n=this.buildEndpoint(st,{tokenName:e}),s=await this.http.patch(n,{slowModeSeconds:t},this.getDualAuthHeaders());return this.extractData(s)},`Failed to set slow mode for token: ${e}`,this.logger)}}es({IDLE:"IDLE",ACTIVE:"ACTIVE",DISABLED:"DISABLED"}),es({PREPARING:"preparing",READY:"ready",ERRORED:"errored"});const vc=es({YOUTUBE:"youtube",TWITCH:"twitch",FACEBOOK:"facebook",CUSTOM:"custom"});const Ac={OWNER:"OWNER",MANAGER:"MANAGER",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MODERATOR:"MODERATOR"};es(Ac),es({OWNER:"OWNER",MODERATOR:"MODERATOR"});function Ec(e,t="tokenName"){ns(e,t,ms)}es({...Ac,OVERSEER:"OVERSEER"});const yc=/^rtmps?:\/\/\S+$/u,Tc=255;function Sc(e){if(Ec(e.tokenName),!Jn(e.language))throw zt("language");if(t=e.language,!Jn(t)||!/^[a-z]{2}(-[A-Z]{2})?$/.test(t))throw new Ot('language must be a valid ISO 639-1 code (e.g., "en", "es", "zh-CN")',"language",It);var t}class bc extends gi{constructor(e,t,n,s=!1,r){super(e,t,n,s,r)}async startStream(e){this.validateTokenName(e,ms);const t=this.buildEndpoint(F,{tokenName:e}),n=await this.http.post(t,{},this.getJwtHeaders());return this.extractData(n)}async stopStream(e){this.validateTokenName(e,ms);const t=this.buildEndpoint(L,{tokenName:e});await this.http.post(t,{},this.getJwtHeaders())}async disableStream(e){return this.toggleFeature(e,x,ms)}async enableStream(e){return this.toggleFeature(e,P,ms)}async resetStreamKey(e){this.validateTokenName(e,ms);const t=this.buildEndpoint(B,{tokenName:e}),n=await this.http.post(t,{},this.getJwtHeaders());return this.extractData(n)}async getStreamCredentials(e){this.validateTokenName(e,ms);const t=this.buildEndpoint(Y,{tokenName:e}),n=await this.http.get(t,{},this.getJwtHeaders());return this.extractData(n)}async getRecordings(e){!function(e){Ec(e.tokenName)}(e);const t=this.buildEndpoint($,{tokenName:e.tokenName}),n=await this.http.get(t),s=this.extractData(n);if(!Array.isArray(s))throw Xt("Invalid recordings response: expected an array of recordings");return{recordings:s,tokenName:fn(e.tokenName)}}async getRecordingDownload(e,t){this.validateTokenName(e,ms),this.validateRequiredString(t,"assetId","Asset ID");const n=this.buildEndpoint(G,{tokenName:e,assetId:t}),s=await this.http.get(n,{},this.getJwtHeaders());return this.extractData(s)}async deleteRecording(e,t){this.validateTokenName(e,ms),this.validateRequiredString(t,"assetId","Asset ID");const n=this.buildEndpoint(K,{tokenName:e,assetId:t});await this.http.delete(n,void 0,this.getJwtHeaders())}async getSimulcastTargets(e){this.validateTokenName(e,ms);const t=this.buildEndpoint(W,{tokenName:e}),n=await this.http.get(t,void 0,this.getJwtHeaders()),s=this.extractData(n);if(!Array.isArray(s))throw Xt("Invalid simulcast response: expected an array of targets");return{targets:s,tokenName:fn(e)}}async addSimulcastTarget(e){!function(e){if(Ec(e.tokenName),!Jn(e.platform))throw zt("platform");if(!vc(e.platform))throw new Ot("platform must be one of: 'youtube', 'twitch', 'facebook', 'custom'","platform",Nt);if(!Jn(e.url))throw zt("url");if(!yc.test(e.url))throw new Ot("url must be a valid RTMP or RTMPS URL","url",It);if(e.url.length>2048)throw new Ot(`url must not exceed ${String(2048)} characters`,"url",_t);if(!Jn(e.streamKey))throw zt("streamKey");if(e.streamKey.length>Tc)throw new Ot(`streamKey must not exceed ${String(Tc)} characters`,"streamKey",_t);if(void 0!==e.passthrough){if("string"!=typeof e.passthrough)throw new Ot("passthrough must be a string","passthrough",wt);if(e.passthrough.length>Tc)throw new Ot(`passthrough must not exceed ${String(Tc)} characters`,"passthrough",_t)}}(e);const t=this.buildEndpoint(H,{tokenName:e.tokenName}),n=await this.http.post(t,{platform:e.platform,url:e.url,streamKey:e.streamKey,...void 0!==e.passthrough&&{passthrough:e.passthrough}},this.getJwtHeaders());return{target:this.extractData(n),tokenName:fn(e.tokenName)}}async removeSimulcastTarget(e,t){this.validateTokenName(e,ms),this.validateRequiredString(t,"targetId","Target ID");const n=this.buildEndpoint(j,{tokenName:e,targetId:t});await this.http.delete(n,void 0,this.getJwtHeaders())}async getGlobalStreamingStatus(){const e=await this.http.get(q);return this.extractData(e)}async disableGlobalStreaming(){const e=await this.http.put(V,{},this.getAdminHeaders());return this.extractData(e)}async enableGlobalStreaming(){const e=await this.http.put(z,{},this.getAdminHeaders());return this.extractData(e)}async setNextLiveStream(e){let t;!function(e){if(Ec(e.tokenName),null!==e.nextLiveStreamAt){if(!(e.nextLiveStreamAt instanceof Date||Jn(e.nextLiveStreamAt)))throw new Ot("nextLiveStreamAt must be a Date, ISO 8601 string, or null","nextLiveStreamAt",wt);if("string"==typeof e.nextLiveStreamAt){const t=Date.parse(e.nextLiveStreamAt);if(isNaN(t))throw new Ot("nextLiveStreamAt must be a valid ISO 8601 date string","nextLiveStreamAt",It)}}}(e),t=null===e.nextLiveStreamAt?null:e.nextLiveStreamAt instanceof Date?e.nextLiveStreamAt.toISOString():e.nextLiveStreamAt;const n=`/v1/tokens/${e.tokenName.toLowerCase().trim()}`;await this.http.patch(n,{nextLiveStreamAt:t},this.getJwtHeaders())}async clearNextLiveStream(e){this.validateTokenName(e,ms);const t=`/v1/tokens/${e.toLowerCase().trim()}`;await this.http.patch(t,{nextLiveStreamAt:null},this.getJwtHeaders())}async setStreamLanguage(e){Sc(e);const t=`/v1/tokens/${e.tokenName.toLowerCase().trim()}`;await this.http.patch(t,{streamLanguage:e.language},this.getJwtHeaders())}async getStreamRole(e){!function(e){Ec(e.tokenName)}(e);const t=this.buildEndpoint(Q,{tokenName:e.tokenName}),n=this.jwtAuth?this.getJwtHeaders():{},s=await this.http.get(t,{},n);return this.extractData(s)}async getAvailableRoles(){const e=await this.http.get(X);return this.extractData(e)}async getTokenAccess(e){!function(e){Ec(e.tokenName)}(e);const t=await this.http.get(J,{tokenName:fn(e.tokenName)},this.getJwtHeaders());return this.extractData(t)}async setNextLiveStreamCountdown(e,t){return this.setNextLiveStream({tokenName:e,nextLiveStreamAt:t})}}const kc="subscribe_token",wc="unsubscribe_token",Nc="subscribe_comment",Ic="unsubscribe_comment",_c="subscribe_global_feed",Cc="unsubscribe_global_feed",Dc="subscribe_events_firehose",Rc="unsubscribe_events_firehose",Oc="authenticate",Mc="send_stream_chat",Uc="SEND_STREAM_REACTION",Fc="typing_start",Lc="typing_stop",xc=e=>Pc(e.flagId);function Pc(e){return"string"==typeof e||"number"==typeof e?String(e):void 0}function Bc(e,t){const n=t.map(t=>Pc(e[t]));return n.every(e=>void 0!==e)?n.join("|"):void 0}const $c={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=>Pc(e.id)},FLAG_RESOLVED:{duplicateKey:e=>Bc(e,["id","status","reviewedAt"])},AI_MODERATION_COMPLETE:{duplicateKey:xc},AI_MODERATION_FAILED:{duplicateKey:xc},MODERATOR_INVITE_CREATED:{},MODERATOR_ADDED:{},MODERATOR_REMOVED:{},MODERATOR_ROLE_UPDATED:{},OVERSEER_ADDED:{token:"none",duplicateKey:e=>Bc(e,["userAddress","addedAt"])},OVERSEER_REMOVED:{token:"none",duplicateKey:e=>Bc(e,["userAddress","removedAt"])},POOL_CREATED:{duplicateKey:e=>Bc(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 Gc(e){return $c[e]}const Kc=Object.keys($c);const Wc="token:",Hc="comment:",jc="global:feed",qc="global:events_firehose";function Vc(e){if(e.startsWith(Wc)){const t={tokenName:e.slice(Wc.length)};return{join:{event:kc,payload:t},leave:{event:wc,payload:t}}}if(e.startsWith(Hc)){const t={tokenName:e.slice(8)};return{join:{event:Nc,payload:t},leave:{event:Ic,payload:t}}}return e===qc?{join:{event:Dc},leave:{event:Rc}}:{join:{event:_c},leave:{event:Cc}}}const zc=new Set(["token_subscribed","room_subscribed","global_feed_subscribed","events_firehose_subscribed"]);const Qc={STREAM_CHAT_GLOBAL_STATUS:"chatEnabled",STREAM_GLOBAL_STATUS:"streamingEnabled",COMMENTS_GLOBAL_STATUS:"commentsEnabled",WEBHOOKS_GLOBAL_STATUS:"webhooksEnabled",AI_MODERATION_GLOBAL_STATUS:"aiModerationEnabled"},Xc=["STREAM_STATUS","TRADE_EXECUTED","HOLDER_COUNT_UPDATED","POOL_BADGE_ASSIGNED","VIEWER_COUNT","TOKEN_CONFIG_UPDATED","STATS_UPDATED","POOL_CREATED"],Jc=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"]),Yc=new Set(["COMMENT_CREATED","COMMENT_UPDATED","COMMENT_DELETED"]);const Zc={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"},el={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"},tl=()=>{};function nl(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function sl(e,t){return t}function rl(e){return`${Wc}${e}`}function il(e){return`${Hc}${e}`}function al(e){const t=fn(e);if(""===t)throw zt("tokenName","Token name");return t}class ol extends ds{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 xt("Stream WebSocket URL is required. Set streamWebSocketUrl in SDK config.");this.config={url:e.url,reconnectAttempts:e.reconnectAttempts??5,reconnectDelay:e.reconnectDelay??2e3,reconnectDelayMax:e.reconnectDelayMax,subscriptionTimeout:e.subscriptionTimeout??1e4,tokenProvider:e.tokenProvider,autoConnect:e.autoConnect??!0},this.isSocketIOAvailable="function"==typeof I}register(e,t,n={}){if(this.disposed)return tl;const s={name:e,deliver:t,token:n.token,filter:n.filter,room:n.room,active:!0};let r=this.subscribers.get(e);return void 0===r&&(r=new Set,this.subscribers.set(e,r)),r.add(s),void 0!==n.room&&this.acquireRoom(n.room),this.openIfNeeded(),()=>{this.release(s)}}release(e){if(!e.active)return;e.active=!1;const t=this.subscribers.get(e.name);t?.delete(e),0===t?.size&&this.subscribers.delete(e.name),void 0!==e.room&&this.releaseRoom(e.room)}hold(e){if(this.disposed)return tl;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: ${$t(e)}`)})}acquireRoom(e){this.roomRefs.set(e,(this.roomRefs.get(e)??0)+1),this.syncRoom(e)}releaseRoom(e){const t=(this.roomRefs.get(e)??1)-1;t<=0?this.roomRefs.delete(e):this.roomRefs.set(e,t),this.syncRoom(e)}syncRoom(e){const t=this.liveSocket();if(null===t)return;const n=(this.roomRefs.get(e)??0)>0,s=this.roomStates.get(e);if(n&&void 0===s){if(function(e){return e===qc}(e)&&!this.authenticated)return;this.joinRoom(t,e)}else n||"joined"!==s?.phase||(t.emit(Vc(e).leave.event,Vc(e).leave.payload),this.roomStates.delete(e))}syncAllRooms(){for(const e of new Set([...this.roomRefs.keys(),...this.roomStates.keys()]))this.syncRoom(e)}joinRoom(e,t){const n=setTimeout(()=>{const e=this.roomStates.get(t);"joining"===e?.phase&&(this.roomStates.delete(t),this.rejectWaiters(t,new Error(`Subscription to ${t} timed out after ${this.config.subscriptionTimeout}ms`)))},this.config.subscriptionTimeout);this.roomStates.set(t,{phase:"joining",timer:n});const s=Vc(t).join;e.emit(s.event,s.payload)}onRoomAcknowledged(e){const t=this.roomStates.get(e);void 0!==t?.timer&&clearTimeout(t.timer),this.roomStates.set(e,{phase:"joined",timer:void 0});const n=this.roomWaiters.get(e);if(void 0!==n){this.roomWaiters.delete(e);const t=e.startsWith(Wc)?e.slice(Wc.length):e;for(const s of n)clearTimeout(s.timer),s.resolve({room:e,tokenName:t})}this.syncRoom(e)}rejectWaiters(e,t){const n=this.roomWaiters.get(e);if(void 0!==n){this.roomWaiters.delete(e);for(const e of n)clearTimeout(e.timer),e.reject(t)}}clearRoomStates(){for(const e of this.roomStates.values())void 0!==e.timer&&clearTimeout(e.timer);this.roomStates.clear()}onServerEvent(e,t){try{this.applyEffects(e,t)}catch(t){this.logger.error(`Error handling ${e}:`,t)}if((!nl(t)||!this.isDuplicate(e,t))&&(this.deliver(e,t,nl(t)?function(e,t){const n=Gc(e).token??"payload";if("none"===n)return;if("room"===n){const e=t.room;return"string"==typeof e&&e.startsWith(Wc)?e.slice(Wc.length):void 0}const s=t.tokenName;return"string"==typeof s&&""!==s?s:void 0}(e,t):void 0),nl(t)))for(const n of function(e,t){if("TOKEN_CONFIG_UPDATED"!==e)return[];const n=t.tokenName;if("string"!=typeof n)return[];const s=[];if("nextLiveStreamAt"in t){const e=t.nextLiveStreamAt;s.push({name:"STREAM_COUNTDOWN_UPDATED",payload:{tokenName:n,nextLiveStreamAt:"string"==typeof e?e:null}})}const r=t.streamLanguage;return"string"==typeof r&&s.push({name:"STREAM_LANGUAGE_UPDATED",payload:{tokenName:n,language:r}}),s}(e,t))this.deliver(n.name,n.payload,n.payload.tokenName)}isDuplicate(e,t){const n=Gc(e).duplicateKey?.(t);if(void 0===n)return!1;const s=Date.now(),r=`${e}:${n}`,i=this.recentOccurrences.get(r);if(void 0!==i&&s-i<5e3)return!0;if(this.recentOccurrences.set(r,s),this.recentOccurrences.size>256)for(const[e,t]of this.recentOccurrences)s-t>=5e3&&this.recentOccurrences.delete(e);return!1}deliver(e,t,n){const s=this.subscribers.get(e);if(void 0===s)return;const r=void 0===n?void 0:fn(n);for(const n of[...s])n.active&&(void 0!==n.token&&n.token!==r||(void 0===n.filter||this.passes(n,t))&&this.invoke(e,n.deliver,t))}passes(e,t){try{return e.filter?.(t)??!0}catch(t){return this.logger.error(`Error in a ${e.name} filter:`,t),!1}}invoke(e,t,n){try{const s=t(n);s instanceof Promise&&s.catch(t=>{this.logger.error(`Error in a ${e} subscriber:`,t)})}catch(t){this.logger.error(`Error in a ${e} subscriber:`,t)}}applyEffects(e,t){if("authenticated"===e)null!==this.inFlight?this.inFlight.settle(!0):this.adoptLateAuthentication();else if("stream_chat_auth_error"===e)this.authenticated=!1,this.inFlight?.settle(!1);else if("exception"===e)this.inFlight?.settle(!1);else if(function(e){return zc.has(e)}(e))nl(t)&&"string"==typeof t.room&&this.onRoomAcknowledged(t.room);else{const n=Qc[e];void 0!==n&&(this.siteConfig={...this.siteConfig,[n]:cl(t)})}}liveSocket(){return null!==this.socket&&this.socket.connected?this.socket:null}connect(){if(this.disposed)return Promise.reject(new xt("The stream WebSocket service has been disposed."));if(!this.isSocketIOAvailable)return Promise.reject(new xt('Socket.IO not available. Install "socket.io-client" package.'));const e=this.socket??this.createSocket();if(e.connected)return Promise.resolve();if(null===this.connectAttempt){let e=()=>{},t=()=>{};const n=new Promise((n,s)=>{e=n,t=s});this.connectAttempt={promise:n,resolve:e,reject:t}}return e.connect(),this.connectAttempt.promise}createSocket(){this.logger.debug(`🔌 Connecting to Stream WebSocket: ${this.config.url}`);const e=I(this.config.url,{transports:["websocket"],reconnection:!0,reconnectionAttempts:this.config.reconnectAttempts,reconnectionDelay:this.config.reconnectDelay,...void 0!==this.config.reconnectDelayMax&&{reconnectionDelayMax:this.config.reconnectDelayMax}});return this.socket=e,this.attachListeners(e),e}attachListeners(e){e.on("connect",()=>{this.onSocketConnect()}),e.on("disconnect",e=>{this.onSocketDisconnect(e)}),e.on("connect_error",e=>{this.logger.error("❌ Stream WebSocket connection error:",e),this.settleConnectWaiters(e)}),e.on("error",e=>{this.logger.error("❌ Stream WebSocket error:",e)});for(const t of Kc)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: ${$t(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?tl:(this.connectionStateListeners.add(e),()=>{this.connectionStateListeners.delete(e)})}onReconnect(e){return this.disposed?tl:(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: ${$t(e)}`),null}}authenticate(e){if(""===e)return Promise.reject(zt("token","Authentication token"));const t=this.pendingAuthenticate;if(null!==t&&t.token===e&&t.generation===this.connectionGeneration)return t.promise;this.authSequence+=1;const n=this.authSequence,s=this.runAuthenticate(e,n).finally(()=>{this.pendingAuthenticate?.promise===s&&(this.pendingAuthenticate=null)});return this.pendingAuthenticate={token:e,generation:this.connectionGeneration,promise:s},s}async runAuthenticate(e,t){if(this.disposed)return!1;const n=e??await this.resolveToken();if(t!==this.authSequence||null===n)return!1;void 0!==e&&(this.lastExplicitToken=e);try{await this.connect()}catch(e){return this.logger.warn(`Cannot authenticate, the connection failed: ${$t(e)}`),!1}for(;null!==this.inFlight;)if(await this.inFlight.settled,t!==this.authSequence)return!1;const s=this.liveSocket();if(t!==this.authSequence||null===s)return!1;if(this.authenticated&&this.authenticatedToken===n&&this.authenticatedGeneration===this.connectionGeneration)return!0;const r=this.beginAuthentication(t,n);this.lastEmitted={seq:t,token:n,generation:this.connectionGeneration},this.logger.debug("📡 Authenticating with stream server"),s.emit(Oc,{token:n});return await r.result&&t===this.authSequence}beginAuthentication(e,t){let n=()=>{};const s=new Promise(e=>{n=e}),r={seq:e,token:t,generation:this.connectionGeneration,result:s,settled:s.then(()=>{}),timer:void 0,settle:e=>{this.finishAuthentication(r,e,n)}};return r.timer=setTimeout(()=>{this.logger.warn("Stream WebSocket authentication timed out"),r.settle(!1)},this.config.subscriptionTimeout),this.inFlight=r,r}finishAuthentication(e,t,n){if(this.inFlight!==e)return;void 0!==e.timer&&clearTimeout(e.timer),this.inFlight=null;const s=e.seq===this.authSequence&&e.generation===this.connectionGeneration;t&&s&&this.markAuthenticated(e.token,e.generation),n(t&&s)}markAuthenticated(e,t){this.authenticated=!0,this.authenticatedToken=e,this.authenticatedGeneration=t,this.wantsAuthentication=!0,this.syncAllRooms()}adoptLateAuthentication(){const e=this.lastEmitted;null===e||this.authenticated||e.seq===this.authSequence&&e.generation===this.connectionGeneration&&this.markAuthenticated(e.token,e.generation)}deauthenticate(){this.authSequence+=1;const e=this.authenticated||null!==this.inFlight;this.inFlight?.settle(!1),this.pendingAuthenticate=null,this.wantsAuthentication=!1,this.lastExplicitToken=null,this.authenticated=!1,this.authenticatedToken=null,this.authenticatedGeneration=-1,e&&null!==this.socket&&!this.disposed&&(this.socket.disconnect(),this.socket.connect())}isAuthenticatedForChat(){return this.authenticated}isConnected(){return this.socket?.connected??!1}requireReady(){const e=this.liveSocket();if(null===e)throw new Ot("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(!this.authenticated)throw new Ot("Not authenticated. Call authenticate() first.","auth","NOT_AUTHENTICATED");return e}sendChatMessage(e,t){if(""===e)throw zt("tokenName","Token name");if(""===t)throw zt("content","Message content");const n=this.requireReady(),s=fn(e);this.logger.debug(`📡 Sending chat message to ${s}: ${t.slice(0,30)}...`),n.emit(Mc,{tokenName:s,content:t})}sendReaction(e,t,n=0){if(""===e)throw zt("tokenName","Token name");if(""===t)throw zt("emoji");const s=this.requireReady(),r=fn(e);this.logger.debug(`📡 Sending reaction to ${r}: ${t}`),s.emit(Uc,{tokenName:r,emoji:t,streamTime:n})}sendTypingStart(e){this.sendTypingEvent(e,Fc)}sendTypingStop(e){this.sendTypingEvent(e,Lc)}sendTypingEvent(e,t){if(""===e)throw zt("tokenName","Token name");this.requireReady().emit(t,{tokenName:fn(e)})}subscribeToken(e,t,n){const s=al(t);return this.register(e,e=>n(sl(0,e)),{token:s,room:rl(s)})}joinTokenRoom(e){return this.hold(rl(al(e)))}subscribeComment(e,t,n){const s=al(t);return this.register(e,e=>n(sl(0,e)),{token:s,room:il(s)})}subscribeFeed(e,t){return this.register(e,e=>t(sl(0,e)),{room:jc})}subscribeEvent(e,t){return this.register(e,e=>t(sl(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:fn(e.tokenName),s=e.userAddress;return void 0!==t||void 0!==n||void 0!==s?e=>{if(!nl(e))return!1;const r=e.eventType;if(void 0!==t&&("string"!=typeof r||!t.includes(r.toLowerCase())))return!1;const i=e.tokenName;if(void 0!==n&&("string"!=typeof i||fn(i)!==n))return!1;const a=e.userAddress;return void 0===s||"string"==typeof a&&Cn(a,s)}:void 0}(t);return this.register("EVENT",t=>e(sl(0,t)),{room:qc,...void 0!==n&&{filter:n}})}subscribeFeedTokenEvents(e){const t=Xc.map(t=>this.register(t,n=>e(function(e,t){return{event:e,data:sl(0,t)}}(t,n)),{room:jc}));return()=>{for(const e of t)e()}}subscribeToGlobalFeed(e={}){const t=this.registerCallbacks(e,el,()=>({})),n=this.hold(jc);return()=>{t(),n()}}addCallbacks(e){return this.registerCallbacks(e,Zc,()=>({}))}registerCallbacks(e,t,n){const s=[],r={...e};for(const[e,i]of Object.entries(t)){const t=r[e];"function"==typeof t&&s.push(this.register(i,e=>Reflect.apply(t,void 0,[e]),n(i)))}return()=>{for(const e of s)e()}}async subscribeToStream(e,t={}){const n=al(e),s=rl(n),r=this.epoch;if(await this.connect(),r!==this.epoch||this.disposed)throw new Error("WebSocket disconnected");const i=this.registerCallbacks(t,Zc,e=>{return t=e,Jc.has(t)?{token:n}:function(e){return Yc.has(e)}(e)?{token:n,room:il(n)}:{};var t}),a=this.hold(s),o={release:()=>{i(),a()}},c=this.explicitHolds.get(n)??[];c.push(o),this.explicitHolds.set(n,c);try{return await this.waitForRoom(s,n)}catch(e){throw this.dropExplicitHold(n,o),e}}waitForRoom(e,t){return"joined"===this.roomStates.get(e)?.phase?Promise.resolve({room:e,tokenName:t}):new Promise((n,s)=>{const r={resolve:n,reject:s,timer:setTimeout(()=>{this.roomWaiters.get(e)?.delete(r),s(new Error(`Subscription to ${t} timed out after ${this.config.subscriptionTimeout}ms`))},this.config.subscriptionTimeout)},i=this.roomWaiters.get(e)??new Set;i.add(r),this.roomWaiters.set(e,i)})}dropExplicitHold(e,t){t.release();const n=(this.explicitHolds.get(e)??[]).filter(e=>e!==t);0===n.length?this.explicitHolds.delete(e):this.explicitHolds.set(e,n)}unsubscribeFromStream(e){const t=fn(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(Wc)&&e.push(t.slice(Wc.length));return e}isSubscribedToGlobalFeed(){return(this.roomRefs.get(jc)??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 cl(e){if(!nl(e))return;const t=e.enabled;return"boolean"==typeof t?t:void 0}function ll(e){if(ns(e.tokenName,"tokenName",gs),!(null==(t=e.reason)||""===t||"string"==typeof t&&!rs(t)&&t.length<=Ts.BAN_REASON.MAX_LENGTH))throw new Ot(`reason must be at most ${Ts.BAN_REASON.MAX_LENGTH} characters`,"reason","TOO_LONG");var t}class dl extends gi{constructor(e,t,n,s=!1,r){super(e,t,n,s,r)}async banToken(e){ll(e);const t=He,n={tokenName:fn(e.tokenName)};if(void 0!==e.reason)try{Qn(e.reason,"reason",!0),e.reason.trim().length>0&&(n.reason=e.reason)}catch{}const s=await this.http.post(t,n,this.getDualAuthHeaders());return{ban:this.extractData(s),tokenName:fn(e.tokenName)}}async unbanToken(e){!function(e){ns(e.tokenName,"tokenName",ms)}(e);const t=this.buildEndpoint(Ve,{tokenName:e.tokenName});return on(await this.http.delete(t,void 0,this.getDualAuthHeaders()),"Failed to unban token",!1),{tokenName:fn(e.tokenName)}}async listTokenBans(e={}){!function(e){Zn(0,void 0,vs,e.pageSize)}(e);const t=je,n=this.buildPaginationParams(e,vs);this.addOptionalFilterParams(n,e,["search"]);const s=await this.http.get(t,n,this.getDualAuthHeaders()),r=this.extractData(s);return{items:r.bans,pageInfo:r.pageInfo}}async getTokenBan(e){!function(e){ns(e.tokenName,"tokenName",ms)}(e);const t=this.buildEndpoint(qe,{tokenName:e.tokenName}),n=await this.http.get(t,{},this.getDualAuthHeaders()),s=this.extractDataOrNull(n);return{banned:null!==s,...null!==s&&{ban:s},tokenName:fn(e.tokenName)}}async isTokenBanned(e){return this.getTokenBan(e)}}class ul extends ds{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(!Jn(e))throw zt("tokenName","Token name");const t=fn(e),n=this.getCacheEntry(t);if(null!==n)return this.cacheHits++,this.updateAccessOrder(t),n.vaultAddress;this.cacheMisses++;const s=await this.poolService.resolveTokenNameToVault(e);if(null!==s&&""!==s){const e=this.parseVaultAddressToTokenClassKey(s);this.setCacheEntry(t,{vaultAddress:s,tokenClassKey:e,cachedAt:Date.now()})}return s}async resolveTokenClassKey(e){if(!Jn(e))throw zt("tokenName","Token name");const t=fn(e),n=this.getCacheEntry(t);if(null!==n)return this.cacheHits++,this.updateAccessOrder(t),n.tokenClassKey;this.cacheMisses++;const s=await this.poolService.resolveTokenNameToVault(e);if(null===s||""===s)throw Vt(e);const r=this.parseVaultAddressToTokenClassKey(s);return this.setCacheEntry(t,{vaultAddress:s,tokenClassKey:r,cachedAt:Date.now()}),r}get(e){const t=this.getCacheEntry(fn(e));return t?.vaultAddress??null}getCacheEntry(e){return this.cache.get(e)??null}setCacheEntry(e,t){this.cache.size>=ul.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=fn(e),s=this.parseVaultAddressToTokenClassKey(t);this.setCacheEntry(n,{vaultAddress:t,tokenClassKey:s,cachedAt:Date.now()})}clear(){this.cache.clear(),this.accessOrder=new Set,this.cacheHits=0,this.cacheMisses=0}getStats(){const e=Array.from(this.cache.values()).map(e=>e.cachedAt),t=this.cacheHits+this.cacheMisses;return{size:this.cache.size,keys:Array.from(this.cache.keys()),maxSize:ul.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(fn(e));return t?.tokenClassKey??null}preWarm(e){for(const{tokenName:t,vaultAddress:n}of e)this.set(t,n)}preWarmWithTokenClassKey(e){for(const{tokenName:t,vaultAddress:n,tokenClassKey:s}of e){const e=fn(t);this.setCacheEntry(e,{vaultAddress:n,tokenClassKey:s,cachedAt:Date.now()})}}parseVaultAddressToTokenClassKey(e){try{return Vi(e)}catch(e){if(e instanceof Ot)throw Qt("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad","Vault address");throw e}}}ul.MAX_CACHE_SIZE=1e4;class hl extends ls{constructor(e,t=!1){super(e,t)}async fetchLaunchpadFee(){const e=await dn(()=>this.http.get(lt),{errorContext:"Failed to fetch launchpad fee"});if("number"!=typeof e.feeAmount||!Number.isFinite(e.feeAmount))throw new Ot("Failed to fetch launchpad fee: no feeAmount in the response","feeAmount","INVALID_RESPONSE");return e.feeAmount}async fetchSaleDetails(e){return dn(()=>this.http.get(dt,{tokenName:e}),{errorContext:`Failed to fetch sale details for ${e}`})}async getTradeQuote(e){const t={tokenName:e.tokenName,amount:e.amount,type:e.type,method:e.method},{signal:n}=e;return Dr(await dn(()=>void 0===n?this.http.get(ut,t):this.http.request({method:"GET",url:ut,params:t,signal:n}),{errorContext:`Failed to get trade quote for ${e.tokenName}`}),`trade quote for ${e.tokenName}`)}async getPremintQuote(e){return Dr(await dn(()=>this.http.get(ht,{amount:e}),{errorContext:"Failed to get premint quote"}),"premint quote")}}class gl extends gi{constructor(e,t,n,s=!1,r){super(e,t,n,s,r)}async emitTradeExecuted(e,t){this.validateTokenName(e,ps);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,ps);const s={action:"balance_updated",userAddress:Nn(e,"userAddress"),tokenName:t,payload:n};await this.emitEvent(s)}async emitStreamStatus(e,t,n=!0){this.validateTokenName(e,ps);const s={action:"stream_status",tokenName:e,payload:t,broadcast:n};await this.emitEvent(s)}async emitViewerCount(e,t,n=!1){this.validateTokenName(e,ps);const s={action:"viewer_count",tokenName:e,payload:t,broadcast:n};await this.emitEvent(s)}async emitStreamCountdown(e,t,n=!0){this.validateTokenName(e,ps);const s={action:"stream_countdown",tokenName:e,payload:t,broadcast:n};await this.emitEvent(s)}async emitChatMessage(e,t,n=!1){this.validateTokenName(e,ps);const s={action:"chat_message",tokenName:e,payload:t,broadcast:n};await this.emitEvent(s)}async emitChatStatus(e,t,n=!1){this.validateTokenName(e,ps);const s={action:"chat_status",tokenName:e,payload:t,broadcast:n};await this.emitEvent(s)}async emitTypingIndicator(e,t,n=!1){this.validateTokenName(e,ps);const s={action:"typing_indicator",tokenName:e,payload:t,broadcast:n};await this.emitEvent(s)}async emitTokenBanned(e,t){this.validateTokenName(e,ps);const n={action:"token_banned",tokenName:e,payload:t,broadcast:!0};await this.emitEvent(n)}async emitTokenUnbanned(e,t){this.validateTokenName(e,ps);const n={action:"token_unbanned",tokenName:e,payload:t,broadcast:!0};await this.emitEvent(n)}async emitModeratorAdded(e,t,n=!1){this.validateTokenName(e,ps);const s={action:"moderator_added",tokenName:e,payload:t,broadcast:n};await this.emitEvent(s)}async emitModeratorRemoved(e,t,n=!1){this.validateTokenName(e,ps);const s={action:"moderator_removed",tokenName:e,payload:t,broadcast:n};await this.emitEvent(s)}async emitUserProfileUpdated(e,t){this.validateRequiredString(e,"userAddress","User Address");const n={action:"user_profile_updated",userAddress:Nn(e,"userAddress"),payload:t};await this.emitEvent(n)}async emitSiteConfigChanged(e){const t={action:"site_config_changed",payload:e,broadcast:!0};await this.emitEvent(t)}async emitFeatureStatus(e){const t={action:"feature_status",payload:e,broadcast:!0};await this.emitEvent(t)}async emitEvent(e){this.validateRequiredString(e.action,"action","Event Action");const t=this.buildEndpoint("/v1/websocket",{});await this.http.post(t,e,this.getDualAuthHeaders())}async getConnectedClients(e){const t=this.buildEndpoint("/v1/connected-clients",{}),n={};void 0!==e?.room&&""!==e.room&&(n.room=e.room),void 0!==e?.tokenName&&(n.tokenName=e.tokenName),void 0!==e?.userAddress&&(n.userAddress=wn(e.userAddress,"userAddress")),void 0!==e?.userAddresses&&(n.userAddresses=e.userAddresses.split(",").map(e=>wn(e.trim(),"userAddresses")).join(",")),void 0!==e?.authenticated&&(n.authenticated=e.authenticated),void 0!==e?.isOverseer&&(n.isOverseer=e.isOverseer),void 0!==e?.minConnectionSeconds&&(n.minConnectionSeconds=e.minConnectionSeconds),void 0!==e?.offset&&(n.offset=e.offset),void 0!==e?.limit&&(n.limit=e.limit);const s=await this.http.get(t,Object.keys(n).length>0?n:void 0,this.getDualAuthHeaders());return this.extractData(s)}async isUserOnline(e){this.validateRequiredString(e,"userAddress","User Address");const t=await this.getConnectedClients({userAddress:e,limit:1});if(0===t.clients.length)return{online:!1};const n=t.clients[0];return void 0===n?{online:!1}:{online:!0,socketId:n.socketId,rooms:n.rooms,connectedAt:n.connectedAt}}async getOnlineUsers(e){if(!Array.isArray(e)||0===e.length)throw new xt("userAddresses must be a non-empty array");const t=await this.getConnectedClients({userAddresses:e.join(","),limit:e.length}),n=t.clients.filter(e=>"string"==typeof e.address&&""!==e.address).map(e=>e.address);return{online:n,offline:e.filter(e=>!n.some(t=>Cn(t,e))),clients:t.clients.map(e=>{const t={socketId:e.socketId,rooms:e.rooms};return"string"==typeof e.address&&(t.address=e.address),t})}}async getTokenViewers(e,t){this.validateTokenName(e,ps);const n={tokenName:e};void 0!==t?.authenticated&&(n.authenticated=t.authenticated),void 0!==t?.limit&&(n.limit=t.limit);const s=await this.getConnectedClients(n);return{clients:s.clients,count:s.summary.totalConnected,authenticatedCount:s.summary.authenticatedCount}}async getOnlineOverseers(){const e=await this.getConnectedClients({isOverseer:!0});return{clients:e.clients,count:e.summary.totalConnected}}async emitRecordingStatus(e,t){this.validateTokenName(e,ps);const n={action:"recording_status",tokenName:e,payload:t};await this.emitEvent(n)}async emitRecordingsCountUpdated(e,t){this.validateTokenName(e,ps);const n={action:"recordings_count_updated",tokenName:e,payload:t};await this.emitEvent(n)}async emitDownloadReady(e,t){this.validateTokenName(e,ps);const n={action:"download_ready",tokenName:e,payload:t};await this.emitEvent(n)}}class ml{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 fl{constructor(e=0){this.defaultTtlMs=e,this.cache=new Map}get(e){const t=this.cache.get(e);if(t){if(!(void 0!==t.expiresAt&&Date.now()>t.expiresAt))return t.value;this.cache.delete(e)}}set(e,t,n){const s=n??this.defaultTtlMs,r={value:t};s>0&&(r.expiresAt=Date.now()+s),this.cache.set(e,r)}has(e){return void 0!==this.get(e)}delete(e){this.cache.delete(e)}clear(){this.cache.clear()}get size(){return this.cache.size}}class pl extends ds{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 ml({maxAttempts:this.config.reconnectAttempts??5,baseDelayMs:this.config.reconnectDelay??2e3}),this.eventBuffer=new fl(3e4),this.isSocketIOAvailable=this.checkSocketIOAvailability(),pl.instances.add(this)}checkSocketIOAvailability(){try{return"function"==typeof I||(this.logger.warn('⚠️ Socket.IO client not available. Install "socket.io-client" package.'),!1)}catch(e){return this.logger.warn("⚠️ Socket.IO availability check failed:",e),!1}}async connect(){return new Promise((e,t)=>{Vr(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:",$t(e)),e}this.logger.debug("🔌 Connecting to Socket.IO server:",this.config.url),this.socket=I(this.config.url,{transports:["websocket"],reconnection:!0,reconnectionAttempts:this.config.reconnectAttempts??5,reconnectionDelay:this.config.reconnectDelay??2e3}),this.socket.on("connect",()=>{this.logger.debug("✅ Socket.IO connected successfully:",this.socket?.id),this.logger.debug("📡 Connected to bundle backend WebSocket:",this.config.url),this.logger.debug("🔗 Ready to monitor transaction updates"),this.reconnectionManager.reset(),e()}),this.socket.on("connect_error",e=>{this.logger.error("❌ Socket.IO connection error:",e),t(e)}),this.socket.on("disconnect",e=>{this.logger.debug(`🔌 Socket.IO disconnected: ${e}`),this.handleReconnect()}),this.socket.on("error",e=>{this.logger.error("❌ Socket.IO error:",e)}),this.socket.onAny((e,...t)=>{if(""!==e&&t.length>0&&"object"==typeof t[0]&&null!==t[0]){const n=t[0],s=n.status??n.Status;"string"==typeof s&&(this.logger.debug(`📡 [Event Buffer] Buffering event for ${e}: ${s}`),this.eventBuffer.size>=this.MAX_BUFFER_SIZE&&this.logger.warn(`📡 [Event Buffer] Buffer approaching limit (${this.eventBuffer.size}/${this.MAX_BUFFER_SIZE})`),this.eventBuffer.set(e,n))}this.debug&&this.logger.debug(`📡 [WebSocket Event] "${e}":`,JSON.stringify(t,null,2))}),this.hasOnAnyListener=!0},"Socket.IO connection failed",this.logger,e=>{this.logger.error("Socket.IO connection failed:",e);const n=Bt(e)?e:new Error($t(e));throw t(n),n}).catch(t)})}async monitorTransaction(e,t){this.listeners.set(e,t),this.logger.debug(`📡 Starting to monitor transaction: ${e}`),this.logger.debug(`📡 WebSocket connected: ${String(this.socket?.connected??!1)}`);const n=this.eventBuffer.get(e);null!=n&&(this.logger.debug(`📡 [Event Buffer] Found buffered event for ${e}, delivering immediately`),setImmediate(()=>{this.processTransactionEvent(e,n,t)}),this.eventBuffer.delete(e));const s=this.config.timeout??3e5,r=setTimeout(()=>{if(this.listeners.has(e)){const n=Math.round(s/1e3),r={transactionId:e,status:ei.TIMEOUT,message:`Transaction monitoring timeout - no response after ${n} seconds`,timestamp:Date.now()};this.logger.debug(`📡 Transaction timeout for ${e} (${n}s)`),t(r),this.listeners.delete(e),this.timeouts.delete(e),this.socket?.off(e)}},s);if(this.timeouts.set(e,r),this.socket?.connected)this.socket.off(e),this.logger.debug(`📡 Listening for transaction updates: ${e}`),this.logger.debug(`📡 WebSocket connection ID: ${String(this.socket.id)}`),this.logger.debug(`📡 WebSocket URL: ${this.config.url}`),this.socket.on(e,n=>{this.processTransactionEvent(e,n,t)});else{const n={transactionId:e,status:ei.FAILED,message:"WebSocket not connected - cannot monitor transaction",timestamp:Date.now()};t(n),this.listeners.delete(e),this.timeouts.delete(e)}await Promise.resolve()}processTransactionEvent(e,t,n){this.logger.debug(`📡 Socket.IO transaction update for ${e}:`,JSON.stringify(t,null,2));const s=t,r=s?.data,i=s?.status??s?.Status??r?.status??r?.Status;let a=s?.message??s?.Message??r?.message??r?.Message??s?.error??r?.error;Jn(a)||(a=i===Zr.FAILED||i===Zr.ERROR?"Transaction failed - check transaction details":i===Zr.COMPLETED||i===Zr.PROCESSED||i===Zr.SUCCESS?"Transaction completed successfully":null!=i?`Transaction status: ${String(i)}`:"Unknown transaction status");const o=s?.blockHash??r?.blockHash,c=s?.gasUsed??r?.gasUsed,l=s?.Data??r?.Data,d={transactionId:e,status:this.mapSocketStatus(i),message:"string"==typeof a?a:"Transaction update received",timestamp:Date.now(),...null!=o?{blockHash:o}:{},...null!=c?{gasUsed:c}:{},...null!=l?{data:l}:{}};if(this.logger.debug(`📡 Mapped status for ${e}: ${String(i)} -> ${d.status}`),this.logger.debug(`📡 Final message: "${String(a)}"`),n(d),d.status===ei.COMPLETED||d.status===ei.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===ei.COMPLETED?t(e):e.status!==ei.FAILED&&e.status!==ei.TIMEOUT||n(new Error(`Transaction ${String(e.status)}: ${e.message}`))})})}mapSocketStatus(e){const t=e?.toUpperCase();return ti[t]??ei.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")),pl.instances.delete(this)}static cleanupAll(e=!1){for(const e of pl.instances)e.disconnect();pl.instances.clear()}isConnected(){return this.socket?.connected??!1}getSocket(){return this.socket}}pl.instances=new Set;class vl extends ls{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 Ot("limit must be between 1 and 50","limit","INVALID_LIMIT");this.logger.debug("Fetching weekly challenge leaderboard",{limit:t});const n={limit:String(t)},s=await this.http.get(gt.GET_LEADERBOARD,n),r=this.extractData(s);return this.logger.debug("Fetched weekly challenge leaderboard",{count:r.count}),{leaderboard:r}}async getTokenHistory(e){const{vaultAddress:t}=e;if("string"!=typeof t||""===t.trim())throw new Ot("vaultAddress is required","vaultAddress","REQUIRED_FIELD");this.logger.debug("Fetching token weekly history",{vaultAddress:t});const n=gt.GET_TOKEN_HISTORY.replace(":vaultAddress",encodeURIComponent(t)),s=await this.http.get(n),r=this.extractData(s);return this.logger.debug("Fetched token weekly history",{count:r.length}),{snapshots:r}}}const Al=["CreateSale","BuyWithNative","BuyExactToken","SellWithNative","SellExactToken"];class El{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 yl{constructor(e){this.bundleBaseUrl=Dl(e.bundleBaseUrl),this.launchpadBaseUrl=Dl(e.launchpadBaseUrl),this.signer=e.signer,this.walletAddress=""===e.walletAddress?"":wn(e.walletAddress,"walletAddress"),this.requestor=e.httpRequestor??fetch.bind(globalThis),this.socketFactory=e.socketFactory??(e=>I(e,{transports:["websocket"]})),this.bundleSocketFactory=e.bundleSocketFactory}attach(e){const{bundleId:t,method:n,uniqueKey:s,tokenName:r}=e;if("string"!=typeof t||""===t)throw Sl("bundleId");if(i=n,!Al.some(e=>e===i))throw Sl("method");var i;if("string"!=typeof s||""===s)throw Sl("uniqueKey");if(void 0!==r&&("string"!=typeof r||""===r))throw Sl("tokenName");if("CreateSale"===n&&void 0===r)throw Sl("tokenName");const a={method:n,dto:{uniqueKey:s,...void 0===r?{}:{tokenName:r}},stringsInstructions:[]};return new El({bundleId:t,uniqueKey:s,method:n,wait:e=>this.waitForResult(a,t,e)})}async submit(e){let t;try{t=await this.signer.signTypedData(e.method,e.dto)}catch(e){throw function(e){if(e instanceof Ri)return e;if(E(e)){const t=e instanceof Error?e.message:"The signature was rejected in the wallet.",n=y(e);return new Ri(t,"WALLET_USER_REJECTED",{details:void 0===n?{}:{walletCode:n}})}const t=e instanceof Error?e.message:"Launchpad signing failed.";return new Ri(t,"LAUNCHPAD_SIGNING_FAILED",{chainMessage:t})}(e)}const n=function(e){return Object.fromEntries(Object.entries(e).filter(([e])=>"prefix"!==e))}(t),s=`${this.bundleBaseUrl}/bundle`,r=await this.requestor(s,{method:"POST",headers:{"content-type":"application/json","X-Wallet-Address":this.walletAddress},body:JSON.stringify({stringsInstructions:e.stringsInstructions,method:e.method,signedDto:n})}),i=await _l(r);if(!r.ok)throw kl(r.status,i,s);const a=function(e){if("string"==typeof e&&""!==e)return e;if(!Cl(e))throw new Ri("Bundler returned no bundle id.","INVALID_BUNDLE_RESPONSE");const t=e.data,n=e.bundleId;if("string"==typeof t&&""!==t)return t;if(Cl(t)&&"string"==typeof t.bundleId&&""!==t.bundleId)return t.bundleId;if("string"==typeof n&&""!==n)return n;throw new Ri("Bundler returned no bundle id.","INVALID_BUNDLE_RESPONSE")}(i),o=Il(e.dto,"uniqueKey");return new El({bundleId:a,uniqueKey:o,method:e.method,wait:t=>this.waitForResult(e,a,t)})}waitForResult(e,t,n={}){const s=n.timeoutMs??6e4,r=n.pollIntervalMs??2500,i=n.signal;return new Promise((n,a)=>{const o=this.confirmationUrl(e,t);if(!0===i?.aborted)return void a(Tl(e.method,t));const c=Date.now(),l=new AbortController,d=void 0===this.bundleSocketFactory;let u,h,g,m=!1;const f=()=>{p(()=>a(Tl(e.method,t)))},p=e=>{m||(m=!0,clearTimeout(A),i?.removeEventListener("abort",f),l.abort(),void 0!==u&&(void 0!==h&&u.off(t,h),d&&u.disconnect()),e())},v=()=>{p(()=>a(function(e,t){const n="string"==typeof e.dto.uniqueKey?e.dto.uniqueKey:"";return new Ri(`Timed out waiting for bundle ${n}`,"BUNDLE_CONFIRMATION_TIMEOUT",{details:{method:e.method,...void 0===t?{}:{lastReadFailure:{message:t.message,...void 0===t.status?{}:{status:t.status}}}}})}(e,g)))};i?.addEventListener("abort",f,{once:!0});const A=setTimeout(v,s);try{u=(this.bundleSocketFactory??this.socketFactory)(this.bundleBaseUrl),h=e=>{const t=function(e){if(!Cl(e))return;const t=e.status;return"PROCESSED"!==t&&"FAILED"!==t?void 0:{status:t,data:e.data}}(e);void 0!==t&&p(()=>{"FAILED"===t.status?a(bl(t.data)):n(t)})},u.on(t,h)}catch{u=void 0,h=void 0}this.pollConfirmation({request:e,confirmationUrl:o,startedAt:c,timeoutMs:s,pollIntervalMs:r,signal:l.signal,onReadFailure:e=>{g=e}}).then(e=>{void 0===e?v():p(()=>n(e))},e=>p(()=>a(e instanceof Error?e:new Error(String(e)))))})}confirmationUrl(e,t){return"CreateSale"===e.method?function(e,t){const n=Il(t,"tokenName");return`${e}/v1/tokens/${encodeURIComponent(n)}`}(this.launchpadBaseUrl,e.dto):`${this.bundleBaseUrl}/bundle?id=${encodeURIComponent(t)}`}async pollConfirmation(e){const{request:t,confirmationUrl:n,startedAt:s,timeoutMs:r,pollIntervalMs:i,signal:a,onReadFailure:o}=e;for(;!a.aborted&&Date.now()-s<=r;){const e=await this.readConfirmation(t,n,a);if(a.aborted)return;if("processed"===e.kind)return e.result;if("failed"===e.kind)throw bl(e.data);o("read-failed"===e.kind?e.error:void 0);const c=r-(Date.now()-s);if(c<=0)break;await Rl(Math.min(Math.max(0,i),c),a)}}async readConfirmation(e,t,n){try{const s=await this.requestor(t,{method:"GET",signal:n}),r=await _l(s);if("CreateSale"===e.method)return s.ok?{kind:"processed",result:{status:"PROCESSED",data:Nl(r)}}:404===s.status||202===s.status?{kind:"pending"}:{kind:"read-failed",error:kl(s.status,r,t)};if(!s.ok)return{kind:"read-failed",error:kl(s.status,r,t)};const i=Cl(r)?r.status:void 0;return"COMPLETED"===i||"PROCESSED"===i?{kind:"processed",result:{status:"PROCESSED",data:r}}:"FAILED"===i?{kind:"failed",data:r}:{kind:"pending"}}catch(e){const n=e instanceof Error?e.message:"The bundle confirmation read failed.";return{kind:"read-failed",error:new Ri(n,"BUNDLE_REQUEST_FAILED",{details:{url:t}})}}}}function Tl(e,t){return new Ri("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 Sl(e){return new Ri(`Cannot attach to a launchpad bundle: ${e} is missing or not accepted.`,"INVALID_BUNDLE_ATTACHMENT",{details:{field:e}})}function bl(e){const t=wl(e)??"Launchpad bundle failed on chain.";return new Ri(t,"BUNDLE_FAILED",{chainMessage:t})}function kl(e,t,n){const s=wl(t)??`Bundle request failed with HTTP ${e}`;return new Ri(s,"BUNDLE_REQUEST_FAILED",{status:e,chainMessage:s,details:{body:t,url:n}})}function wl(e){if("string"==typeof e&&""!==e)return e;if(Cl(e))for(const t of["chainMessage","message","Message","error"]){const n=e[t];if("string"==typeof n&&""!==n)return n;if(Cl(n)){const e=wl(n);if(void 0!==e)return e}}}function Nl(e){return Cl(e)?e.data??e.Data??e:e}function Il(e,t){const n=e[t];if("string"!=typeof n||""===n)throw new Ri(`Missing ${t} in launchpad DTO.`,"INVALID_LAUNCHPAD_DTO");return n}async function _l(e){try{return await e.json()}catch{return e.text()}}function Cl(e){return"object"==typeof e&&null!==e}function Dl(e){return e.replace(/\/$/u,"")}function Rl(e,t){return new Promise(n=>{if(t.aborted)return void n();const s=()=>{clearTimeout(r),n()},r=setTimeout(()=>{t.removeEventListener("abort",s),n()},e);t.addEventListener("abort",s,{once:!0})})}function Ol(e){return async t=>{const n=t.tokenName??await async function(e,t){const n=Ki(t).type,s=await e.findTokenNameByVault(t,n);if(void 0===s)throw new Ot(`Could not find the launchpad token for vault ${t}, so the reverse bonding curve fee ceiling cannot be quoted. Pass tokenName, or pass extraFees.maxAcceptableReverseBondingCurveFee explicitly.`,"tokenName","TOKEN_NOT_FOUND_FOR_VAULT");return s}(e,t.vaultAddress);return function(e,t){if(!/^\d+(\.\d+)?$/.test(e))throw new Ot(`Quoted reverse bonding curve fee is not a non-negative number: ${e}`,"extraFees","INVALID_QUOTED_FEE");if(!Number.isFinite(t)||t<0)throw new Ot(`Fee slippage factor must be a non-negative number, got ${String(t)}`,"maxAcceptableReverseBondingCurveFeeSlippageFactor","INVALID_FEE_SLIPPAGE_FACTOR");return new _(e).multipliedBy(new _(1).plus(new _(String(t)))).decimalPlaces(8,_.ROUND_UP).toFixed()}((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 Ml="0.1",Ul="0.5",Fl=/^(?:\d+\.?\d*|\.\d+)$/u,Ll=/^[0-9A-Z]+$/u,xl=/^[A-Za-z0-9]+$/u,Pl=new _("0.1"),Bl=new _("0.5");function $l(e){if("string"!=typeof e||!Fl.test(e))return;const t=new _(e);return t.isFinite()?t.toFixed():void 0}function Gl(e){return"string"==typeof e&&""!==e}function Kl(e,t,n){void 0!==n&&"string"!=typeof n&&e.push(`${t} must be a string`)}function Wl(e,t,n){void 0===n||Gl(n)||e.push(`${t} must be a non-empty string`)}function Hl(e){const t=[];if("object"!=typeof e||null===e)throw new Ot("CreateSale input must be an object","data","VALIDATION_ERROR");const n={...e},s=n.tokenName;Gl(s)?xl.test(s)||t.push("Token name can only contain letters and numbers"):t.push("Token name is required");const r=n.tokenSymbol;Gl(r)?Ll.test(r.toUpperCase())||t.push("Token symbol can only contain letters and numbers"):t.push("Token symbol is required");const i=n.tokenDescription;Gl(i)?i.length>1e3&&t.push("Token description must be at most 1000 characters"):t.push("Token description is required");const a=n.tokenImage;Gl(a)?a.length>500&&t.push("Token image must be at most 500 characters"):t.push("Token image is required");const o=n.preBuyQuantity;void 0!==o&&void 0===$l(o)&&t.push("preBuyQuantity must be a non-negative decimal number");for(const e of["websiteUrl","telegramUrl","twitterUrl","instagramUrl","facebookUrl","redditUrl","tiktokUrl"])Kl(t,e,n[e]);Wl(t,"tokenCategory",n.tokenCategory),Wl(t,"tokenCollection",n.tokenCollection);const c=n.saleStartTime;if(void 0===c||Number.isInteger(c)||t.push("saleStartTime must be an integer"),function(e,t){if(void 0!==t&&("object"!=typeof t||null===t))return void e.push("reverseBondingCurveConfiguration must be an object");const n=t??{},s=n.minFeePortion??Ml,r=n.maxFeePortion??Ul,i=$l(s),a=$l(r);if(void 0===i&&e.push("minFeePortion must be a decimal number"),void 0===a&&e.push("maxFeePortion must be a decimal number"),void 0===i||void 0===a)return;const o=new _(i),c=new _(a);o.isLessThan(Pl)&&e.push("minFeePortion must be greater than or equal to 0.1"),c.isGreaterThan(Bl)&&e.push("maxFeePortion must be less than or equal to 0.5"),o.isGreaterThan(c)&&e.push("minFeePortion must be less than or equal to maxFeePortion")}(t,n.reverseBondingCurveConfiguration),t.length>0)throw new Ot(t.join("; "),"data","VALIDATION_ERROR")}class jl{constructor(e){this.transport=e.transport,this.walletAddress=""===e.walletAddress?"":wn(e.walletAddress,"walletAddress"),this.sellFeeCeiling=e.sellFeeCeiling}createSale(e){Hl(e);const t=function(e,t){const n={tokenName:e.tokenName,tokenSymbol:e.tokenSymbol,tokenDescription:e.tokenDescription,tokenImage:e.tokenImage,preBuyQuantity:$l(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??ql(t)},s=e.reverseBondingCurveConfiguration;n.reverseBondingCurveConfiguration={minFeePortion:$l(s?.minFeePortion??Ml),maxFeePortion:$l(s?.maxFeePortion??Ul)},void 0!==e.saleStartTime&&(n.saleStartTime=e.saleStartTime);return n}(e,this.walletAddress);return this.transport.submit({method:"CreateSale",dto:t,stringsInstructions:Hi(e)})}attach(e){return this.transport.attach(e)}buyWithNative(e){return this.submitTrade("BuyWithNative",e,{nativeTokenQuantity:e.quantity,expectedToken:e.expectedAmount})}buyExactToken(e){return this.submitTrade("BuyExactToken",e,{tokenQuantity:e.quantity,expectedNativeToken:e.expectedAmount})}sellWithNative(e){return this.submitTrade("SellWithNative",e,{nativeTokenQuantity:e.quantity,expectedToken:e.expectedAmount})}sellExactToken(e){return this.submitTrade("SellExactToken",e,{tokenQuantity:e.quantity,expectedNativeToken:e.expectedAmount})}async submitTrade(e,t,n){const s={vaultAddress:t.vaultAddress,...n,extraFees:t.extraFees??await this.defaultExtraFees(e,t),uniqueKey:t.uniqueKey??ql(this.walletAddress)};return this.transport.submit({method:e,dto:s,stringsInstructions:Wi(t.vaultAddress)})}async defaultExtraFees(e,t){if("BuyWithNative"===e||"BuyExactToken"===e)return{maxAcceptableReverseBondingCurveFee:"0"};if(void 0===this.sellFeeCeiling)throw new Ot("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 ql(e){return`galaswap-operation-${N()}-${Date.now()}-${e}`}function Vl(e,t=3e4){return C.create({baseURL:e,timeout:t,headers:{"Content-Type":"application/json"}})}const zl=new Set(["accesstoken","refreshtoken","token","password","privatekey","secret","apikey","api_key","rawkey","authorization","x-api-key","bearer","streamadminapikey","userapikey","signature","signedpayload"]);function Ql(e,t=0){if(t>5)return"[...]";if(null==e)return e;if(Array.isArray(e))return e.map(e=>Ql(e,t+1));if(e instanceof Map){const n={};for(const[s,r]of e.entries()){const e=String(s);n[e]=zl.has(e.toLowerCase())?"[REDACTED]":Ql(r,t+1)}return n}if("object"==typeof e){const n={};for(const[s,r]of Object.entries(e))n[s]=zl.has(s.toLowerCase())?"[REDACTED]":Ql(r,t+1);return n}return e}class Xl{constructor(e,t={},n={signRequests:!0}){this.auth=e,this.signRequests=n.signRequests,this.session=n.session,this.debug=t.debug??!1,this.logger=new An({debug:this.debug,context:"HttpClient"});const s=t.baseUrl??Yr("stage").launchpadBaseUrl,r=t.timeout??6e4;this.axios=Vl(s,r),t.headers&&(this.axios.defaults.headers.common={...this.axios.defaults.headers.common,...t.headers}),void 0!==this.session&&"omit"!==this.session.credentials&&(this.axios.defaults.withCredentials=!0),this.setupInterceptors()}async request(e){return(await this.requestWithMeta(e)).data}async requestWithMeta(e){return Vr(async()=>{const t=void 0!==this.session&&!1!==e.withSession&&!function(e){return void 0!==e&&Object.keys(e).some(e=>"authorization"===e.toLowerCase())}(e.headers),n=t&&void 0!==this.session?await this.session.accessToken():null,s=this.toAxiosConfig(e,n);e.headers&&this.logger.debug("Custom headers provided:",Object.keys(s.headers??{}));const r=e.data instanceof FormData?"[FormData object - multipart/form-data]":Ql(e.data);this.logger.debug("Request:",{method:e.method,url:e.url?.split("?")[0],baseURL:this.axios.defaults.baseURL,params:Ql(s.params),data:r,isFormData:e.data instanceof FormData,contentType:s.headers?.["Content-Type"]??"not set"});const i=await this.sendWithSession(e,s,t,n),a=function(e){const t={};if(null==e||"object"!=typeof e)return t;for(const[n,s]of Object.entries(e))"string"==typeof s?t[n.toLowerCase()]=s:"number"!=typeof s&&"boolean"!=typeof s||(t[n.toLowerCase()]=String(s));return t}(i.headers);return this.logger.debug("Response:",{status:i.status,data:Ql(i.data),transactionId:a["x-transaction-id"],blockNumber:a["x-block-number"]}),{data:i.data,headers:a,status:i.status}},`HTTP ${e.method} ${e.url}`,this.logger)}toAxiosConfig(e,t){const n=null===t?e.headers:{...e.headers,Authorization:`Bearer ${t}`},s={method:e.method,url:e.url,data:e.data,...void 0!==e.params&&{params:To(e.params)},...void 0!==n&&{headers:{...n}},...void 0!==e.timeout&&{timeout:e.timeout},...void 0!==e.signal&&{signal:e.signal}};if(e.data instanceof FormData){const e=new D(n);e.set("Content-Type",void 0),s.headers=e,this.logger.debug("FormData detected - clearing the JSON Content-Type default for the multipart upload")}return s}async sendWithSession(e,t,n,s){try{return await this.axios.request(t)}catch(t){if(!n||void 0===this.session||!function(e){if("object"!=typeof e||null===e||!("response"in e))return!1;const t=e.response;return"object"==typeof t&&null!==t&&"status"in t&&401===t.status}(t))throw t;const r=await this.session.onUnauthorized(s);if(null===r)throw t;return this.logger.debug("Retrying once with the refreshed session token"),await this.axios.request(this.toAxiosConfig(e,r))}}async get(e,t,n){return this.request({method:"GET",url:e,...t&&{params:t},...n&&{headers:n}})}async post(e,t,n){return this.request({method:"POST",url:e,data:t,...n&&{headers:n}})}async postWithMeta(e,t,n){return this.requestWithMeta({method:"POST",url:e,data:t,...n&&{headers:n}})}async put(e,t,n){return this.request({method:"PUT",url:e,data:t,...n&&{headers:n}})}async delete(e,t,n){return this.request({method:"DELETE",url:e,...t&&{params:t},...n&&{headers:n}})}async patch(e,t,n){return this.request({method:"PATCH",url:e,data:t,...n&&{headers:n}})}getAddress(){return this.auth.getAddress()}getEthereumAddress(){return this.auth.getEthereumAddress()}async signMessage(e){return(await this.auth.signMessage(e)).signature}async signTypedData(e,t,n){return await this.auth.signTypedData(e,t,n)}async signCustomMessage(e){return Vr(async()=>{const t=await this.auth.generateCustomSignature(e);return this.logger.debug("Generated custom signature:",{message:e,address:t.address,ethereumAddress:this.auth.getEthereumAddress()}),{signature:t.signature,address:t.address,ethereumAddress:this.auth.getEthereumAddress()}},"Failed to generate custom signature for message",this.logger)}setupInterceptors(){this.requestInterceptorId=this.axios.interceptors.request.use(async e=>{if(e.headers??(e.headers={}),this.signRequests&&this.auth?.hasWallet()){const t=await this.auth.generateSignature();e.headers.Sign=t.signature,this.logger.debug("Added signature header:",{address:t.address,message:t.message,timestamp:t.timestamp})}else this.logger.debug("Skipping signature header (no wallet, or signRequests is off)");return e.data instanceof FormData||(e.headers["Content-Type"]="application/json"),this.logger.debug("Final request header keys being sent:",Object.keys(e.headers)),e},e=>Promise.reject(e instanceof Error?e:new Error(String(e)))),this.responseInterceptorId=this.axios.interceptors.response.use(e=>e,e=>{const t=e;if(void 0!==t.response){const n=t.response.data,s={message:n?.message??$t(e),...n&&"string"==typeof n.error&&""!==n.error&&{error:n.error},statusCode:t.response.status,...n&&Boolean(n.details)&&{details:n.details},...n&&Boolean(n.timestamp)&&{timestamp:n.timestamp},...n&&Boolean(n.path)&&{path:n.path}};t.launchpadError=s,this.logger.error("Backend error:",s)}else void 0!==t.request?this.logger.error("Network error:",t.message??"Unknown error"):this.logger.error("Request setup error:",t.message??"Unknown error");return Promise.reject(e instanceof Error?e:new Error(String(e)))})}cleanup(){void 0!==this.requestInterceptorId&&(this.axios.interceptors.request.eject(this.requestInterceptorId),this.requestInterceptorId=void 0),void 0!==this.responseInterceptorId&&(this.axios.interceptors.response.eject(this.responseInterceptorId),this.responseInterceptorId=void 0),this.logger.debug("Interceptors cleaned up")}}class Jl extends Error{constructor(e,t){super(e),this.cause=t,this.name="WebSocketError"}}class Yl extends Jl{constructor(e,t){super(`WebSocket confirmation timeout for transaction ${e} after ${t}ms`),this.name="WebSocketTimeoutError"}}class Zl 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 ed(e,t){if(Yn(e))throw new Jl(`Invalid WebSocket response received for transaction ${t}: response is null or undefined`);if("object"!=typeof e)throw new Jl(`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 Jl(`Invalid WebSocket response received for transaction ${t}: missing status field`)}function td(e,t,n,s){ed(e,t);const r=e,i=r.data??{};if(!function(e){if(Yn(e)||"object"!=typeof e)return!1;const t=e;return!(void 0!==t.inputQuantity&&"string"!=typeof t.inputQuantity||void 0!==t.outputQuantity&&"string"!=typeof t.outputQuantity||void 0!==t.totalFees&&"string"!=typeof t.totalFees||void 0!==t.vaultAddress&&"string"!=typeof t.vaultAddress)}(i))throw new Jl(`Invalid trade data received for transaction ${t}`);const a={transactionId:t,type:n,method:"native"===s.type?"native":"exact",inputAmount:i.inputQuantity??s.amount,outputAmount:i.outputQuantity??s.expectedAmount??"0",totalFees:i.totalFees??"0",tokenName:s.tokenName,vaultAddress:i.vaultAddress??"",timestamp:Date.now()};return void 0!==r.blockHash&&(a.blockHash=r.blockHash),void 0!==r.gasUsed&&(a.gasUsed=r.gasUsed),void 0!==s.slippageToleranceFactor&&(a.slippageTolerance=s.slippageToleranceFactor),a}function nd(e){return void 0!==e&&b(e)?new i(e.exportPrivateKey()):void 0}const sd={MUSIC:"$MUSIC",GMUSIC:"$GMUSIC"};function rd(e){if(void 0===e||!("walletAddress"in e))return;const t=e.walletAddress;return"string"==typeof t&&""!==t?t:void 0}const id=/^(?:eth\||0x)([0-9a-fA-F]{40})$/;function ad(e,t,n){if(void 0===e||void 0===t)return;const s=id.exec(e)?.[1],r=id.exec(t)?.[1];if(void 0!==s&&void 0!==r&&s.toLowerCase()!==r.toLowerCase())throw Jt(`${n} ${t} is not the identity of the configured signing key (${e}); writes would be signed as the key, not as ${n}.`,n)}class od{constructor(e){let t,n;this.walletGeneration=0,e.walletProvider?(t=e.walletProvider,n=nd(e.walletProvider)):e.wallet&&(n=e.wallet,t=S.fromWallet(e.wallet)),this.wallet=n;const s=e.env??"prod",r=Yr(s);this.environment=s,this.config={baseUrl:e.launchpadBaseUrl??r.launchpadBaseUrl,gatewayBaseUrl:r.gatewayBaseUrl,bundleBaseUrl:r.bundleBaseUrl,webSocketUrl:r.webSocketUrl,dexApiBaseUrl:r.dexApiBaseUrl,dexBackendBaseUrl:r.dexBackendBaseUrl,launchpadFrontendUrl:r.launchpadFrontendUrl,timeout:3e4,debug:!1,...e};const i=e.signer??(void 0!==n?new Bi(n.privateKey):void 0),a=void 0!==n?`eth|${n.address.slice(2)}`:rd(i),o=void 0===e.walletAddress?void 0:wn(e.walletAddress,"walletAddress"),c=void 0===e.galaChainAddress?void 0:wn(e.galaChainAddress,"galaChainAddress");ad(a,o,"walletAddress"),ad(a,c,"galaChainAddress");const l=o??c??(void 0!==n?`eth|${n.address.slice(2)}`:rd(i)),d=i??{signObject:()=>Promise.reject(new Error("A signer is required for token writes.")),signTypedData:()=>Promise.reject(new Error("A signer is required for launchpad writes."))},u=l??"";this.tokenWriter=void 0===n&&void 0!==e.signer&&void 0!==l?{signer:e.signer,walletAddress:l}:void 0;const h=new yl({bundleBaseUrl:this.config.bundleBaseUrl,launchpadBaseUrl:this.config.baseUrl,signer:d,walletAddress:u,...void 0!==e.httpRequestor&&{httpRequestor:e.httpRequestor},bundleSocketFactory:e.bundleSocketFactory}),g=Ol({getTradeQuote:e=>this.tradingQuotesService.getTradeQuote(e),findTokenNameByVault:(e,t)=>this.findTokenNameByVault(e,t),defaultFeeSlippageFactor:()=>this.maxAcceptableReverseBondingCurveFeeSlippageFactor});this.sellFeeCeiling=g,this.launchpad=new jl({transport:h,walletAddress:u,sellFeeCeiling:g}),this.logger=new An({debug:this.config.debug??!1,context:"LaunchpadSDK"}),this.validateConfiguration(),this.slippageToleranceFactor=void 0===e.slippageToleranceFactor?od.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR:this.parseSlippageToleranceFactor(e.slippageToleranceFactor),this.maxAcceptableReverseBondingCurveFeeSlippageFactor=void 0===e.maxAcceptableReverseBondingCurveFeeSlippageFactor?od.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR:this.parseFeeSlippageFactor(e.maxAcceptableReverseBondingCurveFeeSlippageFactor),this.calculateAmountMode=e.calculateAmountMode??od.DEFAULT_CALCULATE_AMOUNT_MODE,this.galaChainAddressOverride=c,this.signerWalletAddress=o??(void 0===n?l:void 0),this.auth=new Xr({wallet:n,walletProvider:t,messagePrefix:"Create a GalaChain Wallet"});const m=e.session;if(void 0!==m){if(!function(e){if("object"!=typeof e||null===e)return!1;const t=e,n=t.credentials;return"function"==typeof t.accessToken&&"function"==typeof t.onUnauthorized&&(void 0===n||"include"===n||"omit"===n)}(m))throw Jt("session must provide accessToken() and onUnauthorized()","session");if(void 0!==e.accessToken&&""!==e.accessToken)throw Jt("Pass either session or accessToken, not both: the session owns the token.","accessToken")}if(this.jwtAuth=void 0===m?new jr:new qr,void 0!==e.accessToken&&""!==e.accessToken){const t=e.accessTokenExpiresIn??86400;this.jwtAuth.setToken(e.accessToken,t)}this.http=new Xl(this.auth,this.config,{signRequests:!0,session:m}),this.sessionAuth=new Qr(this.http,this.auth,this.jwtAuth,e.debug??!1,m);const f={signRequests:!1};this.galaChainHttp=new Xl(this.auth,{...this.config,baseUrl:this.config.gatewayBaseUrl},f),this.bundleHttp=new Xl(this.auth,{...this.config,baseUrl:this.config.bundleBaseUrl},f),this.dexApiHttp=new Xl(this.auth,{...this.config,baseUrl:this.config.dexApiBaseUrl},f),this.dexBackendHttp=new Xl(this.auth,{...this.config,baseUrl:this.config.dexBackendBaseUrl},f),this.galaChainPublicAxios=Vl(this.config.gatewayBaseUrl,this.config.timeout??3e4),this.cache=new hs(e.debug??!1),this.launchpadService=new $o(this.http,this.jwtAuth),this.tokenResolverService=new ul(this.launchpadService.poolService),this.launchpadAPI=new xr(this.http,this.logger,this.bundleHttp,this.calculateAmountMode,this.launchpad),this.galaChainService=new fo(this.galaChainHttp,n,this.tokenResolverService,e.debug??!1,this.galaChainPublicAxios,this.tokenWriter),this.priceService=new va(this.dexBackendHttp,this.cache,e=>this.galaChainService.fetchTokenDetails(e),e.debug??!1),this.bundleService=this.createBundleService(),this.websocketService=new pl({url:this.config.webSocketUrl},this.config.debug),this.nftCollectionService=new tc(this.galaChainHttp),this.tradingQuotesService=new hl(this.http,e.debug??!1)}createOverrideSdk(e){if(!Jn(e))throw Jt("Invalid privateKey: must be a non-empty string","privateKey");if(!e.match(/^0x[a-fA-F0-9]{64}$/))throw Jt('Invalid privateKey format: must be "0x" followed by 64 hexadecimal characters',"privateKey");const t=new i(e),n={...this.config,wallet:t};return new od(n)}getAddress(){return void 0!==this.galaChainAddressOverride&&""!==this.galaChainAddressOverride?this.galaChainAddressOverride:void 0!==this.signerWalletAddress&&""!==this.signerWalletAddress?this.signerWalletAddress:(this.validateWallet(),this.auth.getAddress())}getEthereumAddress(){return this.validateWallet(),this.wallet.address}validateWallet(){if(!this.wallet)throw zt("wallet","Wallet");return this.wallet}assertTokenWriter(){if(void 0===this.wallet&&void 0===this.tokenWriter)throw zt("wallet","Wallet")}setWallet(e){if(null==e||"object"!=typeof e||!("address"in e))throw new Ot("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 sa(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 fo(this.galaChainHttp,this.wallet,this.tokenResolverService,this.config.debug??!1,this.galaChainPublicAxios)}setWalletProvider(e){this.auth.setWalletProvider(e),this.wallet=e?nd(e):void 0,this.onWalletChanged()}getWallet(){return this.wallet}get events(){return this.getEventsBatcherService()}getWalletProvider(){return this.auth.getWalletProvider()}hasWallet(){return this.auth.hasWallet()}getConfig(){const{wallet:e,walletProvider:t,signer:n,httpRequestor:s,streamAdminApiKey:r,userApiKey:i,accessToken:a,headers:o,...c}=this.config;return{...c,...void 0!==r&&{streamAdminApiKey:"[REDACTED]"},...void 0!==i&&{userApiKey:"[REDACTED]"},...void 0!==a&&{accessToken:"[REDACTED]"},...void 0!==o&&{headers:Object.fromEntries(Object.keys(o).map(e=>[e,"[REDACTED]"]))},environment:this.environment,slippageToleranceFactor:this.slippageToleranceFactor,maxAcceptableReverseBondingCurveFeeSlippageFactor:this.maxAcceptableReverseBondingCurveFeeSlippageFactor,calculateAmountMode:this.calculateAmountMode,gasFee:mn.GAS_FEE}}getVersion(){return ni}getUrlByTokenName(e){const t=this.config.launchpadFrontendUrl;if(void 0===t||""===t)throw Jt("launchpadFrontendUrl not configured in SDK","launchpadFrontendUrl");return`${t.replace(/\/$/,"")}/buy-sell/${e}`}async fetchPools(e){const t=await this.launchpadService.fetchPools(e??{});return await this.warmCacheFromPools(t.items),t}async fetchAllPools(e){const t=await this.launchpadService.fetchAllPools(e);return await this.warmCacheFromPools(t.items),t}async fetchTokenDistribution(e){return this.launchpadService.fetchTokenDistribution(e)}async getTopHolders(e,t=10){const n=await this.fetchTokenDistribution(e),s=Math.min(t,100);return n.holders.slice(0,s).map((e,t)=>({...e,rank:t+1}))}async getHolderCount(e){const t=await this.fetchTokenDistribution(e);return{count:t.totalHolders,totalBalance:t.totalSupply}}async getHolderRank(e,t){const n=Nn(t,"userAddress"),s=await this.fetchTokenDistribution(e),r=s.holders.findIndex(e=>e.address.toLowerCase()===n);if(-1===r)return null;const i=s.holders[r];return void 0===i?null:{rank:r+1,balance:i.balance,holderCount:s.totalHolders}}async getHoldersByBalance(e,t){const n=await this.fetchTokenDistribution(e),s=t?.minBalance??0,r=t?.maxBalance??1/0,i=Math.min(t?.limit??100,1e3),a=new Map;return n.holders.forEach((e,t)=>{a.set(e.address,t+1)}),n.holders.filter(e=>{const t=parseFloat(e.balance);return t>=s&&t<=r}).map(e=>({...e,rank:a.get(e.address)??0})).slice(0,i)}async getHolderHistory(e,t,n=20){return this.getTrades({tokenName:e,userAddress:t,pageSize:Math.min(n,100)})}async fetchUserHolderContext(e,t){return this.launchpadService.fetchUserHolderContext(e,t)}async fetchTokenPrice(e){const t="object"==typeof e&&null!==e?e:{};if(void 0!==t.tokenId)throw new Ot("fetchTokenPrice prices a launchpad token by tokenName; a token by class key is priced by gswap-sdk (gSwap.market.getPrice)","tokenId",Rt);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 $n}),n=t(e)??this.getAddress();return this.galaChainService.fetchGalaBalance({owner:n,collection:"GALA",category:"Unit",additionalKey:"none",type:"none"})}loadCoreBridge(){const e=this.config.bridge;return void 0===e?Promise.reject(Jt("The bridge and wrap methods need gala-core-sdk's ./bridge: create the SDK with `bridge: () => import('@gala-chain/gala-core-sdk/bridge')` (it needs the optional peers ethers, @solana/web3.js and @solana/spl-token).","bridge")):(this.coreBridgeLoad??(this.coreBridgeLoad=Promise.resolve().then(()=>e()).then(e=>{if("object"!=typeof(t=e)||null===t||"function"!=typeof t.BridgeService)throw new Error("the module has no BridgeService export");var t;return e}).catch(e=>{throw this.coreBridgeLoad=void 0,Jt(`The bridge and wrap methods use @gala-chain/gala-core-sdk/bridge, which needs its optional peers ethers, @solana/web3.js and @solana/spl-token installed: ${$t(e)}`,"bridge")})),this.coreBridgeLoad)}async coreBridge(){const e=this.walletGeneration,t=await this.loadCoreBridge();if(e!==this.walletGeneration)throw Jt("The wallet changed while this bridge or wrap call was starting; nothing was sent. Call it again.","wallet");return t}getBridgeService(e){if(!this._bridgeService){const t=this.getWallet();if(!t)throw new Error("Bridge operations require a wallet. Configure SDK with a wallet first.");const n=globalThis.process?.env.SOLANA_PRIVATE_KEY;this._bridgeService=new e.BridgeService({galaConnectBaseUrl:this.config.dexApiBaseUrl,galaChainWalletAddress:this.getAddress(),ethereumPrivateKey:t.privateKey,...void 0!==n&&""!==n?{solanaPrivateKey:n}:{},bridgeableTokenService:this.getBridgeableTokenService(e),environment:this.environment,...void 0!==this.config.ethereumRpcUrl&&""!==this.config.ethereumRpcUrl?{ethereumRpcUrl:this.config.ethereumRpcUrl}:{},...void 0!==this.config.solanaRpcUrl&&""!==this.config.solanaRpcUrl?{solanaRpcUrl:this.config.solanaRpcUrl}:{}})}return this._bridgeService}getBridgeableTokenService(e){return this._bridgeableTokenService??(this._bridgeableTokenService=new e.BridgeableTokenService(this.dexApiHttp)),this._bridgeableTokenService}getWrappableTokenService(e){return this._wrappableTokenService??(this._wrappableTokenService=new e.WrappableTokenService(this.dexApiHttp)),this._wrappableTokenService}getGalaConnectClient(e){if(void 0===this._galaConnectClient){const t=this.getAddress();if(void 0===this.config.dexApiBaseUrl||""===this.config.dexApiBaseUrl)throw new Error("DEX API base URL is required for GalaConnectClient. Check SDK configuration.");this._galaConnectClient=new e.GalaConnectClient({baseUrl:this.config.dexApiBaseUrl,...void 0!==this.config.gatewayBaseUrl&&""!==this.config.gatewayBaseUrl?{galachainBaseUrl:this.config.gatewayBaseUrl}:{},walletAddress:t})}return this._galaConnectClient}getWrapService(e){if(!this._wrapService){const t=this.getWallet();this._wrapService=new e.WrapService({galaConnectClient:this.getGalaConnectClient(e),wrappableTokenService:this.getWrappableTokenService(e),...void 0!==t&&{walletAddress:this.getAddress(),signer:new Bi(t.privateKey)}})}return this._wrapService}getStreamingService(){return this._streamingService??(this._streamingService=new bc(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._streamingService}getStreamChatService(){return this._streamChatService??(this._streamChatService=new pc(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._streamChatService}getBanService(){return this._banService??(this._banService=new Si(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._banService}getTokenBanService(){return this._tokenBanService??(this._tokenBanService=new dl(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._tokenBanService}getAIModerationService(){return this._aiModerationService??(this._aiModerationService=new mi(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._aiModerationService}getWeeklyChallengeService(){return this._weeklyChallengeService??(this._weeklyChallengeService=new vl(this.http,this.config.debug??!1)),this._weeklyChallengeService}getOEmbedService(){return this._oembedService??(this._oembedService=new sc(this.http,this.config.debug??!1)),this._oembedService}getPlatformStatsService(){return this._platformStatsService??(this._platformStatsService=new mc(this.http,this.config.debug??!1)),this._platformStatsService}getHealthService(){return this._healthService??(this._healthService=new po(this.http,this.config.debug??!1)),this._healthService}getEventsQueryService(){return this._eventsQueryService??(this._eventsQueryService=new Ma(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._eventsQueryService}getNotificationService(){return this._notificationService??(this._notificationService=new nc(this.http,this.config.debug??!1,this.jwtAuth)),this._notificationService}getClientConfigService(){return this._clientConfigService??(this._clientConfigService=new ra(this.http,this.config.debug??!1)),this._clientConfigService}getApiKeyService(){return this._apiKeyService??(this._apiKeyService=new Ai(this.http,this.jwtAuth,this.config.debug??!1)),this._apiKeyService}getModeratorService(){return this._moderatorService??(this._moderatorService=new Vo(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._moderatorService}getFlagService(){return this._flagService??(this._flagService=new ha(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._flagService}getOverseerService(){return this._overseerService??(this._overseerService=new hc(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._overseerService}getWebSocketAdminService(){return this._websocketAdminService??(this._websocketAdminService=new gl(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._websocketAdminService}getContentReactionService(){return this._contentReactionService??(this._contentReactionService=new ma(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._contentReactionService}buildMessageFetchOptions(e,t){return{type:t,...void 0!==e.tokenName&&{tokenName:e.tokenName},...void 0!==e.userAddress&&{userAddress:e.userAddress},...void 0!==e.cursor&&{cursor:e.cursor},...void 0!==e.pageSize&&{pageSize:e.pageSize}}}resolveReferralAddress(e){return void 0===e||""===e?this.getAddress():wn(e,"address")}getMessagesService(){return this._messagesService??(this._messagesService=new Ko(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._messagesService}getRestrictedNamesService(){return this._restrictedNamesService??(this._restrictedNamesService=new fc(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.userApiKey)),this._restrictedNamesService}getPlatformConfigService(){return this._platformConfigService??(this._platformConfigService=new gc(this.http,this.jwtAuth,this.config.debug??!1)),this._platformConfigService}getEventsBatcherService(){return this._eventsBatcherService??(this._eventsBatcherService=new wa(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 ol({url:this.config.streamWebSocketUrl,tokenProvider:()=>this.streamSocketToken(),...void 0!==this.config.streamReconnectAttempts&&{reconnectAttempts:this.config.streamReconnectAttempts},...void 0!==this.config.streamReconnectDelay&&{reconnectDelay:this.config.streamReconnectDelay},...void 0!==this.config.streamReconnectDelayMax&&{reconnectDelayMax:this.config.streamReconnectDelayMax}},this.config.debug??!1)}return this._streamWebSocketService}async streamSocketToken(){const e=this.config.session;return void 0!==e?e.accessToken():this.ensureValidToken()}get realtime(){return this.getStreamWebSocketService()}async fetchEthereumWalletTokenBalance(e,t){return this.getBridgeService(await this.coreBridge()).fetchEthereumWalletTokenBalance(e,t)}async fetchEthereumWalletNativeBalance(e){return this.getBridgeService(await this.coreBridge()).fetchEthereumWalletNativeBalance(e)}async fetchSolanaWalletTokenBalance(e,t){return this.getBridgeService(await this.coreBridge()).fetchSolanaWalletTokenBalance(e,t)}async fetchSolanaWalletNativeBalance(e){return this.getBridgeService(await this.coreBridge()).fetchSolanaWalletNativeBalance(e)}async requestSolanaDevnetAirdrop(e,t){return this.getBridgeService(await this.coreBridge()).requestSolanaDevnetAirdrop(e,t)}async getSolanaTransactionStatus(e){return this.getBridgeService(await this.coreBridge()).getSolanaTransactionStatus(e)}async getEthereumTransactionStatus(e){return this.getBridgeService(await this.coreBridge()).getEthereumTransactionStatus(e)}async fetchEthereumWalletAllBalances(e){return this.getBridgeService(await this.coreBridge()).fetchEthereumWalletAllBalances(e)}async fetchSolanaWalletAllBalances(e){return this.getBridgeService(await this.coreBridge()).fetchSolanaWalletAllBalances(e)}async fetchBridgeableTokensByNetwork(e){return this.getBridgeableTokenService(await this.coreBridge()).fetchBridgeableTokensByNetwork(e)}async fetchAllBridgeableTokensByNetwork(e){return this.getBridgeableTokenService(await this.coreBridge()).fetchAllBridgeableTokensByNetwork(e)}async fetchAllTokensBridgeableToEthereum(){return this.getBridgeableTokenService(await this.coreBridge()).fetchAllTokensBridgeableToEthereum()}async fetchAllTokensBridgeableToSolana(){return this.getBridgeableTokenService(await this.coreBridge()).fetchAllTokensBridgeableToSolana()}async isTokenBridgeableToNetwork(e){return this.getBridgeableTokenService(await this.coreBridge()).isTokenBridgeableToNetwork(e)}async isTokenBridgeableToEthereum(e){return this.getBridgeableTokenService(await this.coreBridge()).isTokenBridgeableToEthereum(e)}async isTokenBridgeableToSolana(e){return this.getBridgeableTokenService(await this.coreBridge()).isTokenBridgeableToSolana(e)}async fetchWrappableTokens(e={}){return this.getWrappableTokenService(await this.coreBridge()).fetchWrappableTokens(e)}async fetchAllWrappableTokens(){return this.getWrappableTokenService(await this.coreBridge()).fetchAllWrappableTokens()}async getWrappableToken(e){return this.getWrappableTokenService(await this.coreBridge()).getWrappableToken(e)}async getWrapCounterpart(e){return this.getWrappableTokenService(await this.coreBridge()).getWrapCounterpart(e)}async isTokenWrappable(e){return this.getWrappableTokenService(await this.coreBridge()).isTokenWrappable(e)}async wrapToken(e){return this.getWrapService(await this.coreBridge()).wrapToken(e)}async unwrapToken(e){return this.getWrapService(await this.coreBridge()).unwrapToken(e)}async estimateWrapFee(e,t){return this.getWrapService(await this.coreBridge()).estimateWrapFee(e,t)}async estimateUnwrapFee(e,t){return this.getWrapService(await this.coreBridge()).estimateUnwrapFee(e,t)}async login(){return this.sessionAuth.login()}async loginWithSignature(e){return this.sessionAuth.loginWithSignature(e)}async loginWithDevBypass(e){return this.sessionAuth.loginWithDevBypass(e)}async refreshToken(){return this.sessionAuth.refresh()}async logout(e){return this.sessionAuth.logout(e)}isAuthenticated(){return this.sessionAuth.isAuthenticated()}shouldRefreshToken(e){return this.sessionAuth.shouldRefresh(e)}async getSession(){return this.sessionAuth.getSession()}getAccessToken(){return this.sessionAuth.getAccessToken()}async ensureValidToken(e){return this.sessionAuth.ensureValidToken(e)}async startStream(e){return this.getStreamingService().startStream(e)}async stopStream(e){return this.getStreamingService().stopStream(e)}async disableStream(e){return this.getStreamingService().disableStream(e)}async enableStream(e){return this.getStreamingService().enableStream(e)}async resetStreamKey(e){return this.getStreamingService().resetStreamKey(e)}async getStreamCredentials(e){return this.getStreamingService().getStreamCredentials(e)}async getStreamRecordings(e){return this.getStreamingService().getRecordings(e)}async getRecordingDownload(e,t){return this.getStreamingService().getRecordingDownload(e,t)}async deleteRecording(e,t){return this.getStreamingService().deleteRecording(e,t)}async getSimulcastTargets(e){return this.getStreamingService().getSimulcastTargets(e)}async addSimulcastTarget(e){return this.getStreamingService().addSimulcastTarget(e)}async removeSimulcastTarget(e,t){return this.getStreamingService().removeSimulcastTarget(e,t)}async getGlobalStreamingStatus(){return this.getStreamingService().getGlobalStreamingStatus()}async setNextLiveStreamCountdown(e,t){return this.getStreamingService().setNextLiveStreamCountdown(e,t)}async setGlobalStreamingEnabled(e){const t=this.getStreamingService();return e?t.enableGlobalStreaming():t.disableGlobalStreaming()}async getStreamRole(e){return this.getStreamingService().getStreamRole(e)}async getAvailableRoles(){return this.getStreamingService().getAvailableRoles()}async getTokenAccess(e){return this.getStreamingService().getTokenAccess(e)}async getChatStatus(e){return this.getStreamChatService().getChatStatus(e)}async disableChat(e){return this.getStreamChatService().disableChat(e)}async enableChat(e){return this.getStreamChatService().enableChat(e)}async getPinnedChatMessage(e){const t=this.getMessagesService();return{tokenName:e,pinnedMessage:(await t.getPinnedMessage(e)).message}}async pinChatMessage(e,t){const n=this.getMessagesService();await n.pinMessage(t);return{tokenName:e,pinnedMessage:(await n.getPinnedMessage(e)).message}}async unpinChatMessage(e){const t=this.getMessagesService(),n=await t.getPinnedMessage(e);return n.message?(await t.unpinMessage(n.message.messageId),{tokenName:e,unpinned:!0,unpinnedMessageId:n.message.messageId}):{tokenName:e,unpinned:!1}}async setSlowMode(e,t){return this.getStreamChatService().setSlowMode(e,t)}async createBan(e){return this.getBanService().createBan(e)}async removeBan(e){return this.getBanService().removeBan(e)}async listBans(e){return this.getBanService().listBans(e)}async getBanStatus(e){return this.getBanService().getBanStatus(e)}async getActiveUsers(e){return this.getBanService().getActiveUsers(e)}async createGlobalBan(e){return this.getBanService().createGlobalBan(e)}async removeGlobalBan(e){return this.getBanService().removeGlobalBan(e)}async listGlobalBans(e){return this.getBanService().listGlobalBans(e)}async getGlobalBan(e){return this.getBanService().getGlobalBan(e)}async createApiKey(e){return this.getApiKeyService().create(e)}async listApiKeys(e={}){return this.getApiKeyService().findAll(e)}async getApiKey(e){return this.getApiKeyService().findOne(e)}async updateApiKey(e,t){return this.getApiKeyService().update(e,t)}async revokeApiKey(e){return this.getApiKeyService().revoke(e)}getApiKeyRoles(){return this.getApiKeyService().getRoles()}async createModeratorInvite(e){return this.getModeratorService().createInvite(e)}async claimModeratorInvite(e){return this.getModeratorService().claimInvite(e)}async getModeratedTokens(e){return this.getModeratorService().getModeratedTokens(e)}async listModeratorInvites(e){return this.getModeratorService().listInvites(e)}async getActiveModerators(e){return(await this.listModeratorInvites({tokenName:e,status:"CLAIMED"})).items.filter(e=>null!==e.claimedBy).map(e=>({address:e.claimedBy,role:e.role,joinedAt:e.claimedAt,inviteId:e.id}))}async revokeModeratorInvite(e){return this.getModeratorService().revokeInvite(e)}async updateModeratorInviteRole(e){return this.getModeratorService().updateInviteRole(e)}async updateModeratorInvite(e){return this.getModeratorService().updateInvite(e)}async getModeratorInviteByCode(e){return this.getModeratorService().getInviteByCode(e)}async createFlag(e){return this.getFlagService().createFlag(e)}async listFlags(e){return this.getFlagService().listFlags(e)}async listGlobalFlags(e={}){return this.getFlagService().listGlobalFlags(e)}async dismissFlag(e){return this.getFlagService().dismissFlag(e)}async actionFlag(e){return this.getFlagService().actionFlag(e)}async createOverseerInvite(e={}){return this.getOverseerService().createInvite(e)}async listOverseerInvites(e={}){return this.getOverseerService().listInvites(e)}async getOverseerInviteByCode(e){return this.getOverseerService().getInviteByCode(e)}async claimOverseerInvite(e){return this.getOverseerService().claimInvite(e)}async revokeOverseerInvite(e){return this.getOverseerService().revokeInvite(e)}async listOverseers(e={}){return this.getOverseerService().listOverseers(e)}async createOverseerDirect(e){return this.getOverseerService().createOverseerDirect(e)}async revokeOverseer(e){return this.getOverseerService().revokeOverseer(e)}async getMyOverseerStatus(){return this.getOverseerService().getMyStatus()}async getOverseerSummary(){return this.getOverseerService().getSummary()}async getBanStats(){return this.getOverseerService().getBanStats()}async getTokenBanStats(){return this.getOverseerService().getTokenBanStats()}async getInviteStats(){return this.getOverseerService().getInviteStats()}async getFlagStats(){return this.getOverseerService().getFlagStats()}async getUserStats(){return this.getOverseerService().getUserStats()}async listOverseerUsers(e){return this.getOverseerService().listOverseerUsers(e)}async getOverseerUserSummary(e){return this.getOverseerService().getOverseerUserSummary(e)}async flushCacheByAddress(e){return this.getOverseerService().flushCacheByAddress(e)}async flushCacheByToken(e){return this.getOverseerService().flushCacheByToken(e)}async flushAllCache(e){return this.getOverseerService().flushAllCache(e)}async flushWalletAliasCache(e){return this.getOverseerService().flushWalletAliasCache(e)}async emitWebSocketEvent(e){return this.getWebSocketAdminService().emitEvent(e)}async emitTradeExecuted(e,t){return this.getWebSocketAdminService().emitTradeExecuted(e,t)}async emitBalanceUpdated(e,t,n){return this.getWebSocketAdminService().emitBalanceUpdated(e,t,n)}async emitStreamStatus(e,t){return this.getWebSocketAdminService().emitStreamStatus(e,t)}async emitViewerCount(e,t){return this.getWebSocketAdminService().emitViewerCount(e,t)}async emitStreamCountdown(e,t){return this.getWebSocketAdminService().emitStreamCountdown(e,t)}async emitChatMessage(e,t){return this.getWebSocketAdminService().emitChatMessage(e,t)}async emitChatStatus(e,t){return this.getWebSocketAdminService().emitChatStatus(e,t)}async emitTypingIndicator(e,t){return this.getWebSocketAdminService().emitTypingIndicator(e,t)}async emitTokenBanned(e,t){return this.getWebSocketAdminService().emitTokenBanned(e,t)}async emitTokenUnbanned(e,t){return this.getWebSocketAdminService().emitTokenUnbanned(e,t)}async emitModeratorAdded(e,t){return this.getWebSocketAdminService().emitModeratorAdded(e,t)}async emitModeratorRemoved(e,t){return this.getWebSocketAdminService().emitModeratorRemoved(e,t)}async emitUserProfileUpdated(e,t){return this.getWebSocketAdminService().emitUserProfileUpdated(e,t)}async emitSiteConfigChanged(e){return this.getWebSocketAdminService().emitSiteConfigChanged(e)}async emitFeatureStatus(e){return this.getWebSocketAdminService().emitFeatureStatus(e)}async emitRecordingStatus(e,t){return this.getWebSocketAdminService().emitRecordingStatus(e,t)}async emitRecordingsCountUpdated(e,t){return this.getWebSocketAdminService().emitRecordingsCountUpdated(e,t)}async emitDownloadReady(e,t){return this.getWebSocketAdminService().emitDownloadReady(e,t)}async getConnectedClients(e){return this.getWebSocketAdminService().getConnectedClients(e)}async isUserOnline(e){return this.getWebSocketAdminService().isUserOnline(e)}async getOnlineUsers(e){return this.getWebSocketAdminService().getOnlineUsers(e)}async getTokenViewers(e,t){return this.getWebSocketAdminService().getTokenViewers(e,t)}async getOnlineOverseers(){return this.getWebSocketAdminService().getOnlineOverseers()}async banToken(e){return this.getTokenBanService().banToken(e)}async unbanToken(e){return this.getTokenBanService().unbanToken(e)}async listTokenBans(e={}){return this.getTokenBanService().listTokenBans(e)}async getTokenBan(e){return this.getTokenBanService().getTokenBan(e)}async isTokenBanned(e){return this.getTokenBanService().isTokenBanned(e)}async getAIModerationSettings(){return this.getAIModerationService().getSettings()}async updateAIModerationSettings(e){return this.getAIModerationService().updateSettings(e)}async getAIModeration(e){return this.getAIModerationService().getModeration(e)}async triggerAIModeration(e){return this.getAIModerationService().triggerModeration(e)}async getAIModerationStatus(){return this.getAIModerationService().getStatus()}async getWeeklyChallengeLeaderboard(e={}){return this.getWeeklyChallengeService().getLeaderboard(e)}async getTokenWeeklyHistory(e){return this.getWeeklyChallengeService().getTokenHistory(e)}async getHomeOEmbed(e={}){return this.getOEmbedService().getHomeOEmbedJson(e)}async getPoolOEmbed(e){return this.getOEmbedService().getPoolOEmbedJson(e)}async getProfileOEmbed(e){return this.getOEmbedService().getProfileOEmbedJson(e)}async getPlatformStats(){return this.getPlatformStatsService().getStats()}async getHealth(){return this.getHealthService().getHealth()}async getEventStats(){return this.getEventsQueryService().getEventStats()}async queryEvents(e={}){return this.getEventsQueryService().queryEvents(e)}async registerPushToken(e){return this.getNotificationService().registerPushToken(e)}async unregisterPushToken(e){return this.getNotificationService().unregisterPushToken(e)}async fetchNotificationPreferences(){return this.getNotificationService().getPreferences()}async updateNotificationPreferences(e){return this.getNotificationService().updatePreferences(e)}async fetchClientFlags(){return this.getClientConfigService().getClientFlags()}async addContentReaction(e){return this.getContentReactionService().addContentReaction(e)}async removeContentReaction(e){return this.getContentReactionService().removeContentReaction(e)}async addReactionToChatMessage(e){return this.getContentReactionService().addReactionToChatMessage(e)}async removeReactionFromChatMessage(e){return this.getContentReactionService().removeReactionFromChatMessage(e)}async addReactionToComment(e){return this.getContentReactionService().addReactionToComment(e)}async removeReactionFromComment(e){return this.getContentReactionService().removeReactionFromComment(e)}async getComments(e){const t=this.buildMessageFetchOptions(e,"COMMENT"),n=await this.fetchMessages(t);return{messages:n.messages,pageInfo:n.pageInfo}}async createComment(e){return{comment:(await this.createMessage({type:"COMMENT",tokenName:e.tokenName,content:e.content})).message}}async updateComment(e,t){return{comment:(await this.updateMessage(e,{content:t.content,type:"COMMENT"})).message}}async deleteComment(e){return{success:(await this.deleteMessage(e)).success}}async getChatMessages(e){const t=this.buildMessageFetchOptions(e,"CHAT_MESSAGE"),n=await this.fetchMessages(t);return{messages:n.messages,pageInfo:n.pageInfo}}async sendChatMessage(e){return{message:(await this.createMessage({type:"CHAT_MESSAGE",tokenName:e.tokenName,content:e.content})).message}}async updateChatMessage(e,t){return{message:(await this.updateMessage(e,{content:t.content,type:"CHAT_MESSAGE"})).message}}async deleteChatMessage(e){await this.deleteMessage(e)}async fetchMessages(e){return this.getMessagesService().fetchMessages(e)}async createMessage(e){return this.getMessagesService().createMessage(e)}async updateMessage(e,t){return this.getMessagesService().updateMessage(e,t)}async deleteMessage(e){return this.getMessagesService().deleteMessage(e)}async getPinnedMessage(e){return this.getMessagesService().getPinnedMessage(e)}async pinMessage(e){return this.getMessagesService().pinMessage(e)}async unpinMessage(e){return this.getMessagesService().unpinMessage(e)}async getMessageStats(){return this.getMessagesService().getMessageStats()}async getPlatformConfig(){return this.getPlatformConfigService().getPlatformConfig()}async updatePlatformConfig(e){return this.getPlatformConfigService().updatePlatformConfig(e)}async getRestrictedNames(){return this.getRestrictedNamesService().getRestrictedNames()}async updateRestrictedNames(e){return this.getRestrictedNamesService().updateRestrictedNames(e)}async updateTokenConfig(e,t){return this.launchpadService.poolService.updateTokenConfig(e,t)}async getTokenConfig(e){return this.launchpadService.poolService.getTokenConfig(e)}async getTrades(e){return this.launchpadService.getTrades(e)}async getRecentTrades(e,t=50){return this.getTrades({...void 0!==e&&{tokenName:e},pageSize:Math.min(t,500)})}async getPoolRealtimeState(e){const[t,n,s,r]=await Promise.allSettled([this.getHolderCount(e),this.getTokenConfig(e),this.getRecentTrades(e,10),this.fetchTokenPrice({tokenName:e})]);return{tokenName:e,holderCount:"fulfilled"===t.status?t.value:null,..."rejected"===t.status&&{holderCountError:String(t.reason)},chatConfig:"fulfilled"===n.status?n.value:null,..."rejected"===n.status&&{chatConfigError:String(n.reason)},recentTrades:"fulfilled"===s.status?s.value:null,..."rejected"===s.status&&{recentTradesError:String(s.reason)},price:"fulfilled"===r.status?r.value:null,..."rejected"===r.status&&{priceError:String(r.reason)}}}async fetchLaunchpadFee(){return this.tradingQuotesService.fetchLaunchpadFee()}async fetchSaleDetails(e){return this.tradingQuotesService.fetchSaleDetails(e)}async getTradeQuote(e){return this.tradingQuotesService.getTradeQuote(e)}async getPremintQuote(e){return this.tradingQuotesService.getPremintQuote(e)}async connectStreamWebSocket(e){const t=this.getStreamWebSocketService();await t.connect(),e&&t.addCallbacks(e)}async authenticateStreamWebSocket(e){return this.getStreamWebSocketService().authenticate(e)}deauthenticateStreamWebSocket(){this._streamWebSocketService?.deauthenticate()}async subscribeToStream(e,t){return this.getStreamWebSocketService().subscribeToStream(e,t)}unsubscribeFromStream(e){this.getStreamWebSocketService().unsubscribeFromStream(e)}sendStreamChatViaWebSocket(e,t){this.getStreamWebSocketService().sendChatMessage(e,t)}sendStreamReaction(e,t,n=0){this.getStreamWebSocketService().sendReaction(e,t,n)}sendTypingStart(e){return this.getStreamWebSocketService().sendTypingStart(e)}sendTypingStop(e){return this.getStreamWebSocketService().sendTypingStop(e)}disconnectStreamWebSocket(){this._streamWebSocketService&&this._streamWebSocketService.disconnect()}isStreamWebSocketConnected(){return!!this._streamWebSocketService&&this._streamWebSocketService.isConnected()}onStreamStatusChanged(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_STATUS",e)}onUserBanned(e){return this.getStreamWebSocketService().subscribeEvent("USER_BANNED",e)}onUserUnbanned(e){return this.getStreamWebSocketService().subscribeEvent("USER_UNBANNED",e)}onBanEnforcement(e){return this.getStreamWebSocketService().subscribeEvent("BAN_ENFORCEMENT",e)}watchBanEnforcement(e,t={}){const n=(e,n,s,r)=>(void 0===t.actionType||t.actionType===e)&&(!!(void 0===t.userAddress||null!==n&&Cn(t.userAddress,n))&&((void 0===t.tokenName||t.tokenName===s)&&!!(void 0===t.reason||null!==r&&r.includes(t.reason)))),s=this.onUserBanned(t=>{const s=t.userAddress??null,r=t.reason??null;n("BANNED",s,t.tokenName,r)&&e({actionType:"BANNED",userAddress:s,tokenName:t.tokenName,reason:r,...void 0!==t.expiresAt&&{expiresAt:t.expiresAt}})}),r=this.onUserUnbanned(t=>{const s=t.userAddress??null;n("UNBANNED",s,t.tokenName,null)&&e({actionType:"UNBANNED",userAddress:s,tokenName:t.tokenName,reason:null})}),i=this.onBanEnforcement(t=>{const s=t.reason??null;n("ENFORCEMENT",null,t.tokenName,s)&&e({actionType:"ENFORCEMENT",userAddress:null,tokenName:t.tokenName,reason:s,...void 0!==t.expiresAt&&{expiresAt:t.expiresAt}})});return()=>{s(),r(),i()}}watchTokenRoomEvent(e,t,n,s){const r=s.tokenName;if(void 0===r||""===r)throw new Error(`${e} requires a tokenName filter - these are per-token stream events with no way to watch every token at once.`);return t(r,n)}watchCommentCreated(e,t={}){return this.watchTokenRoomEvent("watchCommentCreated",(e,t)=>this.getStreamWebSocketService().subscribeCommentCreated(e,t),n=>{(void 0===t.authorAddress||Cn(t.authorAddress,n.userAddress))&&(void 0!==t.minLength&&n.content.length<t.minLength||e(n))},t)}watchHolderCountUpdated(e,t={}){return this.watchTokenRoomEvent("watchHolderCountUpdated",(e,t)=>this.getStreamWebSocketService().subscribeHolderCountUpdated(e,t),n=>{void 0!==t.minThreshold&&Math.abs(n.change??0)<t.minThreshold||e(n)},t)}watchModeratorAdded(e,t={}){return this.watchTokenRoomEvent("watchModeratorAdded",(e,t)=>this.getStreamWebSocketService().subscribeModeratorAdded(e,t),e,t)}watchPoolMetadataUpdated(e,t={}){return this.watchTokenRoomEvent("watchPoolMetadataUpdated",(e,t)=>this.getStreamWebSocketService().subscribePoolMetadataUpdated(e,t),e,t)}watchTradeExecuted(e,t={}){return this.watchTokenRoomEvent("watchTradeExecuted",(e,t)=>this.getStreamWebSocketService().subscribeTradeExecuted(e,t),n=>{void 0!==t.tradeType&&t.tradeType!==n.tradeType||(void 0===t.userAddress||Cn(t.userAddress,n.userAddress))&&(void 0!==t.minAmount&&Number(n.inputAmount)<t.minAmount||e(n))},t)}watchTokenBanned(e,t={}){return this.watchTokenRoomEvent("watchTokenBanned",(e,t)=>this.getStreamWebSocketService().subscribeTokenBanned(e,t),e,t)}watchModeratorChanged(e,t={}){const n=(e,n)=>(void 0===t.eventType||t.eventType===e)&&!(void 0!==t.moderatorAddress&&!Cn(t.moderatorAddress,n)),s=this.watchModeratorAdded(t=>{n("ADDED",t.userAddress)&&e({actionType:"ADDED",tokenName:t.tokenName,moderatorAddress:t.userAddress,role:t.role})},t),r=this.watchTokenRoomEvent("watchModeratorRemoved",(e,t)=>this.getStreamWebSocketService().subscribeModeratorRemoved(e,t),t=>{n("REMOVED",t.userAddress)&&e({actionType:"REMOVED",tokenName:t.tokenName,moderatorAddress:t.userAddress})},t),i=this.watchTokenRoomEvent("watchModeratorRoleUpdated",(e,t)=>this.getStreamWebSocketService().subscribeModeratorRoleUpdated(e,t),t=>{n("ROLE_UPDATED",t.userAddress)&&e({actionType:"ROLE_UPDATED",tokenName:t.tokenName,moderatorAddress:t.userAddress,oldRole:t.oldRole,newRole:t.newRole})},t);return()=>{s(),r(),i()}}watchPoolUpdated(e,t={}){const n=e=>void 0===t.updateType||t.updateType===e,s=this.watchPoolMetadataUpdated(t=>{n("METADATA")&&e({updateType:"METADATA",tokenName:t.tokenName,details:t})},t),r=this.watchTokenRoomEvent("watchPoolSocialLinksUpdated",(e,t)=>this.getStreamWebSocketService().subscribePoolSocialLinksUpdated(e,t),t=>{n("SOCIAL_LINKS")&&e({updateType:"SOCIAL_LINKS",tokenName:t.tokenName,details:t})},t),i=this.watchTokenRoomEvent("watchPoolBadgeAssigned",(e,t)=>this.getStreamWebSocketService().subscribePoolBadgeAssigned(e,t),t=>{n("BADGE_ASSIGNED")&&e({updateType:"BADGE_ASSIGNED",tokenName:t.tokenName,details:t})},t);return()=>{s(),r(),i()}}watchTokenBanChanged(e,t={}){const n=e=>void 0===t.banStatus||t.banStatus===e,s=this.watchTokenBanned(t=>{n("BANNED")&&e({banStatus:"BANNED",tokenName:t.tokenName,reason:t.reason})},t),r=this.watchTokenRoomEvent("watchTokenUnbanned",(e,t)=>this.getStreamWebSocketService().subscribeTokenUnbanned(e,t),t=>{n("UNBANNED")&&e({banStatus:"UNBANNED",tokenName:t.tokenName})},t);return()=>{s(),r()}}onContentFlagged(e){return this.getStreamWebSocketService().subscribeEvent("CONTENT_FLAGGED",e)}onFlagResolved(e){return this.getStreamWebSocketService().subscribeEvent("FLAG_RESOLVED",e)}onStreamChatMessage(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_CHAT_MESSAGE",e)}onStreamChatUpdated(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_CHAT_UPDATED",e)}onStreamChatDeleted(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_CHAT_DELETED",e)}onStreamChatPinned(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_CHAT_PINNED",e)}onStreamChatUnpinned(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_CHAT_UNPINNED",e)}onChatStatusChanged(e){return this.getStreamWebSocketService().subscribeEvent("CHAT_STATUS_CHANGED",e)}onViewerCountChanged(e){return this.getStreamWebSocketService().subscribeEvent("VIEWER_COUNT",e)}onRecordingStatusChanged(e){return this.getStreamWebSocketService().subscribeEvent("RECORDING_STATUS",e)}onSimulcastStatusChanged(e){return this.getStreamWebSocketService().subscribeEvent("SIMULCAST_STATUS",e)}onDownloadReady(e){return this.getStreamWebSocketService().subscribeEvent("DOWNLOAD_READY",e)}onRecordingsCountUpdated(e){return this.getStreamWebSocketService().subscribeEvent("RECORDINGS_COUNT_UPDATED",e)}onUserTyping(e){return this.getStreamWebSocketService().subscribeEvent("USER_TYPING",e)}onStreamReaction(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_REACTION",e)}onContentReactionAdded(e){return this.getStreamWebSocketService().subscribeEvent("CONTENT_REACTION_ADDED",e)}onContentReactionRemoved(e){return this.getStreamWebSocketService().subscribeEvent("CONTENT_REACTION_REMOVED",e)}onStreamCountdownUpdated(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_COUNTDOWN_UPDATED",e)}onStreamLanguageUpdated(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_LANGUAGE_UPDATED",e)}onStreamControlStatusChanged(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_CONTROL_STATUS_CHANGED",e)}onConnection(e){return this.getStreamWebSocketService().subscribeEvent("connection",e)}onAuthenticated(e){return this.getStreamWebSocketService().subscribeEvent("authenticated",e)}onTokenSubscribed(e){return this.getStreamWebSocketService().subscribeEvent("token_subscribed",e)}onTokenUnsubscribed(e){return this.getStreamWebSocketService().subscribeEvent("token_unsubscribed",e)}onRoomSubscribed(e){return this.getStreamWebSocketService().subscribeEvent("room_subscribed",e)}onRoomLeft(e){return this.getStreamWebSocketService().subscribeEvent("room_left",e)}onEngagementStatsUpdated(e){return this.getStreamWebSocketService().subscribeEvent("ENGAGEMENT_STATS_UPDATED",e)}async estimateBridgeFee(e){return this.getBridgeService(await this.coreBridge()).estimateBridgeFee(e)}async bridgeOut(e){return this.getBridgeService(await this.coreBridge()).bridgeOut(e)}async bridgeIn(e){return this.getBridgeService(await this.coreBridge()).bridgeIn(e)}async getBridgeStatus(e){return this.getBridgeService(await this.coreBridge()).getBridgeStatus(e)}async getSupportedBridgeTokens(){const e=this.getBridgeService(await this.coreBridge()),t=e.getSupportedBridgeTokens();return{tokens:t,totalCount:t.length,supportedChains:e.getSupportedBridgeChains()}}async fetchTokenBalance(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return $n}),n=t(e.address);if(void 0!==e.tokenId&&""!==e.tokenId){const{normalizeToTokenInstanceKey:t}=await Promise.resolve().then(function(){return ea}),s=t(e.tokenId),{collection:r,category:i,type:a,additionalKey:o}=s;return this.galaChainService.fetchTokenBalance({owner:n,collection:r,category:i,additionalKey:o,type:a},e.withExpired??!1)}if(void 0!==e.tokenName&&""!==e.tokenName){const t=pn(e.tokenName),s=sd[t];if(void 0!==s)return this.galaChainService.fetchTokenBalance({owner:n,collection:s,category:"Unit",additionalKey:"none",type:"none"},e.withExpired??!1)}if(void 0!==e.tokenName&&""!==e.tokenName){const t=(await this.fetchTokensHeld({tokenName:e.tokenName,pageSize:1,...void 0!==n?{address:n}:{}})).tokens[0];if(void 0===t)return null;const s=await this.resolveTokenClassKey(e.tokenName);return{quantity:t.balance,collection:s.collection,category:s.category,tokenId:ji(s)}}throw zt("tokenId or tokenName","Either tokenId or tokenName")}async fetchLockedBalance(e){const t=await this.fetchTokenBalance(e);if(!t)return null;const n="lockedHolds"in t||"lockedQuantity"in t;return{tokenId:t.tokenId,lockedQuantity:n?t.lockedQuantity??"0":"0",lockedHolds:n?t.lockedHolds??[]:[]}}async fetchAvailableBalance(e){const t=await this.fetchTokenBalance(e);if(!t)return null;const n="availableQuantity"in t;return{tokenId:t.tokenId,availableQuantity:n?t.availableQuantity??String(t.quantity):String(t.quantity),totalQuantity:String(t.quantity)}}async calculateBuyAmount(e){return this.launchpadAPI.calculateBuyAmount(e)}async calculateSellAmount(e){return this.launchpadAPI.calculateSellAmount(e)}async calculateBuyAmountLocal(e){return this.launchpadAPI.calculateBuyAmountLocal(e)}async calculateSellAmountLocal(e){return this.launchpadAPI.calculateSellAmountLocal(e)}async calculateBuyAmountExternal(e){return this.launchpadAPI.calculateBuyAmountExternal(e)}async calculateSellAmountExternal(e){return this.launchpadAPI.calculateSellAmountExternal(e)}async calculateBuyAmountForGraduation(e){return this.launchpadAPI.calculateBuyAmountForGraduation(e)}async graduateToken(e){const{tokenName:t,slippageToleranceFactor:n,maxAcceptableReverseBondingCurveFeeSlippageFactor:s,privateKey:r,calculateAmountMode:i,currentSupply:a}=e;let o=t;void 0===i&&void 0===a||(o={tokenName:t,...void 0!==i&&{calculateAmountMode:i},...void 0!==a&&{currentSupply:a}});const c=await this.calculateBuyAmountForGraduation(o),l={tokenName:t,amount:c.remainingTokens,type:"exact",expectedAmount:c.amount,maxAcceptableReverseBondingCurveFee:c.reverseBondingCurveFee,slippageToleranceFactor:this.slippageToleranceFactor};return void 0!==n&&(l.slippageToleranceFactor=n),void 0!==s&&(l.maxAcceptableReverseBondingCurveFeeSlippageFactor=s),void 0!==r&&(l.privateKey=r),await this.buy(l)}async calculateInitialBuyAmount(e){const t={nativeTokenQuantity:e};return this.launchpadAPI.calculateInitialBuyAmount(t)}async buy(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...s}=e;return t.buy(s)}this.validateWallet(),await this.ensureWebSocketConnection();const t=(await this.bundleService.buyToken(e)).data,n=t?.transactionId;if(void 0===n||""===n)throw Yt("No transaction ID returned from buy operation");return this.waitForConfirmation(n,t=>td(t,n,"buy",e))}async sell(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...s}=e;return t.sell(s)}this.validateWallet(),await this.ensureWebSocketConnection();const t=(await this.bundleService.sellToken(e)).data,n=t?.transactionId;if(void 0===n||""===n)throw Yt("No transaction ID returned from sell operation");return this.waitForConfirmation(n,t=>td(t,n,"sell",e))}async getBundlerTransactionResult(e){return this.bundleService.getBundlerTransactionResult(e)}async launchToken(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...s}=e;return t.launchToken(s)}this.validateWallet(),await this.ensureWebSocketConnection();const t=await this.launchpadAPI.launchToken(e);return this.waitForConfirmation(t,n=>{ed(n,t);const s=n.data??{};if(!function(e){if(Yn(e)||"object"!=typeof e)return!1;const t=e;return!(void 0!==t.vaultAddress&&"string"!=typeof t.vaultAddress||void 0!==t.tokenStringKey&&"string"!=typeof t.tokenStringKey||void 0!==t.creatorAddress&&"string"!=typeof t.creatorAddress)}(s))throw new Jl(`Invalid launch data received for transaction ${t}`);const r={transactionId:t,vaultAddress:s.vaultAddress??"",tokenStringKey:s.tokenStringKey??"",tokenName:e.tokenName,tokenSymbol:e.tokenSymbol,creatorAddress:s.creatorAddress??this.getAddress(),timestamp:Date.now(),...void 0!==n.blockHash&&""!==n.blockHash?{blockHash:n.blockHash}:{},...void 0!==n.gasUsed?{gasUsed:n.gasUsed}:{}};return"string"==typeof e.tokenImage&&(r.tokenImage=e.tokenImage),void 0!==e.preBuyQuantity&&(r.preBuyQuantity=e.preBuyQuantity),""!==r.vaultAddress&&this.tokenResolverService.set(e.tokenName,r.vaultAddress),r})}async uploadTokenImage(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...s}=e;return t.uploadTokenImage(s)}return this.launchpadService.uploadImageByTokenName(e)}async checkPoolExists(e,t){return this.launchpadService.checkPoolExists(e,t)}async isTokenNameAvailable(e){return this.launchpadService.isTokenNameAvailable(e)}async isTokenSymbolAvailable(e){return this.launchpadService.isTokenSymbolAvailable(e)}async fetchToken(e){return this.launchpadService.fetchToken(e)}async validateToken(e){return this.launchpadService.validateToken(e)}async fetchTokenStats(e){return this.launchpadService.fetchTokenStats(e)}async fetchProfile(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return $n}),n=t(e)??this.getAddress();return this.launchpadService.fetchProfile(n)}async fetchReferralUrl(){this.validateWallet();const e=this.getAddress();return await this.dexApiHttp.get(O,void 0,{"x-wallet-address":e})}async fetchReferrals(e){const t=this.resolveReferralAddress(e?.address),n=e?.page??1,s=e?.limit??10,r={pageNumber:n,limit:s,sortBy:e?.sortBy??"joined",sortDir:e?.sortDir??"desc"},i=await this.dexApiHttp.get(M,r,{"x-wallet-address":t});if(!Array.isArray(i))throw new Lt("Unexpected API response: expected array, got "+typeof i);return{referrals:i,page:n,limit:s,hasMore:i.length===s}}async fetchAllReferrals(e){const t=await async function(e,t={}){const{maxPages:n=1e4,logger:s,pageSize:r=20,concurrency:i=1,startPage:a=1}=t,o=[];let c=a;const l=a+n-1;let d=!0,u=0;if(i<=1)for(;d&&c<=l;){s&&s.debug(`Auto-pagination: fetching page ${c} with limit ${r}`);const t=await e(c,r);if(null==t||!Array.isArray(t.items)){s&&s.warn("Auto-pagination: received invalid result structure, stopping");break}if(o.push(...t.items),u=t.total,s&&s.debug(`Auto-pagination: page ${c} returned ${t.items.length} items, hasNext: ${String(t.hasNext)}`),0===t.items.length){s&&s.debug(`Auto-pagination: no items returned on page ${c}, exiting loop`);break}d=t.hasNext,c++}else for(s&&s.debug(`Auto-pagination: using concurrent mode with concurrency=${i}`);d&&c<=l;){const t=[];for(let e=0;e<i&&c+e<=l;e++)t.push(c+e);s&&s.debug(`Auto-pagination: fetching pages ${t.join(", ")} concurrently`);const n=t.map(t=>e(t,r).catch(e=>{const n=e,i=n.statusCode??n.response?.status??n.originalError?.response?.status??n.status??n.launchpadError?.statusCode;if(400===i||404===i)return s&&s.debug(`Auto-pagination: page ${t} returned ${i} (end of pagination)`,{statusCode:i}),{items:[],total:0,totalPages:0,page:t,limit:r,hasNext:!1,hasPrevious:!1};throw e})),a=await Promise.all(n);for(const e of a){if(null==e||!Array.isArray(e.items)){s&&s.warn("Auto-pagination: received invalid result structure in batch, stopping"),d=!1;break}if(0===e.items.length){s&&s.debug("Auto-pagination: empty page in batch, reached end of results"),d=!1;break}if(o.push(...e.items),u=e.total,!e.hasNext){d=!1;break}}c+=t.length,s&&s.debug(`Auto-pagination: batch complete, total items so far: ${o.length}`)}return c>l&&s&&s.warn(`Auto-pagination: exceeded maxPages limit of ${n} (maxPage=${l}), stopping iteration`),s&&s.debug(`Auto-pagination: completed with total items: ${o.length}, total count: ${u}`),{items:o,total:u}}((t,n)=>this.fetchReferrals({...e,page:t,limit:n}).then(e=>({items:e.referrals,page:e.page,limit:e.limit,total:0,totalPages:0,hasNext:e.hasMore,hasPrevious:e.page>1})),{maxPages:100,pageSize:100,logger:this.logger});return{referrals:t.items,total:t.items.length}}async fetchReferralsSummary(e){const t=this.resolveReferralAddress(e?.address),n=await this.dexApiHttp.get(U,void 0,{"x-wallet-address":t});if(void 0===n||"number"!=typeof n.referralCount||void 0===n.rewardTotals)throw new Lt(`Unexpected API response: expected { referralCount, rewardTotals }, got ${JSON.stringify(n)}`);return n}async updateProfile(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return $n}),{address:n,...s}=e,r=void 0===n?void 0:t(n),i={...s,...void 0!==r&&{address:r}};if(void 0!==i.privateKey&&""!==i.privateKey){const e=this.createOverrideSdk(i.privateKey),{privateKey:t,...n}=i;return e.updateProfile(n)}return this.launchpadService.updateProfile(i)}async uploadProfileImage(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return $n}),n=void 0===e.address?void 0:t(e.address)??e.address,s={...e,...void 0!==n&&{address:n}};if(void 0!==s.privateKey&&""!==s.privateKey){const e=this.createOverrideSdk(s.privateKey),{privateKey:t,...n}=s;return e.uploadProfileImage(n)}return this.launchpadService.uploadProfileImage(s)}async fetchTokensHeld(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return $n}),n=t(e?.address)??this.getAddress(),s={pageSize:e?.pageSize??10,address:n,...void 0!==e?.cursor?{cursor:e.cursor}:{}};return void 0!==e?.tokenName&&""!==e.tokenName&&(s.tokenName=e.tokenName),void 0!==e?.search&&""!==e.search&&(s.search=e.search),this.launchpadService.fetchTokensHeld(s)}async fetchTokensCreated(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return $n}),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 $n}),n={...e,recipientAddress:t(e.recipientAddress)};if(void 0!==n.privateKey&&""!==n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...s}=n;return e.transferGala(s)}return this.assertTokenWriter(),this.galaChainService.transferGala(n)}async transferToken(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return $n}),n={...e,to:t(e.to)};if(void 0!==n.privateKey&&""!==n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...s}=n;return e.transferToken(s)}return this.assertTokenWriter(),this.galaChainService.transferToken(n)}async resolveTokenClassKey(e){return this.galaChainService.resolveTokenClassKey(e)}async convertTokenNameToTokenClassKey(e){return this.resolveTokenClassKey(e)}async lockTokens(e){const t=await Promise.all(e.tokens.map(async e=>{if(void 0!==e.lockAuthority&&""!==e.lockAuthority){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return $n});return{...e,lockAuthority:t(e.lockAuthority)}}return e})),n={...e,tokens:t};if(void 0!==n.privateKey&&""!==n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...s}=n;return e.lockTokens(s)}return this.assertTokenWriter(),this.galaChainService.lockTokens(n)}async unlockTokens(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...s}=e;return t.unlockTokens(s)}return this.assertTokenWriter(),this.galaChainService.unlockTokens(e)}async burnTokens(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...s}=e;return t.burnTokens(s)}return this.assertTokenWriter(),this.galaChainService.burnTokens(e)}async resolveVaultAddress(e){return this.tokenResolverService.resolveTokenToVault(e)}async findTokenNameByVault(e,t){let n;for(let s=0;s<10;s+=1){const s=await this.launchpadService.poolService.fetchPools({search:t,pageSize:100,...void 0===n?{}:{cursor:n}}),r=s.items.find(t=>t.vaultAddress===e);if(void 0!==r)return r.tokenName;const i=ai(s.pageInfo,n);if(void 0===i)return;n=i}}getCacheInfo(){const e={...this.launchpadAPI.getCacheStats()};if(this._bridgeableTokenService){const t=this._bridgeableTokenService.getCacheStats();e.bridgeableTokens={ETHEREUM:t.tokensByNetwork.ETHEREUM,SOLANA:t.tokensByNetwork.SOLANA,total:t.totalTokens}}return this._wrappableTokenService&&(e.wrappableTokens=this._wrappableTokenService.getCacheStats()),e}clearCache(e){this.launchpadAPI.clearCache(e),void 0!==e&&""!==e||(void 0!==this._bridgeableTokenService&&this._bridgeableTokenService.clearCache(),void 0!==this._wrappableTokenService&&this._wrappableTokenService.clearCache())}validateConfiguration(){try{qn(this.config.timeout,1,3e5,"timeout")}catch{this.logger.warn(`Invalid timeout value: ${this.config.timeout??"undefined"}. Using default 30000ms.`),this.config.timeout=3e4}if(void 0===this.config.baseUrl||""===this.config.baseUrl)throw Jt("baseUrl is required in configuration","baseUrl");if(void 0===this.config.webSocketUrl||""===this.config.webSocketUrl)throw Jt("webSocketUrl is required in configuration","webSocketUrl");try{new URL(this.config.baseUrl)}catch{throw Jt(`Invalid baseUrl format: ${this.config.baseUrl}`,"baseUrl")}try{new URL(this.config.webSocketUrl)}catch{throw Jt(`Invalid webSocketUrl format: ${this.config.webSocketUrl}`,"webSocketUrl")}if(void 0!==this.config.gatewayBaseUrl&&""!==this.config.gatewayBaseUrl)try{new URL(this.config.gatewayBaseUrl)}catch{throw Jt(`Invalid gatewayBaseUrl format: ${this.config.gatewayBaseUrl}`,"gatewayBaseUrl")}if(void 0!==this.config.bundleBaseUrl&&""!==this.config.bundleBaseUrl)try{new URL(this.config.bundleBaseUrl)}catch{throw Jt(`Invalid bundleBaseUrl format: ${this.config.bundleBaseUrl}`,"bundleBaseUrl")}if(void 0!==this.config.launchpadFrontendUrl&&""!==this.config.launchpadFrontendUrl)try{new URL(this.config.launchpadFrontendUrl)}catch{throw Jt(`Invalid launchpadFrontendUrl format: ${this.config.launchpadFrontendUrl}`,"launchpadFrontendUrl")}}parseSlippageToleranceFactor(e){const t=Gn("string"==typeof e||"number"==typeof e?e:String(e),od.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR);return t<0||t>1?(this.logger.warn(`Invalid slippage tolerance factor: ${String(e)}, using default: ${od.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR}`),od.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR):t}parseFeeSlippageFactor(e){const t=Gn("string"==typeof e||"number"==typeof e?e:String(e),od.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: ${od.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR}`),od.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!==ei.COMPLETED)throw new Zl(e,n.status,n.message);let s;try{s=t(n)}catch(t){if(t instanceof Jl)throw t;throw new Jl(`Failed to transform WebSocket response for transaction ${e}`,Bt(t)?t:new Error($t(t)))}return this.logger.debug(`Transaction confirmed: ${e}`,s),s}catch(t){if(this.logger.error(`Transaction confirmation failed: ${e}`,t),t instanceof Zl||t instanceof Jl)throw t;throw new Jl(`WebSocket confirmation failed for transaction ${e}`,Bt(t)?t:new Error($t(t)))}}async warmCacheFromPools(e){if(void 0===e||!Array.isArray(e))return;const{extractMetadataFromPoolData:t,isValidPoolForCaching:n}=await Promise.resolve().then(function(){return ld});e.forEach(e=>{if(!n(e))return;const s=t(e,this.logger);s&&this.launchpadAPI.warmCacheFromPoolData(e.tokenName,s)})}connectWebSocket(){this.websocketService.connect()}disconnectWebSocket(){this.websocketService.disconnect()}isWebSocketConnected(){return this.websocketService.isConnected()}subscribeToEvent(e,t){const n=this.websocketService.getSocket();return n?(n.on(e,t),()=>{n.off(e,t),this.logger.debug(`Unsubscribed from event: "${e}"`)}):(this.logger.warn(`⚠️ WebSocket not connected - subscribing to "${e}" without connection`),()=>{})}onLaunchpadTokenCreation(e,t){const n=1e3,s=Math.max(t?.intervalMs??3e4,n);null!=t?.intervalMs&&t.intervalMs<n&&this.logger.warn(`Poll interval ${t.intervalMs}ms is below minimum 1000ms. Using minimum interval instead.`);const r=t?.creatorAddress,i=new Map;let a=!0,o=null;let c=0;const l=async()=>{if(a){try{const t=await this.fetchPools({type:"recent",pageSize:20});c>0&&(this.logger.debug("Successfully recovered from polling errors"),c=0),t.items.forEach(t=>{i.has(t.tokenName)||((e=>{if(i.set(e,!0),i.size>1e3){const e=i.keys().next().value;void 0!==e&&i.delete(e)}})(t.tokenName),void 0!==r&&""!==r&&t.creatorAddress!==r||e(t))})}catch(e){c++;const t=$t(e);c>=5?this.logger.error(`Polling for new launchpad tokens failed ${c} consecutive times. Last error: ${t}. Continuing to retry...`):c>1?this.logger.warn(`Error polling for new launchpad tokens (attempt ${c}/5): ${t}`):this.logger.debug(`Error polling for new launchpad tokens: ${t}`)}if(a){const e=Math.min(Math.max(c-1,0),2),t=s*Math.pow(2,e);o=setTimeout(()=>{l()},t)}}};return l(),()=>{a=!1,o&&clearTimeout(o),this.logger.debug("Stopped watching for launchpad token creation")}}matchesCreatorFilter(e,t){return void 0===t||""===t||e.creatorAddress===t}subscribeToTokenCreations(e,t){if(this.logger.debug("Subscribing to token creation broadcasts"+(void 0!==t?.creatorFilter&&""!==t.creatorFilter?` (filter: ${t.creatorFilter})`:"")),null===this.websocketService||void 0===this.websocketService)throw Jt("WebSocket service not initialized. Ensure websocketUrl is configured and the service is connected.","websocketService");let n=!1,s=null;const r=(n,...s)=>{try{if(s.length>0&&"object"==typeof s[0]&&null!==s[0]){const n=s[0].data;if(void 0!==n?.Data&&null!==n.Data&&"object"==typeof n.Data){const s=n.Data;if("CreateSale"===s.functionName){const n=(e,t="")=>{const n=s[e];return"string"==typeof n&&""!==n?n:t},r={tokenName:n("tokenName"),symbol:n("symbol"),creatorAddress:n("creatorAddress"),description:n("description"),image:n("image"),vaultAddress:n("vaultAddress"),tokenStringKey:n("tokenStringKey"),preBuyQuantity:n("initialBuyQuantity","0"),websiteUrl:n("websiteUrl"),telegramUrl:n("telegramUrl"),twitterUrl:n("twitterUrl"),instagramUrl:n("instagramUrl"),facebookUrl:n("facebookUrl"),redditUrl:n("redditUrl"),tiktokUrl:n("tiktokUrl"),isFinalized:!0===s.isFinalized};this.matchesCreatorFilter(r,t?.creatorFilter)&&e(r)}}}}catch(e){this.logger.warn(`Error processing token creation broadcast: ${$t(e)}`)}};let i=this.websocketService.getSocket();if(i)i.onAny(r),n=!0,this.logger.debug("Token creation broadcast listener registered");else{this.logger.debug("WebSocket not yet connected, initiating connection..."),this.websocketService.connect().catch(e=>{const n=new Error(`WebSocket connection failed: ${$t(e)}`);this.logger.warn("Failed to establish WebSocket connection:",e),t?.onError&&t.onError(n)});let e=0;const a=()=>{if(i=this.websocketService.getSocket(),!i&&e<od.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS)return e++,void(s=setTimeout(()=>a(),od.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS));if(!i&&e>=od.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS){const e=new Error(`WebSocket not available after ${od.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS*od.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS}ms`);return this.logger.warn("Token creation broadcast subscription timeout:",e.message),void(t?.onError&&t.onError(e))}i&&(i.onAny(r),n=!0,this.logger.debug("Token creation broadcast listener registered"))};a()}return()=>{try{if(null!==s&&(clearTimeout(s),s=null,this.logger.debug("Cleared token creation broadcast polling timeout")),!n)return void this.logger.debug("Cleanup called before listener registration - no action needed");const e=this.websocketService.getSocket();e&&(e.offAny(r),n=!1,this.logger.debug("Stopped listening to token creation broadcasts"))}catch(e){this.logger.warn("Error removing token creation listener:",e)}}}getNftCollectionClaimFee(){return this.nftCollectionService.getCollectionClaimFee()}getNftTokenClassCreateFee(){return this.nftCollectionService.getTokenClassCreateFee()}estimateNftMintFee(e){return this.nftCollectionService.estimateMintFee(e)}estimateNftOperationFees(e){return this.nftCollectionService.estimateNftOperationFees(e)}claimNftCollection(e){return this.nftCollectionService.claimCollection(e)}fetchNftCollections(e){return this.nftCollectionService.fetchUserCollections(e)}isNftCollectionAvailable(e){return this.nftCollectionService.isCollectionAvailable(e)}createNftTokenClass(e){return this.nftCollectionService.createTokenClass(e)}fetchNftTokenClasses(e){return this.nftCollectionService.fetchTokenClasses(e)}mintNft(e){return this.nftCollectionService.mintNft(e)}fetchNftBalances(e,t){return this.nftCollectionService.fetchNftBalances(e,t)}async cleanup(){try{if(this.logger.debug("Starting cleanup..."),void 0!==this._eventsBatcherService)try{await this._eventsBatcherService.shutdown(5e3),this._eventsBatcherService=void 0}catch(e){this.logger.warn("Error during events shutdown:",e)}this.http.cleanup(),null!==this.websocketService&&void 0!==this.websocketService&&this.websocketService.disconnect(),void 0!==this._streamWebSocketService&&(this._streamWebSocketService.dispose(),this._streamWebSocketService=void 0),this.logger.debug("Cleanup completed")}catch(e){this.logger.error("Error during cleanup:",e)}}static cleanupAll(e=!1){const t=new An({debug:e,context:"LaunchpadSDK"});t.debug("Starting global cleanup..."),pl.cleanupAll(e),t.debug("Global cleanup completed")}}function cd(e){Yn(e)&&(e={});const{wallet:t,env:n,config:s={},...r}=e,a={...{...r,...s}};delete a.wallet,delete a.env,delete a.config;const o=!Yn(a.signer)||!Yn(a.walletProvider);let c;if(Yn(t))c=o?void 0:new i(T().privateKey);else if("string"==typeof t)c=new i(T(t).privateKey);else{if(!(t instanceof i))throw Jt("Invalid wallet input. Expected string (private key or mnemonic) or Wallet instance.","wallet");c=t}const l={...void 0!==c?{wallet:c}:{},...void 0!==n?{env:n}:{},debug:!1,timeout:3e4,...a};return new od(l)}od.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR=.15,od.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR=.01,od.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY=mn.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY,od.DEFAULT_CALCULATE_AMOUNT_MODE="local",od.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS=30,od.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS=100;var ld=Object.freeze({__proto__:null,extractMetadataFromPoolData:function(e,t){const n={};if(void 0!==e.vaultAddress&&(n.vaultAddress=e.vaultAddress),void 0!==e.reverseBondingCurveMinFeePortion){const s=Gn(e.reverseBondingCurveMinFeePortion,NaN);isNaN(s)?t&&t.debug(`Skipping invalid reverseBondingCurveMinFeePortion for ${e.tokenName}: "${e.reverseBondingCurveMinFeePortion}"`):n.reverseBondingCurveMinFeeFactor=s}if(void 0!==e.reverseBondingCurveMaxFeePortion){const s=Gn(e.reverseBondingCurveMaxFeePortion,NaN);isNaN(s)?t&&t.debug(`Skipping invalid reverseBondingCurveMaxFeePortion for ${e.tokenName}: "${e.reverseBondingCurveMaxFeePortion}"`):n.reverseBondingCurveMaxFeeFactor=s}return void 0!==n.reverseBondingCurveMaxFeeFactor&&void 0!==n.reverseBondingCurveMinFeeFactor&&(n.reverseBondingCurveNetFeeFactor=n.reverseBondingCurveMaxFeeFactor-n.reverseBondingCurveMinFeeFactor),Object.keys(n).length>0?n:null},isValidPoolForCaching:function(e){if(null===e||"object"!=typeof e)return!1;const t=e;return"tokenName"in t&&"string"==typeof t.tokenName&&t.tokenName.length>0}});export{Gi as BrowserWalletSigner,ka as EVENT_TYPES,$i as GalaWalletSigner,od as LaunchpadSDK,Ri as LaunchpadSDKError,Bi as PrivateKeySigner,ni as SDK_VERSION,Zl as TransactionFailedError,Jl as WebSocketError,Yl as WebSocketTimeoutError,cd as createLaunchpadSDK};