@gala-chain/launchpad-sdk 7.0.0-beta.3 → 7.0.0-beta.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.
- package/README.md +2 -0
- package/dist/LaunchpadSDK.d.ts +10 -8
- package/dist/LaunchpadSDK.d.ts.map +1 -1
- package/dist/api/dto/BondingCurveDTOs.d.ts +2 -2
- package/dist/api/dto/BondingCurveDTOs.d.ts.map +1 -1
- package/dist/api/dto/BurnTokensDto.d.ts +1 -1
- package/dist/api/dto/BurnTokensDto.d.ts.map +1 -1
- package/dist/api/dto/LockTokenDto.d.ts +1 -1
- package/dist/api/dto/LockTokenDto.d.ts.map +1 -1
- package/dist/api/dto/TransferTokenDto.d.ts +1 -1
- package/dist/api/dto/TransferTokenDto.d.ts.map +1 -1
- package/dist/api/dto/UnlockTokenDto.d.ts +1 -1
- package/dist/api/dto/UnlockTokenDto.d.ts.map +1 -1
- package/dist/bridge/strategies/EthereumBridgeStrategy.d.ts.map +1 -1
- package/dist/constants/version.generated.d.ts +1 -1
- package/dist/helpers/sdk.d.ts.map +1 -1
- package/dist/index.browser.esm.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.esm.js +1 -1
- package/dist/index.js +1 -1
- package/dist/launchpad/writes.d.ts.map +1 -1
- package/dist/native.cjs +1 -1
- package/dist/native.esm.js +1 -1
- package/dist/react.cjs +1 -1
- package/dist/react.esm.js +1 -1
- package/dist/schemas/user.d.ts +6 -6
- package/dist/schemas/user.d.ts.map +1 -1
- package/dist/schemas/validators.d.ts +1 -1
- package/dist/services/ContentReactionService.d.ts.map +1 -1
- package/dist/services/LaunchpadService.d.ts +1 -6
- package/dist/services/LaunchpadService.d.ts.map +1 -1
- package/dist/services/ModeratorService.d.ts.map +1 -1
- package/dist/services/NftCollectionService.d.ts.map +1 -1
- package/dist/services/UserService.d.ts +3 -10
- package/dist/services/UserService.d.ts.map +1 -1
- package/dist/signing/signers.d.ts +4 -2
- package/dist/signing/signers.d.ts.map +1 -1
- package/dist/types/backend-responses.d.ts +1 -1
- package/dist/types/backend-responses.d.ts.map +1 -1
- package/dist/types/dto.d.ts +2 -2
- package/dist/types/dto.d.ts.map +1 -1
- package/dist/types/options.dto.d.ts +10 -10
- package/dist/types/user.dto.d.ts +13 -5
- package/dist/types/user.dto.d.ts.map +1 -1
- package/dist/wallet/GalaChainConnectProvider.d.ts.map +1 -1
- package/dist/wallet.cjs +1 -1
- package/dist/wallet.esm.js +1 -1
- package/package.json +32 -27
package/dist/native.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("zod"),t=require("ethers"),n=require("@gala-chain/gswap-sdk"),a=require("@solana/web3.js"),s=require("json-stringify-deterministic"),r=require("node:crypto"),i=require("@solana/spl-token"),o=require("bs58"),c=require("@gala-chain/connect"),l=require("uuid"),d=require("@gala-chain/api"),u=require("bignumber.js"),h=require("socket.io-client"),g=require("axios");function m(e){var t=Object.create(null);return e&&Object.keys(e).forEach(function(n){if("default"!==n){var a=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,a.get?a:{enumerable:!0,get:function(){return e[n]}})}}),t.default=e,Object.freeze(t)}var p=m(r);const f={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",GET_TOKEN_LIST:"/v1/users/:address/tokens",GET_TOKENS_HELD:"/v1/users/:address/tokens",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"},y="/v1/users/referrals/url",v="/v1/users/referrals",k="/v1/users/referrals/summary",b="/market/price-series",w="/v1/tokens/:tokenName/start-stream",S="/v1/tokens/:tokenName/stop-stream",A="/v1/tokens/:tokenName/stream/disable",E="/v1/tokens/:tokenName/stream/enable",T="/v1/tokens/:tokenName/reset-key",C="/v1/tokens/:tokenName/recordings",N="/v1/tokens/:tokenName/recordings/:assetId/download",I="/v1/tokens/:tokenName/recordings/:assetId",D="/v1/tokens/:tokenName/simulcasts",_="/v1/tokens/:tokenName/simulcasts",R="/v1/tokens/:tokenName/simulcasts/:targetId",x="/v1/config",O="/v1/config",F="/v1/config",B="/v1/tokens/:tokenName/role",U="/v1/roles",P="/v1/permissions",M="/v1/tokens/:tokenName/credentials",L="/auth/login",$="/auth/logout",K="/auth/refresh",G="/auth/session",W="/v1/tokens/:tokenName/bans",H="/v1/tokens/:tokenName/bans",q="/v1/tokens/:tokenName/bans/:userAddress",z="/v1/tokens/:tokenName/bans/:userAddress",j="/v1/tokens/:tokenName/active-users",V="/v1/user-bans",X="/v1/user-bans",Q="/v1/user-bans/:userAddress",J="/v1/user-bans/:userAddress",Y={CREATE:"/v1/api-keys",LIST:"/v1/api-keys",GET:"/v1/api-keys/:id",UPDATE:"/v1/api-keys/:id",REVOKE:"/v1/api-keys/:id"},Z="/v1/moderator-invites",ee="/v1/moderator-invites/claim",te="/v1/moderated-tokens",ne="/v1/moderator-invites",ae="/v1/moderator-invites/:id",se="/v1/moderator-invites/:id/role",re="/v1/moderator-invites/:id",ie="/v1/moderator-invites/code/:code",oe={CREATE:"/v1/content-flags",LIST:"/v1/content-flags",DISMISS:"/v1/content-flags/:id/dismiss",ACTION:"/v1/content-flags/:id/action"},ce="/v1/overseer-invites",le="/v1/overseer-invites",de="/v1/overseer-invites/code/:code",ue="/v1/overseer-invites/claim",he="/v1/overseer-invites/:id",ge="/v1/overseers",me="/v1/overseers",pe="/v1/overseers/:address",fe="/v1/overseers/me",ye="/v1/overseer-summary",ve="/v1/overseer-summary/bans",ke="/v1/overseer-summary/token-bans",be="/v1/overseer-summary/invites",we="/v1/overseer-summary/flags",Se="/v1/overseer-summary/users",Ae="/v1/users",Ee="/v1/users/:address/summary",Te="/v1/cache/flush/address/:address",Ce="/v1/cache/flush/token/:tokenName",Ne="/v1/cache/flush/all",Ie="/v1/cache/flush/wallet-aliases/:address",De="/v1/cache/flush/wallet-aliases",_e="/v1/token-bans",Re="/v1/token-bans",xe="/v1/token-bans/:tokenName",Oe="/v1/token-bans/:tokenName",Fe="/v1/reactions",Be="/v1/reactions",Ue="/v1/trades",Pe={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"},Me="/v1/restricted-token-names",Le="/v1/restricted-token-names",$e="/live/:tokenName/chat",Ke="/live/:tokenName/chat",Ge="/live/:tokenName/chat",We="/live/:tokenName/chat/slow-mode",He={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"},qe="/v1/stats",ze="/v1/trading/fee",je="/v1/trading/sale-details",Ve="/v1/trading/quote",Xe="/v1/trading/premint-quote",Qe={GET_LEADERBOARD:"/weekly-challenge",GET_TOKEN_HISTORY:"/weekly-challenge/history/:vaultAddress"},Je="/v1/notifications/register",Ye="/v1/notifications/unregister",Ze="/v1/notifications/preferences",et="/v1/notifications/preferences",tt="/v1/config/client-flags",nt="native",at="exact";function st(e){return e instanceof Error}function rt(e){return st(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 it(e){return st(e)||"object"==typeof e&&null!==e&&"stack"in e&&"string"==typeof e.stack?e.stack:void 0}function ot(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 ct(e){return"object"==typeof e&&null!==e&&"message"in e&&("response"in e||"request"in e||"config"in e)}function lt(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 a=n.Status;if("number"!=typeof a)throw new Error(`${t}: Response Status must be a number, got ${typeof a}`);if(1!==a)throw new Error(`${t}: Response status indicates failure (Status: ${a})`);return n}function dt(e){if(null==e||"object"!=typeof e)return"";const t=e.Message;return"string"==typeof t&&t.trim().length>0?` - ${t}`:""}function ut(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)}}}const ht="Token name is required and must be a string",gt=e=>`Could not find vault address for token: ${e}`,mt="REQUIRED",pt="INVALID_TYPE",ft="INVALID_VALUE",yt="INVALID_FORMAT",vt="TOO_LARGE",kt="INVALID_RANGE";class bt extends Error{constructor(e,t,n){super(e),this.field=t,this.code=n,this.name="ValidationError"}}class wt extends Error{constructor(e,t,n){super(e),this.statusCode=t,this.originalError=n,this.name="NetworkError"}}class St extends Error{constructor(e,t){super(e),this.field=t,this.name="ConfigurationError"}}class At extends Error{constructor(e,t,n){super(e),this.transactionId=t,this.code=n,this.name="TransactionError"}}function Et(e,t){return void 0!==t?t:e.charAt(0).toUpperCase()+e.slice(1)}function Tt(e,t){return new bt(`Token "${e}" not found. Please verify the token name is correct.`,"tokenName","TOKEN_NOT_FOUND")}function Ct(e,t){const n=Et(e,t);return new bt(`${n} is required`,e,"REQUIRED")}function Nt(e,t,n){const a=Et(e,n);return new bt(`${a} must be ${t}`,e,"INVALID_FORMAT")}function It(e,t,n){return new wt(e,t,n)}function Dt(e,t){return new St(e,t)}function _t(e,t,n){return new At(e,t,n)}function Rt(e,t,n,a){n&&n.error(`${t}:`,e);const s=ct(e)?e.response?.status:void 0;return It(`${t}: ${rt(e)}`,s,st(e)?e:void 0)}function xt(e,t,n,a,s){const r=Et(e,s);return new bt(`${r} must be between ${t} and ${n}${void 0!==a?`, received: ${a}`:""}`,e,"OUT_OF_RANGE")}function Ot(e,t,n,a){const s=Et(e,a);return new bt(`${s} must be at least ${t}${void 0!==n?`, received: ${n}`:""}`,e,"TOO_SMALL")}function Ft(e,t,n,a){const s=Et(e,a);return new bt(`${s} must be at most ${t}${void 0!==n?`, received: ${n}`:""}`,e,"TOO_LARGE")}function Bt(e,t,n,a){const s=Et(e,a),r=void 0!==n?`, received: ${"object"==typeof n?"object":String(n)}`:"";return new bt(`${s} must be ${t}${r}`,e,"INVALID_TYPE")}function Ut(e,t,n){const a=Et(e,n);return new bt(`${a} must be a valid number${void 0!==t?`: "${t}"`:""}`,e,"INVALID_NUMBER")}function Pt(e,t,n,a){const s=Et(e,a);return new bt(`Invalid ${s}: ${t}. Must be one of: ${n.join(", ")}`,e,"INVALID_ENUM")}function Mt(e){return null!=e&&"object"==typeof e&&"data"in e}function Lt(e,t,n=!1){const a=!0===e.error,s=n&&(null===e.data||void 0===e.data);if(a||s){const n=e?.statusCode??e.status??void 0;throw It(e?.message??t,n)}}function $t(e){if(Mt(e))return e.data}function Kt(e,t="No data found in response"){if(!Mt(e))throw It(t);const n=e.data;if(null==n)throw It(t);return n}async function Gt(e,t={}){return qt(e,t,e=>{if(void 0===e.data)throw new bt(`${t.errorContext??"Operation failed"}: No data returned from API`,"data","NO_DATA");return e.data})}async function Wt(e,t={}){const{errorContext:n="Operation failed",logger:a,debugLogEnabled:s=!1}=t;s&&a&&a.debug(`${n}: starting operation`);try{const t=await e();return s&&a&&a.debug(`${n}: completed successfully`),t}catch(e){throw a&&a.error(n,{error:e}),e}}async function Ht(e,t={}){return qt(e,t,e=>e)}async function qt(e,t,n){const{errorContext:a="Operation failed",logger:s,debugLogEnabled:r=!1}=t;r&&s&&s.debug(`${a}: starting operation`);try{const t=await e();if(null==t)throw new bt(`${a}: No response from server`,"response","NO_RESPONSE");return Lt(t,a,!0),r&&s&&s.debug(`${a}: completed successfully`),n(t)}catch(e){throw s&&s.error(a,{error:e}),e}}const zt={BASE_PRICE:1650667151e-14,PRICE_SCALING_FACTOR:1166069e-12,TRADING_FEE_FACTOR:.001,GAS_FEE:"1",DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY:1e7};function jt(e){return e.trim().toLowerCase()}function Vt(e){return e.trim().toUpperCase()}function Xt(e){return e.trim().toUpperCase()}var Qt;!function(e){e.DEBUG="DEBUG",e.INFO="INFO",e.WARN="WARN",e.ERROR="ERROR"}(Qt||(Qt={}));class Jt{constructor(e){this.levelPriority={[Qt.DEBUG]:0,[Qt.INFO]:1,[Qt.WARN]:2,[Qt.ERROR]:3},this.debugEnabled=e.debug,this.context=e.context??"SDK",this.minLevel=e.minLevel??(e.debug?Qt.DEBUG:Qt.INFO)}debug(e,t){this.log(Qt.DEBUG,e,t)}info(e,t){this.log(Qt.INFO,e,t)}warn(e,t){this.log(Qt.WARN,e,t)}error(e,t){this.log(Qt.ERROR,e,t)}log(e,t,n){if(this.levelPriority[e]<this.levelPriority[this.minLevel])return;if(e===Qt.DEBUG&&!this.debugEnabled)return;const a=`[${(new Date).toISOString()}] [${this.context}] [${e}]`,s=this.getConsoleMethod(e);void 0!==n?st(n)?s(`${a} ${t}`,n.message,it(n)??""):s(`${a} ${t}`,n):s(`${a} ${t}`)}getConsoleMethod(e){switch(e){case Qt.DEBUG:return console.debug;case Qt.INFO:return console.info;case Qt.WARN:return console.warn;case Qt.ERROR:return console.error;default:return console.log}}child(e){return new Jt({debug:this.debugEnabled,context:`${this.context}:${e}`,minLevel:this.minLevel})}isDebugEnabled(){return this.debugEnabled&&this.levelPriority[Qt.DEBUG]>=this.levelPriority[this.minLevel]}}function Yt(e){return null==e||""===e}function Zt(e){return null==e}const en=new Jt({debug:!1,context:"DateUtils"});function tn(e,t){if(null==e)return t??new Date;if(e instanceof Date)return isNaN(e.getTime())?t??new Date:e;try{const n=new Date(e);return isNaN(n.getTime())?(en.warn(`Invalid date string received: "${e}". Using fallback.`),t??new Date):n}catch(n){return en.warn(`Date parsing error for "${e}":`,n),t??new Date}}function nn(e){if(null==e)return!1;if(e instanceof Date)return!isNaN(e.getTime());if("string"!=typeof e)return!1;const t=new Date(e);return!isNaN(t.getTime())}function an(e){return Date.now()-e}const sn={MIN_LENGTH:3,MAX_LENGTH:20,PATTERN:/^[a-zA-Z0-9]{3,20}$/},rn={MIN_LENGTH:2,MAX_LENGTH:20,PATTERN:/^[a-zA-Z0-9]+$/},on={MIN_LENGTH:1,MAX_LENGTH:50},cn=100,ln=20,dn={MAX_LIMIT:50},un={PATTERN:/^(eth\|[0-9a-fA-F]{40}|client\|[a-zA-Z0-9_-]+)$/},hn={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}},gn={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})$/}},mn=60,pn=31536e3,fn={MAX_LENGTH:64,PATTERN:/^(galaswap-operation-|galaconnect-operation-)/},yn={PATTERN:/^[a-fA-F0-9]{64}$/},vn={STREAM_URL_PATTERN:/^(rtmps?|srt):\/\/.+/},kn=50,bn=1,wn=100,Sn={FULL_NAME:{MIN_LENGTH:1,MAX_LENGTH:100,ALPHABETS_ONLY_PATTERN:/^[a-zA-Z]+(?:\s[a-zA-Z]+)?$/}};function An(e,t){if(Yt(e))return t;try{return JSON.parse(e)}catch{return t}}function En(e,t=0){if(Yt(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 Tn(e,t,n){if(Zt(e))return t;if("number"==typeof e)return isNaN(e)?t:e;const a=Number(e);return isNaN(a)?t:a}function Cn(e,t,n){if(Zt(e))return t;if("bigint"==typeof e)try{return Number(e)}catch{return t}if("number"==typeof e)return isNaN(e)?t:Math.floor(e);const a=parseInt(String(e),10);return isNaN(a)?t:a}function Nn(e,t){if(Zt(e)||""===e)throw Ct(t);if(u.isBigNumber(e)){if(e.isNaN())throw Ut(t,"NaN");return e}try{const n=new u(e);if(n.isNaN())throw Ut(t,e);if(!n.isFinite())throw Ut(t,e);return n}catch(n){if(n instanceof bt)throw n;throw Ut(t,e)}}function In(e,t=0){if(Zt(e))return t;if("number"==typeof e)return isNaN(e)?t:e;return En(String(e).replace("%","").trim(),t)}function Dn(e,t=18){const n=En(e,0);if(0===n)return"0";return n.toFixed(t).replace(/\.?0+$/,"")}function _n(e){return Dn(e,8)}function Rn(e){return Dn(e,18)}function xn(e,t,n,a){if("number"!=typeof e)throw Bt(a,"a number",e,a);if(e<t||e>n)throw xt(a,t,n,e)}function On(e,t,n){if("string"!=typeof e)throw Bt(n,"a string",e,n);if(e.length>t)throw Ft(n,t,e.length)}function Fn(e,t){if("number"!=typeof e)throw Bt(t,"a number",e,t);if(!Number.isInteger(e))throw Bt(t,"an integer",e,t);if(e<=0)throw Ot(t,1,e,t)}function Bn(e,t,n=!1){if("string"!=typeof e)throw Bt(t,"a string",e,t);if(!n&&0===e.trim().length)throw Ct(t,`${t} (non-empty string)`)}const Un={ETH_ADDRESS:/^0x[0-9a-fA-F]{40}$/,BACKEND_ADDRESS:/^eth\|(0x)?[0-9a-fA-F]{40}$/,CLIENT_ADDRESS:/^client\|[a-zA-Z0-9_-]+$/},Pn=function(e){return"string"==typeof e&&e.trim().length>0},Mn=Zt;function Ln(e,t,n=100,a,s){if(void 0!==s&&"string"!=typeof s)throw new bt("cursor must be a string","cursor",pt);const r=a??t,i=void 0!==a?"pageSize":"limit";if(void 0!==r&&(Fn(r,i),r>n))throw new bt(`${i} must be at most ${n}`,i,vt)}function $n(e){const t=Object.values(e);return e=>"string"==typeof e&&t.includes(e)}function Kn(e){return Object.values(e)}function Gn(e,t,n,a={}){const{description:s="parameter",treatEmptyAsNull:r=!0}=a,i=e[t],o=e[n],c=null!=i&&(!r||""!==i),l=null!=o&&(!r||""!==o);if(!c&&!l)throw Dt(`Either ${t} or ${n} must be provided (${s})`,n);if(c&&l)throw Dt(`Cannot provide both ${t} and ${n}. Provide exactly one (${s}).`,n);return{chosen:c?t:n,hasA:c,hasB:l}}function Wn(e,t="tokenName",n=sn){if(!Pn(e))throw Ct(t);const a=e.trim();if(0===a.length)throw Ct(t);if(a.length<n.MIN_LENGTH)throw xt(t,n.MIN_LENGTH,n.MAX_LENGTH,a.length,`${t} length`);if(a.length>n.MAX_LENGTH)throw xt(t,n.MIN_LENGTH,n.MAX_LENGTH,a.length,`${t} length`);if(!n.PATTERN.test(a))throw new bt(`${t} must contain only alphanumeric characters`,t,yt)}function Hn(e,t="tokenName",n=sn){if(null==e)throw Ct(t,t);if("string"!=typeof e)throw Bt(t,"a string",e);const a=e.trim();if(0===a.length)throw Ct(t,t);if(!n.PATTERN.test(a))throw new bt(`${t} must be ${n.MIN_LENGTH}-${n.MAX_LENGTH} alphanumeric characters`,t,yt)}function qn(e){return""===e||0===e.trim().length}function zn(e,t,n){if(!Mn(e)){if("string"!=typeof e)throw Bt(t,"a string",e,t);if(e.length>n)throw new bt(`${t} must be at most ${n} characters`,t,vt)}}function jn(e,t){Mn(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 Bt(t,"a date",e,t);if(isNaN(n.getTime()))throw new bt(`${t} must be a valid date`,t,yt)}(e,t)}function Vn(e,t,n){try{Fn(e,t)}catch{throw function(e,t,n,a="OPERATION_FAILED"){return new bt(`${e} failed: ${t}`,n,a)}(n,"must be a positive integer",t)}}function Xn(e,t,n="status"){void 0!==e&&function(e,t,n){const a=Object.values(t);if(!a.includes(e))throw new bt(`${n} must be one of: ${a.join(", ")}`,n,yt)}(e,t,n)}class Qn{constructor(e,t=!1,n){this.http=e,this.logger=new Jt({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 St("JWT authentication required. Call sdk.login() first.")}return this.jwtAuth.getJwtHeaders()}isCalledFromUserCode(){const e=it(new Error)??"";return!(!e.includes("expect")&&!e.includes("jest"))||!(!e.includes("tests/")&&!e.includes(".test.ts"))}validatePositiveInteger(e,t,n){Vn(e,t,n)}}class Jn{constructor(e=!1,t){this.logger=t||new Jt({debug:e,context:this.constructor.name})}}class Yn extends Jn{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 Zn extends Yn{constructor(e=!1){super(e)}normalizeKey(e){return jt(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>=Zn.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??zt.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,a)=>{n.lastUpdated<e&&(e=n.lastUpdated);let s=0;s+=2*a.length,void 0!==n.reverseBondingCurveMinFeeFactor&&(s+=8),void 0!==n.reverseBondingCurveMaxFeeFactor&&(s+=8),void 0!==n.reverseBondingCurveNetFeeFactor&&(s+=8),s+=8,void 0!==n.vaultAddress&&""!==n.vaultAddress&&(s+=2*n.vaultAddress.length),void 0!==n.maxSupply&&""!==n.maxSupply&&(s+=2*n.maxSupply.length),void 0!==n.symbol&&""!==n.symbol&&(s+=2*n.symbol.length),s+=32,t+=s}),{cacheSize:t,oldestEntry:this.cache.size>0?e:0}}getByTokenId(e){const t=`token:${jt(e)}`;return this.cache.get(t)??null}setByTokenId(e,t){const n=`token:${jt(e)}`;this.updateCacheEntry(n,t)}hasByTokenId(e){const t=`token:${jt(e)}`;return this.cache.has(t)}}function ea(e){return""===e?"":e.startsWith("0x")?e.slice(2):e}Zn.MAX_CACHE_SIZE=1e4;const ta={ETHEREUM:Un.ETH_ADDRESS,ETHEREUM_NO_PREFIX:/^[a-fA-F0-9]{40}$/,BACKEND:Un.BACKEND_ADDRESS,CLIENT:Un.CLIENT_ADDRESS};class na{toBackendFormat(e){if(!Pn(e))throw new bt("Address is required and must be a string","address","REQUIRED");let n=e;if(e.startsWith("eth|")){if(n=e.slice(4),!/^[a-fA-F0-9]{40}$/.test(n))throw new bt(`Invalid Ethereum address format in backend address. Expected 40 hex characters after 'eth|'. Got: "${e}"`,"address","INVALID_FORMAT");return e}if(n=ea(e),!/^[a-fA-F0-9]{40}$/.test(n))throw new bt(`Invalid Ethereum address format. Expected 40 hex characters (with or without 0x prefix). Got: "${e}"`,"address","INVALID_FORMAT");return`eth|${t.getAddress(`0x${n}`).slice(2)}`}toEthereumFormat(e){if(!Pn(e))throw new bt("Backend address is required and must be a string","address","REQUIRED");const t=e.match(/^eth\|(0x)?([0-9a-fA-F]{40})$/i);if(!t)throw new bt(`Invalid backend address format. Expected "eth|{40-hex-characters}" or "eth|0x{40-hex-characters}". Got: "${e}"`,"address","INVALID_FORMAT");const n=t[1],a=void 0!==n&&""!==n?6:4;return`0x${e.substring(a)}`}normalizeInput(e){if(void 0!==e&&""!==e){if(e.startsWith("client|")){if(!ta.CLIENT.test(e))throw new bt(`Invalid client address format: "${e}"`,"address","INVALID_FORMAT");return e}if(e.startsWith("eth|")){if(!ta.BACKEND.test(e))throw new bt(`Invalid backend address format: "${e}"`,"address","INVALID_FORMAT");return e}return this.toBackendFormat(e)}}isValid(e){return!!Pn(e)&&(!!ta.ETHEREUM.test(e)||(!!ta.ETHEREUM_NO_PREFIX.test(e)||(!!ta.BACKEND.test(e)||!!ta.CLIENT.test(e))))}assertValid(e,t="address"){if(!this.isValid(e))throw new bt(`${t} must be a valid wallet address (Ethereum or backend format)`,t,"INVALID_FORMAT")}detectFormat(e){return Pn(e)?ta.ETHEREUM.test(e)||ta.ETHEREUM_NO_PREFIX.test(e)?"ethereum":ta.BACKEND.test(e)?"backend":ta.CLIENT.test(e)?"client":null:null}normalize(e){if(void 0!==e&&""!==e)return e.toLowerCase()}extractHex(e){if(e.startsWith("eth|"))return e.substring(4).toLowerCase();if(e.startsWith("0x"))return ea(e).toLowerCase();if(/^[a-fA-F0-9]{40}$/.test(e))return e.toLowerCase();throw new bt(`Cannot extract hex from address: "${e}". Expected Ethereum or backend format.`,"address","INVALID_FORMAT")}}const aa=new na,sa=ea;function ra(e){return aa.toBackendFormat(e)}function ia(e){return aa.toEthereumFormat(e)}function oa(e){return aa.isValid(e)}function ca(e,t="address"){aa.assertValid(e,t)}function la(e){return aa.detectFormat(e)}var da=Object.freeze({__proto__:null,AddressFormatter:na,assertValidWalletAddress:ca,detectFormat:la,fromBackendAddressFormat:ia,isValidAddress:oa,normalizeAddressInput:function(e){return aa.normalizeInput(e)},stripHexPrefix:sa,toBackendAddressFormat:ra});const ua=e.z.string({message:"Token name is required"}).min(3,"Token name must be at least 3 characters").max(20,"Token name must be at most 20 characters").regex(/^[a-zA-Z0-9]{3,20}$/,"Token name can only contain letters and numbers"),ha=e.z.string({message:"Token symbol is required"}).min(1,"Token symbol must be at least 1 character").max(8,"Token symbol must be at most 8 characters").regex(/^[A-Z]{1,8}$/,"Token symbol must be uppercase letters only"),ga=e.z.string({message:"Token description is required"}).min(1,"Token description is required").max(500,"Token description must be at most 500 characters"),ma=e.z.string().min(1,"Token name must be at least 1 character").max(50,"Token name must be at most 50 characters"),pa=e.z.string().min(1,"Search query must be at least 1 character").max(100,"Search query must be at most 100 characters"),fa=e.z.string().min(1,"Full name is required").max(100,"Full name must be at most 100 characters").regex(/^[a-zA-Z\s]+$/,"Full name can only contain letters and spaces");e.z.string().regex(Un.BACKEND_ADDRESS,"Address must be in format: eth|[40-hex-chars]"),e.z.string().regex(Un.ETH_ADDRESS,"Invalid Ethereum address format");const ya=e.z.string().refine(e=>Un.BACKEND_ADDRESS.test(e)||Un.ETH_ADDRESS.test(e)||Un.CLIENT_ADDRESS.test(e),"Address must be eth|[40-hex], 0x[40-hex], or client|[identifier] format").transform(e=>(new na).normalizeInput(e)??e),va=e.z.string().refine(e=>Un.BACKEND_ADDRESS.test(e)||/^service\|Token\$Unit\$[A-Z0-9]+\$eth:[0-9a-fA-F]{40}\$launchpad$/.test(e),"Invalid vault address format"),ka=e.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>En(e,0)>0,"Amount must be greater than zero"),ba=e.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>En(e,0)>=0,"Amount must be zero or greater");e.z.string().url("Must be a valid URL").regex(/^https?:\/\//,"URL must start with http:// or https://");const wa=e.z.string().optional().refine(e=>void 0===e||""===e||/^https?:\/\/.+\..+/.test(e),"Must be a valid URL if provided");function Sa(t=100){return e.z.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.z.number().int("Page must be an integer").min(1,"Page must be at least 1").max(1e3,"Page must be at most 1000").default(1),Sa(100),Sa(20),Sa(20);const Aa=e.z.number().int("File size must be an integer").min(1,"File must be at least 1 byte").max(10485760,"File must be at most 10MB"),Ea=e.z.string().max(255,"Filename must be at most 255 characters"),Ta=e.z.enum(["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"]);e.z.string().datetime("Must be a valid ISO 8601 date string"),e.z.number().int("Timestamp must be an integer").min(0,"Timestamp must be non-negative");const Ca=e.z.string().regex(/^0x[a-fA-F0-9]{64}$/,"Private key must be format: 0x + 64 hex characters");e.z.string().regex(/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/,"Transaction ID must be in UUID format"),e.z.string().regex(/^galaconnect-operation-[a-z0-9-]+$/,"Unique key must be format: galaconnect-operation-{unique-id}");const Na=[".png",".jpg",".jpeg",".gif",".webp",".svg"];e.z.object({file:e.z.union([e.z.instanceof(File),e.z.instanceof(Buffer)]),name:Ea,size:Aa,type:Ta});const Ia=e.z.instanceof(File).refine(e=>e.size>=1&&e.size<=10485760,"File size must be between 1 byte and 10MB").refine(e=>["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"].includes(e.type),"File must be a valid image type (PNG, JPG, JPEG, GIF, WebP, or SVG)").refine(e=>e.name.length<=255,"Filename must be at most 255 characters"),Da=e.z.instanceof(Buffer).refine(e=>e.length>=1&&e.length<=10485760,"Buffer size must be between 1 byte and 10MB");e.z.union([Ia,Da]),e.z.enum([".png",".jpg",".jpeg",".gif",".webp",".svg"]),Ea.refine(e=>{const t=e.slice(e.lastIndexOf(".")).toLowerCase();return Na.includes(t)},`Filename must end with one of: ${Na.join(", ")}`),e.z.object({websiteUrl:wa,telegramUrl:wa,twitterUrl:wa,instagramUrl:wa,facebookUrl:wa,redditUrl:wa,tiktokUrl:wa}).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 _a=e.z.string().min(1,"Token category must not be empty").default("Unit"),Ra=e.z.string().min(1,"Token collection must not be empty").default("Token"),xa=e.z.object({minFeePortion:e.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal string").refine(e=>En(e,0)>=.1,"Minimum fee must be >= 0.1").refine(e=>En(e,0)<=.5,"Minimum fee must be <= 0.5"),maxFeePortion:e.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal string").refine(e=>En(e,0)>=.1,"Maximum fee must be >= 0.1").refine(e=>En(e,0)<=.5,"Maximum fee must be <= 0.5")}).refine(e=>En(e.maxFeePortion,0)>=En(e.minFeePortion,0),{message:"Maximum fee must be >= minimum fee",path:["maxFeePortion"]}),Oa=e.z.object({tokenName:ua,tokenSymbol:ha,tokenDescription:ga,tokenImage:e.z.union([e.z.instanceof(File),e.z.instanceof(Buffer),e.z.string().url("Token image must be a valid URL")]).optional(),preBuyQuantity:ba.default("0"),websiteUrl:wa,telegramUrl:wa,twitterUrl:wa,instagramUrl:wa,facebookUrl:wa,redditUrl:wa,tiktokUrl:wa,tokenCategory:_a,tokenCollection:Ra,reverseBondingCurveConfiguration:xa.optional(),saleStartTime:e.z.number().int().positive().optional(),privateKey:Ca.optional()});e.z.object({file:e.z.union([e.z.instanceof(File),e.z.instanceof(Buffer)]),tokenName:ua}),e.z.enum(["RECENT","POPULAR"]);const Fa=e.z.object({tokenName:ua.optional(),symbol:ha.optional()}).refine(e=>void 0!==e.tokenName||void 0!==e.symbol,"At least one of tokenName or symbol is required");e.z.enum(["NATIVE","MEME"]),e.z.enum(["IN","OUT"]);const Ba=e.z.object({from:e.z.number().int("From timestamp must be an integer").min(173e6,"From timestamp must be at least 173000000"),to:e.z.number().int("To timestamp must be an integer").min(173e6,"To timestamp must be at least 173000000"),resolution:e.z.number().int("Resolution must be an integer").min(1,"Resolution must be at least 1"),tokenName:ua});e.z.object({tokenName:ua,slippageToleranceFactor:e.z.number().min(0).max(1).optional(),maxAcceptableReverseBondingCurveFeeSlippageFactor:e.z.number().min(0).max(1).optional(),privateKey:Ca.optional()});const Ua=e.z.object({offset:e.z.number().int().min(0).default(0),pageSize:e.z.number().int().min(1).max(100).default(10)}),Pa=e.z.object({offset:e.z.number().int().min(0).default(0),pageSize:e.z.number().int().min(1).max(20).default(10)}),Ma=e.z.object({offset:e.z.number().int().min(0).default(0),pageSize:e.z.number().int().min(1).max(20).default(10)});Ua.extend({type:e.z.enum(["RECENT","POPULAR"]).optional(),tokenName:e.z.string().min(1).max(50).optional(),search:e.z.string().min(1).max(100).optional()}),Pa.extend({tokenName:e.z.string().min(1).max(50).optional(),search:e.z.string().min(1).max(100).optional()}),Ma.extend({tradeType:e.z.enum(["BUY","SELL"]).optional(),tokenName:e.z.string().min(1).max(50).optional(),userAddress:e.z.string().regex(/^(0x[a-fA-F0-9]{40}|eth\|[a-fA-F0-9]{40})$/).optional(),startDate:e.z.string().datetime().optional(),endDate:e.z.string().datetime().optional(),sortOrder:e.z.enum(["ASC","DESC"]).default("DESC")});const La={page:e.z.number().int().min(1),limit:e.z.number().int().min(1),total:e.z.number().int().min(0),totalPages:e.z.number().int().min(0),hasNext:e.z.boolean(),hasPrevious:e.z.boolean()};e.z.object(La);const $a=e.z.enum(["buy","sell"]);e.z.enum(["BUY","SELL"]),e.z.object({tradeType:$a,tokenAmount:ka,vaultAddress:va,userAddress:ya,slippageTolerance:ka.optional(),deadline:e.z.number().int().positive().optional()}),e.z.object({tokenSymbol:ha,nativeTokenQuantity:ka,expectedToken:ka,maxAcceptableReverseBondingCurveFee:ba.default("0").optional()}),e.z.object({tokenSymbol:ha,tokenQuantity:ka,expectedNativeToken:ka,maxAcceptableReverseBondingCurveFee:ba.default("0").optional()}),Ma.extend({tokenName:ma.optional()}),e.z.object({page:e.z.number().int().min(1).max(1e3).default(1).optional(),limit:e.z.number().int().min(1).max(20).default(10).optional()});const Ka=e.z.enum(["NATIVE","MEME"]),Ga=e.z.enum(["IN","OUT"]);e.z.object({type:Ka,method:Ga,vaultAddress:va,amount:ka}),e.z.object({nativeTokenQuantity:ka}),e.z.object({vaultAddress:va}),e.z.object({minFeePortion:ka,maxFeePortion:ka});const Wa=e.z.enum(["all","DEFI","ASSET"]);function Ha(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)}}}Pa.extend({type:Wa.optional(),address:ya.optional(),search:pa.optional(),tokenName:ma.optional()}),e.z.object({address:ya.optional(),refresh:e.z.boolean().optional()}),e.z.object({profileImage:e.z.string(),fullName:fa,address:ya,privateKey:Ca.optional()}),e.z.object({file:e.z.union([e.z.instanceof(File),e.z.instanceof(Buffer)]),address:ya.optional(),privateKey:Ca.optional()}),e.z.object({created:e.z.number(),createdBy:e.z.string(),expires:e.z.number(),instanceId:e.z.string(),lockAuthority:e.z.string(),name:e.z.string(),quantity:e.z.string(),vestingPeriodStart:e.z.number()}),e.z.object({address:ya,tokenId:e.z.union([e.z.string(),e.z.object({collection:e.z.string(),category:e.z.string(),type:e.z.string(),additionalKey:e.z.string()}),e.z.object({collection:e.z.string(),category:e.z.string(),type:e.z.string(),additionalKey:e.z.string(),instance:e.z.string()})]).optional(),tokenName:ma.optional(),withExpired:e.z.boolean().optional()}).refine(e=>void 0!==e.tokenId||void 0!==e.tokenName,"At least one token identifier (tokenId or tokenName) is required");const qa=Ha(ua),za=Ha(Oa),ja=Ha(Fa);function Va(e){const t=function(e){const t=za(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 Xa(e,t){return"string"==typeof e[t]}function Qa(e,t){return void 0===e[t]||"string"==typeof e[t]}function Ja(e,t){return void 0===e[t]||"number"==typeof e[t]}function Ya(e,t){switch(t){case"string":return"string"==typeof e;case"number":return"number"==typeof e;case"boolean":return"boolean"==typeof e;case"object":return null!==e&&"object"==typeof e&&!Array.isArray(e);case"array":return Array.isArray(e);case"optional-string":return void 0===e||"string"==typeof e;case"optional-number":return void 0===e||"number"==typeof e;case"optional-boolean":return void 0===e||"boolean"==typeof e;case"optional-object":return void 0===e||null!==e&&"object"==typeof e&&!Array.isArray(e);case"optional-array":return void 0===e||Array.isArray(e);default:return!1}}function Za(e){return t=>{if(null==t||"object"!=typeof t||Array.isArray(t))return!1;const n=t;for(const[t,a]of Object.entries(e)){if(!Ya(n[t],a))return!1}return!0}}$n({BUY:"buy",SELL:"sell"});const es=Za({vaultAddress:"string"}),ts=Za({nativeTokenQuantity:"string"});function ns(e){if(Mn(e)||"object"!=typeof e)return{};const t={};for(const[n,a]of Object.entries(e))Mn(a)||(Pn(a)?t[n]=a:"number"==typeof a||"boolean"==typeof a?t[n]=a.toString():Array.isArray(a)?t[n]=a.join(","):t[n]="object"==typeof a?JSON.stringify(a):String(a));return t}function as(e,t="0"){return function(e,t="0"){if(Yt(e))return new u(t);if(u.isBigNumber(e))return e.isNaN()?new u(t):e;try{const n=new u(e);return n.isNaN()||!n.isFinite()?new u(t):n}catch{return new u(t)}}(e,t)}function ss(e,t){return void 0!==t?as(e).toFixed(t):as(e).toFixed()}function rs(e){return as(e).isZero()}function is(e,t){return as(e).isLessThan(as(t))}function os(...e){e.forEach(e=>{if(e.isNaN())throw Ut("value","NaN");if(!e.isFinite())throw Ft("value","finite");if(e.isLessThanOrEqualTo(0))throw Ot("value","0",e.toString())})}function cs(e,t,n="0"){const a=as(t);return rs(a)?as(n):as(e).dividedBy(a)}const ls={calculateBuyWithExact(e,t){const n=En(e),a=En(t),{BASE_PRICE:s,PRICE_SCALING_FACTOR:r,TRADING_FEE_FACTOR:i,GAS_FEE:o}=zt,c=function(e,t){const n=Math.pow(10,t);return Math.ceil(e*n)/n}(s*(Math.exp((a+n)*r)-Math.exp(a*r))/r,8),l=ss(as(c).multipliedBy(i));return{amount:c.toString(),reverseBondingCurveFee:"0",transactionFee:l,gasFee:o}},calculateBuyWithNative(e,t){const n=En(e),a=En(t),{BASE_PRICE:s,PRICE_SCALING_FACTOR:r,TRADING_FEE_FACTOR:i,GAS_FEE:o}=zt,c=Math.log(n*r/s+Math.exp(a*r))/r-a,l=ss(as(c).multipliedBy(i));return{amount:c.toString(),reverseBondingCurveFee:"0",transactionFee:l,gasFee:o}},calculateSellWithExact(e,t,n,a,s){const r=En(e),i=En(t),o=En(n),{BASE_PRICE:c,PRICE_SCALING_FACTOR:l,TRADING_FEE_FACTOR:d,GAS_FEE:u}=zt,h=c*(Math.exp(i*l)-Math.exp((i-r)*l))/l,g=as(h),m=a+i/o*(s-a),p=ss(g.multipliedBy(m),8),f=ss(g.multipliedBy(d));return{amount:h.toString(),reverseBondingCurveFee:p,transactionFee:f,gasFee:u}},calculateSellWithNative(e,t,n,a,s){const r=En(e),i=En(t),o=En(n),{BASE_PRICE:c,PRICE_SCALING_FACTOR:l,TRADING_FEE_FACTOR:d,GAS_FEE:u}=zt;if(r>=c*(Math.exp(i*l)-1)/l){const e=as(r),t=a+i/o*(s-a),n=ss(e.multipliedBy(t),8),c=ss(e.multipliedBy(d));return{amount:i.toString(),reverseBondingCurveFee:n,transactionFee:c,gasFee:u}}const h=i-Math.log(Math.exp(i*l)-r*l/c)/l,g=as(r),m=a+i/o*(s-a),p=ss(g.multipliedBy(m),8),f=ss(g.multipliedBy(d));return{amount:h.toString(),reverseBondingCurveFee:p,transactionFee:f,gasFee:u}}};class ds extends Error{constructor(e,t,n){super(e),this.filename=t,this.mimeType=n,this.name="FileValidationError"}}function us(e,t,n){if(null==e)throw new ds("File is required",t,n);if("undefined"!=typeof File&&e instanceof File){const t=Ia.safeParse(e);if(!t.success){const n=t.error.issues.map(e=>e.message).join("; ");throw new ds(n,e.name,e.type)}return}if(Buffer.isBuffer(e)){if(void 0===t||""===t)throw new ds("Filename is required when uploading Buffer objects",t,n);const a=Da.safeParse(e);if(!a.success){const e=a.error.issues.map(e=>e.message).join("; ");throw new ds(e,t,n)}try{On(t,255,"filename")}catch(e){throw new ds(e.message,t,n)}const s=["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"];if(!s.includes(n))throw new ds(`Invalid file type "${n}" is not allowed. Allowed types: ${s.join(", ")}`,t,n);const r=function(e){if(null==e||""===e)return"";const t=e.lastIndexOf(".");if(-1===t)return"";return e.substring(t).toLowerCase()}(t),i=[".png",".jpg",".jpeg",".gif",".webp",".svg"];if(!i.includes(r))throw new ds(`File extension "${r}" is not allowed. Allowed extensions: ${i.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"}}(r);if(o!==n&&"application/octet-stream"!==o)throw new ds(`File extension "${r}" does not match MIME type "${n}"`,t,n);return}throw new ds("File must be a File object (browser) or Buffer (Node.js)",t,n)}class hs{validate(e,t={}){const{allowZero:n=!0,minimum:a,maximum:s,maxDecimals:r=hs.MAX_DECIMAL_PLACES,fieldName:i="amount"}=t;if(!Pn(e))throw new bt(`${i} cannot be empty or whitespace-only. Provide a valid numeric string.`,i,"INVALID_NUMERIC_STRING");if(/[eE]/.test(e))throw new bt(`${i} cannot use scientific notation. Use standard decimal format (e.g., "1000" instead of "1e3").`,i,"INVALID_NUMERIC_STRING");const o=En(e,NaN);if(isNaN(o))throw new bt(`${i} must be a valid numeric string. Received: "${e}"`,i,"INVALID_NUMERIC_STRING");if(!isFinite(o))throw new bt(`${i} must be a finite number. Cannot be Infinity or -Infinity.`,i,"INVALID_NUMERIC_STRING");if(o<0)throw new bt(`${i} must be non-negative. Received: "${e}"`,i,"INVALID_NUMERIC_STRING");if(!n&&0===o)throw new bt(`${i} must be greater than zero. Received: "${e}"`,i,"INVALID_NUMERIC_STRING");const c=as(e),l=c.decimalPlaces()??0;if(l>r)throw new bt(`${i} cannot exceed ${r} decimal places. Received: ${l} decimal places`,i,"PRECISION_EXCEEDED");if(void 0!==a&&is(c,a))throw new bt(`${i} must be at least ${a}. Received: "${e}"`,i,"BELOW_MINIMUM");if(void 0!==s&&(d=s,as(c).isGreaterThan(as(d))))throw new bt(`${i} cannot exceed ${s}. Received: "${e}"`,i,"EXCEEDS_MAXIMUM");var d}parseAmount(e,t="0"){return as(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 ss(e,t)}clampAmount(e,t,n){const a=as(e),s=as(t),r=as(n);return function(e,t,n){const a=as(e),s=as(t),r=as(n);return a.isGreaterThanOrEqualTo(s)&&a.isLessThanOrEqualTo(r)}(a,s,r)?ss(a):is(a,s)?ss(s):ss(r)}}function gs(e,t){throw new bt(e.join("; "),t,"VALIDATION_ERROR")}function ms(e){const t=qa(e);!t.success&&t.errors&&gs(t.errors,"tokenName")}function ps(e){const t=Ba.safeParse(e);var n;t.success||gs((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 fs(e,t,n=!0){ys.validate(e,{fieldName:t,allowZero:n})}hs.MAX_DECIMAL_PLACES=18,hs.MIN_POSITIVE="0.00000000000000001";const ys=new hs;function vs(e,t,n=ss){if(!Array.isArray(e))throw It("Invalid API response: expected array of holders",t);for(const n of e){if(!ks(n))throw It("Invalid holder data: missing or invalid owner field",t);if(!bs(n))throw It("Invalid holder data: missing or invalid quantity field",t);const e=En(n.quantity,NaN);if(isNaN(e)||!isFinite(e))throw It(`Invalid holder quantity: "${n.quantity}"`,t)}const a=e,s=a.reduce((e,t)=>e.plus(t.quantity),as(0));return{holders:a.map(e=>({address:e.owner,balance:e.quantity,percentage:cs(as(e.quantity),s,as(0)).multipliedBy(100).toNumber()})),totalSupply:n(s),totalHolders:a.length,lastUpdated:new Date}}function ks(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.owner&&""!==t.owner}function bs(e){return"string"==typeof e.quantity&&""!==e.quantity}class ws{constructor(e,t,n,a,s,r,i="local",o){this.http=e,this.tokenResolver=t,this.logger=n,this.bundleHttp=a,this.galaChainHttp=s,this.dexApiHttp=r,this.defaultCalculateAmountMode=i,this.launchpadWrites=o,this.metadataCache=new Zn}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 uploadImageByTokenName(e){const{tokenName:t,options:n}=e;ms(t);const a=`${t}.png`;us(n.file,a,"image/png");try{const e=new FormData;if("undefined"!=typeof File&&n.file instanceof File)e.append("image",n.file);else{if(!Buffer.isBuffer(n.file))throw Nt("file","a File object (browser) or Buffer (Node.js)");{const a=`${void 0!==n.tokenName&&""!==n.tokenName?n.tokenName:t}.png`,s=new Blob([n.file],{type:"image/png"});e.append("image",s,a)}}const a=await this.http.request({method:"POST",url:`/launchpad/upload-image?tokenName=${encodeURIComponent(void 0!==n.tokenName&&""!==n.tokenName?n.tokenName:t)}`,data:e,headers:{}});if(!0===a.error||200!==a.status)throw It(void 0!==a.message&&""!==a.message?a.message:"Image upload failed - no URL returned",a.status);const s=$t(a);if(!s?.imageUrl)throw It("Image upload failed - no URL returned",a.status);return s.imageUrl}catch(e){if(st(e)&&e.message.includes("FormData"))throw Dt("File upload failed: FormData not supported in this environment. Ensure you have proper polyfills for Node.js environments.","FormData");throw e}}async fetchPoolsFromAPI(e){void 0!==e.pageSize&&Ln(0,void 0,100,e.pageSize),void 0!==e.tokenName&&""!==e.tokenName&&ms(e.tokenName);const t={pageSize:String(e.pageSize??10)};void 0!==e.cursor&&(t.cursor=e.cursor),void 0!==e.type&&(t.type=e.type),void 0!==e.tokenName&&(t.tokenName=e.tokenName),void 0!==e.search&&(t.search=e.search),void 0!==e.hasUpcomingShows&&(t.hasUpcomingShows=e.hasUpcomingShows.toString()),void 0!==e.language&&(t.language=e.language),void 0!==e.recentlyStreamed&&(t.recentlyStreamed=e.recentlyStreamed.toString());const n=ns(t),a=await this.http.get(f.FETCH_POOLS,n);if(!0===a.error||200!==a.status)throw It(void 0!==a.message&&""!==a.message?a.message:"Failed to fetch pools",a.status);const s=$t(a);if(null==s)throw It("Failed to fetch pools - no data returned",a.status);let r=[];if(s.tokens)if(Array.isArray(s.tokens))r=s.tokens.map(e=>this.normalizePoolData(e));else{const e=s.tokens;r=[this.normalizePoolData(e)]}else s.pools&&Array.isArray(s.pools)&&(r=s.pools.map(e=>this.normalizePoolData(e)));const{extractMetadataFromPoolData:i,isValidPoolForCaching:o}=await Promise.resolve().then(function(){return Eu});r.forEach(e=>{if(!o(e))return void this.logger.debug("Skipping pool with invalid structure for caching",e);const t=i(e,this.logger);t&&this.warmCacheFromPoolData(e.tokenName,t)});const c=s.count??s.total??0,l={hasNextPage:s.hasNextPage??!1};return void 0!==s.hasPrevPage&&(l.hasPrevPage=s.hasPrevPage),void 0!==s.nextCursor&&(l.nextCursor=s.nextCursor),void 0!==s.prevCursor&&(l.prevCursor=s.prevCursor),c>0&&(l.totalCount=c),{items:r,pageInfo:l}}async fetchPools(e={}){let t;"recent"===e.type?t="RECENT":"popular"===e.type&&(t="POPULAR");const n={pageSize:e.pageSize??10};return void 0!==e.cursor&&(n.cursor=e.cursor),void 0!==e.search&&""!==e.search&&(n.search=e.search),void 0!==e.tokenName&&""!==e.tokenName&&(n.tokenName=e.tokenName),null!=t&&(n.type=t),void 0!==e.hasUpcomingShows&&(n.hasUpcomingShows=e.hasUpcomingShows),void 0!==e.language&&""!==e.language&&(n.language=e.language),void 0!==e.recentlyStreamed&&(n.recentlyStreamed=e.recentlyStreamed),this.fetchPoolsFromAPI(n)}async calculateBuyAmount(e){if(null==e||"object"!=typeof e)throw Nt("options","an options object");const{tokenName:t,amount:n,type:a,currentSupply:s}=e;return"external"===this.validateAmountCalculationInputs(t,n,a,e.mode,[nt,at],'"native" or "exact"')?this.calculateBuyAmountExternal({tokenName:t,amount:n,type:a}):this.calculateBuyAmountLocal(this.addIfDefined({tokenName:t,amount:n,type:a},"currentSupply",s))}async calculateBuyAmountExternal(e){const{tokenName:t,amount:n,type:a}=e;return this.validateExternalAmountInputs(t,n),"exact"===a?Gt(()=>this.http.get(Ve,{tokenName:t,amount:n,type:"MEME",method:"OUT"}),{errorContext:`Failed to calculate buy amount for ${t} (exact tokens)`}):Gt(()=>this.http.get(Ve,{tokenName:t,amount:n,type:"NATIVE",method:"IN"}),{errorContext:`Failed to calculate buy amount for ${t} (native/GALA budget)`})}async calculateSellAmount(e){const{tokenName:t,amount:n,type:a,currentSupply:s,maxSupply:r,reverseBondingCurveMaxFeeFactor:i,reverseBondingCurveMinFeeFactor:o}=e;if("external"===this.validateAmountCalculationInputs(t,n,a,e.mode,[at,nt],'"exact" or "native"'))return this.calculateSellAmountExternal({tokenName:t,amount:n,type:a});{const e={tokenName:t,amount:n,type:a,...void 0!==s&&{currentSupply:s},...void 0!==r&&{maxSupply:r},...void 0!==i&&{reverseBondingCurveMaxFeeFactor:i},...void 0!==o&&{reverseBondingCurveMinFeeFactor:o}};return this.calculateSellAmountLocal(e)}}async calculateSellAmountExternal(e){const{tokenName:t,amount:n,type:a}=e;return this.validateExternalAmountInputs(t,n),"exact"===a?Gt(()=>this.http.get(Ve,{tokenName:t,amount:n,type:"MEME",method:"IN"}),{errorContext:`Failed to calculate sell amount for ${t} (exact tokens)`}):Gt(()=>this.http.get(Ve,{tokenName:t,amount:n,type:"NATIVE",method:"OUT"}),{errorContext:`Failed to calculate sell amount for ${t} (native/GALA target)`})}async calculateBuyAmountLocal(e){const{tokenName:t,amount:n,type:a,currentSupply:s}=e;if(!Pn(n))throw Ct("amount","Amount");if(a!==nt&&a!==at)throw Bt("type",'"native" or "exact"',a);void 0!==s&&fs(s,"currentSupply");const r=null==s||""===s;if(r&&(null==t||""===t))throw Ct("tokenName","Token name (required when currentSupply is not provided)");null!=t&&""!==t&&ms(t);let i=s;if(r){i=(await this.fetchPoolDetailsForCalculation(t)).currentSupply}return a===at?ls.calculateBuyWithExact(n,i):ls.calculateBuyWithNative(n,i)}async calculateSellAmountLocal(e){const{tokenName:t,amount:n,type:a,currentSupply:s,maxSupply:r,reverseBondingCurveMaxFeeFactor:i,reverseBondingCurveMinFeeFactor:o}=e;if(!Pn(n))throw Ct("amount","Amount");if(a!==at&&a!==nt)throw Bt("type",'"exact" or "native"',a);void 0!==s&&fs(s,"currentSupply");const c=null==s||""===s||null==r||""===r||void 0===i||void 0===o;if(c&&(null==t||""===t))throw Ct("tokenName","Token name (required when currentSupply, maxSupply, or fee factors are not provided)");null!=t&&""!==t&&ms(t);let l=s,d=r,u=i,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 a===at?ls.calculateSellWithExact(n,l,d,h,u):ls.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 Xa(t,"tokenName")&&function(e){return void 0===e.calculateAmountMode||"local"===e.calculateAmountMode||"external"===e.calculateAmountMode}(t)&&Qa(t,"currentSupply")}(e))throw Bt("options","CalculateBuyAmountForGraduationOptions or string (token name)",typeof e);const{tokenName:n,calculateAmountMode:a,currentSupply:s}=t;ms(n);const r=await this.fetchSaleDetails(n),i=s??ss(as(r.maxSupply).minus(r.sellingTokenQuantity)),o=r.sellingTokenQuantity;if("0"===o)throw Ct("tokenName",`Token ${n} is already graduated (no tokens remaining in pool)`);const c={tokenName:n,amount:o,type:"exact",currentSupply:i,...void 0!==a&&{mode:a}};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 Dt("Bundle backend client not configured. LaunchToken requires bundleHttp client.","bundleHttp");Va(e);const t=void 0!==e.preBuyQuantity&&""!==e.preBuyQuantity?e.preBuyQuantity:"0",n=En(t);if(0===n&&"0"!==t)throw Ut("preBuyQuantity",t,"Pre-buy quantity");if(n<0)throw Ut("preBuyQuantity",t,"Pre-buy quantity");if(e.reverseBondingCurveConfiguration){const{minFeePortion:t,maxFeePortion:n}=e.reverseBondingCurveConfiguration;!function(e,t,n){const a="string"==typeof e?parseFloat(e):e,s="string"==typeof t?parseFloat(t):t;if(!isFinite(a))throw new bt(`${n} minFee must be a valid finite number`,n,"INVALID_FEE_MINIMUM");if(!isFinite(s))throw new bt(`${n} maxFee must be a valid finite number`,n,"INVALID_FEE_MAXIMUM");if(a<.1)throw new bt(`${n} minFee must be >= 0.1, received ${a}`,n,"INVALID_FEE_MINIMUM");if(s>.5)throw new bt(`${n} maxFee must be <= 0.5, received ${s}`,n,"INVALID_FEE_MAXIMUM");if(a>s)throw new bt(`${n} minFee (${a}) must be <= maxFee (${s})`,n,"INVALID_FEE_RANGE")}(t,n,"reverseBondingCurve")}throw new Error("Legacy launchToken signing is unavailable; configure the v6 launchpad write transport.")}async fetchTokenDistribution(e){if(null==e||""===e)throw Ct("tokenName","Token name");ms(e);const t=await this.http.get(`/holders/${e}`);if(!0===t.error||200!==t.status)throw It(void 0!==t.message&&""!==t.message?t.message:"Failed to fetch token distribution",t.status);const n=$t(t);if(null==n)throw It("Failed to fetch token distribution - no data returned",t.status);return vs(n,t.status)}async calculateInitialBuyAmount(e){if(!ts(e))throw Nt("data","valid pre-mint calculation data");if(!this.galaChainHttp)throw Dt("GalaChain HTTP client not available. Please initialize SDK with gatewayBaseUrl.","galaChainHttp");try{const t={vaultAddress:"service|testToken",nativeTokenQuantity:e.nativeTokenQuantity,IsPreMint:!0},n=await this.galaChainHttp.post("/api/asset/launchpad-contract/CallMemeTokenOut",t);if(!function(e){if(null==e||"object"!=typeof e)return!1;const t=e,n=t.Status,a=t.Data;if("number"!=typeof n||"object"!=typeof a||null===a)return!1;const s=a,r=s.calculatedQuantity,i=s.extraFees;if("string"!=typeof r||"object"!=typeof i||null===i)return!1;const o=i;return"string"==typeof o.reverseBondingCurve&&"string"==typeof o.transactionFees}(n))throw It("Malformed response data from GalaChain gateway");try{lt(n,"Pre-mint calculation")}catch(e){throw It(rt(e),500)}const{calculatedQuantity:a,extraFees:s}=n.Data;return{amount:a,reverseBondingCurveFee:s.reverseBondingCurve,transactionFee:s.transactionFees,gasFee:"1"}}catch(e){if(st(e)&&e instanceof wt)throw e;throw It(rt(e),500)}}async fetchPoolDetailsForCalculation(e){const t=await this.fetchSaleDetails(e),n=ss(as(t.maxSupply).minus(t.sellingTokenQuantity)),a=t.sellingTokenQuantity,s=t.maxSupply;let r=.5,i=.1;const o=t.reverseBondingCurveConfiguration;null!=o?.maxFeePortion&&(r=In(o.maxFeePortion,.5)),null!=o?.minFeePortion&&(i=In(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=r-i;return this.metadataCache.set(e,{maxSupply:s,reverseBondingCurveMaxFeeFactor:r,reverseBondingCurveMinFeeFactor:i,reverseBondingCurveNetFeeFactor:c}),{currentSupply:n,remainingTokens:a,maxSupply:s,reverseBondingCurveMaxFeeFactor:r,reverseBondingCurveMinFeeFactor:i,reverseBondingCurveNetFeeFactor:c}}async fetchCurrentSupply(e){ms(e);const t=await this.fetchSaleDetails(e),n=ss(as(t.maxSupply).minus(t.sellingTokenQuantity)),a=t.maxSupply;return this.metadataCache.set(e,{maxSupply:a}),n}normalizePoolData(e){const t=e.reverseBondingCurveMinFeePortion??"0",n=e.reverseBondingCurveMaxFeePortion??"0";return{...e,reverseBondingCurveMinFeePortion:t,reverseBondingCurveMaxFeePortion:n,hasReverseBondingCurveFee:!rs(t)||!rs(n),createdAt:void 0!==e.created_at&&""!==e.created_at?e.created_at:void 0!==e.createdAt&&""!==e.createdAt?e.createdAt:""}}async fetchSaleDetails(e){const t=await this.tokenResolver.resolveTokenToVault(e);if(null==t||""===t)throw new bt(gt(e),"tokenName","VAULT_NOT_FOUND");if(void 0===this.galaChainHttp||null===this.galaChainHttp)throw Dt("GalaChain HTTP client not configured");const n=await this.galaChainHttp.post("/api/asset/launchpad-contract/FetchSaleDetails",{vaultAddress:t});if(1!==n.Status)throw It(`Failed to fetch pool details: Status ${n.Status}`,n.Status);return n.Data}validateAmountCalculationInputs(e,t,n,a,s,r){const i=a??this.defaultCalculateAmountMode;if("local"!==i&&"external"!==i)throw Bt("mode",'"local" or "external"',i);if(!Pn(e))throw Ct("tokenName","Token name");if(!Pn(t))throw Ct("amount","Amount");if("string"!=typeof n||!s.includes(n))throw Bt("type",r,n);return i}validateExternalAmountInputs(e,t){if("string"!=typeof e||""===e)throw new bt("Token name must be a non-empty string","tokenName","INVALID_TOKEN_NAME");if("string"!=typeof t||""===t)throw new bt("Amount must be a non-empty string","amount","INVALID_AMOUNT")}getAddress(){return this.http.getAddress()}formatAddressForBackend(e){return ra(e)}validateTokenName(e){return ms(e)}validatePagination(e){void 0!==e.pageSize&&Ln(0,void 0,100,e.pageSize)}async fetchTokenPrice(e){if(void 0===this.dexApiHttp||null===this.dexApiHttp)throw Dt("DEX API client not configured. Token price fetching requires dexApiHttp client.","dexApiHttp");if(null==e||""===e||Array.isArray(e)&&0===e.length)throw Ct("symbols","At least one symbol");const t=Array.isArray(e)?e.join(","):e;try{const e=await this.dexApiHttp.request({method:"GET",url:"/v1/tokens",params:{symbols:t}}),n=[];return void 0!==e.tokens&&null!==e.tokens&&Array.isArray(e.tokens)&&e.tokens.forEach(e=>{void 0!==e.currentPrices&&null!==e.currentPrices&&void 0!==e.symbol&&null!==e.symbol&&n.push({symbol:e.symbol,price:e.currentPrices.usd})}),n}catch(e){throw It(`Failed to fetch token prices: ${rt(e)}`,void 0,st(e)?e:void 0)}}warmCacheFromPoolData(e,t){this.metadataCache.warmFromPoolData(e,t)}getCacheStats(){return this.metadataCache.getStats()}clearCache(e){this.metadataCache.clear(e)}}const Ss=3e5,As="Sign in to Launchpad t:",Es="Authorization",Ts="Bearer ";class Cs{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 Ns,Is;!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"}(Ns||(Ns={}));class Ds extends Error{constructor(e,t,n){super(t),this.type=e,this.originalError=n,this.name="AuthError"}}class _s{constructor(e,t=Ss){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 Cs,this.refreshThresholdMs=t}setToken(e,t){if(!Pn(e))throw new Ds(Ns.SIGNATURE_FAILED,"JWT token must be a non-empty string");if("number"!=typeof t)throw new Ds(Ns.SIGNATURE_FAILED,"Token expiration must be a positive finite number (seconds)");if(!Number.isFinite(t))throw new Ds(Ns.SIGNATURE_FAILED,"Token expiration must be a positive finite number (seconds)");if(t<=0)throw new Ds(Ns.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,a){if(this.setToken(e,t),n){const e=Date.now()+1e3*(a??7776e3);if(!this.tokenState)throw new Ds(Ns.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:`${Ts}${e}`}getJwtHeaders(){const e=this.getAuthorizationHeader();if(null===e||""===e)throw new Ds(Ns.WALLET_NOT_CONNECTED,"No JWT token available. Call login() first.");return{[Es]: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 a=Date.now();this.tokenState={token:e,issuedAt:a,expiresAt:n};const s=await this.storage.get(this.STORAGE_KEYS.REFRESH_TOKEN),r=await this.storage.get(this.STORAGE_KEYS.REFRESH_EXPIRES);if(s&&r){const e=Number(r);Number.isFinite(e)&&Date.now()<e&&(this.tokenState.refreshToken=s,this.tokenState.refreshExpiresAt=e)}return!0}async clear(){this.tokenState=null,await this.storage.remove(this.STORAGE_KEYS.ACCESS_TOKEN),await this.storage.remove(this.STORAGE_KEYS.ACCESS_EXPIRES),await this.storage.remove(this.STORAGE_KEYS.REFRESH_TOKEN),await this.storage.remove(this.STORAGE_KEYS.REFRESH_EXPIRES)}isValid(){return this.hasToken()&&!this.isExpired()}getDebugInfo(){return{hasToken:this.hasToken(),isExpired:this.isExpired(),shouldRefresh:this.shouldRefresh(),timeUntilExpiryMs:this.getTimeUntilExpiry(),expiresAt:this.tokenState?new Date(this.tokenState.expiresAt):null}}}async function Rs(e,t,n,a){try{return await e()}catch(e){throw a?(a(e,t,n),new Error("Unreachable after error handler")):(n&&n.error(`${t}:`,e),Rt(e,t,n))}}function xs(e,t,n,a){try{return e()}catch(e){throw a?(a(e,t,n),new Error("Unreachable after error handler")):(n&&n.error(`${t}:`,e),Rt(e,t,n))}}class Os{constructor(e,t,n,a=!1){this.http=e,this.signatureAuth=t,this.jwtAuth=n,this.refreshPromise=null,this.loginPromise=null,this.logger=new Jt({debug:a,context:"SessionAuthService"})}async login(){if(this.loginPromise)return this.logger.debug("Login already in progress, reusing existing promise"),this.loginPromise;if(!this.signatureAuth.hasWallet())throw new Ds(Ns.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 Rs(async()=>{const e=Date.now(),t=`${As}${e}`;this.logger.debug("Generating login signature",{message:t,timestamp:e});const n=await this.signatureAuth.signMessage(t),a=this.signatureAuth.getAddress();ca(a,"address");const s={address:a,message:t,signature:n.signature};let r;try{this.logger.debug("Sending login request with refresh token support",{address:a,message:t}),r=await this.http.post(L,{...s,includeRefreshToken:!0})}catch(e){if(400!==e.statusCode)throw e;this.logger.debug("Login returned 400, retrying without includeRefreshToken (backend may not support it)"),r=await this.http.post(L,s)}const i=this.extractLoginData(r);return await this.jwtAuth.setTokens(i.accessToken,i.expiresIn,i.refreshToken,i.refreshExpiresIn),this.logger.debug("Login successful",{address:i.address,expiresIn:i.expiresIn,hasRefreshToken:!!i.refreshToken}),i},"SessionAuthService.performLogin",this.logger,e=>{if(e instanceof Ds)throw e;throw new Ds(Ns.SIGNATURE_FAILED,`Login failed: ${rt(e)}`,st(e)?e:void 0)})}async refresh(){if(this.refreshPromise)return this.logger.debug("Refresh already in progress, reusing existing promise"),this.refreshPromise;if(!this.jwtAuth.hasToken())throw new Ds(Ns.WALLET_NOT_CONNECTED,"No token to refresh. Call login() first.");this.refreshPromise=this.performRefresh();try{return await this.refreshPromise}finally{this.refreshPromise=null}}async performRefresh(){return Rs(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(K,{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(K,{},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 Ds)throw e;throw new Ds(Ns.SIGNATURE_FAILED,`Token refresh failed: ${rt(e)}`,st(e)?e:void 0)})}async logout(e){this.logger.debug("Logging out",{allDevices:e?.allDevices});const t=e?.allDevices??!1;if(t&&this.jwtAuth.hasToken()&&!this.jwtAuth.isExpired())try{await this.http.post($,{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): ${rt(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 Ds(Ns.WALLET_NOT_CONNECTED,"Not authenticated. Call login() first.");return Rs(async()=>{const e=await this.http.get(G,void 0,this.jwtAuth.getJwtHeaders());return this.extractSessionData(e)},"SessionAuthService.getSession",this.logger,e=>{if(e instanceof Ds)throw e;throw new Ds(Ns.SIGNATURE_FAILED,`Failed to get session: ${rt(e)}`,st(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(!this.jwtAuth.hasToken())throw new Ds(Ns.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: ${rt(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 Ds(Ns.SIGNATURE_FAILED,""!==rt(e)?rt(e):"Authentication failed");const t=Kt(e,"No data in authentication response"),{accessToken:n,expiresIn:a,address:s,refreshToken:r,refreshExpiresIn:i}=t;if(!Pn(n))throw new Ds(Ns.SIGNATURE_FAILED,"Invalid access token in response");if("number"!=typeof a||a<=0)throw new Ds(Ns.SIGNATURE_FAILED,"Invalid expiration in response");return{accessToken:n,expiresIn:a,address:s,...void 0!==r&&{refreshToken:r},...void 0!==i&&{refreshExpiresIn:i}}}extractSessionData(e){if(e.error)throw new Ds(Ns.SIGNATURE_FAILED,""!==rt(e)?rt(e):"Failed to get session");return Kt(e,"No data in session response")}}class Fs extends Error{constructor(e,t,n){super(e),this.code=t,this.originalError=n,this.name="WalletProviderError"}}!function(e){e.USER_REJECTED="USER_REJECTED",e.NOT_CONNECTED="NOT_CONNECTED",e.CONNECTION_FAILED="CONNECTION_FAILED",e.SIGNING_FAILED="SIGNING_FAILED",e.PROVIDER_NOT_AVAILABLE="PROVIDER_NOT_AVAILABLE",e.PRIVATE_KEY_NOT_ACCESSIBLE="PRIVATE_KEY_NOT_ACCESSIBLE",e.INVALID_CONFIG="INVALID_CONFIG",e.CHAIN_MISMATCH="CHAIN_MISMATCH",e.UNKNOWN="UNKNOWN"}(Is||(Is={}));class Bs{constructor(e){this.providerType="privateKey",this.connected=!0;try{this.wallet=new t.Wallet(e)}catch(e){throw new Fs("Invalid private key provided",Is.INVALID_CONFIG,e instanceof Error?e:void 0)}}static fromWallet(e){return new Bs(e.privateKey)}async signMessage(e){try{return await this.wallet.signMessage(e)}catch(e){throw new Fs("Failed to sign message",Is.SIGNING_FAILED,e instanceof Error?e:void 0)}}async signTypedData(e,t,n){try{return await this.wallet.signTypedData(e,t,n)}catch(e){throw new Fs("Failed to sign typed data",Is.SIGNING_FAILED,e instanceof Error?e:void 0)}}getAddress(){return Promise.resolve(t.getAddress(this.wallet.address))}async getGalaAddress(){return`eth|${(await this.getAddress()).slice(2)}`}async connect(){return this.connected=!0,this.getAddress()}disconnect(){return this.connected=!1,Promise.resolve()}isConnected(){return this.connected}getPrivateKey(){return Promise.resolve(this.wallet.privateKey)}getWallet(){return this.wallet}}class Us{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{Bn(e.messagePrefix,"messagePrefix",!1)}catch{throw new Ds(Ns.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=Bs.fromWallet(this.wallet),this.cachedAddress=this.wallet.address,this.cachedGalaAddress=ra(this.wallet.address)}catch(e){if(e instanceof Ds)throw e;if(e instanceof bt&&("INVALID_ADDRESS"===e.code||"INVALID_FORMAT"===e.code||"address"===e.field))throw new Ds(Ns.INVALID_ADDRESS,e.message);if(null!==e&&"object"==typeof e&&"message"in e)throw new Ds(Ns.WALLET_NOT_CONNECTED,e.message);throw e}}setWallet(e){if(void 0!==e){if("object"!=typeof e||!("address"in e))throw new Ds(Ns.WALLET_NOT_CONNECTED,"Invalid wallet: must be an ethers Wallet instance or undefined");if("string"!=typeof e.address||""===e.address)throw new Ds(Ns.INVALID_ADDRESS,"Wallet address is not available");this.walletProvider=Bs.fromWallet(e),this.cachedAddress=e.address,this.cachedGalaAddress=ra(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,this.cachedAddress=void 0,this.cachedGalaAddress=void 0}getWalletProvider(){return this.walletProvider}async cacheAddress(){this.walletProvider&&(this.cachedAddress=await this.walletProvider.getAddress(),this.cachedGalaAddress=await this.walletProvider.getGalaAddress())}async generateSignature(){await this.validateWalletAsync();try{const e=Date.now(),t=`${this.messagePrefix} ${e}`,n=await this.walletProvider.signMessage(t);return{message:t,signature:n,address:await this.walletProvider.getGalaAddress(),timestamp:e}}catch(e){if(e instanceof Ds)throw e;throw new Ds(Ns.SIGNATURE_FAILED,"Failed to generate signature for authentication",st(e)?e:new Error(rt(e)))}}getAddress(){if(this.validateWallet(),this.cachedGalaAddress)return this.cachedGalaAddress;if(this.wallet)return this.formatAddress(this.wallet.address);throw new Ds(Ns.WALLET_NOT_CONNECTED,"Address not available. For external wallets, call cacheAddress() after connecting.")}async getAddressAsync(){return await this.validateWalletAsync(),this.walletProvider.getGalaAddress()}getEthereumAddress(){if(this.validateWallet(),this.cachedAddress)return this.cachedAddress;if(this.wallet)return this.wallet.address;throw new Ds(Ns.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 Ds(Ns.WALLET_NOT_CONNECTED,"Wallet private key not available for @gala-chain signing");return this.wallet.privateKey}if("privateKey"===this.walletProvider?.providerType){return this.walletProvider.getWallet().privateKey}throw new Ds(Ns.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 Ds(Ns.WALLET_NOT_CONNECTED,"Private key not available with this wallet provider");try{return await this.walletProvider.getPrivateKey()}catch(e){throw new Ds(Ns.WALLET_NOT_CONNECTED,"Private key not available. External wallet providers cannot access private keys. Use PrivateKeyProvider for @gala-chain signing operations.",st(e)?e:void 0)}}formatAddress(e){try{return ra(e)}catch{throw new Ds(Ns.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 Ds)throw e;throw new Ds(Ns.SIGNATURE_FAILED,rt(e),st(e)?e:new Error(rt(e)))}}async generateAuthHeaders(e,t){await this.validateWalletAsync();try{const n=Date.now(),a=`${this.messagePrefix} ${t.toUpperCase()} ${e} ${n}`,s=await this.walletProvider.signMessage(a);return{"x-signature":s,"x-address":await this.walletProvider.getGalaAddress(),"x-message":a,"x-timestamp":n.toString()}}catch(e){if(e instanceof Ds)throw e;throw new Ds(Ns.SIGNATURE_FAILED,"Failed to generate authentication headers",st(e)?e:new Error(rt(e)))}}async signTypedData(e,t,n){await this.validateWalletAsync();try{const a={};for(const[e,n]of Object.entries(t))a[e]=n.map(e=>({name:e.name,type:e.type}));return await this.walletProvider.signTypedData(e,a,n)}catch(e){if(e instanceof Ds)throw e;throw new Ds(Ns.SIGNATURE_FAILED,"Failed to sign typed data",st(e)?e:new Error(rt(e)))}}async generateCustomSignature(e){if(!Pn(e))throw new Ds(Ns.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 Ds)throw e;throw new Ds(Ns.SIGNATURE_FAILED,"Failed to generate custom message signature",st(e)?e:new Error(rt(e)))}}validateWallet(){if(this.ensureWalletProvider(),!this.walletProvider)throw new Ds(Ns.WALLET_NOT_CONNECTED,"Wallet is required for authentication")}async validateWalletAsync(){if(this.ensureWalletProvider(),!this.walletProvider)throw new Ds(Ns.WALLET_NOT_CONNECTED,"Wallet is required for authentication");if(!this.walletProvider.isConnected())throw new Ds(Ns.WALLET_NOT_CONNECTED,"Wallet is not connected. Call connect() on the wallet provider first.")}}const Ps={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",gatewayBaseUrl:"https://gateway-mainnet.galachain.com",webSocketUrl:"https://bundle-backend-prod1.defi.gala.com",gdexWebSocketUrl:"wss://dex-backend-prod1.defi.gala.com/ws",dexApiBaseUrl:"https://dex-api-platform-dex-prod-gala.gala.com",launchpadFrontendUrl:"https://lpad-frontend-prod1.defi.gala.com"},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",gatewayBaseUrl:"https://gateway-testnet.galachain.com",webSocketUrl:"https://bundle-backend.stage.defi.ovh.gala.com",gdexWebSocketUrl:"wss://swap-backend.stage.defi.ovh.gala.com/ws",dexApiBaseUrl:"https://dex-api-platform-dex-stage-gala.gala.com",launchpadFrontendUrl:"https://lpad-frontend-test1.defi.gala.com"}};function Ms(e){return Ps[e]}function Ls(e){return`${e.collection}|${e.category}|${e.type}|${e.additionalKey}`}function $s(e){return`${e.collection}$${e.category}$${e.type}$${e.additionalKey}`}const Ks=1,Gs=2,Ws=1002,Hs=1,qs=3,zs=[{symbol:"GALA",amount:"1",contractAddress:"0xd1d2Eb1B1e90B638588728b4130137D262C87cae",bridgeUsesPermit:!0,decimals:8},{symbol:"GWETH",amount:"0.0001",contractAddress:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",bridgeUsesPermit:!1,decimals:18},{symbol:"GUSDC",amount:"1",contractAddress:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",bridgeUsesPermit:!1,decimals:6},{symbol:"GUSDT",amount:"1",contractAddress:"0xdAC17F958D2ee523a2206206994597C13D831ec7",bridgeUsesPermit:!1,decimals:6},{symbol:"GWTRX",amount:"1",contractAddress:"0x50327c6c5a14DCaDE707ABad2E27eB517df87AB5",bridgeUsesPermit:!1,decimals:6},{symbol:"GWBTC",amount:"0.00001",contractAddress:"0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599",bridgeUsesPermit:!1,decimals:8}],js=[{symbol:"GALA",amount:"1",contractAddress:"0x9fBFf09325C1967A135AC9b4860b1cf89aca52DA",bridgeUsesPermit:!0,decimals:8},{symbol:"GWETH",amount:"0.0001",contractAddress:"0xC3F00B9CbC4221D85A66EEbe928551d0d8dD9158",bridgeUsesPermit:!1,decimals:18},{symbol:"GUSDC",amount:"1",contractAddress:"0x081e78E33bfa612b23A99ef61e7c194649AA318E",bridgeUsesPermit:!1,decimals:6},{symbol:"GUSDT",amount:"1",contractAddress:"0x461e3595f087bfb0E32B6e44BCbF4C74D99B0001",bridgeUsesPermit:!1,decimals:6},{symbol:"GWBTC",amount:"0.00001",contractAddress:"0x5f69276935EF17e5aF5289b60aFBf6d48B344770",bridgeUsesPermit:!1,decimals:8}];function Vs(e){return"prod"===e?zs:js}function Xs(e){return"prod"===e?"0x9f452b7cC24e6e6FA690fe77CF5dD2ba3DbF1ED9":"0x6a1734E09f3099a3675645D214ce547080ea67e0"}const Qs=zs,Js=[{symbol:"GALA",amount:"1",mintAddress:"eEUiUs4JWYZrp72djAGF1A8PhpR6rHphGeGN7GbVLp6",isNative:!1,decimals:8},{symbol:"GSOL",amount:"0.001",mintAddress:"So11111111111111111111111111111111111111111",isNative:!0,decimals:9}],Ys={GALA:{descriptor:{collection:"GALA",category:"Unit",type:"none",additionalKey:"none"},decimals:8,channel:"asset"},GWETH:{descriptor:{collection:"GWETH",category:"Unit",type:"none",additionalKey:"none"},decimals:18,channel:"asset"},GUSDC:{descriptor:{collection:"GUSDC",category:"Unit",type:"none",additionalKey:"none"},decimals:6,channel:"asset"},GUSDT:{descriptor:{collection:"GUSDT",category:"Unit",type:"none",additionalKey:"none"},decimals:6,channel:"asset"},GWTRX:{descriptor:{collection:"GWTRX",category:"Unit",type:"none",additionalKey:"none"},decimals:6,channel:"asset"},GWBTC:{descriptor:{collection:"GWBTC",category:"Unit",type:"none",additionalKey:"none"},decimals:8,channel:"asset"},GSOL:{descriptor:{collection:"GSOL",category:"Unit",type:"none",additionalKey:"none"},decimals:9,channel:"asset"}},Zs=["function decimals() view returns (uint8)","function balanceOf(address owner) view returns (uint256)","function approve(address spender, uint256 value) returns (bool)","function allowance(address owner, address spender) view returns (uint256)","function transfer(address to, uint256 value) returns (bool)","function name() view returns (string)","function nonces(address owner) view returns (uint256)","function permit(address owner,address spender,uint256 value,uint256 deadline,uint8 v,bytes32 r,bytes32 s)"],er=["function bridgeOut(address token,uint256 amount,uint256 tokenId,uint16 destinationChainId,bytes recipient) external","function bridgeOutWithPermit(address token,uint256 amount,uint16 destinationChainId,bytes recipient,uint256 deadline,uint8 v,bytes32 r,bytes32 s) external"],tr={BRIDGE_OUT:Buffer.from([27,194,57,119,215,165,247,150]),BRIDGE_OUT_NATIVE:Buffer.from([243,44,75,224,249,206,98,79])};function nr(e){return/^0x[a-fA-F0-9]{64}$/.test(e)}function ar(e){const t=new Map;for(const n of e)t.set(Vt(n.symbol),n);return t}function sr(e,t,n){const a=function(e,t){return e.get(Vt(t))}(e,t);if(!a){throw Dt(`Token ${t} not supported for ${n}. Supported: ${Array.from(e.keys()).join(", ")}`,"tokenSymbol")}return a}function rr(e){if(null==e||!nr(e))throw Nt("privateKey","a 0x-prefixed 64-character hex string (e.g., 0x1234...abcd)","Ethereum private key")}function ir(e,t,n){return{symbol:e,quantity:t,decimals:n,contractAddress:null,isNative:!0}}function or(e,t){return{symbol:e.symbol,quantity:t,decimals:e.decimals??18,contractAddress:e.contractAddress,isNative:!1}}function cr(e,t){return{symbol:e.symbol,quantity:t,decimals:e.decimals??9,contractAddress:e.mintAddress,isNative:e.isNative??!1}}function lr(e,t,n){const a=e.find(e=>e.symbol===t);if(!a){const a=e.map(e=>e.symbol).join(", ");throw Ct("tokenSymbol",`Unsupported ${n} token: ${t}. Supported: ${a}`)}return a}const dr={Ethereum:"Ethereum bridging not configured. Provide ethereumPrivateKey in config.",Solana:"Solana bridging not configured. Provide solanaPrivateKey in config."};function ur(e,t,n){if(void 0===e)throw Dt(n??dr[t],`${t.toLowerCase()}Strategy`);return e}function hr(e){return{direction:"inbound",fromChain:e.fromChain,toChain:"GalaChain",transactionHash:e.transactionHash,tokenSymbol:e.tokenSymbol,amount:e.amount,timestamp:Date.now(),statusUrl:`${e.baseUrl}/v1/bridge/transaction?hash=${e.transactionHash}`}}const gr="Token symbol resolution failed. This is an internal error - BridgeService should resolve tokenId to symbol before calling strategy.",mr="Bridge request ID missing from RequestTokenBridgeOut response",pr="BridgeTokenOut response missing transaction hash";function fr(e){if(void 0===e||""===e)throw Dt(gr,"tokenSymbol");return e}function yr(e,n){if(!t.isAddress(e)){throw Nt(n??"address","a valid 0x-prefixed Ethereum address",e)}}function vr(e,t){try{return new a.PublicKey(e)}catch{throw Nt(t??"address","a valid Solana address (base58)",e)}}function kr(e){try{return new a.PublicKey(e)}catch{throw Nt("address","a valid Solana address (base58)",e)}}function br(e){const t={};for(const[n,a]of Object.entries(e))void 0!==a&&(a&&"object"==typeof a&&!Array.isArray(a)?t[n]=br(a):t[n]=a);return t}function wr(e,t){const n=En(e,-1);if(n<=0)throw new Error(`Invalid bridge amount for ${t}: "${e}". Amount must be a positive number.`);return n}let Sr=null;if("undefined"==typeof window&&"undefined"!=typeof require)try{Sr=p}catch{}function Ar(){if(void 0!==Sr?.randomUUID)try{return Sr.randomUUID()}catch{}if(void 0!==globalThis.crypto&&"function"==typeof globalThis.crypto.randomUUID)try{return crypto.randomUUID()}catch{}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}const Er={name:"GalaConnect",chainId:1},Tr=[{name:"destinationChainId",type:"uint256"},{name:"destinationChainTxFee",type:"destinationChainTxFee"},{name:"quantity",type:"string"},{name:"recipient",type:"string"},{name:"tokenInstance",type:"tokenInstance"},{name:"uniqueKey",type:"string"}],Cr=[{name:"collection",type:"string"},{name:"category",type:"string"},{name:"type",type:"string"},{name:"additionalKey",type:"string"}],Nr=[{name:"collection",type:"string"},{name:"category",type:"string"},{name:"type",type:"string"},{name:"additionalKey",type:"string"},{name:"instance",type:"string"}],Ir=[{name:"name",type:"string"},{name:"symbol",type:"string"}],Dr={GalaTransaction:Tr,destinationChainTxFee:[{name:"bridgeToken",type:"bridgeToken"},{name:"bridgeTokenIsNonFungible",type:"bool"},{name:"estimatedPricePerTxFeeUnit",type:"string"},{name:"estimatedTotalTxFeeInExternalToken",type:"string"},{name:"estimatedTotalTxFeeInGala",type:"string"},{name:"estimatedTxFeeUnitsTotal",type:"string"},{name:"galaDecimals",type:"uint256"},{name:"galaExchangeRate",type:"galaExchangeRate"},{name:"timestamp",type:"uint256"},{name:"signingIdentity",type:"string"},{name:"signature",type:"string"}],bridgeToken:Cr,galaExchangeRate:[{name:"identity",type:"string"},{name:"oracle",type:"string"},{name:"source",type:"string"},{name:"sourceUrl",type:"string"},{name:"timestamp",type:"uint256"},{name:"baseToken",type:"baseToken"},{name:"exchangeRate",type:"string"},{name:"externalQuoteToken",type:"externalQuoteToken"}],baseToken:Nr,externalQuoteToken:Ir,tokenInstance:Nr},_r={GalaTransaction:Tr,destinationChainTxFee:[{name:"bridgeToken",type:"bridgeToken"},{name:"bridgeTokenIsNonFungible",type:"bool"},{name:"estimatedPricePerTxFeeUnit",type:"string"},{name:"estimatedTotalTxFeeInExternalToken",type:"string"},{name:"estimatedTotalTxFeeInGala",type:"string"},{name:"estimatedTxFeeUnitsTotal",type:"string"},{name:"galaDecimals",type:"uint256"},{name:"galaExchangeCrossRate",type:"galaExchangeCrossRate"},{name:"timestamp",type:"uint256"},{name:"signingIdentity",type:"string"},{name:"signature",type:"string"}],bridgeToken:Cr,galaExchangeCrossRate:[{name:"baseTokenCrossRate",type:"baseTokenCrossRate"},{name:"crossRate",type:"string"},{name:"externalCrossRateToken",type:"externalCrossRateToken"},{name:"identity",type:"string"},{name:"oracle",type:"string"},{name:"quoteTokenCrossRate",type:"quoteTokenCrossRate"},{name:"source",type:"string"},{name:"timestamp",type:"uint256"}],baseTokenCrossRate:[{name:"identity",type:"string"},{name:"oracle",type:"string"},{name:"source",type:"string"},{name:"sourceUrl",type:"string"},{name:"timestamp",type:"uint256"},{name:"exchangeRate",type:"string"},{name:"externalBaseToken",type:"externalBaseToken"},{name:"externalQuoteToken",type:"externalQuoteToken"},{name:"signature",type:"string"}],externalBaseToken:Ir,externalQuoteToken:Ir,externalCrossRateToken:Ir,quoteTokenCrossRate:[{name:"identity",type:"string"},{name:"oracle",type:"string"},{name:"source",type:"string"},{name:"sourceUrl",type:"string"},{name:"timestamp",type:"uint256"},{name:"baseToken",type:"baseToken"},{name:"exchangeRate",type:"string"},{name:"externalQuoteToken",type:"externalQuoteToken"},{name:"signature",type:"string"}],baseToken:Nr,tokenInstance:Nr};async function Rr(e,t){const{wallet:n}=t,a=e.uniqueKey??`galaconnect-operation-${Ar()}`,r="string"==typeof e.destinationChainId?Cn(e.destinationChainId,1):e.destinationChainId,i=function(e){const t={...e,galaDecimals:"string"==typeof e.galaDecimals?Cn(e.galaDecimals,0):e.galaDecimals,timestamp:"string"==typeof e.timestamp?Cn(e.timestamp,0):e.timestamp};if(e.galaExchangeRate&&(t.galaExchangeRate={...e.galaExchangeRate,timestamp:"string"==typeof e.galaExchangeRate.timestamp?Cn(e.galaExchangeRate.timestamp,0):e.galaExchangeRate.timestamp}),e.galaExchangeCrossRate){const n=e.galaExchangeCrossRate;t.galaExchangeCrossRate={...n,timestamp:"string"==typeof n.timestamp?Cn(n.timestamp,0):n.timestamp},n.baseTokenCrossRate&&(t.galaExchangeCrossRate.baseTokenCrossRate={...n.baseTokenCrossRate,timestamp:"string"==typeof n.baseTokenCrossRate.timestamp?Cn(n.baseTokenCrossRate.timestamp,0):n.baseTokenCrossRate.timestamp}),n.quoteTokenCrossRate&&(t.galaExchangeCrossRate.quoteTokenCrossRate={...n.quoteTokenCrossRate,timestamp:"string"==typeof n.quoteTokenCrossRate.timestamp?Cn(n.quoteTokenCrossRate.timestamp,0):n.quoteTokenCrossRate.timestamp})}return t}(e.destinationChainTxFee),o=Boolean(i.galaExchangeCrossRate),c={destinationChainId:r,destinationChainTxFee:br(o?{...i,galaExchangeRate:void 0}:{...i,galaExchangeCrossRate:void 0}),quantity:e.quantity,recipient:e.recipient,tokenInstance:e.tokenInstance,uniqueKey:a},l=function(e){return e?_r:Dr}(o),d=await n.signTypedData(Er,l,c),u=`Ethereum Signed Message:\n${s({domain:Er,message:c,primaryType:"GalaTransaction",types:l}).length}`;return{...c,signature:d,prefix:u,types:l,domain:Er}}async function xr(e,t){const{amount:n,recipientAddress:a,tokenSymbol:s}=e,{galaConnectClient:r,tokenMetadataResolver:i,ethereumWallet:o,destinationChainId:c,destinationChain:l,validateRecipientAddress:d}=t,u=fr(s);wr(n,u),d(a,"recipient");const h=await i.getTokenMetadata(u),g=await r.fetchBridgeFee({chainId:l,bridgeToken:h.descriptor}),m=function(e){return{destinationChainId:e.destinationChainId,destinationChainTxFee:e.bridgeFee,quantity:e.amount,recipient:e.recipientAddress,tokenInstance:{...e.tokenDescriptor,instance:"0"}}}({destinationChainId:c,bridgeFee:g,amount:n,recipientAddress:a,tokenDescriptor:h.descriptor}),p=await Rr(m,{wallet:o}),f=function(e){if(void 0===e||""===e)throw Dt(mr,"bridgeRequestId");return e}(function(e){if("string"==typeof e.Data)return e.Data;const t=e.data;if(null!=t){if("string"==typeof t)return t;if("object"==typeof t){const e=t;if("string"==typeof e.Data)return e.Data}}}(await r.requestBridgeOut(p)));return function(e){return{direction:"outbound",fromChain:"GalaChain",toChain:e.toChain,transactionHash:e.transactionHash,tokenSymbol:e.tokenSymbol,amount:e.amount,feePaid:e.feePaid,timestamp:Date.now(),statusUrl:`${e.baseUrl}/v1/bridge/transaction?hash=${e.transactionHash}`}}({toChain:l,transactionHash:function(e){const t=e.Hash??e.hash??"";if(""===t)throw Dt(pr,"transactionHash");return t}(await r.bridgeTokenOut({bridgeFromChannel:"asset",bridgeRequestId:f})),tokenSymbol:u,amount:n,feePaid:g.estimatedTotalTxFeeInGala,baseUrl:r.getBaseUrl()})}var Or;!function(e){e[e.PENDING=0]="PENDING",e[e.SUBMITTED=1]="SUBMITTED",e[e.CONFIRMED=2]="CONFIRMED",e[e.PROCESSING=3]="PROCESSING",e[e.FINALIZING=4]="FINALIZING",e[e.COMPLETED=5]="COMPLETED",e[e.FAILED=6]="FAILED",e[e.DELIVERY_FAILED=7]="DELIVERY_FAILED"}(Or||(Or={}));const Fr=Or.COMPLETED,Br=Or.FAILED,Ur=Or.DELIVERY_FAILED;class Pr{constructor(e){if(this.lastTimestamp=0,this.pendingPromise=Promise.resolve(),this.chainLength=0,this.maxChainLength=1e3,e<=0)throw Ot("requestsPerSecond","1",e,"Requests per second");this.minIntervalMs=1e3/e}async schedule(e){let t,n;const a=new Promise((e,a)=>{t=e,n=a});if(this.pendingPromise=this.pendingPromise.then(async()=>{const a=Date.now()-this.lastTimestamp,s=Math.max(0,this.minIntervalMs-a);s>0&&await new Promise(e=>setTimeout(e,s)),this.lastTimestamp=Date.now();try{const n=await e();t(n)}catch(e){n(st(e)?e:new Error(rt(e)))}}),this.chainLength++,this.chainLength>=this.maxChainLength){this.chainLength=0;const e=this.pendingPromise;this.pendingPromise=e.then(()=>Promise.resolve())}return a}}const Mr={maxRetries:3,initialDelayMs:1e3,maxDelayMs:3e4,backoffMultiplier:2,jitterFactor:.1},Lr=new Set([408,429,500,502,503,504]),$r=[/ECONNRESET/i,/ECONNREFUSED/i,/ETIMEDOUT/i,/ENOTFOUND/i,/EAI_AGAIN/i,/socket hang up/i,/network/i,/timeout/i,/aborted/i];function Kr(e){if(null!=e&&"object"==typeof e){const t=e;if("number"==typeof t.status)return Lr.has(t.status);if("number"==typeof t.statusCode)return Lr.has(t.statusCode);const n=ot(e);if("string"==typeof n&&("ECONNRESET"===n||"ECONNREFUSED"===n||"ETIMEDOUT"===n||"ENOTFOUND"===n||"EAI_AGAIN"===n))return!0}const t=rt(e);return $r.some(e=>e.test(t))}function Gr(e,t){const n=t.initialDelayMs*Math.pow(t.backoffMultiplier,e-1),a=Math.min(n,t.maxDelayMs),s=a*t.jitterFactor*Math.random();return Math.floor(a+s)}function Wr(e){return new Promise(t=>setTimeout(t,e))}function Hr(e,t){return ur(e.get("Ethereum"),"Ethereum",t)}function qr(e,t){return ur(e.get("Solana"),"Solana",t)}function zr(e,t){return e??t.getWalletAddress()}async function jr(e,t,n,a,s){const r=await t.getTokenMetadata(a);return function(e){const t="string"==typeof e.timestamp?Cn(e.timestamp,0):e.timestamp;return{estimatedFeeInGala:e.estimatedTotalTxFeeInGala,estimatedFeeInExternalToken:e.estimatedTotalTxFeeInExternalToken,feeToken:e.bridgeToken,pricePerUnit:e.estimatedPricePerTxFeeUnit,estimatedGasUnits:e.estimatedTxFeeUnitsTotal,exchangeRate:e.galaExchangeRate?.exchangeRate??"0",timestamp:t,raw:e}}(await e.fetchBridgeFee({chainId:n,bridgeToken:r.descriptor}))}async function Vr(e,t){return function(e){const t=Cn(e.status,0);return{status:t,statusDescription:e.statusDescription,fromChain:e.fromChain,toChain:e.toChain,quantity:e.quantity,transactionHash:e.emitterTransactionHash,tokenInstance:e.tokenInstance,isComplete:t===Fr,isFailed:t===Br||t===Ur}}(await e.getBridgeStatus(t))}function Xr(e,t,n){try{const n=function(e,t){if(!Pn(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}(e,t),[a,s,r,...i]=n;if(""===a||""===s||""===r)throw new Error("Collection, category, and type must be non-empty");const o=i.join(t);if(void 0===a||void 0===s||void 0===r||""===o)throw new Error("AdditionalKey must be non-empty");return{collection:a,category:s,type:r,additionalKey:o}}catch(a){throw function(e,t,n,a){const s=e?.split?.(t)??[],r=void 0!==n?` (${n})`:"";return new bt(`Invalid ${"|"===t?"pipe":"dollar"}-delimited token: "${e}" (${s.length} parts)${r}. Expected format: "collection${t}category${t}type${t}additionalKey" (4 parts minimum). Received: [${s.map(e=>`"${e}"`).join(", ")}]. Error: ${rt(a)}`,"token",`INVALID_${"|"===t?"PIPE":"DOLLAR"}_DELIMITED_TOKEN`)}(e,t,n,a)}}function Qr(e){return Xr(e,"|","pipe-delimited token")}function Jr(e){return"string"==typeof e&&e.includes("$")}function Yr(e){if("object"!=typeof e||null===e)return!1;const t=e,n=t.collection,a=t.category,s=t.type,r=t.additionalKey;return"string"==typeof n&&"string"==typeof a&&"string"==typeof s&&"string"==typeof r&&n.length>0&&a.length>0&&s.length>0&&r.length>0}function Zr(e){let t;if("string"==typeof e)t=Qr(e);else{if(!Yr(e))throw new Error('Invalid tokenId format. Expected pipe-delimited string (e.g., "GALA|Unit|none|none") or TokenClassKey object.');t=e}return{tokenClassKey:t,stringified:Ls(t)}}function ei(e,t){let n;try{n=Nn(e,"amount")}catch(t){throw Ut("amount",`${e} (${rt(t)})`)}if(!n.isFinite())throw Ut("amount",e);const a=n.multipliedBy(as(10).pow(t));if(!a.isInteger())throw Ut("amount",`${e} (cannot be represented with ${t} decimals)`);return BigInt(a.toFixed(0))}function ti(e,t){return as(e.toString()).dividedBy(as(10).pow(t)).toFixed(t).replace(/\.?0+$/,"")}class ni{constructor(e){this.cache=new Map,this.galaConnectClient=e.galaConnectClient}async getTokenMetadata(e){const t=Xt(e),n=this.cache.get(t);if(n)return n;const a=Ys[t];if(void 0!==a)return this.cache.set(t,a),a;const s=await this.fetchFromApi(e);return this.cache.set(t,s),s}hasMetadata(e){const t=Xt(e);return this.cache.has(t)||t in Ys}clearCache(){this.cache.clear()}async fetchFromApi(e){let t=e,n=await this.galaConnectClient.getBridgeConfigurations(t),a=n.find(e=>Xt(e.symbol)===Xt(t)&&e.verified);if(a||e.startsWith("G")||(t=`G${e}`,n=await this.galaConnectClient.getBridgeConfigurations(t),a=n.find(e=>Xt(e.symbol)===Xt(t)&&e.verified)),!a)throw new Error(`Unable to locate token metadata for ${e}`);return s={collection:a.collection,category:a.category,type:a.type,additionalKey:a.additionalKey},r=a.decimals,i=a.channel,{descriptor:{collection:s.collection,category:s.category,type:s.type,additionalKey:s.additionalKey},decimals:r,...void 0!==i?{channel:i}:{}};var s,r,i}}class ai extends Error{constructor(e,t,n){super(`GalaConnect request to ${t} failed with status ${e}${null!=n?`: ${JSON.stringify(n)}`:""}`),this.status=e,this.path=t,this.responseBody=n,this.name="GalaConnectHttpError"}}const si="https://dex-api-platform-dex-prod-gala.gala.com",ri="https://galachain-gateway-chain-platform-galachain-mainnet.gala.com",ii=12,oi=!0,ci=3,li=1e3;class di{constructor(e){this.baseUrl=e.baseUrl??si,this.galachainBaseUrl=e.galachainBaseUrl??ri,this.walletAddress=e.walletAddress,this.rateLimiter=new Pr(e.requestsPerSecond??ii),this.defaultHeaders={"Content-Type":"application/json","X-Wallet-Address":this.walletAddress};const t=e.enableRetry??oi;this.retryOptions=t?{maxRetries:e.maxRetries??ci,initialDelayMs:e.retryInitialDelayMs??li,...e.onRetry&&{onRetry:e.onRetry},shouldRetry:e=>Kr(e instanceof ai?{status:e.status}:e)}:null}getBaseUrl(){return this.baseUrl}async getBridgeConfigurations(e){return Rs(async()=>{const t=new URL("/v1/connect/bridge-configurations",this.baseUrl);t.searchParams.set("searchprefix",e);const n=await this.request(t.toString(),{method:"GET"});if(!n.ok){const e=await n.text();let t;throw t=""!==e?An(e,{rawBody:e}):{message:"Failed to fetch bridge configurations"},new ai(n.status,"/v1/connect/bridge-configurations",t)}return(await n.json()).data.tokens},"GalaConnectClient.getBridgeConfigurations",void 0,e=>{if(e instanceof ai)throw e;throw Rt(e,"GalaConnectClient.getBridgeConfigurations")})}async fetchBridgeFee(e){return this.postJson("/v1/bridge/fee",e,{skipWalletHeader:!0})}async requestBridgeOut(e){return this.postJson("/v1/RequestTokenBridgeOut",e)}async bridgeTokenOut(e){return this.postJson("/v1/BridgeTokenOut",e)}async getBridgeStatus(e){return this.postJson("/v1/bridge/status",{hash:e})}async registerBridgeTransaction(e){return this.postJson("/v1/bridge/transaction",e)}async fetchBalances(e="asset"){return this.postJson("/v1/FetchBalances",{owner:this.walletAddress,channel:e},{baseUrl:this.galachainBaseUrl})}async postJson(e,t,n={}){return Rs(async()=>{const a=n.baseUrl??this.baseUrl,s=new URL(e,a),r=n.skipWalletHeader?{"Content-Type":"application/json","X-Wallet-Address":""}:this.defaultHeaders,i=await this.request(s.toString(),{method:"POST",headers:r,body:JSON.stringify(t,(e,t)=>"bigint"==typeof t?t.toString():t)});if(!i.ok){const t=await i.text(),n=500,a=An(t,{rawBody:t.slice(0,n)});throw new ai(i.status,e,a)}const o=await i.text();if(""!==o){const t=function(e){if(Yt(e))return{success:!1,value:null,error:"Value is empty"};try{return{success:!0,value:JSON.parse(e)}}catch(e){return{success:!1,value:null,error:`JSON parse error: ${rt(e)}`}}}(o);if(!t.success)throw new Error(`Failed to parse JSON response from ${e}: ${String(t.error)}`);return t.value}},`Failed to execute POST request to ${e}`,void 0,(e,t)=>{if(e instanceof ai)throw e;throw Rt(e,t)})}async request(e,t){const n=async()=>this.rateLimiter.schedule(async()=>{const n={...this.defaultHeaders,...t.headers};""===n["X-Wallet-Address"]?delete n["X-Wallet-Address"]:n["X-Wallet-Address"]??(n["X-Wallet-Address"]=this.walletAddress);const a=await fetch(e,{...t,headers:n});if(this.retryOptions&&!a.ok){const t=a.status;if(429===t||t>=500){const n=a.clone(),s=await this.safeParseJson(n);throw new ai(t,e,s)}}return a});return this.retryOptions?async function(e,t={}){const n={...Mr,...t},a=t.shouldRetry??(e=>Kr(e));let s;for(let r=1;r<=n.maxRetries+1;r++)try{return await e()}catch(e){if(s=e,r>n.maxRetries)break;if(!a(e,r))break;const i=Gr(r,n);t.onRetry&&t.onRetry(e,r,i),await new Promise(e=>setTimeout(e,i))}throw s}(n,this.retryOptions):n()}async safeParseJson(e){const t=await e.text();try{return JSON.parse(t)}catch{return{rawBody:t}}}}class ui{async waitForCompletion(e,t={}){const{pollInterval:n=15e3,timeout:a=27e5,onStatusUpdate:s}=t,r=Date.now();for(;;){const t=await this.getStatus(e);if(s&&s(t),t.status===Or.COMPLETED||t.status===Or.FAILED||t.status===Or.DELIVERY_FAILED)return t;if(an(r)>a)throw _t(`Bridge transaction timed out after ${a}ms. Last status: ${t.status}`,e,"TIMEOUT");await new Promise(e=>setTimeout(e,n))}}}class hi extends ui{constructor(e,t){super(),this.galaConnectClient=e,this.tokenConfigs=t}async getStatus(e){return Vr(this.galaConnectClient,e)}getSupportedTokens(){return e=this.tokenConfigs,Array.from(e.keys());var e}isTokenSupported(e){return function(e,t){return e.has(Vt(t))}(this.tokenConfigs,e)}}async function gi(e,t,...n){const a=e[t];return"function"==typeof a?await a(...n):await e.getFunction(t)(...n)}class mi extends hi{constructor(e){const n=e.tokenConfigs??Qs;super(e.galaConnectClient,ar(n)),this.network="Ethereum",this.galaChainWalletAddress=e.galaChainWalletAddress,rr(e.ethereumPrivateKey);const a=e.ethereumRpcUrl??"https://ethereum.publicnode.com";this.ethereumProvider=new t.JsonRpcProvider(a),this.ethereumWallet=new t.Wallet(e.ethereumPrivateKey,this.ethereumProvider),this.ethereumWalletAddress=e.ethereumWalletAddress??this.ethereumWallet.address,this.ethereumBridgeContract=e.ethereumBridgeContract??"0x3F98b5A26EF3f04E1DA3B0B41dD350E8C8F3A7c2",this.tokenMetadataResolver=new ni({galaConnectClient:this.galaConnectClient})}async estimateFee(e,t){return jr(this.galaConnectClient,this.tokenMetadataResolver,"Ethereum",e)}async bridgeOut(e){return xr(e,{galaConnectClient:this.galaConnectClient,tokenMetadataResolver:this.tokenMetadataResolver,ethereumWallet:this.ethereumWallet,destinationChainId:Gs,destinationChain:"Ethereum",validateRecipientAddress:yr})}async bridgeIn(e){const{amount:n,sourcePrivateKey:a,recipientAddress:s,tokenSymbol:r}=e,i=fr(r);if(wr(n,i),void 0!==a&&""!==a&&!nr(a))throw Nt("sourcePrivateKey","0x-prefixed 64-character hex string",a.slice(0,10)+"...");const o=void 0!==a&&""!==a?new t.Wallet(a,this.ethereumProvider):this.ethereumWallet,c=sr(this.tokenConfigs,i,"Ethereum bridge"),l=await this.tokenMetadataResolver.getTokenMetadata(i),d=new t.Contract(c.contractAddress,Zs,o),u=await gi(d,"decimals"),h=Cn("string"==typeof u||"number"==typeof u||"bigint"==typeof u?u:void 0,18),g=ei(n,h),m=await gi(d,"balanceOf",o.address);if("bigint"!=typeof m)throw new Error("Ethereum balance response was not a bigint");const p=m;if(p<g){throw Dt(`Insufficient ${i} balance on Ethereum. Needed ${ti(g,h)}, have ${ti(p,h)}`,"amount")}const f=function(e){const n=new na;if("client"===n.detectFormat(e))return e;const a=n.normalizeInput(e);if(null==a)throw Nt("address","a valid GalaChain address (eth|0x{40-hex}, 0x{40-hex}, or {40-hex})","GalaChain address");const s=n.extractHex(a);return`eth|${t.getAddress("0x"+s).slice(2)}`}(s??this.galaChainWalletAddress);return hr({fromChain:"Ethereum",transactionHash:(await this.executeBridgeDeposit({wallet:o,tokenContract:d,tokenConfig:c,amountBaseUnits:g,decimals:h,recipient:f,metadata:l})).txHash,tokenSymbol:i,amount:n,baseUrl:this.galaConnectClient.getBaseUrl()})}isValidAddress(e){return Un.ETH_ADDRESS.test(e)}getWalletAddress(){return this.ethereumWalletAddress}async getEthereumTokenBalance(e,n){const a=sr(this.tokenConfigs,e,"Ethereum"),s=n??this.ethereumWalletAddress;yr(s);const r=new t.Contract(a.contractAddress,Zs,this.ethereumProvider),i=await gi(r,"balanceOf",s);if("bigint"!=typeof i)throw new Error("Ethereum balance response was not a bigint");return ti(i,a.decimals??18)}async getEthereumNativeBalance(e){const t=e??this.ethereumWalletAddress;yr(t);return ti(await this.ethereumProvider.getBalance(t),18)}async getEthereumTransactionStatus(e){!function(e){if(!function(e){return/^0x[a-fA-F0-9]{64}$/.test(e)}(e))throw Nt("hash","a 0x-prefixed 64-character hex string (66 total characters)","Ethereum transaction hash")}(e);const t=e.toLowerCase();try{const e=await this.ethereumProvider.getTransactionReceipt(t);if(e){const n=await this.ethereumProvider.getBlockNumber()-e.blockNumber+1;if(!(1===e.status))return{confirmed:!1,status:"failed",blockNumber:e.blockNumber,confirmations:n,transactionHash:t,gasUsed:e.gasUsed.toString(),effectiveGasPrice:e.gasPrice?.toString(),error:"Transaction reverted during execution"};return{confirmed:!0,status:n>=mi.ETHEREUM_FINALITY_THRESHOLD?"finalized":"confirmed",blockNumber:e.blockNumber,confirmations:n,transactionHash:t,gasUsed:e.gasUsed.toString(),effectiveGasPrice:e.gasPrice?.toString()}}return await this.ethereumProvider.getTransaction(t)?{confirmed:!1,status:"pending",transactionHash:t}:{confirmed:!1,status:"not_found",transactionHash:t,error:"Transaction not found on Ethereum network"}}catch(e){return{confirmed:!1,status:"not_found",transactionHash:t,error:`Failed to query transaction status: ${rt(e)}`}}}async executeBridgeDeposit(e){const n=new t.Contract(this.ethereumBridgeContract,er,e.wallet),a=(new TextEncoder).encode(e.recipient);let s;s=e.tokenConfig.bridgeUsesPermit?await this.bridgeWithPermit(e.wallet,e.tokenContract,e.tokenConfig,n,e.amountBaseUnits,a):await this.bridgeWithApproval(e.wallet,e.tokenContract,n,e.tokenConfig,e.amountBaseUnits,a);if(!await s.wait())throw Dt("Bridge transaction receipt not available","ethereumRpcUrl");await Wr(3e4);const r={collection:e.metadata.descriptor.collection,category:e.metadata.descriptor.category,type:e.metadata.descriptor.type,additionalKey:e.metadata.descriptor.additionalKey,instance:"0"};return await this.galaConnectClient.registerBridgeTransaction({quantity:ti(e.amountBaseUnits,e.decimals),tokenInstance:r,fromChain:"Ethereum",toChain:"GC",hash:s.hash}),{txHash:s.hash}}async bridgeWithPermit(e,n,a,s,r,i){const o=await this.ethereumProvider.getNetwork(),c=await gi(n,"name");if("string"!=typeof c)throw new Error("Ethereum token name response was not a string");const l=c,d=await gi(n,"nonces",e.address);if("bigint"!=typeof d)throw new Error("Ethereum token nonce response was not a bigint");const u=d,h=BigInt(Math.floor(Date.now()/1e3)+3600),g=await e.signTypedData({name:l,version:"1",chainId:Cn(o.chainId,1),verifyingContract:a.contractAddress},{Permit:[{name:"owner",type:"address"},{name:"spender",type:"address"},{name:"value",type:"uint256"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}]},{owner:e.address,spender:this.ethereumBridgeContract,value:r,nonce:u,deadline:h}),m=t.Signature.from(g);return await gi(s,"bridgeOutWithPermit",a.contractAddress,r,Ks,i,h,m.v,m.r,m.s)}async bridgeWithApproval(e,t,n,a,s,r){const i=await gi(t,"allowance",e.address,this.ethereumBridgeContract);if("bigint"!=typeof i)throw new Error("Ethereum allowance response was not a bigint");if(BigInt(i)<s){const e=await gi(t,"approve",this.ethereumBridgeContract,s);await e.wait()}return await gi(n,"bridgeOut",a.contractAddress,s,0,Ks,r)}}mi.ETHEREUM_FINALITY_THRESHOLD=12;function pi(e,t,n,s,r){const[i]=a.PublicKey.findProgramAddressSync([t.toBuffer(),s.toBuffer(),e.toBuffer()],r);return i}class fi extends hi{constructor(e){const n=e.tokenConfigs??Js;super(e.galaConnectClient,ar(n)),this.network="Solana",this.solanaBridgeAccountCache=new Map,this.galaChainWalletAddress=e.galaChainWalletAddress,rr(e.ethereumPrivateKey);const s=new t.JsonRpcProvider("https://ethereum.publicnode.com");this.ethereumWallet=new t.Wallet(e.ethereumPrivateKey,s);const r=e.solanaRpcUrl??"https://api.mainnet-beta.solana.com";let i;this.solanaConnection=new a.Connection(r,"confirmed");try{i=o.decode(e.solanaPrivateKeyBase58)}catch{throw Nt("solanaPrivateKeyBase58","base58-encoded string",e.solanaPrivateKeyBase58.slice(0,20)+"...")}if(64!==i.length)throw Nt("solanaPrivateKeyBase58","64 bytes when decoded",`${i.length} bytes`);this.solanaKeypair=a.Keypair.fromSecretKey(i);const c=e.solanaBridgeProgram??"AaE4dTnL75XqgUJpdxBKg6vS9sTJgBPJwBQRVhD29WwS";this.solanaBridgeProgramId=new a.PublicKey(c),[this.solanaBridgeTokenAuthority]=a.PublicKey.findProgramAddressSync([Buffer.from("bridge_token_authority")],this.solanaBridgeProgramId),[this.solanaBridgeConfigPda]=a.PublicKey.findProgramAddressSync([Buffer.from("configv1")],this.solanaBridgeProgramId),[this.solanaNativeBridgePda]=a.PublicKey.findProgramAddressSync([Buffer.from("native_sol_bridge")],this.solanaBridgeProgramId),this.tokenMetadataResolver=new ni({galaConnectClient:this.galaConnectClient})}async estimateFee(e,t){return jr(this.galaConnectClient,this.tokenMetadataResolver,"Solana",e)}async bridgeOut(e){return xr(e,{galaConnectClient:this.galaConnectClient,tokenMetadataResolver:this.tokenMetadataResolver,ethereumWallet:this.ethereumWallet,destinationChainId:Ws,destinationChain:"Solana",validateRecipientAddress:vr})}async bridgeIn(e){const{amount:t,sourcePrivateKey:n,recipientAddress:s,tokenSymbol:r}=e,i=fr(r);wr(t,i);let c=this.solanaKeypair;if(void 0!==n&&""!==n){let e;try{e=o.decode(n)}catch{throw Nt("sourcePrivateKey","base58-encoded string",n.slice(0,20)+"...")}if(64!==e.length)throw Nt("sourcePrivateKey","64 bytes when decoded",`${e.length} bytes`);c=a.Keypair.fromSecretKey(e)}const l=sr(this.tokenConfigs,i,"Solana bridge"),d=await this.tokenMetadataResolver.getTokenMetadata(i),u=ei(t,d.decimals),h=s??this.galaChainWalletAddress;return hr({fromChain:"Solana",transactionHash:await this.executeSolanaBridgeOut({keypair:c,tokenConfig:l,metadata:d,amountBaseUnits:u,recipient:h,amount:t}),tokenSymbol:i,amount:t,baseUrl:this.galaConnectClient.getBaseUrl()})}isValidAddress(e){try{return new a.PublicKey(e),!0}catch{return!1}}getWalletAddress(){return this.solanaKeypair.publicKey.toBase58()}async getSolanaTokenBalance(e,t){const n=sr(this.tokenConfigs,e,"Solana");if(n.isNative)return this.getSolanaNativeBalance(t);const s=t??this.solanaKeypair.publicKey.toBase58(),r=kr(s),o=pi(new a.PublicKey(n.mintAddress),r,0,i.TOKEN_PROGRAM_ID,i.ASSOCIATED_TOKEN_PROGRAM_ID);try{const e=await async function(e,t,n,a){const s=await e.getAccountInfo(t);if(!s)throw new Error(`could not find account ${t.toBase58()}`);if(!s.owner.equals(a))throw new Error(`account owner mismatch: expected ${a.toBase58()}, got ${s.owner.toBase58()}`);return{amount:i.AccountLayout.decode(s.data).amount,decimals:0}}(this.solanaConnection,o,0,i.TOKEN_PROGRAM_ID),t=n.decimals??8;return ti(e.amount,t)}catch(t){if(st(t)&&t.message.includes("could not find")){return ti(0n,n.decimals??8)}throw Dt(`Failed to fetch ${e} balance for ${s}: ${rt(t)}`,`${e}Account`)}}async getSolanaNativeBalance(e){const t=kr(e??this.solanaKeypair.publicKey.toBase58()),n=await this.solanaConnection.getBalance(t,"confirmed");return ti(BigInt(n),9)}async requestDevnetAirdrop(e=1,t){xn(e,1e-5,2,"amount");const n=void 0!==t&&""!==t?kr(t):this.solanaKeypair.publicKey,s=this.solanaConnection.rpcEndpoint;if(!s.includes("devnet"))throw Dt(`Solana devnet faucet only available on devnet. Current RPC: ${s}. Ensure SDK is configured with environment='stage' for devnet access.`,"solanaRpcUrl");const r=Math.floor(e*a.LAMPORTS_PER_SOL);return await this.solanaConnection.requestAirdrop(n,r)}async getSolanaTransactionStatus(e){if(!Pn(e))throw Nt("signature","a non-empty string");if(!/^[1-9A-HJ-NP-Za-km-z]{80,90}$/.test(e))throw Nt("signature","a base58-encoded string (87-88 characters)",e.slice(0,20)+"...");const t=(await this.solanaConnection.getSignatureStatuses([e])).value[0];return t?null!==t.err&&void 0!==t.err?{confirmed:!1,status:"failed",slot:t.slot,error:JSON.stringify(t.err)}:{confirmed:!0,status:t.confirmationStatus??"processed",slot:t.slot}:{confirmed:!1,status:"not_found"}}async executeSolanaBridgeOut(e){const t=new a.PublicKey(e.tokenConfig.mintAddress),n=Boolean(e.tokenConfig.isNative),s=n?void 0:await this.getSolanaBridgeAccounts(t),r=n?void 0:pi(t,e.keypair.publicKey,0,i.TOKEN_PROGRAM_ID,i.ASSOCIATED_TOKEN_PROGRAM_ID),o=Buffer.from(e.recipient,"utf8"),c=Buffer.alloc(8);c.writeBigUInt64LE(e.amountBaseUnits);const l=Buffer.alloc(4);l.writeUInt32LE(o.length);const d=n?this.buildNativeBridgeInstruction(e.keypair.publicKey,c,l,o):this.buildTokenBridgeInstruction(e.keypair.publicKey,r,t,s,c,l,o),u=new a.Transaction;u.add(a.ComputeBudgetProgram.setComputeUnitPrice({microLamports:375e3}),a.ComputeBudgetProgram.setComputeUnitLimit({units:2e5}),d),u.feePayer=e.keypair.publicKey;const h=await this.sendAndConfirmWithFallback(u,e.keypair),g={collection:e.metadata.descriptor.collection,category:e.metadata.descriptor.category,type:e.metadata.descriptor.type,additionalKey:e.metadata.descriptor.additionalKey,instance:"0"};return await this.galaConnectClient.registerBridgeTransaction({quantity:e.amount,tokenInstance:g,fromChain:"Solana",toChain:"GC",hash:h}),h}async sendAndConfirmWithFallback(e,t,n=3){let a=null;for(let s=1;s<=n;s++){try{const r=await this.solanaConnection.getLatestBlockhash("confirmed");e.recentBlockhash=r.blockhash,e.feePayer=t.publicKey,e.signatures=[],e.sign(t);const i=await this.solanaConnection.sendRawTransaction(e.serialize(),{skipPreflight:!1,preflightCommitment:"confirmed"});try{return await this.solanaConnection.confirmTransaction({signature:i,blockhash:r.blockhash,lastValidBlockHeight:r.lastValidBlockHeight},"confirmed"),i}catch(e){const t=st(e)?e.message.toLowerCase():"";if(!(t.includes("block height exceeded")||t.includes("blockhash not found")||t.includes("expired")))throw e;const r=await this.solanaConnection.getSignatureStatuses([i]);if("confirmed"===r.value[0]?.confirmationStatus||"finalized"===r.value[0]?.confirmationStatus)return i;a=new Error(`Transaction ${i} not confirmed - block height exceeded (attempt ${s}/${n})`)}}catch(e){a=st(e)?e:new Error(rt(e));const t=a.message.toLowerCase();if(!(t.includes("block height exceeded")||t.includes("blockhash not found")||t.includes("timeout")||t.includes("expired"))||s===n)throw a}const r=Math.min(1e3*Math.pow(2,s-1),5e3);await Wr(r)}throw a??new Error("Transaction confirmation failed after max retries")}buildNativeBridgeInstruction(e,t,n,s){const r=Buffer.concat([tr.BRIDGE_OUT_NATIVE,t,n,s]);return new a.TransactionInstruction({programId:this.solanaBridgeProgramId,keys:[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:this.solanaBridgeTokenAuthority,isSigner:!1,isWritable:!0},{pubkey:this.solanaNativeBridgePda,isSigner:!1,isWritable:!1},{pubkey:this.solanaBridgeConfigPda,isSigner:!1,isWritable:!0},{pubkey:a.SystemProgram.programId,isSigner:!1,isWritable:!1}],data:r})}buildTokenBridgeInstruction(e,t,n,s,r,o,c){const l=Buffer.concat([tr.BRIDGE_OUT,r,o,c]);return new a.TransactionInstruction({programId:this.solanaBridgeProgramId,keys:[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!0},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:s.mintLookup,isSigner:!1,isWritable:!1},{pubkey:s.tokenBridge,isSigner:!1,isWritable:!1},{pubkey:s.bridgeTokenAccount,isSigner:!1,isWritable:!0},{pubkey:this.solanaBridgeTokenAuthority,isSigner:!1,isWritable:!1},{pubkey:this.solanaBridgeConfigPda,isSigner:!1,isWritable:!0},{pubkey:a.SystemProgram.programId,isSigner:!1,isWritable:!1},{pubkey:i.TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1}],data:l})}async getSolanaBridgeAccounts(e){const t=e.toBase58(),n=this.solanaBridgeAccountCache.get(t);if(n)return n;const[s]=a.PublicKey.findProgramAddressSync([Buffer.from("mint_lookup_v1"),e.toBuffer()],this.solanaBridgeProgramId),r=await this.solanaConnection.getAccountInfo(s,"confirmed");if(!r)throw Dt(`Mint lookup account not found for ${s.toBase58()}`,"solanaBridgeProgram");if(!r.owner.equals(this.solanaBridgeProgramId))throw Dt("Mint lookup account owner mismatch for Solana bridge program","solanaBridgeProgram");if(r.data.length<40)throw Dt("Mint lookup account data is unexpectedly short","solanaBridgeProgram");const o={mintLookup:s,tokenBridge:new a.PublicKey(r.data.slice(8,40)),bridgeTokenAccount:pi(e,this.solanaBridgeTokenAuthority,0,i.TOKEN_PROGRAM_ID,i.ASSOCIATED_TOKEN_PROGRAM_ID)};return this.solanaBridgeAccountCache.set(t,o),o}}const yi={prod:{ethereum:"https://eth.gala.games",solana:"https://api.mainnet-beta.solana.com"},stage:{ethereum:"https://dev.eth.gala.games",solana:"https://api.devnet.solana.com"}},vi={solanaBridgeProgram:"AaE4dTnL75XqgUJpdxBKg6vS9sTJgBPJwBQRVhD29WwS",rateLimit:12,pollInterval:15e3,pollTimeout:27e5};class ki{static normalizeGalaChainAddress(e){const t=new na;if("client"===t.detectFormat(e))return e;let n=e;(e.startsWith("eth|0x")||e.startsWith("eth|0X"))&&(n=e.substring(0,4)+e.substring(6));const a=t.normalizeInput(n);if(!a)throw Dt(`Invalid GalaChain address format: ${e}`,"galaChainWalletAddress");const s=t.extractHex(a);return`eth|${ki.checksumAddress(s)}`}static checksumAddress(e){const n=e.toLowerCase(),a=ea(t.keccak256(t.toUtf8Bytes(n)));let s="";for(let e=0;e<n.length;e++){const t=n[e],r=a[e];void 0!==t&&void 0!==r&&parseInt(r,16)>=8?s+=t.toUpperCase():s+=t??""}return s}constructor(e){const t=ki.normalizeGalaChainAddress(e.galaChainWalletAddress),n=e.environment??"prod",a=Ps["stage"===n?"stage":"prod"],s=yi[n],r={galaConnectBaseUrl:e.galaConnectBaseUrl??a.dexApiBaseUrl,galaChainApiBaseUrl:e.galaChainApiBaseUrl??a.gatewayBaseUrl,ethereumRpcUrl:e.ethereumRpcUrl??s.ethereum,solanaRpcUrl:e.solanaRpcUrl??s.solana,ethereumBridgeContract:e.ethereumBridgeContract??Xs(n),solanaBridgeProgram:e.solanaBridgeProgram??vi.solanaBridgeProgram,rateLimit:e.rateLimit??vi.rateLimit,pollInterval:e.pollInterval??vi.pollInterval,pollTimeout:e.pollTimeout??vi.pollTimeout,galaChainWalletAddress:t,ethereumPrivateKey:e.ethereumPrivateKey,environment:n};this.config=e.solanaPrivateKey?{...r,solanaPrivateKey:e.solanaPrivateKey}:r,this.galaConnectClient=new di({baseUrl:this.config.galaConnectBaseUrl,galachainBaseUrl:this.config.galaChainApiBaseUrl,walletAddress:this.config.galaChainWalletAddress,requestsPerSecond:this.config.rateLimit}),e.bridgeableTokenService&&(this.bridgeableTokenService=e.bridgeableTokenService),this.strategies=new Map,this.initializeStrategies()}initializeStrategies(){const e=Vs(this.config.environment),t={galaConnectClient:this.galaConnectClient,galaChainWalletAddress:this.config.galaChainWalletAddress,ethereumPrivateKey:this.config.ethereumPrivateKey,ethereumRpcUrl:this.config.ethereumRpcUrl,ethereumBridgeContract:this.config.ethereumBridgeContract,tokenConfigs:e};if(this.strategies.set("Ethereum",new mi(t)),null!==this.config.solanaPrivateKey&&void 0!==this.config.solanaPrivateKey){const e={galaConnectClient:this.galaConnectClient,galaChainWalletAddress:this.config.galaChainWalletAddress,ethereumPrivateKey:this.config.ethereumPrivateKey,solanaPrivateKeyBase58:this.config.solanaPrivateKey,solanaRpcUrl:this.config.solanaRpcUrl,solanaBridgeProgram:this.config.solanaBridgeProgram,tokenConfigs:Js};this.strategies.set("Solana",new fi(e))}}async resolveTokenSymbol(e,t){return Rs(async()=>{if(!this.bridgeableTokenService)throw Dt("BridgeableTokenService is required for tokenId resolution. Pass bridgeableTokenService in BridgeServiceConfig or use the SDK's bridge methods.","bridgeableTokenService");const n=Zr(e).stringified,a="Ethereum"===t?"ETHEREUM":"SOLANA",s=await this.bridgeableTokenService.getTokenByTokenId(n,a);if(!s){throw Dt([`Token "${n}" was not found in the list of tokens bridgeable to ${t}.`,"","Troubleshooting suggestions:",' 1. Verify the tokenId format is correct (e.g., "GALA|Unit|none|none")'," 2. Check if the token supports bridging to this network:",` - Use sdk.fetchAllBridgeableTokensByNetwork('${a}')`," - Or use sdk.isTokenBridgeableToNetwork({ tokenSymbol, network })"," 3. Common tokenId formats for bridge tokens:",' - GALA: "GALA|Unit|none|none"',' - GUSDC: "GUSDC|Unit|none|eth:0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"'," 4. Use sdk.getSupportedBridgeTokens() to list all available tokens"].join("\n"),"tokenId")}return s.symbol},"BridgeService.resolveTokenSymbol")}async estimateBridgeFee(e){return Rs(async()=>{const t=await this.resolveTokenSymbol(e.tokenId,e.destinationChain);return this.getStrategy(e.destinationChain).estimateFee(t,e.amount??"0")},"BridgeService.estimateBridgeFee")}async bridgeOut(e){return Rs(async()=>{const t=await this.resolveTokenSymbol(e.tokenId,e.destinationChain),n=this.getStrategy(e.destinationChain);if(!n.isValidAddress(e.recipientAddress))throw Dt(`Invalid recipient address for ${e.destinationChain}: ${e.recipientAddress}`,"recipientAddress");if(!n.isTokenSupported(t))throw Dt(`Token ${t} is not supported for ${e.destinationChain} bridging`,"tokenSymbol");return n.bridgeOut({...e,tokenSymbol:t})},"BridgeService.bridgeOut")}async bridgeIn(e){return Rs(async()=>{const t=await this.resolveTokenSymbol(e.tokenId,e.sourceChain),n=this.getStrategy(e.sourceChain);if(!n.isTokenSupported(t))throw Dt(`Token ${t} is not supported for ${e.sourceChain} bridging`,"tokenSymbol");return n.bridgeIn({...e,tokenSymbol:t})},"BridgeService.bridgeIn")}async getBridgeStatus(e,t){return Rs(async()=>{if(null!=t){const n=this.strategies.get(t);if(n)return n.getStatus(e)}const n=this.strategies.get("Ethereum");let a;if(n)try{return await n.getStatus(e)}catch(e){a=st(e)?e:new Error(rt(e))}const s=this.strategies.get("Solana");if(s)try{return await s.getStatus(e)}catch(e){a=st(e)?e:new Error(rt(e))}const r=a?` (last error: ${a.message})`:"";throw _t(`Unable to get status for transaction ${e}${r}`,e)},"BridgeService.getBridgeStatus")}async waitForBridgeCompletion(e,t){return Rs(async()=>{const n={pollInterval:t?.pollInterval??this.config.pollInterval,timeout:t?.timeout??this.config.pollTimeout,...t?.onStatusUpdate&&{onStatusUpdate:t.onStatusUpdate}},a=this.strategies.get("Ethereum");if(a)try{return await a.getStatus(e),a.waitForCompletion(e,n)}catch{}const s=this.strategies.get("Solana");if(s)return s.waitForCompletion(e,n);throw _t(`Unable to wait for transaction ${e}: no suitable strategy found`,e)},"BridgeService.waitForBridgeCompletion")}getSupportedBridgeTokens(e){const t=[],n=Vs(this.config.environment);if(null==e||"Ethereum"===e)for(const e of n)t.push({symbol:e.symbol,decimals:e.decimals??18,verified:!0,supportedChains:["Ethereum"],galaChainDescriptor:{collection:e.symbol.startsWith("G")?e.symbol:`G${e.symbol}`,category:"Unit",type:"none",additionalKey:"none"},externalAddresses:{ethereum:e.contractAddress}});if(null==e||"Solana"===e)for(const e of Js){const n=t.find(t=>t.symbol===e.symbol);n?(n.supportedChains.push("Solana"),n.externalAddresses.solana=e.mintAddress):t.push({symbol:e.symbol,decimals:e.decimals??9,verified:!0,supportedChains:["Solana"],galaChainDescriptor:{collection:e.symbol.startsWith("G")?e.symbol:`G${e.symbol}`,category:"Unit",type:"none",additionalKey:"none"},externalAddresses:{solana:e.mintAddress}})}return t}getSupportedBridgeChains(){return Array.from(this.strategies.keys())}isTokenSupported(e,t){if(null!=t){const n=this.strategies.get(t);return n?.isTokenSupported(e)??!1}for(const t of this.strategies.values())if(t.isTokenSupported(e))return!0;return!1}isValidAddress(e,t){const n=this.strategies.get(t);return n?.isValidAddress(e)??!1}async getEthereumTokenBalance(e,t){return Rs(async()=>Hr(this.strategies).getEthereumTokenBalance(e,t),"BridgeService.getEthereumTokenBalance")}async getEthereumNativeBalance(e){return Rs(async()=>Hr(this.strategies).getEthereumNativeBalance(e),"BridgeService.getEthereumNativeBalance")}async getSolanaTokenBalance(e,t){return Rs(async()=>qr(this.strategies).getSolanaTokenBalance(e,t),"BridgeService.getSolanaTokenBalance")}async getSolanaNativeBalance(e){return Rs(async()=>qr(this.strategies).getSolanaNativeBalance(e),"BridgeService.getSolanaNativeBalance")}async fetchEthereumWalletTokenBalance(e,t){return Rs(async()=>{const n=Hr(this.strategies),a=lr(Vs(this.config.environment),e,"Ethereum"),s=zr(t,n);return or(a,await n.getEthereumTokenBalance(e,s))},"BridgeService.fetchEthereumWalletTokenBalance")}async fetchEthereumWalletNativeBalance(e){return Rs(async()=>{const t=Hr(this.strategies),n=zr(e,t);return ir("ETH",await t.getEthereumNativeBalance(n),18)},"BridgeService.fetchEthereumWalletNativeBalance")}async fetchSolanaWalletTokenBalance(e,t){return Rs(async()=>{const n=qr(this.strategies),a=lr(Js,e,"Solana"),s=zr(t,n);return cr(a,await n.getSolanaTokenBalance(e,s))},"BridgeService.fetchSolanaWalletTokenBalance")}async fetchSolanaWalletNativeBalance(e){return Rs(async()=>{const t=qr(this.strategies),n=zr(e,t);return ir("SOL",await t.getSolanaNativeBalance(n),9)},"BridgeService.fetchSolanaWalletNativeBalance")}async requestSolanaDevnetAirdrop(e,t){return Rs(async()=>qr(this.strategies).requestDevnetAirdrop(e,t),"BridgeService.requestSolanaDevnetAirdrop")}async getSolanaTransactionStatus(e){return Rs(async()=>qr(this.strategies,"Solana bridge strategy not configured. This method requires Solana wallet configuration. Initialize SDK with solanaPrivateKey to use Solana features.").getSolanaTransactionStatus(e),"BridgeService.getSolanaTransactionStatus")}async getEthereumTransactionStatus(e){return Rs(async()=>Hr(this.strategies,"Ethereum bridge strategy not configured. This method requires Ethereum wallet configuration. Initialize SDK with ethereumPrivateKey to use Ethereum features.").getEthereumTransactionStatus(e),"BridgeService.getEthereumTransactionStatus")}async fetchEthereumWalletAllBalances(e){return Rs(async()=>{const t=Hr(this.strategies),n=zr(e,t),a=Vs(this.config.environment),[s,...r]=await Promise.all([t.getEthereumNativeBalance(n),...a.map(async e=>or(e,await t.getEthereumTokenBalance(e.symbol,n)))]);return{address:n,native:ir("ETH",s,18),tokens:r,timestamp:Date.now()}},"BridgeService.fetchEthereumWalletAllBalances")}async fetchSolanaWalletAllBalances(e){return Rs(async()=>{const t=qr(this.strategies),n=zr(e,t),[a,...s]=await Promise.all([t.getSolanaNativeBalance(n),...Js.map(async e=>cr(e,await t.getSolanaTokenBalance(e.symbol,n)))]);return{address:n,native:ir("SOL",a,9),tokens:s,timestamp:Date.now()}},"BridgeService.fetchSolanaWalletAllBalances")}getStrategy(e){const t=this.strategies.get(e);if(!t)throw Dt(`Bridging to ${e} is not configured. `+("Solana"===e?"Please provide solanaPrivateKey in config.":"Please check your configuration."),`${e.toLowerCase()}PrivateKey`);return t}}var bi,wi;!function(e){e.PROCESSED="PROCESSED",e.COMPLETED="COMPLETED",e.SUCCESS="SUCCESS",e.FAILED="FAILED",e.ERROR="ERROR",e.PROCESSING="PROCESSING",e.PENDING="PENDING"}(bi||(bi={})),function(e){e.PENDING="pending",e.PROCESSING="processing",e.COMPLETED="completed",e.FAILED="failed",e.TIMEOUT="timeout"}(wi||(wi={}));const Si={[bi.PROCESSED]:wi.COMPLETED,[bi.COMPLETED]:wi.COMPLETED,[bi.SUCCESS]:wi.COMPLETED,[bi.FAILED]:wi.FAILED,[bi.ERROR]:wi.FAILED,[bi.PROCESSING]:wi.PROCESSING,[bi.PENDING]:wi.PENDING},Ai="7.0.0-beta.3",Ei={DEFAULT_LIMIT:10,BACKEND_MAX_PAGE_SIZE:20};function Ti(e,t){if("number"!=typeof e||!Number.isInteger(e))throw Bt("total","a non-negative integer",e);if(e<0)throw xt("total",0,1/0,e);if("number"!=typeof t||!Number.isInteger(t))throw Bt("limit","a non-negative integer",t);if(t<0)throw xt("limit",0,1/0,t);return 0===t?1:0===e?0:Math.ceil(e/t)}function Ci(e){return"string"==typeof e?e:"number"==typeof e||"boolean"==typeof e||"bigint"==typeof e?String(e):JSON.stringify(e)??""}function Ni(e,t){const n={};void 0!==e.cursor&&(n.cursor=e.cursor);const a=void 0!==e.pageSize?Math.min(e.pageSize,t):t;return n.pageSize=String(a),n}function Ii(e,t,n){for(const a of n){const n=t[a];null!=n&&""!==n&&(e[a]=Ci(n))}return e}const Di="x-api-key";class _i extends Qn{constructor(e,t,n,a=!1,s){super(e,a),this.adminApiKey=t??void 0,this.jwtAuth=n,this.userApiKey=s??void 0}setJwtAuth(e){this.jwtAuth=e}validateTokenName(e,t){!function(e,t){if(!Pn(e))throw Ct("tokenName","Token name");const n=jt(e);if(!t.PATTERN.test(n))throw Nt("tokenName",`${t.MIN_LENGTH}-${t.MAX_LENGTH} alphanumeric characters`,"Token name")}(e,t)}validateRequiredString(e,t,n){!function(e,t,n){if(!Pn(e))throw Ct(t,n)}(e,t,n)}validateOptionalString(e,t,n,a){!function(e,t,n,a){if(null!=e){if("string"!=typeof e)throw Bt(t,"string",typeof e,n);if(e.length>a)throw Ft(t,a,e.length,n)}}(e,t,n,a)}validateOptionalNumber(e,t,n,a,s,r,i){!function(e,t,n,a,s){if(null!=e){if("number"!=typeof e)throw Bt(t,"number",typeof e,n);if(e<a||e>s)throw xt(t,a,s,e,n)}}(e,t,n,a,s)}validateOptionalDate(e,t,n){!function(e,t,n){if(null!=e&&!nn(e))throw Nt(t,"a valid ISO 8601 date string",n)}(e,t,n)}validatePositiveInteger(e,t,n){Vn(e,t,n)}validateStatusFilter(e,t,n="status"){Xn(e,t,n)}buildPaginationParams(e,t){return Ni(e,t)}addOptionalFilterParams(e,t,n){return Ii(e,t,n)}buildEndpoint(e,t){return function(e,t){let n=e;for(const[e,a]of Object.entries(t))n=n.replace(`:${e}`,encodeURIComponent(a.toLowerCase()));return n}(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 St("Admin API key required for this operation. Set streamAdminApiKey in SDK config.");return{[Di]:this.adminApiKey}}getJwtHeaders(){if(!this.jwtAuth)throw new St("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?{[Di]:this.userApiKey}:this.getJwtHeaders()}extractData(e){return Lt(e,"Backend request failed",!0),Kt(e,"No data in backend response")}extractDataOrNull(e){return Lt(e,"Backend request failed",!1),e.data??null}async toggleFeature(e,t,n){this.validateTokenName(e,n);const a=this.buildEndpoint(t,{tokenName:e}),s=await this.http.post(a,{},this.getAdminHeaders()),r=this.extractData(s);return{enabled:r.enabled,tokenName:r.tokenName??jt(e)}}}class Ri extends _i{constructor(e,t,n,a=!1,s){super(e,t,n,a,s)}async getSettings(){return{settings:(await this.http.get(He.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(He.UPDATE_SETTINGS,t,this.getDualAuthHeaders())).settings}}async getModeration(e){this.validatePositiveInteger(e.flagId,"flagId","Flag ID");const t=He.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=He.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(He.GET_STATUS,{},this.getDualAuthHeaders())).status}}}const xi=Kn({MODERATOR:"MODERATOR",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MANAGER:"MANAGER",OWNER:"OWNER"});function Oi(e){return xi.includes(e)}function Fi(e,t,n=!1){const a=t.length;if(ut(t,()=>{zn(e.description,"description",255)}),t.length>a&&(t[a]="Description must be 255 characters or less"),void 0!==e.tokenNames){const n=t.length;ut(t,()=>{if(!Array.isArray(e.tokenNames))throw Bt("tokenNames","an array",e.tokenNames);if(!e.tokenNames.every(e=>"string"==typeof e))throw Bt("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;ut(t,()=>{jn(e.expiresAt,"expiresAt")}),t.length>n&&(t[n]="expiresAt must be a valid ISO 8601 date string")}}class Bi extends Qn{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),Lt(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"):Oi(e.role)||t.push(`Invalid role. Must be one of: ${xi.join(", ")}`),Fi(e,t),t}(e);if(t.length>0)throw new bt(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 a=await this.http.post(Y.CREATE,n,this.getJwtHeaders()),s=this.extractData(a);return this.logger.debug("API key created",{id:s.id,keyPrefix:s.keyPrefix}),s}async findAll(e={}){!function(e){if(void 0!==e.pageSize&&("number"!=typeof e.pageSize||e.pageSize<1||e.pageSize>cn))throw Bt("pageSize",`number between 1 and ${cn}`,typeof e.pageSize);if(void 0!==e.cursor&&("string"!=typeof e.cursor||""===e.cursor.trim()))throw Bt("cursor","non-empty string",typeof e.cursor)}(e),this.logger.debug("Listing API keys",e);const t=Ni(e,cn),n=await this.http.get(Y.LIST,t,this.getJwtHeaders()),a=this.extractData(n);return this.logger.debug("Listed API keys",{count:a.apiKeys.length,total:a.pageInfo.totalCount}),a}async findOne(e){this.validateApiKeyId(e),this.logger.debug("Getting API key",{id:e});const t=Y.GET.replace(":id",String(e)),n=await this.http.get(t,{},this.getJwtHeaders()),a=this.extractData(n);return this.logger.debug("Got API key",{id:a.id,keyPrefix:a.keyPrefix}),a}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||Oi(e.role)||t.push(`Invalid role. Must be one of: ${xi.join(", ")}`),Fi(e,t,!0),t}(t);if(n.length>0)throw new bt(n.join("; "),"options","VALIDATION_FAILED");this.logger.debug("Updating API key",{id:e,options:t});const a={};void 0!==t.role&&(a.role=t.role),void 0!==t.description&&(a.description=t.description),void 0!==t.delegateAllTokens&&(a.delegateAllTokens=t.delegateAllTokens),void 0!==t.tokenNames&&(a.tokenNames=t.tokenNames),void 0!==t.expiresAt&&(a.expiresAt=t.expiresAt),void 0!==t.tokenPermissions&&(a.tokenPermissions=t.tokenPermissions);const s=Y.UPDATE.replace(":id",String(e)),r=await this.http.patch(s,a,this.getJwtHeaders()),i=this.extractData(r);return this.logger.debug("Updated API key",{id:i.id,keyPrefix:i.keyPrefix}),i}async revoke(e){this.validateApiKeyId(e),this.logger.debug("Revoking API key",{id:e});const t=Y.REVOKE.replace(":id",String(e));await this.http.delete(t,{},this.getJwtHeaders()),this.logger.debug("API key revoked",{id:e})}getRoles(){return[...xi]}}const Ui={VIEWERS:"viewers",CHAT_PARTICIPANTS:"chat_participants"},Pi=$n(Ui);function Mi(e){if(!Pn(e.userAddress))throw Ct("userAddress");if(!(null==(t=e.reason)||""===t||"string"==typeof t&&!qn(t)&&t.length<=hn.BAN_REASON.MAX_LENGTH))throw new bt(`reason must be at most ${hn.BAN_REASON.MAX_LENGTH} characters`,"reason","TOO_LONG");var t,n;if(n=e.durationSeconds,!(Mn(n)||"number"==typeof n&&n>=mn&&n<=pn))throw new bt(`durationSeconds must be between ${mn} and ${pn} seconds`,"durationSeconds","OUT_OF_RANGE")}class Li extends _i{constructor(e,t,n,a=!1,s){super(e,t,n,a,s)}async createBan(e){!function(e){Wn(e.tokenName,"tokenName",sn),Mi(e)}(e);const t=this.buildEndpoint(W,{tokenName:e.tokenName}),n=$i(e),a=await this.http.post(t,n,this.getMultiAuthHeaders());return{ban:this.extractData(a),tokenName:jt(e.tokenName)}}async removeBan(e){!function(e){if(Wn(e.tokenName,"tokenName",sn),!Pn(e.userAddress))throw Ct("userAddress")}(e);const t=this.buildEndpoint(z,{tokenName:e.tokenName,userAddress:e.userAddress}),n=await this.http.delete(t,{},this.getMultiAuthHeaders()),a=this.extractDataOrNull(n);return{removed:a?.removed??!0,tokenName:jt(e.tokenName),userAddress:a?.userAddress??e.userAddress.toLowerCase()}}async listBans(e){!function(e){Wn(e.tokenName,"tokenName",sn),Ln(0,void 0,cn,e.pageSize)}(e);const t=this.buildEndpoint(H,{tokenName:e.tokenName}),n=this.buildPaginationParams(e,cn);this.addOptionalFilterParams(n,e,["search","name","userAddress"]);const a=await this.http.get(t,n,this.getMultiAuthHeaders()),s=this.extractData(a);return{items:s.bans,pageInfo:s.pageInfo}}async getBanStatus(e){!function(e){if(Wn(e.tokenName,"tokenName",sn),!Pn(e.userAddress))throw Ct("userAddress")}(e);const t=this.buildEndpoint(q,{tokenName:e.tokenName,userAddress:e.userAddress}),n=await this.http.get(t,{},this.getMultiAuthHeaders()),a=this.extractDataOrNull(n);return{banned:null!==a,...null!==a&&{ban:a},tokenName:jt(e.tokenName),userAddress:e.userAddress.toLowerCase()}}async getActiveUsers(e){!function(e){if(Wn(e.tokenName,"tokenName",sn),void 0!==e.type&&!Pi(e.type))throw new bt(`type must be one of: ${Object.values(Ui).join(", ")}`,"type",ft)}(e);const t=this.buildEndpoint(j,{tokenName:e.tokenName}),n={};this.addOptionalFilterParams(n,e,["type","search","name","userAddress"]);const a=await this.http.get(t,n,this.getMultiAuthHeaders());return this.extractData(a)}async createGlobalBan(e){!function(e){Mi(e)}(e);const t=$i(e),n=await this.http.post(V,t,this.getDualAuthHeaders());return{ban:this.extractData(n)}}async removeGlobalBan(e){!function(e){if(!Pn(e.userAddress))throw Ct("userAddress")}(e);const t=this.buildEndpoint(J,{userAddress:e.userAddress}),n=await this.http.delete(t,{},this.getDualAuthHeaders()),a=this.extractDataOrNull(n);return{removed:a?.removed??!0,userAddress:a?.userAddress??e.userAddress.toLowerCase()}}async listGlobalBans(e){const t=e??{pageSize:20};!function(e){Ln(0,void 0,cn,e.pageSize)}(t);const n=this.buildPaginationParams(t,cn);this.addOptionalFilterParams(n,t,["search","name","userAddress"]);const a=await this.http.get(X,n,this.getDualAuthHeaders()),s=this.extractData(a);return{items:s.bans,pageInfo:s.pageInfo}}async getGlobalBan(e){!function(e){if(!Pn(e.userAddress))throw Ct("userAddress")}(e);const t=this.buildEndpoint(Q,{userAddress:e.userAddress}),n=await this.http.get(t,{},this.getDualAuthHeaders()),a=this.extractDataOrNull(n);return{banned:null!==a,...null!==a&&{ban:a},userAddress:e.userAddress.toLowerCase()}}}function $i(e){const t={userAddress:e.userAddress};return void 0!==e.reason&&(t.reason=e.reason),void 0!==e.durationSeconds&&(t.durationSeconds=e.durationSeconds),t}async function Ki(e,t={}){const{maxPages:n=1e4,logger:a,pageSize:s=20,concurrency:r=1,startPage:i=1}=t,o=[];let c=i;const l=i+n-1;let d=!0,u=0;if(r<=1)for(;d&&c<=l;){a&&a.debug(`Auto-pagination: fetching page ${c} with limit ${s}`);const t=await e(c,s);if(null==t||!Array.isArray(t.items)){a&&a.warn("Auto-pagination: received invalid result structure, stopping");break}if(o.push(...t.items),u=t.total,a&&a.debug(`Auto-pagination: page ${c} returned ${t.items.length} items, hasNext: ${String(t.hasNext)}`),0===t.items.length){a&&a.debug(`Auto-pagination: no items returned on page ${c}, exiting loop`);break}d=t.hasNext,c++}else for(a&&a.debug(`Auto-pagination: using concurrent mode with concurrency=${r}`);d&&c<=l;){const t=[];for(let e=0;e<r&&c+e<=l;e++)t.push(c+e);a&&a.debug(`Auto-pagination: fetching pages ${t.join(", ")} concurrently`);const n=t.map(t=>e(t,s).catch(e=>{const n=e,r=n.statusCode??n.response?.status??n.originalError?.response?.status??n.status??n.launchpadError?.statusCode;if(400===r||404===r)return a&&a.debug(`Auto-pagination: page ${t} returned ${r} (end of pagination)`,{statusCode:r}),{items:[],total:0,totalPages:0,page:t,limit:s,hasNext:!1,hasPrevious:!1};throw e})),i=await Promise.all(n);for(const e of i){if(null==e||!Array.isArray(e.items)){a&&a.warn("Auto-pagination: received invalid result structure in batch, stopping"),d=!1;break}if(0===e.items.length){a&&a.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,a&&a.debug(`Auto-pagination: batch complete, total items so far: ${o.length}`)}return c>l&&a&&a.warn(`Auto-pagination: exceeded maxPages limit of ${n} (maxPage=${l}), stopping iteration`),a&&a.debug(`Auto-pagination: completed with total items: ${o.length}, total count: ${u}`),{items:o,total:u}}function Gi(e){if("string"==typeof e){if(!Pn(t=e)||!t.includes("|"))throw new bt(`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=Qr(n.slice(0,4).join("|")),t=n[4]??"0";return{...e,instance:t.length>0?t:"0"}}return{...Qr(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(!Yr(e))throw new bt("Invalid tokenId object format. All fields (collection, category, type, additionalKey) must be non-empty strings","tokenId","INVALID_TOKEN_ID_FORMAT");return e}if(!Yr(e))throw new bt("Invalid tokenId object format. All fields (collection, category, type, additionalKey) are required","tokenId","INVALID_TOKEN_ID_FORMAT");return{...e,instance:"0"}}throw new bt(`Invalid tokenId type: ${typeof e}. Expected string, TokenClassKey, or TokenInstanceKey`,"tokenId","INVALID_TOKEN_ID_TYPE")}function Wi(e){return function(e){try{if(!Pn(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("$");if(n.length<4)throw new Error(`Invalid vault address format: expected at least 4 parts separated by $, got ${n.length}`);const[a,s,r,...i]=n;if(""===a||""===s||""===r)throw new Error("Collection, category, and type must be non-empty");const o=i.slice(0,-1),c=o.length>0?o.join("$"):i[0];if(void 0===a||void 0===s||void 0===r||""===c||void 0===c)throw new Error("AdditionalKey must be non-empty");return{collection:a,category:s,type:r,additionalKey:c}}catch(t){throw new bt(`Invalid vault address: "${e}". Expected format: "service|Token$Unit$SYMBOL$additionalKey$launchpad". Error: ${rt(t)}`,"vaultAddress","INVALID_VAULT_ADDRESS_FORMAT")}}(e)}function Hi(e){return{...Wi(e),instance:"0"}}function qi(e){return Wi(e).type}function zi(e){return Ls(Gi(e))}var ji=Object.freeze({__proto__:null,extractTokenSymbolFromVault:qi,isTokenClassKeyStrict:Yr,normalizeToTokenInstanceKey:Gi,normalizeTokenIdToString:zi,parseVaultAddressToTokenClassKey:Wi,parseVaultAddressToTokenInstance:Hi});class Vi{constructor(e,t=!1,n){this.dexApiHttp=e,this.logger=new Jt({debug:t,context:n??this.constructor.name})}getApiEndpoint(){return"/v1/tokens"}getMaxLimit(){return 1e3}getDefaultLimit(){return 1e3}async executePaginatedRequest(e,t,n){const a=Math.min(t,this.getMaxLimit()),s=this.buildApiParams(n),r=await this.dexApiHttp.request({method:"GET",url:this.getApiEndpoint(),params:{...s,pageSize:a,offset:e}});if(Mn(r)||!Array.isArray(r.tokens))throw new bt("Invalid API response: expected { tokens: array }","response","INVALID_RESPONSE");return{items:this.transformApiResponse(r.tokens),rawCount:r.tokens.length}}async autoPaginateFetch(e){return async function(e,t){const{maxLimit:n,logger:a,maxPages:s=1e4}=t,r=[];let i=0,o=!0,c=0;for(;o&&c<s;){a&&a.debug(`Auto-pagination (offset): fetching at offset ${i} with limit ${n}`);const t=await e(i,n);if(null==t||!Array.isArray(t.items)){a&&a.warn("Auto-pagination (offset): received invalid result structure, stopping");break}r.push(...t.items),o=t.rawCount===n,i+=n,c++,a&&a.debug(`Auto-pagination (offset): fetched ${r.length} items so far (hasMore=${String(o)})`)}return c>=s&&a&&a.warn(`Auto-pagination (offset): exceeded maxPages limit of ${s}, stopping`),a&&a.debug(`Auto-pagination (offset): completed with total items: ${r.length}`),r}(async(t,n)=>this.executePaginatedRequest(t,n,e),{maxLimit:this.getMaxLimit(),logger:this.logger})}handleError(e,t){throw Rt(e,t,this.logger)}}class Xi extends Jn{constructor(e=!1){super(e),this.primaryIndex=new Map,this.secondaryIndex=new Map,this.fetchTimestamps=new Map}normalizeKey(e){return Vt(e)}has(e){const t=this.primaryIndex.get(e);return void 0!==t&&t.size>0}getAll(e){const t=this.primaryIndex.get(e);return t?Array.from(t.values()):[]}getByPrimaryKey(e,t){const n=this.normalizeKey(t);return this.primaryIndex.get(e)?.get(n)}getBySecondaryKey(e,t){const n=this.normalizeKey(t);return this.secondaryIndex.get(e)?.get(n)}set(e,t){const n=new Map,a=new Map;for(const e of t){const t=this.normalizeKey(this.extractPrimaryKey(e));n.set(t,e);const s=this.normalizeKey(this.extractSecondaryKey(e));a.set(s,e)}this.primaryIndex.set(e,n),this.secondaryIndex.set(e,a),this.fetchTimestamps.set(e,Date.now()),this.logger.debug(`Cached ${t.length} items for ${e}`)}merge(e,t){let n=this.primaryIndex.get(e);n||(n=new Map,this.primaryIndex.set(e,n));let a=this.secondaryIndex.get(e);a||(a=new Map,this.secondaryIndex.set(e,a));for(const e of t){const t=this.normalizeKey(this.extractPrimaryKey(e));n.set(t,e);const s=this.normalizeKey(this.extractSecondaryKey(e));a.set(s,e)}this.fetchTimestamps.set(e,Date.now()),this.logger.debug(`Merged ${t.length} items for ${e} (total: ${n.size})`)}getFetchTimestamp(e){return this.fetchTimestamps.get(e)}buildBaseStats(e){const t=[];let n=0;const a={},s={};for(const t of e)a[t]=0;for(const[e,r]of this.primaryIndex){t.push(e),n+=r.size,a[e]=r.size;const i=this.fetchTimestamps.get(e);void 0!==i&&(s[e]=i)}return{networks:t,totalItems:n,itemsByNetwork:a,fetchTimestamps:s}}clear(e){void 0!==e&&""!==e?(this.primaryIndex.delete(e),this.secondaryIndex.delete(e),this.fetchTimestamps.delete(e),this.logger.debug(`Cleared cache for ${e}`)):(this.primaryIndex.clear(),this.secondaryIndex.clear(),this.fetchTimestamps.clear(),this.logger.debug("Cleared all caches"))}size(e){return this.primaryIndex.get(e)?.size??0}hasByPrimaryKey(e,t){return void 0!==this.getByPrimaryKey(e,t)}getCachedNetworks(){return Array.from(this.primaryIndex.keys())}dump(){const e={};for(const t of this.getCachedNetworks())e[t]=this.getAll(t);return e}}const Qi=["ETHEREUM","SOLANA"];class Ji extends Xi{constructor(e=!1){super(e)}extractPrimaryKey(e){return e.symbol}extractSecondaryKey(e){return e.stringifiedTokenClassKey}getBySymbol(e,t){return this.getByPrimaryKey(e,t)}getByTokenId(e,t){return this.getBySecondaryKey(e,t)}getContractAddress(e,t){const n=this.getBySymbol(e,t);if(n)return"ETHEREUM"===e?n.ethereumContractAddress:n.solanaContractAddress}isTokenBridgeable(e,t){return void 0!==this.getBySymbol(e,t)}getStats(){const e=this.buildBaseStats(Qi);return{...e,totalTokens:e.totalItems,tokensByNetwork:e.itemsByNetwork}}}class Yi extends Vi{constructor(e,t=!1){super(e,t,"BridgeableTokenService"),this.cache=new Ji(t)}buildApiParams(e){return{canBridgeTo:(e?.network??"ETHEREUM").toLowerCase()}}transformApiResponse(e){return e.map(e=>{const t=e.otherNetworks?.find(e=>"Ethereum"===e.network),n=e.otherNetworks?.find(e=>"Solana"===e.network),a=e.canBridgeTo.map(e=>e.network).filter(e=>"Ethereum"===e||"Solana"===e),s={symbol:e.symbol,name:e.name,decimals:e.decimals,galaChainDescriptor:{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey},stringifiedTokenClassKey:e.stringifiedTokenClassKey,verified:e.verified,supportedChains:a};return void 0!==t?.contractAddress&&(s.ethereumContractAddress=t.contractAddress),void 0!==t?.symbol&&(s.ethereumSymbol=t.symbol),void 0!==t?.allowanceStorageSlot&&(s.ethereumAllowanceSlot=t.allowanceStorageSlot),void 0!==n?.contractAddress&&(s.solanaContractAddress=n.contractAddress),void 0!==n?.symbol&&(s.solanaSymbol=n.symbol),void 0!==e.image&&(s.image=e.image),void 0!==e.description&&(s.description=e.description),s})}async fetchBridgeableTokensByNetwork(e){const{network:t,offset:n=0,limit:a=this.getDefaultLimit()}=e,s=Math.min(a,this.getMaxLimit());return this.logger.debug(`Fetching bridgeable tokens for ${t} (offset=${n}, limit=${s})`),Rs(async()=>{const e=(await this.executePaginatedRequest(n,s,{network:t})).items;return 0===n?this.cache.set(t,e):this.cache.merge(t,e),{tokens:e,network:t,fetchedAt:Date.now(),tokenCount:e.length}},`Failed to fetch bridgeable tokens for ${t}`,this.logger)}async fetchAllBridgeableTokensByNetwork(e){return Rs(async()=>{const t=await async function(e){const{network:t,cache:n,fetchFn:a,logger:s,itemTypeName:r="items"}=e;if(n.has(t)){const e=n.getAll(t);return s&&s.debug(`Returning ${e.length} cached ${r} for ${t}`),{items:e,fetchedAt:n.getFetchTimestamp(t)??Date.now(),itemCount:e.length}}s&&s.debug(`Fetching all ${r} for ${t} (no cache)`);const i=await a();return n.set(t,i),{items:i,fetchedAt:Date.now(),itemCount:i.length}}({network:e,cache:this.cache,fetchFn:()=>this.autoPaginateFetch({network:e}),logger:this.logger,itemTypeName:"bridgeable tokens"});return{tokens:t.items,network:e,fetchedAt:t.fetchedAt,tokenCount:t.itemCount}},`Failed to fetch bridgeable tokens for ${e}`,this.logger)}async fetchAllTokensBridgeableToEthereum(){return this.fetchAllBridgeableTokensByNetwork("ETHEREUM")}async fetchAllTokensBridgeableToSolana(){return this.fetchAllBridgeableTokensByNetwork("SOLANA")}async isTokenBridgeableToNetwork(e){const{tokenId:t,network:n}=e,a=zi(t);this.cache.has(n)||await this.fetchAllBridgeableTokensByNetwork(n);const s=this.cache.getByTokenId(n,a),r=void 0!==s,i=r?"ETHEREUM"===n?s.ethereumContractAddress:s.solanaContractAddress:void 0,o={isBridgeable:r,tokenSymbol:s?.symbol??Qr(a).collection,network:n};return void 0!==i&&(o.contractAddress=i),o}async isTokenBridgeableToEthereum(e){return this.isTokenBridgeableToNetwork({tokenId:e,network:"ETHEREUM"})}async isTokenBridgeableToSolana(e){return this.isTokenBridgeableToNetwork({tokenId:e,network:"SOLANA"})}async getTokenBySymbol(e,t){const n=this.cache.getBySymbol(t,e);return n||(await this.fetchAllBridgeableTokensByNetwork(t),this.cache.getBySymbol(t,e))}async getTokenByTokenId(e,t){const n=this.cache.getByTokenId(t,e);return n||(await this.fetchAllBridgeableTokensByNetwork(t),this.cache.getByTokenId(t,e))}async getContractAddress(e,t){const n=await this.getTokenBySymbol(e,t);if(n)return"ETHEREUM"===t?n.ethereumContractAddress:n.solanaContractAddress}async getSupportedTokenSymbols(e){return this.cache.has(e)||await this.fetchAllBridgeableTokensByNetwork(e),this.cache.getAll(e).map(e=>e.symbol)}async preload(){this.logger.debug("Preloading bridgeable tokens for all networks"),await Promise.all([this.fetchAllBridgeableTokensByNetwork("ETHEREUM"),this.fetchAllBridgeableTokensByNetwork("SOLANA")]),this.logger.debug("Preloading complete")}getCacheStats(){return this.cache.getStats()}clearCache(e){this.cache.clear(e)}}function Zi(e){return{maxAcceptableReverseBondingCurveFee:_n(e.maxAcceptableReverseBondingCurveFee)}}class eo extends c.ChainCallDTO{constructor(e,t,n="0",a={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=_n(t),this.expectedToken=Rn(n),this.extraFees=Zi(a)}}class to extends c.ChainCallDTO{constructor(e,t,n,a={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=Rn(t),this.expectedNativeToken=_n(n),this.extraFees=Zi(a)}}class no extends c.ChainCallDTO{constructor(e,t,n="0",a={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=Rn(t),this.expectedNativeToken=_n(n),this.extraFees=Zi(a)}}class ao extends c.ChainCallDTO{constructor(e,t,n,a={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=_n(t),this.expectedToken=Rn(n),this.extraFees=Zi(a)}}const so={BuyNativeDto:eo,BuyExactDto:to,SellExactDto:no,SellNativeDto:ao};function ro(e,t,n){let a;xn(t,0,1,"slippageToleranceFactor");try{a=Nn(e,"expectedAmount")}catch{throw new Error(`Invalid expected amount: ${e}. Must be a valid number`)}if(0===t)return e;const s=a.multipliedBy(t);let r;switch(n){case"buy-native":case"sell-exact":r=a.minus(s);break;case"buy-exact":case"sell-native":r=a.plus(s);break;default:throw new Error(`Unknown operation type: ${n}`)}return as(r).isLessThan(0)&&(r=as(0)),ss(r)}function io(e){return`${e}-${Date.now()}_${l.v4().replace(/-/gu,"").substring(0,26)}`}function oo(){return io("galaconnect-operation")}function co(e,t){const n={[e]:[]},a=new Set;function s(e){const t=n[e];if(void 0===t)throw new Error("Missing EIP-712 type "+e);return t}function r(e,t,i,o=!1){if(void 0===t)return;if(Array.isArray(t)){const n=r(e,t[0],i,!0);return o||(a.add(e),s(i).push({name:e,type:(n??e)+"[]"})),void 0===n?void 0:n+"[]"}if("object"==typeof t&&null!==t){if(void 0!==n[e]||a.has(e))throw new Error("Name collisions not yet supported");n[e]=[];for(const[n,s]of Object.entries(t)){if(a.has(n))throw new Error("Name collisions not yet supported");r(n,s,e)}return o||(a.add(e),s(i).push({name:e,type:e})),e}let c;switch(typeof t){case"string":c="string";break;case"number":c="uint256";break;case"boolean":c="bool";break;case"bigint":case"symbol":case"function":case"undefined":case"object":throw new Error("Unsupported type for fieldName "+e+", "+typeof t);default:throw new Error("Unsupported type: "+typeof t)}return o||(a.add(e),s(i).push({name:e,type:c})),c}for(const[n,a]of Object.entries(t))r(n,a,e);return n}const lo={name:"GalaChain"},uo={name:"ethereum",chainId:1};function ho(e){if("string"!=typeof e)throw new Error("Wallet returned an invalid signature");return e}function go(e,t,n,a){return{...e,signature:t,types:n,domain:a}}class mo extends n.PrivateKeySigner{constructor(e){super(e),this.typedDataClient=new c.SigningClient(e)}async signTypedData(e,t){const n=await this.typedDataClient.sign(e,t,c.SigningType.SIGN_TYPED_DATA),a=co(e,t);return{...go(t,n.signature,a,lo)}}}class po extends n.GalaWalletSigner{async signTypedData(e,t){const n=co(e,t),a=c.calculatePersonalSignPrefix(t),s={domain:uo,types:n,message:{...t,prefix:a},Primary_type:e};return go(t,ho(await function(){const e=globalThis.window,t=e?.gala;if(void 0===t)throw new Error("Gala wallet is not available");return t}().request({method:"eth_signTypedData",params:[JSON.stringify(s),this.walletAddress]})),n,uo)}}class fo extends n.BrowserWalletSigner{constructor(e,t){super(e,t),this.typedDataProvider=e}async signTypedData(e,t){const n=this.typedDataProvider,a=await n.getNetwork(),s={name:a.name,chainId:Number(a.chainId)},r=co(e,t),i=c.calculatePersonalSignPrefix(t),o=await n.getSigner();return go(t,ho(await o.signTypedData(s,r,{...t,prefix:i})),r,s)}}function yo(e){if(!Pn(e))throw new Error("Invalid token format: token must be a non-empty string");return e.replace(/\|/g,"$")}function vo(e){return Xr(e,"$","dollar-delimited token")}class ko extends Jn{constructor(e=!1){super(e)}generateStringsInstructions(e){try{this.logger.debug("🔧 Generating stringsInstructions for:",e);const t=this.extractTokenSymbolFromVault(e),n=this.createTokenInstance(t),a=this.createGalaInstance(),s=`$service$${n.toStringKey()}$launchpad`,r=`$tokenBalance$${n.toStringKey()}$${e}`,i=`$tokenBalance$${n.toStringKey()}$${e}`,o=`$tokenBalance$${a.toStringKey()}$${e}`,c=[s,r,i,o,`$tokenBalance$${a.toStringKey()}$${e}`];return this.logger.debug("✅ Generated stringsInstructions:",c),c}catch(e){this.logger.error("❌ Failed to generate stringsInstructions:",e);const t=rt(e);throw new bt(`Failed to generate stringsInstructions: ${t}`,"vaultAddress","INVALID_VAULT_ADDRESS")}}createTokenInstance(e){const t=new d.TokenClassKey;return t.collection=e.toLowerCase(),t.category="Unit",t.type="none",t.additionalKey="none",this.logger.debug("🪙 Created token instance:",{symbol:e,lowercaseCollection:e.toLowerCase(),stringKey:t.toStringKey()}),t}createGalaInstance(){const e=new d.TokenClassKey;return e.collection="GALA",e.category="Unit",e.type="none",e.additionalKey="none",this.logger.debug("🟡 Created GALA instance:",{stringKey:e.toStringKey()}),e}extractTokenSymbolFromVault(e){if(!Pn(e))throw Ct("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 bt)throw Nt("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad");throw e}}validateVaultAddress(e){if(!Pn(e))throw Ct("vaultAddress","Vault address");if(!e.startsWith("service|Token$Unit$"))throw Nt("vaultAddress",'starting with "service|Token$Unit$"');if(!e.endsWith("$launchpad"))throw Nt("vaultAddress",'ending with "$launchpad"');const t=function(e){if(!Pn(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],a=t[2];return void 0===n||void 0===a?null:{tokenSymbol:n,creatorAddress:a.toLowerCase()}}(e);if(!t)throw Nt("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 Nt("vaultAddress","containing a 1-10 letter token symbol (case insensitive)");return this.logger.debug("✅ Vault address validation passed:",e),!0}generateTokenClassKeyString(e,t,n,a){return`${e}$${t}$${n}$${a}`}parseTokenClassKeyString(e){try{return vo(e)}catch(e){if(e instanceof bt)throw Nt("stringKey","format: collection$category$type$additionalKey (4 parts)");throw e}}}function bo(e){return"object"==typeof e&&null!==e?e:void 0}class wo extends Qn{constructor(e,t,n=!1,a,s,r=.05,i=.01){if(super(e,n),this.tokenResolver=t,this._walletProvider=a,this.userAddress=s,this.defaultSlippageToleranceFactor=r,this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor=i,this.bundleEndpoint="/bundle",null!==this._walletProvider&&void 0!==this._walletProvider&&null!=s){const e=bo(this._walletProvider),t=e?.privateKey;"string"==typeof t?this.signer=new mo(t):function(e){const t=bo(e);return"function"==typeof t?.request}(this._walletProvider)&&void 0!==this.userAddress&&(this.signer=new fo(this._walletProvider,this.userAddress)),this.tokenKeyService=new ko(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 Wt(()=>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:Mt(n),error:n.error}),this.handleBundleResponse(n))}catch(e){if(e instanceof bt)return{success:!1,error:rt(e)};throw e}}validateBundleData(e){if(null==e)throw Ct("bundleData","Bundle data");if(null===e.signedDto||void 0===e.signedDto)throw Ct("signedDto","Signed DTO");if(!Pn(e.method))throw Ct("method","Method name");if(!Array.isArray(e.stringsInstructions))throw Nt("stringsInstructions","an array of resource tracking strings");if(0===e.stringsInstructions.length)throw new bt("stringsInstructions cannot be empty","stringsInstructions","EMPTY_ARRAY");const t=["BuyWithNative","BuyExactToken","SellExactToken","SellWithNative"];if(!t.includes(e.method))throw Nt("method",`one of: ${t.join(", ")}`);e.stringsInstructions.forEach((e,t)=>{if(!Pn(e))throw new bt(`stringsInstructions[${t}] must be a non-empty string`,`stringsInstructions[${t}]`,"INVALID_INSTRUCTION");if(!Jr(e))throw new bt(`stringsInstructions[${t}] must start with '$': ${e}`,`stringsInstructions[${t}]`,"INVALID_INSTRUCTION_FORMAT")}),this.logger.debug("✅ Bundle data validation passed")}formatBundleRequest(e){return{signedDto:e.signedDto,stringsInstructions:e.stringsInstructions,method:e.method}}handleBundleResponse(e){const t=$t(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(ct(e)&&null!==e.response&&void 0!==e.response){const t=$t(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 rt(e)??"Unknown bundle transaction error"}async getBundlerTransactionResult(e){try{if(!Pn(e))throw Ct("transactionId","Transaction ID");let t;this.logger.debug("🔍 Checking bundler transaction result:",e);try{t=await Wt(()=>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 bt)return{success:!1,error:rt(e)};throw e}}async cancelTransaction(e){try{if(!Pn(e))throw Ct("transactionId","Transaction ID");let t;this.logger.debug("🚫 Cancelling transaction:",e);try{t=await Wt(()=>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 bt)return{success:!1,error:rt(e)};throw e}}async getHealthStatus(){this.logger.debug("🏥 Checking bundle service health");try{const e=await Wt(()=>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:a,expectedAmount:s}=e,{effectiveSlippageFactor:r,effectiveMaxFee:i,vaultAddress:o}=await this.prepareTradingOperation(t,e.maxAcceptableReverseBondingCurveFee,e.maxAcceptableReverseBondingCurveFeeSlippageFactor,e.slippageToleranceFactor);if("native"===a){if(null==s||""===s)throw new bt("expectedAmount is required for native buy operations. Use getBuyTokenAmount() first to calculate expected tokens.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=ro(s,r,"buy-native");this.logger.debug("BuyNative slippage applied:",{originalExpectedTokens:s,slippageFactor:r,adjustedMinTokens:e});const t=new so.BuyNativeDto(o,n,e,{maxAcceptableReverseBondingCurveFee:i});return await this.executeBundleTransaction(t,"BuyWithNative",o)}{if(null==s||""===s)throw new bt("expectedAmount is required for exact buy operations. Use getBuyTokenAmount() first to calculate expected GALA cost.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=ro(s,r,"buy-exact");this.logger.debug("BuyExact slippage applied:",{originalExpectedGalaCost:s,slippageFactor:r,adjustedMaxGalaCost:e});const t=new so.BuyExactDto(o,n,e,{maxAcceptableReverseBondingCurveFee:i});return await this.executeBundleTransaction(t,"BuyExactToken",o)}}async sellToken(e){this.ensureTradingServicesAvailable();const{tokenName:t,amount:n,type:a,expectedAmount:s}=e,{effectiveSlippageFactor:r,effectiveMaxFee:i,vaultAddress:o}=await this.prepareTradingOperation(t,e.maxAcceptableReverseBondingCurveFee,e.maxAcceptableReverseBondingCurveFeeSlippageFactor,e.slippageToleranceFactor);if("exact"===a){if(null==s||""===s)throw new bt("expectedAmount is required for exact sell operations. Use getSellTokenAmount() first to calculate expected GALA.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=ro(s,r,"sell-exact");this.logger.debug("SellExact slippage applied:",{originalExpectedGala:s,slippageFactor:r,adjustedMinGala:e});const t=new so.SellExactDto(o,n,e,{maxAcceptableReverseBondingCurveFee:i});return await this.executeBundleTransaction(t,"SellExactToken",o)}{if(null==s||""===s)throw new bt("expectedAmount is required for native sell operations. Use getSellTokenAmount() first to calculate tokens to sell.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=ro(s,r,"sell-native");this.logger.debug("SellNative slippage applied:",{originalExpectedTokensToSell:s,slippageFactor:r,adjustedMaxTokensToSell:e});const t=new so.SellNativeDto(o,n,e,{maxAcceptableReverseBondingCurveFee:i});return await this.executeBundleTransaction(t,"SellWithNative",o)}}async prepareTradingOperation(e,t,n,a){const{effectiveSlippageFactor:s,effectiveMaxFee:r}=this.calculateEffectiveSlippage(t,n,a),i=await this.resolveTokenNameToVault(e);if(null==i)throw Tt(e);return{effectiveSlippageFactor:s,effectiveMaxFee:r,vaultAddress:i}}calculateEffectiveSlippage(e,t,n){const a=n??this.defaultSlippageToleranceFactor,s=t??this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor;let r=e??"0";return null!=e&&(r=ro(e,s,"buy-exact"),this.logger.debug("Reverse bonding curve fee slippage applied:",{baseFee:e,slippageFactor:s,adjustedMaxFee:r})),{effectiveSlippageFactor:a,effectiveFeeSlippageFactor:s,effectiveMaxFee:r}}ensureTradingServicesAvailable(){if(!this.signer||!this.tokenKeyService)throw Dt("Trading services not available. BundleService requires walletProvider and userAddress for trading operations.","walletProvider");if(null===this.userAddress||void 0===this.userAddress)throw Ct("userAddress","User address")}async executeBundleTransaction(e,t,n){this.ensureTradingServicesAvailable();try{e.uniqueKey=io("galaswap-operation");const a=await this.signer.signObject(t,e),s=this.tokenKeyService.generateStringsInstructions(n),r={stringsInstructions:s,method:t,signedDto:a};this.logger.debug("📦 Bundle transaction data:",{method:t,stringsInstructions:s,dtoKeys:Object.keys(a)});const i=await this.submitTransaction(r);if(i.success){const e=$t(i);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=i.error;throw new At("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 So extends Qn{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(tt),t=this.extractData(e);return this.logger.debug("Fetched client feature flags",{flagCount:Object.keys(t.flags).length}),{flags:t.flags}}}var Ao,Eo,To,Co;!function(e){e.CHAT_MESSAGE="CHAT_MESSAGE",e.COMMENT="COMMENT",e.STREAM="STREAM",e.RECORDING="RECORDING"}(Ao||(Ao={})),function(e){e.INAPPROPRIATE_CONTENT="INAPPROPRIATE_CONTENT",e.SPAM="SPAM",e.HARASSMENT="HARASSMENT",e.SCAM="SCAM",e.OTHER="OTHER"}(Eo||(Eo={})),function(e){e.PENDING="PENDING",e.DISMISSED="DISMISSED",e.ACTIONED="ACTIONED"}(To||(To={})),function(e){e.DELETE_CONTENT="DELETE_CONTENT",e.BAN_USER="BAN_USER",e.DELETE_AND_BAN="DELETE_AND_BAN"}(Co||(Co={})),Eo.INAPPROPRIATE_CONTENT,Eo.SPAM,Eo.HARASSMENT,Eo.SCAM,Eo.OTHER,To.PENDING,To.DISMISSED,To.ACTIONED,Co.DELETE_CONTENT,Co.BAN_USER,Co.DELETE_AND_BAN,Ao.CHAT_MESSAGE,Ao.COMMENT,Ao.STREAM,Ao.RECORDING;const No=$n(Ao),Io=$n(Eo),Do=$n(To),_o=$n(Co),Ro={TOKEN_NAME:rn,CONTENT_ID:hn.CONTENT_ID,DETAILS:hn.FLAG_DETAILS,PAGINATION:{MAX_LIMIT:cn}};function xo(e,t="tokenName"){Wn(e,t,Ro.TOKEN_NAME)}function Oo(e){if(void 0!==e.contentType&&!No(e.contentType))throw Nt("contentType",`one of: ${Object.values(Ao).join(", ")}`,"Content type");if(void 0!==e.status&&!Do(e.status))throw Nt("status",`one of: ${Object.values(To).join(", ")}`);if(void 0!==e.reason&&!Io(e.reason))throw Nt("reason",`one of: ${Object.values(Eo).join(", ")}`);if(void 0!==e.reporterAddress&&!Pn(e.reporterAddress))throw Bt("reporterAddress","a non-empty string",typeof e.reporterAddress);if(void 0!==e.reporterAddress&&ca(e.reporterAddress,"reporterAddress"),void 0!==e.reportedUserAddress&&!Pn(e.reportedUserAddress))throw Bt("reportedUserAddress","a non-empty string",typeof e.reportedUserAddress);void 0!==e.reportedUserAddress&&ca(e.reportedUserAddress,"reportedUserAddress"),Ln(0,void 0,Ro.PAGINATION.MAX_LIMIT,e.pageSize)}class Fo extends _i{constructor(e,t,n,a=!1,s){super(e,t,n,a,s)}async createFlag(e){!function(e){if(xo(e.tokenName),void 0===e.contentType)throw Ct("contentType","Content type");if(!No(e.contentType))throw Nt("contentType",`one of: ${Object.values(Ao).join(", ")}`,"Content type");if(!Pn(e.contentId))throw Ct("contentId","Content ID");if(e.contentId.length>Ro.CONTENT_ID.MAX_LENGTH)throw Ft("contentId",Ro.CONTENT_ID.MAX_LENGTH,e.contentId.length,"Content ID");if(!Pn(e.reportedUserAddress))throw Ct("reportedUserAddress","Reported user address");if(ca(e.reportedUserAddress,"reportedUserAddress"),!(e.contentType!==Ao.STREAM&&e.contentType!==Ao.RECORDING||void 0!==e.reason&&null!==e.reason))throw Ct("reason","Reason");if(void 0!==e.reason&&!Io(e.reason))throw Nt("reason",`one of: ${Object.values(Eo).join(", ")}`,"Reason");if(void 0!==e.details&&!Pn(e.details))throw Bt("details","a non-empty string",typeof e.details);if(void 0!==e.details&&e.details.length>Ro.DETAILS.MAX_LENGTH)throw Ft("details",Ro.DETAILS.MAX_LENGTH,e.details.length)}(e);const t={tokenName:e.tokenName,contentType:e.contentType,contentId:e.contentId,reportedUserAddress:e.reportedUserAddress};null!==e.reason&&void 0!==e.reason&&(t.reason=e.reason),null!==e.details&&void 0!==e.details&&(t.details=e.details);const n=await this.http.post(oe.CREATE,t,this.getMultiAuthHeaders());return{flag:this.extractData(n).flag}}async listFlags(e){return function(e){xo(e.tokenName),Oo(e)}(e),this.fetchFlagList(e)}async listGlobalFlags(e={}){return function(e){void 0!==e.tokenName&&xo(e.tokenName),Oo(e)}(e),this.fetchFlagList(e)}async dismissFlag(e){!function(e){if(void 0===e.flagId||null===e.flagId)throw Ct("flagId","Flag ID");try{Fn(e.flagId,"flagId")}catch{throw Nt("flagId","a positive integer","Flag ID")}}(e);const t=oe.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 Ct("flagId","Flag ID");try{Fn(e.flagId,"flagId")}catch{throw Nt("flagId","a positive integer","Flag ID")}if(void 0===e.action)throw Ct("action","Action");if(!_o(e.action))throw Nt("action",`one of: ${Object.values(Co).join(", ")}`,"Action")}(e);const t=oe.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=Ni(e,cn);Ii(t,e,["tokenName","contentType","status","reason","reporterAddress","reportedUserAddress"]);const n=await this.http.get(oe.LIST,t,this.getMultiAuthHeaders()),a=this.extractData(n);return{items:a.flags,pageInfo:a.pageInfo}}}const Bo=["heart","fire","laugh","wow","thumbs_up"];class Uo extends _i{constructor(e,t,n,a=!1,s){super(e,t,n,a,s)}validateReactionTokenName(e){this.validateTokenName(e,rn)}validateMessageId(e){if(!Pn(e))throw Ct("messageId","Message ID");if(On(e,gn.CONTENT_REACTION.MAX_LENGTH,"messageId"),!gn.CONTENT_REACTION.PATTERN.test(e))throw Nt("messageId","msg-{timestamp}-{uuid} or chat-{timestamp}-{uuid} format","Message ID")}validateReactionType(e){if(!Pn(e))throw Ct("reactionType","Reaction type");if(!Bo.includes(e))throw Nt("reactionType",`one of: ${Bo.join(", ")}`,"Reaction type")}async addContentReaction(e){void 0!==e.tokenName&&this.validateReactionTokenName(e.tokenName),this.validateMessageId(e.messageId),this.validateReactionType(e.reactionType);const t=Fe,n={messageId:e.messageId,reactionType:e.reactionType};void 0!==e.tokenName&&(n.tokenName=jt(e.tokenName));const a=await this.http.post(t,n,this.getMultiAuthHeaders()),s=this.extractData(a),{created:r,...i}=s;return{data:i,created:r}}async removeContentReaction(e){void 0!==e.tokenName&&this.validateReactionTokenName(e.tokenName),this.validateMessageId(e.messageId),this.validateReactionType(e.reactionType);const t=`${Be}?${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)}}class Po extends Jn{constructor(e,t,n,a=!1){super(a),this.dexBackendHttp=e,this.cache=t,this.galaChainService=n}async fetchTokenPrice(e){const{tokenId:t}=e,{hasB:n}=Gn(e,"tokenName","tokenId",{description:"token identifier"});if(!0===n&&null!=t)return this.logger.debug(`Fetching spot price by tokenId: ${String(t)}`),this._fetchDexTokenSpotPrice(t);throw new bt("tokenName parameter requires LaunchpadSDK routing - call LaunchpadSDK.fetchTokenPrice({tokenName}) instead","tokenName","INVALID_PARAMS")}async _fetchDexTokenSpotPrice(e){if(null==e)throw Ct("tokenId","Token ID");try{const t=Gi(e),n=Ls(t),a=yo(n);if(this.logger.debug(`Fetching DEX spot price for token: ${a}`),!this.dexBackendHttp)throw It("DEX Backend API client not configured");const s=await this.dexBackendHttp.request({method:"GET",url:"/market/price",params:{assetIds:a}}),r=null!==s&&"object"==typeof s?s:{},i=[t.type,t.collection].filter(e=>"string"==typeof e&&""!==e&&"none"!==e).map(e=>e.toUpperCase()).map(e=>r[e]).find(e=>void 0!==e)??(1===Object.keys(r).length?Object.values(r)[0]:void 0),o=i?.price;if("number"!=typeof o||!Number.isFinite(o))throw new bt(`Invalid price response: no market price for ${a}`,"data","INVALID_RESPONSE");const c=n;let l;try{if(null!==this.cache&&void 0!==this.cache){const e=this.cache.getByTokenId(c);if(null!=e?.symbol)return l=e.symbol,this.logger.debug(`DEX spot price for ${l} (cached): $${o}`),{symbol:l,price:o}}this.logger.debug(`Symbol cache miss for ${c}, fetching from API`);l=(await this.fetchTokenDetails(e)).symbol,this.cache&&(this.cache.setByTokenId(c,{symbol:l}),this.logger.debug(`Cached symbol for ${c}: ${l}`)),this.logger.debug(`DEX spot price for ${l}: $${o}`)}catch(e){this.logger.debug(`Could not fetch token details for symbol, falling back to token format parsing: ${st(e)?e.message:String(e)}`),l=Xt("Token"===t.collection?t.type:t.collection),this.logger.debug(`DEX spot price for ${l} (fallback): $${o}`)}return{symbol:l,price:o}}catch(e){if(e instanceof bt)throw e;throw It(`Failed to fetch DEX spot price: ${rt(e)}`)}}async fetchLaunchpadTokenSpotPrice(e,t,n){if(!Pn(e))throw new bt(ht,"tokenName",mt);try{if(null!=n)try{this.logger.debug(`Checking graduation status for token: ${e}`);const t=await n(e);if(!0===t?.isGraduated){this.logger.debug(`Token ${e} is graduated, using DEX spot price`);const n=Ls(t.sellingToken);return this._fetchDexTokenSpotPrice(n)}}catch(t){this.logger.debug(`Could not determine graduation status for ${e}, falling back to bonding curve: ${rt(t)}`)}this.logger.debug(`Using bonding curve calculation for token: ${e}`);const a=await t({tokenName:e,amount:"1",type:"native"}),s=await this._fetchDexTokenSpotPrice({collection:"GALA",category:"Unit",type:"none",additionalKey:"none"});if(null==s)throw It("GALA price not available");const r=En(a.amount,0)/1e18;if(r<=0)throw new bt(`Invalid token amount calculation: ${r}`,"amount","INVALID_CALCULATION");const i=s.price/r;return{symbol:Xt(e),price:i}}catch(t){if(st(t))throw It(`Failed to calculate launchpad token spot price for ${e}: ${rt(t)}`);throw It(`Failed to calculate launchpad token spot price for ${e}: ${rt(t)}`)}}async fetchTokenDetails(e){this.logger.debug("Fetching token details from GalaChain for tokenId:",e);try{if(!this.galaChainService)throw It("GalaChainService not available for token metadata fetch",500);const t=await this.galaChainService.fetchTokenClassFromChain(e),n={collection:t.collection,category:t.category,type:t.type,additionalKey:t.additionalKey,symbol:t.symbol,decimals:t.decimals,name:t.name,image:t.image,description:t.description,network:t.network,...void 0!==t.contractAddress&&{contractAddress:t.contractAddress}};return this.logger.debug(`Fetched token details for ${t.symbol} from GalaChain`),n}catch(t){if((t instanceof bt||st(t))&&("NetworkError"===t.name||rt(t).includes("Token not found")))throw t;throw It(`Failed to fetch token details from GalaChain for ${String(e)}: ${rt(t)}`,500)}}async fetchAllDexSeasons(){try{if(!this.dexBackendHttp)throw It("DEX Backend API client not configured");const e=await this.dexBackendHttp.request({method:"GET",url:"/leaderboard/seasons"});let t;if(Array.isArray(e))t=e;else{if(null==e||"object"!=typeof e)return this.logger.warn("Seasons endpoint returned invalid data:",e),[];{const n=$t(e);if(Array.isArray(n))t=n;else if(null!=n&&"object"==typeof n&&Array.isArray(n.seasons))t=n.seasons;else{if(!Array.isArray(e.seasons))return this.logger.warn("Seasons endpoint returned unexpected structure:",e),[];t=e.seasons}}}const n=t.map(e=>{const t=e;return{id:t?.id??0,name:t?.name??"",start:tn(t?.start??null),end:tn(t?.end??null),rulesId:t?.rules_id??0}});return this.logger.debug(`Fetched ${n.length} DEX seasons`),n}catch(e){if(st(e)&&rt(e).includes("not configured"))throw e;if(ct(e)&&404===e.response?.status)return this.logger.warn("Seasons endpoint not available"),[];throw It(`Failed to fetch DEX seasons: ${rt(e)}`)}}async fetchCurrentDexSeason(){const e=await this.fetchAllDexSeasons(),t=new Date,n=e.find(e=>t>=e.start&&t<=e.end);return n?this.logger.debug(`Current DEX season: ${n.name} (ID: ${n.id})`):this.logger.debug("No active DEX season found"),n??null}async fetchDexLeaderboardBySeasonId(e){try{Fn(e,"seasonId")}catch{throw Ct("seasonId","Season ID must be a positive number")}try{if(!this.dexBackendHttp)throw It("DEX Backend API client not configured");const t=await this.dexBackendHttp.request({method:"GET",url:"/leaderboard",params:{seasonId:e.toString()}});let n;if(Array.isArray(t))n=t;else{if(null==t||"object"!=typeof t)return this.logger.warn("Leaderboard endpoint returned invalid data:",t),{entries:[],seasonId:e,totalEntries:0};{const a=$t(t);if(null!=a&&"object"==typeof a&&Array.isArray(a.leaderboard))n=a.leaderboard;else if(Array.isArray(t.leaderboard))n=t.leaderboard;else{if(!Array.isArray(a))return this.logger.warn("Leaderboard endpoint returned unexpected structure:",t),{entries:[],seasonId:e,totalEntries:0};n=a}}}const a=n.map(e=>{const t=e,n=t?.mastery_titles??[];return{wallet:t?.wallet??"",rank:t?.rank??0,totalXp:String(t?.total_xp??0),distributionPercent:String(t?.distribution_percent??0),liquidityXp:String(t?.liquidity_xp??0),tradingXp:String(t?.trading_xp??0),masteryTitles:n.map(e=>{const t=e;return{name:t?.name??"",type:t?.type??"trade",order:t?.order??0}})}});return this.logger.debug(`Fetched leaderboard for season ${e} with ${a.length} entries`),{entries:a,seasonId:e,totalEntries:a.length}}catch(t){if(st(t)&&rt(t).includes("must be a positive number"))throw t;throw It(`Failed to fetch DEX leaderboard for season ${e}: ${rt(t)}`)}}async fetchCurrentDexLeaderboard(){const e=await this.fetchCurrentDexSeason();return e?this.fetchDexLeaderboardBySeasonId(e.id):(this.logger.debug("Cannot fetch current leaderboard - no active season"),null)}async fetchDexAggregatedVolumeSummary(){try{if(!this.dexBackendHttp)throw It("DEX Backend API client not configured");const e=$t(await this.dexBackendHttp.request({method:"GET",url:"/v2/trade/volume"}));if(!e)throw It("No data in DEX volume response",500);const t={volume1d:e.volume1d,volume1dDelta:e.volume1dDelta,volume7d:e.volume7d,volume7dDelta:e.volume7dDelta,volume30d:e.volume30d,volume30dDelta:e.volume30dDelta};return this.logger.debug(`Fetched DEX volume summary: $${t.volume1d.toFixed(2)} (1d)`),t}catch(e){throw It(`Failed to fetch DEX volume summary: ${rt(e)}`)}}}const Mo=20,Lo=3e3,$o=1e3,Ko=!0,Go=!0,Wo=!1;class Ho{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 Jt({debug:t.debug??!1,context:"EventsBatcherService"}),this.config={batchSize:t.batchSize??Mo,flushIntervalMs:t.flushIntervalMs??Lo,maxQueueSize:t.maxQueueSize??$o,flushOnPageHide:t.flushOnPageHide??Ko,flushOnPageUnload:t.flushOnPageUnload??Go,debug:t.debug??Wo},this.setupPageLifecycleListeners()}track(e,t,n){if(this.isShuttingDown)return void this.logger.warn("EventsBatcher is shutting down, ignoring track call");const a={eventType:e,payload:t,clientTimestamp:(new Date).toISOString(),...void 0!==n?.userAddress&&""!==n.userAddress&&{userAddress:n.userAddress},...void 0!==n?.tokenName&&""!==n.tokenName&&{tokenName:n.tokenName},...void 0!==n?.sessionId&&""!==n.sessionId&&{sessionId:n.sessionId}};this.buffer(a),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??""}}function qo(e){return 0===(e?.length??0)?"0":e.reduce((e,t)=>u(e).plus(t.quantity).toString(),"0")}function zo(e,t){if(0===(e?.length??0))return[];if(t)return e;const n=Date.now();return e.filter(e=>0===e.expires||e.expires>n)}class jo extends Qn{constructor(e,t=!1){super(e,t)}getChannelForCollection(e){return"MUSIC"===(Jr(e)?e.slice(1).toUpperCase():e.toUpperCase())?"music":"asset"}async fetchGalaBalance(e){return this.fetchTokenBalance(e)}async fetchTokenBalance(e,t=!1){try{const n=`/api/${this.getChannelForCollection(e.collection)}/token-contract/FetchBalances`,a=await this.http.post(n,e);if(null==a)return null;try{lt(a,"Fetch balances")}catch{return null}if(0===(a.Data?.length??0))return null;const s=a.Data.find(t=>t.collection===e.collection&&t.category===e.category&&t.additionalKey===e.additionalKey&&t.type===e.type);if(!s||"0"===s.quantity)return null;const r=Ls(s),i={quantity:s.quantity,collection:s.collection,category:s.category,tokenId:r};if((s.inUseHolds?.length??0)>0){const e=zo(s.inUseHolds??[],t);e.length>0&&(i.inUseHolds=e,i.inUseQuantity=qo(e))}if((s.lockedHolds?.length??0)>0){const e=zo(s.lockedHolds??[],t);e.length>0&&(i.lockedHolds=e,i.lockedQuantity=qo(e))}return void 0===i.lockedQuantity&&void 0===i.inUseQuantity||(i.availableQuantity=function(e,t="0",n="0"){return u(e).minus(t).minus(n).toString()}(i.quantity,i.lockedQuantity,i.inUseQuantity)),i}catch(e){throw It(`Failed to fetch token balance from GalaChain: ${rt(e)}`,void 0,st(e)?e:void 0)}}}function Vo(e){return"string"==typeof e?{...vo(e),instance:"0"}:{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey,instance:"0"}}function Xo(e){return $s(e)}function Qo(e){const t=e[0];return void 0===t?void 0:Xo(t.tokenInstanceKey)}class Jo extends c.ChainCallDTO{constructor(e){super(),this.lockAuthority=e.lockAuthority,this.tokenInstances=e.tokenInstances,this.uniqueKey=e.uniqueKey,void 0!==e.expires&&(this.expires=e.expires),void 0!==e.name&&(this.name=e.name),void 0!==e.signedPayload&&(this.signature=e.signedPayload.signature)}static fromTokenClassKey(e,t,n,a,s){const r=Vo(a);return new Jo({lockAuthority:t??e,tokenInstances:[{owner:e,quantity:n,tokenInstanceKey:r}],...void 0!==s?.expires&&{expires:s.expires},...void 0!==s?.name&&{name:s.name},uniqueKey:s?.uniqueKey??oo()})}static forGALA(e,t,n,a){return new Jo({lockAuthority:t??e,tokenInstances:[{owner:e,quantity:n,tokenInstanceKey:{collection:"GALA",category:"Unit",type:"none",additionalKey:"none",instance:"0"}}],...void 0!==a?.expires&&{expires:a.expires},...void 0!==a?.name&&{name:a.name},uniqueKey:a?.uniqueKey??oo()})}getTokenClassKey(){return Qo(this.tokenInstances)}toSigningPayload(){return{lockAuthority:this.lockAuthority,tokenInstances:this.tokenInstances,...void 0!==this.expires&&{expires:this.expires},...void 0!==this.name&&{name:this.name},uniqueKey:this.uniqueKey}}}class Yo extends c.ChainCallDTO{constructor(e){super(),this.tokenInstances=e.tokenInstances,this.uniqueKey=e.uniqueKey,void 0!==e.name&&(this.name=e.name),e.signedPayload&&(this.signature=e.signedPayload.signature)}static fromTokenClassKey(e,t,n,a){const s=Vo(n);return new Yo({tokenInstances:[{owner:e,quantity:t,tokenInstanceKey:s}],...void 0!==a?.name&&{name:a.name},uniqueKey:a?.uniqueKey??oo()})}static forGALA(e,t,n){return new Yo({tokenInstances:[{owner:e,quantity:t,tokenInstanceKey:{collection:"GALA",category:"Unit",type:"none",additionalKey:"none",instance:"0"}}],...void 0!==n?.name&&{name:n.name},uniqueKey:n?.uniqueKey??oo()})}getTokenClassKey(){return Qo(this.tokenInstances)}toSigningPayload(){return{tokenInstances:this.tokenInstances,...void 0!==this.name&&{name:this.name},uniqueKey:this.uniqueKey}}}function Zo(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Pn(t.amount)&&(void 0!==t.tokenId||Pn(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 ec(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Pn(t.amount)&&(void 0!==t.tokenId||Pn(t.tokenName))&&(void 0===t.name||"string"==typeof t.name)}var tc,nc;!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"}(tc||(tc={}));class ac 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"}(nc||(nc={}));class sc extends Error{constructor(e,t,n){super(e),this.type=t,this.details=n,this.name="TransferError"}}function rc(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 ic(e,t,n,a="[DEBUG] Token resolution (launchpad)"){const s=await t.resolveTokenToVault(e);if(null!==s){const t=Hi(s);return n.debug(a,{tokenName:e,vaultAddress:s,tokenInstance:{collection:t.collection,category:t.category,type:t.type,instance:t.instance}}),t}const r={collection:Vt(e),category:"Unit",type:"none",additionalKey:"none",instance:"0"};return n.debug("[DEBUG] Token resolution (standard format)",{tokenName:e,tokenInstance:{collection:r.collection,category:r.category,type:r.type}}),r}const oc=100,cc=100;class lc extends Qn{constructor(e,t,n,a=!1){super(e,a),this.wallet=t,this.tokenResolver=n,this.nativeSigner=t?new mo(t.privateKey):void 0}async lockTokens(e){if(this.validateLockTokensData(e),!this.wallet||!this.nativeSigner)throw new ac("Wallet required for token lock operations",tc.WALLET_REQUIRED);return Rs(async()=>{const{ownerAddress:t,tokenInstances:n}=this.createTokenOperationContext(),a=[];let s=t;const r=e.tokens.find(e=>void 0!==e.lockAuthority);void 0!==r?.lockAuthority&&(s=ra(r.lockAuthority));const i=e.tokens.find(e=>void 0!==e.expires),o=e.tokens.find(e=>void 0!==e.name);for(const r of e.tokens){const e=await this.resolveTokenEntry(r);n.push({owner:t,quantity:r.amount,tokenInstanceKey:e}),a.push({tokenClassKey:{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey},quantity:r.amount,lockAuthority:void 0!==r.lockAuthority?ra(r.lockAuthority):s})}const c=new Jo({lockAuthority:s,tokenInstances:n,...void 0!==i?.expires&&{expires:i.expires},...void 0!==o?.name&&{name:o.name},uniqueKey:e.uniqueKey??oo()}),l=await this.nativeSigner.signObject("LockToken",c.toSigningPayload()),d=new Jo({...c.toSigningPayload(),signedPayload:l}),u=await this.http.post("/api/asset/token-contract/LockToken",d);try{lt(u,"Token lock failed")}catch(e){const t=dt(u);throw new ac(`${rt(e)}${t}`,tc.NETWORK_ERROR)}return this.extractLockResult(u,a)},"Token lock failed",this.logger,t=>{throw this.handleLockError(t,"Token lock failed",e)})}async unlockTokens(e){if(this.validateUnlockTokensData(e),!this.wallet||!this.nativeSigner)throw new ac("Wallet required for token unlock operations",tc.WALLET_REQUIRED);return Rs(async()=>{const{ownerAddress:t,tokenInstances:n}=this.createTokenOperationContext(),a=[],s=e.tokens.find(e=>void 0!==e.name);for(const s of e.tokens){const e=await this.resolveTokenEntry(s);n.push({owner:t,quantity:s.amount,tokenInstanceKey:e}),a.push({tokenClassKey:{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey},quantity:s.amount})}const r=new Yo({tokenInstances:n,...void 0!==s?.name&&{name:s.name},uniqueKey:e.uniqueKey??oo()}),i=await this.nativeSigner.signObject("UnlockToken",r.toSigningPayload()),o=new Yo({...r.toSigningPayload(),signedPayload:i}),c=await this.http.post("/api/asset/token-contract/UnlockToken",o);try{lt(c,"Token unlock failed")}catch(e){const t=dt(c);throw new ac(`${rt(e)}${t}`,tc.NETWORK_ERROR)}return this.extractUnlockResult(c,a)},"Token unlock failed",this.logger,t=>{throw this.handleLockError(t,"Token unlock failed",e)})}validateSharedTokenEntry(e,t,n){if(void 0===e.tokenId&&void 0===e.tokenName)throw new ac("Must provide either tokenId or tokenName for token identification",tc.TOKEN_NOT_FOUND);if(void 0!==e.tokenName)try{Hn(e.tokenName,"tokenName")}catch{throw new ac("Invalid token name format",tc.TOKEN_NOT_FOUND,{tokenName:e.tokenName})}try{os(as(e.amount))}catch{throw new ac(Nt(t,"a positive number",n).message,tc.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(Zo)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}(e))throw new ac("Invalid lock data: missing required fields",tc.VALIDATION_ERROR);if(e.tokens.length>oc)throw new ac(`Batch size exceeds maximum limit of ${oc} tokens per lock operation`,tc.VALIDATION_ERROR);for(const t of e.tokens){if(this.validateSharedTokenEntry(t,"lockAmount","Lock amount"),void 0!==t.lockAuthority&&!oa(t.lockAuthority))throw new ac("Invalid lock authority address format",tc.VALIDATION_ERROR,{lockAuthority:t.lockAuthority});if(void 0!==t.expires)try{Fn(t.expires,"expires")}catch{throw new ac(Nt("expires","a positive integer (epoch milliseconds)","Expires").message,tc.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(ec)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}(e))throw new ac("Invalid unlock data: missing required fields",tc.VALIDATION_ERROR);if(e.tokens.length>cc)throw new ac(`Batch size exceeds maximum limit of ${cc} tokens per unlock operation`,tc.VALIDATION_ERROR);for(const t of e.tokens)this.validateSharedTokenEntry(t,"unlockAmount","Unlock amount")}extractLockResult(e,t){let n;if(void 0!==e.Data&&e.Data.length>0){const a=e.Data[0];if(void 0===a)return{locked:t};n=a.transactionId??a.txnId??a.TxnId??a.id??void 0}return{...void 0!==n&&{transactionId:n},locked:t}}extractUnlockResult(e,t){let n;if(void 0!==e.Data&&e.Data.length>0){const a=e.Data[0];if(void 0===a)return{unlocked:t};n=a.transactionId??a.txnId??a.TxnId??a.id??void 0}return{...void 0!==n&&{transactionId:n},unlocked:t}}handleLockError(e,t,n){if(e instanceof ac)return e;let a=t,s=tc.NETWORK_ERROR;if(ct(e)){const n=e.response?.data;if("object"==typeof n&&null!==n){const e=n.Message;"string"==typeof e&&e.length>0&&(a=`${t}: ${e}`);const r="string"==typeof e?e.toLowerCase():"";r.includes("insufficient")||r.includes("balance")?s=tc.INSUFFICIENT_BALANCE:r.includes("lock")&&r.includes("not found")?s=tc.LOCK_NOT_FOUND:r.includes("not found")||r.includes("token")?s=tc.TOKEN_NOT_FOUND:r.includes("authority")?s=tc.NOT_LOCK_AUTHORITY:r.includes("expired")&&(s=tc.LOCK_EXPIRED)}}else st(e)&&(a=`${t}: ${rt(e)}`);return new ac(a,s,rc(n))}async resolveTokenInstance(e){return Rs(async()=>ic(e,this.tokenResolver,this.logger),`Failed to resolve token '${e}'`,this.logger,t=>{if(t instanceof sc)throw new ac(rt(t),tc.TOKEN_NOT_FOUND);throw new ac(`Failed to resolve token '${e}': ${rt(t)}`,tc.TOKEN_NOT_FOUND,{tokenName:e})})}async resolveTokenEntry(e){if(void 0!==e.tokenId){const t=Gi(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 ac("Must provide either tokenId or tokenName for token identification",tc.TOKEN_NOT_FOUND)}createTokenOperationContext(){return{ownerAddress:ra(this.wallet.address),tokenInstances:[]}}}class dc extends Qn{constructor(e,t=!1,n){super(e,t),this.publicAxios=n}async fetchTokenClassFromChain(e){try{const t="string"==typeof e?Gi(e):e,n={tokenClasses:[{collection:t.collection,category:t.category,type:t.type,additionalKey:t.additionalKey}]};if(!this.publicAxios)throw Ct("publicAxios","Public Axios instance");const a=(await this.publicAxios.post("/api/asset/token-contract/FetchTokenClasses",n)).data;if(lt(a,"Failed to fetch token class from GalaChain"),null===a.Data||void 0===a.Data||0===a.Data.length)throw It(`Token not found on GalaChain: ${Ls(t)}`,404);const s=a.Data[0];if(void 0===s)throw It(`Token not found on GalaChain: ${Ls(t)}`,404);return s}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 Ct("tokenClasses","Token classes array");const t={tokenClasses:e};if(!this.publicAxios)throw Ct("publicAxios","Public Axios instance");const n=(await this.publicAxios.post("/api/asset/token-contract/FetchTokenClassesWithSupply",t)).data;if(lt(n,"Failed to fetch token classes with supply from GalaChain"),!n.Data||0===n.Data.length)throw It("No token supply data found for requested token classes",404);return n.Data}catch(e){return this.handleTokenServiceError(e,"Token supply data not found on GalaChain","Failed to fetch token classes with supply from GalaChain")}}handleTokenServiceError(e,t,n){if(e instanceof bt)throw e;if(ct(e)&&404===e.response?.status)throw It(t,404,st(e)?e:void 0);if(st(e)&&"Error"===e.name&&rt(e).includes("status indicates failure"))throw It(rt(e),400,st(e)?e:void 0);const a=rt(e);if(a.includes("Token not found")){if(e instanceof Error)throw e;throw new Error(a)}throw It(`${n}: ${a}`,void 0,st(e)?e:void 0)}}class uc extends c.ChainCallDTO{constructor(e){super(),this.tokenInstances=e.tokenInstances,this.uniqueKey=e.uniqueKey,e.signedPayload&&(this.signature=e.signedPayload.signature)}static fromTokens(e,t){const n=e.map(e=>{const t=Vo(e.tokenClassKey);return{quantity:e.quantity,tokenInstanceKey:t}});return new uc({tokenInstances:n,uniqueKey:t?.uniqueKey??oo()})}static fromTokenClassKey(e,t,n){return uc.fromTokens([{tokenClassKey:t,quantity:e}],n)}static forGALA(e,t){return new uc({tokenInstances:[{quantity:e,tokenInstanceKey:{collection:"GALA",category:"Unit",type:"none",additionalKey:"none",instance:"0"}}],uniqueKey:t?.uniqueKey??oo()})}getTokenClassKey(){if(0===this.tokenInstances.length)return;const e=this.tokenInstances[0];return void 0!==e?Xo(e.tokenInstanceKey):void 0}toSigningPayload(){return{tokenInstances:this.tokenInstances,uniqueKey:this.uniqueKey}}}class hc extends c.ChainCallDTO{constructor(e){super(),this.from=e.from,this.to=e.to,this.quantity=e.quantity,this.tokenInstance=e.tokenInstance,this.uniqueKey=e.uniqueKey,e.signedPayload&&(this.signature=e.signedPayload.signature)}static fromTokenClassKey(e,t,n,a,s){let r;if("string"==typeof a){r={...vo(a),instance:"0"}}else r={collection:a.collection,category:a.category,type:a.type,additionalKey:a.additionalKey,instance:"0"};return new hc({from:e,to:t,quantity:n,tokenInstance:r,uniqueKey:s??oo()})}static forGALA(e,t,n,a){return new hc({from:e,to:t,quantity:n,tokenInstance:{collection:"GALA",category:"Unit",type:"none",additionalKey:"none",instance:"0"},uniqueKey:a??oo()})}getTokenClassKey(){return $s(this.tokenInstance)}toSigningPayload(){return{from:this.from,to:this.to,quantity:this.quantity,tokenInstance:this.tokenInstance,uniqueKey:this.uniqueKey}}}function gc(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Pn(t.amount)&&(void 0!==t.tokenId||Pn(t.tokenName))}var mc;!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"}(mc||(mc={}));class pc extends Error{constructor(e,t,n){super(e),this.type=t,this.details=n,this.name="BurnError"}}const fc={validateAmount(e){const t=as(e);try{!function(e,t){if(e.isNaN())throw Ut(t,"NaN");if(!e.isFinite())throw Ft(t,"finite");if(e.isLessThanOrEqualTo(0))throw Ot(t,"0",e.toString())}(t,"amount")}catch(t){throw new sc(t.message,nc.INVALID_AMOUNT,{amount:e})}},validateUniqueKey(e){if(!Mn(e)&&Pn(e)){if(e.length>fn.MAX_LENGTH)throw new bt(`Unique key too long. Maximum length: ${fn.MAX_LENGTH}`);if(!fn.PATTERN.test(e))throw new sc('Invalid unique key format. Must start with "galaswap-operation-" or "galaconnect-operation-"',nc.INVALID_AMOUNT,{uniqueKey:e})}}},yc="gala-transfer-successful",vc="token-transfer-successful",kc="token-locked-successfully",bc="token-unlocked-successfully",wc="transfer-successful-no-id",Sc=50;class Ac extends Qn{constructor(e,t,n,a=!1){super(e,a),this.wallet=t,this.tokenResolver=n,this.nativeSigner=t?new mo(t.privateKey):void 0}async transferGala(e){if(this.validateTransferGalaData(e),!this.wallet||!this.nativeSigner)throw new sc("Wallet required for GALA transfer operations",nc.WALLET_REQUIRED);try{const t=ra(e.recipientAddress),n=ra(this.wallet.address),a=hc.forGALA(n,t,e.amount,e.uniqueKey),s=await this.nativeSigner.signObject("TransferToken",a.toSigningPayload()),r=new hc({...a.toSigningPayload(),signedPayload:s}),{data:i,headers:o}=await this.http.postWithMeta("/api/asset/token-contract/TransferToken",r);if(null==i)throw new sc("No response from GalaChain transfer service",nc.NETWORK_ERROR);return this.extractTransferResult(i,o,"gala")}catch(t){throw this.handleTransferError(t,"GALA transfer failed",e)}}async transferToken(e){if(this.validateTransferTokenData(e),!this.wallet||!this.nativeSigner)throw new sc("Wallet required for token transfer operations",nc.WALLET_REQUIRED);try{const t=ra(e.to),n=ra(this.wallet.address);let a;if(null!==e.tokenId&&void 0!==e.tokenId)a=Gi(e.tokenId),this.logger.debug("[DEBUG] Using provided tokenId:",e.tokenId),this.logger.debug("[DEBUG] Normalized Token Instance:",{collection:a.collection,category:a.category,type:a.type,instance:a.instance});else{if(null===e.tokenName||void 0===e.tokenName)throw new sc("Must provide either tokenId or tokenName for token identification",nc.TOKEN_NOT_FOUND);a=await this.resolveTokenInstance(e.tokenName)}const s=new hc({from:n,to:t,quantity:e.amount,tokenInstance:a,uniqueKey:e.uniqueKey??oo()}),r=await this.nativeSigner.signObject("TransferToken",s.toSigningPayload()),i=new hc({...s.toSigningPayload(),signedPayload:r}),{data:o,headers:c}=await this.http.postWithMeta("/api/asset/token-contract/TransferToken",i);if(null==o)throw new sc("No response from GalaChain transfer service",nc.NETWORK_ERROR);return this.extractTransferResult(o,c,"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 sc)throw t;throw new sc(`Failed to resolve token class key for '${e}': ${rt(t)}`,nc.TOKEN_NOT_FOUND,{tokenName:e})}}async burnTokens(e){if(this.validateBurnTokensData(e),!this.wallet||!this.nativeSigner)throw new pc("Wallet required for token burn operations",mc.WALLET_REQUIRED);try{const t=[];for(const n of e.tokens){let e;if(null!==n.tokenId&&void 0!==n.tokenId)e=Gi(n.tokenId),this.logger.debug("[DEBUG] Using provided tokenId:",n.tokenId);else{if(null===n.tokenName||void 0===n.tokenName)throw new pc("Must provide either tokenId or tokenName for token identification",mc.TOKEN_NOT_FOUND);e=await this.resolveTokenInstance(n.tokenName)}t.push({quantity:n.amount,tokenInstanceKey:e})}const n=new uc({tokenInstances:t,uniqueKey:e.uniqueKey??oo()}),a=await this.nativeSigner.signObject("BurnTokens",n.toSigningPayload()),s=new uc({...n.toSigningPayload(),signedPayload:a}),r=await this.http.post("/api/asset/token-contract/BurnTokens",s);if(null==r)throw new pc("No response from GalaChain burn service",mc.NETWORK_ERROR);try{lt(r,"Token burn operation")}catch(e){throw new wt(rt(e),500)}return this.extractBurnResult(r)}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 Pn(t.recipientAddress)&&Pn(t.amount)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)}(e))throw new bt("Invalid GALA transfer data: missing required fields");if(!oa(e.recipientAddress))throw new sc("Invalid recipient address format",nc.INVALID_RECIPIENT,{recipientAddress:e.recipientAddress});fc.validateAmount(e.amount),fc.validateUniqueKey(e.uniqueKey)}validateTransferTokenData(e){if(!function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Pn(t.to)&&Pn(t.amount)&&(void 0!==t.tokenId||Pn(t.tokenName))&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)}(e))throw new bt("Invalid token transfer data: missing required fields");if(!oa(e.to))throw new sc("Invalid recipient address format",nc.INVALID_RECIPIENT,{recipientAddress:e.to});if(!(null!==e.tokenId&&void 0!==e.tokenId||null!==e.tokenName&&void 0!==e.tokenName))throw new sc("Must provide either tokenId or tokenName for token identification",nc.TOKEN_NOT_FOUND);if(null!==e.tokenName&&void 0!==e.tokenName)try{Hn(e.tokenName,"tokenName")}catch{throw new sc("Invalid token name format",nc.TOKEN_NOT_FOUND,{tokenName:e.tokenName})}fc.validateAmount(e.amount),fc.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(gc)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}(e))throw new pc("Invalid burn data: missing required fields",mc.VALIDATION_ERROR);if(e.tokens.length>Sc)throw new pc(`Batch size exceeds maximum limit of ${Sc} tokens per burn operation`,mc.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 pc("Must provide either tokenId or tokenName for token identification",mc.TOKEN_NOT_FOUND);const e=as(t.amount);try{os(e)}catch{throw new pc("Burn amount must be a positive number",mc.INVALID_AMOUNT,{amount:t.amount})}}}async resolveTokenInstance(e){try{return await ic(e,this.tokenResolver,this.logger,`[DEBUG] Token resolution for '${e}' (launchpad):`)}catch(t){if(t instanceof sc)throw t;throw new sc(`Failed to resolve token '${e}': ${rt(t)}`,nc.TOKEN_NOT_FOUND,{tokenName:e})}}extractTransferResult(e,t,n){const a=this.readHeaderValue(t,"x-transaction-id"),s=this.readBlockNumberHeader(t),r=null!=e&&"object"==typeof e&&"Status"in e;r&<(e,"Extract transaction ID");const i=r&&"Data"in e;if(void 0!==a&&a.length>0)return{transactionId:a,...void 0!==s?{blockNumber:s}:{}};if(null!=e&&"object"==typeof e){if("transactionId"in e&&"string"==typeof e.transactionId&&e.transactionId.length>0)return{transactionId:e.transactionId,...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=wc;if(t.Data.length>0)switch(n){case"gala":e=yc;break;case"token":e=vc;break;case"lock":e=kc;break;case"unlock":e=bc}return{transactionId:e,...void 0!==s?{blockNumber:s}:{}}}}}throw new sc("Operation succeeded but transaction ID could not be extracted (missing x-transaction-id header and body fields)",nc.NETWORK_ERROR)}readHeaderValue(e,t){const n=e[t.toLowerCase()];if("string"==typeof n&&n.trim().length>0)return n.trim()}readBlockNumberHeader(e){const t=this.readHeaderValue(e,"x-block-number");if(void 0===t)return;const n=Number.parseInt(t,10);return Number.isFinite(n)?n:void 0}extractBurnResult(e){const t=[];if(null!==e.Data&&void 0!==e.Data&&Array.isArray(e.Data))for(const n of e.Data)t.push({collection:n.collection??"",category:n.category??"",type:n.type??"",additionalKey:n.additionalKey??"",instance:n.instance??"0",quantity:n.quantity??"0",burnedBy:n.burnedBy??""});let n;if(null!==e.Data&&void 0!==e.Data&&e.Data.length>0){const a=e.Data[0];if(void 0===a)return{burned:t};n=a.transactionId??a.txnId??a.TxnId??a.id??void 0}return{...void 0!==n&&{transactionId:n},burned:t}}handleTransferError(e,t,n){if(e instanceof sc)return e;if(e instanceof bt)return new sc(rt(e),nc.INVALID_AMOUNT);if(ct(e)&&e.response){const t=e.response.status,a=e.response.data;if(400===t){const e=a?.message;return new sc(("string"==typeof e?e:void 0)??"Invalid transfer request",nc.INVALID_AMOUNT)}if(403===t)return new sc("Insufficient balance for transfer",nc.INSUFFICIENT_BALANCE);if(404===t){const e={};return"tokenName"in n&&(e.tokenName=n.tokenName),new sc("Token not found",nc.TOKEN_NOT_FOUND,e)}}if("object"==typeof e&&null!==e&&"code"in e&&("ECONNABORTED"===ot(e)||"ETIMEDOUT"===ot(e)))return new sc("Transfer request timed out",nc.NETWORK_ERROR);const a=""!==rt(e)?rt(e):t;return new sc(a,nc.NETWORK_ERROR)}handleBurnError(e,t,n){if(e instanceof pc)return e;let a=t,s=mc.NETWORK_ERROR;if(ct(e)){const n=e.response?.data;if("object"==typeof n){const e=n.Message;if("string"==typeof e&&e.length>0){a=`${t}: ${e}`;const n=e.toLowerCase();n.includes("insufficient")||n.includes("balance")?s=mc.INSUFFICIENT_BALANCE:(n.includes("not found")||n.includes("token"))&&(s=mc.TOKEN_NOT_FOUND)}}}else st(e)&&(a=`${t}: ${rt(e)}`);return new pc(a,s,rc(n))}}class Ec extends Qn{constructor(e,t,n,a=!1,s){super(e,a),this.balanceService=new jo(e,a),this.tokenService=new dc(e,a,s),this.lockService=new lc(e,t,n,a),this.transferService=new Ac(e,t,n,a)}async fetchPoolDetails(e){this.validateFetchPoolDetailsData(e);const t=await this.http.post("/api/asset/launchpad-contract/FetchSaleDetails",e);xs(()=>lt(t,"Failed to fetch pool details"),"Failed to fetch pool details",this.logger,e=>{throw It(rt(e),500)});const n=t.Data.reverseBondingCurveConfiguration,a=n?.minFeePortion??"0",s=n?.maxFeePortion??"0",r=!rs(a)||!rs(s),i=t.Data;return i.reverseBondingCurveMinFeePortion=a,i.reverseBondingCurveMaxFeePortion=s,i.hasReverseBondingCurveFee=r,i.isGraduated="Finished"===t.Data.saleStatus,delete i.reverseBondingCurveConfiguration,t}async fetchLaunchTokenFee(){const e=await this.http.post("/api/asset/launchpad-contract/FetchLaunchpadFeeAmount",{});return xs(()=>lt(e,"Failed to fetch launch token fee"),"Failed to fetch launch token fee",this.logger,e=>{throw It(rt(e),500)}),e.Data.feeAmount}validateFetchPoolDetailsData(e){if(!es(e))throw Ct("data","Fetch pool details data");if("string"!=typeof e.vaultAddress||""===e.vaultAddress)throw Ct("vaultAddress","Vault address");if(!e.vaultAddress.startsWith("service|Token$Unit$"))throw new bt("Vault address must be in service format: service|Token$Unit$...","vaultAddress","INVALID_VAULT_ADDRESS")}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 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 Tc{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 Cc extends Error{constructor(e,t,n){super(t),this.name="GdexStreamError",this.code=e,void 0!==n&&(this.data=n)}}class Nc extends Jn{constructor(e={}){super(),this.nextRequestId=0,this.pending=new Map,this.subscriptionsByServerId=new Map,this.activeSubscriptions=new Set,this.intentionalClose=!1,this.reconnecting=!1,this.url=e.url??Ms("prod").gdexWebSocketUrl,this.requestTimeoutMs=e.requestTimeoutMs??15e3,this.reconnectionManager=new Tc({maxAttempts:e.reconnectAttempts??5,baseDelayMs:e.reconnectDelayMs??2e3,useExponentialBackoff:!0});const t=e.webSocketImpl??globalThis.WebSocket;if("function"!=typeof t)throw new Error('GdexStreamService requires a standards-compatible WebSocket constructor. Node.js versions before 22 must provide one with config.webSocketImpl (for example, from the "ws" package).');this.webSocketConstructor=t}connect(){return this.isConnected()?Promise.resolve():(this.connectPromise||(this.intentionalClose=!1,this.clearReconnectTimer(),this.connectPromise=this.openSocket()),this.connectPromise)}disconnect(){this.intentionalClose=!0,this.reconnecting=!1,this.clearReconnectTimer(),this.rejectPending(new Error("GDEX stream disconnected"));const e=this.socket;this.socket=void 0,this.connectPromise=void 0,e?.close(1e3,"client disconnect")}isConnected(){return 1===this.socket?.readyState}request(e,t){if(!this.isConnected()||!this.socket)return Promise.reject(new Error("GDEX stream is not connected. Call connect() first."));const n=++this.nextRequestId,a={jsonrpc:"2.0",id:n,method:e};return void 0!==t&&(a.params=t),new Promise((t,s)=>{const r=setTimeout(()=>{this.pending.delete(n),s(new Error(`GDEX request "${e}" timed out after ${this.requestTimeoutMs}ms`))},this.requestTimeoutMs);this.pending.set(n,{resolve:e=>t(e),reject:s,timeout:r});try{this.socket?.send(JSON.stringify(a))}catch(e){clearTimeout(r),this.pending.delete(n),s(e instanceof Error?e:new Error(String(e)))}})}serverInfo(){return this.request("gdex_serverInfo")}ping(){return this.request("gdex_ping")}getPool(e){return this.request("gdex_getPool",e)}getBalance(e,t){return this.request("gdex_getBalance",void 0===t?{owner:e}:{owner:e,tokenClassKey:t})}getPositions(e){return this.request("gdex_getPositions",e)}getBlockHeight(){return this.request("gdex_getBlockHeight")}quote(e){return this.request("gdex_quote",e)}getToken(e){return this.request("gdex_getToken",{tokenClassKey:e})}subscribeSwaps(e,t={}){return this.subscribe("swap",e,t)}subscribePool(e,t,n={}){return this.subscribe("pool",t,{...e,...n})}subscribeBalances(e,t,n={}){return this.subscribe("balance",t,{owner:e,...n})}subscribePoolCreated(e,t={}){return this.subscribe("poolCreated",e,t)}subscribeBlocks(e,t={}){return this.subscribe("blocks",e,t)}openSocket(){return new Promise((e,t)=>{let n=!1;const a=new this.webSocketConstructor(this.url,"gdex.jsonrpc.v1");this.socket=a,a.onopen=()=>{this.socket===a&&(n=!0,this.connectPromise=void 0,this.reconnecting||this.reconnectionManager.reset(),this.logger.info("Connected to GDEX stream"),e())},a.onmessage=e=>this.handleMessage(e.data),a.onerror=()=>{n||t(new Error(`Failed to connect to GDEX stream at ${this.url}`))},a.onclose=e=>{this.socket===a&&(this.socket=void 0,this.connectPromise=void 0,n||t(new Error(`GDEX stream closed before connecting (code ${e.code??0})`)),this.rejectPending(new Error(`GDEX stream connection closed (code ${e.code??0})`)),this.intentionalClose||this.reconnecting||this.startReconnectLoop())}})}handleMessage(e){if("string"!=typeof e)return void this.logger.warn("Ignoring non-text GDEX WebSocket frame");let t;try{t=JSON.parse(e)}catch{return void this.logger.warn("Ignoring invalid JSON from GDEX stream")}if("number"==typeof t.id){const e=this.pending.get(t.id);if(!e)return;if(clearTimeout(e.timeout),this.pending.delete(t.id),t.error){const n="number"==typeof t.error.code?t.error.code:-32603,a="string"==typeof t.error.message?t.error.message:"GDEX request failed";e.reject(new Cc(n,a,t.error.data))}else e.resolve(t.result);return}if("gdex_subscription"!==t.method||!this.isRecord(t.params))return;const n=t.params.subscription,a=t.params.result;if("string"!=typeof n||!this.isRecord(a))return;const s=this.subscriptionsByServerId.get(n);if(s?.active)try{s.callback(a)}catch(e){this.logger.error("GDEX subscription callback failed",e)}}async subscribe(e,t,n){const a={channel:e,...n},s=await this.request("gdex_subscribe",a);let r;const i={subscriptionId:s.subscriptionId,unsubscribe:async()=>this.unsubscribe(r)};return r={serverId:s.subscriptionId,params:a,callback:t,handle:i,active:!0},this.activeSubscriptions.add(r),this.subscriptionsByServerId.set(r.serverId,r),i}async unsubscribe(e){e.active&&(e.active=!1,this.activeSubscriptions.delete(e),this.subscriptionsByServerId.delete(e.serverId),this.isConnected()&&await this.request("gdex_unsubscribe",{subscriptionId:e.serverId}))}startReconnectLoop(){this.reconnecting||this.intentionalClose||(this.reconnecting=!0,this.reconnectLoop())}async reconnectLoop(){for(;!this.intentionalClose&&this.reconnectionManager.shouldRetry();){const e=this.reconnectionManager.getNextDelay();if(this.reconnectionManager.recordAttempt(),this.logger.warn(`GDEX reconnect attempt ${this.reconnectionManager.getAttempts()}/${this.reconnectionManager.getMaxAttempts()} in ${e}ms`),await this.waitForReconnectDelay(e),this.intentionalClose)break;try{return await this.openSocket(),await this.resubscribeAll(),this.reconnectionManager.reset(),void(this.reconnecting=!1)}catch(e){this.logger.warn(`GDEX reconnect failed: ${e instanceof Error?e.message:String(e)}`)}}this.reconnecting=!1,this.intentionalClose||this.logger.error("GDEX reconnection attempts exhausted")}async resubscribeAll(){this.subscriptionsByServerId.clear();for(const e of this.activeSubscriptions){if(!e.active)continue;const t={...e.params,snapshot:!0},n=await this.resubscribeWithRateLimitRetry(t);e.active?(e.serverId=n.subscriptionId,e.handle.subscriptionId=n.subscriptionId,this.subscriptionsByServerId.set(n.subscriptionId,e)):await this.request("gdex_unsubscribe",{subscriptionId:n.subscriptionId})}}async resubscribeWithRateLimitRetry(e){for(let t=0;;t++)try{return await this.request("gdex_subscribe",e)}catch(e){if(!(e instanceof Cc)||-32003!==e.code||t>=5)throw e;const n=this.readRetryAfterMs(e.data);this.logger.warn(`GDEX resubscribe rate limited; retrying in ${n}ms`),await new Promise(e=>setTimeout(e,n))}}waitForReconnectDelay(e){return new Promise(t=>{this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectDelayResolve=void 0,t()},e),this.reconnectDelayResolve=t})}clearReconnectTimer(){void 0!==this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0;const e=this.reconnectDelayResolve;this.reconnectDelayResolve=void 0,e?.()}rejectPending(e){for(const t of this.pending.values())clearTimeout(t.timeout),t.reject(e);this.pending.clear()}readRetryAfterMs(e){return!this.isRecord(e)||"number"!=typeof e.retryAfterMs||e.retryAfterMs<0?1e3:e.retryAfterMs}isRecord(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}}function Ic(e,t="image",n){const a=new FormData;if("undefined"!=typeof File&&e instanceof File)a.append(t,e);else{if(!Buffer.isBuffer(e))throw Nt("file","a File object (browser) or Buffer (Node.js)");{const s=new Blob([e],{type:"image/png"});a.append(t,s,n)}}return a}class Dc extends Qn{constructor(e,t,n=!1){super(e,n,t)}async uploadImageByTokenName(e){const{tokenName:t,options:n}=e;ms(t);const a=`${t}.png`;us(n.file,a,"image/png");try{const e=`${n.tokenName??t}.png`,a=Ic(n.file,"image",e),s=await Gt(()=>this.http.request({method:"POST",url:`${f.UPLOAD_IMAGE}?tokenName=${encodeURIComponent(n.tokenName??t)}`,data:a,headers:this.getJwtHeaders()}),{errorContext:"Image upload failed"});return"string"==typeof s?s:""}catch(e){if(e instanceof St)throw e;if(st(e)&&rt(e).includes("FormData"))throw Dt("File upload failed: FormData not supported in this environment. Ensure you have proper polyfills for Node.js environments.","FormData");throw e}}}const _c={CHAT_MESSAGE:"CHAT_MESSAGE",COMMENT:"COMMENT"};function Rc(e,t){if(null==e)return[];if(Array.isArray(e))return e;const n=e[t];return Array.isArray(n)?n:[]}class xc extends Qn{constructor(e,t,n=!1){super(e,n,t)}buildPoolFilters(e){return{...!Mn(e.search)&&{search:e.search},...!Mn(e.tokenName)&&{tokenName:e.tokenName},...!Mn(e.type)&&{type:e.type},...!Mn(e.hasUpcomingShows)&&{hasUpcomingShows:e.hasUpcomingShows},...!Mn(e.language)&&{language:e.language},...!Mn(e.recentlyStreamed)&&{recentlyStreamed:e.recentlyStreamed},...!Mn(e.hasRecordings)&&{hasRecordings:e.hasRecordings},...!Mn(e.streamStatus)&&{streamStatus:e.streamStatus}}}async fetchSinglePage(e){const t=Math.min(e.pageSize,20),n=e.cursor,a={pageSize:String(t)};void 0!==n&&(a.cursor=n),Mn(e.type)||(a.type=e.type),Mn(e.tokenName)||(a.tokenName=e.tokenName),Mn(e.search)||(a.search=e.search),Mn(e.hasUpcomingShows)||(a.hasUpcomingShows=e.hasUpcomingShows.toString()),Mn(e.language)||(a.language=e.language),Mn(e.recentlyStreamed)||(a.recentlyStreamed=e.recentlyStreamed.toString()),Mn(e.hasRecordings)||(a.hasRecordings=e.hasRecordings.toString()),Mn(e.streamStatus)||(a.streamStatus=e.streamStatus);const s=ns(a),r=$t(await Ht(()=>this.http.get(f.FETCH_POOLS,s),{errorContext:"Failed to fetch pools"})),i=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}(r),o={hasNextPage:r.hasNextPage??r.pageInfo?.hasNextPage??!1},c=r.count??r.total;void 0!==c&&(o.totalCount=c);const l=r.nextCursor??r.pageInfo?.endCursor;null!=l&&(o.nextCursor=l);const d=r.prevCursor??r.pageInfo?.startCursor;null!=d&&(o.prevCursor=d);const u=r.hasPrevPage??r.pageInfo?.hasPreviousPage;return void 0!==u&&(o.hasPrevPage=u),{items:i,pageInfo:o}}async fetchPools(e){const t=e?.cursor,n=e?.pageSize??Ei.DEFAULT_LIMIT;Pn(e?.tokenName)&&ms(e.tokenName);const a=void 0!==e?.type?{recent:"RECENT",popular:"POPULAR",recordings:"RECORDINGS",seconds_streamed:"SECONDS_STREAMED"}[e.type]:void 0,s=void 0!==e?.streamStatus?{idle:"IDLE",active:"ACTIVE",disabled:"DISABLED"}[e.streamStatus]:void 0,r={...this.buildPoolFilters({search:e?.search,tokenName:e?.tokenName,type:a,hasUpcomingShows:e?.hasUpcomingShows,language:e?.language,recentlyStreamed:e?.recentlyStreamed,hasRecordings:e?.hasRecordings,streamStatus:s}),pageSize:n,...void 0!==t&&{cursor:t}},i=await this.fetchSinglePage(r);return{items:i.items,pageInfo:i.pageInfo}}async fetchAllPools(e){const t=[];let n;const a=Ei.BACKEND_MAX_PAGE_SIZE;for(;;){const s={...e,pageSize:a,...void 0!==n&&{cursor:n}},r=await this.fetchPools(s);if(t.push(...r.items),0===r.items.length)break;if(!r.pageInfo.hasNextPage)break;n=r.pageInfo.nextCursor}return{items:t,pageInfo:{hasNextPage:!1,totalCount:t.length}}}async checkPool(e){!function(e){const t=ja(e);!t.success&&t.errors&&gs(t.errors,"options")}(e),Pn(e.tokenName)&&ms(e.tokenName);try{const t=await this.http.post(f.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===Pn(e.symbol)){return!n.symbolAvailable}if(!0===Pn(e.tokenName)){return!n.nameAvailable}return!1}catch(e){const t=String(e),n=e,a="string"==typeof n.message?n.message:"";if(t.includes("404")||t.includes("Pool not found")||a.includes("404")||a.includes("Pool not found"))return!1;const s="number"==typeof n.statusCode?n.statusCode:null;if(404===s)return!1;if(t.includes("400")||t.includes("Missing required pool identifier")||a.includes("400")||a.includes("Missing required pool identifier"))return!1;if(400===s&&a.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 Xa(t,"tokenName")&&Ja(t,"from")&&Ja(t,"to")&&Ja(t,"resolution")}(e))throw new bt("Invalid options provided. Expected { tokenName: string, from?: number, to?: number, resolution?: number }","options","INVALID_OPTIONS");const{tokenName:t,from:n,to:a,resolution:s}=e;if(ms(t),null==n||null==a||null==s)throw new bt("Graph options (from, to, resolution) are required","options","MISSING_GRAPH_OPTIONS");const r={tokenName:t,from:n,to:a,resolution:s};ps(r);const i=ns(r);return{dataPoints:await Gt(()=>this.http.get(f.CHART,i),{errorContext:"Failed to fetch graph data"})}}async fetchTokenDistribution(e){if(""===e||null==e)throw Ct("tokenName","Token name");let t;ms(e);try{t=await Ht(()=>this.http.get(`${f.GET_TOKEN_DISTRIBUTION}?tokenName=${e}`),{errorContext:"Failed to fetch token distribution"})}catch(t){if(ct(t)&&500===t.response?.status)throw It(`Token distribution data temporarily unavailable for ${e}. This is a backend issue - please try again later.`,500);throw t}return vs($t(t),t.status,e=>e.toFixed())}async fetchUserHolderContext(e,t){if(""===e||null==e)throw Ct("tokenName","Token name");if(""===t||null==t)throw Ct("userAddress","User address");return ms(e),Gt(()=>this.http.get(`${f.GET_TOKEN_DISTRIBUTION}?tokenName=${e}`,{userAddress:t}),{errorContext:"Failed to fetch user holder context"})}async resolveTokenNameToVault(e){const t=await this.fetchPools({tokenName:e});if(null!==t.items&&void 0!==t.items&&Array.isArray(t.items)&&t.items.length>0)return t.items[0]?.vaultAddress??null;if(null!==t.items&&void 0!==t.items&&"object"==typeof t.items){const e=t.items.tokens;return e?.vaultAddress??null}return null}async fetchToken(e){if(null==e||"string"!=typeof e||""===e.trim())throw new Error("Token name is required and must be a non-empty string");ms(e);try{const t=f.GET_TOKEN.replace(":tokenName",e.toLowerCase().trim()),n=$t(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 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&&ms(e.tokenName);try{const t=await this.http.post(f.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(!Pn(e))throw Ct("tokenName","Token name");ms(e);const t=f.TOKEN_STATS.replace(":tokenName",e.toLowerCase().trim());try{const e=$t(await this.http.get(t));if(!e?.stats)throw new Error("Invalid response: missing stats data");return{success:!0,data:e.stats}}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 Ct("tokenName","Token name");ms(e),function(e){if(void 0===e.messagesEnabled&&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 bt("At least one config option must be provided (messagesEnabled, commentsEnabled, streamingEnabled, nextLiveStreamAt, streamLanguage, or social URLs)","options",mt);if(void 0!==e.messagesEnabled&&"boolean"!=typeof e.messagesEnabled)throw Bt("messagesEnabled","boolean");if(void 0!==e.commentsEnabled&&"boolean"!=typeof e.commentsEnabled)throw Bt("commentsEnabled","boolean");if(void 0!==e.streamingEnabled&&"boolean"!=typeof e.streamingEnabled)throw Bt("streamingEnabled","boolean");if(void 0!==e.streamLanguage&&"string"!=typeof e.streamLanguage)throw Bt("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 Bt(n,"string or null")}if(void 0!==e.nextLiveStreamAt&&null!==e.nextLiveStreamAt){if("string"!=typeof e.nextLiveStreamAt)throw Bt("nextLiveStreamAt","string or null");const t=new Date(e.nextLiveStreamAt);if(isNaN(t.getTime()))throw new bt("nextLiveStreamAt must be a valid ISO date string","nextLiveStreamAt",yt)}}(t);const n=f.UPDATE_TOKEN_CONFIG.replace(":tokenName",e.toLowerCase().trim()),a={};void 0!==t.messagesEnabled&&(a.messagesEnabled=t.messagesEnabled),void 0!==t.commentsEnabled&&(a.commentsEnabled=t.commentsEnabled),void 0!==t.streamingEnabled&&(a.streamingEnabled=t.streamingEnabled),void 0!==t.nextLiveStreamAt&&(a.nextLiveStreamAt=t.nextLiveStreamAt),void 0!==t.streamLanguage&&(a.streamLanguage=t.streamLanguage),void 0!==t.websiteUrl&&(a.websiteUrl=t.websiteUrl),void 0!==t.telegramUrl&&(a.telegramUrl=t.telegramUrl),void 0!==t.twitterUrl&&(a.twitterUrl=t.twitterUrl),void 0!==t.instagramUrl&&(a.instagramUrl=t.instagramUrl),void 0!==t.facebookUrl&&(a.facebookUrl=t.facebookUrl),void 0!==t.redditUrl&&(a.redditUrl=t.redditUrl),void 0!==t.tiktokUrl&&(a.tiktokUrl=t.tiktokUrl),await this.http.patch(n,a,this.getJwtHeaders())}}const Oc=dn,Fc=on,Bc={MAX_LENGTH:100};function Uc(e){if(void 0!==e.tokenName){if(!Pn(e.tokenName))throw Bt("tokenName","a non-empty string",typeof e.tokenName);if(e.tokenName.length>Fc.MAX_LENGTH)throw Ft("tokenName",Fc.MAX_LENGTH,e.tokenName.length)}if(void 0!==e.userAddress){if(!Pn(e.userAddress))throw Bt("userAddress","a non-empty string",typeof e.userAddress);if(e.userAddress.length>Bc.MAX_LENGTH)throw Ft("userAddress",Bc.MAX_LENGTH,e.userAddress.length)}if(void 0!==e.search){if("string"!=typeof e.search)throw Bt("search","a string",typeof e.search);if(e.search.length>256)throw Ft("search",256,e.search.length)}if(Ln(0,void 0,Oc.MAX_LIMIT,e.pageSize),void 0!==e.txnType&&"BUY"!==e.txnType&&"SELL"!==e.txnType)throw Nt("txnType",'"BUY" or "SELL"');if(void 0!==e.startDate){if(!Pn(e.startDate))throw Bt("startDate","a non-empty string",typeof e.startDate);if(isNaN(Date.parse(e.startDate)))throw Nt("startDate","a valid ISO 8601 date")}if(void 0!==e.endDate){if(!Pn(e.endDate))throw Bt("endDate","a non-empty string",typeof e.endDate);if(isNaN(Date.parse(e.endDate)))throw Nt("endDate","a valid ISO 8601 date")}if(void 0!==e.minAmount)try{xn(e.minAmount,0,Number.MAX_SAFE_INTEGER,"minAmount")}catch{throw Nt("minAmount","a non-negative number")}if(void 0!==e.maxAmount)try{xn(e.maxAmount,0,Number.MAX_SAFE_INTEGER,"maxAmount")}catch{throw Nt("maxAmount","a non-negative number")}void 0!==e.minAmount&&void 0!==e.maxAmount&&function(e,t,n="range"){const a="number"==typeof e?e:Number(e),s="number"==typeof t?t:Number(t);if(isNaN(a)||isNaN(s))throw Bt(n,"numeric values",void 0,n);if(a>s)throw new bt(`Minimum value (${a}) must be less than or equal to maximum value (${s}) for ${n}`,n,kt)}(e.minAmount,e.maxAmount,"amountRange")}class Pc extends Qn{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 Xa(t,"tokenName")&&(void 0===t.tradeType||"buy"===t.tradeType||"sell"===t.tradeType)&&Qa(t,"userAddress")&&Ja(t,"offset")&&Ja(t,"pageSize")&&Ja(t,"page")&&Ja(t,"limit")}(e))throw new bt("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:a=Ei.DEFAULT_LIMIT}=e;if(!Pn(t))throw Ct("tokenName","Token name");const s={pageSize:String(Math.min(a,ln))};void 0!==n&&(s.cursor=n);const r={...s};r.tokenName=t;const i=await this.http.get(f.GET_TRADES,r);if(null==i)throw new bt("No response from trade service","response","NO_RESPONSE");const o=$t(i),c=Rc(o,"trades"),l=o?.pageInfo;return{items:c,pageInfo:l??{hasNextPage:!1}}}buildTradesQueryParams(e){const t={};null!==e.tokenName&&void 0!==e.tokenName&&e.tokenName.length>0&&(t.tokenName=jt(e.tokenName)),null!==e.userAddress&&void 0!==e.userAddress&&e.userAddress.length>0&&(t.userAddress=e.userAddress),null!==e.search&&void 0!==e.search&&e.search.length>0&&(t.search=e.search);const n=void 0!==e.pageSize?function(e,t=1,n=Ei.BACKEND_MAX_PAGE_SIZE){return Math.max(t,Math.min(n,Math.ceil(e??t)))}(e.pageSize,1,Oc.MAX_LIMIT):Oc.MAX_LIMIT;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){Uc(e);const t=this.buildTradesQueryParams(e);return Gt(()=>this.http.get(Ue,t),{errorContext:"Failed to fetch trades"})}}function Mc(e){return!!Pn(e)&&un.PATTERN.test(e)}function Lc(e,t,n=1){if(null==e||""===e)return null;if("string"!=typeof e)return null;const a=e.trim();return a.length<n?null:a}$n({ALL:"all",DEFI:"DEFI",ASSET:"ASSET",COLLECTION:"COLLECTION",CREATED:"created"});class $c extends Qn{constructor(e,t,n=!1){super(e,n,t)}async fetchProfile(e){const t=e??this.http.getAddress();if(""===t||null==t||!Mc(t))throw Nt("address","eth|[40-hex-chars] or client|[identifier]","Address");const n=null==e,a=n?f.GET_CURRENT_USER:f.GET_PROFILE.replace(":address",t),s=await this.http.get(a,void 0,n?this.getJwtHeaders():void 0);if(null==s)throw new bt("No response from user service","response","NO_RESPONSE");return s}async updateProfile(e){this.validateUpdateProfileData(e);let t=e.profileImage;if(!Pn(t))try{const n=await this.fetchProfile(e.address);t=n.data?.profileImage??""}catch{t=""}const n={profileImage:t,fullName:e.fullName};await Gt(()=>this.http.put(f.UPDATE_PROFILE,n,this.getJwtHeaders()),{errorContext:"Profile update failed"})}async uploadProfileImage(e){this.validateUploadProfileImageOptions(e);const t=e.address??this.http.getAddress();if(null==t||""===t)throw new bt("Wallet address not available - wallet not configured","address","NO_WALLET");try{const n=`profile-image-${t}.png`,a=Ic(e.file,"image",n),s=await Gt(()=>this.http.request({method:"POST",url:`${f.UPLOAD_IMAGE}?tokenName=${encodeURIComponent(t)}`,data:a,headers:this.getJwtHeaders()}),{errorContext:"Image upload failed"});return"string"==typeof s?s:""}catch(e){if(e instanceof bt||e instanceof St)throw e;throw new bt(`Profile image upload failed: ${rt(e)}`,"file","UPLOAD_FAILED")}}async fetchTokenList(e){return this.buildFetchRequest(f.GET_TOKEN_LIST,e,{includeType:!0,errorMessage:"Failed to fetch token list"})}async fetchTokensHeld(e){return this.buildFetchRequest(f.GET_TOKENS_HELD,e,{includeType:!1,errorMessage:"Failed to fetch tokens held"})}async fetchTokensCreated(e){const{cursor:t,pageSize:n,search:a,tokenName:s,status:r}=e??{},i=e?.type??(void 0!==r?"created":"DEFI"),o=this.http.getAddress();if(null==o||""===o)throw new bt("Wallet address not available - wallet not configured","address","NO_WALLET");const c={type:i,address:o,pageSize:n??Ei.DEFAULT_LIMIT};return void 0!==t&&(c.cursor=t),void 0!==a&&(c.search=a),void 0!==s&&(c.tokenName=s),void 0!==r&&(c.status=r),this.fetchTokenList(c)}async getManagedTokens(e={}){const t=Ni({pageSize:e.pageSize??Ei.DEFAULT_LIMIT,...void 0!==e.cursor&&{cursor:e.cursor}},ln);return Gt(()=>this.http.get(f.GET_MANAGED_TOKENS,t,this.getJwtHeaders()),{errorContext:"Failed to fetch managed tokens"})}async buildFetchRequest(e,t,n){this.validateGetTokenListOptions(t);const a=Ni({pageSize:t.pageSize??Ei.DEFAULT_LIMIT,...void 0!==t.cursor&&{cursor:t.cursor}},ln);Ii(a,t,["address","search","tokenName","status"]),n.includeType&&!e.includes("?type=")&&(a.type="all"===(t.type??"DEFI")?"DEFI":t.type??"DEFI");let s=e;if(e.includes(":address")){const n=t.address??this.http.getAddress();if(0===n.length)throw Ct("address","User address");s=e.replace(":address",n),delete a.address}const r=$t(await Ht(()=>this.http.get(s,a),{errorContext:n.errorMessage})),i=Rc(r,"token"),o={hasNextPage:r.hasNextPage??!1},c=r.count??r.total;void 0!==c&&(o.totalCount=c),void 0!==r.nextCursor&&(o.nextCursor=r.nextCursor),void 0!==r.prevCursor&&(o.prevCursor=r.prevCursor),void 0!==r.hasPrevPage&&(o.hasPrevPage=r.hasPrevPage);const l={tokens:i,pageInfo:o};return void 0!==c&&(l.total=c),l}validateGetTokenListOptions(e){const t=e.pageSize??Ei.DEFAULT_LIMIT;if(t<1||t>ln)throw new bt(`pageSize must be between 1 and ${ln}`,"pageSize","OUT_OF_RANGE");if(void 0!==e.address&&!Mc(e.address))throw Nt("address","eth|[40-hex-chars] or client|[identifier]","Address");const n=Lc(e.search);if(null!==n&&!(Pn(a=n)&&a.length>=bn&&a.length<=wn))throw xt("search",bn,wn,n.length,"Search query");var a;const s=Lc(e.tokenName);if(null!==s&&!(Pn(r=s)&&r.length>=on.MIN_LENGTH&&r.length<=on.MAX_LENGTH))throw xt("tokenName",on.MIN_LENGTH,on.MAX_LENGTH,s.length,"Token name");var r}validateUpdateProfileData(e){if(!Mc(e.address))throw Nt("address","eth|[40-hex-chars] or client|[identifier]","Address");if(t=e.fullName,!(Pn(t)&&t.length>=Sn.FULL_NAME.MIN_LENGTH&&t.length<=Sn.FULL_NAME.MAX_LENGTH&&Sn.FULL_NAME.ALPHABETS_ONLY_PATTERN.test(t)))throw xt("fullName",Sn.FULL_NAME.MIN_LENGTH,Sn.FULL_NAME.MAX_LENGTH,e.fullName.length,"Full name");var t}validateUploadProfileImageOptions(e){if(void 0!==e.address&&!Mc(e.address))throw Nt("address","eth|[40-hex-chars] or client|[identifier]","Address")}}class Kc{constructor(e,t,n=!1){this.http=e,this.poolService=new xc(e,t,n),this.tradeService=new Pc(e,n),this.userService=new $c(e,t,n),this.imageService=new Dc(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 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)}getAddress(){return this.http.getAddress()}validateTokenName(e){return ms(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)}}class Gc extends _i{constructor(e,t,n,a=!1,s){super(e,t,n,a,s)}validateContent(e,t){if(!Pn(e))throw Ct("content","Message content");if(0===e.trim().length)throw Ct("content","Message content");On(e,t===_c.CHAT_MESSAGE?hn.CHAT_MESSAGES_V1.MAX_LENGTH:hn.COMMENTS_V1.MAX_LENGTH,"content")}validateMessageId(e){if(!Pn(e))throw Ct("id","Message ID");if(e.length<10||e.length>64)throw Nt("id","valid message ID format","Message ID")}validateMessageType(e){if(e!==_c.CHAT_MESSAGE&&e!==_c.COMMENT)throw new bt(`type must be one of: ${Object.values(_c).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,rn);const a={};void 0!==e.cursor&&(a.cursor=e.cursor),a.pageSize=e.pageSize??Ei.DEFAULT_LIMIT;const s=Ni(a,dn.MAX_LIMIT),r={};void 0!==s.pageSize&&(r.pageSize=s.pageSize),void 0!==s.cursor&&(r.cursor=s.cursor),t&&(r.type=e.type.toUpperCase()),n&&(r.tokenName=jt(e.tokenName)),void 0!==e.userAddress&&""!==e.userAddress&&(r.userAddress=e.userAddress),void 0!==e.search&&""!==e.search&&(r.search=e.search);const i=await this.http.get(Pe.GET_MESSAGES,r),o=this.extractData(i);return{messages:o.messages,pageInfo:o.pageInfo}}async createMessage(e){this.validateMessageType(e.type),this.validateTokenName(e.tokenName,rn),this.validateContent(e.content,e.type);const t={type:e.type,tokenName:jt(e.tokenName),content:e.content.trim()},n=await this.http.post(Pe.CREATE_MESSAGE,t,this.getJwtHeaders());return{message:this.extractData(n)}}async updateMessage(e,t){this.validateMessageId(e),this.validateContent(t.content);const n=this.buildEndpointWithId(Pe.UPDATE_MESSAGE,e),a={content:t.content.trim()},s=await this.http.put(n,a,this.getJwtHeaders());return{message:this.extractData(s)}}async deleteMessage(e){this.validateMessageId(e);const t=this.buildEndpointWithId(Pe.DELETE_MESSAGE,e);return await this.http.delete(t,void 0,this.getDualAuthHeaders()),{success:!0}}async getPinnedMessage(e){this.validateTokenName(e,rn);const t=await this.http.get(Pe.GET_PINNED,{tokenName:jt(e)});return{message:this.extractData(t)}}async pinMessage(e){this.validateMessageId(e);const t=Pe.PIN_MESSAGE.replace(":id",e);return await this.http.post(t,{},this.getDualAuthHeaders()),{success:!0}}async unpinMessage(e){this.validateMessageId(e);const t=Pe.UNPIN_MESSAGE.replace(":id",e);return await this.http.delete(t,void 0,this.getDualAuthHeaders()),{success:!0}}async getMessageStats(){const e=await this.http.get(Pe.GET_MESSAGE_STATS,void 0,this.getDualAuthHeaders());return this.extractData(e)}}const Wc=Kn({MODERATOR:"MODERATOR",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MANAGER:"MANAGER"}),Hc={TOKEN:"TOKEN",ALL_OWNER_TOKENS:"ALL_OWNER_TOKENS"},qc=Kn(Hc),zc={PENDING:"PENDING",CLAIMED:"CLAIMED",REVOKED:"REVOKED",EXPIRED:"EXPIRED"};Kn(zc);class jc extends _i{constructor(e,t,n,a=!1,s){super(e,t,n,a,s)}validateRole(e){if(!Pn(e))throw Ct("role","Role");if(!function(e){return Wc.includes(e)}(e))throw Nt("role",`one of: ${Wc.join(", ")}`,"Role")}validateInviteCodeFormat(e){if(!Pn(e))throw Ct("inviteCode","Invite code");if(t=e,!yn.PATTERN.test(t))throw Nt("inviteCode","valid invite code format","Invite code");var t}validateInviteScope(e){if(void 0!==e&&(t=e,!qc.includes(t)))throw new bt(`Invalid invite scope. Must be one of: ${qc.join(", ")}`,"inviteScope","INVALID_VALUE");var t}async createInvite(e){this.validateInviteScope(e.inviteScope);const t=e.inviteScope??Hc.TOKEN;if(t===Hc.TOKEN){if(void 0===e.tokenName||""===e.tokenName)throw new bt("Token name is required for TOKEN scope invites","tokenName","REQUIRED");this.validateTokenName(e.tokenName,sn)}else if(t===Hc.ALL_OWNER_TOKENS&&e.tokenName)throw new bt("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",hn.DESCRIPTION.MAX_LENGTH),this.validateOptionalDate(e.expiresAt,"expiresAt","Expiration date");const n=Z,a={inviteScope:t,role:e.role};t===Hc.TOKEN&&null!==e.tokenName&&void 0!==e.tokenName&&""!==e.tokenName&&(a.tokenName=jt(e.tokenName)),void 0!==e.description&&(a.description=e.description),void 0!==e.expiresAt&&(a.expiresAt=e.expiresAt);const s=await this.http.post(n,a,this.getMultiAuthHeaders());return{invite:this.extractData(s)}}async listInvites(e){void 0!==e.tokenName&&""!==e.tokenName&&this.validateTokenName(e.tokenName,sn),this.validateStatusFilter(e.status,zc);const t=ne,n={...this.buildPaginationParams(e,dn.MAX_LIMIT)};void 0!==e.tokenName&&""!==e.tokenName&&(n.tokenName=jt(e.tokenName)),void 0!==e.status&&(n.status=e.status);const a=await this.http.get(t,n,this.getMultiAuthHeaders()),s=this.extractData(a);return{items:s.invites,pageInfo:s.pageInfo}}async revokeInvite(e){this.validatePositiveInteger(e,"inviteId","Invite ID");const t=this.buildEndpoint(ae,{id:String(e)});Lt(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(se,{id:String(e.inviteId)}),n={role:e.role},a=await this.http.patch(t,n,this.getMultiAuthHeaders());return{invite:this.extractData(a)}}async updateInvite(e){if(this.validatePositiveInteger(e.inviteId,"inviteId","Invite ID"),void 0===e.role&&(void 0===e.description||""===e.description))throw new bt("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",hn.DESCRIPTION.MAX_LENGTH);const t=this.buildEndpoint(re,{id:String(e.inviteId)}),n={};void 0!==e.role&&(n.role=e.role),void 0!==e.description&&(n.description=e.description);const a=await this.http.patch(t,n,this.getMultiAuthHeaders());return{invite:this.extractData(a)}}async claimInvite(e){this.validateInviteCodeFormat(e.inviteCode);const t=ee,n={inviteCode:e.inviteCode},a=await this.http.post(t,n,this.getMultiAuthHeaders()),s=this.extractData(a);return"tokenName"in s&&void 0!==s.tokenName?{token:s}:{blanketAccess:s}}async getModeratedTokens(e){const t=te,n=this.buildPaginationParams(e??{},dn.MAX_LIMIT),a=await this.http.get(t,n,this.getMultiAuthHeaders()),s=this.extractData(a);return{items:s.tokens,pageInfo:s.pageInfo}}async getInviteByCode(e){this.validateInviteCodeFormat(e);const t=this.buildEndpoint(ie,{code:e}),n=await this.http.get(t,{});return this.extractData(n)}}const Vc="10000",Xc="1000";function Qc(e){return`${e}-${Date.now()}-${Math.random().toString(36).substring(2,11)}`}function Jc(){return Date.now()+6e4}function Yc(e){return""!==e&&"string"==typeof e&&/^[a-zA-Z0-9]{3,50}$/.test(e)}function Zc(e){try{return Math.floor(parseFloat(String(e))??0).toString()}catch{return"0"}}function el(e){return""!==e&&"string"==typeof e&&/^eth\|[0-9a-fA-F]{40}$/.test(e)}class tl extends Qn{constructor(e){super(e)}getCollectionClaimFee(){return Vc}getTokenClassCreateFee(){return Xc}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(!el(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=Vc;n.collectionClaim=e,t=String(BigInt(t)+BigInt(e))}if((e.createTokenClasses??0)>0){const a=Xc,s=String(BigInt(a)*BigInt(e.createTokenClasses));n.tokenClassCreate=a,n.tokenClassCount=e.createTokenClasses,t=String(BigInt(t)+BigInt(s))}return{totalFee:t,breakdown:n}}async claimCollection(e){try{if(this.logger.debug("Claiming NFT collection",e.collectionName),!Yc(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:Jc(),uniqueKey:Qc("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),!el(e))throw new Error(`Invalid wallet address format: ${e}`);const t=[];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),!Yc(e))throw new Error(`Invalid collection name format: ${e}`);const t=!0;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(!Yc(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?Zc(e.maxSupply):void 0,maxCapacity:void 0!==e.maxCapacity?Zc(e.maxCapacity):void 0,additionalKey:e.additionalKey,expiresAt:Jc(),uniqueKey:Qc("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),!Yc(e.collection))throw new Error(`Invalid collection name: ${e.collection}`);const t=[];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(!el(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 a={collection:e.collection,type:e.type,category:e.category,quantity:e.quantity,owner:e.ownerAddress,additionalKey:e.additionalKey??"none",expiresAt:Jc(),uniqueKey:Qc("mint")};this.logger.debug("Built mint DTO",a);const s=`mint-${Date.now()}`,r=Array.from({length:t},(e,t)=>t+1);return{transactionId:s,mintedQuantity:e.quantity,owner:e.ownerAddress,tokenInstances:r,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}),!el(e))throw new Error(`Invalid owner address: ${e}`);const n=[];return this.logger.debug(`Found ${n.length} NFT balances`),n}catch(e){throw this.logger.error("Failed to fetch NFT balances",e),e}}}class nl extends Qn{constructor(e,t=!1,n){super(e,t,n)}extractData(e){if(e.error||void 0===e.data){const t=e.message??"Notification operation failed";throw new Error(t)}return e.data}async registerPushToken(e){this.logger.debug("Registering push token",{platform:e.platform});const t=this.getJwtHeaders(),n=await this.http.post(Je,{token:e.token,platform:e.platform,...void 0!==e.deviceId?{deviceId:e.deviceId}:{}},t),a=this.extractData(n);return this.logger.debug("Push token registered",{registered:a.registered}),a}async unregisterPushToken(e){this.logger.debug("Unregistering push token");const t=this.getJwtHeaders(),n=await this.http.request({method:"DELETE",url:Ye,data:{token:e},headers:t}),a=this.extractData(n);return this.logger.debug("Push token unregistered",{unregistered:a.unregistered}),a}async getPreferences(){this.logger.debug("Fetching notification preferences");const e=this.getJwtHeaders(),t=await this.http.get(Ze,void 0,e),n=this.extractData(t);return this.logger.debug("Fetched notification preferences",{tradesEnabled:n.tradesEnabled,streamsEnabled:n.streamsEnabled}),{preferences:n}}async updatePreferences(e){this.logger.debug("Updating notification preferences",e);const t=this.getJwtHeaders(),n=await this.http.put(et,e,t),a=this.extractData(n);return this.logger.debug("Updated notification preferences",{tradesEnabled:a.tradesEnabled,streamsEnabled:a.streamsEnabled}),{preferences:a}}}class al extends Qn{constructor(e,t=!1){super(e,t)}async getHomeOEmbedJson(e={}){this.logger.debug("Fetching home oEmbed (JSON)");const t=await this.http.get(f.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(f.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 bt("tokenName is required","tokenName","REQUIRED_FIELD");this.logger.debug("Fetching pool oEmbed (JSON)",{tokenName:t});const n=f.OEMBED_BUY_SELL.replace(":tokenName",t.toLowerCase().trim()),a=await this.http.get(n,{format:"json"});return this.logger.debug("Fetched pool oEmbed (JSON)",{tokenName:t,title:a.title}),{oembed:a}}async getPoolOEmbedHtml(e){const{tokenName:t}=e;if(null==t||"string"!=typeof t||""===t.trim())throw new bt("tokenName is required","tokenName","REQUIRED_FIELD");this.logger.debug("Fetching pool oEmbed (HTML)",{tokenName:t});const n=f.OEMBED_BUY_SELL.replace(":tokenName",t.toLowerCase().trim()),a=await this.http.get(n,{},{responseType:"text"});return this.logger.debug("Fetched pool oEmbed (HTML)",{tokenName:t}),{html:a}}async getProfileOEmbedJson(e){const{address:t}=e;if(null==t||"string"!=typeof t||""===t.trim())throw new bt("address is required","address","REQUIRED_FIELD");this.logger.debug("Fetching profile oEmbed (JSON)",{address:t});const n=f.OEMBED_PROFILE.replace(":address",encodeURIComponent(t.toLowerCase().trim())),a=await this.http.get(n,{format:"json"});return this.logger.debug("Fetched profile oEmbed (JSON)",{address:t,title:a.title}),{oembed:a}}async getProfileOEmbedHtml(e){const{address:t}=e;if(null==t||"string"!=typeof t||""===t.trim())throw new bt("address is required","address","REQUIRED_FIELD");this.logger.debug("Fetching profile oEmbed (HTML)",{address:t});const n=f.OEMBED_PROFILE.replace(":address",encodeURIComponent(t.toLowerCase().trim())),a=await this.http.get(n,{},{responseType:"text"});return this.logger.debug("Fetched profile oEmbed (HTML)",{address:t}),{html:a}}}function sl(e){if(!Pn(e))throw Ct("address","Address")}const rl={PENDING:"PENDING",CLAIMED:"CLAIMED",REVOKED:"REVOKED",EXPIRED:"EXPIRED"},il={ACTIVE:"ACTIVE",REVOKED:"REVOKED"},ol=$n(rl),cl=$n(il);function ll(e){if(!Pn(e))throw new Error("Address must be a non-empty string");try{ca(e,"address")}catch{throw new Error("Invalid wallet address format. Must be eth|..., 0x..., or client|... format")}}function dl(e){try{Fn(e,"id")}catch(e){if(e instanceof bt)throw new Error("Invite ID must be a positive integer");throw e}}class ul extends _i{constructor(e,t,n,a=!1,s){super(e,t,n,a,s)}validateInviteCodeFormat(e){if(!Pn(e))throw Ct("inviteCode","Invite code");!function(e){if(!Pn(e))throw new Error("Invite code must be a non-empty string");On(e,100,"code")}(e)}validateWalletAddressFormat(e){if(!Pn(e))throw Ct("address","Address");ll(e)}async createInvite(e={}){!function(e){try{zn(e.description,"description",255)}catch(e){if(e instanceof bt)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(!Pn(e.expiresAt))throw new Error("expiresAt must be a non-empty string");try{jn(e.expiresAt,"expiresAt")}catch(e){if(e instanceof bt)throw new Error("expiresAt must be a valid ISO 8601 date string");throw e}if(nn(e.expiresAt)&&tn(e.expiresAt)<=new Date)throw new Error("expiresAt must be in the future")}}(e),this.validateOptionalString(e.description,"description","Description",hn.DESCRIPTION.MAX_LENGTH),this.validateOptionalDate(e.expiresAt,"expiresAt","Expiration date");const t=ce,n={};void 0!==e.description&&(n.description=e.description),void 0!==e.expiresAt&&(n.expiresAt=e.expiresAt);const a=await this.http.post(t,n,this.getDualAuthHeaders());return{invite:this.extractData(a)}}async listInvites(e={}){!function(e){if(void 0!==e.status&&!ol(e.status))throw Pt("status",e.status,Object.values(rl),"status");Ln(0,void 0,50,e.pageSize,e.cursor)}(e),this.validateStatusFilter(e.status,rl);const t=le,n={...this.buildPaginationParams(e,dn.MAX_LIMIT)};void 0!==e.status&&(n.status=e.status);const a=await this.http.get(t,n,this.getDualAuthHeaders()),s=this.extractData(a);return{items:s.invites,pageInfo:s.pageInfo}}async getInviteByCode(e){this.validateInviteCodeFormat(e);const t=this.buildEndpoint(de,{code:e}),n=await this.http.get(t,{});return this.extractData(n)}async revokeInvite(e){dl(e);const t=this.buildEndpoint(he,{id:String(e)});Lt(await this.http.delete(t,this.getDualAuthHeaders()),"Failed to revoke invite")}async claimInvite(e){this.validateInviteCodeFormat(e);const t=ue,n={inviteCode:e},a=await this.http.post(t,n,this.getJwtHeaders());return{invite:this.extractData(a)}}async listOverseers(e={}){!function(e){if(void 0!==e.status&&!cl(e.status))throw Pt("status",e.status,Object.values(il),"status");Ln(0,void 0,50,e.pageSize,e.cursor)}(e),this.validateStatusFilter(e.status,il);const t=ge,n={...this.buildPaginationParams(e,dn.MAX_LIMIT)};void 0!==e.status&&(n.status=e.status);const a=await this.http.get(t,n,this.getDualAuthHeaders()),s=this.extractData(a);return{items:s.overseers,pageInfo:s.pageInfo}}async createOverseerDirect(e){!function(e){if(null==e||"object"!=typeof e)throw new bt("Options are required");if(!Pn(e.userAddress))throw new bt("userAddress is required and must be a non-empty string");try{ca(e.userAddress,"userAddress")}catch{throw new bt("Invalid wallet address format. Must be eth|..., 0x..., or client|... format")}if(void 0!==e.description){if("string"!=typeof e.description)throw new bt("description must be a string");if(e.description.length>255)throw new bt("description must be at most 255 characters")}}(e),this.validateWalletAddressFormat(e.userAddress),this.validateOptionalString(e.description,"description","Description",hn.DESCRIPTION.MAX_LENGTH);const t=me,n={userAddress:e.userAddress};void 0!==e.description&&(n.description=e.description);const a=await this.http.post(t,n,this.getDualAuthHeaders());return{overseer:this.extractData(a)}}async revokeOverseer(e){this.validateWalletAddressFormat(e);const t=this.buildEndpoint(pe,{address:e});Lt(await this.http.delete(t,this.getDualAuthHeaders()),"Failed to revoke overseer")}async getMyStatus(){const e=fe,t=await this.http.get(e,{},this.getJwtHeaders());return this.extractData(t)}async getSummary(){const e=ye,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getBanStats(){const e=ve,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getTokenBanStats(){const e=ke,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getInviteStats(){const e=be,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getFlagStats(){const e=we,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getUserStats(){const e=Se,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 bt("Options are required");if(void 0!==e.search){if("string"!=typeof e.search)throw new bt("Search must be a string");if(0===e.search.length)throw new bt("Search query cannot be empty string")}if(void 0!==e.sortBy){if("string"!=typeof e.sortBy)throw new bt("Sort field must be a string");if(0===e.sortBy.length)throw new bt("Sort field cannot be empty string")}if(void 0!==e.sortOrder&&"asc"!==e.sortOrder&&"desc"!==e.sortOrder)throw new bt('Sort order must be "asc" or "desc"')}(t);const n=Ae,a=this.buildPaginationParams(t,dn.MAX_LIMIT);void 0!==t.search&&""!==t.search&&(a.search=t.search),void 0!==t.sortBy&&""!==t.sortBy&&(a.sortBy=t.sortBy),void 0!==t.sortOrder&&(a.sortOrder=t.sortOrder);const s=await this.http.get(n,a,this.getDualAuthHeaders()),r=this.extractData(s);return{items:r.users,pageInfo:r.pageInfo}}async getOverseerUserSummary(e){if(!Pn(e))throw Ct("address","User address");ll(e);const t=this.buildEndpoint(Ee,{address:e}),n=await this.http.get(t,{},this.getDualAuthHeaders());return this.extractData(n)}async flushCacheByAddress(e){sl(e);const t=this.buildEndpoint(Te,{address:e}),n=await this.http.delete(t,void 0,this.getDualAuthHeaders());return this.extractData(n)}async flushCacheByToken(e){!function(e){if(!Pn(e))throw Ct("tokenName","Token name")}(e);const t=this.buildEndpoint(Ce,{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 bt("Safety confirmation required: must pass confirm=true to flush all cache","confirm","CONFIRMATION_REQUIRED")}(e);const t=Ne,n=await this.http.delete(t,{confirm:"true"},this.getDualAuthHeaders());return this.extractData(n)}async flushWalletAliasCache(e){if(void 0!==e){sl(e);const t=this.buildEndpoint(Ie,{address:e}),n=await this.http.delete(t,void 0,this.getDualAuthHeaders());return this.extractData(n)}const t=De,n=await this.http.delete(t,{confirm:"true"},this.getDualAuthHeaders());return this.extractData(n)}}class hl extends Qn{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),Lt(t,"Platform config operation failed",!0),e.data}async getPlatformConfig(){const e=await this.http.get(x);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 bt(t.join("; "),"options","VALIDATION_FAILED");const n=await this.http.put(O,e,this.getJwtHeaders());return this.extractData(n)}async getAvailableRoles(){const e=await this.http.get(U);return this.extractData(e)}}class gl extends Qn{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(qe),t=this.extractData(e);return this.logger.debug("Fetched platform stats",{totalTokens:t.totalTokens,timestamp:t.timestamp}),{stats:t}}}class ml extends Qn{constructor(e,t=!1,n){super(e,t),this.tokenResolverService=n}async fetchTokenClassKeyByTokenName(e){if(""===e)throw Ct("tokenName","Token name");if(!this.tokenResolverService)throw Dt("TokenResolverService is required for token name resolution. Ensure it is passed to PriceHistoryService constructor.","tokenResolverService");try{Wn(e)}catch(e){throw Dt(rt(e),"tokenName")}this.logger.debug(`Resolving token name '${e}' to token class key`);try{const t=await this.tokenResolverService.resolveTokenToVault(e);if(null==t)throw Dt(`Token '${e}' not found or could not be resolved to vault address`,"tokenName");this.logger.debug(`Resolved '${e}' to vault address: ${t}`);const n=Ls(Wi(t));return this.logger.debug(`Extracted token class key: ${n}`),n}catch(t){if(st(t)&&rt(t).includes("ConfigurationError"))throw t;throw It(`Failed to resolve token name '${e}': ${rt(t)}`,500)}}async fetchPriceHistory(e){if(null==e)throw Ct("options","Fetch options");return this.logger.debug("Fetching price history from DEX Backend API with options:",e),this.validateOptions(e),await Rs(async()=>{let t=e.tokenId;if(null!==e.tokenName&&void 0!==e.tokenName){this.logger.debug(`Resolving token name '${e.tokenName}' to token ID`);const n=await this.fetchTokenClassKeyByTokenName(e.tokenName);t=n,this.logger.debug(`Resolved to token ID: ${n}`)}if(null==t)throw Dt("Token ID is required but was not provided or resolved","tokenId");const{normalizeToTokenInstanceKey:n}=await Promise.resolve().then(function(){return ji}),a=yo(Ls(n(t))),{from:s,to:r,sortOrder:i="DESC"}=e,o=e.timeframe??this.inferTimeframe(s,r),c={token:a,timeframe:o};this.logger.debug(`Querying price series for token ${a}, timeframe ${o}`);const l=await this.http.get(b,c);if(null==l)throw It("No response from price history service",500);const d=this.transformApiResponseToPriceHistory(l,e,i);return this.logger.debug(`Found ${d.snapshots.length} price snapshots, total ${d.total}`),d},"Failed to fetch price history",this.logger)}transformApiResponseToPriceHistory(e,t,n){if(!Array.isArray(e.prices))throw It("Invalid API response: missing price series",500);const a="string"==typeof t.tokenId?t.tokenId:t.tokenName??Ls(t.tokenId),s=t.from?.getTime(),r=t.to?.getTime(),i=e.prices.filter(e=>"number"==typeof e.time&&"number"==typeof e.price).filter(e=>(void 0===s||1e3*e.time>=s)&&(void 0===r||1e3*e.time<=r)).sort((e,t)=>"ASC"===n?e.time-t.time:t.time-e.time),o=Tn(t.offset,0),c=Tn(t.pageSize??t.limit,10),l=i.slice(o,o+c).map(e=>({price:String(e.price),timestamp:new Date(1e3*e.time),tokenId:a})),d=Math.max(1,Math.ceil(i.length/c)),u=Math.floor(o/c)+1;return{snapshots:l,page:u,limit:c,total:i.length,totalPages:d,hasNext:u<d,hasPrevious:u>1}}async fetchAllPriceHistory(e){if(null==e)throw Ct("options","Fetch options");return this.logger.debug("Fetching all price history with options:",e),Rs(async()=>{const t=await Ki((t,n)=>this.fetchPriceHistory({...e,offset:t,limit:n}).then(e=>({items:e.snapshots,page:e.page,limit:e.limit,total:e.total,totalPages:e.totalPages,hasNext:e.hasNext,hasPrevious:e.hasPrevious})),{maxPages:1e4,logger:this.logger,pageSize:50,startPage:0});return function(e,t=e.length,n="items"){const a=e.length;return{offset:0,limit:a,total:t,totalPages:0!==a?Ti(t,a):void 0,hasNext:!1,hasPrevious:!1,[n]:e}}(t.items,t.total,"snapshots")},"Failed to fetch all price history",this.logger)}validateOptions(e){const{from:t,to:n,sortOrder:a}=e;if(Gn(e,"tokenName","tokenId",{description:"token identifier"}),t&&!nn(t))throw Dt("from must be a valid Date","from");if(void 0!==n&&!nn(n))throw Dt("to must be a valid Date","to");null!=a&&function(e,t){if("ASC"!==e&&"DESC"!==e)throw new bt(`${t} must be either 'ASC' or 'DESC'`,t,"INVALID_ENUM_VALUE")}(a,"sortOrder"),Ln(0,void 0,50,e.pageSize)}inferTimeframe(e,t){if(void 0===e||void 0===t)return"1M";const n=Math.max(0,t.getTime()-e.getTime())/864e5;return n<=1?"1D":n<=7?"1W":n<=31?"1M":n<=365?"1Y":"ALL"}}class pl extends _i{constructor(e,t,n,a){super(e,t,n,!1,a)}async getRestrictedNames(){try{return{success:!0,data:(await this.http.get(Me)).data}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}async updateRestrictedNames(e){try{if(!Pn(e.content))throw new bt("Content is required");return{success:!0,data:(await this.http.put(Le,e)).data}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}}class fl extends _i{constructor(e,t,n,a=!1,s){super(e,t,n,a,s)}async getChatStatus(e){if(null==e||""===e)throw Ct("tokenName","Token name");return this.validateTokenName(e,sn),Rs(async()=>{const t=this.buildEndpoint($e,{tokenName:e}),n=await this.http.get(t);return this.buildChatStatusResult(e,this.extractData(n))},`Failed to get chat status for token: ${e}`,this.logger)}async disableChat(e){if(null==e||""===e)throw Ct("tokenName","Token name");return this.validateTokenName(e,sn),Rs(async()=>{const t=this.buildEndpoint(Ge,{tokenName:e}),n=await this.http.post(t,{enabled:!1},this.getDualAuthHeaders());return this.buildChatStatusResult(e,this.extractData(n))},`Failed to disable chat for token: ${e}`,this.logger)}async enableChat(e){if(null==e||""===e)throw Ct("tokenName","Token name");return this.validateTokenName(e,sn),Rs(async()=>{const t=this.buildEndpoint(Ke,{tokenName:e}),n=await this.http.post(t,{enabled:!0},this.getDualAuthHeaders());return this.buildChatStatusResult(e,this.extractData(n))},`Failed to enable chat for token: ${e}`,this.logger)}buildChatStatusResult(e,t){const n={enabled:t.enabled,tokenName:t.tokenName??jt(e)};return void 0!==t.status&&null!==t.status&&(n.status=t.status),n}async setSlowMode(e,t){if(null==e||""===e)throw Ct("tokenName","Token name");if(this.validateTokenName(e,sn),"number"!=typeof t||t<0||t>600)throw new Error("slowModeSeconds must be a number between 0 and 600");return Rs(async()=>{const n=this.buildEndpoint(We,{tokenName:e}),a=await this.http.patch(n,{slowModeSeconds:t},this.getDualAuthHeaders());return this.extractData(a)},`Failed to set slow mode for token: ${e}`,this.logger)}}class yl extends Jn{constructor(e=!1){super(e),this.eventRegistry=this.createEmptyRegistry()}setSocket(e){this.logger.debug("📡 [Events] Socket attached to StreamingEventService")}clearSocket(){this.logger.debug("📡 [Events] Socket cleared from StreamingEventService")}createEmptyRegistry(){return{stream_status:new Set,user_banned:new Set,user_unbanned:new Set,ban_enforcement:new Set,content_flagged:new Set,flag_resolved:new Set,stream_chat_message:new Set,stream_chat_updated:new Set,stream_chat_deleted:new Set,stream_chat_pinned:new Set,stream_chat_unpinned:new Set,chat_status_changed:new Set,viewer_count:new Set,recording_status:new Set,simulcast_status:new Set,download_ready:new Set,recordings_count_updated:new Set,user_typing:new Set,stream_reaction:new Set,content_reaction_added:new Set,content_reaction_removed:new Set,stream_countdown_updated:new Set,stream_language_updated:new Set,stream_control_status_changed:new Set,connection:new Set,authenticated:new Set,token_subscribed:new Set,token_unsubscribed:new Set,room_subscribed:new Set,room_left:new Set}}registerCallback(e,t){const n=this.eventRegistry[e];return n.add(t),()=>{n.delete(t)}}async emitEvent(e,t){const n=this.eventRegistry[e];if(0!==n.size)for(const a of n)try{const e=a(t);e instanceof Promise&&await e}catch(t){this.logger.error(`Error in ${e} callback:`,t instanceof Error?t.message:String(t))}}onStreamStatusChanged(e){return this.registerCallback("stream_status",e)}onUserBanned(e){return this.registerCallback("user_banned",e)}onUserUnbanned(e){return this.registerCallback("user_unbanned",e)}onBanEnforcement(e){return this.registerCallback("ban_enforcement",e)}onContentFlagged(e){return this.registerCallback("content_flagged",e)}onFlagResolved(e){return this.registerCallback("flag_resolved",e)}onStreamChatMessage(e){return this.registerCallback("stream_chat_message",e)}onStreamChatUpdated(e){return this.registerCallback("stream_chat_updated",e)}onStreamChatDeleted(e){return this.registerCallback("stream_chat_deleted",e)}onStreamChatPinned(e){return this.registerCallback("stream_chat_pinned",e)}onStreamChatUnpinned(e){return this.registerCallback("stream_chat_unpinned",e)}onChatStatusChanged(e){return this.registerCallback("chat_status_changed",e)}onViewerCountChanged(e){return this.registerCallback("viewer_count",e)}onRecordingStatusChanged(e){return this.registerCallback("recording_status",e)}onSimulcastStatusChanged(e){return this.registerCallback("simulcast_status",e)}onDownloadReady(e){return this.registerCallback("download_ready",e)}onRecordingsCountUpdated(e){return this.registerCallback("recordings_count_updated",e)}onUserTyping(e){return this.registerCallback("user_typing",e)}onStreamReaction(e){return this.registerCallback("stream_reaction",e)}onContentReactionAdded(e){return this.registerCallback("content_reaction_added",e)}onContentReactionRemoved(e){return this.registerCallback("content_reaction_removed",e)}onStreamCountdownUpdated(e){return this.registerCallback("stream_countdown_updated",e)}onStreamLanguageUpdated(e){return this.registerCallback("stream_language_updated",e)}onStreamControlStatusChanged(e){return this.registerCallback("stream_control_status_changed",e)}onConnection(e){return this.registerCallback("connection",e)}onAuthenticated(e){return this.registerCallback("authenticated",e)}onTokenSubscribed(e){return this.registerCallback("token_subscribed",e)}onTokenUnsubscribed(e){return this.registerCallback("token_unsubscribed",e)}onRoomSubscribed(e){return this.registerCallback("room_subscribed",e)}onRoomLeft(e){return this.registerCallback("room_left",e)}async emitStreamStatusChanged(e){await this.emitEvent("stream_status",e)}async emitUserBanned(e){await this.emitEvent("user_banned",e)}async emitUserUnbanned(e){await this.emitEvent("user_unbanned",e)}async emitBanEnforcement(e){await this.emitEvent("ban_enforcement",e)}async emitContentFlagged(e){await this.emitEvent("content_flagged",e)}async emitFlagResolved(e){await this.emitEvent("flag_resolved",e)}async emitStreamChatMessage(e){await this.emitEvent("stream_chat_message",e)}async emitStreamChatUpdated(e){await this.emitEvent("stream_chat_updated",e)}async emitStreamChatDeleted(e){await this.emitEvent("stream_chat_deleted",e)}async emitStreamChatPinned(e){await this.emitEvent("stream_chat_pinned",e)}async emitStreamChatUnpinned(e){await this.emitEvent("stream_chat_unpinned",e)}async emitChatStatusChanged(e){await this.emitEvent("chat_status_changed",e)}async emitViewerCountChanged(e){await this.emitEvent("viewer_count",e)}async emitRecordingStatusChanged(e){await this.emitEvent("recording_status",e)}async emitSimulcastStatusChanged(e){await this.emitEvent("simulcast_status",e)}async emitDownloadReady(e){await this.emitEvent("download_ready",e)}async emitRecordingsCountUpdated(e){await this.emitEvent("recordings_count_updated",e)}async emitUserTyping(e){await this.emitEvent("user_typing",e)}async emitStreamReaction(e){await this.emitEvent("stream_reaction",e)}async emitContentReactionAdded(e){await this.emitEvent("content_reaction_added",e)}async emitContentReactionRemoved(e){await this.emitEvent("content_reaction_removed",e)}async emitStreamCountdownUpdated(e){await this.emitEvent("stream_countdown_updated",e)}async emitStreamLanguageUpdated(e){await this.emitEvent("stream_language_updated",e)}async emitStreamControlStatusChanged(e){await this.emitEvent("stream_control_status_changed",e)}async emitConnection(e){await this.emitEvent("connection",e)}async emitAuthenticated(e){await this.emitEvent("authenticated",e)}async emitTokenSubscribed(e){await this.emitEvent("token_subscribed",e)}async emitTokenUnsubscribed(e){await this.emitEvent("token_unsubscribed",e)}async emitRoomSubscribed(e){await this.emitEvent("room_subscribed",e)}async emitRoomLeft(e){await this.emitEvent("room_left",e)}}$n({IDLE:"IDLE",ACTIVE:"ACTIVE",DISABLED:"DISABLED"}),$n({READY:"READY",PROCESSING:"PROCESSING",ERRORED:"ERRORED",DELETED:"DELETED"});const vl=$n({YOUTUBE:"YOUTUBE",TWITCH:"TWITCH",FACEBOOK:"FACEBOOK",CUSTOM:"CUSTOM"});const kl={OWNER:"OWNER",MANAGER:"MANAGER",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MODERATOR:"MODERATOR"};$n(kl),$n({OWNER:"OWNER",MODERATOR:"MODERATOR"});function bl(e,t="tokenName"){Wn(e,t,sn)}function wl(e){if(bl(e.tokenName),!Pn(e.language))throw Ct("language");if(t=e.language,!Pn(t)||!/^[a-z]{2}(-[A-Z]{2})?$/.test(t))throw new bt('language must be a valid ISO 639-1 code (e.g., "en", "es", "zh-CN")',"language",yt);var t}$n({...kl,OVERSEER:"OVERSEER"});class Sl extends _i{constructor(e,t,n,a=!1,s){super(e,t,n,a,s)}async startStream(e){this.validateTokenName(e,sn);const t=this.buildEndpoint(w,{tokenName:e}),n=await this.http.post(t,{},this.getJwtHeaders());return this.extractData(n)}async stopStream(e){this.validateTokenName(e,sn);const t=this.buildEndpoint(S,{tokenName:e});await this.http.post(t,{},this.getJwtHeaders())}async disableStream(e){return this.toggleFeature(e,A,sn)}async enableStream(e){return this.toggleFeature(e,E,sn)}async resetStreamKey(e){this.validateTokenName(e,sn);const t=this.buildEndpoint(T,{tokenName:e}),n=await this.http.post(t,{},this.getJwtHeaders());return this.extractData(n)}async getStreamCredentials(e){this.validateTokenName(e,sn);const t=this.buildEndpoint(M,{tokenName:e}),n=await this.http.get(t,{},this.getJwtHeaders());return this.extractData(n)}async getRecordings(e){!function(e){bl(e.tokenName),Ln(0,void 0,kn,e.pageSize)}(e);const t=this.buildEndpoint(C,{tokenName:e.tokenName}),n=this.buildPaginationParams(e,kn),a=e.offset;"number"==typeof a&&(n.offset=String(a));const s=await this.http.get(t,n),r=this.extractData(s),i=e,o=r.pageSize??r.limit??e.pageSize??("number"==typeof i.limit?i.limit:20),c="number"==typeof i.offset?i.offset:0,l=Math.floor(c/o)+1;return{recordings:r.recordings,tokenName:jt(e.tokenName),page:r.page??l,limit:o,total:r.total,hasNext:r.recordings.length===o}}async getRecordingDownload(e,t){this.validateTokenName(e,sn),this.validateRequiredString(t,"assetId","Asset ID");const n=this.buildEndpoint(N,{tokenName:e,assetId:t}),a=await this.http.get(n,{},this.getJwtHeaders());return this.extractData(a)}async deleteRecording(e,t){this.validateTokenName(e,sn),this.validateRequiredString(t,"assetId","Asset ID");const n=this.buildEndpoint(I,{tokenName:e,assetId:t});await this.http.delete(n,void 0,this.getJwtHeaders())}async getSimulcastTargets(e){this.validateTokenName(e,sn);const t=this.buildEndpoint(D,{tokenName:e}),n=await this.http.get(t);return this.extractData(n)}async addSimulcastTarget(e){!function(e){if(bl(e.tokenName),!Pn(e.platform))throw Ct("platform");if(!vl(e.platform))throw new bt("platform must be one of: 'YOUTUBE', 'TWITCH', 'FACEBOOK', 'CUSTOM'","platform",ft);if(!Pn(e.rtmpUrl))throw Ct("rtmpUrl");if(!vn.STREAM_URL_PATTERN.test(e.rtmpUrl))throw new bt("rtmpUrl must be a valid RTMP, RTMPS, or SRT URL","rtmpUrl",yt);if(!Pn(e.streamKey))throw Ct("streamKey");if(void 0!==e.name&&"string"!=typeof e.name)throw new bt("name must be a string","name",pt)}(e);const t=this.buildEndpoint(_,{tokenName:e.tokenName}),n=await this.http.post(t,{platform:e.platform,rtmpUrl:e.rtmpUrl,streamKey:e.streamKey,name:e.name},this.getJwtHeaders());return this.extractData(n)}async removeSimulcastTarget(e,t){this.validateTokenName(e,sn),this.validateRequiredString(t,"targetId","Target ID");const n=this.buildEndpoint(R,{tokenName:e,targetId:t});await this.http.delete(n,void 0,this.getJwtHeaders())}async getGlobalStreamingStatus(){const e=await this.http.get(x);return this.extractData(e)}async disableGlobalStreaming(){const e=await this.http.put(O,{},this.getAdminHeaders());return this.extractData(e)}async enableGlobalStreaming(){const e=await this.http.put(F,{},this.getAdminHeaders());return this.extractData(e)}async setNextLiveStream(e){let t;!function(e){if(bl(e.tokenName),null!==e.nextLiveStreamAt){if(!(e.nextLiveStreamAt instanceof Date||Pn(e.nextLiveStreamAt)))throw new bt("nextLiveStreamAt must be a Date, ISO 8601 string, or null","nextLiveStreamAt",pt);if("string"==typeof e.nextLiveStreamAt){const t=Date.parse(e.nextLiveStreamAt);if(isNaN(t))throw new bt("nextLiveStreamAt must be a valid ISO 8601 date string","nextLiveStreamAt",yt)}}}(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,sn);const t=`/v1/tokens/${e.toLowerCase().trim()}`;await this.http.patch(t,{nextLiveStreamAt:null},this.getJwtHeaders())}async setStreamLanguage(e){wl(e);const t=`/v1/tokens/${e.tokenName.toLowerCase().trim()}`;await this.http.patch(t,{streamLanguage:e.language},this.getJwtHeaders())}async getStreamRole(e){!function(e){bl(e.tokenName)}(e);const t=this.buildEndpoint(B,{tokenName:e.tokenName}),n=this.jwtAuth?this.getJwtHeaders():{},a=await this.http.get(t,{},n);return this.extractData(a)}async getAvailableRoles(){const e=await this.http.get(U);return this.extractData(e)}async getTokenAccess(e){!function(e){bl(e.tokenName)}(e);const t=await this.http.get(P,{tokenName:jt(e.tokenName)},this.getJwtHeaders());return this.extractData(t)}async setNextLiveStreamCountdown(e,t){return this.setNextLiveStream({tokenName:e,nextLiveStreamAt:t})}}const Al="subscribe_token",El="unsubscribe_token",Tl="authenticate",Cl="send_stream_chat",Nl="SEND_STREAM_REACTION",Il="typing_start",Dl="typing_stop",_l="STREAM_STATUS",Rl="STREAM_COUNTDOWN_UPDATED",xl="STREAM_LANGUAGE_UPDATED",Ol="VIEWER_COUNT",Fl="token_subscribed",Bl="token_unsubscribed",Ul="STREAM_GLOBAL_STATUS",Pl="ENGAGEMENT_STATS_UPDATED",Ml="STREAM_CHAT_MESSAGE",Ll="STREAM_CHAT_SENT",$l="stream_chat_error",Kl="CHAT_STATUS_CHANGED",Gl="STREAM_CHAT_GLOBAL_STATUS",Wl="authenticated",Hl="stream_chat_auth_error",ql="STREAM_REACTION",zl="stream_reaction_error",jl="USER_TYPING",Vl="STREAM_CHAT_PINNED",Xl="STREAM_CHAT_UNPINNED",Ql="COMMENT_CREATED",Jl="TOKEN_BANNED",Yl="TOKEN_UNBANNED",Zl="MODERATOR_INVITE_CREATED",ed="MODERATOR_ADDED",td="MODERATOR_REMOVED",nd="MODERATOR_ROLE_UPDATED",ad="OVERSEER_ADDED",sd="OVERSEER_REMOVED",rd="TRADE_EXECUTED",id="BALANCE_UPDATED",od="STATS_UPDATED",cd="POOL_METADATA_UPDATED",ld="POOL_SOCIAL_LINKS_UPDATED",dd="POOL_BADGE_ASSIGNED",ud="HOLDER_COUNT_UPDATED",hd="USER_PROFILE_UPDATED",gd="API_KEY_CREATED",md="API_KEY_UPDATED",pd="API_KEY_REVOKED",fd="TOKEN_CONFIG_UPDATED",yd="SITE_CONFIG_CHANGED",vd="COMMENTS_GLOBAL_STATUS",kd="WEBHOOKS_GLOBAL_STATUS",bd="subscribe_global_feed",wd="unsubscribe_global_feed",Sd="global_feed_subscribed",Ad="global_feed_unsubscribed";class Ed extends Jn{constructor(e,t=!1){if(super(t),this.socket=null,this.isAuthenticated=!1,this.subscribedRooms=new Map,this.roomCallbacks=new Map,this.pendingSubscriptions=new Map,this.eventBuffer=new Map,this.eventBufferTimeouts=new Map,this.MAX_BUFFER_SIZE=100,this.BUFFER_CLEANUP_MS=3e4,this.globalCallbacks={},this.isGlobalFeedSubscribed=!1,this.globalFeedCallbacks={},this.pendingGlobalFeedSubscription=null,""===e.url)throw new St("Stream WebSocket URL is required. Set streamWebSocketUrl in SDK config.");this.config={url:e.url,authToken:e.authToken??"",reconnectAttempts:e.reconnectAttempts??5,reconnectDelay:e.reconnectDelay??2e3,subscriptionTimeout:e.subscriptionTimeout??1e4},this.reconnectionManager=new Tc({maxAttempts:this.config.reconnectAttempts,baseDelayMs:this.config.reconnectDelay}),this.isSocketIOAvailable=this.checkSocketIOAvailability()}checkSocketIOAvailability(){try{return"function"==typeof h.io||(this.logger.warn('⚠️ Socket.IO client not available. Install "socket.io-client" package.'),!1)}catch(e){return this.logger.warn("⚠️ Socket.IO availability check failed:",rt(e)),!1}}getRoomName(e){return`token:${jt(e)}`}bufferEvent(e,t,n){const a=`${e}:${t}`;let s=this.eventBuffer.get(a);s||(s=[],this.eventBuffer.set(a,s)),s.length>=this.MAX_BUFFER_SIZE&&(s.shift(),this.logger.warn(`⚠️ [Stream Buffer] Event buffer overflow for ${a} - dropping oldest event. Consider processing events faster or increasing buffer size.`)),s.push(n);const r=this.eventBufferTimeouts.get(a);r&&clearTimeout(r);const i=setTimeout(()=>{this.eventBuffer.delete(a),this.eventBufferTimeouts.delete(a),this.logger.debug(`📡 [Stream Buffer] Cleaned up buffer for ${a}`)},this.BUFFER_CLEANUP_MS);this.eventBufferTimeouts.set(a,i)}processBufferedEvents(e,t){const n=jt(e),a=[{key:`${_l}:${n}`,callback:t.onStreamStatus},{key:`${Ol}:${n}`,callback:t.onViewerCount},{key:`${Ml}:${n}`,callback:t.onChatMessage},{key:`${Kl}:${n}`,callback:t.onChatStatus},{key:`${Vl}:${n}`,callback:t.onChatPinned},{key:`${Xl}:${n}`,callback:t.onChatUnpinned},{key:`${Rl}:${n}`,callback:t.onCountdownUpdated},{key:`${xl}:${n}`,callback:t.onLanguageUpdated},{key:`${Jl}:${n}`,callback:t.onTokenBanned},{key:`${Yl}:${n}`,callback:t.onTokenUnbanned},{key:`${Zl}:${n}`,callback:t.onModeratorInviteCreated},{key:`${ed}:${n}`,callback:t.onModeratorAdded},{key:`${td}:${n}`,callback:t.onModeratorRemoved},{key:`${nd}:${n}`,callback:t.onModeratorRoleUpdated},{key:`${rd}:${n}`,callback:t.onTradeExecuted},{key:`${id}:${n}`,callback:t.onBalanceUpdated},{key:`${cd}:${n}`,callback:t.onPoolMetadataUpdated},{key:`${ld}:${n}`,callback:t.onPoolSocialLinksUpdated},{key:`${dd}:${n}`,callback:t.onPoolBadgeAssigned},{key:`${ud}:${n}`,callback:t.onHolderCountUpdated},{key:`${Ql}:${n}`,callback:t.onCommentCreated}];for(const{key:e,callback:t}of a){const n=this.eventBuffer.get(e);if(n&&t){this.logger.debug(`📡 [Stream Buffer] Delivering ${n.length} buffered events for ${e}`);for(const a of n)try{t(a)}catch(t){this.logger.error(`Error delivering buffered event for ${e}:`,t)}this.eventBuffer.delete(e);const a=this.eventBufferTimeouts.get(e);a&&(clearTimeout(a),this.eventBufferTimeouts.delete(e))}}}setupGlobalListeners(){this.socket&&(this.socket.on(_l,e=>{this.logger.debug(`📡 [Stream Status] ${e.tokenName}: ${e.status}`),this.bufferEvent(_l,e.tokenName,e);const t=this.roomCallbacks.get(jt(e.tokenName));t?.onStreamStatus&&t.onStreamStatus(e),this.globalCallbacks.onStreamStatus&&this.globalCallbacks.onStreamStatus(e),this.isGlobalFeedSubscribed&&!t&&this.globalFeedCallbacks.onStreamStatus&&this.globalFeedCallbacks.onStreamStatus(e)}),this.socket.on(Fl,e=>{this.logger.debug(`📡 [Subscribed] ${e.tokenName}`);const t=jt(e.tokenName),n=this.pendingSubscriptions.get(t);n&&(clearTimeout(n.timeoutId),this.pendingSubscriptions.delete(t),n.resolve(e));const a=this.roomCallbacks.get(t);a?.onStreamSubscribed&&a.onStreamSubscribed(e)}),this.socket.on(Bl,e=>{const t=e.room.replace("token:","");this.logger.debug(`📡 [Unsubscribed] ${t}`);const n=this.roomCallbacks.get(jt(t));n?.onStreamUnsubscribed&&n.onStreamUnsubscribed(e)}),this.socket.on(Ol,e=>{this.logger.debug(`📡 [Viewer Count] ${e.tokenName}: ${e.viewerCount}`),this.bufferEvent(Ol,e.tokenName,e);const t=this.roomCallbacks.get(jt(e.tokenName));t?.onViewerCount&&t.onViewerCount(e),this.globalCallbacks.onViewerCount&&this.globalCallbacks.onViewerCount(e),this.isGlobalFeedSubscribed&&!t&&this.globalFeedCallbacks.onViewerCount&&this.globalFeedCallbacks.onViewerCount(e)}),this.socket.on(Ul,e=>{this.logger.debug(`📡 [Global Stream Status] enabled: ${String(e.enabled)}`),this.globalCallbacks.onStreamGlobalStatus&&this.globalCallbacks.onStreamGlobalStatus(e)}),this.socket.on(Ml,e=>{this.logger.debug(`📡 [Chat Message] ${e.tokenName}: ${e.content.slice(0,50)}...`),this.bufferEvent(Ml,e.tokenName,e);const t=this.roomCallbacks.get(jt(e.tokenName));t?.onChatMessage&&t.onChatMessage(e),this.globalCallbacks.onChatMessage&&this.globalCallbacks.onChatMessage(e)}),this.socket.on(Ll,e=>{this.logger.debug(`📡 [Chat Sent] ${e.tokenName}: ${e.messageId}`);const t=this.roomCallbacks.get(jt(e.tokenName));t?.onChatSent&&t.onChatSent(e)}),this.socket.on($l,e=>{this.logger.error(`📡 [Chat Error] ${e.tokenName}: ${e.message}`);const t=this.roomCallbacks.get(jt(e.tokenName));t?.onChatError&&t.onChatError(e),this.globalCallbacks.onChatError&&this.globalCallbacks.onChatError(e)}),this.socket.on(Kl,e=>{this.logger.debug(`📡 [Chat Status] ${e.tokenName}: ${String(e.enabled)}`),this.bufferEvent(Kl,e.tokenName,e);const t=this.roomCallbacks.get(jt(e.tokenName));t?.onChatStatus&&t.onChatStatus(e),this.globalCallbacks.onChatStatus&&this.globalCallbacks.onChatStatus(e)}),this.socket.on(Gl,e=>{this.logger.debug(`📡 [Global Chat Status] enabled: ${String(e.enabled)}`),this.globalCallbacks.onChatGlobalStatus&&this.globalCallbacks.onChatGlobalStatus(e)}),this.socket.on(Wl,e=>{this.logger.debug(`📡 [Authenticated] ${e.address}`),this.isAuthenticated=!0,this.globalCallbacks.onChatAuthenticated&&this.globalCallbacks.onChatAuthenticated(e)}),this.socket.on(Hl,e=>{this.logger.error(`📡 [Auth Error] ${e.message}`),this.isAuthenticated=!1,this.globalCallbacks.onChatAuthError&&this.globalCallbacks.onChatAuthError(e)}),this.socket.on(ql,e=>{this.logger.debug(`📡 [Reaction] ${e.tokenName}: ${e.emoji}`);const t=this.roomCallbacks.get(jt(e.tokenName));t?.onReaction&&t.onReaction(e),this.globalCallbacks.onReaction&&this.globalCallbacks.onReaction(e)}),this.socket.on(zl,e=>{this.logger.error(`📡 [Reaction Error] ${e.tokenName}: ${e.message}`);const t=this.roomCallbacks.get(jt(e.tokenName));t?.onReactionError&&t.onReactionError(e),this.globalCallbacks.onReactionError&&this.globalCallbacks.onReactionError(e)}),this.socket.on(jl,e=>{const t=e.typingUsers.length;this.logger.debug(`📡 [Typing] ${e.tokenName}: ${t} user(s) typing`);const n=this.roomCallbacks.get(jt(e.tokenName));n?.onTypingIndicator&&n.onTypingIndicator(e),this.globalCallbacks.onTypingIndicator&&this.globalCallbacks.onTypingIndicator(e)}),this.socket.on(Vl,e=>{this.logger.debug(`📡 [Chat Pinned] ${e.tokenName}: ${e.pinnedMessage.messageId}`),this.bufferEvent(Vl,e.tokenName,e);const t=this.roomCallbacks.get(jt(e.tokenName));t?.onChatPinned&&t.onChatPinned(e),this.globalCallbacks.onChatPinned&&this.globalCallbacks.onChatPinned(e)}),this.socket.on(Xl,e=>{this.logger.debug(`📡 [Chat Unpinned] ${e.tokenName}: ${e.unpinnedMessageId}`),this.bufferEvent(Xl,e.tokenName,e);const t=this.roomCallbacks.get(jt(e.tokenName));t?.onChatUnpinned&&t.onChatUnpinned(e),this.globalCallbacks.onChatUnpinned&&this.globalCallbacks.onChatUnpinned(e)}),this.socket.on(Rl,e=>{const t=e.nextLiveStreamAt??"cleared";this.logger.debug(`📡 [Countdown Updated] ${e.tokenName}: ${t}`),this.bufferEvent(Rl,e.tokenName,e);const n=this.roomCallbacks.get(jt(e.tokenName));n?.onCountdownUpdated&&n.onCountdownUpdated(e),this.globalCallbacks.onCountdownUpdated&&this.globalCallbacks.onCountdownUpdated(e)}),this.socket.on(xl,e=>{this.logger.debug(`📡 [Language Updated] ${e.tokenName}: ${e.language}`),this.bufferEvent(xl,e.tokenName,e);const t=this.roomCallbacks.get(jt(e.tokenName));t?.onLanguageUpdated&&t.onLanguageUpdated(e),this.globalCallbacks.onLanguageUpdated&&this.globalCallbacks.onLanguageUpdated(e)}),this.socket.on(Jl,e=>{this.logger.debug(`📡 [Token Banned] ${e.tokenName}`),this.bufferEvent(Jl,e.tokenName,e);const t=this.roomCallbacks.get(jt(e.tokenName));t?.onTokenBanned&&t.onTokenBanned(e),this.globalCallbacks.onTokenBanned&&this.globalCallbacks.onTokenBanned(e)}),this.socket.on(Yl,e=>{this.logger.debug(`📡 [Token Unbanned] ${e.tokenName}`),this.bufferEvent(Yl,e.tokenName,e);const t=this.roomCallbacks.get(jt(e.tokenName));t?.onTokenUnbanned&&t.onTokenUnbanned(e),this.globalCallbacks.onTokenUnbanned&&this.globalCallbacks.onTokenUnbanned(e)}),this.socket.on(Zl,e=>{this.logger.debug(`📡 [Moderator Invite Created] ${e.tokenName}: by ${e.invitedBy}`),this.bufferEvent(Zl,e.tokenName,e);const t=this.roomCallbacks.get(jt(e.tokenName));t?.onModeratorInviteCreated&&t.onModeratorInviteCreated(e)}),this.socket.on(ed,e=>{this.logger.debug(`📡 [Moderator Added] ${e.tokenName}: ${e.userAddress}`),this.bufferEvent(ed,e.tokenName,e);const t=this.roomCallbacks.get(jt(e.tokenName));t?.onModeratorAdded&&t.onModeratorAdded(e)}),this.socket.on(td,e=>{this.logger.debug(`📡 [Moderator Removed] ${e.tokenName}: ${e.userAddress}`),this.bufferEvent(td,e.tokenName,e);const t=this.roomCallbacks.get(jt(e.tokenName));t?.onModeratorRemoved&&t.onModeratorRemoved(e)}),this.socket.on(nd,e=>{this.logger.debug(`📡 [Moderator Role Updated] ${e.tokenName}: ${e.userAddress}`),this.bufferEvent(nd,e.tokenName,e);const t=this.roomCallbacks.get(jt(e.tokenName));t?.onModeratorRoleUpdated&&t.onModeratorRoleUpdated(e)}),this.socket.on(ad,e=>{this.logger.debug(`📡 [Overseer Added] ${e.userAddress}`),this.globalCallbacks.onOverseerAdded&&this.globalCallbacks.onOverseerAdded(e)}),this.socket.on(sd,e=>{this.logger.debug(`📡 [Overseer Removed] ${e.userAddress}`),this.globalCallbacks.onOverseerRemoved&&this.globalCallbacks.onOverseerRemoved(e)}),this.socket.on(rd,e=>{this.logger.debug(`📡 [Trade Executed] ${e.tokenName}: ${e.tradeType}`),this.bufferEvent(rd,e.tokenName,e);const t=this.roomCallbacks.get(jt(e.tokenName));t?.onTradeExecuted&&t.onTradeExecuted(e),this.isGlobalFeedSubscribed&&!t&&this.globalFeedCallbacks.onTradeExecuted&&this.globalFeedCallbacks.onTradeExecuted(e)}),this.socket.on(id,e=>{this.logger.debug(`📡 [Balance Updated] ${e.tokenName}: ${e.tradeType}`),this.bufferEvent(id,e.tokenName,e);const t=this.roomCallbacks.get(jt(e.tokenName));t?.onBalanceUpdated&&t.onBalanceUpdated(e)}),this.socket.on(cd,e=>{this.logger.debug(`📡 [Pool Metadata Updated] ${e.tokenName}`),this.bufferEvent(cd,e.tokenName,e);const t=this.roomCallbacks.get(jt(e.tokenName));t?.onPoolMetadataUpdated&&t.onPoolMetadataUpdated(e)}),this.socket.on(ld,e=>{this.logger.debug(`📡 [Pool Social Links Updated] ${e.tokenName}`),this.bufferEvent(ld,e.tokenName,e);const t=this.roomCallbacks.get(jt(e.tokenName));t?.onPoolSocialLinksUpdated&&t.onPoolSocialLinksUpdated(e)}),this.socket.on(dd,e=>{this.logger.debug(`📡 [Pool Badge Assigned] ${e.tokenName}: ${e.badge}`),this.bufferEvent(dd,e.tokenName,e);const t=this.roomCallbacks.get(jt(e.tokenName));t?.onPoolBadgeAssigned&&t.onPoolBadgeAssigned(e),this.isGlobalFeedSubscribed&&!t&&this.globalFeedCallbacks.onPoolBadgeAssigned&&this.globalFeedCallbacks.onPoolBadgeAssigned(e)}),this.socket.on(ud,e=>{this.logger.debug(`📡 [Holder Count Updated] ${e.tokenName}: ${e.holderCount}`),this.bufferEvent(ud,e.tokenName,e);const t=this.roomCallbacks.get(jt(e.tokenName));t?.onHolderCountUpdated&&t.onHolderCountUpdated(e),this.isGlobalFeedSubscribed&&!t&&this.globalFeedCallbacks.onHolderCountUpdated&&this.globalFeedCallbacks.onHolderCountUpdated(e)}),this.socket.on(Ql,e=>{this.logger.debug(`📡 [Comment Created] ${e.tokenName}: ID ${e.id}`),this.bufferEvent(Ql,e.tokenName,e);const t=this.roomCallbacks.get(jt(e.tokenName));t?.onCommentCreated&&t.onCommentCreated(e)}),this.socket.on(hd,e=>{this.logger.debug(`📡 [User Profile Updated] ${e.userAddress}`),this.globalCallbacks.onUserProfileUpdated&&this.globalCallbacks.onUserProfileUpdated(e)}),this.socket.on(gd,e=>{this.logger.debug(`📡 [API Key Created] ${e.keyId}`),this.globalCallbacks.onApiKeyCreated&&this.globalCallbacks.onApiKeyCreated(e)}),this.socket.on(md,e=>{this.logger.debug(`📡 [API Key Updated] ${e.keyId}`),this.globalCallbacks.onApiKeyUpdated&&this.globalCallbacks.onApiKeyUpdated(e)}),this.socket.on(pd,e=>{this.logger.debug(`📡 [API Key Revoked] ${e.keyId}`),this.globalCallbacks.onApiKeyRevoked&&this.globalCallbacks.onApiKeyRevoked(e)}),this.socket.on(fd,e=>{this.logger.debug(`📡 [Token Config Updated] ${e.tokenName}`),this.bufferEvent(fd,e.tokenName,e);const t=this.roomCallbacks.get(jt(e.tokenName));t?.onTokenConfigUpdated&&t.onTokenConfigUpdated(e),this.isGlobalFeedSubscribed&&!t&&this.globalFeedCallbacks.onTokenConfigUpdated&&this.globalFeedCallbacks.onTokenConfigUpdated(e)}),this.socket.on(od,e=>{this.logger.debug(`📡 [Stats Updated] ${e.tokenName} price=${e.galaPrice}`),this.bufferEvent(od,e.tokenName,e);const t=this.roomCallbacks.get(jt(e.tokenName));t?.onStatsUpdated&&t.onStatsUpdated(e),this.globalCallbacks.onStatsUpdated&&this.globalCallbacks.onStatsUpdated(e),this.isGlobalFeedSubscribed&&!t&&this.globalFeedCallbacks.onStatsUpdated&&this.globalFeedCallbacks.onStatsUpdated(e)}),this.socket.on(Pl,e=>{this.logger.debug(`📡 [Engagement Stats Updated] ${e.tokenName} chatters=${e.chat.uniqueChatters}`),this.bufferEvent(Pl,e.tokenName,e);const t=this.roomCallbacks.get(jt(e.tokenName));t?.onEngagementStatsUpdated&&t.onEngagementStatsUpdated(e),this.globalCallbacks.onEngagementStatsUpdated&&this.globalCallbacks.onEngagementStatsUpdated(e)}),this.socket.on(Sd,e=>{if(this.logger.debug("📡 [Global Feed Subscribed]"),this.isGlobalFeedSubscribed=!0,this.pendingGlobalFeedSubscription){const{resolve:t,timeoutId:n}=this.pendingGlobalFeedSubscription;clearTimeout(n),this.pendingGlobalFeedSubscription=null,t(e)}this.globalFeedCallbacks.onGlobalFeedSubscribed&&this.globalFeedCallbacks.onGlobalFeedSubscribed(e)}),this.socket.on(Ad,e=>{this.logger.debug("📡 [Global Feed Unsubscribed]"),this.isGlobalFeedSubscribed=!1,this.globalFeedCallbacks.onGlobalFeedUnsubscribed&&this.globalFeedCallbacks.onGlobalFeedUnsubscribed(e)}),this.socket.on(yd,e=>{this.logger.debug(`📡 [Site Config Changed] ${e.key}`),this.globalFeedCallbacks.onSiteConfigChanged&&this.globalFeedCallbacks.onSiteConfigChanged(e)}),this.socket.on(Ul,e=>{this.logger.debug(`📡 [Stream Global Status] enabled=${String(e.enabled)}`),this.globalFeedCallbacks.onStreamGlobalStatus&&this.globalFeedCallbacks.onStreamGlobalStatus(e)}),this.socket.on(Gl,e=>{this.logger.debug(`📡 [Chat Global Status] enabled=${String(e.enabled)}`),this.globalFeedCallbacks.onStreamChatGlobalStatus&&this.globalFeedCallbacks.onStreamChatGlobalStatus(e)}),this.socket.on(vd,e=>{this.logger.debug(`📡 [Comments Global Status] enabled=${String(e.enabled)}`),this.globalFeedCallbacks.onCommentsGlobalStatus&&this.globalFeedCallbacks.onCommentsGlobalStatus(e)}),this.socket.on(kd,e=>{this.logger.debug(`📡 [Webhooks Global Status] enabled=${String(e.enabled)}`),this.globalFeedCallbacks.onWebhooksGlobalStatus&&this.globalFeedCallbacks.onWebhooksGlobalStatus(e)}))}resubscribeAll(){const e=Array.from(this.subscribedRooms.keys());this.logger.debug(`📡 Re-subscribing to ${e.length} rooms after reconnect`);for(const t of e)try{this.roomCallbacks.get(t)&&this.socket?.emit(Al,{tokenName:t})}catch(e){this.logger.error(`Failed to re-subscribe to ${t}:`,e)}if(this.isGlobalFeedSubscribed)try{this.logger.debug("📡 Re-subscribing to global feed after reconnect"),this.socket?.emit(bd)}catch(e){this.logger.error("Failed to re-subscribe to global feed:",e)}}async connect(){return new Promise((e,t)=>{Rs(async()=>{if(!this.isSocketIOAvailable)throw new St('Socket.IO not available. Install "socket.io-client" package.');this.logger.debug(`🔌 Connecting to Stream WebSocket: ${this.config.url}`);const n={};return""!==this.config.authToken&&(n.token=this.config.authToken),this.socket=h.io(this.config.url,{transports:["websocket"],reconnection:!0,reconnectionAttempts:this.config.reconnectAttempts,reconnectionDelay:this.config.reconnectDelay,auth:n}),this.socket.on("connect",()=>{this.logger.debug(`✅ Stream WebSocket connected: ${String(this.socket?.id)}`),this.reconnectionManager.reset(),this.setupGlobalListeners(),this.subscribedRooms.size>0&&this.resubscribeAll(),e()}),this.socket.on("connect_error",e=>{this.logger.error("❌ Stream WebSocket connection error:",e),t(e)}),this.socket.on("disconnect",e=>{this.logger.debug(`🔌 Stream WebSocket disconnected: ${e}`),this.isAuthenticated=!1}),this.socket.on("error",e=>{this.logger.error("❌ Stream WebSocket error:",e)}),this.socket.io.on("reconnect",e=>{this.logger.debug(`🔄 Stream WebSocket reconnected after ${e} attempts`),this.reconnectionManager.reset(),""!==this.config.authToken&&this.authenticate(this.config.authToken)}),this.socket.io.on("reconnect_attempt",()=>{this.reconnectionManager.recordAttempt(),this.logger.debug(`🔄 Stream WebSocket reconnect attempt ${this.reconnectionManager.getStatusString()}`)}),this.socket.io.on("reconnect_failed",()=>{this.logger.error("❌ Stream WebSocket max reconnection attempts reached")}),Promise.resolve(void 0)},"Stream WebSocket connection setup",this.logger,e=>{const n=e instanceof Error?e:new Error(String(e));throw t(n),n})})}authenticate(e){if(!this.socket?.connected)throw new bt("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(""===e)throw Ct("token","Authentication token");this.logger.debug("📡 Authenticating with stream server"),this.socket.emit(Tl,{token:e}),this.config.authToken=e}async subscribeToStream(e,t={}){if(""===e)throw Ct("tokenName","Token name");if(!this.socket?.connected)throw new bt("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");const n=jt(e);return this.subscribedRooms.has(n)?(this.logger.debug(`📡 Already subscribed to ${n}, updating callbacks`),this.roomCallbacks.set(n,t),this.processBufferedEvents(n,t),{tokenName:n,room:this.getRoomName(e)}):new Promise((a,s)=>{const r=setTimeout(()=>{this.pendingSubscriptions.delete(n),s(new Error(`Subscription to ${e} timed out after ${this.config.subscriptionTimeout}ms`))},this.config.subscriptionTimeout);this.pendingSubscriptions.set(n,{resolve:a,reject:s,timeoutId:r}),this.roomCallbacks.set(n,t),this.subscribedRooms.set(n,{tokenName:n,subscribedAt:Date.now()}),this.logger.debug(`📡 Subscribing to stream: ${n}`),this.socket.emit(Al,{tokenName:n})})}unsubscribeFromStream(e){const t=jt(e);if(!this.subscribedRooms.has(t))return void this.logger.debug(`📡 Not subscribed to ${t}, skipping unsubscribe`);this.logger.debug(`📡 Unsubscribing from stream: ${t}`),this.socket?.connected&&this.socket.emit(El,{tokenName:t}),this.subscribedRooms.delete(t),this.roomCallbacks.delete(t);const n=this.pendingSubscriptions.get(t);n&&(clearTimeout(n.timeoutId),this.pendingSubscriptions.delete(t));for(const e of this.eventBuffer.keys())if(e.endsWith(`:${t}`)){this.eventBuffer.delete(e);const t=this.eventBufferTimeouts.get(e);t&&(clearTimeout(t),this.eventBufferTimeouts.delete(e))}}sendChatMessage(e,t){if(""===e)throw Ct("tokenName","Token name");if(""===t)throw Ct("content","Message content");if(!this.socket?.connected)throw new bt("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(!this.isAuthenticated)throw new bt("Not authenticated. Call authenticate() first.","auth","NOT_AUTHENTICATED");const n=jt(e);this.logger.debug(`📡 Sending chat message to ${n}: ${t.slice(0,30)}...`),this.socket.emit(Cl,{tokenName:n,content:t})}sendReaction(e,t,n=0){if(""===e)throw Ct("tokenName","Token name");if(""===t)throw Ct("emoji");if(!this.socket?.connected)throw new bt("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(!this.isAuthenticated)throw new bt("Not authenticated. Call authenticate() first.","auth","NOT_AUTHENTICATED");const a=jt(e);this.logger.debug(`📡 Sending reaction to ${a}: ${t}`),this.socket.emit(Nl,{tokenName:a,emoji:t,streamTime:n})}sendTypingStart(e){this.sendTypingEvent(e,Il,"typing_start")}sendTypingStop(e){this.sendTypingEvent(e,Dl,"typing_stop")}sendTypingEvent(e,t,n){if(""===e)throw Ct("tokenName","Token name");if(!this.socket?.connected)throw new bt("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(!this.isAuthenticated)throw new bt("Not authenticated. Call authenticate() first.","auth","NOT_AUTHENTICATED");const a=jt(e);this.logger.debug(`📡 Sending ${n} to ${a}`),this.socket.emit(t,{tokenName:a})}subscribeTokenBanned(e,t){const n=jt(e),a={onTokenBanned:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...a}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onTokenBanned,this.roomCallbacks.set(n,t)}}}subscribeTokenUnbanned(e,t){const n=jt(e),a={onTokenUnbanned:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...a}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onTokenUnbanned,this.roomCallbacks.set(n,t)}}}subscribeModeratorInviteCreated(e,t){const n=jt(e),a={onModeratorInviteCreated:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...a}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onModeratorInviteCreated,this.roomCallbacks.set(n,t)}}}subscribeModeratorAdded(e,t){const n=jt(e),a={onModeratorAdded:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...a}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onModeratorAdded,this.roomCallbacks.set(n,t)}}}subscribeModeratorRemoved(e,t){const n=jt(e),a={onModeratorRemoved:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...a}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onModeratorRemoved,this.roomCallbacks.set(n,t)}}}subscribeModeratorRoleUpdated(e,t){const n=jt(e),a={onModeratorRoleUpdated:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...a}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onModeratorRoleUpdated,this.roomCallbacks.set(n,t)}}}subscribeOverseerAdded(e){return this.globalCallbacks.onOverseerAdded=e,()=>{delete this.globalCallbacks.onOverseerAdded}}subscribeOverseerRemoved(e){return this.globalCallbacks.onOverseerRemoved=e,()=>{delete this.globalCallbacks.onOverseerRemoved}}subscribeTradeExecuted(e,t){const n=jt(e),a={onTradeExecuted:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...a}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onTradeExecuted,this.roomCallbacks.set(n,t)}}}subscribePoolMetadataUpdated(e,t){const n=jt(e),a={onPoolMetadataUpdated:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...a}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onPoolMetadataUpdated,this.roomCallbacks.set(n,t)}}}subscribePoolSocialLinksUpdated(e,t){const n=jt(e),a={onPoolSocialLinksUpdated:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...a}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onPoolSocialLinksUpdated,this.roomCallbacks.set(n,t)}}}subscribePoolBadgeAssigned(e,t){const n=jt(e),a={onPoolBadgeAssigned:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...a}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onPoolBadgeAssigned,this.roomCallbacks.set(n,t)}}}subscribeHolderCountUpdated(e,t){const n=jt(e),a={onHolderCountUpdated:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...a}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onHolderCountUpdated,this.roomCallbacks.set(n,t)}}}subscribeCommentCreated(e,t){const n=jt(e),a={onCommentCreated:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...a}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onCommentCreated,this.roomCallbacks.set(n,t)}}}subscribeUserProfileUpdated(e){return this.globalCallbacks.onUserProfileUpdated=e,()=>{delete this.globalCallbacks.onUserProfileUpdated}}subscribeApiKeyCreated(e){return this.globalCallbacks.onApiKeyCreated=e,()=>{delete this.globalCallbacks.onApiKeyCreated}}subscribeApiKeyUpdated(e){return this.globalCallbacks.onApiKeyUpdated=e,()=>{delete this.globalCallbacks.onApiKeyUpdated}}subscribeApiKeyRevoked(e){return this.globalCallbacks.onApiKeyRevoked=e,()=>{delete this.globalCallbacks.onApiKeyRevoked}}subscribeStatsUpdated(e){return this.globalCallbacks.onStatsUpdated=e,()=>{delete this.globalCallbacks.onStatsUpdated}}subscribeEngagementStatsUpdated(e){return this.globalCallbacks.onEngagementStatsUpdated=e,()=>{delete this.globalCallbacks.onEngagementStatsUpdated}}setGlobalCallbacks(e){this.globalCallbacks=e}getSubscribedTokens(){return Array.from(this.subscribedRooms.keys())}isConnected(){return this.socket?.connected??!1}isAuthenticatedForChat(){return this.isAuthenticated}async subscribeToGlobalFeed(e){if(!this.socket?.connected)throw new bt("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");return this.isGlobalFeedSubscribed?(this.logger.debug("📡 Already subscribed to global feed, updating callbacks"),e&&(this.globalFeedCallbacks=e),{room:"global:feed"}):new Promise((t,n)=>{const a=setTimeout(()=>{this.pendingGlobalFeedSubscription=null,n(new Error(`Global feed subscription timed out after ${this.config.subscriptionTimeout}ms`))},this.config.subscriptionTimeout);this.pendingGlobalFeedSubscription={resolve:t,reject:n,timeoutId:a},e&&(this.globalFeedCallbacks=e),this.logger.debug("📡 Subscribing to global feed"),this.socket.emit(bd)})}unsubscribeFromGlobalFeed(){this.isGlobalFeedSubscribed?(this.logger.debug("📡 Unsubscribing from global feed"),this.socket?.connected&&this.socket.emit(wd),this.isGlobalFeedSubscribed=!1,this.globalFeedCallbacks={},this.pendingGlobalFeedSubscription&&(clearTimeout(this.pendingGlobalFeedSubscription.timeoutId),this.pendingGlobalFeedSubscription=null)):this.logger.debug("📡 Not subscribed to global feed, skipping unsubscribe")}isSubscribedToGlobalFeed(){return this.isGlobalFeedSubscribed}setGlobalFeedCallbacks(e){this.globalFeedCallbacks=e,this.logger.debug("📡 Updated global feed callbacks")}getSocket(){return this.socket}disconnect(){if(this.socket){this.logger.debug("🔌 Disconnecting from Stream WebSocket");try{for(const[e,t]of this.pendingSubscriptions){try{clearTimeout(t.timeoutId),t.reject(new Error("WebSocket disconnected"))}catch(t){this.logger.error(`Error cleaning up pending subscription for ${e}:`,t)}this.pendingSubscriptions.delete(e)}}catch(e){this.logger.error("Error clearing pending subscriptions:",e)}try{this.subscribedRooms.clear(),this.roomCallbacks.clear()}catch(e){this.logger.error("Error clearing room tracking:",e)}try{for(const e of this.eventBufferTimeouts.values())clearTimeout(e);this.eventBuffer.clear(),this.eventBufferTimeouts.clear()}catch(e){this.logger.error("Error clearing event buffers:",e)}this.globalCallbacks={};try{this.globalFeedCallbacks={},this.isGlobalFeedSubscribed=!1,this.pendingGlobalFeedSubscription&&(clearTimeout(this.pendingGlobalFeedSubscription.timeoutId),this.pendingGlobalFeedSubscription.reject(new Error("WebSocket disconnected")),this.pendingGlobalFeedSubscription=null)}catch(e){this.logger.error("Error clearing global feed state:",e)}try{this.socket.disconnect()}catch(e){this.logger.error("Error disconnecting socket:",e)}this.socket=null,this.isAuthenticated=!1,this.logger.debug("✅ Stream WebSocket disconnected and cleaned up")}}}function Td(e){if(Wn(e.tokenName,"tokenName",sn),!(null==(t=e.reason)||""===t||"string"==typeof t&&!qn(t)&&t.length<=hn.BAN_REASON.MAX_LENGTH))throw new bt(`reason must be at most ${hn.BAN_REASON.MAX_LENGTH} characters`,"reason","TOO_LONG");var t}class Cd extends _i{constructor(e,t,n,a=!1,s){super(e,t,n,a,s)}async banToken(e){Td(e);const t=_e,n={tokenName:jt(e.tokenName)};if(void 0!==e.reason)try{Bn(e.reason,"reason",!0),e.reason.trim().length>0&&(n.reason=e.reason)}catch{}const a=await this.http.post(t,n,this.getDualAuthHeaders());return{ban:this.extractData(a),tokenName:jt(e.tokenName)}}async unbanToken(e){!function(e){Wn(e.tokenName,"tokenName",sn)}(e);const t=this.buildEndpoint(Oe,{tokenName:e.tokenName});return Lt(await this.http.delete(t,void 0,this.getDualAuthHeaders()),"Failed to unban token",!1),{tokenName:jt(e.tokenName)}}async listTokenBans(e={}){!function(e){Ln(0,void 0,cn,e.pageSize)}(e);const t=Re,n=this.buildPaginationParams(e,cn);this.addOptionalFilterParams(n,e,["search"]);const a=await this.http.get(t,n,this.getDualAuthHeaders()),s=this.extractData(a);return{items:s.bans,pageInfo:s.pageInfo}}async getTokenBan(e){!function(e){Wn(e.tokenName,"tokenName",sn)}(e);const t=this.buildEndpoint(xe,{tokenName:e.tokenName}),n=await this.http.get(t,{},this.getDualAuthHeaders()),a=this.extractDataOrNull(n);return{banned:null!==a,...null!==a&&{ban:a},tokenName:jt(e.tokenName)}}async isTokenBanned(e){return this.getTokenBan(e)}}class Nd extends Jn{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(!Pn(e))throw Ct("tokenName","Token name");const t=jt(e),n=this.getCacheEntry(t);if(null!==n)return this.cacheHits++,this.updateAccessOrder(t),n.vaultAddress;this.cacheMisses++;const a=await this.poolService.resolveTokenNameToVault(e);if(null!==a&&""!==a){const e=this.parseVaultAddressToTokenClassKey(a);this.setCacheEntry(t,{vaultAddress:a,tokenClassKey:e,cachedAt:Date.now()})}return a}async resolveTokenClassKey(e){if(!Pn(e))throw Ct("tokenName","Token name");const t=jt(e),n=this.getCacheEntry(t);if(null!==n)return this.cacheHits++,this.updateAccessOrder(t),n.tokenClassKey;this.cacheMisses++;const a=await this.poolService.resolveTokenNameToVault(e);if(null===a||""===a)throw Tt(e);const s=this.parseVaultAddressToTokenClassKey(a);return this.setCacheEntry(t,{vaultAddress:a,tokenClassKey:s,cachedAt:Date.now()}),s}get(e){const t=this.getCacheEntry(jt(e));return t?.vaultAddress??null}getCacheEntry(e){return this.cache.get(e)??null}setCacheEntry(e,t){this.cache.size>=Nd.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=jt(e),a=this.parseVaultAddressToTokenClassKey(t);this.setCacheEntry(n,{vaultAddress:t,tokenClassKey:a,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:Nd.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(jt(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:a}of e){const e=jt(t);this.setCacheEntry(e,{vaultAddress:n,tokenClassKey:a,cachedAt:Date.now()})}}parseVaultAddressToTokenClassKey(e){try{return Wi(e)}catch(e){if(e instanceof bt)throw Nt("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad","Vault address");throw e}}}Nd.MAX_CACHE_SIZE=1e4;class Id extends Qn{constructor(e,t=!1){super(e,t)}async fetchLaunchpadFee(){return Gt(()=>this.http.get(ze),{errorContext:"Failed to fetch launchpad fee"})}async fetchSaleDetails(e){return Gt(()=>this.http.get(je,{tokenName:e}),{errorContext:`Failed to fetch sale details for ${e}`})}async getTradeQuote(e){return Gt(()=>this.http.get(Ve,{tokenName:e.tokenName,amount:e.amount,type:e.type,method:e.method}),{errorContext:`Failed to get trade quote for ${e.tokenName}`})}async getPremintQuote(e){return Gt(()=>this.http.get(Xe,{amount:e}),{errorContext:"Failed to get premint quote"})}}class Dd extends _i{constructor(e,t,n,a=!1,s){super(e,t,n,a,s)}async emitTradeExecuted(e,t){this.validateTokenName(e,rn);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,rn);const a={action:"balance_updated",userAddress:e,tokenName:t,payload:n};await this.emitEvent(a)}async emitStreamStatus(e,t,n=!0){this.validateTokenName(e,rn);const a={action:"stream_status",tokenName:e,payload:t,broadcast:n};await this.emitEvent(a)}async emitViewerCount(e,t,n=!1){this.validateTokenName(e,rn);const a={action:"viewer_count",tokenName:e,payload:t,broadcast:n};await this.emitEvent(a)}async emitStreamCountdown(e,t,n=!0){this.validateTokenName(e,rn);const a={action:"stream_countdown",tokenName:e,payload:t,broadcast:n};await this.emitEvent(a)}async emitChatMessage(e,t,n=!1){this.validateTokenName(e,rn);const a={action:"chat_message",tokenName:e,payload:t,broadcast:n};await this.emitEvent(a)}async emitChatStatus(e,t,n=!1){this.validateTokenName(e,rn);const a={action:"chat_status",tokenName:e,payload:t,broadcast:n};await this.emitEvent(a)}async emitTypingIndicator(e,t,n=!1){this.validateTokenName(e,rn);const a={action:"typing_indicator",tokenName:e,payload:t,broadcast:n};await this.emitEvent(a)}async emitTokenBanned(e,t){this.validateTokenName(e,rn);const n={action:"token_banned",tokenName:e,payload:t,broadcast:!0};await this.emitEvent(n)}async emitTokenUnbanned(e,t){this.validateTokenName(e,rn);const n={action:"token_unbanned",tokenName:e,payload:t,broadcast:!0};await this.emitEvent(n)}async emitModeratorAdded(e,t,n=!1){this.validateTokenName(e,rn);const a={action:"moderator_added",tokenName:e,payload:t,broadcast:n};await this.emitEvent(a)}async emitModeratorRemoved(e,t,n=!1){this.validateTokenName(e,rn);const a={action:"moderator_removed",tokenName:e,payload:t,broadcast:n};await this.emitEvent(a)}async emitUserProfileUpdated(e,t){this.validateRequiredString(e,"userAddress","User Address");const n={action:"user_profile_updated",userAddress:e,payload:t};await this.emitEvent(n)}async emitSiteConfigChanged(e){const t={action:"site_config_changed",payload:e,broadcast:!0};await this.emitEvent(t)}async emitFeatureStatus(e){const t={action:"feature_status",payload:e,broadcast:!0};await this.emitEvent(t)}async emitEvent(e){this.validateRequiredString(e.action,"action","Event Action");const t=this.buildEndpoint("/v1/websocket",{});await this.http.post(t,e,this.getDualAuthHeaders())}async getConnectedClients(e){const t=this.buildEndpoint("/v1/connected-clients",{}),n={};void 0!==e?.room&&""!==e.room&&(n.room=e.room),void 0!==e?.tokenName&&(n.tokenName=e.tokenName),void 0!==e?.userAddress&&(n.userAddress=e.userAddress),void 0!==e?.userAddresses&&(n.userAddresses=e.userAddresses),void 0!==e?.authenticated&&(n.authenticated=e.authenticated),void 0!==e?.isOverseer&&(n.isOverseer=e.isOverseer),void 0!==e?.minConnectionSeconds&&(n.minConnectionSeconds=e.minConnectionSeconds),void 0!==e?.offset&&(n.offset=e.offset),void 0!==e?.limit&&(n.limit=e.limit);const a=await this.http.get(t,Object.keys(n).length>0?n:void 0,this.getDualAuthHeaders());return this.extractData(a)}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 St("userAddresses must be a non-empty array");const t=await this.getConnectedClients({userAddresses:e.join(","),limit:e.length}),n=t.clients.filter(e=>"string"==typeof e.address&&""!==e.address).map(e=>e.address);return{online:n,offline:e.filter(e=>!n.includes(e)),clients:t.clients.map(e=>{const t={socketId:e.socketId,rooms:e.rooms};return"string"==typeof e.address&&(t.address=e.address),t})}}async getTokenViewers(e,t){this.validateTokenName(e,rn);const n={tokenName:e};void 0!==t?.authenticated&&(n.authenticated=t.authenticated),void 0!==t?.limit&&(n.limit=t.limit);const a=await this.getConnectedClients(n);return{clients:a.clients,count:a.summary.totalConnected,authenticatedCount:a.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,rn);const n={action:"recording_status",tokenName:e,payload:t};await this.emitEvent(n)}async emitRecordingsCountUpdated(e,t){this.validateTokenName(e,rn);const n={action:"recordings_count_updated",tokenName:e,payload:t};await this.emitEvent(n)}async emitDownloadReady(e,t){this.validateTokenName(e,rn);const n={action:"download_ready",tokenName:e,payload:t};await this.emitEvent(n)}}class _d{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 a=n??this.defaultTtlMs,s={value:t};a>0&&(s.expiresAt=Date.now()+a),this.cache.set(e,s)}has(e){return void 0!==this.get(e)}delete(e){this.cache.delete(e)}clear(){this.cache.clear()}get size(){return this.cache.size}}async function Rd(e,t,n,a={}){const{logger:s,cacheNullish:r=!1,keyGenerator:i}=a,o=i?i(e):String(e),c=n.get(o);if(void 0!==c)return s&&s.debug(`Cache hit for key: ${o}`),c;s&&s.debug(`Cache miss for key: ${o}, fetching...`);const l=await t();return null!=l?(n.set(o,l),s&&s.debug(`Cached result for key: ${o}`)):r&&(n.set(o,l),s&&s.debug(`Cached nullish result for key: ${o}`)),l}class xd extends Jn{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 Tc({maxAttempts:this.config.reconnectAttempts??5,baseDelayMs:this.config.reconnectDelay??2e3}),this.eventBuffer=new _d(3e4),this.isSocketIOAvailable=this.checkSocketIOAvailability(),xd.instances.add(this)}checkSocketIOAvailability(){try{return"function"==typeof h.io||(this.logger.warn('⚠️ Socket.IO client not available. Install "socket.io-client" package.'),!1)}catch(e){return this.logger.warn("⚠️ Socket.IO availability check failed:",e),!1}}async connect(){return new Promise((e,t)=>{Rs(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:",rt(e)),e}this.logger.debug("🔌 Connecting to Socket.IO server:",this.config.url),this.socket=h.io(this.config.url,{transports:["websocket"],reconnection:!0,reconnectionAttempts:this.config.reconnectAttempts??5,reconnectionDelay:this.config.reconnectDelay??2e3}),this.socket.on("connect",()=>{this.logger.debug("✅ Socket.IO connected successfully:",this.socket?.id),this.logger.debug("📡 Connected to bundle backend WebSocket:",this.config.url),this.logger.debug("🔗 Ready to monitor transaction updates"),this.reconnectionManager.reset(),e()}),this.socket.on("connect_error",e=>{this.logger.error("❌ Socket.IO connection error:",e),t(e)}),this.socket.on("disconnect",e=>{this.logger.debug(`🔌 Socket.IO disconnected: ${e}`),this.handleReconnect()}),this.socket.on("error",e=>{this.logger.error("❌ Socket.IO error:",e)}),this.socket.onAny((e,...t)=>{if(""!==e&&t.length>0&&"object"==typeof t[0]&&null!==t[0]){const n=t[0],a=n.status??n.Status;"string"==typeof a&&(this.logger.debug(`📡 [Event Buffer] Buffering event for ${e}: ${a}`),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=st(e)?e:new Error(rt(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 a=this.config.timeout??3e5,s=setTimeout(()=>{if(this.listeners.has(e)){const n=Math.round(a/1e3),s={transactionId:e,status:wi.TIMEOUT,message:`Transaction monitoring timeout - no response after ${n} seconds`,timestamp:Date.now()};this.logger.debug(`📡 Transaction timeout for ${e} (${n}s)`),t(s),this.listeners.delete(e),this.timeouts.delete(e),this.socket?.off(e)}},a);if(this.timeouts.set(e,s),this.socket?.connected)this.socket.off(e),this.logger.debug(`📡 Listening for transaction updates: ${e}`),this.logger.debug(`📡 WebSocket connection ID: ${String(this.socket.id)}`),this.logger.debug(`📡 WebSocket URL: ${this.config.url}`),this.socket.on(e,n=>{this.processTransactionEvent(e,n,t)});else{const n={transactionId:e,status:wi.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 a=t,s=a?.data,r=a?.status??a?.Status??s?.status??s?.Status;let i=a?.message??a?.Message??s?.message??s?.Message??a?.error??s?.error;Pn(i)||(i=r===bi.FAILED||r===bi.ERROR?"Transaction failed - check transaction details":r===bi.COMPLETED||r===bi.PROCESSED||r===bi.SUCCESS?"Transaction completed successfully":null!=r?`Transaction status: ${String(r)}`:"Unknown transaction status");const o=a?.blockHash??s?.blockHash,c=a?.gasUsed??s?.gasUsed,l=a?.Data??s?.Data,d={transactionId:e,status:this.mapSocketStatus(r),message:"string"==typeof i?i:"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(r)} -> ${d.status}`),this.logger.debug(`📡 Final message: "${String(i)}"`),n(d),d.status===wi.COMPLETED||d.status===wi.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===wi.COMPLETED?t(e):e.status!==wi.FAILED&&e.status!==wi.TIMEOUT||n(new Error(`Transaction ${String(e.status)}: ${e.message}`))})})}mapSocketStatus(e){const t=e?.toUpperCase();return Si[t]??wi.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")),xd.instances.delete(this)}static cleanupAll(e=!1){for(const e of xd.instances)e.disconnect();xd.instances.clear()}isConnected(){return this.socket?.connected??!1}getSocket(){return this.socket}}xd.instances=new Set;class Od extends Qn{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 bt("limit must be between 1 and 50","limit","INVALID_LIMIT");this.logger.debug("Fetching weekly challenge leaderboard",{limit:t});const n={limit:String(t)},a=await this.http.get(Qe.GET_LEADERBOARD,n),s=this.extractData(a);return this.logger.debug("Fetched weekly challenge leaderboard",{count:s.count}),{leaderboard:s}}async getTokenHistory(e){const{vaultAddress:t}=e;if("string"!=typeof t||""===t.trim())throw new bt("vaultAddress is required","vaultAddress","REQUIRED_FIELD");this.logger.debug("Fetching token weekly history",{vaultAddress:t});const n=Qe.GET_TOKEN_HISTORY.replace(":vaultAddress",encodeURIComponent(t)),a=await this.http.get(n),s=this.extractData(a);return this.logger.debug("Fetched token weekly history",{count:s.length}),{snapshots:s}}}class Fd extends Yn{constructor(e=!1){super(e),this.lastFetchedAt=null}normalizeKey(e){return Vt(e)}hasItems(){return this.cache.size>0}getAllItems(){return Array.from(this.cache.values())}setAll(e){this.cache.clear();for(const t of e){const e=this.extractKey(t),n=this.normalizeKey(e);this.cache.set(n,t)}this.lastFetchedAt=Date.now(),this.logger.debug(`Cached ${e.length} items`)}merge(e){for(const t of e){const e=this.extractKey(t),n=this.normalizeKey(e);this.cache.set(n,t)}this.lastFetchedAt=Date.now(),this.logger.debug(`Merged ${e.length} items (total: ${this.cache.size})`)}getFetchTimestamp(){return this.lastFetchedAt}clear(){super.clear(),this.lastFetchedAt=null}getByKey(e){const t=this.normalizeKey(e);return this.cache.get(t)}hasKey(e){const t=this.normalizeKey(e);return this.cache.has(t)}buildBaseStats(){return{totalItems:this.cache.size,isPopulated:this.cache.size>0,lastFetchedAt:this.lastFetchedAt}}}class Bd extends Fd{constructor(e=!1){super(e)}extractKey(e){return e.stringifiedTokenClassKey}has(){return this.hasItems()}getAll(){return this.getAllItems()}getByTokenId(e){return this.getByKey(e)}getStats(){const e=this.buildBaseStats();return{...e,tokenCount:e.totalItems}}size(){return this.cache.size}isTokenWrappable(e){return void 0!==this.getByTokenId(e)}getWrapCounterpart(e){const t=this.getByTokenId(e);if(t)return this.getByTokenId(t.wrapCounterpart)}}class Ud extends Vi{constructor(e,t=!1){super(e,t,"WrappableTokenService"),this.cache=new Bd(t)}buildApiParams(e){return{wrappable:!0}}transformApiResponse(e){return e.map(e=>{const t={symbol:e.symbol,name:e.name,decimals:e.decimals,galaChainDescriptor:{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey},stringifiedTokenClassKey:e.stringifiedTokenClassKey,wrapCounterpart:e.wrap,swappable:e.swappable,verified:e.verified};return void 0!==e.channel&&""!==e.channel&&(t.channel=e.channel),void 0!==e.trending&&(t.trending=e.trending),void 0!==e.image&&""!==e.image&&(t.image=e.image),void 0!==e.description&&""!==e.description&&(t.description=e.description),void 0!==e.currentPrices&&(t.currentPrices=e.currentPrices),t})}async fetchWrappableTokens(e={}){const{offset:t=0,limit:n=this.getDefaultLimit()}=e;return this.logger.debug(`Fetching wrappable tokens (offset=${t}, limit=${Math.min(n,this.getMaxLimit())})`),Rs(async()=>{const e=(await this.executePaginatedRequest(t,n)).items;try{0===t?this.cache.setAll(e):this.cache.merge(e)}catch(e){this.logger.error("Cache operation failed (non-fatal):",e)}return{tokens:e,fetchedAt:Date.now(),tokenCount:e.length}},"Failed to fetch wrappable tokens",this.logger)}async fetchAllWrappableTokens(){return Rs(async()=>{const e=await async function(e){const{cache:t,fetchFn:n,logger:a,itemTypeName:s="items"}=e;if(t.has()){const e=t.getAll();return a&&a.debug(`Returning ${e.length} cached ${s}`),{items:e,fetchedAt:t.getFetchTimestamp()??Date.now(),itemCount:e.length}}a&&a.debug(`Fetching all ${s} (no cache)`);const r=await n();try{t.setAll(r)}catch(e){a&&a.error("Cache operation failed (non-fatal):",e)}return{items:r,fetchedAt:Date.now(),itemCount:r.length}}({cache:this.cache,fetchFn:()=>this.autoPaginateFetch(),logger:this.logger,itemTypeName:"wrappable tokens"});return{tokens:e.items,fetchedAt:e.fetchedAt,tokenCount:e.itemCount}},"Failed to fetch wrappable tokens",this.logger)}async getWrappableToken(e){const t=zi(e),n=this.cache.getByTokenId(t);return n||(await Rd("wrappable:all",()=>this.fetchAllWrappableTokens(),{get:()=>this.cache.has()?{}:void 0,set:()=>{}},{logger:this.logger}),this.cache.getByTokenId(t))}async getWrapCounterpart(e){const t=await this.getWrappableToken(e);if(t)return this.getWrappableToken(t.wrapCounterpart)}async isTokenWrappable(e){const t=zi(e);await Rd("wrappable:check",()=>this.fetchAllWrappableTokens(),{get:()=>this.cache.has()?{}:void 0,set:()=>{}},{logger:this.logger});const n=this.cache.getByTokenId(t),a=void 0!==n,s={isWrappable:a,tokenId:t};return a&&(s.wrapCounterpart=n.wrapCounterpart),s}getCacheStats(){return this.cache.getStats()}clearCache(){this.cache.clear()}}class Pd extends Jn{constructor(e){super(!1,e.logger),this.galaConnectClient=e.galaConnectClient,this.wrappableTokenService=e.wrappableTokenService;const t=e.wallet?.privateKey;this.nativeSigner=e.signer??("string"==typeof t?new mo(t):void 0),this.walletAddress=e.walletAddress}async wrapToken(e){return this.executeWrapOrUnwrap(e,!0)}async unwrapToken(e){return this.executeWrapOrUnwrap(e,!1)}async estimateWrapFee(e,t){return this.estimateChannelFee(e,t,!0)}async estimateUnwrapFee(e,t){return this.estimateChannelFee(e,t,!1)}getWrapStatus(e){if(0===e.length)throw Ct("transactionId");return{success:!0,status:"completed",transactionId:e,fromToken:"",toToken:"",amount:"",fromChannel:"",toChannel:""}}async executeWrapOrUnwrap(e,t){const n=await this.getWrappableTokenOrThrow(e.tokenId);if(t?"asset"===n.channel:"asset"!==n.channel){const e=t?"already on asset channel":"not on asset channel",a=t?"unwrapToken()":"wrapToken()",s=t?"ALREADY_ON_ASSET_CHANNEL":"NOT_ON_ASSET_CHANNEL";throw new bt(`Cannot ${t?"wrap":"unwrap"} ${n.symbol} - it's ${e}. Use ${a} instead.`,"tokenId",s)}const a=await this.getCounterpartOrThrow(e.tokenId,n.symbol);return this.executeChannelBridge({sourceToken:n,destinationToken:a,amount:e.amount,...void 0!==e.recipient&&""!==e.recipient&&{recipient:e.recipient},...void 0!==e.memo&&""!==e.memo&&{memo:e.memo},isWrap:t})}async estimateChannelFee(e,t,n){if("string"==typeof e&&0===e.length)throw Ct("tokenId","Token identifier");if(0===t.length)throw Ct("amount");const a=await this.getWrappableTokenOrThrow(e);if(n?"asset"===a.channel:"asset"!==a.channel){const e=n?"already on asset channel":"not on asset channel",t=n?"ALREADY_ON_ASSET_CHANNEL":"NOT_ON_ASSET_CHANNEL";throw new bt(`Cannot ${n?"wrap":"unwrap"} ${a.symbol} - it's ${e}`,"tokenId",t)}const s=this.determineChannelRouting(a,n);return{fee:"0",feeToken:"GALA",authorizationType:s.authType,feeChannel:s.sourceChannel}}async executeChannelBridge(e){const{sourceToken:t,destinationToken:n,amount:a,recipient:s,isWrap:r}=e;if(void 0===this.nativeSigner||void 0===this.walletAddress||0===this.walletAddress.length)throw new bt("Wallet required for wrap/unwrap operations. Initialize SDK with a private key.","wallet","WALLET_REQUIRED");const i=this.walletAddress,o=this.determineChannelRouting(t,r),c=`galaswap-operation-${Ar()}`,l={quantity:a,tokenInstance:{collection:t.galaChainDescriptor.collection,category:t.galaChainDescriptor.category,type:t.galaChainDescriptor.type,additionalKey:t.galaChainDescriptor.additionalKey,instance:"0"},destinationChainId:o.destinationChannelId,recipient:s??i,wrap:!0,uniqueKey:c};return this.logger.debug(`[WrapService] ${r?"Wrap":"Unwrap"} message (pre-signing)`,{amount:a,uniqueKey:c,sourceChannel:o.sourceChannel}),this.executeWrapBridgeRequest({sourceToken:t,destinationToken:n,amount:a,message:l,routing:o,isWrap:r,senderAddress:i})}async executeWrapBridgeRequest(e){const{sourceToken:t,destinationToken:n,amount:a,message:s,routing:r,isWrap:i}=e;try{const e=await this.nativeSigner.signObject("RequestTokenBridgeOut",s);this.logger.debug(`[WrapService] ${i?"Wrap":"Unwrap"} request (signed)`,{sourceToken:t.symbol,destinationToken:n.symbol,amount:a,channel:r.sourceChannel});const o=await this.galaConnectClient.requestBridgeOut(e);if(this.logger.debug("[WrapService] RequestBridgeOut response",{status:o.Status,hasData:"Data"in o}),function(e){return"object"==typeof e&&null!==e&&"Status"in e&&"number"==typeof e.Status&&1!==e.Status}(o)){const e=`Status=${o.Status}`,s="string"==typeof o.Message&&o.Message.length>0?`: ${o.Message}`:"";return{success:!1,fromToken:t.symbol,toToken:n.symbol,amount:a,fromChannel:r.sourceChannel,toChannel:i?"asset":n.channel??"music",error:`GalaChain request failed (${e}${s})`}}if(function(e){return"object"==typeof e&&null!==e&&"Data"in e&&"string"==typeof e.Data}(o)){const e=o.Data;this.logger.debug("[WrapService] Step 1 complete, bridgeRequestId:",e);const s={bridgeFromChannel:r.sourceChannel,bridgeRequestId:e};this.logger.debug("[WrapService] Step 2 - BridgeTokenOut",{bridgeFromChannel:s.bridgeFromChannel});const c=await this.galaConnectClient.bridgeTokenOut(s);return this.logger.debug("[WrapService] BridgeTokenOut response",{status:c.Status,hash:c.Hash}),1!==c.Status?{success:!1,fromToken:t.symbol,toToken:n.symbol,amount:a,fromChannel:r.sourceChannel,toChannel:i?"asset":n.channel??"music",error:`BridgeTokenOut failed: status=${String(c.Status)}`}:{success:!0,transactionId:c.Hash??e,fromToken:t.symbol,toToken:n.symbol,amount:a,fromChannel:r.sourceChannel,toChannel:i?"asset":n.channel??"music",completedAt:Date.now()}}return{success:!1,fromToken:t.symbol,toToken:n.symbol,amount:a,fromChannel:r.sourceChannel,toChannel:i?"asset":n.channel??"music",error:`Unexpected response format from GalaChain (type=${typeof o})`}}catch(e){const s=rt(e);return this.logger.error(`[WrapService] ${i?"Wrap":"Unwrap"} operation failed:`,s),{success:!1,fromToken:t.symbol,toToken:n.symbol,amount:a,fromChannel:r.sourceChannel,toChannel:i?"asset":n.channel??"music",error:s}}}determineChannelRouting(e,t){if(t){return{sourceChannel:e.channel??"music",destinationChannelId:Hs,authType:"cross_channel_authorization"}}return{sourceChannel:"asset",destinationChannelId:qs,authType:"automatic"}}async getCounterpartOrThrow(e,t){const n=await this.wrappableTokenService.getWrapCounterpart(e);if(null==n)throw new bt(`Counterpart token not found for ${t}`,"tokenId","COUNTERPART_NOT_FOUND");return n}async getWrappableTokenOrThrow(e){const t=await this.wrappableTokenService.getWrappableToken(e);if(null==t)throw new bt(`Token not found or not wrappable: ${this.formatTokenId(e)}`,"tokenId","TOKEN_NOT_WRAPPABLE");return t}formatTokenId(e){return"string"==typeof e?e:Ls(e)}}class Md 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}}class Ld{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 $d{constructor(e){this.bundleBaseUrl=Vd(e.bundleBaseUrl),this.launchpadBaseUrl=Vd(e.launchpadBaseUrl),this.signer=e.signer,this.walletAddress=e.walletAddress,this.requestor=e.httpRequestor??fetch.bind(globalThis),this.socketFactory=e.socketFactory??(e=>h.io(e,{transports:["websocket"]}))}async submit(e){let t;try{t=await this.signer.signTypedData(e.method,e.dto)}catch(e){if(e instanceof Md)throw e;const t=e instanceof Error?e.message:"Launchpad signing failed.";throw new Md(t,"LAUNCHPAD_SIGNING_FAILED",{chainMessage:t})}const n=function(e){return Object.fromEntries(Object.entries(e).filter(([e])=>"prefix"!==e))}(t),a=`${this.bundleBaseUrl}/bundle`,s=await this.requestor(a,{method:"POST",headers:{"content-type":"application/json","X-Wallet-Address":this.walletAddress},body:JSON.stringify({stringsInstructions:e.stringsInstructions,method:e.method,signedDto:n})}),r=await zd(s);if(!s.ok)throw Gd(s.status,r,a);const i=function(e){if("string"==typeof e&&""!==e)return e;if(!jd(e))throw new Md("Bundler returned no bundle id.","INVALID_BUNDLE_RESPONSE");const t=e.data,n=e.bundleId;if("string"==typeof t&&""!==t)return t;if(jd(t)&&"string"==typeof t.bundleId&&""!==t.bundleId)return t.bundleId;if("string"==typeof n&&""!==n)return n;throw new Md("Bundler returned no bundle id.","INVALID_BUNDLE_RESPONSE")}(r),o=qd(e.dto,"uniqueKey");return new Ld({bundleId:i,uniqueKey:o,method:e.method,wait:t=>this.waitForResult(e,i,t)})}async waitForResult(e,t,n={}){const a=n.timeoutMs??6e4,s=n.pollIntervalMs??2500,r=Date.now();let i,o,c=!1,l=new Promise(()=>{});try{i=this.socketFactory(this.bundleBaseUrl),l=new Promise((e,n)=>{o=t=>{const a=function(e){if(!jd(e))return;const t=e.status;return"PROCESSED"!==t&&"FAILED"!==t?void 0:{status:t,data:e.data}}(t);void 0===a||c||(c=!0,"FAILED"===a.status?n(Kd(a.data)):e(a))},i?.on(t,o)})}catch{i=void 0}const d=this.pollConfirmation(e,t,r,a,s);try{return await Promise.race([l,d])}finally{c=!0,void 0!==i&&(void 0!==o&&i.off(t,o),i.disconnect())}}async pollConfirmation(e,t,n,a,s){const r="CreateSale"===e.method,i=r?function(e,t){const n=qd(t,"tokenName");return`${e}/v1/tokens/${encodeURIComponent(n)}`}(this.launchpadBaseUrl,e.dto):`${this.bundleBaseUrl}/bundle?id=${encodeURIComponent(t)}`;for(;Date.now()-n<=a;){const e=await this.requestor(i,{method:"GET"}),t=await zd(e);if(r){if(e.ok)return{status:"PROCESSED",data:Hd(t)};if(404!==e.status&&202!==e.status)throw Gd(e.status,t,i)}else{if(!e.ok)throw Gd(e.status,t,i);const n=jd(t)?t.status:void 0;if("COMPLETED"===n||"PROCESSED"===n)return{status:"PROCESSED",data:t};if("FAILED"===n)throw Kd(t)}const o=a-(Date.now()-n);if(o<=0)break;await Xd(Math.min(Math.max(0,s),o))}throw new Md(`Timed out waiting for bundle ${e.dto.uniqueKey}`,"BUNDLE_CONFIRMATION_TIMEOUT",{details:{method:e.method}})}}function Kd(e){const t=Wd(e)??"Launchpad bundle failed on chain.";return new Md(t,"BUNDLE_FAILED",{chainMessage:t})}function Gd(e,t,n){const a=Wd(t)??`Bundle request failed with HTTP ${e}`;return new Md(a,"BUNDLE_REQUEST_FAILED",{status:e,chainMessage:a,details:{body:t,url:n}})}function Wd(e){if("string"==typeof e&&""!==e)return e;if(jd(e))for(const t of["chainMessage","message","Message","error"]){const n=e[t];if("string"==typeof n&&""!==n)return n;if(jd(n)){const e=Wd(n);if(void 0!==e)return e}}}function Hd(e){return jd(e)?e.data??e.Data??e:e}function qd(e,t){const n=e[t];if("string"!=typeof n||""===n)throw new Md(`Missing ${t} in launchpad DTO.`,"INVALID_LAUNCHPAD_DTO");return n}async function zd(e){try{return await e.json()}catch{return e.text()}}function jd(e){return"object"==typeof e&&null!==e}function Vd(e){return e.replace(/\/$/u,"")}function Xd(e){return new Promise(t=>setTimeout(t,e))}function Qd(e){const{collection:t,category:n,type:a}=function(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[a,s,r,i,o,...c]=n.split("$");if(void 0===a||void 0===s||void 0===r||void 0===i||"launchpad"!==o||c.length>0||""===a||""===s||""===r||""===i)throw new Error(`Invalid vaultAddress format (expected service|<collection>$<category>$<type>$<additionalKey>$launchpad): ${e}`);return{collection:a,category:s,type:r,additionalKey:i}}(e),s=`${t}$${n}$${a}$none`,r="GALA$Unit$none$none";return[`$service$${s}$launchpad`,`$tokenBalance$${s}$${e}`,`$tokenBalance$${s}$${e}`,`$tokenBalance$${r}$${e}`,`$tokenBalance$${r}$${e}`]}function Jd(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}`]}class Yd{constructor(e){this.transport=e.transport,this.walletAddress=e.walletAddress}createSale(e){const t=function(e,t){const n={tokenName:e.tokenName,tokenSymbol:e.tokenSymbol,tokenDescription:e.tokenDescription,tokenImage:e.tokenImage,preBuyQuantity: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??Zd(t)};void 0!==e.reverseBondingCurveConfiguration&&(n.reverseBondingCurveConfiguration=e.reverseBondingCurveConfiguration);void 0!==e.saleStartTime&&(n.saleStartTime=e.saleStartTime);return n}(e,this.walletAddress);return this.transport.submit({method:"CreateSale",dto:t,stringsInstructions:Jd(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})}submitTrade(e,t,n){const a={vaultAddress:t.vaultAddress,...n,extraFees:t.extraFees??{maxAcceptableReverseBondingCurveFee:"0"},uniqueKey:t.uniqueKey??Zd(this.walletAddress)};return this.transport.submit({method:e,dto:a,stringsInstructions:Qd(t.vaultAddress)})}}function Zd(e){return`galaswap-operation-${l.v4()}-${Date.now()}-${e}`}class eu{constructor(e){this.gatewayBaseUrl=e.gatewayBaseUrl.replace(/\/$/u,""),this.signer=e.signer,this.walletAddress=ou(e.walletAddress),this.requestor=e.httpRequestor??fetch.bind(globalThis)}transfer(e){const t=tu(e),n={from:this.walletAddress,to:ou(e.to),quantity:e.quantity,tokenInstance:t,uniqueKey:e.uniqueKey??iu(this.walletAddress)};return this.direct("TransferToken",n)}burn(e){const t={tokenInstances:[{quantity:e.quantity,tokenInstanceKey:tu(e)}],uniqueKey:e.uniqueKey??iu(this.walletAddress)};return this.direct("BurnTokens",t)}lock(e){const t={lockAuthority:e.lockAuthority??this.walletAddress,tokenInstances:[{owner:this.walletAddress,quantity:e.quantity,tokenInstanceKey:tu(e)}],uniqueKey:e.uniqueKey??iu(this.walletAddress)};return void 0!==e.expires&&(t.expires=e.expires),void 0!==e.name&&(t.name=e.name),this.direct("LockToken",t)}unlock(e){const t={tokenInstances:[{owner:this.walletAddress,quantity:e.quantity,tokenInstanceKey:tu(e)}],uniqueKey:e.uniqueKey??iu(this.walletAddress)};return void 0!==e.name&&(t.name=e.name),this.direct("UnlockToken",t)}async direct(e,t){const n=await this.signNative(e,t),a=`${this.gatewayBaseUrl}/api/asset/token-contract/${e}`,s=await this.post(a,n),r=await async function(e){try{return await e.json()}catch{return e.text()}}(s),i=ru(r);if(!s.ok||void 0!==i?.Status&&1!==i.Status)throw function(e,t,n){const a=ru(t),s=su(a,"Message")??su(a,"message")??su(a,"ErrorKey")??`Gateway request failed with HTTP ${e}`,r=su(a,"ErrorKey")??"GATEWAY_REQUEST_FAILED";return new Md(s,r,{status:e,chainMessage:s,details:{body:t,url:n}})}(s.status,r,a);const o=ru(nu(r))?.mode??i?.mode;if(void 0!==o&&"sync"!==o){throw new Md(`Unsupported gateway transaction mode: ${"string"==typeof o?o:"non-sync"}`,"INVALID_GATEWAY_RESPONSE",{status:s.status,details:{body:r,url:a}})}const c=nu(r),l=cu(s,"x-transaction-id")??au(c)??au(r),d=function(e){const t=cu(e,"x-block-number");if(void 0===t)return;const n=Number.parseInt(t,10);return Number.isFinite(n)?n:void 0}(s);return{status:"PROCESSED",data:c,...void 0!==l&&{transactionId:l},...void 0!==d&&{blockNumber:d}}}post(e,t){return this.requestor(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)})}async signNative(e,t){try{return await this.signer.signObject(e,t)}catch(e){if(e instanceof Md)throw e;const t=e instanceof Error?e.message:"Native GalaChain signing failed.";throw new Md(t,"NATIVE_SIGNING_FAILED",{chainMessage:t})}}}function tu(e){const t=e.tokenClassKey??e.symbol;if(void 0===t)throw new Md("tokenClassKey or symbol is required.","INVALID_TOKEN_IDENTIFIER");const n=function(e){if("string"!=typeof e)return e;const t=e.includes("|")?"|":e.includes("$")?"$":void 0;if(void 0===t)return"GALA"===e.toUpperCase()?{collection:"GALA",category:"Unit",type:"none",additionalKey:"none"}:{collection:"Token",category:"Unit",type:e,additionalKey:"none"};const[n,a,s,r]=e.split(t);if(void 0===n||void 0===a||void 0===s||void 0===r||[n,a,s,r].some(e=>""===e))throw new Md(`Invalid token class key: ${e}`,"INVALID_TOKEN_IDENTIFIER");return{collection:n,category:a,type:s,additionalKey:r}}(t);return{...n,instance:e.instance??"0"}}function nu(e){const t=ru(e);return t?.Data??t?.data??e}function au(e){if("string"==typeof e&&""!==e)return e;const t=ru(e);return su(t,"transactionId")??su(t,"txnId")??su(t,"id")}function su(e,t){const n=e?.[t];return"string"==typeof n&&""!==n?n:void 0}function ru(e){return"object"==typeof e&&null!==e?e:void 0}function iu(e){return`galaswap-operation-${l.v4()}-${Date.now()}-${e}`}function ou(e){return"eth|0x"===e.slice(0,6).toLowerCase()?`eth|${e.slice(6)}`:e}function cu(e,t){const n=e.headers;if(void 0===n)return;if("function"==typeof n.get)return lu(n.get(t));const a=t.toLowerCase();for(const[e,t]of Object.entries(n))if(e.toLowerCase()===a)return lu(t)}function lu(e){const t=e?.trim();return void 0===t||""===t?void 0:t}function du(e,t=3e4){return g.create({baseURL:e,timeout:t,headers:{"Content-Type":"application/json"}})}const uu=new Set(["accesstoken","refreshtoken","token","password","privatekey","secret","apikey","api_key","rawkey","authorization","x-api-key","bearer","streamadminapikey","userapikey","signature","signedpayload"]);function hu(e,t=0){if(t>5)return"[...]";if(null==e)return e;if(Array.isArray(e))return e.map(e=>hu(e,t+1));if(e instanceof Map){const n={};for(const[a,s]of e.entries()){const e=String(a);n[e]=uu.has(e.toLowerCase())?"[REDACTED]":hu(s,t+1)}return n}if("object"==typeof e){const n={};for(const[a,s]of Object.entries(e))n[a]=uu.has(a.toLowerCase())?"[REDACTED]":hu(s,t+1);return n}return e}class gu{constructor(e,t={}){this.auth=e,this.debug=t.debug??!1,this.logger=new Jt({debug:this.debug,context:"HttpClient"});const n=t.baseUrl??Ms("stage").launchpadBaseUrl,a=t.timeout??6e4;this.axios=du(n,a),t.headers&&(this.axios.defaults.headers.common={...this.axios.defaults.headers.common,...t.headers}),this.setupInterceptors()}async request(e){return(await this.requestWithMeta(e)).data}async requestWithMeta(e){return Rs(async()=>{const t={method:e.method,url:e.url,data:e.data,...void 0!==e.params&&{params:ns(e.params)},...void 0!==e.headers&&{headers:e.headers},...void 0!==e.timeout&&{timeout:e.timeout},...void 0!==e.signal&&{signal:e.signal}};e.data instanceof FormData&&(void 0!==t.headers&&"Content-Type"in t.headers&&delete t.headers["Content-Type"],this.logger.debug("FormData detected - removing Content-Type header for multipart upload")),e.headers&&this.logger.debug("Custom headers provided:",Object.keys(t.headers??{}));const n=e.data instanceof FormData?"[FormData object - multipart/form-data]":hu(e.data);this.logger.debug("Request:",{method:e.method,url:e.url?.split("?")[0],baseURL:this.axios.defaults.baseURL,params:hu(t.params),data:n,isFormData:e.data instanceof FormData,contentType:t.headers?.["Content-Type"]??"not set"});const a=await this.axios.request(t),s=function(e){const t={};if(null==e||"object"!=typeof e)return t;for(const[n,a]of Object.entries(e))"string"==typeof a?t[n.toLowerCase()]=a:"number"!=typeof a&&"boolean"!=typeof a||(t[n.toLowerCase()]=String(a));return t}(a.headers);return this.logger.debug("Response:",{status:a.status,data:hu(a.data),transactionId:s["x-transaction-id"],blockNumber:s["x-block-number"]}),{data:a.data,headers:s,status:a.status}},`HTTP ${e.method} ${e.url}`,this.logger)}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 Rs(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.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("No wallet configured - skipping signature header");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,a={message:n?.message??rt(e),...n&&Boolean(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=a,this.logger.error("Backend error:",a)}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 mu extends Error{constructor(e,t){super(e),this.cause=t,this.name="WebSocketError"}}class pu 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 fu(e,t){if(Mn(e))throw new mu(`Invalid WebSocket response received for transaction ${t}: response is null or undefined`);if("object"!=typeof e)throw new mu(`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 mu(`Invalid WebSocket response received for transaction ${t}: missing status field`)}function yu(e,t,n,a){fu(e,t);const s=e,r=s.data??{};if(!function(e){if(Mn(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)}(r))throw new mu(`Invalid trade data received for transaction ${t}`);const i={transactionId:t,type:n,method:"native"===a.type?"native":"exact",inputAmount:r.inputQuantity??a.amount,outputAmount:r.outputQuantity??a.expectedAmount??"0",totalFees:r.totalFees??"0",tokenName:a.tokenName,vaultAddress:r.vaultAddress??"",timestamp:Date.now()};return void 0!==s.blockHash&&(i.blockHash=s.blockHash),void 0!==s.gasUsed&&(i.gasUsed=s.gasUsed),void 0!==a.slippageToleranceFactor&&(i.slippageTolerance=a.slippageToleranceFactor),i}function vu(e){if(e&&function(e){return"privateKey"===e.providerType}(e))return e.getWallet()}class ku{constructor(e){let t,a;e.walletProvider?(t=e.walletProvider,a=vu(e.walletProvider)):e.wallet&&(a=e.wallet,t=Bs.fromWallet(e.wallet)),this.wallet=a;const s=e.env??"prod",r=Ms(s);this.environment=s,this.config={baseUrl:e.launchpadBaseUrl??r.launchpadBaseUrl,gatewayBaseUrl:r.gatewayBaseUrl,bundleBaseUrl:r.bundleBaseUrl,webSocketUrl:r.webSocketUrl,gdexWebSocketUrl:r.gdexWebSocketUrl,dexApiBaseUrl:r.dexApiBaseUrl,dexBackendBaseUrl:r.dexBackendBaseUrl,launchpadFrontendUrl:r.launchpadFrontendUrl,timeout:3e4,debug:!1,...e};const i=e.signer??(void 0!==a?new mo(a.privateKey):void 0),o=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."))},c=e.walletAddress??e.galaChainAddress??(void 0!==a?`eth|${a.address.slice(2)}`:function(e){if(void 0===e||!("walletAddress"in e))return;const t=e.walletAddress;return"string"==typeof t&&""!==t?t:void 0}(i))??"",l=new $d({bundleBaseUrl:this.config.bundleBaseUrl,launchpadBaseUrl:this.config.baseUrl,signer:o,walletAddress:c,...void 0!==e.httpRequestor&&{httpRequestor:e.httpRequestor}});if(this.launchpad=new Yd({transport:l,walletAddress:c}),this.tokens=new eu({gatewayBaseUrl:this.config.gatewayBaseUrl,dexBackendBaseUrl:this.config.dexBackendBaseUrl,signer:o,walletAddress:c,...void 0!==e.httpRequestor&&{httpRequestor:e.httpRequestor}}),this.logger=new Jt({debug:this.config.debug??!1,context:"LaunchpadSDK"}),this.validateConfiguration(),this.slippageToleranceFactor=void 0===e.slippageToleranceFactor?ku.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR:this.parseSlippageToleranceFactor(e.slippageToleranceFactor),this.maxAcceptableReverseBondingCurveFeeSlippageFactor=void 0===e.maxAcceptableReverseBondingCurveFeeSlippageFactor?ku.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR:this.parseFeeSlippageFactor(e.maxAcceptableReverseBondingCurveFeeSlippageFactor),this.calculateAmountMode=e.calculateAmountMode??ku.DEFAULT_CALCULATE_AMOUNT_MODE,this.galaChainAddressOverride=e.galaChainAddress,this.auth=new Us({wallet:a,walletProvider:t,messagePrefix:"Create a GalaChain Wallet"}),this.jwtAuth=new _s,void 0!==e.accessToken&&""!==e.accessToken){const t=e.accessTokenExpiresIn??86400;this.jwtAuth.setToken(e.accessToken,t)}this.http=new gu(this.auth,this.config),this.sessionAuth=new Os(this.http,this.auth,this.jwtAuth,e.debug??!1),this.galaChainHttp=new gu(this.auth,{...this.config,baseUrl:this.config.gatewayBaseUrl}),this.bundleHttp=new gu(this.auth,{...this.config,baseUrl:this.config.bundleBaseUrl}),this.dexApiHttp=new gu(this.auth,{...this.config,baseUrl:this.config.dexApiBaseUrl}),this.dexBackendHttp=new gu(this.auth,{...this.config,baseUrl:this.config.dexBackendBaseUrl}),this.galaChainPublicAxios=du(this.config.gatewayBaseUrl,this.config.timeout??3e4),this.cache=new Zn(e.debug??!1),this.launchpadService=new Kc(this.http,this.jwtAuth),this.tokenResolverService=new Nd(this.launchpadService.poolService),this.launchpadAPI=new ws(this.http,this.tokenResolverService,this.logger,this.bundleHttp,this.galaChainHttp,this.dexApiHttp,this.calculateAmountMode,this.launchpad),this.galaChainService=new Ec(this.galaChainHttp,a,this.tokenResolverService,e.debug??!1,this.galaChainPublicAxios),this.dexService=new Po(this.dexBackendHttp,this.cache,this.galaChainService,e.debug??!1),this.bundleService=new wo(this.bundleHttp,this.tokenResolverService,this.config.debug??!1,a,a?this.getAddress():void 0,this.slippageToleranceFactor,this.maxAcceptableReverseBondingCurveFeeSlippageFactor),this.websocketService=new xd({url:this.config.webSocketUrl},this.config.debug),this.priceHistoryService=new ml(this.dexBackendHttp,this.config.debug??!1,this.tokenResolverService);const d=e.signer??(void 0===a?void 0:new mo(a.privateKey)),u=e.walletAddress??(void 0===a?void 0:this.getAddress());this.dexClient=new n.GSwap({env:this.environment,...void 0===d?{}:{signer:d},...void 0===u?{}:{walletAddress:u},...void 0===this.config.dexBackendBaseUrl?{}:{dexBackendBaseUrl:this.config.dexBackendBaseUrl},...void 0===this.config.gatewayBaseUrl?{}:{gatewayBaseUrl:this.config.gatewayBaseUrl},...void 0===e.httpRequestor?{}:{httpRequestor:e.httpRequestor}}),this.nftCollectionService=new tl(this.galaChainHttp),this.tradingQuotesService=new Id(this.http,e.debug??!1)}createOverrideSdk(e){if(!Pn(e))throw Dt("Invalid privateKey: must be a non-empty string","privateKey");if(!e.match(/^0x[a-fA-F0-9]{64}$/))throw Dt('Invalid privateKey format: must be "0x" followed by 64 hexadecimal characters',"privateKey");const n=new t.Wallet(e),a={...this.config,wallet:n};return new ku(a)}get dex(){return this.dexClient}getAddress(){return void 0!==this.galaChainAddressOverride&&""!==this.galaChainAddressOverride?this.galaChainAddressOverride:(this.validateWallet(),this.auth.getAddress())}getEthereumAddress(){return this.validateWallet(),this.wallet.address}validateWallet(){if(!this.wallet)throw Ct("wallet","Wallet");return this.wallet}setWallet(e){if(null==e||"object"!=typeof e||!("address"in e))throw new bt("Invalid wallet: must be an ethers Wallet instance, received "+typeof e,"wallet","INVALID_WALLET");this.wallet=e,this.auth.setWallet(e)}setWalletProvider(e){this.auth.setWalletProvider(e),this.wallet=e?vu(e):void 0}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:a,streamAdminApiKey:s,userApiKey:r,accessToken:i,headers:o,...c}=this.config;return{...c,...void 0!==s&&{streamAdminApiKey:"[REDACTED]"},...void 0!==r&&{userApiKey:"[REDACTED]"},...void 0!==i&&{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:zt.GAS_FEE}}getVersion(){return Ai}getUrlByTokenName(e){const t=this.config.launchpadFrontendUrl;if(void 0===t||""===t)throw Dt("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),a=Math.min(t,100);return n.holders.slice(0,a).map((e,t)=>({...e,rank:t+1}))}async getHolderCount(e){const t=await this.fetchTokenDistribution(e);return{count:t.totalHolders,totalBalance:t.totalSupply}}async getHolderRank(e,t){const n=await this.fetchTokenDistribution(e),a=n.holders.findIndex(e=>e.address.toLowerCase()===t.toLowerCase());if(-1===a)return null;const s=n.holders[a];return void 0===s?null:{rank:a+1,balance:s.balance,holderCount:n.totalHolders}}async getHoldersByBalance(e,t){const n=await this.fetchTokenDistribution(e),a=t?.minBalance??0,s=t?.maxBalance??1/0,r=Math.min(t?.limit??100,1e3),i=new Map;return n.holders.forEach((e,t)=>{i.set(e.address,t+1)}),n.holders.filter(e=>{const t=parseFloat(e.balance);return t>=a&&t<=s}).map(e=>({...e,rank:i.get(e.address)??0})).slice(0,r)}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{tokenName:t,tokenId:n}=e,{hasA:a}=Gn(e,"tokenName","tokenId",{description:"token identifier"});if(a&&void 0!==t&&""!==t)return this.dexService.fetchLaunchpadTokenSpotPrice(t,e=>this.launchpadAPI.calculateBuyAmount(e),e=>this.fetchPoolDetails(e));const s=n;try{return await this.dexService.fetchTokenPrice({tokenId:s})}catch(e){const t=function(e){if(ct(e)&&e.response)return e.response.status}(e);if(400===t||404===t){this.logger.debug(`DEX spot price not available (HTTP ${t}) for tokenId, attempting launchpad fallback`);try{const t=jt((await this.fetchTokenDetails(s)).name);if(!/^[a-z0-9]{3,20}$/.test(t))throw this.logger.error(`Token name extracted from GalaChain doesn't match launchpad format: "${t}"`),e;return this.logger.debug(`Falling back to launchpad pricing using extracted token name: "${t}"`),this.dexService.fetchLaunchpadTokenSpotPrice(t,e=>this.launchpadAPI.calculateBuyAmount(e),e=>this.fetchPoolDetails(e))}catch(t){throw this.logger.error(`Launchpad fallback failed: ${rt(t)}`),e}}throw e}}async fetchGalaPrice(){return this.fetchTokenPrice({tokenId:{collection:"GALA",category:"Unit",type:"none",additionalKey:"none"}})}async fetchTokenDetails(e){return this.dexService.fetchTokenDetails(e)}async fetchAllDexSeasons(){return this.dexService.fetchAllDexSeasons()}async fetchCurrentDexSeason(){return this.dexService.fetchCurrentDexSeason()}async fetchDexLeaderboardBySeasonId(e){return this.dexService.fetchDexLeaderboardBySeasonId(e)}async fetchCurrentDexLeaderboard(){return this.dexService.fetchCurrentDexLeaderboard()}async fetchDexAggregatedVolumeSummary(){return this.dexService.fetchDexAggregatedVolumeSummary()}async fetchLaunchTokenFee(){return this.galaChainService.fetchLaunchTokenFee()}async fetchTokenClassesWithSupply(e){return this.galaChainService.fetchTokenClassesWithSupply(e)}async fetchPoolDetails(e){const t=await this.resolveVaultAddress(e);if(null==t)throw new Error(gt(e));const n=(await this.galaChainService.fetchPoolDetails({vaultAddress:t})).Data,a=await this.launchpadAPI.fetchPoolDetailsForCalculation(e);return n.currentSupply=a.currentSupply,n.reverseBondingCurveMaxFeeFactor=a.reverseBondingCurveMaxFeeFactor,n.reverseBondingCurveMinFeeFactor=a.reverseBondingCurveMinFeeFactor,n.reverseBondingCurveNetFeeFactor=a.reverseBondingCurveNetFeeFactor,n.tokenName=e,n}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 da}),n=t(e)??this.getAddress();return this.galaChainService.fetchGalaBalance({owner:n,collection:"GALA",category:"Unit",additionalKey:"none",type:"none",instance:"0"})}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=e?.solanaPrivateKey??globalThis.process?.env.SOLANA_PRIVATE_KEY;this._bridgeService=new ki({galaConnectBaseUrl:this.config.dexApiBaseUrl,galaChainWalletAddress:this.getAddress(),ethereumPrivateKey:e?.ethereumPrivateKey??t.privateKey,...void 0!==n&&""!==n?{solanaPrivateKey:n}:{},bridgeableTokenService:this.getBridgeableTokenService(),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(){return this._bridgeableTokenService??(this._bridgeableTokenService=new Yi(this.dexApiHttp,this.config.debug??!1)),this._bridgeableTokenService}getWrappableTokenService(){return this._wrappableTokenService??(this._wrappableTokenService=new Ud(this.dexApiHttp,this.config.debug??!1)),this._wrappableTokenService}getGalaConnectClient(){if(null===this._galaConnectClient||void 0===this._galaConnectClient){const e=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 di({baseUrl:this.config.dexApiBaseUrl,...void 0!==this.config.gatewayBaseUrl&&""!==this.config.gatewayBaseUrl?{galachainBaseUrl:this.config.gatewayBaseUrl}:{},walletAddress:e})}return this._galaConnectClient}getWrapService(){if(!this._wrapService){const e=this.getWallet();this._wrapService=new Pd({galaConnectClient:this.getGalaConnectClient(),wrappableTokenService:this.getWrappableTokenService(),...e&&{walletAddress:this.getAddress(),wallet:e}})}return this._wrapService}getStreamingService(){return this._streamingService??(this._streamingService=new Sl(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._streamingService}getStreamChatService(){return this._streamChatService??(this._streamChatService=new fl(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._streamChatService}getBanService(){return this._banService??(this._banService=new Li(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._banService}getTokenBanService(){return this._tokenBanService??(this._tokenBanService=new Cd(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._tokenBanService}getAIModerationService(){return this._aiModerationService??(this._aiModerationService=new Ri(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._aiModerationService}getWeeklyChallengeService(){return this._weeklyChallengeService??(this._weeklyChallengeService=new Od(this.http,this.config.debug??!1)),this._weeklyChallengeService}getOEmbedService(){return this._oembedService??(this._oembedService=new al(this.http,this.config.debug??!1)),this._oembedService}getPlatformStatsService(){return this._platformStatsService??(this._platformStatsService=new gl(this.http,this.config.debug??!1)),this._platformStatsService}getNotificationService(){return this._notificationService??(this._notificationService=new nl(this.http,this.config.debug??!1,this.jwtAuth)),this._notificationService}getClientConfigService(){return this._clientConfigService??(this._clientConfigService=new So(this.http,this.config.debug??!1)),this._clientConfigService}getApiKeyService(){return this._apiKeyService??(this._apiKeyService=new Bi(this.http,this.jwtAuth,this.config.debug??!1)),this._apiKeyService}getModeratorService(){return this._moderatorService??(this._moderatorService=new jc(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._moderatorService}getFlagService(){return this._flagService??(this._flagService=new Fo(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._flagService}getOverseerService(){return this._overseerService??(this._overseerService=new ul(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._overseerService}getWebSocketAdminService(){return this._websocketAdminService??(this._websocketAdminService=new Dd(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._websocketAdminService}getContentReactionService(){return this._contentReactionService??(this._contentReactionService=new Uo(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._contentReactionService}toLegacyPinnedMessage(e){return{messageId:e.id,content:e.content,userAddress:e.userAddress,pinnedBy:""!==e.pinnedBy?e.pinnedBy:e.userAddress,pinnedAt:""!==e.pinnedAt?e.pinnedAt:e.createdAt}}buildMessageFetchOptions(e,t){return{type:t,...void 0!==e.tokenName&&{tokenName:e.tokenName},...void 0!==e.userAddress&&{userAddress:e.userAddress},...void 0!==e.cursor&&{cursor:e.cursor},...void 0!==e.pageSize&&{pageSize:e.pageSize}}}async resolveReferralAddress(e){if(void 0===e||""===e)return this.getAddress();if(e.startsWith("client|"))return e;const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return da}),n=t(e);if(void 0===n)throw new bt(`Invalid address format: "${e}". Expected formats: eth|0x..., 0x..., or client|...`);return n}getMessagesService(){return this._messagesService??(this._messagesService=new Gc(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._messagesService}getRestrictedNamesService(){return this._restrictedNamesService??(this._restrictedNamesService=new pl(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.userApiKey)),this._restrictedNamesService}getPlatformConfigService(){return this._platformConfigService??(this._platformConfigService=new hl(this.http,this.jwtAuth,this.config.debug??!1)),this._platformConfigService}getEventsBatcherService(){return this._eventsBatcherService??(this._eventsBatcherService=new Ho(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 Ed({url:this.config.streamWebSocketUrl},this.config.debug??!1)}return this._streamWebSocketService}getGdexStreamService(){return this._gdexStreamService??(this._gdexStreamService=new Nc({url:this.config.gdexWebSocketUrl})),this._gdexStreamService}getStreamingEventService(){return this._streamingEventService??(this._streamingEventService=new yl(this.config.debug??!1)),this._streamingEventService}async fetchEthereumWalletTokenBalance(e,t){return this.getBridgeService().fetchEthereumWalletTokenBalance(e,t)}async fetchEthereumWalletNativeBalance(e){return this.getBridgeService().fetchEthereumWalletNativeBalance(e)}async fetchSolanaWalletTokenBalance(e,t){return this.getBridgeService().fetchSolanaWalletTokenBalance(e,t)}async fetchSolanaWalletNativeBalance(e){return this.getBridgeService().fetchSolanaWalletNativeBalance(e)}async requestSolanaDevnetAirdrop(e,t){return this.getBridgeService().requestSolanaDevnetAirdrop(e,t)}async getSolanaTransactionStatus(e){return this.getBridgeService().getSolanaTransactionStatus(e)}async getEthereumTransactionStatus(e){return this.getBridgeService().getEthereumTransactionStatus(e)}async fetchEthereumWalletAllBalances(e){return this.getBridgeService().fetchEthereumWalletAllBalances(e)}async fetchSolanaWalletAllBalances(e){return this.getBridgeService().fetchSolanaWalletAllBalances(e)}async fetchBridgeableTokensByNetwork(e){return this.getBridgeableTokenService().fetchBridgeableTokensByNetwork(e)}async fetchAllBridgeableTokensByNetwork(e){return this.getBridgeableTokenService().fetchAllBridgeableTokensByNetwork(e)}async fetchAllTokensBridgeableToEthereum(){return this.getBridgeableTokenService().fetchAllTokensBridgeableToEthereum()}async fetchAllTokensBridgeableToSolana(){return this.getBridgeableTokenService().fetchAllTokensBridgeableToSolana()}async isTokenBridgeableToNetwork(e){return this.getBridgeableTokenService().isTokenBridgeableToNetwork(e)}async isTokenBridgeableToEthereum(e){return this.getBridgeableTokenService().isTokenBridgeableToEthereum(e)}async isTokenBridgeableToSolana(e){return this.getBridgeableTokenService().isTokenBridgeableToSolana(e)}async fetchWrappableTokens(e={}){return this.getWrappableTokenService().fetchWrappableTokens(e)}async fetchAllWrappableTokens(){return this.getWrappableTokenService().fetchAllWrappableTokens()}async getWrappableToken(e){return this.getWrappableTokenService().getWrappableToken(e)}async getWrapCounterpart(e){return this.getWrappableTokenService().getWrapCounterpart(e)}async isTokenWrappable(e){return this.getWrappableTokenService().isTokenWrappable(e)}async wrapToken(e){return this.getWrapService().wrapToken(e)}async unwrapToken(e){return this.getWrapService().unwrapToken(e)}async estimateWrapFee(e,t){return this.getWrapService().estimateWrapFee(e,t)}async estimateUnwrapFee(e,t){return this.getWrapService().estimateUnwrapFee(e,t)}getWrapStatus(e){return this.getWrapService().getWrapStatus(e)}async login(){return this.sessionAuth.login()}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 disableChat(e){return this.getStreamChatService().disableChat(e)}async enableChat(e){return this.getStreamChatService().enableChat(e)}async getPinnedChatMessage(e){const t=this.getMessagesService(),n=await t.getPinnedMessage(e);return{tokenName:e,pinnedMessage:null===n.message?null:this.toLegacyPinnedMessage(n.message)}}async pinChatMessage(e,t){const n=this.getMessagesService();await n.pinMessage(t);const a=await n.getPinnedMessage(e);return{tokenName:e,pinnedMessage:null===a.message?null:this.toLegacyPinnedMessage(a.message)}}async unpinChatMessage(e){const t=this.getMessagesService(),n=await t.getPinnedMessage(e);return n.message?(await t.unpinMessage(n.message.id),{tokenName:e,unpinned:!0,unpinnedMessageId:n.message.id}):{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 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 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 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})).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})).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 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 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.setGlobalCallbacks(e)}async authenticateStreamWebSocket(){const e=this.getStreamWebSocketService(),t=await this.ensureValidToken();e.authenticate(t)}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.getStreamingEventService().onStreamStatusChanged(e)}onUserBanned(e){return this.getStreamingEventService().onUserBanned(e)}onUserUnbanned(e){return this.getStreamingEventService().onUserUnbanned(e)}onBanEnforcement(e){return this.getStreamingEventService().onBanEnforcement(e)}onContentFlagged(e){return this.getStreamingEventService().onContentFlagged(e)}onFlagResolved(e){return this.getStreamingEventService().onFlagResolved(e)}onStreamChatMessage(e){return this.getStreamingEventService().onStreamChatMessage(e)}onStreamChatUpdated(e){return this.getStreamingEventService().onStreamChatUpdated(e)}onStreamChatDeleted(e){return this.getStreamingEventService().onStreamChatDeleted(e)}onStreamChatPinned(e){return this.getStreamingEventService().onStreamChatPinned(e)}onStreamChatUnpinned(e){return this.getStreamingEventService().onStreamChatUnpinned(e)}onChatStatusChanged(e){return this.getStreamingEventService().onChatStatusChanged(e)}onViewerCountChanged(e){return this.getStreamingEventService().onViewerCountChanged(e)}onRecordingStatusChanged(e){return this.getStreamingEventService().onRecordingStatusChanged(e)}onSimulcastStatusChanged(e){return this.getStreamingEventService().onSimulcastStatusChanged(e)}onDownloadReady(e){return this.getStreamingEventService().onDownloadReady(e)}onRecordingsCountUpdated(e){return this.getStreamingEventService().onRecordingsCountUpdated(e)}onUserTyping(e){return this.getStreamingEventService().onUserTyping(e)}onStreamReaction(e){return this.getStreamingEventService().onStreamReaction(e)}onContentReactionAdded(e){return this.getStreamingEventService().onContentReactionAdded(e)}onContentReactionRemoved(e){return this.getStreamingEventService().onContentReactionRemoved(e)}onStreamCountdownUpdated(e){return this.getStreamingEventService().onStreamCountdownUpdated(e)}onStreamLanguageUpdated(e){return this.getStreamingEventService().onStreamLanguageUpdated(e)}onStreamControlStatusChanged(e){return this.getStreamingEventService().onStreamControlStatusChanged(e)}onConnection(e){return this.getStreamingEventService().onConnection(e)}onAuthenticated(e){return this.getStreamingEventService().onAuthenticated(e)}onTokenSubscribed(e){return this.getStreamingEventService().onTokenSubscribed(e)}onTokenUnsubscribed(e){return this.getStreamingEventService().onTokenUnsubscribed(e)}onRoomSubscribed(e){return this.getStreamingEventService().onRoomSubscribed(e)}onRoomLeft(e){return this.getStreamingEventService().onRoomLeft(e)}onEngagementStatsUpdated(e){return this.getStreamWebSocketService().subscribeEngagementStatsUpdated(e)}async estimateBridgeFee(e){return this.getBridgeService().estimateBridgeFee(e)}async bridgeOut(e){return this.getBridgeService().bridgeOut(e)}async bridgeIn(e){return this.getBridgeService().bridgeIn(e)}async getBridgeStatus(e,t){return this.getBridgeService().getBridgeStatus(e,t)}getSupportedBridgeTokens(){const e=this.getBridgeService(),t=e.getSupportedBridgeTokens();return Promise.resolve({tokens:t,totalCount:t.length,supportedChains:e.getSupportedBridgeChains()})}async fetchTokenBalance(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return da}),n=t(e.address);if(void 0!==e.tokenId&&""!==e.tokenId){const{normalizeToTokenInstanceKey:t}=await Promise.resolve().then(function(){return ji}),a=t(e.tokenId),{collection:s,category:r,type:i,additionalKey:o}=a;return this.galaChainService.fetchTokenBalance({owner:n,collection:s,category:r,additionalKey:o,type:i,instance:"0"},e.withExpired??!1)}if(void 0!==e.tokenName&&""!==e.tokenName){const t=Xt(e.tokenName);if("MUSIC"===t||"GMUSIC"===t){const a=`$${t}`;return this.galaChainService.fetchTokenBalance({owner:n,collection:a,category:"Unit",additionalKey:"none",type:"none",instance:"0"},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 a=t.collection??"Token",s={collection:a,category:"Unit",type:t.symbol,additionalKey:"none"};return{quantity:t.balance,collection:a,category:"Unit",tokenId:Ls(s)}}throw Ct("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:a,privateKey:s,calculateAmountMode:r,currentSupply:i}=e;let o=t;void 0===r&&void 0===i||(o={tokenName:t,...void 0!==r&&{calculateAmountMode:r},...void 0!==i&&{currentSupply:i}});const c=await this.calculateBuyAmountForGraduation(o),l={tokenName:t,amount:c.amount,type:"exact",expectedAmount:c.amount,maxAcceptableReverseBondingCurveFee:c.reverseBondingCurveFee,slippageToleranceFactor:this.slippageToleranceFactor};return void 0!==n&&(l.slippageToleranceFactor=n),void 0!==a&&(l.maxAcceptableReverseBondingCurveFeeSlippageFactor=a),void 0!==s&&(l.privateKey=s),await this.buy(l)}async calculateInitialBuyAmount(e){const t={nativeTokenQuantity:e};return this.launchpadAPI.calculateInitialBuyAmount(t)}async buy(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...a}=e;return t.buy(a)}this.validateWallet(),await this.ensureWebSocketConnection();const t=(await this.bundleService.buyToken(e)).data,n=t?.transactionId;if(void 0===n||""===n)throw _t("No transaction ID returned from buy operation");return this.waitForConfirmation(n,t=>yu(t,n,"buy",e))}async sell(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...a}=e;return t.sell(a)}this.validateWallet(),await this.ensureWebSocketConnection();const t=(await this.bundleService.sellToken(e)).data,n=t?.transactionId;if(void 0===n||""===n)throw _t("No transaction ID returned from sell operation");return this.waitForConfirmation(n,t=>yu(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,...a}=e;return t.launchToken(a)}this.validateWallet(),await this.ensureWebSocketConnection();const t=await this.launchpadAPI.launchToken(e);return this.waitForConfirmation(t,n=>{fu(n,t);const a=n.data??{};if(!function(e){if(Mn(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)}(a))throw new mu(`Invalid launch data received for transaction ${t}`);const s={transactionId:t,vaultAddress:a.vaultAddress??"",tokenStringKey:a.tokenStringKey??"",tokenName:e.tokenName,tokenSymbol:e.tokenSymbol,creatorAddress:a.creatorAddress??this.getAddress(),timestamp:Date.now(),...void 0!==n.blockHash&&""!==n.blockHash?{blockHash:n.blockHash}:{},...void 0!==n.gasUsed?{gasUsed:n.gasUsed}:{}};return"string"==typeof e.tokenImage&&(s.tokenImage=e.tokenImage),void 0!==e.preBuyQuantity&&(s.preBuyQuantity=e.preBuyQuantity),""!==s.vaultAddress&&this.tokenResolverService.set(e.tokenName,s.vaultAddress),s})}async uploadTokenImage(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...a}=e;return t.uploadTokenImage(a)}return this.validateWallet(),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 da}),n=t(e)??this.getAddress();return this.launchpadService.fetchProfile(n)}async fetchReferralUrl(){this.validateWallet();const e=this.getAddress();return await this.dexApiHttp.get(y,void 0,{"x-wallet-address":e})}async fetchReferrals(e){const t=await this.resolveReferralAddress(e?.address),n=e?.page??1,a=e?.limit??10,s={pageNumber:n,limit:a,sortBy:e?.sortBy??"joined",sortDir:e?.sortDir??"desc"},r=await this.dexApiHttp.get(v,s,{"x-wallet-address":t});if(!Array.isArray(r))throw new wt("Unexpected API response: expected array, got "+typeof r);return{referrals:r,page:n,limit:a,hasMore:r.length===a}}async fetchAllReferrals(e){const t=await Ki((t,n)=>this.fetchReferrals({...e,page:t,limit:n}).then(e=>({items:e.referrals,page:e.page,limit:e.limit,total:0,totalPages:0,hasNext:e.hasMore,hasPrevious:e.page>1})),{maxPages:100,pageSize:100,logger:this.logger});return{referrals:t.items,total:t.items.length}}async fetchReferralsSummary(e){const t=await this.resolveReferralAddress(e?.address),n=await this.dexApiHttp.get(k,void 0,{"x-wallet-address":t});if(void 0===n||"number"!=typeof n.referralCount||void 0===n.rewardTotals)throw new wt(`Unexpected API response: expected { referralCount, rewardTotals }, got ${JSON.stringify(n)}`);return n}async updateProfile(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return da}),n={...e,address:t(e.address)};if(void 0!==n.privateKey&&""!==n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...a}=n;return e.updateProfile(a)}return this.validateWallet(),this.launchpadService.updateProfile(n)}async uploadProfileImage(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return da}),n={...e,address:t(e.address)??this.getAddress()};if(void 0!==n.privateKey&&""!==n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...a}=n;return e.uploadProfileImage(a)}return this.validateWallet(),this.launchpadService.uploadProfileImage(n)}async fetchTokensHeld(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return da}),n=t(e?.address)??this.getAddress(),a={pageSize:e?.pageSize??10,address:n,...void 0!==e?.cursor?{cursor:e.cursor}:{}};return void 0!==e?.tokenName&&""!==e.tokenName&&(a.tokenName=e.tokenName),void 0!==e?.search&&""!==e.search&&(a.search=e.search),this.launchpadService.fetchTokensHeld(a)}async fetchTokensCreated(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return da}),n=t(e?.address)??this.getAddress(),a={type:void 0!==e?.status?"created":"DEFI",address:n,pageSize:e?.pageSize??10};return void 0!==e?.cursor&&(a.cursor=e.cursor),void 0!==e?.tokenName&&""!==e.tokenName&&(a.tokenName=e.tokenName),void 0!==e?.search&&""!==e.search&&(a.search=e.search),void 0!==e?.status&&(a.status=e.status),this.launchpadService.fetchTokenList(a)}async getManagedTokens(e){return this.launchpadService.getManagedTokens(e??{})}async fetchPriceHistory(e){return this.priceHistoryService.fetchPriceHistory(e)}async fetchAllPriceHistory(e){return this.priceHistoryService.fetchAllPriceHistory(e)}async transferGala(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return da}),n={...e,recipientAddress:t(e.recipientAddress)};if(void 0!==n.privateKey&&""!==n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...a}=n;return e.transferGala(a)}return this.validateWallet(),this.galaChainService.transferGala(n)}async transferToken(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return da}),n={...e,to:t(e.to)};if(void 0!==n.privateKey&&""!==n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...a}=n;return e.transferToken(a)}return this.validateWallet(),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 da});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,...a}=n;return e.lockTokens(a)}return this.validateWallet(),this.galaChainService.lockTokens(n)}async unlockTokens(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...a}=e;return t.unlockTokens(a)}return this.validateWallet(),this.galaChainService.unlockTokens(e)}async burnTokens(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...a}=e;return t.burnTokens(a)}return this.validateWallet(),this.galaChainService.burnTokens(e)}async resolveVaultAddress(e){return this.tokenResolverService.resolveTokenToVault(e)}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{xn(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 Dt("baseUrl is required in configuration","baseUrl");if(void 0===this.config.webSocketUrl||""===this.config.webSocketUrl)throw Dt("webSocketUrl is required in configuration","webSocketUrl");try{new URL(this.config.baseUrl)}catch{throw Dt(`Invalid baseUrl format: ${this.config.baseUrl}`,"baseUrl")}try{new URL(this.config.webSocketUrl)}catch{throw Dt(`Invalid webSocketUrl format: ${this.config.webSocketUrl}`,"webSocketUrl")}if(void 0!==this.config.gatewayBaseUrl&&""!==this.config.gatewayBaseUrl)try{new URL(this.config.gatewayBaseUrl)}catch{throw Dt(`Invalid gatewayBaseUrl format: ${this.config.gatewayBaseUrl}`,"gatewayBaseUrl")}if(void 0!==this.config.bundleBaseUrl&&""!==this.config.bundleBaseUrl)try{new URL(this.config.bundleBaseUrl)}catch{throw Dt(`Invalid bundleBaseUrl format: ${this.config.bundleBaseUrl}`,"bundleBaseUrl")}if(void 0!==this.config.launchpadFrontendUrl&&""!==this.config.launchpadFrontendUrl)try{new URL(this.config.launchpadFrontendUrl)}catch{throw Dt(`Invalid launchpadFrontendUrl format: ${this.config.launchpadFrontendUrl}`,"launchpadFrontendUrl")}}parseSlippageToleranceFactor(e){const t=En("string"==typeof e||"number"==typeof e?e:String(e),ku.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR);return t<0||t>1?(this.logger.warn(`Invalid slippage tolerance factor: ${String(e)}, using default: ${ku.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR}`),ku.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR):t}parseFeeSlippageFactor(e){const t=En("string"==typeof e||"number"==typeof e?e:String(e),ku.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR);return t<0||t>1?(this.logger.warn(`Invalid fee slippage factor: ${String(e)}, using default: ${ku.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR}`),ku.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR):t}async ensureWebSocketConnection(){this.websocketService.isConnected()||(await this.websocketService.connect(),this.logger.debug("WebSocket connection established"))}async waitForConfirmation(e,t){this.logger.debug(`Waiting for confirmation of transaction: ${e}`);try{const n=await this.websocketService.waitForTransaction(e);if(n.status!==wi.COMPLETED)throw new pu(e,n.status,n.message);let a;try{a=t(n)}catch(t){if(t instanceof mu)throw t;throw new mu(`Failed to transform WebSocket response for transaction ${e}`,st(t)?t:new Error(rt(t)))}return this.logger.debug(`Transaction confirmed: ${e}`,a),a}catch(t){if(this.logger.error(`Transaction confirmation failed: ${e}`,t),t instanceof pu||t instanceof mu)throw t;throw new mu(`WebSocket confirmation failed for transaction ${e}`,st(t)?t:new Error(rt(t)))}}async warmCacheFromPools(e){if(void 0===e||!Array.isArray(e))return;const{extractMetadataFromPoolData:t,isValidPoolForCaching:n}=await Promise.resolve().then(function(){return Eu});e.forEach(e=>{if(!n(e))return;const a=t(e,this.logger);a&&this.launchpadAPI.warmCacheFromPoolData(e.tokenName,a)})}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,a=Math.max(t?.intervalMs??3e4,n);null!=t?.intervalMs&&t.intervalMs<n&&this.logger.warn(`Poll interval ${t.intervalMs}ms is below minimum 1000ms. Using minimum interval instead.`);const s=t?.creatorAddress,r=new Map;let i=!0,o=null;let c=0;const l=async()=>{if(i){try{const t=await this.fetchPools({type:"recent",pageSize:20});c>0&&(this.logger.debug("Successfully recovered from polling errors"),c=0),t.items.forEach(t=>{r.has(t.tokenName)||((e=>{if(r.set(e,!0),r.size>1e3){const e=r.keys().next().value;void 0!==e&&r.delete(e)}})(t.tokenName),void 0!==s&&""!==s&&t.creatorAddress!==s||e(t))})}catch(e){c++;const t=rt(e);c>=5?this.logger.error(`Polling for new launchpad tokens failed ${c} consecutive times. Last error: ${t}. Continuing to retry...`):c>1?this.logger.warn(`Error polling for new launchpad tokens (attempt ${c}/5): ${t}`):this.logger.debug(`Error polling for new launchpad tokens: ${t}`)}if(i){const e=Math.min(Math.max(c-1,0),2),t=a*Math.pow(2,e);o=setTimeout(()=>{l()},t)}}};return l(),()=>{i=!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 Dt("WebSocket service not initialized. Ensure websocketUrl is configured and the service is connected.","websocketService");let n=!1,a=null;const s=(n,...a)=>{try{if(a.length>0&&"object"==typeof a[0]&&null!==a[0]){const n=a[0].data;if(void 0!==n?.Data&&null!==n.Data&&"object"==typeof n.Data){const a=n.Data;if("CreateSale"===a.functionName){const n={tokenName:""!==a.tokenName?a.tokenName:"",symbol:""!==a.symbol?a.symbol:"",creatorAddress:""!==a.creatorAddress?a.creatorAddress:"",description:""!==a.description?a.description:"",image:""!==a.image?a.image:"",vaultAddress:""!==a.vaultAddress?a.vaultAddress:"",tokenStringKey:""!==a.tokenStringKey?a.tokenStringKey:"",preBuyQuantity:""!==a.initialBuyQuantity?a.initialBuyQuantity:"0",websiteUrl:""!==a.websiteUrl?a.websiteUrl:"",telegramUrl:""!==a.telegramUrl?a.telegramUrl:"",twitterUrl:""!==a.twitterUrl?a.twitterUrl:"",instagramUrl:""!==a.instagramUrl?a.instagramUrl:"",facebookUrl:""!==a.facebookUrl?a.facebookUrl:"",redditUrl:""!==a.redditUrl?a.redditUrl:"",tiktokUrl:""!==a.tiktokUrl?a.tiktokUrl:"",isFinalized:!1!==a.isFinalized&&null!==a.isFinalized&&void 0!==a.isFinalized&&a.isFinalized};this.matchesCreatorFilter(n,t?.creatorFilter)&&e(n)}}}}catch(e){this.logger.warn(`Error processing token creation broadcast: ${rt(e)}`)}};let r=this.websocketService.getSocket();if(r)r.onAny(s),n=!0,this.logger.debug("Token creation broadcast listener registered");else{this.logger.debug("WebSocket not yet connected, initiating connection..."),this.websocketService.connect().catch(e=>{const n=new Error(`WebSocket connection failed: ${rt(e)}`);this.logger.warn("Failed to establish WebSocket connection:",e),t?.onError&&t.onError(n)});let e=0;const i=()=>{if(r=this.websocketService.getSocket(),!r&&e<ku.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS)return e++,void(a=setTimeout(()=>i(),ku.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS));if(!r&&e>=ku.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS){const e=new Error(`WebSocket not available after ${ku.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS*ku.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS}ms`);return this.logger.warn("Token creation broadcast subscription timeout:",e.message),void(t?.onError&&t.onError(e))}r&&(r.onAny(s),n=!0,this.logger.debug("Token creation broadcast listener registered"))};i()}return()=>{try{if(null!==a&&(clearTimeout(a),a=null,this.logger.debug("Cleared token creation broadcast polling timeout")),!n)return void this.logger.debug("Cleanup called before listener registration - no action needed");const e=this.websocketService.getSocket();e&&(e.offAny(s),n=!1,this.logger.debug("Stopped listening to token creation broadcasts"))}catch(e){this.logger.warn("Error removing token creation listener:",e)}}}getNftCollectionClaimFee(){return this.nftCollectionService.getCollectionClaimFee()}getNftTokenClassCreateFee(){return this.nftCollectionService.getTokenClassCreateFee()}estimateNftMintFee(e){return this.nftCollectionService.estimateMintFee(e)}estimateNftOperationFees(e){return this.nftCollectionService.estimateNftOperationFees(e)}claimNftCollection(e){return this.nftCollectionService.claimCollection(e)}fetchNftCollections(e){return this.nftCollectionService.fetchUserCollections(e)}isNftCollectionAvailable(e){return this.nftCollectionService.isCollectionAvailable(e)}createNftTokenClass(e){return this.nftCollectionService.createTokenClass(e)}fetchNftTokenClasses(e){return this.nftCollectionService.fetchTokenClasses(e)}mintNft(e){return this.nftCollectionService.mintNft(e)}fetchNftBalances(e,t){return this.nftCollectionService.fetchNftBalances(e,t)}async cleanup(){try{if(this.logger.debug("Starting cleanup..."),void 0!==this._eventsBatcherService)try{await this._eventsBatcherService.shutdown(5e3),this._eventsBatcherService=void 0}catch(e){this.logger.warn("Error during events shutdown:",e)}this.http.cleanup(),null!==this.websocketService&&void 0!==this.websocketService&&this.websocketService.disconnect(),void 0!==this._streamWebSocketService&&(this._streamWebSocketService.disconnect(),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 Jt({debug:e,context:"LaunchpadSDK"});t.debug("Starting global cleanup..."),xd.cleanupAll(e),t.debug("Global cleanup completed")}}function bu(){const e=globalThis;return e.process?.env??{}}ku.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR=.15,ku.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR=.01,ku.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY=zt.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY,ku.DEFAULT_CALCULATE_AMOUNT_MODE="local",ku.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS=30,ku.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS=100;let wu=0;class Su{constructor(){this.utilityInstance=!0,this.utilityInstance}static generateWallet(){try{const e=t.Wallet.createRandom();if(null===e.mnemonic?.phrase||void 0===e.mnemonic?.phrase||""===e.mnemonic.phrase)throw Ct("mnemonic","Mnemonic phrase");const n=Su.toGalaAddress(e.address);return{privateKey:e.privateKey,address:e.address,galaAddress:n,mnemonic:e.mnemonic.phrase,wallet:new t.Wallet(e.privateKey)}}catch(e){if("test"===bu().NODE_ENV){const e=`test-wallet-${Date.now()}-${++wu}`,n="0x"+Buffer.from(e).toString("hex").padStart(64,"1").slice(0,64),a=new t.Wallet(n),s=Su.toGalaAddress(a.address);return{privateKey:a.privateKey,address:a.address,galaAddress:s,mnemonic:"test test test test test test test test test test test junk",wallet:a}}throw e}}static fromPrivateKey(e){const n=new t.Wallet(e),a=Su.toGalaAddress(n.address);return{privateKey:n.privateKey,address:n.address,galaAddress:a,mnemonic:"",wallet:n}}static fromMnemonic(e,n=0){try{const a=t.Mnemonic.fromPhrase(e),s=t.HDNodeWallet.fromMnemonic(a,`m/44'/60'/0'/0/${n}`),r=new t.Wallet(s.privateKey),i=Su.toGalaAddress(r.address);return{privateKey:r.privateKey,address:r.address,galaAddress:i,mnemonic:e,wallet:r}}catch(a){if("test"===bu().NODE_ENV){const a=`test-mnemonic-index-${n}-${e}`,s="0x"+Buffer.from(a).toString("hex").padStart(64,"1").slice(0,64),r=new t.Wallet(s),i=Su.toGalaAddress(r.address);return{privateKey:r.privateKey,address:r.address,galaAddress:i,mnemonic:e,wallet:r}}throw a}}static toGalaAddress(e){const n=sa(e);if(!/^[a-fA-F0-9]{40}$/.test(n))throw Nt("address","a valid Ethereum address (40 hex characters)");return`eth|${t.getAddress(`0x${n}`).slice(2)}`}static toEthereumAddress(e){try{return ia(e)}catch(t){const n=rt(t);if(n.includes("required")||!e?.startsWith("eth|"))throw Ct("galaAddress","Gala address starting with eth|");if(n.includes("Invalid backend"))throw Nt("galaAddress","Gala format (eth|{40-hex-chars})");throw t}}static isValidEthereumAddress(e){try{const t=sa(e);return/^[a-fA-F0-9]{40}$/.test(t)}catch{return!1}}static isValidGalaAddress(e){return""!==e&&"backend"===la(e)}static generateMultipleWallets(e=1){xn(e,1,100,"count");const t=[];if("test"===bu().NODE_ENV)for(let n=0;n<e;n++){const e=`test-multi-${n}-${Date.now()}-${++wu}`,a="0x"+Buffer.from(e).toString("hex").padStart(64,"1").slice(0,64);t.push(Su.fromPrivateKey(a))}else for(let n=0;n<e;n++)t.push(Su.generateWallet());return t}static getWalletSummary(e,t=!1){const n=["🔐 Wallet Information","═".repeat(50),`📍 Address: ${e.address}`,`🎮 Gala Address: ${e.galaAddress}`,`🌱 Mnemonic: ${null!==e.mnemonic&&void 0!==e.mnemonic&&""!==e.mnemonic?e.mnemonic:"Not available"}`];return t?n.splice(3,0,`🔑 Private Key: ${e.privateKey}`):n.splice(3,0,"🔑 Private Key: [HIDDEN - use includeSensitive=true to show]"),n.push("═".repeat(50)),n.push("💾 IMPORTANT: Save your mnemonic phrase securely!"),n.push("This is your backup to recover the wallet."),n.join("\n")}}function Au(e){if(void 0===e)return Su.generateWallet();const t=e.trim();if(!Pn(t))throw Nt("input","a non-empty string");if(function(e){const t=sa(e);return/^[a-fA-F0-9]{64}$/.test(t)}(t))return Su.fromPrivateKey(t);if(function(e){const t=e.split(/\s+/).filter(e=>e.length>0);if(12!==t.length&&24!==t.length)return!1;return t.every(e=>/^[a-zA-Z]+$/.test(e))}(t))return Su.fromMnemonic(t);throw Nt("input","a private key (64 hex characters) or mnemonic (12/24 words)","Wallet input")}var Eu=Object.freeze({__proto__:null,extractMetadataFromPoolData:function(e,t){const n={};if(void 0!==e.vaultAddress&&(n.vaultAddress=e.vaultAddress),void 0!==e.reverseBondingCurveMinFeePortion){const a=En(e.reverseBondingCurveMinFeePortion,NaN);isNaN(a)?t&&t.debug(`Skipping invalid reverseBondingCurveMinFeePortion for ${e.tokenName}: "${e.reverseBondingCurveMinFeePortion}"`):n.reverseBondingCurveMinFeeFactor=a}if(void 0!==e.reverseBondingCurveMaxFeePortion){const a=En(e.reverseBondingCurveMaxFeePortion,NaN);isNaN(a)?t&&t.debug(`Skipping invalid reverseBondingCurveMaxFeePortion for ${e.tokenName}: "${e.reverseBondingCurveMaxFeePortion}"`):n.reverseBondingCurveMaxFeeFactor=a}return void 0!==n.reverseBondingCurveMaxFeeFactor&&void 0!==n.reverseBondingCurveMinFeeFactor&&(n.reverseBondingCurveNetFeeFactor=n.reverseBondingCurveMaxFeeFactor-n.reverseBondingCurveMinFeeFactor),Object.keys(n).length>0?n:null},isValidPoolForCaching:function(e){if(null===e||"object"!=typeof e)return!1;const t=e;return"tokenName"in t&&"string"==typeof t.tokenName&&t.tokenName.length>0}});exports.BrowserWalletSigner=fo,exports.EVENT_TYPES={LOGIN:"login",LOGOUT:"logout",TOKEN_BUY:"token_buy",TOKEN_SELL:"token_sell",TOKEN_SWAP:"token_swap",TOKEN_CREATED:"token_created",TOKEN_GRADUATED:"token_graduated",PAGE_VIEW:"page_view",PAGE_LEAVE:"page_leave",STREAM_START:"stream_start",STREAM_END:"stream_end",STREAM_VIEWERS_CHANGED:"stream_viewers_changed",CHAT_MESSAGE_SENT:"chat_message_sent",CHAT_MESSAGE_RECEIVED:"chat_message_received",LIQUIDITY_ADDED:"liquidity_added",LIQUIDITY_REMOVED:"liquidity_removed",BRIDGE_DEPOSIT:"bridge_deposit",BRIDGE_WITHDRAW:"bridge_withdraw",PROFILE_UPDATED:"profile_updated",BALANCE_CHANGED:"balance_changed",ERROR_OCCURRED:"error_occurred"},exports.GalaWalletSigner=po,exports.LaunchpadSDK=ku,exports.LaunchpadSDKError=Md,exports.PrivateKeySigner=mo,exports.SDK_VERSION=Ai,exports.TransactionFailedError=pu,exports.WebSocketError=mu,exports.WebSocketTimeoutError=class extends mu{constructor(e,t){super(`WebSocket confirmation timeout for transaction ${e} after ${t}ms`),this.name="WebSocketTimeoutError"}},exports.createLaunchpadSDK=function(e){Mn(e)&&(e={});const{wallet:n,env:a,config:s={},...r}=e,i={...{...r,...s}};let o;if(delete i.wallet,delete i.env,delete i.config,Mn(n)){o=Au().wallet}else if("string"==typeof n){o=Au(n).wallet}else{if(!(n instanceof t.Wallet))throw Dt("Invalid wallet input. Expected string (private key or mnemonic) or Wallet instance.","wallet");o=n}const c={wallet:o,...void 0!==a?{env:a}:{},debug:!1,timeout:3e4,...i};return new ku(c)},exports.createWallet=Au,exports.generateEIP712Types=co,exports.getEthereumAddressFromPrivateKey=function(e){if(!e.match(/^0x[a-fA-F0-9]{64}$/))throw Nt("privateKey","0x-prefixed 64 hexadecimal characters","Private key");return t.getAddress(t.computeAddress(e))},exports.getPublicKeyFromPrivateKey=function(e){if(!e.match(/^0x[a-fA-F0-9]{64}$/))throw Nt("privateKey","0x-prefixed 64 hexadecimal characters","Private key");const n=new t.SigningKey(e);return{publicKey:n.publicKey,compressedPublicKey:n.compressedPublicKey}};
|
|
1
|
+
"use strict";var e=require("zod"),t=require("ethers"),n=require("@gala-chain/gswap-sdk"),a=require("@solana/web3.js"),s=require("json-stringify-deterministic"),r=require("node:crypto"),i=require("@solana/spl-token"),o=require("bs58"),c=require("@gala-chain/api"),l=require("uuid"),d=require("bignumber.js"),u=require("socket.io-client"),h=require("axios");function g(e){var t=Object.create(null);return e&&Object.keys(e).forEach(function(n){if("default"!==n){var a=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,a.get?a:{enumerable:!0,get:function(){return e[n]}})}}),t.default=e,Object.freeze(t)}var m=g(r);const p={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",GET_TOKEN_LIST:"/v1/users/:address/tokens",GET_TOKENS_HELD:"/v1/users/:address/tokens",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"},f="/v1/users/referrals/url",y="/v1/users/referrals",v="/v1/users/referrals/summary",k="/market/price-series",b="/v1/tokens/:tokenName/start-stream",w="/v1/tokens/:tokenName/stop-stream",S="/v1/tokens/:tokenName/stream/disable",A="/v1/tokens/:tokenName/stream/enable",E="/v1/tokens/:tokenName/reset-key",T="/v1/tokens/:tokenName/recordings",C="/v1/tokens/:tokenName/recordings/:assetId/download",N="/v1/tokens/:tokenName/recordings/:assetId",I="/v1/tokens/:tokenName/simulcasts",D="/v1/tokens/:tokenName/simulcasts",_="/v1/tokens/:tokenName/simulcasts/:targetId",R="/v1/config",x="/v1/config",O="/v1/config",F="/v1/tokens/:tokenName/role",B="/v1/roles",U="/v1/permissions",P="/v1/tokens/:tokenName/credentials",M="/auth/login",L="/auth/logout",$="/auth/refresh",K="/auth/session",G="/v1/tokens/:tokenName/bans",W="/v1/tokens/:tokenName/bans",H="/v1/tokens/:tokenName/bans/:userAddress",q="/v1/tokens/:tokenName/bans/:userAddress",z="/v1/tokens/:tokenName/active-users",j="/v1/user-bans",V="/v1/user-bans",X="/v1/user-bans/:userAddress",Q="/v1/user-bans/:userAddress",J={CREATE:"/v1/api-keys",LIST:"/v1/api-keys",GET:"/v1/api-keys/:id",UPDATE:"/v1/api-keys/:id",REVOKE:"/v1/api-keys/:id"},Y="/v1/moderator-invites",Z="/v1/moderator-invites/claim",ee="/v1/moderated-tokens",te="/v1/moderator-invites",ne="/v1/moderator-invites/:id",ae="/v1/moderator-invites/:id/role",se="/v1/moderator-invites/:id",re="/v1/moderator-invites/code/:code",ie={CREATE:"/v1/content-flags",LIST:"/v1/content-flags",DISMISS:"/v1/content-flags/:id/dismiss",ACTION:"/v1/content-flags/:id/action"},oe="/v1/overseer-invites",ce="/v1/overseer-invites",le="/v1/overseer-invites/code/:code",de="/v1/overseer-invites/claim",ue="/v1/overseer-invites/:id",he="/v1/overseers",ge="/v1/overseers",me="/v1/overseers/:address",pe="/v1/overseers/me",fe="/v1/overseer-summary",ye="/v1/overseer-summary/bans",ve="/v1/overseer-summary/token-bans",ke="/v1/overseer-summary/invites",be="/v1/overseer-summary/flags",we="/v1/overseer-summary/users",Se="/v1/users",Ae="/v1/users/:address/summary",Ee="/v1/cache/flush/address/:address",Te="/v1/cache/flush/token/:tokenName",Ce="/v1/cache/flush/all",Ne="/v1/cache/flush/wallet-aliases/:address",Ie="/v1/cache/flush/wallet-aliases",De="/v1/token-bans",_e="/v1/token-bans",Re="/v1/token-bans/:tokenName",xe="/v1/token-bans/:tokenName",Oe="/v1/reactions",Fe="/v1/reactions",Be="/v1/trades",Ue={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"},Pe="/v1/restricted-token-names",Me="/v1/restricted-token-names",Le="/live/:tokenName/chat",$e="/live/:tokenName/chat",Ke="/live/:tokenName/chat",Ge="/live/:tokenName/chat/slow-mode",We={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"},He="/v1/stats",qe="/v1/trading/fee",ze="/v1/trading/sale-details",je="/v1/trading/quote",Ve="/v1/trading/premint-quote",Xe={GET_LEADERBOARD:"/weekly-challenge",GET_TOKEN_HISTORY:"/weekly-challenge/history/:vaultAddress"},Qe="/v1/notifications/register",Je="/v1/notifications/unregister",Ye="/v1/notifications/preferences",Ze="/v1/notifications/preferences",et="/v1/config/client-flags",tt="native",nt="exact";function at(e){return e instanceof Error}function st(e){return at(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 rt(e){return at(e)||"object"==typeof e&&null!==e&&"stack"in e&&"string"==typeof e.stack?e.stack:void 0}function it(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 ot(e){return"object"==typeof e&&null!==e&&"message"in e&&("response"in e||"request"in e||"config"in e)}function ct(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 a=n.Status;if("number"!=typeof a)throw new Error(`${t}: Response Status must be a number, got ${typeof a}`);if(1!==a)throw new Error(`${t}: Response status indicates failure (Status: ${a})`);return n}function lt(e){if(null==e||"object"!=typeof e)return"";const t=e.Message;return"string"==typeof t&&t.trim().length>0?` - ${t}`:""}function dt(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)}}}const ut="Token name is required and must be a string",ht=e=>`Could not find vault address for token: ${e}`,gt="REQUIRED",mt="INVALID_TYPE",pt="INVALID_VALUE",ft="INVALID_FORMAT",yt="TOO_LARGE",vt="INVALID_RANGE";class kt extends Error{constructor(e,t,n){super(e),this.field=t,this.code=n,this.name="ValidationError"}}class bt extends Error{constructor(e,t,n){super(e),this.statusCode=t,this.originalError=n,this.name="NetworkError"}}class wt extends Error{constructor(e,t){super(e),this.field=t,this.name="ConfigurationError"}}class St extends Error{constructor(e,t,n){super(e),this.transactionId=t,this.code=n,this.name="TransactionError"}}function At(e,t){return void 0!==t?t:e.charAt(0).toUpperCase()+e.slice(1)}function Et(e,t){return new kt(`Token "${e}" not found. Please verify the token name is correct.`,"tokenName","TOKEN_NOT_FOUND")}function Tt(e,t){const n=At(e,t);return new kt(`${n} is required`,e,"REQUIRED")}function Ct(e,t,n){const a=At(e,n);return new kt(`${a} must be ${t}`,e,"INVALID_FORMAT")}function Nt(e,t,n){return new bt(e,t,n)}function It(e,t){return new wt(e,t)}function Dt(e,t,n){return new St(e,t,n)}function _t(e,t,n,a){n&&n.error(`${t}:`,e);const s=ot(e)?e.response?.status:void 0;return Nt(`${t}: ${st(e)}`,s,at(e)?e:void 0)}function Rt(e,t,n,a,s){const r=At(e,s);return new kt(`${r} must be between ${t} and ${n}${void 0!==a?`, received: ${a}`:""}`,e,"OUT_OF_RANGE")}function xt(e,t,n,a){const s=At(e,a);return new kt(`${s} must be at least ${t}${void 0!==n?`, received: ${n}`:""}`,e,"TOO_SMALL")}function Ot(e,t,n,a){const s=At(e,a);return new kt(`${s} must be at most ${t}${void 0!==n?`, received: ${n}`:""}`,e,"TOO_LARGE")}function Ft(e,t,n,a){const s=At(e,a),r=void 0!==n?`, received: ${"object"==typeof n?"object":String(n)}`:"";return new kt(`${s} must be ${t}${r}`,e,"INVALID_TYPE")}function Bt(e,t,n){const a=At(e,n);return new kt(`${a} must be a valid number${void 0!==t?`: "${t}"`:""}`,e,"INVALID_NUMBER")}function Ut(e,t,n,a){const s=At(e,a);return new kt(`Invalid ${s}: ${t}. Must be one of: ${n.join(", ")}`,e,"INVALID_ENUM")}function Pt(e){return null!=e&&"object"==typeof e&&"data"in e}function Mt(e,t,n=!1){const a=!0===e.error,s=n&&(null===e.data||void 0===e.data);if(a||s){const n=e?.statusCode??e.status??void 0;throw Nt(e?.message??t,n)}}function Lt(e){if(Pt(e))return e.data}function $t(e,t="No data found in response"){if(!Pt(e))throw Nt(t);const n=e.data;if(null==n)throw Nt(t);return n}async function Kt(e,t={}){return Ht(e,t,e=>{if(void 0===e.data)throw new kt(`${t.errorContext??"Operation failed"}: No data returned from API`,"data","NO_DATA");return e.data})}async function Gt(e,t={}){const{errorContext:n="Operation failed",logger:a,debugLogEnabled:s=!1}=t;s&&a&&a.debug(`${n}: starting operation`);try{const t=await e();return s&&a&&a.debug(`${n}: completed successfully`),t}catch(e){throw a&&a.error(n,{error:e}),e}}async function Wt(e,t={}){return Ht(e,t,e=>e)}async function Ht(e,t,n){const{errorContext:a="Operation failed",logger:s,debugLogEnabled:r=!1}=t;r&&s&&s.debug(`${a}: starting operation`);try{const t=await e();if(null==t)throw new kt(`${a}: No response from server`,"response","NO_RESPONSE");return Mt(t,a,!0),r&&s&&s.debug(`${a}: completed successfully`),n(t)}catch(e){throw s&&s.error(a,{error:e}),e}}const qt={BASE_PRICE:1650667151e-14,PRICE_SCALING_FACTOR:1166069e-12,TRADING_FEE_FACTOR:.001,GAS_FEE:"1",DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY:1e7};function zt(e){return e.trim().toLowerCase()}function jt(e){return e.trim().toUpperCase()}function Vt(e){return e.trim().toUpperCase()}var Xt;!function(e){e.DEBUG="DEBUG",e.INFO="INFO",e.WARN="WARN",e.ERROR="ERROR"}(Xt||(Xt={}));class Qt{constructor(e){this.levelPriority={[Xt.DEBUG]:0,[Xt.INFO]:1,[Xt.WARN]:2,[Xt.ERROR]:3},this.debugEnabled=e.debug,this.context=e.context??"SDK",this.minLevel=e.minLevel??(e.debug?Xt.DEBUG:Xt.INFO)}debug(e,t){this.log(Xt.DEBUG,e,t)}info(e,t){this.log(Xt.INFO,e,t)}warn(e,t){this.log(Xt.WARN,e,t)}error(e,t){this.log(Xt.ERROR,e,t)}log(e,t,n){if(this.levelPriority[e]<this.levelPriority[this.minLevel])return;if(e===Xt.DEBUG&&!this.debugEnabled)return;const a=`[${(new Date).toISOString()}] [${this.context}] [${e}]`,s=this.getConsoleMethod(e);void 0!==n?at(n)?s(`${a} ${t}`,n.message,rt(n)??""):s(`${a} ${t}`,n):s(`${a} ${t}`)}getConsoleMethod(e){switch(e){case Xt.DEBUG:return console.debug;case Xt.INFO:return console.info;case Xt.WARN:return console.warn;case Xt.ERROR:return console.error;default:return console.log}}child(e){return new Qt({debug:this.debugEnabled,context:`${this.context}:${e}`,minLevel:this.minLevel})}isDebugEnabled(){return this.debugEnabled&&this.levelPriority[Xt.DEBUG]>=this.levelPriority[this.minLevel]}}function Jt(e){return null==e||""===e}function Yt(e){return null==e}const Zt=new Qt({debug:!1,context:"DateUtils"});function en(e,t){if(null==e)return t??new Date;if(e instanceof Date)return isNaN(e.getTime())?t??new Date:e;try{const n=new Date(e);return isNaN(n.getTime())?(Zt.warn(`Invalid date string received: "${e}". Using fallback.`),t??new Date):n}catch(n){return Zt.warn(`Date parsing error for "${e}":`,n),t??new Date}}function tn(e){if(null==e)return!1;if(e instanceof Date)return!isNaN(e.getTime());if("string"!=typeof e)return!1;const t=new Date(e);return!isNaN(t.getTime())}function nn(e){return Date.now()-e}const an={MIN_LENGTH:3,MAX_LENGTH:20,PATTERN:/^[a-zA-Z0-9]{3,20}$/},sn={MIN_LENGTH:2,MAX_LENGTH:20,PATTERN:/^[a-zA-Z0-9]+$/},rn={MIN_LENGTH:1,MAX_LENGTH:50},on=100,cn=20,ln={MAX_LIMIT:50},dn={PATTERN:/^(eth\|[0-9a-fA-F]{40}|client\|[a-zA-Z0-9_-]+)$/},un={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}},hn={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})$/}},gn=60,mn=31536e3,pn={MAX_LENGTH:64,PATTERN:/^(galaswap-operation-|galaconnect-operation-)/},fn={PATTERN:/^[a-fA-F0-9]{64}$/},yn={STREAM_URL_PATTERN:/^(rtmps?|srt):\/\/.+/},vn=50,kn=1,bn=100,wn={FULL_NAME:{MIN_LENGTH:1,MAX_LENGTH:100,ALPHABETS_ONLY_PATTERN:/^[a-zA-Z]+(?:\s[a-zA-Z]+)?$/}};function Sn(e,t){if(Jt(e))return t;try{return JSON.parse(e)}catch{return t}}function An(e,t=0){if(Jt(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 En(e,t,n){if(Yt(e))return t;if("number"==typeof e)return isNaN(e)?t:e;const a=Number(e);return isNaN(a)?t:a}function Tn(e,t,n){if(Yt(e))return t;if("bigint"==typeof e)try{return Number(e)}catch{return t}if("number"==typeof e)return isNaN(e)?t:Math.floor(e);const a=parseInt(String(e),10);return isNaN(a)?t:a}function Cn(e,t){if(Yt(e)||""===e)throw Tt(t);if(d.isBigNumber(e)){if(e.isNaN())throw Bt(t,"NaN");return e}try{const n=new d(e);if(n.isNaN())throw Bt(t,e);if(!n.isFinite())throw Bt(t,e);return n}catch(n){if(n instanceof kt)throw n;throw Bt(t,e)}}function Nn(e,t=0){if(Yt(e))return t;if("number"==typeof e)return isNaN(e)?t:e;return An(String(e).replace("%","").trim(),t)}function In(e,t=18){const n=An(e,0);if(0===n)return"0";return n.toFixed(t).replace(/\.?0+$/,"")}function Dn(e){return In(e,8)}function _n(e){return In(e,18)}function Rn(e,t,n,a){if("number"!=typeof e)throw Ft(a,"a number",e,a);if(e<t||e>n)throw Rt(a,t,n,e)}function xn(e,t,n){if("string"!=typeof e)throw Ft(n,"a string",e,n);if(e.length>t)throw Ot(n,t,e.length)}function On(e,t){if("number"!=typeof e)throw Ft(t,"a number",e,t);if(!Number.isInteger(e))throw Ft(t,"an integer",e,t);if(e<=0)throw xt(t,1,e,t)}function Fn(e,t,n=!1){if("string"!=typeof e)throw Ft(t,"a string",e,t);if(!n&&0===e.trim().length)throw Tt(t,`${t} (non-empty string)`)}const Bn={ETH_ADDRESS:/^0x[0-9a-fA-F]{40}$/,BACKEND_ADDRESS:/^eth\|(0x)?[0-9a-fA-F]{40}$/,CLIENT_ADDRESS:/^client\|[a-zA-Z0-9_-]+$/},Un=function(e){return"string"==typeof e&&e.trim().length>0},Pn=Yt;function Mn(e,t,n=100,a,s){if(void 0!==s&&"string"!=typeof s)throw new kt("cursor must be a string","cursor",mt);const r=a??t,i=void 0!==a?"pageSize":"limit";if(void 0!==r&&(On(r,i),r>n))throw new kt(`${i} must be at most ${n}`,i,yt)}function Ln(e){const t=Object.values(e);return e=>"string"==typeof e&&t.includes(e)}function $n(e){return Object.values(e)}function Kn(e,t,n,a={}){const{description:s="parameter",treatEmptyAsNull:r=!0}=a,i=e[t],o=e[n],c=null!=i&&(!r||""!==i),l=null!=o&&(!r||""!==o);if(!c&&!l)throw It(`Either ${t} or ${n} must be provided (${s})`,n);if(c&&l)throw It(`Cannot provide both ${t} and ${n}. Provide exactly one (${s}).`,n);return{chosen:c?t:n,hasA:c,hasB:l}}function Gn(e,t="tokenName",n=an){if(!Un(e))throw Tt(t);const a=e.trim();if(0===a.length)throw Tt(t);if(a.length<n.MIN_LENGTH)throw Rt(t,n.MIN_LENGTH,n.MAX_LENGTH,a.length,`${t} length`);if(a.length>n.MAX_LENGTH)throw Rt(t,n.MIN_LENGTH,n.MAX_LENGTH,a.length,`${t} length`);if(!n.PATTERN.test(a))throw new kt(`${t} must contain only alphanumeric characters`,t,ft)}function Wn(e,t="tokenName",n=an){if(null==e)throw Tt(t,t);if("string"!=typeof e)throw Ft(t,"a string",e);const a=e.trim();if(0===a.length)throw Tt(t,t);if(!n.PATTERN.test(a))throw new kt(`${t} must be ${n.MIN_LENGTH}-${n.MAX_LENGTH} alphanumeric characters`,t,ft)}function Hn(e){return""===e||0===e.trim().length}function qn(e,t,n){if(!Pn(e)){if("string"!=typeof e)throw Ft(t,"a string",e,t);if(e.length>n)throw new kt(`${t} must be at most ${n} characters`,t,yt)}}function zn(e,t){Pn(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 Ft(t,"a date",e,t);if(isNaN(n.getTime()))throw new kt(`${t} must be a valid date`,t,ft)}(e,t)}function jn(e,t,n){try{On(e,t)}catch{throw function(e,t,n,a="OPERATION_FAILED"){return new kt(`${e} failed: ${t}`,n,a)}(n,"must be a positive integer",t)}}function Vn(e,t,n="status"){void 0!==e&&function(e,t,n){const a=Object.values(t);if(!a.includes(e))throw new kt(`${n} must be one of: ${a.join(", ")}`,n,ft)}(e,t,n)}class Xn{constructor(e,t=!1,n){this.http=e,this.logger=new Qt({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 wt("JWT authentication required. Call sdk.login() first.")}return this.jwtAuth.getJwtHeaders()}isCalledFromUserCode(){const e=rt(new Error)??"";return!(!e.includes("expect")&&!e.includes("jest"))||!(!e.includes("tests/")&&!e.includes(".test.ts"))}validatePositiveInteger(e,t,n){jn(e,t,n)}}class Qn{constructor(e=!1,t){this.logger=t||new Qt({debug:e,context:this.constructor.name})}}class Jn extends Qn{constructor(e=!1){super(e),this.cache=new Map}get(e){const t=this.normalizeKey(e);return this.cache.get(t)}set(e,t){const n=this.normalizeKey(e);this.cache.set(n,t)}has(e){const t=this.normalizeKey(e);return this.cache.has(t)}clear(){this.cache.clear(),this.logger.debug("Cleared cache")}dump(){return new Map(this.cache)}size(){return this.cache.size}isEmpty(){return 0===this.cache.size}buildBaseStats(){return{totalItems:this.cache.size}}}class Yn extends Jn{constructor(e=!1){super(e)}normalizeKey(e){return zt(e).replace(/\s+/g," ").replace(/[\u0000-\u001F\u007F-\u009F\u200B-\u200D\uFEFF]/g,"")}getLRUKey(){return this.cache.keys().next().value??null}updateCacheEntry(e,t){const n=this.cache.get(e);if(this.cache.has(e)&&this.cache.delete(e),this.cache.size>=Yn.MAX_CACHE_SIZE){const e=this.getLRUKey();null!==e&&this.cache.delete(e)}this.cache.set(e,{...n??{},...t,lastUpdated:Date.now()})}warmFromPoolData(e,t){const n=this.normalizeKey(e);this.updateCacheEntry(n,t)}set(e,t){const n=this.normalizeKey(e);this.updateCacheEntry(n,t)}getByName(e){const t=this.normalizeKey(e);return this.cache.get(t)}getMaxSupply(e){const t=this.normalizeKey(e),n=this.cache.get(t);return n?.maxSupply??qt.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,a)=>{n.lastUpdated<e&&(e=n.lastUpdated);let s=0;s+=2*a.length,void 0!==n.reverseBondingCurveMinFeeFactor&&(s+=8),void 0!==n.reverseBondingCurveMaxFeeFactor&&(s+=8),void 0!==n.reverseBondingCurveNetFeeFactor&&(s+=8),s+=8,void 0!==n.vaultAddress&&""!==n.vaultAddress&&(s+=2*n.vaultAddress.length),void 0!==n.maxSupply&&""!==n.maxSupply&&(s+=2*n.maxSupply.length),void 0!==n.symbol&&""!==n.symbol&&(s+=2*n.symbol.length),s+=32,t+=s}),{cacheSize:t,oldestEntry:this.cache.size>0?e:0}}getByTokenId(e){const t=`token:${zt(e)}`;return this.cache.get(t)??null}setByTokenId(e,t){const n=`token:${zt(e)}`;this.updateCacheEntry(n,t)}hasByTokenId(e){const t=`token:${zt(e)}`;return this.cache.has(t)}}function Zn(e){return""===e?"":e.startsWith("0x")?e.slice(2):e}Yn.MAX_CACHE_SIZE=1e4;const ea={ETHEREUM:Bn.ETH_ADDRESS,ETHEREUM_NO_PREFIX:/^[a-fA-F0-9]{40}$/,BACKEND:Bn.BACKEND_ADDRESS,CLIENT:Bn.CLIENT_ADDRESS};class ta{toBackendFormat(e){if(!Un(e))throw new kt("Address is required and must be a string","address","REQUIRED");let n=e;if(e.startsWith("eth|")){if(n=e.slice(4),!/^[a-fA-F0-9]{40}$/.test(n))throw new kt(`Invalid Ethereum address format in backend address. Expected 40 hex characters after 'eth|'. Got: "${e}"`,"address","INVALID_FORMAT");return e}if(n=Zn(e),!/^[a-fA-F0-9]{40}$/.test(n))throw new kt(`Invalid Ethereum address format. Expected 40 hex characters (with or without 0x prefix). Got: "${e}"`,"address","INVALID_FORMAT");return`eth|${t.getAddress(`0x${n}`).slice(2)}`}toEthereumFormat(e){if(!Un(e))throw new kt("Backend address is required and must be a string","address","REQUIRED");const t=e.match(/^eth\|(0x)?([0-9a-fA-F]{40})$/i);if(!t)throw new kt(`Invalid backend address format. Expected "eth|{40-hex-characters}" or "eth|0x{40-hex-characters}". Got: "${e}"`,"address","INVALID_FORMAT");const n=t[1],a=void 0!==n&&""!==n?6:4;return`0x${e.substring(a)}`}normalizeInput(e){if(void 0!==e&&""!==e){if(e.startsWith("client|")){if(!ea.CLIENT.test(e))throw new kt(`Invalid client address format: "${e}"`,"address","INVALID_FORMAT");return e}if(e.startsWith("eth|")){if(!ea.BACKEND.test(e))throw new kt(`Invalid backend address format: "${e}"`,"address","INVALID_FORMAT");return e}return this.toBackendFormat(e)}}isValid(e){return!!Un(e)&&(!!ea.ETHEREUM.test(e)||(!!ea.ETHEREUM_NO_PREFIX.test(e)||(!!ea.BACKEND.test(e)||!!ea.CLIENT.test(e))))}assertValid(e,t="address"){if(!this.isValid(e))throw new kt(`${t} must be a valid wallet address (Ethereum or backend format)`,t,"INVALID_FORMAT")}detectFormat(e){return Un(e)?ea.ETHEREUM.test(e)||ea.ETHEREUM_NO_PREFIX.test(e)?"ethereum":ea.BACKEND.test(e)?"backend":ea.CLIENT.test(e)?"client":null:null}normalize(e){if(void 0!==e&&""!==e)return e.toLowerCase()}extractHex(e){if(e.startsWith("eth|"))return e.substring(4).toLowerCase();if(e.startsWith("0x"))return Zn(e).toLowerCase();if(/^[a-fA-F0-9]{40}$/.test(e))return e.toLowerCase();throw new kt(`Cannot extract hex from address: "${e}". Expected Ethereum or backend format.`,"address","INVALID_FORMAT")}}const na=new ta,aa=Zn;function sa(e){return na.toBackendFormat(e)}function ra(e){return na.toEthereumFormat(e)}function ia(e){return na.isValid(e)}function oa(e,t="address"){na.assertValid(e,t)}function ca(e){return na.detectFormat(e)}var la=Object.freeze({__proto__:null,AddressFormatter:ta,assertValidWalletAddress:oa,detectFormat:ca,fromBackendAddressFormat:ra,isValidAddress:ia,normalizeAddressInput:function(e){return na.normalizeInput(e)},stripHexPrefix:aa,toBackendAddressFormat:sa});const da=e.z.string({message:"Token name is required"}).min(3,"Token name must be at least 3 characters").max(20,"Token name must be at most 20 characters").regex(/^[a-zA-Z0-9]{3,20}$/,"Token name can only contain letters and numbers"),ua=e.z.string({message:"Token symbol is required"}).min(1,"Token symbol must be at least 1 character").max(8,"Token symbol must be at most 8 characters").regex(/^[A-Z]{1,8}$/,"Token symbol must be uppercase letters only"),ha=e.z.string({message:"Token description is required"}).min(1,"Token description is required").max(500,"Token description must be at most 500 characters"),ga=e.z.string().min(1,"Token name must be at least 1 character").max(50,"Token name must be at most 50 characters"),ma=e.z.string().min(1,"Search query must be at least 1 character").max(100,"Search query must be at most 100 characters"),pa=e.z.string().min(1,"Full name is required").max(100,"Full name must be at most 100 characters").regex(/^[a-zA-Z\s]+$/,"Full name can only contain letters and spaces");e.z.string().regex(Bn.BACKEND_ADDRESS,"Address must be in format: eth|[40-hex-chars]"),e.z.string().regex(Bn.ETH_ADDRESS,"Invalid Ethereum address format");const fa=e.z.string().refine(e=>Bn.BACKEND_ADDRESS.test(e)||Bn.ETH_ADDRESS.test(e)||Bn.CLIENT_ADDRESS.test(e),"Address must be eth|[40-hex], 0x[40-hex], or client|[identifier] format").transform(e=>(new ta).normalizeInput(e)??e),ya=e.z.string().refine(e=>Bn.BACKEND_ADDRESS.test(e)||/^service\|Token\$Unit\$[A-Z0-9]+\$eth:[0-9a-fA-F]{40}\$launchpad$/.test(e),"Invalid vault address format"),va=e.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>An(e,0)>0,"Amount must be greater than zero"),ka=e.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>An(e,0)>=0,"Amount must be zero or greater");e.z.string().url("Must be a valid URL").regex(/^https?:\/\//,"URL must start with http:// or https://");const ba=e.z.string().optional().refine(e=>void 0===e||""===e||/^https?:\/\/.+\..+/.test(e),"Must be a valid URL if provided");function wa(t=100){return e.z.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.z.number().int("Page must be an integer").min(1,"Page must be at least 1").max(1e3,"Page must be at most 1000").default(1),wa(100),wa(20),wa(20);const Sa=e.z.number().int("File size must be an integer").min(1,"File must be at least 1 byte").max(10485760,"File must be at most 10MB"),Aa=e.z.string().max(255,"Filename must be at most 255 characters"),Ea=e.z.enum(["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"]);e.z.string().datetime("Must be a valid ISO 8601 date string"),e.z.number().int("Timestamp must be an integer").min(0,"Timestamp must be non-negative");const Ta=e.z.string().regex(/^0x[a-fA-F0-9]{64}$/,"Private key must be format: 0x + 64 hex characters");e.z.string().regex(/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/,"Transaction ID must be in UUID format"),e.z.string().regex(/^galaconnect-operation-[a-z0-9-]+$/,"Unique key must be format: galaconnect-operation-{unique-id}");const Ca=[".png",".jpg",".jpeg",".gif",".webp",".svg"];e.z.object({file:e.z.union([e.z.instanceof(File),e.z.instanceof(Buffer)]),name:Aa,size:Sa,type:Ea});const Na=e.z.instanceof(File).refine(e=>e.size>=1&&e.size<=10485760,"File size must be between 1 byte and 10MB").refine(e=>["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"].includes(e.type),"File must be a valid image type (PNG, JPG, JPEG, GIF, WebP, or SVG)").refine(e=>e.name.length<=255,"Filename must be at most 255 characters"),Ia=e.z.instanceof(Buffer).refine(e=>e.length>=1&&e.length<=10485760,"Buffer size must be between 1 byte and 10MB");e.z.union([Na,Ia]),e.z.enum([".png",".jpg",".jpeg",".gif",".webp",".svg"]),Aa.refine(e=>{const t=e.slice(e.lastIndexOf(".")).toLowerCase();return Ca.includes(t)},`Filename must end with one of: ${Ca.join(", ")}`),e.z.object({websiteUrl:ba,telegramUrl:ba,twitterUrl:ba,instagramUrl:ba,facebookUrl:ba,redditUrl:ba,tiktokUrl:ba}).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 Da=e.z.string().min(1,"Token category must not be empty").default("Unit"),_a=e.z.string().min(1,"Token collection must not be empty").default("Token"),Ra=e.z.object({minFeePortion:e.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal string").refine(e=>An(e,0)>=.1,"Minimum fee must be >= 0.1").refine(e=>An(e,0)<=.5,"Minimum fee must be <= 0.5"),maxFeePortion:e.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal string").refine(e=>An(e,0)>=.1,"Maximum fee must be >= 0.1").refine(e=>An(e,0)<=.5,"Maximum fee must be <= 0.5")}).refine(e=>An(e.maxFeePortion,0)>=An(e.minFeePortion,0),{message:"Maximum fee must be >= minimum fee",path:["maxFeePortion"]}),xa=e.z.object({tokenName:da,tokenSymbol:ua,tokenDescription:ha,tokenImage:e.z.union([e.z.instanceof(File),e.z.instanceof(Buffer),e.z.string().url("Token image must be a valid URL")]).optional(),preBuyQuantity:ka.default("0"),websiteUrl:ba,telegramUrl:ba,twitterUrl:ba,instagramUrl:ba,facebookUrl:ba,redditUrl:ba,tiktokUrl:ba,tokenCategory:Da,tokenCollection:_a,reverseBondingCurveConfiguration:Ra.optional(),saleStartTime:e.z.number().int().positive().optional(),privateKey:Ta.optional()});e.z.object({file:e.z.union([e.z.instanceof(File),e.z.instanceof(Buffer)]),tokenName:da}),e.z.enum(["RECENT","POPULAR"]);const Oa=e.z.object({tokenName:da.optional(),symbol:ua.optional()}).refine(e=>void 0!==e.tokenName||void 0!==e.symbol,"At least one of tokenName or symbol is required");e.z.enum(["NATIVE","MEME"]),e.z.enum(["IN","OUT"]);const Fa=e.z.object({from:e.z.number().int("From timestamp must be an integer").min(173e6,"From timestamp must be at least 173000000"),to:e.z.number().int("To timestamp must be an integer").min(173e6,"To timestamp must be at least 173000000"),resolution:e.z.number().int("Resolution must be an integer").min(1,"Resolution must be at least 1"),tokenName:da});e.z.object({tokenName:da,slippageToleranceFactor:e.z.number().min(0).max(1).optional(),maxAcceptableReverseBondingCurveFeeSlippageFactor:e.z.number().min(0).max(1).optional(),privateKey:Ta.optional()});const Ba=e.z.object({offset:e.z.number().int().min(0).default(0),pageSize:e.z.number().int().min(1).max(100).default(10)}),Ua=e.z.object({offset:e.z.number().int().min(0).default(0),pageSize:e.z.number().int().min(1).max(20).default(10)}),Pa=e.z.object({offset:e.z.number().int().min(0).default(0),pageSize:e.z.number().int().min(1).max(20).default(10)});Ba.extend({type:e.z.enum(["RECENT","POPULAR"]).optional(),tokenName:e.z.string().min(1).max(50).optional(),search:e.z.string().min(1).max(100).optional()}),Ua.extend({tokenName:e.z.string().min(1).max(50).optional(),search:e.z.string().min(1).max(100).optional()}),Pa.extend({tradeType:e.z.enum(["BUY","SELL"]).optional(),tokenName:e.z.string().min(1).max(50).optional(),userAddress:e.z.string().regex(/^(0x[a-fA-F0-9]{40}|eth\|[a-fA-F0-9]{40})$/).optional(),startDate:e.z.string().datetime().optional(),endDate:e.z.string().datetime().optional(),sortOrder:e.z.enum(["ASC","DESC"]).default("DESC")});const Ma={page:e.z.number().int().min(1),limit:e.z.number().int().min(1),total:e.z.number().int().min(0),totalPages:e.z.number().int().min(0),hasNext:e.z.boolean(),hasPrevious:e.z.boolean()};e.z.object(Ma);const La=e.z.enum(["buy","sell"]);e.z.enum(["BUY","SELL"]),e.z.object({tradeType:La,tokenAmount:va,vaultAddress:ya,userAddress:fa,slippageTolerance:va.optional(),deadline:e.z.number().int().positive().optional()}),e.z.object({tokenSymbol:ua,nativeTokenQuantity:va,expectedToken:va,maxAcceptableReverseBondingCurveFee:ka.default("0").optional()}),e.z.object({tokenSymbol:ua,tokenQuantity:va,expectedNativeToken:va,maxAcceptableReverseBondingCurveFee:ka.default("0").optional()}),Pa.extend({tokenName:ga.optional()}),e.z.object({page:e.z.number().int().min(1).max(1e3).default(1).optional(),limit:e.z.number().int().min(1).max(20).default(10).optional()});const $a=e.z.enum(["NATIVE","MEME"]),Ka=e.z.enum(["IN","OUT"]);e.z.object({type:$a,method:Ka,vaultAddress:ya,amount:va}),e.z.object({nativeTokenQuantity:va}),e.z.object({vaultAddress:ya}),e.z.object({minFeePortion:va,maxFeePortion:va});const Ga=e.z.enum(["both","held","created"]);function Wa(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)}}}Ua.extend({type:Ga.optional(),address:fa.optional(),search:ma.optional(),tokenName:ga.optional()}),e.z.object({address:fa.optional(),refresh:e.z.boolean().optional()}),e.z.object({profileImage:e.z.string(),fullName:pa,address:fa,privateKey:Ta.optional()}),e.z.object({file:e.z.union([e.z.instanceof(File),e.z.instanceof(Buffer)]),address:fa.optional(),privateKey:Ta.optional()}),e.z.object({created:e.z.number(),createdBy:e.z.string(),expires:e.z.number(),instanceId:e.z.string(),lockAuthority:e.z.string(),name:e.z.string(),quantity:e.z.string(),vestingPeriodStart:e.z.number()}),e.z.object({address:fa,tokenId:e.z.union([e.z.string(),e.z.object({collection:e.z.string(),category:e.z.string(),type:e.z.string(),additionalKey:e.z.string()}),e.z.object({collection:e.z.string(),category:e.z.string(),type:e.z.string(),additionalKey:e.z.string(),instance:e.z.string()})]).optional(),tokenName:ga.optional(),withExpired:e.z.boolean().optional()}).refine(e=>void 0!==e.tokenId||void 0!==e.tokenName,"At least one token identifier (tokenId or tokenName) is required");const Ha=Wa(da),qa=Wa(xa),za=Wa(Oa);function ja(e){const t=function(e){const t=qa(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 Va(e,t){return"string"==typeof e[t]}function Xa(e,t){return void 0===e[t]||"string"==typeof e[t]}function Qa(e,t){return void 0===e[t]||"number"==typeof e[t]}function Ja(e,t){switch(t){case"string":return"string"==typeof e;case"number":return"number"==typeof e;case"boolean":return"boolean"==typeof e;case"object":return null!==e&&"object"==typeof e&&!Array.isArray(e);case"array":return Array.isArray(e);case"optional-string":return void 0===e||"string"==typeof e;case"optional-number":return void 0===e||"number"==typeof e;case"optional-boolean":return void 0===e||"boolean"==typeof e;case"optional-object":return void 0===e||null!==e&&"object"==typeof e&&!Array.isArray(e);case"optional-array":return void 0===e||Array.isArray(e);default:return!1}}function Ya(e){return t=>{if(null==t||"object"!=typeof t||Array.isArray(t))return!1;const n=t;for(const[t,a]of Object.entries(e)){if(!Ja(n[t],a))return!1}return!0}}Ln({BUY:"buy",SELL:"sell"});const Za=Ya({vaultAddress:"string"}),es=Ya({nativeTokenQuantity:"string"});function ts(e){if(Pn(e)||"object"!=typeof e)return{};const t={};for(const[n,a]of Object.entries(e))Pn(a)||(Un(a)?t[n]=a:"number"==typeof a||"boolean"==typeof a?t[n]=a.toString():Array.isArray(a)?t[n]=a.join(","):t[n]="object"==typeof a?JSON.stringify(a):String(a));return t}function ns(e,t="0"){return function(e,t="0"){if(Jt(e))return new d(t);if(d.isBigNumber(e))return e.isNaN()?new d(t):e;try{const n=new d(e);return n.isNaN()||!n.isFinite()?new d(t):n}catch{return new d(t)}}(e,t)}function as(e,t){return void 0!==t?ns(e).toFixed(t):ns(e).toFixed()}function ss(e){return ns(e).isZero()}function rs(e,t){return ns(e).isLessThan(ns(t))}function is(...e){e.forEach(e=>{if(e.isNaN())throw Bt("value","NaN");if(!e.isFinite())throw Ot("value","finite");if(e.isLessThanOrEqualTo(0))throw xt("value","0",e.toString())})}function os(e,t,n="0"){const a=ns(t);return ss(a)?ns(n):ns(e).dividedBy(a)}const cs={calculateBuyWithExact(e,t){const n=An(e),a=An(t),{BASE_PRICE:s,PRICE_SCALING_FACTOR:r,TRADING_FEE_FACTOR:i,GAS_FEE:o}=qt,c=function(e,t){const n=Math.pow(10,t);return Math.ceil(e*n)/n}(s*(Math.exp((a+n)*r)-Math.exp(a*r))/r,8),l=as(ns(c).multipliedBy(i));return{amount:c.toString(),reverseBondingCurveFee:"0",transactionFee:l,gasFee:o}},calculateBuyWithNative(e,t){const n=An(e),a=An(t),{BASE_PRICE:s,PRICE_SCALING_FACTOR:r,TRADING_FEE_FACTOR:i,GAS_FEE:o}=qt,c=Math.log(n*r/s+Math.exp(a*r))/r-a,l=as(ns(c).multipliedBy(i));return{amount:c.toString(),reverseBondingCurveFee:"0",transactionFee:l,gasFee:o}},calculateSellWithExact(e,t,n,a,s){const r=An(e),i=An(t),o=An(n),{BASE_PRICE:c,PRICE_SCALING_FACTOR:l,TRADING_FEE_FACTOR:d,GAS_FEE:u}=qt,h=c*(Math.exp(i*l)-Math.exp((i-r)*l))/l,g=ns(h),m=a+i/o*(s-a),p=as(g.multipliedBy(m),8),f=as(g.multipliedBy(d));return{amount:h.toString(),reverseBondingCurveFee:p,transactionFee:f,gasFee:u}},calculateSellWithNative(e,t,n,a,s){const r=An(e),i=An(t),o=An(n),{BASE_PRICE:c,PRICE_SCALING_FACTOR:l,TRADING_FEE_FACTOR:d,GAS_FEE:u}=qt;if(r>=c*(Math.exp(i*l)-1)/l){const e=ns(r),t=a+i/o*(s-a),n=as(e.multipliedBy(t),8),c=as(e.multipliedBy(d));return{amount:i.toString(),reverseBondingCurveFee:n,transactionFee:c,gasFee:u}}const h=i-Math.log(Math.exp(i*l)-r*l/c)/l,g=ns(r),m=a+i/o*(s-a),p=as(g.multipliedBy(m),8),f=as(g.multipliedBy(d));return{amount:h.toString(),reverseBondingCurveFee:p,transactionFee:f,gasFee:u}}};class ls extends Error{constructor(e,t,n){super(e),this.filename=t,this.mimeType=n,this.name="FileValidationError"}}function ds(e,t,n){if(null==e)throw new ls("File is required",t,n);if("undefined"!=typeof File&&e instanceof File){const t=Na.safeParse(e);if(!t.success){const n=t.error.issues.map(e=>e.message).join("; ");throw new ls(n,e.name,e.type)}return}if(Buffer.isBuffer(e)){if(void 0===t||""===t)throw new ls("Filename is required when uploading Buffer objects",t,n);const a=Ia.safeParse(e);if(!a.success){const e=a.error.issues.map(e=>e.message).join("; ");throw new ls(e,t,n)}try{xn(t,255,"filename")}catch(e){throw new ls(e.message,t,n)}const s=["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"];if(!s.includes(n))throw new ls(`Invalid file type "${n}" is not allowed. Allowed types: ${s.join(", ")}`,t,n);const r=function(e){if(null==e||""===e)return"";const t=e.lastIndexOf(".");if(-1===t)return"";return e.substring(t).toLowerCase()}(t),i=[".png",".jpg",".jpeg",".gif",".webp",".svg"];if(!i.includes(r))throw new ls(`File extension "${r}" is not allowed. Allowed extensions: ${i.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"}}(r);if(o!==n&&"application/octet-stream"!==o)throw new ls(`File extension "${r}" does not match MIME type "${n}"`,t,n);return}throw new ls("File must be a File object (browser) or Buffer (Node.js)",t,n)}class us{validate(e,t={}){const{allowZero:n=!0,minimum:a,maximum:s,maxDecimals:r=us.MAX_DECIMAL_PLACES,fieldName:i="amount"}=t;if(!Un(e))throw new kt(`${i} cannot be empty or whitespace-only. Provide a valid numeric string.`,i,"INVALID_NUMERIC_STRING");if(/[eE]/.test(e))throw new kt(`${i} cannot use scientific notation. Use standard decimal format (e.g., "1000" instead of "1e3").`,i,"INVALID_NUMERIC_STRING");const o=An(e,NaN);if(isNaN(o))throw new kt(`${i} must be a valid numeric string. Received: "${e}"`,i,"INVALID_NUMERIC_STRING");if(!isFinite(o))throw new kt(`${i} must be a finite number. Cannot be Infinity or -Infinity.`,i,"INVALID_NUMERIC_STRING");if(o<0)throw new kt(`${i} must be non-negative. Received: "${e}"`,i,"INVALID_NUMERIC_STRING");if(!n&&0===o)throw new kt(`${i} must be greater than zero. Received: "${e}"`,i,"INVALID_NUMERIC_STRING");const c=ns(e),l=c.decimalPlaces()??0;if(l>r)throw new kt(`${i} cannot exceed ${r} decimal places. Received: ${l} decimal places`,i,"PRECISION_EXCEEDED");if(void 0!==a&&rs(c,a))throw new kt(`${i} must be at least ${a}. Received: "${e}"`,i,"BELOW_MINIMUM");if(void 0!==s&&(d=s,ns(c).isGreaterThan(ns(d))))throw new kt(`${i} cannot exceed ${s}. Received: "${e}"`,i,"EXCEEDS_MAXIMUM");var d}parseAmount(e,t="0"){return ns(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 as(e,t)}clampAmount(e,t,n){const a=ns(e),s=ns(t),r=ns(n);return function(e,t,n){const a=ns(e),s=ns(t),r=ns(n);return a.isGreaterThanOrEqualTo(s)&&a.isLessThanOrEqualTo(r)}(a,s,r)?as(a):rs(a,s)?as(s):as(r)}}function hs(e,t){throw new kt(e.join("; "),t,"VALIDATION_ERROR")}function gs(e){const t=Ha(e);!t.success&&t.errors&&hs(t.errors,"tokenName")}function ms(e){const t=Fa.safeParse(e);var n;t.success||hs((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 ps(e,t,n=!0){fs.validate(e,{fieldName:t,allowZero:n})}us.MAX_DECIMAL_PLACES=18,us.MIN_POSITIVE="0.00000000000000001";const fs=new us;function ys(e,t,n=as){if(!Array.isArray(e))throw Nt("Invalid API response: expected array of holders",t);for(const n of e){if(!vs(n))throw Nt("Invalid holder data: missing or invalid owner field",t);if(!ks(n))throw Nt("Invalid holder data: missing or invalid quantity field",t);const e=An(n.quantity,NaN);if(isNaN(e)||!isFinite(e))throw Nt(`Invalid holder quantity: "${n.quantity}"`,t)}const a=e,s=a.reduce((e,t)=>e.plus(t.quantity),ns(0));return{holders:a.map(e=>({address:e.owner,balance:e.quantity,percentage:os(ns(e.quantity),s,ns(0)).multipliedBy(100).toNumber()})),totalSupply:n(s),totalHolders:a.length,lastUpdated:new Date}}function vs(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.owner&&""!==t.owner}function ks(e){return"string"==typeof e.quantity&&""!==e.quantity}class bs{constructor(e,t,n,a,s,r,i="local",o){this.http=e,this.tokenResolver=t,this.logger=n,this.bundleHttp=a,this.galaChainHttp=s,this.dexApiHttp=r,this.defaultCalculateAmountMode=i,this.launchpadWrites=o,this.metadataCache=new Yn}createSale(e){if(void 0===this.launchpadWrites)throw new Error("Launchpad write transport is not configured.");return this.launchpadWrites.createSale(e)}addIfDefined(e,t,n){return void 0!==n&&(e[t]=n),e}async uploadImageByTokenName(e){const{tokenName:t,options:n}=e;gs(t);const a=`${t}.png`;ds(n.file,a,"image/png");try{const e=new FormData;if("undefined"!=typeof File&&n.file instanceof File)e.append("image",n.file);else{if(!Buffer.isBuffer(n.file))throw Ct("file","a File object (browser) or Buffer (Node.js)");{const a=`${void 0!==n.tokenName&&""!==n.tokenName?n.tokenName:t}.png`,s=new Blob([n.file],{type:"image/png"});e.append("image",s,a)}}const a=await this.http.request({method:"POST",url:`/launchpad/upload-image?tokenName=${encodeURIComponent(void 0!==n.tokenName&&""!==n.tokenName?n.tokenName:t)}`,data:e,headers:{}});if(!0===a.error||200!==a.status)throw Nt(void 0!==a.message&&""!==a.message?a.message:"Image upload failed - no URL returned",a.status);const s=Lt(a);if(!s?.imageUrl)throw Nt("Image upload failed - no URL returned",a.status);return s.imageUrl}catch(e){if(at(e)&&e.message.includes("FormData"))throw It("File upload failed: FormData not supported in this environment. Ensure you have proper polyfills for Node.js environments.","FormData");throw e}}async fetchPoolsFromAPI(e){void 0!==e.pageSize&&Mn(0,void 0,100,e.pageSize),void 0!==e.tokenName&&""!==e.tokenName&&gs(e.tokenName);const t={pageSize:String(e.pageSize??10)};void 0!==e.cursor&&(t.cursor=e.cursor),void 0!==e.type&&(t.type=e.type),void 0!==e.tokenName&&(t.tokenName=e.tokenName),void 0!==e.search&&(t.search=e.search),void 0!==e.hasUpcomingShows&&(t.hasUpcomingShows=e.hasUpcomingShows.toString()),void 0!==e.language&&(t.language=e.language),void 0!==e.recentlyStreamed&&(t.recentlyStreamed=e.recentlyStreamed.toString());const n=ts(t),a=await this.http.get(p.FETCH_POOLS,n);if(!0===a.error||200!==a.status)throw Nt(void 0!==a.message&&""!==a.message?a.message:"Failed to fetch pools",a.status);const s=Lt(a);if(null==s)throw Nt("Failed to fetch pools - no data returned",a.status);let r=[];if(s.tokens)if(Array.isArray(s.tokens))r=s.tokens.map(e=>this.normalizePoolData(e));else{const e=s.tokens;r=[this.normalizePoolData(e)]}else s.pools&&Array.isArray(s.pools)&&(r=s.pools.map(e=>this.normalizePoolData(e)));const{extractMetadataFromPoolData:i,isValidPoolForCaching:o}=await Promise.resolve().then(function(){return wu});r.forEach(e=>{if(!o(e))return void this.logger.debug("Skipping pool with invalid structure for caching",e);const t=i(e,this.logger);t&&this.warmCacheFromPoolData(e.tokenName,t)});const c=s.count??s.total??0,l={hasNextPage:s.hasNextPage??!1};return void 0!==s.hasPrevPage&&(l.hasPrevPage=s.hasPrevPage),void 0!==s.nextCursor&&(l.nextCursor=s.nextCursor),void 0!==s.prevCursor&&(l.prevCursor=s.prevCursor),c>0&&(l.totalCount=c),{items:r,pageInfo:l}}async fetchPools(e={}){let t;"recent"===e.type?t="RECENT":"popular"===e.type&&(t="POPULAR");const n={pageSize:e.pageSize??10};return void 0!==e.cursor&&(n.cursor=e.cursor),void 0!==e.search&&""!==e.search&&(n.search=e.search),void 0!==e.tokenName&&""!==e.tokenName&&(n.tokenName=e.tokenName),null!=t&&(n.type=t),void 0!==e.hasUpcomingShows&&(n.hasUpcomingShows=e.hasUpcomingShows),void 0!==e.language&&""!==e.language&&(n.language=e.language),void 0!==e.recentlyStreamed&&(n.recentlyStreamed=e.recentlyStreamed),this.fetchPoolsFromAPI(n)}async calculateBuyAmount(e){if(null==e||"object"!=typeof e)throw Ct("options","an options object");const{tokenName:t,amount:n,type:a,currentSupply:s}=e;return"external"===this.validateAmountCalculationInputs(t,n,a,e.mode,[tt,nt],'"native" or "exact"')?this.calculateBuyAmountExternal({tokenName:t,amount:n,type:a}):this.calculateBuyAmountLocal(this.addIfDefined({tokenName:t,amount:n,type:a},"currentSupply",s))}async calculateBuyAmountExternal(e){const{tokenName:t,amount:n,type:a}=e;return this.validateExternalAmountInputs(t,n),"exact"===a?Kt(()=>this.http.get(je,{tokenName:t,amount:n,type:"MEME",method:"OUT"}),{errorContext:`Failed to calculate buy amount for ${t} (exact tokens)`}):Kt(()=>this.http.get(je,{tokenName:t,amount:n,type:"NATIVE",method:"IN"}),{errorContext:`Failed to calculate buy amount for ${t} (native/GALA budget)`})}async calculateSellAmount(e){const{tokenName:t,amount:n,type:a,currentSupply:s,maxSupply:r,reverseBondingCurveMaxFeeFactor:i,reverseBondingCurveMinFeeFactor:o}=e;if("external"===this.validateAmountCalculationInputs(t,n,a,e.mode,[nt,tt],'"exact" or "native"'))return this.calculateSellAmountExternal({tokenName:t,amount:n,type:a});{const e={tokenName:t,amount:n,type:a,...void 0!==s&&{currentSupply:s},...void 0!==r&&{maxSupply:r},...void 0!==i&&{reverseBondingCurveMaxFeeFactor:i},...void 0!==o&&{reverseBondingCurveMinFeeFactor:o}};return this.calculateSellAmountLocal(e)}}async calculateSellAmountExternal(e){const{tokenName:t,amount:n,type:a}=e;return this.validateExternalAmountInputs(t,n),"exact"===a?Kt(()=>this.http.get(je,{tokenName:t,amount:n,type:"MEME",method:"IN"}),{errorContext:`Failed to calculate sell amount for ${t} (exact tokens)`}):Kt(()=>this.http.get(je,{tokenName:t,amount:n,type:"NATIVE",method:"OUT"}),{errorContext:`Failed to calculate sell amount for ${t} (native/GALA target)`})}async calculateBuyAmountLocal(e){const{tokenName:t,amount:n,type:a,currentSupply:s}=e;if(!Un(n))throw Tt("amount","Amount");if(a!==tt&&a!==nt)throw Ft("type",'"native" or "exact"',a);void 0!==s&&ps(s,"currentSupply");const r=null==s||""===s;if(r&&(null==t||""===t))throw Tt("tokenName","Token name (required when currentSupply is not provided)");null!=t&&""!==t&&gs(t);let i=s;if(r){i=(await this.fetchPoolDetailsForCalculation(t)).currentSupply}return a===nt?cs.calculateBuyWithExact(n,i):cs.calculateBuyWithNative(n,i)}async calculateSellAmountLocal(e){const{tokenName:t,amount:n,type:a,currentSupply:s,maxSupply:r,reverseBondingCurveMaxFeeFactor:i,reverseBondingCurveMinFeeFactor:o}=e;if(!Un(n))throw Tt("amount","Amount");if(a!==nt&&a!==tt)throw Ft("type",'"exact" or "native"',a);void 0!==s&&ps(s,"currentSupply");const c=null==s||""===s||null==r||""===r||void 0===i||void 0===o;if(c&&(null==t||""===t))throw Tt("tokenName","Token name (required when currentSupply, maxSupply, or fee factors are not provided)");null!=t&&""!==t&&gs(t);let l=s,d=r,u=i,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 a===nt?cs.calculateSellWithExact(n,l,d,h,u):cs.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 Va(t,"tokenName")&&function(e){return void 0===e.calculateAmountMode||"local"===e.calculateAmountMode||"external"===e.calculateAmountMode}(t)&&Xa(t,"currentSupply")}(e))throw Ft("options","CalculateBuyAmountForGraduationOptions or string (token name)",typeof e);const{tokenName:n,calculateAmountMode:a,currentSupply:s}=t;gs(n);const r=await this.fetchSaleDetails(n),i=s??as(ns(r.maxSupply).minus(r.sellingTokenQuantity)),o=r.sellingTokenQuantity;if("0"===o)throw Tt("tokenName",`Token ${n} is already graduated (no tokens remaining in pool)`);const c={tokenName:n,amount:o,type:"exact",currentSupply:i,...void 0!==a&&{mode:a}};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 It("Bundle backend client not configured. LaunchToken requires bundleHttp client.","bundleHttp");ja(e);const t=void 0!==e.preBuyQuantity&&""!==e.preBuyQuantity?e.preBuyQuantity:"0",n=An(t);if(0===n&&"0"!==t)throw Bt("preBuyQuantity",t,"Pre-buy quantity");if(n<0)throw Bt("preBuyQuantity",t,"Pre-buy quantity");if(e.reverseBondingCurveConfiguration){const{minFeePortion:t,maxFeePortion:n}=e.reverseBondingCurveConfiguration;!function(e,t,n){const a="string"==typeof e?parseFloat(e):e,s="string"==typeof t?parseFloat(t):t;if(!isFinite(a))throw new kt(`${n} minFee must be a valid finite number`,n,"INVALID_FEE_MINIMUM");if(!isFinite(s))throw new kt(`${n} maxFee must be a valid finite number`,n,"INVALID_FEE_MAXIMUM");if(a<.1)throw new kt(`${n} minFee must be >= 0.1, received ${a}`,n,"INVALID_FEE_MINIMUM");if(s>.5)throw new kt(`${n} maxFee must be <= 0.5, received ${s}`,n,"INVALID_FEE_MAXIMUM");if(a>s)throw new kt(`${n} minFee (${a}) must be <= maxFee (${s})`,n,"INVALID_FEE_RANGE")}(t,n,"reverseBondingCurve")}throw new Error("Legacy launchToken signing is unavailable; configure the v6 launchpad write transport.")}async fetchTokenDistribution(e){if(null==e||""===e)throw Tt("tokenName","Token name");gs(e);const t=await this.http.get(`/holders/${e}`);if(!0===t.error||200!==t.status)throw Nt(void 0!==t.message&&""!==t.message?t.message:"Failed to fetch token distribution",t.status);const n=Lt(t);if(null==n)throw Nt("Failed to fetch token distribution - no data returned",t.status);return ys(n,t.status)}async calculateInitialBuyAmount(e){if(!es(e))throw Ct("data","valid pre-mint calculation data");if(!this.galaChainHttp)throw It("GalaChain HTTP client not available. Please initialize SDK with gatewayBaseUrl.","galaChainHttp");try{const t={vaultAddress:"service|testToken",nativeTokenQuantity:e.nativeTokenQuantity,IsPreMint:!0},n=await this.galaChainHttp.post("/api/asset/launchpad-contract/CallMemeTokenOut",t);if(!function(e){if(null==e||"object"!=typeof e)return!1;const t=e,n=t.Status,a=t.Data;if("number"!=typeof n||"object"!=typeof a||null===a)return!1;const s=a,r=s.calculatedQuantity,i=s.extraFees;if("string"!=typeof r||"object"!=typeof i||null===i)return!1;const o=i;return"string"==typeof o.reverseBondingCurve&&"string"==typeof o.transactionFees}(n))throw Nt("Malformed response data from GalaChain gateway");try{ct(n,"Pre-mint calculation")}catch(e){throw Nt(st(e),500)}const{calculatedQuantity:a,extraFees:s}=n.Data;return{amount:a,reverseBondingCurveFee:s.reverseBondingCurve,transactionFee:s.transactionFees,gasFee:"1"}}catch(e){if(at(e)&&e instanceof bt)throw e;throw Nt(st(e),500)}}async fetchPoolDetailsForCalculation(e){const t=await this.fetchSaleDetails(e),n=as(ns(t.maxSupply).minus(t.sellingTokenQuantity)),a=t.sellingTokenQuantity,s=t.maxSupply;let r=.5,i=.1;const o=t.reverseBondingCurveConfiguration;null!=o?.maxFeePortion&&(r=Nn(o.maxFeePortion,.5)),null!=o?.minFeePortion&&(i=Nn(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=r-i;return this.metadataCache.set(e,{maxSupply:s,reverseBondingCurveMaxFeeFactor:r,reverseBondingCurveMinFeeFactor:i,reverseBondingCurveNetFeeFactor:c}),{currentSupply:n,remainingTokens:a,maxSupply:s,reverseBondingCurveMaxFeeFactor:r,reverseBondingCurveMinFeeFactor:i,reverseBondingCurveNetFeeFactor:c}}async fetchCurrentSupply(e){gs(e);const t=await this.fetchSaleDetails(e),n=as(ns(t.maxSupply).minus(t.sellingTokenQuantity)),a=t.maxSupply;return this.metadataCache.set(e,{maxSupply:a}),n}normalizePoolData(e){const t=e.reverseBondingCurveMinFeePortion??"0",n=e.reverseBondingCurveMaxFeePortion??"0";return{...e,reverseBondingCurveMinFeePortion:t,reverseBondingCurveMaxFeePortion:n,hasReverseBondingCurveFee:!ss(t)||!ss(n),createdAt:void 0!==e.created_at&&""!==e.created_at?e.created_at:void 0!==e.createdAt&&""!==e.createdAt?e.createdAt:""}}async fetchSaleDetails(e){const t=await this.tokenResolver.resolveTokenToVault(e);if(null==t||""===t)throw new kt(ht(e),"tokenName","VAULT_NOT_FOUND");if(void 0===this.galaChainHttp||null===this.galaChainHttp)throw It("GalaChain HTTP client not configured");const n=await this.galaChainHttp.post("/api/asset/launchpad-contract/FetchSaleDetails",{vaultAddress:t});if(1!==n.Status)throw Nt(`Failed to fetch pool details: Status ${n.Status}`,n.Status);return n.Data}validateAmountCalculationInputs(e,t,n,a,s,r){const i=a??this.defaultCalculateAmountMode;if("local"!==i&&"external"!==i)throw Ft("mode",'"local" or "external"',i);if(!Un(e))throw Tt("tokenName","Token name");if(!Un(t))throw Tt("amount","Amount");if("string"!=typeof n||!s.includes(n))throw Ft("type",r,n);return i}validateExternalAmountInputs(e,t){if("string"!=typeof e||""===e)throw new kt("Token name must be a non-empty string","tokenName","INVALID_TOKEN_NAME");if("string"!=typeof t||""===t)throw new kt("Amount must be a non-empty string","amount","INVALID_AMOUNT")}getAddress(){return this.http.getAddress()}formatAddressForBackend(e){return sa(e)}validateTokenName(e){return gs(e)}validatePagination(e){void 0!==e.pageSize&&Mn(0,void 0,100,e.pageSize)}async fetchTokenPrice(e){if(void 0===this.dexApiHttp||null===this.dexApiHttp)throw It("DEX API client not configured. Token price fetching requires dexApiHttp client.","dexApiHttp");if(null==e||""===e||Array.isArray(e)&&0===e.length)throw Tt("symbols","At least one symbol");const t=Array.isArray(e)?e.join(","):e;try{const e=await this.dexApiHttp.request({method:"GET",url:"/v1/tokens",params:{symbols:t}}),n=[];return void 0!==e.tokens&&null!==e.tokens&&Array.isArray(e.tokens)&&e.tokens.forEach(e=>{void 0!==e.currentPrices&&null!==e.currentPrices&&void 0!==e.symbol&&null!==e.symbol&&n.push({symbol:e.symbol,price:e.currentPrices.usd})}),n}catch(e){throw Nt(`Failed to fetch token prices: ${st(e)}`,void 0,at(e)?e:void 0)}}warmCacheFromPoolData(e,t){this.metadataCache.warmFromPoolData(e,t)}getCacheStats(){return this.metadataCache.getStats()}clearCache(e){this.metadataCache.clear(e)}}const ws=3e5,Ss="Sign in to Launchpad t:",As="Authorization",Es="Bearer ";class Ts{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 Cs,Ns;!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"}(Cs||(Cs={}));class Is extends Error{constructor(e,t,n){super(t),this.type=e,this.originalError=n,this.name="AuthError"}}class Ds{constructor(e,t=ws){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 Ts,this.refreshThresholdMs=t}setToken(e,t){if(!Un(e))throw new Is(Cs.SIGNATURE_FAILED,"JWT token must be a non-empty string");if("number"!=typeof t)throw new Is(Cs.SIGNATURE_FAILED,"Token expiration must be a positive finite number (seconds)");if(!Number.isFinite(t))throw new Is(Cs.SIGNATURE_FAILED,"Token expiration must be a positive finite number (seconds)");if(t<=0)throw new Is(Cs.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,a){if(this.setToken(e,t),n){const e=Date.now()+1e3*(a??7776e3);if(!this.tokenState)throw new Is(Cs.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:`${Es}${e}`}getJwtHeaders(){const e=this.getAuthorizationHeader();if(null===e||""===e)throw new Is(Cs.WALLET_NOT_CONNECTED,"No JWT token available. Call login() first.");return{[As]: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 a=Date.now();this.tokenState={token:e,issuedAt:a,expiresAt:n};const s=await this.storage.get(this.STORAGE_KEYS.REFRESH_TOKEN),r=await this.storage.get(this.STORAGE_KEYS.REFRESH_EXPIRES);if(s&&r){const e=Number(r);Number.isFinite(e)&&Date.now()<e&&(this.tokenState.refreshToken=s,this.tokenState.refreshExpiresAt=e)}return!0}async clear(){this.tokenState=null,await this.storage.remove(this.STORAGE_KEYS.ACCESS_TOKEN),await this.storage.remove(this.STORAGE_KEYS.ACCESS_EXPIRES),await this.storage.remove(this.STORAGE_KEYS.REFRESH_TOKEN),await this.storage.remove(this.STORAGE_KEYS.REFRESH_EXPIRES)}isValid(){return this.hasToken()&&!this.isExpired()}getDebugInfo(){return{hasToken:this.hasToken(),isExpired:this.isExpired(),shouldRefresh:this.shouldRefresh(),timeUntilExpiryMs:this.getTimeUntilExpiry(),expiresAt:this.tokenState?new Date(this.tokenState.expiresAt):null}}}async function _s(e,t,n,a){try{return await e()}catch(e){throw a?(a(e,t,n),new Error("Unreachable after error handler")):(n&&n.error(`${t}:`,e),_t(e,t,n))}}function Rs(e,t,n,a){try{return e()}catch(e){throw a?(a(e,t,n),new Error("Unreachable after error handler")):(n&&n.error(`${t}:`,e),_t(e,t,n))}}class xs{constructor(e,t,n,a=!1){this.http=e,this.signatureAuth=t,this.jwtAuth=n,this.refreshPromise=null,this.loginPromise=null,this.logger=new Qt({debug:a,context:"SessionAuthService"})}async login(){if(this.loginPromise)return this.logger.debug("Login already in progress, reusing existing promise"),this.loginPromise;if(!this.signatureAuth.hasWallet())throw new Is(Cs.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 _s(async()=>{const e=Date.now(),t=`${Ss}${e}`;this.logger.debug("Generating login signature",{message:t,timestamp:e});const n=await this.signatureAuth.signMessage(t),a=this.signatureAuth.getAddress();oa(a,"address");const s={address:a,message:t,signature:n.signature};let r;try{this.logger.debug("Sending login request with refresh token support",{address:a,message:t}),r=await this.http.post(M,{...s,includeRefreshToken:!0})}catch(e){if(400!==e.statusCode)throw e;this.logger.debug("Login returned 400, retrying without includeRefreshToken (backend may not support it)"),r=await this.http.post(M,s)}const i=this.extractLoginData(r);return await this.jwtAuth.setTokens(i.accessToken,i.expiresIn,i.refreshToken,i.refreshExpiresIn),this.logger.debug("Login successful",{address:i.address,expiresIn:i.expiresIn,hasRefreshToken:!!i.refreshToken}),i},"SessionAuthService.performLogin",this.logger,e=>{if(e instanceof Is)throw e;throw new Is(Cs.SIGNATURE_FAILED,`Login failed: ${st(e)}`,at(e)?e:void 0)})}async refresh(){if(this.refreshPromise)return this.logger.debug("Refresh already in progress, reusing existing promise"),this.refreshPromise;if(!this.jwtAuth.hasToken())throw new Is(Cs.WALLET_NOT_CONNECTED,"No token to refresh. Call login() first.");this.refreshPromise=this.performRefresh();try{return await this.refreshPromise}finally{this.refreshPromise=null}}async performRefresh(){return _s(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($,{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($,{},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 Is)throw e;throw new Is(Cs.SIGNATURE_FAILED,`Token refresh failed: ${st(e)}`,at(e)?e:void 0)})}async logout(e){this.logger.debug("Logging out",{allDevices:e?.allDevices});const t=e?.allDevices??!1;if(t&&this.jwtAuth.hasToken()&&!this.jwtAuth.isExpired())try{await this.http.post(L,{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): ${st(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 Is(Cs.WALLET_NOT_CONNECTED,"Not authenticated. Call login() first.");return _s(async()=>{const e=await this.http.get(K,void 0,this.jwtAuth.getJwtHeaders());return this.extractSessionData(e)},"SessionAuthService.getSession",this.logger,e=>{if(e instanceof Is)throw e;throw new Is(Cs.SIGNATURE_FAILED,`Failed to get session: ${st(e)}`,at(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(!this.jwtAuth.hasToken())throw new Is(Cs.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: ${st(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 Is(Cs.SIGNATURE_FAILED,""!==st(e)?st(e):"Authentication failed");const t=$t(e,"No data in authentication response"),{accessToken:n,expiresIn:a,address:s,refreshToken:r,refreshExpiresIn:i}=t;if(!Un(n))throw new Is(Cs.SIGNATURE_FAILED,"Invalid access token in response");if("number"!=typeof a||a<=0)throw new Is(Cs.SIGNATURE_FAILED,"Invalid expiration in response");return{accessToken:n,expiresIn:a,address:s,...void 0!==r&&{refreshToken:r},...void 0!==i&&{refreshExpiresIn:i}}}extractSessionData(e){if(e.error)throw new Is(Cs.SIGNATURE_FAILED,""!==st(e)?st(e):"Failed to get session");return $t(e,"No data in session response")}}class Os extends Error{constructor(e,t,n){super(e),this.code=t,this.originalError=n,this.name="WalletProviderError"}}!function(e){e.USER_REJECTED="USER_REJECTED",e.NOT_CONNECTED="NOT_CONNECTED",e.CONNECTION_FAILED="CONNECTION_FAILED",e.SIGNING_FAILED="SIGNING_FAILED",e.PROVIDER_NOT_AVAILABLE="PROVIDER_NOT_AVAILABLE",e.PRIVATE_KEY_NOT_ACCESSIBLE="PRIVATE_KEY_NOT_ACCESSIBLE",e.INVALID_CONFIG="INVALID_CONFIG",e.CHAIN_MISMATCH="CHAIN_MISMATCH",e.UNKNOWN="UNKNOWN"}(Ns||(Ns={}));class Fs{constructor(e){this.providerType="privateKey",this.connected=!0;try{this.wallet=new t.Wallet(e)}catch(e){throw new Os("Invalid private key provided",Ns.INVALID_CONFIG,e instanceof Error?e:void 0)}}static fromWallet(e){return new Fs(e.privateKey)}async signMessage(e){try{return await this.wallet.signMessage(e)}catch(e){throw new Os("Failed to sign message",Ns.SIGNING_FAILED,e instanceof Error?e:void 0)}}async signTypedData(e,t,n){try{return await this.wallet.signTypedData(e,t,n)}catch(e){throw new Os("Failed to sign typed data",Ns.SIGNING_FAILED,e instanceof Error?e:void 0)}}getAddress(){return Promise.resolve(t.getAddress(this.wallet.address))}async getGalaAddress(){return`eth|${(await this.getAddress()).slice(2)}`}async connect(){return this.connected=!0,this.getAddress()}disconnect(){return this.connected=!1,Promise.resolve()}isConnected(){return this.connected}getPrivateKey(){return Promise.resolve(this.wallet.privateKey)}getWallet(){return this.wallet}}class Bs{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{Fn(e.messagePrefix,"messagePrefix",!1)}catch{throw new Is(Cs.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=Fs.fromWallet(this.wallet),this.cachedAddress=this.wallet.address,this.cachedGalaAddress=sa(this.wallet.address)}catch(e){if(e instanceof Is)throw e;if(e instanceof kt&&("INVALID_ADDRESS"===e.code||"INVALID_FORMAT"===e.code||"address"===e.field))throw new Is(Cs.INVALID_ADDRESS,e.message);if(null!==e&&"object"==typeof e&&"message"in e)throw new Is(Cs.WALLET_NOT_CONNECTED,e.message);throw e}}setWallet(e){if(void 0!==e){if("object"!=typeof e||!("address"in e))throw new Is(Cs.WALLET_NOT_CONNECTED,"Invalid wallet: must be an ethers Wallet instance or undefined");if("string"!=typeof e.address||""===e.address)throw new Is(Cs.INVALID_ADDRESS,"Wallet address is not available");this.walletProvider=Fs.fromWallet(e),this.cachedAddress=e.address,this.cachedGalaAddress=sa(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,this.cachedAddress=void 0,this.cachedGalaAddress=void 0}getWalletProvider(){return this.walletProvider}async cacheAddress(){this.walletProvider&&(this.cachedAddress=await this.walletProvider.getAddress(),this.cachedGalaAddress=await this.walletProvider.getGalaAddress())}async generateSignature(){await this.validateWalletAsync();try{const e=Date.now(),t=`${this.messagePrefix} ${e}`,n=await this.walletProvider.signMessage(t);return{message:t,signature:n,address:await this.walletProvider.getGalaAddress(),timestamp:e}}catch(e){if(e instanceof Is)throw e;throw new Is(Cs.SIGNATURE_FAILED,"Failed to generate signature for authentication",at(e)?e:new Error(st(e)))}}getAddress(){if(this.validateWallet(),this.cachedGalaAddress)return this.cachedGalaAddress;if(this.wallet)return this.formatAddress(this.wallet.address);throw new Is(Cs.WALLET_NOT_CONNECTED,"Address not available. For external wallets, call cacheAddress() after connecting.")}async getAddressAsync(){return await this.validateWalletAsync(),this.walletProvider.getGalaAddress()}getEthereumAddress(){if(this.validateWallet(),this.cachedAddress)return this.cachedAddress;if(this.wallet)return this.wallet.address;throw new Is(Cs.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 Is(Cs.WALLET_NOT_CONNECTED,"Wallet private key not available for @gala-chain signing");return this.wallet.privateKey}if("privateKey"===this.walletProvider?.providerType){return this.walletProvider.getWallet().privateKey}throw new Is(Cs.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 Is(Cs.WALLET_NOT_CONNECTED,"Private key not available with this wallet provider");try{return await this.walletProvider.getPrivateKey()}catch(e){throw new Is(Cs.WALLET_NOT_CONNECTED,"Private key not available. External wallet providers cannot access private keys. Use PrivateKeyProvider for @gala-chain signing operations.",at(e)?e:void 0)}}formatAddress(e){try{return sa(e)}catch{throw new Is(Cs.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 Is)throw e;throw new Is(Cs.SIGNATURE_FAILED,st(e),at(e)?e:new Error(st(e)))}}async generateAuthHeaders(e,t){await this.validateWalletAsync();try{const n=Date.now(),a=`${this.messagePrefix} ${t.toUpperCase()} ${e} ${n}`,s=await this.walletProvider.signMessage(a);return{"x-signature":s,"x-address":await this.walletProvider.getGalaAddress(),"x-message":a,"x-timestamp":n.toString()}}catch(e){if(e instanceof Is)throw e;throw new Is(Cs.SIGNATURE_FAILED,"Failed to generate authentication headers",at(e)?e:new Error(st(e)))}}async signTypedData(e,t,n){await this.validateWalletAsync();try{const a={};for(const[e,n]of Object.entries(t))a[e]=n.map(e=>({name:e.name,type:e.type}));return await this.walletProvider.signTypedData(e,a,n)}catch(e){if(e instanceof Is)throw e;throw new Is(Cs.SIGNATURE_FAILED,"Failed to sign typed data",at(e)?e:new Error(st(e)))}}async generateCustomSignature(e){if(!Un(e))throw new Is(Cs.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 Is)throw e;throw new Is(Cs.SIGNATURE_FAILED,"Failed to generate custom message signature",at(e)?e:new Error(st(e)))}}validateWallet(){if(this.ensureWalletProvider(),!this.walletProvider)throw new Is(Cs.WALLET_NOT_CONNECTED,"Wallet is required for authentication")}async validateWalletAsync(){if(this.ensureWalletProvider(),!this.walletProvider)throw new Is(Cs.WALLET_NOT_CONNECTED,"Wallet is required for authentication");if(!this.walletProvider.isConnected())throw new Is(Cs.WALLET_NOT_CONNECTED,"Wallet is not connected. Call connect() on the wallet provider first.")}}const Us={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",gatewayBaseUrl:"https://gateway-mainnet.galachain.com",webSocketUrl:"https://bundle-backend-prod1.defi.gala.com",gdexWebSocketUrl:"wss://dex-backend-prod1.defi.gala.com/ws",dexApiBaseUrl:"https://dex-api-platform-dex-prod-gala.gala.com",launchpadFrontendUrl:"https://lpad-frontend-prod1.defi.gala.com"},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",gatewayBaseUrl:"https://gateway-testnet.galachain.com",webSocketUrl:"https://bundle-backend.stage.defi.ovh.gala.com",gdexWebSocketUrl:"wss://swap-backend.stage.defi.ovh.gala.com/ws",dexApiBaseUrl:"https://dex-api-platform-dex-stage-gala.gala.com",launchpadFrontendUrl:"https://lpad-frontend-test1.defi.gala.com"}};function Ps(e){return Us[e]}function Ms(e){return`${e.collection}|${e.category}|${e.type}|${e.additionalKey}`}function Ls(e){return`${e.collection}$${e.category}$${e.type}$${e.additionalKey}`}const $s=1,Ks=2,Gs=1002,Ws=1,Hs=3,qs=[{symbol:"GALA",amount:"1",contractAddress:"0xd1d2Eb1B1e90B638588728b4130137D262C87cae",bridgeUsesPermit:!0,decimals:8},{symbol:"GWETH",amount:"0.0001",contractAddress:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",bridgeUsesPermit:!1,decimals:18},{symbol:"GUSDC",amount:"1",contractAddress:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",bridgeUsesPermit:!1,decimals:6},{symbol:"GUSDT",amount:"1",contractAddress:"0xdAC17F958D2ee523a2206206994597C13D831ec7",bridgeUsesPermit:!1,decimals:6},{symbol:"GWTRX",amount:"1",contractAddress:"0x50327c6c5a14DCaDE707ABad2E27eB517df87AB5",bridgeUsesPermit:!1,decimals:6},{symbol:"GWBTC",amount:"0.00001",contractAddress:"0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599",bridgeUsesPermit:!1,decimals:8}],zs=[{symbol:"GALA",amount:"1",contractAddress:"0x9fBFf09325C1967A135AC9b4860b1cf89aca52DA",bridgeUsesPermit:!0,decimals:8},{symbol:"GWETH",amount:"0.0001",contractAddress:"0xC3F00B9CbC4221D85A66EEbe928551d0d8dD9158",bridgeUsesPermit:!1,decimals:18},{symbol:"GUSDC",amount:"1",contractAddress:"0x081e78E33bfa612b23A99ef61e7c194649AA318E",bridgeUsesPermit:!1,decimals:6},{symbol:"GUSDT",amount:"1",contractAddress:"0x461e3595f087bfb0E32B6e44BCbF4C74D99B0001",bridgeUsesPermit:!1,decimals:6},{symbol:"GWBTC",amount:"0.00001",contractAddress:"0x5f69276935EF17e5aF5289b60aFBf6d48B344770",bridgeUsesPermit:!1,decimals:8}];function js(e){return"prod"===e?qs:zs}function Vs(e){return"prod"===e?"0x9f452b7cC24e6e6FA690fe77CF5dD2ba3DbF1ED9":"0x6a1734E09f3099a3675645D214ce547080ea67e0"}const Xs=qs,Qs=[{symbol:"GALA",amount:"1",mintAddress:"eEUiUs4JWYZrp72djAGF1A8PhpR6rHphGeGN7GbVLp6",isNative:!1,decimals:8},{symbol:"GSOL",amount:"0.001",mintAddress:"So11111111111111111111111111111111111111111",isNative:!0,decimals:9}],Js={GALA:{descriptor:{collection:"GALA",category:"Unit",type:"none",additionalKey:"none"},decimals:8,channel:"asset"},GWETH:{descriptor:{collection:"GWETH",category:"Unit",type:"none",additionalKey:"none"},decimals:18,channel:"asset"},GUSDC:{descriptor:{collection:"GUSDC",category:"Unit",type:"none",additionalKey:"none"},decimals:6,channel:"asset"},GUSDT:{descriptor:{collection:"GUSDT",category:"Unit",type:"none",additionalKey:"none"},decimals:6,channel:"asset"},GWTRX:{descriptor:{collection:"GWTRX",category:"Unit",type:"none",additionalKey:"none"},decimals:6,channel:"asset"},GWBTC:{descriptor:{collection:"GWBTC",category:"Unit",type:"none",additionalKey:"none"},decimals:8,channel:"asset"},GSOL:{descriptor:{collection:"GSOL",category:"Unit",type:"none",additionalKey:"none"},decimals:9,channel:"asset"}},Ys=["function decimals() view returns (uint8)","function balanceOf(address owner) view returns (uint256)","function approve(address spender, uint256 value) returns (bool)","function allowance(address owner, address spender) view returns (uint256)","function transfer(address to, uint256 value) returns (bool)","function name() view returns (string)","function nonces(address owner) view returns (uint256)","function permit(address owner,address spender,uint256 value,uint256 deadline,uint8 v,bytes32 r,bytes32 s)"],Zs=["function bridgeOut(address token,uint256 amount,uint256 tokenId,uint16 destinationChainId,bytes recipient) external","function bridgeOutWithPermit(address token,uint256 amount,uint16 destinationChainId,bytes recipient,uint256 deadline,uint8 v,bytes32 r,bytes32 s) external"],er={BRIDGE_OUT:Buffer.from([27,194,57,119,215,165,247,150]),BRIDGE_OUT_NATIVE:Buffer.from([243,44,75,224,249,206,98,79])};function tr(e){return/^0x[a-fA-F0-9]{64}$/.test(e)}function nr(e){const t=new Map;for(const n of e)t.set(jt(n.symbol),n);return t}function ar(e,t,n){const a=function(e,t){return e.get(jt(t))}(e,t);if(!a){throw It(`Token ${t} not supported for ${n}. Supported: ${Array.from(e.keys()).join(", ")}`,"tokenSymbol")}return a}function sr(e){if(null==e||!tr(e))throw Ct("privateKey","a 0x-prefixed 64-character hex string (e.g., 0x1234...abcd)","Ethereum private key")}function rr(e,t,n){return{symbol:e,quantity:t,decimals:n,contractAddress:null,isNative:!0}}function ir(e,t){return{symbol:e.symbol,quantity:t,decimals:e.decimals??18,contractAddress:e.contractAddress,isNative:!1}}function or(e,t){return{symbol:e.symbol,quantity:t,decimals:e.decimals??9,contractAddress:e.mintAddress,isNative:e.isNative??!1}}function cr(e,t,n){const a=e.find(e=>e.symbol===t);if(!a){const a=e.map(e=>e.symbol).join(", ");throw Tt("tokenSymbol",`Unsupported ${n} token: ${t}. Supported: ${a}`)}return a}const lr={Ethereum:"Ethereum bridging not configured. Provide ethereumPrivateKey in config.",Solana:"Solana bridging not configured. Provide solanaPrivateKey in config."};function dr(e,t,n){if(void 0===e)throw It(n??lr[t],`${t.toLowerCase()}Strategy`);return e}function ur(e){return{direction:"inbound",fromChain:e.fromChain,toChain:"GalaChain",transactionHash:e.transactionHash,tokenSymbol:e.tokenSymbol,amount:e.amount,timestamp:Date.now(),statusUrl:`${e.baseUrl}/v1/bridge/transaction?hash=${e.transactionHash}`}}const hr="Token symbol resolution failed. This is an internal error - BridgeService should resolve tokenId to symbol before calling strategy.",gr="Bridge request ID missing from RequestTokenBridgeOut response",mr="BridgeTokenOut response missing transaction hash";function pr(e){if(void 0===e||""===e)throw It(hr,"tokenSymbol");return e}function fr(e,n){if(!t.isAddress(e)){throw Ct(n??"address","a valid 0x-prefixed Ethereum address",e)}}function yr(e,t){try{return new a.PublicKey(e)}catch{throw Ct(t??"address","a valid Solana address (base58)",e)}}function vr(e){try{return new a.PublicKey(e)}catch{throw Ct("address","a valid Solana address (base58)",e)}}function kr(e){const t={};for(const[n,a]of Object.entries(e))void 0!==a&&(a&&"object"==typeof a&&!Array.isArray(a)?t[n]=kr(a):t[n]=a);return t}function br(e,t){const n=An(e,-1);if(n<=0)throw new Error(`Invalid bridge amount for ${t}: "${e}". Amount must be a positive number.`);return n}let wr=null;if("undefined"==typeof window&&"undefined"!=typeof require)try{wr=m}catch{}function Sr(){if(void 0!==wr?.randomUUID)try{return wr.randomUUID()}catch{}if(void 0!==globalThis.crypto&&"function"==typeof globalThis.crypto.randomUUID)try{return crypto.randomUUID()}catch{}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}const Ar={name:"GalaConnect",chainId:1},Er=[{name:"destinationChainId",type:"uint256"},{name:"destinationChainTxFee",type:"destinationChainTxFee"},{name:"quantity",type:"string"},{name:"recipient",type:"string"},{name:"tokenInstance",type:"tokenInstance"},{name:"uniqueKey",type:"string"}],Tr=[{name:"collection",type:"string"},{name:"category",type:"string"},{name:"type",type:"string"},{name:"additionalKey",type:"string"}],Cr=[{name:"collection",type:"string"},{name:"category",type:"string"},{name:"type",type:"string"},{name:"additionalKey",type:"string"},{name:"instance",type:"string"}],Nr=[{name:"name",type:"string"},{name:"symbol",type:"string"}],Ir={GalaTransaction:Er,destinationChainTxFee:[{name:"bridgeToken",type:"bridgeToken"},{name:"bridgeTokenIsNonFungible",type:"bool"},{name:"estimatedPricePerTxFeeUnit",type:"string"},{name:"estimatedTotalTxFeeInExternalToken",type:"string"},{name:"estimatedTotalTxFeeInGala",type:"string"},{name:"estimatedTxFeeUnitsTotal",type:"string"},{name:"galaDecimals",type:"uint256"},{name:"galaExchangeRate",type:"galaExchangeRate"},{name:"timestamp",type:"uint256"},{name:"signingIdentity",type:"string"},{name:"signature",type:"string"}],bridgeToken:Tr,galaExchangeRate:[{name:"identity",type:"string"},{name:"oracle",type:"string"},{name:"source",type:"string"},{name:"sourceUrl",type:"string"},{name:"timestamp",type:"uint256"},{name:"baseToken",type:"baseToken"},{name:"exchangeRate",type:"string"},{name:"externalQuoteToken",type:"externalQuoteToken"}],baseToken:Cr,externalQuoteToken:Nr,tokenInstance:Cr},Dr={GalaTransaction:Er,destinationChainTxFee:[{name:"bridgeToken",type:"bridgeToken"},{name:"bridgeTokenIsNonFungible",type:"bool"},{name:"estimatedPricePerTxFeeUnit",type:"string"},{name:"estimatedTotalTxFeeInExternalToken",type:"string"},{name:"estimatedTotalTxFeeInGala",type:"string"},{name:"estimatedTxFeeUnitsTotal",type:"string"},{name:"galaDecimals",type:"uint256"},{name:"galaExchangeCrossRate",type:"galaExchangeCrossRate"},{name:"timestamp",type:"uint256"},{name:"signingIdentity",type:"string"},{name:"signature",type:"string"}],bridgeToken:Tr,galaExchangeCrossRate:[{name:"baseTokenCrossRate",type:"baseTokenCrossRate"},{name:"crossRate",type:"string"},{name:"externalCrossRateToken",type:"externalCrossRateToken"},{name:"identity",type:"string"},{name:"oracle",type:"string"},{name:"quoteTokenCrossRate",type:"quoteTokenCrossRate"},{name:"source",type:"string"},{name:"timestamp",type:"uint256"}],baseTokenCrossRate:[{name:"identity",type:"string"},{name:"oracle",type:"string"},{name:"source",type:"string"},{name:"sourceUrl",type:"string"},{name:"timestamp",type:"uint256"},{name:"exchangeRate",type:"string"},{name:"externalBaseToken",type:"externalBaseToken"},{name:"externalQuoteToken",type:"externalQuoteToken"},{name:"signature",type:"string"}],externalBaseToken:Nr,externalQuoteToken:Nr,externalCrossRateToken:Nr,quoteTokenCrossRate:[{name:"identity",type:"string"},{name:"oracle",type:"string"},{name:"source",type:"string"},{name:"sourceUrl",type:"string"},{name:"timestamp",type:"uint256"},{name:"baseToken",type:"baseToken"},{name:"exchangeRate",type:"string"},{name:"externalQuoteToken",type:"externalQuoteToken"},{name:"signature",type:"string"}],baseToken:Cr,tokenInstance:Cr};async function _r(e,t){const{wallet:n}=t,a=e.uniqueKey??`galaconnect-operation-${Sr()}`,r="string"==typeof e.destinationChainId?Tn(e.destinationChainId,1):e.destinationChainId,i=function(e){const t={...e,galaDecimals:"string"==typeof e.galaDecimals?Tn(e.galaDecimals,0):e.galaDecimals,timestamp:"string"==typeof e.timestamp?Tn(e.timestamp,0):e.timestamp};if(e.galaExchangeRate&&(t.galaExchangeRate={...e.galaExchangeRate,timestamp:"string"==typeof e.galaExchangeRate.timestamp?Tn(e.galaExchangeRate.timestamp,0):e.galaExchangeRate.timestamp}),e.galaExchangeCrossRate){const n=e.galaExchangeCrossRate;t.galaExchangeCrossRate={...n,timestamp:"string"==typeof n.timestamp?Tn(n.timestamp,0):n.timestamp},n.baseTokenCrossRate&&(t.galaExchangeCrossRate.baseTokenCrossRate={...n.baseTokenCrossRate,timestamp:"string"==typeof n.baseTokenCrossRate.timestamp?Tn(n.baseTokenCrossRate.timestamp,0):n.baseTokenCrossRate.timestamp}),n.quoteTokenCrossRate&&(t.galaExchangeCrossRate.quoteTokenCrossRate={...n.quoteTokenCrossRate,timestamp:"string"==typeof n.quoteTokenCrossRate.timestamp?Tn(n.quoteTokenCrossRate.timestamp,0):n.quoteTokenCrossRate.timestamp})}return t}(e.destinationChainTxFee),o=Boolean(i.galaExchangeCrossRate),c={destinationChainId:r,destinationChainTxFee:kr(o?{...i,galaExchangeRate:void 0}:{...i,galaExchangeCrossRate:void 0}),quantity:e.quantity,recipient:e.recipient,tokenInstance:e.tokenInstance,uniqueKey:a},l=function(e){return e?Dr:Ir}(o),d=await n.signTypedData(Ar,l,c),u=`Ethereum Signed Message:\n${s({domain:Ar,message:c,primaryType:"GalaTransaction",types:l}).length}`;return{...c,signature:d,prefix:u,types:l,domain:Ar}}async function Rr(e,t){const{amount:n,recipientAddress:a,tokenSymbol:s}=e,{galaConnectClient:r,tokenMetadataResolver:i,ethereumWallet:o,destinationChainId:c,destinationChain:l,validateRecipientAddress:d}=t,u=pr(s);br(n,u),d(a,"recipient");const h=await i.getTokenMetadata(u),g=await r.fetchBridgeFee({chainId:l,bridgeToken:h.descriptor}),m=function(e){return{destinationChainId:e.destinationChainId,destinationChainTxFee:e.bridgeFee,quantity:e.amount,recipient:e.recipientAddress,tokenInstance:{...e.tokenDescriptor,instance:"0"}}}({destinationChainId:c,bridgeFee:g,amount:n,recipientAddress:a,tokenDescriptor:h.descriptor}),p=await _r(m,{wallet:o}),f=function(e){if(void 0===e||""===e)throw It(gr,"bridgeRequestId");return e}(function(e){if("string"==typeof e.Data)return e.Data;const t=e.data;if(null!=t){if("string"==typeof t)return t;if("object"==typeof t){const e=t;if("string"==typeof e.Data)return e.Data}}}(await r.requestBridgeOut(p)));return function(e){return{direction:"outbound",fromChain:"GalaChain",toChain:e.toChain,transactionHash:e.transactionHash,tokenSymbol:e.tokenSymbol,amount:e.amount,feePaid:e.feePaid,timestamp:Date.now(),statusUrl:`${e.baseUrl}/v1/bridge/transaction?hash=${e.transactionHash}`}}({toChain:l,transactionHash:function(e){const t=e.Hash??e.hash??"";if(""===t)throw It(mr,"transactionHash");return t}(await r.bridgeTokenOut({bridgeFromChannel:"asset",bridgeRequestId:f})),tokenSymbol:u,amount:n,feePaid:g.estimatedTotalTxFeeInGala,baseUrl:r.getBaseUrl()})}var xr;!function(e){e[e.PENDING=0]="PENDING",e[e.SUBMITTED=1]="SUBMITTED",e[e.CONFIRMED=2]="CONFIRMED",e[e.PROCESSING=3]="PROCESSING",e[e.FINALIZING=4]="FINALIZING",e[e.COMPLETED=5]="COMPLETED",e[e.FAILED=6]="FAILED",e[e.DELIVERY_FAILED=7]="DELIVERY_FAILED"}(xr||(xr={}));const Or={COMPLETED:xr.COMPLETED,FAILED:xr.FAILED,DELIVERY_FAILED:xr.DELIVERY_FAILED};class Fr{constructor(e){if(this.lastTimestamp=0,this.pendingPromise=Promise.resolve(),this.chainLength=0,this.maxChainLength=1e3,e<=0)throw xt("requestsPerSecond","1",e,"Requests per second");this.minIntervalMs=1e3/e}async schedule(e){let t,n;const a=new Promise((e,a)=>{t=e,n=a});if(this.pendingPromise=this.pendingPromise.then(async()=>{const a=Date.now()-this.lastTimestamp,s=Math.max(0,this.minIntervalMs-a);s>0&&await new Promise(e=>setTimeout(e,s)),this.lastTimestamp=Date.now();try{const n=await e();t(n)}catch(e){n(at(e)?e:new Error(st(e)))}}),this.chainLength++,this.chainLength>=this.maxChainLength){this.chainLength=0;const e=this.pendingPromise;this.pendingPromise=e.then(()=>Promise.resolve())}return a}}const Br={maxRetries:3,initialDelayMs:1e3,maxDelayMs:3e4,backoffMultiplier:2,jitterFactor:.1},Ur=new Set([408,429,500,502,503,504]),Pr=[/ECONNRESET/i,/ECONNREFUSED/i,/ETIMEDOUT/i,/ENOTFOUND/i,/EAI_AGAIN/i,/socket hang up/i,/network/i,/timeout/i,/aborted/i];function Mr(e){if(null!=e&&"object"==typeof e){const t=e;if("number"==typeof t.status)return Ur.has(t.status);if("number"==typeof t.statusCode)return Ur.has(t.statusCode);const n=it(e);if("string"==typeof n&&("ECONNRESET"===n||"ECONNREFUSED"===n||"ETIMEDOUT"===n||"ENOTFOUND"===n||"EAI_AGAIN"===n))return!0}const t=st(e);return Pr.some(e=>e.test(t))}function Lr(e,t){const n=t.initialDelayMs*Math.pow(t.backoffMultiplier,e-1),a=Math.min(n,t.maxDelayMs),s=a*t.jitterFactor*Math.random();return Math.floor(a+s)}function $r(e){return new Promise(t=>setTimeout(t,e))}function Kr(e,t){return dr(e.get("Ethereum"),"Ethereum",t)}function Gr(e,t){return dr(e.get("Solana"),"Solana",t)}function Wr(e,t){return e??t.getWalletAddress()}async function Hr(e,t,n,a,s){const r=await t.getTokenMetadata(a);return function(e){const t="string"==typeof e.timestamp?Tn(e.timestamp,0):e.timestamp;return{estimatedFeeInGala:e.estimatedTotalTxFeeInGala,estimatedFeeInExternalToken:e.estimatedTotalTxFeeInExternalToken,feeToken:e.bridgeToken,pricePerUnit:e.estimatedPricePerTxFeeUnit,estimatedGasUnits:e.estimatedTxFeeUnitsTotal,exchangeRate:e.galaExchangeRate?.exchangeRate??"0",timestamp:t,raw:e}}(await e.fetchBridgeFee({chainId:n,bridgeToken:r.descriptor}))}async function qr(e,t){return function(e){const t=Tn(e.status,0);return{status:t,statusDescription:e.statusDescription,fromChain:e.fromChain,toChain:e.toChain,quantity:e.quantity,transactionHash:e.emitterTransactionHash,tokenInstance:e.tokenInstance,isComplete:t===Number(Or.COMPLETED),isFailed:t===Number(Or.FAILED)||t===Number(Or.DELIVERY_FAILED)}}(await e.getBridgeStatus(t))}function zr(e,t,n){try{const n=function(e,t){if(!Un(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}(e,t),[a,s,r,...i]=n;if(""===a||""===s||""===r)throw new Error("Collection, category, and type must be non-empty");const o=i.join(t);if(void 0===a||void 0===s||void 0===r||""===o)throw new Error("AdditionalKey must be non-empty");return{collection:a,category:s,type:r,additionalKey:o}}catch(a){throw function(e,t,n,a){const s=e?.split?.(t)??[],r=void 0!==n?` (${n})`:"";return new kt(`Invalid ${"|"===t?"pipe":"dollar"}-delimited token: "${e}" (${s.length} parts)${r}. Expected format: "collection${t}category${t}type${t}additionalKey" (4 parts minimum). Received: [${s.map(e=>`"${e}"`).join(", ")}]. Error: ${st(a)}`,"token",`INVALID_${"|"===t?"PIPE":"DOLLAR"}_DELIMITED_TOKEN`)}(e,t,n,a)}}function jr(e){return zr(e,"|","pipe-delimited token")}function Vr(e){return"string"==typeof e&&e.includes("$")}function Xr(e){if("object"!=typeof e||null===e)return!1;const t=e,n=t.collection,a=t.category,s=t.type,r=t.additionalKey;return"string"==typeof n&&"string"==typeof a&&"string"==typeof s&&"string"==typeof r&&n.length>0&&a.length>0&&s.length>0&&r.length>0}function Qr(e){let t;if("string"==typeof e)t=jr(e);else{if(!Xr(e))throw new Error('Invalid tokenId format. Expected pipe-delimited string (e.g., "GALA|Unit|none|none") or TokenClassKey object.');t=e}return{tokenClassKey:t,stringified:Ms(t)}}function Jr(e,t){let n;try{n=Cn(e,"amount")}catch(t){throw Bt("amount",`${e} (${st(t)})`)}if(!n.isFinite())throw Bt("amount",e);const a=n.multipliedBy(ns(10).pow(t));if(!a.isInteger())throw Bt("amount",`${e} (cannot be represented with ${t} decimals)`);return BigInt(a.toFixed(0))}function Yr(e,t){return ns(e.toString()).dividedBy(ns(10).pow(t)).toFixed(t).replace(/\.?0+$/,"")}class Zr{constructor(e){this.cache=new Map,this.galaConnectClient=e.galaConnectClient}async getTokenMetadata(e){const t=Vt(e),n=this.cache.get(t);if(n)return n;const a=Js[t];if(void 0!==a)return this.cache.set(t,a),a;const s=await this.fetchFromApi(e);return this.cache.set(t,s),s}hasMetadata(e){const t=Vt(e);return this.cache.has(t)||t in Js}clearCache(){this.cache.clear()}async fetchFromApi(e){let t=e,n=await this.galaConnectClient.getBridgeConfigurations(t),a=n.find(e=>Vt(e.symbol)===Vt(t)&&e.verified);if(a||e.startsWith("G")||(t=`G${e}`,n=await this.galaConnectClient.getBridgeConfigurations(t),a=n.find(e=>Vt(e.symbol)===Vt(t)&&e.verified)),!a)throw new Error(`Unable to locate token metadata for ${e}`);return s={collection:a.collection,category:a.category,type:a.type,additionalKey:a.additionalKey},r=a.decimals,i=a.channel,{descriptor:{collection:s.collection,category:s.category,type:s.type,additionalKey:s.additionalKey},decimals:r,...void 0!==i?{channel:i}:{}};var s,r,i}}class ei extends Error{constructor(e,t,n){super(`GalaConnect request to ${t} failed with status ${e}${null!=n?`: ${JSON.stringify(n)}`:""}`),this.status=e,this.path=t,this.responseBody=n,this.name="GalaConnectHttpError"}}const ti="https://dex-api-platform-dex-prod-gala.gala.com",ni="https://galachain-gateway-chain-platform-galachain-mainnet.gala.com",ai=12,si=!0,ri=3,ii=1e3;class oi{constructor(e){this.baseUrl=e.baseUrl??ti,this.galachainBaseUrl=e.galachainBaseUrl??ni,this.walletAddress=e.walletAddress,this.rateLimiter=new Fr(e.requestsPerSecond??ai),this.defaultHeaders={"Content-Type":"application/json","X-Wallet-Address":this.walletAddress};const t=e.enableRetry??si;this.retryOptions=t?{maxRetries:e.maxRetries??ri,initialDelayMs:e.retryInitialDelayMs??ii,...e.onRetry&&{onRetry:e.onRetry},shouldRetry:e=>Mr(e instanceof ei?{status:e.status}:e)}:null}getBaseUrl(){return this.baseUrl}async getBridgeConfigurations(e){return _s(async()=>{const t=new URL("/v1/connect/bridge-configurations",this.baseUrl);t.searchParams.set("searchprefix",e);const n=await this.request(t.toString(),{method:"GET"});if(!n.ok){const e=await n.text();let t;throw t=""!==e?Sn(e,{rawBody:e}):{message:"Failed to fetch bridge configurations"},new ei(n.status,"/v1/connect/bridge-configurations",t)}return(await n.json()).data.tokens},"GalaConnectClient.getBridgeConfigurations",void 0,e=>{if(e instanceof ei)throw e;throw _t(e,"GalaConnectClient.getBridgeConfigurations")})}async fetchBridgeFee(e){return this.postJson("/v1/bridge/fee",e,{skipWalletHeader:!0})}async requestBridgeOut(e){return this.postJson("/v1/RequestTokenBridgeOut",e)}async bridgeTokenOut(e){return this.postJson("/v1/BridgeTokenOut",e)}async getBridgeStatus(e){return this.postJson("/v1/bridge/status",{hash:e})}async registerBridgeTransaction(e){return this.postJson("/v1/bridge/transaction",e)}async fetchBalances(e="asset"){return this.postJson("/v1/FetchBalances",{owner:this.walletAddress,channel:e},{baseUrl:this.galachainBaseUrl})}async postJson(e,t,n={}){return _s(async()=>{const a=n.baseUrl??this.baseUrl,s=new URL(e,a),r=n.skipWalletHeader?{"Content-Type":"application/json","X-Wallet-Address":""}:this.defaultHeaders,i=await this.request(s.toString(),{method:"POST",headers:r,body:JSON.stringify(t,(e,t)=>"bigint"==typeof t?t.toString():t)});if(!i.ok){const t=await i.text(),n=500,a=Sn(t,{rawBody:t.slice(0,n)});throw new ei(i.status,e,a)}const o=await i.text();if(""!==o){const t=function(e){if(Jt(e))return{success:!1,value:null,error:"Value is empty"};try{return{success:!0,value:JSON.parse(e)}}catch(e){return{success:!1,value:null,error:`JSON parse error: ${st(e)}`}}}(o);if(!t.success)throw new Error(`Failed to parse JSON response from ${e}: ${String(t.error)}`);return t.value}},`Failed to execute POST request to ${e}`,void 0,(e,t)=>{if(e instanceof ei)throw e;throw _t(e,t)})}async request(e,t){const n=async()=>this.rateLimiter.schedule(async()=>{const n={...this.defaultHeaders,...t.headers};""===n["X-Wallet-Address"]?delete n["X-Wallet-Address"]:n["X-Wallet-Address"]??(n["X-Wallet-Address"]=this.walletAddress);const a=await fetch(e,{...t,headers:n});if(this.retryOptions&&!a.ok){const t=a.status;if(429===t||t>=500){const n=a.clone(),s=await this.safeParseJson(n);throw new ei(t,e,s)}}return a});return this.retryOptions?async function(e,t={}){const n={...Br,...t},a=t.shouldRetry??(e=>Mr(e));let s;for(let r=1;r<=n.maxRetries+1;r++)try{return await e()}catch(e){if(s=e,r>n.maxRetries)break;if(!a(e,r))break;const i=Lr(r,n);t.onRetry&&t.onRetry(e,r,i),await new Promise(e=>setTimeout(e,i))}throw s}(n,this.retryOptions):n()}async safeParseJson(e){const t=await e.text();try{return JSON.parse(t)}catch{return{rawBody:t}}}}class ci{async waitForCompletion(e,t={}){const{pollInterval:n=15e3,timeout:a=27e5,onStatusUpdate:s}=t,r=Date.now();for(;;){const t=await this.getStatus(e);if(s&&s(t),t.status===xr.COMPLETED||t.status===xr.FAILED||t.status===xr.DELIVERY_FAILED)return t;if(nn(r)>a)throw Dt(`Bridge transaction timed out after ${a}ms. Last status: ${t.status}`,e,"TIMEOUT");await new Promise(e=>setTimeout(e,n))}}}class li extends ci{constructor(e,t){super(),this.galaConnectClient=e,this.tokenConfigs=t}async getStatus(e){return qr(this.galaConnectClient,e)}getSupportedTokens(){return e=this.tokenConfigs,Array.from(e.keys());var e}isTokenSupported(e){return function(e,t){return e.has(jt(t))}(this.tokenConfigs,e)}}async function di(e,t,...n){const a=e[t];return"function"==typeof a?await a(...n):await e.getFunction(t)(...n)}class ui extends li{constructor(e){const n=e.tokenConfigs??Xs;super(e.galaConnectClient,nr(n)),this.network="Ethereum",this.galaChainWalletAddress=e.galaChainWalletAddress,sr(e.ethereumPrivateKey);const a=e.ethereumRpcUrl??"https://ethereum.publicnode.com";this.ethereumProvider=new t.JsonRpcProvider(a),this.ethereumWallet=new t.Wallet(e.ethereumPrivateKey,this.ethereumProvider),this.ethereumWalletAddress=e.ethereumWalletAddress??this.ethereumWallet.address,this.ethereumBridgeContract=e.ethereumBridgeContract??"0x3F98b5A26EF3f04E1DA3B0B41dD350E8C8F3A7c2",this.tokenMetadataResolver=new Zr({galaConnectClient:this.galaConnectClient})}async estimateFee(e,t){return Hr(this.galaConnectClient,this.tokenMetadataResolver,"Ethereum",e)}async bridgeOut(e){return Rr(e,{galaConnectClient:this.galaConnectClient,tokenMetadataResolver:this.tokenMetadataResolver,ethereumWallet:this.ethereumWallet,destinationChainId:Ks,destinationChain:"Ethereum",validateRecipientAddress:fr})}async bridgeIn(e){const{amount:n,sourcePrivateKey:a,recipientAddress:s,tokenSymbol:r}=e,i=pr(r);if(br(n,i),void 0!==a&&""!==a&&!tr(a))throw Ct("sourcePrivateKey","0x-prefixed 64-character hex string",a.slice(0,10)+"...");const o=void 0!==a&&""!==a?new t.Wallet(a,this.ethereumProvider):this.ethereumWallet,c=ar(this.tokenConfigs,i,"Ethereum bridge"),l=await this.tokenMetadataResolver.getTokenMetadata(i),d=new t.Contract(c.contractAddress,Ys,o),u=await di(d,"decimals"),h=Tn("string"==typeof u||"number"==typeof u||"bigint"==typeof u?u:void 0,18),g=Jr(n,h),m=await di(d,"balanceOf",o.address);if("bigint"!=typeof m)throw new Error("Ethereum balance response was not a bigint");const p=m;if(p<g){throw It(`Insufficient ${i} balance on Ethereum. Needed ${Yr(g,h)}, have ${Yr(p,h)}`,"amount")}const f=function(e){const n=new ta;if("client"===n.detectFormat(e))return e;const a=n.normalizeInput(e);if(null==a)throw Ct("address","a valid GalaChain address (eth|0x{40-hex}, 0x{40-hex}, or {40-hex})","GalaChain address");const s=n.extractHex(a);return`eth|${t.getAddress("0x"+s).slice(2)}`}(s??this.galaChainWalletAddress);return ur({fromChain:"Ethereum",transactionHash:(await this.executeBridgeDeposit({wallet:o,tokenContract:d,tokenConfig:c,amountBaseUnits:g,decimals:h,recipient:f,metadata:l})).txHash,tokenSymbol:i,amount:n,baseUrl:this.galaConnectClient.getBaseUrl()})}isValidAddress(e){return Bn.ETH_ADDRESS.test(e)}getWalletAddress(){return this.ethereumWalletAddress}async getEthereumTokenBalance(e,n){const a=ar(this.tokenConfigs,e,"Ethereum"),s=n??this.ethereumWalletAddress;fr(s);const r=new t.Contract(a.contractAddress,Ys,this.ethereumProvider),i=await di(r,"balanceOf",s);if("bigint"!=typeof i)throw new Error("Ethereum balance response was not a bigint");return Yr(i,a.decimals??18)}async getEthereumNativeBalance(e){const t=e??this.ethereumWalletAddress;fr(t);return Yr(await this.ethereumProvider.getBalance(t),18)}async getEthereumTransactionStatus(e){!function(e){if(!function(e){return/^0x[a-fA-F0-9]{64}$/.test(e)}(e))throw Ct("hash","a 0x-prefixed 64-character hex string (66 total characters)","Ethereum transaction hash")}(e);const t=e.toLowerCase();try{const e=await this.ethereumProvider.getTransactionReceipt(t);if(e){const n=await this.ethereumProvider.getBlockNumber()-e.blockNumber+1;if(!(1===e.status))return{confirmed:!1,status:"failed",blockNumber:e.blockNumber,confirmations:n,transactionHash:t,gasUsed:e.gasUsed.toString(),effectiveGasPrice:e.gasPrice?.toString(),error:"Transaction reverted during execution"};return{confirmed:!0,status:n>=ui.ETHEREUM_FINALITY_THRESHOLD?"finalized":"confirmed",blockNumber:e.blockNumber,confirmations:n,transactionHash:t,gasUsed:e.gasUsed.toString(),effectiveGasPrice:e.gasPrice?.toString()}}return await this.ethereumProvider.getTransaction(t)?{confirmed:!1,status:"pending",transactionHash:t}:{confirmed:!1,status:"not_found",transactionHash:t,error:"Transaction not found on Ethereum network"}}catch(e){return{confirmed:!1,status:"not_found",transactionHash:t,error:`Failed to query transaction status: ${st(e)}`}}}async executeBridgeDeposit(e){const n=new t.Contract(this.ethereumBridgeContract,Zs,e.wallet),a=(new TextEncoder).encode(e.recipient);let s;s=e.tokenConfig.bridgeUsesPermit?await this.bridgeWithPermit(e.wallet,e.tokenContract,e.tokenConfig,n,e.amountBaseUnits,a):await this.bridgeWithApproval(e.wallet,e.tokenContract,n,e.tokenConfig,e.amountBaseUnits,a);if(!await s.wait())throw It("Bridge transaction receipt not available","ethereumRpcUrl");await $r(3e4);const r={collection:e.metadata.descriptor.collection,category:e.metadata.descriptor.category,type:e.metadata.descriptor.type,additionalKey:e.metadata.descriptor.additionalKey,instance:"0"};return await this.galaConnectClient.registerBridgeTransaction({quantity:Yr(e.amountBaseUnits,e.decimals),tokenInstance:r,fromChain:"Ethereum",toChain:"GC",hash:s.hash}),{txHash:s.hash}}async bridgeWithPermit(e,n,a,s,r,i){const o=await this.ethereumProvider.getNetwork(),c=await di(n,"name");if("string"!=typeof c)throw new Error("Ethereum token name response was not a string");const l=c,d=await di(n,"nonces",e.address);if("bigint"!=typeof d)throw new Error("Ethereum token nonce response was not a bigint");const u=d,h=BigInt(Math.floor(Date.now()/1e3)+3600),g=await e.signTypedData({name:l,version:"1",chainId:Tn(o.chainId,1),verifyingContract:a.contractAddress},{Permit:[{name:"owner",type:"address"},{name:"spender",type:"address"},{name:"value",type:"uint256"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}]},{owner:e.address,spender:this.ethereumBridgeContract,value:r,nonce:u,deadline:h}),m=t.Signature.from(g);return await di(s,"bridgeOutWithPermit",a.contractAddress,r,$s,i,h,m.v,m.r,m.s)}async bridgeWithApproval(e,t,n,a,s,r){const i=await di(t,"allowance",e.address,this.ethereumBridgeContract);if("bigint"!=typeof i)throw new Error("Ethereum allowance response was not a bigint");if(BigInt(i)<s){const e=await di(t,"approve",this.ethereumBridgeContract,s);await e.wait()}return await di(n,"bridgeOut",a.contractAddress,s,0,$s,r)}}ui.ETHEREUM_FINALITY_THRESHOLD=12;function hi(e,t,n,s,r){const[i]=a.PublicKey.findProgramAddressSync([t.toBuffer(),s.toBuffer(),e.toBuffer()],r);return i}class gi extends li{constructor(e){const n=e.tokenConfigs??Qs;super(e.galaConnectClient,nr(n)),this.network="Solana",this.solanaBridgeAccountCache=new Map,this.galaChainWalletAddress=e.galaChainWalletAddress,sr(e.ethereumPrivateKey);const s=new t.JsonRpcProvider("https://ethereum.publicnode.com");this.ethereumWallet=new t.Wallet(e.ethereumPrivateKey,s);const r=e.solanaRpcUrl??"https://api.mainnet-beta.solana.com";let i;this.solanaConnection=new a.Connection(r,"confirmed");try{i=o.decode(e.solanaPrivateKeyBase58)}catch{throw Ct("solanaPrivateKeyBase58","base58-encoded string",e.solanaPrivateKeyBase58.slice(0,20)+"...")}if(64!==i.length)throw Ct("solanaPrivateKeyBase58","64 bytes when decoded",`${i.length} bytes`);this.solanaKeypair=a.Keypair.fromSecretKey(i);const c=e.solanaBridgeProgram??"AaE4dTnL75XqgUJpdxBKg6vS9sTJgBPJwBQRVhD29WwS";this.solanaBridgeProgramId=new a.PublicKey(c),[this.solanaBridgeTokenAuthority]=a.PublicKey.findProgramAddressSync([Buffer.from("bridge_token_authority")],this.solanaBridgeProgramId),[this.solanaBridgeConfigPda]=a.PublicKey.findProgramAddressSync([Buffer.from("configv1")],this.solanaBridgeProgramId),[this.solanaNativeBridgePda]=a.PublicKey.findProgramAddressSync([Buffer.from("native_sol_bridge")],this.solanaBridgeProgramId),this.tokenMetadataResolver=new Zr({galaConnectClient:this.galaConnectClient})}async estimateFee(e,t){return Hr(this.galaConnectClient,this.tokenMetadataResolver,"Solana",e)}async bridgeOut(e){return Rr(e,{galaConnectClient:this.galaConnectClient,tokenMetadataResolver:this.tokenMetadataResolver,ethereumWallet:this.ethereumWallet,destinationChainId:Gs,destinationChain:"Solana",validateRecipientAddress:yr})}async bridgeIn(e){const{amount:t,sourcePrivateKey:n,recipientAddress:s,tokenSymbol:r}=e,i=pr(r);br(t,i);let c=this.solanaKeypair;if(void 0!==n&&""!==n){let e;try{e=o.decode(n)}catch{throw Ct("sourcePrivateKey","base58-encoded string",n.slice(0,20)+"...")}if(64!==e.length)throw Ct("sourcePrivateKey","64 bytes when decoded",`${e.length} bytes`);c=a.Keypair.fromSecretKey(e)}const l=ar(this.tokenConfigs,i,"Solana bridge"),d=await this.tokenMetadataResolver.getTokenMetadata(i),u=Jr(t,d.decimals),h=s??this.galaChainWalletAddress;return ur({fromChain:"Solana",transactionHash:await this.executeSolanaBridgeOut({keypair:c,tokenConfig:l,metadata:d,amountBaseUnits:u,recipient:h,amount:t}),tokenSymbol:i,amount:t,baseUrl:this.galaConnectClient.getBaseUrl()})}isValidAddress(e){try{return new a.PublicKey(e),!0}catch{return!1}}getWalletAddress(){return this.solanaKeypair.publicKey.toBase58()}async getSolanaTokenBalance(e,t){const n=ar(this.tokenConfigs,e,"Solana");if(n.isNative)return this.getSolanaNativeBalance(t);const s=t??this.solanaKeypair.publicKey.toBase58(),r=vr(s),o=hi(new a.PublicKey(n.mintAddress),r,0,i.TOKEN_PROGRAM_ID,i.ASSOCIATED_TOKEN_PROGRAM_ID);try{const e=await async function(e,t,n,a){const s=await e.getAccountInfo(t);if(!s)throw new Error(`could not find account ${t.toBase58()}`);if(!s.owner.equals(a))throw new Error(`account owner mismatch: expected ${a.toBase58()}, got ${s.owner.toBase58()}`);return{amount:i.AccountLayout.decode(s.data).amount,decimals:0}}(this.solanaConnection,o,0,i.TOKEN_PROGRAM_ID),t=n.decimals??8;return Yr(e.amount,t)}catch(t){if(at(t)&&t.message.includes("could not find")){return Yr(0n,n.decimals??8)}throw It(`Failed to fetch ${e} balance for ${s}: ${st(t)}`,`${e}Account`)}}async getSolanaNativeBalance(e){const t=vr(e??this.solanaKeypair.publicKey.toBase58()),n=await this.solanaConnection.getBalance(t,"confirmed");return Yr(BigInt(n),9)}async requestDevnetAirdrop(e=1,t){Rn(e,1e-5,2,"amount");const n=void 0!==t&&""!==t?vr(t):this.solanaKeypair.publicKey,s=this.solanaConnection.rpcEndpoint;if(!s.includes("devnet"))throw It(`Solana devnet faucet only available on devnet. Current RPC: ${s}. Ensure SDK is configured with environment='stage' for devnet access.`,"solanaRpcUrl");const r=Math.floor(e*a.LAMPORTS_PER_SOL);return await this.solanaConnection.requestAirdrop(n,r)}async getSolanaTransactionStatus(e){if(!Un(e))throw Ct("signature","a non-empty string");if(!/^[1-9A-HJ-NP-Za-km-z]{80,90}$/.test(e))throw Ct("signature","a base58-encoded string (87-88 characters)",e.slice(0,20)+"...");const t=(await this.solanaConnection.getSignatureStatuses([e])).value[0];return t?null!==t.err&&void 0!==t.err?{confirmed:!1,status:"failed",slot:t.slot,error:JSON.stringify(t.err)}:{confirmed:!0,status:t.confirmationStatus??"processed",slot:t.slot}:{confirmed:!1,status:"not_found"}}async executeSolanaBridgeOut(e){const t=new a.PublicKey(e.tokenConfig.mintAddress),n=Boolean(e.tokenConfig.isNative),s=n?void 0:await this.getSolanaBridgeAccounts(t),r=n?void 0:hi(t,e.keypair.publicKey,0,i.TOKEN_PROGRAM_ID,i.ASSOCIATED_TOKEN_PROGRAM_ID),o=Buffer.from(e.recipient,"utf8"),c=Buffer.alloc(8);c.writeBigUInt64LE(e.amountBaseUnits);const l=Buffer.alloc(4);l.writeUInt32LE(o.length);const d=n?this.buildNativeBridgeInstruction(e.keypair.publicKey,c,l,o):this.buildTokenBridgeInstruction(e.keypair.publicKey,r,t,s,c,l,o),u=new a.Transaction;u.add(a.ComputeBudgetProgram.setComputeUnitPrice({microLamports:375e3}),a.ComputeBudgetProgram.setComputeUnitLimit({units:2e5}),d),u.feePayer=e.keypair.publicKey;const h=await this.sendAndConfirmWithFallback(u,e.keypair),g={collection:e.metadata.descriptor.collection,category:e.metadata.descriptor.category,type:e.metadata.descriptor.type,additionalKey:e.metadata.descriptor.additionalKey,instance:"0"};return await this.galaConnectClient.registerBridgeTransaction({quantity:e.amount,tokenInstance:g,fromChain:"Solana",toChain:"GC",hash:h}),h}async sendAndConfirmWithFallback(e,t,n=3){let a=null;for(let s=1;s<=n;s++){try{const r=await this.solanaConnection.getLatestBlockhash("confirmed");e.recentBlockhash=r.blockhash,e.feePayer=t.publicKey,e.signatures=[],e.sign(t);const i=await this.solanaConnection.sendRawTransaction(e.serialize(),{skipPreflight:!1,preflightCommitment:"confirmed"});try{return await this.solanaConnection.confirmTransaction({signature:i,blockhash:r.blockhash,lastValidBlockHeight:r.lastValidBlockHeight},"confirmed"),i}catch(e){const t=at(e)?e.message.toLowerCase():"";if(!(t.includes("block height exceeded")||t.includes("blockhash not found")||t.includes("expired")))throw e;const r=await this.solanaConnection.getSignatureStatuses([i]);if("confirmed"===r.value[0]?.confirmationStatus||"finalized"===r.value[0]?.confirmationStatus)return i;a=new Error(`Transaction ${i} not confirmed - block height exceeded (attempt ${s}/${n})`)}}catch(e){a=at(e)?e:new Error(st(e));const t=a.message.toLowerCase();if(!(t.includes("block height exceeded")||t.includes("blockhash not found")||t.includes("timeout")||t.includes("expired"))||s===n)throw a}const r=Math.min(1e3*Math.pow(2,s-1),5e3);await $r(r)}throw a??new Error("Transaction confirmation failed after max retries")}buildNativeBridgeInstruction(e,t,n,s){const r=Buffer.concat([er.BRIDGE_OUT_NATIVE,t,n,s]);return new a.TransactionInstruction({programId:this.solanaBridgeProgramId,keys:[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:this.solanaBridgeTokenAuthority,isSigner:!1,isWritable:!0},{pubkey:this.solanaNativeBridgePda,isSigner:!1,isWritable:!1},{pubkey:this.solanaBridgeConfigPda,isSigner:!1,isWritable:!0},{pubkey:a.SystemProgram.programId,isSigner:!1,isWritable:!1}],data:r})}buildTokenBridgeInstruction(e,t,n,s,r,o,c){const l=Buffer.concat([er.BRIDGE_OUT,r,o,c]);return new a.TransactionInstruction({programId:this.solanaBridgeProgramId,keys:[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!0},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:s.mintLookup,isSigner:!1,isWritable:!1},{pubkey:s.tokenBridge,isSigner:!1,isWritable:!1},{pubkey:s.bridgeTokenAccount,isSigner:!1,isWritable:!0},{pubkey:this.solanaBridgeTokenAuthority,isSigner:!1,isWritable:!1},{pubkey:this.solanaBridgeConfigPda,isSigner:!1,isWritable:!0},{pubkey:a.SystemProgram.programId,isSigner:!1,isWritable:!1},{pubkey:i.TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1}],data:l})}async getSolanaBridgeAccounts(e){const t=e.toBase58(),n=this.solanaBridgeAccountCache.get(t);if(n)return n;const[s]=a.PublicKey.findProgramAddressSync([Buffer.from("mint_lookup_v1"),e.toBuffer()],this.solanaBridgeProgramId),r=await this.solanaConnection.getAccountInfo(s,"confirmed");if(!r)throw It(`Mint lookup account not found for ${s.toBase58()}`,"solanaBridgeProgram");if(!r.owner.equals(this.solanaBridgeProgramId))throw It("Mint lookup account owner mismatch for Solana bridge program","solanaBridgeProgram");if(r.data.length<40)throw It("Mint lookup account data is unexpectedly short","solanaBridgeProgram");const o={mintLookup:s,tokenBridge:new a.PublicKey(r.data.slice(8,40)),bridgeTokenAccount:hi(e,this.solanaBridgeTokenAuthority,0,i.TOKEN_PROGRAM_ID,i.ASSOCIATED_TOKEN_PROGRAM_ID)};return this.solanaBridgeAccountCache.set(t,o),o}}const mi={prod:{ethereum:"https://eth.gala.games",solana:"https://api.mainnet-beta.solana.com"},stage:{ethereum:"https://dev.eth.gala.games",solana:"https://api.devnet.solana.com"}},pi={solanaBridgeProgram:"AaE4dTnL75XqgUJpdxBKg6vS9sTJgBPJwBQRVhD29WwS",rateLimit:12,pollInterval:15e3,pollTimeout:27e5};class fi{static normalizeGalaChainAddress(e){const t=new ta;if("client"===t.detectFormat(e))return e;let n=e;(e.startsWith("eth|0x")||e.startsWith("eth|0X"))&&(n=e.substring(0,4)+e.substring(6));const a=t.normalizeInput(n);if(!a)throw It(`Invalid GalaChain address format: ${e}`,"galaChainWalletAddress");const s=t.extractHex(a);return`eth|${fi.checksumAddress(s)}`}static checksumAddress(e){const n=e.toLowerCase(),a=Zn(t.keccak256(t.toUtf8Bytes(n)));let s="";for(let e=0;e<n.length;e++){const t=n[e],r=a[e];void 0!==t&&void 0!==r&&parseInt(r,16)>=8?s+=t.toUpperCase():s+=t??""}return s}constructor(e){const t=fi.normalizeGalaChainAddress(e.galaChainWalletAddress),n=e.environment??"prod",a=Us["stage"===n?"stage":"prod"],s=mi[n],r={galaConnectBaseUrl:e.galaConnectBaseUrl??a.dexApiBaseUrl,galaChainApiBaseUrl:e.galaChainApiBaseUrl??a.gatewayBaseUrl,ethereumRpcUrl:e.ethereumRpcUrl??s.ethereum,solanaRpcUrl:e.solanaRpcUrl??s.solana,ethereumBridgeContract:e.ethereumBridgeContract??Vs(n),solanaBridgeProgram:e.solanaBridgeProgram??pi.solanaBridgeProgram,rateLimit:e.rateLimit??pi.rateLimit,pollInterval:e.pollInterval??pi.pollInterval,pollTimeout:e.pollTimeout??pi.pollTimeout,galaChainWalletAddress:t,ethereumPrivateKey:e.ethereumPrivateKey,environment:n};this.config=e.solanaPrivateKey?{...r,solanaPrivateKey:e.solanaPrivateKey}:r,this.galaConnectClient=new oi({baseUrl:this.config.galaConnectBaseUrl,galachainBaseUrl:this.config.galaChainApiBaseUrl,walletAddress:this.config.galaChainWalletAddress,requestsPerSecond:this.config.rateLimit}),e.bridgeableTokenService&&(this.bridgeableTokenService=e.bridgeableTokenService),this.strategies=new Map,this.initializeStrategies()}initializeStrategies(){const e=js(this.config.environment),t={galaConnectClient:this.galaConnectClient,galaChainWalletAddress:this.config.galaChainWalletAddress,ethereumPrivateKey:this.config.ethereumPrivateKey,ethereumRpcUrl:this.config.ethereumRpcUrl,ethereumBridgeContract:this.config.ethereumBridgeContract,tokenConfigs:e};if(this.strategies.set("Ethereum",new ui(t)),null!==this.config.solanaPrivateKey&&void 0!==this.config.solanaPrivateKey){const e={galaConnectClient:this.galaConnectClient,galaChainWalletAddress:this.config.galaChainWalletAddress,ethereumPrivateKey:this.config.ethereumPrivateKey,solanaPrivateKeyBase58:this.config.solanaPrivateKey,solanaRpcUrl:this.config.solanaRpcUrl,solanaBridgeProgram:this.config.solanaBridgeProgram,tokenConfigs:Qs};this.strategies.set("Solana",new gi(e))}}async resolveTokenSymbol(e,t){return _s(async()=>{if(!this.bridgeableTokenService)throw It("BridgeableTokenService is required for tokenId resolution. Pass bridgeableTokenService in BridgeServiceConfig or use the SDK's bridge methods.","bridgeableTokenService");const n=Qr(e).stringified,a="Ethereum"===t?"ETHEREUM":"SOLANA",s=await this.bridgeableTokenService.getTokenByTokenId(n,a);if(!s){throw It([`Token "${n}" was not found in the list of tokens bridgeable to ${t}.`,"","Troubleshooting suggestions:",' 1. Verify the tokenId format is correct (e.g., "GALA|Unit|none|none")'," 2. Check if the token supports bridging to this network:",` - Use sdk.fetchAllBridgeableTokensByNetwork('${a}')`," - Or use sdk.isTokenBridgeableToNetwork({ tokenSymbol, network })"," 3. Common tokenId formats for bridge tokens:",' - GALA: "GALA|Unit|none|none"',' - GUSDC: "GUSDC|Unit|none|eth:0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"'," 4. Use sdk.getSupportedBridgeTokens() to list all available tokens"].join("\n"),"tokenId")}return s.symbol},"BridgeService.resolveTokenSymbol")}async estimateBridgeFee(e){return _s(async()=>{const t=await this.resolveTokenSymbol(e.tokenId,e.destinationChain);return this.getStrategy(e.destinationChain).estimateFee(t,e.amount??"0")},"BridgeService.estimateBridgeFee")}async bridgeOut(e){return _s(async()=>{const t=await this.resolveTokenSymbol(e.tokenId,e.destinationChain),n=this.getStrategy(e.destinationChain);if(!n.isValidAddress(e.recipientAddress))throw It(`Invalid recipient address for ${e.destinationChain}: ${e.recipientAddress}`,"recipientAddress");if(!n.isTokenSupported(t))throw It(`Token ${t} is not supported for ${e.destinationChain} bridging`,"tokenSymbol");return n.bridgeOut({...e,tokenSymbol:t})},"BridgeService.bridgeOut")}async bridgeIn(e){return _s(async()=>{const t=await this.resolveTokenSymbol(e.tokenId,e.sourceChain),n=this.getStrategy(e.sourceChain);if(!n.isTokenSupported(t))throw It(`Token ${t} is not supported for ${e.sourceChain} bridging`,"tokenSymbol");return n.bridgeIn({...e,tokenSymbol:t})},"BridgeService.bridgeIn")}async getBridgeStatus(e,t){return _s(async()=>{if(null!=t){const n=this.strategies.get(t);if(n)return n.getStatus(e)}const n=this.strategies.get("Ethereum");let a;if(n)try{return await n.getStatus(e)}catch(e){a=at(e)?e:new Error(st(e))}const s=this.strategies.get("Solana");if(s)try{return await s.getStatus(e)}catch(e){a=at(e)?e:new Error(st(e))}const r=a?` (last error: ${a.message})`:"";throw Dt(`Unable to get status for transaction ${e}${r}`,e)},"BridgeService.getBridgeStatus")}async waitForBridgeCompletion(e,t){return _s(async()=>{const n={pollInterval:t?.pollInterval??this.config.pollInterval,timeout:t?.timeout??this.config.pollTimeout,...t?.onStatusUpdate&&{onStatusUpdate:t.onStatusUpdate}},a=this.strategies.get("Ethereum");if(a)try{return await a.getStatus(e),a.waitForCompletion(e,n)}catch{}const s=this.strategies.get("Solana");if(s)return s.waitForCompletion(e,n);throw Dt(`Unable to wait for transaction ${e}: no suitable strategy found`,e)},"BridgeService.waitForBridgeCompletion")}getSupportedBridgeTokens(e){const t=[],n=js(this.config.environment);if(null==e||"Ethereum"===e)for(const e of n)t.push({symbol:e.symbol,decimals:e.decimals??18,verified:!0,supportedChains:["Ethereum"],galaChainDescriptor:{collection:e.symbol.startsWith("G")?e.symbol:`G${e.symbol}`,category:"Unit",type:"none",additionalKey:"none"},externalAddresses:{ethereum:e.contractAddress}});if(null==e||"Solana"===e)for(const e of Qs){const n=t.find(t=>t.symbol===e.symbol);n?(n.supportedChains.push("Solana"),n.externalAddresses.solana=e.mintAddress):t.push({symbol:e.symbol,decimals:e.decimals??9,verified:!0,supportedChains:["Solana"],galaChainDescriptor:{collection:e.symbol.startsWith("G")?e.symbol:`G${e.symbol}`,category:"Unit",type:"none",additionalKey:"none"},externalAddresses:{solana:e.mintAddress}})}return t}getSupportedBridgeChains(){return Array.from(this.strategies.keys())}isTokenSupported(e,t){if(null!=t){const n=this.strategies.get(t);return n?.isTokenSupported(e)??!1}for(const t of this.strategies.values())if(t.isTokenSupported(e))return!0;return!1}isValidAddress(e,t){const n=this.strategies.get(t);return n?.isValidAddress(e)??!1}async getEthereumTokenBalance(e,t){return _s(async()=>Kr(this.strategies).getEthereumTokenBalance(e,t),"BridgeService.getEthereumTokenBalance")}async getEthereumNativeBalance(e){return _s(async()=>Kr(this.strategies).getEthereumNativeBalance(e),"BridgeService.getEthereumNativeBalance")}async getSolanaTokenBalance(e,t){return _s(async()=>Gr(this.strategies).getSolanaTokenBalance(e,t),"BridgeService.getSolanaTokenBalance")}async getSolanaNativeBalance(e){return _s(async()=>Gr(this.strategies).getSolanaNativeBalance(e),"BridgeService.getSolanaNativeBalance")}async fetchEthereumWalletTokenBalance(e,t){return _s(async()=>{const n=Kr(this.strategies),a=cr(js(this.config.environment),e,"Ethereum"),s=Wr(t,n);return ir(a,await n.getEthereumTokenBalance(e,s))},"BridgeService.fetchEthereumWalletTokenBalance")}async fetchEthereumWalletNativeBalance(e){return _s(async()=>{const t=Kr(this.strategies),n=Wr(e,t);return rr("ETH",await t.getEthereumNativeBalance(n),18)},"BridgeService.fetchEthereumWalletNativeBalance")}async fetchSolanaWalletTokenBalance(e,t){return _s(async()=>{const n=Gr(this.strategies),a=cr(Qs,e,"Solana"),s=Wr(t,n);return or(a,await n.getSolanaTokenBalance(e,s))},"BridgeService.fetchSolanaWalletTokenBalance")}async fetchSolanaWalletNativeBalance(e){return _s(async()=>{const t=Gr(this.strategies),n=Wr(e,t);return rr("SOL",await t.getSolanaNativeBalance(n),9)},"BridgeService.fetchSolanaWalletNativeBalance")}async requestSolanaDevnetAirdrop(e,t){return _s(async()=>Gr(this.strategies).requestDevnetAirdrop(e,t),"BridgeService.requestSolanaDevnetAirdrop")}async getSolanaTransactionStatus(e){return _s(async()=>Gr(this.strategies,"Solana bridge strategy not configured. This method requires Solana wallet configuration. Initialize SDK with solanaPrivateKey to use Solana features.").getSolanaTransactionStatus(e),"BridgeService.getSolanaTransactionStatus")}async getEthereumTransactionStatus(e){return _s(async()=>Kr(this.strategies,"Ethereum bridge strategy not configured. This method requires Ethereum wallet configuration. Initialize SDK with ethereumPrivateKey to use Ethereum features.").getEthereumTransactionStatus(e),"BridgeService.getEthereumTransactionStatus")}async fetchEthereumWalletAllBalances(e){return _s(async()=>{const t=Kr(this.strategies),n=Wr(e,t),a=js(this.config.environment),[s,...r]=await Promise.all([t.getEthereumNativeBalance(n),...a.map(async e=>ir(e,await t.getEthereumTokenBalance(e.symbol,n)))]);return{address:n,native:rr("ETH",s,18),tokens:r,timestamp:Date.now()}},"BridgeService.fetchEthereumWalletAllBalances")}async fetchSolanaWalletAllBalances(e){return _s(async()=>{const t=Gr(this.strategies),n=Wr(e,t),[a,...s]=await Promise.all([t.getSolanaNativeBalance(n),...Qs.map(async e=>or(e,await t.getSolanaTokenBalance(e.symbol,n)))]);return{address:n,native:rr("SOL",a,9),tokens:s,timestamp:Date.now()}},"BridgeService.fetchSolanaWalletAllBalances")}getStrategy(e){const t=this.strategies.get(e);if(!t)throw It(`Bridging to ${e} is not configured. `+("Solana"===e?"Please provide solanaPrivateKey in config.":"Please check your configuration."),`${e.toLowerCase()}PrivateKey`);return t}}var yi,vi;!function(e){e.PROCESSED="PROCESSED",e.COMPLETED="COMPLETED",e.SUCCESS="SUCCESS",e.FAILED="FAILED",e.ERROR="ERROR",e.PROCESSING="PROCESSING",e.PENDING="PENDING"}(yi||(yi={})),function(e){e.PENDING="pending",e.PROCESSING="processing",e.COMPLETED="completed",e.FAILED="failed",e.TIMEOUT="timeout"}(vi||(vi={}));const ki={[yi.PROCESSED]:vi.COMPLETED,[yi.COMPLETED]:vi.COMPLETED,[yi.SUCCESS]:vi.COMPLETED,[yi.FAILED]:vi.FAILED,[yi.ERROR]:vi.FAILED,[yi.PROCESSING]:vi.PROCESSING,[yi.PENDING]:vi.PENDING},bi="7.0.0-beta.4",wi={DEFAULT_LIMIT:10,BACKEND_MAX_PAGE_SIZE:20};function Si(e,t){if("number"!=typeof e||!Number.isInteger(e))throw Ft("total","a non-negative integer",e);if(e<0)throw Rt("total",0,1/0,e);if("number"!=typeof t||!Number.isInteger(t))throw Ft("limit","a non-negative integer",t);if(t<0)throw Rt("limit",0,1/0,t);return 0===t?1:0===e?0:Math.ceil(e/t)}function Ai(e){return"string"==typeof e?e:"number"==typeof e||"boolean"==typeof e||"bigint"==typeof e?String(e):JSON.stringify(e)??""}function Ei(e,t){const n={};void 0!==e.cursor&&(n.cursor=e.cursor);const a=void 0!==e.pageSize?Math.min(e.pageSize,t):t;return n.pageSize=String(a),n}function Ti(e,t,n){for(const a of n){const n=t[a];null!=n&&""!==n&&(e[a]=Ai(n))}return e}const Ci="x-api-key";class Ni extends Xn{constructor(e,t,n,a=!1,s){super(e,a),this.adminApiKey=t??void 0,this.jwtAuth=n,this.userApiKey=s??void 0}setJwtAuth(e){this.jwtAuth=e}validateTokenName(e,t){!function(e,t){if(!Un(e))throw Tt("tokenName","Token name");const n=zt(e);if(!t.PATTERN.test(n))throw Ct("tokenName",`${t.MIN_LENGTH}-${t.MAX_LENGTH} alphanumeric characters`,"Token name")}(e,t)}validateRequiredString(e,t,n){!function(e,t,n){if(!Un(e))throw Tt(t,n)}(e,t,n)}validateOptionalString(e,t,n,a){!function(e,t,n,a){if(null!=e){if("string"!=typeof e)throw Ft(t,"string",typeof e,n);if(e.length>a)throw Ot(t,a,e.length,n)}}(e,t,n,a)}validateOptionalNumber(e,t,n,a,s,r,i){!function(e,t,n,a,s){if(null!=e){if("number"!=typeof e)throw Ft(t,"number",typeof e,n);if(e<a||e>s)throw Rt(t,a,s,e,n)}}(e,t,n,a,s)}validateOptionalDate(e,t,n){!function(e,t,n){if(null!=e&&!tn(e))throw Ct(t,"a valid ISO 8601 date string",n)}(e,t,n)}validatePositiveInteger(e,t,n){jn(e,t,n)}validateStatusFilter(e,t,n="status"){Vn(e,t,n)}buildPaginationParams(e,t){return Ei(e,t)}addOptionalFilterParams(e,t,n){return Ti(e,t,n)}buildEndpoint(e,t){return function(e,t){let n=e;for(const[e,a]of Object.entries(t))n=n.replace(`:${e}`,encodeURIComponent(a.toLowerCase()));return n}(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 wt("Admin API key required for this operation. Set streamAdminApiKey in SDK config.");return{[Ci]:this.adminApiKey}}getJwtHeaders(){if(!this.jwtAuth)throw new wt("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?{[Ci]:this.userApiKey}:this.getJwtHeaders()}extractData(e){return Mt(e,"Backend request failed",!0),$t(e,"No data in backend response")}extractDataOrNull(e){return Mt(e,"Backend request failed",!1),e.data??null}async toggleFeature(e,t,n){this.validateTokenName(e,n);const a=this.buildEndpoint(t,{tokenName:e}),s=await this.http.post(a,{},this.getAdminHeaders()),r=this.extractData(s);return{enabled:r.enabled,tokenName:r.tokenName??zt(e)}}}class Ii extends Ni{constructor(e,t,n,a=!1,s){super(e,t,n,a,s)}async getSettings(){return{settings:(await this.http.get(We.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(We.UPDATE_SETTINGS,t,this.getDualAuthHeaders())).settings}}async getModeration(e){this.validatePositiveInteger(e.flagId,"flagId","Flag ID");const t=We.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=We.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(We.GET_STATUS,{},this.getDualAuthHeaders())).status}}}const Di=$n({MODERATOR:"MODERATOR",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MANAGER:"MANAGER",OWNER:"OWNER"});function _i(e){return Di.includes(e)}function Ri(e,t,n=!1){const a=t.length;if(dt(t,()=>{qn(e.description,"description",255)}),t.length>a&&(t[a]="Description must be 255 characters or less"),void 0!==e.tokenNames){const n=t.length;dt(t,()=>{if(!Array.isArray(e.tokenNames))throw Ft("tokenNames","an array",e.tokenNames);if(!e.tokenNames.every(e=>"string"==typeof e))throw Ft("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;dt(t,()=>{zn(e.expiresAt,"expiresAt")}),t.length>n&&(t[n]="expiresAt must be a valid ISO 8601 date string")}}class xi extends Xn{constructor(e,t,n=!1){super(e,n,t)}extractData(e){let t;t="error"in e?e.error:"success"in e&&!e.success;const n={status:200,error:t,data:e.data};return void 0!==e.message&&(n.message=e.message),Mt(n,"API key operation failed",!0),e.data}validateApiKeyId(e){this.validatePositiveInteger(e,"id","API key ID")}async create(e){const t=function(e){const t=[];return void 0===e.role||null===e.role?t.push("Role is required"):_i(e.role)||t.push(`Invalid role. Must be one of: ${Di.join(", ")}`),Ri(e,t),t}(e);if(t.length>0)throw new kt(t.join("; "),"options","VALIDATION_FAILED");this.logger.debug("Creating API key",{role:e.role,delegateAllTokens:e.delegateAllTokens});const n={role:e.role};void 0!==e.description&&(n.description=e.description),void 0!==e.delegateAllTokens&&(n.delegateAllTokens=e.delegateAllTokens),void 0!==e.tokenNames&&e.tokenNames.length>0&&(n.tokenNames=e.tokenNames),void 0!==e.expiresAt&&(n.expiresAt=e.expiresAt),void 0!==e.tokenPermissions&&(n.tokenPermissions=e.tokenPermissions);const a=await this.http.post(J.CREATE,n,this.getJwtHeaders()),s=this.extractData(a);return this.logger.debug("API key created",{id:s.id,keyPrefix:s.keyPrefix}),s}async findAll(e={}){!function(e){if(void 0!==e.pageSize&&("number"!=typeof e.pageSize||e.pageSize<1||e.pageSize>on))throw Ft("pageSize",`number between 1 and ${on}`,typeof e.pageSize);if(void 0!==e.cursor&&("string"!=typeof e.cursor||""===e.cursor.trim()))throw Ft("cursor","non-empty string",typeof e.cursor)}(e),this.logger.debug("Listing API keys",e);const t=Ei(e,on),n=await this.http.get(J.LIST,t,this.getJwtHeaders()),a=this.extractData(n);return this.logger.debug("Listed API keys",{count:a.apiKeys.length,total:a.pageInfo.totalCount}),a}async findOne(e){this.validateApiKeyId(e),this.logger.debug("Getting API key",{id:e});const t=J.GET.replace(":id",String(e)),n=await this.http.get(t,{},this.getJwtHeaders()),a=this.extractData(n);return this.logger.debug("Got API key",{id:a.id,keyPrefix:a.keyPrefix}),a}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||_i(e.role)||t.push(`Invalid role. Must be one of: ${Di.join(", ")}`),Ri(e,t,!0),t}(t);if(n.length>0)throw new kt(n.join("; "),"options","VALIDATION_FAILED");this.logger.debug("Updating API key",{id:e,options:t});const a={};void 0!==t.role&&(a.role=t.role),void 0!==t.description&&(a.description=t.description),void 0!==t.delegateAllTokens&&(a.delegateAllTokens=t.delegateAllTokens),void 0!==t.tokenNames&&(a.tokenNames=t.tokenNames),void 0!==t.expiresAt&&(a.expiresAt=t.expiresAt),void 0!==t.tokenPermissions&&(a.tokenPermissions=t.tokenPermissions);const s=J.UPDATE.replace(":id",String(e)),r=await this.http.patch(s,a,this.getJwtHeaders()),i=this.extractData(r);return this.logger.debug("Updated API key",{id:i.id,keyPrefix:i.keyPrefix}),i}async revoke(e){this.validateApiKeyId(e),this.logger.debug("Revoking API key",{id:e});const t=J.REVOKE.replace(":id",String(e));await this.http.delete(t,{},this.getJwtHeaders()),this.logger.debug("API key revoked",{id:e})}getRoles(){return[...Di]}}const Oi={VIEWERS:"viewers",CHAT_PARTICIPANTS:"chat_participants"},Fi=Ln(Oi);function Bi(e){if(!Un(e.userAddress))throw Tt("userAddress");if(!(null==(t=e.reason)||""===t||"string"==typeof t&&!Hn(t)&&t.length<=un.BAN_REASON.MAX_LENGTH))throw new kt(`reason must be at most ${un.BAN_REASON.MAX_LENGTH} characters`,"reason","TOO_LONG");var t,n;if(n=e.durationSeconds,!(Pn(n)||"number"==typeof n&&n>=gn&&n<=mn))throw new kt(`durationSeconds must be between ${gn} and ${mn} seconds`,"durationSeconds","OUT_OF_RANGE")}class Ui extends Ni{constructor(e,t,n,a=!1,s){super(e,t,n,a,s)}async createBan(e){!function(e){Gn(e.tokenName,"tokenName",an),Bi(e)}(e);const t=this.buildEndpoint(G,{tokenName:e.tokenName}),n=Pi(e),a=await this.http.post(t,n,this.getMultiAuthHeaders());return{ban:this.extractData(a),tokenName:zt(e.tokenName)}}async removeBan(e){!function(e){if(Gn(e.tokenName,"tokenName",an),!Un(e.userAddress))throw Tt("userAddress")}(e);const t=this.buildEndpoint(q,{tokenName:e.tokenName,userAddress:e.userAddress}),n=await this.http.delete(t,{},this.getMultiAuthHeaders()),a=this.extractDataOrNull(n);return{removed:a?.removed??!0,tokenName:zt(e.tokenName),userAddress:a?.userAddress??e.userAddress.toLowerCase()}}async listBans(e){!function(e){Gn(e.tokenName,"tokenName",an),Mn(0,void 0,on,e.pageSize)}(e);const t=this.buildEndpoint(W,{tokenName:e.tokenName}),n=this.buildPaginationParams(e,on);this.addOptionalFilterParams(n,e,["search","name","userAddress"]);const a=await this.http.get(t,n,this.getMultiAuthHeaders()),s=this.extractData(a);return{items:s.bans,pageInfo:s.pageInfo}}async getBanStatus(e){!function(e){if(Gn(e.tokenName,"tokenName",an),!Un(e.userAddress))throw Tt("userAddress")}(e);const t=this.buildEndpoint(H,{tokenName:e.tokenName,userAddress:e.userAddress}),n=await this.http.get(t,{},this.getMultiAuthHeaders()),a=this.extractDataOrNull(n);return{banned:null!==a,...null!==a&&{ban:a},tokenName:zt(e.tokenName),userAddress:e.userAddress.toLowerCase()}}async getActiveUsers(e){!function(e){if(Gn(e.tokenName,"tokenName",an),void 0!==e.type&&!Fi(e.type))throw new kt(`type must be one of: ${Object.values(Oi).join(", ")}`,"type",pt)}(e);const t=this.buildEndpoint(z,{tokenName:e.tokenName}),n={};this.addOptionalFilterParams(n,e,["type","search","name","userAddress"]);const a=await this.http.get(t,n,this.getMultiAuthHeaders());return this.extractData(a)}async createGlobalBan(e){!function(e){Bi(e)}(e);const t=Pi(e),n=await this.http.post(j,t,this.getDualAuthHeaders());return{ban:this.extractData(n)}}async removeGlobalBan(e){!function(e){if(!Un(e.userAddress))throw Tt("userAddress")}(e);const t=this.buildEndpoint(Q,{userAddress:e.userAddress}),n=await this.http.delete(t,{},this.getDualAuthHeaders()),a=this.extractDataOrNull(n);return{removed:a?.removed??!0,userAddress:a?.userAddress??e.userAddress.toLowerCase()}}async listGlobalBans(e){const t=e??{pageSize:20};!function(e){Mn(0,void 0,on,e.pageSize)}(t);const n=this.buildPaginationParams(t,on);this.addOptionalFilterParams(n,t,["search","name","userAddress"]);const a=await this.http.get(V,n,this.getDualAuthHeaders()),s=this.extractData(a);return{items:s.bans,pageInfo:s.pageInfo}}async getGlobalBan(e){!function(e){if(!Un(e.userAddress))throw Tt("userAddress")}(e);const t=this.buildEndpoint(X,{userAddress:e.userAddress}),n=await this.http.get(t,{},this.getDualAuthHeaders()),a=this.extractDataOrNull(n);return{banned:null!==a,...null!==a&&{ban:a},userAddress:e.userAddress.toLowerCase()}}}function Pi(e){const t={userAddress:e.userAddress};return void 0!==e.reason&&(t.reason=e.reason),void 0!==e.durationSeconds&&(t.durationSeconds=e.durationSeconds),t}async function Mi(e,t={}){const{maxPages:n=1e4,logger:a,pageSize:s=20,concurrency:r=1,startPage:i=1}=t,o=[];let c=i;const l=i+n-1;let d=!0,u=0;if(r<=1)for(;d&&c<=l;){a&&a.debug(`Auto-pagination: fetching page ${c} with limit ${s}`);const t=await e(c,s);if(null==t||!Array.isArray(t.items)){a&&a.warn("Auto-pagination: received invalid result structure, stopping");break}if(o.push(...t.items),u=t.total,a&&a.debug(`Auto-pagination: page ${c} returned ${t.items.length} items, hasNext: ${String(t.hasNext)}`),0===t.items.length){a&&a.debug(`Auto-pagination: no items returned on page ${c}, exiting loop`);break}d=t.hasNext,c++}else for(a&&a.debug(`Auto-pagination: using concurrent mode with concurrency=${r}`);d&&c<=l;){const t=[];for(let e=0;e<r&&c+e<=l;e++)t.push(c+e);a&&a.debug(`Auto-pagination: fetching pages ${t.join(", ")} concurrently`);const n=t.map(t=>e(t,s).catch(e=>{const n=e,r=n.statusCode??n.response?.status??n.originalError?.response?.status??n.status??n.launchpadError?.statusCode;if(400===r||404===r)return a&&a.debug(`Auto-pagination: page ${t} returned ${r} (end of pagination)`,{statusCode:r}),{items:[],total:0,totalPages:0,page:t,limit:s,hasNext:!1,hasPrevious:!1};throw e})),i=await Promise.all(n);for(const e of i){if(null==e||!Array.isArray(e.items)){a&&a.warn("Auto-pagination: received invalid result structure in batch, stopping"),d=!1;break}if(0===e.items.length){a&&a.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,a&&a.debug(`Auto-pagination: batch complete, total items so far: ${o.length}`)}return c>l&&a&&a.warn(`Auto-pagination: exceeded maxPages limit of ${n} (maxPage=${l}), stopping iteration`),a&&a.debug(`Auto-pagination: completed with total items: ${o.length}, total count: ${u}`),{items:o,total:u}}function Li(e){if("string"==typeof e){if(!Un(t=e)||!t.includes("|"))throw new kt(`Invalid tokenId string format: "${e}". Expected pipe-delimited format: "collection|category|type|additionalKey" or "collection|category|type|additionalKey|instance"`,"tokenId","INVALID_TOKEN_ID_FORMAT");const n=e.split("|");if(n.length>=5){const e=jr(n.slice(0,4).join("|")),t=n[4]??"0";return{...e,instance:t.length>0?t:"0"}}return{...jr(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(!Xr(e))throw new kt("Invalid tokenId object format. All fields (collection, category, type, additionalKey) must be non-empty strings","tokenId","INVALID_TOKEN_ID_FORMAT");return e}if(!Xr(e))throw new kt("Invalid tokenId object format. All fields (collection, category, type, additionalKey) are required","tokenId","INVALID_TOKEN_ID_FORMAT");return{...e,instance:"0"}}throw new kt(`Invalid tokenId type: ${typeof e}. Expected string, TokenClassKey, or TokenInstanceKey`,"tokenId","INVALID_TOKEN_ID_TYPE")}function $i(e){return function(e){try{if(!Un(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("$");if(n.length<4)throw new Error(`Invalid vault address format: expected at least 4 parts separated by $, got ${n.length}`);const[a,s,r,...i]=n;if(""===a||""===s||""===r)throw new Error("Collection, category, and type must be non-empty");const o=i.slice(0,-1),c=o.length>0?o.join("$"):i[0];if(void 0===a||void 0===s||void 0===r||""===c||void 0===c)throw new Error("AdditionalKey must be non-empty");return{collection:a,category:s,type:r,additionalKey:c}}catch(t){throw new kt(`Invalid vault address: "${e}". Expected format: "service|Token$Unit$SYMBOL$additionalKey$launchpad". Error: ${st(t)}`,"vaultAddress","INVALID_VAULT_ADDRESS_FORMAT")}}(e)}function Ki(e){return{...$i(e),instance:"0"}}function Gi(e){return $i(e).type}function Wi(e){return Ms(Li(e))}var Hi=Object.freeze({__proto__:null,extractTokenSymbolFromVault:Gi,isTokenClassKeyStrict:Xr,normalizeToTokenInstanceKey:Li,normalizeTokenIdToString:Wi,parseVaultAddressToTokenClassKey:$i,parseVaultAddressToTokenInstance:Ki});class qi{constructor(e,t=!1,n){this.dexApiHttp=e,this.logger=new Qt({debug:t,context:n??this.constructor.name})}getApiEndpoint(){return"/v1/tokens"}getMaxLimit(){return 1e3}getDefaultLimit(){return 1e3}async executePaginatedRequest(e,t,n){const a=Math.min(t,this.getMaxLimit()),s=this.buildApiParams(n),r=await this.dexApiHttp.request({method:"GET",url:this.getApiEndpoint(),params:{...s,pageSize:a,offset:e}});if(Pn(r)||!Array.isArray(r.tokens))throw new kt("Invalid API response: expected { tokens: array }","response","INVALID_RESPONSE");return{items:this.transformApiResponse(r.tokens),rawCount:r.tokens.length}}async autoPaginateFetch(e){return async function(e,t){const{maxLimit:n,logger:a,maxPages:s=1e4}=t,r=[];let i=0,o=!0,c=0;for(;o&&c<s;){a&&a.debug(`Auto-pagination (offset): fetching at offset ${i} with limit ${n}`);const t=await e(i,n);if(null==t||!Array.isArray(t.items)){a&&a.warn("Auto-pagination (offset): received invalid result structure, stopping");break}r.push(...t.items),o=t.rawCount===n,i+=n,c++,a&&a.debug(`Auto-pagination (offset): fetched ${r.length} items so far (hasMore=${String(o)})`)}return c>=s&&a&&a.warn(`Auto-pagination (offset): exceeded maxPages limit of ${s}, stopping`),a&&a.debug(`Auto-pagination (offset): completed with total items: ${r.length}`),r}(async(t,n)=>this.executePaginatedRequest(t,n,e),{maxLimit:this.getMaxLimit(),logger:this.logger})}handleError(e,t){throw _t(e,t,this.logger)}}class zi extends Qn{constructor(e=!1){super(e),this.primaryIndex=new Map,this.secondaryIndex=new Map,this.fetchTimestamps=new Map}normalizeKey(e){return jt(e)}has(e){const t=this.primaryIndex.get(e);return void 0!==t&&t.size>0}getAll(e){const t=this.primaryIndex.get(e);return t?Array.from(t.values()):[]}getByPrimaryKey(e,t){const n=this.normalizeKey(t);return this.primaryIndex.get(e)?.get(n)}getBySecondaryKey(e,t){const n=this.normalizeKey(t);return this.secondaryIndex.get(e)?.get(n)}set(e,t){const n=new Map,a=new Map;for(const e of t){const t=this.normalizeKey(this.extractPrimaryKey(e));n.set(t,e);const s=this.normalizeKey(this.extractSecondaryKey(e));a.set(s,e)}this.primaryIndex.set(e,n),this.secondaryIndex.set(e,a),this.fetchTimestamps.set(e,Date.now()),this.logger.debug(`Cached ${t.length} items for ${e}`)}merge(e,t){let n=this.primaryIndex.get(e);n||(n=new Map,this.primaryIndex.set(e,n));let a=this.secondaryIndex.get(e);a||(a=new Map,this.secondaryIndex.set(e,a));for(const e of t){const t=this.normalizeKey(this.extractPrimaryKey(e));n.set(t,e);const s=this.normalizeKey(this.extractSecondaryKey(e));a.set(s,e)}this.fetchTimestamps.set(e,Date.now()),this.logger.debug(`Merged ${t.length} items for ${e} (total: ${n.size})`)}getFetchTimestamp(e){return this.fetchTimestamps.get(e)}buildBaseStats(e){const t=[];let n=0;const a={},s={};for(const t of e)a[t]=0;for(const[e,r]of this.primaryIndex){t.push(e),n+=r.size,a[e]=r.size;const i=this.fetchTimestamps.get(e);void 0!==i&&(s[e]=i)}return{networks:t,totalItems:n,itemsByNetwork:a,fetchTimestamps:s}}clear(e){void 0!==e&&""!==e?(this.primaryIndex.delete(e),this.secondaryIndex.delete(e),this.fetchTimestamps.delete(e),this.logger.debug(`Cleared cache for ${e}`)):(this.primaryIndex.clear(),this.secondaryIndex.clear(),this.fetchTimestamps.clear(),this.logger.debug("Cleared all caches"))}size(e){return this.primaryIndex.get(e)?.size??0}hasByPrimaryKey(e,t){return void 0!==this.getByPrimaryKey(e,t)}getCachedNetworks(){return Array.from(this.primaryIndex.keys())}dump(){const e={};for(const t of this.getCachedNetworks())e[t]=this.getAll(t);return e}}const ji=["ETHEREUM","SOLANA"];class Vi extends zi{constructor(e=!1){super(e)}extractPrimaryKey(e){return e.symbol}extractSecondaryKey(e){return e.stringifiedTokenClassKey}getBySymbol(e,t){return this.getByPrimaryKey(e,t)}getByTokenId(e,t){return this.getBySecondaryKey(e,t)}getContractAddress(e,t){const n=this.getBySymbol(e,t);if(n)return"ETHEREUM"===e?n.ethereumContractAddress:n.solanaContractAddress}isTokenBridgeable(e,t){return void 0!==this.getBySymbol(e,t)}getStats(){const e=this.buildBaseStats(ji);return{...e,totalTokens:e.totalItems,tokensByNetwork:e.itemsByNetwork}}}class Xi extends qi{constructor(e,t=!1){super(e,t,"BridgeableTokenService"),this.cache=new Vi(t)}buildApiParams(e){return{canBridgeTo:(e?.network??"ETHEREUM").toLowerCase()}}transformApiResponse(e){return e.map(e=>{const t=e.otherNetworks?.find(e=>"Ethereum"===e.network),n=e.otherNetworks?.find(e=>"Solana"===e.network),a=e.canBridgeTo.map(e=>e.network).filter(e=>"Ethereum"===e||"Solana"===e),s={symbol:e.symbol,name:e.name,decimals:e.decimals,galaChainDescriptor:{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey},stringifiedTokenClassKey:e.stringifiedTokenClassKey,verified:e.verified,supportedChains:a};return void 0!==t?.contractAddress&&(s.ethereumContractAddress=t.contractAddress),void 0!==t?.symbol&&(s.ethereumSymbol=t.symbol),void 0!==t?.allowanceStorageSlot&&(s.ethereumAllowanceSlot=t.allowanceStorageSlot),void 0!==n?.contractAddress&&(s.solanaContractAddress=n.contractAddress),void 0!==n?.symbol&&(s.solanaSymbol=n.symbol),void 0!==e.image&&(s.image=e.image),void 0!==e.description&&(s.description=e.description),s})}async fetchBridgeableTokensByNetwork(e){const{network:t,offset:n=0,limit:a=this.getDefaultLimit()}=e,s=Math.min(a,this.getMaxLimit());return this.logger.debug(`Fetching bridgeable tokens for ${t} (offset=${n}, limit=${s})`),_s(async()=>{const e=(await this.executePaginatedRequest(n,s,{network:t})).items;return 0===n?this.cache.set(t,e):this.cache.merge(t,e),{tokens:e,network:t,fetchedAt:Date.now(),tokenCount:e.length}},`Failed to fetch bridgeable tokens for ${t}`,this.logger)}async fetchAllBridgeableTokensByNetwork(e){return _s(async()=>{const t=await async function(e){const{network:t,cache:n,fetchFn:a,logger:s,itemTypeName:r="items"}=e;if(n.has(t)){const e=n.getAll(t);return s&&s.debug(`Returning ${e.length} cached ${r} for ${t}`),{items:e,fetchedAt:n.getFetchTimestamp(t)??Date.now(),itemCount:e.length}}s&&s.debug(`Fetching all ${r} for ${t} (no cache)`);const i=await a();return n.set(t,i),{items:i,fetchedAt:Date.now(),itemCount:i.length}}({network:e,cache:this.cache,fetchFn:()=>this.autoPaginateFetch({network:e}),logger:this.logger,itemTypeName:"bridgeable tokens"});return{tokens:t.items,network:e,fetchedAt:t.fetchedAt,tokenCount:t.itemCount}},`Failed to fetch bridgeable tokens for ${e}`,this.logger)}async fetchAllTokensBridgeableToEthereum(){return this.fetchAllBridgeableTokensByNetwork("ETHEREUM")}async fetchAllTokensBridgeableToSolana(){return this.fetchAllBridgeableTokensByNetwork("SOLANA")}async isTokenBridgeableToNetwork(e){const{tokenId:t,network:n}=e,a=Wi(t);this.cache.has(n)||await this.fetchAllBridgeableTokensByNetwork(n);const s=this.cache.getByTokenId(n,a),r=void 0!==s,i=r?"ETHEREUM"===n?s.ethereumContractAddress:s.solanaContractAddress:void 0,o={isBridgeable:r,tokenSymbol:s?.symbol??jr(a).collection,network:n};return void 0!==i&&(o.contractAddress=i),o}async isTokenBridgeableToEthereum(e){return this.isTokenBridgeableToNetwork({tokenId:e,network:"ETHEREUM"})}async isTokenBridgeableToSolana(e){return this.isTokenBridgeableToNetwork({tokenId:e,network:"SOLANA"})}async getTokenBySymbol(e,t){const n=this.cache.getBySymbol(t,e);return n||(await this.fetchAllBridgeableTokensByNetwork(t),this.cache.getBySymbol(t,e))}async getTokenByTokenId(e,t){const n=this.cache.getByTokenId(t,e);return n||(await this.fetchAllBridgeableTokensByNetwork(t),this.cache.getByTokenId(t,e))}async getContractAddress(e,t){const n=await this.getTokenBySymbol(e,t);if(n)return"ETHEREUM"===t?n.ethereumContractAddress:n.solanaContractAddress}async getSupportedTokenSymbols(e){return this.cache.has(e)||await this.fetchAllBridgeableTokensByNetwork(e),this.cache.getAll(e).map(e=>e.symbol)}async preload(){this.logger.debug("Preloading bridgeable tokens for all networks"),await Promise.all([this.fetchAllBridgeableTokensByNetwork("ETHEREUM"),this.fetchAllBridgeableTokensByNetwork("SOLANA")]),this.logger.debug("Preloading complete")}getCacheStats(){return this.cache.getStats()}clearCache(e){this.cache.clear(e)}}function Qi(e){return{maxAcceptableReverseBondingCurveFee:Dn(e.maxAcceptableReverseBondingCurveFee)}}class Ji extends c.ChainCallDTO{constructor(e,t,n="0",a={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=Dn(t),this.expectedToken=_n(n),this.extraFees=Qi(a)}}class Yi extends c.ChainCallDTO{constructor(e,t,n,a={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=_n(t),this.expectedNativeToken=Dn(n),this.extraFees=Qi(a)}}class Zi extends c.ChainCallDTO{constructor(e,t,n="0",a={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=_n(t),this.expectedNativeToken=Dn(n),this.extraFees=Qi(a)}}class eo extends c.ChainCallDTO{constructor(e,t,n,a={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=Dn(t),this.expectedToken=_n(n),this.extraFees=Qi(a)}}const to={BuyNativeDto:Ji,BuyExactDto:Yi,SellExactDto:Zi,SellNativeDto:eo};function no(e,t,n){let a;Rn(t,0,1,"slippageToleranceFactor");try{a=Cn(e,"expectedAmount")}catch{throw new Error(`Invalid expected amount: ${e}. Must be a valid number`)}if(0===t)return e;const s=a.multipliedBy(t);let r;switch(n){case"buy-native":case"sell-exact":r=a.minus(s);break;case"buy-exact":case"sell-native":r=a.plus(s);break;default:throw new Error(`Unknown operation type: ${n}`)}return ns(r).isLessThan(0)&&(r=ns(0)),as(r)}function ao(e){return`${e}-${Date.now()}_${l.v4().replace(/-/gu,"").substring(0,26)}`}function so(){return ao("galaconnect-operation")}function ro(e,t){const n={[e]:[]},a=new Set;function s(e){const t=n[e];if(void 0===t)throw new Error("Missing EIP-712 type "+e);return t}function r(e,t,i,o=!1){if(void 0===t)return;if(Array.isArray(t)){const n=r(e,t[0],i,!0);return o||(a.add(e),s(i).push({name:e,type:(n??e)+"[]"})),void 0===n?void 0:n+"[]"}if("object"==typeof t&&null!==t){if(void 0!==n[e]||a.has(e))throw new Error("Name collisions not yet supported");n[e]=[];for(const[n,s]of Object.entries(t)){if(a.has(n))throw new Error("Name collisions not yet supported");r(n,s,e)}return o||(a.add(e),s(i).push({name:e,type:e})),e}let c;switch(typeof t){case"string":c="string";break;case"number":c="uint256";break;case"boolean":c="bool";break;case"bigint":case"symbol":case"function":case"undefined":case"object":throw new Error("Unsupported type for fieldName "+e+", "+typeof t);default:throw new Error("Unsupported type: "+typeof t)}return o||(a.add(e),s(i).push({name:e,type:c})),c}for(const[n,a]of Object.entries(t))r(n,a,e);return n}const io={name:"GalaChain"},oo={name:"ethereum",chainId:1};function co(e){if("string"!=typeof e)throw new Error("Wallet returned an invalid signature");return e}function lo(e,t,n,a){return{...e,signature:t,types:n,domain:a}}class uo extends n.PrivateKeySigner{constructor(e){super(e),this.typedDataWallet=new t.Wallet(e),this.walletAddress=`eth|${this.typedDataWallet.address.slice(2)}`}async signTypedData(e,t){const n=ro(e,t);return lo(t,await this.typedDataWallet.signTypedData(io,n,t),n,io)}}class ho extends n.GalaWalletSigner{async signTypedData(e,t){const n=ro(e,t),a={domain:oo,types:n,message:t,Primary_type:e};return lo(t,co(await function(){const e=globalThis.window,t=e?.gala;if(void 0===t)throw new Error("Gala wallet is not available");return t}().request({method:"eth_signTypedData",params:[JSON.stringify(a),this.walletAddress]})),n,oo)}}class go extends n.BrowserWalletSigner{constructor(e,t){super(e,t),this.typedDataProvider=e}async signTypedData(e,t){const n=this.typedDataProvider,a=await n.getNetwork(),s={name:a.name,chainId:Number(a.chainId)},r=ro(e,t),i=await n.getSigner();return lo(t,co(await i.signTypedData(s,r,t)),r,s)}}function mo(e){if(!Un(e))throw new Error("Invalid token format: token must be a non-empty string");return e.replace(/\|/g,"$")}function po(e){return zr(e,"$","dollar-delimited token")}class fo extends Qn{constructor(e=!1){super(e)}generateStringsInstructions(e){try{this.logger.debug("🔧 Generating stringsInstructions for:",e);const t=this.extractTokenSymbolFromVault(e),n=this.createTokenInstance(t),a=this.createGalaInstance(),s=`$service$${n.toStringKey()}$launchpad`,r=`$tokenBalance$${n.toStringKey()}$${e}`,i=`$tokenBalance$${n.toStringKey()}$${e}`,o=`$tokenBalance$${a.toStringKey()}$${e}`,c=[s,r,i,o,`$tokenBalance$${a.toStringKey()}$${e}`];return this.logger.debug("✅ Generated stringsInstructions:",c),c}catch(e){this.logger.error("❌ Failed to generate stringsInstructions:",e);const t=st(e);throw new kt(`Failed to generate stringsInstructions: ${t}`,"vaultAddress","INVALID_VAULT_ADDRESS")}}createTokenInstance(e){const t=new c.TokenClassKey;return t.collection=e.toLowerCase(),t.category="Unit",t.type="none",t.additionalKey="none",this.logger.debug("🪙 Created token instance:",{symbol:e,lowercaseCollection:e.toLowerCase(),stringKey:t.toStringKey()}),t}createGalaInstance(){const e=new c.TokenClassKey;return e.collection="GALA",e.category="Unit",e.type="none",e.additionalKey="none",this.logger.debug("🟡 Created GALA instance:",{stringKey:e.toStringKey()}),e}extractTokenSymbolFromVault(e){if(!Un(e))throw Tt("vaultAddress","Vault address");try{const t=Gi(e);return this.logger.debug("🔍 Extracted token symbol:",{vaultAddress:e,tokenSymbol:t}),t}catch(e){if(e instanceof kt)throw Ct("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad");throw e}}validateVaultAddress(e){if(!Un(e))throw Tt("vaultAddress","Vault address");if(!e.startsWith("service|Token$Unit$"))throw Ct("vaultAddress",'starting with "service|Token$Unit$"');if(!e.endsWith("$launchpad"))throw Ct("vaultAddress",'ending with "$launchpad"');const t=function(e){if(!Un(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],a=t[2];return void 0===n||void 0===a?null:{tokenSymbol:n,creatorAddress:a.toLowerCase()}}(e);if(!t)throw Ct("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 Ct("vaultAddress","containing a 1-10 letter token symbol (case insensitive)");return this.logger.debug("✅ Vault address validation passed:",e),!0}generateTokenClassKeyString(e,t,n,a){return`${e}$${t}$${n}$${a}`}parseTokenClassKeyString(e){try{return po(e)}catch(e){if(e instanceof kt)throw Ct("stringKey","format: collection$category$type$additionalKey (4 parts)");throw e}}}function yo(e){return"object"==typeof e&&null!==e?e:void 0}class vo extends Xn{constructor(e,t,n=!1,a,s,r=.05,i=.01){if(super(e,n),this.tokenResolver=t,this._walletProvider=a,this.userAddress=s,this.defaultSlippageToleranceFactor=r,this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor=i,this.bundleEndpoint="/bundle",null!==this._walletProvider&&void 0!==this._walletProvider&&null!=s){const e=yo(this._walletProvider),t=e?.privateKey;"string"==typeof t?this.signer=new uo(t):function(e){const t=yo(e);return"function"==typeof t?.request}(this._walletProvider)&&void 0!==this.userAddress&&(this.signer=new go(this._walletProvider,this.userAddress)),this.tokenKeyService=new fo(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 Gt(()=>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:Pt(n),error:n.error}),this.handleBundleResponse(n))}catch(e){if(e instanceof kt)return{success:!1,error:st(e)};throw e}}validateBundleData(e){if(null==e)throw Tt("bundleData","Bundle data");if(null===e.signedDto||void 0===e.signedDto)throw Tt("signedDto","Signed DTO");if(!Un(e.method))throw Tt("method","Method name");if(!Array.isArray(e.stringsInstructions))throw Ct("stringsInstructions","an array of resource tracking strings");if(0===e.stringsInstructions.length)throw new kt("stringsInstructions cannot be empty","stringsInstructions","EMPTY_ARRAY");const t=["BuyWithNative","BuyExactToken","SellExactToken","SellWithNative"];if(!t.includes(e.method))throw Ct("method",`one of: ${t.join(", ")}`);e.stringsInstructions.forEach((e,t)=>{if(!Un(e))throw new kt(`stringsInstructions[${t}] must be a non-empty string`,`stringsInstructions[${t}]`,"INVALID_INSTRUCTION");if(!Vr(e))throw new kt(`stringsInstructions[${t}] must start with '$': ${e}`,`stringsInstructions[${t}]`,"INVALID_INSTRUCTION_FORMAT")}),this.logger.debug("✅ Bundle data validation passed")}formatBundleRequest(e){return{signedDto:e.signedDto,stringsInstructions:e.stringsInstructions,method:e.method}}handleBundleResponse(e){const t=Lt(e);if(null!=t&&!1===e.error)return this.logger.debug("✅ Bundle transaction successful:",t),{success:!0,data:t};const n=("string"==typeof e.error?e.error:e.message)??"Bundle transaction failed";return this.logger.debug("❌ Bundle transaction failed:",n),{success:!1,error:n}}formatErrorMessage(e){if("string"==typeof e)return e;if(ot(e)&&null!==e.response&&void 0!==e.response){const t=Lt(e.response);if(null!=t&&"object"==typeof t){const e=t;if(null!==e.error&&void 0!==e.error)return"string"==typeof e.error?e.error:JSON.stringify(e.error);if(null!==e.message&&void 0!==e.message)return"string"==typeof e.message?e.message:JSON.stringify(e.message)}}return st(e)??"Unknown bundle transaction error"}async getBundlerTransactionResult(e){try{if(!Un(e))throw Tt("transactionId","Transaction ID");let t;this.logger.debug("🔍 Checking bundler transaction result:",e);try{t=await Gt(()=>this.http.get(`${this.bundleEndpoint}?id=${e}`),{errorContext:"Failed to get bundler transaction result",logger:this.logger})}catch(e){return{success:!1,error:this.formatErrorMessage(e)}}return null==t?{success:!1,error:"No response from bundler transaction query"}:(this.logger.debug("📊 Bundler transaction result:",t),{success:!0,data:t})}catch(e){if(e instanceof kt)return{success:!1,error:st(e)};throw e}}async cancelTransaction(e){try{if(!Un(e))throw Tt("transactionId","Transaction ID");let t;this.logger.debug("🚫 Cancelling transaction:",e);try{t=await Gt(()=>this.http.delete(`${this.bundleEndpoint}/${e}`),{errorContext:"Failed to cancel transaction",logger:this.logger})}catch(e){return{success:!1,error:this.formatErrorMessage(e)}}return null==t?{success:!1,error:"No response from transaction cancellation"}:(this.logger.debug("🗑️ Transaction cancellation response:",t),{success:!0,data:t})}catch(e){if(e instanceof kt)return{success:!1,error:st(e)};throw e}}async getHealthStatus(){this.logger.debug("🏥 Checking bundle service health");try{const e=await Gt(()=>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:a,expectedAmount:s}=e,{effectiveSlippageFactor:r,effectiveMaxFee:i,vaultAddress:o}=await this.prepareTradingOperation(t,e.maxAcceptableReverseBondingCurveFee,e.maxAcceptableReverseBondingCurveFeeSlippageFactor,e.slippageToleranceFactor);if("native"===a){if(null==s||""===s)throw new kt("expectedAmount is required for native buy operations. Use getBuyTokenAmount() first to calculate expected tokens.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=no(s,r,"buy-native");this.logger.debug("BuyNative slippage applied:",{originalExpectedTokens:s,slippageFactor:r,adjustedMinTokens:e});const t=new to.BuyNativeDto(o,n,e,{maxAcceptableReverseBondingCurveFee:i});return await this.executeBundleTransaction(t,"BuyWithNative",o)}{if(null==s||""===s)throw new kt("expectedAmount is required for exact buy operations. Use getBuyTokenAmount() first to calculate expected GALA cost.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=no(s,r,"buy-exact");this.logger.debug("BuyExact slippage applied:",{originalExpectedGalaCost:s,slippageFactor:r,adjustedMaxGalaCost:e});const t=new to.BuyExactDto(o,n,e,{maxAcceptableReverseBondingCurveFee:i});return await this.executeBundleTransaction(t,"BuyExactToken",o)}}async sellToken(e){this.ensureTradingServicesAvailable();const{tokenName:t,amount:n,type:a,expectedAmount:s}=e,{effectiveSlippageFactor:r,effectiveMaxFee:i,vaultAddress:o}=await this.prepareTradingOperation(t,e.maxAcceptableReverseBondingCurveFee,e.maxAcceptableReverseBondingCurveFeeSlippageFactor,e.slippageToleranceFactor);if("exact"===a){if(null==s||""===s)throw new kt("expectedAmount is required for exact sell operations. Use getSellTokenAmount() first to calculate expected GALA.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=no(s,r,"sell-exact");this.logger.debug("SellExact slippage applied:",{originalExpectedGala:s,slippageFactor:r,adjustedMinGala:e});const t=new to.SellExactDto(o,n,e,{maxAcceptableReverseBondingCurveFee:i});return await this.executeBundleTransaction(t,"SellExactToken",o)}{if(null==s||""===s)throw new kt("expectedAmount is required for native sell operations. Use getSellTokenAmount() first to calculate tokens to sell.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=no(s,r,"sell-native");this.logger.debug("SellNative slippage applied:",{originalExpectedTokensToSell:s,slippageFactor:r,adjustedMaxTokensToSell:e});const t=new to.SellNativeDto(o,n,e,{maxAcceptableReverseBondingCurveFee:i});return await this.executeBundleTransaction(t,"SellWithNative",o)}}async prepareTradingOperation(e,t,n,a){const{effectiveSlippageFactor:s,effectiveMaxFee:r}=this.calculateEffectiveSlippage(t,n,a),i=await this.resolveTokenNameToVault(e);if(null==i)throw Et(e);return{effectiveSlippageFactor:s,effectiveMaxFee:r,vaultAddress:i}}calculateEffectiveSlippage(e,t,n){const a=n??this.defaultSlippageToleranceFactor,s=t??this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor;let r=e??"0";return null!=e&&(r=no(e,s,"buy-exact"),this.logger.debug("Reverse bonding curve fee slippage applied:",{baseFee:e,slippageFactor:s,adjustedMaxFee:r})),{effectiveSlippageFactor:a,effectiveFeeSlippageFactor:s,effectiveMaxFee:r}}ensureTradingServicesAvailable(){if(!this.signer||!this.tokenKeyService)throw It("Trading services not available. BundleService requires walletProvider and userAddress for trading operations.","walletProvider");if(null===this.userAddress||void 0===this.userAddress)throw Tt("userAddress","User address")}async executeBundleTransaction(e,t,n){this.ensureTradingServicesAvailable();try{e.uniqueKey=ao("galaswap-operation");const a=await this.signer.signObject(t,e),s=this.tokenKeyService.generateStringsInstructions(n),r={stringsInstructions:s,method:t,signedDto:a};this.logger.debug("📦 Bundle transaction data:",{method:t,stringsInstructions:s,dtoKeys:Object.keys(a)});const i=await this.submitTransaction(r);if(i.success){const e=Lt(i);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=i.error;throw new St("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 ko extends Xn{constructor(e,t=!1){super(e,t)}extractData(e){if(e.error||void 0===e.data){const t=e.message??"Client config operation failed";throw new Error(t)}return e.data}async getClientFlags(){this.logger.debug("Fetching client feature flags");const e=await this.http.get(et),t=this.extractData(e);return this.logger.debug("Fetched client feature flags",{flagCount:Object.keys(t.flags).length}),{flags:t.flags}}}var bo,wo,So,Ao;!function(e){e.CHAT_MESSAGE="CHAT_MESSAGE",e.COMMENT="COMMENT",e.STREAM="STREAM",e.RECORDING="RECORDING"}(bo||(bo={})),function(e){e.INAPPROPRIATE_CONTENT="INAPPROPRIATE_CONTENT",e.SPAM="SPAM",e.HARASSMENT="HARASSMENT",e.SCAM="SCAM",e.OTHER="OTHER"}(wo||(wo={})),function(e){e.PENDING="PENDING",e.DISMISSED="DISMISSED",e.ACTIONED="ACTIONED"}(So||(So={})),function(e){e.DELETE_CONTENT="DELETE_CONTENT",e.BAN_USER="BAN_USER",e.DELETE_AND_BAN="DELETE_AND_BAN"}(Ao||(Ao={})),wo.INAPPROPRIATE_CONTENT,wo.SPAM,wo.HARASSMENT,wo.SCAM,wo.OTHER,So.PENDING,So.DISMISSED,So.ACTIONED,Ao.DELETE_CONTENT,Ao.BAN_USER,Ao.DELETE_AND_BAN,bo.CHAT_MESSAGE,bo.COMMENT,bo.STREAM,bo.RECORDING;const Eo=Ln(bo),To=Ln(wo),Co=Ln(So),No=Ln(Ao),Io={TOKEN_NAME:sn,CONTENT_ID:un.CONTENT_ID,DETAILS:un.FLAG_DETAILS,PAGINATION:{MAX_LIMIT:on}};function Do(e,t="tokenName"){Gn(e,t,Io.TOKEN_NAME)}function _o(e){if(void 0!==e.contentType&&!Eo(e.contentType))throw Ct("contentType",`one of: ${Object.values(bo).join(", ")}`,"Content type");if(void 0!==e.status&&!Co(e.status))throw Ct("status",`one of: ${Object.values(So).join(", ")}`);if(void 0!==e.reason&&!To(e.reason))throw Ct("reason",`one of: ${Object.values(wo).join(", ")}`);if(void 0!==e.reporterAddress&&!Un(e.reporterAddress))throw Ft("reporterAddress","a non-empty string",typeof e.reporterAddress);if(void 0!==e.reporterAddress&&oa(e.reporterAddress,"reporterAddress"),void 0!==e.reportedUserAddress&&!Un(e.reportedUserAddress))throw Ft("reportedUserAddress","a non-empty string",typeof e.reportedUserAddress);void 0!==e.reportedUserAddress&&oa(e.reportedUserAddress,"reportedUserAddress"),Mn(0,void 0,Io.PAGINATION.MAX_LIMIT,e.pageSize)}class Ro extends Ni{constructor(e,t,n,a=!1,s){super(e,t,n,a,s)}async createFlag(e){!function(e){if(Do(e.tokenName),void 0===e.contentType)throw Tt("contentType","Content type");if(!Eo(e.contentType))throw Ct("contentType",`one of: ${Object.values(bo).join(", ")}`,"Content type");if(!Un(e.contentId))throw Tt("contentId","Content ID");if(e.contentId.length>Io.CONTENT_ID.MAX_LENGTH)throw Ot("contentId",Io.CONTENT_ID.MAX_LENGTH,e.contentId.length,"Content ID");if(!Un(e.reportedUserAddress))throw Tt("reportedUserAddress","Reported user address");if(oa(e.reportedUserAddress,"reportedUserAddress"),!(e.contentType!==bo.STREAM&&e.contentType!==bo.RECORDING||void 0!==e.reason&&null!==e.reason))throw Tt("reason","Reason");if(void 0!==e.reason&&!To(e.reason))throw Ct("reason",`one of: ${Object.values(wo).join(", ")}`,"Reason");if(void 0!==e.details&&!Un(e.details))throw Ft("details","a non-empty string",typeof e.details);if(void 0!==e.details&&e.details.length>Io.DETAILS.MAX_LENGTH)throw Ot("details",Io.DETAILS.MAX_LENGTH,e.details.length)}(e);const t={tokenName:e.tokenName,contentType:e.contentType,contentId:e.contentId,reportedUserAddress:e.reportedUserAddress};null!==e.reason&&void 0!==e.reason&&(t.reason=e.reason),null!==e.details&&void 0!==e.details&&(t.details=e.details);const n=await this.http.post(ie.CREATE,t,this.getMultiAuthHeaders());return{flag:this.extractData(n).flag}}async listFlags(e){return function(e){Do(e.tokenName),_o(e)}(e),this.fetchFlagList(e)}async listGlobalFlags(e={}){return function(e){void 0!==e.tokenName&&Do(e.tokenName),_o(e)}(e),this.fetchFlagList(e)}async dismissFlag(e){!function(e){if(void 0===e.flagId||null===e.flagId)throw Tt("flagId","Flag ID");try{On(e.flagId,"flagId")}catch{throw Ct("flagId","a positive integer","Flag ID")}}(e);const t=ie.DISMISS.replace(":id",e.flagId.toString()),n=await this.http.post(t,{},this.getMultiAuthHeaders());return{flag:this.extractData(n).flag}}async actionFlag(e){!function(e){if(void 0===e.flagId||null===e.flagId)throw Tt("flagId","Flag ID");try{On(e.flagId,"flagId")}catch{throw Ct("flagId","a positive integer","Flag ID")}if(void 0===e.action)throw Tt("action","Action");if(!No(e.action))throw Ct("action",`one of: ${Object.values(Ao).join(", ")}`,"Action")}(e);const t=ie.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=Ei(e,on);Ti(t,e,["tokenName","contentType","status","reason","reporterAddress","reportedUserAddress"]);const n=await this.http.get(ie.LIST,t,this.getMultiAuthHeaders()),a=this.extractData(n);return{items:a.flags,pageInfo:a.pageInfo}}}const xo=["heart","fire","laugh","wow","thumbs_up"];class Oo extends Ni{constructor(e,t,n,a=!1,s){super(e,t,n,a,s)}validateReactionTokenName(e){this.validateTokenName(e,sn)}validateMessageId(e){if(!Un(e))throw Tt("messageId","Message ID");if(xn(e,hn.CONTENT_REACTION.MAX_LENGTH,"messageId"),!hn.CONTENT_REACTION.PATTERN.test(e))throw Ct("messageId","msg-{timestamp}-{uuid} or chat-{timestamp}-{uuid} format","Message ID")}validateReactionType(e){if(!Un(e))throw Tt("reactionType","Reaction type");if(!xo.includes(e))throw Ct("reactionType",`one of: ${xo.join(", ")}`,"Reaction type")}async addContentReaction(e){void 0!==e.tokenName&&this.validateReactionTokenName(e.tokenName),this.validateMessageId(e.messageId),this.validateReactionType(e.reactionType);const t=Oe,n={messageId:e.messageId,reactionType:e.reactionType};void 0!==e.tokenName&&(n.tokenName=zt(e.tokenName));const a=await this.http.post(t,n,this.getMultiAuthHeaders()),s=this.extractData(a),{created:r,...i}=s;return{data:i,created:r}}async removeContentReaction(e){void 0!==e.tokenName&&this.validateReactionTokenName(e.tokenName),this.validateMessageId(e.messageId),this.validateReactionType(e.reactionType);const t=`${Fe}?${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)}}class Fo extends Qn{constructor(e,t,n,a=!1){super(a),this.dexBackendHttp=e,this.cache=t,this.galaChainService=n}async fetchTokenPrice(e){const{tokenId:t}=e,{hasB:n}=Kn(e,"tokenName","tokenId",{description:"token identifier"});if(!0===n&&null!=t)return this.logger.debug(`Fetching spot price by tokenId: ${String(t)}`),this._fetchDexTokenSpotPrice(t);throw new kt("tokenName parameter requires LaunchpadSDK routing - call LaunchpadSDK.fetchTokenPrice({tokenName}) instead","tokenName","INVALID_PARAMS")}async _fetchDexTokenSpotPrice(e){if(null==e)throw Tt("tokenId","Token ID");try{const t=Li(e),n=Ms(t),a=mo(n);if(this.logger.debug(`Fetching DEX spot price for token: ${a}`),!this.dexBackendHttp)throw Nt("DEX Backend API client not configured");const s=await this.dexBackendHttp.request({method:"GET",url:"/market/price",params:{assetIds:a}}),r=null!==s&&"object"==typeof s?s:{},i=[t.type,t.collection].filter(e=>"string"==typeof e&&""!==e&&"none"!==e).map(e=>e.toUpperCase()).map(e=>r[e]).find(e=>void 0!==e)??(1===Object.keys(r).length?Object.values(r)[0]:void 0),o=i?.price;if("number"!=typeof o||!Number.isFinite(o))throw new kt(`Invalid price response: no market price for ${a}`,"data","INVALID_RESPONSE");const c=n;let l;try{if(null!==this.cache&&void 0!==this.cache){const e=this.cache.getByTokenId(c);if(null!=e?.symbol)return l=e.symbol,this.logger.debug(`DEX spot price for ${l} (cached): $${o}`),{symbol:l,price:o}}this.logger.debug(`Symbol cache miss for ${c}, fetching from API`);l=(await this.fetchTokenDetails(e)).symbol,this.cache&&(this.cache.setByTokenId(c,{symbol:l}),this.logger.debug(`Cached symbol for ${c}: ${l}`)),this.logger.debug(`DEX spot price for ${l}: $${o}`)}catch(e){this.logger.debug(`Could not fetch token details for symbol, falling back to token format parsing: ${at(e)?e.message:String(e)}`),l=Vt("Token"===t.collection?t.type:t.collection),this.logger.debug(`DEX spot price for ${l} (fallback): $${o}`)}return{symbol:l,price:o}}catch(e){if(e instanceof kt)throw e;throw Nt(`Failed to fetch DEX spot price: ${st(e)}`)}}async fetchLaunchpadTokenSpotPrice(e,t,n){if(!Un(e))throw new kt(ut,"tokenName",gt);try{if(null!=n)try{this.logger.debug(`Checking graduation status for token: ${e}`);const t=await n(e);if(!0===t?.isGraduated){this.logger.debug(`Token ${e} is graduated, using DEX spot price`);const n=Ms(t.sellingToken);return this._fetchDexTokenSpotPrice(n)}}catch(t){this.logger.debug(`Could not determine graduation status for ${e}, falling back to bonding curve: ${st(t)}`)}this.logger.debug(`Using bonding curve calculation for token: ${e}`);const a=await t({tokenName:e,amount:"1",type:"native"}),s=await this._fetchDexTokenSpotPrice({collection:"GALA",category:"Unit",type:"none",additionalKey:"none"});if(null==s)throw Nt("GALA price not available");const r=An(a.amount,0)/1e18;if(r<=0)throw new kt(`Invalid token amount calculation: ${r}`,"amount","INVALID_CALCULATION");const i=s.price/r;return{symbol:Vt(e),price:i}}catch(t){if(at(t))throw Nt(`Failed to calculate launchpad token spot price for ${e}: ${st(t)}`);throw Nt(`Failed to calculate launchpad token spot price for ${e}: ${st(t)}`)}}async fetchTokenDetails(e){this.logger.debug("Fetching token details from GalaChain for tokenId:",e);try{if(!this.galaChainService)throw Nt("GalaChainService not available for token metadata fetch",500);const t=await this.galaChainService.fetchTokenClassFromChain(e),n={collection:t.collection,category:t.category,type:t.type,additionalKey:t.additionalKey,symbol:t.symbol,decimals:t.decimals,name:t.name,image:t.image,description:t.description,network:t.network,...void 0!==t.contractAddress&&{contractAddress:t.contractAddress}};return this.logger.debug(`Fetched token details for ${t.symbol} from GalaChain`),n}catch(t){if((t instanceof kt||at(t))&&("NetworkError"===t.name||st(t).includes("Token not found")))throw t;throw Nt(`Failed to fetch token details from GalaChain for ${String(e)}: ${st(t)}`,500)}}async fetchAllDexSeasons(){try{if(!this.dexBackendHttp)throw Nt("DEX Backend API client not configured");const e=await this.dexBackendHttp.request({method:"GET",url:"/leaderboard/seasons"});let t;if(Array.isArray(e))t=e;else{if(null==e||"object"!=typeof e)return this.logger.warn("Seasons endpoint returned invalid data:",e),[];{const n=Lt(e);if(Array.isArray(n))t=n;else if(null!=n&&"object"==typeof n&&Array.isArray(n.seasons))t=n.seasons;else{if(!Array.isArray(e.seasons))return this.logger.warn("Seasons endpoint returned unexpected structure:",e),[];t=e.seasons}}}const n=t.map(e=>{const t=e;return{id:t?.id??0,name:t?.name??"",start:en(t?.start??null),end:en(t?.end??null),rulesId:t?.rules_id??0}});return this.logger.debug(`Fetched ${n.length} DEX seasons`),n}catch(e){if(at(e)&&st(e).includes("not configured"))throw e;if(ot(e)&&404===e.response?.status)return this.logger.warn("Seasons endpoint not available"),[];throw Nt(`Failed to fetch DEX seasons: ${st(e)}`)}}async fetchCurrentDexSeason(){const e=await this.fetchAllDexSeasons(),t=new Date,n=e.find(e=>t>=e.start&&t<=e.end);return n?this.logger.debug(`Current DEX season: ${n.name} (ID: ${n.id})`):this.logger.debug("No active DEX season found"),n??null}async fetchDexLeaderboardBySeasonId(e){try{On(e,"seasonId")}catch{throw Tt("seasonId","Season ID must be a positive number")}try{if(!this.dexBackendHttp)throw Nt("DEX Backend API client not configured");const t=await this.dexBackendHttp.request({method:"GET",url:"/leaderboard",params:{seasonId:e.toString()}});let n;if(Array.isArray(t))n=t;else{if(null==t||"object"!=typeof t)return this.logger.warn("Leaderboard endpoint returned invalid data:",t),{entries:[],seasonId:e,totalEntries:0};{const a=Lt(t);if(null!=a&&"object"==typeof a&&Array.isArray(a.leaderboard))n=a.leaderboard;else if(Array.isArray(t.leaderboard))n=t.leaderboard;else{if(!Array.isArray(a))return this.logger.warn("Leaderboard endpoint returned unexpected structure:",t),{entries:[],seasonId:e,totalEntries:0};n=a}}}const a=n.map(e=>{const t=e,n=t?.mastery_titles??[];return{wallet:t?.wallet??"",rank:t?.rank??0,totalXp:String(t?.total_xp??0),distributionPercent:String(t?.distribution_percent??0),liquidityXp:String(t?.liquidity_xp??0),tradingXp:String(t?.trading_xp??0),masteryTitles:n.map(e=>{const t=e;return{name:t?.name??"",type:t?.type??"trade",order:t?.order??0}})}});return this.logger.debug(`Fetched leaderboard for season ${e} with ${a.length} entries`),{entries:a,seasonId:e,totalEntries:a.length}}catch(t){if(at(t)&&st(t).includes("must be a positive number"))throw t;throw Nt(`Failed to fetch DEX leaderboard for season ${e}: ${st(t)}`)}}async fetchCurrentDexLeaderboard(){const e=await this.fetchCurrentDexSeason();return e?this.fetchDexLeaderboardBySeasonId(e.id):(this.logger.debug("Cannot fetch current leaderboard - no active season"),null)}async fetchDexAggregatedVolumeSummary(){try{if(!this.dexBackendHttp)throw Nt("DEX Backend API client not configured");const e=Lt(await this.dexBackendHttp.request({method:"GET",url:"/v2/trade/volume"}));if(!e)throw Nt("No data in DEX volume response",500);const t={volume1d:e.volume1d,volume1dDelta:e.volume1dDelta,volume7d:e.volume7d,volume7dDelta:e.volume7dDelta,volume30d:e.volume30d,volume30dDelta:e.volume30dDelta};return this.logger.debug(`Fetched DEX volume summary: $${t.volume1d.toFixed(2)} (1d)`),t}catch(e){throw Nt(`Failed to fetch DEX volume summary: ${st(e)}`)}}}const Bo=20,Uo=3e3,Po=1e3,Mo=!0,Lo=!0,$o=!1;class Ko{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 Qt({debug:t.debug??!1,context:"EventsBatcherService"}),this.config={batchSize:t.batchSize??Bo,flushIntervalMs:t.flushIntervalMs??Uo,maxQueueSize:t.maxQueueSize??Po,flushOnPageHide:t.flushOnPageHide??Mo,flushOnPageUnload:t.flushOnPageUnload??Lo,debug:t.debug??$o},this.setupPageLifecycleListeners()}track(e,t,n){if(this.isShuttingDown)return void this.logger.warn("EventsBatcher is shutting down, ignoring track call");const a={eventType:e,payload:t,clientTimestamp:(new Date).toISOString(),...void 0!==n?.userAddress&&""!==n.userAddress&&{userAddress:n.userAddress},...void 0!==n?.tokenName&&""!==n.tokenName&&{tokenName:n.tokenName},...void 0!==n?.sessionId&&""!==n.sessionId&&{sessionId:n.sessionId}};this.buffer(a),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??""}}function Go(e){return 0===(e?.length??0)?"0":e.reduce((e,t)=>d(e).plus(t.quantity).toString(),"0")}function Wo(e,t){if(0===(e?.length??0))return[];if(t)return e;const n=Date.now();return e.filter(e=>0===e.expires||e.expires>n)}class Ho extends Xn{constructor(e,t=!1){super(e,t)}getChannelForCollection(e){return"MUSIC"===(Vr(e)?e.slice(1).toUpperCase():e.toUpperCase())?"music":"asset"}async fetchGalaBalance(e){return this.fetchTokenBalance(e)}async fetchTokenBalance(e,t=!1){try{const n=`/api/${this.getChannelForCollection(e.collection)}/token-contract/FetchBalances`,a=await this.http.post(n,e);if(null==a)return null;try{ct(a,"Fetch balances")}catch{return null}if(0===(a.Data?.length??0))return null;const s=a.Data.find(t=>t.collection===e.collection&&t.category===e.category&&t.additionalKey===e.additionalKey&&t.type===e.type);if(!s||"0"===s.quantity)return null;const r=Ms(s),i={quantity:s.quantity,collection:s.collection,category:s.category,tokenId:r};if((s.inUseHolds?.length??0)>0){const e=Wo(s.inUseHolds??[],t);e.length>0&&(i.inUseHolds=e,i.inUseQuantity=Go(e))}if((s.lockedHolds?.length??0)>0){const e=Wo(s.lockedHolds??[],t);e.length>0&&(i.lockedHolds=e,i.lockedQuantity=Go(e))}return void 0===i.lockedQuantity&&void 0===i.inUseQuantity||(i.availableQuantity=function(e,t="0",n="0"){return d(e).minus(t).minus(n).toString()}(i.quantity,i.lockedQuantity,i.inUseQuantity)),i}catch(e){throw Nt(`Failed to fetch token balance from GalaChain: ${st(e)}`,void 0,at(e)?e:void 0)}}}function qo(e){return"string"==typeof e?{...po(e),instance:"0"}:{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey,instance:"0"}}function zo(e){return Ls(e)}function jo(e){const t=e[0];return void 0===t?void 0:zo(t.tokenInstanceKey)}class Vo extends c.ChainCallDTO{constructor(e){super(),this.lockAuthority=e.lockAuthority,this.tokenInstances=e.tokenInstances,this.uniqueKey=e.uniqueKey,void 0!==e.expires&&(this.expires=e.expires),void 0!==e.name&&(this.name=e.name),void 0!==e.signedPayload&&(this.signature=e.signedPayload.signature)}static fromTokenClassKey(e,t,n,a,s){const r=qo(a);return new Vo({lockAuthority:t??e,tokenInstances:[{owner:e,quantity:n,tokenInstanceKey:r}],...void 0!==s?.expires&&{expires:s.expires},...void 0!==s?.name&&{name:s.name},uniqueKey:s?.uniqueKey??so()})}static forGALA(e,t,n,a){return new Vo({lockAuthority:t??e,tokenInstances:[{owner:e,quantity:n,tokenInstanceKey:{collection:"GALA",category:"Unit",type:"none",additionalKey:"none",instance:"0"}}],...void 0!==a?.expires&&{expires:a.expires},...void 0!==a?.name&&{name:a.name},uniqueKey:a?.uniqueKey??so()})}getTokenClassKey(){return jo(this.tokenInstances)}toSigningPayload(){return{lockAuthority:this.lockAuthority,tokenInstances:this.tokenInstances,...void 0!==this.expires&&{expires:this.expires},...void 0!==this.name&&{name:this.name},uniqueKey:this.uniqueKey}}}class Xo extends c.ChainCallDTO{constructor(e){super(),this.tokenInstances=e.tokenInstances,this.uniqueKey=e.uniqueKey,void 0!==e.name&&(this.name=e.name),e.signedPayload&&(this.signature=e.signedPayload.signature)}static fromTokenClassKey(e,t,n,a){const s=qo(n);return new Xo({tokenInstances:[{owner:e,quantity:t,tokenInstanceKey:s}],...void 0!==a?.name&&{name:a.name},uniqueKey:a?.uniqueKey??so()})}static forGALA(e,t,n){return new Xo({tokenInstances:[{owner:e,quantity:t,tokenInstanceKey:{collection:"GALA",category:"Unit",type:"none",additionalKey:"none",instance:"0"}}],...void 0!==n?.name&&{name:n.name},uniqueKey:n?.uniqueKey??so()})}getTokenClassKey(){return jo(this.tokenInstances)}toSigningPayload(){return{tokenInstances:this.tokenInstances,...void 0!==this.name&&{name:this.name},uniqueKey:this.uniqueKey}}}function Qo(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Un(t.amount)&&(void 0!==t.tokenId||Un(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 Jo(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Un(t.amount)&&(void 0!==t.tokenId||Un(t.tokenName))&&(void 0===t.name||"string"==typeof t.name)}var Yo,Zo;!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"}(Yo||(Yo={}));class ec extends Error{constructor(e,t,n){super(e),this.type=t,this.details=n,this.name="LockError"}}!function(e){e.INVALID_RECIPIENT="INVALID_RECIPIENT",e.INVALID_AMOUNT="INVALID_AMOUNT",e.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",e.TOKEN_NOT_FOUND="TOKEN_NOT_FOUND",e.SIGNATURE_FAILED="SIGNATURE_FAILED",e.NETWORK_ERROR="NETWORK_ERROR",e.DUPLICATE_TRANSFER="DUPLICATE_TRANSFER",e.TRANSFER_LIMIT_EXCEEDED="TRANSFER_LIMIT_EXCEEDED",e.WALLET_REQUIRED="WALLET_REQUIRED"}(Zo||(Zo={}));class tc extends Error{constructor(e,t,n){super(e),this.type=t,this.details=n,this.name="TransferError"}}function nc(e){const t=e?.tokens?.[0];if(void 0===t)return;const n={};return void 0!==t.tokenName&&(n.tokenName=t.tokenName),void 0!==t.amount&&(n.amount=t.amount),Object.keys(n).length>0?n:void 0}async function ac(e,t,n,a="[DEBUG] Token resolution (launchpad)"){const s=await t.resolveTokenToVault(e);if(null!==s){const t=Ki(s);return n.debug(a,{tokenName:e,vaultAddress:s,tokenInstance:{collection:t.collection,category:t.category,type:t.type,instance:t.instance}}),t}const r={collection:jt(e),category:"Unit",type:"none",additionalKey:"none",instance:"0"};return n.debug("[DEBUG] Token resolution (standard format)",{tokenName:e,tokenInstance:{collection:r.collection,category:r.category,type:r.type}}),r}const sc=100,rc=100;class ic extends Xn{constructor(e,t,n,a=!1){super(e,a),this.wallet=t,this.tokenResolver=n,this.nativeSigner=t?new uo(t.privateKey):void 0}async lockTokens(e){if(this.validateLockTokensData(e),!this.wallet||!this.nativeSigner)throw new ec("Wallet required for token lock operations",Yo.WALLET_REQUIRED);return _s(async()=>{const{ownerAddress:t,tokenInstances:n}=this.createTokenOperationContext(),a=[];let s=t;const r=e.tokens.find(e=>void 0!==e.lockAuthority);void 0!==r?.lockAuthority&&(s=sa(r.lockAuthority));const i=e.tokens.find(e=>void 0!==e.expires),o=e.tokens.find(e=>void 0!==e.name);for(const r of e.tokens){const e=await this.resolveTokenEntry(r);n.push({owner:t,quantity:r.amount,tokenInstanceKey:e}),a.push({tokenClassKey:{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey},quantity:r.amount,lockAuthority:void 0!==r.lockAuthority?sa(r.lockAuthority):s})}const c=new Vo({lockAuthority:s,tokenInstances:n,...void 0!==i?.expires&&{expires:i.expires},...void 0!==o?.name&&{name:o.name},uniqueKey:e.uniqueKey??so()}),l=await this.nativeSigner.signObject("LockToken",c.toSigningPayload()),d=new Vo({...c.toSigningPayload(),signedPayload:l}),u=await this.http.post("/api/asset/token-contract/LockToken",d);try{ct(u,"Token lock failed")}catch(e){const t=lt(u);throw new ec(`${st(e)}${t}`,Yo.NETWORK_ERROR)}return this.extractLockResult(u,a)},"Token lock failed",this.logger,t=>{throw this.handleLockError(t,"Token lock failed",e)})}async unlockTokens(e){if(this.validateUnlockTokensData(e),!this.wallet||!this.nativeSigner)throw new ec("Wallet required for token unlock operations",Yo.WALLET_REQUIRED);return _s(async()=>{const{ownerAddress:t,tokenInstances:n}=this.createTokenOperationContext(),a=[],s=e.tokens.find(e=>void 0!==e.name);for(const s of e.tokens){const e=await this.resolveTokenEntry(s);n.push({owner:t,quantity:s.amount,tokenInstanceKey:e}),a.push({tokenClassKey:{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey},quantity:s.amount})}const r=new Xo({tokenInstances:n,...void 0!==s?.name&&{name:s.name},uniqueKey:e.uniqueKey??so()}),i=await this.nativeSigner.signObject("UnlockToken",r.toSigningPayload()),o=new Xo({...r.toSigningPayload(),signedPayload:i}),c=await this.http.post("/api/asset/token-contract/UnlockToken",o);try{ct(c,"Token unlock failed")}catch(e){const t=lt(c);throw new ec(`${st(e)}${t}`,Yo.NETWORK_ERROR)}return this.extractUnlockResult(c,a)},"Token unlock failed",this.logger,t=>{throw this.handleLockError(t,"Token unlock failed",e)})}validateSharedTokenEntry(e,t,n){if(void 0===e.tokenId&&void 0===e.tokenName)throw new ec("Must provide either tokenId or tokenName for token identification",Yo.TOKEN_NOT_FOUND);if(void 0!==e.tokenName)try{Wn(e.tokenName,"tokenName")}catch{throw new ec("Invalid token name format",Yo.TOKEN_NOT_FOUND,{tokenName:e.tokenName})}try{is(ns(e.amount))}catch{throw new ec(Ct(t,"a positive number",n).message,Yo.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(Qo)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}(e))throw new ec("Invalid lock data: missing required fields",Yo.VALIDATION_ERROR);if(e.tokens.length>sc)throw new ec(`Batch size exceeds maximum limit of ${sc} tokens per lock operation`,Yo.VALIDATION_ERROR);for(const t of e.tokens){if(this.validateSharedTokenEntry(t,"lockAmount","Lock amount"),void 0!==t.lockAuthority&&!ia(t.lockAuthority))throw new ec("Invalid lock authority address format",Yo.VALIDATION_ERROR,{lockAuthority:t.lockAuthority});if(void 0!==t.expires)try{On(t.expires,"expires")}catch{throw new ec(Ct("expires","a positive integer (epoch milliseconds)","Expires").message,Yo.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(Jo)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}(e))throw new ec("Invalid unlock data: missing required fields",Yo.VALIDATION_ERROR);if(e.tokens.length>rc)throw new ec(`Batch size exceeds maximum limit of ${rc} tokens per unlock operation`,Yo.VALIDATION_ERROR);for(const t of e.tokens)this.validateSharedTokenEntry(t,"unlockAmount","Unlock amount")}extractLockResult(e,t){let n;if(void 0!==e.Data&&e.Data.length>0){const a=e.Data[0];if(void 0===a)return{locked:t};n=a.transactionId??a.txnId??a.TxnId??a.id??void 0}return{...void 0!==n&&{transactionId:n},locked:t}}extractUnlockResult(e,t){let n;if(void 0!==e.Data&&e.Data.length>0){const a=e.Data[0];if(void 0===a)return{unlocked:t};n=a.transactionId??a.txnId??a.TxnId??a.id??void 0}return{...void 0!==n&&{transactionId:n},unlocked:t}}handleLockError(e,t,n){if(e instanceof ec)return e;let a=t,s=Yo.NETWORK_ERROR;if(ot(e)){const n=e.response?.data;if("object"==typeof n&&null!==n){const e=n.Message;"string"==typeof e&&e.length>0&&(a=`${t}: ${e}`);const r="string"==typeof e?e.toLowerCase():"";r.includes("insufficient")||r.includes("balance")?s=Yo.INSUFFICIENT_BALANCE:r.includes("lock")&&r.includes("not found")?s=Yo.LOCK_NOT_FOUND:r.includes("not found")||r.includes("token")?s=Yo.TOKEN_NOT_FOUND:r.includes("authority")?s=Yo.NOT_LOCK_AUTHORITY:r.includes("expired")&&(s=Yo.LOCK_EXPIRED)}}else at(e)&&(a=`${t}: ${st(e)}`);return new ec(a,s,nc(n))}async resolveTokenInstance(e){return _s(async()=>ac(e,this.tokenResolver,this.logger),`Failed to resolve token '${e}'`,this.logger,t=>{if(t instanceof tc)throw new ec(st(t),Yo.TOKEN_NOT_FOUND);throw new ec(`Failed to resolve token '${e}': ${st(t)}`,Yo.TOKEN_NOT_FOUND,{tokenName:e})})}async resolveTokenEntry(e){if(void 0!==e.tokenId){const t=Li(e.tokenId);return this.logger.debug("[DEBUG] Using provided tokenId:",e.tokenId),t}if(void 0!==e.tokenName)return this.resolveTokenInstance(e.tokenName);throw new ec("Must provide either tokenId or tokenName for token identification",Yo.TOKEN_NOT_FOUND)}createTokenOperationContext(){return{ownerAddress:sa(this.wallet.address),tokenInstances:[]}}}class oc extends Xn{constructor(e,t=!1,n){super(e,t),this.publicAxios=n}async fetchTokenClassFromChain(e){try{const t="string"==typeof e?Li(e):e,n={tokenClasses:[{collection:t.collection,category:t.category,type:t.type,additionalKey:t.additionalKey}]};if(!this.publicAxios)throw Tt("publicAxios","Public Axios instance");const a=(await this.publicAxios.post("/api/asset/token-contract/FetchTokenClasses",n)).data;if(ct(a,"Failed to fetch token class from GalaChain"),null===a.Data||void 0===a.Data||0===a.Data.length)throw Nt(`Token not found on GalaChain: ${Ms(t)}`,404);const s=a.Data[0];if(void 0===s)throw Nt(`Token not found on GalaChain: ${Ms(t)}`,404);return s}catch(e){return this.handleTokenServiceError(e,"Token not found on GalaChain","Failed to fetch token class from GalaChain")}}async fetchTokenClassesWithSupply(e){try{if(null==e||0===e.length)throw Tt("tokenClasses","Token classes array");const t={tokenClasses:e};if(!this.publicAxios)throw Tt("publicAxios","Public Axios instance");const n=(await this.publicAxios.post("/api/asset/token-contract/FetchTokenClassesWithSupply",t)).data;if(ct(n,"Failed to fetch token classes with supply from GalaChain"),!n.Data||0===n.Data.length)throw Nt("No token supply data found for requested token classes",404);return n.Data}catch(e){return this.handleTokenServiceError(e,"Token supply data not found on GalaChain","Failed to fetch token classes with supply from GalaChain")}}handleTokenServiceError(e,t,n){if(e instanceof kt)throw e;if(ot(e)&&404===e.response?.status)throw Nt(t,404,at(e)?e:void 0);if(at(e)&&"Error"===e.name&&st(e).includes("status indicates failure"))throw Nt(st(e),400,at(e)?e:void 0);const a=st(e);if(a.includes("Token not found")){if(e instanceof Error)throw e;throw new Error(a)}throw Nt(`${n}: ${a}`,void 0,at(e)?e:void 0)}}class cc extends c.ChainCallDTO{constructor(e){super(),this.tokenInstances=e.tokenInstances,this.uniqueKey=e.uniqueKey,e.signedPayload&&(this.signature=e.signedPayload.signature)}static fromTokens(e,t){const n=e.map(e=>{const t=qo(e.tokenClassKey);return{quantity:e.quantity,tokenInstanceKey:t}});return new cc({tokenInstances:n,uniqueKey:t?.uniqueKey??so()})}static fromTokenClassKey(e,t,n){return cc.fromTokens([{tokenClassKey:t,quantity:e}],n)}static forGALA(e,t){return new cc({tokenInstances:[{quantity:e,tokenInstanceKey:{collection:"GALA",category:"Unit",type:"none",additionalKey:"none",instance:"0"}}],uniqueKey:t?.uniqueKey??so()})}getTokenClassKey(){if(0===this.tokenInstances.length)return;const e=this.tokenInstances[0];return void 0!==e?zo(e.tokenInstanceKey):void 0}toSigningPayload(){return{tokenInstances:this.tokenInstances,uniqueKey:this.uniqueKey}}}class lc extends c.ChainCallDTO{constructor(e){super(),this.from=e.from,this.to=e.to,this.quantity=e.quantity,this.tokenInstance=e.tokenInstance,this.uniqueKey=e.uniqueKey,e.signedPayload&&(this.signature=e.signedPayload.signature)}static fromTokenClassKey(e,t,n,a,s){let r;if("string"==typeof a){r={...po(a),instance:"0"}}else r={collection:a.collection,category:a.category,type:a.type,additionalKey:a.additionalKey,instance:"0"};return new lc({from:e,to:t,quantity:n,tokenInstance:r,uniqueKey:s??so()})}static forGALA(e,t,n,a){return new lc({from:e,to:t,quantity:n,tokenInstance:{collection:"GALA",category:"Unit",type:"none",additionalKey:"none",instance:"0"},uniqueKey:a??so()})}getTokenClassKey(){return Ls(this.tokenInstance)}toSigningPayload(){return{from:this.from,to:this.to,quantity:this.quantity,tokenInstance:this.tokenInstance,uniqueKey:this.uniqueKey}}}function dc(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Un(t.amount)&&(void 0!==t.tokenId||Un(t.tokenName))}var uc;!function(e){e.TOKEN_NOT_FOUND="TOKEN_NOT_FOUND",e.INVALID_AMOUNT="INVALID_AMOUNT",e.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",e.SIGNATURE_FAILED="SIGNATURE_FAILED",e.NETWORK_ERROR="NETWORK_ERROR",e.WALLET_REQUIRED="WALLET_REQUIRED",e.VALIDATION_ERROR="VALIDATION_ERROR"}(uc||(uc={}));class hc extends Error{constructor(e,t,n){super(e),this.type=t,this.details=n,this.name="BurnError"}}const gc={validateAmount(e){const t=ns(e);try{!function(e,t){if(e.isNaN())throw Bt(t,"NaN");if(!e.isFinite())throw Ot(t,"finite");if(e.isLessThanOrEqualTo(0))throw xt(t,"0",e.toString())}(t,"amount")}catch(t){throw new tc(t.message,Zo.INVALID_AMOUNT,{amount:e})}},validateUniqueKey(e){if(!Pn(e)&&Un(e)){if(e.length>pn.MAX_LENGTH)throw new kt(`Unique key too long. Maximum length: ${pn.MAX_LENGTH}`);if(!pn.PATTERN.test(e))throw new tc('Invalid unique key format. Must start with "galaswap-operation-" or "galaconnect-operation-"',Zo.INVALID_AMOUNT,{uniqueKey:e})}}},mc="gala-transfer-successful",pc="token-transfer-successful",fc="token-locked-successfully",yc="token-unlocked-successfully",vc="transfer-successful-no-id",kc=50;class bc extends Xn{constructor(e,t,n,a=!1){super(e,a),this.wallet=t,this.tokenResolver=n,this.nativeSigner=t?new uo(t.privateKey):void 0}async transferGala(e){if(this.validateTransferGalaData(e),!this.wallet||!this.nativeSigner)throw new tc("Wallet required for GALA transfer operations",Zo.WALLET_REQUIRED);try{const t=sa(e.recipientAddress),n=sa(this.wallet.address),a=lc.forGALA(n,t,e.amount,e.uniqueKey),s=await this.nativeSigner.signObject("TransferToken",a.toSigningPayload()),r=new lc({...a.toSigningPayload(),signedPayload:s}),{data:i,headers:o}=await this.http.postWithMeta("/api/asset/token-contract/TransferToken",r);if(null==i)throw new tc("No response from GalaChain transfer service",Zo.NETWORK_ERROR);return this.extractTransferResult(i,o,"gala")}catch(t){throw this.handleTransferError(t,"GALA transfer failed",e)}}async transferToken(e){if(this.validateTransferTokenData(e),!this.wallet||!this.nativeSigner)throw new tc("Wallet required for token transfer operations",Zo.WALLET_REQUIRED);try{const t=sa(e.to),n=sa(this.wallet.address);let a;if(null!==e.tokenId&&void 0!==e.tokenId)a=Li(e.tokenId),this.logger.debug("[DEBUG] Using provided tokenId:",e.tokenId),this.logger.debug("[DEBUG] Normalized Token Instance:",{collection:a.collection,category:a.category,type:a.type,instance:a.instance});else{if(null===e.tokenName||void 0===e.tokenName)throw new tc("Must provide either tokenId or tokenName for token identification",Zo.TOKEN_NOT_FOUND);a=await this.resolveTokenInstance(e.tokenName)}const s=new lc({from:n,to:t,quantity:e.amount,tokenInstance:a,uniqueKey:e.uniqueKey??so()}),r=await this.nativeSigner.signObject("TransferToken",s.toSigningPayload()),i=new lc({...s.toSigningPayload(),signedPayload:r}),{data:o,headers:c}=await this.http.postWithMeta("/api/asset/token-contract/TransferToken",i);if(null==o)throw new tc("No response from GalaChain transfer service",Zo.NETWORK_ERROR);return this.extractTransferResult(o,c,"token")}catch(t){throw this.handleTransferError(t,"Token transfer failed",e)}}async resolveTokenClassKey(e){try{const t=await this.tokenResolver.resolveTokenClassKey(e);return this.logger.debug(`[DEBUG] Token class key resolution for '${e}':`,{collection:t.collection,category:t.category,type:t.type}),t}catch(t){if(t instanceof tc)throw t;throw new tc(`Failed to resolve token class key for '${e}': ${st(t)}`,Zo.TOKEN_NOT_FOUND,{tokenName:e})}}async burnTokens(e){if(this.validateBurnTokensData(e),!this.wallet||!this.nativeSigner)throw new hc("Wallet required for token burn operations",uc.WALLET_REQUIRED);try{const t=[];for(const n of e.tokens){let e;if(null!==n.tokenId&&void 0!==n.tokenId)e=Li(n.tokenId),this.logger.debug("[DEBUG] Using provided tokenId:",n.tokenId);else{if(null===n.tokenName||void 0===n.tokenName)throw new hc("Must provide either tokenId or tokenName for token identification",uc.TOKEN_NOT_FOUND);e=await this.resolveTokenInstance(n.tokenName)}t.push({quantity:n.amount,tokenInstanceKey:e})}const n=new cc({tokenInstances:t,uniqueKey:e.uniqueKey??so()}),a=await this.nativeSigner.signObject("BurnTokens",n.toSigningPayload()),s=new cc({...n.toSigningPayload(),signedPayload:a}),r=await this.http.post("/api/asset/token-contract/BurnTokens",s);if(null==r)throw new hc("No response from GalaChain burn service",uc.NETWORK_ERROR);try{ct(r,"Token burn operation")}catch(e){throw new bt(st(e),500)}return this.extractBurnResult(r)}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 Un(t.recipientAddress)&&Un(t.amount)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)}(e))throw new kt("Invalid GALA transfer data: missing required fields");if(!ia(e.recipientAddress))throw new tc("Invalid recipient address format",Zo.INVALID_RECIPIENT,{recipientAddress:e.recipientAddress});gc.validateAmount(e.amount),gc.validateUniqueKey(e.uniqueKey)}validateTransferTokenData(e){if(!function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Un(t.to)&&Un(t.amount)&&(void 0!==t.tokenId||Un(t.tokenName))&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)}(e))throw new kt("Invalid token transfer data: missing required fields");if(!ia(e.to))throw new tc("Invalid recipient address format",Zo.INVALID_RECIPIENT,{recipientAddress:e.to});if(!(null!==e.tokenId&&void 0!==e.tokenId||null!==e.tokenName&&void 0!==e.tokenName))throw new tc("Must provide either tokenId or tokenName for token identification",Zo.TOKEN_NOT_FOUND);if(null!==e.tokenName&&void 0!==e.tokenName)try{Wn(e.tokenName,"tokenName")}catch{throw new tc("Invalid token name format",Zo.TOKEN_NOT_FOUND,{tokenName:e.tokenName})}gc.validateAmount(e.amount),gc.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(dc)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}(e))throw new hc("Invalid burn data: missing required fields",uc.VALIDATION_ERROR);if(e.tokens.length>kc)throw new hc(`Batch size exceeds maximum limit of ${kc} tokens per burn operation`,uc.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 hc("Must provide either tokenId or tokenName for token identification",uc.TOKEN_NOT_FOUND);const e=ns(t.amount);try{is(e)}catch{throw new hc("Burn amount must be a positive number",uc.INVALID_AMOUNT,{amount:t.amount})}}}async resolveTokenInstance(e){try{return await ac(e,this.tokenResolver,this.logger,`[DEBUG] Token resolution for '${e}' (launchpad):`)}catch(t){if(t instanceof tc)throw t;throw new tc(`Failed to resolve token '${e}': ${st(t)}`,Zo.TOKEN_NOT_FOUND,{tokenName:e})}}extractTransferResult(e,t,n){const a=this.readHeaderValue(t,"x-transaction-id"),s=this.readBlockNumberHeader(t),r=null!=e&&"object"==typeof e&&"Status"in e;r&&ct(e,"Extract transaction ID");const i=r&&"Data"in e;if(void 0!==a&&a.length>0)return{transactionId:a,...void 0!==s?{blockNumber:s}:{}};if(null!=e&&"object"==typeof e){if("transactionId"in e&&"string"==typeof e.transactionId&&e.transactionId.length>0)return{transactionId:e.transactionId,...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=vc;if(t.Data.length>0)switch(n){case"gala":e=mc;break;case"token":e=pc;break;case"lock":e=fc;break;case"unlock":e=yc}return{transactionId:e,...void 0!==s?{blockNumber:s}:{}}}}}throw new tc("Operation succeeded but transaction ID could not be extracted (missing x-transaction-id header and body fields)",Zo.NETWORK_ERROR)}readHeaderValue(e,t){const n=e[t.toLowerCase()];if("string"==typeof n&&n.trim().length>0)return n.trim()}readBlockNumberHeader(e){const t=this.readHeaderValue(e,"x-block-number");if(void 0===t)return;const n=Number.parseInt(t,10);return Number.isFinite(n)?n:void 0}extractBurnResult(e){const t=[];if(null!==e.Data&&void 0!==e.Data&&Array.isArray(e.Data))for(const n of e.Data)t.push({collection:n.collection??"",category:n.category??"",type:n.type??"",additionalKey:n.additionalKey??"",instance:n.instance??"0",quantity:n.quantity??"0",burnedBy:n.burnedBy??""});let n;if(null!==e.Data&&void 0!==e.Data&&e.Data.length>0){const a=e.Data[0];if(void 0===a)return{burned:t};n=a.transactionId??a.txnId??a.TxnId??a.id??void 0}return{...void 0!==n&&{transactionId:n},burned:t}}handleTransferError(e,t,n){if(e instanceof tc)return e;if(e instanceof kt)return new tc(st(e),Zo.INVALID_AMOUNT);if(ot(e)&&e.response){const t=e.response.status,a=e.response.data;if(400===t){const e=a?.message;return new tc(("string"==typeof e?e:void 0)??"Invalid transfer request",Zo.INVALID_AMOUNT)}if(403===t)return new tc("Insufficient balance for transfer",Zo.INSUFFICIENT_BALANCE);if(404===t){const e={};return"tokenName"in n&&(e.tokenName=n.tokenName),new tc("Token not found",Zo.TOKEN_NOT_FOUND,e)}}if("object"==typeof e&&null!==e&&"code"in e&&("ECONNABORTED"===it(e)||"ETIMEDOUT"===it(e)))return new tc("Transfer request timed out",Zo.NETWORK_ERROR);const a=""!==st(e)?st(e):t;return new tc(a,Zo.NETWORK_ERROR)}handleBurnError(e,t,n){if(e instanceof hc)return e;let a=t,s=uc.NETWORK_ERROR;if(ot(e)){const n=e.response?.data;if("object"==typeof n){const e=n.Message;if("string"==typeof e&&e.length>0){a=`${t}: ${e}`;const n=e.toLowerCase();n.includes("insufficient")||n.includes("balance")?s=uc.INSUFFICIENT_BALANCE:(n.includes("not found")||n.includes("token"))&&(s=uc.TOKEN_NOT_FOUND)}}}else at(e)&&(a=`${t}: ${st(e)}`);return new hc(a,s,nc(n))}}class wc extends Xn{constructor(e,t,n,a=!1,s){super(e,a),this.balanceService=new Ho(e,a),this.tokenService=new oc(e,a,s),this.lockService=new ic(e,t,n,a),this.transferService=new bc(e,t,n,a)}async fetchPoolDetails(e){this.validateFetchPoolDetailsData(e);const t=await this.http.post("/api/asset/launchpad-contract/FetchSaleDetails",e);Rs(()=>ct(t,"Failed to fetch pool details"),"Failed to fetch pool details",this.logger,e=>{throw Nt(st(e),500)});const n=t.Data.reverseBondingCurveConfiguration,a=n?.minFeePortion??"0",s=n?.maxFeePortion??"0",r=!ss(a)||!ss(s),i=t.Data;return i.reverseBondingCurveMinFeePortion=a,i.reverseBondingCurveMaxFeePortion=s,i.hasReverseBondingCurveFee=r,i.isGraduated="Finished"===t.Data.saleStatus,delete i.reverseBondingCurveConfiguration,t}async fetchLaunchTokenFee(){const e=await this.http.post("/api/asset/launchpad-contract/FetchLaunchpadFeeAmount",{});return Rs(()=>ct(e,"Failed to fetch launch token fee"),"Failed to fetch launch token fee",this.logger,e=>{throw Nt(st(e),500)}),e.Data.feeAmount}validateFetchPoolDetailsData(e){if(!Za(e))throw Tt("data","Fetch pool details data");if("string"!=typeof e.vaultAddress||""===e.vaultAddress)throw Tt("vaultAddress","Vault address");if(!e.vaultAddress.startsWith("service|Token$Unit$"))throw new kt("Vault address must be in service format: service|Token$Unit$...","vaultAddress","INVALID_VAULT_ADDRESS")}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 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 Sc{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 Ac extends Error{constructor(e,t,n){super(t),this.name="GdexStreamError",this.code=e,void 0!==n&&(this.data=n)}}class Ec extends Qn{constructor(e={}){super(),this.nextRequestId=0,this.pending=new Map,this.subscriptionsByServerId=new Map,this.activeSubscriptions=new Set,this.intentionalClose=!1,this.reconnecting=!1,this.url=e.url??Ps("prod").gdexWebSocketUrl,this.requestTimeoutMs=e.requestTimeoutMs??15e3,this.reconnectionManager=new Sc({maxAttempts:e.reconnectAttempts??5,baseDelayMs:e.reconnectDelayMs??2e3,useExponentialBackoff:!0});const t=e.webSocketImpl??globalThis.WebSocket;if("function"!=typeof t)throw new Error('GdexStreamService requires a standards-compatible WebSocket constructor. Node.js versions before 22 must provide one with config.webSocketImpl (for example, from the "ws" package).');this.webSocketConstructor=t}connect(){return this.isConnected()?Promise.resolve():(this.connectPromise||(this.intentionalClose=!1,this.clearReconnectTimer(),this.connectPromise=this.openSocket()),this.connectPromise)}disconnect(){this.intentionalClose=!0,this.reconnecting=!1,this.clearReconnectTimer(),this.rejectPending(new Error("GDEX stream disconnected"));const e=this.socket;this.socket=void 0,this.connectPromise=void 0,e?.close(1e3,"client disconnect")}isConnected(){return 1===this.socket?.readyState}request(e,t){if(!this.isConnected()||!this.socket)return Promise.reject(new Error("GDEX stream is not connected. Call connect() first."));const n=++this.nextRequestId,a={jsonrpc:"2.0",id:n,method:e};return void 0!==t&&(a.params=t),new Promise((t,s)=>{const r=setTimeout(()=>{this.pending.delete(n),s(new Error(`GDEX request "${e}" timed out after ${this.requestTimeoutMs}ms`))},this.requestTimeoutMs);this.pending.set(n,{resolve:e=>t(e),reject:s,timeout:r});try{this.socket?.send(JSON.stringify(a))}catch(e){clearTimeout(r),this.pending.delete(n),s(e instanceof Error?e:new Error(String(e)))}})}serverInfo(){return this.request("gdex_serverInfo")}ping(){return this.request("gdex_ping")}getPool(e){return this.request("gdex_getPool",e)}getBalance(e,t){return this.request("gdex_getBalance",void 0===t?{owner:e}:{owner:e,tokenClassKey:t})}getPositions(e){return this.request("gdex_getPositions",e)}getBlockHeight(){return this.request("gdex_getBlockHeight")}quote(e){return this.request("gdex_quote",e)}getToken(e){return this.request("gdex_getToken",{tokenClassKey:e})}subscribeSwaps(e,t={}){return this.subscribe("swap",e,t)}subscribePool(e,t,n={}){return this.subscribe("pool",t,{...e,...n})}subscribeBalances(e,t,n={}){return this.subscribe("balance",t,{owner:e,...n})}subscribePoolCreated(e,t={}){return this.subscribe("poolCreated",e,t)}subscribeBlocks(e,t={}){return this.subscribe("blocks",e,t)}openSocket(){return new Promise((e,t)=>{let n=!1;const a=new this.webSocketConstructor(this.url,"gdex.jsonrpc.v1");this.socket=a,a.onopen=()=>{this.socket===a&&(n=!0,this.connectPromise=void 0,this.reconnecting||this.reconnectionManager.reset(),this.logger.info("Connected to GDEX stream"),e())},a.onmessage=e=>this.handleMessage(e.data),a.onerror=()=>{n||t(new Error(`Failed to connect to GDEX stream at ${this.url}`))},a.onclose=e=>{this.socket===a&&(this.socket=void 0,this.connectPromise=void 0,n||t(new Error(`GDEX stream closed before connecting (code ${e.code??0})`)),this.rejectPending(new Error(`GDEX stream connection closed (code ${e.code??0})`)),this.intentionalClose||this.reconnecting||this.startReconnectLoop())}})}handleMessage(e){if("string"!=typeof e)return void this.logger.warn("Ignoring non-text GDEX WebSocket frame");let t;try{t=JSON.parse(e)}catch{return void this.logger.warn("Ignoring invalid JSON from GDEX stream")}if("number"==typeof t.id){const e=this.pending.get(t.id);if(!e)return;if(clearTimeout(e.timeout),this.pending.delete(t.id),t.error){const n="number"==typeof t.error.code?t.error.code:-32603,a="string"==typeof t.error.message?t.error.message:"GDEX request failed";e.reject(new Ac(n,a,t.error.data))}else e.resolve(t.result);return}if("gdex_subscription"!==t.method||!this.isRecord(t.params))return;const n=t.params.subscription,a=t.params.result;if("string"!=typeof n||!this.isRecord(a))return;const s=this.subscriptionsByServerId.get(n);if(s?.active)try{s.callback(a)}catch(e){this.logger.error("GDEX subscription callback failed",e)}}async subscribe(e,t,n){const a={channel:e,...n},s=await this.request("gdex_subscribe",a);let r;const i={subscriptionId:s.subscriptionId,unsubscribe:async()=>this.unsubscribe(r)};return r={serverId:s.subscriptionId,params:a,callback:t,handle:i,active:!0},this.activeSubscriptions.add(r),this.subscriptionsByServerId.set(r.serverId,r),i}async unsubscribe(e){e.active&&(e.active=!1,this.activeSubscriptions.delete(e),this.subscriptionsByServerId.delete(e.serverId),this.isConnected()&&await this.request("gdex_unsubscribe",{subscriptionId:e.serverId}))}startReconnectLoop(){this.reconnecting||this.intentionalClose||(this.reconnecting=!0,this.reconnectLoop())}async reconnectLoop(){for(;!this.intentionalClose&&this.reconnectionManager.shouldRetry();){const e=this.reconnectionManager.getNextDelay();if(this.reconnectionManager.recordAttempt(),this.logger.warn(`GDEX reconnect attempt ${this.reconnectionManager.getAttempts()}/${this.reconnectionManager.getMaxAttempts()} in ${e}ms`),await this.waitForReconnectDelay(e),this.intentionalClose)break;try{return await this.openSocket(),await this.resubscribeAll(),this.reconnectionManager.reset(),void(this.reconnecting=!1)}catch(e){this.logger.warn(`GDEX reconnect failed: ${e instanceof Error?e.message:String(e)}`)}}this.reconnecting=!1,this.intentionalClose||this.logger.error("GDEX reconnection attempts exhausted")}async resubscribeAll(){this.subscriptionsByServerId.clear();for(const e of this.activeSubscriptions){if(!e.active)continue;const t={...e.params,snapshot:!0},n=await this.resubscribeWithRateLimitRetry(t);e.active?(e.serverId=n.subscriptionId,e.handle.subscriptionId=n.subscriptionId,this.subscriptionsByServerId.set(n.subscriptionId,e)):await this.request("gdex_unsubscribe",{subscriptionId:n.subscriptionId})}}async resubscribeWithRateLimitRetry(e){for(let t=0;;t++)try{return await this.request("gdex_subscribe",e)}catch(e){if(!(e instanceof Ac)||-32003!==e.code||t>=5)throw e;const n=this.readRetryAfterMs(e.data);this.logger.warn(`GDEX resubscribe rate limited; retrying in ${n}ms`),await new Promise(e=>setTimeout(e,n))}}waitForReconnectDelay(e){return new Promise(t=>{this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectDelayResolve=void 0,t()},e),this.reconnectDelayResolve=t})}clearReconnectTimer(){void 0!==this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0;const e=this.reconnectDelayResolve;this.reconnectDelayResolve=void 0,e?.()}rejectPending(e){for(const t of this.pending.values())clearTimeout(t.timeout),t.reject(e);this.pending.clear()}readRetryAfterMs(e){return!this.isRecord(e)||"number"!=typeof e.retryAfterMs||e.retryAfterMs<0?1e3:e.retryAfterMs}isRecord(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}}function Tc(e,t="image",n){const a=new FormData;if("undefined"!=typeof File&&e instanceof File)a.append(t,e);else{if(!Buffer.isBuffer(e))throw Ct("file","a File object (browser) or Buffer (Node.js)");{const s=new Blob([e],{type:"image/png"});a.append(t,s,n)}}return a}class Cc extends Xn{constructor(e,t,n=!1){super(e,n,t)}async uploadImageByTokenName(e){const{tokenName:t,options:n}=e;gs(t);const a=`${t}.png`;ds(n.file,a,"image/png");try{const e=`${n.tokenName??t}.png`,a=Tc(n.file,"image",e),s=await Kt(()=>this.http.request({method:"POST",url:`${p.UPLOAD_IMAGE}?tokenName=${encodeURIComponent(n.tokenName??t)}`,data:a,headers:this.getJwtHeaders()}),{errorContext:"Image upload failed"});return"string"==typeof s?s:""}catch(e){if(e instanceof wt)throw e;if(at(e)&&st(e).includes("FormData"))throw It("File upload failed: FormData not supported in this environment. Ensure you have proper polyfills for Node.js environments.","FormData");throw e}}}const Nc={CHAT_MESSAGE:"CHAT_MESSAGE",COMMENT:"COMMENT"};function Ic(e,t){if(null==e)return[];if(Array.isArray(e))return e;const n=e[t];return Array.isArray(n)?n:[]}class Dc extends Xn{constructor(e,t,n=!1){super(e,n,t)}buildPoolFilters(e){return{...!Pn(e.search)&&{search:e.search},...!Pn(e.tokenName)&&{tokenName:e.tokenName},...!Pn(e.type)&&{type:e.type},...!Pn(e.hasUpcomingShows)&&{hasUpcomingShows:e.hasUpcomingShows},...!Pn(e.language)&&{language:e.language},...!Pn(e.recentlyStreamed)&&{recentlyStreamed:e.recentlyStreamed},...!Pn(e.hasRecordings)&&{hasRecordings:e.hasRecordings},...!Pn(e.streamStatus)&&{streamStatus:e.streamStatus}}}async fetchSinglePage(e){const t=Math.min(e.pageSize,20),n=e.cursor,a={pageSize:String(t)};void 0!==n&&(a.cursor=n),Pn(e.type)||(a.type=e.type),Pn(e.tokenName)||(a.tokenName=e.tokenName),Pn(e.search)||(a.search=e.search),Pn(e.hasUpcomingShows)||(a.hasUpcomingShows=e.hasUpcomingShows.toString()),Pn(e.language)||(a.language=e.language),Pn(e.recentlyStreamed)||(a.recentlyStreamed=e.recentlyStreamed.toString()),Pn(e.hasRecordings)||(a.hasRecordings=e.hasRecordings.toString()),Pn(e.streamStatus)||(a.streamStatus=e.streamStatus);const s=ts(a),r=Lt(await Wt(()=>this.http.get(p.FETCH_POOLS,s),{errorContext:"Failed to fetch pools"})),i=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}(r),o={hasNextPage:r.hasNextPage??r.pageInfo?.hasNextPage??!1},c=r.count??r.total;void 0!==c&&(o.totalCount=c);const l=r.nextCursor??r.pageInfo?.endCursor;null!=l&&(o.nextCursor=l);const d=r.prevCursor??r.pageInfo?.startCursor;null!=d&&(o.prevCursor=d);const u=r.hasPrevPage??r.pageInfo?.hasPreviousPage;return void 0!==u&&(o.hasPrevPage=u),{items:i,pageInfo:o}}async fetchPools(e){const t=e?.cursor,n=e?.pageSize??wi.DEFAULT_LIMIT;Un(e?.tokenName)&&gs(e.tokenName);const a=void 0!==e?.type?{recent:"RECENT",popular:"POPULAR",recordings:"RECORDINGS",seconds_streamed:"SECONDS_STREAMED"}[e.type]:void 0,s=void 0!==e?.streamStatus?{idle:"IDLE",active:"ACTIVE",disabled:"DISABLED"}[e.streamStatus]:void 0,r={...this.buildPoolFilters({search:e?.search,tokenName:e?.tokenName,type:a,hasUpcomingShows:e?.hasUpcomingShows,language:e?.language,recentlyStreamed:e?.recentlyStreamed,hasRecordings:e?.hasRecordings,streamStatus:s}),pageSize:n,...void 0!==t&&{cursor:t}},i=await this.fetchSinglePage(r);return{items:i.items,pageInfo:i.pageInfo}}async fetchAllPools(e){const t=[];let n;const a=wi.BACKEND_MAX_PAGE_SIZE;for(;;){const s={...e,pageSize:a,...void 0!==n&&{cursor:n}},r=await this.fetchPools(s);if(t.push(...r.items),0===r.items.length)break;if(!r.pageInfo.hasNextPage)break;n=r.pageInfo.nextCursor}return{items:t,pageInfo:{hasNextPage:!1,totalCount:t.length}}}async checkPool(e){!function(e){const t=za(e);!t.success&&t.errors&&hs(t.errors,"options")}(e),Un(e.tokenName)&&gs(e.tokenName);try{const t=await this.http.post(p.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===Un(e.symbol)){return!n.symbolAvailable}if(!0===Un(e.tokenName)){return!n.nameAvailable}return!1}catch(e){const t=String(e),n=e,a="string"==typeof n.message?n.message:"";if(t.includes("404")||t.includes("Pool not found")||a.includes("404")||a.includes("Pool not found"))return!1;const s="number"==typeof n.statusCode?n.statusCode:null;if(404===s)return!1;if(t.includes("400")||t.includes("Missing required pool identifier")||a.includes("400")||a.includes("Missing required pool identifier"))return!1;if(400===s&&a.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 Va(t,"tokenName")&&Qa(t,"from")&&Qa(t,"to")&&Qa(t,"resolution")}(e))throw new kt("Invalid options provided. Expected { tokenName: string, from?: number, to?: number, resolution?: number }","options","INVALID_OPTIONS");const{tokenName:t,from:n,to:a,resolution:s}=e;if(gs(t),null==n||null==a||null==s)throw new kt("Graph options (from, to, resolution) are required","options","MISSING_GRAPH_OPTIONS");const r={tokenName:t,from:n,to:a,resolution:s};ms(r);const i=ts(r);return{dataPoints:await Kt(()=>this.http.get(p.CHART,i),{errorContext:"Failed to fetch graph data"})}}async fetchTokenDistribution(e){if(""===e||null==e)throw Tt("tokenName","Token name");let t;gs(e);try{t=await Wt(()=>this.http.get(`${p.GET_TOKEN_DISTRIBUTION}?tokenName=${e}`),{errorContext:"Failed to fetch token distribution"})}catch(t){if(ot(t)&&500===t.response?.status)throw Nt(`Token distribution data temporarily unavailable for ${e}. This is a backend issue - please try again later.`,500);throw t}return ys(Lt(t),t.status,e=>e.toFixed())}async fetchUserHolderContext(e,t){if(""===e||null==e)throw Tt("tokenName","Token name");if(""===t||null==t)throw Tt("userAddress","User address");return gs(e),Kt(()=>this.http.get(`${p.GET_TOKEN_DISTRIBUTION}?tokenName=${e}`,{userAddress:t}),{errorContext:"Failed to fetch user holder context"})}async resolveTokenNameToVault(e){const t=await this.fetchPools({tokenName:e});if(null!==t.items&&void 0!==t.items&&Array.isArray(t.items)&&t.items.length>0)return t.items[0]?.vaultAddress??null;if(null!==t.items&&void 0!==t.items&&"object"==typeof t.items){const e=t.items.tokens;return e?.vaultAddress??null}return null}async fetchToken(e){if(null==e||"string"!=typeof e||""===e.trim())throw new Error("Token name is required and must be a non-empty string");gs(e);try{const t=p.GET_TOKEN.replace(":tokenName",e.toLowerCase().trim()),n=Lt(await this.http.get(t));if(null!=n?.tokens){const t=Array.isArray(n.tokens)?n.tokens[0]:n.tokens;if(null==t)throw new Error(`Token not found: ${e}`);return t}throw new Error(`Invalid response format when fetching token: ${e}`)}catch(t){const n=String(t);if(n.includes("404")||n.includes("not found"))throw 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&&gs(e.tokenName);try{const t=await this.http.post(p.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(!Un(e))throw Tt("tokenName","Token name");gs(e);const t=p.TOKEN_STATS.replace(":tokenName",e.toLowerCase().trim());try{const e=Lt(await this.http.get(t));if(!e?.stats)throw new Error("Invalid response: missing stats data");return{success:!0,data:e.stats}}catch(t){throw this.logger.warn(`Failed to fetch token stats for ${e}: ${String(t)}`),t}}async updateTokenConfig(e,t){if(""===e||null==e)throw Tt("tokenName","Token name");gs(e),function(e){if(void 0===e.messagesEnabled&&void 0===e.commentsEnabled&&void 0===e.streamingEnabled&&void 0===e.nextLiveStreamAt&&void 0===e.streamLanguage&&void 0===e.websiteUrl&&void 0===e.telegramUrl&&void 0===e.twitterUrl&&void 0===e.instagramUrl&&void 0===e.facebookUrl&&void 0===e.redditUrl&&void 0===e.tiktokUrl)throw new kt("At least one config option must be provided (messagesEnabled, commentsEnabled, streamingEnabled, nextLiveStreamAt, streamLanguage, or social URLs)","options",gt);if(void 0!==e.messagesEnabled&&"boolean"!=typeof e.messagesEnabled)throw Ft("messagesEnabled","boolean");if(void 0!==e.commentsEnabled&&"boolean"!=typeof e.commentsEnabled)throw Ft("commentsEnabled","boolean");if(void 0!==e.streamingEnabled&&"boolean"!=typeof e.streamingEnabled)throw Ft("streamingEnabled","boolean");if(void 0!==e.streamLanguage&&"string"!=typeof e.streamLanguage)throw Ft("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 Ft(n,"string or null")}if(void 0!==e.nextLiveStreamAt&&null!==e.nextLiveStreamAt){if("string"!=typeof e.nextLiveStreamAt)throw Ft("nextLiveStreamAt","string or null");const t=new Date(e.nextLiveStreamAt);if(isNaN(t.getTime()))throw new kt("nextLiveStreamAt must be a valid ISO date string","nextLiveStreamAt",ft)}}(t);const n=p.UPDATE_TOKEN_CONFIG.replace(":tokenName",e.toLowerCase().trim()),a={};void 0!==t.messagesEnabled&&(a.messagesEnabled=t.messagesEnabled),void 0!==t.commentsEnabled&&(a.commentsEnabled=t.commentsEnabled),void 0!==t.streamingEnabled&&(a.streamingEnabled=t.streamingEnabled),void 0!==t.nextLiveStreamAt&&(a.nextLiveStreamAt=t.nextLiveStreamAt),void 0!==t.streamLanguage&&(a.streamLanguage=t.streamLanguage),void 0!==t.websiteUrl&&(a.websiteUrl=t.websiteUrl),void 0!==t.telegramUrl&&(a.telegramUrl=t.telegramUrl),void 0!==t.twitterUrl&&(a.twitterUrl=t.twitterUrl),void 0!==t.instagramUrl&&(a.instagramUrl=t.instagramUrl),void 0!==t.facebookUrl&&(a.facebookUrl=t.facebookUrl),void 0!==t.redditUrl&&(a.redditUrl=t.redditUrl),void 0!==t.tiktokUrl&&(a.tiktokUrl=t.tiktokUrl),await this.http.patch(n,a,this.getJwtHeaders())}}const _c=ln,Rc=rn,xc={MAX_LENGTH:100};function Oc(e){if(void 0!==e.tokenName){if(!Un(e.tokenName))throw Ft("tokenName","a non-empty string",typeof e.tokenName);if(e.tokenName.length>Rc.MAX_LENGTH)throw Ot("tokenName",Rc.MAX_LENGTH,e.tokenName.length)}if(void 0!==e.userAddress){if(!Un(e.userAddress))throw Ft("userAddress","a non-empty string",typeof e.userAddress);if(e.userAddress.length>xc.MAX_LENGTH)throw Ot("userAddress",xc.MAX_LENGTH,e.userAddress.length)}if(void 0!==e.search){if("string"!=typeof e.search)throw Ft("search","a string",typeof e.search);if(e.search.length>256)throw Ot("search",256,e.search.length)}if(Mn(0,void 0,_c.MAX_LIMIT,e.pageSize),void 0!==e.txnType&&"BUY"!==e.txnType&&"SELL"!==e.txnType)throw Ct("txnType",'"BUY" or "SELL"');if(void 0!==e.startDate){if(!Un(e.startDate))throw Ft("startDate","a non-empty string",typeof e.startDate);if(isNaN(Date.parse(e.startDate)))throw Ct("startDate","a valid ISO 8601 date")}if(void 0!==e.endDate){if(!Un(e.endDate))throw Ft("endDate","a non-empty string",typeof e.endDate);if(isNaN(Date.parse(e.endDate)))throw Ct("endDate","a valid ISO 8601 date")}if(void 0!==e.minAmount)try{Rn(e.minAmount,0,Number.MAX_SAFE_INTEGER,"minAmount")}catch{throw Ct("minAmount","a non-negative number")}if(void 0!==e.maxAmount)try{Rn(e.maxAmount,0,Number.MAX_SAFE_INTEGER,"maxAmount")}catch{throw Ct("maxAmount","a non-negative number")}void 0!==e.minAmount&&void 0!==e.maxAmount&&function(e,t,n="range"){const a="number"==typeof e?e:Number(e),s="number"==typeof t?t:Number(t);if(isNaN(a)||isNaN(s))throw Ft(n,"numeric values",void 0,n);if(a>s)throw new kt(`Minimum value (${a}) must be less than or equal to maximum value (${s}) for ${n}`,n,vt)}(e.minAmount,e.maxAmount,"amountRange")}class Fc extends Xn{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 Va(t,"tokenName")&&(void 0===t.tradeType||"buy"===t.tradeType||"sell"===t.tradeType)&&Xa(t,"userAddress")&&Qa(t,"offset")&&Qa(t,"pageSize")&&Qa(t,"page")&&Qa(t,"limit")}(e))throw new kt("Invalid options provided. Expected { tokenName: string, tradeType?: string, userAddress?: string, cursor?: string, pageSize?: number, startDate?: Date, endDate?: Date, sortOrder?: string }","options","INVALID_OPTIONS");const{tokenName:t,cursor:n,pageSize:a=wi.DEFAULT_LIMIT}=e;if(!Un(t))throw Tt("tokenName","Token name");const s={pageSize:String(Math.min(a,cn))};void 0!==n&&(s.cursor=n);const r={...s};r.tokenName=t;const i=await this.http.get(p.GET_TRADES,r);if(null==i)throw new kt("No response from trade service","response","NO_RESPONSE");const o=Lt(i),c=Ic(o,"trades"),l=o?.pageInfo;return{items:c,pageInfo:l??{hasNextPage:!1}}}buildTradesQueryParams(e){const t={};null!==e.tokenName&&void 0!==e.tokenName&&e.tokenName.length>0&&(t.tokenName=zt(e.tokenName)),null!==e.userAddress&&void 0!==e.userAddress&&e.userAddress.length>0&&(t.userAddress=e.userAddress),null!==e.search&&void 0!==e.search&&e.search.length>0&&(t.search=e.search);const n=void 0!==e.pageSize?function(e,t=1,n=wi.BACKEND_MAX_PAGE_SIZE){return Math.max(t,Math.min(n,Math.ceil(e??t)))}(e.pageSize,1,_c.MAX_LIMIT):_c.MAX_LIMIT;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){Oc(e);const t=this.buildTradesQueryParams(e);return Kt(()=>this.http.get(Be,t),{errorContext:"Failed to fetch trades"})}}function Bc(e){return!!Un(e)&&dn.PATTERN.test(e)}function Uc(e,t,n=1){if(null==e||""===e)return null;if("string"!=typeof e)return null;const a=e.trim();return a.length<n?null:a}Ln({BOTH:"both",HELD:"held",CREATED:"created"});class Pc extends Xn{constructor(e,t,n=!1){super(e,n,t)}async fetchProfile(e){const t=e??this.http.getAddress();if(""===t||null==t||!Bc(t))throw Ct("address","eth|[40-hex-chars] or client|[identifier]","Address");const n=null==e,a=n?p.GET_CURRENT_USER:p.GET_PROFILE.replace(":address",t),s=await this.http.get(a,void 0,n?this.getJwtHeaders():void 0);if(null==s)throw new kt("No response from user service","response","NO_RESPONSE");return s}async updateProfile(e){this.validateUpdateProfileData(e);let t=e.profileImage;if(!Un(t))try{const n=await this.fetchProfile(e.address);t=n.data?.profileImage??""}catch{t=""}const n={profileImage:t,fullName:e.fullName};await Kt(()=>this.http.put(p.UPDATE_PROFILE,n,this.getJwtHeaders()),{errorContext:"Profile update failed"})}async uploadProfileImage(e){this.validateUploadProfileImageOptions(e);const t=e.address??this.http.getAddress();if(null==t||""===t)throw new kt("Wallet address not available - wallet not configured","address","NO_WALLET");try{const n=`profile-image-${t}.png`,a=Tc(e.file,"image",n),s=await Kt(()=>this.http.request({method:"POST",url:`${p.UPLOAD_IMAGE}?tokenName=${encodeURIComponent(t)}`,data:a,headers:this.getJwtHeaders()}),{errorContext:"Image upload failed"});return"string"==typeof s?s:""}catch(e){if(e instanceof kt||e instanceof wt)throw e;throw new kt(`Profile image upload failed: ${st(e)}`,"file","UPLOAD_FAILED")}}async fetchTokenList(e){if(void 0!==e.status&&"created"!==e.type)throw new kt("status filters only apply when type=created","status","INVALID_FILTER");const t=e.tokenName,n={...e},a="created"===e.type;a&&(delete n.tokenName,void 0!==t&&void 0===n.search&&(n.search=t));const s=await this.buildFetchRequest(p.GET_TOKEN_LIST,n,{includeType:!0,requestType:e.type??"both",responseKey:a?"launches":"token",errorMessage:"Failed to fetch token list"});return a&&void 0!==t?{...s,tokens:s.tokens.filter(e=>e.tokenName===t||e.name===t)}:s}async fetchTokensHeld(e){if(void 0!==e.type&&"held"!==e.type)throw new kt("fetchTokensHeld only supports type=held","type","INVALID_TYPE");if(void 0!==e.status)throw new kt("status filters only apply when type=created","status","INVALID_FILTER");return this.buildFetchRequest(p.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:a,tokenName:s,status:r}=e??{};if(void 0!==e?.type&&"created"!==e.type)throw new kt("fetchTokensCreated only supports type=created","type","INVALID_TYPE");const i=e?.address??this.http.getAddress();if(null==i||""===i)throw new kt("Wallet address not available - wallet not configured","address","NO_WALLET");const o={type:"created",address:i,pageSize:n??wi.DEFAULT_LIMIT};return void 0!==t&&(o.cursor=t),void 0!==a&&(o.search=a),void 0!==s&&void 0===a&&(o.search=s),void 0!==s&&(o.tokenName=s),void 0!==r&&(o.status=r),this.fetchTokenList(o)}async getManagedTokens(e={}){const t=Ei({pageSize:e.pageSize??wi.DEFAULT_LIMIT,...void 0!==e.cursor&&{cursor:e.cursor}},cn);return Kt(()=>this.http.get(p.GET_MANAGED_TOKENS,t,this.getJwtHeaders()),{errorContext:"Failed to fetch managed tokens"})}async buildFetchRequest(e,t,n){this.validateGetTokenListOptions(t);const a=Ei({pageSize:t.pageSize??wi.DEFAULT_LIMIT,...void 0!==t.cursor&&{cursor:t.cursor}},cn);Ti(a,t,["address","search","tokenName","status"]),n.includeType&&!e.includes("?type=")&&(a.type=n.requestType);let s=e;const r=t.address??this.http.getAddress();if(e.includes(":address")){if(0===r.length)throw Tt("address","User address");s=e.replace(":address",r),delete a.address}const i=Lt(await Wt(()=>this.http.get(s,a),{errorContext:n.errorMessage})),o=Ic(i,n.responseKey).map(e=>{const t="string"==typeof e.tokenName?e.tokenName:"",a="string"==typeof e.name?e.name:t,s="string"==typeof e.createdAt?e.createdAt:"",i=e.metadata,o={...e};return delete o.metadata,{...o,id:"string"==typeof e.id?e.id:t,name:a,symbol:"string"==typeof e.symbol?e.symbol:"",type:n.requestType,address:r,balance:"string"==typeof e.balance?e.balance:"string"==typeof e.quantity?e.quantity:"0",decimals:"number"==typeof e.decimals?e.decimals:0,...null!==i&&"object"==typeof i?{metadata:i}:{},createdAt:s,updatedAt:"string"==typeof e.updatedAt?e.updatedAt:s}}),c={hasNextPage:i.hasNextPage??!1},l=i.pageInfo,d=i.count??i.total??l?.totalCount;void 0!==l&&(c.hasNextPage=l.hasNextPage??!1,void 0!==l.hasPreviousPage&&(c.hasPrevPage=l.hasPreviousPage),null!==l.endCursor&&void 0!==l.endCursor&&(c.nextCursor=l.endCursor),null!==l.startCursor&&void 0!==l.startCursor&&(c.prevCursor=l.startCursor)),void 0!==d&&(c.totalCount=d),void 0!==i.nextCursor&&(c.nextCursor=i.nextCursor),void 0!==i.prevCursor&&(c.prevCursor=i.prevCursor),void 0!==i.hasPrevPage&&(c.hasPrevPage=i.hasPrevPage);const u={tokens:o,pageInfo:c};return void 0!==d&&(u.total=d),u}validateGetTokenListOptions(e){const t=e.pageSize??wi.DEFAULT_LIMIT;if(t<1||t>cn)throw new kt(`pageSize must be between 1 and ${cn}`,"pageSize","OUT_OF_RANGE");if(void 0!==e.address&&!Bc(e.address))throw Ct("address","eth|[40-hex-chars] or client|[identifier]","Address");const n=Uc(e.search);if(null!==n&&!(Un(a=n)&&a.length>=kn&&a.length<=bn))throw Rt("search",kn,bn,n.length,"Search query");var a;const s=Uc(e.tokenName);if(null!==s&&!(Un(r=s)&&r.length>=rn.MIN_LENGTH&&r.length<=rn.MAX_LENGTH))throw Rt("tokenName",rn.MIN_LENGTH,rn.MAX_LENGTH,s.length,"Token name");var r}validateUpdateProfileData(e){if(!Bc(e.address))throw Ct("address","eth|[40-hex-chars] or client|[identifier]","Address");if(t=e.fullName,!(Un(t)&&t.length>=wn.FULL_NAME.MIN_LENGTH&&t.length<=wn.FULL_NAME.MAX_LENGTH&&wn.FULL_NAME.ALPHABETS_ONLY_PATTERN.test(t)))throw Rt("fullName",wn.FULL_NAME.MIN_LENGTH,wn.FULL_NAME.MAX_LENGTH,e.fullName.length,"Full name");var t}validateUploadProfileImageOptions(e){if(void 0!==e.address&&!Bc(e.address))throw Ct("address","eth|[40-hex-chars] or client|[identifier]","Address")}}class Mc{constructor(e,t,n=!1){this.http=e,this.poolService=new Dc(e,t,n),this.tradeService=new Fc(e,n),this.userService=new Pc(e,t,n),this.imageService=new Cc(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 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)}getAddress(){return this.http.getAddress()}validateTokenName(e){return gs(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)}}class Lc extends Ni{constructor(e,t,n,a=!1,s){super(e,t,n,a,s)}validateContent(e,t){if(!Un(e))throw Tt("content","Message content");if(0===e.trim().length)throw Tt("content","Message content");xn(e,t===Nc.CHAT_MESSAGE?un.CHAT_MESSAGES_V1.MAX_LENGTH:un.COMMENTS_V1.MAX_LENGTH,"content")}validateMessageId(e){if(!Un(e))throw Tt("id","Message ID");if(e.length<10||e.length>64)throw Ct("id","valid message ID format","Message ID")}validateMessageType(e){if(e!==Nc.CHAT_MESSAGE&&e!==Nc.COMMENT)throw new kt(`type must be one of: ${Object.values(Nc).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,sn);const a={};void 0!==e.cursor&&(a.cursor=e.cursor),a.pageSize=e.pageSize??wi.DEFAULT_LIMIT;const s=Ei(a,ln.MAX_LIMIT),r={};void 0!==s.pageSize&&(r.pageSize=s.pageSize),void 0!==s.cursor&&(r.cursor=s.cursor),t&&(r.type=e.type.toUpperCase()),n&&(r.tokenName=zt(e.tokenName)),void 0!==e.userAddress&&""!==e.userAddress&&(r.userAddress=e.userAddress),void 0!==e.search&&""!==e.search&&(r.search=e.search);const i=await this.http.get(Ue.GET_MESSAGES,r),o=this.extractData(i);return{messages:o.messages,pageInfo:o.pageInfo}}async createMessage(e){this.validateMessageType(e.type),this.validateTokenName(e.tokenName,sn),this.validateContent(e.content,e.type);const t={type:e.type,tokenName:zt(e.tokenName),content:e.content.trim()},n=await this.http.post(Ue.CREATE_MESSAGE,t,this.getJwtHeaders());return{message:this.extractData(n)}}async updateMessage(e,t){this.validateMessageId(e),this.validateContent(t.content);const n=this.buildEndpointWithId(Ue.UPDATE_MESSAGE,e),a={content:t.content.trim()},s=await this.http.put(n,a,this.getJwtHeaders());return{message:this.extractData(s)}}async deleteMessage(e){this.validateMessageId(e);const t=this.buildEndpointWithId(Ue.DELETE_MESSAGE,e);return await this.http.delete(t,void 0,this.getDualAuthHeaders()),{success:!0}}async getPinnedMessage(e){this.validateTokenName(e,sn);const t=await this.http.get(Ue.GET_PINNED,{tokenName:zt(e)});return{message:this.extractData(t)}}async pinMessage(e){this.validateMessageId(e);const t=Ue.PIN_MESSAGE.replace(":id",e);return await this.http.post(t,{},this.getDualAuthHeaders()),{success:!0}}async unpinMessage(e){this.validateMessageId(e);const t=Ue.UNPIN_MESSAGE.replace(":id",e);return await this.http.delete(t,void 0,this.getDualAuthHeaders()),{success:!0}}async getMessageStats(){const e=await this.http.get(Ue.GET_MESSAGE_STATS,void 0,this.getDualAuthHeaders());return this.extractData(e)}}const $c=$n({MODERATOR:"MODERATOR",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MANAGER:"MANAGER"}),Kc={TOKEN:"TOKEN",ALL_OWNER_TOKENS:"ALL_OWNER_TOKENS"},Gc=$n(Kc),Wc={PENDING:"PENDING",CLAIMED:"CLAIMED",REVOKED:"REVOKED",EXPIRED:"EXPIRED"};$n(Wc);class Hc extends Ni{constructor(e,t,n,a=!1,s){super(e,t,n,a,s)}validateRole(e){if(!Un(e))throw Tt("role","Role");if(!function(e){return $c.includes(e)}(e))throw Ct("role",`one of: ${$c.join(", ")}`,"Role")}validateInviteCodeFormat(e){if(!Un(e))throw Tt("inviteCode","Invite code");if(t=e,!fn.PATTERN.test(t))throw Ct("inviteCode","valid invite code format","Invite code");var t}validateInviteScope(e){if(void 0!==e&&(t=e,!Gc.includes(t)))throw new kt(`Invalid invite scope. Must be one of: ${Gc.join(", ")}`,"inviteScope","INVALID_VALUE");var t}async createInvite(e){this.validateInviteScope(e.inviteScope);const t=e.inviteScope??Kc.TOKEN;if(t===Kc.TOKEN){if(void 0===e.tokenName||""===e.tokenName)throw new kt("Token name is required for TOKEN scope invites","tokenName","REQUIRED");this.validateTokenName(e.tokenName,an)}else if(t===Kc.ALL_OWNER_TOKENS&&e.tokenName)throw new kt("Token name should not be provided for ALL_OWNER_TOKENS scope invites","tokenName","INVALID_VALUE");this.validateRole(e.role),this.validateOptionalString(e.description,"description","Description",un.DESCRIPTION.MAX_LENGTH),this.validateOptionalDate(e.expiresAt,"expiresAt","Expiration date");const n=Y,a={inviteScope:t,role:e.role};t===Kc.TOKEN&&null!==e.tokenName&&void 0!==e.tokenName&&""!==e.tokenName&&(a.tokenName=zt(e.tokenName)),void 0!==e.description&&(a.description=e.description),void 0!==e.expiresAt&&(a.expiresAt=e.expiresAt);const s=await this.http.post(n,a,this.getMultiAuthHeaders());return{invite:this.extractData(s)}}async listInvites(e){void 0!==e.tokenName&&""!==e.tokenName&&this.validateTokenName(e.tokenName,an),this.validateStatusFilter(e.status,Wc);const t=te,n={...this.buildPaginationParams(e,ln.MAX_LIMIT)};void 0!==e.tokenName&&""!==e.tokenName&&(n.tokenName=zt(e.tokenName)),void 0!==e.status&&(n.status=e.status);const a=await this.http.get(t,n,this.getMultiAuthHeaders()),s=this.extractData(a);return{items:s.invites,pageInfo:s.pageInfo}}async revokeInvite(e){this.validatePositiveInteger(e,"inviteId","Invite ID");const t=this.buildEndpoint(ne,{id:String(e)});Mt(await this.http.delete(t,void 0,this.getMultiAuthHeaders()),"Failed to revoke invite")}async updateInviteRole(e){this.validatePositiveInteger(e.inviteId,"inviteId","Invite ID"),this.validateRole(e.role);const t=this.buildEndpoint(ae,{id:String(e.inviteId)}),n={role:e.role},a=await this.http.patch(t,n,this.getMultiAuthHeaders());return{invite:this.extractData(a)}}async updateInvite(e){if(this.validatePositiveInteger(e.inviteId,"inviteId","Invite ID"),void 0===e.role&&(void 0===e.description||""===e.description))throw new kt("At least one of role or description must be provided","options","REQUIRED");void 0!==e.role&&this.validateRole(e.role),void 0!==e.description&&this.validateOptionalString(e.description,"description","Description",un.DESCRIPTION.MAX_LENGTH);const t=this.buildEndpoint(se,{id:String(e.inviteId)}),n={};void 0!==e.role&&(n.role=e.role),void 0!==e.description&&(n.description=e.description);const a=await this.http.patch(t,n,this.getMultiAuthHeaders());return{invite:this.extractData(a)}}async claimInvite(e){this.validateInviteCodeFormat(e.inviteCode);const t=Z,n={inviteCode:e.inviteCode},a=await this.http.post(t,n,this.getMultiAuthHeaders()),s=this.extractData(a);return"tokenName"in s&&void 0!==s.tokenName?{token:s}:{blanketAccess:s}}async getModeratedTokens(e){const t=ee,n=this.buildPaginationParams(e??{},ln.MAX_LIMIT),a=await this.http.get(t,n,this.getMultiAuthHeaders()),s=this.extractData(a);return{items:s.tokens,pageInfo:s.pageInfo}}async getInviteByCode(e){this.validateInviteCodeFormat(e);const t=this.buildEndpoint(re,{code:e}),n=await this.http.get(t,{});return this.extractData(n)}}const qc="10000",zc="1000";function jc(e){return`${e}-${Date.now()}-${Math.random().toString(36).substring(2,11)}`}function Vc(){return Date.now()+6e4}function Xc(e){return""!==e&&"string"==typeof e&&/^[a-zA-Z0-9]{3,50}$/.test(e)}function Qc(e){try{return Math.floor(parseFloat(String(e))??0).toString()}catch{return"0"}}function Jc(e){return""!==e&&"string"==typeof e&&/^eth\|[0-9a-fA-F]{40}$/.test(e)}class Yc extends Xn{constructor(e){super(e)}getCollectionClaimFee(){return qc}getTokenClassCreateFee(){return zc}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(!Jc(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=qc;n.collectionClaim=e,t=String(BigInt(t)+BigInt(e))}if((e.createTokenClasses??0)>0){const a=zc,s=String(BigInt(a)*BigInt(e.createTokenClasses));n.tokenClassCreate=a,n.tokenClassCount=e.createTokenClasses,t=String(BigInt(t)+BigInt(s))}return{totalFee:t,breakdown:n}}async claimCollection(e){try{if(this.logger.debug("Claiming NFT collection",e.collectionName),!Xc(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:Vc(),uniqueKey:jc("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),!Jc(e))throw new Error(`Invalid wallet address format: ${e}`);const t=[];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),!Xc(e))throw new Error(`Invalid collection name format: ${e}`);const t=!0;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(!Xc(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?Qc(e.maxSupply):void 0,maxCapacity:void 0!==e.maxCapacity?Qc(e.maxCapacity):void 0,additionalKey:e.additionalKey,expiresAt:Vc(),uniqueKey:jc("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),!Xc(e.collection))throw new Error(`Invalid collection name: ${e.collection}`);const t=[];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(!Jc(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 a={collection:e.collection,type:e.type,category:e.category,quantity:e.quantity,owner:e.ownerAddress,additionalKey:e.additionalKey??"none",expiresAt:Vc(),uniqueKey:jc("mint")};this.logger.debug("Built mint DTO",a);const s=`mint-${Date.now()}`,r=Array.from({length:t},(e,t)=>t+1);return{transactionId:s,mintedQuantity:e.quantity,owner:e.ownerAddress,tokenInstances:r,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}),!Jc(e))throw new Error(`Invalid owner address: ${e}`);const n=[];return this.logger.debug(`Found ${n.length} NFT balances`),n}catch(e){throw this.logger.error("Failed to fetch NFT balances",e),e}}}class Zc extends Xn{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(Qe,{token:e.token,platform:e.platform,...void 0!==e.deviceId?{deviceId:e.deviceId}:{}},t),a=this.extractData(n);return this.logger.debug("Push token registered",{registered:a.registered}),a}async unregisterPushToken(e){this.logger.debug("Unregistering push token");const t=this.getJwtHeaders(),n=await this.http.request({method:"DELETE",url:Je,data:{token:e},headers:t}),a=this.extractData(n);return this.logger.debug("Push token unregistered",{unregistered:a.unregistered}),a}async getPreferences(){this.logger.debug("Fetching notification preferences");const e=this.getJwtHeaders(),t=await this.http.get(Ye,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(Ze,e,t),a=this.extractData(n);return this.logger.debug("Updated notification preferences",{tradesEnabled:a.tradesEnabled,streamsEnabled:a.streamsEnabled}),{preferences:a}}}class el extends Xn{constructor(e,t=!1){super(e,t)}async getHomeOEmbedJson(e={}){this.logger.debug("Fetching home oEmbed (JSON)");const t=await this.http.get(p.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(p.OEMBED,{},{responseType:"text"});return this.logger.debug("Fetched home oEmbed (HTML)"),{html:t}}async getPoolOEmbedJson(e){const{tokenName:t}=e;if(null==t||"string"!=typeof t||""===t.trim())throw new kt("tokenName is required","tokenName","REQUIRED_FIELD");this.logger.debug("Fetching pool oEmbed (JSON)",{tokenName:t});const n=p.OEMBED_BUY_SELL.replace(":tokenName",t.toLowerCase().trim()),a=await this.http.get(n,{format:"json"});return this.logger.debug("Fetched pool oEmbed (JSON)",{tokenName:t,title:a.title}),{oembed:a}}async getPoolOEmbedHtml(e){const{tokenName:t}=e;if(null==t||"string"!=typeof t||""===t.trim())throw new kt("tokenName is required","tokenName","REQUIRED_FIELD");this.logger.debug("Fetching pool oEmbed (HTML)",{tokenName:t});const n=p.OEMBED_BUY_SELL.replace(":tokenName",t.toLowerCase().trim()),a=await this.http.get(n,{},{responseType:"text"});return this.logger.debug("Fetched pool oEmbed (HTML)",{tokenName:t}),{html:a}}async getProfileOEmbedJson(e){const{address:t}=e;if(null==t||"string"!=typeof t||""===t.trim())throw new kt("address is required","address","REQUIRED_FIELD");this.logger.debug("Fetching profile oEmbed (JSON)",{address:t});const n=p.OEMBED_PROFILE.replace(":address",encodeURIComponent(t.toLowerCase().trim())),a=await this.http.get(n,{format:"json"});return this.logger.debug("Fetched profile oEmbed (JSON)",{address:t,title:a.title}),{oembed:a}}async getProfileOEmbedHtml(e){const{address:t}=e;if(null==t||"string"!=typeof t||""===t.trim())throw new kt("address is required","address","REQUIRED_FIELD");this.logger.debug("Fetching profile oEmbed (HTML)",{address:t});const n=p.OEMBED_PROFILE.replace(":address",encodeURIComponent(t.toLowerCase().trim())),a=await this.http.get(n,{},{responseType:"text"});return this.logger.debug("Fetched profile oEmbed (HTML)",{address:t}),{html:a}}}function tl(e){if(!Un(e))throw Tt("address","Address")}const nl={PENDING:"PENDING",CLAIMED:"CLAIMED",REVOKED:"REVOKED",EXPIRED:"EXPIRED"},al={ACTIVE:"ACTIVE",REVOKED:"REVOKED"},sl=Ln(nl),rl=Ln(al);function il(e){if(!Un(e))throw new Error("Address must be a non-empty string");try{oa(e,"address")}catch{throw new Error("Invalid wallet address format. Must be eth|..., 0x..., or client|... format")}}function ol(e){try{On(e,"id")}catch(e){if(e instanceof kt)throw new Error("Invite ID must be a positive integer");throw e}}class cl extends Ni{constructor(e,t,n,a=!1,s){super(e,t,n,a,s)}validateInviteCodeFormat(e){if(!Un(e))throw Tt("inviteCode","Invite code");!function(e){if(!Un(e))throw new Error("Invite code must be a non-empty string");xn(e,100,"code")}(e)}validateWalletAddressFormat(e){if(!Un(e))throw Tt("address","Address");il(e)}async createInvite(e={}){!function(e){try{qn(e.description,"description",255)}catch(e){if(e instanceof kt)throw e.message.includes("255")?new Error("description must be at most 255 characters"):new Error("description must be a string");throw e}if(void 0!==e.expiresAt){if(!Un(e.expiresAt))throw new Error("expiresAt must be a non-empty string");try{zn(e.expiresAt,"expiresAt")}catch(e){if(e instanceof kt)throw new Error("expiresAt must be a valid ISO 8601 date string");throw e}if(tn(e.expiresAt)&&en(e.expiresAt)<=new Date)throw new Error("expiresAt must be in the future")}}(e),this.validateOptionalString(e.description,"description","Description",un.DESCRIPTION.MAX_LENGTH),this.validateOptionalDate(e.expiresAt,"expiresAt","Expiration date");const t=oe,n={};void 0!==e.description&&(n.description=e.description),void 0!==e.expiresAt&&(n.expiresAt=e.expiresAt);const a=await this.http.post(t,n,this.getDualAuthHeaders());return{invite:this.extractData(a)}}async listInvites(e={}){!function(e){if(void 0!==e.status&&!sl(e.status))throw Ut("status",e.status,Object.values(nl),"status");Mn(0,void 0,50,e.pageSize,e.cursor)}(e),this.validateStatusFilter(e.status,nl);const t=ce,n={...this.buildPaginationParams(e,ln.MAX_LIMIT)};void 0!==e.status&&(n.status=e.status);const a=await this.http.get(t,n,this.getDualAuthHeaders()),s=this.extractData(a);return{items:s.invites,pageInfo:s.pageInfo}}async getInviteByCode(e){this.validateInviteCodeFormat(e);const t=this.buildEndpoint(le,{code:e}),n=await this.http.get(t,{});return this.extractData(n)}async revokeInvite(e){ol(e);const t=this.buildEndpoint(ue,{id:String(e)});Mt(await this.http.delete(t,this.getDualAuthHeaders()),"Failed to revoke invite")}async claimInvite(e){this.validateInviteCodeFormat(e);const t=de,n={inviteCode:e},a=await this.http.post(t,n,this.getJwtHeaders());return{invite:this.extractData(a)}}async listOverseers(e={}){!function(e){if(void 0!==e.status&&!rl(e.status))throw Ut("status",e.status,Object.values(al),"status");Mn(0,void 0,50,e.pageSize,e.cursor)}(e),this.validateStatusFilter(e.status,al);const t=he,n={...this.buildPaginationParams(e,ln.MAX_LIMIT)};void 0!==e.status&&(n.status=e.status);const a=await this.http.get(t,n,this.getDualAuthHeaders()),s=this.extractData(a);return{items:s.overseers,pageInfo:s.pageInfo}}async createOverseerDirect(e){!function(e){if(null==e||"object"!=typeof e)throw new kt("Options are required");if(!Un(e.userAddress))throw new kt("userAddress is required and must be a non-empty string");try{oa(e.userAddress,"userAddress")}catch{throw new kt("Invalid wallet address format. Must be eth|..., 0x..., or client|... format")}if(void 0!==e.description){if("string"!=typeof e.description)throw new kt("description must be a string");if(e.description.length>255)throw new kt("description must be at most 255 characters")}}(e),this.validateWalletAddressFormat(e.userAddress),this.validateOptionalString(e.description,"description","Description",un.DESCRIPTION.MAX_LENGTH);const t=ge,n={userAddress:e.userAddress};void 0!==e.description&&(n.description=e.description);const a=await this.http.post(t,n,this.getDualAuthHeaders());return{overseer:this.extractData(a)}}async revokeOverseer(e){this.validateWalletAddressFormat(e);const t=this.buildEndpoint(me,{address:e});Mt(await this.http.delete(t,this.getDualAuthHeaders()),"Failed to revoke overseer")}async getMyStatus(){const e=pe,t=await this.http.get(e,{},this.getJwtHeaders());return this.extractData(t)}async getSummary(){const e=fe,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getBanStats(){const e=ye,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getTokenBanStats(){const e=ve,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getInviteStats(){const e=ke,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getFlagStats(){const e=be,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getUserStats(){const e=we,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 kt("Options are required");if(void 0!==e.search){if("string"!=typeof e.search)throw new kt("Search must be a string");if(0===e.search.length)throw new kt("Search query cannot be empty string")}if(void 0!==e.sortBy){if("string"!=typeof e.sortBy)throw new kt("Sort field must be a string");if(0===e.sortBy.length)throw new kt("Sort field cannot be empty string")}if(void 0!==e.sortOrder&&"asc"!==e.sortOrder&&"desc"!==e.sortOrder)throw new kt('Sort order must be "asc" or "desc"')}(t);const n=Se,a=this.buildPaginationParams(t,ln.MAX_LIMIT);void 0!==t.search&&""!==t.search&&(a.search=t.search),void 0!==t.sortBy&&""!==t.sortBy&&(a.sortBy=t.sortBy),void 0!==t.sortOrder&&(a.sortOrder=t.sortOrder);const s=await this.http.get(n,a,this.getDualAuthHeaders()),r=this.extractData(s);return{items:r.users,pageInfo:r.pageInfo}}async getOverseerUserSummary(e){if(!Un(e))throw Tt("address","User address");il(e);const t=this.buildEndpoint(Ae,{address:e}),n=await this.http.get(t,{},this.getDualAuthHeaders());return this.extractData(n)}async flushCacheByAddress(e){tl(e);const t=this.buildEndpoint(Ee,{address:e}),n=await this.http.delete(t,void 0,this.getDualAuthHeaders());return this.extractData(n)}async flushCacheByToken(e){!function(e){if(!Un(e))throw Tt("tokenName","Token name")}(e);const t=this.buildEndpoint(Te,{tokenName:e}),n=await this.http.delete(t,void 0,this.getDualAuthHeaders());return this.extractData(n)}async flushAllCache(e){!function(e){if(!0!==e)throw new kt("Safety confirmation required: must pass confirm=true to flush all cache","confirm","CONFIRMATION_REQUIRED")}(e);const t=Ce,n=await this.http.delete(t,{confirm:"true"},this.getDualAuthHeaders());return this.extractData(n)}async flushWalletAliasCache(e){if(void 0!==e){tl(e);const t=this.buildEndpoint(Ne,{address:e}),n=await this.http.delete(t,void 0,this.getDualAuthHeaders());return this.extractData(n)}const t=Ie,n=await this.http.delete(t,{confirm:"true"},this.getDualAuthHeaders());return this.extractData(n)}}class ll extends Xn{constructor(e,t,n=!1){super(e,n,t)}extractData(e){const t={status:200,error:"error"in e?e.error:"success"in e?!e.success:!("data"in e),data:e.data};return void 0!==e.message&&(t.message=e.message),Mt(t,"Platform config operation failed",!0),e.data}async getPlatformConfig(){const e=await this.http.get(R);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 kt(t.join("; "),"options","VALIDATION_FAILED");const n=await this.http.put(x,e,this.getJwtHeaders());return this.extractData(n)}async getAvailableRoles(){const e=await this.http.get(B);return this.extractData(e)}}class dl extends Xn{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(He),t=this.extractData(e);return this.logger.debug("Fetched platform stats",{totalTokens:t.totalTokens,timestamp:t.timestamp}),{stats:t}}}class ul extends Xn{constructor(e,t=!1,n){super(e,t),this.tokenResolverService=n}async fetchTokenClassKeyByTokenName(e){if(""===e)throw Tt("tokenName","Token name");if(!this.tokenResolverService)throw It("TokenResolverService is required for token name resolution. Ensure it is passed to PriceHistoryService constructor.","tokenResolverService");try{Gn(e)}catch(e){throw It(st(e),"tokenName")}this.logger.debug(`Resolving token name '${e}' to token class key`);try{const t=await this.tokenResolverService.resolveTokenToVault(e);if(null==t)throw It(`Token '${e}' not found or could not be resolved to vault address`,"tokenName");this.logger.debug(`Resolved '${e}' to vault address: ${t}`);const n=Ms($i(t));return this.logger.debug(`Extracted token class key: ${n}`),n}catch(t){if(at(t)&&st(t).includes("ConfigurationError"))throw t;throw Nt(`Failed to resolve token name '${e}': ${st(t)}`,500)}}async fetchPriceHistory(e){if(null==e)throw Tt("options","Fetch options");return this.logger.debug("Fetching price history from DEX Backend API with options:",e),this.validateOptions(e),await _s(async()=>{let t=e.tokenId;if(null!==e.tokenName&&void 0!==e.tokenName){this.logger.debug(`Resolving token name '${e.tokenName}' to token ID`);const n=await this.fetchTokenClassKeyByTokenName(e.tokenName);t=n,this.logger.debug(`Resolved to token ID: ${n}`)}if(null==t)throw It("Token ID is required but was not provided or resolved","tokenId");const{normalizeToTokenInstanceKey:n}=await Promise.resolve().then(function(){return Hi}),a=mo(Ms(n(t))),{from:s,to:r,sortOrder:i="DESC"}=e,o=e.timeframe??this.inferTimeframe(s,r),c={token:a,timeframe:o};this.logger.debug(`Querying price series for token ${a}, timeframe ${o}`);const l=await this.http.get(k,c);if(null==l)throw Nt("No response from price history service",500);const d=this.transformApiResponseToPriceHistory(l,e,i);return this.logger.debug(`Found ${d.snapshots.length} price snapshots, total ${d.total}`),d},"Failed to fetch price history",this.logger)}transformApiResponseToPriceHistory(e,t,n){if(!Array.isArray(e.prices))throw Nt("Invalid API response: missing price series",500);const a="string"==typeof t.tokenId?t.tokenId:t.tokenName??Ms(t.tokenId),s=t.from?.getTime(),r=t.to?.getTime(),i=e.prices.filter(e=>"number"==typeof e.time&&"number"==typeof e.price).filter(e=>(void 0===s||1e3*e.time>=s)&&(void 0===r||1e3*e.time<=r)).sort((e,t)=>"ASC"===n?e.time-t.time:t.time-e.time),o=En(t.offset,0),c=En(t.pageSize??t.limit,10),l=i.slice(o,o+c).map(e=>({price:String(e.price),timestamp:new Date(1e3*e.time),tokenId:a})),d=Math.max(1,Math.ceil(i.length/c)),u=Math.floor(o/c)+1;return{snapshots:l,page:u,limit:c,total:i.length,totalPages:d,hasNext:u<d,hasPrevious:u>1}}async fetchAllPriceHistory(e){if(null==e)throw Tt("options","Fetch options");return this.logger.debug("Fetching all price history with options:",e),_s(async()=>{const t=await Mi((t,n)=>this.fetchPriceHistory({...e,offset:t,limit:n}).then(e=>({items:e.snapshots,page:e.page,limit:e.limit,total:e.total,totalPages:e.totalPages,hasNext:e.hasNext,hasPrevious:e.hasPrevious})),{maxPages:1e4,logger:this.logger,pageSize:50,startPage:0});return function(e,t=e.length,n="items"){const a=e.length;return{offset:0,limit:a,total:t,totalPages:0!==a?Si(t,a):void 0,hasNext:!1,hasPrevious:!1,[n]:e}}(t.items,t.total,"snapshots")},"Failed to fetch all price history",this.logger)}validateOptions(e){const{from:t,to:n,sortOrder:a}=e;if(Kn(e,"tokenName","tokenId",{description:"token identifier"}),t&&!tn(t))throw It("from must be a valid Date","from");if(void 0!==n&&!tn(n))throw It("to must be a valid Date","to");null!=a&&function(e,t){if("ASC"!==e&&"DESC"!==e)throw new kt(`${t} must be either 'ASC' or 'DESC'`,t,"INVALID_ENUM_VALUE")}(a,"sortOrder"),Mn(0,void 0,50,e.pageSize)}inferTimeframe(e,t){if(void 0===e||void 0===t)return"1M";const n=Math.max(0,t.getTime()-e.getTime())/864e5;return n<=1?"1D":n<=7?"1W":n<=31?"1M":n<=365?"1Y":"ALL"}}class hl extends Ni{constructor(e,t,n,a){super(e,t,n,!1,a)}async getRestrictedNames(){try{return{success:!0,data:(await this.http.get(Pe)).data}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}async updateRestrictedNames(e){try{if(!Un(e.content))throw new kt("Content is required");return{success:!0,data:(await this.http.put(Me,e)).data}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}}class gl extends Ni{constructor(e,t,n,a=!1,s){super(e,t,n,a,s)}async getChatStatus(e){if(null==e||""===e)throw Tt("tokenName","Token name");return this.validateTokenName(e,an),_s(async()=>{const t=this.buildEndpoint(Le,{tokenName:e}),n=await this.http.get(t);return this.buildChatStatusResult(e,this.extractData(n))},`Failed to get chat status for token: ${e}`,this.logger)}async disableChat(e){if(null==e||""===e)throw Tt("tokenName","Token name");return this.validateTokenName(e,an),_s(async()=>{const t=this.buildEndpoint(Ke,{tokenName:e}),n=await this.http.post(t,{enabled:!1},this.getDualAuthHeaders());return this.buildChatStatusResult(e,this.extractData(n))},`Failed to disable chat for token: ${e}`,this.logger)}async enableChat(e){if(null==e||""===e)throw Tt("tokenName","Token name");return this.validateTokenName(e,an),_s(async()=>{const t=this.buildEndpoint($e,{tokenName:e}),n=await this.http.post(t,{enabled:!0},this.getDualAuthHeaders());return this.buildChatStatusResult(e,this.extractData(n))},`Failed to enable chat for token: ${e}`,this.logger)}buildChatStatusResult(e,t){const n={enabled:t.enabled,tokenName:t.tokenName??zt(e)};return void 0!==t.status&&null!==t.status&&(n.status=t.status),n}async setSlowMode(e,t){if(null==e||""===e)throw Tt("tokenName","Token name");if(this.validateTokenName(e,an),"number"!=typeof t||t<0||t>600)throw new Error("slowModeSeconds must be a number between 0 and 600");return _s(async()=>{const n=this.buildEndpoint(Ge,{tokenName:e}),a=await this.http.patch(n,{slowModeSeconds:t},this.getDualAuthHeaders());return this.extractData(a)},`Failed to set slow mode for token: ${e}`,this.logger)}}class ml extends Qn{constructor(e=!1){super(e),this.eventRegistry=this.createEmptyRegistry()}setSocket(e){this.logger.debug("📡 [Events] Socket attached to StreamingEventService")}clearSocket(){this.logger.debug("📡 [Events] Socket cleared from StreamingEventService")}createEmptyRegistry(){return{stream_status:new Set,user_banned:new Set,user_unbanned:new Set,ban_enforcement:new Set,content_flagged:new Set,flag_resolved:new Set,stream_chat_message:new Set,stream_chat_updated:new Set,stream_chat_deleted:new Set,stream_chat_pinned:new Set,stream_chat_unpinned:new Set,chat_status_changed:new Set,viewer_count:new Set,recording_status:new Set,simulcast_status:new Set,download_ready:new Set,recordings_count_updated:new Set,user_typing:new Set,stream_reaction:new Set,content_reaction_added:new Set,content_reaction_removed:new Set,stream_countdown_updated:new Set,stream_language_updated:new Set,stream_control_status_changed:new Set,connection:new Set,authenticated:new Set,token_subscribed:new Set,token_unsubscribed:new Set,room_subscribed:new Set,room_left:new Set}}registerCallback(e,t){const n=this.eventRegistry[e];return n.add(t),()=>{n.delete(t)}}async emitEvent(e,t){const n=this.eventRegistry[e];if(0!==n.size)for(const a of n)try{const e=a(t);e instanceof Promise&&await e}catch(t){this.logger.error(`Error in ${e} callback:`,t instanceof Error?t.message:String(t))}}onStreamStatusChanged(e){return this.registerCallback("stream_status",e)}onUserBanned(e){return this.registerCallback("user_banned",e)}onUserUnbanned(e){return this.registerCallback("user_unbanned",e)}onBanEnforcement(e){return this.registerCallback("ban_enforcement",e)}onContentFlagged(e){return this.registerCallback("content_flagged",e)}onFlagResolved(e){return this.registerCallback("flag_resolved",e)}onStreamChatMessage(e){return this.registerCallback("stream_chat_message",e)}onStreamChatUpdated(e){return this.registerCallback("stream_chat_updated",e)}onStreamChatDeleted(e){return this.registerCallback("stream_chat_deleted",e)}onStreamChatPinned(e){return this.registerCallback("stream_chat_pinned",e)}onStreamChatUnpinned(e){return this.registerCallback("stream_chat_unpinned",e)}onChatStatusChanged(e){return this.registerCallback("chat_status_changed",e)}onViewerCountChanged(e){return this.registerCallback("viewer_count",e)}onRecordingStatusChanged(e){return this.registerCallback("recording_status",e)}onSimulcastStatusChanged(e){return this.registerCallback("simulcast_status",e)}onDownloadReady(e){return this.registerCallback("download_ready",e)}onRecordingsCountUpdated(e){return this.registerCallback("recordings_count_updated",e)}onUserTyping(e){return this.registerCallback("user_typing",e)}onStreamReaction(e){return this.registerCallback("stream_reaction",e)}onContentReactionAdded(e){return this.registerCallback("content_reaction_added",e)}onContentReactionRemoved(e){return this.registerCallback("content_reaction_removed",e)}onStreamCountdownUpdated(e){return this.registerCallback("stream_countdown_updated",e)}onStreamLanguageUpdated(e){return this.registerCallback("stream_language_updated",e)}onStreamControlStatusChanged(e){return this.registerCallback("stream_control_status_changed",e)}onConnection(e){return this.registerCallback("connection",e)}onAuthenticated(e){return this.registerCallback("authenticated",e)}onTokenSubscribed(e){return this.registerCallback("token_subscribed",e)}onTokenUnsubscribed(e){return this.registerCallback("token_unsubscribed",e)}onRoomSubscribed(e){return this.registerCallback("room_subscribed",e)}onRoomLeft(e){return this.registerCallback("room_left",e)}async emitStreamStatusChanged(e){await this.emitEvent("stream_status",e)}async emitUserBanned(e){await this.emitEvent("user_banned",e)}async emitUserUnbanned(e){await this.emitEvent("user_unbanned",e)}async emitBanEnforcement(e){await this.emitEvent("ban_enforcement",e)}async emitContentFlagged(e){await this.emitEvent("content_flagged",e)}async emitFlagResolved(e){await this.emitEvent("flag_resolved",e)}async emitStreamChatMessage(e){await this.emitEvent("stream_chat_message",e)}async emitStreamChatUpdated(e){await this.emitEvent("stream_chat_updated",e)}async emitStreamChatDeleted(e){await this.emitEvent("stream_chat_deleted",e)}async emitStreamChatPinned(e){await this.emitEvent("stream_chat_pinned",e)}async emitStreamChatUnpinned(e){await this.emitEvent("stream_chat_unpinned",e)}async emitChatStatusChanged(e){await this.emitEvent("chat_status_changed",e)}async emitViewerCountChanged(e){await this.emitEvent("viewer_count",e)}async emitRecordingStatusChanged(e){await this.emitEvent("recording_status",e)}async emitSimulcastStatusChanged(e){await this.emitEvent("simulcast_status",e)}async emitDownloadReady(e){await this.emitEvent("download_ready",e)}async emitRecordingsCountUpdated(e){await this.emitEvent("recordings_count_updated",e)}async emitUserTyping(e){await this.emitEvent("user_typing",e)}async emitStreamReaction(e){await this.emitEvent("stream_reaction",e)}async emitContentReactionAdded(e){await this.emitEvent("content_reaction_added",e)}async emitContentReactionRemoved(e){await this.emitEvent("content_reaction_removed",e)}async emitStreamCountdownUpdated(e){await this.emitEvent("stream_countdown_updated",e)}async emitStreamLanguageUpdated(e){await this.emitEvent("stream_language_updated",e)}async emitStreamControlStatusChanged(e){await this.emitEvent("stream_control_status_changed",e)}async emitConnection(e){await this.emitEvent("connection",e)}async emitAuthenticated(e){await this.emitEvent("authenticated",e)}async emitTokenSubscribed(e){await this.emitEvent("token_subscribed",e)}async emitTokenUnsubscribed(e){await this.emitEvent("token_unsubscribed",e)}async emitRoomSubscribed(e){await this.emitEvent("room_subscribed",e)}async emitRoomLeft(e){await this.emitEvent("room_left",e)}}Ln({IDLE:"IDLE",ACTIVE:"ACTIVE",DISABLED:"DISABLED"}),Ln({READY:"READY",PROCESSING:"PROCESSING",ERRORED:"ERRORED",DELETED:"DELETED"});const pl=Ln({YOUTUBE:"YOUTUBE",TWITCH:"TWITCH",FACEBOOK:"FACEBOOK",CUSTOM:"CUSTOM"});const fl={OWNER:"OWNER",MANAGER:"MANAGER",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MODERATOR:"MODERATOR"};Ln(fl),Ln({OWNER:"OWNER",MODERATOR:"MODERATOR"});function yl(e,t="tokenName"){Gn(e,t,an)}function vl(e){if(yl(e.tokenName),!Un(e.language))throw Tt("language");if(t=e.language,!Un(t)||!/^[a-z]{2}(-[A-Z]{2})?$/.test(t))throw new kt('language must be a valid ISO 639-1 code (e.g., "en", "es", "zh-CN")',"language",ft);var t}Ln({...fl,OVERSEER:"OVERSEER"});class kl extends Ni{constructor(e,t,n,a=!1,s){super(e,t,n,a,s)}async startStream(e){this.validateTokenName(e,an);const t=this.buildEndpoint(b,{tokenName:e}),n=await this.http.post(t,{},this.getJwtHeaders());return this.extractData(n)}async stopStream(e){this.validateTokenName(e,an);const t=this.buildEndpoint(w,{tokenName:e});await this.http.post(t,{},this.getJwtHeaders())}async disableStream(e){return this.toggleFeature(e,S,an)}async enableStream(e){return this.toggleFeature(e,A,an)}async resetStreamKey(e){this.validateTokenName(e,an);const t=this.buildEndpoint(E,{tokenName:e}),n=await this.http.post(t,{},this.getJwtHeaders());return this.extractData(n)}async getStreamCredentials(e){this.validateTokenName(e,an);const t=this.buildEndpoint(P,{tokenName:e}),n=await this.http.get(t,{},this.getJwtHeaders());return this.extractData(n)}async getRecordings(e){!function(e){yl(e.tokenName),Mn(0,void 0,vn,e.pageSize)}(e);const t=this.buildEndpoint(T,{tokenName:e.tokenName}),n=this.buildPaginationParams(e,vn),a=e.offset;"number"==typeof a&&(n.offset=String(a));const s=await this.http.get(t,n),r=this.extractData(s),i=e,o=r.pageSize??r.limit??e.pageSize??("number"==typeof i.limit?i.limit:20),c="number"==typeof i.offset?i.offset:0,l=Math.floor(c/o)+1;return{recordings:r.recordings,tokenName:zt(e.tokenName),page:r.page??l,limit:o,total:r.total,hasNext:r.recordings.length===o}}async getRecordingDownload(e,t){this.validateTokenName(e,an),this.validateRequiredString(t,"assetId","Asset ID");const n=this.buildEndpoint(C,{tokenName:e,assetId:t}),a=await this.http.get(n,{},this.getJwtHeaders());return this.extractData(a)}async deleteRecording(e,t){this.validateTokenName(e,an),this.validateRequiredString(t,"assetId","Asset ID");const n=this.buildEndpoint(N,{tokenName:e,assetId:t});await this.http.delete(n,void 0,this.getJwtHeaders())}async getSimulcastTargets(e){this.validateTokenName(e,an);const t=this.buildEndpoint(I,{tokenName:e}),n=await this.http.get(t);return this.extractData(n)}async addSimulcastTarget(e){!function(e){if(yl(e.tokenName),!Un(e.platform))throw Tt("platform");if(!pl(e.platform))throw new kt("platform must be one of: 'YOUTUBE', 'TWITCH', 'FACEBOOK', 'CUSTOM'","platform",pt);if(!Un(e.rtmpUrl))throw Tt("rtmpUrl");if(!yn.STREAM_URL_PATTERN.test(e.rtmpUrl))throw new kt("rtmpUrl must be a valid RTMP, RTMPS, or SRT URL","rtmpUrl",ft);if(!Un(e.streamKey))throw Tt("streamKey");if(void 0!==e.name&&"string"!=typeof e.name)throw new kt("name must be a string","name",mt)}(e);const t=this.buildEndpoint(D,{tokenName:e.tokenName}),n=await this.http.post(t,{platform:e.platform,rtmpUrl:e.rtmpUrl,streamKey:e.streamKey,name:e.name},this.getJwtHeaders());return this.extractData(n)}async removeSimulcastTarget(e,t){this.validateTokenName(e,an),this.validateRequiredString(t,"targetId","Target ID");const n=this.buildEndpoint(_,{tokenName:e,targetId:t});await this.http.delete(n,void 0,this.getJwtHeaders())}async getGlobalStreamingStatus(){const e=await this.http.get(R);return this.extractData(e)}async disableGlobalStreaming(){const e=await this.http.put(x,{},this.getAdminHeaders());return this.extractData(e)}async enableGlobalStreaming(){const e=await this.http.put(O,{},this.getAdminHeaders());return this.extractData(e)}async setNextLiveStream(e){let t;!function(e){if(yl(e.tokenName),null!==e.nextLiveStreamAt){if(!(e.nextLiveStreamAt instanceof Date||Un(e.nextLiveStreamAt)))throw new kt("nextLiveStreamAt must be a Date, ISO 8601 string, or null","nextLiveStreamAt",mt);if("string"==typeof e.nextLiveStreamAt){const t=Date.parse(e.nextLiveStreamAt);if(isNaN(t))throw new kt("nextLiveStreamAt must be a valid ISO 8601 date string","nextLiveStreamAt",ft)}}}(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,an);const t=`/v1/tokens/${e.toLowerCase().trim()}`;await this.http.patch(t,{nextLiveStreamAt:null},this.getJwtHeaders())}async setStreamLanguage(e){vl(e);const t=`/v1/tokens/${e.tokenName.toLowerCase().trim()}`;await this.http.patch(t,{streamLanguage:e.language},this.getJwtHeaders())}async getStreamRole(e){!function(e){yl(e.tokenName)}(e);const t=this.buildEndpoint(F,{tokenName:e.tokenName}),n=this.jwtAuth?this.getJwtHeaders():{},a=await this.http.get(t,{},n);return this.extractData(a)}async getAvailableRoles(){const e=await this.http.get(B);return this.extractData(e)}async getTokenAccess(e){!function(e){yl(e.tokenName)}(e);const t=await this.http.get(U,{tokenName:zt(e.tokenName)},this.getJwtHeaders());return this.extractData(t)}async setNextLiveStreamCountdown(e,t){return this.setNextLiveStream({tokenName:e,nextLiveStreamAt:t})}}const bl="subscribe_token",wl="unsubscribe_token",Sl="authenticate",Al="send_stream_chat",El="SEND_STREAM_REACTION",Tl="typing_start",Cl="typing_stop",Nl="STREAM_STATUS",Il="STREAM_COUNTDOWN_UPDATED",Dl="STREAM_LANGUAGE_UPDATED",_l="VIEWER_COUNT",Rl="token_subscribed",xl="token_unsubscribed",Ol="STREAM_GLOBAL_STATUS",Fl="ENGAGEMENT_STATS_UPDATED",Bl="STREAM_CHAT_MESSAGE",Ul="STREAM_CHAT_SENT",Pl="stream_chat_error",Ml="CHAT_STATUS_CHANGED",Ll="STREAM_CHAT_GLOBAL_STATUS",$l="authenticated",Kl="stream_chat_auth_error",Gl="STREAM_REACTION",Wl="stream_reaction_error",Hl="USER_TYPING",ql="STREAM_CHAT_PINNED",zl="STREAM_CHAT_UNPINNED",jl="COMMENT_CREATED",Vl="TOKEN_BANNED",Xl="TOKEN_UNBANNED",Ql="MODERATOR_INVITE_CREATED",Jl="MODERATOR_ADDED",Yl="MODERATOR_REMOVED",Zl="MODERATOR_ROLE_UPDATED",ed="OVERSEER_ADDED",td="OVERSEER_REMOVED",nd="TRADE_EXECUTED",ad="BALANCE_UPDATED",sd="STATS_UPDATED",rd="POOL_METADATA_UPDATED",id="POOL_SOCIAL_LINKS_UPDATED",od="POOL_BADGE_ASSIGNED",cd="HOLDER_COUNT_UPDATED",ld="USER_PROFILE_UPDATED",dd="API_KEY_CREATED",ud="API_KEY_UPDATED",hd="API_KEY_REVOKED",gd="TOKEN_CONFIG_UPDATED",md="SITE_CONFIG_CHANGED",pd="COMMENTS_GLOBAL_STATUS",fd="WEBHOOKS_GLOBAL_STATUS",yd="subscribe_global_feed",vd="unsubscribe_global_feed",kd="global_feed_subscribed",bd="global_feed_unsubscribed";class wd extends Qn{constructor(e,t=!1){if(super(t),this.socket=null,this.isAuthenticated=!1,this.subscribedRooms=new Map,this.roomCallbacks=new Map,this.pendingSubscriptions=new Map,this.eventBuffer=new Map,this.eventBufferTimeouts=new Map,this.MAX_BUFFER_SIZE=100,this.BUFFER_CLEANUP_MS=3e4,this.globalCallbacks={},this.isGlobalFeedSubscribed=!1,this.globalFeedCallbacks={},this.pendingGlobalFeedSubscription=null,""===e.url)throw new wt("Stream WebSocket URL is required. Set streamWebSocketUrl in SDK config.");this.config={url:e.url,authToken:e.authToken??"",reconnectAttempts:e.reconnectAttempts??5,reconnectDelay:e.reconnectDelay??2e3,subscriptionTimeout:e.subscriptionTimeout??1e4},this.reconnectionManager=new Sc({maxAttempts:this.config.reconnectAttempts,baseDelayMs:this.config.reconnectDelay}),this.isSocketIOAvailable=this.checkSocketIOAvailability()}checkSocketIOAvailability(){try{return"function"==typeof u.io||(this.logger.warn('⚠️ Socket.IO client not available. Install "socket.io-client" package.'),!1)}catch(e){return this.logger.warn("⚠️ Socket.IO availability check failed:",st(e)),!1}}getRoomName(e){return`token:${zt(e)}`}bufferEvent(e,t,n){const a=`${e}:${t}`;let s=this.eventBuffer.get(a);s||(s=[],this.eventBuffer.set(a,s)),s.length>=this.MAX_BUFFER_SIZE&&(s.shift(),this.logger.warn(`⚠️ [Stream Buffer] Event buffer overflow for ${a} - dropping oldest event. Consider processing events faster or increasing buffer size.`)),s.push(n);const r=this.eventBufferTimeouts.get(a);r&&clearTimeout(r);const i=setTimeout(()=>{this.eventBuffer.delete(a),this.eventBufferTimeouts.delete(a),this.logger.debug(`📡 [Stream Buffer] Cleaned up buffer for ${a}`)},this.BUFFER_CLEANUP_MS);this.eventBufferTimeouts.set(a,i)}processBufferedEvents(e,t){const n=zt(e),a=[{key:`${Nl}:${n}`,callback:t.onStreamStatus},{key:`${_l}:${n}`,callback:t.onViewerCount},{key:`${Bl}:${n}`,callback:t.onChatMessage},{key:`${Ml}:${n}`,callback:t.onChatStatus},{key:`${ql}:${n}`,callback:t.onChatPinned},{key:`${zl}:${n}`,callback:t.onChatUnpinned},{key:`${Il}:${n}`,callback:t.onCountdownUpdated},{key:`${Dl}:${n}`,callback:t.onLanguageUpdated},{key:`${Vl}:${n}`,callback:t.onTokenBanned},{key:`${Xl}:${n}`,callback:t.onTokenUnbanned},{key:`${Ql}:${n}`,callback:t.onModeratorInviteCreated},{key:`${Jl}:${n}`,callback:t.onModeratorAdded},{key:`${Yl}:${n}`,callback:t.onModeratorRemoved},{key:`${Zl}:${n}`,callback:t.onModeratorRoleUpdated},{key:`${nd}:${n}`,callback:t.onTradeExecuted},{key:`${ad}:${n}`,callback:t.onBalanceUpdated},{key:`${rd}:${n}`,callback:t.onPoolMetadataUpdated},{key:`${id}:${n}`,callback:t.onPoolSocialLinksUpdated},{key:`${od}:${n}`,callback:t.onPoolBadgeAssigned},{key:`${cd}:${n}`,callback:t.onHolderCountUpdated},{key:`${jl}:${n}`,callback:t.onCommentCreated}];for(const{key:e,callback:t}of a){const n=this.eventBuffer.get(e);if(n&&t){this.logger.debug(`📡 [Stream Buffer] Delivering ${n.length} buffered events for ${e}`);for(const a of n)try{t(a)}catch(t){this.logger.error(`Error delivering buffered event for ${e}:`,t)}this.eventBuffer.delete(e);const a=this.eventBufferTimeouts.get(e);a&&(clearTimeout(a),this.eventBufferTimeouts.delete(e))}}}setupGlobalListeners(){this.socket&&(this.socket.on(Nl,e=>{this.logger.debug(`📡 [Stream Status] ${e.tokenName}: ${e.status}`),this.bufferEvent(Nl,e.tokenName,e);const t=this.roomCallbacks.get(zt(e.tokenName));t?.onStreamStatus&&t.onStreamStatus(e),this.globalCallbacks.onStreamStatus&&this.globalCallbacks.onStreamStatus(e),this.isGlobalFeedSubscribed&&!t&&this.globalFeedCallbacks.onStreamStatus&&this.globalFeedCallbacks.onStreamStatus(e)}),this.socket.on(Rl,e=>{this.logger.debug(`📡 [Subscribed] ${e.tokenName}`);const t=zt(e.tokenName),n=this.pendingSubscriptions.get(t);n&&(clearTimeout(n.timeoutId),this.pendingSubscriptions.delete(t),n.resolve(e));const a=this.roomCallbacks.get(t);a?.onStreamSubscribed&&a.onStreamSubscribed(e)}),this.socket.on(xl,e=>{const t=e.room.replace("token:","");this.logger.debug(`📡 [Unsubscribed] ${t}`);const n=this.roomCallbacks.get(zt(t));n?.onStreamUnsubscribed&&n.onStreamUnsubscribed(e)}),this.socket.on(_l,e=>{this.logger.debug(`📡 [Viewer Count] ${e.tokenName}: ${e.viewerCount}`),this.bufferEvent(_l,e.tokenName,e);const t=this.roomCallbacks.get(zt(e.tokenName));t?.onViewerCount&&t.onViewerCount(e),this.globalCallbacks.onViewerCount&&this.globalCallbacks.onViewerCount(e),this.isGlobalFeedSubscribed&&!t&&this.globalFeedCallbacks.onViewerCount&&this.globalFeedCallbacks.onViewerCount(e)}),this.socket.on(Ol,e=>{this.logger.debug(`📡 [Global Stream Status] enabled: ${String(e.enabled)}`),this.globalCallbacks.onStreamGlobalStatus&&this.globalCallbacks.onStreamGlobalStatus(e)}),this.socket.on(Bl,e=>{this.logger.debug(`📡 [Chat Message] ${e.tokenName}: ${e.content.slice(0,50)}...`),this.bufferEvent(Bl,e.tokenName,e);const t=this.roomCallbacks.get(zt(e.tokenName));t?.onChatMessage&&t.onChatMessage(e),this.globalCallbacks.onChatMessage&&this.globalCallbacks.onChatMessage(e)}),this.socket.on(Ul,e=>{this.logger.debug(`📡 [Chat Sent] ${e.tokenName}: ${e.messageId}`);const t=this.roomCallbacks.get(zt(e.tokenName));t?.onChatSent&&t.onChatSent(e)}),this.socket.on(Pl,e=>{this.logger.error(`📡 [Chat Error] ${e.tokenName}: ${e.message}`);const t=this.roomCallbacks.get(zt(e.tokenName));t?.onChatError&&t.onChatError(e),this.globalCallbacks.onChatError&&this.globalCallbacks.onChatError(e)}),this.socket.on(Ml,e=>{this.logger.debug(`📡 [Chat Status] ${e.tokenName}: ${String(e.enabled)}`),this.bufferEvent(Ml,e.tokenName,e);const t=this.roomCallbacks.get(zt(e.tokenName));t?.onChatStatus&&t.onChatStatus(e),this.globalCallbacks.onChatStatus&&this.globalCallbacks.onChatStatus(e)}),this.socket.on(Ll,e=>{this.logger.debug(`📡 [Global Chat Status] enabled: ${String(e.enabled)}`),this.globalCallbacks.onChatGlobalStatus&&this.globalCallbacks.onChatGlobalStatus(e)}),this.socket.on($l,e=>{this.logger.debug(`📡 [Authenticated] ${e.address}`),this.isAuthenticated=!0,this.globalCallbacks.onChatAuthenticated&&this.globalCallbacks.onChatAuthenticated(e)}),this.socket.on(Kl,e=>{this.logger.error(`📡 [Auth Error] ${e.message}`),this.isAuthenticated=!1,this.globalCallbacks.onChatAuthError&&this.globalCallbacks.onChatAuthError(e)}),this.socket.on(Gl,e=>{this.logger.debug(`📡 [Reaction] ${e.tokenName}: ${e.emoji}`);const t=this.roomCallbacks.get(zt(e.tokenName));t?.onReaction&&t.onReaction(e),this.globalCallbacks.onReaction&&this.globalCallbacks.onReaction(e)}),this.socket.on(Wl,e=>{this.logger.error(`📡 [Reaction Error] ${e.tokenName}: ${e.message}`);const t=this.roomCallbacks.get(zt(e.tokenName));t?.onReactionError&&t.onReactionError(e),this.globalCallbacks.onReactionError&&this.globalCallbacks.onReactionError(e)}),this.socket.on(Hl,e=>{const t=e.typingUsers.length;this.logger.debug(`📡 [Typing] ${e.tokenName}: ${t} user(s) typing`);const n=this.roomCallbacks.get(zt(e.tokenName));n?.onTypingIndicator&&n.onTypingIndicator(e),this.globalCallbacks.onTypingIndicator&&this.globalCallbacks.onTypingIndicator(e)}),this.socket.on(ql,e=>{this.logger.debug(`📡 [Chat Pinned] ${e.tokenName}: ${e.pinnedMessage.messageId}`),this.bufferEvent(ql,e.tokenName,e);const t=this.roomCallbacks.get(zt(e.tokenName));t?.onChatPinned&&t.onChatPinned(e),this.globalCallbacks.onChatPinned&&this.globalCallbacks.onChatPinned(e)}),this.socket.on(zl,e=>{this.logger.debug(`📡 [Chat Unpinned] ${e.tokenName}: ${e.unpinnedMessageId}`),this.bufferEvent(zl,e.tokenName,e);const t=this.roomCallbacks.get(zt(e.tokenName));t?.onChatUnpinned&&t.onChatUnpinned(e),this.globalCallbacks.onChatUnpinned&&this.globalCallbacks.onChatUnpinned(e)}),this.socket.on(Il,e=>{const t=e.nextLiveStreamAt??"cleared";this.logger.debug(`📡 [Countdown Updated] ${e.tokenName}: ${t}`),this.bufferEvent(Il,e.tokenName,e);const n=this.roomCallbacks.get(zt(e.tokenName));n?.onCountdownUpdated&&n.onCountdownUpdated(e),this.globalCallbacks.onCountdownUpdated&&this.globalCallbacks.onCountdownUpdated(e)}),this.socket.on(Dl,e=>{this.logger.debug(`📡 [Language Updated] ${e.tokenName}: ${e.language}`),this.bufferEvent(Dl,e.tokenName,e);const t=this.roomCallbacks.get(zt(e.tokenName));t?.onLanguageUpdated&&t.onLanguageUpdated(e),this.globalCallbacks.onLanguageUpdated&&this.globalCallbacks.onLanguageUpdated(e)}),this.socket.on(Vl,e=>{this.logger.debug(`📡 [Token Banned] ${e.tokenName}`),this.bufferEvent(Vl,e.tokenName,e);const t=this.roomCallbacks.get(zt(e.tokenName));t?.onTokenBanned&&t.onTokenBanned(e),this.globalCallbacks.onTokenBanned&&this.globalCallbacks.onTokenBanned(e)}),this.socket.on(Xl,e=>{this.logger.debug(`📡 [Token Unbanned] ${e.tokenName}`),this.bufferEvent(Xl,e.tokenName,e);const t=this.roomCallbacks.get(zt(e.tokenName));t?.onTokenUnbanned&&t.onTokenUnbanned(e),this.globalCallbacks.onTokenUnbanned&&this.globalCallbacks.onTokenUnbanned(e)}),this.socket.on(Ql,e=>{this.logger.debug(`📡 [Moderator Invite Created] ${e.tokenName}: by ${e.invitedBy}`),this.bufferEvent(Ql,e.tokenName,e);const t=this.roomCallbacks.get(zt(e.tokenName));t?.onModeratorInviteCreated&&t.onModeratorInviteCreated(e)}),this.socket.on(Jl,e=>{this.logger.debug(`📡 [Moderator Added] ${e.tokenName}: ${e.userAddress}`),this.bufferEvent(Jl,e.tokenName,e);const t=this.roomCallbacks.get(zt(e.tokenName));t?.onModeratorAdded&&t.onModeratorAdded(e)}),this.socket.on(Yl,e=>{this.logger.debug(`📡 [Moderator Removed] ${e.tokenName}: ${e.userAddress}`),this.bufferEvent(Yl,e.tokenName,e);const t=this.roomCallbacks.get(zt(e.tokenName));t?.onModeratorRemoved&&t.onModeratorRemoved(e)}),this.socket.on(Zl,e=>{this.logger.debug(`📡 [Moderator Role Updated] ${e.tokenName}: ${e.userAddress}`),this.bufferEvent(Zl,e.tokenName,e);const t=this.roomCallbacks.get(zt(e.tokenName));t?.onModeratorRoleUpdated&&t.onModeratorRoleUpdated(e)}),this.socket.on(ed,e=>{this.logger.debug(`📡 [Overseer Added] ${e.userAddress}`),this.globalCallbacks.onOverseerAdded&&this.globalCallbacks.onOverseerAdded(e)}),this.socket.on(td,e=>{this.logger.debug(`📡 [Overseer Removed] ${e.userAddress}`),this.globalCallbacks.onOverseerRemoved&&this.globalCallbacks.onOverseerRemoved(e)}),this.socket.on(nd,e=>{this.logger.debug(`📡 [Trade Executed] ${e.tokenName}: ${e.tradeType}`),this.bufferEvent(nd,e.tokenName,e);const t=this.roomCallbacks.get(zt(e.tokenName));t?.onTradeExecuted&&t.onTradeExecuted(e),this.isGlobalFeedSubscribed&&!t&&this.globalFeedCallbacks.onTradeExecuted&&this.globalFeedCallbacks.onTradeExecuted(e)}),this.socket.on(ad,e=>{this.logger.debug(`📡 [Balance Updated] ${e.tokenName}: ${e.tradeType}`),this.bufferEvent(ad,e.tokenName,e);const t=this.roomCallbacks.get(zt(e.tokenName));t?.onBalanceUpdated&&t.onBalanceUpdated(e)}),this.socket.on(rd,e=>{this.logger.debug(`📡 [Pool Metadata Updated] ${e.tokenName}`),this.bufferEvent(rd,e.tokenName,e);const t=this.roomCallbacks.get(zt(e.tokenName));t?.onPoolMetadataUpdated&&t.onPoolMetadataUpdated(e)}),this.socket.on(id,e=>{this.logger.debug(`📡 [Pool Social Links Updated] ${e.tokenName}`),this.bufferEvent(id,e.tokenName,e);const t=this.roomCallbacks.get(zt(e.tokenName));t?.onPoolSocialLinksUpdated&&t.onPoolSocialLinksUpdated(e)}),this.socket.on(od,e=>{this.logger.debug(`📡 [Pool Badge Assigned] ${e.tokenName}: ${e.badge}`),this.bufferEvent(od,e.tokenName,e);const t=this.roomCallbacks.get(zt(e.tokenName));t?.onPoolBadgeAssigned&&t.onPoolBadgeAssigned(e),this.isGlobalFeedSubscribed&&!t&&this.globalFeedCallbacks.onPoolBadgeAssigned&&this.globalFeedCallbacks.onPoolBadgeAssigned(e)}),this.socket.on(cd,e=>{this.logger.debug(`📡 [Holder Count Updated] ${e.tokenName}: ${e.holderCount}`),this.bufferEvent(cd,e.tokenName,e);const t=this.roomCallbacks.get(zt(e.tokenName));t?.onHolderCountUpdated&&t.onHolderCountUpdated(e),this.isGlobalFeedSubscribed&&!t&&this.globalFeedCallbacks.onHolderCountUpdated&&this.globalFeedCallbacks.onHolderCountUpdated(e)}),this.socket.on(jl,e=>{this.logger.debug(`📡 [Comment Created] ${e.tokenName}: ID ${e.id}`),this.bufferEvent(jl,e.tokenName,e);const t=this.roomCallbacks.get(zt(e.tokenName));t?.onCommentCreated&&t.onCommentCreated(e)}),this.socket.on(ld,e=>{this.logger.debug(`📡 [User Profile Updated] ${e.userAddress}`),this.globalCallbacks.onUserProfileUpdated&&this.globalCallbacks.onUserProfileUpdated(e)}),this.socket.on(dd,e=>{this.logger.debug(`📡 [API Key Created] ${e.keyId}`),this.globalCallbacks.onApiKeyCreated&&this.globalCallbacks.onApiKeyCreated(e)}),this.socket.on(ud,e=>{this.logger.debug(`📡 [API Key Updated] ${e.keyId}`),this.globalCallbacks.onApiKeyUpdated&&this.globalCallbacks.onApiKeyUpdated(e)}),this.socket.on(hd,e=>{this.logger.debug(`📡 [API Key Revoked] ${e.keyId}`),this.globalCallbacks.onApiKeyRevoked&&this.globalCallbacks.onApiKeyRevoked(e)}),this.socket.on(gd,e=>{this.logger.debug(`📡 [Token Config Updated] ${e.tokenName}`),this.bufferEvent(gd,e.tokenName,e);const t=this.roomCallbacks.get(zt(e.tokenName));t?.onTokenConfigUpdated&&t.onTokenConfigUpdated(e),this.isGlobalFeedSubscribed&&!t&&this.globalFeedCallbacks.onTokenConfigUpdated&&this.globalFeedCallbacks.onTokenConfigUpdated(e)}),this.socket.on(sd,e=>{this.logger.debug(`📡 [Stats Updated] ${e.tokenName} price=${e.galaPrice}`),this.bufferEvent(sd,e.tokenName,e);const t=this.roomCallbacks.get(zt(e.tokenName));t?.onStatsUpdated&&t.onStatsUpdated(e),this.globalCallbacks.onStatsUpdated&&this.globalCallbacks.onStatsUpdated(e),this.isGlobalFeedSubscribed&&!t&&this.globalFeedCallbacks.onStatsUpdated&&this.globalFeedCallbacks.onStatsUpdated(e)}),this.socket.on(Fl,e=>{this.logger.debug(`📡 [Engagement Stats Updated] ${e.tokenName} chatters=${e.chat.uniqueChatters}`),this.bufferEvent(Fl,e.tokenName,e);const t=this.roomCallbacks.get(zt(e.tokenName));t?.onEngagementStatsUpdated&&t.onEngagementStatsUpdated(e),this.globalCallbacks.onEngagementStatsUpdated&&this.globalCallbacks.onEngagementStatsUpdated(e)}),this.socket.on(kd,e=>{if(this.logger.debug("📡 [Global Feed Subscribed]"),this.isGlobalFeedSubscribed=!0,this.pendingGlobalFeedSubscription){const{resolve:t,timeoutId:n}=this.pendingGlobalFeedSubscription;clearTimeout(n),this.pendingGlobalFeedSubscription=null,t(e)}this.globalFeedCallbacks.onGlobalFeedSubscribed&&this.globalFeedCallbacks.onGlobalFeedSubscribed(e)}),this.socket.on(bd,e=>{this.logger.debug("📡 [Global Feed Unsubscribed]"),this.isGlobalFeedSubscribed=!1,this.globalFeedCallbacks.onGlobalFeedUnsubscribed&&this.globalFeedCallbacks.onGlobalFeedUnsubscribed(e)}),this.socket.on(md,e=>{this.logger.debug(`📡 [Site Config Changed] ${e.key}`),this.globalFeedCallbacks.onSiteConfigChanged&&this.globalFeedCallbacks.onSiteConfigChanged(e)}),this.socket.on(Ol,e=>{this.logger.debug(`📡 [Stream Global Status] enabled=${String(e.enabled)}`),this.globalFeedCallbacks.onStreamGlobalStatus&&this.globalFeedCallbacks.onStreamGlobalStatus(e)}),this.socket.on(Ll,e=>{this.logger.debug(`📡 [Chat Global Status] enabled=${String(e.enabled)}`),this.globalFeedCallbacks.onStreamChatGlobalStatus&&this.globalFeedCallbacks.onStreamChatGlobalStatus(e)}),this.socket.on(pd,e=>{this.logger.debug(`📡 [Comments Global Status] enabled=${String(e.enabled)}`),this.globalFeedCallbacks.onCommentsGlobalStatus&&this.globalFeedCallbacks.onCommentsGlobalStatus(e)}),this.socket.on(fd,e=>{this.logger.debug(`📡 [Webhooks Global Status] enabled=${String(e.enabled)}`),this.globalFeedCallbacks.onWebhooksGlobalStatus&&this.globalFeedCallbacks.onWebhooksGlobalStatus(e)}))}resubscribeAll(){const e=Array.from(this.subscribedRooms.keys());this.logger.debug(`📡 Re-subscribing to ${e.length} rooms after reconnect`);for(const t of e)try{this.roomCallbacks.get(t)&&this.socket?.emit(bl,{tokenName:t})}catch(e){this.logger.error(`Failed to re-subscribe to ${t}:`,e)}if(this.isGlobalFeedSubscribed)try{this.logger.debug("📡 Re-subscribing to global feed after reconnect"),this.socket?.emit(yd)}catch(e){this.logger.error("Failed to re-subscribe to global feed:",e)}}async connect(){return new Promise((e,t)=>{_s(async()=>{if(!this.isSocketIOAvailable)throw new wt('Socket.IO not available. Install "socket.io-client" package.');this.logger.debug(`🔌 Connecting to Stream WebSocket: ${this.config.url}`);const n={};return""!==this.config.authToken&&(n.token=this.config.authToken),this.socket=u.io(this.config.url,{transports:["websocket"],reconnection:!0,reconnectionAttempts:this.config.reconnectAttempts,reconnectionDelay:this.config.reconnectDelay,auth:n}),this.socket.on("connect",()=>{this.logger.debug(`✅ Stream WebSocket connected: ${String(this.socket?.id)}`),this.reconnectionManager.reset(),this.setupGlobalListeners(),this.subscribedRooms.size>0&&this.resubscribeAll(),e()}),this.socket.on("connect_error",e=>{this.logger.error("❌ Stream WebSocket connection error:",e),t(e)}),this.socket.on("disconnect",e=>{this.logger.debug(`🔌 Stream WebSocket disconnected: ${e}`),this.isAuthenticated=!1}),this.socket.on("error",e=>{this.logger.error("❌ Stream WebSocket error:",e)}),this.socket.io.on("reconnect",e=>{this.logger.debug(`🔄 Stream WebSocket reconnected after ${e} attempts`),this.reconnectionManager.reset(),""!==this.config.authToken&&this.authenticate(this.config.authToken)}),this.socket.io.on("reconnect_attempt",()=>{this.reconnectionManager.recordAttempt(),this.logger.debug(`🔄 Stream WebSocket reconnect attempt ${this.reconnectionManager.getStatusString()}`)}),this.socket.io.on("reconnect_failed",()=>{this.logger.error("❌ Stream WebSocket max reconnection attempts reached")}),Promise.resolve(void 0)},"Stream WebSocket connection setup",this.logger,e=>{const n=e instanceof Error?e:new Error(String(e));throw t(n),n})})}authenticate(e){if(!this.socket?.connected)throw new kt("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(""===e)throw Tt("token","Authentication token");this.logger.debug("📡 Authenticating with stream server"),this.socket.emit(Sl,{token:e}),this.config.authToken=e}async subscribeToStream(e,t={}){if(""===e)throw Tt("tokenName","Token name");if(!this.socket?.connected)throw new kt("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");const n=zt(e);return this.subscribedRooms.has(n)?(this.logger.debug(`📡 Already subscribed to ${n}, updating callbacks`),this.roomCallbacks.set(n,t),this.processBufferedEvents(n,t),{tokenName:n,room:this.getRoomName(e)}):new Promise((a,s)=>{const r=setTimeout(()=>{this.pendingSubscriptions.delete(n),s(new Error(`Subscription to ${e} timed out after ${this.config.subscriptionTimeout}ms`))},this.config.subscriptionTimeout);this.pendingSubscriptions.set(n,{resolve:a,reject:s,timeoutId:r}),this.roomCallbacks.set(n,t),this.subscribedRooms.set(n,{tokenName:n,subscribedAt:Date.now()}),this.logger.debug(`📡 Subscribing to stream: ${n}`),this.socket.emit(bl,{tokenName:n})})}unsubscribeFromStream(e){const t=zt(e);if(!this.subscribedRooms.has(t))return void this.logger.debug(`📡 Not subscribed to ${t}, skipping unsubscribe`);this.logger.debug(`📡 Unsubscribing from stream: ${t}`),this.socket?.connected&&this.socket.emit(wl,{tokenName:t}),this.subscribedRooms.delete(t),this.roomCallbacks.delete(t);const n=this.pendingSubscriptions.get(t);n&&(clearTimeout(n.timeoutId),this.pendingSubscriptions.delete(t));for(const e of this.eventBuffer.keys())if(e.endsWith(`:${t}`)){this.eventBuffer.delete(e);const t=this.eventBufferTimeouts.get(e);t&&(clearTimeout(t),this.eventBufferTimeouts.delete(e))}}sendChatMessage(e,t){if(""===e)throw Tt("tokenName","Token name");if(""===t)throw Tt("content","Message content");if(!this.socket?.connected)throw new kt("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(!this.isAuthenticated)throw new kt("Not authenticated. Call authenticate() first.","auth","NOT_AUTHENTICATED");const n=zt(e);this.logger.debug(`📡 Sending chat message to ${n}: ${t.slice(0,30)}...`),this.socket.emit(Al,{tokenName:n,content:t})}sendReaction(e,t,n=0){if(""===e)throw Tt("tokenName","Token name");if(""===t)throw Tt("emoji");if(!this.socket?.connected)throw new kt("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(!this.isAuthenticated)throw new kt("Not authenticated. Call authenticate() first.","auth","NOT_AUTHENTICATED");const a=zt(e);this.logger.debug(`📡 Sending reaction to ${a}: ${t}`),this.socket.emit(El,{tokenName:a,emoji:t,streamTime:n})}sendTypingStart(e){this.sendTypingEvent(e,Tl,"typing_start")}sendTypingStop(e){this.sendTypingEvent(e,Cl,"typing_stop")}sendTypingEvent(e,t,n){if(""===e)throw Tt("tokenName","Token name");if(!this.socket?.connected)throw new kt("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(!this.isAuthenticated)throw new kt("Not authenticated. Call authenticate() first.","auth","NOT_AUTHENTICATED");const a=zt(e);this.logger.debug(`📡 Sending ${n} to ${a}`),this.socket.emit(t,{tokenName:a})}subscribeTokenBanned(e,t){const n=zt(e),a={onTokenBanned:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...a}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onTokenBanned,this.roomCallbacks.set(n,t)}}}subscribeTokenUnbanned(e,t){const n=zt(e),a={onTokenUnbanned:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...a}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onTokenUnbanned,this.roomCallbacks.set(n,t)}}}subscribeModeratorInviteCreated(e,t){const n=zt(e),a={onModeratorInviteCreated:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...a}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onModeratorInviteCreated,this.roomCallbacks.set(n,t)}}}subscribeModeratorAdded(e,t){const n=zt(e),a={onModeratorAdded:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...a}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onModeratorAdded,this.roomCallbacks.set(n,t)}}}subscribeModeratorRemoved(e,t){const n=zt(e),a={onModeratorRemoved:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...a}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onModeratorRemoved,this.roomCallbacks.set(n,t)}}}subscribeModeratorRoleUpdated(e,t){const n=zt(e),a={onModeratorRoleUpdated:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...a}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onModeratorRoleUpdated,this.roomCallbacks.set(n,t)}}}subscribeOverseerAdded(e){return this.globalCallbacks.onOverseerAdded=e,()=>{delete this.globalCallbacks.onOverseerAdded}}subscribeOverseerRemoved(e){return this.globalCallbacks.onOverseerRemoved=e,()=>{delete this.globalCallbacks.onOverseerRemoved}}subscribeTradeExecuted(e,t){const n=zt(e),a={onTradeExecuted:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...a}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onTradeExecuted,this.roomCallbacks.set(n,t)}}}subscribePoolMetadataUpdated(e,t){const n=zt(e),a={onPoolMetadataUpdated:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...a}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onPoolMetadataUpdated,this.roomCallbacks.set(n,t)}}}subscribePoolSocialLinksUpdated(e,t){const n=zt(e),a={onPoolSocialLinksUpdated:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...a}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onPoolSocialLinksUpdated,this.roomCallbacks.set(n,t)}}}subscribePoolBadgeAssigned(e,t){const n=zt(e),a={onPoolBadgeAssigned:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...a}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onPoolBadgeAssigned,this.roomCallbacks.set(n,t)}}}subscribeHolderCountUpdated(e,t){const n=zt(e),a={onHolderCountUpdated:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...a}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onHolderCountUpdated,this.roomCallbacks.set(n,t)}}}subscribeCommentCreated(e,t){const n=zt(e),a={onCommentCreated:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...a}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onCommentCreated,this.roomCallbacks.set(n,t)}}}subscribeUserProfileUpdated(e){return this.globalCallbacks.onUserProfileUpdated=e,()=>{delete this.globalCallbacks.onUserProfileUpdated}}subscribeApiKeyCreated(e){return this.globalCallbacks.onApiKeyCreated=e,()=>{delete this.globalCallbacks.onApiKeyCreated}}subscribeApiKeyUpdated(e){return this.globalCallbacks.onApiKeyUpdated=e,()=>{delete this.globalCallbacks.onApiKeyUpdated}}subscribeApiKeyRevoked(e){return this.globalCallbacks.onApiKeyRevoked=e,()=>{delete this.globalCallbacks.onApiKeyRevoked}}subscribeStatsUpdated(e){return this.globalCallbacks.onStatsUpdated=e,()=>{delete this.globalCallbacks.onStatsUpdated}}subscribeEngagementStatsUpdated(e){return this.globalCallbacks.onEngagementStatsUpdated=e,()=>{delete this.globalCallbacks.onEngagementStatsUpdated}}setGlobalCallbacks(e){this.globalCallbacks=e}getSubscribedTokens(){return Array.from(this.subscribedRooms.keys())}isConnected(){return this.socket?.connected??!1}isAuthenticatedForChat(){return this.isAuthenticated}async subscribeToGlobalFeed(e){if(!this.socket?.connected)throw new kt("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");return this.isGlobalFeedSubscribed?(this.logger.debug("📡 Already subscribed to global feed, updating callbacks"),e&&(this.globalFeedCallbacks=e),{room:"global:feed"}):new Promise((t,n)=>{const a=setTimeout(()=>{this.pendingGlobalFeedSubscription=null,n(new Error(`Global feed subscription timed out after ${this.config.subscriptionTimeout}ms`))},this.config.subscriptionTimeout);this.pendingGlobalFeedSubscription={resolve:t,reject:n,timeoutId:a},e&&(this.globalFeedCallbacks=e),this.logger.debug("📡 Subscribing to global feed"),this.socket.emit(yd)})}unsubscribeFromGlobalFeed(){this.isGlobalFeedSubscribed?(this.logger.debug("📡 Unsubscribing from global feed"),this.socket?.connected&&this.socket.emit(vd),this.isGlobalFeedSubscribed=!1,this.globalFeedCallbacks={},this.pendingGlobalFeedSubscription&&(clearTimeout(this.pendingGlobalFeedSubscription.timeoutId),this.pendingGlobalFeedSubscription=null)):this.logger.debug("📡 Not subscribed to global feed, skipping unsubscribe")}isSubscribedToGlobalFeed(){return this.isGlobalFeedSubscribed}setGlobalFeedCallbacks(e){this.globalFeedCallbacks=e,this.logger.debug("📡 Updated global feed callbacks")}getSocket(){return this.socket}disconnect(){if(this.socket){this.logger.debug("🔌 Disconnecting from Stream WebSocket");try{for(const[e,t]of this.pendingSubscriptions){try{clearTimeout(t.timeoutId),t.reject(new Error("WebSocket disconnected"))}catch(t){this.logger.error(`Error cleaning up pending subscription for ${e}:`,t)}this.pendingSubscriptions.delete(e)}}catch(e){this.logger.error("Error clearing pending subscriptions:",e)}try{this.subscribedRooms.clear(),this.roomCallbacks.clear()}catch(e){this.logger.error("Error clearing room tracking:",e)}try{for(const e of this.eventBufferTimeouts.values())clearTimeout(e);this.eventBuffer.clear(),this.eventBufferTimeouts.clear()}catch(e){this.logger.error("Error clearing event buffers:",e)}this.globalCallbacks={};try{this.globalFeedCallbacks={},this.isGlobalFeedSubscribed=!1,this.pendingGlobalFeedSubscription&&(clearTimeout(this.pendingGlobalFeedSubscription.timeoutId),this.pendingGlobalFeedSubscription.reject(new Error("WebSocket disconnected")),this.pendingGlobalFeedSubscription=null)}catch(e){this.logger.error("Error clearing global feed state:",e)}try{this.socket.disconnect()}catch(e){this.logger.error("Error disconnecting socket:",e)}this.socket=null,this.isAuthenticated=!1,this.logger.debug("✅ Stream WebSocket disconnected and cleaned up")}}}function Sd(e){if(Gn(e.tokenName,"tokenName",an),!(null==(t=e.reason)||""===t||"string"==typeof t&&!Hn(t)&&t.length<=un.BAN_REASON.MAX_LENGTH))throw new kt(`reason must be at most ${un.BAN_REASON.MAX_LENGTH} characters`,"reason","TOO_LONG");var t}class Ad extends Ni{constructor(e,t,n,a=!1,s){super(e,t,n,a,s)}async banToken(e){Sd(e);const t=De,n={tokenName:zt(e.tokenName)};if(void 0!==e.reason)try{Fn(e.reason,"reason",!0),e.reason.trim().length>0&&(n.reason=e.reason)}catch{}const a=await this.http.post(t,n,this.getDualAuthHeaders());return{ban:this.extractData(a),tokenName:zt(e.tokenName)}}async unbanToken(e){!function(e){Gn(e.tokenName,"tokenName",an)}(e);const t=this.buildEndpoint(xe,{tokenName:e.tokenName});return Mt(await this.http.delete(t,void 0,this.getDualAuthHeaders()),"Failed to unban token",!1),{tokenName:zt(e.tokenName)}}async listTokenBans(e={}){!function(e){Mn(0,void 0,on,e.pageSize)}(e);const t=_e,n=this.buildPaginationParams(e,on);this.addOptionalFilterParams(n,e,["search"]);const a=await this.http.get(t,n,this.getDualAuthHeaders()),s=this.extractData(a);return{items:s.bans,pageInfo:s.pageInfo}}async getTokenBan(e){!function(e){Gn(e.tokenName,"tokenName",an)}(e);const t=this.buildEndpoint(Re,{tokenName:e.tokenName}),n=await this.http.get(t,{},this.getDualAuthHeaders()),a=this.extractDataOrNull(n);return{banned:null!==a,...null!==a&&{ban:a},tokenName:zt(e.tokenName)}}async isTokenBanned(e){return this.getTokenBan(e)}}class Ed extends Qn{constructor(e,t=!1){super(t),this.poolService=e,this.cache=new Map,this.accessOrder=new Set,this.cacheHits=0,this.cacheMisses=0}async resolveTokenToVault(e){if(!Un(e))throw Tt("tokenName","Token name");const t=zt(e),n=this.getCacheEntry(t);if(null!==n)return this.cacheHits++,this.updateAccessOrder(t),n.vaultAddress;this.cacheMisses++;const a=await this.poolService.resolveTokenNameToVault(e);if(null!==a&&""!==a){const e=this.parseVaultAddressToTokenClassKey(a);this.setCacheEntry(t,{vaultAddress:a,tokenClassKey:e,cachedAt:Date.now()})}return a}async resolveTokenClassKey(e){if(!Un(e))throw Tt("tokenName","Token name");const t=zt(e),n=this.getCacheEntry(t);if(null!==n)return this.cacheHits++,this.updateAccessOrder(t),n.tokenClassKey;this.cacheMisses++;const a=await this.poolService.resolveTokenNameToVault(e);if(null===a||""===a)throw Et(e);const s=this.parseVaultAddressToTokenClassKey(a);return this.setCacheEntry(t,{vaultAddress:a,tokenClassKey:s,cachedAt:Date.now()}),s}get(e){const t=this.getCacheEntry(zt(e));return t?.vaultAddress??null}getCacheEntry(e){return this.cache.get(e)??null}setCacheEntry(e,t){this.cache.size>=Ed.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=zt(e),a=this.parseVaultAddressToTokenClassKey(t);this.setCacheEntry(n,{vaultAddress:t,tokenClassKey:a,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:Ed.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(zt(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:a}of e){const e=zt(t);this.setCacheEntry(e,{vaultAddress:n,tokenClassKey:a,cachedAt:Date.now()})}}parseVaultAddressToTokenClassKey(e){try{return $i(e)}catch(e){if(e instanceof kt)throw Ct("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad","Vault address");throw e}}}Ed.MAX_CACHE_SIZE=1e4;class Td extends Xn{constructor(e,t=!1){super(e,t)}async fetchLaunchpadFee(){return Kt(()=>this.http.get(qe),{errorContext:"Failed to fetch launchpad fee"})}async fetchSaleDetails(e){return Kt(()=>this.http.get(ze,{tokenName:e}),{errorContext:`Failed to fetch sale details for ${e}`})}async getTradeQuote(e){return Kt(()=>this.http.get(je,{tokenName:e.tokenName,amount:e.amount,type:e.type,method:e.method}),{errorContext:`Failed to get trade quote for ${e.tokenName}`})}async getPremintQuote(e){return Kt(()=>this.http.get(Ve,{amount:e}),{errorContext:"Failed to get premint quote"})}}class Cd extends Ni{constructor(e,t,n,a=!1,s){super(e,t,n,a,s)}async emitTradeExecuted(e,t){this.validateTokenName(e,sn);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,sn);const a={action:"balance_updated",userAddress:e,tokenName:t,payload:n};await this.emitEvent(a)}async emitStreamStatus(e,t,n=!0){this.validateTokenName(e,sn);const a={action:"stream_status",tokenName:e,payload:t,broadcast:n};await this.emitEvent(a)}async emitViewerCount(e,t,n=!1){this.validateTokenName(e,sn);const a={action:"viewer_count",tokenName:e,payload:t,broadcast:n};await this.emitEvent(a)}async emitStreamCountdown(e,t,n=!0){this.validateTokenName(e,sn);const a={action:"stream_countdown",tokenName:e,payload:t,broadcast:n};await this.emitEvent(a)}async emitChatMessage(e,t,n=!1){this.validateTokenName(e,sn);const a={action:"chat_message",tokenName:e,payload:t,broadcast:n};await this.emitEvent(a)}async emitChatStatus(e,t,n=!1){this.validateTokenName(e,sn);const a={action:"chat_status",tokenName:e,payload:t,broadcast:n};await this.emitEvent(a)}async emitTypingIndicator(e,t,n=!1){this.validateTokenName(e,sn);const a={action:"typing_indicator",tokenName:e,payload:t,broadcast:n};await this.emitEvent(a)}async emitTokenBanned(e,t){this.validateTokenName(e,sn);const n={action:"token_banned",tokenName:e,payload:t,broadcast:!0};await this.emitEvent(n)}async emitTokenUnbanned(e,t){this.validateTokenName(e,sn);const n={action:"token_unbanned",tokenName:e,payload:t,broadcast:!0};await this.emitEvent(n)}async emitModeratorAdded(e,t,n=!1){this.validateTokenName(e,sn);const a={action:"moderator_added",tokenName:e,payload:t,broadcast:n};await this.emitEvent(a)}async emitModeratorRemoved(e,t,n=!1){this.validateTokenName(e,sn);const a={action:"moderator_removed",tokenName:e,payload:t,broadcast:n};await this.emitEvent(a)}async emitUserProfileUpdated(e,t){this.validateRequiredString(e,"userAddress","User Address");const n={action:"user_profile_updated",userAddress:e,payload:t};await this.emitEvent(n)}async emitSiteConfigChanged(e){const t={action:"site_config_changed",payload:e,broadcast:!0};await this.emitEvent(t)}async emitFeatureStatus(e){const t={action:"feature_status",payload:e,broadcast:!0};await this.emitEvent(t)}async emitEvent(e){this.validateRequiredString(e.action,"action","Event Action");const t=this.buildEndpoint("/v1/websocket",{});await this.http.post(t,e,this.getDualAuthHeaders())}async getConnectedClients(e){const t=this.buildEndpoint("/v1/connected-clients",{}),n={};void 0!==e?.room&&""!==e.room&&(n.room=e.room),void 0!==e?.tokenName&&(n.tokenName=e.tokenName),void 0!==e?.userAddress&&(n.userAddress=e.userAddress),void 0!==e?.userAddresses&&(n.userAddresses=e.userAddresses),void 0!==e?.authenticated&&(n.authenticated=e.authenticated),void 0!==e?.isOverseer&&(n.isOverseer=e.isOverseer),void 0!==e?.minConnectionSeconds&&(n.minConnectionSeconds=e.minConnectionSeconds),void 0!==e?.offset&&(n.offset=e.offset),void 0!==e?.limit&&(n.limit=e.limit);const a=await this.http.get(t,Object.keys(n).length>0?n:void 0,this.getDualAuthHeaders());return this.extractData(a)}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 wt("userAddresses must be a non-empty array");const t=await this.getConnectedClients({userAddresses:e.join(","),limit:e.length}),n=t.clients.filter(e=>"string"==typeof e.address&&""!==e.address).map(e=>e.address);return{online:n,offline:e.filter(e=>!n.includes(e)),clients:t.clients.map(e=>{const t={socketId:e.socketId,rooms:e.rooms};return"string"==typeof e.address&&(t.address=e.address),t})}}async getTokenViewers(e,t){this.validateTokenName(e,sn);const n={tokenName:e};void 0!==t?.authenticated&&(n.authenticated=t.authenticated),void 0!==t?.limit&&(n.limit=t.limit);const a=await this.getConnectedClients(n);return{clients:a.clients,count:a.summary.totalConnected,authenticatedCount:a.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,sn);const n={action:"recording_status",tokenName:e,payload:t};await this.emitEvent(n)}async emitRecordingsCountUpdated(e,t){this.validateTokenName(e,sn);const n={action:"recordings_count_updated",tokenName:e,payload:t};await this.emitEvent(n)}async emitDownloadReady(e,t){this.validateTokenName(e,sn);const n={action:"download_ready",tokenName:e,payload:t};await this.emitEvent(n)}}class Nd{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 a=n??this.defaultTtlMs,s={value:t};a>0&&(s.expiresAt=Date.now()+a),this.cache.set(e,s)}has(e){return void 0!==this.get(e)}delete(e){this.cache.delete(e)}clear(){this.cache.clear()}get size(){return this.cache.size}}async function Id(e,t,n,a={}){const{logger:s,cacheNullish:r=!1,keyGenerator:i}=a,o=i?i(e):String(e),c=n.get(o);if(void 0!==c)return s&&s.debug(`Cache hit for key: ${o}`),c;s&&s.debug(`Cache miss for key: ${o}, fetching...`);const l=await t();return null!=l?(n.set(o,l),s&&s.debug(`Cached result for key: ${o}`)):r&&(n.set(o,l),s&&s.debug(`Cached nullish result for key: ${o}`)),l}class Dd extends Qn{constructor(e,t=!1){super(t),this.socket=null,this.listeners=new Map,this.timeouts=new Map,this.hasOnAnyListener=!1,this.MAX_BUFFER_SIZE=1e3,this.config={reconnectAttempts:5,reconnectDelay:2e3,timeout:3e5,...e},this.debug=t,this.reconnectionManager=new Sc({maxAttempts:this.config.reconnectAttempts??5,baseDelayMs:this.config.reconnectDelay??2e3}),this.eventBuffer=new Nd(3e4),this.isSocketIOAvailable=this.checkSocketIOAvailability(),Dd.instances.add(this)}checkSocketIOAvailability(){try{return"function"==typeof u.io||(this.logger.warn('⚠️ Socket.IO client not available. Install "socket.io-client" package.'),!1)}catch(e){return this.logger.warn("⚠️ Socket.IO availability check failed:",e),!1}}async connect(){return new Promise((e,t)=>{_s(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:",st(e)),e}this.logger.debug("🔌 Connecting to Socket.IO server:",this.config.url),this.socket=u.io(this.config.url,{transports:["websocket"],reconnection:!0,reconnectionAttempts:this.config.reconnectAttempts??5,reconnectionDelay:this.config.reconnectDelay??2e3}),this.socket.on("connect",()=>{this.logger.debug("✅ Socket.IO connected successfully:",this.socket?.id),this.logger.debug("📡 Connected to bundle backend WebSocket:",this.config.url),this.logger.debug("🔗 Ready to monitor transaction updates"),this.reconnectionManager.reset(),e()}),this.socket.on("connect_error",e=>{this.logger.error("❌ Socket.IO connection error:",e),t(e)}),this.socket.on("disconnect",e=>{this.logger.debug(`🔌 Socket.IO disconnected: ${e}`),this.handleReconnect()}),this.socket.on("error",e=>{this.logger.error("❌ Socket.IO error:",e)}),this.socket.onAny((e,...t)=>{if(""!==e&&t.length>0&&"object"==typeof t[0]&&null!==t[0]){const n=t[0],a=n.status??n.Status;"string"==typeof a&&(this.logger.debug(`📡 [Event Buffer] Buffering event for ${e}: ${a}`),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=at(e)?e:new Error(st(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 a=this.config.timeout??3e5,s=setTimeout(()=>{if(this.listeners.has(e)){const n=Math.round(a/1e3),s={transactionId:e,status:vi.TIMEOUT,message:`Transaction monitoring timeout - no response after ${n} seconds`,timestamp:Date.now()};this.logger.debug(`📡 Transaction timeout for ${e} (${n}s)`),t(s),this.listeners.delete(e),this.timeouts.delete(e),this.socket?.off(e)}},a);if(this.timeouts.set(e,s),this.socket?.connected)this.socket.off(e),this.logger.debug(`📡 Listening for transaction updates: ${e}`),this.logger.debug(`📡 WebSocket connection ID: ${String(this.socket.id)}`),this.logger.debug(`📡 WebSocket URL: ${this.config.url}`),this.socket.on(e,n=>{this.processTransactionEvent(e,n,t)});else{const n={transactionId:e,status:vi.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 a=t,s=a?.data,r=a?.status??a?.Status??s?.status??s?.Status;let i=a?.message??a?.Message??s?.message??s?.Message??a?.error??s?.error;Un(i)||(i=r===yi.FAILED||r===yi.ERROR?"Transaction failed - check transaction details":r===yi.COMPLETED||r===yi.PROCESSED||r===yi.SUCCESS?"Transaction completed successfully":null!=r?`Transaction status: ${String(r)}`:"Unknown transaction status");const o=a?.blockHash??s?.blockHash,c=a?.gasUsed??s?.gasUsed,l=a?.Data??s?.Data,d={transactionId:e,status:this.mapSocketStatus(r),message:"string"==typeof i?i:"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(r)} -> ${d.status}`),this.logger.debug(`📡 Final message: "${String(i)}"`),n(d),d.status===vi.COMPLETED||d.status===vi.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===vi.COMPLETED?t(e):e.status!==vi.FAILED&&e.status!==vi.TIMEOUT||n(new Error(`Transaction ${String(e.status)}: ${e.message}`))})})}mapSocketStatus(e){const t=e?.toUpperCase();return ki[t]??vi.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")),Dd.instances.delete(this)}static cleanupAll(e=!1){for(const e of Dd.instances)e.disconnect();Dd.instances.clear()}isConnected(){return this.socket?.connected??!1}getSocket(){return this.socket}}Dd.instances=new Set;class _d extends Xn{constructor(e,t=!1){super(e,t)}extractData(e){if(e.error||void 0===e.data){const t=e.message??"Weekly challenge operation failed";throw new Error(t)}return e.data}async getLeaderboard(e={}){const{limit:t=10}=e;if(t<1||t>50)throw new kt("limit must be between 1 and 50","limit","INVALID_LIMIT");this.logger.debug("Fetching weekly challenge leaderboard",{limit:t});const n={limit:String(t)},a=await this.http.get(Xe.GET_LEADERBOARD,n),s=this.extractData(a);return this.logger.debug("Fetched weekly challenge leaderboard",{count:s.count}),{leaderboard:s}}async getTokenHistory(e){const{vaultAddress:t}=e;if("string"!=typeof t||""===t.trim())throw new kt("vaultAddress is required","vaultAddress","REQUIRED_FIELD");this.logger.debug("Fetching token weekly history",{vaultAddress:t});const n=Xe.GET_TOKEN_HISTORY.replace(":vaultAddress",encodeURIComponent(t)),a=await this.http.get(n),s=this.extractData(a);return this.logger.debug("Fetched token weekly history",{count:s.length}),{snapshots:s}}}class Rd extends Jn{constructor(e=!1){super(e),this.lastFetchedAt=null}normalizeKey(e){return jt(e)}hasItems(){return this.cache.size>0}getAllItems(){return Array.from(this.cache.values())}setAll(e){this.cache.clear();for(const t of e){const e=this.extractKey(t),n=this.normalizeKey(e);this.cache.set(n,t)}this.lastFetchedAt=Date.now(),this.logger.debug(`Cached ${e.length} items`)}merge(e){for(const t of e){const e=this.extractKey(t),n=this.normalizeKey(e);this.cache.set(n,t)}this.lastFetchedAt=Date.now(),this.logger.debug(`Merged ${e.length} items (total: ${this.cache.size})`)}getFetchTimestamp(){return this.lastFetchedAt}clear(){super.clear(),this.lastFetchedAt=null}getByKey(e){const t=this.normalizeKey(e);return this.cache.get(t)}hasKey(e){const t=this.normalizeKey(e);return this.cache.has(t)}buildBaseStats(){return{totalItems:this.cache.size,isPopulated:this.cache.size>0,lastFetchedAt:this.lastFetchedAt}}}class xd extends Rd{constructor(e=!1){super(e)}extractKey(e){return e.stringifiedTokenClassKey}has(){return this.hasItems()}getAll(){return this.getAllItems()}getByTokenId(e){return this.getByKey(e)}getStats(){const e=this.buildBaseStats();return{...e,tokenCount:e.totalItems}}size(){return this.cache.size}isTokenWrappable(e){return void 0!==this.getByTokenId(e)}getWrapCounterpart(e){const t=this.getByTokenId(e);if(t)return this.getByTokenId(t.wrapCounterpart)}}class Od extends qi{constructor(e,t=!1){super(e,t,"WrappableTokenService"),this.cache=new xd(t)}buildApiParams(e){return{wrappable:!0}}transformApiResponse(e){return e.map(e=>{const t={symbol:e.symbol,name:e.name,decimals:e.decimals,galaChainDescriptor:{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey},stringifiedTokenClassKey:e.stringifiedTokenClassKey,wrapCounterpart:e.wrap,swappable:e.swappable,verified:e.verified};return void 0!==e.channel&&""!==e.channel&&(t.channel=e.channel),void 0!==e.trending&&(t.trending=e.trending),void 0!==e.image&&""!==e.image&&(t.image=e.image),void 0!==e.description&&""!==e.description&&(t.description=e.description),void 0!==e.currentPrices&&(t.currentPrices=e.currentPrices),t})}async fetchWrappableTokens(e={}){const{offset:t=0,limit:n=this.getDefaultLimit()}=e;return this.logger.debug(`Fetching wrappable tokens (offset=${t}, limit=${Math.min(n,this.getMaxLimit())})`),_s(async()=>{const e=(await this.executePaginatedRequest(t,n)).items;try{0===t?this.cache.setAll(e):this.cache.merge(e)}catch(e){this.logger.error("Cache operation failed (non-fatal):",e)}return{tokens:e,fetchedAt:Date.now(),tokenCount:e.length}},"Failed to fetch wrappable tokens",this.logger)}async fetchAllWrappableTokens(){return _s(async()=>{const e=await async function(e){const{cache:t,fetchFn:n,logger:a,itemTypeName:s="items"}=e;if(t.has()){const e=t.getAll();return a&&a.debug(`Returning ${e.length} cached ${s}`),{items:e,fetchedAt:t.getFetchTimestamp()??Date.now(),itemCount:e.length}}a&&a.debug(`Fetching all ${s} (no cache)`);const r=await n();try{t.setAll(r)}catch(e){a&&a.error("Cache operation failed (non-fatal):",e)}return{items:r,fetchedAt:Date.now(),itemCount:r.length}}({cache:this.cache,fetchFn:()=>this.autoPaginateFetch(),logger:this.logger,itemTypeName:"wrappable tokens"});return{tokens:e.items,fetchedAt:e.fetchedAt,tokenCount:e.itemCount}},"Failed to fetch wrappable tokens",this.logger)}async getWrappableToken(e){const t=Wi(e),n=this.cache.getByTokenId(t);return n||(await Id("wrappable:all",()=>this.fetchAllWrappableTokens(),{get:()=>this.cache.has()?{}:void 0,set:()=>{}},{logger:this.logger}),this.cache.getByTokenId(t))}async getWrapCounterpart(e){const t=await this.getWrappableToken(e);if(t)return this.getWrappableToken(t.wrapCounterpart)}async isTokenWrappable(e){const t=Wi(e);await Id("wrappable:check",()=>this.fetchAllWrappableTokens(),{get:()=>this.cache.has()?{}:void 0,set:()=>{}},{logger:this.logger});const n=this.cache.getByTokenId(t),a=void 0!==n,s={isWrappable:a,tokenId:t};return a&&(s.wrapCounterpart=n.wrapCounterpart),s}getCacheStats(){return this.cache.getStats()}clearCache(){this.cache.clear()}}class Fd extends Qn{constructor(e){super(!1,e.logger),this.galaConnectClient=e.galaConnectClient,this.wrappableTokenService=e.wrappableTokenService;const t=e.wallet?.privateKey;this.nativeSigner=e.signer??("string"==typeof t?new uo(t):void 0),this.walletAddress=e.walletAddress}async wrapToken(e){return this.executeWrapOrUnwrap(e,!0)}async unwrapToken(e){return this.executeWrapOrUnwrap(e,!1)}async estimateWrapFee(e,t){return this.estimateChannelFee(e,t,!0)}async estimateUnwrapFee(e,t){return this.estimateChannelFee(e,t,!1)}getWrapStatus(e){if(0===e.length)throw Tt("transactionId");return{success:!0,status:"completed",transactionId:e,fromToken:"",toToken:"",amount:"",fromChannel:"",toChannel:""}}async executeWrapOrUnwrap(e,t){const n=await this.getWrappableTokenOrThrow(e.tokenId);if(t?"asset"===n.channel:"asset"!==n.channel){const e=t?"already on asset channel":"not on asset channel",a=t?"unwrapToken()":"wrapToken()",s=t?"ALREADY_ON_ASSET_CHANNEL":"NOT_ON_ASSET_CHANNEL";throw new kt(`Cannot ${t?"wrap":"unwrap"} ${n.symbol} - it's ${e}. Use ${a} instead.`,"tokenId",s)}const a=await this.getCounterpartOrThrow(e.tokenId,n.symbol);return this.executeChannelBridge({sourceToken:n,destinationToken:a,amount:e.amount,...void 0!==e.recipient&&""!==e.recipient&&{recipient:e.recipient},...void 0!==e.memo&&""!==e.memo&&{memo:e.memo},isWrap:t})}async estimateChannelFee(e,t,n){if("string"==typeof e&&0===e.length)throw Tt("tokenId","Token identifier");if(0===t.length)throw Tt("amount");const a=await this.getWrappableTokenOrThrow(e);if(n?"asset"===a.channel:"asset"!==a.channel){const e=n?"already on asset channel":"not on asset channel",t=n?"ALREADY_ON_ASSET_CHANNEL":"NOT_ON_ASSET_CHANNEL";throw new kt(`Cannot ${n?"wrap":"unwrap"} ${a.symbol} - it's ${e}`,"tokenId",t)}const s=this.determineChannelRouting(a,n);return{fee:"0",feeToken:"GALA",authorizationType:s.authType,feeChannel:s.sourceChannel}}async executeChannelBridge(e){const{sourceToken:t,destinationToken:n,amount:a,recipient:s,isWrap:r}=e;if(void 0===this.nativeSigner||void 0===this.walletAddress||0===this.walletAddress.length)throw new kt("Wallet required for wrap/unwrap operations. Initialize SDK with a private key.","wallet","WALLET_REQUIRED");const i=this.walletAddress,o=this.determineChannelRouting(t,r),c=`galaswap-operation-${Sr()}`,l={quantity:a,tokenInstance:{collection:t.galaChainDescriptor.collection,category:t.galaChainDescriptor.category,type:t.galaChainDescriptor.type,additionalKey:t.galaChainDescriptor.additionalKey,instance:"0"},destinationChainId:o.destinationChannelId,recipient:s??i,wrap:!0,uniqueKey:c};return this.logger.debug(`[WrapService] ${r?"Wrap":"Unwrap"} message (pre-signing)`,{amount:a,uniqueKey:c,sourceChannel:o.sourceChannel}),this.executeWrapBridgeRequest({sourceToken:t,destinationToken:n,amount:a,message:l,routing:o,isWrap:r,senderAddress:i})}async executeWrapBridgeRequest(e){const{sourceToken:t,destinationToken:n,amount:a,message:s,routing:r,isWrap:i}=e;try{const e=await this.nativeSigner.signObject("RequestTokenBridgeOut",s);this.logger.debug(`[WrapService] ${i?"Wrap":"Unwrap"} request (signed)`,{sourceToken:t.symbol,destinationToken:n.symbol,amount:a,channel:r.sourceChannel});const o=await this.galaConnectClient.requestBridgeOut(e);if(this.logger.debug("[WrapService] RequestBridgeOut response",{status:o.Status,hasData:"Data"in o}),function(e){return"object"==typeof e&&null!==e&&"Status"in e&&"number"==typeof e.Status&&1!==e.Status}(o)){const e=`Status=${o.Status}`,s="string"==typeof o.Message&&o.Message.length>0?`: ${o.Message}`:"";return{success:!1,fromToken:t.symbol,toToken:n.symbol,amount:a,fromChannel:r.sourceChannel,toChannel:i?"asset":n.channel??"music",error:`GalaChain request failed (${e}${s})`}}if(function(e){return"object"==typeof e&&null!==e&&"Data"in e&&"string"==typeof e.Data}(o)){const e=o.Data;this.logger.debug("[WrapService] Step 1 complete, bridgeRequestId:",e);const s={bridgeFromChannel:r.sourceChannel,bridgeRequestId:e};this.logger.debug("[WrapService] Step 2 - BridgeTokenOut",{bridgeFromChannel:s.bridgeFromChannel});const c=await this.galaConnectClient.bridgeTokenOut(s);return this.logger.debug("[WrapService] BridgeTokenOut response",{status:c.Status,hash:c.Hash}),1!==c.Status?{success:!1,fromToken:t.symbol,toToken:n.symbol,amount:a,fromChannel:r.sourceChannel,toChannel:i?"asset":n.channel??"music",error:`BridgeTokenOut failed: status=${String(c.Status)}`}:{success:!0,transactionId:c.Hash??e,fromToken:t.symbol,toToken:n.symbol,amount:a,fromChannel:r.sourceChannel,toChannel:i?"asset":n.channel??"music",completedAt:Date.now()}}return{success:!1,fromToken:t.symbol,toToken:n.symbol,amount:a,fromChannel:r.sourceChannel,toChannel:i?"asset":n.channel??"music",error:`Unexpected response format from GalaChain (type=${typeof o})`}}catch(e){const s=st(e);return this.logger.error(`[WrapService] ${i?"Wrap":"Unwrap"} operation failed:`,s),{success:!1,fromToken:t.symbol,toToken:n.symbol,amount:a,fromChannel:r.sourceChannel,toChannel:i?"asset":n.channel??"music",error:s}}}determineChannelRouting(e,t){if(t){return{sourceChannel:e.channel??"music",destinationChannelId:Ws,authType:"cross_channel_authorization"}}return{sourceChannel:"asset",destinationChannelId:Hs,authType:"automatic"}}async getCounterpartOrThrow(e,t){const n=await this.wrappableTokenService.getWrapCounterpart(e);if(null==n)throw new kt(`Counterpart token not found for ${t}`,"tokenId","COUNTERPART_NOT_FOUND");return n}async getWrappableTokenOrThrow(e){const t=await this.wrappableTokenService.getWrappableToken(e);if(null==t)throw new kt(`Token not found or not wrappable: ${this.formatTokenId(e)}`,"tokenId","TOKEN_NOT_WRAPPABLE");return t}formatTokenId(e){return"string"==typeof e?e:Ms(e)}}class Bd 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}}class Ud{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 Pd{constructor(e){this.bundleBaseUrl=qd(e.bundleBaseUrl),this.launchpadBaseUrl=qd(e.launchpadBaseUrl),this.signer=e.signer,this.walletAddress=e.walletAddress,this.requestor=e.httpRequestor??fetch.bind(globalThis),this.socketFactory=e.socketFactory??(e=>u.io(e,{transports:["websocket"]}))}async submit(e){let t;try{t=await this.signer.signTypedData(e.method,e.dto)}catch(e){if(e instanceof Bd)throw e;const t=e instanceof Error?e.message:"Launchpad signing failed.";throw new Bd(t,"LAUNCHPAD_SIGNING_FAILED",{chainMessage:t})}const n=function(e){return Object.fromEntries(Object.entries(e).filter(([e])=>"prefix"!==e))}(t),a=`${this.bundleBaseUrl}/bundle`,s=await this.requestor(a,{method:"POST",headers:{"content-type":"application/json","X-Wallet-Address":this.walletAddress},body:JSON.stringify({stringsInstructions:e.stringsInstructions,method:e.method,signedDto:n})}),r=await Wd(s);if(!s.ok)throw Ld(s.status,r,a);const i=function(e){if("string"==typeof e&&""!==e)return e;if(!Hd(e))throw new Bd("Bundler returned no bundle id.","INVALID_BUNDLE_RESPONSE");const t=e.data,n=e.bundleId;if("string"==typeof t&&""!==t)return t;if(Hd(t)&&"string"==typeof t.bundleId&&""!==t.bundleId)return t.bundleId;if("string"==typeof n&&""!==n)return n;throw new Bd("Bundler returned no bundle id.","INVALID_BUNDLE_RESPONSE")}(r),o=Gd(e.dto,"uniqueKey");return new Ud({bundleId:i,uniqueKey:o,method:e.method,wait:t=>this.waitForResult(e,i,t)})}async waitForResult(e,t,n={}){const a=n.timeoutMs??6e4,s=n.pollIntervalMs??2500,r=Date.now();let i,o,c=!1,l=new Promise(()=>{});try{i=this.socketFactory(this.bundleBaseUrl),l=new Promise((e,n)=>{o=t=>{const a=function(e){if(!Hd(e))return;const t=e.status;return"PROCESSED"!==t&&"FAILED"!==t?void 0:{status:t,data:e.data}}(t);void 0===a||c||(c=!0,"FAILED"===a.status?n(Md(a.data)):e(a))},i?.on(t,o)})}catch{i=void 0}const d=this.pollConfirmation(e,t,r,a,s);try{return await Promise.race([l,d])}finally{c=!0,void 0!==i&&(void 0!==o&&i.off(t,o),i.disconnect())}}async pollConfirmation(e,t,n,a,s){const r="CreateSale"===e.method,i=r?function(e,t){const n=Gd(t,"tokenName");return`${e}/v1/tokens/${encodeURIComponent(n)}`}(this.launchpadBaseUrl,e.dto):`${this.bundleBaseUrl}/bundle?id=${encodeURIComponent(t)}`;for(;Date.now()-n<=a;){const e=await this.requestor(i,{method:"GET"}),t=await Wd(e);if(r){if(e.ok)return{status:"PROCESSED",data:Kd(t)};if(404!==e.status&&202!==e.status)throw Ld(e.status,t,i)}else{if(!e.ok)throw Ld(e.status,t,i);const n=Hd(t)?t.status:void 0;if("COMPLETED"===n||"PROCESSED"===n)return{status:"PROCESSED",data:t};if("FAILED"===n)throw Md(t)}const o=a-(Date.now()-n);if(o<=0)break;await zd(Math.min(Math.max(0,s),o))}throw new Bd(`Timed out waiting for bundle ${e.dto.uniqueKey}`,"BUNDLE_CONFIRMATION_TIMEOUT",{details:{method:e.method}})}}function Md(e){const t=$d(e)??"Launchpad bundle failed on chain.";return new Bd(t,"BUNDLE_FAILED",{chainMessage:t})}function Ld(e,t,n){const a=$d(t)??`Bundle request failed with HTTP ${e}`;return new Bd(a,"BUNDLE_REQUEST_FAILED",{status:e,chainMessage:a,details:{body:t,url:n}})}function $d(e){if("string"==typeof e&&""!==e)return e;if(Hd(e))for(const t of["chainMessage","message","Message","error"]){const n=e[t];if("string"==typeof n&&""!==n)return n;if(Hd(n)){const e=$d(n);if(void 0!==e)return e}}}function Kd(e){return Hd(e)?e.data??e.Data??e:e}function Gd(e,t){const n=e[t];if("string"!=typeof n||""===n)throw new Bd(`Missing ${t} in launchpad DTO.`,"INVALID_LAUNCHPAD_DTO");return n}async function Wd(e){try{return await e.json()}catch{return e.text()}}function Hd(e){return"object"==typeof e&&null!==e}function qd(e){return e.replace(/\/$/u,"")}function zd(e){return new Promise(t=>setTimeout(t,e))}function jd(e){const{collection:t,category:n,type:a}=function(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[a,s,r,i,o,...c]=n.split("$");if(void 0===a||void 0===s||void 0===r||void 0===i||"launchpad"!==o||c.length>0||""===a||""===s||""===r||""===i)throw new Error(`Invalid vaultAddress format (expected service|<collection>$<category>$<type>$<additionalKey>$launchpad): ${e}`);return{collection:a,category:s,type:r,additionalKey:i}}(e),s=`${t}$${n}$${a}$none`,r="GALA$Unit$none$none";return[`$service$${s}$launchpad`,`$tokenBalance$${s}$${e}`,`$tokenBalance$${s}$${e}`,`$tokenBalance$${r}$${e}`,`$tokenBalance$${r}$${e}`]}function Vd(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}`]}class Xd{constructor(e){this.transport=e.transport,this.walletAddress=e.walletAddress}createSale(e){!function(e){const t=qa(e);!t.success&&t.errors&&hs(t.errors,"data")}(e);const t=function(e,t){const n={tokenName:e.tokenName,tokenSymbol:e.tokenSymbol,tokenDescription:e.tokenDescription,tokenImage:e.tokenImage,preBuyQuantity: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??Qd(t)};void 0!==e.reverseBondingCurveConfiguration&&(n.reverseBondingCurveConfiguration=e.reverseBondingCurveConfiguration);void 0!==e.saleStartTime&&(n.saleStartTime=e.saleStartTime);return n}(e,this.walletAddress);return this.transport.submit({method:"CreateSale",dto:t,stringsInstructions:Vd(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})}submitTrade(e,t,n){const a={vaultAddress:t.vaultAddress,...n,extraFees:t.extraFees??{maxAcceptableReverseBondingCurveFee:"0"},uniqueKey:t.uniqueKey??Qd(this.walletAddress)};return this.transport.submit({method:e,dto:a,stringsInstructions:jd(t.vaultAddress)})}}function Qd(e){return`galaswap-operation-${l.v4()}-${Date.now()}-${e}`}class Jd{constructor(e){this.gatewayBaseUrl=e.gatewayBaseUrl.replace(/\/$/u,""),this.signer=e.signer,this.walletAddress=su(e.walletAddress),this.requestor=e.httpRequestor??fetch.bind(globalThis)}transfer(e){const t=Yd(e),n={from:this.walletAddress,to:su(e.to),quantity:e.quantity,tokenInstance:t,uniqueKey:e.uniqueKey??au(this.walletAddress)};return this.direct("TransferToken",n)}burn(e){const t={tokenInstances:[{quantity:e.quantity,tokenInstanceKey:Yd(e)}],uniqueKey:e.uniqueKey??au(this.walletAddress)};return this.direct("BurnTokens",t)}lock(e){const t={lockAuthority:e.lockAuthority??this.walletAddress,tokenInstances:[{owner:this.walletAddress,quantity:e.quantity,tokenInstanceKey:Yd(e)}],uniqueKey:e.uniqueKey??au(this.walletAddress)};return void 0!==e.expires&&(t.expires=e.expires),void 0!==e.name&&(t.name=e.name),this.direct("LockToken",t)}unlock(e){const t={tokenInstances:[{owner:this.walletAddress,quantity:e.quantity,tokenInstanceKey:Yd(e)}],uniqueKey:e.uniqueKey??au(this.walletAddress)};return void 0!==e.name&&(t.name=e.name),this.direct("UnlockToken",t)}async direct(e,t){const n=await this.signNative(e,t),a=`${this.gatewayBaseUrl}/api/asset/token-contract/${e}`,s=await this.post(a,n),r=await async function(e){try{return await e.json()}catch{return e.text()}}(s),i=nu(r);if(!s.ok||void 0!==i?.Status&&1!==i.Status)throw function(e,t,n){const a=nu(t),s=tu(a,"Message")??tu(a,"message")??tu(a,"ErrorKey")??`Gateway request failed with HTTP ${e}`,r=tu(a,"ErrorKey")??"GATEWAY_REQUEST_FAILED";return new Bd(s,r,{status:e,chainMessage:s,details:{body:t,url:n}})}(s.status,r,a);const o=nu(Zd(r))?.mode??i?.mode;if(void 0!==o&&"sync"!==o){throw new Bd(`Unsupported gateway transaction mode: ${"string"==typeof o?o:"non-sync"}`,"INVALID_GATEWAY_RESPONSE",{status:s.status,details:{body:r,url:a}})}const c=Zd(r),l=ru(s,"x-transaction-id")??eu(c)??eu(r),d=function(e){const t=ru(e,"x-block-number");if(void 0===t)return;const n=Number.parseInt(t,10);return Number.isFinite(n)?n:void 0}(s);return{status:"PROCESSED",data:c,...void 0!==l&&{transactionId:l},...void 0!==d&&{blockNumber:d}}}post(e,t){return this.requestor(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)})}async signNative(e,t){try{return await this.signer.signObject(e,t)}catch(e){if(e instanceof Bd)throw e;const t=e instanceof Error?e.message:"Native GalaChain signing failed.";throw new Bd(t,"NATIVE_SIGNING_FAILED",{chainMessage:t})}}}function Yd(e){const t=e.tokenClassKey??e.symbol;if(void 0===t)throw new Bd("tokenClassKey or symbol is required.","INVALID_TOKEN_IDENTIFIER");const n=function(e){if("string"!=typeof e)return e;const t=e.includes("|")?"|":e.includes("$")?"$":void 0;if(void 0===t)return"GALA"===e.toUpperCase()?{collection:"GALA",category:"Unit",type:"none",additionalKey:"none"}:{collection:"Token",category:"Unit",type:e,additionalKey:"none"};const[n,a,s,r]=e.split(t);if(void 0===n||void 0===a||void 0===s||void 0===r||[n,a,s,r].some(e=>""===e))throw new Bd(`Invalid token class key: ${e}`,"INVALID_TOKEN_IDENTIFIER");return{collection:n,category:a,type:s,additionalKey:r}}(t);return{...n,instance:e.instance??"0"}}function Zd(e){const t=nu(e);return t?.Data??t?.data??e}function eu(e){if("string"==typeof e&&""!==e)return e;const t=nu(e);return tu(t,"transactionId")??tu(t,"txnId")??tu(t,"id")}function tu(e,t){const n=e?.[t];return"string"==typeof n&&""!==n?n:void 0}function nu(e){return"object"==typeof e&&null!==e?e:void 0}function au(e){return`galaswap-operation-${l.v4()}-${Date.now()}-${e}`}function su(e){return"eth|0x"===e.slice(0,6).toLowerCase()?`eth|${e.slice(6)}`:e}function ru(e,t){const n=e.headers;if(void 0===n)return;if("function"==typeof n.get)return iu(n.get(t));const a=t.toLowerCase();for(const[e,t]of Object.entries(n))if(e.toLowerCase()===a)return iu(t)}function iu(e){const t=e?.trim();return void 0===t||""===t?void 0:t}function ou(e,t=3e4){return h.create({baseURL:e,timeout:t,headers:{"Content-Type":"application/json"}})}const cu=new Set(["accesstoken","refreshtoken","token","password","privatekey","secret","apikey","api_key","rawkey","authorization","x-api-key","bearer","streamadminapikey","userapikey","signature","signedpayload"]);function lu(e,t=0){if(t>5)return"[...]";if(null==e)return e;if(Array.isArray(e))return e.map(e=>lu(e,t+1));if(e instanceof Map){const n={};for(const[a,s]of e.entries()){const e=String(a);n[e]=cu.has(e.toLowerCase())?"[REDACTED]":lu(s,t+1)}return n}if("object"==typeof e){const n={};for(const[a,s]of Object.entries(e))n[a]=cu.has(a.toLowerCase())?"[REDACTED]":lu(s,t+1);return n}return e}class du{constructor(e,t={}){this.auth=e,this.debug=t.debug??!1,this.logger=new Qt({debug:this.debug,context:"HttpClient"});const n=t.baseUrl??Ps("stage").launchpadBaseUrl,a=t.timeout??6e4;this.axios=ou(n,a),t.headers&&(this.axios.defaults.headers.common={...this.axios.defaults.headers.common,...t.headers}),this.setupInterceptors()}async request(e){return(await this.requestWithMeta(e)).data}async requestWithMeta(e){return _s(async()=>{const t={method:e.method,url:e.url,data:e.data,...void 0!==e.params&&{params:ts(e.params)},...void 0!==e.headers&&{headers:e.headers},...void 0!==e.timeout&&{timeout:e.timeout},...void 0!==e.signal&&{signal:e.signal}};e.data instanceof FormData&&(void 0!==t.headers&&"Content-Type"in t.headers&&delete t.headers["Content-Type"],this.logger.debug("FormData detected - removing Content-Type header for multipart upload")),e.headers&&this.logger.debug("Custom headers provided:",Object.keys(t.headers??{}));const n=e.data instanceof FormData?"[FormData object - multipart/form-data]":lu(e.data);this.logger.debug("Request:",{method:e.method,url:e.url?.split("?")[0],baseURL:this.axios.defaults.baseURL,params:lu(t.params),data:n,isFormData:e.data instanceof FormData,contentType:t.headers?.["Content-Type"]??"not set"});const a=await this.axios.request(t),s=function(e){const t={};if(null==e||"object"!=typeof e)return t;for(const[n,a]of Object.entries(e))"string"==typeof a?t[n.toLowerCase()]=a:"number"!=typeof a&&"boolean"!=typeof a||(t[n.toLowerCase()]=String(a));return t}(a.headers);return this.logger.debug("Response:",{status:a.status,data:lu(a.data),transactionId:s["x-transaction-id"],blockNumber:s["x-block-number"]}),{data:a.data,headers:s,status:a.status}},`HTTP ${e.method} ${e.url}`,this.logger)}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 _s(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.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("No wallet configured - skipping signature header");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,a={message:n?.message??st(e),...n&&Boolean(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=a,this.logger.error("Backend error:",a)}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 uu extends Error{constructor(e,t){super(e),this.cause=t,this.name="WebSocketError"}}class hu 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 gu(e,t){if(Pn(e))throw new uu(`Invalid WebSocket response received for transaction ${t}: response is null or undefined`);if("object"!=typeof e)throw new uu(`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 uu(`Invalid WebSocket response received for transaction ${t}: missing status field`)}function mu(e,t,n,a){gu(e,t);const s=e,r=s.data??{};if(!function(e){if(Pn(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)}(r))throw new uu(`Invalid trade data received for transaction ${t}`);const i={transactionId:t,type:n,method:"native"===a.type?"native":"exact",inputAmount:r.inputQuantity??a.amount,outputAmount:r.outputQuantity??a.expectedAmount??"0",totalFees:r.totalFees??"0",tokenName:a.tokenName,vaultAddress:r.vaultAddress??"",timestamp:Date.now()};return void 0!==s.blockHash&&(i.blockHash=s.blockHash),void 0!==s.gasUsed&&(i.gasUsed=s.gasUsed),void 0!==a.slippageToleranceFactor&&(i.slippageTolerance=a.slippageToleranceFactor),i}function pu(e){if(e&&function(e){return"privateKey"===e.providerType}(e))return e.getWallet()}class fu{constructor(e){let t,a;e.walletProvider?(t=e.walletProvider,a=pu(e.walletProvider)):e.wallet&&(a=e.wallet,t=Fs.fromWallet(e.wallet)),this.wallet=a;const s=e.env??"prod",r=Ps(s);this.environment=s,this.config={baseUrl:e.launchpadBaseUrl??r.launchpadBaseUrl,gatewayBaseUrl:r.gatewayBaseUrl,bundleBaseUrl:r.bundleBaseUrl,webSocketUrl:r.webSocketUrl,gdexWebSocketUrl:r.gdexWebSocketUrl,dexApiBaseUrl:r.dexApiBaseUrl,dexBackendBaseUrl:r.dexBackendBaseUrl,launchpadFrontendUrl:r.launchpadFrontendUrl,timeout:3e4,debug:!1,...e};const i=e.signer??(void 0!==a?new uo(a.privateKey):void 0),o=e.walletAddress??e.galaChainAddress??(void 0!==a?`eth|${a.address.slice(2)}`:function(e){if(void 0===e||!("walletAddress"in e))return;const t=e.walletAddress;return"string"==typeof t&&""!==t?t:void 0}(i)),c=i??{signObject:()=>Promise.reject(new Error("A signer is required for token writes.")),signTypedData:()=>Promise.reject(new Error("A signer is required for launchpad writes."))},l=o??"",d=new Pd({bundleBaseUrl:this.config.bundleBaseUrl,launchpadBaseUrl:this.config.baseUrl,signer:c,walletAddress:l,...void 0!==e.httpRequestor&&{httpRequestor:e.httpRequestor}});if(this.launchpad=new Xd({transport:d,walletAddress:l}),this.tokens=new Jd({gatewayBaseUrl:this.config.gatewayBaseUrl,dexBackendBaseUrl:this.config.dexBackendBaseUrl,signer:c,walletAddress:l,...void 0!==e.httpRequestor&&{httpRequestor:e.httpRequestor}}),this.logger=new Qt({debug:this.config.debug??!1,context:"LaunchpadSDK"}),this.validateConfiguration(),this.slippageToleranceFactor=void 0===e.slippageToleranceFactor?fu.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR:this.parseSlippageToleranceFactor(e.slippageToleranceFactor),this.maxAcceptableReverseBondingCurveFeeSlippageFactor=void 0===e.maxAcceptableReverseBondingCurveFeeSlippageFactor?fu.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR:this.parseFeeSlippageFactor(e.maxAcceptableReverseBondingCurveFeeSlippageFactor),this.calculateAmountMode=e.calculateAmountMode??fu.DEFAULT_CALCULATE_AMOUNT_MODE,this.galaChainAddressOverride=e.galaChainAddress,this.signerWalletAddress=e.walletAddress??(void 0===a?o:void 0),this.auth=new Bs({wallet:a,walletProvider:t,messagePrefix:"Create a GalaChain Wallet"}),this.jwtAuth=new Ds,void 0!==e.accessToken&&""!==e.accessToken){const t=e.accessTokenExpiresIn??86400;this.jwtAuth.setToken(e.accessToken,t)}this.http=new du(this.auth,this.config),this.sessionAuth=new xs(this.http,this.auth,this.jwtAuth,e.debug??!1),this.galaChainHttp=new du(this.auth,{...this.config,baseUrl:this.config.gatewayBaseUrl}),this.bundleHttp=new du(this.auth,{...this.config,baseUrl:this.config.bundleBaseUrl}),this.dexApiHttp=new du(this.auth,{...this.config,baseUrl:this.config.dexApiBaseUrl}),this.dexBackendHttp=new du(this.auth,{...this.config,baseUrl:this.config.dexBackendBaseUrl}),this.galaChainPublicAxios=ou(this.config.gatewayBaseUrl,this.config.timeout??3e4),this.cache=new Yn(e.debug??!1),this.launchpadService=new Mc(this.http,this.jwtAuth),this.tokenResolverService=new Ed(this.launchpadService.poolService),this.launchpadAPI=new bs(this.http,this.tokenResolverService,this.logger,this.bundleHttp,this.galaChainHttp,this.dexApiHttp,this.calculateAmountMode,this.launchpad),this.galaChainService=new wc(this.galaChainHttp,a,this.tokenResolverService,e.debug??!1,this.galaChainPublicAxios),this.dexService=new Fo(this.dexBackendHttp,this.cache,this.galaChainService,e.debug??!1),this.bundleService=new vo(this.bundleHttp,this.tokenResolverService,this.config.debug??!1,a,a?this.getAddress():void 0,this.slippageToleranceFactor,this.maxAcceptableReverseBondingCurveFeeSlippageFactor),this.websocketService=new Dd({url:this.config.webSocketUrl},this.config.debug),this.priceHistoryService=new ul(this.dexBackendHttp,this.config.debug??!1,this.tokenResolverService);const u=e.signer??(void 0===a?void 0:new uo(a.privateKey)),h=e.walletAddress??(void 0===a?void 0:this.getAddress());this.dexClient=new n.GSwap({env:this.environment,...void 0===u?{}:{signer:u},...void 0===h?{}:{walletAddress:h},...void 0===this.config.dexBackendBaseUrl?{}:{dexBackendBaseUrl:this.config.dexBackendBaseUrl},...void 0===this.config.gatewayBaseUrl?{}:{gatewayBaseUrl:this.config.gatewayBaseUrl},...void 0===e.httpRequestor?{}:{httpRequestor:e.httpRequestor}}),this.nftCollectionService=new Yc(this.galaChainHttp),this.tradingQuotesService=new Td(this.http,e.debug??!1)}createOverrideSdk(e){if(!Un(e))throw It("Invalid privateKey: must be a non-empty string","privateKey");if(!e.match(/^0x[a-fA-F0-9]{64}$/))throw It('Invalid privateKey format: must be "0x" followed by 64 hexadecimal characters',"privateKey");const n=new t.Wallet(e),a={...this.config,wallet:n};return new fu(a)}get dex(){return this.dexClient}getAddress(){return void 0!==this.galaChainAddressOverride&&""!==this.galaChainAddressOverride?this.galaChainAddressOverride:void 0!==this.signerWalletAddress&&""!==this.signerWalletAddress?this.signerWalletAddress:(this.validateWallet(),this.auth.getAddress())}getEthereumAddress(){return this.validateWallet(),this.wallet.address}validateWallet(){if(!this.wallet)throw Tt("wallet","Wallet");return this.wallet}setWallet(e){if(null==e||"object"!=typeof e||!("address"in e))throw new kt("Invalid wallet: must be an ethers Wallet instance, received "+typeof e,"wallet","INVALID_WALLET");this.wallet=e,this.auth.setWallet(e)}setWalletProvider(e){this.auth.setWalletProvider(e),this.wallet=e?pu(e):void 0}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:a,streamAdminApiKey:s,userApiKey:r,accessToken:i,headers:o,...c}=this.config;return{...c,...void 0!==s&&{streamAdminApiKey:"[REDACTED]"},...void 0!==r&&{userApiKey:"[REDACTED]"},...void 0!==i&&{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:qt.GAS_FEE}}getVersion(){return bi}getUrlByTokenName(e){const t=this.config.launchpadFrontendUrl;if(void 0===t||""===t)throw It("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),a=Math.min(t,100);return n.holders.slice(0,a).map((e,t)=>({...e,rank:t+1}))}async getHolderCount(e){const t=await this.fetchTokenDistribution(e);return{count:t.totalHolders,totalBalance:t.totalSupply}}async getHolderRank(e,t){const n=await this.fetchTokenDistribution(e),a=n.holders.findIndex(e=>e.address.toLowerCase()===t.toLowerCase());if(-1===a)return null;const s=n.holders[a];return void 0===s?null:{rank:a+1,balance:s.balance,holderCount:n.totalHolders}}async getHoldersByBalance(e,t){const n=await this.fetchTokenDistribution(e),a=t?.minBalance??0,s=t?.maxBalance??1/0,r=Math.min(t?.limit??100,1e3),i=new Map;return n.holders.forEach((e,t)=>{i.set(e.address,t+1)}),n.holders.filter(e=>{const t=parseFloat(e.balance);return t>=a&&t<=s}).map(e=>({...e,rank:i.get(e.address)??0})).slice(0,r)}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{tokenName:t,tokenId:n}=e,{hasA:a}=Kn(e,"tokenName","tokenId",{description:"token identifier"});if(a&&void 0!==t&&""!==t)return this.dexService.fetchLaunchpadTokenSpotPrice(t,e=>this.launchpadAPI.calculateBuyAmount(e),e=>this.fetchPoolDetails(e));const s=n;try{return await this.dexService.fetchTokenPrice({tokenId:s})}catch(e){const t=function(e){if(ot(e)&&e.response)return e.response.status}(e);if(400===t||404===t){this.logger.debug(`DEX spot price not available (HTTP ${t}) for tokenId, attempting launchpad fallback`);try{const t=zt((await this.fetchTokenDetails(s)).name);if(!/^[a-z0-9]{3,20}$/.test(t))throw this.logger.error(`Token name extracted from GalaChain doesn't match launchpad format: "${t}"`),e;return this.logger.debug(`Falling back to launchpad pricing using extracted token name: "${t}"`),this.dexService.fetchLaunchpadTokenSpotPrice(t,e=>this.launchpadAPI.calculateBuyAmount(e),e=>this.fetchPoolDetails(e))}catch(t){throw this.logger.error(`Launchpad fallback failed: ${st(t)}`),e}}throw e}}async fetchGalaPrice(){return this.fetchTokenPrice({tokenId:{collection:"GALA",category:"Unit",type:"none",additionalKey:"none"}})}async fetchTokenDetails(e){return this.dexService.fetchTokenDetails(e)}async fetchAllDexSeasons(){return this.dexService.fetchAllDexSeasons()}async fetchCurrentDexSeason(){return this.dexService.fetchCurrentDexSeason()}async fetchDexLeaderboardBySeasonId(e){return this.dexService.fetchDexLeaderboardBySeasonId(e)}async fetchCurrentDexLeaderboard(){return this.dexService.fetchCurrentDexLeaderboard()}async fetchDexAggregatedVolumeSummary(){return this.dexService.fetchDexAggregatedVolumeSummary()}async fetchLaunchTokenFee(){return this.galaChainService.fetchLaunchTokenFee()}async fetchTokenClassesWithSupply(e){return this.galaChainService.fetchTokenClassesWithSupply(e)}async fetchPoolDetails(e){const t=await this.resolveVaultAddress(e);if(null==t)throw new Error(ht(e));const n=(await this.galaChainService.fetchPoolDetails({vaultAddress:t})).Data,a=await this.launchpadAPI.fetchPoolDetailsForCalculation(e);return n.currentSupply=a.currentSupply,n.reverseBondingCurveMaxFeeFactor=a.reverseBondingCurveMaxFeeFactor,n.reverseBondingCurveMinFeeFactor=a.reverseBondingCurveMinFeeFactor,n.reverseBondingCurveNetFeeFactor=a.reverseBondingCurveNetFeeFactor,n.tokenName=e,n}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 la}),n=t(e)??this.getAddress();return this.galaChainService.fetchGalaBalance({owner:n,collection:"GALA",category:"Unit",additionalKey:"none",type:"none",instance:"0"})}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=e?.solanaPrivateKey??globalThis.process?.env.SOLANA_PRIVATE_KEY;this._bridgeService=new fi({galaConnectBaseUrl:this.config.dexApiBaseUrl,galaChainWalletAddress:this.getAddress(),ethereumPrivateKey:e?.ethereumPrivateKey??t.privateKey,...void 0!==n&&""!==n?{solanaPrivateKey:n}:{},bridgeableTokenService:this.getBridgeableTokenService(),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(){return this._bridgeableTokenService??(this._bridgeableTokenService=new Xi(this.dexApiHttp,this.config.debug??!1)),this._bridgeableTokenService}getWrappableTokenService(){return this._wrappableTokenService??(this._wrappableTokenService=new Od(this.dexApiHttp,this.config.debug??!1)),this._wrappableTokenService}getGalaConnectClient(){if(null===this._galaConnectClient||void 0===this._galaConnectClient){const e=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 oi({baseUrl:this.config.dexApiBaseUrl,...void 0!==this.config.gatewayBaseUrl&&""!==this.config.gatewayBaseUrl?{galachainBaseUrl:this.config.gatewayBaseUrl}:{},walletAddress:e})}return this._galaConnectClient}getWrapService(){if(!this._wrapService){const e=this.getWallet();this._wrapService=new Fd({galaConnectClient:this.getGalaConnectClient(),wrappableTokenService:this.getWrappableTokenService(),...e&&{walletAddress:this.getAddress(),wallet:e}})}return this._wrapService}getStreamingService(){return this._streamingService??(this._streamingService=new kl(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._streamingService}getStreamChatService(){return this._streamChatService??(this._streamChatService=new gl(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._streamChatService}getBanService(){return this._banService??(this._banService=new Ui(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._banService}getTokenBanService(){return this._tokenBanService??(this._tokenBanService=new Ad(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._tokenBanService}getAIModerationService(){return this._aiModerationService??(this._aiModerationService=new Ii(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._aiModerationService}getWeeklyChallengeService(){return this._weeklyChallengeService??(this._weeklyChallengeService=new _d(this.http,this.config.debug??!1)),this._weeklyChallengeService}getOEmbedService(){return this._oembedService??(this._oembedService=new el(this.http,this.config.debug??!1)),this._oembedService}getPlatformStatsService(){return this._platformStatsService??(this._platformStatsService=new dl(this.http,this.config.debug??!1)),this._platformStatsService}getNotificationService(){return this._notificationService??(this._notificationService=new Zc(this.http,this.config.debug??!1,this.jwtAuth)),this._notificationService}getClientConfigService(){return this._clientConfigService??(this._clientConfigService=new ko(this.http,this.config.debug??!1)),this._clientConfigService}getApiKeyService(){return this._apiKeyService??(this._apiKeyService=new xi(this.http,this.jwtAuth,this.config.debug??!1)),this._apiKeyService}getModeratorService(){return this._moderatorService??(this._moderatorService=new Hc(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._moderatorService}getFlagService(){return this._flagService??(this._flagService=new Ro(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._flagService}getOverseerService(){return this._overseerService??(this._overseerService=new cl(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._overseerService}getWebSocketAdminService(){return this._websocketAdminService??(this._websocketAdminService=new Cd(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._websocketAdminService}getContentReactionService(){return this._contentReactionService??(this._contentReactionService=new Oo(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._contentReactionService}toLegacyPinnedMessage(e){return{messageId:e.id,content:e.content,userAddress:e.userAddress,pinnedBy:""!==e.pinnedBy?e.pinnedBy:e.userAddress,pinnedAt:""!==e.pinnedAt?e.pinnedAt:e.createdAt}}buildMessageFetchOptions(e,t){return{type:t,...void 0!==e.tokenName&&{tokenName:e.tokenName},...void 0!==e.userAddress&&{userAddress:e.userAddress},...void 0!==e.cursor&&{cursor:e.cursor},...void 0!==e.pageSize&&{pageSize:e.pageSize}}}async resolveReferralAddress(e){if(void 0===e||""===e)return this.getAddress();if(e.startsWith("client|"))return e;const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return la}),n=t(e);if(void 0===n)throw new kt(`Invalid address format: "${e}". Expected formats: eth|0x..., 0x..., or client|...`);return n}getMessagesService(){return this._messagesService??(this._messagesService=new Lc(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._messagesService}getRestrictedNamesService(){return this._restrictedNamesService??(this._restrictedNamesService=new hl(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.userApiKey)),this._restrictedNamesService}getPlatformConfigService(){return this._platformConfigService??(this._platformConfigService=new ll(this.http,this.jwtAuth,this.config.debug??!1)),this._platformConfigService}getEventsBatcherService(){return this._eventsBatcherService??(this._eventsBatcherService=new Ko(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 wd({url:this.config.streamWebSocketUrl},this.config.debug??!1)}return this._streamWebSocketService}getGdexStreamService(){return this._gdexStreamService??(this._gdexStreamService=new Ec({url:this.config.gdexWebSocketUrl})),this._gdexStreamService}getStreamingEventService(){return this._streamingEventService??(this._streamingEventService=new ml(this.config.debug??!1)),this._streamingEventService}async fetchEthereumWalletTokenBalance(e,t){return this.getBridgeService().fetchEthereumWalletTokenBalance(e,t)}async fetchEthereumWalletNativeBalance(e){return this.getBridgeService().fetchEthereumWalletNativeBalance(e)}async fetchSolanaWalletTokenBalance(e,t){return this.getBridgeService().fetchSolanaWalletTokenBalance(e,t)}async fetchSolanaWalletNativeBalance(e){return this.getBridgeService().fetchSolanaWalletNativeBalance(e)}async requestSolanaDevnetAirdrop(e,t){return this.getBridgeService().requestSolanaDevnetAirdrop(e,t)}async getSolanaTransactionStatus(e){return this.getBridgeService().getSolanaTransactionStatus(e)}async getEthereumTransactionStatus(e){return this.getBridgeService().getEthereumTransactionStatus(e)}async fetchEthereumWalletAllBalances(e){return this.getBridgeService().fetchEthereumWalletAllBalances(e)}async fetchSolanaWalletAllBalances(e){return this.getBridgeService().fetchSolanaWalletAllBalances(e)}async fetchBridgeableTokensByNetwork(e){return this.getBridgeableTokenService().fetchBridgeableTokensByNetwork(e)}async fetchAllBridgeableTokensByNetwork(e){return this.getBridgeableTokenService().fetchAllBridgeableTokensByNetwork(e)}async fetchAllTokensBridgeableToEthereum(){return this.getBridgeableTokenService().fetchAllTokensBridgeableToEthereum()}async fetchAllTokensBridgeableToSolana(){return this.getBridgeableTokenService().fetchAllTokensBridgeableToSolana()}async isTokenBridgeableToNetwork(e){return this.getBridgeableTokenService().isTokenBridgeableToNetwork(e)}async isTokenBridgeableToEthereum(e){return this.getBridgeableTokenService().isTokenBridgeableToEthereum(e)}async isTokenBridgeableToSolana(e){return this.getBridgeableTokenService().isTokenBridgeableToSolana(e)}async fetchWrappableTokens(e={}){return this.getWrappableTokenService().fetchWrappableTokens(e)}async fetchAllWrappableTokens(){return this.getWrappableTokenService().fetchAllWrappableTokens()}async getWrappableToken(e){return this.getWrappableTokenService().getWrappableToken(e)}async getWrapCounterpart(e){return this.getWrappableTokenService().getWrapCounterpart(e)}async isTokenWrappable(e){return this.getWrappableTokenService().isTokenWrappable(e)}async wrapToken(e){return this.getWrapService().wrapToken(e)}async unwrapToken(e){return this.getWrapService().unwrapToken(e)}async estimateWrapFee(e,t){return this.getWrapService().estimateWrapFee(e,t)}async estimateUnwrapFee(e,t){return this.getWrapService().estimateUnwrapFee(e,t)}getWrapStatus(e){return this.getWrapService().getWrapStatus(e)}async login(){return this.sessionAuth.login()}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 disableChat(e){return this.getStreamChatService().disableChat(e)}async enableChat(e){return this.getStreamChatService().enableChat(e)}async getPinnedChatMessage(e){const t=this.getMessagesService(),n=await t.getPinnedMessage(e);return{tokenName:e,pinnedMessage:null===n.message?null:this.toLegacyPinnedMessage(n.message)}}async pinChatMessage(e,t){const n=this.getMessagesService();await n.pinMessage(t);const a=await n.getPinnedMessage(e);return{tokenName:e,pinnedMessage:null===a.message?null:this.toLegacyPinnedMessage(a.message)}}async unpinChatMessage(e){const t=this.getMessagesService(),n=await t.getPinnedMessage(e);return n.message?(await t.unpinMessage(n.message.id),{tokenName:e,unpinned:!0,unpinnedMessageId:n.message.id}):{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 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 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 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})).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})).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 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 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.setGlobalCallbacks(e)}async authenticateStreamWebSocket(){const e=this.getStreamWebSocketService(),t=await this.ensureValidToken();e.authenticate(t)}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.getStreamingEventService().onStreamStatusChanged(e)}onUserBanned(e){return this.getStreamingEventService().onUserBanned(e)}onUserUnbanned(e){return this.getStreamingEventService().onUserUnbanned(e)}onBanEnforcement(e){return this.getStreamingEventService().onBanEnforcement(e)}onContentFlagged(e){return this.getStreamingEventService().onContentFlagged(e)}onFlagResolved(e){return this.getStreamingEventService().onFlagResolved(e)}onStreamChatMessage(e){return this.getStreamingEventService().onStreamChatMessage(e)}onStreamChatUpdated(e){return this.getStreamingEventService().onStreamChatUpdated(e)}onStreamChatDeleted(e){return this.getStreamingEventService().onStreamChatDeleted(e)}onStreamChatPinned(e){return this.getStreamingEventService().onStreamChatPinned(e)}onStreamChatUnpinned(e){return this.getStreamingEventService().onStreamChatUnpinned(e)}onChatStatusChanged(e){return this.getStreamingEventService().onChatStatusChanged(e)}onViewerCountChanged(e){return this.getStreamingEventService().onViewerCountChanged(e)}onRecordingStatusChanged(e){return this.getStreamingEventService().onRecordingStatusChanged(e)}onSimulcastStatusChanged(e){return this.getStreamingEventService().onSimulcastStatusChanged(e)}onDownloadReady(e){return this.getStreamingEventService().onDownloadReady(e)}onRecordingsCountUpdated(e){return this.getStreamingEventService().onRecordingsCountUpdated(e)}onUserTyping(e){return this.getStreamingEventService().onUserTyping(e)}onStreamReaction(e){return this.getStreamingEventService().onStreamReaction(e)}onContentReactionAdded(e){return this.getStreamingEventService().onContentReactionAdded(e)}onContentReactionRemoved(e){return this.getStreamingEventService().onContentReactionRemoved(e)}onStreamCountdownUpdated(e){return this.getStreamingEventService().onStreamCountdownUpdated(e)}onStreamLanguageUpdated(e){return this.getStreamingEventService().onStreamLanguageUpdated(e)}onStreamControlStatusChanged(e){return this.getStreamingEventService().onStreamControlStatusChanged(e)}onConnection(e){return this.getStreamingEventService().onConnection(e)}onAuthenticated(e){return this.getStreamingEventService().onAuthenticated(e)}onTokenSubscribed(e){return this.getStreamingEventService().onTokenSubscribed(e)}onTokenUnsubscribed(e){return this.getStreamingEventService().onTokenUnsubscribed(e)}onRoomSubscribed(e){return this.getStreamingEventService().onRoomSubscribed(e)}onRoomLeft(e){return this.getStreamingEventService().onRoomLeft(e)}onEngagementStatsUpdated(e){return this.getStreamWebSocketService().subscribeEngagementStatsUpdated(e)}async estimateBridgeFee(e){return this.getBridgeService().estimateBridgeFee(e)}async bridgeOut(e){return this.getBridgeService().bridgeOut(e)}async bridgeIn(e){return this.getBridgeService().bridgeIn(e)}async getBridgeStatus(e,t){return this.getBridgeService().getBridgeStatus(e,t)}getSupportedBridgeTokens(){const e=this.getBridgeService(),t=e.getSupportedBridgeTokens();return Promise.resolve({tokens:t,totalCount:t.length,supportedChains:e.getSupportedBridgeChains()})}async fetchTokenBalance(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return la}),n=t(e.address);if(void 0!==e.tokenId&&""!==e.tokenId){const{normalizeToTokenInstanceKey:t}=await Promise.resolve().then(function(){return Hi}),a=t(e.tokenId),{collection:s,category:r,type:i,additionalKey:o}=a;return this.galaChainService.fetchTokenBalance({owner:n,collection:s,category:r,additionalKey:o,type:i,instance:"0"},e.withExpired??!1)}if(void 0!==e.tokenName&&""!==e.tokenName){const t=Vt(e.tokenName);if("MUSIC"===t||"GMUSIC"===t){const a=`$${t}`;return this.galaChainService.fetchTokenBalance({owner:n,collection:a,category:"Unit",additionalKey:"none",type:"none",instance:"0"},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 a=t.collection??"Token",s={collection:a,category:"Unit",type:t.symbol,additionalKey:"none"};return{quantity:t.balance,collection:a,category:"Unit",tokenId:Ms(s)}}throw Tt("tokenId or tokenName","Either tokenId or tokenName")}async fetchLockedBalance(e){const t=await this.fetchTokenBalance(e);if(!t)return null;const n="lockedHolds"in t||"lockedQuantity"in t;return{tokenId:t.tokenId,lockedQuantity:n?t.lockedQuantity??"0":"0",lockedHolds:n?t.lockedHolds??[]:[]}}async fetchAvailableBalance(e){const t=await this.fetchTokenBalance(e);if(!t)return null;const n="availableQuantity"in t;return{tokenId:t.tokenId,availableQuantity:n?t.availableQuantity??String(t.quantity):String(t.quantity),totalQuantity:String(t.quantity)}}async calculateBuyAmount(e){return this.launchpadAPI.calculateBuyAmount(e)}async calculateSellAmount(e){return this.launchpadAPI.calculateSellAmount(e)}async calculateBuyAmountLocal(e){return this.launchpadAPI.calculateBuyAmountLocal(e)}async calculateSellAmountLocal(e){return this.launchpadAPI.calculateSellAmountLocal(e)}async calculateBuyAmountExternal(e){return this.launchpadAPI.calculateBuyAmountExternal(e)}async calculateSellAmountExternal(e){return this.launchpadAPI.calculateSellAmountExternal(e)}async calculateBuyAmountForGraduation(e){return this.launchpadAPI.calculateBuyAmountForGraduation(e)}async graduateToken(e){const{tokenName:t,slippageToleranceFactor:n,maxAcceptableReverseBondingCurveFeeSlippageFactor:a,privateKey:s,calculateAmountMode:r,currentSupply:i}=e;let o=t;void 0===r&&void 0===i||(o={tokenName:t,...void 0!==r&&{calculateAmountMode:r},...void 0!==i&&{currentSupply:i}});const c=await this.calculateBuyAmountForGraduation(o),l={tokenName:t,amount:c.amount,type:"exact",expectedAmount:c.amount,maxAcceptableReverseBondingCurveFee:c.reverseBondingCurveFee,slippageToleranceFactor:this.slippageToleranceFactor};return void 0!==n&&(l.slippageToleranceFactor=n),void 0!==a&&(l.maxAcceptableReverseBondingCurveFeeSlippageFactor=a),void 0!==s&&(l.privateKey=s),await this.buy(l)}async calculateInitialBuyAmount(e){const t={nativeTokenQuantity:e};return this.launchpadAPI.calculateInitialBuyAmount(t)}async buy(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...a}=e;return t.buy(a)}this.validateWallet(),await this.ensureWebSocketConnection();const t=(await this.bundleService.buyToken(e)).data,n=t?.transactionId;if(void 0===n||""===n)throw Dt("No transaction ID returned from buy operation");return this.waitForConfirmation(n,t=>mu(t,n,"buy",e))}async sell(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...a}=e;return t.sell(a)}this.validateWallet(),await this.ensureWebSocketConnection();const t=(await this.bundleService.sellToken(e)).data,n=t?.transactionId;if(void 0===n||""===n)throw Dt("No transaction ID returned from sell operation");return this.waitForConfirmation(n,t=>mu(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,...a}=e;return t.launchToken(a)}this.validateWallet(),await this.ensureWebSocketConnection();const t=await this.launchpadAPI.launchToken(e);return this.waitForConfirmation(t,n=>{gu(n,t);const a=n.data??{};if(!function(e){if(Pn(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)}(a))throw new uu(`Invalid launch data received for transaction ${t}`);const s={transactionId:t,vaultAddress:a.vaultAddress??"",tokenStringKey:a.tokenStringKey??"",tokenName:e.tokenName,tokenSymbol:e.tokenSymbol,creatorAddress:a.creatorAddress??this.getAddress(),timestamp:Date.now(),...void 0!==n.blockHash&&""!==n.blockHash?{blockHash:n.blockHash}:{},...void 0!==n.gasUsed?{gasUsed:n.gasUsed}:{}};return"string"==typeof e.tokenImage&&(s.tokenImage=e.tokenImage),void 0!==e.preBuyQuantity&&(s.preBuyQuantity=e.preBuyQuantity),""!==s.vaultAddress&&this.tokenResolverService.set(e.tokenName,s.vaultAddress),s})}async uploadTokenImage(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...a}=e;return t.uploadTokenImage(a)}return this.validateWallet(),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 la}),n=t(e)??this.getAddress();return this.launchpadService.fetchProfile(n)}async fetchReferralUrl(){this.validateWallet();const e=this.getAddress();return await this.dexApiHttp.get(f,void 0,{"x-wallet-address":e})}async fetchReferrals(e){const t=await this.resolveReferralAddress(e?.address),n=e?.page??1,a=e?.limit??10,s={pageNumber:n,limit:a,sortBy:e?.sortBy??"joined",sortDir:e?.sortDir??"desc"},r=await this.dexApiHttp.get(y,s,{"x-wallet-address":t});if(!Array.isArray(r))throw new bt("Unexpected API response: expected array, got "+typeof r);return{referrals:r,page:n,limit:a,hasMore:r.length===a}}async fetchAllReferrals(e){const t=await Mi((t,n)=>this.fetchReferrals({...e,page:t,limit:n}).then(e=>({items:e.referrals,page:e.page,limit:e.limit,total:0,totalPages:0,hasNext:e.hasMore,hasPrevious:e.page>1})),{maxPages:100,pageSize:100,logger:this.logger});return{referrals:t.items,total:t.items.length}}async fetchReferralsSummary(e){const t=await this.resolveReferralAddress(e?.address),n=await this.dexApiHttp.get(v,void 0,{"x-wallet-address":t});if(void 0===n||"number"!=typeof n.referralCount||void 0===n.rewardTotals)throw new bt(`Unexpected API response: expected { referralCount, rewardTotals }, got ${JSON.stringify(n)}`);return n}async updateProfile(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return la}),n={...e,address:t(e.address)};if(void 0!==n.privateKey&&""!==n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...a}=n;return e.updateProfile(a)}return this.validateWallet(),this.launchpadService.updateProfile(n)}async uploadProfileImage(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return la}),n={...e,address:t(e.address)??this.getAddress()};if(void 0!==n.privateKey&&""!==n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...a}=n;return e.uploadProfileImage(a)}return this.validateWallet(),this.launchpadService.uploadProfileImage(n)}async fetchTokensHeld(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return la}),n=t(e?.address)??this.getAddress(),a={pageSize:e?.pageSize??10,address:n,...void 0!==e?.cursor?{cursor:e.cursor}:{}};return void 0!==e?.tokenName&&""!==e.tokenName&&(a.tokenName=e.tokenName),void 0!==e?.search&&""!==e.search&&(a.search=e.search),this.launchpadService.fetchTokensHeld(a)}async fetchTokensCreated(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return la}),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 fetchPriceHistory(e){return this.priceHistoryService.fetchPriceHistory(e)}async fetchAllPriceHistory(e){return this.priceHistoryService.fetchAllPriceHistory(e)}async transferGala(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return la}),n={...e,recipientAddress:t(e.recipientAddress)};if(void 0!==n.privateKey&&""!==n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...a}=n;return e.transferGala(a)}return this.validateWallet(),this.galaChainService.transferGala(n)}async transferToken(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return la}),n={...e,to:t(e.to)};if(void 0!==n.privateKey&&""!==n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...a}=n;return e.transferToken(a)}return this.validateWallet(),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 la});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,...a}=n;return e.lockTokens(a)}return this.validateWallet(),this.galaChainService.lockTokens(n)}async unlockTokens(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...a}=e;return t.unlockTokens(a)}return this.validateWallet(),this.galaChainService.unlockTokens(e)}async burnTokens(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...a}=e;return t.burnTokens(a)}return this.validateWallet(),this.galaChainService.burnTokens(e)}async resolveVaultAddress(e){return this.tokenResolverService.resolveTokenToVault(e)}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{Rn(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 It("baseUrl is required in configuration","baseUrl");if(void 0===this.config.webSocketUrl||""===this.config.webSocketUrl)throw It("webSocketUrl is required in configuration","webSocketUrl");try{new URL(this.config.baseUrl)}catch{throw It(`Invalid baseUrl format: ${this.config.baseUrl}`,"baseUrl")}try{new URL(this.config.webSocketUrl)}catch{throw It(`Invalid webSocketUrl format: ${this.config.webSocketUrl}`,"webSocketUrl")}if(void 0!==this.config.gatewayBaseUrl&&""!==this.config.gatewayBaseUrl)try{new URL(this.config.gatewayBaseUrl)}catch{throw It(`Invalid gatewayBaseUrl format: ${this.config.gatewayBaseUrl}`,"gatewayBaseUrl")}if(void 0!==this.config.bundleBaseUrl&&""!==this.config.bundleBaseUrl)try{new URL(this.config.bundleBaseUrl)}catch{throw It(`Invalid bundleBaseUrl format: ${this.config.bundleBaseUrl}`,"bundleBaseUrl")}if(void 0!==this.config.launchpadFrontendUrl&&""!==this.config.launchpadFrontendUrl)try{new URL(this.config.launchpadFrontendUrl)}catch{throw It(`Invalid launchpadFrontendUrl format: ${this.config.launchpadFrontendUrl}`,"launchpadFrontendUrl")}}parseSlippageToleranceFactor(e){const t=An("string"==typeof e||"number"==typeof e?e:String(e),fu.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR);return t<0||t>1?(this.logger.warn(`Invalid slippage tolerance factor: ${String(e)}, using default: ${fu.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR}`),fu.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR):t}parseFeeSlippageFactor(e){const t=An("string"==typeof e||"number"==typeof e?e:String(e),fu.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: ${fu.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR}`),fu.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!==vi.COMPLETED)throw new hu(e,n.status,n.message);let a;try{a=t(n)}catch(t){if(t instanceof uu)throw t;throw new uu(`Failed to transform WebSocket response for transaction ${e}`,at(t)?t:new Error(st(t)))}return this.logger.debug(`Transaction confirmed: ${e}`,a),a}catch(t){if(this.logger.error(`Transaction confirmation failed: ${e}`,t),t instanceof hu||t instanceof uu)throw t;throw new uu(`WebSocket confirmation failed for transaction ${e}`,at(t)?t:new Error(st(t)))}}async warmCacheFromPools(e){if(void 0===e||!Array.isArray(e))return;const{extractMetadataFromPoolData:t,isValidPoolForCaching:n}=await Promise.resolve().then(function(){return wu});e.forEach(e=>{if(!n(e))return;const a=t(e,this.logger);a&&this.launchpadAPI.warmCacheFromPoolData(e.tokenName,a)})}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,a=Math.max(t?.intervalMs??3e4,n);null!=t?.intervalMs&&t.intervalMs<n&&this.logger.warn(`Poll interval ${t.intervalMs}ms is below minimum 1000ms. Using minimum interval instead.`);const s=t?.creatorAddress,r=new Map;let i=!0,o=null;let c=0;const l=async()=>{if(i){try{const t=await this.fetchPools({type:"recent",pageSize:20});c>0&&(this.logger.debug("Successfully recovered from polling errors"),c=0),t.items.forEach(t=>{r.has(t.tokenName)||((e=>{if(r.set(e,!0),r.size>1e3){const e=r.keys().next().value;void 0!==e&&r.delete(e)}})(t.tokenName),void 0!==s&&""!==s&&t.creatorAddress!==s||e(t))})}catch(e){c++;const t=st(e);c>=5?this.logger.error(`Polling for new launchpad tokens failed ${c} consecutive times. Last error: ${t}. Continuing to retry...`):c>1?this.logger.warn(`Error polling for new launchpad tokens (attempt ${c}/5): ${t}`):this.logger.debug(`Error polling for new launchpad tokens: ${t}`)}if(i){const e=Math.min(Math.max(c-1,0),2),t=a*Math.pow(2,e);o=setTimeout(()=>{l()},t)}}};return l(),()=>{i=!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 It("WebSocket service not initialized. Ensure websocketUrl is configured and the service is connected.","websocketService");let n=!1,a=null;const s=(n,...a)=>{try{if(a.length>0&&"object"==typeof a[0]&&null!==a[0]){const n=a[0].data;if(void 0!==n?.Data&&null!==n.Data&&"object"==typeof n.Data){const a=n.Data;if("CreateSale"===a.functionName){const n={tokenName:""!==a.tokenName?a.tokenName:"",symbol:""!==a.symbol?a.symbol:"",creatorAddress:""!==a.creatorAddress?a.creatorAddress:"",description:""!==a.description?a.description:"",image:""!==a.image?a.image:"",vaultAddress:""!==a.vaultAddress?a.vaultAddress:"",tokenStringKey:""!==a.tokenStringKey?a.tokenStringKey:"",preBuyQuantity:""!==a.initialBuyQuantity?a.initialBuyQuantity:"0",websiteUrl:""!==a.websiteUrl?a.websiteUrl:"",telegramUrl:""!==a.telegramUrl?a.telegramUrl:"",twitterUrl:""!==a.twitterUrl?a.twitterUrl:"",instagramUrl:""!==a.instagramUrl?a.instagramUrl:"",facebookUrl:""!==a.facebookUrl?a.facebookUrl:"",redditUrl:""!==a.redditUrl?a.redditUrl:"",tiktokUrl:""!==a.tiktokUrl?a.tiktokUrl:"",isFinalized:!1!==a.isFinalized&&null!==a.isFinalized&&void 0!==a.isFinalized&&a.isFinalized};this.matchesCreatorFilter(n,t?.creatorFilter)&&e(n)}}}}catch(e){this.logger.warn(`Error processing token creation broadcast: ${st(e)}`)}};let r=this.websocketService.getSocket();if(r)r.onAny(s),n=!0,this.logger.debug("Token creation broadcast listener registered");else{this.logger.debug("WebSocket not yet connected, initiating connection..."),this.websocketService.connect().catch(e=>{const n=new Error(`WebSocket connection failed: ${st(e)}`);this.logger.warn("Failed to establish WebSocket connection:",e),t?.onError&&t.onError(n)});let e=0;const i=()=>{if(r=this.websocketService.getSocket(),!r&&e<fu.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS)return e++,void(a=setTimeout(()=>i(),fu.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS));if(!r&&e>=fu.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS){const e=new Error(`WebSocket not available after ${fu.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS*fu.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS}ms`);return this.logger.warn("Token creation broadcast subscription timeout:",e.message),void(t?.onError&&t.onError(e))}r&&(r.onAny(s),n=!0,this.logger.debug("Token creation broadcast listener registered"))};i()}return()=>{try{if(null!==a&&(clearTimeout(a),a=null,this.logger.debug("Cleared token creation broadcast polling timeout")),!n)return void this.logger.debug("Cleanup called before listener registration - no action needed");const e=this.websocketService.getSocket();e&&(e.offAny(s),n=!1,this.logger.debug("Stopped listening to token creation broadcasts"))}catch(e){this.logger.warn("Error removing token creation listener:",e)}}}getNftCollectionClaimFee(){return this.nftCollectionService.getCollectionClaimFee()}getNftTokenClassCreateFee(){return this.nftCollectionService.getTokenClassCreateFee()}estimateNftMintFee(e){return this.nftCollectionService.estimateMintFee(e)}estimateNftOperationFees(e){return this.nftCollectionService.estimateNftOperationFees(e)}claimNftCollection(e){return this.nftCollectionService.claimCollection(e)}fetchNftCollections(e){return this.nftCollectionService.fetchUserCollections(e)}isNftCollectionAvailable(e){return this.nftCollectionService.isCollectionAvailable(e)}createNftTokenClass(e){return this.nftCollectionService.createTokenClass(e)}fetchNftTokenClasses(e){return this.nftCollectionService.fetchTokenClasses(e)}mintNft(e){return this.nftCollectionService.mintNft(e)}fetchNftBalances(e,t){return this.nftCollectionService.fetchNftBalances(e,t)}async cleanup(){try{if(this.logger.debug("Starting cleanup..."),void 0!==this._eventsBatcherService)try{await this._eventsBatcherService.shutdown(5e3),this._eventsBatcherService=void 0}catch(e){this.logger.warn("Error during events shutdown:",e)}this.http.cleanup(),null!==this.websocketService&&void 0!==this.websocketService&&this.websocketService.disconnect(),void 0!==this._streamWebSocketService&&(this._streamWebSocketService.disconnect(),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 Qt({debug:e,context:"LaunchpadSDK"});t.debug("Starting global cleanup..."),Dd.cleanupAll(e),t.debug("Global cleanup completed")}}function yu(){const e=globalThis;return e.process?.env??{}}fu.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR=.15,fu.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR=.01,fu.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY=qt.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY,fu.DEFAULT_CALCULATE_AMOUNT_MODE="local",fu.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS=30,fu.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS=100;let vu=0;class ku{constructor(){this.utilityInstance=!0,this.utilityInstance}static generateWallet(){try{const e=t.Wallet.createRandom();if(null===e.mnemonic?.phrase||void 0===e.mnemonic?.phrase||""===e.mnemonic.phrase)throw Tt("mnemonic","Mnemonic phrase");const n=ku.toGalaAddress(e.address);return{privateKey:e.privateKey,address:e.address,galaAddress:n,mnemonic:e.mnemonic.phrase,wallet:new t.Wallet(e.privateKey)}}catch(e){if("test"===yu().NODE_ENV){const e=`test-wallet-${Date.now()}-${++vu}`,n="0x"+Buffer.from(e).toString("hex").padStart(64,"1").slice(0,64),a=new t.Wallet(n),s=ku.toGalaAddress(a.address);return{privateKey:a.privateKey,address:a.address,galaAddress:s,mnemonic:"test test test test test test test test test test test junk",wallet:a}}throw e}}static fromPrivateKey(e){const n=new t.Wallet(e),a=ku.toGalaAddress(n.address);return{privateKey:n.privateKey,address:n.address,galaAddress:a,mnemonic:"",wallet:n}}static fromMnemonic(e,n=0){try{const a=t.Mnemonic.fromPhrase(e),s=t.HDNodeWallet.fromMnemonic(a,`m/44'/60'/0'/0/${n}`),r=new t.Wallet(s.privateKey),i=ku.toGalaAddress(r.address);return{privateKey:r.privateKey,address:r.address,galaAddress:i,mnemonic:e,wallet:r}}catch(a){if("test"===yu().NODE_ENV){const a=`test-mnemonic-index-${n}-${e}`,s="0x"+Buffer.from(a).toString("hex").padStart(64,"1").slice(0,64),r=new t.Wallet(s),i=ku.toGalaAddress(r.address);return{privateKey:r.privateKey,address:r.address,galaAddress:i,mnemonic:e,wallet:r}}throw a}}static toGalaAddress(e){const n=aa(e);if(!/^[a-fA-F0-9]{40}$/.test(n))throw Ct("address","a valid Ethereum address (40 hex characters)");return`eth|${t.getAddress(`0x${n}`).slice(2)}`}static toEthereumAddress(e){try{return ra(e)}catch(t){const n=st(t);if(n.includes("required")||!e?.startsWith("eth|"))throw Tt("galaAddress","Gala address starting with eth|");if(n.includes("Invalid backend"))throw Ct("galaAddress","Gala format (eth|{40-hex-chars})");throw t}}static isValidEthereumAddress(e){try{const t=aa(e);return/^[a-fA-F0-9]{40}$/.test(t)}catch{return!1}}static isValidGalaAddress(e){return""!==e&&"backend"===ca(e)}static generateMultipleWallets(e=1){Rn(e,1,100,"count");const t=[];if("test"===yu().NODE_ENV)for(let n=0;n<e;n++){const e=`test-multi-${n}-${Date.now()}-${++vu}`,a="0x"+Buffer.from(e).toString("hex").padStart(64,"1").slice(0,64);t.push(ku.fromPrivateKey(a))}else for(let n=0;n<e;n++)t.push(ku.generateWallet());return t}static getWalletSummary(e,t=!1){const n=["🔐 Wallet Information","═".repeat(50),`📍 Address: ${e.address}`,`🎮 Gala Address: ${e.galaAddress}`,`🌱 Mnemonic: ${null!==e.mnemonic&&void 0!==e.mnemonic&&""!==e.mnemonic?e.mnemonic:"Not available"}`];return t?n.splice(3,0,`🔑 Private Key: ${e.privateKey}`):n.splice(3,0,"🔑 Private Key: [HIDDEN - use includeSensitive=true to show]"),n.push("═".repeat(50)),n.push("💾 IMPORTANT: Save your mnemonic phrase securely!"),n.push("This is your backup to recover the wallet."),n.join("\n")}}function bu(e){if(void 0===e)return ku.generateWallet();const t=e.trim();if(!Un(t))throw Ct("input","a non-empty string");if(function(e){const t=aa(e);return/^[a-fA-F0-9]{64}$/.test(t)}(t))return ku.fromPrivateKey(t);if(function(e){const t=e.split(/\s+/).filter(e=>e.length>0);if(12!==t.length&&24!==t.length)return!1;return t.every(e=>/^[a-zA-Z]+$/.test(e))}(t))return ku.fromMnemonic(t);throw Ct("input","a private key (64 hex characters) or mnemonic (12/24 words)","Wallet input")}var wu=Object.freeze({__proto__:null,extractMetadataFromPoolData:function(e,t){const n={};if(void 0!==e.vaultAddress&&(n.vaultAddress=e.vaultAddress),void 0!==e.reverseBondingCurveMinFeePortion){const a=An(e.reverseBondingCurveMinFeePortion,NaN);isNaN(a)?t&&t.debug(`Skipping invalid reverseBondingCurveMinFeePortion for ${e.tokenName}: "${e.reverseBondingCurveMinFeePortion}"`):n.reverseBondingCurveMinFeeFactor=a}if(void 0!==e.reverseBondingCurveMaxFeePortion){const a=An(e.reverseBondingCurveMaxFeePortion,NaN);isNaN(a)?t&&t.debug(`Skipping invalid reverseBondingCurveMaxFeePortion for ${e.tokenName}: "${e.reverseBondingCurveMaxFeePortion}"`):n.reverseBondingCurveMaxFeeFactor=a}return void 0!==n.reverseBondingCurveMaxFeeFactor&&void 0!==n.reverseBondingCurveMinFeeFactor&&(n.reverseBondingCurveNetFeeFactor=n.reverseBondingCurveMaxFeeFactor-n.reverseBondingCurveMinFeeFactor),Object.keys(n).length>0?n:null},isValidPoolForCaching:function(e){if(null===e||"object"!=typeof e)return!1;const t=e;return"tokenName"in t&&"string"==typeof t.tokenName&&t.tokenName.length>0}});exports.BrowserWalletSigner=go,exports.EVENT_TYPES={LOGIN:"login",LOGOUT:"logout",TOKEN_BUY:"token_buy",TOKEN_SELL:"token_sell",TOKEN_SWAP:"token_swap",TOKEN_CREATED:"token_created",TOKEN_GRADUATED:"token_graduated",PAGE_VIEW:"page_view",PAGE_LEAVE:"page_leave",STREAM_START:"stream_start",STREAM_END:"stream_end",STREAM_VIEWERS_CHANGED:"stream_viewers_changed",CHAT_MESSAGE_SENT:"chat_message_sent",CHAT_MESSAGE_RECEIVED:"chat_message_received",LIQUIDITY_ADDED:"liquidity_added",LIQUIDITY_REMOVED:"liquidity_removed",BRIDGE_DEPOSIT:"bridge_deposit",BRIDGE_WITHDRAW:"bridge_withdraw",PROFILE_UPDATED:"profile_updated",BALANCE_CHANGED:"balance_changed",ERROR_OCCURRED:"error_occurred"},exports.GalaWalletSigner=ho,exports.LaunchpadSDK=fu,exports.LaunchpadSDKError=Bd,exports.PrivateKeySigner=uo,exports.SDK_VERSION=bi,exports.TransactionFailedError=hu,exports.WebSocketError=uu,exports.WebSocketTimeoutError=class extends uu{constructor(e,t){super(`WebSocket confirmation timeout for transaction ${e} after ${t}ms`),this.name="WebSocketTimeoutError"}},exports.createLaunchpadSDK=function(e){Pn(e)&&(e={});const{wallet:n,env:a,config:s={},...r}=e,i={...{...r,...s}};delete i.wallet,delete i.env,delete i.config;const o=!Pn(i.signer)||!Pn(i.walletProvider);let c;if(Pn(n))c=o?void 0:bu().wallet;else if("string"==typeof n){c=bu(n).wallet}else{if(!(n instanceof t.Wallet))throw It("Invalid wallet input. Expected string (private key or mnemonic) or Wallet instance.","wallet");c=n}const l={...void 0!==c?{wallet:c}:{},...void 0!==a?{env:a}:{},debug:!1,timeout:3e4,...i};return new fu(l)},exports.createWallet=bu,exports.generateEIP712Types=ro,exports.getEthereumAddressFromPrivateKey=function(e){if(!e.match(/^0x[a-fA-F0-9]{64}$/))throw Ct("privateKey","0x-prefixed 64 hexadecimal characters","Private key");return t.getAddress(t.computeAddress(e))},exports.getPublicKeyFromPrivateKey=function(e){if(!e.match(/^0x[a-fA-F0-9]{64}$/))throw Ct("privateKey","0x-prefixed 64 hexadecimal characters","Private key");const n=new t.SigningKey(e);return{publicKey:n.publicKey,compressedPublicKey:n.compressedPublicKey}};
|