@gala-chain/launchpad-sdk 7.0.0-beta.5 → 7.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/LaunchpadSDK.d.ts +344 -1
- package/dist/LaunchpadSDK.d.ts.map +1 -1
- package/dist/api/dto/BondingCurveDTOs.d.ts +1 -1
- package/dist/bridge/BridgeService.d.ts.map +1 -1
- package/dist/bridge/constants/tokens.d.ts.map +1 -1
- package/dist/bridge/types/bridgeable-token.dto.d.ts +6 -2
- package/dist/bridge/types/bridgeable-token.dto.d.ts.map +1 -1
- package/dist/bridge/utils/tokenMetadataResolver.d.ts +2 -2
- package/dist/bridge/utils/tokenMetadataResolver.d.ts.map +1 -1
- package/dist/constants/version.generated.d.ts +1 -1
- package/dist/constants/version.generated.d.ts.map +1 -1
- package/dist/index.browser.d.ts +1 -2
- package/dist/index.browser.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/strings-instructions.d.ts.map +1 -1
- package/dist/native.cjs +1 -1
- package/dist/native.esm.js +1 -1
- package/dist/react/index.d.ts +1 -1
- package/dist/react/index.d.ts.map +1 -1
- package/dist/react.cjs +1 -1
- package/dist/react.esm.js +1 -1
- package/dist/services/BridgeableTokenService.d.ts.map +1 -1
- package/dist/services/DexService.d.ts +8 -1
- package/dist/services/DexService.d.ts.map +1 -1
- package/dist/services/LaunchpadService.d.ts +7 -0
- package/dist/services/LaunchpadService.d.ts.map +1 -1
- package/dist/services/PoolService.d.ts +22 -0
- package/dist/services/PoolService.d.ts.map +1 -1
- package/dist/services/StreamWebSocketService.d.ts +10 -0
- package/dist/services/StreamWebSocketService.d.ts.map +1 -1
- package/dist/services/TokenClassKeyService.d.ts +0 -22
- package/dist/services/TokenClassKeyService.d.ts.map +1 -1
- package/dist/tokens/transfers.d.ts +6 -2
- package/dist/tokens/transfers.d.ts.map +1 -1
- package/dist/utils/data-transform-patterns.d.ts +1 -1
- package/dist/utils/data-transform-patterns.d.ts.map +1 -1
- package/dist/utils/delimiter-parser.d.ts +3 -2
- package/dist/utils/delimiter-parser.d.ts.map +1 -1
- package/dist/utils/token-format-converter.d.ts +15 -130
- package/dist/utils/token-format-converter.d.ts.map +1 -1
- package/dist/utils/token-instance-resolver.d.ts +5 -3
- package/dist/utils/token-instance-resolver.d.ts.map +1 -1
- package/dist/utils/token-parser.d.ts +2 -2
- package/dist/utils/token-parser.d.ts.map +1 -1
- package/dist/utils/tokenNormalizer.d.ts +2 -1
- package/dist/utils/tokenNormalizer.d.ts.map +1 -1
- package/dist/utils/validation.d.ts +0 -16
- package/dist/utils/validation.d.ts.map +1 -1
- package/dist/wallet/detection.d.ts.map +1 -1
- package/dist/wallet/index.d.ts +3 -4
- package/dist/wallet/index.d.ts.map +1 -1
- package/dist/wallet/types.d.ts +2 -2
- package/dist/wallet.cjs +1 -1
- package/dist/wallet.esm.js +1 -1
- package/package.json +3 -7
- package/dist/services/TokenMetadataService.d.ts +0 -509
- package/dist/services/TokenMetadataService.d.ts.map +0 -1
- package/dist/wallet/GalaChainConnectProvider.d.ts +0 -125
- package/dist/wallet/GalaChainConnectProvider.d.ts.map +0 -1
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("ethers"),t=require("@gala-chain/gswap-sdk"),n=require("zod"),r=require("uuid"),s=require("node:crypto"),i=require("@gala-chain/api"),o=require("bignumber.js"),a=require("socket.io-client"),c=require("axios"),l=require("dotenv"),u=require("fs"),d=require("path");function h(e){var t=Object.create(null);return e&&Object.keys(e).forEach(function(n){if("default"!==n){var r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:function(){return e[n]}})}}),t.default=e,Object.freeze(t)}var g=h(r),f=h(s),p=h(l),m=h(u),y=h(d);const b={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"},v="/v1/users/referrals/url",w="/v1/users/referrals",E="/v1/users/referrals/summary",A="/market/price-series",S="/v1/tokens/:tokenName/start-stream",k="/v1/tokens/:tokenName/stop-stream",T="/v1/tokens/:tokenName/stream/disable",I="/v1/tokens/:tokenName/stream/enable",C="/v1/tokens/:tokenName/reset-key",N="/v1/tokens/:tokenName/recordings",_="/v1/tokens/:tokenName/recordings/:assetId/download",x="/v1/tokens/:tokenName/recordings/:assetId",R="/v1/tokens/:tokenName/simulcasts",B="/v1/tokens/:tokenName/simulcasts",D="/v1/tokens/:tokenName/simulcasts/:targetId",O="/v1/config",M="/v1/config",L="/v1/config",U="/v1/tokens/:tokenName/role",P="/v1/roles",F="/v1/permissions",$="/v1/tokens/:tokenName/credentials",K="/auth/login",G="/auth/logout",H="/auth/refresh",W="/auth/session",q="/v1/tokens/:tokenName/bans",z="/v1/tokens/:tokenName/bans",V="/v1/tokens/:tokenName/bans/:userAddress",j="/v1/tokens/:tokenName/bans/:userAddress",X="/v1/tokens/:tokenName/active-users",Y="/v1/user-bans",J="/v1/user-bans",Q="/v1/user-bans/:userAddress",Z="/v1/user-bans/:userAddress",ee={CREATE:"/v1/api-keys",LIST:"/v1/api-keys",GET:"/v1/api-keys/:id",UPDATE:"/v1/api-keys/:id",REVOKE:"/v1/api-keys/:id"},te="/v1/moderator-invites",ne="/v1/moderator-invites/claim",re="/v1/moderated-tokens",se="/v1/moderator-invites",ie="/v1/moderator-invites/:id",oe="/v1/moderator-invites/:id/role",ae="/v1/moderator-invites/:id",ce="/v1/moderator-invites/code/:code",le={CREATE:"/v1/content-flags",LIST:"/v1/content-flags",DISMISS:"/v1/content-flags/:id/dismiss",ACTION:"/v1/content-flags/:id/action"},ue="/v1/overseer-invites",de="/v1/overseer-invites",he="/v1/overseer-invites/code/:code",ge="/v1/overseer-invites/claim",fe="/v1/overseer-invites/:id",pe="/v1/overseers",me="/v1/overseers",ye="/v1/overseers/:address",be="/v1/overseers/me",ve="/v1/overseer-summary",we="/v1/overseer-summary/bans",Ee="/v1/overseer-summary/token-bans",Ae="/v1/overseer-summary/invites",Se="/v1/overseer-summary/flags",ke="/v1/overseer-summary/users",Te="/v1/users",Ie="/v1/users/:address/summary",Ce="/v1/cache/flush/address/:address",Ne="/v1/cache/flush/token/:tokenName",_e="/v1/cache/flush/all",xe="/v1/cache/flush/wallet-aliases/:address",Re="/v1/cache/flush/wallet-aliases",Be="/v1/token-bans",De="/v1/token-bans",Oe="/v1/token-bans/:tokenName",Me="/v1/token-bans/:tokenName",Le="/v1/reactions",Ue="/v1/reactions",Pe="/v1/trades",Fe={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"},$e="/v1/restricted-token-names",Ke="/v1/restricted-token-names",Ge="/live/:tokenName/chat",He="/live/:tokenName/chat",We="/live/:tokenName/chat",qe="/live/:tokenName/chat/slow-mode",ze={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"},Ve="/v1/stats",je="/v1/trading/fee",Xe="/v1/trading/sale-details",Ye="/v1/trading/quote",Je="/v1/trading/premint-quote",Qe={GET_LEADERBOARD:"/weekly-challenge",GET_TOKEN_HISTORY:"/weekly-challenge/history/:vaultAddress"},Ze="/v1/notifications/register",et="/v1/notifications/unregister",tt="/v1/notifications/preferences",nt="/v1/notifications/preferences",rt="/v1/config/client-flags",st={NATIVE:"native",EXACT:"exact"},it={LOCAL:"local",EXTERNAL:"external"};function ot(e){return e instanceof Error}function at(e){return ot(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 ct(e){return ot(e)||"object"==typeof e&&null!==e&&"stack"in e&&"string"==typeof e.stack?e.stack:void 0}function lt(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 ut(e){return"object"==typeof e&&null!==e&&"message"in e&&("response"in e||"request"in e||"config"in e)}function dt(e,t){if(null==e||"object"!=typeof e)throw new Error(`${t}: No response - expected object, got ${typeof e}`);const n=e;if(!("Status"in n))throw new Error(`${t}: Response missing 'Status' property`);const r=n.Status;if("number"!=typeof r)throw new Error(`${t}: Response Status must be a number, got ${typeof r}`);if(1!==r)throw new Error(`${t}: Response status indicates failure (Status: ${r})`);return n}function ht(e){if(null==e||"object"!=typeof e)return"";const t=e.Message;return"string"==typeof t&&t.trim().length>0?` - ${t}`:""}function gt(e,t,n){try{t()}catch(t){if(!function(e){return e instanceof Error&&"ValidationError"===e.name}(t))throw t;{const n=t.message;e.push(n)}}}const ft="Token name is required and must be a string",pt=e=>`Could not find vault address for token: ${e}`,mt={REQUIRED:"REQUIRED",INVALID_TYPE:"INVALID_TYPE",INVALID_VALUE:"INVALID_VALUE",INVALID_FORMAT:"INVALID_FORMAT",TOO_SHORT:"TOO_SHORT",TOO_LONG:"TOO_LONG",TOO_LARGE:"TOO_LARGE",TOO_SMALL:"TOO_SMALL",EMPTY_ARRAY:"EMPTY_ARRAY",ARRAY_TOO_LARGE:"ARRAY_TOO_LARGE",ZERO_VALUE:"ZERO_VALUE",INVALID_TICK_SPACING:"INVALID_TICK_SPACING",INVALID_FEE_TIER:"INVALID_FEE_TIER",INVALID_RANGE:"INVALID_RANGE",INVALID_PARAMETERS:"INVALID_PARAMETERS",NOT_FOUND:"NOT_FOUND",INVALID_DATA:"INVALID_DATA"};class yt 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 vt extends Error{constructor(e,t){super(e),this.field=t,this.name="ConfigurationError"}}class wt 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 At(e,t){return new yt(`Token "${e}" not found. Please verify the token name is correct.`,"tokenName","TOKEN_NOT_FOUND")}function St(e,t){const n=Et(e,t);return new yt(`${n} is required`,e,"REQUIRED")}function kt(e,t,n){const r=Et(e,n);return new yt(`${r} must be ${t}`,e,"INVALID_FORMAT")}function Tt(e,t,n){return new bt(e,t,n)}function It(e,t){return new vt(e,t)}function Ct(e,t,n){return new wt(e,t,n)}function Nt(e,t,n,r){n&&n.error(`${t}:`,e);const s=ut(e)?e.response?.status:void 0;return Tt(`${t}: ${at(e)}`,s,ot(e)?e:void 0)}function _t(e,t,n,r,s){const i=Et(e,s);return new yt(`${i} must be between ${t} and ${n}${void 0!==r?`, received: ${r}`:""}`,e,"OUT_OF_RANGE")}function xt(e,t,n,r){const s=Et(e,r);return new yt(`${s} must be at least ${t}${void 0!==n?`, received: ${n}`:""}`,e,"TOO_SMALL")}function Rt(e,t,n,r){const s=Et(e,r);return new yt(`${s} must be at most ${t}${void 0!==n?`, received: ${n}`:""}`,e,"TOO_LARGE")}function Bt(e,t,n,r){const s=Et(e,r),i=void 0!==n?`, received: ${"object"==typeof n?"object":String(n)}`:"";return new yt(`${s} must be ${t}${i}`,e,"INVALID_TYPE")}function Dt(e,t,n){const r=Et(e,n);return new yt(`${r} must be a valid number${void 0!==t?`: "${t}"`:""}`,e,"INVALID_NUMBER")}function Ot(e,t,n,r){const s=Et(e,r);return new yt(`Invalid ${s}: ${t}. Must be one of: ${n.join(", ")}`,e,"INVALID_ENUM")}function Mt(e,t){if(e.length<2)return St(void 0!==e[0]&&""!==e[0]?e[0]:"field");let n;if(2===e.length)n=e.join(" or ");else{n=`${e.slice(0,-1).join(", ")} or ${e[e.length-1]??"field"}`}return new yt(`At least one of ${n} must be provided`,e[0],"REQUIRED")}function Lt(e,t,n,r){const s=Et(e,r);return new yt(`${s} must be at most ${t} characters${void 0!==n?`, received: ${n}`:""}`,e,"TOO_LONG")}function Ut(e,t){const n=Et(e,t);return new yt(`${n} cannot be empty`,e,"EMPTY_STRING")}function Pt(e){return null!=e&&"object"==typeof e&&"data"in e}function Ft(e,t,n=!1){const r=!0===e.error,s=n&&(null===e.data||void 0===e.data);if(r||s){const n=e?.statusCode??e.status??void 0;throw Tt(e?.message??t,n)}}function $t(e){if(Pt(e))return e.data}function Kt(e,t="No data found in response"){if(!Pt(e))throw Tt(t);const n=e.data;if(null==n)throw Tt(t);return n}async function Gt(e,t={}){return qt(e,t,e=>{if(void 0===e.data)throw new yt(`${t.errorContext??"Operation failed"}: No data returned from API`,"data","NO_DATA");return e.data})}async function Ht(e,t={}){const{errorContext:n="Operation failed",logger:r,debugLogEnabled:s=!1}=t;s&&r&&r.debug(`${n}: starting operation`);try{const t=await e();return s&&r&&r.debug(`${n}: completed successfully`),t}catch(e){throw r&&r.error(n,{error:e}),e}}async function Wt(e,t={}){return qt(e,t,e=>e)}async function qt(e,t,n){const{errorContext:r="Operation failed",logger:s,debugLogEnabled:i=!1}=t;i&&s&&s.debug(`${r}: starting operation`);try{const t=await e();if(null==t)throw new yt(`${r}: No response from server`,"response","NO_RESPONSE");return Ft(t,r,!0),i&&s&&s.debug(`${r}: completed successfully`),n(t)}catch(e){throw s&&s.error(r,{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 Vt(e){return e.trim().toLowerCase()}function jt(e){return e.trim().toUpperCase()}function Xt(e){return e.trim().toUpperCase()}var Yt;!function(e){e.DEBUG="DEBUG",e.INFO="INFO",e.WARN="WARN",e.ERROR="ERROR"}(Yt||(Yt={}));class Jt{constructor(e){this.levelPriority={[Yt.DEBUG]:0,[Yt.INFO]:1,[Yt.WARN]:2,[Yt.ERROR]:3},this.debugEnabled=e.debug,this.context=e.context??"SDK",this.minLevel=e.minLevel??(e.debug?Yt.DEBUG:Yt.INFO)}debug(e,t){this.log(Yt.DEBUG,e,t)}info(e,t){this.log(Yt.INFO,e,t)}warn(e,t){this.log(Yt.WARN,e,t)}error(e,t){this.log(Yt.ERROR,e,t)}log(e,t,n){if(this.levelPriority[e]<this.levelPriority[this.minLevel])return;if(e===Yt.DEBUG&&!this.debugEnabled)return;const r=`[${(new Date).toISOString()}] [${this.context}] [${e}]`,s=this.getConsoleMethod(e);void 0!==n?ot(n)?s(`${r} ${t}`,n.message,ct(n)??""):s(`${r} ${t}`,n):s(`${r} ${t}`)}getConsoleMethod(e){switch(e){case Yt.DEBUG:return console.debug;case Yt.INFO:return console.info;case Yt.WARN:return console.warn;case Yt.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[Yt.DEBUG]>=this.levelPriority[this.minLevel]}}function Qt(e){return"string"==typeof e&&e.trim().length>0}function Zt(e){return null==e||""===e}function en(e){return null==e}const tn=new Jt({debug:!1,context:"DateUtils"});function nn(e,t){if(null==e)return new Date;if(e instanceof Date)return isNaN(e.getTime())?new Date:e;try{const t=new Date(e);return isNaN(t.getTime())?(tn.warn(`Invalid date string received: "${e}". Using fallback.`),new Date):t}catch(t){return tn.warn(`Date parsing error for "${e}":`,t),new Date}}function rn(e){if(null==e)return!1;if(e instanceof Date)return!isNaN(e.getTime());if("string"!=typeof e)return!1;const t=new Date(e);return!isNaN(t.getTime())}function sn(e){return Date.now()-e}const on={MIN_LENGTH:3,MAX_LENGTH:20,PATTERN:/^[a-zA-Z0-9]{3,20}$/},an={MIN_LENGTH:2,MAX_LENGTH:20,PATTERN:/^[a-zA-Z0-9]+$/},cn={MIN_LENGTH:1,MAX_LENGTH:50},ln=100,un=20,dn={MAX_LIMIT:50,DEFAULT_OFFSET:0,DEFAULT_LIMIT:20},hn={PATTERN:/^(eth\|[0-9a-fA-F]{40}|client\|[a-zA-Z0-9_-]+)$/},gn={MAX_LENGTH:100},fn={COMMENTS_V1:{MAX_LENGTH:2e3},CHAT_MESSAGE:{MIN_LENGTH:1,MAX_LENGTH:500},CHAT_MESSAGES_V1:{MAX_LENGTH:500},BAN_REASON:{MAX_LENGTH:500},DESCRIPTION:{MAX_LENGTH:255},FLAG_DETAILS:{MAX_LENGTH:1e3},CONTENT_ID:{MAX_LENGTH:100}},pn={CHAT_MESSAGE:{PATTERN:/^chat-\d{13}-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i},CONTENT_REACTION:{MAX_LENGTH:64,PATTERN:/^(msg-\d{13}-[a-f0-9]{32}|chat-\d{13}-[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})$/}},mn=60,yn=31536e3,bn={MAX_LENGTH:64,PATTERN:/^(galaswap-operation-|galaconnect-operation-)/},vn={PATTERN:/^[a-fA-F0-9]{64}$/},wn={STREAM_URL_PATTERN:/^(rtmps?|srt):\/\/.+/},En=50,An=1,Sn=100,kn={FULL_NAME:{MIN_LENGTH:1,MAX_LENGTH:100,ALPHABETS_ONLY_PATTERN:/^[a-zA-Z]+(?:\s[a-zA-Z]+)?$/}};function Tn(e,t){if(Zt(e))return t;try{return JSON.parse(e)}catch{return t}}function In(e,t=0){if(Zt(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 Cn(e,t,n){if(en(e))return t;if("number"==typeof e)return isNaN(e)?t:e;const r=Number(e);return isNaN(r)?t:r}function Nn(e,t,n){if(en(e))return t;if("bigint"==typeof e)try{return Number(e)}catch{return t}if("number"==typeof e)return isNaN(e)?t:Math.floor(e);const r=parseInt(String(e),10);return isNaN(r)?t:r}function _n(e,t){if(en(e)||""===e)throw St(t);if(o.isBigNumber(e)){if(e.isNaN())throw Dt(t,"NaN");return e}try{const n=new o(e);if(n.isNaN())throw Dt(t,e);if(!n.isFinite())throw Dt(t,e);return n}catch(n){if(n instanceof yt)throw n;throw Dt(t,e)}}function xn(e,t=0){if(en(e))return t;if("number"==typeof e)return isNaN(e)?t:e;return In(String(e).replace("%","").trim(),t)}function Rn(e,t=18){const n=In(e,0);if(0===n)return"0";return n.toFixed(t).replace(/\.?0+$/,"")}function Bn(e){return Rn(e,8)}function Dn(e){return Rn(e,18)}function On(e,t,n,r){if("number"!=typeof e)throw Bt(r,"a number",e,r);if(e<t||e>n)throw _t(r,t,n,e)}function Mn(e,t,n){if("string"!=typeof e)throw Bt(n,"a string",e,n);if(e.length>t)throw Rt(n,t,e.length)}function Ln(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 xt(t,1,e,t)}function Un(e,t,n=!1){if("string"!=typeof e)throw Bt(t,"a string",e,t);if(!n&&0===e.trim().length)throw St(t,`${t} (non-empty string)`)}function Pn(e,t){if("ASC"!==e&&"DESC"!==e)throw new yt(`${t} must be either 'ASC' or 'DESC'`,t,"INVALID_ENUM_VALUE")}function Fn(e,t,n){const r="string"==typeof e?parseFloat(e):e,s="string"==typeof t?parseFloat(t):t;if(!isFinite(r))throw new yt(`${n} minFee must be a valid finite number`,n,"INVALID_FEE_MINIMUM");if(!isFinite(s))throw new yt(`${n} maxFee must be a valid finite number`,n,"INVALID_FEE_MAXIMUM");if(r<.1)throw new yt(`${n} minFee must be >= 0.1, received ${r}`,n,"INVALID_FEE_MINIMUM");if(s>.5)throw new yt(`${n} maxFee must be <= 0.5, received ${s}`,n,"INVALID_FEE_MAXIMUM");if(r>s)throw new yt(`${n} minFee (${r}) must be <= maxFee (${s})`,n,"INVALID_FEE_RANGE")}const $n={ETH_ADDRESS:/^0x[0-9a-fA-F]{40}$/,BACKEND_ADDRESS:/^eth\|(0x)?[0-9a-fA-F]{40}$/,CLIENT_ADDRESS:/^client\|[a-zA-Z0-9_-]+$/},Kn=Qt,Gn=Zt,Hn=en;function Wn(e,t,n=100,r,s){if(void 0!==s&&"string"!=typeof s)throw new yt("cursor must be a string","cursor",mt.INVALID_TYPE);const i=r??t,o=void 0!==r?"pageSize":"limit";if(void 0!==i&&(Ln(i,o),i>n))throw new yt(`${o} must be at most ${n}`,o,mt.TOO_LARGE)}function qn(e){const t=Object.values(e);return e=>"string"==typeof e&&t.includes(e)}function zn(e){return Object.values(e)}function Vn(e,t,n,r={}){const{description:s="parameter",treatEmptyAsNull:i=!0}=r,o=e[t],a=e[n],c=null!=o&&(!i||""!==o),l=null!=a&&(!i||""!==a);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 jn(e,t="tokenName",n=on){if(!Kn(e))throw St(t);const r=e.trim();if(0===r.length)throw St(t);if(r.length<n.MIN_LENGTH)throw _t(t,n.MIN_LENGTH,n.MAX_LENGTH,r.length,`${t} length`);if(r.length>n.MAX_LENGTH)throw _t(t,n.MIN_LENGTH,n.MAX_LENGTH,r.length,`${t} length`);if(!n.PATTERN.test(r))throw new yt(`${t} must contain only alphanumeric characters`,t,mt.INVALID_FORMAT)}function Xn(e,t="tokenName",n=on){if(null==e)throw St(t,t);if("string"!=typeof e)throw Bt(t,"a string",e);const r=e.trim();if(0===r.length)throw St(t,t);if(!n.PATTERN.test(r))throw new yt(`${t} must be ${n.MIN_LENGTH}-${n.MAX_LENGTH} alphanumeric characters`,t,mt.INVALID_FORMAT)}function Yn(e){return t=>{if(null==t||"object"!=typeof t)return!1;const n=t;for(const{field:t,type:r,nullable:s=!1,optional:i=!1,validator:o}of e){const e=n[t];if((!i||void 0!==e)&&(!s||null!==e)){if(typeof e!==r)return!1;if(o&&!o(e))return!1}}return!0}}const Jn={requiredString:e=>t=>Hn(t)?`${e} is required`:"string"!=typeof t?`${e} must be a string`:0===t.trim().length?`${e} cannot be empty`:void 0,maxLength:(e,t)=>n=>{if(!Gn(n))return"string"!=typeof n?`${e} must be a string`:n.length>t?`${e} must be at most ${t} characters`:void 0},positiveInteger:e=>t=>{if(!Hn(t))return"number"==typeof t&&Number.isInteger(t)?t<1?`${e} must be a positive integer`:void 0:`${e} must be an integer`},requiredPositiveInteger:e=>t=>Hn(t)?`${e} is required`:"number"==typeof t&&Number.isInteger(t)?t<1?`${e} must be a positive integer`:void 0:`${e} must be an integer`,enumValue:(e,t)=>n=>{if(!Hn(n))return t.includes(n)?void 0:`${e} must be one of: ${t.join(", ")}`},requiredEnumValue:(e,t)=>n=>Hn(n)?`${e} is required`:t.includes(n)?void 0:`${e} must be one of: ${t.join(", ")}`,isoDate:e=>t=>{if(!Hn(t))return"string"!=typeof t?`${e} must be a string`:rn(t)?void 0:`${e} must be a valid ISO 8601 date string`},walletAddress:(e,t=!1)=>n=>{if(Hn(n))return t?`${e} is required`:void 0;if("string"!=typeof n)return`${e} must be a string`;return $n.ETH_ADDRESS.test(n)||$n.BACKEND_ADDRESS.test(n)||$n.CLIENT_ADDRESS.test(n)?void 0:`${e} must be a valid wallet address`}};function Qn(e){return""===e||0===e.trim().length}function Zn(e,t,n){if(!Hn(e)){if("string"!=typeof e)throw Bt(t,"a string",e,t);if(e.length>n)throw new yt(`${t} must be at most ${n} characters`,t,mt.TOO_LARGE)}}function er(e,t){Hn(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 yt(`${t} must be a valid date`,t,mt.INVALID_FORMAT)}(e,t)}function tr(e,t,n){try{Ln(e,t)}catch{throw function(e,t,n,r="OPERATION_FAILED"){return new yt(`${e} failed: ${t}`,n,r)}(n,"must be a positive integer",t)}}function nr(e,t,n="status"){void 0!==e&&function(e,t,n){const r=Object.values(t);if(!r.includes(e))throw new yt(`${n} must be one of: ${r.join(", ")}`,n,mt.INVALID_FORMAT)}(e,t,n)}class rr{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 vt("JWT authentication required. Call sdk.login() first.")}return this.jwtAuth.getJwtHeaders()}isCalledFromUserCode(){const e=ct(new Error)??"";return!(!e.includes("expect")&&!e.includes("jest"))||!(!e.includes("tests/")&&!e.includes(".test.ts"))}validatePositiveInteger(e,t,n){tr(e,t,n)}}class sr{constructor(e=!1,t){this.logger=t||new Jt({debug:e,context:this.constructor.name})}}class ir extends sr{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 or extends ir{constructor(e=!1){super(e)}normalizeKey(e){return Vt(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>=or.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,r)=>{n.lastUpdated<e&&(e=n.lastUpdated);let s=0;s+=2*r.length,void 0!==n.reverseBondingCurveMinFeeFactor&&(s+=8),void 0!==n.reverseBondingCurveMaxFeeFactor&&(s+=8),void 0!==n.reverseBondingCurveNetFeeFactor&&(s+=8),s+=8,void 0!==n.vaultAddress&&""!==n.vaultAddress&&(s+=2*n.vaultAddress.length),void 0!==n.maxSupply&&""!==n.maxSupply&&(s+=2*n.maxSupply.length),void 0!==n.symbol&&""!==n.symbol&&(s+=2*n.symbol.length),s+=32,t+=s}),{cacheSize:t,oldestEntry:this.cache.size>0?e:0}}getByTokenId(e){const t=`token:${Vt(e)}`;return this.cache.get(t)??null}setByTokenId(e,t){const n=`token:${Vt(e)}`;this.updateCacheEntry(n,t)}hasByTokenId(e){const t=`token:${Vt(e)}`;return this.cache.has(t)}}function ar(e){return""===e?"":e.startsWith("0x")?e.slice(2):e}or.MAX_CACHE_SIZE=1e4;const cr={ETHEREUM:$n.ETH_ADDRESS,ETHEREUM_NO_PREFIX:/^[a-fA-F0-9]{40}$/,BACKEND:$n.BACKEND_ADDRESS,CLIENT:$n.CLIENT_ADDRESS};class lr{toBackendFormat(t){if(!Kn(t))throw new yt("Address is required and must be a string","address","REQUIRED");let n=t;if(t.startsWith("eth|")){if(n=t.slice(4),!/^[a-fA-F0-9]{40}$/.test(n))throw new yt(`Invalid Ethereum address format in backend address. Expected 40 hex characters after 'eth|'. Got: "${t}"`,"address","INVALID_FORMAT");return t}if(n=ar(t),!/^[a-fA-F0-9]{40}$/.test(n))throw new yt(`Invalid Ethereum address format. Expected 40 hex characters (with or without 0x prefix). Got: "${t}"`,"address","INVALID_FORMAT");return`eth|${e.getAddress(`0x${n}`).slice(2)}`}toEthereumFormat(e){if(!Kn(e))throw new yt("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 yt(`Invalid backend address format. Expected "eth|{40-hex-characters}" or "eth|0x{40-hex-characters}". Got: "${e}"`,"address","INVALID_FORMAT");const n=t[1],r=void 0!==n&&""!==n?6:4;return`0x${e.substring(r)}`}normalizeInput(e){if(void 0!==e&&""!==e){if(e.startsWith("client|")){if(!cr.CLIENT.test(e))throw new yt(`Invalid client address format: "${e}"`,"address","INVALID_FORMAT");return e}if(e.startsWith("eth|")){if(!cr.BACKEND.test(e))throw new yt(`Invalid backend address format: "${e}"`,"address","INVALID_FORMAT");return e}return this.toBackendFormat(e)}}isValid(e){return!!Kn(e)&&(!!cr.ETHEREUM.test(e)||(!!cr.ETHEREUM_NO_PREFIX.test(e)||(!!cr.BACKEND.test(e)||!!cr.CLIENT.test(e))))}assertValid(e,t="address"){if(!this.isValid(e))throw new yt(`${t} must be a valid wallet address (Ethereum or backend format)`,t,"INVALID_FORMAT")}detectFormat(e){return Kn(e)?cr.ETHEREUM.test(e)||cr.ETHEREUM_NO_PREFIX.test(e)?"ethereum":cr.BACKEND.test(e)?"backend":cr.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 ar(e).toLowerCase();if(/^[a-fA-F0-9]{40}$/.test(e))return e.toLowerCase();throw new yt(`Cannot extract hex from address: "${e}". Expected Ethereum or backend format.`,"address","INVALID_FORMAT")}}const ur=new lr,dr=ar;function hr(e){return ur.toBackendFormat(e)}function gr(e){return ur.toEthereumFormat(e)}function fr(e){return ur.normalizeInput(e)}function pr(e){return ur.isValid(e)}function mr(e,t="address"){ur.assertValid(e,t)}function yr(e){const t="string"==typeof e?e:e.address;return ur.toBackendFormat(t)}function br(e){return ur.detectFormat(e)}var vr=Object.freeze({__proto__:null,AddressFormatter:lr,assertValidWalletAddress:mr,detectFormat:br,fromBackendAddressFormat:gr,isValidAddress:pr,normalizeAddressInput:fr,stripHexPrefix:dr,toBackendAddressFormat:hr,toBackendAddressFromEthers:yr});const wr=n.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"),Er=n.z.string({message:"Token symbol is required"}).min(1,"Token symbol must be at least 1 character").max(8,"Token symbol must be at most 8 characters").regex(/^[A-Z]{1,8}$/,"Token symbol must be uppercase letters only"),Ar=n.z.string({message:"Token description is required"}).min(1,"Token description is required").max(500,"Token description must be at most 500 characters"),Sr=n.z.string().min(1,"Token name must be at least 1 character").max(50,"Token name must be at most 50 characters"),kr=n.z.string().min(1,"Search query must be at least 1 character").max(100,"Search query must be at most 100 characters"),Tr=n.z.string().min(1,"Full name is required").max(100,"Full name must be at most 100 characters").regex(/^[a-zA-Z\s]+$/,"Full name can only contain letters and spaces"),Ir=n.z.string().regex($n.BACKEND_ADDRESS,"Address must be in format: eth|[40-hex-chars]"),Cr=n.z.string().regex($n.ETH_ADDRESS,"Invalid Ethereum address format"),Nr=n.z.string().refine(e=>$n.BACKEND_ADDRESS.test(e)||$n.ETH_ADDRESS.test(e)||$n.CLIENT_ADDRESS.test(e),"Address must be eth|[40-hex], 0x[40-hex], or client|[identifier] format").transform(e=>(new lr).normalizeInput(e)??e),_r=n.z.string().refine(e=>$n.BACKEND_ADDRESS.test(e)||/^service\|Token\$Unit\$[A-Z0-9]+\$eth:[0-9a-fA-F]{40}\$launchpad$/.test(e),"Invalid vault address format"),xr=n.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>In(e,0)>0,"Amount must be greater than zero"),Rr=n.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>In(e,0)>=0,"Amount must be zero or greater"),Br=n.z.string().url("Must be a valid URL").regex(/^https?:\/\//,"URL must start with http:// or https://"),Dr=n.z.string().optional().refine(e=>void 0===e||""===e||/^https?:\/\/.+\..+/.test(e),"Must be a valid URL if provided"),Or=n.z.number().int("Page must be an integer").min(1,"Page must be at least 1").max(1e3,"Page must be at most 1000").default(1);function Mr(e=100){return n.z.number().int("Limit must be an integer").min(1,"Limit must be at least 1").max(e,`Limit must be at most ${e}`).default(10)}const Lr=Mr(100),Ur=Mr(20),Pr=Mr(20),Fr=n.z.number().int("File size must be an integer").min(1,"File must be at least 1 byte").max(10485760,"File must be at most 10MB"),$r=n.z.string().max(255,"Filename must be at most 255 characters"),Kr=n.z.enum(["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"]),Gr=n.z.string().datetime("Must be a valid ISO 8601 date string"),Hr=n.z.number().int("Timestamp must be an integer").min(0,"Timestamp must be non-negative"),Wr=n.z.string().regex(/^0x[a-fA-F0-9]{64}$/,"Private key must be format: 0x + 64 hex characters"),qr=n.z.string().regex(/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/,"Transaction ID must be in UUID format"),zr=n.z.string().regex(/^galaconnect-operation-[a-z0-9-]+$/,"Unique key must be format: galaconnect-operation-{unique-id}"),Vr=[".png",".jpg",".jpeg",".gif",".webp",".svg"],jr=n.z.object({file:n.z.union([n.z.instanceof(File),n.z.instanceof(Buffer)]),name:$r,size:Fr,type:Kr}),Xr=n.z.instanceof(File).refine(e=>e.size>=1&&e.size<=10485760,"File size must be between 1 byte and 10MB").refine(e=>["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"].includes(e.type),"File must be a valid image type (PNG, JPG, JPEG, GIF, WebP, or SVG)").refine(e=>e.name.length<=255,"Filename must be at most 255 characters"),Yr=n.z.instanceof(Buffer).refine(e=>e.length>=1&&e.length<=10485760,"Buffer size must be between 1 byte and 10MB"),Jr=n.z.union([Xr,Yr]),Qr=n.z.enum([".png",".jpg",".jpeg",".gif",".webp",".svg"]),Zr=$r.refine(e=>{const t=e.slice(e.lastIndexOf(".")).toLowerCase();return Vr.includes(t)},`Filename must end with one of: ${Vr.join(", ")}`),es=n.z.object({websiteUrl:Dr,telegramUrl:Dr,twitterUrl:Dr,instagramUrl:Dr,facebookUrl:Dr,redditUrl:Dr,tiktokUrl:Dr}).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"),ts=n.z.string().min(1,"Token category must not be empty").default("Unit"),ns=n.z.string().min(1,"Token collection must not be empty").default("Token"),rs=n.z.object({minFeePortion:n.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal string").refine(e=>In(e,0)>=.1,"Minimum fee must be >= 0.1").refine(e=>In(e,0)<=.5,"Minimum fee must be <= 0.5"),maxFeePortion:n.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal string").refine(e=>In(e,0)>=.1,"Maximum fee must be >= 0.1").refine(e=>In(e,0)<=.5,"Maximum fee must be <= 0.5")}).refine(e=>In(e.maxFeePortion,0)>=In(e.minFeePortion,0),{message:"Maximum fee must be >= minimum fee",path:["maxFeePortion"]}),ss=n.z.object({tokenName:wr,tokenSymbol:Er,tokenDescription:Ar,tokenImage:n.z.union([n.z.instanceof(File),n.z.instanceof(Buffer),n.z.string().url("Token image must be a valid URL")]).optional(),preBuyQuantity:Rr.default("0"),websiteUrl:Dr,telegramUrl:Dr,twitterUrl:Dr,instagramUrl:Dr,facebookUrl:Dr,redditUrl:Dr,tiktokUrl:Dr,tokenCategory:ts,tokenCollection:ns,reverseBondingCurveConfiguration:rs.optional(),saleStartTime:n.z.number().int().positive().optional(),privateKey:Wr.optional()}),is=n.z.object({file:n.z.union([n.z.instanceof(File),n.z.instanceof(Buffer)]),tokenName:wr}),os=n.z.enum(["RECENT","POPULAR"]),as=n.z.object({tokenName:wr.optional(),symbol:Er.optional()}).refine(e=>void 0!==e.tokenName||void 0!==e.symbol,"At least one of tokenName or symbol is required"),cs=n.z.enum(["NATIVE","MEME"]),ls=n.z.enum(["IN","OUT"]),us=n.z.object({from:n.z.number().int("From timestamp must be an integer").min(173e6,"From timestamp must be at least 173000000"),to:n.z.number().int("To timestamp must be an integer").min(173e6,"To timestamp must be at least 173000000"),resolution:n.z.number().int("Resolution must be an integer").min(1,"Resolution must be at least 1"),tokenName:wr}),ds=n.z.object({tokenName:wr,slippageToleranceFactor:n.z.number().min(0).max(1).optional(),maxAcceptableReverseBondingCurveFeeSlippageFactor:n.z.number().min(0).max(1).optional(),privateKey:Wr.optional()}),hs=n.z.object({offset:n.z.number().int().min(0).default(0),pageSize:n.z.number().int().min(1).max(100).default(10)}),gs=n.z.object({offset:n.z.number().int().min(0).default(0),pageSize:n.z.number().int().min(1).max(20).default(10)}),fs=n.z.object({offset:n.z.number().int().min(0).default(0),pageSize:n.z.number().int().min(1).max(20).default(10)}),ps=hs.extend({type:n.z.enum(["RECENT","POPULAR"]).optional(),tokenName:n.z.string().min(1).max(50).optional(),search:n.z.string().min(1).max(100).optional()}),ms=gs.extend({tokenName:n.z.string().min(1).max(50).optional(),search:n.z.string().min(1).max(100).optional()}),ys=fs.extend({tradeType:n.z.enum(["BUY","SELL"]).optional(),tokenName:n.z.string().min(1).max(50).optional(),userAddress:n.z.string().regex(/^(0x[a-fA-F0-9]{40}|eth\|[a-fA-F0-9]{40})$/).optional(),startDate:n.z.string().datetime().optional(),endDate:n.z.string().datetime().optional(),sortOrder:n.z.enum(["ASC","DESC"]).default("DESC")}),bs={page:n.z.number().int().min(1),limit:n.z.number().int().min(1),total:n.z.number().int().min(0),totalPages:n.z.number().int().min(0),hasNext:n.z.boolean(),hasPrevious:n.z.boolean()},vs=n.z.object(bs);const ws=n.z.enum(["buy","sell"]),Es=n.z.enum(["BUY","SELL"]),As=n.z.object({tradeType:ws,tokenAmount:xr,vaultAddress:_r,userAddress:Nr,slippageTolerance:xr.optional(),deadline:n.z.number().int().positive().optional()}),Ss=n.z.object({tokenSymbol:Er,nativeTokenQuantity:xr,expectedToken:xr,maxAcceptableReverseBondingCurveFee:Rr.default("0").optional()}),ks=n.z.object({tokenSymbol:Er,tokenQuantity:xr,expectedNativeToken:xr,maxAcceptableReverseBondingCurveFee:Rr.default("0").optional()}),Ts=fs.extend({tokenName:Sr.optional()}),Is=n.z.object({page:n.z.number().int().min(1).max(1e3).default(1).optional(),limit:n.z.number().int().min(1).max(20).default(10).optional()}),Cs=n.z.enum(["NATIVE","MEME"]),Ns=n.z.enum(["IN","OUT"]),_s=n.z.object({type:Cs,method:Ns,vaultAddress:_r,amount:xr}),xs=n.z.object({nativeTokenQuantity:xr}),Rs=n.z.object({vaultAddress:_r}),Bs=n.z.object({minFeePortion:xr,maxFeePortion:xr}),Ds=n.z.enum(["both","held","created"]),Os=gs.extend({type:Ds.optional(),address:Nr.optional(),search:kr.optional(),tokenName:Sr.optional()}),Ms=n.z.object({address:Nr.optional(),refresh:n.z.boolean().optional()}),Ls=n.z.object({profileImage:n.z.string(),fullName:Tr,address:Nr,privateKey:Wr.optional()}),Us=n.z.object({file:n.z.union([n.z.instanceof(File),n.z.instanceof(Buffer)]),address:Nr.optional(),privateKey:Wr.optional()}),Ps=n.z.object({created:n.z.number(),createdBy:n.z.string(),expires:n.z.number(),instanceId:n.z.string(),lockAuthority:n.z.string(),name:n.z.string(),quantity:n.z.string(),vestingPeriodStart:n.z.number()}),Fs=n.z.object({address:Nr,tokenId:n.z.union([n.z.string(),n.z.object({collection:n.z.string(),category:n.z.string(),type:n.z.string(),additionalKey:n.z.string()}),n.z.object({collection:n.z.string(),category:n.z.string(),type:n.z.string(),additionalKey:n.z.string(),instance:n.z.string()})]).optional(),tokenName:Sr.optional(),withExpired:n.z.boolean().optional()}).refine(e=>void 0!==e.tokenId||void 0!==e.tokenName,"At least one token identifier (tokenId or tokenName) is required");function $s(e){return t=>{const n=e.safeParse(t);return{success:n.success,data:n.success?n.data:void 0,errors:n.success?void 0:n.error.issues.map(e=>e.message)}}}const Ks=$s(wr),Gs=$s(Er),Hs=$s(Ar),Ws=$s(Nr),qs=$s(_r),zs=$s(xr),Vs=$s(Tr),js=$s(kr),Xs=$s(Sr),Ys=$s(ss),Js=$s(es),Qs=$s(is),Zs=$s(as),ei=$s(Os),ti=$s(Ms),ni=$s(Ls),ri=$s(Us),si=$s(Fs),ii=$s(As),oi=$s(Ss),ai=$s(ks),ci=$s(Ts),li=$s(Is),ui=$s(_s),di=$s(xs),hi=$s(Rs);function gi(e){const t=Ys(e);return t.success?[]:t.errors??["Unknown validation error"]}function fi(e){const t=gi(e);if(t.length>0)throw new Error(`LaunchTokenData validation failed:\n${t.map(e=>`- ${e}`).join("\n")}`)}function pi(e,t){return"string"==typeof e[t]}function mi(e,t){return void 0===e[t]||"string"==typeof e[t]}function yi(e,t){return void 0===e[t]||"number"==typeof e[t]}function bi(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 vi(e){return t=>{if(null==t||"object"!=typeof t||Array.isArray(t))return!1;const n=t;for(const[t,r]of Object.entries(e)){if(!bi(n[t],r))return!1}return!0}}qn({BUY:"buy",SELL:"sell"});const wi=vi({vaultAddress:"string"}),Ei=vi({nativeTokenQuantity:"string"});function Ai(e){if(Hn(e)||"object"!=typeof e)return{};const t={};for(const[n,r]of Object.entries(e))Hn(r)||(Kn(r)?t[n]=r:"number"==typeof r||"boolean"==typeof r?t[n]=r.toString():Array.isArray(r)?t[n]=r.join(","):t[n]="object"==typeof r?JSON.stringify(r):String(r));return t}var Si=Object.freeze({__proto__:null,adaptQueryParams:Ai});function ki(e,t="0"){return function(e,t="0"){if(Zt(e))return new o(t);if(o.isBigNumber(e))return e.isNaN()?new o(t):e;try{const n=new o(e);return n.isNaN()||!n.isFinite()?new o(t):n}catch{return new o(t)}}(e,t)}function Ti(e,t){return void 0!==t?ki(e).toFixed(t):ki(e).toFixed()}function Ii(e){const t=ki(e),n=Math.log(1.0001),r=t.toNumber();return Math.log(r)/n}function Ci(e){return ki(e).isZero()}function Ni(e,t){return ki(e).isLessThan(ki(t))}function _i(...e){e.forEach(e=>{if(e.isNaN())throw Dt("value","NaN");if(!e.isFinite())throw Rt("value","finite");if(e.isLessThanOrEqualTo(0))throw xt("value","0",e.toString())})}function xi(e,t,n){if(e.isNaN())throw Dt(t,"NaN");if(!e.isFinite())throw Rt(t,"finite");if(e.isLessThanOrEqualTo(0))throw xt(t,"0",e.toString())}function Ri(e,t,n="0"){const r=ki(t);return Ci(r)?ki(n):ki(e).dividedBy(r)}const Bi={calculateBuyWithExact(e,t){const n=In(e),r=In(t),{BASE_PRICE:s,PRICE_SCALING_FACTOR:i,TRADING_FEE_FACTOR:o,GAS_FEE:a}=zt,c=function(e,t){const n=Math.pow(10,t);return Math.ceil(e*n)/n}(s*(Math.exp((r+n)*i)-Math.exp(r*i))/i,8),l=Ti(ki(c).multipliedBy(o));return{amount:c.toString(),reverseBondingCurveFee:"0",transactionFee:l,gasFee:a}},calculateBuyWithNative(e,t){const n=In(e),r=In(t),{BASE_PRICE:s,PRICE_SCALING_FACTOR:i,TRADING_FEE_FACTOR:o,GAS_FEE:a}=zt,c=Math.log(n*i/s+Math.exp(r*i))/i-r,l=Ti(ki(c).multipliedBy(o));return{amount:c.toString(),reverseBondingCurveFee:"0",transactionFee:l,gasFee:a}},calculateSellWithExact(e,t,n,r,s){const i=In(e),o=In(t),a=In(n),{BASE_PRICE:c,PRICE_SCALING_FACTOR:l,TRADING_FEE_FACTOR:u,GAS_FEE:d}=zt,h=c*(Math.exp(o*l)-Math.exp((o-i)*l))/l,g=ki(h),f=r+o/a*(s-r),p=Ti(g.multipliedBy(f),8),m=Ti(g.multipliedBy(u));return{amount:h.toString(),reverseBondingCurveFee:p,transactionFee:m,gasFee:d}},calculateSellWithNative(e,t,n,r,s){const i=In(e),o=In(t),a=In(n),{BASE_PRICE:c,PRICE_SCALING_FACTOR:l,TRADING_FEE_FACTOR:u,GAS_FEE:d}=zt;if(i>=c*(Math.exp(o*l)-1)/l){const e=ki(i),t=r+o/a*(s-r),n=Ti(e.multipliedBy(t),8),c=Ti(e.multipliedBy(u));return{amount:o.toString(),reverseBondingCurveFee:n,transactionFee:c,gasFee:d}}const h=o-Math.log(Math.exp(o*l)-i*l/c)/l,g=ki(i),f=r+o/a*(s-r),p=Ti(g.multipliedBy(f),8),m=Ti(g.multipliedBy(u));return{amount:h.toString(),reverseBondingCurveFee:p,transactionFee:m,gasFee:d}}};class Di extends Error{constructor(e,t,n){super(e),this.filename=t,this.mimeType=n,this.name="FileValidationError"}}function Oi(e,t,n){if(null==e)throw new Di("File is required",t,n);if("undefined"!=typeof File&&e instanceof File){const t=Xr.safeParse(e);if(!t.success){const n=t.error.issues.map(e=>e.message).join("; ");throw new Di(n,e.name,e.type)}return}if(Buffer.isBuffer(e)){if(void 0===t||""===t)throw new Di("Filename is required when uploading Buffer objects",t,n);const r=Yr.safeParse(e);if(!r.success){const e=r.error.issues.map(e=>e.message).join("; ");throw new Di(e,t,n)}try{Mn(t,255,"filename")}catch(e){throw new Di(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 Di(`Invalid file type "${n}" is not allowed. Allowed types: ${s.join(", ")}`,t,n);const i=function(e){if(null==e||""===e)return"";const t=e.lastIndexOf(".");if(-1===t)return"";return e.substring(t).toLowerCase()}(t),o=[".png",".jpg",".jpeg",".gif",".webp",".svg"];if(!o.includes(i))throw new Di(`File extension "${i}" is not allowed. Allowed extensions: ${o.join(", ")}`,t,n);const a=function(e){switch(e.toLowerCase()){case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";case".gif":return"image/gif";case".webp":return"image/webp";case".svg":return"image/svg+xml";default:return"application/octet-stream"}}(i);if(a!==n&&"application/octet-stream"!==a)throw new Di(`File extension "${i}" does not match MIME type "${n}"`,t,n);return}throw new Di("File must be a File object (browser) or Buffer (Node.js)",t,n)}class Mi{validate(e,t={}){const{allowZero:n=!0,minimum:r,maximum:s,maxDecimals:i=Mi.MAX_DECIMAL_PLACES,fieldName:o="amount"}=t;if(!Kn(e))throw new yt(`${o} cannot be empty or whitespace-only. Provide a valid numeric string.`,o,"INVALID_NUMERIC_STRING");if(/[eE]/.test(e))throw new yt(`${o} cannot use scientific notation. Use standard decimal format (e.g., "1000" instead of "1e3").`,o,"INVALID_NUMERIC_STRING");const a=In(e,NaN);if(isNaN(a))throw new yt(`${o} must be a valid numeric string. Received: "${e}"`,o,"INVALID_NUMERIC_STRING");if(!isFinite(a))throw new yt(`${o} must be a finite number. Cannot be Infinity or -Infinity.`,o,"INVALID_NUMERIC_STRING");if(a<0)throw new yt(`${o} must be non-negative. Received: "${e}"`,o,"INVALID_NUMERIC_STRING");if(!n&&0===a)throw new yt(`${o} must be greater than zero. Received: "${e}"`,o,"INVALID_NUMERIC_STRING");const c=ki(e),l=c.decimalPlaces()??0;if(l>i)throw new yt(`${o} cannot exceed ${i} decimal places. Received: ${l} decimal places`,o,"PRECISION_EXCEEDED");if(void 0!==r&&Ni(c,r))throw new yt(`${o} must be at least ${r}. Received: "${e}"`,o,"BELOW_MINIMUM");if(void 0!==s&&(u=s,ki(c).isGreaterThan(ki(u))))throw new yt(`${o} cannot exceed ${s}. Received: "${e}"`,o,"EXCEEDS_MAXIMUM");var u}parseAmount(e,t="0"){return ki(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 Ti(e,t)}clampAmount(e,t,n){const r=ki(e),s=ki(t),i=ki(n);return function(e,t,n){const r=ki(e),s=ki(t),i=ki(n);return r.isGreaterThanOrEqualTo(s)&&r.isLessThanOrEqualTo(i)}(r,s,i)?Ti(r):Ni(r,s)?Ti(s):Ti(i)}}function Li(e,t){throw new yt(e.join("; "),t,"VALIDATION_ERROR")}function Ui(e){const t=Ks(e);!t.success&&t.errors&&Li(t.errors,"tokenName")}function Pi(e){const t=us.safeParse(e);var n;t.success||Li((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 Fi(e,t,n=!0){$i.validate(e,{fieldName:t,allowZero:n})}Mi.MAX_DECIMAL_PLACES=18,Mi.MIN_POSITIVE="0.00000000000000001";const $i=new Mi;function Ki(e,t,n=Ti){if(!Array.isArray(e))throw Tt("Invalid API response: expected array of holders",t);for(const n of e){if(!Gi(n))throw Tt("Invalid holder data: missing or invalid owner field",t);if(!Hi(n))throw Tt("Invalid holder data: missing or invalid quantity field",t);const e=In(n.quantity,NaN);if(isNaN(e)||!isFinite(e))throw Tt(`Invalid holder quantity: "${n.quantity}"`,t)}const r=e,s=r.reduce((e,t)=>e.plus(t.quantity),ki(0));return{holders:r.map(e=>({address:e.owner,balance:e.quantity,percentage:Ri(ki(e.quantity),s,ki(0)).multipliedBy(100).toNumber()})),totalSupply:n(s),totalHolders:r.length,lastUpdated:new Date}}function Gi(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.owner&&""!==t.owner}function Hi(e){return"string"==typeof e.quantity&&""!==e.quantity}class Wi{constructor(e,t,n,r,s,i,o="local",a){this.http=e,this.tokenResolver=t,this.logger=n,this.bundleHttp=r,this.galaChainHttp=s,this.dexApiHttp=i,this.defaultCalculateAmountMode=o,this.launchpadWrites=a,this.metadataCache=new or}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;Ui(t);const r=`${t}.png`;Oi(n.file,r,"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 kt("file","a File object (browser) or Buffer (Node.js)");{const r=`${void 0!==n.tokenName&&""!==n.tokenName?n.tokenName:t}.png`,s=new Blob([n.file],{type:"image/png"});e.append("image",s,r)}}const r=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===r.error||200!==r.status)throw Tt(void 0!==r.message&&""!==r.message?r.message:"Image upload failed - no URL returned",r.status);const s=$t(r);if(!s?.imageUrl)throw Tt("Image upload failed - no URL returned",r.status);return s.imageUrl}catch(e){if(ot(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&&Wn(0,void 0,100,e.pageSize),void 0!==e.tokenName&&""!==e.tokenName&&Ui(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=Ai(t),r=await this.http.get(b.FETCH_POOLS,n);if(!0===r.error||200!==r.status)throw Tt(void 0!==r.message&&""!==r.message?r.message:"Failed to fetch pools",r.status);const s=$t(r);if(null==s)throw Tt("Failed to fetch pools - no data returned",r.status);let i=[];if(s.tokens)if(Array.isArray(s.tokens))i=s.tokens.map(e=>this.normalizePoolData(e));else{const e=s.tokens;i=[this.normalizePoolData(e)]}else s.pools&&Array.isArray(s.pools)&&(i=s.pools.map(e=>this.normalizePoolData(e)));const{extractMetadataFromPoolData:o,isValidPoolForCaching:a}=await Promise.resolve().then(function(){return QI});i.forEach(e=>{if(!a(e))return void this.logger.debug("Skipping pool with invalid structure for caching",e);const t=o(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:i,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 kt("options","an options object");const{tokenName:t,amount:n,type:r,currentSupply:s}=e;return"external"===this.validateAmountCalculationInputs(t,n,r,e.mode,[st.NATIVE,st.EXACT],'"native" or "exact"')?this.calculateBuyAmountExternal({tokenName:t,amount:n,type:r}):this.calculateBuyAmountLocal(this.addIfDefined({tokenName:t,amount:n,type:r},"currentSupply",s))}async calculateBuyAmountExternal(e){const{tokenName:t,amount:n,type:r}=e;return this.validateExternalAmountInputs(t,n),"exact"===r?Gt(()=>this.http.get(Ye,{tokenName:t,amount:n,type:"MEME",method:"OUT"}),{errorContext:`Failed to calculate buy amount for ${t} (exact tokens)`}):Gt(()=>this.http.get(Ye,{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:r,currentSupply:s,maxSupply:i,reverseBondingCurveMaxFeeFactor:o,reverseBondingCurveMinFeeFactor:a}=e;if("external"===this.validateAmountCalculationInputs(t,n,r,e.mode,[st.EXACT,st.NATIVE],'"exact" or "native"'))return this.calculateSellAmountExternal({tokenName:t,amount:n,type:r});{const e={tokenName:t,amount:n,type:r,...void 0!==s&&{currentSupply:s},...void 0!==i&&{maxSupply:i},...void 0!==o&&{reverseBondingCurveMaxFeeFactor:o},...void 0!==a&&{reverseBondingCurveMinFeeFactor:a}};return this.calculateSellAmountLocal(e)}}async calculateSellAmountExternal(e){const{tokenName:t,amount:n,type:r}=e;return this.validateExternalAmountInputs(t,n),"exact"===r?Gt(()=>this.http.get(Ye,{tokenName:t,amount:n,type:"MEME",method:"IN"}),{errorContext:`Failed to calculate sell amount for ${t} (exact tokens)`}):Gt(()=>this.http.get(Ye,{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:r,currentSupply:s}=e;if(!Kn(n))throw St("amount","Amount");if(r!==st.NATIVE&&r!==st.EXACT)throw Bt("type",'"native" or "exact"',r);void 0!==s&&Fi(s,"currentSupply");const i=null==s||""===s;if(i&&(null==t||""===t))throw St("tokenName","Token name (required when currentSupply is not provided)");null!=t&&""!==t&&Ui(t);let o=s;if(i){o=(await this.fetchPoolDetailsForCalculation(t)).currentSupply}return r===st.EXACT?Bi.calculateBuyWithExact(n,o):Bi.calculateBuyWithNative(n,o)}async calculateSellAmountLocal(e){const{tokenName:t,amount:n,type:r,currentSupply:s,maxSupply:i,reverseBondingCurveMaxFeeFactor:o,reverseBondingCurveMinFeeFactor:a}=e;if(!Kn(n))throw St("amount","Amount");if(r!==st.EXACT&&r!==st.NATIVE)throw Bt("type",'"exact" or "native"',r);void 0!==s&&Fi(s,"currentSupply");const c=null==s||""===s||null==i||""===i||void 0===o||void 0===a;if(c&&(null==t||""===t))throw St("tokenName","Token name (required when currentSupply, maxSupply, or fee factors are not provided)");null!=t&&""!==t&&Ui(t);let l=s,u=i,d=o,h=a;if(c&&null!=t&&""!==t){const e=this.metadataCache.getByName(t);u=u??this.metadataCache.getMaxSupply(t),d=d??e?.reverseBondingCurveMaxFeeFactor,h=h??e?.reverseBondingCurveMinFeeFactor,null!=l&&""!==l||(l=await this.fetchCurrentSupply(t));if(void 0===d||void 0===h){const e=await this.fetchPoolDetailsForCalculation(t);d=d??e.reverseBondingCurveMaxFeeFactor,h=h??e.reverseBondingCurveMinFeeFactor}}return r===st.EXACT?Bi.calculateSellWithExact(n,l,u,h,d):Bi.calculateSellWithNative(n,l,u,h,d)}async calculateBuyAmountForGraduation(e){const t="string"==typeof e?{tokenName:e}:e;if("object"==typeof e&&!function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return pi(t,"tokenName")&&function(e){return void 0===e.calculateAmountMode||"local"===e.calculateAmountMode||"external"===e.calculateAmountMode}(t)&&mi(t,"currentSupply")}(e))throw Bt("options","CalculateBuyAmountForGraduationOptions or string (token name)",typeof e);const{tokenName:n,calculateAmountMode:r,currentSupply:s}=t;Ui(n);const i=await this.fetchSaleDetails(n),o=s??Ti(ki(i.maxSupply).minus(i.sellingTokenQuantity)),a=i.sellingTokenQuantity;if("0"===a)throw St("tokenName",`Token ${n} is already graduated (no tokens remaining in pool)`);const c={tokenName:n,amount:a,type:"exact",currentSupply:o,...void 0!==r&&{mode:r}};return{...await this.calculateBuyAmount(c),remainingTokens:a}}async launchToken(e){if(void 0!==this.launchpadWrites){return(await this.launchpadWrites.createSale(e)).bundleId}if(!this.bundleHttp)throw It("Bundle backend client not configured. LaunchToken requires bundleHttp client.","bundleHttp");fi(e);const t=void 0!==e.preBuyQuantity&&""!==e.preBuyQuantity?e.preBuyQuantity:"0",n=In(t);if(0===n&&"0"!==t)throw Dt("preBuyQuantity",t,"Pre-buy quantity");if(n<0)throw Dt("preBuyQuantity",t,"Pre-buy quantity");if(e.reverseBondingCurveConfiguration){const{minFeePortion:t,maxFeePortion:n}=e.reverseBondingCurveConfiguration;Fn(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 St("tokenName","Token name");Ui(e);const t=await this.http.get(`/holders/${e}`);if(!0===t.error||200!==t.status)throw Tt(void 0!==t.message&&""!==t.message?t.message:"Failed to fetch token distribution",t.status);const n=$t(t);if(null==n)throw Tt("Failed to fetch token distribution - no data returned",t.status);return Ki(n,t.status)}async calculateInitialBuyAmount(e){if(!Ei(e))throw kt("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,r=t.Data;if("number"!=typeof n||"object"!=typeof r||null===r)return!1;const s=r,i=s.calculatedQuantity,o=s.extraFees;if("string"!=typeof i||"object"!=typeof o||null===o)return!1;const a=o;return"string"==typeof a.reverseBondingCurve&&"string"==typeof a.transactionFees}(n))throw Tt("Malformed response data from GalaChain gateway");try{dt(n,"Pre-mint calculation")}catch(e){throw Tt(at(e),500)}const{calculatedQuantity:r,extraFees:s}=n.Data;return{amount:r,reverseBondingCurveFee:s.reverseBondingCurve,transactionFee:s.transactionFees,gasFee:"1"}}catch(e){if(ot(e)&&e instanceof bt)throw e;throw Tt(at(e),500)}}async fetchPoolDetailsForCalculation(e){const t=await this.fetchSaleDetails(e),n=Ti(ki(t.maxSupply).minus(t.sellingTokenQuantity)),r=t.sellingTokenQuantity,s=t.maxSupply;let i=.5,o=.1;const a=t.reverseBondingCurveConfiguration;null!=a?.maxFeePortion&&(i=xn(a.maxFeePortion,.5)),null!=a?.minFeePortion&&(o=xn(a.minFeePortion,.1)),void 0===a&&this.logger.debug(`Pool details missing reverse bonding curve configuration for token ${e}, using defaults (min: 0.1, max: 0.5)`);const c=i-o;return this.metadataCache.set(e,{maxSupply:s,reverseBondingCurveMaxFeeFactor:i,reverseBondingCurveMinFeeFactor:o,reverseBondingCurveNetFeeFactor:c}),{currentSupply:n,remainingTokens:r,maxSupply:s,reverseBondingCurveMaxFeeFactor:i,reverseBondingCurveMinFeeFactor:o,reverseBondingCurveNetFeeFactor:c}}async fetchCurrentSupply(e){Ui(e);const t=await this.fetchSaleDetails(e),n=Ti(ki(t.maxSupply).minus(t.sellingTokenQuantity)),r=t.maxSupply;return this.metadataCache.set(e,{maxSupply:r}),n}normalizePoolData(e){const t=e.reverseBondingCurveMinFeePortion??"0",n=e.reverseBondingCurveMaxFeePortion??"0";return{...e,reverseBondingCurveMinFeePortion:t,reverseBondingCurveMaxFeePortion:n,hasReverseBondingCurveFee:!Ci(t)||!Ci(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 yt(pt(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 Tt(`Failed to fetch pool details: Status ${n.Status}`,n.Status);return n.Data}validateAmountCalculationInputs(e,t,n,r,s,i){const o=r??this.defaultCalculateAmountMode;if("local"!==o&&"external"!==o)throw Bt("mode",'"local" or "external"',o);if(!Kn(e))throw St("tokenName","Token name");if(!Kn(t))throw St("amount","Amount");if("string"!=typeof n||!s.includes(n))throw Bt("type",i,n);return o}validateExternalAmountInputs(e,t){if("string"!=typeof e||""===e)throw new yt("Token name must be a non-empty string","tokenName","INVALID_TOKEN_NAME");if("string"!=typeof t||""===t)throw new yt("Amount must be a non-empty string","amount","INVALID_AMOUNT")}getAddress(){return this.http.getAddress()}formatAddressForBackend(e){return hr(e)}validateTokenName(e){return Ui(e)}validatePagination(e){void 0!==e.pageSize&&Wn(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 St("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 Tt(`Failed to fetch token prices: ${at(e)}`,void 0,ot(e)?e:void 0)}}warmCacheFromPoolData(e,t){this.metadataCache.warmFromPoolData(e,t)}getCacheStats(){return this.metadataCache.getStats()}clearCache(e){this.metadataCache.clear(e)}}const qi={REFRESH_THRESHOLD_MS:3e5,DEFAULT_EXPIRY_S:86400,LOGIN_MESSAGE_PREFIX:"Sign in to Launchpad t:",AUTH_HEADER:"Authorization",BEARER_PREFIX:"Bearer "};class zi{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 Vi,ji;exports.AuthErrorType=void 0,(Vi=exports.AuthErrorType||(exports.AuthErrorType={})).WALLET_NOT_CONNECTED="WALLET_NOT_CONNECTED",Vi.SIGNATURE_FAILED="SIGNATURE_FAILED",Vi.INVALID_ADDRESS="INVALID_ADDRESS",Vi.MESSAGE_GENERATION_FAILED="MESSAGE_GENERATION_FAILED";class Xi extends Error{constructor(e,t,n){super(t),this.type=e,this.originalError=n,this.name="AuthError"}}class Yi{constructor(e,t=qi.REFRESH_THRESHOLD_MS){this.tokenState=null,this.STORAGE_KEYS={ACCESS_TOKEN:"lpad_access_token",ACCESS_EXPIRES:"lpad_access_expires",REFRESH_TOKEN:"lpad_refresh_token",REFRESH_EXPIRES:"lpad_refresh_expires"},this.storage=e??new zi,this.refreshThresholdMs=t}setToken(e,t){if(!Kn(e))throw new Xi(exports.AuthErrorType.SIGNATURE_FAILED,"JWT token must be a non-empty string");if("number"!=typeof t)throw new Xi(exports.AuthErrorType.SIGNATURE_FAILED,"Token expiration must be a positive finite number (seconds)");if(!Number.isFinite(t))throw new Xi(exports.AuthErrorType.SIGNATURE_FAILED,"Token expiration must be a positive finite number (seconds)");if(t<=0)throw new Xi(exports.AuthErrorType.SIGNATURE_FAILED,"Token expiration must be a positive finite number (seconds)");const n=Date.now();this.tokenState={token:e.trim(),issuedAt:n,expiresAt:n+1e3*t},this.storage.set(this.STORAGE_KEYS.ACCESS_TOKEN,e.trim()),this.storage.set(this.STORAGE_KEYS.ACCESS_EXPIRES,String(this.tokenState.expiresAt))}async setTokens(e,t,n,r){if(this.setToken(e,t),n){const e=Date.now()+1e3*(r??7776e3);if(!this.tokenState)throw new Xi(exports.AuthErrorType.SIGNATURE_FAILED,"Access token must be set before refresh token");this.tokenState.refreshToken=n.trim(),this.tokenState.refreshExpiresAt=e,await this.storage.set(this.STORAGE_KEYS.REFRESH_TOKEN,n.trim()),await this.storage.set(this.STORAGE_KEYS.REFRESH_EXPIRES,String(e))}}getToken(){return this.tokenState?.token??null}hasToken(){return null!==this.tokenState}isExpired(){return!this.tokenState||Date.now()>=this.tokenState.expiresAt}shouldRefresh(e){if(!this.tokenState)return!1;const t=e??this.refreshThresholdMs,n=this.tokenState.expiresAt-Date.now();return n>0&&n<=t}getTimeUntilExpiry(){if(!this.tokenState)return 0;const e=this.tokenState.expiresAt-Date.now();return Math.max(0,e)}getExpiresAt(){return this.tokenState?.expiresAt??null}getAuthorizationHeader(){const e=this.getToken();return null===e||""===e?null:`${qi.BEARER_PREFIX}${e}`}getJwtHeaders(){const e=this.getAuthorizationHeader();if(null===e||""===e)throw new Xi(exports.AuthErrorType.WALLET_NOT_CONNECTED,"No JWT token available. Call login() first.");return{[qi.AUTH_HEADER]:e}}async getRefreshToken(){if(!this.tokenState?.refreshToken){const e=await this.storage.get(this.STORAGE_KEYS.REFRESH_TOKEN),t=await this.storage.get(this.STORAGE_KEYS.REFRESH_EXPIRES);if(e&&t){const n=Number(t);if(Number.isFinite(n)&&Date.now()<n)return e}return null}return null!==this.tokenState.refreshExpiresAt&&void 0!==this.tokenState.refreshExpiresAt&&(!Number.isFinite(this.tokenState.refreshExpiresAt)||Date.now()>=this.tokenState.refreshExpiresAt)?null:this.tokenState.refreshToken??null}async restoreFromStorage(){const e=await this.storage.get(this.STORAGE_KEYS.ACCESS_TOKEN),t=await this.storage.get(this.STORAGE_KEYS.ACCESS_EXPIRES);if(!e||!t)return!1;const n=Number(t);if(!Number.isFinite(n)||Date.now()>=n)return!1;const r=Date.now();this.tokenState={token:e,issuedAt:r,expiresAt:n};const s=await this.storage.get(this.STORAGE_KEYS.REFRESH_TOKEN),i=await this.storage.get(this.STORAGE_KEYS.REFRESH_EXPIRES);if(s&&i){const e=Number(i);Number.isFinite(e)&&Date.now()<e&&(this.tokenState.refreshToken=s,this.tokenState.refreshExpiresAt=e)}return!0}async clear(){this.tokenState=null,await this.storage.remove(this.STORAGE_KEYS.ACCESS_TOKEN),await this.storage.remove(this.STORAGE_KEYS.ACCESS_EXPIRES),await this.storage.remove(this.STORAGE_KEYS.REFRESH_TOKEN),await this.storage.remove(this.STORAGE_KEYS.REFRESH_EXPIRES)}isValid(){return this.hasToken()&&!this.isExpired()}getDebugInfo(){return{hasToken:this.hasToken(),isExpired:this.isExpired(),shouldRefresh:this.shouldRefresh(),timeUntilExpiryMs:this.getTimeUntilExpiry(),expiresAt:this.tokenState?new Date(this.tokenState.expiresAt):null}}}async function Ji(e,t,n,r){try{return await e()}catch(e){throw r?(r(e,t,n),new Error("Unreachable after error handler")):(n&&n.error(`${t}:`,e),Nt(e,t,n))}}function Qi(e,t,n,r){try{return e()}catch(e){throw r?(r(e,t,n),new Error("Unreachable after error handler")):(n&&n.error(`${t}:`,e),Nt(e,t,n))}}class Zi{constructor(e,t,n,r=!1){this.http=e,this.signatureAuth=t,this.jwtAuth=n,this.refreshPromise=null,this.loginPromise=null,this.logger=new Jt({debug:r,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 Xi(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Wallet is required for login. Configure privateKey in SDK.");this.loginPromise=this.performLogin();try{return await this.loginPromise}finally{this.loginPromise=null}}async performLogin(){return Ji(async()=>{const e=Date.now(),t=`${qi.LOGIN_MESSAGE_PREFIX}${e}`;this.logger.debug("Generating login signature",{message:t,timestamp:e});const n=await this.signatureAuth.signMessage(t),r=this.signatureAuth.getAddress();mr(r,"address");const s={address:r,message:t,signature:n.signature};let i;try{this.logger.debug("Sending login request with refresh token support",{address:r,message:t}),i=await this.http.post(K,{...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)"),i=await this.http.post(K,s)}const o=this.extractLoginData(i);return await this.jwtAuth.setTokens(o.accessToken,o.expiresIn,o.refreshToken,o.refreshExpiresIn),this.logger.debug("Login successful",{address:o.address,expiresIn:o.expiresIn,hasRefreshToken:!!o.refreshToken}),o},"SessionAuthService.performLogin",this.logger,e=>{if(e instanceof Xi)throw e;throw new Xi(exports.AuthErrorType.SIGNATURE_FAILED,`Login failed: ${at(e)}`,ot(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 Xi(exports.AuthErrorType.WALLET_NOT_CONNECTED,"No token to refresh. Call login() first.");this.refreshPromise=this.performRefresh();try{return await this.refreshPromise}finally{this.refreshPromise=null}}async performRefresh(){return Ji(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(H,{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(H,{},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 Xi)throw e;throw new Xi(exports.AuthErrorType.SIGNATURE_FAILED,`Token refresh failed: ${at(e)}`,ot(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(G,{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): ${at(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 Xi(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Not authenticated. Call login() first.");return Ji(async()=>{const e=await this.http.get(W,void 0,this.jwtAuth.getJwtHeaders());return this.extractSessionData(e)},"SessionAuthService.getSession",this.logger,e=>{if(e instanceof Xi)throw e;throw new Xi(exports.AuthErrorType.SIGNATURE_FAILED,`Failed to get session: ${at(e)}`,ot(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 Xi(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Not authenticated. Call login() first.");if(this.jwtAuth.isExpired()){if(await this.jwtAuth.getRefreshToken()){this.logger.debug("Token expired - refresh token available, attempting refresh");try{return(await this.refresh()).accessToken}catch(e){this.logger.warn(`Refresh failed after expiry: ${at(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 Xi(exports.AuthErrorType.SIGNATURE_FAILED,""!==at(e)?at(e):"Authentication failed");const t=Kt(e,"No data in authentication response"),{accessToken:n,expiresIn:r,address:s,refreshToken:i,refreshExpiresIn:o}=t;if(!Kn(n))throw new Xi(exports.AuthErrorType.SIGNATURE_FAILED,"Invalid access token in response");if("number"!=typeof r||r<=0)throw new Xi(exports.AuthErrorType.SIGNATURE_FAILED,"Invalid expiration in response");return{accessToken:n,expiresIn:r,address:s,...void 0!==i&&{refreshToken:i},...void 0!==o&&{refreshExpiresIn:o}}}extractSessionData(e){if(e.error)throw new Xi(exports.AuthErrorType.SIGNATURE_FAILED,""!==at(e)?at(e):"Failed to get session");return Kt(e,"No data in session response")}}class eo 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"}(ji||(ji={}));class to{constructor(t){this.providerType="privateKey",this.connected=!0;try{this.wallet=new e.Wallet(t)}catch(e){throw new eo("Invalid private key provided",ji.INVALID_CONFIG,e instanceof Error?e:void 0)}}static fromWallet(e){return new to(e.privateKey)}async signMessage(e){try{return await this.wallet.signMessage(e)}catch(e){throw new eo("Failed to sign message",ji.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 eo("Failed to sign typed data",ji.SIGNING_FAILED,e instanceof Error?e:void 0)}}getAddress(){return Promise.resolve(e.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 no{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{Un(e.messagePrefix,"messagePrefix",!1)}catch{throw new Xi(exports.AuthErrorType.SIGNATURE_FAILED,"Message prefix cannot be empty")}}hasWallet(){return void 0!==this.walletProvider||void 0!==this.wallet}ensureWalletProvider(){if(this.wallet&&!this.walletProvider)try{this.walletProvider=to.fromWallet(this.wallet),this.cachedAddress=this.wallet.address,this.cachedGalaAddress=hr(this.wallet.address)}catch(e){if(e instanceof Xi)throw e;if(e instanceof yt&&("INVALID_ADDRESS"===e.code||"INVALID_FORMAT"===e.code||"address"===e.field))throw new Xi(exports.AuthErrorType.INVALID_ADDRESS,e.message);if(null!==e&&"object"==typeof e&&"message"in e)throw new Xi(exports.AuthErrorType.WALLET_NOT_CONNECTED,e.message);throw e}}setWallet(e){if(void 0!==e){if("object"!=typeof e||!("address"in e))throw new Xi(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Invalid wallet: must be an ethers Wallet instance or undefined");if("string"!=typeof e.address||""===e.address)throw new Xi(exports.AuthErrorType.INVALID_ADDRESS,"Wallet address is not available");this.walletProvider=to.fromWallet(e),this.cachedAddress=e.address,this.cachedGalaAddress=hr(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 Xi)throw e;throw new Xi(exports.AuthErrorType.SIGNATURE_FAILED,"Failed to generate signature for authentication",ot(e)?e:new Error(at(e)))}}getAddress(){if(this.validateWallet(),this.cachedGalaAddress)return this.cachedGalaAddress;if(this.wallet)return this.formatAddress(this.wallet.address);throw new Xi(exports.AuthErrorType.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 Xi(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Address not available. For external wallets, call cacheAddress() after connecting.")}async getEthereumAddressAsync(){return await this.validateWalletAsync(),this.walletProvider.getAddress()}getPrivateKey(){if(this.validateWallet(),this.wallet){if(""===this.wallet.privateKey||null===this.wallet.privateKey||void 0===this.wallet.privateKey)throw new Xi(exports.AuthErrorType.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 Xi(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Private key not available. External wallet providers cannot access private keys. Use PrivateKeyProvider for @gala-chain signing operations.")}async getPrivateKeyAsync(){if(await this.validateWalletAsync(),!this.walletProvider.getPrivateKey)throw new Xi(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Private key not available with this wallet provider");try{return await this.walletProvider.getPrivateKey()}catch(e){throw new Xi(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Private key not available. External wallet providers cannot access private keys. Use PrivateKeyProvider for @gala-chain signing operations.",ot(e)?e:void 0)}}formatAddress(e){try{return hr(e)}catch{throw new Xi(exports.AuthErrorType.INVALID_ADDRESS,`Invalid Ethereum address format: ${e}`)}}async signMessage(e){await this.validateWalletAsync();try{const t=await this.walletProvider.signMessage(e);return{message:e,signature:t,address:await this.walletProvider.getAddress(),timestamp:Date.now()}}catch(e){if(e instanceof Xi)throw e;throw new Xi(exports.AuthErrorType.SIGNATURE_FAILED,at(e),ot(e)?e:new Error(at(e)))}}async generateAuthHeaders(e,t){await this.validateWalletAsync();try{const n=Date.now(),r=`${this.messagePrefix} ${t.toUpperCase()} ${e} ${n}`,s=await this.walletProvider.signMessage(r);return{"x-signature":s,"x-address":await this.walletProvider.getGalaAddress(),"x-message":r,"x-timestamp":n.toString()}}catch(e){if(e instanceof Xi)throw e;throw new Xi(exports.AuthErrorType.SIGNATURE_FAILED,"Failed to generate authentication headers",ot(e)?e:new Error(at(e)))}}async signTypedData(e,t,n){await this.validateWalletAsync();try{const r={};for(const[e,n]of Object.entries(t))r[e]=n.map(e=>({name:e.name,type:e.type}));return await this.walletProvider.signTypedData(e,r,n)}catch(e){if(e instanceof Xi)throw e;throw new Xi(exports.AuthErrorType.SIGNATURE_FAILED,"Failed to sign typed data",ot(e)?e:new Error(at(e)))}}async generateCustomSignature(e){if(!Kn(e))throw new Xi(exports.AuthErrorType.SIGNATURE_FAILED,"Custom message must be a non-empty string");await this.validateWalletAsync();try{const t=await this.walletProvider.signMessage(e);return{message:e,signature:t,address:await this.walletProvider.getGalaAddress(),timestamp:Date.now()}}catch(e){if(e instanceof Xi)throw e;throw new Xi(exports.AuthErrorType.SIGNATURE_FAILED,"Failed to generate custom message signature",ot(e)?e:new Error(at(e)))}}validateWallet(){if(this.ensureWalletProvider(),!this.walletProvider)throw new Xi(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Wallet is required for authentication")}async validateWalletAsync(){if(this.ensureWalletProvider(),!this.walletProvider)throw new Xi(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Wallet is required for authentication");if(!this.walletProvider.isConnected())throw new Xi(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Wallet is not connected. Call connect() on the wallet provider first.")}}const ro={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 so(e){return ro[e]}function io(e){return`${e.collection}|${e.category}|${e.type}|${e.additionalKey}`}function oo(e){return`${e.collection}$${e.category}$${e.type}$${e.additionalKey}`}const ao={GALA_CHAIN:1,ETHEREUM:2,SOLANA:1002},co={ASSET:1,MUSIC:3};const lo="0x9f452b7cC24e6e6FA690fe77CF5dD2ba3DbF1ED9",uo="0x6a1734E09f3099a3675645D214ce547080ea67e0",ho="https://dex-api-platform-dex-prod-gala.gala.com",go=[{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}],fo=[{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 po(e){return"prod"===e?go:fo}function mo(e){return"prod"===e?lo:uo}const yo=go,bo=[{symbol:"GALA",amount:"1",mintAddress:"eEUiUs4JWYZrp72djAGF1A8PhpR6rHphGeGN7GbVLp6",isNative:!1,decimals:8},{symbol:"GSOL",amount:"0.001",mintAddress:"So11111111111111111111111111111111111111111",isNative:!0,decimals:9}],vo={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"}},wo=["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)"],Eo=["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"],Ao={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 So(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function ko(e){if(Object.prototype.hasOwnProperty.call(e,"__esModule"))return e;var t=e.default;if("function"==typeof t){var n=function e(){var n=!1;try{n=this instanceof e}catch(e){}return n?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};n.prototype=t.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(e).forEach(function(t){var r=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(n,t,r.get?r:{enumerable:!0,get:function(){return e[t]}})}),n}var To,Io={},Co={};function No(){if(To)return Co;To=1,Co.byteLength=function(e){var t=i(e),n=t[0],r=t[1];return 3*(n+r)/4-r},Co.toByteArray=function(e){var r,s,o=i(e),a=o[0],c=o[1],l=new n(function(e,t,n){return 3*(t+n)/4-n}(0,a,c)),u=0,d=c>0?a-4:a;for(s=0;s<d;s+=4)r=t[e.charCodeAt(s)]<<18|t[e.charCodeAt(s+1)]<<12|t[e.charCodeAt(s+2)]<<6|t[e.charCodeAt(s+3)],l[u++]=r>>16&255,l[u++]=r>>8&255,l[u++]=255&r;2===c&&(r=t[e.charCodeAt(s)]<<2|t[e.charCodeAt(s+1)]>>4,l[u++]=255&r);1===c&&(r=t[e.charCodeAt(s)]<<10|t[e.charCodeAt(s+1)]<<4|t[e.charCodeAt(s+2)]>>2,l[u++]=r>>8&255,l[u++]=255&r);return l},Co.fromByteArray=function(t){for(var n,r=t.length,s=r%3,i=[],o=16383,c=0,l=r-s;c<l;c+=o)i.push(a(t,c,c+o>l?l:c+o));1===s?(n=t[r-1],i.push(e[n>>2]+e[n<<4&63]+"==")):2===s&&(n=(t[r-2]<<8)+t[r-1],i.push(e[n>>10]+e[n>>4&63]+e[n<<2&63]+"="));return i.join("")};for(var e=[],t=[],n="undefined"!=typeof Uint8Array?Uint8Array:Array,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s=0;s<64;++s)e[s]=r[s],t[r.charCodeAt(s)]=s;function i(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var n=e.indexOf("=");return-1===n&&(n=t),[n,n===t?0:4-n%4]}function o(t){return e[t>>18&63]+e[t>>12&63]+e[t>>6&63]+e[63&t]}function a(e,t,n){for(var r,s=[],i=t;i<n;i+=3)r=(e[i]<<16&16711680)+(e[i+1]<<8&65280)+(255&e[i+2]),s.push(o(r));return s.join("")}return t["-".charCodeAt(0)]=62,t["_".charCodeAt(0)]=63,Co}var _o,xo,Ro={};function Bo(){return _o||(_o=1,Ro.read=function(e,t,n,r,s){var i,o,a=8*s-r-1,c=(1<<a)-1,l=c>>1,u=-7,d=n?s-1:0,h=n?-1:1,g=e[t+d];for(d+=h,i=g&(1<<-u)-1,g>>=-u,u+=a;u>0;i=256*i+e[t+d],d+=h,u-=8);for(o=i&(1<<-u)-1,i>>=-u,u+=r;u>0;o=256*o+e[t+d],d+=h,u-=8);if(0===i)i=1-l;else{if(i===c)return o?NaN:1/0*(g?-1:1);o+=Math.pow(2,r),i-=l}return(g?-1:1)*o*Math.pow(2,i-r)},Ro.write=function(e,t,n,r,s,i){var o,a,c,l=8*i-s-1,u=(1<<l)-1,d=u>>1,h=23===s?Math.pow(2,-24)-Math.pow(2,-77):0,g=r?0:i-1,f=r?1:-1,p=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,o=u):(o=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-o))<1&&(o--,c*=2),(t+=o+d>=1?h/c:h*Math.pow(2,1-d))*c>=2&&(o++,c/=2),o+d>=u?(a=0,o=u):o+d>=1?(a=(t*c-1)*Math.pow(2,s),o+=d):(a=t*Math.pow(2,d-1)*Math.pow(2,s),o=0));s>=8;e[n+g]=255&a,g+=f,a/=256,s-=8);for(o=o<<s|a,l+=s;l>0;e[n+g]=255&o,g+=f,o/=256,l-=8);e[n+g-f]|=128*p}),Ro}function Do(){return xo||(xo=1,function(e){const t=No(),n=Bo(),r="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;e.Buffer=o,e.SlowBuffer=function(e){+e!=e&&(e=0);return o.alloc(+e)},e.INSPECT_MAX_BYTES=50;const s=2147483647;function i(e){if(e>s)throw new RangeError('The value "'+e+'" is invalid for option "size"');const t=new Uint8Array(e);return Object.setPrototypeOf(t,o.prototype),t}function o(e,t,n){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return l(e)}return a(e,t,n)}function a(e,t,n){if("string"==typeof e)return function(e,t){"string"==typeof t&&""!==t||(t="utf8");if(!o.isEncoding(t))throw new TypeError("Unknown encoding: "+t);const n=0|g(e,t);let r=i(n);const s=r.write(e,t);s!==n&&(r=r.slice(0,s));return r}(e,t);if(ArrayBuffer.isView(e))return function(e){if(V(e,Uint8Array)){const t=new Uint8Array(e);return d(t.buffer,t.byteOffset,t.byteLength)}return u(e)}(e);if(null==e)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(V(e,ArrayBuffer)||e&&V(e.buffer,ArrayBuffer))return d(e,t,n);if("undefined"!=typeof SharedArrayBuffer&&(V(e,SharedArrayBuffer)||e&&V(e.buffer,SharedArrayBuffer)))return d(e,t,n);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');const r=e.valueOf&&e.valueOf();if(null!=r&&r!==e)return o.from(r,t,n);const s=function(e){if(o.isBuffer(e)){const t=0|h(e.length),n=i(t);return 0===n.length||e.copy(n,0,0,t),n}if(void 0!==e.length)return"number"!=typeof e.length||j(e.length)?i(0):u(e);if("Buffer"===e.type&&Array.isArray(e.data))return u(e.data)}(e);if(s)return s;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return o.from(e[Symbol.toPrimitive]("string"),t,n);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function c(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function l(e){return c(e),i(e<0?0:0|h(e))}function u(e){const t=e.length<0?0:0|h(e.length),n=i(t);for(let r=0;r<t;r+=1)n[r]=255&e[r];return n}function d(e,t,n){if(t<0||e.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(n||0))throw new RangeError('"length" is outside of buffer bounds');let r;return r=void 0===t&&void 0===n?new Uint8Array(e):void 0===n?new Uint8Array(e,t):new Uint8Array(e,t,n),Object.setPrototypeOf(r,o.prototype),r}function h(e){if(e>=s)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s.toString(16)+" bytes");return 0|e}function g(e,t){if(o.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||V(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);const n=e.length,r=arguments.length>2&&!0===arguments[2];if(!r&&0===n)return 0;let s=!1;for(;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":return W(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return q(e).length;default:if(s)return r?-1:W(e).length;t=(""+t).toLowerCase(),s=!0}}function f(e,t,n){let r=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if((n>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return N(this,t,n);case"utf8":case"utf-8":return k(this,t,n);case"ascii":return I(this,t,n);case"latin1":case"binary":return C(this,t,n);case"base64":return S(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return _(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function p(e,t,n){const r=e[t];e[t]=e[n],e[n]=r}function m(e,t,n,r,s){if(0===e.length)return-1;if("string"==typeof n?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),j(n=+n)&&(n=s?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(s)return-1;n=e.length-1}else if(n<0){if(!s)return-1;n=0}if("string"==typeof t&&(t=o.from(t,r)),o.isBuffer(t))return 0===t.length?-1:y(e,t,n,r,s);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?s?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):y(e,[t],n,r,s);throw new TypeError("val must be string, number or Buffer")}function y(e,t,n,r,s){let i,o=1,a=e.length,c=t.length;if(void 0!==r&&("ucs2"===(r=String(r).toLowerCase())||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(e.length<2||t.length<2)return-1;o=2,a/=2,c/=2,n/=2}function l(e,t){return 1===o?e[t]:e.readUInt16BE(t*o)}if(s){let r=-1;for(i=n;i<a;i++)if(l(e,i)===l(t,-1===r?0:i-r)){if(-1===r&&(r=i),i-r+1===c)return r*o}else-1!==r&&(i-=i-r),r=-1}else for(n+c>a&&(n=a-c),i=n;i>=0;i--){let n=!0;for(let r=0;r<c;r++)if(l(e,i+r)!==l(t,r)){n=!1;break}if(n)return i}return-1}function b(e,t,n,r){n=Number(n)||0;const s=e.length-n;r?(r=Number(r))>s&&(r=s):r=s;const i=t.length;let o;for(r>i/2&&(r=i/2),o=0;o<r;++o){const r=parseInt(t.substr(2*o,2),16);if(j(r))return o;e[n+o]=r}return o}function v(e,t,n,r){return z(W(t,e.length-n),e,n,r)}function w(e,t,n,r){return z(function(e){const t=[];for(let n=0;n<e.length;++n)t.push(255&e.charCodeAt(n));return t}(t),e,n,r)}function E(e,t,n,r){return z(q(t),e,n,r)}function A(e,t,n,r){return z(function(e,t){let n,r,s;const i=[];for(let o=0;o<e.length&&!((t-=2)<0);++o)n=e.charCodeAt(o),r=n>>8,s=n%256,i.push(s),i.push(r);return i}(t,e.length-n),e,n,r)}function S(e,n,r){return 0===n&&r===e.length?t.fromByteArray(e):t.fromByteArray(e.slice(n,r))}function k(e,t,n){n=Math.min(e.length,n);const r=[];let s=t;for(;s<n;){const t=e[s];let i=null,o=t>239?4:t>223?3:t>191?2:1;if(s+o<=n){let n,r,a,c;switch(o){case 1:t<128&&(i=t);break;case 2:n=e[s+1],128==(192&n)&&(c=(31&t)<<6|63&n,c>127&&(i=c));break;case 3:n=e[s+1],r=e[s+2],128==(192&n)&&128==(192&r)&&(c=(15&t)<<12|(63&n)<<6|63&r,c>2047&&(c<55296||c>57343)&&(i=c));break;case 4:n=e[s+1],r=e[s+2],a=e[s+3],128==(192&n)&&128==(192&r)&&128==(192&a)&&(c=(15&t)<<18|(63&n)<<12|(63&r)<<6|63&a,c>65535&&c<1114112&&(i=c))}}null===i?(i=65533,o=1):i>65535&&(i-=65536,r.push(i>>>10&1023|55296),i=56320|1023&i),r.push(i),s+=o}return function(e){const t=e.length;if(t<=T)return String.fromCharCode.apply(String,e);let n="",r=0;for(;r<t;)n+=String.fromCharCode.apply(String,e.slice(r,r+=T));return n}(r)}e.kMaxLength=s,o.TYPED_ARRAY_SUPPORT=function(){try{const e=new Uint8Array(1),t={foo:function(){return 42}};return Object.setPrototypeOf(t,Uint8Array.prototype),Object.setPrototypeOf(e,t),42===e.foo()}catch(e){return!1}}(),!o.TYPED_ARRAY_SUPPORT&&"undefined"!=typeof console&&console.error,Object.defineProperty(o.prototype,"parent",{enumerable:!0,get:function(){if(o.isBuffer(this))return this.buffer}}),Object.defineProperty(o.prototype,"offset",{enumerable:!0,get:function(){if(o.isBuffer(this))return this.byteOffset}}),o.poolSize=8192,o.from=function(e,t,n){return a(e,t,n)},Object.setPrototypeOf(o.prototype,Uint8Array.prototype),Object.setPrototypeOf(o,Uint8Array),o.alloc=function(e,t,n){return function(e,t,n){return c(e),e<=0?i(e):void 0!==t?"string"==typeof n?i(e).fill(t,n):i(e).fill(t):i(e)}(e,t,n)},o.allocUnsafe=function(e){return l(e)},o.allocUnsafeSlow=function(e){return l(e)},o.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==o.prototype},o.compare=function(e,t){if(V(e,Uint8Array)&&(e=o.from(e,e.offset,e.byteLength)),V(t,Uint8Array)&&(t=o.from(t,t.offset,t.byteLength)),!o.isBuffer(e)||!o.isBuffer(t))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;let n=e.length,r=t.length;for(let s=0,i=Math.min(n,r);s<i;++s)if(e[s]!==t[s]){n=e[s],r=t[s];break}return n<r?-1:r<n?1:0},o.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},o.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return o.alloc(0);let n;if(void 0===t)for(t=0,n=0;n<e.length;++n)t+=e[n].length;const r=o.allocUnsafe(t);let s=0;for(n=0;n<e.length;++n){let t=e[n];if(V(t,Uint8Array))s+t.length>r.length?(o.isBuffer(t)||(t=o.from(t)),t.copy(r,s)):Uint8Array.prototype.set.call(r,t,s);else{if(!o.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(r,s)}s+=t.length}return r},o.byteLength=g,o.prototype._isBuffer=!0,o.prototype.swap16=function(){const e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let t=0;t<e;t+=2)p(this,t,t+1);return this},o.prototype.swap32=function(){const e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let t=0;t<e;t+=4)p(this,t,t+3),p(this,t+1,t+2);return this},o.prototype.swap64=function(){const e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let t=0;t<e;t+=8)p(this,t,t+7),p(this,t+1,t+6),p(this,t+2,t+5),p(this,t+3,t+4);return this},o.prototype.toString=function(){const e=this.length;return 0===e?"":0===arguments.length?k(this,0,e):f.apply(this,arguments)},o.prototype.toLocaleString=o.prototype.toString,o.prototype.equals=function(e){if(!o.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===o.compare(this,e)},o.prototype.inspect=function(){let t="";const n=e.INSPECT_MAX_BYTES;return t=this.toString("hex",0,n).replace(/(.{2})/g,"$1 ").trim(),this.length>n&&(t+=" ... "),"<Buffer "+t+">"},r&&(o.prototype[r]=o.prototype.inspect),o.prototype.compare=function(e,t,n,r,s){if(V(e,Uint8Array)&&(e=o.from(e,e.offset,e.byteLength)),!o.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===r&&(r=0),void 0===s&&(s=this.length),t<0||n>e.length||r<0||s>this.length)throw new RangeError("out of range index");if(r>=s&&t>=n)return 0;if(r>=s)return-1;if(t>=n)return 1;if(this===e)return 0;let i=(s>>>=0)-(r>>>=0),a=(n>>>=0)-(t>>>=0);const c=Math.min(i,a),l=this.slice(r,s),u=e.slice(t,n);for(let e=0;e<c;++e)if(l[e]!==u[e]){i=l[e],a=u[e];break}return i<a?-1:a<i?1:0},o.prototype.includes=function(e,t,n){return-1!==this.indexOf(e,t,n)},o.prototype.indexOf=function(e,t,n){return m(this,e,t,n,!0)},o.prototype.lastIndexOf=function(e,t,n){return m(this,e,t,n,!1)},o.prototype.write=function(e,t,n,r){if(void 0===t)r="utf8",n=this.length,t=0;else if(void 0===n&&"string"==typeof t)r=t,n=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t>>>=0,isFinite(n)?(n>>>=0,void 0===r&&(r="utf8")):(r=n,n=void 0)}const s=this.length-t;if((void 0===n||n>s)&&(n=s),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");let i=!1;for(;;)switch(r){case"hex":return b(this,e,t,n);case"utf8":case"utf-8":return v(this,e,t,n);case"ascii":case"latin1":case"binary":return w(this,e,t,n);case"base64":return E(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return A(this,e,t,n);default:if(i)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),i=!0}},o.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const T=4096;function I(e,t,n){let r="";n=Math.min(e.length,n);for(let s=t;s<n;++s)r+=String.fromCharCode(127&e[s]);return r}function C(e,t,n){let r="";n=Math.min(e.length,n);for(let s=t;s<n;++s)r+=String.fromCharCode(e[s]);return r}function N(e,t,n){const r=e.length;(!t||t<0)&&(t=0),(!n||n<0||n>r)&&(n=r);let s="";for(let r=t;r<n;++r)s+=X[e[r]];return s}function _(e,t,n){const r=e.slice(t,n);let s="";for(let e=0;e<r.length-1;e+=2)s+=String.fromCharCode(r[e]+256*r[e+1]);return s}function x(e,t,n){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>n)throw new RangeError("Trying to access beyond buffer length")}function R(e,t,n,r,s,i){if(!o.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>s||t<i)throw new RangeError('"value" argument is out of bounds');if(n+r>e.length)throw new RangeError("Index out of range")}function B(e,t,n,r,s){$(t,r,s,e,n,7);let i=Number(t&BigInt(4294967295));e[n++]=i,i>>=8,e[n++]=i,i>>=8,e[n++]=i,i>>=8,e[n++]=i;let o=Number(t>>BigInt(32)&BigInt(4294967295));return e[n++]=o,o>>=8,e[n++]=o,o>>=8,e[n++]=o,o>>=8,e[n++]=o,n}function D(e,t,n,r,s){$(t,r,s,e,n,7);let i=Number(t&BigInt(4294967295));e[n+7]=i,i>>=8,e[n+6]=i,i>>=8,e[n+5]=i,i>>=8,e[n+4]=i;let o=Number(t>>BigInt(32)&BigInt(4294967295));return e[n+3]=o,o>>=8,e[n+2]=o,o>>=8,e[n+1]=o,o>>=8,e[n]=o,n+8}function O(e,t,n,r,s,i){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function M(e,t,r,s,i){return t=+t,r>>>=0,i||O(e,0,r,4),n.write(e,t,r,s,23,4),r+4}function L(e,t,r,s,i){return t=+t,r>>>=0,i||O(e,0,r,8),n.write(e,t,r,s,52,8),r+8}o.prototype.slice=function(e,t){const n=this.length;(e=~~e)<0?(e+=n)<0&&(e=0):e>n&&(e=n),(t=void 0===t?n:~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),t<e&&(t=e);const r=this.subarray(e,t);return Object.setPrototypeOf(r,o.prototype),r},o.prototype.readUintLE=o.prototype.readUIntLE=function(e,t,n){e>>>=0,t>>>=0,n||x(e,t,this.length);let r=this[e],s=1,i=0;for(;++i<t&&(s*=256);)r+=this[e+i]*s;return r},o.prototype.readUintBE=o.prototype.readUIntBE=function(e,t,n){e>>>=0,t>>>=0,n||x(e,t,this.length);let r=this[e+--t],s=1;for(;t>0&&(s*=256);)r+=this[e+--t]*s;return r},o.prototype.readUint8=o.prototype.readUInt8=function(e,t){return e>>>=0,t||x(e,1,this.length),this[e]},o.prototype.readUint16LE=o.prototype.readUInt16LE=function(e,t){return e>>>=0,t||x(e,2,this.length),this[e]|this[e+1]<<8},o.prototype.readUint16BE=o.prototype.readUInt16BE=function(e,t){return e>>>=0,t||x(e,2,this.length),this[e]<<8|this[e+1]},o.prototype.readUint32LE=o.prototype.readUInt32LE=function(e,t){return e>>>=0,t||x(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},o.prototype.readUint32BE=o.prototype.readUInt32BE=function(e,t){return e>>>=0,t||x(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},o.prototype.readBigUInt64LE=Y(function(e){K(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||G(e,this.length-8);const r=t+256*this[++e]+65536*this[++e]+this[++e]*2**24,s=this[++e]+256*this[++e]+65536*this[++e]+n*2**24;return BigInt(r)+(BigInt(s)<<BigInt(32))}),o.prototype.readBigUInt64BE=Y(function(e){K(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||G(e,this.length-8);const r=t*2**24+65536*this[++e]+256*this[++e]+this[++e],s=this[++e]*2**24+65536*this[++e]+256*this[++e]+n;return(BigInt(r)<<BigInt(32))+BigInt(s)}),o.prototype.readIntLE=function(e,t,n){e>>>=0,t>>>=0,n||x(e,t,this.length);let r=this[e],s=1,i=0;for(;++i<t&&(s*=256);)r+=this[e+i]*s;return s*=128,r>=s&&(r-=Math.pow(2,8*t)),r},o.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||x(e,t,this.length);let r=t,s=1,i=this[e+--r];for(;r>0&&(s*=256);)i+=this[e+--r]*s;return s*=128,i>=s&&(i-=Math.pow(2,8*t)),i},o.prototype.readInt8=function(e,t){return e>>>=0,t||x(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},o.prototype.readInt16LE=function(e,t){e>>>=0,t||x(e,2,this.length);const n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},o.prototype.readInt16BE=function(e,t){e>>>=0,t||x(e,2,this.length);const n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},o.prototype.readInt32LE=function(e,t){return e>>>=0,t||x(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},o.prototype.readInt32BE=function(e,t){return e>>>=0,t||x(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},o.prototype.readBigInt64LE=Y(function(e){K(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||G(e,this.length-8);const r=this[e+4]+256*this[e+5]+65536*this[e+6]+(n<<24);return(BigInt(r)<<BigInt(32))+BigInt(t+256*this[++e]+65536*this[++e]+this[++e]*2**24)}),o.prototype.readBigInt64BE=Y(function(e){K(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||G(e,this.length-8);const r=(t<<24)+65536*this[++e]+256*this[++e]+this[++e];return(BigInt(r)<<BigInt(32))+BigInt(this[++e]*2**24+65536*this[++e]+256*this[++e]+n)}),o.prototype.readFloatLE=function(e,t){return e>>>=0,t||x(e,4,this.length),n.read(this,e,!0,23,4)},o.prototype.readFloatBE=function(e,t){return e>>>=0,t||x(e,4,this.length),n.read(this,e,!1,23,4)},o.prototype.readDoubleLE=function(e,t){return e>>>=0,t||x(e,8,this.length),n.read(this,e,!0,52,8)},o.prototype.readDoubleBE=function(e,t){return e>>>=0,t||x(e,8,this.length),n.read(this,e,!1,52,8)},o.prototype.writeUintLE=o.prototype.writeUIntLE=function(e,t,n,r){if(e=+e,t>>>=0,n>>>=0,!r){R(this,e,t,n,Math.pow(2,8*n)-1,0)}let s=1,i=0;for(this[t]=255&e;++i<n&&(s*=256);)this[t+i]=e/s&255;return t+n},o.prototype.writeUintBE=o.prototype.writeUIntBE=function(e,t,n,r){if(e=+e,t>>>=0,n>>>=0,!r){R(this,e,t,n,Math.pow(2,8*n)-1,0)}let s=n-1,i=1;for(this[t+s]=255&e;--s>=0&&(i*=256);)this[t+s]=e/i&255;return t+n},o.prototype.writeUint8=o.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||R(this,e,t,1,255,0),this[t]=255&e,t+1},o.prototype.writeUint16LE=o.prototype.writeUInt16LE=function(e,t,n){return e=+e,t>>>=0,n||R(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},o.prototype.writeUint16BE=o.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||R(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},o.prototype.writeUint32LE=o.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||R(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},o.prototype.writeUint32BE=o.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||R(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},o.prototype.writeBigUInt64LE=Y(function(e,t=0){return B(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),o.prototype.writeBigUInt64BE=Y(function(e,t=0){return D(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),o.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t>>>=0,!r){const r=Math.pow(2,8*n-1);R(this,e,t,n,r-1,-r)}let s=0,i=1,o=0;for(this[t]=255&e;++s<n&&(i*=256);)e<0&&0===o&&0!==this[t+s-1]&&(o=1),this[t+s]=(e/i|0)-o&255;return t+n},o.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t>>>=0,!r){const r=Math.pow(2,8*n-1);R(this,e,t,n,r-1,-r)}let s=n-1,i=1,o=0;for(this[t+s]=255&e;--s>=0&&(i*=256);)e<0&&0===o&&0!==this[t+s+1]&&(o=1),this[t+s]=(e/i|0)-o&255;return t+n},o.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||R(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},o.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||R(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},o.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||R(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},o.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||R(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},o.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||R(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},o.prototype.writeBigInt64LE=Y(function(e,t=0){return B(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),o.prototype.writeBigInt64BE=Y(function(e,t=0){return D(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),o.prototype.writeFloatLE=function(e,t,n){return M(this,e,t,!0,n)},o.prototype.writeFloatBE=function(e,t,n){return M(this,e,t,!1,n)},o.prototype.writeDoubleLE=function(e,t,n){return L(this,e,t,!0,n)},o.prototype.writeDoubleBE=function(e,t,n){return L(this,e,t,!1,n)},o.prototype.copy=function(e,t,n,r){if(!o.isBuffer(e))throw new TypeError("argument should be a Buffer");if(n||(n=0),r||0===r||(r=this.length),t>=e.length&&(t=e.length),t||(t=0),r>0&&r<n&&(r=n),r===n)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(n<0||n>=this.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-t<r-n&&(r=e.length-t+n);const s=r-n;return this===e&&"function"==typeof Uint8Array.prototype.copyWithin?this.copyWithin(t,n,r):Uint8Array.prototype.set.call(e,this.subarray(n,r),t),s},o.prototype.fill=function(e,t,n,r){if("string"==typeof e){if("string"==typeof t?(r=t,t=0,n=this.length):"string"==typeof n&&(r=n,n=this.length),void 0!==r&&"string"!=typeof r)throw new TypeError("encoding must be a string");if("string"==typeof r&&!o.isEncoding(r))throw new TypeError("Unknown encoding: "+r);if(1===e.length){const t=e.charCodeAt(0);("utf8"===r&&t<128||"latin1"===r)&&(e=t)}}else"number"==typeof e?e&=255:"boolean"==typeof e&&(e=Number(e));if(t<0||this.length<t||this.length<n)throw new RangeError("Out of range index");if(n<=t)return this;let s;if(t>>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(s=t;s<n;++s)this[s]=e;else{const i=o.isBuffer(e)?e:o.from(e,r),a=i.length;if(0===a)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(s=0;s<n-t;++s)this[s+t]=i[s%a]}return this};const U={};function P(e,t,n){U[e]=class extends n{constructor(){super(),Object.defineProperty(this,"message",{value:t.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${e}]`,this.stack,delete this.name}get code(){return e}set code(e){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:e,writable:!0})}toString(){return`${this.name} [${e}]: ${this.message}`}}}function F(e){let t="",n=e.length;const r="-"===e[0]?1:0;for(;n>=r+4;n-=3)t=`_${e.slice(n-3,n)}${t}`;return`${e.slice(0,n)}${t}`}function $(e,t,n,r,s,i){if(e>n||e<t){const n="bigint"==typeof t?"n":"";let r;throw r=0===t||t===BigInt(0)?`>= 0${n} and < 2${n} ** ${8*(i+1)}${n}`:`>= -(2${n} ** ${8*(i+1)-1}${n}) and < 2 ** ${8*(i+1)-1}${n}`,new U.ERR_OUT_OF_RANGE("value",r,e)}!function(e,t,n){K(t,"offset"),void 0!==e[t]&&void 0!==e[t+n]||G(t,e.length-(n+1))}(r,s,i)}function K(e,t){if("number"!=typeof e)throw new U.ERR_INVALID_ARG_TYPE(t,"number",e)}function G(e,t,n){if(Math.floor(e)!==e)throw K(e,n),new U.ERR_OUT_OF_RANGE("offset","an integer",e);if(t<0)throw new U.ERR_BUFFER_OUT_OF_BOUNDS;throw new U.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${t}`,e)}P("ERR_BUFFER_OUT_OF_BOUNDS",function(e){return e?`${e} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),P("ERR_INVALID_ARG_TYPE",function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`},TypeError),P("ERR_OUT_OF_RANGE",function(e,t,n){let r=`The value of "${e}" is out of range.`,s=n;return Number.isInteger(n)&&Math.abs(n)>2**32?s=F(String(n)):"bigint"==typeof n&&(s=String(n),(n>BigInt(2)**BigInt(32)||n<-(BigInt(2)**BigInt(32)))&&(s=F(s)),s+="n"),r+=` It must be ${t}. Received ${s}`,r},RangeError);const H=/[^+/0-9A-Za-z-_]/g;function W(e,t){let n;t=t||1/0;const r=e.length;let s=null;const i=[];for(let o=0;o<r;++o){if(n=e.charCodeAt(o),n>55295&&n<57344){if(!s){if(n>56319){(t-=3)>-1&&i.push(239,191,189);continue}if(o+1===r){(t-=3)>-1&&i.push(239,191,189);continue}s=n;continue}if(n<56320){(t-=3)>-1&&i.push(239,191,189),s=n;continue}n=65536+(s-55296<<10|n-56320)}else s&&(t-=3)>-1&&i.push(239,191,189);if(s=null,n<128){if((t-=1)<0)break;i.push(n)}else if(n<2048){if((t-=2)<0)break;i.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;i.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;i.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return i}function q(e){return t.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(H,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function z(e,t,n,r){let s;for(s=0;s<r&&!(s+n>=t.length||s>=e.length);++s)t[s+n]=e[s];return s}function V(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function j(e){return e!=e}const X=function(){const e="0123456789abcdef",t=new Array(256);for(let n=0;n<16;++n){const r=16*n;for(let s=0;s<16;++s)t[r+s]=e[n]+e[s]}return t}();function Y(e){return"undefined"==typeof BigInt?J:e}function J(){throw new Error("BigInt not supported")}}(Io)),Io}var Oo=Do();const Mo="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0;function Lo(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function Uo(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function Po(e,...t){if(!Lo(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function Fo(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.createHasher");Uo(e.outputLen),Uo(e.blockLen)}function $o(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function Ko(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Go(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Ho(e,t){return e<<32-t|e>>>t}const Wo=(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)(),qo=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function zo(e){if(Po(e),Wo)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=qo[e[n]];return t}const Vo=48,jo=57,Xo=65,Yo=70,Jo=97,Qo=102;function Zo(e){return e>=Vo&&e<=jo?e-Vo:e>=Xo&&e<=Yo?e-(Xo-10):e>=Jo&&e<=Qo?e-(Jo-10):void 0}function ea(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);if(Wo)return Uint8Array.fromHex(e);const t=e.length,n=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);const r=new Uint8Array(n);for(let t=0,s=0;t<n;t++,s+=2){const n=Zo(e.charCodeAt(s)),i=Zo(e.charCodeAt(s+1));if(void 0===n||void 0===i){const t=e[s]+e[s+1];throw new Error('hex string expected, got non-hex character "'+t+'" at index '+s)}r[t]=16*n+i}return r}function ta(e){return"string"==typeof e&&(e=function(e){if("string"!=typeof e)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(e))}(e)),Po(e),e}function na(...e){let t=0;for(let n=0;n<e.length;n++){const r=e[n];Po(r),t+=r.length}const n=new Uint8Array(t);for(let t=0,r=0;t<e.length;t++){const s=e[t];n.set(s,r),r+=s.length}return n}class ra{}function sa(e){const t=t=>e().update(ta(t)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function ia(e=32){if(Mo&&"function"==typeof Mo.getRandomValues)return Mo.getRandomValues(new Uint8Array(e));if(Mo&&"function"==typeof Mo.randomBytes)return Uint8Array.from(Mo.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}function oa(e,t,n){return e&t^~e&n}function aa(e,t,n){return e&t^e&n^t&n}class ca extends ra{constructor(e,t,n,r){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(e),this.view=Go(this.buffer)}update(e){$o(this),Po(e=ta(e));const{view:t,buffer:n,blockLen:r}=this,s=e.length;for(let i=0;i<s;){const o=Math.min(r-this.pos,s-i);if(o===r){const t=Go(e);for(;r<=s-i;i+=r)this.process(t,i);continue}n.set(e.subarray(i,i+o),this.pos),this.pos+=o,i+=o,this.pos===r&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){$o(this),function(e,t){Po(e);const n=t.outputLen;if(e.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}(e,this),this.finished=!0;const{buffer:t,view:n,blockLen:r,isLE:s}=this;let{pos:i}=this;t[i++]=128,Ko(this.buffer.subarray(i)),this.padOffset>r-i&&(this.process(n,0),i=0);for(let e=i;e<r;e++)t[e]=0;!function(e,t,n,r){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,n,r);const s=BigInt(32),i=BigInt(4294967295),o=Number(n>>s&i),a=Number(n&i),c=r?4:0,l=r?0:4;e.setUint32(t+c,o,r),e.setUint32(t+l,a,r)}(n,r-8,BigInt(8*this.length),s),this.process(n,0);const o=Go(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const c=a/4,l=this.get();if(c>l.length)throw new Error("_sha2: outputLen bigger than state");for(let e=0;e<c;e++)o.setUint32(4*e,l[e],s)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:n,length:r,finished:s,destroyed:i,pos:o}=this;return e.destroyed=i,e.finished=s,e.length=r,e.pos=o,r%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}}const la=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ua=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),da=BigInt(2**32-1),ha=BigInt(32);function ga(e,t=!1){return t?{h:Number(e&da),l:Number(e>>ha&da)}:{h:0|Number(e>>ha&da),l:0|Number(e&da)}}const fa=(e,t,n)=>e>>>n,pa=(e,t,n)=>e<<32-n|t>>>n,ma=(e,t,n)=>e>>>n|t<<32-n,ya=(e,t,n)=>e<<32-n|t>>>n,ba=(e,t,n)=>e<<64-n|t>>>n-32,va=(e,t,n)=>e>>>n-32|t<<64-n;function wa(e,t,n,r){const s=(t>>>0)+(r>>>0);return{h:e+n+(s/2**32|0)|0,l:0|s}}const Ea=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),Aa=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,Sa=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),ka=(e,t,n,r,s)=>t+n+r+s+(e/2**32|0)|0,Ta=(e,t,n,r,s)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(s>>>0),Ia=(e,t,n,r,s,i)=>t+n+r+s+i+(e/2**32|0)|0,Ca=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Na=new Uint32Array(64);class _a extends ca{constructor(e=32){super(64,e,8,!1),this.A=0|la[0],this.B=0|la[1],this.C=0|la[2],this.D=0|la[3],this.E=0|la[4],this.F=0|la[5],this.G=0|la[6],this.H=0|la[7]}get(){const{A:e,B:t,C:n,D:r,E:s,F:i,G:o,H:a}=this;return[e,t,n,r,s,i,o,a]}set(e,t,n,r,s,i,o,a){this.A=0|e,this.B=0|t,this.C=0|n,this.D=0|r,this.E=0|s,this.F=0|i,this.G=0|o,this.H=0|a}process(e,t){for(let n=0;n<16;n++,t+=4)Na[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){const t=Na[e-15],n=Na[e-2],r=Ho(t,7)^Ho(t,18)^t>>>3,s=Ho(n,17)^Ho(n,19)^n>>>10;Na[e]=s+Na[e-7]+r+Na[e-16]|0}let{A:n,B:r,C:s,D:i,E:o,F:a,G:c,H:l}=this;for(let e=0;e<64;e++){const t=l+(Ho(o,6)^Ho(o,11)^Ho(o,25))+oa(o,a,c)+Ca[e]+Na[e]|0,u=(Ho(n,2)^Ho(n,13)^Ho(n,22))+aa(n,r,s)|0;l=c,c=a,a=o,o=i+t|0,i=s,s=r,r=n,n=t+u|0}n=n+this.A|0,r=r+this.B|0,s=s+this.C|0,i=i+this.D|0,o=o+this.E|0,a=a+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(n,r,s,i,o,a,c,l)}roundClean(){Ko(Na)}destroy(){this.set(0,0,0,0,0,0,0,0),Ko(this.buffer)}}const xa=(()=>function(e,t=!1){const n=e.length;let r=new Uint32Array(n),s=new Uint32Array(n);for(let i=0;i<n;i++){const{h:n,l:o}=ga(e[i],t);[r[i],s[i]]=[n,o]}return[r,s]}(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))))(),Ra=(()=>xa[0])(),Ba=(()=>xa[1])(),Da=new Uint32Array(80),Oa=new Uint32Array(80);class Ma extends ca{constructor(e=64){super(128,e,16,!1),this.Ah=0|ua[0],this.Al=0|ua[1],this.Bh=0|ua[2],this.Bl=0|ua[3],this.Ch=0|ua[4],this.Cl=0|ua[5],this.Dh=0|ua[6],this.Dl=0|ua[7],this.Eh=0|ua[8],this.El=0|ua[9],this.Fh=0|ua[10],this.Fl=0|ua[11],this.Gh=0|ua[12],this.Gl=0|ua[13],this.Hh=0|ua[14],this.Hl=0|ua[15]}get(){const{Ah:e,Al:t,Bh:n,Bl:r,Ch:s,Cl:i,Dh:o,Dl:a,Eh:c,El:l,Fh:u,Fl:d,Gh:h,Gl:g,Hh:f,Hl:p}=this;return[e,t,n,r,s,i,o,a,c,l,u,d,h,g,f,p]}set(e,t,n,r,s,i,o,a,c,l,u,d,h,g,f,p){this.Ah=0|e,this.Al=0|t,this.Bh=0|n,this.Bl=0|r,this.Ch=0|s,this.Cl=0|i,this.Dh=0|o,this.Dl=0|a,this.Eh=0|c,this.El=0|l,this.Fh=0|u,this.Fl=0|d,this.Gh=0|h,this.Gl=0|g,this.Hh=0|f,this.Hl=0|p}process(e,t){for(let n=0;n<16;n++,t+=4)Da[n]=e.getUint32(t),Oa[n]=e.getUint32(t+=4);for(let e=16;e<80;e++){const t=0|Da[e-15],n=0|Oa[e-15],r=ma(t,n,1)^ma(t,n,8)^fa(t,0,7),s=ya(t,n,1)^ya(t,n,8)^pa(t,n,7),i=0|Da[e-2],o=0|Oa[e-2],a=ma(i,o,19)^ba(i,o,61)^fa(i,0,6),c=ya(i,o,19)^va(i,o,61)^pa(i,o,6),l=Sa(s,c,Oa[e-7],Oa[e-16]),u=ka(l,r,a,Da[e-7],Da[e-16]);Da[e]=0|u,Oa[e]=0|l}let{Ah:n,Al:r,Bh:s,Bl:i,Ch:o,Cl:a,Dh:c,Dl:l,Eh:u,El:d,Fh:h,Fl:g,Gh:f,Gl:p,Hh:m,Hl:y}=this;for(let e=0;e<80;e++){const t=ma(u,d,14)^ma(u,d,18)^ba(u,d,41),b=ya(u,d,14)^ya(u,d,18)^va(u,d,41),v=u&h^~u&f,w=Ta(y,b,d&g^~d&p,Ba[e],Oa[e]),E=Ia(w,m,t,v,Ra[e],Da[e]),A=0|w,S=ma(n,r,28)^ba(n,r,34)^ba(n,r,39),k=ya(n,r,28)^va(n,r,34)^va(n,r,39),T=n&s^n&o^s&o,I=r&i^r&a^i&a;m=0|f,y=0|p,f=0|h,p=0|g,h=0|u,g=0|d,({h:u,l:d}=wa(0|c,0|l,0|E,0|A)),c=0|o,l=0|a,o=0|s,a=0|i,s=0|n,i=0|r;const C=Ea(A,k,I);n=Aa(C,E,S,T),r=0|C}({h:n,l:r}=wa(0|this.Ah,0|this.Al,0|n,0|r)),({h:s,l:i}=wa(0|this.Bh,0|this.Bl,0|s,0|i)),({h:o,l:a}=wa(0|this.Ch,0|this.Cl,0|o,0|a)),({h:c,l:l}=wa(0|this.Dh,0|this.Dl,0|c,0|l)),({h:u,l:d}=wa(0|this.Eh,0|this.El,0|u,0|d)),({h:h,l:g}=wa(0|this.Fh,0|this.Fl,0|h,0|g)),({h:f,l:p}=wa(0|this.Gh,0|this.Gl,0|f,0|p)),({h:m,l:y}=wa(0|this.Hh,0|this.Hl,0|m,0|y)),this.set(n,r,s,i,o,a,c,l,u,d,h,g,f,p,m,y)}roundClean(){Ko(Da,Oa)}destroy(){Ko(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const La=sa(()=>new _a),Ua=sa(()=>new Ma),Pa=BigInt(0),Fa=BigInt(1);function $a(e,t=""){if("boolean"!=typeof e){throw new Error((t&&`"${t}"`)+"expected boolean, got type="+typeof e)}return e}function Ka(e,t,n=""){const r=Lo(e),s=e?.length,i=void 0!==t;if(!r||i&&s!==t){throw new Error((n&&`"${n}" `)+"expected Uint8Array"+(i?` of length ${t}`:"")+", got "+(r?`length=${s}`:"type="+typeof e))}return e}function Ga(e){const t=e.toString(16);return 1&t.length?"0"+t:t}function Ha(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);return""===e?Pa:BigInt("0x"+e)}function Wa(e){return Ha(zo(e))}function qa(e){return Po(e),Ha(zo(Uint8Array.from(e).reverse()))}function za(e,t){return ea(e.toString(16).padStart(2*t,"0"))}function Va(e,t){return za(e,t).reverse()}function ja(e,t,n){let r;if("string"==typeof t)try{r=ea(t)}catch(t){throw new Error(e+" must be hex string or Uint8Array, cause: "+t)}else{if(!Lo(t))throw new Error(e+" must be hex string or Uint8Array");r=Uint8Array.from(t)}const s=r.length;if("number"==typeof n&&s!==n)throw new Error(e+" of length "+n+" expected, got "+s);return r}function Xa(e){return Uint8Array.from(e)}const Ya=e=>"bigint"==typeof e&&Pa<=e;function Ja(e,t,n,r){if(!function(e,t,n){return Ya(e)&&Ya(t)&&Ya(n)&&t<=e&&e<n}(t,n,r))throw new Error("expected valid "+e+": "+n+" <= n < "+r+", got "+t)}function Qa(e){let t;for(t=0;e>Pa;e>>=Fa,t+=1);return t}const Za=e=>(Fa<<BigInt(e))-Fa;function ec(e,t,n={}){if(!e||"object"!=typeof e)throw new Error("expected valid options object");function r(t,n,r){const s=e[t];if(r&&void 0===s)return;const i=typeof s;if(i!==n||null===s)throw new Error(`param "${t}" is invalid: expected ${n}, got ${i}`)}Object.entries(t).forEach(([e,t])=>r(e,t,!1)),Object.entries(n).forEach(([e,t])=>r(e,t,!0))}function tc(e){const t=new WeakMap;return(n,...r)=>{const s=t.get(n);if(void 0!==s)return s;const i=e(n,...r);return t.set(n,i),i}}const nc=BigInt(0),rc=BigInt(1),sc=BigInt(2),ic=BigInt(3),oc=BigInt(4),ac=BigInt(5),cc=BigInt(7),lc=BigInt(8),uc=BigInt(9),dc=BigInt(16);function hc(e,t){const n=e%t;return n>=nc?n:t+n}function gc(e,t,n){let r=e;for(;t-- >nc;)r*=r,r%=n;return r}function fc(e,t){if(e===nc)throw new Error("invert: expected non-zero number");if(t<=nc)throw new Error("invert: expected positive modulus, got "+t);let n=hc(e,t),r=t,s=nc,i=rc;for(;n!==nc;){const e=r%n,t=s-i*(r/n);r=n,n=e,s=i,i=t}if(r!==rc)throw new Error("invert: does not exist");return hc(s,t)}function pc(e,t,n){if(!e.eql(e.sqr(t),n))throw new Error("Cannot find square root")}function mc(e,t){const n=(e.ORDER+rc)/oc,r=e.pow(t,n);return pc(e,r,t),r}function yc(e,t){const n=(e.ORDER-ac)/lc,r=e.mul(t,sc),s=e.pow(r,n),i=e.mul(t,s),o=e.mul(e.mul(i,sc),s),a=e.mul(i,e.sub(o,e.ONE));return pc(e,a,t),a}function bc(e){if(e<ic)throw new Error("sqrt is not defined for small field");let t=e-rc,n=0;for(;t%sc===nc;)t/=sc,n++;let r=sc;const s=kc(e);for(;1===Ac(s,r);)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(1===n)return mc;let i=s.pow(r,t);const o=(t+rc)/sc;return function(e,r){if(e.is0(r))return r;if(1!==Ac(e,r))throw new Error("Cannot find square root");let s=n,a=e.mul(e.ONE,i),c=e.pow(r,t),l=e.pow(r,o);for(;!e.eql(c,e.ONE);){if(e.is0(c))return e.ZERO;let t=1,n=e.sqr(c);for(;!e.eql(n,e.ONE);)if(t++,n=e.sqr(n),t===s)throw new Error("Cannot find square root");const r=rc<<BigInt(s-t-1),i=e.pow(a,r);s=t,a=e.sqr(i),c=e.mul(c,a),l=e.mul(l,i)}return l}}function vc(e){return e%oc===ic?mc:e%lc===ac?yc:e%dc===uc?function(e){const t=kc(e),n=bc(e),r=n(t,t.neg(t.ONE)),s=n(t,r),i=n(t,t.neg(r)),o=(e+cc)/dc;return(e,t)=>{let n=e.pow(t,o),a=e.mul(n,r);const c=e.mul(n,s),l=e.mul(n,i),u=e.eql(e.sqr(a),t),d=e.eql(e.sqr(c),t);n=e.cmov(n,a,u),a=e.cmov(l,c,d);const h=e.eql(e.sqr(a),t),g=e.cmov(n,a,h);return pc(e,g,t),g}}(e):bc(e)}const wc=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Ec(e,t,n=!1){const r=new Array(t.length).fill(n?e.ZERO:void 0),s=t.reduce((t,n,s)=>e.is0(n)?t:(r[s]=t,e.mul(t,n)),e.ONE),i=e.inv(s);return t.reduceRight((t,n,s)=>e.is0(n)?t:(r[s]=e.mul(t,r[s]),e.mul(t,n)),i),r}function Ac(e,t){const n=(e.ORDER-rc)/sc,r=e.pow(t,n),s=e.eql(r,e.ONE),i=e.eql(r,e.ZERO),o=e.eql(r,e.neg(e.ONE));if(!s&&!i&&!o)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function Sc(e,t){void 0!==t&&Uo(t);const n=void 0!==t?t:e.toString(2).length;return{nBitLength:n,nByteLength:Math.ceil(n/8)}}function kc(e,t,n=!1,r={}){if(e<=nc)throw new Error("invalid field: expected ORDER > 0, got "+e);let s,i,o,a=!1;if("object"==typeof t&&null!=t){if(r.sqrt||n)throw new Error("cannot specify opts in two arguments");const e=t;e.BITS&&(s=e.BITS),e.sqrt&&(i=e.sqrt),"boolean"==typeof e.isLE&&(n=e.isLE),"boolean"==typeof e.modFromBytes&&(a=e.modFromBytes),o=e.allowedLengths}else"number"==typeof t&&(s=t),r.sqrt&&(i=r.sqrt);const{nBitLength:c,nByteLength:l}=Sc(e,s);if(l>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let u;const d=Object.freeze({ORDER:e,isLE:n,BITS:c,BYTES:l,MASK:Za(c),ZERO:nc,ONE:rc,allowedLengths:o,create:t=>hc(t,e),isValid:t=>{if("bigint"!=typeof t)throw new Error("invalid field element: expected bigint, got "+typeof t);return nc<=t&&t<e},is0:e=>e===nc,isValidNot0:e=>!d.is0(e)&&d.isValid(e),isOdd:e=>(e&rc)===rc,neg:t=>hc(-t,e),eql:(e,t)=>e===t,sqr:t=>hc(t*t,e),add:(t,n)=>hc(t+n,e),sub:(t,n)=>hc(t-n,e),mul:(t,n)=>hc(t*n,e),pow:(e,t)=>function(e,t,n){if(n<nc)throw new Error("invalid exponent, negatives unsupported");if(n===nc)return e.ONE;if(n===rc)return t;let r=e.ONE,s=t;for(;n>nc;)n&rc&&(r=e.mul(r,s)),s=e.sqr(s),n>>=rc;return r}(d,e,t),div:(t,n)=>hc(t*fc(n,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>fc(t,e),sqrt:i||(t=>(u||(u=vc(e)),u(d,t))),toBytes:e=>n?Va(e,l):za(e,l),fromBytes:(t,r=!0)=>{if(o){if(!o.includes(t.length)||t.length>l)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+t.length);const e=new Uint8Array(l);e.set(t,n?0:e.length-t.length),t=e}if(t.length!==l)throw new Error("Field.fromBytes: expected "+l+" bytes, got "+t.length);let s=n?qa(t):Wa(t);if(a&&(s=hc(s,e)),!r&&!d.isValid(s))throw new Error("invalid field element: outside of range 0..ORDER");return s},invertBatch:e=>Ec(d,e),cmov:(e,t,n)=>n?t:e});return Object.freeze(d)}function Tc(e){if("bigint"!=typeof e)throw new Error("field order must be bigint");const t=e.toString(2).length;return Math.ceil(t/8)}function Ic(e){const t=Tc(e);return t+Math.ceil(t/2)}const Cc=BigInt(0),Nc=BigInt(1);function _c(e,t){const n=t.negate();return e?n:t}function xc(e,t){const n=Ec(e.Fp,t.map(e=>e.Z));return t.map((t,r)=>e.fromAffine(t.toAffine(n[r])))}function Rc(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function Bc(e,t){Rc(e,t);const n=2**e;return{windows:Math.ceil(t/e)+1,windowSize:2**(e-1),mask:Za(e),maxNumber:n,shiftBy:BigInt(e)}}function Dc(e,t,n){const{windowSize:r,mask:s,maxNumber:i,shiftBy:o}=n;let a=Number(e&s),c=e>>o;a>r&&(a-=i,c+=Nc);const l=t*r;return{nextN:c,offset:l+Math.abs(a)-1,isZero:0===a,isNeg:a<0,isNegF:t%2!=0,offsetF:l}}const Oc=new WeakMap,Mc=new WeakMap;function Lc(e){return Mc.get(e)||1}function Uc(e){if(e!==Cc)throw new Error("invalid wNAF")}class Pc{constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,n=this.ZERO){let r=e;for(;t>Cc;)t&Nc&&(n=n.add(r)),r=r.double(),t>>=Nc;return n}precomputeWindow(e,t){const{windows:n,windowSize:r}=Bc(t,this.bits),s=[];let i=e,o=i;for(let e=0;e<n;e++){o=i,s.push(o);for(let e=1;e<r;e++)o=o.add(i),s.push(o);i=o.double()}return s}wNAF(e,t,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let r=this.ZERO,s=this.BASE;const i=Bc(e,this.bits);for(let e=0;e<i.windows;e++){const{nextN:o,offset:a,isZero:c,isNeg:l,isNegF:u,offsetF:d}=Dc(n,e,i);n=o,c?s=s.add(_c(u,t[d])):r=r.add(_c(l,t[a]))}return Uc(n),{p:r,f:s}}wNAFUnsafe(e,t,n,r=this.ZERO){const s=Bc(e,this.bits);for(let e=0;e<s.windows&&n!==Cc;e++){const{nextN:i,offset:o,isZero:a,isNeg:c}=Dc(n,e,s);if(n=i,!a){const e=t[o];r=r.add(c?e.negate():e)}}return Uc(n),r}getPrecomputes(e,t,n){let r=Oc.get(t);return r||(r=this.precomputeWindow(t,e),1!==e&&("function"==typeof n&&(r=n(r)),Oc.set(t,r))),r}cached(e,t,n){const r=Lc(e);return this.wNAF(r,this.getPrecomputes(r,e,n),t)}unsafe(e,t,n,r){const s=Lc(e);return 1===s?this._unsafeLadder(e,t,r):this.wNAFUnsafe(s,this.getPrecomputes(s,e,n),t,r)}createCache(e,t){Rc(t,this.bits),Mc.set(e,t),Oc.delete(e)}hasCache(e){return 1!==Lc(e)}}function Fc(e,t,n,r){!function(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach((e,n)=>{if(!(e instanceof t))throw new Error("invalid point at index "+n)})}(n,e),function(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((e,n)=>{if(!t.isValid(e))throw new Error("invalid scalar at index "+n)})}(r,t);const s=n.length,i=r.length;if(s!==i)throw new Error("arrays of points and scalars must have equal length");const o=e.ZERO,a=Qa(BigInt(s));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const l=Za(c),u=new Array(Number(l)+1).fill(o);let d=o;for(let e=Math.floor((t.BITS-1)/c)*c;e>=0;e-=c){u.fill(o);for(let t=0;t<i;t++){const s=r[t],i=Number(s>>BigInt(e)&l);u[i]=u[i].add(n[t])}let t=o;for(let e=u.length-1,n=o;e>0;e--)n=n.add(u[e]),t=t.add(n);if(d=d.add(t),0!==e)for(let e=0;e<c;e++)d=d.double()}return d}function $c(e,t,n){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return function(e){ec(e,wc.reduce((e,t)=>(e[t]="function",e),{ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"}))}(t),t}return kc(e,{isLE:n})}function Kc(e,t,n={},r){if(void 0===r&&(r="edwards"===e),!t||"object"!=typeof t)throw new Error(`expected valid ${e} CURVE object`);for(const e of["p","n","h"]){const n=t[e];if(!("bigint"==typeof n&&n>Cc))throw new Error(`CURVE.${e} must be positive bigint`)}const s=$c(t.p,n.Fp,r),i=$c(t.n,n.Fn,r),o=["Gx","Gy","a","weierstrass"===e?"b":"d"];for(const e of o)if(!s.isValid(t[e]))throw new Error(`CURVE.${e} must be valid field element of CURVE.Fp`);return{CURVE:t=Object.freeze(Object.assign({},t)),Fp:s,Fn:i}}const Gc=BigInt(0),Hc=BigInt(1),Wc=BigInt(2),qc=BigInt(8);function zc(e,t,n={}){if("function"!=typeof t)throw new Error('"hash" function param is required');ec(n,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});const{prehash:r}=n,{BASE:s,Fp:i,Fn:o}=e,a=n.randomBytes||ia,c=n.adjustScalarBytes||(e=>e),l=n.domain||((e,t,n)=>{if($a(n,"phflag"),t.length||n)throw new Error("Contexts/pre-hash are not supported");return e});function u(e){return o.create(qa(e))}function d(e){const{head:n,prefix:r,scalar:i}=function(e){const n=m.secretKey;e=ja("private key",e,n);const r=ja("hashed private key",t(e),2*n),s=c(r.slice(0,n));return{head:s,prefix:r.slice(n,2*n),scalar:u(s)}}(e),o=s.multiply(i),a=o.toBytes();return{head:n,prefix:r,scalar:i,point:o,pointBytes:a}}function h(e){return d(e).pointBytes}function g(e=Uint8Array.of(),...n){const s=na(...n);return u(t(l(s,ja("context",e),!!r)))}const f={zip215:!0};const p=i.BYTES,m={secretKey:p,publicKey:p,signature:2*p,seed:p};function y(e=a(m.seed)){return Ka(e,m.seed,"seed")}const b={getExtendedPublicKey:d,randomSecretKey:y,isValidSecretKey:function(e){return Lo(e)&&e.length===o.BYTES},isValidPublicKey:function(t,n){try{return!!e.fromBytes(t,n)}catch(e){return!1}},toMontgomery(t){const{y:n}=e.fromBytes(t),r=m.publicKey,s=32===r;if(!s&&57!==r)throw new Error("only defined for 25519 and 448");const o=s?i.div(Hc+n,Hc-n):i.div(n-Hc,n+Hc);return i.toBytes(o)},toMontgomerySecret(e){const n=m.secretKey;Ka(e,n);const r=t(e.subarray(0,n));return c(r).subarray(0,n)},randomPrivateKey:y,precompute:(t=8,n=e.BASE)=>n.precompute(t,!1)};return Object.freeze({keygen:function(e){const t=b.randomSecretKey(e);return{secretKey:t,publicKey:h(t)}},getPublicKey:h,sign:function(e,t,n={}){e=ja("message",e),r&&(e=r(e));const{prefix:i,scalar:a,pointBytes:c}=d(t),l=g(n.context,i,e),u=s.multiply(l).toBytes(),h=g(n.context,u,c,e),f=o.create(l+h*a);if(!o.isValid(f))throw new Error("sign failed: invalid s");return Ka(na(u,o.toBytes(f)),m.signature,"result")},verify:function(t,n,i,o=f){const{context:a,zip215:c}=o,l=m.signature;t=ja("signature",t,l),n=ja("message",n),i=ja("publicKey",i,m.publicKey),void 0!==c&&$a(c,"zip215"),r&&(n=r(n));const u=l/2,d=t.subarray(0,u),h=qa(t.subarray(u,l));let p,y,b;try{p=e.fromBytes(i,c),y=e.fromBytes(d,c),b=s.multiplyUnsafe(h)}catch(e){return!1}if(!c&&p.isSmallOrder())return!1;const v=g(a,y.toBytes(),p.toBytes(),n);return y.add(p.multiplyUnsafe(v)).subtract(b).clearCofactor().is0()},utils:b,Point:e,lengths:m})}function Vc(e){const{CURVE:t,curveOpts:n,hash:r,eddsaOpts:s}=function(e){const t={a:e.a,d:e.d,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},n={Fp:e.Fp,Fn:kc(t.n,e.nBitLength,!0),uvRatio:e.uvRatio},r={randomBytes:e.randomBytes,adjustScalarBytes:e.adjustScalarBytes,domain:e.domain,prehash:e.prehash,mapToCurve:e.mapToCurve};return{CURVE:t,curveOpts:n,hash:e.hash,eddsaOpts:r}}(e),i=function(e,t={}){const n=Kc("edwards",e,t,t.FpFnLE),{Fp:r,Fn:s}=n;let i=n.CURVE;const{h:o}=i;ec(t,{},{uvRatio:"function"});const a=Wc<<BigInt(8*s.BYTES)-Hc,c=e=>r.create(e),l=t.uvRatio||((e,t)=>{try{return{isValid:!0,value:r.sqrt(r.div(e,t))}}catch(e){return{isValid:!1,value:Gc}}});if(!function(e,t,n,r){const s=e.sqr(n),i=e.sqr(r),o=e.add(e.mul(t.a,s),i),a=e.add(e.ONE,e.mul(t.d,e.mul(s,i)));return e.eql(o,a)}(r,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");function u(e,t,n=!1){return Ja("coordinate "+e,t,n?Hc:Gc,a),t}function d(e){if(!(e instanceof f))throw new Error("ExtendedPoint expected")}const h=tc((e,t)=>{const{X:n,Y:s,Z:i}=e,o=e.is0();null==t&&(t=o?qc:r.inv(i));const a=c(n*t),l=c(s*t),u=r.mul(i,t);if(o)return{x:Gc,y:Hc};if(u!==Hc)throw new Error("invZ was invalid");return{x:a,y:l}}),g=tc(e=>{const{a:t,d:n}=i;if(e.is0())throw new Error("bad point: ZERO");const{X:r,Y:s,Z:o,T:a}=e,l=c(r*r),u=c(s*s),d=c(o*o),h=c(d*d),g=c(l*t);if(c(d*c(g+u))!==c(h+c(n*c(l*u))))throw new Error("bad point: equation left != right (1)");if(c(r*s)!==c(o*a))throw new Error("bad point: equation left != right (2)");return!0});class f{constructor(e,t,n,r){this.X=u("x",e),this.Y=u("y",t),this.Z=u("z",n,!0),this.T=u("t",r),Object.freeze(this)}static CURVE(){return i}static fromAffine(e){if(e instanceof f)throw new Error("extended point not allowed");const{x:t,y:n}=e||{};return u("x",t),u("y",n),new f(t,n,Hc,c(t*n))}static fromBytes(e,t=!1){const n=r.BYTES,{a:s,d:o}=i;e=Xa(Ka(e,n,"point")),$a(t,"zip215");const u=Xa(e),d=e[n-1];u[n-1]=-129&d;const h=qa(u),g=t?a:r.ORDER;Ja("point.y",h,Gc,g);const p=c(h*h),m=c(p-Hc),y=c(o*p-s);let{isValid:b,value:v}=l(m,y);if(!b)throw new Error("bad point: invalid y coordinate");const w=(v&Hc)===Hc,E=!!(128&d);if(!t&&v===Gc&&E)throw new Error("bad point: x=0 and x_0=1");return E!==w&&(v=c(-v)),f.fromAffine({x:v,y:h})}static fromHex(e,t=!1){return f.fromBytes(ja("point",e),t)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(e=8,t=!0){return p.createCache(this,e),t||this.multiply(Wc),this}assertValidity(){g(this)}equals(e){d(e);const{X:t,Y:n,Z:r}=this,{X:s,Y:i,Z:o}=e,a=c(t*o),l=c(s*r),u=c(n*o),h=c(i*r);return a===l&&u===h}is0(){return this.equals(f.ZERO)}negate(){return new f(c(-this.X),this.Y,this.Z,c(-this.T))}double(){const{a:e}=i,{X:t,Y:n,Z:r}=this,s=c(t*t),o=c(n*n),a=c(Wc*c(r*r)),l=c(e*s),u=t+n,d=c(c(u*u)-s-o),h=l+o,g=h-a,p=l-o,m=c(d*g),y=c(h*p),b=c(d*p),v=c(g*h);return new f(m,y,v,b)}add(e){d(e);const{a:t,d:n}=i,{X:r,Y:s,Z:o,T:a}=this,{X:l,Y:u,Z:h,T:g}=e,p=c(r*l),m=c(s*u),y=c(a*n*g),b=c(o*h),v=c((r+s)*(l+u)-p-m),w=b-y,E=b+y,A=c(m-t*p),S=c(v*w),k=c(E*A),T=c(v*A),I=c(w*E);return new f(S,k,I,T)}subtract(e){return this.add(e.negate())}multiply(e){if(!s.isValidNot0(e))throw new Error("invalid scalar: expected 1 <= sc < curve.n");const{p:t,f:n}=p.cached(this,e,e=>xc(f,e));return xc(f,[t,n])[0]}multiplyUnsafe(e,t=f.ZERO){if(!s.isValid(e))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return e===Gc?f.ZERO:this.is0()||e===Hc?this:p.unsafe(this,e,e=>xc(f,e),t)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}isTorsionFree(){return p.unsafe(this,i.n).is0()}toAffine(e){return h(this,e)}clearCofactor(){return o===Hc?this:this.multiplyUnsafe(o)}toBytes(){const{x:e,y:t}=this.toAffine(),n=r.toBytes(t);return n[n.length-1]|=e&Hc?128:0,n}toHex(){return zo(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get ex(){return this.X}get ey(){return this.Y}get ez(){return this.Z}get et(){return this.T}static normalizeZ(e){return xc(f,e)}static msm(e,t){return Fc(f,s,e,t)}_setWindowSize(e){this.precompute(e)}toRawBytes(){return this.toBytes()}}f.BASE=new f(i.Gx,i.Gy,Hc,c(i.Gx*i.Gy)),f.ZERO=new f(Gc,Hc,Hc,Gc),f.Fp=r,f.Fn=s;const p=new Pc(f,s.BITS);return f.BASE.precompute(8),f}(t,n);return function(e,t){const n=t.Point;return Object.assign({},t,{ExtendedPoint:n,CURVE:e,nBitLength:n.Fn.BITS,nByteLength:n.Fn.BYTES})}(e,zc(i,r,s))}const jc=BigInt(1),Xc=BigInt(2);BigInt(3);const Yc=BigInt(5),Jc=BigInt(8),Qc=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Zc=(()=>({p:Qc,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Jc,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")}))();function el(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}const tl=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function nl(e,t){const n=Qc,r=hc(t*t*t,n),s=function(e){const t=BigInt(10),n=BigInt(20),r=BigInt(40),s=BigInt(80),i=Qc,o=e*e%i*e%i,a=gc(o,Xc,i)*o%i,c=gc(a,jc,i)*e%i,l=gc(c,Yc,i)*c%i,u=gc(l,t,i)*l%i,d=gc(u,n,i)*u%i,h=gc(d,r,i)*d%i,g=gc(h,s,i)*h%i,f=gc(g,s,i)*h%i,p=gc(f,t,i)*l%i;return{pow_p_5_8:gc(p,Xc,i)*e%i,b2:o}}(e*hc(r*r*t,n)).pow_p_5_8;let i=hc(e*r*s,n);const o=hc(t*i*i,n),a=i,c=hc(i*tl,n),l=o===e,u=o===hc(-e,n),d=o===hc(-e*tl,n);return l&&(i=a),(u||d)&&(i=c),(hc(i,n)&rc)===rc&&(i=hc(-i,n)),{isValid:l||u,value:i}}const rl=(()=>kc(Zc.p,{isLE:!0}))(),sl=(()=>({...Zc,Fp:rl,hash:Ua,adjustScalarBytes:el,uvRatio:nl}))(),il=(()=>Vc(sl))();var ol,al={exports:{}},cl=ko(Object.freeze({__proto__:null,default:{}})),ll=al.exports;function ul(){return ol||(ol=1,function(e,t){function n(e,t){if(!e)throw new Error(t||"Assertion failed")}function r(e,t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}function s(e,t,n){if(s.isBN(e))return e;this.negative=0,this.words=null,this.length=0,this.red=null,null!==e&&("le"!==t&&"be"!==t||(n=t,t=10),this._init(e||0,t||10,n||"be"))}var i;"object"==typeof e?e.exports=s:t.BN=s,s.BN=s,s.wordSize=26;try{i="undefined"!=typeof window&&void 0!==window.Buffer?window.Buffer:cl.Buffer}catch(e){}function o(e,t){var r=e.charCodeAt(t);return r>=48&&r<=57?r-48:r>=65&&r<=70?r-55:r>=97&&r<=102?r-87:void n(!1,"Invalid character in "+e)}function a(e,t,n){var r=o(e,n);return n-1>=t&&(r|=o(e,n-1)<<4),r}function c(e,t,r,s){for(var i=0,o=0,a=Math.min(e.length,r),c=t;c<a;c++){var l=e.charCodeAt(c)-48;i*=s,o=l>=49?l-49+10:l>=17?l-17+10:l,n(l>=0&&o<s,"Invalid character"),i+=o}return i}function l(e,t){e.words=t.words,e.length=t.length,e.negative=t.negative,e.red=t.red}if(s.isBN=function(e){return e instanceof s||null!==e&&"object"==typeof e&&e.constructor.wordSize===s.wordSize&&Array.isArray(e.words)},s.max=function(e,t){return e.cmp(t)>0?e:t},s.min=function(e,t){return e.cmp(t)<0?e:t},s.prototype._init=function(e,t,r){if("number"==typeof e)return this._initNumber(e,t,r);if("object"==typeof e)return this._initArray(e,t,r);"hex"===t&&(t=16),n(t===(0|t)&&t>=2&&t<=36);var s=0;"-"===(e=e.toString().replace(/\s+/g,""))[0]&&(s++,this.negative=1),s<e.length&&(16===t?this._parseHex(e,s,r):(this._parseBase(e,t,s),"le"===r&&this._initArray(this.toArray(),t,r)))},s.prototype._initNumber=function(e,t,r){e<0&&(this.negative=1,e=-e),e<67108864?(this.words=[67108863&e],this.length=1):e<4503599627370496?(this.words=[67108863&e,e/67108864&67108863],this.length=2):(n(e<9007199254740992),this.words=[67108863&e,e/67108864&67108863,1],this.length=3),"le"===r&&this._initArray(this.toArray(),t,r)},s.prototype._initArray=function(e,t,r){if(n("number"==typeof e.length),e.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(e.length/3),this.words=new Array(this.length);for(var s=0;s<this.length;s++)this.words[s]=0;var i,o,a=0;if("be"===r)for(s=e.length-1,i=0;s>=0;s-=3)o=e[s]|e[s-1]<<8|e[s-2]<<16,this.words[i]|=o<<a&67108863,this.words[i+1]=o>>>26-a&67108863,(a+=24)>=26&&(a-=26,i++);else if("le"===r)for(s=0,i=0;s<e.length;s+=3)o=e[s]|e[s+1]<<8|e[s+2]<<16,this.words[i]|=o<<a&67108863,this.words[i+1]=o>>>26-a&67108863,(a+=24)>=26&&(a-=26,i++);return this._strip()},s.prototype._parseHex=function(e,t,n){this.length=Math.ceil((e.length-t)/6),this.words=new Array(this.length);for(var r=0;r<this.length;r++)this.words[r]=0;var s,i=0,o=0;if("be"===n)for(r=e.length-1;r>=t;r-=2)s=a(e,t,r)<<i,this.words[o]|=67108863&s,i>=18?(i-=18,o+=1,this.words[o]|=s>>>26):i+=8;else for(r=(e.length-t)%2==0?t+1:t;r<e.length;r+=2)s=a(e,t,r)<<i,this.words[o]|=67108863&s,i>=18?(i-=18,o+=1,this.words[o]|=s>>>26):i+=8;this._strip()},s.prototype._parseBase=function(e,t,n){this.words=[0],this.length=1;for(var r=0,s=1;s<=67108863;s*=t)r++;r--,s=s/t|0;for(var i=e.length-n,o=i%r,a=Math.min(i,i-o)+n,l=0,u=n;u<a;u+=r)l=c(e,u,u+r,t),this.imuln(s),this.words[0]+l<67108864?this.words[0]+=l:this._iaddn(l);if(0!==o){var d=1;for(l=c(e,u,e.length,t),u=0;u<o;u++)d*=t;this.imuln(d),this.words[0]+l<67108864?this.words[0]+=l:this._iaddn(l)}this._strip()},s.prototype.copy=function(e){e.words=new Array(this.length);for(var t=0;t<this.length;t++)e.words[t]=this.words[t];e.length=this.length,e.negative=this.negative,e.red=this.red},s.prototype._move=function(e){l(e,this)},s.prototype.clone=function(){var e=new s(null);return this.copy(e),e},s.prototype._expand=function(e){for(;this.length<e;)this.words[this.length++]=0;return this},s.prototype._strip=function(){for(;this.length>1&&0===this.words[this.length-1];)this.length--;return this._normSign()},s.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},"undefined"!=typeof Symbol&&"function"==typeof Symbol.for)try{s.prototype[Symbol.for("nodejs.util.inspect.custom")]=u}catch(e){s.prototype.inspect=u}else s.prototype.inspect=u;function u(){return(this.red?"<BN-R: ":"<BN: ")+this.toString(16)+">"}var d=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],h=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],g=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];function f(e,t,n){n.negative=t.negative^e.negative;var r=e.length+t.length|0;n.length=r,r=r-1|0;var s=0|e.words[0],i=0|t.words[0],o=s*i,a=67108863&o,c=o/67108864|0;n.words[0]=a;for(var l=1;l<r;l++){for(var u=c>>>26,d=67108863&c,h=Math.min(l,t.length-1),g=Math.max(0,l-e.length+1);g<=h;g++){var f=l-g|0;u+=(o=(s=0|e.words[f])*(i=0|t.words[g])+d)/67108864|0,d=67108863&o}n.words[l]=0|d,c=0|u}return 0!==c?n.words[l]=0|c:n.length--,n._strip()}s.prototype.toString=function(e,t){var r;if(t=0|t||1,16===(e=e||10)||"hex"===e){r="";for(var s=0,i=0,o=0;o<this.length;o++){var a=this.words[o],c=(16777215&(a<<s|i)).toString(16);i=a>>>24-s&16777215,(s+=2)>=26&&(s-=26,o--),r=0!==i||o!==this.length-1?d[6-c.length]+c+r:c+r}for(0!==i&&(r=i.toString(16)+r);r.length%t!==0;)r="0"+r;return 0!==this.negative&&(r="-"+r),r}if(e===(0|e)&&e>=2&&e<=36){var l=h[e],u=g[e];r="";var f=this.clone();for(f.negative=0;!f.isZero();){var p=f.modrn(u).toString(e);r=(f=f.idivn(u)).isZero()?p+r:d[l-p.length]+p+r}for(this.isZero()&&(r="0"+r);r.length%t!==0;)r="0"+r;return 0!==this.negative&&(r="-"+r),r}n(!1,"Base should be between 2 and 36")},s.prototype.toNumber=function(){var e=this.words[0];return 2===this.length?e+=67108864*this.words[1]:3===this.length&&1===this.words[2]?e+=4503599627370496+67108864*this.words[1]:this.length>2&&n(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-e:e},s.prototype.toJSON=function(){return this.toString(16,2)},i&&(s.prototype.toBuffer=function(e,t){return this.toArrayLike(i,e,t)}),s.prototype.toArray=function(e,t){return this.toArrayLike(Array,e,t)},s.prototype.toArrayLike=function(e,t,r){this._strip();var s=this.byteLength(),i=r||Math.max(1,s);n(s<=i,"byte array longer than desired length"),n(i>0,"Requested array length <= 0");var o=function(e,t){return e.allocUnsafe?e.allocUnsafe(t):new e(t)}(e,i);return this["_toArrayLike"+("le"===t?"LE":"BE")](o,s),o},s.prototype._toArrayLikeLE=function(e,t){for(var n=0,r=0,s=0,i=0;s<this.length;s++){var o=this.words[s]<<i|r;e[n++]=255&o,n<e.length&&(e[n++]=o>>8&255),n<e.length&&(e[n++]=o>>16&255),6===i?(n<e.length&&(e[n++]=o>>24&255),r=0,i=0):(r=o>>>24,i+=2)}if(n<e.length)for(e[n++]=r;n<e.length;)e[n++]=0},s.prototype._toArrayLikeBE=function(e,t){for(var n=e.length-1,r=0,s=0,i=0;s<this.length;s++){var o=this.words[s]<<i|r;e[n--]=255&o,n>=0&&(e[n--]=o>>8&255),n>=0&&(e[n--]=o>>16&255),6===i?(n>=0&&(e[n--]=o>>24&255),r=0,i=0):(r=o>>>24,i+=2)}if(n>=0)for(e[n--]=r;n>=0;)e[n--]=0},Math.clz32?s.prototype._countBits=function(e){return 32-Math.clz32(e)}:s.prototype._countBits=function(e){var t=e,n=0;return t>=4096&&(n+=13,t>>>=13),t>=64&&(n+=7,t>>>=7),t>=8&&(n+=4,t>>>=4),t>=2&&(n+=2,t>>>=2),n+t},s.prototype._zeroBits=function(e){if(0===e)return 26;var t=e,n=0;return 8191&t||(n+=13,t>>>=13),127&t||(n+=7,t>>>=7),15&t||(n+=4,t>>>=4),3&t||(n+=2,t>>>=2),1&t||n++,n},s.prototype.bitLength=function(){var e=this.words[this.length-1],t=this._countBits(e);return 26*(this.length-1)+t},s.prototype.zeroBits=function(){if(this.isZero())return 0;for(var e=0,t=0;t<this.length;t++){var n=this._zeroBits(this.words[t]);if(e+=n,26!==n)break}return e},s.prototype.byteLength=function(){return Math.ceil(this.bitLength()/8)},s.prototype.toTwos=function(e){return 0!==this.negative?this.abs().inotn(e).iaddn(1):this.clone()},s.prototype.fromTwos=function(e){return this.testn(e-1)?this.notn(e).iaddn(1).ineg():this.clone()},s.prototype.isNeg=function(){return 0!==this.negative},s.prototype.neg=function(){return this.clone().ineg()},s.prototype.ineg=function(){return this.isZero()||(this.negative^=1),this},s.prototype.iuor=function(e){for(;this.length<e.length;)this.words[this.length++]=0;for(var t=0;t<e.length;t++)this.words[t]=this.words[t]|e.words[t];return this._strip()},s.prototype.ior=function(e){return n(0===(this.negative|e.negative)),this.iuor(e)},s.prototype.or=function(e){return this.length>e.length?this.clone().ior(e):e.clone().ior(this)},s.prototype.uor=function(e){return this.length>e.length?this.clone().iuor(e):e.clone().iuor(this)},s.prototype.iuand=function(e){var t;t=this.length>e.length?e:this;for(var n=0;n<t.length;n++)this.words[n]=this.words[n]&e.words[n];return this.length=t.length,this._strip()},s.prototype.iand=function(e){return n(0===(this.negative|e.negative)),this.iuand(e)},s.prototype.and=function(e){return this.length>e.length?this.clone().iand(e):e.clone().iand(this)},s.prototype.uand=function(e){return this.length>e.length?this.clone().iuand(e):e.clone().iuand(this)},s.prototype.iuxor=function(e){var t,n;this.length>e.length?(t=this,n=e):(t=e,n=this);for(var r=0;r<n.length;r++)this.words[r]=t.words[r]^n.words[r];if(this!==t)for(;r<t.length;r++)this.words[r]=t.words[r];return this.length=t.length,this._strip()},s.prototype.ixor=function(e){return n(0===(this.negative|e.negative)),this.iuxor(e)},s.prototype.xor=function(e){return this.length>e.length?this.clone().ixor(e):e.clone().ixor(this)},s.prototype.uxor=function(e){return this.length>e.length?this.clone().iuxor(e):e.clone().iuxor(this)},s.prototype.inotn=function(e){n("number"==typeof e&&e>=0);var t=0|Math.ceil(e/26),r=e%26;this._expand(t),r>0&&t--;for(var s=0;s<t;s++)this.words[s]=67108863&~this.words[s];for(r>0&&(this.words[s]=~this.words[s]&67108863>>26-r,s++);s<this.length;s++)this.words[s]=0;return this._strip()},s.prototype.notn=function(e){return this.clone().inotn(e)},s.prototype.setn=function(e,t){n("number"==typeof e&&e>=0);var r=e/26|0,s=e%26;return this._expand(r+1),this.words[r]=t?this.words[r]|1<<s:this.words[r]&~(1<<s),this._strip()},s.prototype.iadd=function(e){var t,n,r;if(0!==this.negative&&0===e.negative)return this.negative=0,t=this.isub(e),this.negative^=1,this._normSign();if(0===this.negative&&0!==e.negative)return e.negative=0,t=this.isub(e),e.negative=1,t._normSign();this.length>e.length?(n=this,r=e):(n=e,r=this);for(var s=0,i=0;i<r.length;i++)t=(0|n.words[i])+(0|r.words[i])+s,this.words[i]=67108863&t,s=t>>>26;for(;0!==s&&i<n.length;i++)t=(0|n.words[i])+s,this.words[i]=67108863&t,s=t>>>26;if(this.length=n.length,0!==s)this.words[this.length]=s,this.length++;else if(n!==this)for(;i<n.length;i++)this.words[i]=n.words[i];return this},s.prototype.add=function(e){var t;return 0!==e.negative&&0===this.negative?(e.negative=0,t=this.sub(e),e.negative^=1,t):0===e.negative&&0!==this.negative?(this.negative=0,t=e.sub(this),this.negative=1,t):this.length>e.length?this.clone().iadd(e):e.clone().iadd(this)},s.prototype.isub=function(e){if(0!==e.negative){e.negative=0;var t=this.iadd(e);return e.negative=1,t._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(e),this.negative=1,this._normSign();var n,r,s=this.cmp(e);if(0===s)return this.negative=0,this.length=1,this.words[0]=0,this;s>0?(n=this,r=e):(n=e,r=this);for(var i=0,o=0;o<r.length;o++)i=(t=(0|n.words[o])-(0|r.words[o])+i)>>26,this.words[o]=67108863&t;for(;0!==i&&o<n.length;o++)i=(t=(0|n.words[o])+i)>>26,this.words[o]=67108863&t;if(0===i&&o<n.length&&n!==this)for(;o<n.length;o++)this.words[o]=n.words[o];return this.length=Math.max(this.length,o),n!==this&&(this.negative=1),this._strip()},s.prototype.sub=function(e){return this.clone().isub(e)};var p=function(e,t,n){var r,s,i,o=e.words,a=t.words,c=n.words,l=0,u=0|o[0],d=8191&u,h=u>>>13,g=0|o[1],f=8191&g,p=g>>>13,m=0|o[2],y=8191&m,b=m>>>13,v=0|o[3],w=8191&v,E=v>>>13,A=0|o[4],S=8191&A,k=A>>>13,T=0|o[5],I=8191&T,C=T>>>13,N=0|o[6],_=8191&N,x=N>>>13,R=0|o[7],B=8191&R,D=R>>>13,O=0|o[8],M=8191&O,L=O>>>13,U=0|o[9],P=8191&U,F=U>>>13,$=0|a[0],K=8191&$,G=$>>>13,H=0|a[1],W=8191&H,q=H>>>13,z=0|a[2],V=8191&z,j=z>>>13,X=0|a[3],Y=8191&X,J=X>>>13,Q=0|a[4],Z=8191&Q,ee=Q>>>13,te=0|a[5],ne=8191&te,re=te>>>13,se=0|a[6],ie=8191&se,oe=se>>>13,ae=0|a[7],ce=8191&ae,le=ae>>>13,ue=0|a[8],de=8191&ue,he=ue>>>13,ge=0|a[9],fe=8191&ge,pe=ge>>>13;n.negative=e.negative^t.negative,n.length=19;var me=(l+(r=Math.imul(d,K))|0)+((8191&(s=(s=Math.imul(d,G))+Math.imul(h,K)|0))<<13)|0;l=((i=Math.imul(h,G))+(s>>>13)|0)+(me>>>26)|0,me&=67108863,r=Math.imul(f,K),s=(s=Math.imul(f,G))+Math.imul(p,K)|0,i=Math.imul(p,G);var ye=(l+(r=r+Math.imul(d,W)|0)|0)+((8191&(s=(s=s+Math.imul(d,q)|0)+Math.imul(h,W)|0))<<13)|0;l=((i=i+Math.imul(h,q)|0)+(s>>>13)|0)+(ye>>>26)|0,ye&=67108863,r=Math.imul(y,K),s=(s=Math.imul(y,G))+Math.imul(b,K)|0,i=Math.imul(b,G),r=r+Math.imul(f,W)|0,s=(s=s+Math.imul(f,q)|0)+Math.imul(p,W)|0,i=i+Math.imul(p,q)|0;var be=(l+(r=r+Math.imul(d,V)|0)|0)+((8191&(s=(s=s+Math.imul(d,j)|0)+Math.imul(h,V)|0))<<13)|0;l=((i=i+Math.imul(h,j)|0)+(s>>>13)|0)+(be>>>26)|0,be&=67108863,r=Math.imul(w,K),s=(s=Math.imul(w,G))+Math.imul(E,K)|0,i=Math.imul(E,G),r=r+Math.imul(y,W)|0,s=(s=s+Math.imul(y,q)|0)+Math.imul(b,W)|0,i=i+Math.imul(b,q)|0,r=r+Math.imul(f,V)|0,s=(s=s+Math.imul(f,j)|0)+Math.imul(p,V)|0,i=i+Math.imul(p,j)|0;var ve=(l+(r=r+Math.imul(d,Y)|0)|0)+((8191&(s=(s=s+Math.imul(d,J)|0)+Math.imul(h,Y)|0))<<13)|0;l=((i=i+Math.imul(h,J)|0)+(s>>>13)|0)+(ve>>>26)|0,ve&=67108863,r=Math.imul(S,K),s=(s=Math.imul(S,G))+Math.imul(k,K)|0,i=Math.imul(k,G),r=r+Math.imul(w,W)|0,s=(s=s+Math.imul(w,q)|0)+Math.imul(E,W)|0,i=i+Math.imul(E,q)|0,r=r+Math.imul(y,V)|0,s=(s=s+Math.imul(y,j)|0)+Math.imul(b,V)|0,i=i+Math.imul(b,j)|0,r=r+Math.imul(f,Y)|0,s=(s=s+Math.imul(f,J)|0)+Math.imul(p,Y)|0,i=i+Math.imul(p,J)|0;var we=(l+(r=r+Math.imul(d,Z)|0)|0)+((8191&(s=(s=s+Math.imul(d,ee)|0)+Math.imul(h,Z)|0))<<13)|0;l=((i=i+Math.imul(h,ee)|0)+(s>>>13)|0)+(we>>>26)|0,we&=67108863,r=Math.imul(I,K),s=(s=Math.imul(I,G))+Math.imul(C,K)|0,i=Math.imul(C,G),r=r+Math.imul(S,W)|0,s=(s=s+Math.imul(S,q)|0)+Math.imul(k,W)|0,i=i+Math.imul(k,q)|0,r=r+Math.imul(w,V)|0,s=(s=s+Math.imul(w,j)|0)+Math.imul(E,V)|0,i=i+Math.imul(E,j)|0,r=r+Math.imul(y,Y)|0,s=(s=s+Math.imul(y,J)|0)+Math.imul(b,Y)|0,i=i+Math.imul(b,J)|0,r=r+Math.imul(f,Z)|0,s=(s=s+Math.imul(f,ee)|0)+Math.imul(p,Z)|0,i=i+Math.imul(p,ee)|0;var Ee=(l+(r=r+Math.imul(d,ne)|0)|0)+((8191&(s=(s=s+Math.imul(d,re)|0)+Math.imul(h,ne)|0))<<13)|0;l=((i=i+Math.imul(h,re)|0)+(s>>>13)|0)+(Ee>>>26)|0,Ee&=67108863,r=Math.imul(_,K),s=(s=Math.imul(_,G))+Math.imul(x,K)|0,i=Math.imul(x,G),r=r+Math.imul(I,W)|0,s=(s=s+Math.imul(I,q)|0)+Math.imul(C,W)|0,i=i+Math.imul(C,q)|0,r=r+Math.imul(S,V)|0,s=(s=s+Math.imul(S,j)|0)+Math.imul(k,V)|0,i=i+Math.imul(k,j)|0,r=r+Math.imul(w,Y)|0,s=(s=s+Math.imul(w,J)|0)+Math.imul(E,Y)|0,i=i+Math.imul(E,J)|0,r=r+Math.imul(y,Z)|0,s=(s=s+Math.imul(y,ee)|0)+Math.imul(b,Z)|0,i=i+Math.imul(b,ee)|0,r=r+Math.imul(f,ne)|0,s=(s=s+Math.imul(f,re)|0)+Math.imul(p,ne)|0,i=i+Math.imul(p,re)|0;var Ae=(l+(r=r+Math.imul(d,ie)|0)|0)+((8191&(s=(s=s+Math.imul(d,oe)|0)+Math.imul(h,ie)|0))<<13)|0;l=((i=i+Math.imul(h,oe)|0)+(s>>>13)|0)+(Ae>>>26)|0,Ae&=67108863,r=Math.imul(B,K),s=(s=Math.imul(B,G))+Math.imul(D,K)|0,i=Math.imul(D,G),r=r+Math.imul(_,W)|0,s=(s=s+Math.imul(_,q)|0)+Math.imul(x,W)|0,i=i+Math.imul(x,q)|0,r=r+Math.imul(I,V)|0,s=(s=s+Math.imul(I,j)|0)+Math.imul(C,V)|0,i=i+Math.imul(C,j)|0,r=r+Math.imul(S,Y)|0,s=(s=s+Math.imul(S,J)|0)+Math.imul(k,Y)|0,i=i+Math.imul(k,J)|0,r=r+Math.imul(w,Z)|0,s=(s=s+Math.imul(w,ee)|0)+Math.imul(E,Z)|0,i=i+Math.imul(E,ee)|0,r=r+Math.imul(y,ne)|0,s=(s=s+Math.imul(y,re)|0)+Math.imul(b,ne)|0,i=i+Math.imul(b,re)|0,r=r+Math.imul(f,ie)|0,s=(s=s+Math.imul(f,oe)|0)+Math.imul(p,ie)|0,i=i+Math.imul(p,oe)|0;var Se=(l+(r=r+Math.imul(d,ce)|0)|0)+((8191&(s=(s=s+Math.imul(d,le)|0)+Math.imul(h,ce)|0))<<13)|0;l=((i=i+Math.imul(h,le)|0)+(s>>>13)|0)+(Se>>>26)|0,Se&=67108863,r=Math.imul(M,K),s=(s=Math.imul(M,G))+Math.imul(L,K)|0,i=Math.imul(L,G),r=r+Math.imul(B,W)|0,s=(s=s+Math.imul(B,q)|0)+Math.imul(D,W)|0,i=i+Math.imul(D,q)|0,r=r+Math.imul(_,V)|0,s=(s=s+Math.imul(_,j)|0)+Math.imul(x,V)|0,i=i+Math.imul(x,j)|0,r=r+Math.imul(I,Y)|0,s=(s=s+Math.imul(I,J)|0)+Math.imul(C,Y)|0,i=i+Math.imul(C,J)|0,r=r+Math.imul(S,Z)|0,s=(s=s+Math.imul(S,ee)|0)+Math.imul(k,Z)|0,i=i+Math.imul(k,ee)|0,r=r+Math.imul(w,ne)|0,s=(s=s+Math.imul(w,re)|0)+Math.imul(E,ne)|0,i=i+Math.imul(E,re)|0,r=r+Math.imul(y,ie)|0,s=(s=s+Math.imul(y,oe)|0)+Math.imul(b,ie)|0,i=i+Math.imul(b,oe)|0,r=r+Math.imul(f,ce)|0,s=(s=s+Math.imul(f,le)|0)+Math.imul(p,ce)|0,i=i+Math.imul(p,le)|0;var ke=(l+(r=r+Math.imul(d,de)|0)|0)+((8191&(s=(s=s+Math.imul(d,he)|0)+Math.imul(h,de)|0))<<13)|0;l=((i=i+Math.imul(h,he)|0)+(s>>>13)|0)+(ke>>>26)|0,ke&=67108863,r=Math.imul(P,K),s=(s=Math.imul(P,G))+Math.imul(F,K)|0,i=Math.imul(F,G),r=r+Math.imul(M,W)|0,s=(s=s+Math.imul(M,q)|0)+Math.imul(L,W)|0,i=i+Math.imul(L,q)|0,r=r+Math.imul(B,V)|0,s=(s=s+Math.imul(B,j)|0)+Math.imul(D,V)|0,i=i+Math.imul(D,j)|0,r=r+Math.imul(_,Y)|0,s=(s=s+Math.imul(_,J)|0)+Math.imul(x,Y)|0,i=i+Math.imul(x,J)|0,r=r+Math.imul(I,Z)|0,s=(s=s+Math.imul(I,ee)|0)+Math.imul(C,Z)|0,i=i+Math.imul(C,ee)|0,r=r+Math.imul(S,ne)|0,s=(s=s+Math.imul(S,re)|0)+Math.imul(k,ne)|0,i=i+Math.imul(k,re)|0,r=r+Math.imul(w,ie)|0,s=(s=s+Math.imul(w,oe)|0)+Math.imul(E,ie)|0,i=i+Math.imul(E,oe)|0,r=r+Math.imul(y,ce)|0,s=(s=s+Math.imul(y,le)|0)+Math.imul(b,ce)|0,i=i+Math.imul(b,le)|0,r=r+Math.imul(f,de)|0,s=(s=s+Math.imul(f,he)|0)+Math.imul(p,de)|0,i=i+Math.imul(p,he)|0;var Te=(l+(r=r+Math.imul(d,fe)|0)|0)+((8191&(s=(s=s+Math.imul(d,pe)|0)+Math.imul(h,fe)|0))<<13)|0;l=((i=i+Math.imul(h,pe)|0)+(s>>>13)|0)+(Te>>>26)|0,Te&=67108863,r=Math.imul(P,W),s=(s=Math.imul(P,q))+Math.imul(F,W)|0,i=Math.imul(F,q),r=r+Math.imul(M,V)|0,s=(s=s+Math.imul(M,j)|0)+Math.imul(L,V)|0,i=i+Math.imul(L,j)|0,r=r+Math.imul(B,Y)|0,s=(s=s+Math.imul(B,J)|0)+Math.imul(D,Y)|0,i=i+Math.imul(D,J)|0,r=r+Math.imul(_,Z)|0,s=(s=s+Math.imul(_,ee)|0)+Math.imul(x,Z)|0,i=i+Math.imul(x,ee)|0,r=r+Math.imul(I,ne)|0,s=(s=s+Math.imul(I,re)|0)+Math.imul(C,ne)|0,i=i+Math.imul(C,re)|0,r=r+Math.imul(S,ie)|0,s=(s=s+Math.imul(S,oe)|0)+Math.imul(k,ie)|0,i=i+Math.imul(k,oe)|0,r=r+Math.imul(w,ce)|0,s=(s=s+Math.imul(w,le)|0)+Math.imul(E,ce)|0,i=i+Math.imul(E,le)|0,r=r+Math.imul(y,de)|0,s=(s=s+Math.imul(y,he)|0)+Math.imul(b,de)|0,i=i+Math.imul(b,he)|0;var Ie=(l+(r=r+Math.imul(f,fe)|0)|0)+((8191&(s=(s=s+Math.imul(f,pe)|0)+Math.imul(p,fe)|0))<<13)|0;l=((i=i+Math.imul(p,pe)|0)+(s>>>13)|0)+(Ie>>>26)|0,Ie&=67108863,r=Math.imul(P,V),s=(s=Math.imul(P,j))+Math.imul(F,V)|0,i=Math.imul(F,j),r=r+Math.imul(M,Y)|0,s=(s=s+Math.imul(M,J)|0)+Math.imul(L,Y)|0,i=i+Math.imul(L,J)|0,r=r+Math.imul(B,Z)|0,s=(s=s+Math.imul(B,ee)|0)+Math.imul(D,Z)|0,i=i+Math.imul(D,ee)|0,r=r+Math.imul(_,ne)|0,s=(s=s+Math.imul(_,re)|0)+Math.imul(x,ne)|0,i=i+Math.imul(x,re)|0,r=r+Math.imul(I,ie)|0,s=(s=s+Math.imul(I,oe)|0)+Math.imul(C,ie)|0,i=i+Math.imul(C,oe)|0,r=r+Math.imul(S,ce)|0,s=(s=s+Math.imul(S,le)|0)+Math.imul(k,ce)|0,i=i+Math.imul(k,le)|0,r=r+Math.imul(w,de)|0,s=(s=s+Math.imul(w,he)|0)+Math.imul(E,de)|0,i=i+Math.imul(E,he)|0;var Ce=(l+(r=r+Math.imul(y,fe)|0)|0)+((8191&(s=(s=s+Math.imul(y,pe)|0)+Math.imul(b,fe)|0))<<13)|0;l=((i=i+Math.imul(b,pe)|0)+(s>>>13)|0)+(Ce>>>26)|0,Ce&=67108863,r=Math.imul(P,Y),s=(s=Math.imul(P,J))+Math.imul(F,Y)|0,i=Math.imul(F,J),r=r+Math.imul(M,Z)|0,s=(s=s+Math.imul(M,ee)|0)+Math.imul(L,Z)|0,i=i+Math.imul(L,ee)|0,r=r+Math.imul(B,ne)|0,s=(s=s+Math.imul(B,re)|0)+Math.imul(D,ne)|0,i=i+Math.imul(D,re)|0,r=r+Math.imul(_,ie)|0,s=(s=s+Math.imul(_,oe)|0)+Math.imul(x,ie)|0,i=i+Math.imul(x,oe)|0,r=r+Math.imul(I,ce)|0,s=(s=s+Math.imul(I,le)|0)+Math.imul(C,ce)|0,i=i+Math.imul(C,le)|0,r=r+Math.imul(S,de)|0,s=(s=s+Math.imul(S,he)|0)+Math.imul(k,de)|0,i=i+Math.imul(k,he)|0;var Ne=(l+(r=r+Math.imul(w,fe)|0)|0)+((8191&(s=(s=s+Math.imul(w,pe)|0)+Math.imul(E,fe)|0))<<13)|0;l=((i=i+Math.imul(E,pe)|0)+(s>>>13)|0)+(Ne>>>26)|0,Ne&=67108863,r=Math.imul(P,Z),s=(s=Math.imul(P,ee))+Math.imul(F,Z)|0,i=Math.imul(F,ee),r=r+Math.imul(M,ne)|0,s=(s=s+Math.imul(M,re)|0)+Math.imul(L,ne)|0,i=i+Math.imul(L,re)|0,r=r+Math.imul(B,ie)|0,s=(s=s+Math.imul(B,oe)|0)+Math.imul(D,ie)|0,i=i+Math.imul(D,oe)|0,r=r+Math.imul(_,ce)|0,s=(s=s+Math.imul(_,le)|0)+Math.imul(x,ce)|0,i=i+Math.imul(x,le)|0,r=r+Math.imul(I,de)|0,s=(s=s+Math.imul(I,he)|0)+Math.imul(C,de)|0,i=i+Math.imul(C,he)|0;var _e=(l+(r=r+Math.imul(S,fe)|0)|0)+((8191&(s=(s=s+Math.imul(S,pe)|0)+Math.imul(k,fe)|0))<<13)|0;l=((i=i+Math.imul(k,pe)|0)+(s>>>13)|0)+(_e>>>26)|0,_e&=67108863,r=Math.imul(P,ne),s=(s=Math.imul(P,re))+Math.imul(F,ne)|0,i=Math.imul(F,re),r=r+Math.imul(M,ie)|0,s=(s=s+Math.imul(M,oe)|0)+Math.imul(L,ie)|0,i=i+Math.imul(L,oe)|0,r=r+Math.imul(B,ce)|0,s=(s=s+Math.imul(B,le)|0)+Math.imul(D,ce)|0,i=i+Math.imul(D,le)|0,r=r+Math.imul(_,de)|0,s=(s=s+Math.imul(_,he)|0)+Math.imul(x,de)|0,i=i+Math.imul(x,he)|0;var xe=(l+(r=r+Math.imul(I,fe)|0)|0)+((8191&(s=(s=s+Math.imul(I,pe)|0)+Math.imul(C,fe)|0))<<13)|0;l=((i=i+Math.imul(C,pe)|0)+(s>>>13)|0)+(xe>>>26)|0,xe&=67108863,r=Math.imul(P,ie),s=(s=Math.imul(P,oe))+Math.imul(F,ie)|0,i=Math.imul(F,oe),r=r+Math.imul(M,ce)|0,s=(s=s+Math.imul(M,le)|0)+Math.imul(L,ce)|0,i=i+Math.imul(L,le)|0,r=r+Math.imul(B,de)|0,s=(s=s+Math.imul(B,he)|0)+Math.imul(D,de)|0,i=i+Math.imul(D,he)|0;var Re=(l+(r=r+Math.imul(_,fe)|0)|0)+((8191&(s=(s=s+Math.imul(_,pe)|0)+Math.imul(x,fe)|0))<<13)|0;l=((i=i+Math.imul(x,pe)|0)+(s>>>13)|0)+(Re>>>26)|0,Re&=67108863,r=Math.imul(P,ce),s=(s=Math.imul(P,le))+Math.imul(F,ce)|0,i=Math.imul(F,le),r=r+Math.imul(M,de)|0,s=(s=s+Math.imul(M,he)|0)+Math.imul(L,de)|0,i=i+Math.imul(L,he)|0;var Be=(l+(r=r+Math.imul(B,fe)|0)|0)+((8191&(s=(s=s+Math.imul(B,pe)|0)+Math.imul(D,fe)|0))<<13)|0;l=((i=i+Math.imul(D,pe)|0)+(s>>>13)|0)+(Be>>>26)|0,Be&=67108863,r=Math.imul(P,de),s=(s=Math.imul(P,he))+Math.imul(F,de)|0,i=Math.imul(F,he);var De=(l+(r=r+Math.imul(M,fe)|0)|0)+((8191&(s=(s=s+Math.imul(M,pe)|0)+Math.imul(L,fe)|0))<<13)|0;l=((i=i+Math.imul(L,pe)|0)+(s>>>13)|0)+(De>>>26)|0,De&=67108863;var Oe=(l+(r=Math.imul(P,fe))|0)+((8191&(s=(s=Math.imul(P,pe))+Math.imul(F,fe)|0))<<13)|0;return l=((i=Math.imul(F,pe))+(s>>>13)|0)+(Oe>>>26)|0,Oe&=67108863,c[0]=me,c[1]=ye,c[2]=be,c[3]=ve,c[4]=we,c[5]=Ee,c[6]=Ae,c[7]=Se,c[8]=ke,c[9]=Te,c[10]=Ie,c[11]=Ce,c[12]=Ne,c[13]=_e,c[14]=xe,c[15]=Re,c[16]=Be,c[17]=De,c[18]=Oe,0!==l&&(c[19]=l,n.length++),n};function m(e,t,n){n.negative=t.negative^e.negative,n.length=e.length+t.length;for(var r=0,s=0,i=0;i<n.length-1;i++){var o=s;s=0;for(var a=67108863&r,c=Math.min(i,t.length-1),l=Math.max(0,i-e.length+1);l<=c;l++){var u=i-l,d=(0|e.words[u])*(0|t.words[l]),h=67108863&d;a=67108863&(h=h+a|0),s+=(o=(o=o+(d/67108864|0)|0)+(h>>>26)|0)>>>26,o&=67108863}n.words[i]=a,r=o,o=s}return 0!==r?n.words[i]=r:n.length--,n._strip()}function y(e,t,n){return m(e,t,n)}Math.imul||(p=f),s.prototype.mulTo=function(e,t){var n=this.length+e.length;return 10===this.length&&10===e.length?p(this,e,t):n<63?f(this,e,t):n<1024?m(this,e,t):y(this,e,t)},s.prototype.mul=function(e){var t=new s(null);return t.words=new Array(this.length+e.length),this.mulTo(e,t)},s.prototype.mulf=function(e){var t=new s(null);return t.words=new Array(this.length+e.length),y(this,e,t)},s.prototype.imul=function(e){return this.clone().mulTo(e,this)},s.prototype.imuln=function(e){var t=e<0;t&&(e=-e),n("number"==typeof e),n(e<67108864);for(var r=0,s=0;s<this.length;s++){var i=(0|this.words[s])*e,o=(67108863&i)+(67108863&r);r>>=26,r+=i/67108864|0,r+=o>>>26,this.words[s]=67108863&o}return 0!==r&&(this.words[s]=r,this.length++),0===e&&(this.length=1,this._normSign()),t?this.ineg():this},s.prototype.muln=function(e){return this.clone().imuln(e)},s.prototype.sqr=function(){return this.mul(this)},s.prototype.isqr=function(){return this.imul(this.clone())},s.prototype.pow=function(e){var t=function(e){for(var t=new Array(e.bitLength()),n=0;n<t.length;n++){var r=n/26|0,s=n%26;t[n]=e.words[r]>>>s&1}return t}(e);if(0===t.length)return new s(1);for(var n=this,r=0;r<t.length&&0===t[r];r++,n=n.sqr());if(++r<t.length)for(var i=n.sqr();r<t.length;r++,i=i.sqr())0!==t[r]&&(n=n.mul(i));return n},s.prototype.iushln=function(e){n("number"==typeof e&&e>=0);var t,r=e%26,s=(e-r)/26,i=67108863>>>26-r<<26-r;if(0!==r){var o=0;for(t=0;t<this.length;t++){var a=this.words[t]&i,c=(0|this.words[t])-a<<r;this.words[t]=c|o,o=a>>>26-r}o&&(this.words[t]=o,this.length++)}if(0!==s){for(t=this.length-1;t>=0;t--)this.words[t+s]=this.words[t];for(t=0;t<s;t++)this.words[t]=0;this.length+=s}return this._strip()},s.prototype.ishln=function(e){return n(0===this.negative),this.iushln(e)},s.prototype.iushrn=function(e,t,r){var s;n("number"==typeof e&&e>=0),s=t?(t-t%26)/26:0;var i=e%26,o=Math.min((e-i)/26,this.length),a=67108863^67108863>>>i<<i,c=r;if(s-=o,s=Math.max(0,s),c){for(var l=0;l<o;l++)c.words[l]=this.words[l];c.length=o}if(0===o);else if(this.length>o)for(this.length-=o,l=0;l<this.length;l++)this.words[l]=this.words[l+o];else this.words[0]=0,this.length=1;var u=0;for(l=this.length-1;l>=0&&(0!==u||l>=s);l--){var d=0|this.words[l];this.words[l]=u<<26-i|d>>>i,u=d&a}return c&&0!==u&&(c.words[c.length++]=u),0===this.length&&(this.words[0]=0,this.length=1),this._strip()},s.prototype.ishrn=function(e,t,r){return n(0===this.negative),this.iushrn(e,t,r)},s.prototype.shln=function(e){return this.clone().ishln(e)},s.prototype.ushln=function(e){return this.clone().iushln(e)},s.prototype.shrn=function(e){return this.clone().ishrn(e)},s.prototype.ushrn=function(e){return this.clone().iushrn(e)},s.prototype.testn=function(e){n("number"==typeof e&&e>=0);var t=e%26,r=(e-t)/26,s=1<<t;return!(this.length<=r||!(this.words[r]&s))},s.prototype.imaskn=function(e){n("number"==typeof e&&e>=0);var t=e%26,r=(e-t)/26;if(n(0===this.negative,"imaskn works only with positive numbers"),this.length<=r)return this;if(0!==t&&r++,this.length=Math.min(r,this.length),0!==t){var s=67108863^67108863>>>t<<t;this.words[this.length-1]&=s}return 0===this.length&&(this.words[0]=0,this.length=1),this._strip()},s.prototype.maskn=function(e){return this.clone().imaskn(e)},s.prototype.iaddn=function(e){return n("number"==typeof e),n(e<67108864),e<0?this.isubn(-e):0!==this.negative?1===this.length&&(0|this.words[0])<=e?(this.words[0]=e-(0|this.words[0]),this.negative=0,this):(this.negative=0,this.isubn(e),this.negative=1,this):this._iaddn(e)},s.prototype._iaddn=function(e){this.words[0]+=e;for(var t=0;t<this.length&&this.words[t]>=67108864;t++)this.words[t]-=67108864,t===this.length-1?this.words[t+1]=1:this.words[t+1]++;return this.length=Math.max(this.length,t+1),this},s.prototype.isubn=function(e){if(n("number"==typeof e),n(e<67108864),e<0)return this.iaddn(-e);if(0!==this.negative)return this.negative=0,this.iaddn(e),this.negative=1,this;if(this.words[0]-=e,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var t=0;t<this.length&&this.words[t]<0;t++)this.words[t]+=67108864,this.words[t+1]-=1;return this._strip()},s.prototype.addn=function(e){return this.clone().iaddn(e)},s.prototype.subn=function(e){return this.clone().isubn(e)},s.prototype.iabs=function(){return this.negative=0,this},s.prototype.abs=function(){return this.clone().iabs()},s.prototype._ishlnsubmul=function(e,t,r){var s,i,o=e.length+r;this._expand(o);var a=0;for(s=0;s<e.length;s++){i=(0|this.words[s+r])+a;var c=(0|e.words[s])*t;a=((i-=67108863&c)>>26)-(c/67108864|0),this.words[s+r]=67108863&i}for(;s<this.length-r;s++)a=(i=(0|this.words[s+r])+a)>>26,this.words[s+r]=67108863&i;if(0===a)return this._strip();for(n(-1===a),a=0,s=0;s<this.length;s++)a=(i=-(0|this.words[s])+a)>>26,this.words[s]=67108863&i;return this.negative=1,this._strip()},s.prototype._wordDiv=function(e,t){var n=(this.length,e.length),r=this.clone(),i=e,o=0|i.words[i.length-1];0!=(n=26-this._countBits(o))&&(i=i.ushln(n),r.iushln(n),o=0|i.words[i.length-1]);var a,c=r.length-i.length;if("mod"!==t){(a=new s(null)).length=c+1,a.words=new Array(a.length);for(var l=0;l<a.length;l++)a.words[l]=0}var u=r.clone()._ishlnsubmul(i,1,c);0===u.negative&&(r=u,a&&(a.words[c]=1));for(var d=c-1;d>=0;d--){var h=67108864*(0|r.words[i.length+d])+(0|r.words[i.length+d-1]);for(h=Math.min(h/o|0,67108863),r._ishlnsubmul(i,h,d);0!==r.negative;)h--,r.negative=0,r._ishlnsubmul(i,1,d),r.isZero()||(r.negative^=1);a&&(a.words[d]=h)}return a&&a._strip(),r._strip(),"div"!==t&&0!==n&&r.iushrn(n),{div:a||null,mod:r}},s.prototype.divmod=function(e,t,r){return n(!e.isZero()),this.isZero()?{div:new s(0),mod:new s(0)}:0!==this.negative&&0===e.negative?(a=this.neg().divmod(e,t),"mod"!==t&&(i=a.div.neg()),"div"!==t&&(o=a.mod.neg(),r&&0!==o.negative&&o.iadd(e)),{div:i,mod:o}):0===this.negative&&0!==e.negative?(a=this.divmod(e.neg(),t),"mod"!==t&&(i=a.div.neg()),{div:i,mod:a.mod}):0!==(this.negative&e.negative)?(a=this.neg().divmod(e.neg(),t),"div"!==t&&(o=a.mod.neg(),r&&0!==o.negative&&o.isub(e)),{div:a.div,mod:o}):e.length>this.length||this.cmp(e)<0?{div:new s(0),mod:this}:1===e.length?"div"===t?{div:this.divn(e.words[0]),mod:null}:"mod"===t?{div:null,mod:new s(this.modrn(e.words[0]))}:{div:this.divn(e.words[0]),mod:new s(this.modrn(e.words[0]))}:this._wordDiv(e,t);var i,o,a},s.prototype.div=function(e){return this.divmod(e,"div",!1).div},s.prototype.mod=function(e){return this.divmod(e,"mod",!1).mod},s.prototype.umod=function(e){return this.divmod(e,"mod",!0).mod},s.prototype.divRound=function(e){var t=this.divmod(e);if(t.mod.isZero())return t.div;var n=t.mod.abs(),r=e.abs().iushrn(1),i=1&e.words[0],o=n.cmp(r);if(o<0||1===i&&0===o)return t.div;var a=new s(1);return a.negative=this.negative^e.negative,t.div.iadd(a)},s.prototype.modrn=function(e){var t=e<0;t&&(e=-e),n(e<=67108863);for(var r=(1<<26)%e,s=0,i=this.length-1;i>=0;i--)s=(r*s+(0|this.words[i]))%e;return t?-s:s},s.prototype.modn=function(e){return this.modrn(e)},s.prototype.idivn=function(e){var t=e<0;t&&(e=-e),n(e<=67108863);for(var r=0,s=this.length-1;s>=0;s--){var i=(0|this.words[s])+67108864*r;this.words[s]=i/e|0,r=i%e}return this._strip(),t?this.ineg():this},s.prototype.divn=function(e){return this.clone().idivn(e)},s.prototype.egcd=function(e){n(0===e.negative),n(!e.isZero());var t=this,r=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var i=new s(1),o=new s(0),a=new s(0),c=new s(1),l=0;t.isEven()&&r.isEven();)t.iushrn(1),r.iushrn(1),++l;for(var u=r.clone(),d=t.clone();!t.isZero();){for(var h=0,g=1;0===(t.words[0]&g)&&h<26;++h,g<<=1);if(h>0)for(t.iushrn(h);h-- >0;)(i.isOdd()||o.isOdd())&&(i.iadd(u),o.isub(d)),i.iushrn(1),o.iushrn(1);for(var f=0,p=1;0===(r.words[0]&p)&&f<26;++f,p<<=1);if(f>0)for(r.iushrn(f);f-- >0;)(a.isOdd()||c.isOdd())&&(a.iadd(u),c.isub(d)),a.iushrn(1),c.iushrn(1);t.cmp(r)>=0?(t.isub(r),i.isub(a),o.isub(c)):(r.isub(t),a.isub(i),c.isub(o))}return{a:a,b:c,gcd:r.iushln(l)}},s.prototype._invmp=function(e){n(0===e.negative),n(!e.isZero());var t=this,r=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var i,o=new s(1),a=new s(0),c=r.clone();t.cmpn(1)>0&&r.cmpn(1)>0;){for(var l=0,u=1;0===(t.words[0]&u)&&l<26;++l,u<<=1);if(l>0)for(t.iushrn(l);l-- >0;)o.isOdd()&&o.iadd(c),o.iushrn(1);for(var d=0,h=1;0===(r.words[0]&h)&&d<26;++d,h<<=1);if(d>0)for(r.iushrn(d);d-- >0;)a.isOdd()&&a.iadd(c),a.iushrn(1);t.cmp(r)>=0?(t.isub(r),o.isub(a)):(r.isub(t),a.isub(o))}return(i=0===t.cmpn(1)?o:a).cmpn(0)<0&&i.iadd(e),i},s.prototype.gcd=function(e){if(this.isZero())return e.abs();if(e.isZero())return this.abs();var t=this.clone(),n=e.clone();t.negative=0,n.negative=0;for(var r=0;t.isEven()&&n.isEven();r++)t.iushrn(1),n.iushrn(1);for(;;){for(;t.isEven();)t.iushrn(1);for(;n.isEven();)n.iushrn(1);var s=t.cmp(n);if(s<0){var i=t;t=n,n=i}else if(0===s||0===n.cmpn(1))break;t.isub(n)}return n.iushln(r)},s.prototype.invm=function(e){return this.egcd(e).a.umod(e)},s.prototype.isEven=function(){return!(1&this.words[0])},s.prototype.isOdd=function(){return!(1&~this.words[0])},s.prototype.andln=function(e){return this.words[0]&e},s.prototype.bincn=function(e){n("number"==typeof e);var t=e%26,r=(e-t)/26,s=1<<t;if(this.length<=r)return this._expand(r+1),this.words[r]|=s,this;for(var i=s,o=r;0!==i&&o<this.length;o++){var a=0|this.words[o];i=(a+=i)>>>26,a&=67108863,this.words[o]=a}return 0!==i&&(this.words[o]=i,this.length++),this},s.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},s.prototype.cmpn=function(e){var t,r=e<0;if(0!==this.negative&&!r)return-1;if(0===this.negative&&r)return 1;if(this._strip(),this.length>1)t=1;else{r&&(e=-e),n(e<=67108863,"Number is too big");var s=0|this.words[0];t=s===e?0:s<e?-1:1}return 0!==this.negative?0|-t:t},s.prototype.cmp=function(e){if(0!==this.negative&&0===e.negative)return-1;if(0===this.negative&&0!==e.negative)return 1;var t=this.ucmp(e);return 0!==this.negative?0|-t:t},s.prototype.ucmp=function(e){if(this.length>e.length)return 1;if(this.length<e.length)return-1;for(var t=0,n=this.length-1;n>=0;n--){var r=0|this.words[n],s=0|e.words[n];if(r!==s){r<s?t=-1:r>s&&(t=1);break}}return t},s.prototype.gtn=function(e){return 1===this.cmpn(e)},s.prototype.gt=function(e){return 1===this.cmp(e)},s.prototype.gten=function(e){return this.cmpn(e)>=0},s.prototype.gte=function(e){return this.cmp(e)>=0},s.prototype.ltn=function(e){return-1===this.cmpn(e)},s.prototype.lt=function(e){return-1===this.cmp(e)},s.prototype.lten=function(e){return this.cmpn(e)<=0},s.prototype.lte=function(e){return this.cmp(e)<=0},s.prototype.eqn=function(e){return 0===this.cmpn(e)},s.prototype.eq=function(e){return 0===this.cmp(e)},s.red=function(e){return new k(e)},s.prototype.toRed=function(e){return n(!this.red,"Already a number in reduction context"),n(0===this.negative,"red works only with positives"),e.convertTo(this)._forceRed(e)},s.prototype.fromRed=function(){return n(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},s.prototype._forceRed=function(e){return this.red=e,this},s.prototype.forceRed=function(e){return n(!this.red,"Already a number in reduction context"),this._forceRed(e)},s.prototype.redAdd=function(e){return n(this.red,"redAdd works only with red numbers"),this.red.add(this,e)},s.prototype.redIAdd=function(e){return n(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,e)},s.prototype.redSub=function(e){return n(this.red,"redSub works only with red numbers"),this.red.sub(this,e)},s.prototype.redISub=function(e){return n(this.red,"redISub works only with red numbers"),this.red.isub(this,e)},s.prototype.redShl=function(e){return n(this.red,"redShl works only with red numbers"),this.red.shl(this,e)},s.prototype.redMul=function(e){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.mul(this,e)},s.prototype.redIMul=function(e){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.imul(this,e)},s.prototype.redSqr=function(){return n(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},s.prototype.redISqr=function(){return n(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},s.prototype.redSqrt=function(){return n(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},s.prototype.redInvm=function(){return n(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},s.prototype.redNeg=function(){return n(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},s.prototype.redPow=function(e){return n(this.red&&!e.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,e)};var b={k256:null,p224:null,p192:null,p25519:null};function v(e,t){this.name=e,this.p=new s(t,16),this.n=this.p.bitLength(),this.k=new s(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function w(){v.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function E(){v.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function A(){v.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function S(){v.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function k(e){if("string"==typeof e){var t=s._prime(e);this.m=t.p,this.prime=t}else n(e.gtn(1),"modulus must be greater than 1"),this.m=e,this.prime=null}function T(e){k.call(this,e),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new s(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}v.prototype._tmp=function(){var e=new s(null);return e.words=new Array(Math.ceil(this.n/13)),e},v.prototype.ireduce=function(e){var t,n=e;do{this.split(n,this.tmp),t=(n=(n=this.imulK(n)).iadd(this.tmp)).bitLength()}while(t>this.n);var r=t<this.n?-1:n.ucmp(this.p);return 0===r?(n.words[0]=0,n.length=1):r>0?n.isub(this.p):void 0!==n.strip?n.strip():n._strip(),n},v.prototype.split=function(e,t){e.iushrn(this.n,0,t)},v.prototype.imulK=function(e){return e.imul(this.k)},r(w,v),w.prototype.split=function(e,t){for(var n=4194303,r=Math.min(e.length,9),s=0;s<r;s++)t.words[s]=e.words[s];if(t.length=r,e.length<=9)return e.words[0]=0,void(e.length=1);var i=e.words[9];for(t.words[t.length++]=i&n,s=10;s<e.length;s++){var o=0|e.words[s];e.words[s-10]=(o&n)<<4|i>>>22,i=o}i>>>=22,e.words[s-10]=i,0===i&&e.length>10?e.length-=10:e.length-=9},w.prototype.imulK=function(e){e.words[e.length]=0,e.words[e.length+1]=0,e.length+=2;for(var t=0,n=0;n<e.length;n++){var r=0|e.words[n];t+=977*r,e.words[n]=67108863&t,t=64*r+(t/67108864|0)}return 0===e.words[e.length-1]&&(e.length--,0===e.words[e.length-1]&&e.length--),e},r(E,v),r(A,v),r(S,v),S.prototype.imulK=function(e){for(var t=0,n=0;n<e.length;n++){var r=19*(0|e.words[n])+t,s=67108863&r;r>>>=26,e.words[n]=s,t=r}return 0!==t&&(e.words[e.length++]=t),e},s._prime=function(e){if(b[e])return b[e];var t;if("k256"===e)t=new w;else if("p224"===e)t=new E;else if("p192"===e)t=new A;else{if("p25519"!==e)throw new Error("Unknown prime "+e);t=new S}return b[e]=t,t},k.prototype._verify1=function(e){n(0===e.negative,"red works only with positives"),n(e.red,"red works only with red numbers")},k.prototype._verify2=function(e,t){n(0===(e.negative|t.negative),"red works only with positives"),n(e.red&&e.red===t.red,"red works only with red numbers")},k.prototype.imod=function(e){return this.prime?this.prime.ireduce(e)._forceRed(this):(l(e,e.umod(this.m)._forceRed(this)),e)},k.prototype.neg=function(e){return e.isZero()?e.clone():this.m.sub(e)._forceRed(this)},k.prototype.add=function(e,t){this._verify2(e,t);var n=e.add(t);return n.cmp(this.m)>=0&&n.isub(this.m),n._forceRed(this)},k.prototype.iadd=function(e,t){this._verify2(e,t);var n=e.iadd(t);return n.cmp(this.m)>=0&&n.isub(this.m),n},k.prototype.sub=function(e,t){this._verify2(e,t);var n=e.sub(t);return n.cmpn(0)<0&&n.iadd(this.m),n._forceRed(this)},k.prototype.isub=function(e,t){this._verify2(e,t);var n=e.isub(t);return n.cmpn(0)<0&&n.iadd(this.m),n},k.prototype.shl=function(e,t){return this._verify1(e),this.imod(e.ushln(t))},k.prototype.imul=function(e,t){return this._verify2(e,t),this.imod(e.imul(t))},k.prototype.mul=function(e,t){return this._verify2(e,t),this.imod(e.mul(t))},k.prototype.isqr=function(e){return this.imul(e,e.clone())},k.prototype.sqr=function(e){return this.mul(e,e)},k.prototype.sqrt=function(e){if(e.isZero())return e.clone();var t=this.m.andln(3);if(n(t%2==1),3===t){var r=this.m.add(new s(1)).iushrn(2);return this.pow(e,r)}for(var i=this.m.subn(1),o=0;!i.isZero()&&0===i.andln(1);)o++,i.iushrn(1);n(!i.isZero());var a=new s(1).toRed(this),c=a.redNeg(),l=this.m.subn(1).iushrn(1),u=this.m.bitLength();for(u=new s(2*u*u).toRed(this);0!==this.pow(u,l).cmp(c);)u.redIAdd(c);for(var d=this.pow(u,i),h=this.pow(e,i.addn(1).iushrn(1)),g=this.pow(e,i),f=o;0!==g.cmp(a);){for(var p=g,m=0;0!==p.cmp(a);m++)p=p.redSqr();n(m<f);var y=this.pow(d,new s(1).iushln(f-m-1));h=h.redMul(y),d=y.redSqr(),g=g.redMul(d),f=m}return h},k.prototype.invm=function(e){var t=e._invmp(this.m);return 0!==t.negative?(t.negative=0,this.imod(t).redNeg()):this.imod(t)},k.prototype.pow=function(e,t){if(t.isZero())return new s(1).toRed(this);if(0===t.cmpn(1))return e.clone();var n=new Array(16);n[0]=new s(1).toRed(this),n[1]=e;for(var r=2;r<n.length;r++)n[r]=this.mul(n[r-1],e);var i=n[0],o=0,a=0,c=t.bitLength()%26;for(0===c&&(c=26),r=t.length-1;r>=0;r--){for(var l=t.words[r],u=c-1;u>=0;u--){var d=l>>u&1;i!==n[0]&&(i=this.sqr(i)),0!==d||0!==o?(o<<=1,o|=d,(4===++a||0===r&&0===u)&&(i=this.mul(i,n[o]),a=0,o=0)):a=0}c=26}return i},k.prototype.convertTo=function(e){var t=e.umod(this.m);return t===e?t.clone():t},k.prototype.convertFrom=function(e){var t=e.clone();return t.red=null,t},s.mont=function(e){return new T(e)},r(T,k),T.prototype.convertTo=function(e){return this.imod(e.ushln(this.shift))},T.prototype.convertFrom=function(e){var t=this.imod(e.mul(this.rinv));return t.red=null,t},T.prototype.imul=function(e,t){if(e.isZero()||t.isZero())return e.words[0]=0,e.length=1,e;var n=e.imul(t),r=n.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),s=n.isub(r).iushrn(this.shift),i=s;return s.cmp(this.m)>=0?i=s.isub(this.m):s.cmpn(0)<0&&(i=s.iadd(this.m)),i._forceRed(this)},T.prototype.mul=function(e,t){if(e.isZero()||t.isZero())return new s(0)._forceRed(this);var n=e.mul(t),r=n.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=n.isub(r).iushrn(this.shift),o=i;return i.cmp(this.m)>=0?o=i.isub(this.m):i.cmpn(0)<0&&(o=i.iadd(this.m)),o._forceRed(this)},T.prototype.invm=function(e){return this.imod(e._invmp(this.m).mul(this.r2))._forceRed(this)}}(al,ll)),al.exports}var dl,hl,gl,fl,pl,ml=So(ul()),yl={exports:{}};function bl(){return dl||(dl=1,function(e,t){var n=Do(),r=n.Buffer;function s(e,t){for(var n in e)t[n]=e[n]}function i(e,t,n){return r(e,t,n)}r.from&&r.alloc&&r.allocUnsafe&&r.allocUnsafeSlow?e.exports=n:(s(n,t),t.Buffer=i),i.prototype=Object.create(r.prototype),s(r,i),i.from=function(e,t,n){if("number"==typeof e)throw new TypeError("Argument must not be a number");return r(e,t,n)},i.alloc=function(e,t,n){if("number"!=typeof e)throw new TypeError("Argument must be a number");var s=r(e);return void 0!==t?"string"==typeof n?s.fill(t,n):s.fill(t):s.fill(0),s},i.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return r(e)},i.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return n.SlowBuffer(e)}}(yl,yl.exports)),yl.exports}function vl(){if(gl)return hl;gl=1;var e=bl().Buffer;return hl=function(t){if(t.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),r=0;r<n.length;r++)n[r]=255;for(var s=0;s<t.length;s++){var i=t.charAt(s),o=i.charCodeAt(0);if(255!==n[o])throw new TypeError(i+" is ambiguous");n[o]=s}var a=t.length,c=t.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(t){if("string"!=typeof t)throw new TypeError("Expected String");if(0===t.length)return e.alloc(0);for(var r=0,s=0,i=0;t[r]===c;)s++,r++;for(var o=(t.length-r)*l+1>>>0,u=new Uint8Array(o);r<t.length;){var d=t.charCodeAt(r);if(d>255)return;var h=n[d];if(255===h)return;for(var g=0,f=o-1;(0!==h||g<i)&&-1!==f;f--,g++)h+=a*u[f]>>>0,u[f]=h%256>>>0,h=h/256>>>0;if(0!==h)throw new Error("Non-zero carry");i=g,r++}for(var p=o-i;p!==o&&0===u[p];)p++;var m=e.allocUnsafe(s+(o-p));m.fill(0,0,s);for(var y=s;p!==o;)m[y++]=u[p++];return m}return{encode:function(n){if((Array.isArray(n)||n instanceof Uint8Array)&&(n=e.from(n)),!e.isBuffer(n))throw new TypeError("Expected Buffer");if(0===n.length)return"";for(var r=0,s=0,i=0,o=n.length;i!==o&&0===n[i];)i++,r++;for(var l=(o-i)*u+1>>>0,d=new Uint8Array(l);i!==o;){for(var h=n[i],g=0,f=l-1;(0!==h||g<s)&&-1!==f;f--,g++)h+=256*d[f]>>>0,d[f]=h%a>>>0,h=h/a>>>0;if(0!==h)throw new Error("Non-zero carry");s=g,i++}for(var p=l-s;p!==l&&0===d[p];)p++;for(var m=c.repeat(r);p<l;++p)m+=t.charAt(d[p]);return m},decodeUnsafe:d,decode:function(e){var t=d(e);if(t)return t;throw new Error("Non-base"+a+" character")}}},hl}function wl(){if(pl)return fl;pl=1;return fl=vl()("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")}var El=So(wl());const Al=La;var Sl={};function kl(e,t,n){return t<=e&&e<=n}function Tl(e){if(void 0===e)return{};if(e===Object(e))return e;throw TypeError("Could not convert argument to dictionary")}function Il(e){this.tokens=[].slice.call(e)}Il.prototype={endOfStream:function(){return!this.tokens.length},read:function(){return this.tokens.length?this.tokens.shift():-1},prepend:function(e){if(Array.isArray(e))for(var t=e;t.length;)this.tokens.unshift(t.pop());else this.tokens.unshift(e)},push:function(e){if(Array.isArray(e))for(var t=e;t.length;)this.tokens.push(t.shift());else this.tokens.push(e)}};var Cl=-1;function Nl(e,t){if(e)throw TypeError("Decoder error");return t||65533}var _l="utf-8";function xl(e,t){if(!(this instanceof xl))return new xl(e,t);if((e=void 0!==e?String(e).toLowerCase():_l)!==_l)throw new Error("Encoding not supported. Only utf-8 is supported");t=Tl(t),this._streaming=!1,this._BOMseen=!1,this._decoder=null,this._fatal=Boolean(t.fatal),this._ignoreBOM=Boolean(t.ignoreBOM),Object.defineProperty(this,"encoding",{value:"utf-8"}),Object.defineProperty(this,"fatal",{value:this._fatal}),Object.defineProperty(this,"ignoreBOM",{value:this._ignoreBOM})}function Rl(e,t){if(!(this instanceof Rl))return new Rl(e,t);if((e=void 0!==e?String(e).toLowerCase():_l)!==_l)throw new Error("Encoding not supported. Only utf-8 is supported");t=Tl(t),this._streaming=!1,this._encoder=null,this._options={fatal:Boolean(t.fatal)},Object.defineProperty(this,"encoding",{value:"utf-8"})}function Bl(e){var t=e.fatal,n=0,r=0,s=0,i=128,o=191;this.handler=function(e,a){if(-1===a&&0!==s)return s=0,Nl(t);if(-1===a)return Cl;if(0===s){if(kl(a,0,127))return a;if(kl(a,194,223))s=1,n=a-192;else if(kl(a,224,239))224===a&&(i=160),237===a&&(o=159),s=2,n=a-224;else{if(!kl(a,240,244))return Nl(t);240===a&&(i=144),244===a&&(o=143),s=3,n=a-240}return n<<=6*s,null}if(!kl(a,i,o))return n=s=r=0,i=128,o=191,e.prepend(a),Nl(t);if(i=128,o=191,n+=a-128<<6*(s-(r+=1)),r!==s)return null;var c=n;return n=s=r=0,c}}function Dl(e){e.fatal,this.handler=function(e,t){if(-1===t)return Cl;if(kl(t,0,127))return t;var n,r;kl(t,128,2047)?(n=1,r=192):kl(t,2048,65535)?(n=2,r=224):kl(t,65536,1114111)&&(n=3,r=240);for(var s=[(t>>6*n)+r];n>0;){var i=t>>6*(n-1);s.push(128|63&i),n-=1}return s}}xl.prototype={decode:function(e,t){var n;n="object"==typeof e&&e instanceof ArrayBuffer?new Uint8Array(e):"object"==typeof e&&"buffer"in e&&e.buffer instanceof ArrayBuffer?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(0),t=Tl(t),this._streaming||(this._decoder=new Bl({fatal:this._fatal}),this._BOMseen=!1),this._streaming=Boolean(t.stream);for(var r,s=new Il(n),i=[];!s.endOfStream()&&(r=this._decoder.handler(s,s.read()))!==Cl;)null!==r&&(Array.isArray(r)?i.push.apply(i,r):i.push(r));if(!this._streaming){do{if((r=this._decoder.handler(s,s.read()))===Cl)break;null!==r&&(Array.isArray(r)?i.push.apply(i,r):i.push(r))}while(!s.endOfStream());this._decoder=null}return i.length&&(-1===["utf-8"].indexOf(this.encoding)||this._ignoreBOM||this._BOMseen||(65279===i[0]?(this._BOMseen=!0,i.shift()):this._BOMseen=!0)),function(e){for(var t="",n=0;n<e.length;++n){var r=e[n];r<=65535?t+=String.fromCharCode(r):(r-=65536,t+=String.fromCharCode(55296+(r>>10),56320+(1023&r)))}return t}(i)}},Rl.prototype={encode:function(e,t){e=e?String(e):"",t=Tl(t),this._streaming||(this._encoder=new Dl(this._options)),this._streaming=Boolean(t.stream);for(var n,r=[],s=new Il(function(e){for(var t=String(e),n=t.length,r=0,s=[];r<n;){var i=t.charCodeAt(r);if(i<55296||i>57343)s.push(i);else if(56320<=i&&i<=57343)s.push(65533);else if(55296<=i&&i<=56319)if(r===n-1)s.push(65533);else{var o=e.charCodeAt(r+1);if(56320<=o&&o<=57343){var a=1023&i,c=1023&o;s.push(65536+(a<<10)+c),r+=1}else s.push(65533)}r+=1}return s}(e));!s.endOfStream()&&(n=this._encoder.handler(s,s.read()))!==Cl;)Array.isArray(n)?r.push.apply(r,n):r.push(n);if(!this._streaming){for(;(n=this._encoder.handler(s,s.read()))!==Cl;)Array.isArray(n)?r.push.apply(r,n):r.push(n);this._encoder=null}return new Uint8Array(r)}};var Ol,Ml=ko(Object.freeze({__proto__:null,TextDecoder:xl,TextEncoder:Rl}));function Ll(){if(Ol)return Sl;Ol=1;var e=Sl&&Sl.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),t=Sl&&Sl.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=Sl&&Sl.__decorate||function(e,t,n,r){var s,i=arguments.length,o=i<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(s=e[a])&&(o=(i<3?s(o):i>3?s(t,n,o):s(t,n))||o);return i>3&&o&&Object.defineProperty(t,n,o),o},r=Sl&&Sl.__importStar||function(n){if(n&&n.__esModule)return n;var r={};if(null!=n)for(var s in n)"default"!==s&&Object.hasOwnProperty.call(n,s)&&e(r,n,s);return t(r,n),r},s=Sl&&Sl.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Sl,"__esModule",{value:!0}),Sl.deserializeUnchecked=Sl.deserialize=Sl.serialize=Sl.BinaryReader=Sl.BinaryWriter=Sl.BorshError=Sl.baseDecode=Sl.baseEncode=void 0;const i=s(ul()),o=s(wl()),a=r(Ml),c=new("function"!=typeof TextDecoder?a.TextDecoder:TextDecoder)("utf-8",{fatal:!0});Sl.baseEncode=function(e){return"string"==typeof e&&(e=Buffer.from(e,"utf8")),o.default.encode(Buffer.from(e))},Sl.baseDecode=function(e){return Buffer.from(o.default.decode(e))};const l=1024;class u extends Error{constructor(e){super(e),this.fieldPath=[],this.originalMessage=e}addToFieldPath(e){this.fieldPath.splice(0,0,e),this.message=this.originalMessage+": "+this.fieldPath.join(".")}}Sl.BorshError=u;class d{constructor(){this.buf=Buffer.alloc(l),this.length=0}maybeResize(){this.buf.length<16+this.length&&(this.buf=Buffer.concat([this.buf,Buffer.alloc(l)]))}writeU8(e){this.maybeResize(),this.buf.writeUInt8(e,this.length),this.length+=1}writeU16(e){this.maybeResize(),this.buf.writeUInt16LE(e,this.length),this.length+=2}writeU32(e){this.maybeResize(),this.buf.writeUInt32LE(e,this.length),this.length+=4}writeU64(e){this.maybeResize(),this.writeBuffer(Buffer.from(new i.default(e).toArray("le",8)))}writeU128(e){this.maybeResize(),this.writeBuffer(Buffer.from(new i.default(e).toArray("le",16)))}writeU256(e){this.maybeResize(),this.writeBuffer(Buffer.from(new i.default(e).toArray("le",32)))}writeU512(e){this.maybeResize(),this.writeBuffer(Buffer.from(new i.default(e).toArray("le",64)))}writeBuffer(e){this.buf=Buffer.concat([Buffer.from(this.buf.subarray(0,this.length)),e,Buffer.alloc(l)]),this.length+=e.length}writeString(e){this.maybeResize();const t=Buffer.from(e,"utf8");this.writeU32(t.length),this.writeBuffer(t)}writeFixedArray(e){this.writeBuffer(Buffer.from(e))}writeArray(e,t){this.maybeResize(),this.writeU32(e.length);for(const n of e)this.maybeResize(),t(n)}toArray(){return this.buf.subarray(0,this.length)}}function h(e,t,n){const r=n.value;n.value=function(...e){try{return r.apply(this,e)}catch(e){if(e instanceof RangeError){const t=e.code;if(["ERR_BUFFER_OUT_OF_BOUNDS","ERR_OUT_OF_RANGE"].indexOf(t)>=0)throw new u("Reached the end of buffer when deserializing")}throw e}}}Sl.BinaryWriter=d;class g{constructor(e){this.buf=e,this.offset=0}readU8(){const e=this.buf.readUInt8(this.offset);return this.offset+=1,e}readU16(){const e=this.buf.readUInt16LE(this.offset);return this.offset+=2,e}readU32(){const e=this.buf.readUInt32LE(this.offset);return this.offset+=4,e}readU64(){const e=this.readBuffer(8);return new i.default(e,"le")}readU128(){const e=this.readBuffer(16);return new i.default(e,"le")}readU256(){const e=this.readBuffer(32);return new i.default(e,"le")}readU512(){const e=this.readBuffer(64);return new i.default(e,"le")}readBuffer(e){if(this.offset+e>this.buf.length)throw new u(`Expected buffer length ${e} isn't within bounds`);const t=this.buf.slice(this.offset,this.offset+e);return this.offset+=e,t}readString(){const e=this.readU32(),t=this.readBuffer(e);try{return c.decode(t)}catch(e){throw new u(`Error decoding UTF-8 string: ${e}`)}}readFixedArray(e){return new Uint8Array(this.readBuffer(e))}readArray(e){const t=this.readU32(),n=Array();for(let r=0;r<t;++r)n.push(e());return n}}function f(e){return e.charAt(0).toUpperCase()+e.slice(1)}function p(e,t,n,r,s){try{if("string"==typeof r)s[`write${f(r)}`](n);else if(r instanceof Array)if("number"==typeof r[0]){if(n.length!==r[0])throw new u(`Expecting byte array of length ${r[0]}, but got ${n.length} bytes`);s.writeFixedArray(n)}else if(2===r.length&&"number"==typeof r[1]){if(n.length!==r[1])throw new u(`Expecting byte array of length ${r[1]}, but got ${n.length} bytes`);for(let t=0;t<r[1];t++)p(e,null,n[t],r[0],s)}else s.writeArray(n,n=>{p(e,t,n,r[0],s)});else if(void 0!==r.kind)switch(r.kind){case"option":null==n?s.writeU8(0):(s.writeU8(1),p(e,t,n,r.type,s));break;case"map":s.writeU32(n.size),n.forEach((n,i)=>{p(e,t,i,r.key,s),p(e,t,n,r.value,s)});break;default:throw new u(`FieldType ${r} unrecognized`)}else m(e,n,s)}catch(e){throw e instanceof u&&e.addToFieldPath(t),e}}function m(e,t,n){if("function"==typeof t.borshSerialize)return void t.borshSerialize(n);const r=e.get(t.constructor);if(!r)throw new u(`Class ${t.constructor.name} is missing in schema`);if("struct"===r.kind)r.fields.map(([r,s])=>{p(e,r,t[r],s,n)});else{if("enum"!==r.kind)throw new u(`Unexpected schema kind: ${r.kind} for ${t.constructor.name}`);{const s=t[r.field];for(let i=0;i<r.values.length;++i){const[o,a]=r.values[i];if(o===s){n.writeU8(i),p(e,o,t[o],a,n);break}}}}}function y(e,t,n,r){try{if("string"==typeof n)return r[`read${f(n)}`]();if(n instanceof Array){if("number"==typeof n[0])return r.readFixedArray(n[0]);if("number"==typeof n[1]){const t=[];for(let s=0;s<n[1];s++)t.push(y(e,null,n[0],r));return t}return r.readArray(()=>y(e,t,n[0],r))}if("option"===n.kind){return r.readU8()?y(e,t,n.type,r):void 0}if("map"===n.kind){let s=new Map;const i=r.readU32();for(let o=0;o<i;o++){const i=y(e,t,n.key,r),o=y(e,t,n.value,r);s.set(i,o)}return s}return b(e,n,r)}catch(e){throw e instanceof u&&e.addToFieldPath(t),e}}function b(e,t,n){if("function"==typeof t.borshDeserialize)return t.borshDeserialize(n);const r=e.get(t);if(!r)throw new u(`Class ${t.name} is missing in schema`);if("struct"===r.kind){const r={};for(const[s,i]of e.get(t).fields)r[s]=y(e,s,i,n);return new t(r)}if("enum"===r.kind){const s=n.readU8();if(s>=r.values.length)throw new u(`Enum index: ${s} is out of range`);const[i,o]=r.values[s],a=y(e,i,o,n);return new t({[i]:a})}throw new u(`Unexpected schema kind: ${r.kind} for ${t.constructor.name}`)}return n([h],g.prototype,"readU8",null),n([h],g.prototype,"readU16",null),n([h],g.prototype,"readU32",null),n([h],g.prototype,"readU64",null),n([h],g.prototype,"readU128",null),n([h],g.prototype,"readU256",null),n([h],g.prototype,"readU512",null),n([h],g.prototype,"readString",null),n([h],g.prototype,"readFixedArray",null),n([h],g.prototype,"readArray",null),Sl.BinaryReader=g,Sl.serialize=function(e,t,n=d){const r=new n;return m(e,t,r),r.toArray()},Sl.deserialize=function(e,t,n,r=g){const s=new r(n),i=b(e,t,s);if(s.offset<n.length)throw new u(`Unexpected ${n.length-s.offset} bytes after deserialized data`);return i},Sl.deserializeUnchecked=function(e,t,n,r=g){return b(e,t,new r(n))},Sl}var Ul,Pl=Ll(),Fl={};function $l(){if(Ul)return Fl;Ul=1,Object.defineProperty(Fl,"__esModule",{value:!0}),Fl.s16=Fl.s8=Fl.nu64be=Fl.u48be=Fl.u40be=Fl.u32be=Fl.u24be=Fl.u16be=Fl.nu64=Fl.u48=Fl.u40=Fl.u32=Fl.u24=Fl.u16=Fl.u8=Fl.offset=Fl.greedy=Fl.Constant=Fl.UTF8=Fl.CString=Fl.Blob=Fl.Boolean=Fl.BitField=Fl.BitStructure=Fl.VariantLayout=Fl.Union=Fl.UnionLayoutDiscriminator=Fl.UnionDiscriminator=Fl.Structure=Fl.Sequence=Fl.DoubleBE=Fl.Double=Fl.FloatBE=Fl.Float=Fl.NearInt64BE=Fl.NearInt64=Fl.NearUInt64BE=Fl.NearUInt64=Fl.IntBE=Fl.Int=Fl.UIntBE=Fl.UInt=Fl.OffsetLayout=Fl.GreedyCount=Fl.ExternalLayout=Fl.bindConstructorLayout=Fl.nameWithProperty=Fl.Layout=Fl.uint8ArrayToBuffer=Fl.checkUint8Array=void 0,Fl.constant=Fl.utf8=Fl.cstr=Fl.blob=Fl.unionLayoutDiscriminator=Fl.union=Fl.seq=Fl.bits=Fl.struct=Fl.f64be=Fl.f64=Fl.f32be=Fl.f32=Fl.ns64be=Fl.s48be=Fl.s40be=Fl.s32be=Fl.s24be=Fl.s16be=Fl.ns64=Fl.s48=Fl.s40=Fl.s32=Fl.s24=void 0;const e=Do();function t(e){if(!(e instanceof Uint8Array))throw new TypeError("b must be a Uint8Array")}function n(n){return t(n),e.Buffer.from(n.buffer,n.byteOffset,n.length)}Fl.checkUint8Array=t,Fl.uint8ArrayToBuffer=n;let r=class{constructor(e,t){if(!Number.isInteger(e))throw new TypeError("span must be an integer");this.span=e,this.property=t}makeDestinationObject(){return{}}getSpan(e,t){if(0>this.span)throw new RangeError("indeterminate span");return this.span}replicate(e){const t=Object.create(this.constructor.prototype);return Object.assign(t,this),t.property=e,t}fromArray(e){}};function s(e,t){return t.property?e+"["+t.property+"]":e}Fl.Layout=r,Fl.nameWithProperty=s,Fl.bindConstructorLayout=function(e,t){if("function"!=typeof e)throw new TypeError("Class must be constructor");if(Object.prototype.hasOwnProperty.call(e,"layout_"))throw new Error("Class is already bound to a layout");if(!(t&&t instanceof r))throw new TypeError("layout must be a Layout");if(Object.prototype.hasOwnProperty.call(t,"boundConstructor_"))throw new Error("layout is already bound to a constructor");e.layout_=t,t.boundConstructor_=e,t.makeDestinationObject=()=>new e,Object.defineProperty(e.prototype,"encode",{value(e,n){return t.encode(this,e,n)},writable:!0}),Object.defineProperty(e,"decode",{value:(e,n)=>t.decode(e,n),writable:!0})};class i extends r{isCount(){throw new Error("ExternalLayout is abstract")}}Fl.ExternalLayout=i;class o extends i{constructor(e=1,t){if(!Number.isInteger(e)||0>=e)throw new TypeError("elementSpan must be a (positive) integer");super(-1,t),this.elementSpan=e}isCount(){return!0}decode(e,n=0){t(e);const r=e.length-n;return Math.floor(r/this.elementSpan)}encode(e,t,n){return 0}}Fl.GreedyCount=o;class a extends i{constructor(e,t=0,n){if(!(e instanceof r))throw new TypeError("layout must be a Layout");if(!Number.isInteger(t))throw new TypeError("offset must be integer or undefined");super(e.span,n||e.property),this.layout=e,this.offset=t}isCount(){return this.layout instanceof c||this.layout instanceof l}decode(e,t=0){return this.layout.decode(e,t+this.offset)}encode(e,t,n=0){return this.layout.encode(e,t,n+this.offset)}}Fl.OffsetLayout=a;class c extends r{constructor(e,t){if(super(e,t),6<this.span)throw new RangeError("span must not exceed 6 bytes")}decode(e,t=0){return n(e).readUIntLE(t,this.span)}encode(e,t,r=0){return n(t).writeUIntLE(e,r,this.span),this.span}}Fl.UInt=c;class l extends r{constructor(e,t){if(super(e,t),6<this.span)throw new RangeError("span must not exceed 6 bytes")}decode(e,t=0){return n(e).readUIntBE(t,this.span)}encode(e,t,r=0){return n(t).writeUIntBE(e,r,this.span),this.span}}Fl.UIntBE=l;class u extends r{constructor(e,t){if(super(e,t),6<this.span)throw new RangeError("span must not exceed 6 bytes")}decode(e,t=0){return n(e).readIntLE(t,this.span)}encode(e,t,r=0){return n(t).writeIntLE(e,r,this.span),this.span}}Fl.Int=u;class d extends r{constructor(e,t){if(super(e,t),6<this.span)throw new RangeError("span must not exceed 6 bytes")}decode(e,t=0){return n(e).readIntBE(t,this.span)}encode(e,t,r=0){return n(t).writeIntBE(e,r,this.span),this.span}}Fl.IntBE=d;const h=Math.pow(2,32);function g(e){const t=Math.floor(e/h);return{hi32:t,lo32:e-t*h}}function f(e,t){return e*h+t}class p extends r{constructor(e){super(8,e)}decode(e,t=0){const r=n(e),s=r.readUInt32LE(t);return f(r.readUInt32LE(t+4),s)}encode(e,t,r=0){const s=g(e),i=n(t);return i.writeUInt32LE(s.lo32,r),i.writeUInt32LE(s.hi32,r+4),8}}Fl.NearUInt64=p;class m extends r{constructor(e){super(8,e)}decode(e,t=0){const r=n(e);return f(r.readUInt32BE(t),r.readUInt32BE(t+4))}encode(e,t,r=0){const s=g(e),i=n(t);return i.writeUInt32BE(s.hi32,r),i.writeUInt32BE(s.lo32,r+4),8}}Fl.NearUInt64BE=m;class y extends r{constructor(e){super(8,e)}decode(e,t=0){const r=n(e),s=r.readUInt32LE(t);return f(r.readInt32LE(t+4),s)}encode(e,t,r=0){const s=g(e),i=n(t);return i.writeUInt32LE(s.lo32,r),i.writeInt32LE(s.hi32,r+4),8}}Fl.NearInt64=y;class b extends r{constructor(e){super(8,e)}decode(e,t=0){const r=n(e);return f(r.readInt32BE(t),r.readUInt32BE(t+4))}encode(e,t,r=0){const s=g(e),i=n(t);return i.writeInt32BE(s.hi32,r),i.writeUInt32BE(s.lo32,r+4),8}}Fl.NearInt64BE=b;class v extends r{constructor(e){super(4,e)}decode(e,t=0){return n(e).readFloatLE(t)}encode(e,t,r=0){return n(t).writeFloatLE(e,r),4}}Fl.Float=v;class w extends r{constructor(e){super(4,e)}decode(e,t=0){return n(e).readFloatBE(t)}encode(e,t,r=0){return n(t).writeFloatBE(e,r),4}}Fl.FloatBE=w;class E extends r{constructor(e){super(8,e)}decode(e,t=0){return n(e).readDoubleLE(t)}encode(e,t,r=0){return n(t).writeDoubleLE(e,r),8}}Fl.Double=E;class A extends r{constructor(e){super(8,e)}decode(e,t=0){return n(e).readDoubleBE(t)}encode(e,t,r=0){return n(t).writeDoubleBE(e,r),8}}Fl.DoubleBE=A;class S extends r{constructor(e,t,n){if(!(e instanceof r))throw new TypeError("elementLayout must be a Layout");if(!(t instanceof i&&t.isCount()||Number.isInteger(t)&&0<=t))throw new TypeError("count must be non-negative integer or an unsigned integer ExternalLayout");let s=-1;!(t instanceof i)&&0<e.span&&(s=t*e.span),super(s,n),this.elementLayout=e,this.count=t}getSpan(e,t=0){if(0<=this.span)return this.span;let n=0,r=this.count;if(r instanceof i&&(r=r.decode(e,t)),0<this.elementLayout.span)n=r*this.elementLayout.span;else{let s=0;for(;s<r;)n+=this.elementLayout.getSpan(e,t+n),++s}return n}decode(e,t=0){const n=[];let r=0,s=this.count;for(s instanceof i&&(s=s.decode(e,t));r<s;)n.push(this.elementLayout.decode(e,t)),t+=this.elementLayout.getSpan(e,t),r+=1;return n}encode(e,t,n=0){const r=this.elementLayout,s=e.reduce((e,s)=>e+r.encode(s,t,n+e),0);return this.count instanceof i&&this.count.encode(e.length,t,n),s}}Fl.Sequence=S;class k extends r{constructor(e,t,n){if(!Array.isArray(e)||!e.reduce((e,t)=>e&&t instanceof r,!0))throw new TypeError("fields must be array of Layout instances");"boolean"==typeof t&&void 0===n&&(n=t,t=void 0);for(const t of e)if(0>t.span&&void 0===t.property)throw new Error("fields cannot contain unnamed variable-length layout");let s=-1;try{s=e.reduce((e,t)=>e+t.getSpan(),0)}catch(e){}super(s,t),this.fields=e,this.decodePrefixes=!!n}getSpan(e,t=0){if(0<=this.span)return this.span;let n=0;try{n=this.fields.reduce((n,r)=>{const s=r.getSpan(e,t);return t+=s,n+s},0)}catch(e){throw new RangeError("indeterminate span")}return n}decode(e,n=0){t(e);const r=this.makeDestinationObject();for(const t of this.fields)if(void 0!==t.property&&(r[t.property]=t.decode(e,n)),n+=t.getSpan(e,n),this.decodePrefixes&&e.length===n)break;return r}encode(e,t,n=0){const r=n;let s=0,i=0;for(const r of this.fields){let o=r.span;if(i=0<o?o:0,void 0!==r.property){const s=e[r.property];void 0!==s&&(i=r.encode(s,t,n),0>o&&(o=r.getSpan(t,n)))}s=n,n+=o}return s+i-r}fromArray(e){const t=this.makeDestinationObject();for(const n of this.fields)void 0!==n.property&&0<e.length&&(t[n.property]=e.shift());return t}layoutFor(e){if("string"!=typeof e)throw new TypeError("property must be string");for(const t of this.fields)if(t.property===e)return t}offsetOf(e){if("string"!=typeof e)throw new TypeError("property must be string");let t=0;for(const n of this.fields){if(n.property===e)return t;0>n.span?t=-1:0<=t&&(t+=n.span)}}}Fl.Structure=k;class T{constructor(e){this.property=e}decode(e,t){throw new Error("UnionDiscriminator is abstract")}encode(e,t,n){throw new Error("UnionDiscriminator is abstract")}}Fl.UnionDiscriminator=T;class I extends T{constructor(e,t){if(!(e instanceof i&&e.isCount()))throw new TypeError("layout must be an unsigned integer ExternalLayout");super(t||e.property||"variant"),this.layout=e}decode(e,t){return this.layout.decode(e,t)}encode(e,t,n){return this.layout.encode(e,t,n)}}Fl.UnionLayoutDiscriminator=I;class C extends r{constructor(e,t,n){let s;if(e instanceof c||e instanceof l)s=new I(new a(e));else if(e instanceof i&&e.isCount())s=new I(e);else{if(!(e instanceof T))throw new TypeError("discr must be a UnionDiscriminator or an unsigned integer layout");s=e}if(void 0===t&&(t=null),!(null===t||t instanceof r))throw new TypeError("defaultLayout must be null or a Layout");if(null!==t){if(0>t.span)throw new Error("defaultLayout must have constant span");void 0===t.property&&(t=t.replicate("content"))}let o=-1;t&&(o=t.span,0<=o&&(e instanceof c||e instanceof l)&&(o+=s.layout.span)),super(o,n),this.discriminator=s,this.usesPrefixDiscriminator=e instanceof c||e instanceof l,this.defaultLayout=t,this.registry={};let u=this.defaultGetSourceVariant.bind(this);this.getSourceVariant=function(e){return u(e)},this.configGetSourceVariant=function(e){u=e.bind(this)}}getSpan(e,t=0){if(0<=this.span)return this.span;const n=this.getVariant(e,t);if(!n)throw new Error("unable to determine span for unrecognized variant");return n.getSpan(e,t)}defaultGetSourceVariant(e){if(Object.prototype.hasOwnProperty.call(e,this.discriminator.property)){if(this.defaultLayout&&this.defaultLayout.property&&Object.prototype.hasOwnProperty.call(e,this.defaultLayout.property))return;const t=this.registry[e[this.discriminator.property]];if(t&&(!t.layout||t.property&&Object.prototype.hasOwnProperty.call(e,t.property)))return t}else for(const t in this.registry){const n=this.registry[t];if(n.property&&Object.prototype.hasOwnProperty.call(e,n.property))return n}throw new Error("unable to infer src variant")}decode(e,t=0){let n;const r=this.discriminator,s=r.decode(e,t),i=this.registry[s];if(void 0===i){const i=this.defaultLayout;let o=0;this.usesPrefixDiscriminator&&(o=r.layout.span),n=this.makeDestinationObject(),n[r.property]=s,n[i.property]=i.decode(e,t+o)}else n=i.decode(e,t);return n}encode(e,t,n=0){const r=this.getSourceVariant(e);if(void 0===r){const r=this.discriminator,s=this.defaultLayout;let i=0;return this.usesPrefixDiscriminator&&(i=r.layout.span),r.encode(e[r.property],t,n),i+s.encode(e[s.property],t,n+i)}return r.encode(e,t,n)}addVariant(e,t,n){const r=new N(this,e,t,n);return this.registry[e]=r,r}getVariant(e,t=0){let n;return n=e instanceof Uint8Array?this.discriminator.decode(e,t):e,this.registry[n]}}Fl.Union=C;class N extends r{constructor(e,t,n,s){if(!(e instanceof C))throw new TypeError("union must be a Union");if(!Number.isInteger(t)||0>t)throw new TypeError("variant must be a (non-negative) integer");if("string"==typeof n&&void 0===s&&(s=n,n=null),n){if(!(n instanceof r))throw new TypeError("layout must be a Layout");if(null!==e.defaultLayout&&0<=n.span&&n.span>e.defaultLayout.span)throw new Error("variant span exceeds span of containing union");if("string"!=typeof s)throw new TypeError("variant must have a String property")}let i=e.span;0>e.span&&(i=n?n.span:0,0<=i&&e.usesPrefixDiscriminator&&(i+=e.discriminator.layout.span)),super(i,s),this.union=e,this.variant=t,this.layout=n||null}getSpan(e,t=0){if(0<=this.span)return this.span;let n=0;this.union.usesPrefixDiscriminator&&(n=this.union.discriminator.layout.span);let r=0;return this.layout&&(r=this.layout.getSpan(e,t+n)),n+r}decode(e,t=0){const n=this.makeDestinationObject();if(this!==this.union.getVariant(e,t))throw new Error("variant mismatch");let r=0;return this.union.usesPrefixDiscriminator&&(r=this.union.discriminator.layout.span),this.layout?n[this.property]=this.layout.decode(e,t+r):this.property?n[this.property]=!0:this.union.usesPrefixDiscriminator&&(n[this.union.discriminator.property]=this.variant),n}encode(e,t,n=0){let r=0;if(this.union.usesPrefixDiscriminator&&(r=this.union.discriminator.layout.span),this.layout&&!Object.prototype.hasOwnProperty.call(e,this.property))throw new TypeError("variant lacks property "+this.property);this.union.discriminator.encode(this.variant,t,n);let s=r;if(this.layout&&(this.layout.encode(e[this.property],t,n+r),s+=this.layout.getSpan(t,n+r),0<=this.union.span&&s>this.union.span))throw new Error("encoded variant overruns containing union");return s}fromArray(e){if(this.layout)return this.layout.fromArray(e)}}function _(e){return 0>e&&(e+=4294967296),e}Fl.VariantLayout=N;class x extends r{constructor(e,t,n){if(!(e instanceof c||e instanceof l))throw new TypeError("word must be a UInt or UIntBE layout");if("string"==typeof t&&void 0===n&&(n=t,t=!1),4<e.span)throw new RangeError("word cannot exceed 32 bits");super(e.span,n),this.word=e,this.msb=!!t,this.fields=[];let r=0;this._packedSetValue=function(e){return r=_(e),this},this._packedGetValue=function(){return r}}decode(e,t=0){const n=this.makeDestinationObject(),r=this.word.decode(e,t);this._packedSetValue(r);for(const t of this.fields)void 0!==t.property&&(n[t.property]=t.decode(e));return n}encode(e,t,n=0){const r=this.word.decode(t,n);this._packedSetValue(r);for(const t of this.fields)if(void 0!==t.property){const n=e[t.property];void 0!==n&&t.encode(n)}return this.word.encode(this._packedGetValue(),t,n)}addField(e,t){const n=new R(this,e,t);return this.fields.push(n),n}addBoolean(e){const t=new B(this,e);return this.fields.push(t),t}fieldFor(e){if("string"!=typeof e)throw new TypeError("property must be string");for(const t of this.fields)if(t.property===e)return t}}Fl.BitStructure=x;class R{constructor(e,t,n){if(!(e instanceof x))throw new TypeError("container must be a BitStructure");if(!Number.isInteger(t)||0>=t)throw new TypeError("bits must be positive integer");const r=8*e.span,s=e.fields.reduce((e,t)=>e+t.bits,0);if(t+s>r)throw new Error("bits too long for span remainder ("+(r-s)+" of "+r+" remain)");this.container=e,this.bits=t,this.valueMask=(1<<t)-1,32===t&&(this.valueMask=4294967295),this.start=s,this.container.msb&&(this.start=r-s-t),this.wordMask=_(this.valueMask<<this.start),this.property=n}decode(e,t){return _(this.container._packedGetValue()&this.wordMask)>>>this.start}encode(e){if("number"!=typeof e||!Number.isInteger(e)||e!==_(e&this.valueMask))throw new TypeError(s("BitField.encode",this)+" value must be integer not exceeding "+this.valueMask);const t=this.container._packedGetValue(),n=_(e<<this.start);this.container._packedSetValue(_(t&~this.wordMask)|n)}}Fl.BitField=R;class B extends R{constructor(e,t){super(e,1,t)}decode(e,t){return!!super.decode(e,t)}encode(e){"boolean"==typeof e&&(e=+e),super.encode(e)}}Fl.Boolean=B;class D extends r{constructor(e,t){if(!(e instanceof i&&e.isCount()||Number.isInteger(e)&&0<=e))throw new TypeError("length must be positive integer or an unsigned integer ExternalLayout");let n=-1;e instanceof i||(n=e),super(n,t),this.length=e}getSpan(e,t){let n=this.span;return 0>n&&(n=this.length.decode(e,t)),n}decode(e,t=0){let r=this.span;return 0>r&&(r=this.length.decode(e,t)),n(e).slice(t,t+r)}encode(e,t,r){let o=this.length;if(this.length instanceof i&&(o=e.length),!(e instanceof Uint8Array&&o===e.length))throw new TypeError(s("Blob.encode",this)+" requires (length "+o+") Uint8Array as src");if(r+o>t.length)throw new RangeError("encoding overruns Uint8Array");const a=n(e);return n(t).write(a.toString("hex"),r,o,"hex"),this.length instanceof i&&this.length.encode(o,t,r),o}}Fl.Blob=D;class O extends r{constructor(e){super(-1,e)}getSpan(e,n=0){t(e);let r=n;for(;r<e.length&&0!==e[r];)r+=1;return 1+r-n}decode(e,t=0){const r=this.getSpan(e,t);return n(e).slice(t,t+r-1).toString("utf-8")}encode(t,r,s=0){"string"!=typeof t&&(t=String(t));const i=e.Buffer.from(t,"utf8"),o=i.length;if(s+o>r.length)throw new RangeError("encoding overruns Buffer");const a=n(r);return i.copy(a,s),a[s+o]=0,o+1}}Fl.CString=O;class M extends r{constructor(e,t){if("string"==typeof e&&void 0===t&&(t=e,e=void 0),void 0===e)e=-1;else if(!Number.isInteger(e))throw new TypeError("maxSpan must be an integer");super(-1,t),this.maxSpan=e}getSpan(e,n=0){return t(e),e.length-n}decode(e,t=0){const r=this.getSpan(e,t);if(0<=this.maxSpan&&this.maxSpan<r)throw new RangeError("text length exceeds maxSpan");return n(e).slice(t,t+r).toString("utf-8")}encode(t,r,s=0){"string"!=typeof t&&(t=String(t));const i=e.Buffer.from(t,"utf8"),o=i.length;if(0<=this.maxSpan&&this.maxSpan<o)throw new RangeError("text length exceeds maxSpan");if(s+o>r.length)throw new RangeError("encoding overruns Buffer");return i.copy(n(r),s),o}}Fl.UTF8=M;class L extends r{constructor(e,t){super(0,t),this.value=e}decode(e,t){return this.value}encode(e,t,n){return 0}}return Fl.Constant=L,Fl.greedy=(e,t)=>new o(e,t),Fl.offset=(e,t,n)=>new a(e,t,n),Fl.u8=e=>new c(1,e),Fl.u16=e=>new c(2,e),Fl.u24=e=>new c(3,e),Fl.u32=e=>new c(4,e),Fl.u40=e=>new c(5,e),Fl.u48=e=>new c(6,e),Fl.nu64=e=>new p(e),Fl.u16be=e=>new l(2,e),Fl.u24be=e=>new l(3,e),Fl.u32be=e=>new l(4,e),Fl.u40be=e=>new l(5,e),Fl.u48be=e=>new l(6,e),Fl.nu64be=e=>new m(e),Fl.s8=e=>new u(1,e),Fl.s16=e=>new u(2,e),Fl.s24=e=>new u(3,e),Fl.s32=e=>new u(4,e),Fl.s40=e=>new u(5,e),Fl.s48=e=>new u(6,e),Fl.ns64=e=>new y(e),Fl.s16be=e=>new d(2,e),Fl.s24be=e=>new d(3,e),Fl.s32be=e=>new d(4,e),Fl.s40be=e=>new d(5,e),Fl.s48be=e=>new d(6,e),Fl.ns64be=e=>new b(e),Fl.f32=e=>new v(e),Fl.f32be=e=>new w(e),Fl.f64=e=>new E(e),Fl.f64be=e=>new A(e),Fl.struct=(e,t,n)=>new k(e,t,n),Fl.bits=(e,t,n)=>new x(e,t,n),Fl.seq=(e,t,n)=>new S(e,t,n),Fl.union=(e,t,n)=>new C(e,t,n),Fl.unionLayoutDiscriminator=(e,t)=>new I(e,t),Fl.blob=(e,t)=>new D(e,t),Fl.cstr=e=>new O(e),Fl.utf8=(e,t)=>new M(e,t),Fl.constant=(e,t)=>new L(e,t),Fl}var Kl=$l(),Gl=1,Hl=2,Wl=3,ql=4,zl=5,Vl=6,jl=7,Xl=8,Yl=9,Jl=10,Ql=-32700,Zl=-32603,eu=-32602,tu=-32601,nu=-32600,ru=-32019,su=-32018,iu=-32017,ou=-32016,au=-32015,cu=-32014,lu=-32013,uu=-32012,du=-32011,hu=-32010,gu=-32009,fu=-32008,pu=-32007,mu=-32006,yu=-32005,bu=-32004,vu=-32003,wu=-32002,Eu=-32001,Au=28e5,Su=2800001,ku=2800002,Tu=2800003,Iu=2800004,Cu=2800005,Nu=2800006,_u=2800007,xu=2800008,Ru=2800009,Bu=2800010,Du=2800011,Ou=323e4,Mu=32300001,Lu=3230002,Uu=3230003,Pu=3230004,Fu=361e4,$u=3610001,Ku=3610002,Gu=3610003,Hu=3610004,Wu=3610005,qu=3610006,zu=3610007,Vu=3611e3,ju=3704e3,Xu=3704001,Yu=3704002,Ju=3704003,Qu=3704004,Zu=4128e3,ed=4128001,td=4128002,nd=4615e3,rd=4615001,sd=4615002,id=4615003,od=4615004,ad=4615005,cd=4615006,ld=4615007,ud=4615008,dd=4615009,hd=4615010,gd=4615011,fd=4615012,pd=4615013,md=4615014,yd=4615015,bd=4615016,vd=4615017,wd=4615018,Ed=4615019,Ad=4615020,Sd=4615021,kd=4615022,Td=4615023,Id=4615024,Cd=4615025,Nd=4615026,_d=4615027,xd=4615028,Rd=4615029,Bd=4615030,Dd=4615031,Od=4615032,Md=4615033,Ld=4615034,Ud=4615035,Pd=4615036,Fd=4615037,$d=4615038,Kd=4615039,Gd=4615040,Hd=4615041,Wd=4615042,qd=4615043,zd=4615044,Vd=4615045,jd=4615046,Xd=4615047,Yd=4615048,Jd=4615049,Qd=4615050,Zd=4615051,eh=4615052,th=4615053,nh=4615054,rh=5508e3,sh=5508001,ih=5508002,oh=5508003,ah=5508004,ch=5508005,lh=5508006,uh=5508007,dh=5508008,hh=5508009,gh=5508010,fh=5508011,ph=5607e3,mh=5607001,yh=5607002,bh=5607003,vh=5607004,wh=5607005,Eh=5607006,Ah=5607007,Sh=5607008,kh=5607009,Th=5607010,Ih=5607011,Ch=5607012,Nh=5607013,_h=5607014,xh=5607015,Rh=5607016,Bh=5607017,Dh=5663e3,Oh=5663001,Mh=5663002,Lh=5663003,Uh=5663004,Ph=5663005,Fh=5663006,$h=5663007,Kh=5663008,Gh=5663009,Hh=5663010,Wh=5663011,qh=5663012,zh=5663013,Vh=5663014,jh=5663015,Xh=5663016,Yh=5663017,Jh=5663018,Qh=5663019,Zh=5663020,eg=5663021,tg=5663022,ng=705e4,rg=7050001,sg=7050002,ig=7050003,og=7050004,ag=7050005,cg=7050006,lg=7050007,ug=7050008,dg=7050009,hg=7050010,gg=7050011,fg=7050012,pg=7050013,mg=7050014,yg=7050015,bg=7050016,vg=7050017,wg=7050018,Eg=7050019,Ag=7050020,Sg=7050021,kg=7050022,Tg=7050023,Ig=7050024,Cg=7050025,Ng=7050026,_g=7050027,xg=7050028,Rg=7050029,Bg=7050030,Dg=7050031,Og=7050032,Mg=7050033,Lg=7050034,Ug=7050035,Pg=7050036,Fg=7618e3,$g=7618001,Kg=7618002,Gg=7618003,Hg=7618004,Wg=7618005,qg=7618006,zg=7618007,Vg=7618008,jg=7618009,Xg=8078e3,Yg=8078001,Jg=8078002,Qg=8078003,Zg=8078004,ef=8078005,tf=8078006,nf=8078007,rf=8078008,sf=8078009,of=8078010,af=8078011,cf=8078012,lf=8078013,uf=8078014,df=8078015,hf=8078016,gf=8078017,ff=8078018,pf=8078019,mf=8078020,yf=8078021,bf=8078022,vf=8078023,wf=81e5,Ef=8100001,Af=8100002,Sf=8100003,kf=819e4,Tf=8190001,If=8190002,Cf=8190003,Nf=8190004,_f=99e5,xf=9900001,Rf=9900002,Bf=9900003,Df=9900004,Of=9900005,Mf=9900006;function Lf(e){if(Array.isArray(e)){return"%5B"+e.map(Lf).join("%2C%20")+"%5D"}return"bigint"==typeof e?`${e}n`:encodeURIComponent(String(null!=e&&null===Object.getPrototypeOf(e)?{...e}:e))}function Uf([e,t]){return`${e}=${Lf(t)}`}var Pf={[Ou]:"Account not found at address: $address",[Pu]:"Not all accounts were decoded. Encoded accounts found at addresses: $addresses.",[Uu]:"Expected decoded account at address: $address",[Lu]:"Failed to decode account data at address: $address",[Mu]:"Accounts not found at addresses: $addresses",[Ru]:"Unable to find a viable program address bump seed.",[ku]:"$putativeAddress is not a base58-encoded address.",[Au]:"Expected base58 encoded address to decode to a byte array of length 32. Actual length: $actualLength.",[Tu]:"The `CryptoKey` must be an `Ed25519` public key.",[Du]:"$putativeOffCurveAddress is not a base58-encoded off-curve address.",[xu]:"Invalid seeds; point must fall off the Ed25519 curve.",[Iu]:"Expected given program derived address to have the following format: [Address, ProgramDerivedAddressBump].",[Nu]:"A maximum of $maxSeeds seeds, including the bump seed, may be supplied when creating an address. Received: $actual.",[_u]:"The seed at index $index with length $actual exceeds the maximum length of $maxSeedLength bytes.",[Cu]:"Expected program derived address bump to be in the range [0, 255], got: $bump.",[Bu]:"Program address cannot end with PDA marker.",[Su]:"Expected base58-encoded address string of length in the range [32, 44]. Actual length: $actualLength.",[ql]:"Expected base58-encoded blockash string of length in the range [32, 44]. Actual length: $actualLength.",[Gl]:"The network has progressed past the last block for which this transaction could have been committed.",[Xg]:"Codec [$codecDescription] cannot decode empty byte arrays.",[bf]:"Enum codec cannot use lexical values [$stringValues] as discriminators. Either remove all lexical values or set `useValuesAsDiscriminators` to `false`.",[mf]:"Sentinel [$hexSentinel] must not be present in encoded bytes [$hexEncodedBytes].",[ef]:"Encoder and decoder must have the same fixed size, got [$encoderFixedSize] and [$decoderFixedSize].",[tf]:"Encoder and decoder must have the same max size, got [$encoderMaxSize] and [$decoderMaxSize].",[Zg]:"Encoder and decoder must either both be fixed-size or variable-size.",[rf]:"Enum discriminator out of range. Expected a number in [$formattedValidDiscriminators], got $discriminator.",[Jg]:"Expected a fixed-size codec, got a variable-size one.",[lf]:"Codec [$codecDescription] expected a positive byte length, got $bytesLength.",[Qg]:"Expected a variable-size codec, got a fixed-size one.",[pf]:"Codec [$codecDescription] expected zero-value [$hexZeroValue] to have the same size as the provided fixed-size item [$expectedSize bytes].",[Yg]:"Codec [$codecDescription] expected $expected bytes, got $bytesLength.",[ff]:"Expected byte array constant [$hexConstant] to be present in data [$hexData] at offset [$offset].",[sf]:"Invalid discriminated union variant. Expected one of [$variants], got $value.",[of]:"Invalid enum variant. Expected one of [$stringValues] or a number in [$formattedNumericalValues], got $variant.",[df]:"Invalid literal union variant. Expected one of [$variants], got $value.",[nf]:"Expected [$codecDescription] to have $expected items, got $actual.",[cf]:"Invalid value $value for base $base with alphabet $alphabet.",[hf]:"Literal union discriminator out of range. Expected a number between $minRange and $maxRange, got $discriminator.",[af]:"Codec [$codecDescription] expected number to be in the range [$min, $max], got $value.",[uf]:"Codec [$codecDescription] expected offset to be in the range [0, $bytesLength], got $offset.",[yf]:"Expected sentinel [$hexSentinel] to be present in decoded bytes [$hexDecodedBytes].",[gf]:"Union variant out of range. Expected an index between $minRange and $maxRange, got $variant.",[vf]:"This decoder expected a byte array of exactly $expectedLength bytes, but $numExcessBytes unexpected excess bytes remained after decoding. Are you sure that you have chosen the correct decoder for this data?",[Vu]:"No random values implementation could be found.",[dd]:"instruction requires an uninitialized account",[Td]:"instruction tries to borrow reference for an account which is already borrowed",[Id]:"instruction left account with an outstanding borrowed reference",[Sd]:"program other than the account's owner changed the size of the account data",[ad]:"account data too small for instruction",[kd]:"instruction expected an executable account",[jd]:"An account does not have enough lamports to be rent-exempt",[Yd]:"Program arithmetic overflowed",[Vd]:"Failed to serialize or deserialize account data: $encodedData",[nh]:"Builtin programs must consume compute units",[Od]:"Cross-program invocation call depth too deep",[$d]:"Computational budget exceeded",[Nd]:"custom program error: #$code",[vd]:"instruction contains duplicate accounts",[Cd]:"instruction modifications of multiply-passed account differ",[Bd]:"executable accounts must be rent exempt",[xd]:"instruction changed executable accounts data",[Rd]:"instruction changed the balance of an executable account",[wd]:"instruction changed executable bit of an account",[md]:"instruction modified data of an account it does not own",[pd]:"instruction spent from the balance of an account it does not own",[rd]:"generic instruction error",[Qd]:"Provided owner is not allowed",[qd]:"Account is immutable",[zd]:"Incorrect authority provided",[ld]:"incorrect program id for instruction",[cd]:"insufficient funds for instruction",[od]:"invalid account data for instruction",[Xd]:"Invalid account owner",[sd]:"invalid program argument",[_d]:"program returned invalid error code",[id]:"invalid instruction data",[Fd]:"Failed to reallocate account data",[Pd]:"Provided seeds do not result in a valid address",[Zd]:"Accounts data allocations exceeded the maximum allowed per transaction",[eh]:"Max accounts exceeded",[th]:"Max instruction trace length exceeded",[Ud]:"Length of the seed is too long for address generation",[Md]:"An account required by the instruction is missing",[ud]:"missing required signature for instruction",[fd]:"instruction illegally modified the program id of an account",[Ad]:"insufficient account keys for instruction",[Kd]:"Cross-program invocation with unauthorized signer or writable account",[Gd]:"Failed to create program execution environment",[Wd]:"Program failed to compile",[Hd]:"Program failed to complete",[bd]:"instruction modified data of a read-only account",[yd]:"instruction changed the balance of a read-only account",[Ld]:"Cross-program invocation reentrancy not allowed for this instruction",[Ed]:"instruction modified rent epoch of an account",[gd]:"sum of account balances before and after instruction do not match",[hd]:"instruction requires an initialized account",[nd]:"",[Dd]:"Unsupported program id",[Jd]:"Unsupported sysvar",[Of]:"Invalid instruction plan kind: $kind.",[Kg]:"The provided instruction plan is empty.",[Wg]:"No failed transaction plan result was found in the provided transaction plan result.",[Hg]:"This transaction plan executor does not support non-divisible sequential plans. To support them, you may create your own executor such that multi-transaction atomicity is preserved — e.g. by targetting RPCs that support transaction bundles.",[Gg]:"The provided transaction plan failed to execute. See the `transactionPlanResult` attribute for more details. Note that the `cause` property is deprecated, and a future version will not set it.",[Fg]:"The provided message has insufficient capacity to accommodate the next instruction(s) in this plan. Expected at least $numBytesRequired free byte(s), got $numFreeBytes byte(s).",[Mf]:"Invalid transaction plan kind: $kind.",[$g]:"No more instructions to pack; the message packer has completed the instruction plan.",[qg]:"Unexpected instruction plan. Expected $expectedKind plan, got $actualKind plan.",[zg]:"Unexpected transaction plan. Expected $expectedKind plan, got $actualKind plan.",[Vg]:"Unexpected transaction plan result. Expected $expectedKind plan, got $actualKind plan.",[jg]:"Expected a successful transaction plan result. I.e. there is at least one failed or cancelled transaction in the plan.",[Zu]:"The instruction does not have any accounts.",[ed]:"The instruction does not have any data.",[td]:"Expected instruction to have progress address $expectedProgramAddress, got $actualProgramAddress.",[zl]:"Expected base58 encoded blockhash to decode to a byte array of length 32. Actual length: $actualLength.",[Hl]:"The nonce `$expectedNonceValue` is no longer valid. It has advanced to `$actualNonceValue`",[Rf]:"Invariant violation: Found no abortable iterable cache entry for key `$cacheKey`. It should be impossible to hit this error; please file an issue at https://sola.na/web3invariant",[Df]:"Invariant violation: This data publisher does not publish to the channel named `$channelName`. Supported channels include $supportedChannelNames.",[xf]:"Invariant violation: WebSocket message iterator state is corrupt; iterated without first resolving existing message promise. It should be impossible to hit this error; please file an issue at https://sola.na/web3invariant",[_f]:"Invariant violation: WebSocket message iterator is missing state storage. It should be impossible to hit this error; please file an issue at https://sola.na/web3invariant",[Bf]:"Invariant violation: Switch statement non-exhaustive. Received unexpected value `$unexpectedValue`. It should be impossible to hit this error; please file an issue at https://sola.na/web3invariant",[Zl]:"JSON-RPC error: Internal JSON-RPC error ($__serverMessage)",[eu]:"JSON-RPC error: Invalid method parameter(s) ($__serverMessage)",[nu]:"JSON-RPC error: The JSON sent is not a valid `Request` object ($__serverMessage)",[tu]:"JSON-RPC error: The method does not exist / is not available ($__serverMessage)",[Ql]:"JSON-RPC error: An error occurred on the server while parsing the JSON text ($__serverMessage)",[uu]:"$__serverMessage",[Eu]:"$__serverMessage",[bu]:"$__serverMessage",[cu]:"$__serverMessage",[iu]:"Epoch rewards period still active at slot $slot",[hu]:"$__serverMessage",[gu]:"$__serverMessage",[ru]:"Failed to query long-term storage; please try again",[ou]:"Minimum context slot has not been reached",[yu]:"Node is unhealthy; behind by $numSlotsBehind slots",[fu]:"No snapshot",[wu]:"Transaction simulation failed",[su]:"Rewards cannot be found because slot $slot is not the epoch boundary. This may be due to gap in the queried node's local ledger or long-term storage",[pu]:"$__serverMessage",[du]:"Transaction history is not available from this node",[mu]:"$__serverMessage",[lu]:"Transaction signature length mismatch",[vu]:"Transaction signature verification failure",[au]:"$__serverMessage",[ju]:"Key pair bytes must be of length 64, got $byteLength.",[Xu]:"Expected private key bytes with length 32. Actual length: $actualLength.",[Yu]:"Expected base58-encoded signature to decode to a byte array of length 64. Actual length: $actualLength.",[Qu]:"The provided private key does not match the provided public key.",[Ju]:"Expected base58-encoded signature string of length in the range [64, 88]. Actual length: $actualLength.",[Vl]:"Lamports value must be in the range [0, 2e64-1]",[jl]:"`$value` cannot be parsed as a `BigInt`",[Jl]:"$message",[Xl]:"`$value` cannot be parsed as a `Number`",[Wl]:"No nonce account could be found at address `$nonceAccountAddress`",[bh]:"Expected base58 encoded application domain to decode to a byte array of length 32. Actual length: $actualLength.",[Nh]:"Attempted to sign an offchain message with an address that is not a signer for it",[yh]:"Expected base58-encoded application domain string of length in the range [32, 44]. Actual length: $actualLength.",[Ch]:"The signer addresses in this offchain message envelope do not match the list of required signers in the message preamble. These unexpected signers were present in the envelope: `[$unexpectedSigners]`. These required signers were missing from the envelope `[$missingSigners]`.",[ph]:"The message body provided has a byte-length of $actualBytes. The maximum allowable byte-length is $maxBytes",[Ah]:"Expected message format $expectedMessageFormat, got $actualMessageFormat",[Sh]:"The message length specified in the message preamble is $specifiedLength bytes. The actual length of the message is $actualLength bytes.",[kh]:"Offchain message content must be non-empty",[wh]:"Offchain message must specify the address of at least one required signer",[Th]:"Offchain message envelope must reserve space for at least one signature",[vh]:"The offchain message preamble specifies $numRequiredSignatures required signature(s), got $signaturesLength.",[xh]:"The signatories of this offchain message must be listed in lexicographical order",[Rh]:"An address must be listed no more than once among the signatories of an offchain message",[Ih]:"Offchain message is missing signatures for addresses: $addresses.",[Bh]:"Offchain message signature verification failed. Signature mismatch for required signatories [$signatoriesWithInvalidSignatures]. Missing signatures for signatories [$signatoriesWithMissingSignatures]",[mh]:"The message body provided contains characters whose codes fall outside the allowed range. In order to ensure clear-signing compatiblity with hardware wallets, the message may only contain line feeds and characters in the range [\\x20-\\x7e].",[_h]:"Expected offchain message version $expectedVersion. Got $actualVersion.",[Eh]:"This version of Kit does not support decoding offchain messages with version $unsupportedVersion. The current max supported version is 0.",[kf]:"The notification name must end in 'Notifications' and the API must supply a subscription plan creator function for the notification '$notificationName'.",[If]:"WebSocket was closed before payload could be added to the send buffer",[Cf]:"WebSocket connection closed",[Nf]:"WebSocket failed to connect",[Tf]:"Failed to obtain a subscription id from the server",[Sf]:"Could not find an API plan for RPC method: `$method`",[wf]:"The $argumentLabel argument to the `$methodName` RPC method$optionalPathLabel was `$value`. This number is unsafe for use with the Solana JSON-RPC because it exceeds `Number.MAX_SAFE_INTEGER`.",[Af]:"HTTP error ($statusCode): $message",[Ef]:"HTTP header(s) forbidden: $headers. Learn more at https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name.",[rh]:"Multiple distinct signers were identified for address `$address`. Please ensure that you are using the same signer instance for each address.",[sh]:"The provided value does not implement the `KeyPairSigner` interface",[oh]:"The provided value does not implement the `MessageModifyingSigner` interface",[ah]:"The provided value does not implement the `MessagePartialSigner` interface",[ih]:"The provided value does not implement any of the `MessageSigner` interfaces",[lh]:"The provided value does not implement the `TransactionModifyingSigner` interface",[uh]:"The provided value does not implement the `TransactionPartialSigner` interface",[dh]:"The provided value does not implement the `TransactionSendingSigner` interface",[ch]:"The provided value does not implement any of the `TransactionSigner` interfaces",[hh]:"More than one `TransactionSendingSigner` was identified.",[gh]:"No `TransactionSendingSigner` was identified. Please provide a valid `TransactionWithSingleSendingSigner` transaction.",[fh]:"Wallet account signers do not support signing multiple messages/transactions in a single operation",[zu]:"Cannot export a non-extractable key.",[$u]:"No digest implementation could be found.",[Fu]:"Cryptographic operations are only allowed in secure browser contexts. Read more here: https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts.",[Ku]:"This runtime does not support the generation of Ed25519 key pairs.\n\nInstall @solana/webcrypto-ed25519-polyfill and call its `install` function before generating keys in environments that do not support Ed25519.\n\nFor a list of runtimes that currently support Ed25519 operations, visit https://github.com/WICG/webcrypto-secure-curves/issues/20.",[Gu]:"No signature verification implementation could be found.",[Hu]:"No key generation implementation could be found.",[Wu]:"No signing implementation could be found.",[qu]:"No key export implementation could be found.",[Yl]:"Timestamp value must be in the range [-(2n ** 63n), (2n ** 63n) - 1]. `$value` given",[bg]:"Transaction processing left an account with an outstanding borrowed reference",[rg]:"Account in use",[sg]:"Account loaded twice",[ig]:"Attempt to debit an account but found no record of a prior credit.",[Tg]:"Transaction loads an address table account that doesn't exist",[lg]:"This transaction has already been processed",[ug]:"Blockhash not found",[dg]:"Loader call chain is too deep",[yg]:"Transactions are currently disabled due to cluster maintenance",[Bg]:"Transaction contains a duplicate instruction ($index) that is not allowed",[ag]:"Insufficient funds for fee",[Dg]:"Transaction results in an account ($accountIndex) with insufficient funds for rent",[cg]:"This account may not be used to pay transaction fees",[gg]:"Transaction contains an invalid account reference",[Cg]:"Transaction loads an address table account with invalid data",[Ng]:"Transaction address table lookup uses an invalid index",[Ig]:"Transaction loads an address table account with an invalid owner",[Mg]:"LoadedAccountsDataSizeLimit set for transaction must be greater than 0.",[pg]:"This program may not be used for executing instructions",[_g]:"Transaction leaves an account with a lower balance than rent-exempt minimum",[Eg]:"Transaction loads a writable account that cannot be written",[Og]:"Transaction exceeded max loaded accounts data size cap",[hg]:"Transaction requires a fee but has no signature present",[og]:"Attempt to load a program that does not exist",[Ug]:"Execution of the program referenced by account at index $accountIndex is temporarily restricted.",[Lg]:"ResanitizationNeeded",[mg]:"Transaction failed to sanitize accounts offsets correctly",[fg]:"Transaction did not pass signature verification",[kg]:"Transaction locked too many accounts",[Pg]:"Sum of account balances before and after transaction do not match",[ng]:"The transaction failed with the error `$errorName`",[wg]:"Transaction version is unsupported",[Sg]:"Transaction would exceed account data limit within the block",[Rg]:"Transaction would exceed total account data limit",[Ag]:"Transaction would exceed max account limit within the block",[vg]:"Transaction would exceed max Block Cost Limit",[xg]:"Transaction would exceed max Vote Cost Limit",[jh]:"Attempted to sign a transaction with an address that is not a signer for it",[Hh]:"Transaction is missing an address at index: $index.",[Xh]:"Transaction has no expected signers therefore it cannot be encoded",[Zh]:"Transaction size $transactionSize exceeds limit of $transactionSizeLimit bytes",[Mh]:"Transaction does not have a blockhash lifetime",[Lh]:"Transaction is not a durable nonce transaction",[Ph]:"Contents of these address lookup tables unknown: $lookupTableAddresses",[Fh]:"Lookup of address at index $highestRequestedIndex failed for lookup table `$lookupTableAddress`. Highest known index is $highestKnownIndex. The lookup table may have been extended since its contents were retrieved",[Kh]:"No fee payer set in CompiledTransaction",[$h]:"Could not find program address at index $index",[Jh]:"Failed to estimate the compute unit consumption for this transaction message. This is likely because simulating the transaction failed. Inspect the `cause` property of this error to learn more",[Qh]:"Transaction failed when it was simulated in order to estimate the compute unit consumption. The compute unit estimate provided is for a transaction that failed when simulated and may not be representative of the compute units this transaction would consume if successful. Inspect the `cause` property of this error to learn more",[Wh]:"Transaction is missing a fee payer.",[qh]:"Could not determine this transaction's signature. Make sure that the transaction has been signed by its fee payer.",[Vh]:"Transaction first instruction is not advance nonce account instruction.",[zh]:"Transaction with no instructions cannot be durable nonce transaction.",[Dh]:"This transaction includes an address (`$programAddress`) which is both invoked and set as the fee payer. Program addresses may not pay fees",[Oh]:"This transaction includes an address (`$programAddress`) which is both invoked and marked writable. Program addresses may not be writable",[Yh]:"The transaction message expected the transaction to have $numRequiredSignatures signatures, got $signaturesLength.",[Gh]:"Transaction is missing signatures for addresses: $addresses.",[Uh]:"Transaction version must be in the range [0, 127]. `$actualVersion` given",[eg]:"This version of Kit does not support decoding transactions with version $unsupportedVersion. The current max supported version is 0.",[tg]:"The transaction has a durable nonce lifetime (with nonce `$nonce`), but the nonce account address is in a lookup table. The lifetime constraint cannot be constructed without fetching the lookup tables for the transaction."},Ff="i",$f="t";function Kf(e,t={}){if("production"!==process.env.NODE_ENV)return function(e,t={}){const n=Pf[e];if(0===n.length)return"";let r;function s(e){if(2===r[$f]){const s=n.slice(r[Ff]+1,e);i.push(s in t?`${t[s]}`:`$${s}`)}else 1===r[$f]&&i.push(n.slice(r[Ff],e))}const i=[];return n.split("").forEach((e,t)=>{if(0===t)return void(r={[Ff]:0,[$f]:"\\"===n[0]?0:"$"===n[0]?2:1});let i;switch(r[$f]){case 0:i={[Ff]:t,[$f]:1};break;case 1:"\\"===e?i={[Ff]:t,[$f]:0}:"$"===e&&(i={[Ff]:t,[$f]:2});break;case 2:"\\"===e?i={[Ff]:t,[$f]:0}:"$"===e?i={[Ff]:t,[$f]:2}:e.match(/\w/)||(i={[Ff]:t,[$f]:1})}i&&(r!==i&&s(t),r=i)}),s(),i.join("")}(e,t);{let n=`Solana error #${e}; Decode this error by running \`npx @solana/errors decode -- ${e}`;return Object.keys(t).length&&(n+=` '${function(e){const t=Object.entries(e).map(Uf).join("&");return btoa(t)}(t)}'`),`${n}\``}}var Gf=class extends Error{cause=this.cause;context;constructor(...[e,t]){let n,r;t&&Object.entries(Object.getOwnPropertyDescriptors(t)).forEach(([t,s])=>{"cause"===t?r={cause:s.value}:(void 0===n&&(n={__code:e}),Object.defineProperty(n,t,s))});super(Kf(e,n),r),this.context=Object.freeze(void 0===n?{__code:e}:n),this.name="SolanaError"}};function Hf(e){return"fixedSize"in e&&"number"==typeof e.fixedSize}function Wf(e){return 1!==e?.endian}function qf(e){return t={fixedSize:e.size,write(t,n,r){e.range&&function(e,t,n,r){if(r<t||r>n)throw new Gf(af,{codecDescription:e,max:n,min:t,value:r})}(e.name,e.range[0],e.range[1],t);const s=new ArrayBuffer(e.size);return e.set(new DataView(s),t,Wf(e.config)),n.set(new Uint8Array(s),r),r+e.size}},Object.freeze({...t,encode:e=>{const n=new Uint8Array(function(e,t){return"fixedSize"in t?t.fixedSize:t.getSizeFromValue(e)}(e,t));return t.write(e,n,0),n}});var t}function zf(e){return t={fixedSize:e.size,read(t,n=0){!function(e,t,n=0){if(t.length-n<=0)throw new Gf(Xg,{codecDescription:e})}(e.name,t,n),function(e,t,n,r=0){const s=n.length-r;if(s<t)throw new Gf(Yg,{bytesLength:s,codecDescription:e,expected:t})}(e.name,e.size,t,n);const r=new DataView(function(e,t,n){const r=e.byteOffset+(t??0),s=n??e.byteLength;let i;return"undefined"==typeof SharedArrayBuffer?i=e.buffer:e.buffer instanceof SharedArrayBuffer?(i=new ArrayBuffer(e.length),new Uint8Array(i).set(new Uint8Array(e))):i=e.buffer,0!==r&&r!==-e.byteLength||s!==e.byteLength?i.slice(r,r+s):i}(t,n,e.size));return[e.get(r,Wf(e.config)),n+e.size]}},Object.freeze({...t,decode:(e,n=0)=>t.read(e,n)[0]});var t}var Vf=(e={})=>function(e,t){if(Hf(e)!==Hf(t))throw new Gf(Zg);if(Hf(e)&&Hf(t)&&e.fixedSize!==t.fixedSize)throw new Gf(ef,{decoderFixedSize:t.fixedSize,encoderFixedSize:e.fixedSize});if(!Hf(e)&&!Hf(t)&&e.maxSize!==t.maxSize)throw new Gf(tf,{decoderMaxSize:t.maxSize,encoderMaxSize:e.maxSize});return{...t,...e,decode:t.decode,encode:e.encode,read:t.read,write:e.write}}(((e={})=>qf({config:e,name:"u64",range:[0n,BigInt("0xffffffffffffffff")],set:(e,t,n)=>e.setBigUint64(0,BigInt(t),n),size:8}))(e),((e={})=>zf({config:e,get:(e,t)=>e.getBigUint64(0,t),name:"u64",size:8}))(e));class jf extends TypeError{constructor(e,t){let n;const{message:r,explanation:s,...i}=e,{path:o}=e,a=0===o.length?r:`At path: ${o.join(".")} -- ${r}`;super(s??a),null!=s&&(this.cause=a),Object.assign(this,i),this.name=this.constructor.name,this.failures=()=>n??(n=[e,...t()])}}function Xf(e){return"object"==typeof e&&null!=e}function Yf(e){return Xf(e)&&!Array.isArray(e)}function Jf(e){return"symbol"==typeof e?e.toString():"string"==typeof e?JSON.stringify(e):`${e}`}function Qf(e,t,n,r){if(!0===e)return;!1===e?e={}:"string"==typeof e&&(e={message:e});const{path:s,branch:i}=t,{type:o}=n,{refinement:a,message:c=`Expected a value of type \`${o}\`${a?` with refinement \`${a}\``:""}, but received: \`${Jf(r)}\``}=e;return{value:r,type:o,refinement:a,key:s[s.length-1],path:s,branch:i,...e,message:c}}function*Zf(e,t,n,r){var s;Xf(s=e)&&"function"==typeof s[Symbol.iterator]||(e=[e]);for(const s of e){const e=Qf(s,t,n,r);e&&(yield e)}}function*ep(e,t,n={}){const{path:r=[],branch:s=[e],coerce:i=!1,mask:o=!1}=n,a={path:r,branch:s,mask:o};i&&(e=t.coercer(e,a));let c="valid";for(const r of t.validator(e,a))r.explanation=n.message,c="not_valid",yield[r,void 0];for(let[l,u,d]of t.entries(e,a)){const t=ep(u,d,{path:void 0===l?r:[...r,l],branch:void 0===l?s:[...s,u],coerce:i,mask:o,message:n.message});for(const n of t)n[0]?(c=null!=n[0].refinement?"not_refined":"not_valid",yield[n[0],void 0]):i&&(u=n[1],void 0===l?e=u:e instanceof Map?e.set(l,u):e instanceof Set?e.add(u):Xf(e)&&(void 0!==u||l in e)&&(e[l]=u))}if("not_valid"!==c)for(const r of t.refiner(e,a))r.explanation=n.message,c="not_refined",yield[r,void 0];"valid"===c&&(yield[void 0,e])}let tp=class{constructor(e){const{type:t,schema:n,validator:r,refiner:s,coercer:i=e=>e,entries:o=function*(){}}=e;this.type=t,this.schema=n,this.entries=o,this.coercer=i,this.validator=r?(e,t)=>Zf(r(e,t),t,this,e):()=>[],this.refiner=s?(e,t)=>Zf(s(e,t),t,this,e):()=>[]}assert(e,t){return function(e,t,n){const r=sp(e,t,{message:n});if(r[0])throw r[0]}(e,this,t)}create(e,t){return np(e,this,t)}is(e){return rp(e,this)}mask(e,t){return function(e,t,n){const r=sp(e,t,{coerce:!0,mask:!0,message:n});if(r[0])throw r[0];return r[1]}(e,this,t)}validate(e,t={}){return sp(e,this,t)}};function np(e,t,n){const r=sp(e,t,{coerce:!0,message:n});if(r[0])throw r[0];return r[1]}function rp(e,t){return!sp(e,t)[0]}function sp(e,t,n={}){const r=ep(e,t,n),s=function(e){const{done:t,value:n}=e.next();return t?void 0:n}(r);if(s[0]){return[new jf(s[0],function*(){for(const e of r)e[0]&&(yield e[0])}),void 0]}return[void 0,s[1]]}function ip(e,t){return new tp({type:e,schema:null,validator:t})}function op(e){return new tp({type:"array",schema:e,*entries(t){if(e&&Array.isArray(t))for(const[n,r]of t.entries())yield[n,r,e]},coercer:e=>Array.isArray(e)?e.slice():e,validator:e=>Array.isArray(e)||`Expected an array value, but received: ${Jf(e)}`})}function ap(){return ip("boolean",e=>"boolean"==typeof e)}function cp(e){return ip("instance",t=>t instanceof e||`Expected a \`${e.name}\` instance, but received: ${Jf(t)}`)}function lp(e){const t=Jf(e),n=typeof e;return new tp({type:"literal",schema:"string"===n||"number"===n||"boolean"===n?e:null,validator:n=>n===e||`Expected the literal \`${t}\`, but received: ${Jf(n)}`})}function up(e){return new tp({...e,validator:(t,n)=>null===t||e.validator(t,n),refiner:(t,n)=>null===t||e.refiner(t,n)})}function dp(){return ip("number",e=>"number"==typeof e&&!isNaN(e)||`Expected a number, but received: ${Jf(e)}`)}function hp(e){return new tp({...e,validator:(t,n)=>void 0===t||e.validator(t,n),refiner:(t,n)=>void 0===t||e.refiner(t,n)})}function gp(e,t){return new tp({type:"record",schema:null,*entries(n){if(Xf(n))for(const r in n){const s=n[r];yield[r,r,e],yield[r,s,t]}},validator:e=>Yf(e)||`Expected an object, but received: ${Jf(e)}`,coercer:e=>Yf(e)?{...e}:e})}function fp(){return ip("string",e=>"string"==typeof e||`Expected a string, but received: ${Jf(e)}`)}function pp(e){const t=ip("never",()=>!1);return new tp({type:"tuple",schema:null,*entries(n){if(Array.isArray(n)){const r=Math.max(e.length,n.length);for(let s=0;s<r;s++)yield[s,n[s],e[s]||t]}},validator:e=>Array.isArray(e)||`Expected an array, but received: ${Jf(e)}`,coercer:e=>Array.isArray(e)?e.slice():e})}function mp(e){const t=Object.keys(e);return new tp({type:"type",schema:e,*entries(n){if(Xf(n))for(const r of t)yield[r,n[r],e[r]]},validator:e=>Yf(e)||`Expected an object, but received: ${Jf(e)}`,coercer:e=>Yf(e)?{...e}:e})}function yp(e){const t=e.map(e=>e.type).join(" | ");return new tp({type:"union",schema:null,coercer(t,n){for(const r of e){const[e,s]=r.validate(t,{coerce:!0,mask:n.mask});if(!e)return s}return t},validator(n,r){const s=[];for(const t of e){const[...e]=ep(n,t,r),[i]=e;if(!i[0])return[];for(const[t]of e)t&&s.push(t)}return[`Expected the value to satisfy a union of \`${t}\`, but received: ${Jf(n)}`,...s]}})}function bp(){return ip("unknown",()=>!0)}function vp(e,t,n){return new tp({...e,coercer:(r,s)=>rp(r,t)?e.coercer(n(r,s),s):e.coercer(r,s)})}var wp,Ep,Ap,Sp,kp=ko(g);function Tp(){if(Ep)return wp;Ep=1;const e=kp.v4;return wp=function(t,n,r,s){if("string"!=typeof t)throw new TypeError(t+" must be a string");const i="number"==typeof(s=s||{}).version?s.version:2;if(1!==i&&2!==i)throw new TypeError(i+" must be 1 or 2");const o={method:t};if(2===i&&(o.jsonrpc="2.0"),n){if("object"!=typeof n&&!Array.isArray(n))throw new TypeError(n+" must be an object, array or omitted");o.params=n}if(void 0===r){const t="function"==typeof s.generator?s.generator:function(){return e()};o.id=t(o,s)}else 2===i&&null===r?s.notificationIdNull&&(o.id=null):o.id=r;return o}}function Ip(){if(Sp)return Ap;Sp=1;const e=kp.v4,t=Tp(),n=function(t,r){if(!(this instanceof n))return new n(t,r);r||(r={}),this.options={reviver:void 0!==r.reviver?r.reviver:null,replacer:void 0!==r.replacer?r.replacer:null,generator:void 0!==r.generator?r.generator:function(){return e()},version:void 0!==r.version?r.version:2,notificationIdNull:"boolean"==typeof r.notificationIdNull&&r.notificationIdNull},this.callServer=t};return Ap=n,n.prototype.request=function(e,n,r,s){const i=this;let o=null;const a=Array.isArray(e)&&"function"==typeof n;if(1===this.options.version&&a)throw new TypeError("JSON-RPC 1.0 does not support batching");if(a||!a&&e&&"object"==typeof e&&"function"==typeof n)s=n,o=e;else{"function"==typeof r&&(s=r,r=void 0);const i="function"==typeof s;try{o=t(e,n,r,{generator:this.options.generator,version:this.options.version,notificationIdNull:this.options.notificationIdNull})}catch(e){if(i)return void s(e);throw e}if(!i)return o}let c;try{c=JSON.stringify(o,this.options.replacer)}catch(e){return void s(e)}return this.callServer(c,function(e,t){i._parseResponse(e,t,s)}),o},n.prototype._parseResponse=function(e,t,n){if(e)return void n(e);if(!t)return void n();let r;try{r=JSON.parse(t,this.options.reviver)}catch(e){return void n(e)}if(3!==n.length)n(null,r);else{if(Array.isArray(r)){const e=function(e){return void 0!==e.error},t=function(t){return!e(t)};return void n(null,r.filter(e),r.filter(t))}n(null,r.error,r.result)}},Ap}var Cp,Np=So(Ip()),_p={exports:{}};function xp(){return Cp||(Cp=1,function(e){var t=Object.prototype.hasOwnProperty,n="~";function r(){}function s(e,t,n){this.fn=e,this.context=t,this.once=n||!1}function i(e,t,r,i,o){if("function"!=typeof r)throw new TypeError("The listener must be a function");var a=new s(r,i||e,o),c=n?n+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],a]:e._events[c].push(a):(e._events[c]=a,e._eventsCount++),e}function o(e,t){0===--e._eventsCount?e._events=new r:delete e._events[t]}function a(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=Object.create(null),(new r).__proto__||(n=!1)),a.prototype.eventNames=function(){var e,r,s=[];if(0===this._eventsCount)return s;for(r in e=this._events)t.call(e,r)&&s.push(n?r.slice(1):r);return Object.getOwnPropertySymbols?s.concat(Object.getOwnPropertySymbols(e)):s},a.prototype.listeners=function(e){var t=n?n+e:e,r=this._events[t];if(!r)return[];if(r.fn)return[r.fn];for(var s=0,i=r.length,o=new Array(i);s<i;s++)o[s]=r[s].fn;return o},a.prototype.listenerCount=function(e){var t=n?n+e:e,r=this._events[t];return r?r.fn?1:r.length:0},a.prototype.emit=function(e,t,r,s,i,o){var a=n?n+e:e;if(!this._events[a])return!1;var c,l,u=this._events[a],d=arguments.length;if(u.fn){switch(u.once&&this.removeListener(e,u.fn,void 0,!0),d){case 1:return u.fn.call(u.context),!0;case 2:return u.fn.call(u.context,t),!0;case 3:return u.fn.call(u.context,t,r),!0;case 4:return u.fn.call(u.context,t,r,s),!0;case 5:return u.fn.call(u.context,t,r,s,i),!0;case 6:return u.fn.call(u.context,t,r,s,i,o),!0}for(l=1,c=new Array(d-1);l<d;l++)c[l-1]=arguments[l];u.fn.apply(u.context,c)}else{var h,g=u.length;for(l=0;l<g;l++)switch(u[l].once&&this.removeListener(e,u[l].fn,void 0,!0),d){case 1:u[l].fn.call(u[l].context);break;case 2:u[l].fn.call(u[l].context,t);break;case 3:u[l].fn.call(u[l].context,t,r);break;case 4:u[l].fn.call(u[l].context,t,r,s);break;default:if(!c)for(h=1,c=new Array(d-1);h<d;h++)c[h-1]=arguments[h];u[l].fn.apply(u[l].context,c)}}return!0},a.prototype.on=function(e,t,n){return i(this,e,t,n,!1)},a.prototype.once=function(e,t,n){return i(this,e,t,n,!0)},a.prototype.removeListener=function(e,t,r,s){var i=n?n+e:e;if(!this._events[i])return this;if(!t)return o(this,i),this;var a=this._events[i];if(a.fn)a.fn!==t||s&&!a.once||r&&a.context!==r||o(this,i);else{for(var c=0,l=[],u=a.length;c<u;c++)(a[c].fn!==t||s&&!a[c].once||r&&a[c].context!==r)&&l.push(a[c]);l.length?this._events[i]=1===l.length?l[0]:l:o(this,i)}return this},a.prototype.removeAllListeners=function(e){var t;return e?(t=n?n+e:e,this._events[t]&&o(this,t)):(this._events=new r,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=n,a.EventEmitter=a,e.exports=a}(_p)),_p.exports}var Rp=So(xp()),Bp=class extends Rp{socket;constructor(e,t){super(),this.socket=new window.WebSocket(e,t.protocols),this.socket.onopen=()=>this.emit("open"),this.socket.onmessage=e=>this.emit("message",e.data),this.socket.onerror=e=>this.emit("error",e),this.socket.onclose=e=>{this.emit("close",e.code,e.reason)}}send(e,t,n){const r=n||t;try{this.socket.send(e),r()}catch(e){r(e)}}close(e,t){this.socket.close(e,t)}addEventListener(e,t,n){this.socket.addEventListener(e,t,n)}};var Dp=class{encode(e){return JSON.stringify(e)}decode(e){return JSON.parse(e)}},Op=class extends Rp{address;rpc_id;queue;options;autoconnect;ready;reconnect;reconnect_timer_id;reconnect_interval;max_reconnects;rest_options;current_reconnects;generate_request_id;socket;webSocketFactory;dataPack;constructor(e,t="ws://localhost:8080",{autoconnect:n=!0,reconnect:r=!0,reconnect_interval:s=1e3,max_reconnects:i=5,...o}={},a,c){super(),this.webSocketFactory=e,this.queue={},this.rpc_id=0,this.address=t,this.autoconnect=n,this.ready=!1,this.reconnect=r,this.reconnect_timer_id=void 0,this.reconnect_interval=s,this.max_reconnects=i,this.rest_options=o,this.current_reconnects=0,this.generate_request_id=a||(()=>"number"==typeof this.rpc_id?++this.rpc_id:Number(this.rpc_id)+1),this.dataPack=c||new Dp,this.autoconnect&&this._connect(this.address,{autoconnect:this.autoconnect,reconnect:this.reconnect,reconnect_interval:this.reconnect_interval,max_reconnects:this.max_reconnects,...this.rest_options})}connect(){this.socket||this._connect(this.address,{autoconnect:this.autoconnect,reconnect:this.reconnect,reconnect_interval:this.reconnect_interval,max_reconnects:this.max_reconnects,...this.rest_options})}call(e,t,n,r){return r||"object"!=typeof n||(r=n,n=null),new Promise((s,i)=>{if(!this.ready)return i(new Error("socket not ready"));const o=this.generate_request_id(e,t),a={jsonrpc:"2.0",method:e,params:t||void 0,id:o};this.socket.send(this.dataPack.encode(a),r,e=>{if(e)return i(e);this.queue[o]={promise:[s,i]},n&&(this.queue[o].timeout=setTimeout(()=>{delete this.queue[o],i(new Error("reply timeout"))},n))})})}async login(e){const t=await this.call("rpc.login",e);if(!t)throw new Error("authentication failed");return t}async listMethods(){return await this.call("__listMethods")}notify(e,t){return new Promise((n,r)=>{if(!this.ready)return r(new Error("socket not ready"));const s={jsonrpc:"2.0",method:e,params:t};this.socket.send(this.dataPack.encode(s),e=>{if(e)return r(e);n()})})}async subscribe(e){"string"==typeof e&&(e=[e]);const t=await this.call("rpc.on",e);if("string"==typeof e&&"ok"!==t[e])throw new Error("Failed subscribing to an event '"+e+"' with: "+t[e]);return t}async unsubscribe(e){"string"==typeof e&&(e=[e]);const t=await this.call("rpc.off",e);if("string"==typeof e&&"ok"!==t[e])throw new Error("Failed unsubscribing from an event with: "+t);return t}close(e,t){this.socket&&this.socket.close(e||1e3,t)}setAutoReconnect(e){this.reconnect=e}setReconnectInterval(e){this.reconnect_interval=e}setMaxReconnects(e){this.max_reconnects=e}getCurrentReconnects(){return this.current_reconnects}getMaxReconnects(){return this.max_reconnects}isReconnecting(){return void 0!==this.reconnect_timer_id}willReconnect(){return this.reconnect&&(0===this.max_reconnects||this.current_reconnects<this.max_reconnects)}_connect(e,t){clearTimeout(this.reconnect_timer_id),this.socket=this.webSocketFactory(e,t),this.socket.addEventListener("open",()=>{this.ready=!0,this.emit("open"),this.current_reconnects=0}),this.socket.addEventListener("message",({data:e})=>{e instanceof ArrayBuffer&&(e=Oo.Buffer.from(e).toString());try{e=this.dataPack.decode(e)}catch(e){return}if(e.notification&&this.listeners(e.notification).length){if(!Object.keys(e.params).length)return this.emit(e.notification);const t=[e.notification];if(e.params.constructor===Object)t.push(e.params);else for(let n=0;n<e.params.length;n++)t.push(e.params[n]);return Promise.resolve().then(()=>{this.emit.apply(this,t)})}if(!this.queue[e.id])return e.method?Promise.resolve().then(()=>{this.emit(e.method,e?.params)}):void 0;"error"in e=="result"in e&&this.queue[e.id].promise[1](new Error('Server response malformed. Response must include either "result" or "error", but not both.')),this.queue[e.id].timeout&&clearTimeout(this.queue[e.id].timeout),e.error?this.queue[e.id].promise[1](e.error):this.queue[e.id].promise[0](e.result),delete this.queue[e.id]}),this.socket.addEventListener("error",e=>this.emit("error",e)),this.socket.addEventListener("close",({code:n,reason:r})=>{this.ready&&setTimeout(()=>this.emit("close",n,r),0),this.ready=!1,this.socket=void 0,1e3!==n&&(this.current_reconnects++,this.reconnect&&(this.max_reconnects>this.current_reconnects||0===this.max_reconnects)?this.reconnect_timer_id=setTimeout(()=>this._connect(e,t),this.reconnect_interval):this.reconnect&&this.max_reconnects>0&&this.current_reconnects>=this.max_reconnects&&setTimeout(()=>this.emit("max_reconnects_reached",n,r),1))})}};class Mp extends ra{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,Fo(e);const n=ta(t);if(this.iHash=e.create(),"function"!=typeof this.iHash.update)throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const r=this.blockLen,s=new Uint8Array(r);s.set(n.length>r?e.create().update(n).digest():n);for(let e=0;e<s.length;e++)s[e]^=54;this.iHash.update(s),this.oHash=e.create();for(let e=0;e<s.length;e++)s[e]^=106;this.oHash.update(s),Ko(s)}update(e){return $o(this),this.iHash.update(e),this}digestInto(e){$o(this),Po(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:t,iHash:n,finished:r,destroyed:s,blockLen:i,outputLen:o}=this;return e.finished=r,e.destroyed=s,e.blockLen=i,e.outputLen=o,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Lp=(e,t,n)=>new Mp(e,t).update(n).digest();Lp.create=(e,t)=>new Mp(e,t);const Up=(e,t)=>(e+(e>=0?t:-t)/Wp)/t;function Pp(e){if(!["compact","recovered","der"].includes(e))throw new Error('Signature format must be "compact", "recovered", or "der"');return e}function Fp(e,t){const n={};for(let r of Object.keys(t))n[r]=void 0===e[r]?t[r]:e[r];return $a(n.lowS,"lowS"),$a(n.prehash,"prehash"),void 0!==n.format&&Pp(n.format),n}class $p extends Error{constructor(e=""){super(e)}}const Kp={Err:$p,_tlv:{encode:(e,t)=>{const{Err:n}=Kp;if(e<0||e>256)throw new n("tlv.encode: wrong tag");if(1&t.length)throw new n("tlv.encode: unpadded data");const r=t.length/2,s=Ga(r);if(s.length/2&128)throw new n("tlv.encode: long form length too big");const i=r>127?Ga(s.length/2|128):"";return Ga(e)+i+s+t},decode(e,t){const{Err:n}=Kp;let r=0;if(e<0||e>256)throw new n("tlv.encode: wrong tag");if(t.length<2||t[r++]!==e)throw new n("tlv.decode: wrong tlv");const s=t[r++];let i=0;if(!!(128&s)){const e=127&s;if(!e)throw new n("tlv.decode(long): indefinite length not supported");if(e>4)throw new n("tlv.decode(long): byte length is too big");const o=t.subarray(r,r+e);if(o.length!==e)throw new n("tlv.decode: length bytes not complete");if(0===o[0])throw new n("tlv.decode(long): zero leftmost byte");for(const e of o)i=i<<8|e;if(r+=e,i<128)throw new n("tlv.decode(long): not minimal encoding")}else i=s;const o=t.subarray(r,r+i);if(o.length!==i)throw new n("tlv.decode: wrong value length");return{v:o,l:t.subarray(r+i)}}},_int:{encode(e){const{Err:t}=Kp;if(e<Gp)throw new t("integer: negative integers are not allowed");let n=Ga(e);if(8&Number.parseInt(n[0],16)&&(n="00"+n),1&n.length)throw new t("unexpected DER parsing assertion: unpadded hex");return n},decode(e){const{Err:t}=Kp;if(128&e[0])throw new t("invalid signature integer: negative");if(0===e[0]&&!(128&e[1]))throw new t("invalid signature integer: unnecessary leading zero");return Wa(e)}},toSig(e){const{Err:t,_int:n,_tlv:r}=Kp,s=ja("signature",e),{v:i,l:o}=r.decode(48,s);if(o.length)throw new t("invalid signature: left bytes after parsing");const{v:a,l:c}=r.decode(2,i),{v:l,l:u}=r.decode(2,c);if(u.length)throw new t("invalid signature: left bytes after parsing");return{r:n.decode(a),s:n.decode(l)}},hexFromSig(e){const{_tlv:t,_int:n}=Kp,r=t.encode(2,n.encode(e.r))+t.encode(2,n.encode(e.s));return t.encode(48,r)}},Gp=BigInt(0),Hp=BigInt(1),Wp=BigInt(2),qp=BigInt(3),zp=BigInt(4);function Vp(e,t){const{BYTES:n}=e;let r;if("bigint"==typeof t)r=t;else{let s=ja("private key",t);try{r=e.fromBytes(s)}catch(e){throw new Error(`invalid private key: expected ui8a of size ${n}, got ${typeof t}`)}}if(!e.isValidNot0(r))throw new Error("invalid private key: out of range [1..N-1]");return r}function jp(e,t={}){const n=Kc("weierstrass",e,t),{Fp:r,Fn:s}=n;let i=n.CURVE;const{h:o,n:a}=i;ec(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:c}=t;if(c&&(!r.is0(i.a)||"bigint"!=typeof c.beta||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const l=Yp(r,s);function u(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}const d=t.toBytes||function(e,t,n){const{x:s,y:i}=t.toAffine(),o=r.toBytes(s);if($a(n,"isCompressed"),n){u();return na(Xp(!r.isOdd(i)),o)}return na(Uint8Array.of(4),o,r.toBytes(i))},h=t.fromBytes||function(e){Ka(e,void 0,"Point");const{publicKey:t,publicKeyUncompressed:n}=l,s=e.length,i=e[0],o=e.subarray(1);if(s!==t||2!==i&&3!==i){if(s===n&&4===i){const e=r.BYTES,t=r.fromBytes(o.subarray(0,e)),n=r.fromBytes(o.subarray(e,2*e));if(!f(t,n))throw new Error("bad point: is not on curve");return{x:t,y:n}}throw new Error(`bad point: got length ${s}, expected compressed=${t} or uncompressed=${n}`)}{const e=r.fromBytes(o);if(!r.isValid(e))throw new Error("bad point: is not on curve, wrong x");const t=g(e);let n;try{n=r.sqrt(t)}catch(e){const t=e instanceof Error?": "+e.message:"";throw new Error("bad point: is not on curve, sqrt error"+t)}u();return!(1&~i)!==r.isOdd(n)&&(n=r.neg(n)),{x:e,y:n}}};function g(e){const t=r.sqr(e),n=r.mul(t,e);return r.add(r.add(n,r.mul(e,i.a)),i.b)}function f(e,t){const n=r.sqr(t),s=g(e);return r.eql(n,s)}if(!f(i.Gx,i.Gy))throw new Error("bad curve params: generator point");const p=r.mul(r.pow(i.a,qp),zp),m=r.mul(r.sqr(i.b),BigInt(27));if(r.is0(r.add(p,m)))throw new Error("bad curve params: a or b");function y(e,t,n=!1){if(!r.isValid(t)||n&&r.is0(t))throw new Error(`bad point coordinate ${e}`);return t}function b(e){if(!(e instanceof S))throw new Error("ProjectivePoint expected")}function v(e){if(!c||!c.basises)throw new Error("no endo");return function(e,t,n){const[[r,s],[i,o]]=t,a=Up(o*e,n),c=Up(-s*e,n);let l=e-a*r-c*i,u=-a*s-c*o;const d=l<Gp,h=u<Gp;d&&(l=-l),h&&(u=-u);const g=Za(Math.ceil(Qa(n)/2))+Hp;if(l<Gp||l>=g||u<Gp||u>=g)throw new Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:d,k1:l,k2neg:h,k2:u}}(e,c.basises,s.ORDER)}const w=tc((e,t)=>{const{X:n,Y:s,Z:i}=e;if(r.eql(i,r.ONE))return{x:n,y:s};const o=e.is0();null==t&&(t=o?r.ONE:r.inv(i));const a=r.mul(n,t),c=r.mul(s,t),l=r.mul(i,t);if(o)return{x:r.ZERO,y:r.ZERO};if(!r.eql(l,r.ONE))throw new Error("invZ was invalid");return{x:a,y:c}}),E=tc(e=>{if(e.is0()){if(t.allowInfinityPoint&&!r.is0(e.Y))return;throw new Error("bad point: ZERO")}const{x:n,y:s}=e.toAffine();if(!r.isValid(n)||!r.isValid(s))throw new Error("bad point: x or y not field elements");if(!f(n,s))throw new Error("bad point: equation left != right");if(!e.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function A(e,t,n,s,i){return n=new S(r.mul(n.X,e),n.Y,n.Z),t=_c(s,t),n=_c(i,n),t.add(n)}class S{constructor(e,t,n){this.X=y("x",e),this.Y=y("y",t,!0),this.Z=y("z",n),Object.freeze(this)}static CURVE(){return i}static fromAffine(e){const{x:t,y:n}=e||{};if(!e||!r.isValid(t)||!r.isValid(n))throw new Error("invalid affine point");if(e instanceof S)throw new Error("projective point not allowed");return r.is0(t)&&r.is0(n)?S.ZERO:new S(t,n,r.ONE)}static fromBytes(e){const t=S.fromAffine(h(Ka(e,void 0,"point")));return t.assertValidity(),t}static fromHex(e){return S.fromBytes(ja("pointHex",e))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(e=8,t=!0){return T.createCache(this,e),t||this.multiply(qp),this}assertValidity(){E(this)}hasEvenY(){const{y:e}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(e)}equals(e){b(e);const{X:t,Y:n,Z:s}=this,{X:i,Y:o,Z:a}=e,c=r.eql(r.mul(t,a),r.mul(i,s)),l=r.eql(r.mul(n,a),r.mul(o,s));return c&&l}negate(){return new S(this.X,r.neg(this.Y),this.Z)}double(){const{a:e,b:t}=i,n=r.mul(t,qp),{X:s,Y:o,Z:a}=this;let c=r.ZERO,l=r.ZERO,u=r.ZERO,d=r.mul(s,s),h=r.mul(o,o),g=r.mul(a,a),f=r.mul(s,o);return f=r.add(f,f),u=r.mul(s,a),u=r.add(u,u),c=r.mul(e,u),l=r.mul(n,g),l=r.add(c,l),c=r.sub(h,l),l=r.add(h,l),l=r.mul(c,l),c=r.mul(f,c),u=r.mul(n,u),g=r.mul(e,g),f=r.sub(d,g),f=r.mul(e,f),f=r.add(f,u),u=r.add(d,d),d=r.add(u,d),d=r.add(d,g),d=r.mul(d,f),l=r.add(l,d),g=r.mul(o,a),g=r.add(g,g),d=r.mul(g,f),c=r.sub(c,d),u=r.mul(g,h),u=r.add(u,u),u=r.add(u,u),new S(c,l,u)}add(e){b(e);const{X:t,Y:n,Z:s}=this,{X:o,Y:a,Z:c}=e;let l=r.ZERO,u=r.ZERO,d=r.ZERO;const h=i.a,g=r.mul(i.b,qp);let f=r.mul(t,o),p=r.mul(n,a),m=r.mul(s,c),y=r.add(t,n),v=r.add(o,a);y=r.mul(y,v),v=r.add(f,p),y=r.sub(y,v),v=r.add(t,s);let w=r.add(o,c);return v=r.mul(v,w),w=r.add(f,m),v=r.sub(v,w),w=r.add(n,s),l=r.add(a,c),w=r.mul(w,l),l=r.add(p,m),w=r.sub(w,l),d=r.mul(h,v),l=r.mul(g,m),d=r.add(l,d),l=r.sub(p,d),d=r.add(p,d),u=r.mul(l,d),p=r.add(f,f),p=r.add(p,f),m=r.mul(h,m),v=r.mul(g,v),p=r.add(p,m),m=r.sub(f,m),m=r.mul(h,m),v=r.add(v,m),f=r.mul(p,v),u=r.add(u,f),f=r.mul(w,v),l=r.mul(y,l),l=r.sub(l,f),f=r.mul(y,p),d=r.mul(w,d),d=r.add(d,f),new S(l,u,d)}subtract(e){return this.add(e.negate())}is0(){return this.equals(S.ZERO)}multiply(e){const{endo:n}=t;if(!s.isValidNot0(e))throw new Error("invalid scalar: out of range");let r,i;const o=e=>T.cached(this,e,e=>xc(S,e));if(n){const{k1neg:t,k1:s,k2neg:a,k2:c}=v(e),{p:l,f:u}=o(s),{p:d,f:h}=o(c);i=u.add(h),r=A(n.beta,l,d,t,a)}else{const{p:t,f:n}=o(e);r=t,i=n}return xc(S,[r,i])[0]}multiplyUnsafe(e){const{endo:n}=t,r=this;if(!s.isValid(e))throw new Error("invalid scalar: out of range");if(e===Gp||r.is0())return S.ZERO;if(e===Hp)return r;if(T.hasCache(this))return this.multiply(e);if(n){const{k1neg:t,k1:s,k2neg:i,k2:o}=v(e),{p1:a,p2:c}=function(e,t,n,r){let s=t,i=e.ZERO,o=e.ZERO;for(;n>Cc||r>Cc;)n&Nc&&(i=i.add(s)),r&Nc&&(o=o.add(s)),s=s.double(),n>>=Nc,r>>=Nc;return{p1:i,p2:o}}(S,r,s,o);return A(n.beta,a,c,t,i)}return T.unsafe(r,e)}multiplyAndAddUnsafe(e,t,n){const r=this.multiplyUnsafe(t).add(e.multiplyUnsafe(n));return r.is0()?void 0:r}toAffine(e){return w(this,e)}isTorsionFree(){const{isTorsionFree:e}=t;return o===Hp||(e?e(S,this):T.unsafe(this,a).is0())}clearCofactor(){const{clearCofactor:e}=t;return o===Hp?this:e?e(S,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(e=!0){return $a(e,"isCompressed"),this.assertValidity(),d(S,this,e)}toHex(e=!0){return zo(this.toBytes(e))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(e=!0){return this.toBytes(e)}_setWindowSize(e){this.precompute(e)}static normalizeZ(e){return xc(S,e)}static msm(e,t){return Fc(S,s,e,t)}static fromPrivateKey(e){return S.BASE.multiply(Vp(s,e))}}S.BASE=new S(i.Gx,i.Gy,r.ONE),S.ZERO=new S(r.ZERO,r.ONE,r.ZERO),S.Fp=r,S.Fn=s;const k=s.BITS,T=new Pc(S,t.endo?Math.ceil(k/2):k);return S.BASE.precompute(8),S}function Xp(e){return Uint8Array.of(e?2:3)}function Yp(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function Jp(e,t={}){const{Fn:n}=e,r=t.randomBytes||ia,s=Object.assign(Yp(e.Fp,n),{seed:Ic(n.ORDER)});function i(e){try{return!!Vp(n,e)}catch(e){return!1}}function o(e=r(s.seed)){return function(e,t,n=!1){const r=e.length,s=Tc(t),i=Ic(t);if(r<16||r<i||r>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+r);const o=hc(n?qa(e):Wa(e),t-rc)+rc;return n?Va(o,s):za(o,s)}(Ka(e,s.seed,"seed"),n.ORDER)}function a(t,r=!0){return e.BASE.multiply(Vp(n,t)).toBytes(r)}function c(t){if("bigint"==typeof t)return!1;if(t instanceof e)return!0;const{secretKey:r,publicKey:i,publicKeyUncompressed:o}=s;if(n.allowedLengths||r===i)return;const a=ja("key",t).length;return a===i||a===o}const l={isValidSecretKey:i,isValidPublicKey:function(t,n){const{publicKey:r,publicKeyUncompressed:i}=s;try{const s=t.length;return(!0!==n||s===r)&&((!1!==n||s===i)&&!!e.fromBytes(t))}catch(e){return!1}},randomSecretKey:o,isValidPrivateKey:i,randomPrivateKey:o,normPrivateKeyToScalar:e=>Vp(n,e),precompute:(t=8,n=e.BASE)=>n.precompute(t,!1)};return Object.freeze({getPublicKey:a,getSharedSecret:function(t,r,s=!0){if(!0===c(t))throw new Error("first arg must be private key");if(!1===c(r))throw new Error("second arg must be public key");const i=Vp(n,t);return e.fromHex(r).multiply(i).toBytes(s)},keygen:function(e){const t=o(e);return{secretKey:t,publicKey:a(t)}},Point:e,utils:l,lengths:s})}function Qp(e,t,n={}){Fo(t),ec(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const r=n.randomBytes||ia,s=n.hmac||((e,...n)=>Lp(t,e,na(...n))),{Fp:i,Fn:o}=e,{ORDER:a,BITS:c}=o,{keygen:l,getPublicKey:u,getSharedSecret:d,utils:h,lengths:g}=Jp(e,n),f={prehash:!1,lowS:"boolean"==typeof n.lowS&&n.lowS,format:void 0,extraEntropy:!1},p="compact";function m(e){return e>a>>Hp}function y(e,t){if(!o.isValidNot0(t))throw new Error(`invalid signature ${e}: out of range 1..Point.Fn.ORDER`);return t}class b{constructor(e,t,n){this.r=y("r",e),this.s=y("s",t),null!=n&&(this.recovery=n),Object.freeze(this)}static fromBytes(e,t=p){let n;if(function(e,t){Pp(t);const n=g.signature;Ka(e,"compact"===t?n:"recovered"===t?n+1:void 0,`${t} signature`)}(e,t),"der"===t){const{r:t,s:n}=Kp.toSig(Ka(e));return new b(t,n)}"recovered"===t&&(n=e[0],t="compact",e=e.subarray(1));const r=o.BYTES,s=e.subarray(0,r),i=e.subarray(r,2*r);return new b(o.fromBytes(s),o.fromBytes(i),n)}static fromHex(e,t){return this.fromBytes(ea(e),t)}addRecoveryBit(e){return new b(this.r,this.s,e)}recoverPublicKey(t){const n=i.ORDER,{r:r,s:s,recovery:c}=this;if(null==c||![0,1,2,3].includes(c))throw new Error("recovery id invalid");if(a*Wp<n&&c>1)throw new Error("recovery id is ambiguous for h>1 curve");const l=2===c||3===c?r+a:r;if(!i.isValid(l))throw new Error("recovery id 2 or 3 invalid");const u=i.toBytes(l),d=e.fromBytes(na(Xp(!(1&c)),u)),h=o.inv(l),g=w(ja("msgHash",t)),f=o.create(-g*h),p=o.create(s*h),m=e.BASE.multiplyUnsafe(f).add(d.multiplyUnsafe(p));if(m.is0())throw new Error("point at infinify");return m.assertValidity(),m}hasHighS(){return m(this.s)}toBytes(e=p){if(Pp(e),"der"===e)return ea(Kp.hexFromSig(this));const t=o.toBytes(this.r),n=o.toBytes(this.s);if("recovered"===e){if(null==this.recovery)throw new Error("recovery bit must be present");return na(Uint8Array.of(this.recovery),t,n)}return na(t,n)}toHex(e){return zo(this.toBytes(e))}assertValidity(){}static fromCompact(e){return b.fromBytes(ja("sig",e),"compact")}static fromDER(e){return b.fromBytes(ja("sig",e),"der")}normalizeS(){return this.hasHighS()?new b(this.r,o.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return zo(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return zo(this.toBytes("compact"))}}const v=n.bits2int||function(e){if(e.length>8192)throw new Error("input is too large");const t=Wa(e),n=8*e.length-c;return n>0?t>>BigInt(n):t},w=n.bits2int_modN||function(e){return o.create(v(e))},E=Za(c);function A(e){return Ja("num < 2^"+c,e,Gp,E),o.toBytes(e)}function S(e,n){return Ka(e,void 0,"message"),n?Ka(t(e),void 0,"prehashed message"):e}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:d,utils:h,lengths:g,Point:e,sign:function(n,i,a={}){n=ja("message",n);const{seed:c,k2sig:l}=function(t,n,s){if(["recovered","canonical"].some(e=>e in s))throw new Error("sign() legacy options not supported");const{lowS:i,prehash:a,extraEntropy:c}=Fp(s,f);t=S(t,a);const l=w(t),u=Vp(o,n),d=[A(u),A(l)];if(null!=c&&!1!==c){const e=!0===c?r(g.secretKey):c;d.push(ja("extraEntropy",e))}const h=na(...d),p=l;return{seed:h,k2sig:function(t){const n=v(t);if(!o.isValidNot0(n))return;const r=o.inv(n),s=e.BASE.multiply(n).toAffine(),a=o.create(s.x);if(a===Gp)return;const c=o.create(r*o.create(p+a*u));if(c===Gp)return;let l=(s.x===a?0:2)|Number(s.y&Hp),d=c;return i&&m(c)&&(d=o.neg(c),l^=1),new b(a,d,l)}}}(n,i,a);return function(e,t,n){if("number"!=typeof e||e<2)throw new Error("hashLen must be a number");if("number"!=typeof t||t<2)throw new Error("qByteLen must be a number");if("function"!=typeof n)throw new Error("hmacFn must be a function");const r=e=>new Uint8Array(e),s=e=>Uint8Array.of(e);let i=r(e),o=r(e),a=0;const c=()=>{i.fill(1),o.fill(0),a=0},l=(...e)=>n(o,i,...e),u=(e=r(0))=>{o=l(s(0),e),i=l(),0!==e.length&&(o=l(s(1),e),i=l())},d=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let e=0;const n=[];for(;e<t;){i=l();const t=i.slice();n.push(t),e+=i.length}return na(...n)};return(e,t)=>{let n;for(c(),u(e);!(n=t(d()));)u();return c(),n}}(t.outputLen,o.BYTES,s)(c,l)},verify:function(t,n,r,s={}){const{lowS:i,prehash:a,format:c}=Fp(s,f);if(r=ja("publicKey",r),n=S(ja("message",n),a),"strict"in s)throw new Error("options.strict was renamed to lowS");const l=void 0===c?function(e){let t;const n="string"==typeof e||Lo(e),r=!n&&null!==e&&"object"==typeof e&&"bigint"==typeof e.r&&"bigint"==typeof e.s;if(!n&&!r)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(r)t=new b(e.r,e.s);else if(n){try{t=b.fromBytes(ja("sig",e),"der")}catch(e){if(!(e instanceof Kp.Err))throw e}if(!t)try{t=b.fromBytes(ja("sig",e),"compact")}catch(e){return!1}}return t||!1}(t):b.fromBytes(ja("sig",t),c);if(!1===l)return!1;try{const t=e.fromBytes(r);if(i&&l.hasHighS())return!1;const{r:s,s:a}=l,c=w(n),u=o.inv(a),d=o.create(c*u),h=o.create(s*u),g=e.BASE.multiplyUnsafe(d).add(t.multiplyUnsafe(h));if(g.is0())return!1;return o.create(g.x)===s}catch(e){return!1}},recoverPublicKey:function(e,t,n={}){const{prehash:r}=Fp(n,f);return t=S(t,r),b.fromBytes(e,"recovered").recoverPublicKey(t).toBytes()},Signature:b,hash:t})}function Zp(e){const{CURVE:t,curveOpts:n}=function(e){const t={a:e.a,b:e.b,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},n=e.Fp;let r=e.allowedPrivateKeyLengths?Array.from(new Set(e.allowedPrivateKeyLengths.map(e=>Math.ceil(e/2)))):void 0;return{CURVE:t,curveOpts:{Fp:n,Fn:kc(t.n,{BITS:e.nBitLength,allowedLengths:r,modFromBytes:e.wrapPrivateKey}),allowInfinityPoint:e.allowInfinityPoint,endo:e.endo,isTorsionFree:e.isTorsionFree,clearCofactor:e.clearCofactor,fromBytes:e.fromBytes,toBytes:e.toBytes}}}(e),r={hmac:e.hmac,randomBytes:e.randomBytes,lowS:e.lowS,bits2int:e.bits2int,bits2int_modN:e.bits2int_modN};return{CURVE:t,curveOpts:n,hash:e.hash,ecdsaOpts:r}}function em(e){const{CURVE:t,curveOpts:n,hash:r,ecdsaOpts:s}=Zp(e);return function(e,t){const n=t.Point;return Object.assign({},t,{ProjectivePoint:n,CURVE:Object.assign({},e,Sc(n.Fn.ORDER,n.Fn.BITS))})}(e,Qp(jp(t,n),r,s))}const tm={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},nm={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},rm=BigInt(2);const sm=kc(tm.p,{sqrt:function(e){const t=tm.p,n=BigInt(3),r=BigInt(6),s=BigInt(11),i=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),l=e*e*e%t,u=l*l*e%t,d=gc(u,n,t)*u%t,h=gc(d,n,t)*u%t,g=gc(h,rm,t)*l%t,f=gc(g,s,t)*g%t,p=gc(f,i,t)*f%t,m=gc(p,a,t)*p%t,y=gc(m,c,t)*m%t,b=gc(y,a,t)*p%t,v=gc(b,n,t)*u%t,w=gc(v,o,t)*f%t,E=gc(w,r,t)*l%t,A=gc(E,rm,t);if(!sm.eql(sm.sqr(A),e))throw new Error("Cannot find square root");return A}}),im=function(e,t){const n=t=>em({...e,hash:t});return{...n(t),create:n}}({...tm,Fp:sm,lowS:!0,endo:nm},La);il.utils.randomPrivateKey;const om=()=>{const e=il.utils.randomPrivateKey(),t=am(e),n=new Uint8Array(64);return n.set(e),n.set(t,32),{publicKey:t,secretKey:n}},am=il.getPublicKey;function cm(e){try{return il.ExtendedPoint.fromHex(e),!0}catch{return!1}}const lm=il.verify,um=e=>Oo.Buffer.isBuffer(e)?e:e instanceof Uint8Array?Oo.Buffer.from(e.buffer,e.byteOffset,e.byteLength):Oo.Buffer.from(e);class dm{constructor(e){Object.assign(this,e)}encode(){return Oo.Buffer.from(Pl.serialize(hm,this))}static decode(e){return Pl.deserialize(hm,this,e)}static decodeUnchecked(e){return Pl.deserializeUnchecked(hm,this,e)}}const hm=new Map;var gm;const fm=32;let pm=1;class mm extends dm{constructor(e){if(super({}),this._bn=void 0,function(e){return void 0!==e._bn}(e))this._bn=e._bn;else{if("string"==typeof e){const t=El.decode(e);if(t.length!=fm)throw new Error("Invalid public key input");this._bn=new ml(t)}else this._bn=new ml(e);if(this._bn.byteLength()>fm)throw new Error("Invalid public key input")}}static unique(){const e=new mm(pm);return pm+=1,new mm(e.toBuffer())}equals(e){return this._bn.eq(e._bn)}toBase58(){return El.encode(this.toBytes())}toJSON(){return this.toBase58()}toBytes(){const e=this.toBuffer();return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}toBuffer(){const e=this._bn.toArrayLike(Oo.Buffer);if(e.length===fm)return e;const t=Oo.Buffer.alloc(32);return e.copy(t,32-e.length),t}get[Symbol.toStringTag](){return`PublicKey(${this.toString()})`}toString(){return this.toBase58()}static async createWithSeed(e,t,n){const r=Oo.Buffer.concat([e.toBuffer(),Oo.Buffer.from(t),n.toBuffer()]),s=Al(r);return new mm(s)}static createProgramAddressSync(e,t){let n=Oo.Buffer.alloc(0);e.forEach(function(e){if(e.length>32)throw new TypeError("Max seed length exceeded");n=Oo.Buffer.concat([n,um(e)])}),n=Oo.Buffer.concat([n,t.toBuffer(),Oo.Buffer.from("ProgramDerivedAddress")]);const r=Al(n);if(cm(r))throw new Error("Invalid seeds, address must fall off the curve");return new mm(r)}static async createProgramAddress(e,t){return this.createProgramAddressSync(e,t)}static findProgramAddressSync(e,t){let n,r=255;for(;0!=r;){try{const s=e.concat(Oo.Buffer.from([r]));n=this.createProgramAddressSync(s,t)}catch(e){if(e instanceof TypeError)throw e;r--;continue}return[n,r]}throw new Error("Unable to find a viable program address nonce")}static async findProgramAddress(e,t){return this.findProgramAddressSync(e,t)}static isOnCurve(e){return cm(new mm(e).toBytes())}}gm=mm,mm.default=new gm("11111111111111111111111111111111"),hm.set(mm,{kind:"struct",fields:[["_bn","u256"]]}),new mm("BPFLoader1111111111111111111111111111111111");const ym=1232;class bm extends Error{constructor(e){super(`Signature ${e} has expired: block height exceeded.`),this.signature=void 0,this.signature=e}}Object.defineProperty(bm.prototype,"name",{value:"TransactionExpiredBlockheightExceededError"});class vm extends Error{constructor(e,t){super(`Transaction was not confirmed in ${t.toFixed(2)} seconds. It is unknown if it succeeded or failed. Check signature ${e} using the Solana Explorer or CLI tools.`),this.signature=void 0,this.signature=e}}Object.defineProperty(vm.prototype,"name",{value:"TransactionExpiredTimeoutError"});class wm extends Error{constructor(e){super(`Signature ${e} has expired: the nonce is no longer valid.`),this.signature=void 0,this.signature=e}}Object.defineProperty(wm.prototype,"name",{value:"TransactionExpiredNonceInvalidError"});class Em{constructor(e,t){this.staticAccountKeys=void 0,this.accountKeysFromLookups=void 0,this.staticAccountKeys=e,this.accountKeysFromLookups=t}keySegments(){const e=[this.staticAccountKeys];return this.accountKeysFromLookups&&(e.push(this.accountKeysFromLookups.writable),e.push(this.accountKeysFromLookups.readonly)),e}get(e){for(const t of this.keySegments()){if(e<t.length)return t[e];e-=t.length}}get length(){return this.keySegments().flat().length}compileInstructions(e){if(this.length>256)throw new Error("Account index overflow encountered during compilation");const t=new Map;this.keySegments().flat().forEach((e,n)=>{t.set(e.toBase58(),n)});const n=e=>{const n=t.get(e.toBase58());if(void 0===n)throw new Error("Encountered an unknown instruction account key during compilation");return n};return e.map(e=>({programIdIndex:n(e.programId),accountKeyIndexes:e.keys.map(e=>n(e.pubkey)),data:e.data}))}}const Am=(e="publicKey")=>Kl.blob(32,e),Sm=(e="string")=>{const t=Kl.struct([Kl.u32("length"),Kl.u32("lengthPadding"),Kl.blob(Kl.offset(Kl.u32(),-8),"chars")],e),n=t.decode.bind(t),r=t.encode.bind(t),s=t;return s.decode=(e,t)=>n(e,t).chars.toString(),s.encode=(e,t,n)=>{const s={chars:Oo.Buffer.from(e,"utf8")};return r(s,t,n)},s.alloc=e=>Kl.u32().span+Kl.u32().span+Oo.Buffer.from(e,"utf8").length,s};function km(e,t){const n=e=>{if(e.span>=0)return e.span;if("function"==typeof e.alloc)return e.alloc(t[e.property]);if("count"in e&&"elementLayout"in e){const r=t[e.property];if(Array.isArray(r))return r.length*n(e.elementLayout)}else if("fields"in e)return km({layout:e},t[e.property]);return 0};let r=0;return e.layout.fields.forEach(e=>{r+=n(e)}),r}function Tm(e){let t=0,n=0;for(;;){let r=e.shift();if(t|=(127&r)<<7*n,n+=1,!(128&r))break}return t}function Im(e,t){let n=t;for(;;){let t=127&n;if(n>>=7,0==n){e.push(t);break}t|=128,e.push(t)}}function Cm(e,t){if(!e)throw new Error(t||"Assertion failed")}class Nm{constructor(e,t){this.payer=void 0,this.keyMetaMap=void 0,this.payer=e,this.keyMetaMap=t}static compile(e,t){const n=new Map,r=e=>{const t=e.toBase58();let r=n.get(t);return void 0===r&&(r={isSigner:!1,isWritable:!1,isInvoked:!1},n.set(t,r)),r},s=r(t);s.isSigner=!0,s.isWritable=!0;for(const t of e){r(t.programId).isInvoked=!0;for(const e of t.keys){const t=r(e.pubkey);t.isSigner||=e.isSigner,t.isWritable||=e.isWritable}}return new Nm(t,n)}getMessageComponents(){const e=[...this.keyMetaMap.entries()];Cm(e.length<=256,"Max static account keys length exceeded");const t=e.filter(([,e])=>e.isSigner&&e.isWritable),n=e.filter(([,e])=>e.isSigner&&!e.isWritable),r=e.filter(([,e])=>!e.isSigner&&e.isWritable),s=e.filter(([,e])=>!e.isSigner&&!e.isWritable),i={numRequiredSignatures:t.length+n.length,numReadonlySignedAccounts:n.length,numReadonlyUnsignedAccounts:s.length};{Cm(t.length>0,"Expected at least one writable signer key");const[e]=t[0];Cm(e===this.payer.toBase58(),"Expected first writable signer key to be the fee payer")}return[i,[...t.map(([e])=>new mm(e)),...n.map(([e])=>new mm(e)),...r.map(([e])=>new mm(e)),...s.map(([e])=>new mm(e))]]}extractTableLookup(e){const[t,n]=this.drainKeysFoundInLookupTable(e.state.addresses,e=>!e.isSigner&&!e.isInvoked&&e.isWritable),[r,s]=this.drainKeysFoundInLookupTable(e.state.addresses,e=>!e.isSigner&&!e.isInvoked&&!e.isWritable);if(0!==t.length||0!==r.length)return[{accountKey:e.key,writableIndexes:t,readonlyIndexes:r},{writable:n,readonly:s}]}drainKeysFoundInLookupTable(e,t){const n=new Array,r=new Array;for(const[s,i]of this.keyMetaMap.entries())if(t(i)){const t=new mm(s),i=e.findIndex(e=>e.equals(t));i>=0&&(Cm(i<256,"Max lookup table index exceeded"),n.push(i),r.push(t),this.keyMetaMap.delete(s))}return[n,r]}}const _m="Reached end of buffer unexpectedly";function xm(e){if(0===e.length)throw new Error(_m);return e.shift()}function Rm(e,...t){const[n]=t;if(2===t.length?n+(t[1]??0)>e.length:n>=e.length)throw new Error(_m);return e.splice(...t)}class Bm{constructor(e){this.header=void 0,this.accountKeys=void 0,this.recentBlockhash=void 0,this.instructions=void 0,this.indexToProgramIds=new Map,this.header=e.header,this.accountKeys=e.accountKeys.map(e=>new mm(e)),this.recentBlockhash=e.recentBlockhash,this.instructions=e.instructions,this.instructions.forEach(e=>this.indexToProgramIds.set(e.programIdIndex,this.accountKeys[e.programIdIndex]))}get version(){return"legacy"}get staticAccountKeys(){return this.accountKeys}get compiledInstructions(){return this.instructions.map(e=>({programIdIndex:e.programIdIndex,accountKeyIndexes:e.accounts,data:El.decode(e.data)}))}get addressTableLookups(){return[]}getAccountKeys(){return new Em(this.staticAccountKeys)}static compile(e){const t=Nm.compile(e.instructions,e.payerKey),[n,r]=t.getMessageComponents(),s=new Em(r).compileInstructions(e.instructions).map(e=>({programIdIndex:e.programIdIndex,accounts:e.accountKeyIndexes,data:El.encode(e.data)}));return new Bm({header:n,accountKeys:r,recentBlockhash:e.recentBlockhash,instructions:s})}isAccountSigner(e){return e<this.header.numRequiredSignatures}isAccountWritable(e){const t=this.header.numRequiredSignatures;if(e>=this.header.numRequiredSignatures){return e-t<this.accountKeys.length-t-this.header.numReadonlyUnsignedAccounts}return e<t-this.header.numReadonlySignedAccounts}isProgramId(e){return this.indexToProgramIds.has(e)}programIds(){return[...this.indexToProgramIds.values()]}nonProgramIds(){return this.accountKeys.filter((e,t)=>!this.isProgramId(t))}serialize(){const e=this.accountKeys.length;let t=[];Im(t,e);const n=this.instructions.map(e=>{const{accounts:t,programIdIndex:n}=e,r=Array.from(El.decode(e.data));let s=[];Im(s,t.length);let i=[];return Im(i,r.length),{programIdIndex:n,keyIndicesCount:Oo.Buffer.from(s),keyIndices:t,dataLength:Oo.Buffer.from(i),data:r}});let r=[];Im(r,n.length);let s=Oo.Buffer.alloc(ym);Oo.Buffer.from(r).copy(s);let i=r.length;n.forEach(e=>{const t=Kl.struct([Kl.u8("programIdIndex"),Kl.blob(e.keyIndicesCount.length,"keyIndicesCount"),Kl.seq(Kl.u8("keyIndex"),e.keyIndices.length,"keyIndices"),Kl.blob(e.dataLength.length,"dataLength"),Kl.seq(Kl.u8("userdatum"),e.data.length,"data")]).encode(e,s,i);i+=t}),s=s.slice(0,i);const o=Kl.struct([Kl.blob(1,"numRequiredSignatures"),Kl.blob(1,"numReadonlySignedAccounts"),Kl.blob(1,"numReadonlyUnsignedAccounts"),Kl.blob(t.length,"keyCount"),Kl.seq(Am("key"),e,"keys"),Am("recentBlockhash")]),a={numRequiredSignatures:Oo.Buffer.from([this.header.numRequiredSignatures]),numReadonlySignedAccounts:Oo.Buffer.from([this.header.numReadonlySignedAccounts]),numReadonlyUnsignedAccounts:Oo.Buffer.from([this.header.numReadonlyUnsignedAccounts]),keyCount:Oo.Buffer.from(t),keys:this.accountKeys.map(e=>um(e.toBytes())),recentBlockhash:El.decode(this.recentBlockhash)};let c=Oo.Buffer.alloc(2048);const l=o.encode(a,c);return s.copy(c,l),c.slice(0,l+s.length)}static from(e){let t=[...e];const n=xm(t);if(n!==(127&n))throw new Error("Versioned messages must be deserialized with VersionedMessage.deserialize()");const r=xm(t),s=xm(t),i=Tm(t);let o=[];for(let e=0;e<i;e++){const e=Rm(t,0,fm);o.push(new mm(Oo.Buffer.from(e)))}const a=Rm(t,0,fm),c=Tm(t);let l=[];for(let e=0;e<c;e++){const e=xm(t),n=Rm(t,0,Tm(t)),r=Rm(t,0,Tm(t)),s=El.encode(Oo.Buffer.from(r));l.push({programIdIndex:e,accounts:n,data:s})}const u={header:{numRequiredSignatures:n,numReadonlySignedAccounts:r,numReadonlyUnsignedAccounts:s},recentBlockhash:El.encode(Oo.Buffer.from(a)),accountKeys:o,instructions:l};return new Bm(u)}}class Dm{constructor(e){this.header=void 0,this.staticAccountKeys=void 0,this.recentBlockhash=void 0,this.compiledInstructions=void 0,this.addressTableLookups=void 0,this.header=e.header,this.staticAccountKeys=e.staticAccountKeys,this.recentBlockhash=e.recentBlockhash,this.compiledInstructions=e.compiledInstructions,this.addressTableLookups=e.addressTableLookups}get version(){return 0}get numAccountKeysFromLookups(){let e=0;for(const t of this.addressTableLookups)e+=t.readonlyIndexes.length+t.writableIndexes.length;return e}getAccountKeys(e){let t;if(e&&"accountKeysFromLookups"in e&&e.accountKeysFromLookups){if(this.numAccountKeysFromLookups!=e.accountKeysFromLookups.writable.length+e.accountKeysFromLookups.readonly.length)throw new Error("Failed to get account keys because of a mismatch in the number of account keys from lookups");t=e.accountKeysFromLookups}else if(e&&"addressLookupTableAccounts"in e&&e.addressLookupTableAccounts)t=this.resolveAddressTableLookups(e.addressLookupTableAccounts);else if(this.addressTableLookups.length>0)throw new Error("Failed to get account keys because address table lookups were not resolved");return new Em(this.staticAccountKeys,t)}isAccountSigner(e){return e<this.header.numRequiredSignatures}isAccountWritable(e){const t=this.header.numRequiredSignatures,n=this.staticAccountKeys.length;if(e>=n){return e-n<this.addressTableLookups.reduce((e,t)=>e+t.writableIndexes.length,0)}if(e>=this.header.numRequiredSignatures){return e-t<n-t-this.header.numReadonlyUnsignedAccounts}return e<t-this.header.numReadonlySignedAccounts}resolveAddressTableLookups(e){const t={writable:[],readonly:[]};for(const n of this.addressTableLookups){const r=e.find(e=>e.key.equals(n.accountKey));if(!r)throw new Error(`Failed to find address lookup table account for table key ${n.accountKey.toBase58()}`);for(const e of n.writableIndexes){if(!(e<r.state.addresses.length))throw new Error(`Failed to find address for index ${e} in address lookup table ${n.accountKey.toBase58()}`);t.writable.push(r.state.addresses[e])}for(const e of n.readonlyIndexes){if(!(e<r.state.addresses.length))throw new Error(`Failed to find address for index ${e} in address lookup table ${n.accountKey.toBase58()}`);t.readonly.push(r.state.addresses[e])}}return t}static compile(e){const t=Nm.compile(e.instructions,e.payerKey),n=new Array,r={writable:new Array,readonly:new Array},s=e.addressLookupTableAccounts||[];for(const e of s){const s=t.extractTableLookup(e);if(void 0!==s){const[e,{writable:t,readonly:i}]=s;n.push(e),r.writable.push(...t),r.readonly.push(...i)}}const[i,o]=t.getMessageComponents(),a=new Em(o,r).compileInstructions(e.instructions);return new Dm({header:i,staticAccountKeys:o,recentBlockhash:e.recentBlockhash,compiledInstructions:a,addressTableLookups:n})}serialize(){const e=Array();Im(e,this.staticAccountKeys.length);const t=this.serializeInstructions(),n=Array();Im(n,this.compiledInstructions.length);const r=this.serializeAddressTableLookups(),s=Array();Im(s,this.addressTableLookups.length);const i=Kl.struct([Kl.u8("prefix"),Kl.struct([Kl.u8("numRequiredSignatures"),Kl.u8("numReadonlySignedAccounts"),Kl.u8("numReadonlyUnsignedAccounts")],"header"),Kl.blob(e.length,"staticAccountKeysLength"),Kl.seq(Am(),this.staticAccountKeys.length,"staticAccountKeys"),Am("recentBlockhash"),Kl.blob(n.length,"instructionsLength"),Kl.blob(t.length,"serializedInstructions"),Kl.blob(s.length,"addressTableLookupsLength"),Kl.blob(r.length,"serializedAddressTableLookups")]),o=new Uint8Array(ym),a=i.encode({prefix:128,header:this.header,staticAccountKeysLength:new Uint8Array(e),staticAccountKeys:this.staticAccountKeys.map(e=>e.toBytes()),recentBlockhash:El.decode(this.recentBlockhash),instructionsLength:new Uint8Array(n),serializedInstructions:t,addressTableLookupsLength:new Uint8Array(s),serializedAddressTableLookups:r},o);return o.slice(0,a)}serializeInstructions(){let e=0;const t=new Uint8Array(ym);for(const n of this.compiledInstructions){const r=Array();Im(r,n.accountKeyIndexes.length);const s=Array();Im(s,n.data.length);e+=Kl.struct([Kl.u8("programIdIndex"),Kl.blob(r.length,"encodedAccountKeyIndexesLength"),Kl.seq(Kl.u8(),n.accountKeyIndexes.length,"accountKeyIndexes"),Kl.blob(s.length,"encodedDataLength"),Kl.blob(n.data.length,"data")]).encode({programIdIndex:n.programIdIndex,encodedAccountKeyIndexesLength:new Uint8Array(r),accountKeyIndexes:n.accountKeyIndexes,encodedDataLength:new Uint8Array(s),data:n.data},t,e)}return t.slice(0,e)}serializeAddressTableLookups(){let e=0;const t=new Uint8Array(ym);for(const n of this.addressTableLookups){const r=Array();Im(r,n.writableIndexes.length);const s=Array();Im(s,n.readonlyIndexes.length);e+=Kl.struct([Am("accountKey"),Kl.blob(r.length,"encodedWritableIndexesLength"),Kl.seq(Kl.u8(),n.writableIndexes.length,"writableIndexes"),Kl.blob(s.length,"encodedReadonlyIndexesLength"),Kl.seq(Kl.u8(),n.readonlyIndexes.length,"readonlyIndexes")]).encode({accountKey:n.accountKey.toBytes(),encodedWritableIndexesLength:new Uint8Array(r),writableIndexes:n.writableIndexes,encodedReadonlyIndexesLength:new Uint8Array(s),readonlyIndexes:n.readonlyIndexes},t,e)}return t.slice(0,e)}static deserialize(e){let t=[...e];const n=xm(t),r=127&n;Cm(n!==r,"Expected versioned message but received legacy message");Cm(0===r,`Expected versioned message with version 0 but found version ${r}`);const s={numRequiredSignatures:xm(t),numReadonlySignedAccounts:xm(t),numReadonlyUnsignedAccounts:xm(t)},i=[],o=Tm(t);for(let e=0;e<o;e++)i.push(new mm(Rm(t,0,fm)));const a=El.encode(Rm(t,0,fm)),c=Tm(t),l=[];for(let e=0;e<c;e++){const e=xm(t),n=Rm(t,0,Tm(t)),r=Tm(t),s=new Uint8Array(Rm(t,0,r));l.push({programIdIndex:e,accountKeyIndexes:n,data:s})}const u=Tm(t),d=[];for(let e=0;e<u;e++){const e=new mm(Rm(t,0,fm)),n=Rm(t,0,Tm(t)),r=Rm(t,0,Tm(t));d.push({accountKey:e,writableIndexes:n,readonlyIndexes:r})}return new Dm({header:s,staticAccountKeys:i,recentBlockhash:a,compiledInstructions:l,addressTableLookups:d})}}function Om(e){const t=Rm(e,0,4);return t[0]+256*t[1]+65536*t[2]+t[3]*2**24}class Mm{constructor(e){this.header=void 0,this.staticAccountKeys=void 0,this.recentBlockhash=void 0,this.compiledInstructions=void 0,this.transactionConfig=void 0,this.header=e.header,this.staticAccountKeys=e.staticAccountKeys,this.recentBlockhash=e.recentBlockhash,this.compiledInstructions=e.compiledInstructions,this.transactionConfig=e.transactionConfig??{computeUnitLimit:null,heapSize:null,loadedAccountsDataSizeLimit:null,priorityFee:null}}get version(){return 1}get addressTableLookups(){return[]}getAccountKeys(){return new Em(this.staticAccountKeys)}isAccountSigner(e){return e<this.header.numRequiredSignatures}isAccountWritable(e){const t=this.header.numRequiredSignatures,n=this.staticAccountKeys.length;if(e>=n)return!1;if(e>=this.header.numRequiredSignatures){return e-t<n-t-this.header.numReadonlyUnsignedAccounts}return e<t-this.header.numReadonlySignedAccounts}serialize(){throw new Error("Serialization of version 1 transaction messages is not supported")}static deserialize(e){let t=[...e];const n=xm(t),r=127&n;Cm(n!==r,"Expected versioned message but received legacy message");Cm(1===r,`Expected versioned message with version 1 but found version ${r}`);const s={numRequiredSignatures:xm(t),numReadonlySignedAccounts:xm(t),numReadonlyUnsignedAccounts:xm(t)},i=Om(t);Cm(!(-32&i),"Unexpected bits set in the transaction config mask");const o=3&i;Cm(0===o||3===o,"Expected both or neither of the priority fee bits to be set in the transaction config mask");const a=El.encode(Rm(t,0,fm)),c=xm(t),l=xm(t),u=[];for(let e=0;e<l;e++)u.push(new mm(Rm(t,0,fm)));const d={computeUnitLimit:null,heapSize:null,loadedAccountsDataSizeLimit:null,priorityFee:null};0!==o&&(d.priorityFee=function(e){const t=Rm(e,0,8);let n=BigInt(0);for(let e=t.length-1;e>=0;e--)n=n<<BigInt(8)|BigInt(t[e]);return Cm(n<=BigInt(Number.MAX_SAFE_INTEGER),"Expected u64 value to be within the safe integer range"),Number(n)}(t)),4&i&&(d.computeUnitLimit=Om(t)),8&i&&(d.loadedAccountsDataSizeLimit=Om(t)),16&i&&(d.heapSize=Om(t));const h=[];for(let e=0;e<c;e++){const e=xm(t),n=xm(t),r=xm(t)+256*xm(t);h.push({accountKeyIndexesLength:n,dataLength:r,programIdIndex:e})}const g=[];for(const e of h)g.push({programIdIndex:e.programIdIndex,accountKeyIndexes:Rm(t,0,e.accountKeyIndexesLength),data:new Uint8Array(Rm(t,0,e.dataLength))});return Cm(0===t.length,"Expected no bytes to remain after deserializing a version 1 message"),new Mm({header:s,staticAccountKeys:u,recentBlockhash:a,compiledInstructions:g,transactionConfig:d})}}let Lm=function(e){return e[e.BLOCKHEIGHT_EXCEEDED=0]="BLOCKHEIGHT_EXCEEDED",e[e.PROCESSED=1]="PROCESSED",e[e.TIMED_OUT=2]="TIMED_OUT",e[e.NONCE_INVALID=3]="NONCE_INVALID",e}({});const Um=Oo.Buffer.alloc(64).fill(0);class Pm{constructor(e){this.keys=void 0,this.programId=void 0,this.data=Oo.Buffer.alloc(0),this.programId=e.programId,this.keys=e.keys,e.data&&(this.data=e.data)}toJSON(){return{keys:this.keys.map(({pubkey:e,isSigner:t,isWritable:n})=>({pubkey:e.toJSON(),isSigner:t,isWritable:n})),programId:this.programId.toJSON(),data:[...this.data]}}}class Fm{get signature(){return this.signatures.length>0?this.signatures[0].signature:null}constructor(e){if(this.signatures=[],this.feePayer=void 0,this.instructions=[],this.recentBlockhash=void 0,this.lastValidBlockHeight=void 0,this.nonceInfo=void 0,this.minNonceContextSlot=void 0,this._message=void 0,this._json=void 0,e)if(e.feePayer&&(this.feePayer=e.feePayer),e.signatures&&(this.signatures=e.signatures),Object.prototype.hasOwnProperty.call(e,"nonceInfo")){const{minContextSlot:t,nonceInfo:n}=e;this.minNonceContextSlot=t,this.nonceInfo=n}else if(Object.prototype.hasOwnProperty.call(e,"lastValidBlockHeight")){const{blockhash:t,lastValidBlockHeight:n}=e;this.recentBlockhash=t,this.lastValidBlockHeight=n}else{const{recentBlockhash:t,nonceInfo:n}=e;n&&(this.nonceInfo=n),this.recentBlockhash=t}}toJSON(){return{recentBlockhash:this.recentBlockhash||null,feePayer:this.feePayer?this.feePayer.toJSON():null,nonceInfo:this.nonceInfo?{nonce:this.nonceInfo.nonce,nonceInstruction:this.nonceInfo.nonceInstruction.toJSON()}:null,instructions:this.instructions.map(e=>e.toJSON()),signers:this.signatures.map(({publicKey:e})=>e.toJSON())}}add(...e){if(0===e.length)throw new Error("No instructions");return e.forEach(e=>{"instructions"in e?this.instructions=this.instructions.concat(e.instructions):"data"in e&&"programId"in e&&"keys"in e?this.instructions.push(e):this.instructions.push(new Pm(e))}),this}compileMessage(){if(this._message&&JSON.stringify(this.toJSON())===JSON.stringify(this._json))return this._message;let e,t,n;if(this.nonceInfo?(e=this.nonceInfo.nonce,t=this.instructions[0]!=this.nonceInfo.nonceInstruction?[this.nonceInfo.nonceInstruction,...this.instructions]:this.instructions):(e=this.recentBlockhash,t=this.instructions),!e)throw new Error("Transaction recentBlockhash required");if(t.length,this.feePayer)n=this.feePayer;else{if(!(this.signatures.length>0&&this.signatures[0].publicKey))throw new Error("Transaction fee payer required");n=this.signatures[0].publicKey}for(let e=0;e<t.length;e++)if(void 0===t[e].programId)throw new Error(`Transaction instruction index ${e} has undefined program id`);const r=[],s=[];t.forEach(e=>{e.keys.forEach(e=>{s.push({...e})});const t=e.programId.toString();r.includes(t)||r.push(t)}),r.forEach(e=>{s.push({pubkey:new mm(e),isSigner:!1,isWritable:!1})});const i=[];s.forEach(e=>{const t=e.pubkey.toString(),n=i.findIndex(e=>e.pubkey.toString()===t);n>-1?(i[n].isWritable=i[n].isWritable||e.isWritable,i[n].isSigner=i[n].isSigner||e.isSigner):i.push(e)}),i.sort(function(e,t){if(e.isSigner!==t.isSigner)return e.isSigner?-1:1;if(e.isWritable!==t.isWritable)return e.isWritable?-1:1;return e.pubkey.toBase58().localeCompare(t.pubkey.toBase58(),"en",{localeMatcher:"best fit",usage:"sort",sensitivity:"variant",ignorePunctuation:!1,numeric:!1,caseFirst:"lower"})});const o=i.findIndex(e=>e.pubkey.equals(n));if(o>-1){const[e]=i.splice(o,1);e.isSigner=!0,e.isWritable=!0,i.unshift(e)}else i.unshift({pubkey:n,isSigner:!0,isWritable:!0});for(const e of this.signatures){const t=i.findIndex(t=>t.pubkey.equals(e.publicKey));if(!(t>-1))throw new Error(`unknown signer: ${e.publicKey.toString()}`);i[t].isSigner||(i[t].isSigner=!0)}let a=0,c=0,l=0;const u=[],d=[];i.forEach(({pubkey:e,isSigner:t,isWritable:n})=>{t?(u.push(e.toString()),a+=1,n||(c+=1)):(d.push(e.toString()),n||(l+=1))});const h=u.concat(d),g=t.map(e=>{const{data:t,programId:n}=e;return{programIdIndex:h.indexOf(n.toString()),accounts:e.keys.map(e=>h.indexOf(e.pubkey.toString())),data:El.encode(t)}});return g.forEach(e=>{Cm(e.programIdIndex>=0),e.accounts.forEach(e=>Cm(e>=0))}),new Bm({header:{numRequiredSignatures:a,numReadonlySignedAccounts:c,numReadonlyUnsignedAccounts:l},accountKeys:h,recentBlockhash:e,instructions:g})}_compile(){const e=this.compileMessage(),t=e.accountKeys.slice(0,e.header.numRequiredSignatures);if(this.signatures.length===t.length){if(this.signatures.every((e,n)=>t[n].equals(e.publicKey)))return e}return this.signatures=t.map(e=>({signature:null,publicKey:e})),e}serializeMessage(){return this._compile().serialize()}async getEstimatedFee(e){return(await e.getFeeForMessage(this.compileMessage())).value}setSigners(...e){if(0===e.length)throw new Error("No signers");const t=new Set;this.signatures=e.filter(e=>{const n=e.toString();return!t.has(n)&&(t.add(n),!0)}).map(e=>({signature:null,publicKey:e}))}sign(...e){if(0===e.length)throw new Error("No signers");const t=new Set,n=[];for(const r of e){const e=r.publicKey.toString();t.has(e)||(t.add(e),n.push(r))}this.signatures=n.map(e=>({signature:null,publicKey:e.publicKey}));const r=this._compile();this._partialSign(r,...n)}partialSign(...e){if(0===e.length)throw new Error("No signers");const t=new Set,n=[];for(const r of e){const e=r.publicKey.toString();t.has(e)||(t.add(e),n.push(r))}const r=this._compile();this._partialSign(r,...n)}_partialSign(e,...t){const n=e.serialize();t.forEach(e=>{const t=((e,t)=>il.sign(e,t.slice(0,32)))(n,e.secretKey);this._addSignature(e.publicKey,um(t))})}addSignature(e,t){this._compile(),this._addSignature(e,t)}_addSignature(e,t){Cm(64===t.length);const n=this.signatures.findIndex(t=>e.equals(t.publicKey));if(n<0)throw new Error(`unknown signer: ${e.toString()}`);this.signatures[n].signature=Oo.Buffer.from(t)}verifySignatures(e=!0){return!this._getMessageSignednessErrors(this.serializeMessage(),e)}_getMessageSignednessErrors(e,t){const n={};for(const{signature:r,publicKey:s}of this.signatures)null===r?t&&(n.missing||=[]).push(s):lm(r,e,s.toBytes())||(n.invalid||=[]).push(s);return n.invalid||n.missing?n:void 0}serialize(e){const{requireAllSignatures:t,verifySignatures:n}=Object.assign({requireAllSignatures:!0,verifySignatures:!0},e),r=this.serializeMessage();if(n){const e=this._getMessageSignednessErrors(r,t);if(e){let t="Signature verification failed.";throw e.invalid&&(t+=`\nInvalid signature for public key${1===e.invalid.length?"":"(s)"} [\`${e.invalid.map(e=>e.toBase58()).join("`, `")}\`].`),e.missing&&(t+=`\nMissing signature for public key${1===e.missing.length?"":"(s)"} [\`${e.missing.map(e=>e.toBase58()).join("`, `")}\`].`),new Error(t)}}return this._serialize(r)}_serialize(e){const{signatures:t}=this,n=[];Im(n,t.length);const r=n.length+64*t.length+e.length,s=Oo.Buffer.alloc(r);return Cm(t.length<256),Oo.Buffer.from(n).copy(s,0),t.forEach(({signature:e},t)=>{null!==e&&(Cm(64===e.length,"signature has invalid length"),Oo.Buffer.from(e).copy(s,n.length+64*t))}),e.copy(s,n.length+64*t.length),Cm(s.length<=ym,`Transaction too large: ${s.length} > 1232`),s}get keys(){return Cm(1===this.instructions.length),this.instructions[0].keys.map(e=>e.pubkey)}get programId(){return Cm(1===this.instructions.length),this.instructions[0].programId}get data(){return Cm(1===this.instructions.length),this.instructions[0].data}static from(e){let t=[...e];const n=Tm(t);let r=[];for(let e=0;e<n;e++){const e=Rm(t,0,64);r.push(El.encode(Oo.Buffer.from(e)))}return Fm.populate(Bm.from(t),r)}static populate(e,t=[]){const n=new Fm;return n.recentBlockhash=e.recentBlockhash,e.header.numRequiredSignatures>0&&(n.feePayer=e.accountKeys[0]),t.forEach((t,r)=>{const s={signature:t==El.encode(Um)?null:El.decode(t),publicKey:e.accountKeys[r]};n.signatures.push(s)}),e.instructions.forEach(t=>{const r=t.accounts.map(t=>{const r=e.accountKeys[t];return{pubkey:r,isSigner:n.signatures.some(e=>e.publicKey.toString()===r.toString())||e.isAccountSigner(t),isWritable:e.isAccountWritable(t)}});n.instructions.push(new Pm({keys:r,programId:e.accountKeys[t.programIdIndex],data:El.decode(t.data)}))}),n._message=e,n._json=n.toJSON(),n}}new mm("SysvarC1ock11111111111111111111111111111111"),new mm("SysvarEpochSchedu1e111111111111111111111111"),new mm("Sysvar1nstructions1111111111111111111111111");const $m=new mm("SysvarRecentB1ockHashes11111111111111111111"),Km=new mm("SysvarRent111111111111111111111111111111111");new mm("SysvarRewards111111111111111111111111111111"),new mm("SysvarS1otHashes111111111111111111111111111"),new mm("SysvarS1otHistory11111111111111111111111111"),new mm("SysvarStakeHistory1111111111111111111111111");class Gm extends Error{constructor({action:e,signature:t,transactionMessage:n,logs:r}){const s=r?`Logs: \n${JSON.stringify(r.slice(-10),null,2)}. `:"",i="\nCatch the `SendTransactionError` and call `getLogs()` on it for full details.";let o;switch(e){case"send":o=`Transaction ${t} resulted in an error. \n${n}. `+s+i;break;case"simulate":o=`Simulation failed. \nMessage: ${n}. \n`+s+i;break;default:o=`Unknown action '${e}'`}super(o),this.signature=void 0,this.transactionMessage=void 0,this.transactionLogs=void 0,this.signature=t,this.transactionMessage=n,this.transactionLogs=r||void 0}get transactionError(){return{message:this.transactionMessage,logs:Array.isArray(this.transactionLogs)?this.transactionLogs:void 0}}get logs(){const e=this.transactionLogs;if(null==e||"object"!=typeof e||!("then"in e))return e}async getLogs(e){return Array.isArray(this.transactionLogs)||(this.transactionLogs=new Promise((t,n)=>{e.getTransaction(this.signature).then(e=>{if(e&&e.meta&&e.meta.logMessages){const n=e.meta.logMessages;this.transactionLogs=n,t(n)}else n(new Error("Log messages not found"))}).catch(n)})),await this.transactionLogs}}class Hm extends Error{constructor({code:e,message:t,data:n},r){super(null!=r?`${r}: ${t}`:t),this.code=void 0,this.data=void 0,this.code=e,this.data=n,this.name="SolanaJSONRPCError"}}function Wm(e){return new Promise(t=>setTimeout(t,e))}function qm(e,t){const n=e.layout.span>=0?e.layout.span:km(e,t),r=Oo.Buffer.alloc(n),s=Object.assign({instruction:e.index},t);return e.layout.encode(s,r),r}const zm=Kl.nu64("lamportsPerSignature"),Vm=Kl.struct([Kl.u32("version"),Kl.u32("state"),Am("authorizedPubkey"),Am("nonce"),Kl.struct([zm],"feeCalculator")]),jm=Vm.span;class Xm{constructor(e){this.authorizedPubkey=void 0,this.nonce=void 0,this.feeCalculator=void 0,this.authorizedPubkey=e.authorizedPubkey,this.nonce=e.nonce,this.feeCalculator=e.feeCalculator}static fromAccountData(e){const t=Vm.decode(um(e),0);return new Xm({authorizedPubkey:new mm(t.authorizedPubkey),nonce:new mm(t.nonce).toString(),feeCalculator:t.feeCalculator})}}function Ym(e){const t=Kl.blob(8,e),n=t.decode.bind(t),r=t.encode.bind(t),s=t,i=Vf();return s.decode=(e,t)=>{const r=n(e,t);return i.decode(r)},s.encode=(e,t,n)=>{const s=i.encode(e);return r(s,t,n)},s}const Jm=Object.freeze({Create:{index:0,layout:Kl.struct([Kl.u32("instruction"),Kl.ns64("lamports"),Kl.ns64("space"),Am("programId")])},Assign:{index:1,layout:Kl.struct([Kl.u32("instruction"),Am("programId")])},Transfer:{index:2,layout:Kl.struct([Kl.u32("instruction"),Ym("lamports")])},CreateWithSeed:{index:3,layout:Kl.struct([Kl.u32("instruction"),Am("base"),Sm("seed"),Kl.ns64("lamports"),Kl.ns64("space"),Am("programId")])},AdvanceNonceAccount:{index:4,layout:Kl.struct([Kl.u32("instruction")])},WithdrawNonceAccount:{index:5,layout:Kl.struct([Kl.u32("instruction"),Kl.ns64("lamports")])},InitializeNonceAccount:{index:6,layout:Kl.struct([Kl.u32("instruction"),Am("authorized")])},AuthorizeNonceAccount:{index:7,layout:Kl.struct([Kl.u32("instruction"),Am("authorized")])},Allocate:{index:8,layout:Kl.struct([Kl.u32("instruction"),Kl.ns64("space")])},AllocateWithSeed:{index:9,layout:Kl.struct([Kl.u32("instruction"),Am("base"),Sm("seed"),Kl.ns64("space"),Am("programId")])},AssignWithSeed:{index:10,layout:Kl.struct([Kl.u32("instruction"),Am("base"),Sm("seed"),Am("programId")])},TransferWithSeed:{index:11,layout:Kl.struct([Kl.u32("instruction"),Ym("lamports"),Sm("seed"),Am("programId")])},UpgradeNonceAccount:{index:12,layout:Kl.struct([Kl.u32("instruction")])}});class Qm{constructor(){}static createAccount(e){const t=qm(Jm.Create,{lamports:e.lamports,space:e.space,programId:um(e.programId.toBuffer())});return new Pm({keys:[{pubkey:e.fromPubkey,isSigner:!0,isWritable:!0},{pubkey:e.newAccountPubkey,isSigner:!0,isWritable:!0}],programId:this.programId,data:t})}static transfer(e){let t,n;if("basePubkey"in e){t=qm(Jm.TransferWithSeed,{lamports:BigInt(e.lamports),seed:e.seed,programId:um(e.programId.toBuffer())}),n=[{pubkey:e.fromPubkey,isSigner:!1,isWritable:!0},{pubkey:e.basePubkey,isSigner:!0,isWritable:!1},{pubkey:e.toPubkey,isSigner:!1,isWritable:!0}]}else{t=qm(Jm.Transfer,{lamports:BigInt(e.lamports)}),n=[{pubkey:e.fromPubkey,isSigner:!0,isWritable:!0},{pubkey:e.toPubkey,isSigner:!1,isWritable:!0}]}return new Pm({keys:n,programId:this.programId,data:t})}static assign(e){let t,n;if("basePubkey"in e){t=qm(Jm.AssignWithSeed,{base:um(e.basePubkey.toBuffer()),seed:e.seed,programId:um(e.programId.toBuffer())}),n=[{pubkey:e.accountPubkey,isSigner:!1,isWritable:!0},{pubkey:e.basePubkey,isSigner:!0,isWritable:!1}]}else{t=qm(Jm.Assign,{programId:um(e.programId.toBuffer())}),n=[{pubkey:e.accountPubkey,isSigner:!0,isWritable:!0}]}return new Pm({keys:n,programId:this.programId,data:t})}static createAccountWithSeed(e){const t=qm(Jm.CreateWithSeed,{base:um(e.basePubkey.toBuffer()),seed:e.seed,lamports:e.lamports,space:e.space,programId:um(e.programId.toBuffer())});let n=[{pubkey:e.fromPubkey,isSigner:!0,isWritable:!0},{pubkey:e.newAccountPubkey,isSigner:!1,isWritable:!0}];return e.basePubkey.equals(e.fromPubkey)||n.push({pubkey:e.basePubkey,isSigner:!0,isWritable:!1}),new Pm({keys:n,programId:this.programId,data:t})}static createNonceAccount(e){const t=new Fm;"basePubkey"in e&&"seed"in e?t.add(Qm.createAccountWithSeed({fromPubkey:e.fromPubkey,newAccountPubkey:e.noncePubkey,basePubkey:e.basePubkey,seed:e.seed,lamports:e.lamports,space:jm,programId:this.programId})):t.add(Qm.createAccount({fromPubkey:e.fromPubkey,newAccountPubkey:e.noncePubkey,lamports:e.lamports,space:jm,programId:this.programId}));const n={noncePubkey:e.noncePubkey,authorizedPubkey:e.authorizedPubkey};return t.add(this.nonceInitialize(n)),t}static nonceInitialize(e){const t=qm(Jm.InitializeNonceAccount,{authorized:um(e.authorizedPubkey.toBuffer())}),n={keys:[{pubkey:e.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:$m,isSigner:!1,isWritable:!1},{pubkey:Km,isSigner:!1,isWritable:!1}],programId:this.programId,data:t};return new Pm(n)}static nonceAdvance(e){const t=qm(Jm.AdvanceNonceAccount),n={keys:[{pubkey:e.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:$m,isSigner:!1,isWritable:!1},{pubkey:e.authorizedPubkey,isSigner:!0,isWritable:!1}],programId:this.programId,data:t};return new Pm(n)}static nonceWithdraw(e){const t=qm(Jm.WithdrawNonceAccount,{lamports:e.lamports});return new Pm({keys:[{pubkey:e.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:e.toPubkey,isSigner:!1,isWritable:!0},{pubkey:$m,isSigner:!1,isWritable:!1},{pubkey:Km,isSigner:!1,isWritable:!1},{pubkey:e.authorizedPubkey,isSigner:!0,isWritable:!1}],programId:this.programId,data:t})}static nonceAuthorize(e){const t=qm(Jm.AuthorizeNonceAccount,{authorized:um(e.newAuthorizedPubkey.toBuffer())});return new Pm({keys:[{pubkey:e.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:e.authorizedPubkey,isSigner:!0,isWritable:!1}],programId:this.programId,data:t})}static allocate(e){let t,n;if("basePubkey"in e){t=qm(Jm.AllocateWithSeed,{base:um(e.basePubkey.toBuffer()),seed:e.seed,space:e.space,programId:um(e.programId.toBuffer())}),n=[{pubkey:e.accountPubkey,isSigner:!1,isWritable:!0},{pubkey:e.basePubkey,isSigner:!0,isWritable:!1}]}else{t=qm(Jm.Allocate,{space:e.space}),n=[{pubkey:e.accountPubkey,isSigner:!0,isWritable:!0}]}return new Pm({keys:n,programId:this.programId,data:t})}}function Zm(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var ey,ty;function ny(){if(ty)return ey;ty=1;var e=Object.prototype.toString,t=Object.keys||function(e){var t=[];for(var n in e)t.push(n);return t};function n(r,s){var i,o,a,c,l,u,d;if(!0===r)return"true";if(!1===r)return"false";switch(typeof r){case"object":if(null===r)return null;if(r.toJSON&&"function"==typeof r.toJSON)return n(r.toJSON(),s);if("[object Array]"===(d=e.call(r))){for(a="[",o=r.length-1,i=0;i<o;i++)a+=n(r[i],!0)+",";return o>-1&&(a+=n(r[i],!0)),a+"]"}if("[object Object]"===d){for(o=(c=t(r).sort()).length,a="",i=0;i<o;)void 0!==(u=n(r[l=c[i]],!1))&&(a&&(a+=","),a+=JSON.stringify(l)+":"+u),i++;return"{"+a+"}"}return JSON.stringify(r);case"function":case"undefined":return s?null:void 0;case"string":return JSON.stringify(r);default:return isFinite(r)?r:null}}return ey=function(e){var t=n(e,!1);if(void 0!==t)return""+t}}Qm.programId=new mm("11111111111111111111111111111111"),new mm("BPFLoader2111111111111111111111111111111111");var ry=Zm(ny());function sy(e){let t=0;for(;e>1;)e/=2,t++;return t}class iy{constructor(e,t,n,r,s){this.slotsPerEpoch=void 0,this.leaderScheduleSlotOffset=void 0,this.warmup=void 0,this.firstNormalEpoch=void 0,this.firstNormalSlot=void 0,this.slotsPerEpoch=e,this.leaderScheduleSlotOffset=t,this.warmup=n,this.firstNormalEpoch=r,this.firstNormalSlot=s}getEpoch(e){return this.getEpochAndSlotIndex(e)[0]}getEpochAndSlotIndex(e){if(e<this.firstNormalSlot){const n=sy(0===(t=e+32+1)?1:(t--,t|=t>>1,t|=t>>2,t|=t>>4,t|=t>>8,t|=t>>16,1+(t|=t>>32)))-sy(32)-1;return[n,e-(this.getSlotsInEpoch(n)-32)]}{const t=e-this.firstNormalSlot,n=Math.floor(t/this.slotsPerEpoch);return[this.firstNormalEpoch+n,t%this.slotsPerEpoch]}var t}getFirstSlotInEpoch(e){return e<=this.firstNormalEpoch?32*(Math.pow(2,e)-1):(e-this.firstNormalEpoch)*this.slotsPerEpoch+this.firstNormalSlot}getLastSlotInEpoch(e){return this.getFirstSlotInEpoch(e)+this.getSlotsInEpoch(e)-1}getSlotsInEpoch(e){return e<this.firstNormalEpoch?Math.pow(2,e+sy(32)):this.slotsPerEpoch}}var oy=globalThis.fetch;class ay extends Op{constructor(e,t,n){super(e=>{const n=function(e,t){return new Bp(e,t)}(e,{autoconnect:!0,max_reconnects:5,reconnect:!0,reconnect_interval:1e3,...t});return this.underlyingSocket="socket"in n?n.socket:n,n},e,t,n),this.underlyingSocket=void 0}call(...e){const t=this.underlyingSocket?.readyState;return 1===t?super.call(...e):Promise.reject(new Error("Tried to call a JSON-RPC method `"+e[0]+"` but the socket was not `CONNECTING` or `OPEN` (`readyState` was "+t+")"))}notify(...e){const t=this.underlyingSocket?.readyState;return 1===t?super.notify(...e):Promise.reject(new Error("Tried to send a JSON-RPC notification `"+e[0]+"` but the socket was not `CONNECTING` or `OPEN` (`readyState` was "+t+")"))}}class cy{constructor(e){this.key=void 0,this.state=void 0,this.key=e.key,this.state=e.state}isActive(){const e=BigInt("0xffffffffffffffff");return this.state.deactivationSlot===e}static deserialize(e){const t=function(e,t){let n;try{n=e.layout.decode(t)}catch(e){throw new Error("invalid instruction; "+e)}if(n.typeIndex!==e.index)throw new Error(`invalid account data; account type mismatch ${n.typeIndex} != ${e.index}`);return n}(ly,e),n=e.length-56;Cm(n>=0,"lookup table is invalid"),Cm(n%32==0,"lookup table is invalid");const r=n/32,{addresses:s}=Kl.struct([Kl.seq(Am(),r,"addresses")]).decode(e.slice(56));return{deactivationSlot:t.deactivationSlot,lastExtendedSlot:t.lastExtendedSlot,lastExtendedSlotStartIndex:t.lastExtendedStartIndex,authority:0!==t.authority.length?new mm(t.authority[0]):void 0,addresses:s.map(e=>new mm(e))}}}const ly={index:1,layout:Kl.struct([Kl.u32("typeIndex"),Ym("deactivationSlot"),Kl.nu64("lastExtendedSlot"),Kl.u8("lastExtendedStartIndex"),Kl.u8(),Kl.seq(Am(),Kl.offset(Kl.u8(),-1),"authority")])},uy=/^[^:]+:\/\/([^:[]+|\[[^\]]+\])(:\d+)?(.*)/i;const dy=vp(cp(mm),fp(),e=>new mm(e)),hy=pp([fp(),lp("base64")]),gy=vp(cp(Oo.Buffer),hy,e=>Oo.Buffer.from(e[0],"base64"));function fy(e){let t,n;if("string"==typeof e)t=e;else if(e){const{commitment:r,...s}=e;t=r,n=s}return{commitment:t,config:n}}function py(e){return e.map(e=>"memcmp"in e?{...e,memcmp:{...e.memcmp,encoding:e.memcmp.encoding??"base58"}}:e)}function my(e){return yp([mp({jsonrpc:lp("2.0"),id:fp(),result:e}),mp({jsonrpc:lp("2.0"),id:fp(),error:mp({code:bp(),message:fp(),data:hp(ip("any",()=>!0))})})])}const yy=my(bp());function by(e){return vp(my(e),yy,t=>"error"in t?t:{...t,result:np(t.result,e)})}function vy(e){return by(mp({context:mp({slot:dp()}),value:e}))}function wy(e){return mp({context:mp({slot:dp()}),value:e})}function Ey(e,t){if(0===e)return new Dm({header:t.header,staticAccountKeys:t.accountKeys.map(e=>new mm(e)),recentBlockhash:t.recentBlockhash,compiledInstructions:t.instructions.map(e=>({programIdIndex:e.programIdIndex,accountKeyIndexes:e.accounts,data:El.decode(e.data)})),addressTableLookups:t.addressTableLookups});if(1===e){const e=t.transactionConfig;if(null==e)throw new Error("Expected a version 1 transaction message response to have a `transactionConfig`");return new Mm({header:t.header,staticAccountKeys:t.accountKeys.map(e=>new mm(e)),recentBlockhash:t.recentBlockhash,compiledInstructions:t.instructions.map(e=>({programIdIndex:e.programIdIndex,accountKeyIndexes:e.accounts,data:El.decode(e.data)})),transactionConfig:e})}return new Bm(t)}const Ay=mp({foundation:dp(),foundationTerm:dp(),initial:dp(),taper:dp(),terminal:dp()}),Sy=by(op(up(mp({epoch:dp(),effectiveSlot:dp(),amount:dp(),postBalance:dp(),commission:hp(up(dp()))})))),ky=op(mp({slot:dp(),prioritizationFee:dp()})),Ty=mp({total:dp(),validator:dp(),foundation:dp(),epoch:dp()}),Iy=mp({epoch:dp(),slotIndex:dp(),slotsInEpoch:dp(),absoluteSlot:dp(),blockHeight:hp(dp()),transactionCount:hp(dp())}),Cy=mp({slotsPerEpoch:dp(),leaderScheduleSlotOffset:dp(),warmup:ap(),firstNormalEpoch:dp(),firstNormalSlot:dp()}),Ny=gp(fp(),op(dp())),_y=up(yp([mp({}),fp()])),xy=mp({err:_y}),Ry=lp("receivedSignature"),By=mp({"solana-core":fp(),"feature-set":hp(dp())}),Dy=mp({program:fp(),programId:dy,parsed:bp()}),Oy=mp({programId:dy,accounts:op(dy),data:fp()}),My=vy(mp({err:up(yp([mp({}),fp()])),logs:up(op(fp())),accounts:hp(up(op(up(mp({executable:ap(),owner:fp(),lamports:dp(),data:op(fp()),rentEpoch:hp(dp())}))))),unitsConsumed:hp(dp()),returnData:hp(up(mp({programId:fp(),data:pp([fp(),lp("base64")])}))),innerInstructions:hp(up(op(mp({index:dp(),instructions:op(yp([Dy,Oy]))}))))})),Ly=vy(mp({byIdentity:gp(fp(),op(dp())),range:mp({firstSlot:dp(),lastSlot:dp()})}));const Uy=by(Ay),Py=by(Ty),Fy=by(ky),$y=by(Iy),Ky=by(Cy),Gy=by(Ny),Hy=by(dp()),Wy=vy(mp({total:dp(),circulating:dp(),nonCirculating:dp(),nonCirculatingAccounts:op(dy)})),qy=mp({amount:fp(),uiAmount:up(dp()),decimals:dp(),uiAmountString:hp(fp())}),zy=vy(op(mp({address:dy,amount:fp(),uiAmount:up(dp()),decimals:dp(),uiAmountString:hp(fp())}))),Vy=vy(op(mp({pubkey:dy,account:mp({executable:ap(),owner:dy,lamports:dp(),data:gy,rentEpoch:dp()})}))),jy=mp({program:fp(),parsed:bp(),space:dp()}),Xy=vy(op(mp({pubkey:dy,account:mp({executable:ap(),owner:dy,lamports:dp(),data:jy,rentEpoch:dp()})}))),Yy=vy(op(mp({lamports:dp(),address:dy}))),Jy=mp({executable:ap(),owner:dy,lamports:dp(),data:gy,rentEpoch:dp()}),Qy=mp({pubkey:dy,account:Jy}),Zy=vp(yp([cp(Oo.Buffer),jy]),yp([hy,jy]),e=>Array.isArray(e)?np(e,gy):e),eb=mp({executable:ap(),owner:dy,lamports:dp(),data:Zy,rentEpoch:dp()}),tb=mp({pubkey:dy,account:eb}),nb=mp({state:yp([lp("active"),lp("inactive"),lp("activating"),lp("deactivating")]),active:dp(),inactive:dp()}),rb=by(op(mp({signature:fp(),slot:dp(),err:_y,memo:up(fp()),blockTime:hp(up(dp()))}))),sb=by(op(mp({signature:fp(),slot:dp(),err:_y,memo:up(fp()),blockTime:hp(up(dp()))}))),ib=mp({subscription:dp(),result:wy(Jy)}),ob=mp({pubkey:dy,account:Jy}),ab=mp({subscription:dp(),result:wy(ob)}),cb=mp({parent:dp(),slot:dp(),root:dp()}),lb=mp({subscription:dp(),result:cb}),ub=yp([mp({type:yp([lp("firstShredReceived"),lp("completed"),lp("optimisticConfirmation"),lp("root")]),slot:dp(),timestamp:dp()}),mp({type:lp("createdBank"),parent:dp(),slot:dp(),timestamp:dp()}),mp({type:lp("frozen"),slot:dp(),timestamp:dp(),stats:mp({numTransactionEntries:dp(),numSuccessfulTransactions:dp(),numFailedTransactions:dp(),maxTransactionsPerEntry:dp()})}),mp({type:lp("dead"),slot:dp(),timestamp:dp(),err:fp()})]),db=mp({subscription:dp(),result:ub}),hb=mp({subscription:dp(),result:wy(yp([xy,Ry]))}),gb=mp({subscription:dp(),result:dp()}),fb=mp({pubkey:fp(),gossip:up(fp()),tpu:up(fp()),rpc:up(fp()),version:up(fp())}),pb=mp({votePubkey:fp(),nodePubkey:fp(),activatedStake:dp(),epochVoteAccount:ap(),epochCredits:op(pp([dp(),dp(),dp()])),commission:dp(),lastVote:dp(),rootSlot:up(dp())}),mb=by(mp({current:op(pb),delinquent:op(pb)})),yb=yp([lp("processed"),lp("confirmed"),lp("finalized")]),bb=mp({slot:dp(),confirmations:up(dp()),err:_y,confirmationStatus:hp(yb)}),vb=vy(op(up(bb))),wb=by(dp()),Eb=mp({accountKey:dy,writableIndexes:op(dp()),readonlyIndexes:op(dp())}),Ab=mp({computeUnitLimit:up(dp()),heapSize:up(dp()),loadedAccountsDataSizeLimit:up(dp()),priorityFee:up(dp())}),Sb=mp({signatures:op(fp()),message:mp({accountKeys:op(fp()),header:mp({numRequiredSignatures:dp(),numReadonlySignedAccounts:dp(),numReadonlyUnsignedAccounts:dp()}),instructions:op(mp({accounts:op(dp()),data:fp(),programIdIndex:dp()})),recentBlockhash:fp(),addressTableLookups:hp(op(Eb)),transactionConfig:hp(up(Ab))})}),kb=mp({pubkey:dy,signer:ap(),writable:ap(),source:hp(yp([lp("transaction"),lp("lookupTable")]))}),Tb=mp({accountKeys:op(kb),signatures:op(fp())}),Ib=mp({parsed:bp(),program:fp(),programId:dy}),Cb=mp({accounts:op(dy),data:fp(),programId:dy}),Nb=vp(yp([Cb,Ib]),yp([mp({parsed:bp(),program:fp(),programId:fp()}),mp({accounts:op(fp()),data:fp(),programId:fp()})]),e=>np(e,"accounts"in e?Cb:Ib)),_b=mp({signatures:op(fp()),message:mp({accountKeys:op(kb),instructions:op(Nb),recentBlockhash:fp(),addressTableLookups:hp(up(op(Eb))),transactionConfig:hp(up(Ab))})}),xb=mp({accountIndex:dp(),mint:fp(),owner:hp(fp()),programId:hp(fp()),uiTokenAmount:qy}),Rb=mp({writable:op(dy),readonly:op(dy)}),Bb=mp({err:_y,fee:dp(),innerInstructions:hp(up(op(mp({index:dp(),instructions:op(mp({accounts:op(dp()),data:fp(),programIdIndex:dp()}))})))),preBalances:op(dp()),postBalances:op(dp()),logMessages:hp(up(op(fp()))),preTokenBalances:hp(up(op(xb))),postTokenBalances:hp(up(op(xb))),loadedAddresses:hp(Rb),computeUnitsConsumed:hp(dp()),costUnits:hp(dp())}),Db=mp({err:_y,fee:dp(),innerInstructions:hp(up(op(mp({index:dp(),instructions:op(Nb)})))),preBalances:op(dp()),postBalances:op(dp()),logMessages:hp(up(op(fp()))),preTokenBalances:hp(up(op(xb))),postTokenBalances:hp(up(op(xb))),loadedAddresses:hp(Rb),computeUnitsConsumed:hp(dp()),costUnits:hp(dp())}),Ob=yp([lp(0),lp(1),lp("legacy")]),Mb=mp({pubkey:fp(),lamports:dp(),postBalance:up(dp()),rewardType:up(fp()),commission:hp(up(dp()))}),Lb=by(up(mp({blockhash:fp(),previousBlockhash:fp(),parentSlot:dp(),transactions:op(mp({transaction:Sb,meta:up(Bb),version:hp(Ob)})),rewards:hp(op(Mb)),blockTime:up(dp()),blockHeight:up(dp())}))),Ub=by(up(mp({blockhash:fp(),previousBlockhash:fp(),parentSlot:dp(),rewards:hp(op(Mb)),blockTime:up(dp()),blockHeight:up(dp())}))),Pb=by(up(mp({blockhash:fp(),previousBlockhash:fp(),parentSlot:dp(),transactions:op(mp({transaction:Tb,meta:up(Bb),version:hp(Ob)})),rewards:hp(op(Mb)),blockTime:up(dp()),blockHeight:up(dp())}))),Fb=by(up(mp({blockhash:fp(),previousBlockhash:fp(),parentSlot:dp(),transactions:op(mp({transaction:_b,meta:up(Db),version:hp(Ob)})),rewards:hp(op(Mb)),blockTime:up(dp()),blockHeight:up(dp())}))),$b=by(up(mp({blockhash:fp(),previousBlockhash:fp(),parentSlot:dp(),transactions:op(mp({transaction:Tb,meta:up(Db),version:hp(Ob)})),rewards:hp(op(Mb)),blockTime:up(dp()),blockHeight:up(dp())}))),Kb=by(up(mp({blockhash:fp(),previousBlockhash:fp(),parentSlot:dp(),rewards:hp(op(Mb)),blockTime:up(dp()),blockHeight:up(dp())}))),Gb=by(up(mp({blockhash:fp(),previousBlockhash:fp(),parentSlot:dp(),transactions:op(mp({transaction:Sb,meta:up(Bb)})),rewards:hp(op(Mb)),blockTime:up(dp())}))),Hb=by(up(mp({blockhash:fp(),previousBlockhash:fp(),parentSlot:dp(),signatures:op(fp()),blockTime:up(dp())}))),Wb=by(up(mp({slot:dp(),meta:up(Bb),blockTime:hp(up(dp())),transaction:Sb,version:hp(Ob)}))),qb=by(up(mp({slot:dp(),transaction:_b,meta:up(Db),blockTime:hp(up(dp())),version:hp(Ob)}))),zb=vy(mp({blockhash:fp(),lastValidBlockHeight:dp()})),Vb=vy(ap()),jb=by(op(mp({slot:dp(),numTransactions:dp(),numSlots:dp(),samplePeriodSecs:dp()}))),Xb=vy(up(mp({feeCalculator:mp({lamportsPerSignature:dp()})}))),Yb=by(fp()),Jb=by(fp()),Qb=mp({err:_y,logs:op(fp()),signature:fp()}),Zb=mp({result:wy(Qb),subscription:dp()}),ev={"solana-client":"js/1.99.0"};class tv{constructor(e,t){let n,r,s,i,o,a;var c;this._commitment=void 0,this._confirmTransactionInitialTimeout=void 0,this._rpcEndpoint=void 0,this._rpcWsEndpoint=void 0,this._rpcClient=void 0,this._rpcRequest=void 0,this._rpcBatchRequest=void 0,this._rpcWebSocket=void 0,this._rpcWebSocketConnected=!1,this._rpcWebSocketHeartbeat=null,this._rpcWebSocketIdleTimeout=null,this._rpcWebSocketGeneration=0,this._disableBlockhashCaching=!1,this._pollingBlockhash=!1,this._blockhashInfo={latestBlockhash:null,lastFetch:0,transactionSignatures:[],simulatedSignatures:[]},this._nextClientSubscriptionId=0,this._subscriptionDisposeFunctionsByClientSubscriptionId={},this._subscriptionHashByClientSubscriptionId={},this._subscriptionStateChangeCallbacksByHash={},this._subscriptionCallbacksByServerSubscriptionId={},this._subscriptionsByHash={},this._subscriptionsAutoDisposedByRpc=new Set,this.getBlockHeight=(()=>{const e={};return async t=>{const{commitment:n,config:r}=fy(t),s=this._buildArgs([],n,void 0,r),i=ry(s);return e[i]=e[i]??(async()=>{try{const e=np(await this._rpcRequest("getBlockHeight",s),by(dp()));if("error"in e)throw new Hm(e.error,"failed to get block height information");return e.result}finally{delete e[i]}})(),await e[i]}})(),t&&"string"==typeof t?this._commitment=t:t&&(this._commitment=t.commitment,this._confirmTransactionInitialTimeout=t.confirmTransactionInitialTimeout,n=t.wsEndpoint,r=t.httpHeaders,s=t.fetch,i=t.fetchMiddleware,o=t.disableRetryOnRateLimit,a=t.httpAgent),this._rpcEndpoint=function(e){if(!1===/^https?:/.test(e))throw new TypeError("Endpoint URL must start with `http:` or `https:`.");return e}(e),this._rpcWsEndpoint=n||function(e){const t=e.match(uy);if(null==t)throw TypeError(`Failed to validate endpoint URL \`${e}\``);const[n,r,s,i]=t,o=e.startsWith("https:")?"wss:":"ws:",a=null==s?null:parseInt(s.slice(1),10);return`${o}//${r}${null==a?"":`:${a+1}`}${i}`}(e),this._rpcClient=function(e,t,n,r,s){const i=n||oy;let o;return r&&(o=async(e,t)=>{const n=await new Promise((n,s)=>{try{r(e,t,(e,t)=>n([e,t]))}catch(e){s(e)}});return await i(...n)}),new Np(async(n,r)=>{const a={method:"POST",body:n,agent:void 0,headers:Object.assign({"Content-Type":"application/json"},t||{},ev)};try{let t,n=5,c=500;for(;t=o?await o(e,a):await i(e,a),429===t.status&&!0!==s&&(n-=1,0!==n);)await Wm(c),c*=2;const l=await t.text();t.ok?r(null,l):r(new Error(`${t.status} ${t.statusText}: ${l}`))}catch(e){e instanceof Error&&r(e)}},{})}(e,r,s,i,o),this._rpcRequest=(c=this._rpcClient,(e,t)=>new Promise((n,r)=>{c.request(e,t,(e,t)=>{e?r(e):n(t)})})),this._rpcBatchRequest=function(e){return t=>new Promise((n,r)=>{0===t.length&&n([]);const s=t.map(t=>e.request(t.methodName,t.args));e.request(s,(e,t)=>{e?r(e):n(t)})})}(this._rpcClient),this._rpcWebSocket=new ay(this._rpcWsEndpoint,{autoconnect:!1,max_reconnects:1/0}),this._rpcWebSocket.on("open",this._wsOnOpen.bind(this)),this._rpcWebSocket.on("error",this._wsOnError.bind(this)),this._rpcWebSocket.on("close",this._wsOnClose.bind(this)),this._rpcWebSocket.on("accountNotification",this._wsOnAccountNotification.bind(this)),this._rpcWebSocket.on("programNotification",this._wsOnProgramAccountNotification.bind(this)),this._rpcWebSocket.on("slotNotification",this._wsOnSlotNotification.bind(this)),this._rpcWebSocket.on("slotsUpdatesNotification",this._wsOnSlotUpdatesNotification.bind(this)),this._rpcWebSocket.on("signatureNotification",this._wsOnSignatureNotification.bind(this)),this._rpcWebSocket.on("rootNotification",this._wsOnRootNotification.bind(this)),this._rpcWebSocket.on("logsNotification",this._wsOnLogsNotification.bind(this))}get commitment(){return this._commitment}get rpcEndpoint(){return this._rpcEndpoint}async getBalanceAndContext(e,t){const{commitment:n,config:r}=fy(t),s=this._buildArgs([e.toBase58()],n,void 0,r),i=np(await this._rpcRequest("getBalance",s),vy(dp()));if("error"in i)throw new Hm(i.error,`failed to get balance for ${e.toBase58()}`);return i.result}async getBalance(e,t){return await this.getBalanceAndContext(e,t).then(e=>e.value).catch(t=>{throw new Error("failed to get balance of account "+e.toBase58()+": "+t)})}async getBlockTime(e){const t=np(await this._rpcRequest("getBlockTime",[e]),by(up(dp())));if("error"in t)throw new Hm(t.error,`failed to get block time for slot ${e}`);return t.result}async getMinimumLedgerSlot(){const e=np(await this._rpcRequest("minimumLedgerSlot",[]),by(dp()));if("error"in e)throw new Hm(e.error,"failed to get minimum ledger slot");return e.result}async getFirstAvailableBlock(){const e=np(await this._rpcRequest("getFirstAvailableBlock",[]),Hy);if("error"in e)throw new Hm(e.error,"failed to get first available block");return e.result}async getSupply(e){let t={};t="string"==typeof e?{commitment:e}:e?{...e,commitment:e&&e.commitment||this.commitment}:{commitment:this.commitment};const n=np(await this._rpcRequest("getSupply",[t]),Wy);if("error"in n)throw new Hm(n.error,"failed to get supply");return n.result}async getTokenSupply(e,t){const n=this._buildArgs([e.toBase58()],t),r=np(await this._rpcRequest("getTokenSupply",n),vy(qy));if("error"in r)throw new Hm(r.error,"failed to get token supply");return r.result}async getTokenAccountBalance(e,t){const n=this._buildArgs([e.toBase58()],t),r=np(await this._rpcRequest("getTokenAccountBalance",n),vy(qy));if("error"in r)throw new Hm(r.error,"failed to get token account balance");return r.result}async getTokenAccountsByOwner(e,t,n){const{commitment:r,config:s}=fy(n);let i=[e.toBase58()];"mint"in t?i.push({mint:t.mint.toBase58()}):i.push({programId:t.programId.toBase58()});const o=this._buildArgs(i,r,"base64",s),a=np(await this._rpcRequest("getTokenAccountsByOwner",o),Vy);if("error"in a)throw new Hm(a.error,`failed to get token accounts owned by account ${e.toBase58()}`);return a.result}async getParsedTokenAccountsByOwner(e,t,n){let r=[e.toBase58()];"mint"in t?r.push({mint:t.mint.toBase58()}):r.push({programId:t.programId.toBase58()});const s=this._buildArgs(r,n,"jsonParsed"),i=np(await this._rpcRequest("getTokenAccountsByOwner",s),Xy);if("error"in i)throw new Hm(i.error,`failed to get token accounts owned by account ${e.toBase58()}`);return i.result}async getLargestAccounts(e){const t={...e,commitment:e&&e.commitment||this.commitment},n=t.filter||t.commitment?[t]:[],r=np(await this._rpcRequest("getLargestAccounts",n),Yy);if("error"in r)throw new Hm(r.error,"failed to get largest accounts");return r.result}async getTokenLargestAccounts(e,t){const n=this._buildArgs([e.toBase58()],t),r=np(await this._rpcRequest("getTokenLargestAccounts",n),zy);if("error"in r)throw new Hm(r.error,"failed to get token largest accounts");return r.result}async getAccountInfoAndContext(e,t){const{commitment:n,config:r}=fy(t),s=this._buildArgs([e.toBase58()],n,"base64",r),i=np(await this._rpcRequest("getAccountInfo",s),vy(up(Jy)));if("error"in i)throw new Hm(i.error,`failed to get info about account ${e.toBase58()}`);return i.result}async getParsedAccountInfo(e,t){const{commitment:n,config:r}=fy(t),s=this._buildArgs([e.toBase58()],n,"jsonParsed",r),i=np(await this._rpcRequest("getAccountInfo",s),vy(up(eb)));if("error"in i)throw new Hm(i.error,`failed to get info about account ${e.toBase58()}`);return i.result}async getAccountInfo(e,t){try{return(await this.getAccountInfoAndContext(e,t)).value}catch(t){throw new Error("failed to get info about account "+e.toBase58()+": "+t)}}async getMultipleParsedAccounts(e,t){const{commitment:n,config:r}=fy(t),s=e.map(e=>e.toBase58()),i=this._buildArgs([s],n,"jsonParsed",r),o=np(await this._rpcRequest("getMultipleAccounts",i),vy(op(up(eb))));if("error"in o)throw new Hm(o.error,`failed to get info for accounts ${s}`);return o.result}async getMultipleAccountsInfoAndContext(e,t){const{commitment:n,config:r}=fy(t),s=e.map(e=>e.toBase58()),i=this._buildArgs([s],n,"base64",r),o=np(await this._rpcRequest("getMultipleAccounts",i),vy(op(up(Jy))));if("error"in o)throw new Hm(o.error,`failed to get info for accounts ${s}`);return o.result}async getMultipleAccountsInfo(e,t){return(await this.getMultipleAccountsInfoAndContext(e,t)).value}async getStakeActivation(e,t,n){const{commitment:r,config:s}=fy(t),i=this._buildArgs([e.toBase58()],r,void 0,{...s,epoch:null!=n?n:s?.epoch}),o=np(await this._rpcRequest("getStakeActivation",i),by(nb));if("error"in o)throw new Hm(o.error,`failed to get Stake Activation ${e.toBase58()}`);return o.result}async getProgramAccounts(e,t){const{commitment:n,config:r}=fy(t),{encoding:s,...i}=r||{},o=this._buildArgs([e.toBase58()],n,s||"base64",{...i,...i.filters?{filters:py(i.filters)}:null}),a=await this._rpcRequest("getProgramAccounts",o),c=op(Qy),l=!0===i.withContext?np(a,vy(c)):np(a,by(c));if("error"in l)throw new Hm(l.error,`failed to get accounts owned by program ${e.toBase58()}`);return l.result}async getParsedProgramAccounts(e,t){const{commitment:n,config:r}=fy(t),s=this._buildArgs([e.toBase58()],n,"jsonParsed",r),i=np(await this._rpcRequest("getProgramAccounts",s),by(op(tb)));if("error"in i)throw new Hm(i.error,`failed to get accounts owned by program ${e.toBase58()}`);return i.result}async confirmTransaction(e,t){let n,r;if("string"==typeof e)n=e;else{const t=e;if(t.abortSignal?.aborted)return Promise.reject(t.abortSignal.reason);n=t.signature}try{r=El.decode(n)}catch(e){throw new Error("signature must be base58 encoded: "+n)}return Cm(64===r.length,"signature has invalid length"),"string"==typeof e?await this.confirmTransactionUsingLegacyTimeoutStrategy({commitment:t||this.commitment,signature:n}):"lastValidBlockHeight"in e?await this.confirmTransactionUsingBlockHeightExceedanceStrategy({commitment:t||this.commitment,strategy:e}):await this.confirmTransactionUsingDurableNonceStrategy({commitment:t||this.commitment,strategy:e})}getCancellationPromise(e){return new Promise((t,n)=>{null!=e&&(e.aborted?n(e.reason):e.addEventListener("abort",()=>{n(e.reason)}))})}getTransactionConfirmationPromise({commitment:e,signature:t}){let n,r,s=!1;return{abortConfirmation:()=>{r&&(r(),r=void 0),null!=n&&(this.removeSignatureListener(n),n=void 0)},confirmationPromise:new Promise((i,o)=>{try{n=this.onSignature(t,(e,t)=>{n=void 0;const r={context:t,value:e};i({__type:Lm.PROCESSED,response:r})},e);const a=new Promise(e=>{null==n?e():r=this._onSubscriptionStateChange(n,t=>{"subscribed"===t&&e()})});(async()=>{if(await a,s)return;const n=await this.getSignatureStatus(t);if(s)return;if(null==n)return;const{context:r,value:c}=n;if(null!=c)if(c?.err)o(c.err);else{switch(e){case"confirmed":case"single":case"singleGossip":if("processed"===c.confirmationStatus)return;break;case"finalized":case"max":case"root":if("processed"===c.confirmationStatus||"confirmed"===c.confirmationStatus)return}s=!0,i({__type:Lm.PROCESSED,response:{context:r,value:c}})}})()}catch(e){o(e)}})}}async confirmTransactionUsingBlockHeightExceedanceStrategy({commitment:e,strategy:{abortSignal:t,lastValidBlockHeight:n,signature:r}}){let s=!1;const i=new Promise(t=>{const r=async()=>{try{return await this.getBlockHeight(e)}catch(e){return-1}};(async()=>{let e=await r();if(!s){for(;e<=n;){if(await Wm(1e3),s)return;if(e=await r(),s)return}t({__type:Lm.BLOCKHEIGHT_EXCEEDED})}})()}),{abortConfirmation:o,confirmationPromise:a}=this.getTransactionConfirmationPromise({commitment:e,signature:r}),c=this.getCancellationPromise(t);let l;try{const e=await Promise.race([c,a,i]);if(e.__type!==Lm.PROCESSED)throw new bm(r);l=e.response}finally{s=!0,o()}return l}async confirmTransactionUsingDurableNonceStrategy({commitment:e,strategy:{abortSignal:t,minContextSlot:n,nonceAccountPubkey:r,nonceValue:s,signature:i}}){let o=!1;const a=new Promise(t=>{let i=s,a=null;const c=async()=>{try{const{context:t,value:s}=await this.getNonceAndContext(r,{commitment:e,minContextSlot:n});return a=t.slot,s?.nonce}catch(e){return i}};(async()=>{if(i=await c(),!o)for(;;){if(s!==i)return void t({__type:Lm.NONCE_INVALID,slotInWhichNonceDidAdvance:a});if(await Wm(2e3),o)return;if(i=await c(),o)return}})()}),{abortConfirmation:c,confirmationPromise:l}=this.getTransactionConfirmationPromise({commitment:e,signature:i}),u=this.getCancellationPromise(t);let d;try{const t=await Promise.race([u,l,a]);if(t.__type===Lm.PROCESSED)d=t.response;else{let r;for(;;){const e=await this.getSignatureStatus(i);if(null==e)break;if(!(e.context.slot<(t.slotInWhichNonceDidAdvance??n))){r=e;break}await Wm(400)}if(!r?.value)throw new wm(i);{const t=e||"finalized",{confirmationStatus:n}=r.value;switch(t){case"processed":case"recent":if("processed"!==n&&"confirmed"!==n&&"finalized"!==n)throw new wm(i);break;case"confirmed":case"single":case"singleGossip":if("confirmed"!==n&&"finalized"!==n)throw new wm(i);break;case"finalized":case"max":case"root":if("finalized"!==n)throw new wm(i)}d={context:r.context,value:{err:r.value.err}}}}}finally{o=!0,c()}return d}async confirmTransactionUsingLegacyTimeoutStrategy({commitment:e,signature:t}){let n;const r=new Promise(t=>{let r=this._confirmTransactionInitialTimeout||6e4;switch(e){case"processed":case"recent":case"single":case"confirmed":case"singleGossip":r=this._confirmTransactionInitialTimeout||3e4}n=setTimeout(()=>t({__type:Lm.TIMED_OUT,timeoutMs:r}),r)}),{abortConfirmation:s,confirmationPromise:i}=this.getTransactionConfirmationPromise({commitment:e,signature:t});let o;try{const e=await Promise.race([i,r]);if(e.__type!==Lm.PROCESSED)throw new vm(t,e.timeoutMs/1e3);o=e.response}finally{clearTimeout(n),s()}return o}async getClusterNodes(){const e=np(await this._rpcRequest("getClusterNodes",[]),by(op(fb)));if("error"in e)throw new Hm(e.error,"failed to get cluster nodes");return e.result}async getVoteAccounts(e){const t=this._buildArgs([],e),n=np(await this._rpcRequest("getVoteAccounts",t),mb);if("error"in n)throw new Hm(n.error,"failed to get vote accounts");return n.result}async getSlot(e){const{commitment:t,config:n}=fy(e),r=this._buildArgs([],t,void 0,n),s=np(await this._rpcRequest("getSlot",r),by(dp()));if("error"in s)throw new Hm(s.error,"failed to get slot");return s.result}async getSlotLeader(e){const{commitment:t,config:n}=fy(e),r=this._buildArgs([],t,void 0,n),s=np(await this._rpcRequest("getSlotLeader",r),by(fp()));if("error"in s)throw new Hm(s.error,"failed to get slot leader");return s.result}async getSlotLeaders(e,t){const n=[e,t],r=np(await this._rpcRequest("getSlotLeaders",n),by(op(dy)));if("error"in r)throw new Hm(r.error,"failed to get slot leaders");return r.result}async getSignatureStatus(e,t){const{context:n,value:r}=await this.getSignatureStatuses([e],t);Cm(1===r.length);return{context:n,value:r[0]}}async getSignatureStatuses(e,t){const n=[e];t&&n.push(t);const r=np(await this._rpcRequest("getSignatureStatuses",n),vb);if("error"in r)throw new Hm(r.error,"failed to get signature status");return r.result}async getTransactionCount(e){const{commitment:t,config:n}=fy(e),r=this._buildArgs([],t,void 0,n),s=np(await this._rpcRequest("getTransactionCount",r),by(dp()));if("error"in s)throw new Hm(s.error,"failed to get transaction count");return s.result}async getTotalSupply(e){return(await this.getSupply({commitment:e,excludeNonCirculatingAccountsList:!0})).value.total}async getInflationGovernor(e){const t=this._buildArgs([],e),n=np(await this._rpcRequest("getInflationGovernor",t),Uy);if("error"in n)throw new Hm(n.error,"failed to get inflation");return n.result}async getInflationReward(e,t,n){const{commitment:r,config:s}=fy(n),i=this._buildArgs([e.map(e=>e.toBase58())],r,void 0,{...s,epoch:null!=t?t:s?.epoch}),o=np(await this._rpcRequest("getInflationReward",i),Sy);if("error"in o)throw new Hm(o.error,"failed to get inflation reward");return o.result}async getInflationRate(){const e=np(await this._rpcRequest("getInflationRate",[]),Py);if("error"in e)throw new Hm(e.error,"failed to get inflation rate");return e.result}async getEpochInfo(e){const{commitment:t,config:n}=fy(e),r=this._buildArgs([],t,void 0,n),s=np(await this._rpcRequest("getEpochInfo",r),$y);if("error"in s)throw new Hm(s.error,"failed to get epoch info");return s.result}async getEpochSchedule(){const e=np(await this._rpcRequest("getEpochSchedule",[]),Ky);if("error"in e)throw new Hm(e.error,"failed to get epoch schedule");const t=e.result;return new iy(t.slotsPerEpoch,t.leaderScheduleSlotOffset,t.warmup,t.firstNormalEpoch,t.firstNormalSlot)}async getLeaderSchedule(){const e=np(await this._rpcRequest("getLeaderSchedule",[]),Gy);if("error"in e)throw new Hm(e.error,"failed to get leader schedule");return e.result}async getMinimumBalanceForRentExemption(e,t){const n=this._buildArgs([e],t),r=np(await this._rpcRequest("getMinimumBalanceForRentExemption",n),wb);return"error"in r?0:r.result}async getRecentBlockhashAndContext(e){const{context:t,value:{blockhash:n}}=await this.getLatestBlockhashAndContext(e);return{context:t,value:{blockhash:n,feeCalculator:{get lamportsPerSignature(){throw new Error("The capability to fetch `lamportsPerSignature` using the `getRecentBlockhash` API is no longer offered by the network. Use the `getFeeForMessage` API to obtain the fee for a given message.")},toJSON:()=>({})}}}}async getRecentPerformanceSamples(e){const t=np(await this._rpcRequest("getRecentPerformanceSamples",e?[e]:[]),jb);if("error"in t)throw new Hm(t.error,"failed to get recent performance samples");return t.result}async getFeeCalculatorForBlockhash(e,t){const n=this._buildArgs([e],t),r=np(await this._rpcRequest("getFeeCalculatorForBlockhash",n),Xb);if("error"in r)throw new Hm(r.error,"failed to get fee calculator");const{context:s,value:i}=r.result;return{context:s,value:null!==i?i.feeCalculator:null}}async getFeeForMessage(e,t){const n=um(e.serialize()).toString("base64"),r=this._buildArgs([n],t),s=np(await this._rpcRequest("getFeeForMessage",r),vy(up(dp())));if("error"in s)throw new Hm(s.error,"failed to get fee for message");if(null===s.result)throw new Error("invalid blockhash");return s.result}async getRecentPrioritizationFees(e){const t=e?.lockedWritableAccounts?.map(e=>e.toBase58()),n=t?.length?[t]:[],r=np(await this._rpcRequest("getRecentPrioritizationFees",n),Fy);if("error"in r)throw new Hm(r.error,"failed to get recent prioritization fees");return r.result}async getRecentBlockhash(e){try{return(await this.getRecentBlockhashAndContext(e)).value}catch(e){throw new Error("failed to get recent blockhash: "+e)}}async getLatestBlockhash(e){try{return(await this.getLatestBlockhashAndContext(e)).value}catch(e){throw new Error("failed to get recent blockhash: "+e)}}async getLatestBlockhashAndContext(e){const{commitment:t,config:n}=fy(e),r=this._buildArgs([],t,void 0,n),s=np(await this._rpcRequest("getLatestBlockhash",r),zb);if("error"in s)throw new Hm(s.error,"failed to get latest blockhash");return s.result}async isBlockhashValid(e,t){const{commitment:n,config:r}=fy(t),s=this._buildArgs([e],n,void 0,r),i=np(await this._rpcRequest("isBlockhashValid",s),Vb);if("error"in i)throw new Hm(i.error,"failed to determine if the blockhash `"+e+"`is valid");return i.result}async getVersion(){const e=np(await this._rpcRequest("getVersion",[]),by(By));if("error"in e)throw new Hm(e.error,"failed to get version");return e.result}async getGenesisHash(){const e=np(await this._rpcRequest("getGenesisHash",[]),by(fp()));if("error"in e)throw new Hm(e.error,"failed to get genesis hash");return e.result}async getBlock(e,t){const{commitment:n,config:r}=fy(t),s=this._buildArgsAtLeastConfirmed([e],n,void 0,r),i=await this._rpcRequest("getBlock",s);try{switch(r?.transactionDetails){case"accounts":{const e=np(i,Pb);if("error"in e)throw e.error;return e.result}case"none":{const e=np(i,Ub);if("error"in e)throw e.error;return e.result}default:{const e=np(i,Lb);if("error"in e)throw e.error;const{result:t}=e;return t?{...t,transactions:t.transactions.map(({transaction:e,meta:t,version:n})=>({meta:t,transaction:{...e,message:Ey(n,e.message)},version:n}))}:null}}}catch(e){throw new Hm(e,"failed to get confirmed block")}}async getParsedBlock(e,t){const{commitment:n,config:r}=fy(t),s=this._buildArgsAtLeastConfirmed([e],n,"jsonParsed",r),i=await this._rpcRequest("getBlock",s);try{switch(r?.transactionDetails){case"accounts":{const e=np(i,$b);if("error"in e)throw e.error;return e.result}case"none":{const e=np(i,Kb);if("error"in e)throw e.error;return e.result}default:{const e=np(i,Fb);if("error"in e)throw e.error;return e.result}}}catch(e){throw new Hm(e,"failed to get block")}}async getBlockProduction(e){let t,n;if("string"==typeof e)n=e;else if(e){const{commitment:r,...s}=e;n=r,t=s}const r=this._buildArgs([],n,"base64",t),s=np(await this._rpcRequest("getBlockProduction",r),Ly);if("error"in s)throw new Hm(s.error,"failed to get block production information");return s.result}async getTransaction(e,t){const{commitment:n,config:r}=fy(t),s=this._buildArgsAtLeastConfirmed([e],n,void 0,r),i=np(await this._rpcRequest("getTransaction",s),Wb);if("error"in i)throw new Hm(i.error,"failed to get transaction");const o=i.result;return o?{...o,transaction:{...o.transaction,message:Ey(o.version,o.transaction.message)}}:o}async getParsedTransaction(e,t){const{commitment:n,config:r}=fy(t),s=this._buildArgsAtLeastConfirmed([e],n,"jsonParsed",r),i=np(await this._rpcRequest("getTransaction",s),qb);if("error"in i)throw new Hm(i.error,"failed to get transaction");return i.result}async getParsedTransactions(e,t){const{commitment:n,config:r}=fy(t),s=e.map(e=>({methodName:"getTransaction",args:this._buildArgsAtLeastConfirmed([e],n,"jsonParsed",r)}));return(await this._rpcBatchRequest(s)).map(e=>{const t=np(e,qb);if("error"in t)throw new Hm(t.error,"failed to get transactions");return t.result})}async getTransactions(e,t){const{commitment:n,config:r}=fy(t),s=e.map(e=>({methodName:"getTransaction",args:this._buildArgsAtLeastConfirmed([e],n,void 0,r)}));return(await this._rpcBatchRequest(s)).map(e=>{const t=np(e,Wb);if("error"in t)throw new Hm(t.error,"failed to get transactions");const n=t.result;return n?{...n,transaction:{...n.transaction,message:Ey(n.version,n.transaction.message)}}:n})}async getConfirmedBlock(e,t){const n=this._buildArgsAtLeastConfirmed([e],t),r=np(await this._rpcRequest("getBlock",n),Gb);if("error"in r)throw new Hm(r.error,"failed to get confirmed block");const s=r.result;if(!s)throw new Error("Confirmed block "+e+" not found");const i={...s,transactions:s.transactions.map(({transaction:e,meta:t})=>{const n=new Bm(e.message);return{meta:t,transaction:{...e,message:n}}})};return{...i,transactions:i.transactions.map(({transaction:e,meta:t})=>({meta:t,transaction:Fm.populate(e.message,e.signatures)}))}}async getBlocks(e,t,n){const r=this._buildArgsAtLeastConfirmed(void 0!==t?[e,t]:[e],n),s=np(await this._rpcRequest("getBlocks",r),by(op(dp())));if("error"in s)throw new Hm(s.error,"failed to get blocks");return s.result}async getBlockSignatures(e,t){const n=this._buildArgsAtLeastConfirmed([e],t,void 0,{transactionDetails:"signatures",rewards:!1}),r=np(await this._rpcRequest("getBlock",n),Hb);if("error"in r)throw new Hm(r.error,"failed to get block");const s=r.result;if(!s)throw new Error("Block "+e+" not found");return s}async getConfirmedBlockSignatures(e,t){const n=this._buildArgsAtLeastConfirmed([e],t,void 0,{transactionDetails:"signatures",rewards:!1}),r=np(await this._rpcRequest("getBlock",n),Hb);if("error"in r)throw new Hm(r.error,"failed to get confirmed block");const s=r.result;if(!s)throw new Error("Confirmed block "+e+" not found");return s}async getConfirmedTransaction(e,t){const n=this._buildArgsAtLeastConfirmed([e],t),r=np(await this._rpcRequest("getTransaction",n),Wb);if("error"in r)throw new Hm(r.error,"failed to get transaction");const s=r.result;if(!s)return s;const i=new Bm(s.transaction.message),o=s.transaction.signatures;return{...s,transaction:Fm.populate(i,o)}}async getParsedConfirmedTransaction(e,t){const n=this._buildArgsAtLeastConfirmed([e],t,"jsonParsed"),r=np(await this._rpcRequest("getTransaction",n),qb);if("error"in r)throw new Hm(r.error,"failed to get confirmed transaction");return r.result}async getParsedConfirmedTransactions(e,t){const n=e.map(e=>({methodName:"getTransaction",args:this._buildArgsAtLeastConfirmed([e],t,"jsonParsed")}));return(await this._rpcBatchRequest(n)).map(e=>{const t=np(e,qb);if("error"in t)throw new Hm(t.error,"failed to get confirmed transactions");return t.result})}async getConfirmedSignaturesForAddress(e,t,n){let r={},s=await this.getFirstAvailableBlock();for(;!("until"in r)&&!(--t<=0||t<s);)try{const e=await this.getConfirmedBlockSignatures(t,"finalized");e.signatures.length>0&&(r.until=e.signatures[e.signatures.length-1].toString())}catch(e){if(e instanceof Error&&e.message.includes("skipped"))continue;throw e}let i=await this.getSlot("finalized");for(;!("before"in r||++n>i);)try{const e=await this.getConfirmedBlockSignatures(n);e.signatures.length>0&&(r.before=e.signatures[e.signatures.length-1].toString())}catch(e){if(e instanceof Error&&e.message.includes("skipped"))continue;throw e}return(await this.getConfirmedSignaturesForAddress2(e,r)).map(e=>e.signature)}async getConfirmedSignaturesForAddress2(e,t,n){const r=this._buildArgsAtLeastConfirmed([e.toBase58()],n,void 0,t),s=np(await this._rpcRequest("getConfirmedSignaturesForAddress2",r),rb);if("error"in s)throw new Hm(s.error,"failed to get confirmed signatures for address");return s.result}async getSignaturesForAddress(e,t,n){const r=this._buildArgsAtLeastConfirmed([e.toBase58()],n,void 0,t),s=np(await this._rpcRequest("getSignaturesForAddress",r),sb);if("error"in s)throw new Hm(s.error,"failed to get signatures for address");return s.result}async getAddressLookupTable(e,t){const{context:n,value:r}=await this.getAccountInfoAndContext(e,t);let s=null;return null!==r&&(s=new cy({key:e,state:cy.deserialize(r.data)})),{context:n,value:s}}async getNonceAndContext(e,t){const{context:n,value:r}=await this.getAccountInfoAndContext(e,t);let s=null;return null!==r&&(s=Xm.fromAccountData(r.data)),{context:n,value:s}}async getNonce(e,t){return await this.getNonceAndContext(e,t).then(e=>e.value).catch(t=>{throw new Error("failed to get nonce for account "+e.toBase58()+": "+t)})}async requestAirdrop(e,t){const n=np(await this._rpcRequest("requestAirdrop",[e.toBase58(),t]),Yb);if("error"in n)throw new Hm(n.error,`airdrop to ${e.toBase58()} failed`);return n.result}async _blockhashWithExpiryBlockHeight(e){if(!e){for(;this._pollingBlockhash;)await Wm(100);const e=Date.now()-this._blockhashInfo.lastFetch>=3e4;if(null!==this._blockhashInfo.latestBlockhash&&!e)return this._blockhashInfo.latestBlockhash}return await this._pollNewBlockhash()}async _pollNewBlockhash(){this._pollingBlockhash=!0;try{const e=Date.now(),t=this._blockhashInfo.latestBlockhash,n=t?t.blockhash:null;for(let e=0;e<50;e++){const e=await this.getLatestBlockhash("finalized");if(n!==e.blockhash)return this._blockhashInfo={latestBlockhash:e,lastFetch:Date.now(),transactionSignatures:[],simulatedSignatures:[]},e;await Wm(200)}throw new Error(`Unable to obtain a new blockhash after ${Date.now()-e}ms`)}finally{this._pollingBlockhash=!1}}async getStakeMinimumDelegation(e){const{commitment:t,config:n}=fy(e),r=this._buildArgs([],t,"base64",n),s=np(await this._rpcRequest("getStakeMinimumDelegation",r),vy(dp()));if("error"in s)throw new Hm(s.error,"failed to get stake minimum delegation");return s.result}async simulateTransaction(e,t,n){if("message"in e){const r=e.serialize(),s=Oo.Buffer.from(r).toString("base64");if(Array.isArray(t)||void 0!==n)throw new Error("Invalid arguments");const i=t||{};i.encoding="base64","commitment"in i||(i.commitment=this.commitment),t&&"object"==typeof t&&"innerInstructions"in t&&(i.innerInstructions=t.innerInstructions);const o=[s,i],a=np(await this._rpcRequest("simulateTransaction",o),My);if("error"in a)throw new Error("failed to simulate transaction: "+a.error.message);return a.result}let r;if(e instanceof Fm){let t=e;r=new Fm,r.feePayer=t.feePayer,r.instructions=e.instructions,r.nonceInfo=t.nonceInfo,r.signatures=t.signatures}else r=Fm.populate(e),r._message=r._json=void 0;if(void 0!==t&&!Array.isArray(t))throw new Error("Invalid arguments");const s=t;if(r.nonceInfo&&s)r.sign(...s);else{let e=this._disableBlockhashCaching;for(;;){const t=await this._blockhashWithExpiryBlockHeight(e);if(r.lastValidBlockHeight=t.lastValidBlockHeight,r.recentBlockhash=t.blockhash,!s)break;if(r.sign(...s),!r.signature)throw new Error("!signature");const n=r.signature.toString("base64");if(!this._blockhashInfo.simulatedSignatures.includes(n)&&!this._blockhashInfo.transactionSignatures.includes(n)){this._blockhashInfo.simulatedSignatures.push(n);break}e=!0}}const i=r._compile(),o=i.serialize(),a=r._serialize(o).toString("base64"),c={encoding:"base64",commitment:this.commitment};if(n){const e=(Array.isArray(n)?n:i.nonProgramIds()).map(e=>e.toBase58());c.accounts={encoding:"base64",addresses:e}}s&&(c.sigVerify=!0),t&&"object"==typeof t&&"innerInstructions"in t&&(c.innerInstructions=t.innerInstructions);const l=[a,c],u=np(await this._rpcRequest("simulateTransaction",l),My);if("error"in u){let e;if("data"in u.error&&(e=u.error.data.logs,e&&Array.isArray(e))){const t="\n ";e.join(t)}throw new Gm({action:"simulate",signature:"",transactionMessage:u.error.message,logs:e})}return u.result}async sendTransaction(e,t,n){if("version"in e){if(t&&Array.isArray(t))throw new Error("Invalid arguments");const n=e.serialize();return await this.sendRawTransaction(n,t)}if(void 0===t||!Array.isArray(t))throw new Error("Invalid arguments");const r=t;if(e.nonceInfo)e.sign(...r);else{let t=this._disableBlockhashCaching;for(;;){const n=await this._blockhashWithExpiryBlockHeight(t);if(e.lastValidBlockHeight=n.lastValidBlockHeight,e.recentBlockhash=n.blockhash,e.sign(...r),!e.signature)throw new Error("!signature");const s=e.signature.toString("base64");if(!this._blockhashInfo.transactionSignatures.includes(s)){this._blockhashInfo.transactionSignatures.push(s);break}t=!0}}const s=e.serialize();return await this.sendRawTransaction(s,n)}async sendRawTransaction(e,t){const n=um(e).toString("base64");return await this.sendEncodedTransaction(n,t)}async sendEncodedTransaction(e,t){const n={encoding:"base64"},r=t&&t.skipPreflight,s=!0===r?"processed":t&&t.preflightCommitment||this.commitment;t&&null!=t.maxRetries&&(n.maxRetries=t.maxRetries),t&&null!=t.minContextSlot&&(n.minContextSlot=t.minContextSlot),r&&(n.skipPreflight=r),s&&(n.preflightCommitment=s);const i=[e,n],o=np(await this._rpcRequest("sendTransaction",i),Jb);if("error"in o){let e;throw"data"in o.error&&(e=o.error.data.logs),new Gm({action:r?"send":"simulate",signature:"",transactionMessage:o.error.message,logs:e})}return o.result}_wsOnOpen(){this._rpcWebSocketConnected=!0,this._rpcWebSocketHeartbeat=setInterval(()=>{(async()=>{try{await this._rpcWebSocket.notify("ping")}catch{}})()},5e3),this._updateSubscriptions()}_wsOnError(e){this._rpcWebSocketConnected=!1}_wsOnClose(e){this._rpcWebSocketConnected=!1,this._rpcWebSocketGeneration=(this._rpcWebSocketGeneration+1)%Number.MAX_SAFE_INTEGER,this._rpcWebSocketIdleTimeout&&(clearTimeout(this._rpcWebSocketIdleTimeout),this._rpcWebSocketIdleTimeout=null),this._rpcWebSocketHeartbeat&&(clearInterval(this._rpcWebSocketHeartbeat),this._rpcWebSocketHeartbeat=null),1e3!==e?(this._subscriptionCallbacksByServerSubscriptionId={},Object.entries(this._subscriptionsByHash).forEach(([e,t])=>{this._setSubscription(e,{...t,state:"pending"})})):this._updateSubscriptions()}_setSubscription(e,t){const n=this._subscriptionsByHash[e]?.state;if(this._subscriptionsByHash[e]=t,n!==t.state){const n=this._subscriptionStateChangeCallbacksByHash[e];n&&n.forEach(e=>{try{e(t.state)}catch{}})}}_onSubscriptionStateChange(e,t){const n=this._subscriptionHashByClientSubscriptionId[e];if(null==n)return()=>{};const r=this._subscriptionStateChangeCallbacksByHash[n]||=new Set;return r.add(t),()=>{r.delete(t),0===r.size&&delete this._subscriptionStateChangeCallbacksByHash[n]}}async _updateSubscriptions(){if(0===Object.keys(this._subscriptionsByHash).length)return void(this._rpcWebSocketConnected&&(this._rpcWebSocketConnected=!1,this._rpcWebSocketIdleTimeout=setTimeout(()=>{this._rpcWebSocketIdleTimeout=null;try{this._rpcWebSocket.close()}catch(e){Error}},500)));if(null!==this._rpcWebSocketIdleTimeout&&(clearTimeout(this._rpcWebSocketIdleTimeout),this._rpcWebSocketIdleTimeout=null,this._rpcWebSocketConnected=!0),!this._rpcWebSocketConnected)return void this._rpcWebSocket.connect();const e=this._rpcWebSocketGeneration,t=()=>e===this._rpcWebSocketGeneration;await Promise.all(Object.keys(this._subscriptionsByHash).map(async e=>{const n=this._subscriptionsByHash[e];if(void 0!==n)switch(n.state){case"pending":case"unsubscribed":if(0===n.callbacks.size)return delete this._subscriptionsByHash[e],"unsubscribed"===n.state&&delete this._subscriptionCallbacksByServerSubscriptionId[n.serverSubscriptionId],void await this._updateSubscriptions();await(async()=>{const{args:r,method:s}=n;try{this._setSubscription(e,{...n,state:"subscribing"});const t=await this._rpcWebSocket.call(s,r);this._setSubscription(e,{...n,serverSubscriptionId:t,state:"subscribed"}),this._subscriptionCallbacksByServerSubscriptionId[t]=n.callbacks,await this._updateSubscriptions()}catch(r){if(!t())return;this._setSubscription(e,{...n,state:"pending"}),await this._updateSubscriptions()}})();break;case"subscribed":0===n.callbacks.size&&await(async()=>{const{serverSubscriptionId:r,unsubscribeMethod:s}=n;if(this._subscriptionsAutoDisposedByRpc.has(r))this._subscriptionsAutoDisposedByRpc.delete(r);else{this._setSubscription(e,{...n,state:"unsubscribing"}),this._setSubscription(e,{...n,state:"unsubscribing"});try{await this._rpcWebSocket.call(s,[r])}catch(r){if(Error,!t())return;return this._setSubscription(e,{...n,state:"subscribed"}),void await this._updateSubscriptions()}}this._setSubscription(e,{...n,state:"unsubscribed"}),await this._updateSubscriptions()})()}}))}_handleServerNotification(e,t){const n=this._subscriptionCallbacksByServerSubscriptionId[e];void 0!==n&&n.forEach(e=>{try{e(...t)}catch(e){}})}_wsOnAccountNotification(e){const{result:t,subscription:n}=np(e,ib);this._handleServerNotification(n,[t.value,t.context])}_makeSubscription(e,t){const n=this._nextClientSubscriptionId++,r=ry([e.method,t]),s=this._subscriptionsByHash[r];return void 0===s?this._subscriptionsByHash[r]={...e,args:t,callbacks:new Set([e.callback]),state:"pending"}:s.callbacks.add(e.callback),this._subscriptionHashByClientSubscriptionId[n]=r,this._subscriptionDisposeFunctionsByClientSubscriptionId[n]=async()=>{delete this._subscriptionDisposeFunctionsByClientSubscriptionId[n],delete this._subscriptionHashByClientSubscriptionId[n];const t=this._subscriptionsByHash[r];Cm(void 0!==t,`Could not find a \`Subscription\` when tearing down client subscription #${n}`),t.callbacks.delete(e.callback),await this._updateSubscriptions()},this._updateSubscriptions(),n}onAccountChange(e,t,n){const{commitment:r,config:s}=fy(n),i=this._buildArgs([e.toBase58()],r||this._commitment||"finalized","base64",s);return this._makeSubscription({callback:t,method:"accountSubscribe",unsubscribeMethod:"accountUnsubscribe"},i)}async removeAccountChangeListener(e){await this._unsubscribeClientSubscription(e,"account change")}_wsOnProgramAccountNotification(e){const{result:t,subscription:n}=np(e,ab);this._handleServerNotification(n,[{accountId:t.value.pubkey,accountInfo:t.value.account},t.context])}onProgramAccountChange(e,t,n,r){const{commitment:s,config:i}=fy(n),o=this._buildArgs([e.toBase58()],s||this._commitment||"finalized","base64",i||(r?{filters:py(r)}:void 0));return this._makeSubscription({callback:t,method:"programSubscribe",unsubscribeMethod:"programUnsubscribe"},o)}async removeProgramAccountChangeListener(e){await this._unsubscribeClientSubscription(e,"program account change")}onLogs(e,t,n){const r=this._buildArgs(["object"==typeof e?{mentions:[e.toString()]}:e],n||this._commitment||"finalized");return this._makeSubscription({callback:t,method:"logsSubscribe",unsubscribeMethod:"logsUnsubscribe"},r)}async removeOnLogsListener(e){await this._unsubscribeClientSubscription(e,"logs")}_wsOnLogsNotification(e){const{result:t,subscription:n}=np(e,Zb);this._handleServerNotification(n,[t.value,t.context])}_wsOnSlotNotification(e){const{result:t,subscription:n}=np(e,lb);this._handleServerNotification(n,[t])}onSlotChange(e){return this._makeSubscription({callback:e,method:"slotSubscribe",unsubscribeMethod:"slotUnsubscribe"},[])}async removeSlotChangeListener(e){await this._unsubscribeClientSubscription(e,"slot change")}_wsOnSlotUpdatesNotification(e){const{result:t,subscription:n}=np(e,db);this._handleServerNotification(n,[t])}onSlotUpdate(e){return this._makeSubscription({callback:e,method:"slotsUpdatesSubscribe",unsubscribeMethod:"slotsUpdatesUnsubscribe"},[])}async removeSlotUpdateListener(e){await this._unsubscribeClientSubscription(e,"slot update")}async _unsubscribeClientSubscription(e,t){const n=this._subscriptionDisposeFunctionsByClientSubscriptionId[e];n&&await n()}_buildArgs(e,t,n,r){const s=t||this._commitment;if(s||n||r){let t={};n&&(t.encoding=n),s&&(t.commitment=s),r&&(t=Object.assign(t,r)),e.push(t)}return e}_buildArgsAtLeastConfirmed(e,t,n,r){const s=t||this._commitment;if(s&&!["confirmed","finalized"].includes(s))throw new Error("Using Connection with default commitment: `"+this._commitment+"`, but method requires at least `confirmed`");return this._buildArgs(e,t,n,r)}_wsOnSignatureNotification(e){const{result:t,subscription:n}=np(e,hb);"receivedSignature"!==t.value&&this._subscriptionsAutoDisposedByRpc.add(n),this._handleServerNotification(n,"receivedSignature"===t.value?[{type:"received"},t.context]:[{type:"status",result:t.value},t.context])}onSignature(e,t,n){const r=this._buildArgs([e],n||this._commitment||"finalized"),s=this._makeSubscription({callback:(e,n)=>{if("status"===e.type){t(e.result,n);try{this.removeSignatureListener(s)}catch(e){}}},method:"signatureSubscribe",unsubscribeMethod:"signatureUnsubscribe"},r);return s}onSignatureWithOptions(e,t,n){const{commitment:r,...s}={...n,commitment:n&&n.commitment||this._commitment||"finalized"},i=this._buildArgs([e],r,void 0,s),o=this._makeSubscription({callback:(e,n)=>{t(e,n);try{this.removeSignatureListener(o)}catch(e){}},method:"signatureSubscribe",unsubscribeMethod:"signatureUnsubscribe"},i);return o}async removeSignatureListener(e){await this._unsubscribeClientSubscription(e,"signature result")}_wsOnRootNotification(e){const{result:t,subscription:n}=np(e,gb);this._handleServerNotification(n,[t])}onRootChange(e){return this._makeSubscription({callback:e,method:"rootSubscribe",unsubscribeMethod:"rootUnsubscribe"},[])}async removeRootChangeListener(e){await this._unsubscribeClientSubscription(e,"root change")}}class nv{constructor(e){this._keypair=void 0,this._keypair=e??om()}static generate(){return new nv(om())}static fromSecretKey(e,t){if(64!==e.byteLength)throw new Error("bad secret key size");const n=e.slice(32,64);if(!t||!t.skipValidation){const t=e.slice(0,32),r=am(t);for(let e=0;e<32;e++)if(n[e]!==r[e])throw new Error("provided secretKey is invalid")}return new nv({publicKey:n,secretKey:e})}static fromSeed(e){const t=am(e),n=new Uint8Array(64);return n.set(e),n.set(t,32),new nv({publicKey:t,secretKey:n})}get publicKey(){return new mm(this._keypair.publicKey)}get secretKey(){return new Uint8Array(this._keypair.secretKey)}}Object.freeze({CreateLookupTable:{index:0,layout:Kl.struct([Kl.u32("instruction"),Ym("recentSlot"),Kl.u8("bumpSeed")])},FreezeLookupTable:{index:1,layout:Kl.struct([Kl.u32("instruction")])},ExtendLookupTable:{index:2,layout:Kl.struct([Kl.u32("instruction"),Ym(),Kl.seq(Am(),Kl.offset(Kl.u32(),-8),"addresses")])},DeactivateLookupTable:{index:3,layout:Kl.struct([Kl.u32("instruction")])},CloseLookupTable:{index:4,layout:Kl.struct([Kl.u32("instruction")])}}),new mm("AddressLookupTab1e1111111111111111111111111");const rv=Object.freeze({RequestUnits:{index:0,layout:Kl.struct([Kl.u8("instruction"),Kl.u32("units"),Kl.u32("additionalFee")])},RequestHeapFrame:{index:1,layout:Kl.struct([Kl.u8("instruction"),Kl.u32("bytes")])},SetComputeUnitLimit:{index:2,layout:Kl.struct([Kl.u8("instruction"),Kl.u32("units")])},SetComputeUnitPrice:{index:3,layout:Kl.struct([Kl.u8("instruction"),Ym("microLamports")])}});class sv{constructor(){}static requestUnits(e){const t=qm(rv.RequestUnits,e);return new Pm({keys:[],programId:this.programId,data:t})}static requestHeapFrame(e){const t=qm(rv.RequestHeapFrame,e);return new Pm({keys:[],programId:this.programId,data:t})}static setComputeUnitLimit(e){const t=qm(rv.SetComputeUnitLimit,e);return new Pm({keys:[],programId:this.programId,data:t})}static setComputeUnitPrice(e){const t=qm(rv.SetComputeUnitPrice,{microLamports:BigInt(e.microLamports)});return new Pm({keys:[],programId:this.programId,data:t})}}var iv;sv.programId=new mm("ComputeBudget111111111111111111111111111111"),Kl.struct([Kl.u8("numSignatures"),Kl.u8("padding"),Kl.u16("signatureOffset"),Kl.u16("signatureInstructionIndex"),Kl.u16("publicKeyOffset"),Kl.u16("publicKeyInstructionIndex"),Kl.u16("messageDataOffset"),Kl.u16("messageDataSize"),Kl.u16("messageInstructionIndex")]),new mm("Ed25519SigVerify111111111111111111111111111"),im.utils.isValidPrivateKey,Kl.struct([Kl.u8("numSignatures"),Kl.u16("signatureOffset"),Kl.u8("signatureInstructionIndex"),Kl.u16("ethAddressOffset"),Kl.u8("ethAddressInstructionIndex"),Kl.u16("messageDataOffset"),Kl.u16("messageDataSize"),Kl.u8("messageInstructionIndex"),Kl.blob(20,"ethAddress"),Kl.blob(64,"signature"),Kl.u8("recoveryId")]),new mm("KeccakSecp256k11111111111111111111111111111"),new mm("StakeConfig11111111111111111111111111111111");class ov{constructor(e,t,n){this.unixTimestamp=void 0,this.epoch=void 0,this.custodian=void 0,this.unixTimestamp=e,this.epoch=t,this.custodian=n}}iv=ov,ov.default=new iv(0,0,mm.default),Object.freeze({Initialize:{index:0,layout:Kl.struct([Kl.u32("instruction"),((e="authorized")=>Kl.struct([Am("staker"),Am("withdrawer")],e))(),((e="lockup")=>Kl.struct([Kl.ns64("unixTimestamp"),Kl.ns64("epoch"),Am("custodian")],e))()])},Authorize:{index:1,layout:Kl.struct([Kl.u32("instruction"),Am("newAuthorized"),Kl.u32("stakeAuthorizationType")])},Delegate:{index:2,layout:Kl.struct([Kl.u32("instruction")])},Split:{index:3,layout:Kl.struct([Kl.u32("instruction"),Kl.ns64("lamports")])},Withdraw:{index:4,layout:Kl.struct([Kl.u32("instruction"),Kl.ns64("lamports")])},Deactivate:{index:5,layout:Kl.struct([Kl.u32("instruction")])},Merge:{index:7,layout:Kl.struct([Kl.u32("instruction")])},AuthorizeWithSeed:{index:8,layout:Kl.struct([Kl.u32("instruction"),Am("newAuthorized"),Kl.u32("stakeAuthorizationType"),Sm("authoritySeed"),Am("authorityOwner")])}}),new mm("Stake11111111111111111111111111111111111111"),Object.freeze({InitializeAccount:{index:0,layout:Kl.struct([Kl.u32("instruction"),((e="voteInit")=>Kl.struct([Am("nodePubkey"),Am("authorizedVoter"),Am("authorizedWithdrawer"),Kl.u8("commission")],e))()])},Authorize:{index:1,layout:Kl.struct([Kl.u32("instruction"),Am("newAuthorized"),Kl.u32("voteAuthorizationType")])},Withdraw:{index:3,layout:Kl.struct([Kl.u32("instruction"),Kl.ns64("lamports")])},UpdateValidatorIdentity:{index:4,layout:Kl.struct([Kl.u32("instruction")])},AuthorizeWithSeed:{index:10,layout:Kl.struct([Kl.u32("instruction"),((e="voteAuthorizeWithSeedArgs")=>Kl.struct([Kl.u32("voteAuthorizationType"),Am("currentAuthorityDerivedKeyOwnerPubkey"),Sm("currentAuthorityDerivedKeySeed"),Am("newAuthorized")],e))()])}}),new mm("Vote111111111111111111111111111111111111111"),new mm("Va1idator1nfo111111111111111111111111111111"),mp({name:fp(),website:hp(fp()),details:hp(fp()),iconUrl:hp(fp()),keybaseUsername:hp(fp())}),new mm("Vote111111111111111111111111111111111111111"),Kl.struct([Am("nodePubkey"),Am("authorizedWithdrawer"),Kl.u8("commission"),Kl.nu64(),Kl.seq(Kl.struct([Kl.nu64("slot"),Kl.u32("confirmationCount")]),Kl.offset(Kl.u32(),-8),"votes"),Kl.u8("rootSlotValid"),Kl.nu64("rootSlot"),Kl.nu64(),Kl.seq(Kl.struct([Kl.nu64("epoch"),Am("authorizedVoter")]),Kl.offset(Kl.u32(),-8),"authorizedVoters"),Kl.struct([Kl.seq(Kl.struct([Am("authorizedPubkey"),Kl.nu64("epochOfLastAuthorizedSwitch"),Kl.nu64("targetEpoch")]),32,"buf"),Kl.nu64("idx"),Kl.u8("isEmpty")],"priorVoters"),Kl.nu64(),Kl.seq(Kl.struct([Kl.nu64("epoch"),Kl.nu64("credits"),Kl.nu64("prevCredits")]),Kl.offset(Kl.u32(),-8),"epochCredits"),Kl.struct([Kl.nu64("slot"),Kl.nu64("timestamp")],"lastTimestamp")]);function av(e){return/^0x[a-fA-F0-9]{64}$/.test(e)}function cv(e){const t=new Map;for(const n of e)t.set(jt(n.symbol),n);return t}function lv(e,t,n){const r=function(e,t){return e.get(jt(t))}(e,t);if(!r){throw It(`Token ${t} not supported for ${n}. Supported: ${Array.from(e.keys()).join(", ")}`,"tokenSymbol")}return r}function uv(e){if(null==e||!av(e))throw kt("privateKey","a 0x-prefixed 64-character hex string (e.g., 0x1234...abcd)","Ethereum private key")}function dv(e,t,n){return{symbol:e,quantity:t,decimals:n,contractAddress:null,isNative:!0}}function hv(e,t){return{symbol:e.symbol,quantity:t,decimals:e.decimals??18,contractAddress:e.contractAddress,isNative:!1}}function gv(e,t){return{symbol:e.symbol,quantity:t,decimals:e.decimals??9,contractAddress:e.mintAddress,isNative:e.isNative??!1}}function fv(e,t,n){const r=e.find(e=>e.symbol===t);if(!r){const r=e.map(e=>e.symbol).join(", ");throw St("tokenSymbol",`Unsupported ${n} token: ${t}. Supported: ${r}`)}return r}const pv={Ethereum:"Ethereum bridging not configured. Provide ethereumPrivateKey in config.",Solana:"Solana bridging not configured. Provide solanaPrivateKey in config."};function mv(e,t,n){if(void 0===e)throw It(n??pv[t],`${t.toLowerCase()}Strategy`);return e}function yv(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 bv="Token symbol resolution failed. This is an internal error - BridgeService should resolve tokenId to symbol before calling strategy.",vv="Bridge request ID missing from RequestTokenBridgeOut response",wv="BridgeTokenOut response missing transaction hash";function Ev(e){if(void 0===e||""===e)throw It(bv,"tokenSymbol");return e}function Av(t,n){if(!e.isAddress(t)){throw kt(n??"address","a valid 0x-prefixed Ethereum address",t)}}function Sv(e,t){try{return new mm(e)}catch{throw kt(t??"address","a valid Solana address (base58)",e)}}function kv(e){try{return new mm(e)}catch{throw kt("address","a valid Solana address (base58)",e)}}function Tv(e){const t={};for(const[n,r]of Object.entries(e))void 0!==r&&(r&&"object"==typeof r&&!Array.isArray(r)?t[n]=Tv(r):t[n]=r);return t}function Iv(e,t){const n=In(e,-1);if(n<=0)throw new Error(`Invalid bridge amount for ${t}: "${e}". Amount must be a positive number.`);return n}var Cv,Nv,_v,xv,Rv,Bv;function Dv(){return Nv?Cv:(Nv=1,Cv={space:"",cycles:!1,replacer:(e,t)=>t,stringify:JSON.stringify})}function Ov(){return xv?_v:(xv=1,_v={isArray:Array.isArray,assign:Object.assign,isObject:e=>"object"==typeof e,isFunction:e=>"function"==typeof e,isBoolean:e=>"boolean"==typeof e,isRegex:e=>e instanceof RegExp,keys:Object.keys})}function Mv(){if(Bv)return Rv;Bv=1;const e=Dv(),t=Ov().isFunction,n=Ov().isBoolean,r=Ov().isObject,s=Ov().isArray,i=Ov().isRegex,o=Ov().assign,a=Ov().keys;return Rv=function(c,l){l=l||o({},e),t(l)&&(l={compare:l});const u=l.space||e.space,d=n(l.cycles)?l.cycles:e.cycles,h=l.replacer||e.replacer,g=l.stringify||e.stringify,f=l.compare&&(p=l.compare,function(e){return function(t,n){const r={key:t,value:e[t]},s={key:n,value:e[n]};return p(r,s)}});var p;d||g(c);const m=[];return function e(t,n,o,c){const l=u?"\n"+new Array(c+1).join(u):"",p=u?": ":":";if(o=function(e){return null==e?e:i(e)?e.toString():e.toJSON?e.toJSON():e}(o),void 0!==(o=h.call(t,n,o))){if(!r(o)||null===o)return g(o);if(s(o)){const t=[];for(let n=0;n<o.length;n++){const r=e(o,n,o[n],c+1)||g(null);t.push(l+u+r)}return"["+t.join(",")+l+"]"}{if(d){if(-1!==m.indexOf(o))return g("[Circular]");m.push(o)}const t=a(o).sort(f&&f(o)),n=[];for(let r=0;r<t.length;r++){const s=t[r],i=e(o,s,o[s],c+1);if(!i)continue;const a=g(s)+p+i;n.push(l+u+a)}return m.splice(m.indexOf(o),1),"{"+n.join(",")+l+"}"}}}({"":c},"",c,0)},Rv}var Lv=So(Mv());let Uv=null;if("undefined"==typeof window&&"undefined"!=typeof require)try{Uv=f}catch{}function Pv(){if(void 0!==Uv?.randomUUID)try{return Uv.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 Fv={name:"GalaConnect",chainId:1},$v=[{name:"destinationChainId",type:"uint256"},{name:"destinationChainTxFee",type:"destinationChainTxFee"},{name:"quantity",type:"string"},{name:"recipient",type:"string"},{name:"tokenInstance",type:"tokenInstance"},{name:"uniqueKey",type:"string"}],Kv=[{name:"collection",type:"string"},{name:"category",type:"string"},{name:"type",type:"string"},{name:"additionalKey",type:"string"}],Gv=[{name:"collection",type:"string"},{name:"category",type:"string"},{name:"type",type:"string"},{name:"additionalKey",type:"string"},{name:"instance",type:"string"}],Hv=[{name:"name",type:"string"},{name:"symbol",type:"string"}],Wv={GalaTransaction:$v,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:Kv,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:Gv,externalQuoteToken:Hv,tokenInstance:Gv},qv={GalaTransaction:$v,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:Kv,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:Hv,externalQuoteToken:Hv,externalCrossRateToken:Hv,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:Gv,tokenInstance:Gv};function zv(e){return e?qv:Wv}async function Vv(e,t){const{wallet:n}=t,r=e.uniqueKey??`galaconnect-operation-${Pv()}`,s="string"==typeof e.destinationChainId?Nn(e.destinationChainId,1):e.destinationChainId,i=function(e){const t={...e,galaDecimals:"string"==typeof e.galaDecimals?Nn(e.galaDecimals,0):e.galaDecimals,timestamp:"string"==typeof e.timestamp?Nn(e.timestamp,0):e.timestamp};if(e.galaExchangeRate&&(t.galaExchangeRate={...e.galaExchangeRate,timestamp:"string"==typeof e.galaExchangeRate.timestamp?Nn(e.galaExchangeRate.timestamp,0):e.galaExchangeRate.timestamp}),e.galaExchangeCrossRate){const n=e.galaExchangeCrossRate;t.galaExchangeCrossRate={...n,timestamp:"string"==typeof n.timestamp?Nn(n.timestamp,0):n.timestamp},n.baseTokenCrossRate&&(t.galaExchangeCrossRate.baseTokenCrossRate={...n.baseTokenCrossRate,timestamp:"string"==typeof n.baseTokenCrossRate.timestamp?Nn(n.baseTokenCrossRate.timestamp,0):n.baseTokenCrossRate.timestamp}),n.quoteTokenCrossRate&&(t.galaExchangeCrossRate.quoteTokenCrossRate={...n.quoteTokenCrossRate,timestamp:"string"==typeof n.quoteTokenCrossRate.timestamp?Nn(n.quoteTokenCrossRate.timestamp,0):n.quoteTokenCrossRate.timestamp})}return t}(e.destinationChainTxFee),o=Boolean(i.galaExchangeCrossRate),a={destinationChainId:s,destinationChainTxFee:Tv(o?{...i,galaExchangeRate:void 0}:{...i,galaExchangeCrossRate:void 0}),quantity:e.quantity,recipient:e.recipient,tokenInstance:e.tokenInstance,uniqueKey:r},c=zv(o),l=await n.signTypedData(Fv,c,a),u=`Ethereum Signed Message:\n${Lv({domain:Fv,message:a,primaryType:"GalaTransaction",types:c}).length}`;return{...a,signature:l,prefix:u,types:c,domain:Fv}}async function jv(e,t){const{amount:n,recipientAddress:r,tokenSymbol:s}=e,{galaConnectClient:i,tokenMetadataResolver:o,ethereumWallet:a,destinationChainId:c,destinationChain:l,validateRecipientAddress:u}=t,d=Ev(s);Iv(n,d),u(r,"recipient");const h=await o.getTokenMetadata(d),g=await i.fetchBridgeFee({chainId:l,bridgeToken:h.descriptor}),f=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:r,tokenDescriptor:h.descriptor}),p=await Vv(f,{wallet:a}),m=function(e){if(void 0===e||""===e)throw It(vv,"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 i.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(wv,"transactionHash");return t}(await i.bridgeTokenOut({bridgeFromChannel:"asset",bridgeRequestId:m})),tokenSymbol:d,amount:n,feePaid:g.estimatedTotalTxFeeInGala,baseUrl:i.getBaseUrl()})}var Xv;exports.BridgeStatusCode=void 0,(Xv=exports.BridgeStatusCode||(exports.BridgeStatusCode={}))[Xv.PENDING=0]="PENDING",Xv[Xv.SUBMITTED=1]="SUBMITTED",Xv[Xv.CONFIRMED=2]="CONFIRMED",Xv[Xv.PROCESSING=3]="PROCESSING",Xv[Xv.FINALIZING=4]="FINALIZING",Xv[Xv.COMPLETED=5]="COMPLETED",Xv[Xv.FAILED=6]="FAILED",Xv[Xv.DELIVERY_FAILED=7]="DELIVERY_FAILED";const Yv={COMPLETED:exports.BridgeStatusCode.COMPLETED,FAILED:exports.BridgeStatusCode.FAILED,DELIVERY_FAILED:exports.BridgeStatusCode.DELIVERY_FAILED};class Jv{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 r=new Promise((e,r)=>{t=e,n=r});if(this.pendingPromise=this.pendingPromise.then(async()=>{const r=Date.now()-this.lastTimestamp,s=Math.max(0,this.minIntervalMs-r);s>0&&await new Promise(e=>setTimeout(e,s)),this.lastTimestamp=Date.now();try{const n=await e();t(n)}catch(e){n(ot(e)?e:new Error(at(e)))}}),this.chainLength++,this.chainLength>=this.maxChainLength){this.chainLength=0;const e=this.pendingPromise;this.pendingPromise=e.then(()=>Promise.resolve())}return r}}const Qv={maxRetries:3,initialDelayMs:1e3,maxDelayMs:3e4,backoffMultiplier:2,jitterFactor:.1},Zv=new Set([408,429,500,502,503,504]),ew=[/ECONNRESET/i,/ECONNREFUSED/i,/ETIMEDOUT/i,/ENOTFOUND/i,/EAI_AGAIN/i,/socket hang up/i,/network/i,/timeout/i,/aborted/i];function tw(e){if(null!=e&&"object"==typeof e){const t=e;if("number"==typeof t.status)return Zv.has(t.status);if("number"==typeof t.statusCode)return Zv.has(t.statusCode);const n=lt(e);if("string"==typeof n&&("ECONNRESET"===n||"ECONNREFUSED"===n||"ETIMEDOUT"===n||"ENOTFOUND"===n||"EAI_AGAIN"===n))return!0}const t=at(e);return ew.some(e=>e.test(t))}function nw(e,t){const n=t.initialDelayMs*Math.pow(t.backoffMultiplier,e-1),r=Math.min(n,t.maxDelayMs),s=r*t.jitterFactor*Math.random();return Math.floor(r+s)}function rw(e){return new Promise(t=>setTimeout(t,e))}function sw(e,t){return mv(e.get("Ethereum"),"Ethereum",t)}function iw(e,t){return mv(e.get("Solana"),"Solana",t)}function ow(e,t){return e??t.getWalletAddress()}async function aw(e,t,n,r,s){const i=await t.getTokenMetadata(r);return function(e){const t="string"==typeof e.timestamp?Nn(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:i.descriptor}))}async function cw(e,t){return function(e){const t=Nn(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(Yv.COMPLETED),isFailed:t===Number(Yv.FAILED)||t===Number(Yv.DELIVERY_FAILED)}}(await e.getBridgeStatus(t))}function lw(e,t,n){try{const n=function(e,t){if(!Kn(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),[r,s,i,...o]=n;if(""===r||""===s||""===i)throw new Error("Collection, category, and type must be non-empty");const a=o.join(t);if(void 0===r||void 0===s||void 0===i||""===a)throw new Error("AdditionalKey must be non-empty");return{collection:r,category:s,type:i,additionalKey:a}}catch(r){throw function(e,t,n,r){const s=e?.split?.(t)??[],i=void 0!==n?` (${n})`:"";return new yt(`Invalid ${"|"===t?"pipe":"dollar"}-delimited token: "${e}" (${s.length} parts)${i}. Expected format: "collection${t}category${t}type${t}additionalKey" (4 parts minimum). Received: [${s.map(e=>`"${e}"`).join(", ")}]. Error: ${at(r)}`,"token",`INVALID_${"|"===t?"PIPE":"DOLLAR"}_DELIMITED_TOKEN`)}(e,t,n,r)}}function uw(e){return lw(e,"|","pipe-delimited token")}function dw(e){return Kn(e)&&e.includes("|")}function hw(e){return"string"==typeof e&&e.includes("$")}function gw(e){if("object"!=typeof e||null===e)return!1;const t=e,n=t.collection,r=t.category,s=t.type,i=t.additionalKey;return"string"==typeof n&&"string"==typeof r&&"string"==typeof s&&"string"==typeof i&&n.length>0&&r.length>0&&s.length>0&&i.length>0}function fw(e){let t;if("string"==typeof e)t=uw(e);else{if(!gw(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:io(t)}}function pw(e,t){let n;try{n=_n(e,"amount")}catch(t){throw Dt("amount",`${e} (${at(t)})`)}if(!n.isFinite())throw Dt("amount",e);const r=n.multipliedBy(ki(10).pow(t));if(!r.isInteger())throw Dt("amount",`${e} (cannot be represented with ${t} decimals)`);return BigInt(r.toFixed(0))}function mw(e,t){return ki(e.toString()).dividedBy(ki(10).pow(t)).toFixed(t).replace(/\.?0+$/,"")}class yw{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 r=vo[t];if(void 0!==r)return this.cache.set(t,r),r;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 vo}clearCache(){this.cache.clear()}async fetchFromApi(e){let t=e,n=await this.galaConnectClient.getBridgeConfigurations(t),r=n.find(e=>Xt(e.symbol)===Xt(t)&&e.verified);if(r||e.startsWith("G")||(t=`G${e}`,n=await this.galaConnectClient.getBridgeConfigurations(t),r=n.find(e=>Xt(e.symbol)===Xt(t)&&e.verified)),!r)throw new Error(`Unable to locate token metadata for ${e}`);return s={collection:r.collection,category:r.category,type:r.type,additionalKey:r.additionalKey},i=r.decimals,o=r.channel,{descriptor:{collection:s.collection,category:s.category,type:s.type,additionalKey:s.additionalKey},decimals:i,...void 0!==o?{channel:o}:{}};var s,i,o}}class bw 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 vw=ho,ww="https://galachain-gateway-chain-platform-galachain-mainnet.gala.com",Ew=12,Aw=!0,Sw=3,kw=1e3;class Tw{constructor(e){this.baseUrl=e.baseUrl??vw,this.galachainBaseUrl=e.galachainBaseUrl??ww,this.walletAddress=e.walletAddress,this.rateLimiter=new Jv(e.requestsPerSecond??Ew),this.defaultHeaders={"Content-Type":"application/json","X-Wallet-Address":this.walletAddress};const t=e.enableRetry??Aw;this.retryOptions=t?{maxRetries:e.maxRetries??Sw,initialDelayMs:e.retryInitialDelayMs??kw,...e.onRetry&&{onRetry:e.onRetry},shouldRetry:e=>tw(e instanceof bw?{status:e.status}:e)}:null}getBaseUrl(){return this.baseUrl}async getBridgeConfigurations(e){return Ji(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?Tn(e,{rawBody:e}):{message:"Failed to fetch bridge configurations"},new bw(n.status,"/v1/connect/bridge-configurations",t)}return(await n.json()).data.tokens},"GalaConnectClient.getBridgeConfigurations",void 0,e=>{if(e instanceof bw)throw e;throw Nt(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 Ji(async()=>{const r=n.baseUrl??this.baseUrl,s=new URL(e,r),i=n.skipWalletHeader?{"Content-Type":"application/json","X-Wallet-Address":""}:this.defaultHeaders,o=await this.request(s.toString(),{method:"POST",headers:i,body:JSON.stringify(t,(e,t)=>"bigint"==typeof t?t.toString():t)});if(!o.ok){const t=await o.text(),n=500,r=Tn(t,{rawBody:t.slice(0,n)});throw new bw(o.status,e,r)}const a=await o.text();if(""!==a){const t=function(e){if(Zt(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: ${at(e)}`}}}(a);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 bw)throw e;throw Nt(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 r=await fetch(e,{...t,headers:n});if(this.retryOptions&&!r.ok){const t=r.status;if(429===t||t>=500){const n=r.clone(),s=await this.safeParseJson(n);throw new bw(t,e,s)}}return r});return this.retryOptions?async function(e,t={}){const n={...Qv,...t},r=t.shouldRetry??(e=>tw(e));let s;for(let i=1;i<=n.maxRetries+1;i++)try{return await e()}catch(e){if(s=e,i>n.maxRetries)break;if(!r(e,i))break;const o=nw(i,n);t.onRetry&&t.onRetry(e,i,o),await new Promise(e=>setTimeout(e,o))}throw s}(n,this.retryOptions):n()}async safeParseJson(e){const t=await e.text();try{return JSON.parse(t)}catch{return{rawBody:t}}}}class Iw{async waitForCompletion(e,t={}){const{pollInterval:n=15e3,timeout:r=27e5,onStatusUpdate:s}=t,i=Date.now();for(;;){const t=await this.getStatus(e);if(s&&s(t),t.status===exports.BridgeStatusCode.COMPLETED||t.status===exports.BridgeStatusCode.FAILED||t.status===exports.BridgeStatusCode.DELIVERY_FAILED)return t;if(sn(i)>r)throw Ct(`Bridge transaction timed out after ${r}ms. Last status: ${t.status}`,e,"TIMEOUT");await new Promise(e=>setTimeout(e,n))}}}class Cw extends Iw{constructor(e,t){super(),this.galaConnectClient=e,this.tokenConfigs=t}async getStatus(e){return cw(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 Nw(e,t,...n){const r=e[t];return"function"==typeof r?await r(...n):await e.getFunction(t)(...n)}class _w extends Cw{constructor(t){const n=t.tokenConfigs??yo;super(t.galaConnectClient,cv(n)),this.network="Ethereum",this.galaChainWalletAddress=t.galaChainWalletAddress,uv(t.ethereumPrivateKey);const r=t.ethereumRpcUrl??"https://ethereum.publicnode.com";this.ethereumProvider=new e.JsonRpcProvider(r),this.ethereumWallet=new e.Wallet(t.ethereumPrivateKey,this.ethereumProvider),this.ethereumWalletAddress=t.ethereumWalletAddress??this.ethereumWallet.address,this.ethereumBridgeContract=t.ethereumBridgeContract??"0x3F98b5A26EF3f04E1DA3B0B41dD350E8C8F3A7c2",this.tokenMetadataResolver=new yw({galaConnectClient:this.galaConnectClient})}async estimateFee(e,t){return aw(this.galaConnectClient,this.tokenMetadataResolver,"Ethereum",e)}async bridgeOut(e){return jv(e,{galaConnectClient:this.galaConnectClient,tokenMetadataResolver:this.tokenMetadataResolver,ethereumWallet:this.ethereumWallet,destinationChainId:ao.ETHEREUM,destinationChain:"Ethereum",validateRecipientAddress:Av})}async bridgeIn(t){const{amount:n,sourcePrivateKey:r,recipientAddress:s,tokenSymbol:i}=t,o=Ev(i);if(Iv(n,o),void 0!==r&&""!==r&&!av(r))throw kt("sourcePrivateKey","0x-prefixed 64-character hex string",r.slice(0,10)+"...");const a=void 0!==r&&""!==r?new e.Wallet(r,this.ethereumProvider):this.ethereumWallet,c=lv(this.tokenConfigs,o,"Ethereum bridge"),l=await this.tokenMetadataResolver.getTokenMetadata(o),u=new e.Contract(c.contractAddress,wo,a),d=await Nw(u,"decimals"),h=Nn("string"==typeof d||"number"==typeof d||"bigint"==typeof d?d:void 0,18),g=pw(n,h),f=await Nw(u,"balanceOf",a.address);if("bigint"!=typeof f)throw new Error("Ethereum balance response was not a bigint");const p=f;if(p<g){throw It(`Insufficient ${o} balance on Ethereum. Needed ${mw(g,h)}, have ${mw(p,h)}`,"amount")}const m=function(t){const n=new lr;if("client"===n.detectFormat(t))return t;const r=n.normalizeInput(t);if(null==r)throw kt("address","a valid GalaChain address (eth|0x{40-hex}, 0x{40-hex}, or {40-hex})","GalaChain address");const s=n.extractHex(r);return`eth|${e.getAddress("0x"+s).slice(2)}`}(s??this.galaChainWalletAddress);return yv({fromChain:"Ethereum",transactionHash:(await this.executeBridgeDeposit({wallet:a,tokenContract:u,tokenConfig:c,amountBaseUnits:g,decimals:h,recipient:m,metadata:l})).txHash,tokenSymbol:o,amount:n,baseUrl:this.galaConnectClient.getBaseUrl()})}isValidAddress(e){return $n.ETH_ADDRESS.test(e)}getWalletAddress(){return this.ethereumWalletAddress}async getEthereumTokenBalance(t,n){const r=lv(this.tokenConfigs,t,"Ethereum"),s=n??this.ethereumWalletAddress;Av(s);const i=new e.Contract(r.contractAddress,wo,this.ethereumProvider),o=await Nw(i,"balanceOf",s);if("bigint"!=typeof o)throw new Error("Ethereum balance response was not a bigint");return mw(o,r.decimals??18)}async getEthereumNativeBalance(e){const t=e??this.ethereumWalletAddress;Av(t);return mw(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 kt("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>=_w.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: ${at(e)}`}}}async executeBridgeDeposit(t){const n=new e.Contract(this.ethereumBridgeContract,Eo,t.wallet),r=(new TextEncoder).encode(t.recipient);let s;s=t.tokenConfig.bridgeUsesPermit?await this.bridgeWithPermit(t.wallet,t.tokenContract,t.tokenConfig,n,t.amountBaseUnits,r):await this.bridgeWithApproval(t.wallet,t.tokenContract,n,t.tokenConfig,t.amountBaseUnits,r);if(!await s.wait())throw It("Bridge transaction receipt not available","ethereumRpcUrl");await rw(3e4);const i={collection:t.metadata.descriptor.collection,category:t.metadata.descriptor.category,type:t.metadata.descriptor.type,additionalKey:t.metadata.descriptor.additionalKey,instance:"0"};return await this.galaConnectClient.registerBridgeTransaction({quantity:mw(t.amountBaseUnits,t.decimals),tokenInstance:i,fromChain:"Ethereum",toChain:"GC",hash:s.hash}),{txHash:s.hash}}async bridgeWithPermit(t,n,r,s,i,o){const a=await this.ethereumProvider.getNetwork(),c=await Nw(n,"name");if("string"!=typeof c)throw new Error("Ethereum token name response was not a string");const l=c,u=await Nw(n,"nonces",t.address);if("bigint"!=typeof u)throw new Error("Ethereum token nonce response was not a bigint");const d=u,h=BigInt(Math.floor(Date.now()/1e3)+3600),g=await t.signTypedData({name:l,version:"1",chainId:Nn(a.chainId,1),verifyingContract:r.contractAddress},{Permit:[{name:"owner",type:"address"},{name:"spender",type:"address"},{name:"value",type:"uint256"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}]},{owner:t.address,spender:this.ethereumBridgeContract,value:i,nonce:d,deadline:h}),f=e.Signature.from(g);return await Nw(s,"bridgeOutWithPermit",r.contractAddress,i,ao.GALA_CHAIN,o,h,f.v,f.r,f.s)}async bridgeWithApproval(e,t,n,r,s,i){const o=await Nw(t,"allowance",e.address,this.ethereumBridgeContract);if("bigint"!=typeof o)throw new Error("Ethereum allowance response was not a bigint");if(BigInt(o)<s){const e=await Nw(t,"approve",this.ethereumBridgeContract,s);await e.wait()}return await Nw(n,"bridgeOut",r.contractAddress,s,0,ao.GALA_CHAIN,i)}}_w.ETHEREUM_FINALITY_THRESHOLD=12;const xw=new mm("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA");new mm("TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb");const Rw=new mm("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL");new mm("So11111111111111111111111111111111111111112"),new mm("9pan9bMn5HatX4EJdBwg9VgCa7Uz5HL8N1m5D3NdXejP");const Bw=e=>({decode:e.decode.bind(e),encode:e.encode.bind(e)});var Dw,Ow={};function Mw(){if(Dw)return Ow;return Dw=1,Object.defineProperty(Ow,"__esModule",{value:!0}),Ow.toBigIntLE=function(e){{const t=Buffer.from(e);t.reverse();const n=t.toString("hex");return 0===n.length?BigInt(0):BigInt(`0x${n}`)}},Ow.toBigIntBE=function(e){{const t=e.toString("hex");return 0===t.length?BigInt(0):BigInt(`0x${t}`)}},Ow.toBufferLE=function(e,t){{const n=e.toString(16),r=Buffer.from(n.padStart(2*t,"0").slice(0,2*t),"hex");return r.reverse(),r}},Ow.toBufferBE=function(e,t){{const n=e.toString(16);return Buffer.from(n.padStart(2*t,"0").slice(0,2*t),"hex")}},Ow}var Lw=Mw();const Uw=function(e,t){return n=>{const r=Kl.blob(t,n),{encode:s,decode:i}=Bw(r),o=r;return o.decode=(t,n)=>{const r=i(t,n);return e?Lw.toBigIntLE(Oo.Buffer.from(r)):Lw.toBigIntBE(Oo.Buffer.from(r))},o.encode=(n,r,i)=>{let o;return function(e){if("bigint"!=typeof e)throw new Error("Expected a `BigInt`")}(n),o=0===t?Oo.Buffer.alloc(0):e?Lw.toBufferLE(n,t):Lw.toBufferBE(n,t),s(o,r,i)},o}}.bind(null,!0),Pw=Uw(8),Fw=e=>{const t=Kl.blob(32,e),{encode:n,decode:r}=Bw(t),s=t;return s.decode=(e,t)=>{const n=r(e,t);return new mm(n)},s.encode=(e,t,r)=>{const s=e.toBuffer();return n(s,t,r)},s};var $w;!function(e){e[e.Uninitialized=0]="Uninitialized",e[e.Initialized=1]="Initialized",e[e.Frozen=2]="Frozen"}($w||($w={}));const Kw=Kl.struct([Fw("mint"),Fw("owner"),Pw("amount"),Kl.u32("delegateOption"),Fw("delegate"),Kl.u8("state"),Kl.u32("isNativeOption"),Pw("isNative"),Pw("delegatedAmount"),Kl.u32("closeAuthorityOption"),Fw("closeAuthority")]);Kw.span;var Gw=function(e){if(e.length>=255)throw new TypeError("Alphabet too long");const t=new Uint8Array(256);for(let e=0;e<t.length;e++)t[e]=255;for(let n=0;n<e.length;n++){const r=e.charAt(n),s=r.charCodeAt(0);if(255!==t[s])throw new TypeError(r+" is ambiguous");t[s]=n}const n=e.length,r=e.charAt(0),s=Math.log(n)/Math.log(256),i=Math.log(256)/Math.log(n);function o(e){if("string"!=typeof e)throw new TypeError("Expected String");if(0===e.length)return new Uint8Array;let i=0,o=0,a=0;for(;e[i]===r;)o++,i++;const c=(e.length-i)*s+1>>>0,l=new Uint8Array(c);for(;i<e.length;){const r=e.charCodeAt(i);if(r>255)return;let s=t[r];if(255===s)return;let o=0;for(let e=c-1;(0!==s||o<a)&&-1!==e;e--,o++)s+=n*l[e]>>>0,l[e]=s%256>>>0,s=s/256>>>0;if(0!==s)throw new Error("Non-zero carry");a=o,i++}let u=c-a;for(;u!==c&&0===l[u];)u++;const d=new Uint8Array(o+(c-u));let h=o;for(;u!==c;)d[h++]=l[u++];return d}return{encode:function(t){if(t instanceof Uint8Array||(ArrayBuffer.isView(t)?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Array.isArray(t)&&(t=Uint8Array.from(t))),!(t instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(0===t.length)return"";let s=0,o=0,a=0;const c=t.length;for(;a!==c&&0===t[a];)a++,s++;const l=(c-a)*i+1>>>0,u=new Uint8Array(l);for(;a!==c;){let e=t[a],r=0;for(let t=l-1;(0!==e||r<o)&&-1!==t;t--,r++)e+=256*u[t]>>>0,u[t]=e%n>>>0,e=e/n>>>0;if(0!==e)throw new Error("Non-zero carry");o=r,a++}let d=l-o;for(;d!==l&&0===u[d];)d++;let h=r.repeat(s);for(;d<l;++d)h+=e.charAt(u[d]);return h},decodeUnsafe:o,decode:function(e){const t=o(e);if(t)return t;throw new Error("Non-base"+n+" character")}}}("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");function Hw(e,t,n,r,s){const[i]=mm.findProgramAddressSync([t.toBuffer(),r.toBuffer(),e.toBuffer()],s);return i}class Ww extends Cw{constructor(t){const n=t.tokenConfigs??bo;super(t.galaConnectClient,cv(n)),this.network="Solana",this.solanaBridgeAccountCache=new Map,this.galaChainWalletAddress=t.galaChainWalletAddress,uv(t.ethereumPrivateKey);const r=new e.JsonRpcProvider("https://ethereum.publicnode.com");this.ethereumWallet=new e.Wallet(t.ethereumPrivateKey,r);const s=t.solanaRpcUrl??"https://api.mainnet-beta.solana.com";let i;this.solanaConnection=new tv(s,"confirmed");try{i=Gw.decode(t.solanaPrivateKeyBase58)}catch{throw kt("solanaPrivateKeyBase58","base58-encoded string",t.solanaPrivateKeyBase58.slice(0,20)+"...")}if(64!==i.length)throw kt("solanaPrivateKeyBase58","64 bytes when decoded",`${i.length} bytes`);this.solanaKeypair=nv.fromSecretKey(i);const o=t.solanaBridgeProgram??"AaE4dTnL75XqgUJpdxBKg6vS9sTJgBPJwBQRVhD29WwS";this.solanaBridgeProgramId=new mm(o),[this.solanaBridgeTokenAuthority]=mm.findProgramAddressSync([Buffer.from("bridge_token_authority")],this.solanaBridgeProgramId),[this.solanaBridgeConfigPda]=mm.findProgramAddressSync([Buffer.from("configv1")],this.solanaBridgeProgramId),[this.solanaNativeBridgePda]=mm.findProgramAddressSync([Buffer.from("native_sol_bridge")],this.solanaBridgeProgramId),this.tokenMetadataResolver=new yw({galaConnectClient:this.galaConnectClient})}async estimateFee(e,t){return aw(this.galaConnectClient,this.tokenMetadataResolver,"Solana",e)}async bridgeOut(e){return jv(e,{galaConnectClient:this.galaConnectClient,tokenMetadataResolver:this.tokenMetadataResolver,ethereumWallet:this.ethereumWallet,destinationChainId:ao.SOLANA,destinationChain:"Solana",validateRecipientAddress:Sv})}async bridgeIn(e){const{amount:t,sourcePrivateKey:n,recipientAddress:r,tokenSymbol:s}=e,i=Ev(s);Iv(t,i);let o=this.solanaKeypair;if(void 0!==n&&""!==n){let e;try{e=Gw.decode(n)}catch{throw kt("sourcePrivateKey","base58-encoded string",n.slice(0,20)+"...")}if(64!==e.length)throw kt("sourcePrivateKey","64 bytes when decoded",`${e.length} bytes`);o=nv.fromSecretKey(e)}const a=lv(this.tokenConfigs,i,"Solana bridge"),c=await this.tokenMetadataResolver.getTokenMetadata(i),l=pw(t,c.decimals),u=r??this.galaChainWalletAddress;return yv({fromChain:"Solana",transactionHash:await this.executeSolanaBridgeOut({keypair:o,tokenConfig:a,metadata:c,amountBaseUnits:l,recipient:u,amount:t}),tokenSymbol:i,amount:t,baseUrl:this.galaConnectClient.getBaseUrl()})}isValidAddress(e){try{return new mm(e),!0}catch{return!1}}getWalletAddress(){return this.solanaKeypair.publicKey.toBase58()}async getSolanaTokenBalance(e,t){const n=lv(this.tokenConfigs,e,"Solana");if(n.isNative)return this.getSolanaNativeBalance(t);const r=t??this.solanaKeypair.publicKey.toBase58(),s=kv(r),i=Hw(new mm(n.mintAddress),s,0,xw,Rw);try{const e=await async function(e,t,n,r){const s=await e.getAccountInfo(t);if(!s)throw new Error(`could not find account ${t.toBase58()}`);if(!s.owner.equals(r))throw new Error(`account owner mismatch: expected ${r.toBase58()}, got ${s.owner.toBase58()}`);return{amount:Kw.decode(s.data).amount,decimals:0}}(this.solanaConnection,i,0,xw),t=n.decimals??8;return mw(e.amount,t)}catch(t){if(ot(t)&&t.message.includes("could not find")){return mw(0n,n.decimals??8)}throw It(`Failed to fetch ${e} balance for ${r}: ${at(t)}`,`${e}Account`)}}async getSolanaNativeBalance(e){const t=kv(e??this.solanaKeypair.publicKey.toBase58()),n=await this.solanaConnection.getBalance(t,"confirmed");return mw(BigInt(n),9)}async requestDevnetAirdrop(e=1,t){On(e,1e-5,2,"amount");const n=void 0!==t&&""!==t?kv(t):this.solanaKeypair.publicKey,r=this.solanaConnection.rpcEndpoint;if(!r.includes("devnet"))throw It(`Solana devnet faucet only available on devnet. Current RPC: ${r}. Ensure SDK is configured with environment='stage' for devnet access.`,"solanaRpcUrl");const s=Math.floor(1e9*e);return await this.solanaConnection.requestAirdrop(n,s)}async getSolanaTransactionStatus(e){if(!Kn(e))throw kt("signature","a non-empty string");if(!/^[1-9A-HJ-NP-Za-km-z]{80,90}$/.test(e))throw kt("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 mm(e.tokenConfig.mintAddress),n=Boolean(e.tokenConfig.isNative),r=n?void 0:await this.getSolanaBridgeAccounts(t),s=n?void 0:Hw(t,e.keypair.publicKey,0,xw,Rw),i=Buffer.from(e.recipient,"utf8"),o=Buffer.alloc(8);o.writeBigUInt64LE(e.amountBaseUnits);const a=Buffer.alloc(4);a.writeUInt32LE(i.length);const c=n?this.buildNativeBridgeInstruction(e.keypair.publicKey,o,a,i):this.buildTokenBridgeInstruction(e.keypair.publicKey,s,t,r,o,a,i),l=new Fm;l.add(sv.setComputeUnitPrice({microLamports:375e3}),sv.setComputeUnitLimit({units:2e5}),c),l.feePayer=e.keypair.publicKey;const u=await this.sendAndConfirmWithFallback(l,e.keypair),d={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:d,fromChain:"Solana",toChain:"GC",hash:u}),u}async sendAndConfirmWithFallback(e,t,n=3){let r=null;for(let s=1;s<=n;s++){try{const i=await this.solanaConnection.getLatestBlockhash("confirmed");e.recentBlockhash=i.blockhash,e.feePayer=t.publicKey,e.signatures=[],e.sign(t);const o=await this.solanaConnection.sendRawTransaction(e.serialize(),{skipPreflight:!1,preflightCommitment:"confirmed"});try{return await this.solanaConnection.confirmTransaction({signature:o,blockhash:i.blockhash,lastValidBlockHeight:i.lastValidBlockHeight},"confirmed"),o}catch(e){const t=ot(e)?e.message.toLowerCase():"";if(!(t.includes("block height exceeded")||t.includes("blockhash not found")||t.includes("expired")))throw e;const i=await this.solanaConnection.getSignatureStatuses([o]);if("confirmed"===i.value[0]?.confirmationStatus||"finalized"===i.value[0]?.confirmationStatus)return o;r=new Error(`Transaction ${o} not confirmed - block height exceeded (attempt ${s}/${n})`)}}catch(e){r=ot(e)?e:new Error(at(e));const t=r.message.toLowerCase();if(!(t.includes("block height exceeded")||t.includes("blockhash not found")||t.includes("timeout")||t.includes("expired"))||s===n)throw r}const i=Math.min(1e3*Math.pow(2,s-1),5e3);await rw(i)}throw r??new Error("Transaction confirmation failed after max retries")}buildNativeBridgeInstruction(e,t,n,r){const s=Buffer.concat([Ao.BRIDGE_OUT_NATIVE,t,n,r]);return new Pm({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:Qm.programId,isSigner:!1,isWritable:!1}],data:s})}buildTokenBridgeInstruction(e,t,n,r,s,i,o){const a=Buffer.concat([Ao.BRIDGE_OUT,s,i,o]);return new Pm({programId:this.solanaBridgeProgramId,keys:[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!0},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:r.mintLookup,isSigner:!1,isWritable:!1},{pubkey:r.tokenBridge,isSigner:!1,isWritable:!1},{pubkey:r.bridgeTokenAccount,isSigner:!1,isWritable:!0},{pubkey:this.solanaBridgeTokenAuthority,isSigner:!1,isWritable:!1},{pubkey:this.solanaBridgeConfigPda,isSigner:!1,isWritable:!0},{pubkey:Qm.programId,isSigner:!1,isWritable:!1},{pubkey:xw,isSigner:!1,isWritable:!1}],data:a})}async getSolanaBridgeAccounts(e){const t=e.toBase58(),n=this.solanaBridgeAccountCache.get(t);if(n)return n;const[r]=mm.findProgramAddressSync([Buffer.from("mint_lookup_v1"),e.toBuffer()],this.solanaBridgeProgramId),s=await this.solanaConnection.getAccountInfo(r,"confirmed");if(!s)throw It(`Mint lookup account not found for ${r.toBase58()}`,"solanaBridgeProgram");if(!s.owner.equals(this.solanaBridgeProgramId))throw It("Mint lookup account owner mismatch for Solana bridge program","solanaBridgeProgram");if(s.data.length<40)throw It("Mint lookup account data is unexpectedly short","solanaBridgeProgram");const i={mintLookup:r,tokenBridge:new mm(s.data.slice(8,40)),bridgeTokenAccount:Hw(e,this.solanaBridgeTokenAuthority,0,xw,Rw)};return this.solanaBridgeAccountCache.set(t,i),i}}const qw={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"}},zw={solanaBridgeProgram:"AaE4dTnL75XqgUJpdxBKg6vS9sTJgBPJwBQRVhD29WwS",rateLimit:12,pollInterval:15e3,pollTimeout:27e5};class Vw{static normalizeGalaChainAddress(e){const t=new lr;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 r=t.normalizeInput(n);if(!r)throw It(`Invalid GalaChain address format: ${e}`,"galaChainWalletAddress");const s=t.extractHex(r);return`eth|${Vw.checksumAddress(s)}`}static checksumAddress(t){const n=t.toLowerCase(),r=ar(e.keccak256(e.toUtf8Bytes(n)));let s="";for(let e=0;e<n.length;e++){const t=n[e],i=r[e];void 0!==t&&void 0!==i&&parseInt(i,16)>=8?s+=t.toUpperCase():s+=t??""}return s}constructor(e){const t=Vw.normalizeGalaChainAddress(e.galaChainWalletAddress),n=e.environment??"prod",r=ro["stage"===n?"stage":"prod"],s=qw[n],i={galaConnectBaseUrl:e.galaConnectBaseUrl??r.dexApiBaseUrl,galaChainApiBaseUrl:e.galaChainApiBaseUrl??r.gatewayBaseUrl,ethereumRpcUrl:e.ethereumRpcUrl??s.ethereum,solanaRpcUrl:e.solanaRpcUrl??s.solana,ethereumBridgeContract:e.ethereumBridgeContract??mo(n),solanaBridgeProgram:e.solanaBridgeProgram??zw.solanaBridgeProgram,rateLimit:e.rateLimit??zw.rateLimit,pollInterval:e.pollInterval??zw.pollInterval,pollTimeout:e.pollTimeout??zw.pollTimeout,galaChainWalletAddress:t,ethereumPrivateKey:e.ethereumPrivateKey,environment:n};this.config=e.solanaPrivateKey?{...i,solanaPrivateKey:e.solanaPrivateKey}:i,this.galaConnectClient=new Tw({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=po(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 _w(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:bo};this.strategies.set("Solana",new Ww(e))}}async resolveTokenSymbol(e,t){return Ji(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=fw(e).stringified,r="Ethereum"===t?"ETHEREUM":"SOLANA",s=await this.bridgeableTokenService.getTokenByTokenId(n,r);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('${r}')`," - 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 Ji(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 Ji(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 Ji(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 Ji(async()=>{if(null!=t){const n=this.strategies.get(t);if(n)return n.getStatus(e)}const n=this.strategies.get("Ethereum");let r;if(n)try{return await n.getStatus(e)}catch(e){r=ot(e)?e:new Error(at(e))}const s=this.strategies.get("Solana");if(s)try{return await s.getStatus(e)}catch(e){r=ot(e)?e:new Error(at(e))}const i=r?` (last error: ${r.message})`:"";throw Ct(`Unable to get status for transaction ${e}${i}`,e)},"BridgeService.getBridgeStatus")}async waitForBridgeCompletion(e,t){return Ji(async()=>{const n={pollInterval:t?.pollInterval??this.config.pollInterval,timeout:t?.timeout??this.config.pollTimeout,...t?.onStatusUpdate&&{onStatusUpdate:t.onStatusUpdate}},r=this.strategies.get("Ethereum");if(r)try{return await r.getStatus(e),r.waitForCompletion(e,n)}catch{}const s=this.strategies.get("Solana");if(s)return s.waitForCompletion(e,n);throw Ct(`Unable to wait for transaction ${e}: no suitable strategy found`,e)},"BridgeService.waitForBridgeCompletion")}getSupportedBridgeTokens(e){const t=[],n=po(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 bo){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 Ji(async()=>sw(this.strategies).getEthereumTokenBalance(e,t),"BridgeService.getEthereumTokenBalance")}async getEthereumNativeBalance(e){return Ji(async()=>sw(this.strategies).getEthereumNativeBalance(e),"BridgeService.getEthereumNativeBalance")}async getSolanaTokenBalance(e,t){return Ji(async()=>iw(this.strategies).getSolanaTokenBalance(e,t),"BridgeService.getSolanaTokenBalance")}async getSolanaNativeBalance(e){return Ji(async()=>iw(this.strategies).getSolanaNativeBalance(e),"BridgeService.getSolanaNativeBalance")}async fetchEthereumWalletTokenBalance(e,t){return Ji(async()=>{const n=sw(this.strategies),r=fv(po(this.config.environment),e,"Ethereum"),s=ow(t,n);return hv(r,await n.getEthereumTokenBalance(e,s))},"BridgeService.fetchEthereumWalletTokenBalance")}async fetchEthereumWalletNativeBalance(e){return Ji(async()=>{const t=sw(this.strategies),n=ow(e,t);return dv("ETH",await t.getEthereumNativeBalance(n),18)},"BridgeService.fetchEthereumWalletNativeBalance")}async fetchSolanaWalletTokenBalance(e,t){return Ji(async()=>{const n=iw(this.strategies),r=fv(bo,e,"Solana"),s=ow(t,n);return gv(r,await n.getSolanaTokenBalance(e,s))},"BridgeService.fetchSolanaWalletTokenBalance")}async fetchSolanaWalletNativeBalance(e){return Ji(async()=>{const t=iw(this.strategies),n=ow(e,t);return dv("SOL",await t.getSolanaNativeBalance(n),9)},"BridgeService.fetchSolanaWalletNativeBalance")}async requestSolanaDevnetAirdrop(e,t){return Ji(async()=>iw(this.strategies).requestDevnetAirdrop(e,t),"BridgeService.requestSolanaDevnetAirdrop")}async getSolanaTransactionStatus(e){return Ji(async()=>iw(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 Ji(async()=>sw(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 Ji(async()=>{const t=sw(this.strategies),n=ow(e,t),r=po(this.config.environment),[s,...i]=await Promise.all([t.getEthereumNativeBalance(n),...r.map(async e=>hv(e,await t.getEthereumTokenBalance(e.symbol,n)))]);return{address:n,native:dv("ETH",s,18),tokens:i,timestamp:Date.now()}},"BridgeService.fetchEthereumWalletAllBalances")}async fetchSolanaWalletAllBalances(e){return Ji(async()=>{const t=iw(this.strategies),n=ow(e,t),[r,...s]=await Promise.all([t.getSolanaNativeBalance(n),...bo.map(async e=>gv(e,await t.getSolanaTokenBalance(e.symbol,n)))]);return{address:n,native:dv("SOL",r,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 jw,Xw;!function(e){e.PROCESSED="PROCESSED",e.COMPLETED="COMPLETED",e.SUCCESS="SUCCESS",e.FAILED="FAILED",e.ERROR="ERROR",e.PROCESSING="PROCESSING",e.PENDING="PENDING"}(jw||(jw={})),exports.SDKTransactionStatus=void 0,(Xw=exports.SDKTransactionStatus||(exports.SDKTransactionStatus={})).PENDING="pending",Xw.PROCESSING="processing",Xw.COMPLETED="completed",Xw.FAILED="failed",Xw.TIMEOUT="timeout";const Yw={[jw.PROCESSED]:exports.SDKTransactionStatus.COMPLETED,[jw.COMPLETED]:exports.SDKTransactionStatus.COMPLETED,[jw.SUCCESS]:exports.SDKTransactionStatus.COMPLETED,[jw.FAILED]:exports.SDKTransactionStatus.FAILED,[jw.ERROR]:exports.SDKTransactionStatus.FAILED,[jw.PROCESSING]:exports.SDKTransactionStatus.PROCESSING,[jw.PENDING]:exports.SDKTransactionStatus.PENDING},Jw="7.0.0-beta.5",Qw={DEFAULT_PAGE_SIZE:50,MAX_PAGE_SIZE:1e3,SAFETY_MAX_PAGES:1e4,DEFAULT_OFFSET:0,DEFAULT_LIMIT:10,BACKEND_MAX_PAGE_SIZE:20};function Zw(e,t=1,n=Qw.BACKEND_MAX_PAGE_SIZE){return Math.max(t,Math.min(n,Math.ceil(e??t)))}function eE(e,t){if("number"!=typeof e||!Number.isInteger(e))throw Bt("total","a non-negative integer",e);if(e<0)throw _t("total",0,1/0,e);if("number"!=typeof t||!Number.isInteger(t))throw Bt("limit","a non-negative integer",t);if(t<0)throw _t("limit",0,1/0,t);return 0===t?1:0===e?0:Math.ceil(e/t)}function tE(e){return"string"==typeof e?e:"number"==typeof e||"boolean"==typeof e||"bigint"==typeof e?String(e):JSON.stringify(e)??""}function nE(e,t){const n={};void 0!==e.cursor&&(n.cursor=e.cursor);const r=void 0!==e.pageSize?Math.min(e.pageSize,t):t;return n.pageSize=String(r),n}function rE(e,t,n){for(const r of n){const n=t[r];null!=n&&""!==n&&(e[r]=tE(n))}return e}const sE="x-api-key";class iE extends rr{constructor(e,t,n,r=!1,s){super(e,r),this.adminApiKey=t??void 0,this.jwtAuth=n,this.userApiKey=s??void 0}setJwtAuth(e){this.jwtAuth=e}validateTokenName(e,t){!function(e,t){if(!Kn(e))throw St("tokenName","Token name");const n=Vt(e);if(!t.PATTERN.test(n))throw kt("tokenName",`${t.MIN_LENGTH}-${t.MAX_LENGTH} alphanumeric characters`,"Token name")}(e,t)}validateRequiredString(e,t,n){!function(e,t,n){if(!Kn(e))throw St(t,n)}(e,t,n)}validateOptionalString(e,t,n,r){!function(e,t,n,r){if(null!=e){if("string"!=typeof e)throw Bt(t,"string",typeof e,n);if(e.length>r)throw Rt(t,r,e.length,n)}}(e,t,n,r)}validateOptionalNumber(e,t,n,r,s,i,o){!function(e,t,n,r,s){if(null!=e){if("number"!=typeof e)throw Bt(t,"number",typeof e,n);if(e<r||e>s)throw _t(t,r,s,e,n)}}(e,t,n,r,s)}validateOptionalDate(e,t,n){!function(e,t,n){if(null!=e&&!rn(e))throw kt(t,"a valid ISO 8601 date string",n)}(e,t,n)}validatePositiveInteger(e,t,n){tr(e,t,n)}validateStatusFilter(e,t,n="status"){nr(e,t,n)}buildPaginationParams(e,t){return nE(e,t)}addOptionalFilterParams(e,t,n){return rE(e,t,n)}buildEndpoint(e,t){return function(e,t){let n=e;for(const[e,r]of Object.entries(t))n=n.replace(`:${e}`,encodeURIComponent(r.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 vt("Admin API key required for this operation. Set streamAdminApiKey in SDK config.");return{[sE]:this.adminApiKey}}getJwtHeaders(){if(!this.jwtAuth)throw new vt("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?{[sE]:this.userApiKey}:this.getJwtHeaders()}extractData(e){return Ft(e,"Backend request failed",!0),Kt(e,"No data in backend response")}extractDataOrNull(e){return Ft(e,"Backend request failed",!1),e.data??null}async toggleFeature(e,t,n){this.validateTokenName(e,n);const r=this.buildEndpoint(t,{tokenName:e}),s=await this.http.post(r,{},this.getAdminHeaders()),i=this.extractData(s);return{enabled:i.enabled,tokenName:i.tokenName??Vt(e)}}}class oE extends iE{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async getSettings(){return{settings:(await this.http.get(ze.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(ze.UPDATE_SETTINGS,t,this.getDualAuthHeaders())).settings}}async getModeration(e){this.validatePositiveInteger(e.flagId,"flagId","Flag ID");const t=ze.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=ze.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(ze.GET_STATUS,{},this.getDualAuthHeaders())).status}}}const aE={MODERATOR:"MODERATOR",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MANAGER:"MANAGER",OWNER:"OWNER"},cE=zn(aE),lE={MANAGE_COMMUNITY:"MANAGE_COMMUNITY",MANAGE_STREAM:"MANAGE_STREAM",MANAGE_SETTINGS:"MANAGE_SETTINGS",MANAGE_RECORDINGS:"MANAGE_RECORDINGS",VIEW_ANALYTICS:"VIEW_ANALYTICS"},uE=Object.values(lE);function dE(e){return cE.includes(e)}function hE(e){const t=[];return void 0===e.role||null===e.role?t.push("Role is required"):dE(e.role)||t.push(`Invalid role. Must be one of: ${cE.join(", ")}`),fE(e,t),t}function gE(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||dE(e.role)||t.push(`Invalid role. Must be one of: ${cE.join(", ")}`),fE(e,t,!0),t}function fE(e,t,n=!1){const r=t.length;if(gt(t,()=>{Zn(e.description,"description",255)}),t.length>r&&(t[r]="Description must be 255 characters or less"),void 0!==e.tokenNames){const n=t.length;gt(t,()=>{if(!Array.isArray(e.tokenNames))throw 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;gt(t,()=>{er(e.expiresAt,"expiresAt")}),t.length>n&&(t[n]="expiresAt must be a valid ISO 8601 date string")}}function pE(e){if(void 0!==e.pageSize&&("number"!=typeof e.pageSize||e.pageSize<1||e.pageSize>ln))throw Bt("pageSize",`number between 1 and ${ln}`,typeof e.pageSize);if(void 0!==e.cursor&&("string"!=typeof e.cursor||""===e.cursor.trim()))throw Bt("cursor","non-empty string",typeof e.cursor)}const mE={[aE.MODERATOR]:1,[aE.TECHNICAL_PRODUCER]:1,[aE.MANAGER]:2,[aE.OWNER]:3};class yE extends rr{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),Ft(n,"API key operation failed",!0),e.data}validateApiKeyId(e){this.validatePositiveInteger(e,"id","API key ID")}async create(e){const t=hE(e);if(t.length>0)throw new yt(t.join("; "),"options","VALIDATION_FAILED");this.logger.debug("Creating API key",{role:e.role,delegateAllTokens:e.delegateAllTokens});const n={role:e.role};void 0!==e.description&&(n.description=e.description),void 0!==e.delegateAllTokens&&(n.delegateAllTokens=e.delegateAllTokens),void 0!==e.tokenNames&&e.tokenNames.length>0&&(n.tokenNames=e.tokenNames),void 0!==e.expiresAt&&(n.expiresAt=e.expiresAt),void 0!==e.tokenPermissions&&(n.tokenPermissions=e.tokenPermissions);const r=await this.http.post(ee.CREATE,n,this.getJwtHeaders()),s=this.extractData(r);return this.logger.debug("API key created",{id:s.id,keyPrefix:s.keyPrefix}),s}async findAll(e={}){pE(e),this.logger.debug("Listing API keys",e);const t=nE(e,ln),n=await this.http.get(ee.LIST,t,this.getJwtHeaders()),r=this.extractData(n);return this.logger.debug("Listed API keys",{count:r.apiKeys.length,total:r.pageInfo.totalCount}),r}async findOne(e){this.validateApiKeyId(e),this.logger.debug("Getting API key",{id:e});const t=ee.GET.replace(":id",String(e)),n=await this.http.get(t,{},this.getJwtHeaders()),r=this.extractData(n);return this.logger.debug("Got API key",{id:r.id,keyPrefix:r.keyPrefix}),r}async update(e,t){this.validateApiKeyId(e);const n=gE(t);if(n.length>0)throw new yt(n.join("; "),"options","VALIDATION_FAILED");this.logger.debug("Updating API key",{id:e,options:t});const r={};void 0!==t.role&&(r.role=t.role),void 0!==t.description&&(r.description=t.description),void 0!==t.delegateAllTokens&&(r.delegateAllTokens=t.delegateAllTokens),void 0!==t.tokenNames&&(r.tokenNames=t.tokenNames),void 0!==t.expiresAt&&(r.expiresAt=t.expiresAt),void 0!==t.tokenPermissions&&(r.tokenPermissions=t.tokenPermissions);const s=ee.UPDATE.replace(":id",String(e)),i=await this.http.patch(s,r,this.getJwtHeaders()),o=this.extractData(i);return this.logger.debug("Updated API key",{id:o.id,keyPrefix:o.keyPrefix}),o}async revoke(e){this.validateApiKeyId(e),this.logger.debug("Revoking API key",{id:e});const t=ee.REVOKE.replace(":id",String(e));await this.http.delete(t,{},this.getJwtHeaders()),this.logger.debug("API key revoked",{id:e})}getRoles(){return[...cE]}}const bE={VIEWERS:"viewers",CHAT_PARTICIPANTS:"chat_participants"},vE=qn(bE),wE=Yn([{field:"id",type:"number"},{field:"userAddress",type:"string"},{field:"bannedBy",type:"string"},{field:"createdAt",type:"string"},{field:"isPermanent",type:"boolean"},{field:"tokenName",type:"string",nullable:!0},{field:"reason",type:"string",nullable:!0},{field:"expiresAt",type:"string",nullable:!0}]),EE=Yn([{field:"userAddress",type:"string"},{field:"isPermanent",type:"boolean"}]),AE=Yn([{field:"userAddress",type:"string"}]),SE=Yn([{field:"tokenName",type:"string"},{field:"action",type:"string",validator:e=>"CHAT_MESSAGE"===e||"COMMENT"===e||"REACTION"===e}]);function kE(e){return null==e||""===e||"string"==typeof e&&(!Qn(e)&&e.length<=fn.BAN_REASON.MAX_LENGTH)}function TE(e){return!!Hn(e)||"number"==typeof e&&(e>=mn&&e<=yn)}function IE(e){if(!Kn(e.userAddress))throw St("userAddress");if(!kE(e.reason))throw new yt(`reason must be at most ${fn.BAN_REASON.MAX_LENGTH} characters`,"reason","TOO_LONG");if(!TE(e.durationSeconds))throw new yt(`durationSeconds must be between ${mn} and ${yn} seconds`,"durationSeconds","OUT_OF_RANGE")}class CE extends iE{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async createBan(e){!function(e){jn(e.tokenName,"tokenName",on),IE(e)}(e);const t=this.buildEndpoint(q,{tokenName:e.tokenName}),n=NE(e),r=await this.http.post(t,n,this.getMultiAuthHeaders());return{ban:this.extractData(r),tokenName:Vt(e.tokenName)}}async removeBan(e){!function(e){if(jn(e.tokenName,"tokenName",on),!Kn(e.userAddress))throw St("userAddress")}(e);const t=this.buildEndpoint(j,{tokenName:e.tokenName,userAddress:e.userAddress}),n=await this.http.delete(t,{},this.getMultiAuthHeaders()),r=this.extractDataOrNull(n);return{removed:r?.removed??!0,tokenName:Vt(e.tokenName),userAddress:r?.userAddress??e.userAddress.toLowerCase()}}async listBans(e){!function(e){jn(e.tokenName,"tokenName",on),Wn(0,void 0,ln,e.pageSize)}(e);const t=this.buildEndpoint(z,{tokenName:e.tokenName}),n=this.buildPaginationParams(e,ln);this.addOptionalFilterParams(n,e,["search","name","userAddress"]);const r=await this.http.get(t,n,this.getMultiAuthHeaders()),s=this.extractData(r);return{items:s.bans,pageInfo:s.pageInfo}}async getBanStatus(e){!function(e){if(jn(e.tokenName,"tokenName",on),!Kn(e.userAddress))throw St("userAddress")}(e);const t=this.buildEndpoint(V,{tokenName:e.tokenName,userAddress:e.userAddress}),n=await this.http.get(t,{},this.getMultiAuthHeaders()),r=this.extractDataOrNull(n);return{banned:null!==r,...null!==r&&{ban:r},tokenName:Vt(e.tokenName),userAddress:e.userAddress.toLowerCase()}}async getActiveUsers(e){!function(e){if(jn(e.tokenName,"tokenName",on),void 0!==e.type&&!vE(e.type))throw new yt(`type must be one of: ${Object.values(bE).join(", ")}`,"type",mt.INVALID_VALUE)}(e);const t=this.buildEndpoint(X,{tokenName:e.tokenName}),n={};this.addOptionalFilterParams(n,e,["type","search","name","userAddress"]);const r=await this.http.get(t,n,this.getMultiAuthHeaders());return this.extractData(r)}async createGlobalBan(e){!function(e){IE(e)}(e);const t=NE(e),n=await this.http.post(Y,t,this.getDualAuthHeaders());return{ban:this.extractData(n)}}async removeGlobalBan(e){!function(e){if(!Kn(e.userAddress))throw St("userAddress")}(e);const t=this.buildEndpoint(Z,{userAddress:e.userAddress}),n=await this.http.delete(t,{},this.getDualAuthHeaders()),r=this.extractDataOrNull(n);return{removed:r?.removed??!0,userAddress:r?.userAddress??e.userAddress.toLowerCase()}}async listGlobalBans(e){const t=e??{pageSize:20};!function(e){Wn(0,void 0,ln,e.pageSize)}(t);const n=this.buildPaginationParams(t,ln);this.addOptionalFilterParams(n,t,["search","name","userAddress"]);const r=await this.http.get(J,n,this.getDualAuthHeaders()),s=this.extractData(r);return{items:s.bans,pageInfo:s.pageInfo}}async getGlobalBan(e){!function(e){if(!Kn(e.userAddress))throw St("userAddress")}(e);const t=this.buildEndpoint(Q,{userAddress:e.userAddress}),n=await this.http.get(t,{},this.getDualAuthHeaders()),r=this.extractDataOrNull(n);return{banned:null!==r,...null!==r&&{ban:r},userAddress:e.userAddress.toLowerCase()}}}function NE(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 _E(e,t={}){const{maxPages:n=1e4,logger:r,pageSize:s=20,concurrency:i=1,startPage:o=1}=t,a=[];let c=o;const l=o+n-1;let u=!0,d=0;if(i<=1)for(;u&&c<=l;){r&&r.debug(`Auto-pagination: fetching page ${c} with limit ${s}`);const t=await e(c,s);if(null==t||!Array.isArray(t.items)){r&&r.warn("Auto-pagination: received invalid result structure, stopping");break}if(a.push(...t.items),d=t.total,r&&r.debug(`Auto-pagination: page ${c} returned ${t.items.length} items, hasNext: ${String(t.hasNext)}`),0===t.items.length){r&&r.debug(`Auto-pagination: no items returned on page ${c}, exiting loop`);break}u=t.hasNext,c++}else for(r&&r.debug(`Auto-pagination: using concurrent mode with concurrency=${i}`);u&&c<=l;){const t=[];for(let e=0;e<i&&c+e<=l;e++)t.push(c+e);r&&r.debug(`Auto-pagination: fetching pages ${t.join(", ")} concurrently`);const n=t.map(t=>e(t,s).catch(e=>{const n=e,i=n.statusCode??n.response?.status??n.originalError?.response?.status??n.status??n.launchpadError?.statusCode;if(400===i||404===i)return r&&r.debug(`Auto-pagination: page ${t} returned ${i} (end of pagination)`,{statusCode:i}),{items:[],total:0,totalPages:0,page:t,limit:s,hasNext:!1,hasPrevious:!1};throw e})),o=await Promise.all(n);for(const e of o){if(null==e||!Array.isArray(e.items)){r&&r.warn("Auto-pagination: received invalid result structure in batch, stopping"),u=!1;break}if(0===e.items.length){r&&r.debug("Auto-pagination: empty page in batch, reached end of results"),u=!1;break}if(a.push(...e.items),d=e.total,!e.hasNext){u=!1;break}}c+=t.length,r&&r.debug(`Auto-pagination: batch complete, total items so far: ${a.length}`)}return c>l&&r&&r.warn(`Auto-pagination: exceeded maxPages limit of ${n} (maxPage=${l}), stopping iteration`),r&&r.debug(`Auto-pagination: completed with total items: ${a.length}, total count: ${d}`),{items:a,total:d}}function xE(e){if("string"==typeof e){if(!dw(e))throw new yt(`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 t=e.split("|");if(t.length>=5){const e=uw(t.slice(0,4).join("|")),n=t[4]??"0";return{...e,instance:n.length>0?n:"0"}}return{...uw(e),instance:"0"}}if("object"==typeof e&&null!==e){if("instance"in e&&void 0!==e.instance&&"string"==typeof e.instance&&e.instance.length>0){if(!gw(e))throw new yt("Invalid tokenId object format. All fields (collection, category, type, additionalKey) must be non-empty strings","tokenId","INVALID_TOKEN_ID_FORMAT");return e}if(!gw(e))throw new yt("Invalid tokenId object format. All fields (collection, category, type, additionalKey) are required","tokenId","INVALID_TOKEN_ID_FORMAT");return{...e,instance:"0"}}throw new yt(`Invalid tokenId type: ${typeof e}. Expected string, TokenClassKey, or TokenInstanceKey`,"tokenId","INVALID_TOKEN_ID_TYPE")}function RE(e){return function(e){try{if(!Kn(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[r,s,i,...o]=n;if(""===r||""===s||""===i)throw new Error("Collection, category, and type must be non-empty");const a=o.slice(0,-1),c=a.length>0?a.join("$"):o[0];if(void 0===r||void 0===s||void 0===i||""===c||void 0===c)throw new Error("AdditionalKey must be non-empty");return{collection:r,category:s,type:i,additionalKey:c}}catch(t){throw new yt(`Invalid vault address: "${e}". Expected format: "service|Token$Unit$SYMBOL$additionalKey$launchpad". Error: ${at(t)}`,"vaultAddress","INVALID_VAULT_ADDRESS_FORMAT")}}(e)}function BE(e){return{...RE(e),instance:"0"}}function DE(e){return RE(e).type}function OE(e){return io(xE(e))}var ME=Object.freeze({__proto__:null,extractTokenSymbolFromVault:DE,isTokenClassKeyStrict:gw,normalizeToTokenInstanceKey:xE,normalizeTokenIdToString:OE,parseVaultAddressToTokenClassKey:RE,parseVaultAddressToTokenInstance:BE});class LE{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 r=Math.min(t,this.getMaxLimit()),s=this.buildApiParams(n),i=await this.dexApiHttp.request({method:"GET",url:this.getApiEndpoint(),params:{...s,pageSize:r,offset:e}});if(Hn(i)||!Array.isArray(i.tokens))throw new yt("Invalid API response: expected { tokens: array }","response","INVALID_RESPONSE");return{items:this.transformApiResponse(i.tokens),rawCount:i.tokens.length}}async autoPaginateFetch(e){return async function(e,t){const{maxLimit:n,logger:r,maxPages:s=1e4}=t,i=[];let o=0,a=!0,c=0;for(;a&&c<s;){r&&r.debug(`Auto-pagination (offset): fetching at offset ${o} with limit ${n}`);const t=await e(o,n);if(null==t||!Array.isArray(t.items)){r&&r.warn("Auto-pagination (offset): received invalid result structure, stopping");break}i.push(...t.items),a=t.rawCount===n,o+=n,c++,r&&r.debug(`Auto-pagination (offset): fetched ${i.length} items so far (hasMore=${String(a)})`)}return c>=s&&r&&r.warn(`Auto-pagination (offset): exceeded maxPages limit of ${s}, stopping`),r&&r.debug(`Auto-pagination (offset): completed with total items: ${i.length}`),i}(async(t,n)=>this.executePaginatedRequest(t,n,e),{maxLimit:this.getMaxLimit(),logger:this.logger})}handleError(e,t){throw Nt(e,t,this.logger)}}class UE extends sr{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,r=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));r.set(s,e)}this.primaryIndex.set(e,n),this.secondaryIndex.set(e,r),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 r=this.secondaryIndex.get(e);r||(r=new Map,this.secondaryIndex.set(e,r));for(const e of t){const t=this.normalizeKey(this.extractPrimaryKey(e));n.set(t,e);const s=this.normalizeKey(this.extractSecondaryKey(e));r.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 r={},s={};for(const t of e)r[t]=0;for(const[e,i]of this.primaryIndex){t.push(e),n+=i.size,r[e]=i.size;const o=this.fetchTimestamps.get(e);void 0!==o&&(s[e]=o)}return{networks:t,totalItems:n,itemsByNetwork:r,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 PE=["ETHEREUM","SOLANA"];class FE extends UE{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(PE);return{...e,totalTokens:e.totalItems,tokensByNetwork:e.itemsByNetwork}}}class $E extends LE{constructor(e,t=!1){super(e,t,"BridgeableTokenService"),this.cache=new FE(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),r=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:r};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:r=this.getDefaultLimit()}=e,s=Math.min(r,this.getMaxLimit());return this.logger.debug(`Fetching bridgeable tokens for ${t} (offset=${n}, limit=${s})`),Ji(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 Ji(async()=>{const t=await async function(e){const{network:t,cache:n,fetchFn:r,logger:s,itemTypeName:i="items"}=e;if(n.has(t)){const e=n.getAll(t);return s&&s.debug(`Returning ${e.length} cached ${i} for ${t}`),{items:e,fetchedAt:n.getFetchTimestamp(t)??Date.now(),itemCount:e.length}}s&&s.debug(`Fetching all ${i} for ${t} (no cache)`);const o=await r();return n.set(t,o),{items:o,fetchedAt:Date.now(),itemCount:o.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,r=OE(t);this.cache.has(n)||await this.fetchAllBridgeableTokensByNetwork(n);const s=this.cache.getByTokenId(n,r),i=void 0!==s,o=i?"ETHEREUM"===n?s.ethereumContractAddress:s.solanaContractAddress:void 0,a={isBridgeable:i,tokenSymbol:s?.symbol??uw(r).collection,network:n};return void 0!==o&&(a.contractAddress=o),a}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 KE(e){return{maxAcceptableReverseBondingCurveFee:Bn(e.maxAcceptableReverseBondingCurveFee)}}class GE extends i.ChainCallDTO{constructor(e,t,n="0",r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=Bn(t),this.expectedToken=Dn(n),this.extraFees=KE(r)}}class HE extends i.ChainCallDTO{constructor(e,t,n,r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=Dn(t),this.expectedNativeToken=Bn(n),this.extraFees=KE(r)}}class WE extends i.ChainCallDTO{constructor(e,t,n="0",r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=Dn(t),this.expectedNativeToken=Bn(n),this.extraFees=KE(r)}}class qE extends i.ChainCallDTO{constructor(e,t,n,r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=Bn(t),this.expectedToken=Dn(n),this.extraFees=KE(r)}}const zE={BuyNativeDto:GE,BuyExactDto:HE,SellExactDto:WE,SellNativeDto:qE};function VE(e,t,n){let r;On(t,0,1,"slippageToleranceFactor");try{r=_n(e,"expectedAmount")}catch{throw new Error(`Invalid expected amount: ${e}. Must be a valid number`)}if(0===t)return e;const s=r.multipliedBy(t);let i;switch(n){case"buy-native":case"sell-exact":i=r.minus(s);break;case"buy-exact":case"sell-native":i=r.plus(s);break;default:throw new Error(`Unknown operation type: ${n}`)}return ki(i).isLessThan(0)&&(i=ki(0)),Ti(i)}function jE(e){return`${e}-${Date.now()}_${r.v4().replace(/-/gu,"").substring(0,26)}`}function XE(){return jE("galaconnect-operation")}function YE(e,t){const n={[e]:[]},r=new Set;function s(e){const t=n[e];if(void 0===t)throw new Error("Missing EIP-712 type "+e);return t}function i(e,t,o,a=!1){if(void 0===t)return;if(Array.isArray(t)){const n=i(e,t[0],o,!0);return a||(r.add(e),s(o).push({name:e,type:(n??e)+"[]"})),void 0===n?void 0:n+"[]"}if("object"==typeof t&&null!==t){if(void 0!==n[e]||r.has(e))throw new Error("Name collisions not yet supported");n[e]=[];for(const[n,s]of Object.entries(t)){if(r.has(n))throw new Error("Name collisions not yet supported");i(n,s,e)}return a||(r.add(e),s(o).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 a||(r.add(e),s(o).push({name:e,type:c})),c}for(const[n,r]of Object.entries(t))i(n,r,e);return n}const JE={name:"GalaChain"},QE={name:"ethereum",chainId:1};function ZE(e){if("string"!=typeof e)throw new Error("Wallet returned an invalid signature");return e}function eA(e,t,n,r){return{...e,signature:t,types:n,domain:r}}class tA extends t.PrivateKeySigner{constructor(t){super(t),this.typedDataWallet=new e.Wallet(t),this.walletAddress=`eth|${this.typedDataWallet.address.slice(2)}`}async signTypedData(e,t){const n=YE(e,t);return eA(t,await this.typedDataWallet.signTypedData(JE,n,t),n,JE)}}class nA extends t.GalaWalletSigner{async signTypedData(e,t){const n=YE(e,t),r={domain:QE,types:n,message:t,Primary_type:e};return eA(t,ZE(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(r),this.walletAddress]})),n,QE)}}class rA extends t.BrowserWalletSigner{constructor(e,t){super(e,t),this.typedDataProvider=e}async signTypedData(e,t){const n=this.typedDataProvider,r=await n.getNetwork(),s={name:r.name,chainId:Number(r.chainId)},i=YE(e,t),o=await n.getSigner();return eA(t,ZE(await o.signTypedData(s,i,t)),i,s)}}function sA(e){if(!Kn(e))throw new Error("Invalid token format: token must be a non-empty string");return e.replace(/\|/g,"$")}function iA(e){return lw(e,"$","dollar-delimited token")}class oA extends sr{constructor(e=!1){super(e)}generateStringsInstructions(e){try{this.logger.debug("🔧 Generating stringsInstructions for:",e);const t=this.extractTokenSymbolFromVault(e),n=this.createTokenInstance(t),r=this.createGalaInstance(),s=`$service$${n.toStringKey()}$launchpad`,i=`$tokenBalance$${n.toStringKey()}$${e}`,o=`$tokenBalance$${n.toStringKey()}$${e}`,a=`$tokenBalance$${r.toStringKey()}$${e}`,c=[s,i,o,a,`$tokenBalance$${r.toStringKey()}$${e}`];return this.logger.debug("✅ Generated stringsInstructions:",c),c}catch(e){this.logger.error("❌ Failed to generate stringsInstructions:",e);const t=at(e);throw new yt(`Failed to generate stringsInstructions: ${t}`,"vaultAddress","INVALID_VAULT_ADDRESS")}}createTokenInstance(e){const t=new i.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 i.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(!Kn(e))throw St("vaultAddress","Vault address");try{const t=DE(e);return this.logger.debug("🔍 Extracted token symbol:",{vaultAddress:e,tokenSymbol:t}),t}catch(e){if(e instanceof yt)throw kt("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad");throw e}}validateVaultAddress(e){if(!Kn(e))throw St("vaultAddress","Vault address");if(!e.startsWith("service|Token$Unit$"))throw kt("vaultAddress",'starting with "service|Token$Unit$"');if(!e.endsWith("$launchpad"))throw kt("vaultAddress",'ending with "$launchpad"');const t=function(e){if(!Kn(e))return null;const t=e.match(/^service\|Token\$Unit\$([^$]+)\$eth:([a-fA-F0-9]{40})\$launchpad$/);if(!t)return null;const n=t[1],r=t[2];return void 0===n||void 0===r?null:{tokenSymbol:n,creatorAddress:r.toLowerCase()}}(e);if(!t)throw kt("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 kt("vaultAddress","containing a 1-10 letter token symbol (case insensitive)");return this.logger.debug("✅ Vault address validation passed:",e),!0}generateTokenClassKeyString(e,t,n,r){return`${e}$${t}$${n}$${r}`}parseTokenClassKeyString(e){try{return iA(e)}catch(e){if(e instanceof yt)throw kt("stringKey","format: collection$category$type$additionalKey (4 parts)");throw e}}}function aA(e){return"object"==typeof e&&null!==e?e:void 0}class cA extends rr{constructor(e,t,n=!1,r,s,i=.05,o=.01){if(super(e,n),this.tokenResolver=t,this._walletProvider=r,this.userAddress=s,this.defaultSlippageToleranceFactor=i,this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor=o,this.bundleEndpoint="/bundle",null!==this._walletProvider&&void 0!==this._walletProvider&&null!=s){const e=aA(this._walletProvider),t=e?.privateKey;"string"==typeof t?this.signer=new tA(t):function(e){const t=aA(e);return"function"==typeof t?.request}(this._walletProvider)&&void 0!==this.userAddress&&(this.signer=new rA(this._walletProvider,this.userAddress)),this.tokenKeyService=new oA(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 Ht(()=>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 yt)return{success:!1,error:at(e)};throw e}}validateBundleData(e){if(null==e)throw St("bundleData","Bundle data");if(null===e.signedDto||void 0===e.signedDto)throw St("signedDto","Signed DTO");if(!Kn(e.method))throw St("method","Method name");if(!Array.isArray(e.stringsInstructions))throw kt("stringsInstructions","an array of resource tracking strings");if(0===e.stringsInstructions.length)throw new yt("stringsInstructions cannot be empty","stringsInstructions","EMPTY_ARRAY");const t=["BuyWithNative","BuyExactToken","SellExactToken","SellWithNative"];if(!t.includes(e.method))throw kt("method",`one of: ${t.join(", ")}`);e.stringsInstructions.forEach((e,t)=>{if(!Kn(e))throw new yt(`stringsInstructions[${t}] must be a non-empty string`,`stringsInstructions[${t}]`,"INVALID_INSTRUCTION");if(!hw(e))throw new yt(`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(ut(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 at(e)??"Unknown bundle transaction error"}async getBundlerTransactionResult(e){try{if(!Kn(e))throw St("transactionId","Transaction ID");let t;this.logger.debug("🔍 Checking bundler transaction result:",e);try{t=await Ht(()=>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 yt)return{success:!1,error:at(e)};throw e}}async cancelTransaction(e){try{if(!Kn(e))throw St("transactionId","Transaction ID");let t;this.logger.debug("🚫 Cancelling transaction:",e);try{t=await Ht(()=>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 yt)return{success:!1,error:at(e)};throw e}}async getHealthStatus(){this.logger.debug("🏥 Checking bundle service health");try{const e=await Ht(()=>this.http.get(`${this.bundleEndpoint}/health`),{errorContext:"Bundle service health check failed",logger:this.logger});return null==e?{success:!1,error:"No response from bundle service health check"}:(this.logger.debug("💚 Bundle service health:",e),{success:!0,data:e})}catch(e){return{success:!1,error:this.formatErrorMessage(e)}}}async buyToken(e){this.ensureTradingServicesAvailable();const{tokenName:t,amount:n,type:r,expectedAmount:s}=e,{effectiveSlippageFactor:i,effectiveMaxFee:o,vaultAddress:a}=await this.prepareTradingOperation(t,e.maxAcceptableReverseBondingCurveFee,e.maxAcceptableReverseBondingCurveFeeSlippageFactor,e.slippageToleranceFactor);if("native"===r){if(null==s||""===s)throw new yt("expectedAmount is required for native buy operations. Use getBuyTokenAmount() first to calculate expected tokens.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=VE(s,i,"buy-native");this.logger.debug("BuyNative slippage applied:",{originalExpectedTokens:s,slippageFactor:i,adjustedMinTokens:e});const t=new zE.BuyNativeDto(a,n,e,{maxAcceptableReverseBondingCurveFee:o});return await this.executeBundleTransaction(t,"BuyWithNative",a)}{if(null==s||""===s)throw new yt("expectedAmount is required for exact buy operations. Use getBuyTokenAmount() first to calculate expected GALA cost.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=VE(s,i,"buy-exact");this.logger.debug("BuyExact slippage applied:",{originalExpectedGalaCost:s,slippageFactor:i,adjustedMaxGalaCost:e});const t=new zE.BuyExactDto(a,n,e,{maxAcceptableReverseBondingCurveFee:o});return await this.executeBundleTransaction(t,"BuyExactToken",a)}}async sellToken(e){this.ensureTradingServicesAvailable();const{tokenName:t,amount:n,type:r,expectedAmount:s}=e,{effectiveSlippageFactor:i,effectiveMaxFee:o,vaultAddress:a}=await this.prepareTradingOperation(t,e.maxAcceptableReverseBondingCurveFee,e.maxAcceptableReverseBondingCurveFeeSlippageFactor,e.slippageToleranceFactor);if("exact"===r){if(null==s||""===s)throw new yt("expectedAmount is required for exact sell operations. Use getSellTokenAmount() first to calculate expected GALA.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=VE(s,i,"sell-exact");this.logger.debug("SellExact slippage applied:",{originalExpectedGala:s,slippageFactor:i,adjustedMinGala:e});const t=new zE.SellExactDto(a,n,e,{maxAcceptableReverseBondingCurveFee:o});return await this.executeBundleTransaction(t,"SellExactToken",a)}{if(null==s||""===s)throw new yt("expectedAmount is required for native sell operations. Use getSellTokenAmount() first to calculate tokens to sell.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=VE(s,i,"sell-native");this.logger.debug("SellNative slippage applied:",{originalExpectedTokensToSell:s,slippageFactor:i,adjustedMaxTokensToSell:e});const t=new zE.SellNativeDto(a,n,e,{maxAcceptableReverseBondingCurveFee:o});return await this.executeBundleTransaction(t,"SellWithNative",a)}}async prepareTradingOperation(e,t,n,r){const{effectiveSlippageFactor:s,effectiveMaxFee:i}=this.calculateEffectiveSlippage(t,n,r),o=await this.resolveTokenNameToVault(e);if(null==o)throw At(e);return{effectiveSlippageFactor:s,effectiveMaxFee:i,vaultAddress:o}}calculateEffectiveSlippage(e,t,n){const r=n??this.defaultSlippageToleranceFactor,s=t??this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor;let i=e??"0";return null!=e&&(i=VE(e,s,"buy-exact"),this.logger.debug("Reverse bonding curve fee slippage applied:",{baseFee:e,slippageFactor:s,adjustedMaxFee:i})),{effectiveSlippageFactor:r,effectiveFeeSlippageFactor:s,effectiveMaxFee:i}}ensureTradingServicesAvailable(){if(!this.signer||!this.tokenKeyService)throw It("Trading services not available. BundleService requires walletProvider and userAddress for trading operations.","walletProvider");if(null===this.userAddress||void 0===this.userAddress)throw St("userAddress","User address")}async executeBundleTransaction(e,t,n){this.ensureTradingServicesAvailable();try{e.uniqueKey=jE("galaswap-operation");const r=await this.signer.signObject(t,e),s=this.tokenKeyService.generateStringsInstructions(n),i={stringsInstructions:s,method:t,signedDto:r};this.logger.debug("📦 Bundle transaction data:",{method:t,stringsInstructions:s,dtoKeys:Object.keys(r)});const o=await this.submitTransaction(i);if(o.success){const e=$t(o);if(null!=e)return this.logger.debug("✅ Bundle transaction submitted:",e),{success:!0,data:{transactionId:e,message:"Transaction submitted successfully. Monitor WebSocket for completion."}}}const a=o.error;throw new wt("string"==typeof a?a:"Bundle transaction failed",void 0,"BUNDLE_FAILED")}catch(e){throw this.logger.error("❌ Bundle transaction error:",e),e}}async resolveTokenNameToVault(e){return await this.tokenResolver.resolveTokenToVault(e)}}class lA extends rr{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(rt),t=this.extractData(e);return this.logger.debug("Fetched client feature flags",{flagCount:Object.keys(t.flags).length}),{flags:t.flags}}}var uA,dA,hA,gA;exports.ContentType=void 0,(uA=exports.ContentType||(exports.ContentType={})).CHAT_MESSAGE="CHAT_MESSAGE",uA.COMMENT="COMMENT",uA.STREAM="STREAM",uA.RECORDING="RECORDING",exports.FlagReason=void 0,(dA=exports.FlagReason||(exports.FlagReason={})).INAPPROPRIATE_CONTENT="INAPPROPRIATE_CONTENT",dA.SPAM="SPAM",dA.HARASSMENT="HARASSMENT",dA.SCAM="SCAM",dA.OTHER="OTHER",exports.FlagStatus=void 0,(hA=exports.FlagStatus||(exports.FlagStatus={})).PENDING="PENDING",hA.DISMISSED="DISMISSED",hA.ACTIONED="ACTIONED",exports.FlagAction=void 0,(gA=exports.FlagAction||(exports.FlagAction={})).DELETE_CONTENT="DELETE_CONTENT",gA.BAN_USER="BAN_USER",gA.DELETE_AND_BAN="DELETE_AND_BAN";const fA={[exports.FlagReason.INAPPROPRIATE_CONTENT]:"Inappropriate Content",[exports.FlagReason.SPAM]:"Spam",[exports.FlagReason.HARASSMENT]:"Harassment",[exports.FlagReason.SCAM]:"Scam",[exports.FlagReason.OTHER]:"Other"},pA={[exports.FlagStatus.PENDING]:"Pending",[exports.FlagStatus.DISMISSED]:"Dismissed",[exports.FlagStatus.ACTIONED]:"Actioned"},mA={[exports.FlagAction.DELETE_CONTENT]:"Delete Content",[exports.FlagAction.BAN_USER]:"Ban User",[exports.FlagAction.DELETE_AND_BAN]:"Delete & Ban"},yA={[exports.ContentType.CHAT_MESSAGE]:"Chat Message",[exports.ContentType.COMMENT]:"Comment",[exports.ContentType.STREAM]:"Stream",[exports.ContentType.RECORDING]:"Recording"},bA=qn(exports.ContentType),vA=qn(exports.FlagReason),wA=qn(exports.FlagStatus),EA=qn(exports.FlagAction),AA=Yn([{field:"id",type:"number"},{field:"tokenName",type:"string"},{field:"contentType",type:"string",validator:bA},{field:"contentId",type:"string"},{field:"reporterAddress",type:"string"},{field:"reportedUserAddress",type:"string"},{field:"status",type:"string",validator:wA}]),SA={TOKEN_NAME:an,CONTENT_ID:fn.CONTENT_ID,DETAILS:fn.FLAG_DETAILS,PAGINATION:{MAX_LIMIT:ln}};function kA(e,t="tokenName"){jn(e,t,SA.TOKEN_NAME)}function TA(e){if(void 0!==e.contentType&&!bA(e.contentType))throw kt("contentType",`one of: ${Object.values(exports.ContentType).join(", ")}`,"Content type");if(void 0!==e.status&&!wA(e.status))throw kt("status",`one of: ${Object.values(exports.FlagStatus).join(", ")}`);if(void 0!==e.reason&&!vA(e.reason))throw kt("reason",`one of: ${Object.values(exports.FlagReason).join(", ")}`);if(void 0!==e.reporterAddress&&!Kn(e.reporterAddress))throw Bt("reporterAddress","a non-empty string",typeof e.reporterAddress);if(void 0!==e.reporterAddress&&mr(e.reporterAddress,"reporterAddress"),void 0!==e.reportedUserAddress&&!Kn(e.reportedUserAddress))throw Bt("reportedUserAddress","a non-empty string",typeof e.reportedUserAddress);void 0!==e.reportedUserAddress&&mr(e.reportedUserAddress,"reportedUserAddress"),Wn(0,void 0,SA.PAGINATION.MAX_LIMIT,e.pageSize)}class IA extends iE{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async createFlag(e){!function(e){if(kA(e.tokenName),void 0===e.contentType)throw St("contentType","Content type");if(!bA(e.contentType))throw kt("contentType",`one of: ${Object.values(exports.ContentType).join(", ")}`,"Content type");if(!Kn(e.contentId))throw St("contentId","Content ID");if(e.contentId.length>SA.CONTENT_ID.MAX_LENGTH)throw Rt("contentId",SA.CONTENT_ID.MAX_LENGTH,e.contentId.length,"Content ID");if(!Kn(e.reportedUserAddress))throw St("reportedUserAddress","Reported user address");if(mr(e.reportedUserAddress,"reportedUserAddress"),!(e.contentType!==exports.ContentType.STREAM&&e.contentType!==exports.ContentType.RECORDING||void 0!==e.reason&&null!==e.reason))throw St("reason","Reason");if(void 0!==e.reason&&!vA(e.reason))throw kt("reason",`one of: ${Object.values(exports.FlagReason).join(", ")}`,"Reason");if(void 0!==e.details&&!Kn(e.details))throw Bt("details","a non-empty string",typeof e.details);if(void 0!==e.details&&e.details.length>SA.DETAILS.MAX_LENGTH)throw Rt("details",SA.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(le.CREATE,t,this.getMultiAuthHeaders());return{flag:this.extractData(n).flag}}async listFlags(e){return function(e){kA(e.tokenName),TA(e)}(e),this.fetchFlagList(e)}async listGlobalFlags(e={}){return function(e){void 0!==e.tokenName&&kA(e.tokenName),TA(e)}(e),this.fetchFlagList(e)}async dismissFlag(e){!function(e){if(void 0===e.flagId||null===e.flagId)throw St("flagId","Flag ID");try{Ln(e.flagId,"flagId")}catch{throw kt("flagId","a positive integer","Flag ID")}}(e);const t=le.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 St("flagId","Flag ID");try{Ln(e.flagId,"flagId")}catch{throw kt("flagId","a positive integer","Flag ID")}if(void 0===e.action)throw St("action","Action");if(!EA(e.action))throw kt("action",`one of: ${Object.values(exports.FlagAction).join(", ")}`,"Action")}(e);const t=le.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=nE(e,ln);rE(t,e,["tokenName","contentType","status","reason","reporterAddress","reportedUserAddress"]);const n=await this.http.get(le.LIST,t,this.getMultiAuthHeaders()),r=this.extractData(n);return{items:r.flags,pageInfo:r.pageInfo}}}const CA=["heart","fire","laugh","wow","thumbs_up"];class NA extends iE{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}validateReactionTokenName(e){this.validateTokenName(e,an)}validateMessageId(e){if(!Kn(e))throw St("messageId","Message ID");if(Mn(e,pn.CONTENT_REACTION.MAX_LENGTH,"messageId"),!pn.CONTENT_REACTION.PATTERN.test(e))throw kt("messageId","msg-{timestamp}-{uuid} or chat-{timestamp}-{uuid} format","Message ID")}validateReactionType(e){if(!Kn(e))throw St("reactionType","Reaction type");if(!CA.includes(e))throw kt("reactionType",`one of: ${CA.join(", ")}`,"Reaction type")}async addContentReaction(e){void 0!==e.tokenName&&this.validateReactionTokenName(e.tokenName),this.validateMessageId(e.messageId),this.validateReactionType(e.reactionType);const t=Le,n={messageId:e.messageId,reactionType:e.reactionType};void 0!==e.tokenName&&(n.tokenName=Vt(e.tokenName));const r=await this.http.post(t,n,this.getMultiAuthHeaders()),s=this.extractData(r),{created:i,...o}=s;return{data:o,created:i}}async removeContentReaction(e){void 0!==e.tokenName&&this.validateReactionTokenName(e.tokenName),this.validateMessageId(e.messageId),this.validateReactionType(e.reactionType);const t=`${Ue}?${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 _A extends sr{constructor(e,t,n,r=!1){super(r),this.dexBackendHttp=e,this.cache=t,this.galaChainService=n}async fetchTokenPrice(e){const{tokenId:t}=e,{hasB:n}=Vn(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 yt("tokenName parameter requires LaunchpadSDK routing - call LaunchpadSDK.fetchTokenPrice({tokenName}) instead","tokenName","INVALID_PARAMS")}async _fetchDexTokenSpotPrice(e){if(null==e)throw St("tokenId","Token ID");try{const t=xE(e),n=io(t),r=sA(n);if(this.logger.debug(`Fetching DEX spot price for token: ${r}`),!this.dexBackendHttp)throw Tt("DEX Backend API client not configured");const s=await this.dexBackendHttp.request({method:"GET",url:"/market/price",params:{assetIds:r}}),i=null!==s&&"object"==typeof s?s:{},o=[t.type,t.collection].filter(e=>"string"==typeof e&&""!==e&&"none"!==e).map(e=>e.toUpperCase()).map(e=>i[e]).find(e=>void 0!==e)??(1===Object.keys(i).length?Object.values(i)[0]:void 0),a=o?.price;if("number"!=typeof a||!Number.isFinite(a))throw new yt(`Invalid price response: no market price for ${r}`,"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): $${a}`),{symbol:l,price:a}}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}: $${a}`)}catch(e){this.logger.debug(`Could not fetch token details for symbol, falling back to token format parsing: ${ot(e)?e.message:String(e)}`),l=Xt("Token"===t.collection?t.type:t.collection),this.logger.debug(`DEX spot price for ${l} (fallback): $${a}`)}return{symbol:l,price:a}}catch(e){if(e instanceof yt)throw e;throw Tt(`Failed to fetch DEX spot price: ${at(e)}`)}}async fetchLaunchpadTokenSpotPrice(e,t,n){if(!Kn(e))throw new yt(ft,"tokenName",mt.REQUIRED);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=io(t.sellingToken);return this._fetchDexTokenSpotPrice(n)}}catch(t){this.logger.debug(`Could not determine graduation status for ${e}, falling back to bonding curve: ${at(t)}`)}this.logger.debug(`Using bonding curve calculation for token: ${e}`);const r=await t({tokenName:e,amount:"1",type:"native"}),s=await this._fetchDexTokenSpotPrice({collection:"GALA",category:"Unit",type:"none",additionalKey:"none"});if(null==s)throw Tt("GALA price not available");const i=In(r.amount,0)/1e18;if(i<=0)throw new yt(`Invalid token amount calculation: ${i}`,"amount","INVALID_CALCULATION");const o=s.price/i;return{symbol:Xt(e),price:o}}catch(t){if(ot(t))throw Tt(`Failed to calculate launchpad token spot price for ${e}: ${at(t)}`);throw Tt(`Failed to calculate launchpad token spot price for ${e}: ${at(t)}`)}}async fetchTokenDetails(e){this.logger.debug("Fetching token details from GalaChain for tokenId:",e);try{if(!this.galaChainService)throw Tt("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 yt||ot(t))&&("NetworkError"===t.name||at(t).includes("Token not found")))throw t;throw Tt(`Failed to fetch token details from GalaChain for ${String(e)}: ${at(t)}`,500)}}async fetchAllDexSeasons(){try{if(!this.dexBackendHttp)throw Tt("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:nn(t?.start??null),end:nn(t?.end??null),rulesId:t?.rules_id??0}});return this.logger.debug(`Fetched ${n.length} DEX seasons`),n}catch(e){if(ot(e)&&at(e).includes("not configured"))throw e;if(ut(e)&&404===e.response?.status)return this.logger.warn("Seasons endpoint not available"),[];throw Tt(`Failed to fetch DEX seasons: ${at(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{Ln(e,"seasonId")}catch{throw St("seasonId","Season ID must be a positive number")}try{if(!this.dexBackendHttp)throw Tt("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 r=$t(t);if(null!=r&&"object"==typeof r&&Array.isArray(r.leaderboard))n=r.leaderboard;else if(Array.isArray(t.leaderboard))n=t.leaderboard;else{if(!Array.isArray(r))return this.logger.warn("Leaderboard endpoint returned unexpected structure:",t),{entries:[],seasonId:e,totalEntries:0};n=r}}}const r=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 ${r.length} entries`),{entries:r,seasonId:e,totalEntries:r.length}}catch(t){if(ot(t)&&at(t).includes("must be a positive number"))throw t;throw Tt(`Failed to fetch DEX leaderboard for season ${e}: ${at(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 Tt("DEX Backend API client not configured");const e=$t(await this.dexBackendHttp.request({method:"GET",url:"/v2/trade/volume"}));if(!e)throw Tt("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 Tt(`Failed to fetch DEX volume summary: ${at(e)}`)}}}const xA={BATCH_SIZE:20,FLUSH_INTERVAL_MS:3e3,MAX_QUEUE_SIZE:1e3,FLUSH_ON_PAGE_HIDE:!0,FLUSH_ON_PAGE_UNLOAD:!0,DEBUG:!1};class RA{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??xA.BATCH_SIZE,flushIntervalMs:t.flushIntervalMs??xA.FLUSH_INTERVAL_MS,maxQueueSize:t.maxQueueSize??xA.MAX_QUEUE_SIZE,flushOnPageHide:t.flushOnPageHide??xA.FLUSH_ON_PAGE_HIDE,flushOnPageUnload:t.flushOnPageUnload??xA.FLUSH_ON_PAGE_UNLOAD,debug:t.debug??xA.DEBUG},this.setupPageLifecycleListeners()}track(e,t,n){if(this.isShuttingDown)return void this.logger.warn("EventsBatcher is shutting down, ignoring track call");const r={eventType:e,payload:t,clientTimestamp:(new Date).toISOString(),...void 0!==n?.userAddress&&""!==n.userAddress&&{userAddress:n.userAddress},...void 0!==n?.tokenName&&""!==n.tokenName&&{tokenName:n.tokenName},...void 0!==n?.sessionId&&""!==n.sessionId&&{sessionId:n.sessionId}};this.buffer(r),n?.immediate&&this.scheduleFlush(0)}async flush(){if(0===this.eventBuffer.length)return;this.cancelFlushTimer();const e=this.eventBuffer.splice(0);this.logger.debug(`Flushing ${e.length} events`);try{const t=await this.submitEvents(e);this.totalFlushed+=t.accepted,this.lastFlushTime=Date.now(),this.lastError=void 0,this.logger.debug(`Flush successful, accepted ${t.accepted} events`)}catch(t){throw this.eventBuffer.unshift(...e),this.lastError=t instanceof Error?t.message:String(t),this.logger.error(`Flush failed: ${this.lastError}`),t}}getStats(){const e={bufferedCount:this.eventBuffer.length,totalQueued:this.totalQueued,totalFlushed:this.totalFlushed,totalDropped:this.totalDropped};return void 0!==this.lastFlushTime&&(e.lastFlushTime=this.lastFlushTime),void 0!==this.lastError&&(e.lastError=this.lastError),e}configure(e){void 0!==e.batchSize&&(this.config.batchSize=e.batchSize),void 0!==e.flushIntervalMs&&(this.config.flushIntervalMs=e.flushIntervalMs),void 0!==e.maxQueueSize&&(this.config.maxQueueSize=e.maxQueueSize),void 0!==e.flushOnPageHide&&(this.config.flushOnPageHide=e.flushOnPageHide),void 0!==e.flushOnPageUnload&&(this.config.flushOnPageUnload=e.flushOnPageUnload)}async shutdown(e=5e3){if(this.isShuttingDown=!0,this.removePageLifecycleListeners(),0!==this.eventBuffer.length)try{await Promise.race([this.flush(),new Promise((t,n)=>setTimeout(()=>n(new Error("Flush timeout during shutdown")),e))])}catch(e){this.logger.error(`Shutdown flush failed: ${e instanceof Error?e.message:String(e)}`)}}buffer(e){this.eventBuffer.length>=this.config.maxQueueSize&&(this.eventBuffer.shift(),this.totalDropped++,this.logger.warn("Event buffer full, dropped oldest event")),this.eventBuffer.push(e),this.totalQueued++,this.eventBuffer.length>=this.config.batchSize?this.scheduleFlush(0):this.scheduleFlush(this.config.flushIntervalMs)}scheduleFlush(e){null===this.flushTimer&&(this.flushTimer=setTimeout(()=>{this.flushTimer=null,this.flush().catch(e=>{this.logger.error(`Scheduled flush failed: ${e instanceof Error?e.message:String(e)}`)})},e))}cancelFlushTimer(){null!==this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null)}async submitEvents(e){return await this.httpClient.post("/v1/events",{events:e})}setupPageLifecycleListeners(){"undefined"!=typeof document&&(this.config.flushOnPageHide&&document.addEventListener("visibilitychange",this.handleVisibilityChange),this.config.flushOnPageUnload&&window.addEventListener("beforeunload",this.handleBeforeUnload))}removePageLifecycleListeners(){"undefined"!=typeof document&&(this.config.flushOnPageHide&&document.removeEventListener("visibilitychange",this.handleVisibilityChange),this.config.flushOnPageUnload&&window.removeEventListener("beforeunload",this.handleBeforeUnload))}flushWithBeacon(){if("undefined"==typeof navigator||!navigator.sendBeacon)return;const e=this.eventBuffer.splice(0),t=JSON.stringify({events:e});try{const n=this.getBaseUrl();navigator.sendBeacon(`${n}/v1/events`,t)?(this.totalFlushed+=e.length,this.lastFlushTime=Date.now()):(this.eventBuffer.unshift(...e),this.logger.warn("sendBeacon returned false, events re-buffered"))}catch(t){this.eventBuffer.unshift(...e),this.logger.error(`sendBeacon failed: ${t instanceof Error?t.message:String(t)}`)}}getBaseUrl(){const e=this.httpClient.config;return e?.baseUrl??""}}function BA(e){return 0===(e?.length??0)?"0":e.reduce((e,t)=>o(e).plus(t.quantity).toString(),"0")}function DA(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 OA extends rr{constructor(e,t=!1){super(e,t)}getChannelForCollection(e){return"MUSIC"===(hw(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`,r=await this.http.post(n,e);if(null==r)return null;try{dt(r,"Fetch balances")}catch{return null}if(0===(r.Data?.length??0))return null;const s=r.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 i=io(s),a={quantity:s.quantity,collection:s.collection,category:s.category,tokenId:i};if((s.inUseHolds?.length??0)>0){const e=DA(s.inUseHolds??[],t);e.length>0&&(a.inUseHolds=e,a.inUseQuantity=BA(e))}if((s.lockedHolds?.length??0)>0){const e=DA(s.lockedHolds??[],t);e.length>0&&(a.lockedHolds=e,a.lockedQuantity=BA(e))}return void 0===a.lockedQuantity&&void 0===a.inUseQuantity||(a.availableQuantity=function(e,t="0",n="0"){return o(e).minus(t).minus(n).toString()}(a.quantity,a.lockedQuantity,a.inUseQuantity)),a}catch(e){throw Tt(`Failed to fetch token balance from GalaChain: ${at(e)}`,void 0,ot(e)?e:void 0)}}}function MA(e){return"string"==typeof e?{...iA(e),instance:"0"}:{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey,instance:"0"}}function LA(e){return oo(e)}function UA(e){const t=e[0];return void 0===t?void 0:LA(t.tokenInstanceKey)}class PA extends i.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,r,s){const i=MA(r);return new PA({lockAuthority:t??e,tokenInstances:[{owner:e,quantity:n,tokenInstanceKey:i}],...void 0!==s?.expires&&{expires:s.expires},...void 0!==s?.name&&{name:s.name},uniqueKey:s?.uniqueKey??XE()})}static forGALA(e,t,n,r){return new PA({lockAuthority:t??e,tokenInstances:[{owner:e,quantity:n,tokenInstanceKey:{collection:"GALA",category:"Unit",type:"none",additionalKey:"none",instance:"0"}}],...void 0!==r?.expires&&{expires:r.expires},...void 0!==r?.name&&{name:r.name},uniqueKey:r?.uniqueKey??XE()})}getTokenClassKey(){return UA(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 FA extends i.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,r){const s=MA(n);return new FA({tokenInstances:[{owner:e,quantity:t,tokenInstanceKey:s}],...void 0!==r?.name&&{name:r.name},uniqueKey:r?.uniqueKey??XE()})}static forGALA(e,t,n){return new FA({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??XE()})}getTokenClassKey(){return UA(this.tokenInstances)}toSigningPayload(){return{tokenInstances:this.tokenInstances,...void 0!==this.name&&{name:this.name},uniqueKey:this.uniqueKey}}}function $A(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Kn(t.amount)&&(void 0!==t.tokenId||Kn(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 KA(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Kn(t.amount)&&(void 0!==t.tokenId||Kn(t.tokenName))&&(void 0===t.name||"string"==typeof t.name)}function GA(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every($A)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}function HA(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every(KA)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}var WA,qA;exports.LockErrorType=void 0,(WA=exports.LockErrorType||(exports.LockErrorType={})).TOKEN_NOT_FOUND="TOKEN_NOT_FOUND",WA.INVALID_AMOUNT="INVALID_AMOUNT",WA.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",WA.SIGNATURE_FAILED="SIGNATURE_FAILED",WA.NETWORK_ERROR="NETWORK_ERROR",WA.WALLET_REQUIRED="WALLET_REQUIRED",WA.VALIDATION_ERROR="VALIDATION_ERROR",WA.LOCK_NOT_FOUND="LOCK_NOT_FOUND",WA.LOCK_EXPIRED="LOCK_EXPIRED",WA.INSUFFICIENT_LOCKED_BALANCE="INSUFFICIENT_LOCKED_BALANCE",WA.NOT_LOCK_AUTHORITY="NOT_LOCK_AUTHORITY",WA.LOCK_NAME_MISMATCH="LOCK_NAME_MISMATCH";class zA 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"}(qA||(qA={}));class VA extends Error{constructor(e,t,n){super(e),this.type=t,this.details=n,this.name="TransferError"}}function jA(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 XA(e,t,n,r="[DEBUG] Token resolution (launchpad)"){const s=await t.resolveTokenToVault(e);if(null!==s){const t=BE(s);return n.debug(r,{tokenName:e,vaultAddress:s,tokenInstance:{collection:t.collection,category:t.category,type:t.type,instance:t.instance}}),t}const i={collection:jt(e),category:"Unit",type:"none",additionalKey:"none",instance:"0"};return n.debug("[DEBUG] Token resolution (standard format)",{tokenName:e,tokenInstance:{collection:i.collection,category:i.category,type:i.type}}),i}const YA=100,JA=100;class QA extends rr{constructor(e,t,n,r=!1){super(e,r),this.wallet=t,this.tokenResolver=n,this.nativeSigner=t?new tA(t.privateKey):void 0}async lockTokens(e){if(this.validateLockTokensData(e),!this.wallet||!this.nativeSigner)throw new zA("Wallet required for token lock operations",exports.LockErrorType.WALLET_REQUIRED);return Ji(async()=>{const{ownerAddress:t,tokenInstances:n}=this.createTokenOperationContext(),r=[];let s=t;const i=e.tokens.find(e=>void 0!==e.lockAuthority);void 0!==i?.lockAuthority&&(s=hr(i.lockAuthority));const o=e.tokens.find(e=>void 0!==e.expires),a=e.tokens.find(e=>void 0!==e.name);for(const i of e.tokens){const e=await this.resolveTokenEntry(i);n.push({owner:t,quantity:i.amount,tokenInstanceKey:e}),r.push({tokenClassKey:{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey},quantity:i.amount,lockAuthority:void 0!==i.lockAuthority?hr(i.lockAuthority):s})}const c=new PA({lockAuthority:s,tokenInstances:n,...void 0!==o?.expires&&{expires:o.expires},...void 0!==a?.name&&{name:a.name},uniqueKey:e.uniqueKey??XE()}),l=await this.nativeSigner.signObject("LockToken",c.toSigningPayload()),u=new PA({...c.toSigningPayload(),signedPayload:l}),d=await this.http.post("/api/asset/token-contract/LockToken",u);try{dt(d,"Token lock failed")}catch(e){const t=ht(d);throw new zA(`${at(e)}${t}`,exports.LockErrorType.NETWORK_ERROR)}return this.extractLockResult(d,r)},"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 zA("Wallet required for token unlock operations",exports.LockErrorType.WALLET_REQUIRED);return Ji(async()=>{const{ownerAddress:t,tokenInstances:n}=this.createTokenOperationContext(),r=[],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}),r.push({tokenClassKey:{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey},quantity:s.amount})}const i=new FA({tokenInstances:n,...void 0!==s?.name&&{name:s.name},uniqueKey:e.uniqueKey??XE()}),o=await this.nativeSigner.signObject("UnlockToken",i.toSigningPayload()),a=new FA({...i.toSigningPayload(),signedPayload:o}),c=await this.http.post("/api/asset/token-contract/UnlockToken",a);try{dt(c,"Token unlock failed")}catch(e){const t=ht(c);throw new zA(`${at(e)}${t}`,exports.LockErrorType.NETWORK_ERROR)}return this.extractUnlockResult(c,r)},"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 zA("Must provide either tokenId or tokenName for token identification",exports.LockErrorType.TOKEN_NOT_FOUND);if(void 0!==e.tokenName)try{Xn(e.tokenName,"tokenName")}catch{throw new zA("Invalid token name format",exports.LockErrorType.TOKEN_NOT_FOUND,{tokenName:e.tokenName})}try{_i(ki(e.amount))}catch{throw new zA(kt(t,"a positive number",n).message,exports.LockErrorType.INVALID_AMOUNT,{amount:e.amount})}}validateLockTokensData(e){if(!GA(e))throw new zA("Invalid lock data: missing required fields",exports.LockErrorType.VALIDATION_ERROR);if(e.tokens.length>YA)throw new zA(`Batch size exceeds maximum limit of ${YA} tokens per lock operation`,exports.LockErrorType.VALIDATION_ERROR);for(const t of e.tokens){if(this.validateSharedTokenEntry(t,"lockAmount","Lock amount"),void 0!==t.lockAuthority&&!pr(t.lockAuthority))throw new zA("Invalid lock authority address format",exports.LockErrorType.VALIDATION_ERROR,{lockAuthority:t.lockAuthority});if(void 0!==t.expires)try{Ln(t.expires,"expires")}catch{throw new zA(kt("expires","a positive integer (epoch milliseconds)","Expires").message,exports.LockErrorType.VALIDATION_ERROR)}}}validateUnlockTokensData(e){if(!HA(e))throw new zA("Invalid unlock data: missing required fields",exports.LockErrorType.VALIDATION_ERROR);if(e.tokens.length>JA)throw new zA(`Batch size exceeds maximum limit of ${JA} tokens per unlock operation`,exports.LockErrorType.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 r=e.Data[0];if(void 0===r)return{locked:t};n=r.transactionId??r.txnId??r.TxnId??r.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 r=e.Data[0];if(void 0===r)return{unlocked:t};n=r.transactionId??r.txnId??r.TxnId??r.id??void 0}return{...void 0!==n&&{transactionId:n},unlocked:t}}handleLockError(e,t,n){if(e instanceof zA)return e;let r=t,s=exports.LockErrorType.NETWORK_ERROR;if(ut(e)){const n=e.response?.data;if("object"==typeof n&&null!==n){const e=n.Message;"string"==typeof e&&e.length>0&&(r=`${t}: ${e}`);const i="string"==typeof e?e.toLowerCase():"";i.includes("insufficient")||i.includes("balance")?s=exports.LockErrorType.INSUFFICIENT_BALANCE:i.includes("lock")&&i.includes("not found")?s=exports.LockErrorType.LOCK_NOT_FOUND:i.includes("not found")||i.includes("token")?s=exports.LockErrorType.TOKEN_NOT_FOUND:i.includes("authority")?s=exports.LockErrorType.NOT_LOCK_AUTHORITY:i.includes("expired")&&(s=exports.LockErrorType.LOCK_EXPIRED)}}else ot(e)&&(r=`${t}: ${at(e)}`);return new zA(r,s,jA(n))}async resolveTokenInstance(e){return Ji(async()=>XA(e,this.tokenResolver,this.logger),`Failed to resolve token '${e}'`,this.logger,t=>{if(t instanceof VA)throw new zA(at(t),exports.LockErrorType.TOKEN_NOT_FOUND);throw new zA(`Failed to resolve token '${e}': ${at(t)}`,exports.LockErrorType.TOKEN_NOT_FOUND,{tokenName:e})})}async resolveTokenEntry(e){if(void 0!==e.tokenId){const t=xE(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 zA("Must provide either tokenId or tokenName for token identification",exports.LockErrorType.TOKEN_NOT_FOUND)}createTokenOperationContext(){return{ownerAddress:hr(this.wallet.address),tokenInstances:[]}}}class ZA extends rr{constructor(e,t=!1,n){super(e,t),this.publicAxios=n}async fetchTokenClassFromChain(e){try{const t="string"==typeof e?xE(e):e,n={tokenClasses:[{collection:t.collection,category:t.category,type:t.type,additionalKey:t.additionalKey}]};if(!this.publicAxios)throw St("publicAxios","Public Axios instance");const r=(await this.publicAxios.post("/api/asset/token-contract/FetchTokenClasses",n)).data;if(dt(r,"Failed to fetch token class from GalaChain"),null===r.Data||void 0===r.Data||0===r.Data.length)throw Tt(`Token not found on GalaChain: ${io(t)}`,404);const s=r.Data[0];if(void 0===s)throw Tt(`Token not found on GalaChain: ${io(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 St("tokenClasses","Token classes array");const t={tokenClasses:e};if(!this.publicAxios)throw St("publicAxios","Public Axios instance");const n=(await this.publicAxios.post("/api/asset/token-contract/FetchTokenClassesWithSupply",t)).data;if(dt(n,"Failed to fetch token classes with supply from GalaChain"),!n.Data||0===n.Data.length)throw Tt("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 yt)throw e;if(ut(e)&&404===e.response?.status)throw Tt(t,404,ot(e)?e:void 0);if(ot(e)&&"Error"===e.name&&at(e).includes("status indicates failure"))throw Tt(at(e),400,ot(e)?e:void 0);const r=at(e);if(r.includes("Token not found")){if(e instanceof Error)throw e;throw new Error(r)}throw Tt(`${n}: ${r}`,void 0,ot(e)?e:void 0)}}class eS extends i.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=MA(e.tokenClassKey);return{quantity:e.quantity,tokenInstanceKey:t}});return new eS({tokenInstances:n,uniqueKey:t?.uniqueKey??XE()})}static fromTokenClassKey(e,t,n){return eS.fromTokens([{tokenClassKey:t,quantity:e}],n)}static forGALA(e,t){return new eS({tokenInstances:[{quantity:e,tokenInstanceKey:{collection:"GALA",category:"Unit",type:"none",additionalKey:"none",instance:"0"}}],uniqueKey:t?.uniqueKey??XE()})}getTokenClassKey(){if(0===this.tokenInstances.length)return;const e=this.tokenInstances[0];return void 0!==e?LA(e.tokenInstanceKey):void 0}toSigningPayload(){return{tokenInstances:this.tokenInstances,uniqueKey:this.uniqueKey}}}class tS extends i.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,r,s){let i;if("string"==typeof r){i={...iA(r),instance:"0"}}else i={collection:r.collection,category:r.category,type:r.type,additionalKey:r.additionalKey,instance:"0"};return new tS({from:e,to:t,quantity:n,tokenInstance:i,uniqueKey:s??XE()})}static forGALA(e,t,n,r){return new tS({from:e,to:t,quantity:n,tokenInstance:{collection:"GALA",category:"Unit",type:"none",additionalKey:"none",instance:"0"},uniqueKey:r??XE()})}getTokenClassKey(){return oo(this.tokenInstance)}toSigningPayload(){return{from:this.from,to:this.to,quantity:this.quantity,tokenInstance:this.tokenInstance,uniqueKey:this.uniqueKey}}}function nS(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Kn(t.amount)&&(void 0!==t.tokenId||Kn(t.tokenName))}function rS(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every(nS)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}var sS;exports.BurnErrorType=void 0,(sS=exports.BurnErrorType||(exports.BurnErrorType={})).TOKEN_NOT_FOUND="TOKEN_NOT_FOUND",sS.INVALID_AMOUNT="INVALID_AMOUNT",sS.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",sS.SIGNATURE_FAILED="SIGNATURE_FAILED",sS.NETWORK_ERROR="NETWORK_ERROR",sS.WALLET_REQUIRED="WALLET_REQUIRED",sS.VALIDATION_ERROR="VALIDATION_ERROR";class iS extends Error{constructor(e,t,n){super(e),this.type=t,this.details=n,this.name="BurnError"}}const oS={validateAmount(e){const t=ki(e);try{xi(t,"amount")}catch(t){throw new VA(t.message,qA.INVALID_AMOUNT,{amount:e})}},validateUniqueKey(e){if(!Hn(e)&&Kn(e)){if(e.length>bn.MAX_LENGTH)throw new yt(`Unique key too long. Maximum length: ${bn.MAX_LENGTH}`);if(!bn.PATTERN.test(e))throw new VA('Invalid unique key format. Must start with "galaswap-operation-" or "galaconnect-operation-"',qA.INVALID_AMOUNT,{uniqueKey:e})}}},aS="gala-transfer-successful",cS="token-transfer-successful",lS="token-locked-successfully",uS="token-unlocked-successfully",dS="transfer-successful-no-id",hS=50;class gS extends rr{constructor(e,t,n,r=!1){super(e,r),this.wallet=t,this.tokenResolver=n,this.nativeSigner=t?new tA(t.privateKey):void 0}async transferGala(e){if(this.validateTransferGalaData(e),!this.wallet||!this.nativeSigner)throw new VA("Wallet required for GALA transfer operations",qA.WALLET_REQUIRED);try{const t=hr(e.recipientAddress),n=hr(this.wallet.address),r=tS.forGALA(n,t,e.amount,e.uniqueKey),s=await this.nativeSigner.signObject("TransferToken",r.toSigningPayload()),i=new tS({...r.toSigningPayload(),signedPayload:s}),{data:o,headers:a}=await this.http.postWithMeta("/api/asset/token-contract/TransferToken",i);if(null==o)throw new VA("No response from GalaChain transfer service",qA.NETWORK_ERROR);return this.extractTransferResult(o,a,"gala")}catch(t){throw this.handleTransferError(t,"GALA transfer failed",e)}}async transferToken(e){if(this.validateTransferTokenData(e),!this.wallet||!this.nativeSigner)throw new VA("Wallet required for token transfer operations",qA.WALLET_REQUIRED);try{const t=hr(e.to),n=hr(this.wallet.address);let r;if(null!==e.tokenId&&void 0!==e.tokenId)r=xE(e.tokenId),this.logger.debug("[DEBUG] Using provided tokenId:",e.tokenId),this.logger.debug("[DEBUG] Normalized Token Instance:",{collection:r.collection,category:r.category,type:r.type,instance:r.instance});else{if(null===e.tokenName||void 0===e.tokenName)throw new VA("Must provide either tokenId or tokenName for token identification",qA.TOKEN_NOT_FOUND);r=await this.resolveTokenInstance(e.tokenName)}const s=new tS({from:n,to:t,quantity:e.amount,tokenInstance:r,uniqueKey:e.uniqueKey??XE()}),i=await this.nativeSigner.signObject("TransferToken",s.toSigningPayload()),o=new tS({...s.toSigningPayload(),signedPayload:i}),{data:a,headers:c}=await this.http.postWithMeta("/api/asset/token-contract/TransferToken",o);if(null==a)throw new VA("No response from GalaChain transfer service",qA.NETWORK_ERROR);return this.extractTransferResult(a,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 VA)throw t;throw new VA(`Failed to resolve token class key for '${e}': ${at(t)}`,qA.TOKEN_NOT_FOUND,{tokenName:e})}}async burnTokens(e){if(this.validateBurnTokensData(e),!this.wallet||!this.nativeSigner)throw new iS("Wallet required for token burn operations",exports.BurnErrorType.WALLET_REQUIRED);try{const t=[];for(const n of e.tokens){let e;if(null!==n.tokenId&&void 0!==n.tokenId)e=xE(n.tokenId),this.logger.debug("[DEBUG] Using provided tokenId:",n.tokenId);else{if(null===n.tokenName||void 0===n.tokenName)throw new iS("Must provide either tokenId or tokenName for token identification",exports.BurnErrorType.TOKEN_NOT_FOUND);e=await this.resolveTokenInstance(n.tokenName)}t.push({quantity:n.amount,tokenInstanceKey:e})}const n=new eS({tokenInstances:t,uniqueKey:e.uniqueKey??XE()}),r=await this.nativeSigner.signObject("BurnTokens",n.toSigningPayload()),s=new eS({...n.toSigningPayload(),signedPayload:r}),i=await this.http.post("/api/asset/token-contract/BurnTokens",s);if(null==i)throw new iS("No response from GalaChain burn service",exports.BurnErrorType.NETWORK_ERROR);try{dt(i,"Token burn operation")}catch(e){throw new bt(at(e),500)}return this.extractBurnResult(i)}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 Kn(t.recipientAddress)&&Kn(t.amount)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)}(e))throw new yt("Invalid GALA transfer data: missing required fields");if(!pr(e.recipientAddress))throw new VA("Invalid recipient address format",qA.INVALID_RECIPIENT,{recipientAddress:e.recipientAddress});oS.validateAmount(e.amount),oS.validateUniqueKey(e.uniqueKey)}validateTransferTokenData(e){if(!function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Kn(t.to)&&Kn(t.amount)&&(void 0!==t.tokenId||Kn(t.tokenName))&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)}(e))throw new yt("Invalid token transfer data: missing required fields");if(!pr(e.to))throw new VA("Invalid recipient address format",qA.INVALID_RECIPIENT,{recipientAddress:e.to});if(!(null!==e.tokenId&&void 0!==e.tokenId||null!==e.tokenName&&void 0!==e.tokenName))throw new VA("Must provide either tokenId or tokenName for token identification",qA.TOKEN_NOT_FOUND);if(null!==e.tokenName&&void 0!==e.tokenName)try{Xn(e.tokenName,"tokenName")}catch{throw new VA("Invalid token name format",qA.TOKEN_NOT_FOUND,{tokenName:e.tokenName})}oS.validateAmount(e.amount),oS.validateUniqueKey(e.uniqueKey)}validateBurnTokensData(e){if(!rS(e))throw new iS("Invalid burn data: missing required fields",exports.BurnErrorType.VALIDATION_ERROR);if(e.tokens.length>hS)throw new iS(`Batch size exceeds maximum limit of ${hS} tokens per burn operation`,exports.BurnErrorType.VALIDATION_ERROR);for(const t of e.tokens){if(!(null!==t.tokenId&&void 0!==t.tokenId||null!==t.tokenName&&void 0!==t.tokenName))throw new iS("Must provide either tokenId or tokenName for token identification",exports.BurnErrorType.TOKEN_NOT_FOUND);const e=ki(t.amount);try{_i(e)}catch{throw new iS("Burn amount must be a positive number",exports.BurnErrorType.INVALID_AMOUNT,{amount:t.amount})}}}async resolveTokenInstance(e){try{return await XA(e,this.tokenResolver,this.logger,`[DEBUG] Token resolution for '${e}' (launchpad):`)}catch(t){if(t instanceof VA)throw t;throw new VA(`Failed to resolve token '${e}': ${at(t)}`,qA.TOKEN_NOT_FOUND,{tokenName:e})}}extractTransferResult(e,t,n){const r=this.readHeaderValue(t,"x-transaction-id"),s=this.readBlockNumberHeader(t),i=null!=e&&"object"==typeof e&&"Status"in e;i&&dt(e,"Extract transaction ID");const o=i&&"Data"in e;if(void 0!==r&&r.length>0)return{transactionId:r,...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(o){const t=e;if(Array.isArray(t.Data)){for(const e of t.Data)if(null!=e&&"object"==typeof e){const t=e;for(const e of["transactionId","txnId","TxnId","id","txId"]){const n=t[e];if("string"==typeof n&&n.length>0)return{transactionId:n,...void 0!==s?{blockNumber:s}:{}}}}let e=dS;if(t.Data.length>0)switch(n){case"gala":e=aS;break;case"token":e=cS;break;case"lock":e=lS;break;case"unlock":e=uS}return{transactionId:e,...void 0!==s?{blockNumber:s}:{}}}}}throw new VA("Operation succeeded but transaction ID could not be extracted (missing x-transaction-id header and body fields)",qA.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 r=e.Data[0];if(void 0===r)return{burned:t};n=r.transactionId??r.txnId??r.TxnId??r.id??void 0}return{...void 0!==n&&{transactionId:n},burned:t}}handleTransferError(e,t,n){if(e instanceof VA)return e;if(e instanceof yt)return new VA(at(e),qA.INVALID_AMOUNT);if(ut(e)&&e.response){const t=e.response.status,r=e.response.data;if(400===t){const e=r?.message;return new VA(("string"==typeof e?e:void 0)??"Invalid transfer request",qA.INVALID_AMOUNT)}if(403===t)return new VA("Insufficient balance for transfer",qA.INSUFFICIENT_BALANCE);if(404===t){const e={};return"tokenName"in n&&(e.tokenName=n.tokenName),new VA("Token not found",qA.TOKEN_NOT_FOUND,e)}}if("object"==typeof e&&null!==e&&"code"in e&&("ECONNABORTED"===lt(e)||"ETIMEDOUT"===lt(e)))return new VA("Transfer request timed out",qA.NETWORK_ERROR);const r=""!==at(e)?at(e):t;return new VA(r,qA.NETWORK_ERROR)}handleBurnError(e,t,n){if(e instanceof iS)return e;let r=t,s=exports.BurnErrorType.NETWORK_ERROR;if(ut(e)){const n=e.response?.data;if("object"==typeof n){const e=n.Message;if("string"==typeof e&&e.length>0){r=`${t}: ${e}`;const n=e.toLowerCase();n.includes("insufficient")||n.includes("balance")?s=exports.BurnErrorType.INSUFFICIENT_BALANCE:(n.includes("not found")||n.includes("token"))&&(s=exports.BurnErrorType.TOKEN_NOT_FOUND)}}}else ot(e)&&(r=`${t}: ${at(e)}`);return new iS(r,s,jA(n))}}class fS extends rr{constructor(e,t,n,r=!1,s){super(e,r),this.balanceService=new OA(e,r),this.tokenService=new ZA(e,r,s),this.lockService=new QA(e,t,n,r),this.transferService=new gS(e,t,n,r)}async fetchPoolDetails(e){this.validateFetchPoolDetailsData(e);const t=await this.http.post("/api/asset/launchpad-contract/FetchSaleDetails",e);Qi(()=>dt(t,"Failed to fetch pool details"),"Failed to fetch pool details",this.logger,e=>{throw Tt(at(e),500)});const n=t.Data.reverseBondingCurveConfiguration,r=n?.minFeePortion??"0",s=n?.maxFeePortion??"0",i=!Ci(r)||!Ci(s),o=t.Data;return o.reverseBondingCurveMinFeePortion=r,o.reverseBondingCurveMaxFeePortion=s,o.hasReverseBondingCurveFee=i,o.isGraduated="Finished"===t.Data.saleStatus,delete o.reverseBondingCurveConfiguration,t}async fetchLaunchTokenFee(){const e=await this.http.post("/api/asset/launchpad-contract/FetchLaunchpadFeeAmount",{});return Qi(()=>dt(e,"Failed to fetch launch token fee"),"Failed to fetch launch token fee",this.logger,e=>{throw Tt(at(e),500)}),e.Data.feeAmount}validateFetchPoolDetailsData(e){if(!wi(e))throw St("data","Fetch pool details data");if("string"!=typeof e.vaultAddress||""===e.vaultAddress)throw St("vaultAddress","Vault address");if(!e.vaultAddress.startsWith("service|Token$Unit$"))throw new yt("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 pS{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 mS extends Error{constructor(e,t,n){super(t),this.name="GdexStreamError",this.code=e,void 0!==n&&(this.data=n)}}class yS extends sr{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??so("prod").gdexWebSocketUrl,this.requestTimeoutMs=e.requestTimeoutMs??15e3,this.reconnectionManager=new pS({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,r={jsonrpc:"2.0",id:n,method:e};return void 0!==t&&(r.params=t),new Promise((t,s)=>{const i=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:i});try{this.socket?.send(JSON.stringify(r))}catch(e){clearTimeout(i),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 r=new this.webSocketConstructor(this.url,"gdex.jsonrpc.v1");this.socket=r,r.onopen=()=>{this.socket===r&&(n=!0,this.connectPromise=void 0,this.reconnecting||this.reconnectionManager.reset(),this.logger.info("Connected to GDEX stream"),e())},r.onmessage=e=>this.handleMessage(e.data),r.onerror=()=>{n||t(new Error(`Failed to connect to GDEX stream at ${this.url}`))},r.onclose=e=>{this.socket===r&&(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,r="string"==typeof t.error.message?t.error.message:"GDEX request failed";e.reject(new mS(n,r,t.error.data))}else e.resolve(t.result);return}if("gdex_subscription"!==t.method||!this.isRecord(t.params))return;const n=t.params.subscription,r=t.params.result;if("string"!=typeof n||!this.isRecord(r))return;const s=this.subscriptionsByServerId.get(n);if(s?.active)try{s.callback(r)}catch(e){this.logger.error("GDEX subscription callback failed",e)}}async subscribe(e,t,n){const r={channel:e,...n},s=await this.request("gdex_subscribe",r);let i;const o={subscriptionId:s.subscriptionId,unsubscribe:async()=>this.unsubscribe(i)};return i={serverId:s.subscriptionId,params:r,callback:t,handle:o,active:!0},this.activeSubscriptions.add(i),this.subscriptionsByServerId.set(i.serverId,i),o}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 mS)||-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 bS(e,t="image",n){const r=new FormData;if("undefined"!=typeof File&&e instanceof File)r.append(t,e);else{if(!Buffer.isBuffer(e))throw kt("file","a File object (browser) or Buffer (Node.js)");{const s=new Blob([e],{type:"image/png"});r.append(t,s,n)}}return r}class vS extends rr{constructor(e,t,n=!1){super(e,n,t)}async uploadImageByTokenName(e){const{tokenName:t,options:n}=e;Ui(t);const r=`${t}.png`;Oi(n.file,r,"image/png");try{const e=`${n.tokenName??t}.png`,r=bS(n.file,"image",e),s=await Gt(()=>this.http.request({method:"POST",url:`${b.UPLOAD_IMAGE}?tokenName=${encodeURIComponent(n.tokenName??t)}`,data:r,headers:this.getJwtHeaders()}),{errorContext:"Image upload failed"});return"string"==typeof s?s:""}catch(e){if(e instanceof vt)throw e;if(ot(e)&&at(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}}}function wS(e,t){if(void 0!==e){if(!Kn(e))throw Bt("tokenName","string");if(e.length>cn.MAX_LENGTH)throw new yt(`tokenName must be at most ${cn.MAX_LENGTH} characters`,"tokenName",mt.TOO_LONG)}if(void 0!==t){if(!Kn(t))throw Bt("userAddress","string");if(t.length>gn.MAX_LENGTH)throw new yt(`userAddress must be at most ${gn.MAX_LENGTH} characters`,"userAddress",mt.TOO_LONG)}}const ES={CHAT_MESSAGE:"CHAT_MESSAGE",COMMENT:"COMMENT"},AS={PAGINATION:{MAX_LIMIT:dn.MAX_LIMIT},CONTENT:{CHAT_MAX_LENGTH:fn.CHAT_MESSAGES_V1.MAX_LENGTH,COMMENT_MAX_LENGTH:fn.COMMENTS_V1.MAX_LENGTH}};function SS(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 yt("At least one config option must be provided (messagesEnabled, commentsEnabled, streamingEnabled, nextLiveStreamAt, streamLanguage, or social URLs)","options",mt.REQUIRED);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 yt("nextLiveStreamAt must be a valid ISO date string","nextLiveStreamAt",mt.INVALID_FORMAT)}}function kS(e,t){if(null==e)return[];if(Array.isArray(e))return e;const n=e[t];return Array.isArray(n)?n:[]}class TS extends rr{constructor(e,t,n=!1){super(e,n,t)}buildPoolFilters(e){return{...!Hn(e.search)&&{search:e.search},...!Hn(e.tokenName)&&{tokenName:e.tokenName},...!Hn(e.type)&&{type:e.type},...!Hn(e.hasUpcomingShows)&&{hasUpcomingShows:e.hasUpcomingShows},...!Hn(e.language)&&{language:e.language},...!Hn(e.recentlyStreamed)&&{recentlyStreamed:e.recentlyStreamed},...!Hn(e.hasRecordings)&&{hasRecordings:e.hasRecordings},...!Hn(e.streamStatus)&&{streamStatus:e.streamStatus}}}async fetchSinglePage(e){const t=Math.min(e.pageSize,20),n=e.cursor,r={pageSize:String(t)};void 0!==n&&(r.cursor=n),Hn(e.type)||(r.type=e.type),Hn(e.tokenName)||(r.tokenName=e.tokenName),Hn(e.search)||(r.search=e.search),Hn(e.hasUpcomingShows)||(r.hasUpcomingShows=e.hasUpcomingShows.toString()),Hn(e.language)||(r.language=e.language),Hn(e.recentlyStreamed)||(r.recentlyStreamed=e.recentlyStreamed.toString()),Hn(e.hasRecordings)||(r.hasRecordings=e.hasRecordings.toString()),Hn(e.streamStatus)||(r.streamStatus=e.streamStatus);const s=Ai(r),i=$t(await Wt(()=>this.http.get(b.FETCH_POOLS,s),{errorContext:"Failed to fetch pools"})),o=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}(i),a={hasNextPage:i.hasNextPage??i.pageInfo?.hasNextPage??!1},c=i.count??i.total;void 0!==c&&(a.totalCount=c);const l=i.nextCursor??i.pageInfo?.endCursor;null!=l&&(a.nextCursor=l);const u=i.prevCursor??i.pageInfo?.startCursor;null!=u&&(a.prevCursor=u);const d=i.hasPrevPage??i.pageInfo?.hasPreviousPage;return void 0!==d&&(a.hasPrevPage=d),{items:o,pageInfo:a}}async fetchPools(e){const t=e?.cursor,n=e?.pageSize??Qw.DEFAULT_LIMIT;Kn(e?.tokenName)&&Ui(e.tokenName);const r=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,i={...this.buildPoolFilters({search:e?.search,tokenName:e?.tokenName,type:r,hasUpcomingShows:e?.hasUpcomingShows,language:e?.language,recentlyStreamed:e?.recentlyStreamed,hasRecordings:e?.hasRecordings,streamStatus:s}),pageSize:n,...void 0!==t&&{cursor:t}},o=await this.fetchSinglePage(i);return{items:o.items,pageInfo:o.pageInfo}}async fetchAllPools(e){const t=[];let n;const r=Qw.BACKEND_MAX_PAGE_SIZE;for(;;){const s={...e,pageSize:r,...void 0!==n&&{cursor:n}},i=await this.fetchPools(s);if(t.push(...i.items),0===i.items.length)break;if(!i.pageInfo.hasNextPage)break;n=i.pageInfo.nextCursor}return{items:t,pageInfo:{hasNextPage:!1,totalCount:t.length}}}async checkPool(e){!function(e){const t=Zs(e);!t.success&&t.errors&&Li(t.errors,"options")}(e),Kn(e.tokenName)&&Ui(e.tokenName);try{const t=await this.http.post(b.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===Kn(e.symbol)){return!n.symbolAvailable}if(!0===Kn(e.tokenName)){return!n.nameAvailable}return!1}catch(e){const t=String(e),n=e,r="string"==typeof n.message?n.message:"";if(t.includes("404")||t.includes("Pool not found")||r.includes("404")||r.includes("Pool not found"))return!1;const s="number"==typeof n.statusCode?n.statusCode:null;if(404===s)return!1;if(t.includes("400")||t.includes("Missing required pool identifier")||r.includes("400")||r.includes("Missing required pool identifier"))return!1;if(400===s&&r.includes("Missing required pool identifier"))return!1;throw e}}async isTokenNameAvailable(e){try{return!await this.checkPool({tokenName:e})}catch{return!1}}async isTokenSymbolAvailable(e){try{return!await this.checkPool({symbol:e})}catch{return!1}}async fetchVolumeData(e){if(!function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return pi(t,"tokenName")&&yi(t,"from")&&yi(t,"to")&&yi(t,"resolution")}(e))throw new yt("Invalid options provided. Expected { tokenName: string, from?: number, to?: number, resolution?: number }","options","INVALID_OPTIONS");const{tokenName:t,from:n,to:r,resolution:s}=e;if(Ui(t),null==n||null==r||null==s)throw new yt("Graph options (from, to, resolution) are required","options","MISSING_GRAPH_OPTIONS");const i={tokenName:t,from:n,to:r,resolution:s};Pi(i);const o=Ai(i);return{dataPoints:await Gt(()=>this.http.get(b.CHART,o),{errorContext:"Failed to fetch graph data"})}}async fetchTokenDistribution(e){if(""===e||null==e)throw St("tokenName","Token name");let t;Ui(e);try{t=await Wt(()=>this.http.get(`${b.GET_TOKEN_DISTRIBUTION}?tokenName=${e}`),{errorContext:"Failed to fetch token distribution"})}catch(t){if(ut(t)&&500===t.response?.status)throw Tt(`Token distribution data temporarily unavailable for ${e}. This is a backend issue - please try again later.`,500);throw t}return Ki($t(t),t.status,e=>e.toFixed())}async fetchUserHolderContext(e,t){if(""===e||null==e)throw St("tokenName","Token name");if(""===t||null==t)throw St("userAddress","User address");return Ui(e),Gt(()=>this.http.get(`${b.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");Ui(e);try{const t=b.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&&Ui(e.tokenName);try{const t=await this.http.post(b.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(!Kn(e))throw St("tokenName","Token name");Ui(e);const t=b.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 St("tokenName","Token name");Ui(e),SS(t);const n=b.UPDATE_TOKEN_CONFIG.replace(":tokenName",e.toLowerCase().trim()),r={};void 0!==t.messagesEnabled&&(r.messagesEnabled=t.messagesEnabled),void 0!==t.commentsEnabled&&(r.commentsEnabled=t.commentsEnabled),void 0!==t.streamingEnabled&&(r.streamingEnabled=t.streamingEnabled),void 0!==t.nextLiveStreamAt&&(r.nextLiveStreamAt=t.nextLiveStreamAt),void 0!==t.streamLanguage&&(r.streamLanguage=t.streamLanguage),void 0!==t.websiteUrl&&(r.websiteUrl=t.websiteUrl),void 0!==t.telegramUrl&&(r.telegramUrl=t.telegramUrl),void 0!==t.twitterUrl&&(r.twitterUrl=t.twitterUrl),void 0!==t.instagramUrl&&(r.instagramUrl=t.instagramUrl),void 0!==t.facebookUrl&&(r.facebookUrl=t.facebookUrl),void 0!==t.redditUrl&&(r.redditUrl=t.redditUrl),void 0!==t.tiktokUrl&&(r.tiktokUrl=t.tiktokUrl),await this.http.patch(n,r,this.getJwtHeaders())}}const IS={PAGINATION:dn,TOKEN_NAME:cn,USER_ADDRESS:gn};function CS(e){if(void 0!==e.tokenName){if(!Kn(e.tokenName))throw Bt("tokenName","a non-empty string",typeof e.tokenName);if(e.tokenName.length>IS.TOKEN_NAME.MAX_LENGTH)throw Rt("tokenName",IS.TOKEN_NAME.MAX_LENGTH,e.tokenName.length)}if(void 0!==e.userAddress){if(!Kn(e.userAddress))throw Bt("userAddress","a non-empty string",typeof e.userAddress);if(e.userAddress.length>IS.USER_ADDRESS.MAX_LENGTH)throw Rt("userAddress",IS.USER_ADDRESS.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 Rt("search",256,e.search.length)}if(Wn(0,void 0,IS.PAGINATION.MAX_LIMIT,e.pageSize),void 0!==e.txnType&&"BUY"!==e.txnType&&"SELL"!==e.txnType)throw kt("txnType",'"BUY" or "SELL"');if(void 0!==e.startDate){if(!Kn(e.startDate))throw Bt("startDate","a non-empty string",typeof e.startDate);if(isNaN(Date.parse(e.startDate)))throw kt("startDate","a valid ISO 8601 date")}if(void 0!==e.endDate){if(!Kn(e.endDate))throw Bt("endDate","a non-empty string",typeof e.endDate);if(isNaN(Date.parse(e.endDate)))throw kt("endDate","a valid ISO 8601 date")}if(void 0!==e.minAmount)try{On(e.minAmount,0,Number.MAX_SAFE_INTEGER,"minAmount")}catch{throw kt("minAmount","a non-negative number")}if(void 0!==e.maxAmount)try{On(e.maxAmount,0,Number.MAX_SAFE_INTEGER,"maxAmount")}catch{throw kt("maxAmount","a non-negative number")}void 0!==e.minAmount&&void 0!==e.maxAmount&&function(e,t,n="range"){const r="number"==typeof e?e:Number(e),s="number"==typeof t?t:Number(t);if(isNaN(r)||isNaN(s))throw Bt(n,"numeric values",void 0,n);if(r>s)throw new yt(`Minimum value (${r}) must be less than or equal to maximum value (${s}) for ${n}`,n,mt.INVALID_RANGE)}(e.minAmount,e.maxAmount,"amountRange")}class NS extends rr{constructor(e,t=!1){super(e,t)}async fetchTrades(e){if(!function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return pi(t,"tokenName")&&(void 0===t.tradeType||"buy"===t.tradeType||"sell"===t.tradeType)&&mi(t,"userAddress")&&yi(t,"offset")&&yi(t,"pageSize")&&yi(t,"page")&&yi(t,"limit")}(e))throw new yt("Invalid options provided. Expected { tokenName: string, tradeType?: string, userAddress?: string, cursor?: string, pageSize?: number, startDate?: Date, endDate?: Date, sortOrder?: string }","options","INVALID_OPTIONS");const{tokenName:t,cursor:n,pageSize:r=Qw.DEFAULT_LIMIT}=e;if(!Kn(t))throw St("tokenName","Token name");const s={pageSize:String(Math.min(r,un))};void 0!==n&&(s.cursor=n);const i={...s};i.tokenName=t;const o=await this.http.get(b.GET_TRADES,i);if(null==o)throw new yt("No response from trade service","response","NO_RESPONSE");const a=$t(o),c=kS(a,"trades"),l=a?.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=Vt(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?Zw(e.pageSize,1,IS.PAGINATION.MAX_LIMIT):IS.PAGINATION.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){CS(e);const t=this.buildTradesQueryParams(e);return Gt(()=>this.http.get(Pe,t),{errorContext:"Failed to fetch trades"})}}function _S(e){return!!Kn(e)&&hn.PATTERN.test(e)}function xS(e,t,n=1){if(null==e||""===e)return null;if("string"!=typeof e)return null;const r=e.trim();return r.length<n?null:r}function RS(e){if(""===e||"string"!=typeof e)return!1;const t=e.startsWith("0x")?e.slice(2):e;return/^[0-9a-fA-F]{40}$/.test(t)}function BS(e){return e.startsWith("0x")?e.slice(2):e}qn({BOTH:"both",HELD:"held",CREATED:"created"});class DS extends rr{constructor(e,t,n=!1){super(e,n,t)}async fetchProfile(e){const t=e??this.http.getAddress();if(""===t||null==t||!_S(t))throw kt("address","eth|[40-hex-chars] or client|[identifier]","Address");const n=null==e,r=n?b.GET_CURRENT_USER:b.GET_PROFILE.replace(":address",t),s=await this.http.get(r,void 0,n?this.getJwtHeaders():void 0);if(null==s)throw new yt("No response from user service","response","NO_RESPONSE");return s}async updateProfile(e){this.validateUpdateProfileData(e);let t=e.profileImage;if(!Kn(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(b.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 yt("Wallet address not available - wallet not configured","address","NO_WALLET");try{const n=`profile-image-${t}.png`,r=bS(e.file,"image",n),s=await Gt(()=>this.http.request({method:"POST",url:`${b.UPLOAD_IMAGE}?tokenName=${encodeURIComponent(t)}`,data:r,headers:this.getJwtHeaders()}),{errorContext:"Image upload failed"});return"string"==typeof s?s:""}catch(e){if(e instanceof yt||e instanceof vt)throw e;throw new yt(`Profile image upload failed: ${at(e)}`,"file","UPLOAD_FAILED")}}async fetchTokenList(e){if(void 0!==e.status&&"created"!==e.type)throw new yt("status filters only apply when type=created","status","INVALID_FILTER");const t=e.tokenName,n={...e},r="created"===e.type;r&&(delete n.tokenName,void 0!==t&&void 0===n.search&&(n.search=t));const s=await this.buildFetchRequest(b.GET_TOKEN_LIST,n,{includeType:!0,requestType:e.type??"both",responseKey:r?"launches":"token",errorMessage:"Failed to fetch token list"});return r&&void 0!==t?{...s,tokens:s.tokens.filter(e=>e.tokenName===t||e.name===t)}:s}async fetchTokensHeld(e){if(void 0!==e.type&&"held"!==e.type)throw new yt("fetchTokensHeld only supports type=held","type","INVALID_TYPE");if(void 0!==e.status)throw new yt("status filters only apply when type=created","status","INVALID_FILTER");return this.buildFetchRequest(b.GET_TOKENS_HELD,e,{includeType:!0,requestType:"held",responseKey:"token",errorMessage:"Failed to fetch tokens held"})}async fetchTokensCreated(e){const{cursor:t,pageSize:n,search:r,tokenName:s,status:i}=e??{};if(void 0!==e?.type&&"created"!==e.type)throw new yt("fetchTokensCreated only supports type=created","type","INVALID_TYPE");const o=e?.address??this.http.getAddress();if(null==o||""===o)throw new yt("Wallet address not available - wallet not configured","address","NO_WALLET");const a={type:"created",address:o,pageSize:n??Qw.DEFAULT_LIMIT};return void 0!==t&&(a.cursor=t),void 0!==r&&(a.search=r),void 0!==s&&void 0===r&&(a.search=s),void 0!==s&&(a.tokenName=s),void 0!==i&&(a.status=i),this.fetchTokenList(a)}async getManagedTokens(e={}){const t=nE({pageSize:e.pageSize??Qw.DEFAULT_LIMIT,...void 0!==e.cursor&&{cursor:e.cursor}},un);return Gt(()=>this.http.get(b.GET_MANAGED_TOKENS,t,this.getJwtHeaders()),{errorContext:"Failed to fetch managed tokens"})}async buildFetchRequest(e,t,n){this.validateGetTokenListOptions(t);const r=nE({pageSize:t.pageSize??Qw.DEFAULT_LIMIT,...void 0!==t.cursor&&{cursor:t.cursor}},un);rE(r,t,["address","search","tokenName","status"]),n.includeType&&!e.includes("?type=")&&(r.type=n.requestType);let s=e;const i=t.address??this.http.getAddress();if(e.includes(":address")){if(0===i.length)throw St("address","User address");s=e.replace(":address",i),delete r.address}const o=$t(await Wt(()=>this.http.get(s,r),{errorContext:n.errorMessage})),a=kS(o,n.responseKey).map(e=>{const t="string"==typeof e.tokenName?e.tokenName:"",r="string"==typeof e.name?e.name:t,s="string"==typeof e.createdAt?e.createdAt:"",o=e.metadata,a={...e};return delete a.metadata,{...a,id:"string"==typeof e.id?e.id:t,name:r,symbol:"string"==typeof e.symbol?e.symbol:"",type:n.requestType,address:i,balance:"string"==typeof e.balance?e.balance:"string"==typeof e.quantity?e.quantity:"0",decimals:"number"==typeof e.decimals?e.decimals:0,...null!==o&&"object"==typeof o?{metadata:o}:{},createdAt:s,updatedAt:"string"==typeof e.updatedAt?e.updatedAt:s}}),c={hasNextPage:o.hasNextPage??!1},l=o.pageInfo,u=o.count??o.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!==u&&(c.totalCount=u),void 0!==o.nextCursor&&(c.nextCursor=o.nextCursor),void 0!==o.prevCursor&&(c.prevCursor=o.prevCursor),void 0!==o.hasPrevPage&&(c.hasPrevPage=o.hasPrevPage);const d={tokens:a,pageInfo:c};return void 0!==u&&(d.total=u),d}validateGetTokenListOptions(e){const t=e.pageSize??Qw.DEFAULT_LIMIT;if(t<1||t>un)throw new yt(`pageSize must be between 1 and ${un}`,"pageSize","OUT_OF_RANGE");if(void 0!==e.address&&!_S(e.address))throw kt("address","eth|[40-hex-chars] or client|[identifier]","Address");const n=xS(e.search);if(null!==n&&!(Kn(r=n)&&r.length>=An&&r.length<=Sn))throw _t("search",An,Sn,n.length,"Search query");var r;const s=xS(e.tokenName);if(null!==s&&!(Kn(i=s)&&i.length>=cn.MIN_LENGTH&&i.length<=cn.MAX_LENGTH))throw _t("tokenName",cn.MIN_LENGTH,cn.MAX_LENGTH,s.length,"Token name");var i}validateUpdateProfileData(e){if(!_S(e.address))throw kt("address","eth|[40-hex-chars] or client|[identifier]","Address");if(t=e.fullName,!(Kn(t)&&t.length>=kn.FULL_NAME.MIN_LENGTH&&t.length<=kn.FULL_NAME.MAX_LENGTH&&kn.FULL_NAME.ALPHABETS_ONLY_PATTERN.test(t)))throw _t("fullName",kn.FULL_NAME.MIN_LENGTH,kn.FULL_NAME.MAX_LENGTH,e.fullName.length,"Full name");var t}validateUploadProfileImageOptions(e){if(void 0!==e.address&&!_S(e.address))throw kt("address","eth|[40-hex-chars] or client|[identifier]","Address")}}class OS{constructor(e,t,n=!1){this.http=e,this.poolService=new TS(e,t,n),this.tradeService=new NS(e,n),this.userService=new DS(e,t,n),this.imageService=new vS(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 Ui(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 MS extends iE{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}validateContent(e,t){if(!Kn(e))throw St("content","Message content");if(0===e.trim().length)throw St("content","Message content");Mn(e,t===ES.CHAT_MESSAGE?fn.CHAT_MESSAGES_V1.MAX_LENGTH:fn.COMMENTS_V1.MAX_LENGTH,"content")}validateMessageId(e){if(!Kn(e))throw St("id","Message ID");if(e.length<10||e.length>64)throw kt("id","valid message ID format","Message ID")}validateMessageType(e){if(e!==ES.CHAT_MESSAGE&&e!==ES.COMMENT)throw new yt(`type must be one of: ${Object.values(ES).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,an);const r={};void 0!==e.cursor&&(r.cursor=e.cursor),r.pageSize=e.pageSize??Qw.DEFAULT_LIMIT;const s=nE(r,dn.MAX_LIMIT),i={};void 0!==s.pageSize&&(i.pageSize=s.pageSize),void 0!==s.cursor&&(i.cursor=s.cursor),t&&(i.type=e.type.toUpperCase()),n&&(i.tokenName=Vt(e.tokenName)),void 0!==e.userAddress&&""!==e.userAddress&&(i.userAddress=e.userAddress),void 0!==e.search&&""!==e.search&&(i.search=e.search);const o=await this.http.get(Fe.GET_MESSAGES,i),a=this.extractData(o);return{messages:a.messages,pageInfo:a.pageInfo}}async createMessage(e){this.validateMessageType(e.type),this.validateTokenName(e.tokenName,an),this.validateContent(e.content,e.type);const t={type:e.type,tokenName:Vt(e.tokenName),content:e.content.trim()},n=await this.http.post(Fe.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(Fe.UPDATE_MESSAGE,e),r={content:t.content.trim()},s=await this.http.put(n,r,this.getJwtHeaders());return{message:this.extractData(s)}}async deleteMessage(e){this.validateMessageId(e);const t=this.buildEndpointWithId(Fe.DELETE_MESSAGE,e);return await this.http.delete(t,void 0,this.getDualAuthHeaders()),{success:!0}}async getPinnedMessage(e){this.validateTokenName(e,an);const t=await this.http.get(Fe.GET_PINNED,{tokenName:Vt(e)});return{message:this.extractData(t)}}async pinMessage(e){this.validateMessageId(e);const t=Fe.PIN_MESSAGE.replace(":id",e);return await this.http.post(t,{},this.getDualAuthHeaders()),{success:!0}}async unpinMessage(e){this.validateMessageId(e);const t=Fe.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(Fe.GET_MESSAGE_STATS,void 0,this.getDualAuthHeaders());return this.extractData(e)}}const LS={MODERATOR:"MODERATOR",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MANAGER:"MANAGER"},US=zn(LS),PS={TOKEN:"TOKEN",ALL_OWNER_TOKENS:"ALL_OWNER_TOKENS"},FS=zn(PS),$S={PENDING:"PENDING",CLAIMED:"CLAIMED",REVOKED:"REVOKED",EXPIRED:"EXPIRED"},KS=zn($S);function GS(e){return US.includes(e)}function HS(e){return KS.includes(e)}function WS(e){return vn.PATTERN.test(e)}const qS=Yn([{field:"id",type:"number"},{field:"inviteScope",type:"string"},{field:"tokenName",type:"string",nullable:!0},{field:"role",type:"string"},{field:"inviteCode",type:"string"},{field:"inviteUrl",type:"string"},{field:"status",type:"string"},{field:"createdAt",type:"string"}]),zS=Yn([{field:"tokenName",type:"string"},{field:"tokenSymbol",type:"string"},{field:"role",type:"string"},{field:"inviteScope",type:"string"},{field:"creatorAddress",type:"string"},{field:"claimedAt",type:"string"}]),VS=Yn([{field:"inviteScope",type:"string"},{field:"tokenName",type:"string",nullable:!0},{field:"tokenSymbol",type:"string",nullable:!0},{field:"role",type:"string"},{field:"status",type:"string"},{field:"invitedBy",type:"string"}]);function jS(e){return FS.includes(e)}class XS extends iE{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}validateRole(e){if(!Kn(e))throw St("role","Role");if(!GS(e))throw kt("role",`one of: ${US.join(", ")}`,"Role")}validateInviteCodeFormat(e){if(!Kn(e))throw St("inviteCode","Invite code");if(!WS(e))throw kt("inviteCode","valid invite code format","Invite code")}validateInviteScope(e){if(void 0!==e&&!jS(e))throw new yt(`Invalid invite scope. Must be one of: ${FS.join(", ")}`,"inviteScope","INVALID_VALUE")}async createInvite(e){this.validateInviteScope(e.inviteScope);const t=e.inviteScope??PS.TOKEN;if(t===PS.TOKEN){if(void 0===e.tokenName||""===e.tokenName)throw new yt("Token name is required for TOKEN scope invites","tokenName","REQUIRED");this.validateTokenName(e.tokenName,on)}else if(t===PS.ALL_OWNER_TOKENS&&e.tokenName)throw new yt("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",fn.DESCRIPTION.MAX_LENGTH),this.validateOptionalDate(e.expiresAt,"expiresAt","Expiration date");const n=te,r={inviteScope:t,role:e.role};t===PS.TOKEN&&null!==e.tokenName&&void 0!==e.tokenName&&""!==e.tokenName&&(r.tokenName=Vt(e.tokenName)),void 0!==e.description&&(r.description=e.description),void 0!==e.expiresAt&&(r.expiresAt=e.expiresAt);const s=await this.http.post(n,r,this.getMultiAuthHeaders());return{invite:this.extractData(s)}}async listInvites(e){void 0!==e.tokenName&&""!==e.tokenName&&this.validateTokenName(e.tokenName,on),this.validateStatusFilter(e.status,$S);const t=se,n={...this.buildPaginationParams(e,dn.MAX_LIMIT)};void 0!==e.tokenName&&""!==e.tokenName&&(n.tokenName=Vt(e.tokenName)),void 0!==e.status&&(n.status=e.status);const r=await this.http.get(t,n,this.getMultiAuthHeaders()),s=this.extractData(r);return{items:s.invites,pageInfo:s.pageInfo}}async revokeInvite(e){this.validatePositiveInteger(e,"inviteId","Invite ID");const t=this.buildEndpoint(ie,{id:String(e)});Ft(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(oe,{id:String(e.inviteId)}),n={role:e.role},r=await this.http.patch(t,n,this.getMultiAuthHeaders());return{invite:this.extractData(r)}}async updateInvite(e){if(this.validatePositiveInteger(e.inviteId,"inviteId","Invite ID"),void 0===e.role&&(void 0===e.description||""===e.description))throw new yt("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",fn.DESCRIPTION.MAX_LENGTH);const t=this.buildEndpoint(ae,{id:String(e.inviteId)}),n={};void 0!==e.role&&(n.role=e.role),void 0!==e.description&&(n.description=e.description);const r=await this.http.patch(t,n,this.getMultiAuthHeaders());return{invite:this.extractData(r)}}async claimInvite(e){this.validateInviteCodeFormat(e.inviteCode);const t=ne,n={inviteCode:e.inviteCode},r=await this.http.post(t,n,this.getMultiAuthHeaders()),s=this.extractData(r);return"tokenName"in s&&void 0!==s.tokenName?{token:s}:{blanketAccess:s}}async getModeratedTokens(e){const t=re,n=this.buildPaginationParams(e??{},dn.MAX_LIMIT),r=await this.http.get(t,n,this.getMultiAuthHeaders()),s=this.extractData(r);return{items:s.tokens,pageInfo:s.pageInfo}}async getInviteByCode(e){this.validateInviteCodeFormat(e);const t=this.buildEndpoint(ce,{code:e}),n=await this.http.get(t,{});return this.extractData(n)}}const YS={COLLECTION_CLAIM_FEE:"10000",TOKEN_CLASS_CREATE_FEE:"1000",DESCRIPTIONS:{COLLECTION_CLAIM:"10,000 GALA to claim a collection name",TOKEN_CLASS_CREATE:"1,000 GALA to create a token class",MINT:"Dynamic fee estimated via DryRun endpoint"}};function JS(e){return`${e}-${Date.now()}-${Math.random().toString(36).substring(2,11)}`}function QS(){return Date.now()+6e4}function ZS(e){return""!==e&&"string"==typeof e&&/^[a-zA-Z0-9]{3,50}$/.test(e)}function ek(e){try{return Math.floor(parseFloat(String(e))??0).toString()}catch{return"0"}}function tk(e){return""!==e&&"string"==typeof e&&/^eth\|[0-9a-fA-F]{40}$/.test(e)}class nk extends rr{constructor(e){super(e)}getCollectionClaimFee(){return YS.COLLECTION_CLAIM_FEE}getTokenClassCreateFee(){return YS.TOKEN_CLASS_CREATE_FEE}async estimateMintFee(e){try{if(this.logger.debug("Estimating mint fee",e),0===e.collection.length||0===e.type.length||0===e.category.length||0===e.quantity.length)throw new Error("Missing required parameters for mint fee estimation");if(!tk(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=YS.COLLECTION_CLAIM_FEE;n.collectionClaim=e,t=String(BigInt(t)+BigInt(e))}if((e.createTokenClasses??0)>0){const r=YS.TOKEN_CLASS_CREATE_FEE,s=String(BigInt(r)*BigInt(e.createTokenClasses));n.tokenClassCreate=r,n.tokenClassCount=e.createTokenClasses,t=String(BigInt(t)+BigInt(s))}return{totalFee:t,breakdown:n}}async claimCollection(e){try{if(this.logger.debug("Claiming NFT collection",e.collectionName),!ZS(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:QS(),uniqueKey:JS("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),!tk(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),!ZS(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(!ZS(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?ek(e.maxSupply):void 0,maxCapacity:void 0!==e.maxCapacity?ek(e.maxCapacity):void 0,additionalKey:e.additionalKey,expiresAt:QS(),uniqueKey:JS("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),!ZS(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(!tk(e.ownerAddress))throw new Error(`Invalid owner address: ${e.ownerAddress}`);const n=this.estimateMintFee({collection:e.collection,type:e.type,category:e.category,quantity:e.quantity,ownerAddress:e.ownerAddress});this.logger.debug("Estimated mint fee:",n);const r={collection:e.collection,type:e.type,category:e.category,quantity:e.quantity,owner:e.ownerAddress,additionalKey:e.additionalKey??"none",expiresAt:QS(),uniqueKey:JS("mint")};this.logger.debug("Built mint DTO",r);const s=`mint-${Date.now()}`,i=Array.from({length:t},(e,t)=>t+1);return{transactionId:s,mintedQuantity:e.quantity,owner:e.ownerAddress,tokenInstances:i,tokenClass:{collection:e.collection,type:e.type,category:e.category}}}catch(e){throw this.logger.error("Failed to mint NFT",e),e}}async fetchNftBalances(e,t){try{if(this.logger.debug("Fetching NFT balances for",{ownerAddress:e,collectionFilter:t}),!tk(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 rk extends rr{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(Ze,{token:e.token,platform:e.platform,...void 0!==e.deviceId?{deviceId:e.deviceId}:{}},t),r=this.extractData(n);return this.logger.debug("Push token registered",{registered:r.registered}),r}async unregisterPushToken(e){this.logger.debug("Unregistering push token");const t=this.getJwtHeaders(),n=await this.http.request({method:"DELETE",url:et,data:{token:e},headers:t}),r=this.extractData(n);return this.logger.debug("Push token unregistered",{unregistered:r.unregistered}),r}async getPreferences(){this.logger.debug("Fetching notification preferences");const e=this.getJwtHeaders(),t=await this.http.get(tt,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(nt,e,t),r=this.extractData(n);return this.logger.debug("Updated notification preferences",{tradesEnabled:r.tradesEnabled,streamsEnabled:r.streamsEnabled}),{preferences:r}}}class sk extends rr{constructor(e,t=!1){super(e,t)}async getHomeOEmbedJson(e={}){this.logger.debug("Fetching home oEmbed (JSON)");const t=await this.http.get(b.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(b.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 yt("tokenName is required","tokenName","REQUIRED_FIELD");this.logger.debug("Fetching pool oEmbed (JSON)",{tokenName:t});const n=b.OEMBED_BUY_SELL.replace(":tokenName",t.toLowerCase().trim()),r=await this.http.get(n,{format:"json"});return this.logger.debug("Fetched pool oEmbed (JSON)",{tokenName:t,title:r.title}),{oembed:r}}async getPoolOEmbedHtml(e){const{tokenName:t}=e;if(null==t||"string"!=typeof t||""===t.trim())throw new yt("tokenName is required","tokenName","REQUIRED_FIELD");this.logger.debug("Fetching pool oEmbed (HTML)",{tokenName:t});const n=b.OEMBED_BUY_SELL.replace(":tokenName",t.toLowerCase().trim()),r=await this.http.get(n,{},{responseType:"text"});return this.logger.debug("Fetched pool oEmbed (HTML)",{tokenName:t}),{html:r}}async getProfileOEmbedJson(e){const{address:t}=e;if(null==t||"string"!=typeof t||""===t.trim())throw new yt("address is required","address","REQUIRED_FIELD");this.logger.debug("Fetching profile oEmbed (JSON)",{address:t});const n=b.OEMBED_PROFILE.replace(":address",encodeURIComponent(t.toLowerCase().trim())),r=await this.http.get(n,{format:"json"});return this.logger.debug("Fetched profile oEmbed (JSON)",{address:t,title:r.title}),{oembed:r}}async getProfileOEmbedHtml(e){const{address:t}=e;if(null==t||"string"!=typeof t||""===t.trim())throw new yt("address is required","address","REQUIRED_FIELD");this.logger.debug("Fetching profile oEmbed (HTML)",{address:t});const n=b.OEMBED_PROFILE.replace(":address",encodeURIComponent(t.toLowerCase().trim())),r=await this.http.get(n,{},{responseType:"text"});return this.logger.debug("Fetched profile oEmbed (HTML)",{address:t}),{html:r}}}function ik(e){if(!Kn(e))throw St("address","Address")}const ok={PENDING:"PENDING",CLAIMED:"CLAIMED",REVOKED:"REVOKED",EXPIRED:"EXPIRED"},ak={ACTIVE:"ACTIVE",REVOKED:"REVOKED"},ck=qn(ok),lk=qn(ak);function uk(e){try{Zn(e.description,"description",255)}catch(e){if(e instanceof yt){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(!Kn(e.expiresAt))throw new Error("expiresAt must be a non-empty string");try{er(e.expiresAt,"expiresAt")}catch(e){if(e instanceof yt)throw new Error("expiresAt must be a valid ISO 8601 date string");throw e}if(rn(e.expiresAt)){if(nn(e.expiresAt)<=new Date)throw new Error("expiresAt must be in the future")}}}function dk(e){if(void 0!==e.status&&!ck(e.status))throw Ot("status",e.status,Object.values(ok),"status");Wn(0,void 0,50,e.pageSize,e.cursor)}function hk(e){if(void 0!==e.status&&!lk(e.status))throw Ot("status",e.status,Object.values(ak),"status");Wn(0,void 0,50,e.pageSize,e.cursor)}function gk(e){if(!Kn(e))throw new Error("Invite code must be a non-empty string");Mn(e,100,"code")}function fk(e){if(!Kn(e))throw new Error("Address must be a non-empty string");try{mr(e,"address")}catch{throw new Error("Invalid wallet address format. Must be eth|..., 0x..., or client|... format")}}function pk(e){try{Ln(e,"id")}catch(e){if(e instanceof yt)throw new Error("Invite ID must be a positive integer");throw e}}function mk(e){if(null==e||"object"!=typeof e)throw new yt("Options are required");if(void 0!==e.search){if("string"!=typeof e.search)throw new yt("Search must be a string");if(0===e.search.length)throw new yt("Search query cannot be empty string")}if(void 0!==e.sortBy){if("string"!=typeof e.sortBy)throw new yt("Sort field must be a string");if(0===e.sortBy.length)throw new yt("Sort field cannot be empty string")}if(void 0!==e.sortOrder&&"asc"!==e.sortOrder&&"desc"!==e.sortOrder)throw new yt('Sort order must be "asc" or "desc"')}function yk(e){if(null==e||"object"!=typeof e)throw new yt("Options are required");if(!Kn(e.userAddress))throw new yt("userAddress is required and must be a non-empty string");try{mr(e.userAddress,"userAddress")}catch{throw new yt("Invalid wallet address format. Must be eth|..., 0x..., or client|... format")}if(void 0!==e.description){if("string"!=typeof e.description)throw new yt("description must be a string");if(e.description.length>255)throw new yt("description must be at most 255 characters")}}class bk extends iE{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}validateInviteCodeFormat(e){if(!Kn(e))throw St("inviteCode","Invite code");gk(e)}validateWalletAddressFormat(e){if(!Kn(e))throw St("address","Address");fk(e)}async createInvite(e={}){uk(e),this.validateOptionalString(e.description,"description","Description",fn.DESCRIPTION.MAX_LENGTH),this.validateOptionalDate(e.expiresAt,"expiresAt","Expiration date");const t=ue,n={};void 0!==e.description&&(n.description=e.description),void 0!==e.expiresAt&&(n.expiresAt=e.expiresAt);const r=await this.http.post(t,n,this.getDualAuthHeaders());return{invite:this.extractData(r)}}async listInvites(e={}){dk(e),this.validateStatusFilter(e.status,ok);const t=de,n={...this.buildPaginationParams(e,dn.MAX_LIMIT)};void 0!==e.status&&(n.status=e.status);const r=await this.http.get(t,n,this.getDualAuthHeaders()),s=this.extractData(r);return{items:s.invites,pageInfo:s.pageInfo}}async getInviteByCode(e){this.validateInviteCodeFormat(e);const t=this.buildEndpoint(he,{code:e}),n=await this.http.get(t,{});return this.extractData(n)}async revokeInvite(e){pk(e);const t=this.buildEndpoint(fe,{id:String(e)});Ft(await this.http.delete(t,this.getDualAuthHeaders()),"Failed to revoke invite")}async claimInvite(e){this.validateInviteCodeFormat(e);const t=ge,n={inviteCode:e},r=await this.http.post(t,n,this.getJwtHeaders());return{invite:this.extractData(r)}}async listOverseers(e={}){hk(e),this.validateStatusFilter(e.status,ak);const t=pe,n={...this.buildPaginationParams(e,dn.MAX_LIMIT)};void 0!==e.status&&(n.status=e.status);const r=await this.http.get(t,n,this.getDualAuthHeaders()),s=this.extractData(r);return{items:s.overseers,pageInfo:s.pageInfo}}async createOverseerDirect(e){yk(e),this.validateWalletAddressFormat(e.userAddress),this.validateOptionalString(e.description,"description","Description",fn.DESCRIPTION.MAX_LENGTH);const t=me,n={userAddress:e.userAddress};void 0!==e.description&&(n.description=e.description);const r=await this.http.post(t,n,this.getDualAuthHeaders());return{overseer:this.extractData(r)}}async revokeOverseer(e){this.validateWalletAddressFormat(e);const t=this.buildEndpoint(ye,{address:e});Ft(await this.http.delete(t,this.getDualAuthHeaders()),"Failed to revoke overseer")}async getMyStatus(){const e=be,t=await this.http.get(e,{},this.getJwtHeaders());return this.extractData(t)}async getSummary(){const e=ve,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getBanStats(){const e=we,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getTokenBanStats(){const e=Ee,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getInviteStats(){const e=Ae,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getFlagStats(){const e=Se,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getUserStats(){const e=ke,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async listOverseerUsers(e){const t=e??{};Object.keys(t).length>0&&mk(t);const n=Te,r=this.buildPaginationParams(t,dn.MAX_LIMIT);void 0!==t.search&&""!==t.search&&(r.search=t.search),void 0!==t.sortBy&&""!==t.sortBy&&(r.sortBy=t.sortBy),void 0!==t.sortOrder&&(r.sortOrder=t.sortOrder);const s=await this.http.get(n,r,this.getDualAuthHeaders()),i=this.extractData(s);return{items:i.users,pageInfo:i.pageInfo}}async getOverseerUserSummary(e){if(!Kn(e))throw St("address","User address");fk(e);const t=this.buildEndpoint(Ie,{address:e}),n=await this.http.get(t,{},this.getDualAuthHeaders());return this.extractData(n)}async flushCacheByAddress(e){ik(e);const t=this.buildEndpoint(Ce,{address:e}),n=await this.http.delete(t,void 0,this.getDualAuthHeaders());return this.extractData(n)}async flushCacheByToken(e){!function(e){if(!Kn(e))throw St("tokenName","Token name")}(e);const t=this.buildEndpoint(Ne,{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 yt("Safety confirmation required: must pass confirm=true to flush all cache","confirm","CONFIRMATION_REQUIRED")}(e);const t=_e,n=await this.http.delete(t,{confirm:"true"},this.getDualAuthHeaders());return this.extractData(n)}async flushWalletAliasCache(e){if(void 0!==e){ik(e);const t=this.buildEndpoint(xe,{address:e}),n=await this.http.delete(t,void 0,this.getDualAuthHeaders());return this.extractData(n)}const t=Re,n=await this.http.delete(t,{confirm:"true"},this.getDualAuthHeaders());return this.extractData(n)}}function vk(e){const t=[];return 0===Object.keys(e).length&&t.push("At least one field (streamingEnabled, chatEnabled, commentsEnabled, webhooksEnabled, aiModerationEnabled) must be provided"),void 0!==e.streamingEnabled&&"boolean"!=typeof e.streamingEnabled&&t.push("streamingEnabled must be a boolean"),void 0!==e.chatEnabled&&"boolean"!=typeof e.chatEnabled&&t.push("chatEnabled must be a boolean"),void 0!==e.commentsEnabled&&"boolean"!=typeof e.commentsEnabled&&t.push("commentsEnabled must be a boolean"),void 0!==e.webhooksEnabled&&"boolean"!=typeof e.webhooksEnabled&&t.push("webhooksEnabled must be a boolean"),void 0!==e.aiModerationEnabled&&"boolean"!=typeof e.aiModerationEnabled&&t.push("aiModerationEnabled must be a boolean"),t}class wk extends rr{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),Ft(t,"Platform config operation failed",!0),e.data}async getPlatformConfig(){const e=await this.http.get(O);return this.extractData(e)}async updatePlatformConfig(e){const t=vk(e);if(t.length>0)throw new yt(t.join("; "),"options","VALIDATION_FAILED");const n=await this.http.put(M,e,this.getJwtHeaders());return this.extractData(n)}async getAvailableRoles(){const e=await this.http.get(P);return this.extractData(e)}}class Ek extends rr{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(Ve),t=this.extractData(e);return this.logger.debug("Fetched platform stats",{totalTokens:t.totalTokens,timestamp:t.timestamp}),{stats:t}}}class Ak extends rr{constructor(e,t=!1,n){super(e,t),this.tokenResolverService=n}async fetchTokenClassKeyByTokenName(e){if(""===e)throw St("tokenName","Token name");if(!this.tokenResolverService)throw It("TokenResolverService is required for token name resolution. Ensure it is passed to PriceHistoryService constructor.","tokenResolverService");try{jn(e)}catch(e){throw It(at(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=io(RE(t));return this.logger.debug(`Extracted token class key: ${n}`),n}catch(t){if(ot(t)&&at(t).includes("ConfigurationError"))throw t;throw Tt(`Failed to resolve token name '${e}': ${at(t)}`,500)}}async fetchPriceHistory(e){if(null==e)throw St("options","Fetch options");return this.logger.debug("Fetching price history from DEX Backend API with options:",e),this.validateOptions(e),await Ji(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 ME}),r=sA(io(n(t))),{from:s,to:i,sortOrder:o="DESC"}=e,a=e.timeframe??this.inferTimeframe(s,i),c={token:r,timeframe:a};this.logger.debug(`Querying price series for token ${r}, timeframe ${a}`);const l=await this.http.get(A,c);if(null==l)throw Tt("No response from price history service",500);const u=this.transformApiResponseToPriceHistory(l,e,o);return this.logger.debug(`Found ${u.snapshots.length} price snapshots, total ${u.total}`),u},"Failed to fetch price history",this.logger)}transformApiResponseToPriceHistory(e,t,n){if(!Array.isArray(e.prices))throw Tt("Invalid API response: missing price series",500);const r="string"==typeof t.tokenId?t.tokenId:t.tokenName??io(t.tokenId),s=t.from?.getTime(),i=t.to?.getTime(),o=e.prices.filter(e=>"number"==typeof e.time&&"number"==typeof e.price).filter(e=>(void 0===s||1e3*e.time>=s)&&(void 0===i||1e3*e.time<=i)).sort((e,t)=>"ASC"===n?e.time-t.time:t.time-e.time),a=Cn(t.offset,0),c=Cn(t.pageSize??t.limit,10),l=o.slice(a,a+c).map(e=>({price:String(e.price),timestamp:new Date(1e3*e.time),tokenId:r})),u=Math.max(1,Math.ceil(o.length/c)),d=Math.floor(a/c)+1;return{snapshots:l,page:d,limit:c,total:o.length,totalPages:u,hasNext:d<u,hasPrevious:d>1}}async fetchAllPriceHistory(e){if(null==e)throw St("options","Fetch options");return this.logger.debug("Fetching all price history with options:",e),Ji(async()=>{const t=await _E((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 r=e.length;return{offset:0,limit:r,total:t,totalPages:0!==r?eE(t,r):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:r}=e;if(Vn(e,"tokenName","tokenId",{description:"token identifier"}),t&&!rn(t))throw It("from must be a valid Date","from");if(void 0!==n&&!rn(n))throw It("to must be a valid Date","to");null!=r&&Pn(r,"sortOrder"),Wn(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 Sk extends iE{constructor(e,t,n,r){super(e,t,n,!1,r)}async getRestrictedNames(){try{return{success:!0,data:(await this.http.get($e)).data}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}async updateRestrictedNames(e){try{if(!Kn(e.content))throw new yt("Content is required");return{success:!0,data:(await this.http.put(Ke,e)).data}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}}class kk extends iE{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async getChatStatus(e){if(null==e||""===e)throw St("tokenName","Token name");return this.validateTokenName(e,on),Ji(async()=>{const t=this.buildEndpoint(Ge,{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 St("tokenName","Token name");return this.validateTokenName(e,on),Ji(async()=>{const t=this.buildEndpoint(We,{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 St("tokenName","Token name");return this.validateTokenName(e,on),Ji(async()=>{const t=this.buildEndpoint(He,{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??Vt(e)};return void 0!==t.status&&null!==t.status&&(n.status=t.status),n}async setSlowMode(e,t){if(null==e||""===e)throw St("tokenName","Token name");if(this.validateTokenName(e,on),"number"!=typeof t||t<0||t>600)throw new Error("slowModeSeconds must be a number between 0 and 600");return Ji(async()=>{const n=this.buildEndpoint(qe,{tokenName:e}),r=await this.http.patch(n,{slowModeSeconds:t},this.getDualAuthHeaders());return this.extractData(r)},`Failed to set slow mode for token: ${e}`,this.logger)}}class Tk extends sr{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 r of n)try{const e=r(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)}}const Ik={IDLE:"IDLE",ACTIVE:"ACTIVE",DISABLED:"DISABLED"},Ck={READY:"READY",PROCESSING:"PROCESSING",ERRORED:"ERRORED",DELETED:"DELETED"},Nk={YOUTUBE:"YOUTUBE",TWITCH:"TWITCH",FACEBOOK:"FACEBOOK",CUSTOM:"CUSTOM"},_k=qn(Ik),xk=qn(Ck),Rk=qn(Nk);const Bk={OWNER:"OWNER",MANAGER:"MANAGER",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MODERATOR:"MODERATOR"},Dk={OWNER:"OWNER",MODERATOR:"MODERATOR"};qn(Bk),qn(Dk);const Ok={...Bk,OVERSEER:"OVERSEER"},Mk=qn(Ok);function Lk(e,t="tokenName"){jn(e,t,on)}function Uk(e){if(Lk(e.tokenName),!Kn(e.language))throw St("language");if(t=e.language,!Kn(t)||!/^[a-z]{2}(-[A-Z]{2})?$/.test(t))throw new yt('language must be a valid ISO 639-1 code (e.g., "en", "es", "zh-CN")',"language",mt.INVALID_FORMAT);var t}class Pk extends iE{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async startStream(e){this.validateTokenName(e,on);const t=this.buildEndpoint(S,{tokenName:e}),n=await this.http.post(t,{},this.getJwtHeaders());return this.extractData(n)}async stopStream(e){this.validateTokenName(e,on);const t=this.buildEndpoint(k,{tokenName:e});await this.http.post(t,{},this.getJwtHeaders())}async disableStream(e){return this.toggleFeature(e,T,on)}async enableStream(e){return this.toggleFeature(e,I,on)}async resetStreamKey(e){this.validateTokenName(e,on);const t=this.buildEndpoint(C,{tokenName:e}),n=await this.http.post(t,{},this.getJwtHeaders());return this.extractData(n)}async getStreamCredentials(e){this.validateTokenName(e,on);const t=this.buildEndpoint($,{tokenName:e}),n=await this.http.get(t,{},this.getJwtHeaders());return this.extractData(n)}async getRecordings(e){!function(e){Lk(e.tokenName),Wn(0,void 0,En,e.pageSize)}(e);const t=this.buildEndpoint(N,{tokenName:e.tokenName}),n=this.buildPaginationParams(e,En),r=e.offset;"number"==typeof r&&(n.offset=String(r));const s=await this.http.get(t,n),i=this.extractData(s),o=e,a=i.pageSize??i.limit??e.pageSize??("number"==typeof o.limit?o.limit:20),c="number"==typeof o.offset?o.offset:0,l=Math.floor(c/a)+1;return{recordings:i.recordings,tokenName:Vt(e.tokenName),page:i.page??l,limit:a,total:i.total,hasNext:i.recordings.length===a}}async getRecordingDownload(e,t){this.validateTokenName(e,on),this.validateRequiredString(t,"assetId","Asset ID");const n=this.buildEndpoint(_,{tokenName:e,assetId:t}),r=await this.http.get(n,{},this.getJwtHeaders());return this.extractData(r)}async deleteRecording(e,t){this.validateTokenName(e,on),this.validateRequiredString(t,"assetId","Asset ID");const n=this.buildEndpoint(x,{tokenName:e,assetId:t});await this.http.delete(n,void 0,this.getJwtHeaders())}async getSimulcastTargets(e){this.validateTokenName(e,on);const t=this.buildEndpoint(R,{tokenName:e}),n=await this.http.get(t);return this.extractData(n)}async addSimulcastTarget(e){!function(e){if(Lk(e.tokenName),!Kn(e.platform))throw St("platform");if(!Rk(e.platform))throw new yt("platform must be one of: 'YOUTUBE', 'TWITCH', 'FACEBOOK', 'CUSTOM'","platform",mt.INVALID_VALUE);if(!Kn(e.rtmpUrl))throw St("rtmpUrl");if(!wn.STREAM_URL_PATTERN.test(e.rtmpUrl))throw new yt("rtmpUrl must be a valid RTMP, RTMPS, or SRT URL","rtmpUrl",mt.INVALID_FORMAT);if(!Kn(e.streamKey))throw St("streamKey");if(void 0!==e.name&&"string"!=typeof e.name)throw new yt("name must be a string","name",mt.INVALID_TYPE)}(e);const t=this.buildEndpoint(B,{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,on),this.validateRequiredString(t,"targetId","Target ID");const n=this.buildEndpoint(D,{tokenName:e,targetId:t});await this.http.delete(n,void 0,this.getJwtHeaders())}async getGlobalStreamingStatus(){const e=await this.http.get(O);return this.extractData(e)}async disableGlobalStreaming(){const e=await this.http.put(M,{},this.getAdminHeaders());return this.extractData(e)}async enableGlobalStreaming(){const e=await this.http.put(L,{},this.getAdminHeaders());return this.extractData(e)}async setNextLiveStream(e){let t;!function(e){if(Lk(e.tokenName),null!==e.nextLiveStreamAt){if(!(e.nextLiveStreamAt instanceof Date||Kn(e.nextLiveStreamAt)))throw new yt("nextLiveStreamAt must be a Date, ISO 8601 string, or null","nextLiveStreamAt",mt.INVALID_TYPE);if("string"==typeof e.nextLiveStreamAt){const t=Date.parse(e.nextLiveStreamAt);if(isNaN(t))throw new yt("nextLiveStreamAt must be a valid ISO 8601 date string","nextLiveStreamAt",mt.INVALID_FORMAT)}}}(e),t=null===e.nextLiveStreamAt?null:e.nextLiveStreamAt instanceof Date?e.nextLiveStreamAt.toISOString():e.nextLiveStreamAt;const n=`/v1/tokens/${e.tokenName.toLowerCase().trim()}`;await this.http.patch(n,{nextLiveStreamAt:t},this.getJwtHeaders())}async clearNextLiveStream(e){this.validateTokenName(e,on);const t=`/v1/tokens/${e.toLowerCase().trim()}`;await this.http.patch(t,{nextLiveStreamAt:null},this.getJwtHeaders())}async setStreamLanguage(e){Uk(e);const t=`/v1/tokens/${e.tokenName.toLowerCase().trim()}`;await this.http.patch(t,{streamLanguage:e.language},this.getJwtHeaders())}async getStreamRole(e){!function(e){Lk(e.tokenName)}(e);const t=this.buildEndpoint(U,{tokenName:e.tokenName}),n=this.jwtAuth?this.getJwtHeaders():{},r=await this.http.get(t,{},n);return this.extractData(r)}async getAvailableRoles(){const e=await this.http.get(P);return this.extractData(e)}async getTokenAccess(e){!function(e){Lk(e.tokenName)}(e);const t=await this.http.get(F,{tokenName:Vt(e.tokenName)},this.getJwtHeaders());return this.extractData(t)}async setNextLiveStreamCountdown(e,t){return this.setNextLiveStream({tokenName:e,nextLiveStreamAt:t})}}const Fk={SUBSCRIBE:"subscribe_token",UNSUBSCRIBE:"unsubscribe_token",AUTHENTICATE:"authenticate",SEND_CHAT:"send_stream_chat",SEND_REACTION:"SEND_STREAM_REACTION",TYPING_START:"typing_start",TYPING_STOP:"typing_stop",STREAM_STATUS:"STREAM_STATUS",RECORDING_STATUS:"RECORDING_STATUS",RECORDINGS_COUNT_UPDATED:"RECORDINGS_COUNT_UPDATED",SIMULCAST_STATUS:"SIMULCAST_STATUS",DOWNLOAD_READY:"DOWNLOAD_READY",STREAM_COUNTDOWN_UPDATED:"STREAM_COUNTDOWN_UPDATED",STREAM_LANGUAGE_UPDATED:"STREAM_LANGUAGE_UPDATED",VIEWER_COUNT:"VIEWER_COUNT",STREAM_SUBSCRIBED:"token_subscribed",STREAM_UNSUBSCRIBED:"token_unsubscribed",STREAM_GLOBAL_STATUS:"STREAM_GLOBAL_STATUS",ENGAGEMENT_STATS_UPDATED:"ENGAGEMENT_STATS_UPDATED",CHAT_MESSAGE:"STREAM_CHAT_MESSAGE",CHAT_SENT:"STREAM_CHAT_SENT",CHAT_UPDATED:"STREAM_CHAT_UPDATED",CHAT_DELETED:"STREAM_CHAT_DELETED",CHAT_ERROR:"stream_chat_error",CHAT_STATUS:"CHAT_STATUS_CHANGED",CHAT_GLOBAL_STATUS:"STREAM_CHAT_GLOBAL_STATUS",CHAT_AUTHENTICATED:"authenticated",CHAT_AUTH_ERROR:"stream_chat_auth_error",STREAM_CONTROL_STATUS_CHANGED:"STREAM_CONTROL_STATUS_CHANGED",REACTION:"STREAM_REACTION",CONTENT_REACTION_ADDED:"CONTENT_REACTION_ADDED",CONTENT_REACTION_REMOVED:"CONTENT_REACTION_REMOVED",REACTION_ERROR:"stream_reaction_error",USER_TYPING:"USER_TYPING",CHAT_PINNED:"STREAM_CHAT_PINNED",CHAT_UNPINNED:"STREAM_CHAT_UNPINNED",COMMENT_CREATED:"COMMENT_CREATED",COMMENT_UPDATED:"COMMENT_UPDATED",COMMENT_DELETED:"COMMENT_DELETED",USER_BANNED:"USER_BANNED",USER_UNBANNED:"USER_UNBANNED",BAN_ENFORCEMENT:"BAN_ENFORCEMENT",TOKEN_BANNED:"TOKEN_BANNED",TOKEN_UNBANNED:"TOKEN_UNBANNED",CONTENT_FLAGGED:"CONTENT_FLAGGED",FLAG_RESOLVED:"FLAG_RESOLVED",MODERATOR_INVITE_CREATED:"MODERATOR_INVITE_CREATED",MODERATOR_ADDED:"MODERATOR_ADDED",MODERATOR_REMOVED:"MODERATOR_REMOVED",MODERATOR_ROLE_UPDATED:"MODERATOR_ROLE_UPDATED",OVERSEER_ADDED:"OVERSEER_ADDED",OVERSEER_REMOVED:"OVERSEER_REMOVED",TRADE_EXECUTED:"TRADE_EXECUTED",BALANCE_UPDATED:"BALANCE_UPDATED",STATS_UPDATED:"STATS_UPDATED",POOL_METADATA_UPDATED:"POOL_METADATA_UPDATED",POOL_SOCIAL_LINKS_UPDATED:"POOL_SOCIAL_LINKS_UPDATED",POOL_BADGE_ASSIGNED:"POOL_BADGE_ASSIGNED",HOLDER_COUNT_UPDATED:"HOLDER_COUNT_UPDATED",USER_PROFILE_UPDATED:"USER_PROFILE_UPDATED",API_KEY_CREATED:"API_KEY_CREATED",API_KEY_UPDATED:"API_KEY_UPDATED",API_KEY_REVOKED:"API_KEY_REVOKED",TOKEN_CONFIG_UPDATED:"TOKEN_CONFIG_UPDATED",SITE_CONFIG_CHANGED:"SITE_CONFIG_CHANGED",COMMENTS_GLOBAL_STATUS:"COMMENTS_GLOBAL_STATUS",WEBHOOKS_GLOBAL_STATUS:"WEBHOOKS_GLOBAL_STATUS",SUBSCRIBE_GLOBAL_FEED:"subscribe_global_feed",UNSUBSCRIBE_GLOBAL_FEED:"unsubscribe_global_feed",GLOBAL_FEED_SUBSCRIBED:"global_feed_subscribed",GLOBAL_FEED_UNSUBSCRIBED:"global_feed_unsubscribed"};class $k extends sr{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 vt("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 pS({maxAttempts:this.config.reconnectAttempts,baseDelayMs:this.config.reconnectDelay}),this.isSocketIOAvailable=this.checkSocketIOAvailability()}checkSocketIOAvailability(){try{return"function"==typeof a.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:",at(e)),!1}}getRoomName(e){return`token:${Vt(e)}`}bufferEvent(e,t,n){const r=`${e}:${t}`;let s=this.eventBuffer.get(r);s||(s=[],this.eventBuffer.set(r,s)),s.length>=this.MAX_BUFFER_SIZE&&(s.shift(),this.logger.warn(`⚠️ [Stream Buffer] Event buffer overflow for ${r} - dropping oldest event. Consider processing events faster or increasing buffer size.`)),s.push(n);const i=this.eventBufferTimeouts.get(r);i&&clearTimeout(i);const o=setTimeout(()=>{this.eventBuffer.delete(r),this.eventBufferTimeouts.delete(r),this.logger.debug(`📡 [Stream Buffer] Cleaned up buffer for ${r}`)},this.BUFFER_CLEANUP_MS);this.eventBufferTimeouts.set(r,o)}processBufferedEvents(e,t){const n=Vt(e),r=[{key:`${Fk.STREAM_STATUS}:${n}`,callback:t.onStreamStatus},{key:`${Fk.VIEWER_COUNT}:${n}`,callback:t.onViewerCount},{key:`${Fk.CHAT_MESSAGE}:${n}`,callback:t.onChatMessage},{key:`${Fk.CHAT_STATUS}:${n}`,callback:t.onChatStatus},{key:`${Fk.CHAT_PINNED}:${n}`,callback:t.onChatPinned},{key:`${Fk.CHAT_UNPINNED}:${n}`,callback:t.onChatUnpinned},{key:`${Fk.STREAM_COUNTDOWN_UPDATED}:${n}`,callback:t.onCountdownUpdated},{key:`${Fk.STREAM_LANGUAGE_UPDATED}:${n}`,callback:t.onLanguageUpdated},{key:`${Fk.TOKEN_BANNED}:${n}`,callback:t.onTokenBanned},{key:`${Fk.TOKEN_UNBANNED}:${n}`,callback:t.onTokenUnbanned},{key:`${Fk.MODERATOR_INVITE_CREATED}:${n}`,callback:t.onModeratorInviteCreated},{key:`${Fk.MODERATOR_ADDED}:${n}`,callback:t.onModeratorAdded},{key:`${Fk.MODERATOR_REMOVED}:${n}`,callback:t.onModeratorRemoved},{key:`${Fk.MODERATOR_ROLE_UPDATED}:${n}`,callback:t.onModeratorRoleUpdated},{key:`${Fk.TRADE_EXECUTED}:${n}`,callback:t.onTradeExecuted},{key:`${Fk.BALANCE_UPDATED}:${n}`,callback:t.onBalanceUpdated},{key:`${Fk.POOL_METADATA_UPDATED}:${n}`,callback:t.onPoolMetadataUpdated},{key:`${Fk.POOL_SOCIAL_LINKS_UPDATED}:${n}`,callback:t.onPoolSocialLinksUpdated},{key:`${Fk.POOL_BADGE_ASSIGNED}:${n}`,callback:t.onPoolBadgeAssigned},{key:`${Fk.HOLDER_COUNT_UPDATED}:${n}`,callback:t.onHolderCountUpdated},{key:`${Fk.COMMENT_CREATED}:${n}`,callback:t.onCommentCreated}];for(const{key:e,callback:t}of r){const n=this.eventBuffer.get(e);if(n&&t){this.logger.debug(`📡 [Stream Buffer] Delivering ${n.length} buffered events for ${e}`);for(const r of n)try{t(r)}catch(t){this.logger.error(`Error delivering buffered event for ${e}:`,t)}this.eventBuffer.delete(e);const r=this.eventBufferTimeouts.get(e);r&&(clearTimeout(r),this.eventBufferTimeouts.delete(e))}}}setupGlobalListeners(){this.socket&&(this.socket.on(Fk.STREAM_STATUS,e=>{this.logger.debug(`📡 [Stream Status] ${e.tokenName}: ${e.status}`),this.bufferEvent(Fk.STREAM_STATUS,e.tokenName,e);const t=this.roomCallbacks.get(Vt(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(Fk.STREAM_SUBSCRIBED,e=>{this.logger.debug(`📡 [Subscribed] ${e.tokenName}`);const t=Vt(e.tokenName),n=this.pendingSubscriptions.get(t);n&&(clearTimeout(n.timeoutId),this.pendingSubscriptions.delete(t),n.resolve(e));const r=this.roomCallbacks.get(t);r?.onStreamSubscribed&&r.onStreamSubscribed(e)}),this.socket.on(Fk.STREAM_UNSUBSCRIBED,e=>{const t=e.room.replace("token:","");this.logger.debug(`📡 [Unsubscribed] ${t}`);const n=this.roomCallbacks.get(Vt(t));n?.onStreamUnsubscribed&&n.onStreamUnsubscribed(e)}),this.socket.on(Fk.VIEWER_COUNT,e=>{this.logger.debug(`📡 [Viewer Count] ${e.tokenName}: ${e.viewerCount}`),this.bufferEvent(Fk.VIEWER_COUNT,e.tokenName,e);const t=this.roomCallbacks.get(Vt(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(Fk.STREAM_GLOBAL_STATUS,e=>{this.logger.debug(`📡 [Global Stream Status] enabled: ${String(e.enabled)}`),this.globalCallbacks.onStreamGlobalStatus&&this.globalCallbacks.onStreamGlobalStatus(e)}),this.socket.on(Fk.CHAT_MESSAGE,e=>{this.logger.debug(`📡 [Chat Message] ${e.tokenName}: ${e.content.slice(0,50)}...`),this.bufferEvent(Fk.CHAT_MESSAGE,e.tokenName,e);const t=this.roomCallbacks.get(Vt(e.tokenName));t?.onChatMessage&&t.onChatMessage(e),this.globalCallbacks.onChatMessage&&this.globalCallbacks.onChatMessage(e)}),this.socket.on(Fk.CHAT_SENT,e=>{this.logger.debug(`📡 [Chat Sent] ${e.tokenName}: ${e.messageId}`);const t=this.roomCallbacks.get(Vt(e.tokenName));t?.onChatSent&&t.onChatSent(e)}),this.socket.on(Fk.CHAT_ERROR,e=>{this.logger.error(`📡 [Chat Error] ${e.tokenName}: ${e.message}`);const t=this.roomCallbacks.get(Vt(e.tokenName));t?.onChatError&&t.onChatError(e),this.globalCallbacks.onChatError&&this.globalCallbacks.onChatError(e)}),this.socket.on(Fk.CHAT_STATUS,e=>{this.logger.debug(`📡 [Chat Status] ${e.tokenName}: ${String(e.enabled)}`),this.bufferEvent(Fk.CHAT_STATUS,e.tokenName,e);const t=this.roomCallbacks.get(Vt(e.tokenName));t?.onChatStatus&&t.onChatStatus(e),this.globalCallbacks.onChatStatus&&this.globalCallbacks.onChatStatus(e)}),this.socket.on(Fk.CHAT_GLOBAL_STATUS,e=>{this.logger.debug(`📡 [Global Chat Status] enabled: ${String(e.enabled)}`),this.globalCallbacks.onChatGlobalStatus&&this.globalCallbacks.onChatGlobalStatus(e)}),this.socket.on(Fk.CHAT_AUTHENTICATED,e=>{this.logger.debug(`📡 [Authenticated] ${e.address}`),this.isAuthenticated=!0,this.globalCallbacks.onChatAuthenticated&&this.globalCallbacks.onChatAuthenticated(e)}),this.socket.on(Fk.CHAT_AUTH_ERROR,e=>{this.logger.error(`📡 [Auth Error] ${e.message}`),this.isAuthenticated=!1,this.globalCallbacks.onChatAuthError&&this.globalCallbacks.onChatAuthError(e)}),this.socket.on(Fk.REACTION,e=>{this.logger.debug(`📡 [Reaction] ${e.tokenName}: ${e.emoji}`);const t=this.roomCallbacks.get(Vt(e.tokenName));t?.onReaction&&t.onReaction(e),this.globalCallbacks.onReaction&&this.globalCallbacks.onReaction(e)}),this.socket.on(Fk.REACTION_ERROR,e=>{this.logger.error(`📡 [Reaction Error] ${e.tokenName}: ${e.message}`);const t=this.roomCallbacks.get(Vt(e.tokenName));t?.onReactionError&&t.onReactionError(e),this.globalCallbacks.onReactionError&&this.globalCallbacks.onReactionError(e)}),this.socket.on(Fk.USER_TYPING,e=>{const t=e.typingUsers.length;this.logger.debug(`📡 [Typing] ${e.tokenName}: ${t} user(s) typing`);const n=this.roomCallbacks.get(Vt(e.tokenName));n?.onTypingIndicator&&n.onTypingIndicator(e),this.globalCallbacks.onTypingIndicator&&this.globalCallbacks.onTypingIndicator(e)}),this.socket.on(Fk.CHAT_PINNED,e=>{this.logger.debug(`📡 [Chat Pinned] ${e.tokenName}: ${e.pinnedMessage.messageId}`),this.bufferEvent(Fk.CHAT_PINNED,e.tokenName,e);const t=this.roomCallbacks.get(Vt(e.tokenName));t?.onChatPinned&&t.onChatPinned(e),this.globalCallbacks.onChatPinned&&this.globalCallbacks.onChatPinned(e)}),this.socket.on(Fk.CHAT_UNPINNED,e=>{this.logger.debug(`📡 [Chat Unpinned] ${e.tokenName}: ${e.unpinnedMessageId}`),this.bufferEvent(Fk.CHAT_UNPINNED,e.tokenName,e);const t=this.roomCallbacks.get(Vt(e.tokenName));t?.onChatUnpinned&&t.onChatUnpinned(e),this.globalCallbacks.onChatUnpinned&&this.globalCallbacks.onChatUnpinned(e)}),this.socket.on(Fk.STREAM_COUNTDOWN_UPDATED,e=>{const t=e.nextLiveStreamAt??"cleared";this.logger.debug(`📡 [Countdown Updated] ${e.tokenName}: ${t}`),this.bufferEvent(Fk.STREAM_COUNTDOWN_UPDATED,e.tokenName,e);const n=this.roomCallbacks.get(Vt(e.tokenName));n?.onCountdownUpdated&&n.onCountdownUpdated(e),this.globalCallbacks.onCountdownUpdated&&this.globalCallbacks.onCountdownUpdated(e)}),this.socket.on(Fk.STREAM_LANGUAGE_UPDATED,e=>{this.logger.debug(`📡 [Language Updated] ${e.tokenName}: ${e.language}`),this.bufferEvent(Fk.STREAM_LANGUAGE_UPDATED,e.tokenName,e);const t=this.roomCallbacks.get(Vt(e.tokenName));t?.onLanguageUpdated&&t.onLanguageUpdated(e),this.globalCallbacks.onLanguageUpdated&&this.globalCallbacks.onLanguageUpdated(e)}),this.socket.on(Fk.TOKEN_BANNED,e=>{this.logger.debug(`📡 [Token Banned] ${e.tokenName}`),this.bufferEvent(Fk.TOKEN_BANNED,e.tokenName,e);const t=this.roomCallbacks.get(Vt(e.tokenName));t?.onTokenBanned&&t.onTokenBanned(e),this.globalCallbacks.onTokenBanned&&this.globalCallbacks.onTokenBanned(e)}),this.socket.on(Fk.TOKEN_UNBANNED,e=>{this.logger.debug(`📡 [Token Unbanned] ${e.tokenName}`),this.bufferEvent(Fk.TOKEN_UNBANNED,e.tokenName,e);const t=this.roomCallbacks.get(Vt(e.tokenName));t?.onTokenUnbanned&&t.onTokenUnbanned(e),this.globalCallbacks.onTokenUnbanned&&this.globalCallbacks.onTokenUnbanned(e)}),this.socket.on(Fk.MODERATOR_INVITE_CREATED,e=>{this.logger.debug(`📡 [Moderator Invite Created] ${e.tokenName}: by ${e.invitedBy}`),this.bufferEvent(Fk.MODERATOR_INVITE_CREATED,e.tokenName,e);const t=this.roomCallbacks.get(Vt(e.tokenName));t?.onModeratorInviteCreated&&t.onModeratorInviteCreated(e)}),this.socket.on(Fk.MODERATOR_ADDED,e=>{this.logger.debug(`📡 [Moderator Added] ${e.tokenName}: ${e.userAddress}`),this.bufferEvent(Fk.MODERATOR_ADDED,e.tokenName,e);const t=this.roomCallbacks.get(Vt(e.tokenName));t?.onModeratorAdded&&t.onModeratorAdded(e)}),this.socket.on(Fk.MODERATOR_REMOVED,e=>{this.logger.debug(`📡 [Moderator Removed] ${e.tokenName}: ${e.userAddress}`),this.bufferEvent(Fk.MODERATOR_REMOVED,e.tokenName,e);const t=this.roomCallbacks.get(Vt(e.tokenName));t?.onModeratorRemoved&&t.onModeratorRemoved(e)}),this.socket.on(Fk.MODERATOR_ROLE_UPDATED,e=>{this.logger.debug(`📡 [Moderator Role Updated] ${e.tokenName}: ${e.userAddress}`),this.bufferEvent(Fk.MODERATOR_ROLE_UPDATED,e.tokenName,e);const t=this.roomCallbacks.get(Vt(e.tokenName));t?.onModeratorRoleUpdated&&t.onModeratorRoleUpdated(e)}),this.socket.on(Fk.OVERSEER_ADDED,e=>{this.logger.debug(`📡 [Overseer Added] ${e.userAddress}`),this.globalCallbacks.onOverseerAdded&&this.globalCallbacks.onOverseerAdded(e)}),this.socket.on(Fk.OVERSEER_REMOVED,e=>{this.logger.debug(`📡 [Overseer Removed] ${e.userAddress}`),this.globalCallbacks.onOverseerRemoved&&this.globalCallbacks.onOverseerRemoved(e)}),this.socket.on(Fk.TRADE_EXECUTED,e=>{this.logger.debug(`📡 [Trade Executed] ${e.tokenName}: ${e.tradeType}`),this.bufferEvent(Fk.TRADE_EXECUTED,e.tokenName,e);const t=this.roomCallbacks.get(Vt(e.tokenName));t?.onTradeExecuted&&t.onTradeExecuted(e),this.isGlobalFeedSubscribed&&!t&&this.globalFeedCallbacks.onTradeExecuted&&this.globalFeedCallbacks.onTradeExecuted(e)}),this.socket.on(Fk.BALANCE_UPDATED,e=>{this.logger.debug(`📡 [Balance Updated] ${e.tokenName}: ${e.tradeType}`),this.bufferEvent(Fk.BALANCE_UPDATED,e.tokenName,e);const t=this.roomCallbacks.get(Vt(e.tokenName));t?.onBalanceUpdated&&t.onBalanceUpdated(e)}),this.socket.on(Fk.POOL_METADATA_UPDATED,e=>{this.logger.debug(`📡 [Pool Metadata Updated] ${e.tokenName}`),this.bufferEvent(Fk.POOL_METADATA_UPDATED,e.tokenName,e);const t=this.roomCallbacks.get(Vt(e.tokenName));t?.onPoolMetadataUpdated&&t.onPoolMetadataUpdated(e)}),this.socket.on(Fk.POOL_SOCIAL_LINKS_UPDATED,e=>{this.logger.debug(`📡 [Pool Social Links Updated] ${e.tokenName}`),this.bufferEvent(Fk.POOL_SOCIAL_LINKS_UPDATED,e.tokenName,e);const t=this.roomCallbacks.get(Vt(e.tokenName));t?.onPoolSocialLinksUpdated&&t.onPoolSocialLinksUpdated(e)}),this.socket.on(Fk.POOL_BADGE_ASSIGNED,e=>{this.logger.debug(`📡 [Pool Badge Assigned] ${e.tokenName}: ${e.badge}`),this.bufferEvent(Fk.POOL_BADGE_ASSIGNED,e.tokenName,e);const t=this.roomCallbacks.get(Vt(e.tokenName));t?.onPoolBadgeAssigned&&t.onPoolBadgeAssigned(e),this.isGlobalFeedSubscribed&&!t&&this.globalFeedCallbacks.onPoolBadgeAssigned&&this.globalFeedCallbacks.onPoolBadgeAssigned(e)}),this.socket.on(Fk.HOLDER_COUNT_UPDATED,e=>{this.logger.debug(`📡 [Holder Count Updated] ${e.tokenName}: ${e.holderCount}`),this.bufferEvent(Fk.HOLDER_COUNT_UPDATED,e.tokenName,e);const t=this.roomCallbacks.get(Vt(e.tokenName));t?.onHolderCountUpdated&&t.onHolderCountUpdated(e),this.isGlobalFeedSubscribed&&!t&&this.globalFeedCallbacks.onHolderCountUpdated&&this.globalFeedCallbacks.onHolderCountUpdated(e)}),this.socket.on(Fk.COMMENT_CREATED,e=>{this.logger.debug(`📡 [Comment Created] ${e.tokenName}: ID ${e.id}`),this.bufferEvent(Fk.COMMENT_CREATED,e.tokenName,e);const t=this.roomCallbacks.get(Vt(e.tokenName));t?.onCommentCreated&&t.onCommentCreated(e)}),this.socket.on(Fk.USER_PROFILE_UPDATED,e=>{this.logger.debug(`📡 [User Profile Updated] ${e.userAddress}`),this.globalCallbacks.onUserProfileUpdated&&this.globalCallbacks.onUserProfileUpdated(e)}),this.socket.on(Fk.API_KEY_CREATED,e=>{this.logger.debug(`📡 [API Key Created] ${e.keyId}`),this.globalCallbacks.onApiKeyCreated&&this.globalCallbacks.onApiKeyCreated(e)}),this.socket.on(Fk.API_KEY_UPDATED,e=>{this.logger.debug(`📡 [API Key Updated] ${e.keyId}`),this.globalCallbacks.onApiKeyUpdated&&this.globalCallbacks.onApiKeyUpdated(e)}),this.socket.on(Fk.API_KEY_REVOKED,e=>{this.logger.debug(`📡 [API Key Revoked] ${e.keyId}`),this.globalCallbacks.onApiKeyRevoked&&this.globalCallbacks.onApiKeyRevoked(e)}),this.socket.on(Fk.TOKEN_CONFIG_UPDATED,e=>{this.logger.debug(`📡 [Token Config Updated] ${e.tokenName}`),this.bufferEvent(Fk.TOKEN_CONFIG_UPDATED,e.tokenName,e);const t=this.roomCallbacks.get(Vt(e.tokenName));t?.onTokenConfigUpdated&&t.onTokenConfigUpdated(e),this.isGlobalFeedSubscribed&&!t&&this.globalFeedCallbacks.onTokenConfigUpdated&&this.globalFeedCallbacks.onTokenConfigUpdated(e)}),this.socket.on(Fk.STATS_UPDATED,e=>{this.logger.debug(`📡 [Stats Updated] ${e.tokenName} price=${e.galaPrice}`),this.bufferEvent(Fk.STATS_UPDATED,e.tokenName,e);const t=this.roomCallbacks.get(Vt(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(Fk.ENGAGEMENT_STATS_UPDATED,e=>{this.logger.debug(`📡 [Engagement Stats Updated] ${e.tokenName} chatters=${e.chat.uniqueChatters}`),this.bufferEvent(Fk.ENGAGEMENT_STATS_UPDATED,e.tokenName,e);const t=this.roomCallbacks.get(Vt(e.tokenName));t?.onEngagementStatsUpdated&&t.onEngagementStatsUpdated(e),this.globalCallbacks.onEngagementStatsUpdated&&this.globalCallbacks.onEngagementStatsUpdated(e)}),this.socket.on(Fk.GLOBAL_FEED_SUBSCRIBED,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(Fk.GLOBAL_FEED_UNSUBSCRIBED,e=>{this.logger.debug("📡 [Global Feed Unsubscribed]"),this.isGlobalFeedSubscribed=!1,this.globalFeedCallbacks.onGlobalFeedUnsubscribed&&this.globalFeedCallbacks.onGlobalFeedUnsubscribed(e)}),this.socket.on(Fk.SITE_CONFIG_CHANGED,e=>{this.logger.debug(`📡 [Site Config Changed] ${e.key}`),this.globalFeedCallbacks.onSiteConfigChanged&&this.globalFeedCallbacks.onSiteConfigChanged(e)}),this.socket.on(Fk.STREAM_GLOBAL_STATUS,e=>{this.logger.debug(`📡 [Stream Global Status] enabled=${String(e.enabled)}`),this.globalFeedCallbacks.onStreamGlobalStatus&&this.globalFeedCallbacks.onStreamGlobalStatus(e)}),this.socket.on(Fk.CHAT_GLOBAL_STATUS,e=>{this.logger.debug(`📡 [Chat Global Status] enabled=${String(e.enabled)}`),this.globalFeedCallbacks.onStreamChatGlobalStatus&&this.globalFeedCallbacks.onStreamChatGlobalStatus(e)}),this.socket.on(Fk.COMMENTS_GLOBAL_STATUS,e=>{this.logger.debug(`📡 [Comments Global Status] enabled=${String(e.enabled)}`),this.globalFeedCallbacks.onCommentsGlobalStatus&&this.globalFeedCallbacks.onCommentsGlobalStatus(e)}),this.socket.on(Fk.WEBHOOKS_GLOBAL_STATUS,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(Fk.SUBSCRIBE,{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(Fk.SUBSCRIBE_GLOBAL_FEED)}catch(e){this.logger.error("Failed to re-subscribe to global feed:",e)}}async connect(){return new Promise((e,t)=>{Ji(async()=>{if(!this.isSocketIOAvailable)throw new vt('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=a.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 yt("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(""===e)throw St("token","Authentication token");this.logger.debug("📡 Authenticating with stream server"),this.socket.emit(Fk.AUTHENTICATE,{token:e}),this.config.authToken=e}async subscribeToStream(e,t={}){if(""===e)throw St("tokenName","Token name");if(!this.socket?.connected)throw new yt("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");const n=Vt(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((r,s)=>{const i=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:r,reject:s,timeoutId:i}),this.roomCallbacks.set(n,t),this.subscribedRooms.set(n,{tokenName:n,subscribedAt:Date.now()}),this.logger.debug(`📡 Subscribing to stream: ${n}`),this.socket.emit(Fk.SUBSCRIBE,{tokenName:n})})}unsubscribeFromStream(e){const t=Vt(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(Fk.UNSUBSCRIBE,{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 St("tokenName","Token name");if(""===t)throw St("content","Message content");if(!this.socket?.connected)throw new yt("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(!this.isAuthenticated)throw new yt("Not authenticated. Call authenticate() first.","auth","NOT_AUTHENTICATED");const n=Vt(e);this.logger.debug(`📡 Sending chat message to ${n}: ${t.slice(0,30)}...`),this.socket.emit(Fk.SEND_CHAT,{tokenName:n,content:t})}sendReaction(e,t,n=0){if(""===e)throw St("tokenName","Token name");if(""===t)throw St("emoji");if(!this.socket?.connected)throw new yt("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(!this.isAuthenticated)throw new yt("Not authenticated. Call authenticate() first.","auth","NOT_AUTHENTICATED");const r=Vt(e);this.logger.debug(`📡 Sending reaction to ${r}: ${t}`),this.socket.emit(Fk.SEND_REACTION,{tokenName:r,emoji:t,streamTime:n})}sendTypingStart(e){this.sendTypingEvent(e,Fk.TYPING_START,"typing_start")}sendTypingStop(e){this.sendTypingEvent(e,Fk.TYPING_STOP,"typing_stop")}sendTypingEvent(e,t,n){if(""===e)throw St("tokenName","Token name");if(!this.socket?.connected)throw new yt("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(!this.isAuthenticated)throw new yt("Not authenticated. Call authenticate() first.","auth","NOT_AUTHENTICATED");const r=Vt(e);this.logger.debug(`📡 Sending ${n} to ${r}`),this.socket.emit(t,{tokenName:r})}subscribeTokenBanned(e,t){const n=Vt(e),r={onTokenBanned:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...r}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onTokenBanned,this.roomCallbacks.set(n,t)}}}subscribeTokenUnbanned(e,t){const n=Vt(e),r={onTokenUnbanned:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...r}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onTokenUnbanned,this.roomCallbacks.set(n,t)}}}subscribeModeratorInviteCreated(e,t){const n=Vt(e),r={onModeratorInviteCreated:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...r}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onModeratorInviteCreated,this.roomCallbacks.set(n,t)}}}subscribeModeratorAdded(e,t){const n=Vt(e),r={onModeratorAdded:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...r}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onModeratorAdded,this.roomCallbacks.set(n,t)}}}subscribeModeratorRemoved(e,t){const n=Vt(e),r={onModeratorRemoved:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...r}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onModeratorRemoved,this.roomCallbacks.set(n,t)}}}subscribeModeratorRoleUpdated(e,t){const n=Vt(e),r={onModeratorRoleUpdated:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...r}),()=>{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=Vt(e),r={onTradeExecuted:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...r}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onTradeExecuted,this.roomCallbacks.set(n,t)}}}subscribePoolMetadataUpdated(e,t){const n=Vt(e),r={onPoolMetadataUpdated:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...r}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onPoolMetadataUpdated,this.roomCallbacks.set(n,t)}}}subscribePoolSocialLinksUpdated(e,t){const n=Vt(e),r={onPoolSocialLinksUpdated:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...r}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onPoolSocialLinksUpdated,this.roomCallbacks.set(n,t)}}}subscribePoolBadgeAssigned(e,t){const n=Vt(e),r={onPoolBadgeAssigned:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...r}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onPoolBadgeAssigned,this.roomCallbacks.set(n,t)}}}subscribeHolderCountUpdated(e,t){const n=Vt(e),r={onHolderCountUpdated:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...r}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onHolderCountUpdated,this.roomCallbacks.set(n,t)}}}subscribeCommentCreated(e,t){const n=Vt(e),r={onCommentCreated:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...r}),()=>{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 yt("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 r=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:r},e&&(this.globalFeedCallbacks=e),this.logger.debug("📡 Subscribing to global feed"),this.socket.emit(Fk.SUBSCRIBE_GLOBAL_FEED)})}unsubscribeFromGlobalFeed(){this.isGlobalFeedSubscribed?(this.logger.debug("📡 Unsubscribing from global feed"),this.socket?.connected&&this.socket.emit(Fk.UNSUBSCRIBE_GLOBAL_FEED),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 Kk(e){return null==e||""===e||"string"==typeof e&&(!Qn(e)&&e.length<=fn.BAN_REASON.MAX_LENGTH)}function Gk(e){if(jn(e.tokenName,"tokenName",on),!Kk(e.reason))throw new yt(`reason must be at most ${fn.BAN_REASON.MAX_LENGTH} characters`,"reason","TOO_LONG")}function Hk(e){jn(e.tokenName,"tokenName",on)}function Wk(e){Wn(0,void 0,ln,e.pageSize)}function qk(e){jn(e.tokenName,"tokenName",on)}class zk extends iE{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async banToken(e){Gk(e);const t=Be,n={tokenName:Vt(e.tokenName)};if(void 0!==e.reason)try{Un(e.reason,"reason",!0),e.reason.trim().length>0&&(n.reason=e.reason)}catch{}const r=await this.http.post(t,n,this.getDualAuthHeaders());return{ban:this.extractData(r),tokenName:Vt(e.tokenName)}}async unbanToken(e){Hk(e);const t=this.buildEndpoint(Me,{tokenName:e.tokenName});return Ft(await this.http.delete(t,void 0,this.getDualAuthHeaders()),"Failed to unban token",!1),{tokenName:Vt(e.tokenName)}}async listTokenBans(e={}){Wk(e);const t=De,n=this.buildPaginationParams(e,ln);this.addOptionalFilterParams(n,e,["search"]);const r=await this.http.get(t,n,this.getDualAuthHeaders()),s=this.extractData(r);return{items:s.bans,pageInfo:s.pageInfo}}async getTokenBan(e){qk(e);const t=this.buildEndpoint(Oe,{tokenName:e.tokenName}),n=await this.http.get(t,{},this.getDualAuthHeaders()),r=this.extractDataOrNull(n);return{banned:null!==r,...null!==r&&{ban:r},tokenName:Vt(e.tokenName)}}async isTokenBanned(e){return this.getTokenBan(e)}}class Vk extends sr{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(!Kn(e))throw St("tokenName","Token name");const t=Vt(e),n=this.getCacheEntry(t);if(null!==n)return this.cacheHits++,this.updateAccessOrder(t),n.vaultAddress;this.cacheMisses++;const r=await this.poolService.resolveTokenNameToVault(e);if(null!==r&&""!==r){const e=this.parseVaultAddressToTokenClassKey(r);this.setCacheEntry(t,{vaultAddress:r,tokenClassKey:e,cachedAt:Date.now()})}return r}async resolveTokenClassKey(e){if(!Kn(e))throw St("tokenName","Token name");const t=Vt(e),n=this.getCacheEntry(t);if(null!==n)return this.cacheHits++,this.updateAccessOrder(t),n.tokenClassKey;this.cacheMisses++;const r=await this.poolService.resolveTokenNameToVault(e);if(null===r||""===r)throw At(e);const s=this.parseVaultAddressToTokenClassKey(r);return this.setCacheEntry(t,{vaultAddress:r,tokenClassKey:s,cachedAt:Date.now()}),s}get(e){const t=this.getCacheEntry(Vt(e));return t?.vaultAddress??null}getCacheEntry(e){return this.cache.get(e)??null}setCacheEntry(e,t){this.cache.size>=Vk.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=Vt(e),r=this.parseVaultAddressToTokenClassKey(t);this.setCacheEntry(n,{vaultAddress:t,tokenClassKey:r,cachedAt:Date.now()})}clear(){this.cache.clear(),this.accessOrder=new Set,this.cacheHits=0,this.cacheMisses=0}getStats(){const e=Array.from(this.cache.values()).map(e=>e.cachedAt),t=this.cacheHits+this.cacheMisses;return{size:this.cache.size,keys:Array.from(this.cache.keys()),maxSize:Vk.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(Vt(e));return t?.tokenClassKey??null}preWarm(e){for(const{tokenName:t,vaultAddress:n}of e)this.set(t,n)}preWarmWithTokenClassKey(e){for(const{tokenName:t,vaultAddress:n,tokenClassKey:r}of e){const e=Vt(t);this.setCacheEntry(e,{vaultAddress:n,tokenClassKey:r,cachedAt:Date.now()})}}parseVaultAddressToTokenClassKey(e){try{return RE(e)}catch(e){if(e instanceof yt)throw kt("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad","Vault address");throw e}}}Vk.MAX_CACHE_SIZE=1e4;class jk extends rr{constructor(e,t=!1){super(e,t)}async fetchLaunchpadFee(){return Gt(()=>this.http.get(je),{errorContext:"Failed to fetch launchpad fee"})}async fetchSaleDetails(e){return Gt(()=>this.http.get(Xe,{tokenName:e}),{errorContext:`Failed to fetch sale details for ${e}`})}async getTradeQuote(e){return Gt(()=>this.http.get(Ye,{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(Je,{amount:e}),{errorContext:"Failed to get premint quote"})}}class Xk extends iE{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async emitTradeExecuted(e,t){this.validateTokenName(e,an);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,an);const r={action:"balance_updated",userAddress:e,tokenName:t,payload:n};await this.emitEvent(r)}async emitStreamStatus(e,t,n=!0){this.validateTokenName(e,an);const r={action:"stream_status",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitViewerCount(e,t,n=!1){this.validateTokenName(e,an);const r={action:"viewer_count",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitStreamCountdown(e,t,n=!0){this.validateTokenName(e,an);const r={action:"stream_countdown",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitChatMessage(e,t,n=!1){this.validateTokenName(e,an);const r={action:"chat_message",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitChatStatus(e,t,n=!1){this.validateTokenName(e,an);const r={action:"chat_status",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitTypingIndicator(e,t,n=!1){this.validateTokenName(e,an);const r={action:"typing_indicator",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitTokenBanned(e,t){this.validateTokenName(e,an);const n={action:"token_banned",tokenName:e,payload:t,broadcast:!0};await this.emitEvent(n)}async emitTokenUnbanned(e,t){this.validateTokenName(e,an);const n={action:"token_unbanned",tokenName:e,payload:t,broadcast:!0};await this.emitEvent(n)}async emitModeratorAdded(e,t,n=!1){this.validateTokenName(e,an);const r={action:"moderator_added",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitModeratorRemoved(e,t,n=!1){this.validateTokenName(e,an);const r={action:"moderator_removed",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitUserProfileUpdated(e,t){this.validateRequiredString(e,"userAddress","User Address");const n={action:"user_profile_updated",userAddress:e,payload:t};await this.emitEvent(n)}async emitSiteConfigChanged(e){const t={action:"site_config_changed",payload:e,broadcast:!0};await this.emitEvent(t)}async emitFeatureStatus(e){const t={action:"feature_status",payload:e,broadcast:!0};await this.emitEvent(t)}async emitEvent(e){this.validateRequiredString(e.action,"action","Event Action");const t=this.buildEndpoint("/v1/websocket",{});await this.http.post(t,e,this.getDualAuthHeaders())}async getConnectedClients(e){const t=this.buildEndpoint("/v1/connected-clients",{}),n={};void 0!==e?.room&&""!==e.room&&(n.room=e.room),void 0!==e?.tokenName&&(n.tokenName=e.tokenName),void 0!==e?.userAddress&&(n.userAddress=e.userAddress),void 0!==e?.userAddresses&&(n.userAddresses=e.userAddresses),void 0!==e?.authenticated&&(n.authenticated=e.authenticated),void 0!==e?.isOverseer&&(n.isOverseer=e.isOverseer),void 0!==e?.minConnectionSeconds&&(n.minConnectionSeconds=e.minConnectionSeconds),void 0!==e?.offset&&(n.offset=e.offset),void 0!==e?.limit&&(n.limit=e.limit);const r=await this.http.get(t,Object.keys(n).length>0?n:void 0,this.getDualAuthHeaders());return this.extractData(r)}async isUserOnline(e){this.validateRequiredString(e,"userAddress","User Address");const t=await this.getConnectedClients({userAddress:e,limit:1});if(0===t.clients.length)return{online:!1};const n=t.clients[0];return void 0===n?{online:!1}:{online:!0,socketId:n.socketId,rooms:n.rooms,connectedAt:n.connectedAt}}async getOnlineUsers(e){if(!Array.isArray(e)||0===e.length)throw new vt("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,an);const n={tokenName:e};void 0!==t?.authenticated&&(n.authenticated=t.authenticated),void 0!==t?.limit&&(n.limit=t.limit);const r=await this.getConnectedClients(n);return{clients:r.clients,count:r.summary.totalConnected,authenticatedCount:r.summary.authenticatedCount}}async getOnlineOverseers(){const e=await this.getConnectedClients({isOverseer:!0});return{clients:e.clients,count:e.summary.totalConnected}}async emitRecordingStatus(e,t){this.validateTokenName(e,an);const n={action:"recording_status",tokenName:e,payload:t};await this.emitEvent(n)}async emitRecordingsCountUpdated(e,t){this.validateTokenName(e,an);const n={action:"recordings_count_updated",tokenName:e,payload:t};await this.emitEvent(n)}async emitDownloadReady(e,t){this.validateTokenName(e,an);const n={action:"download_ready",tokenName:e,payload:t};await this.emitEvent(n)}}class Yk{constructor(e=0){this.defaultTtlMs=e,this.cache=new Map}get(e){const t=this.cache.get(e);if(t){if(!(void 0!==t.expiresAt&&Date.now()>t.expiresAt))return t.value;this.cache.delete(e)}}set(e,t,n){const r=n??this.defaultTtlMs,s={value:t};r>0&&(s.expiresAt=Date.now()+r),this.cache.set(e,s)}has(e){return void 0!==this.get(e)}delete(e){this.cache.delete(e)}clear(){this.cache.clear()}get size(){return this.cache.size}}async function Jk(e,t,n,r={}){const{logger:s,cacheNullish:i=!1,keyGenerator:o}=r,a=o?o(e):String(e),c=n.get(a);if(void 0!==c)return s&&s.debug(`Cache hit for key: ${a}`),c;s&&s.debug(`Cache miss for key: ${a}, fetching...`);const l=await t();return null!=l?(n.set(a,l),s&&s.debug(`Cached result for key: ${a}`)):i&&(n.set(a,l),s&&s.debug(`Cached nullish result for key: ${a}`)),l}class Qk extends sr{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 pS({maxAttempts:this.config.reconnectAttempts??5,baseDelayMs:this.config.reconnectDelay??2e3}),this.eventBuffer=new Yk(3e4),this.isSocketIOAvailable=this.checkSocketIOAvailability(),Qk.instances.add(this)}checkSocketIOAvailability(){try{return"function"==typeof a.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)=>{Ji(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:",at(e)),e}this.logger.debug("🔌 Connecting to Socket.IO server:",this.config.url),this.socket=a.io(this.config.url,{transports:["websocket"],reconnection:!0,reconnectionAttempts:this.config.reconnectAttempts??5,reconnectionDelay:this.config.reconnectDelay??2e3}),this.socket.on("connect",()=>{this.logger.debug("✅ Socket.IO connected successfully:",this.socket?.id),this.logger.debug("📡 Connected to bundle backend WebSocket:",this.config.url),this.logger.debug("🔗 Ready to monitor transaction updates"),this.reconnectionManager.reset(),e()}),this.socket.on("connect_error",e=>{this.logger.error("❌ Socket.IO connection error:",e),t(e)}),this.socket.on("disconnect",e=>{this.logger.debug(`🔌 Socket.IO disconnected: ${e}`),this.handleReconnect()}),this.socket.on("error",e=>{this.logger.error("❌ Socket.IO error:",e)}),this.socket.onAny((e,...t)=>{if(""!==e&&t.length>0&&"object"==typeof t[0]&&null!==t[0]){const n=t[0],r=n.status??n.Status;"string"==typeof r&&(this.logger.debug(`📡 [Event Buffer] Buffering event for ${e}: ${r}`),this.eventBuffer.size>=this.MAX_BUFFER_SIZE&&this.logger.warn(`📡 [Event Buffer] Buffer approaching limit (${this.eventBuffer.size}/${this.MAX_BUFFER_SIZE})`),this.eventBuffer.set(e,n))}this.debug&&this.logger.debug(`📡 [WebSocket Event] "${e}":`,JSON.stringify(t,null,2))}),this.hasOnAnyListener=!0},"Socket.IO connection failed",this.logger,e=>{this.logger.error("Socket.IO connection failed:",e);const n=ot(e)?e:new Error(at(e));throw t(n),n}).catch(t)})}async monitorTransaction(e,t){this.listeners.set(e,t),this.logger.debug(`📡 Starting to monitor transaction: ${e}`),this.logger.debug(`📡 WebSocket connected: ${String(this.socket?.connected??!1)}`);const n=this.eventBuffer.get(e);null!=n&&(this.logger.debug(`📡 [Event Buffer] Found buffered event for ${e}, delivering immediately`),setImmediate(()=>{this.processTransactionEvent(e,n,t)}),this.eventBuffer.delete(e));const r=this.config.timeout??3e5,s=setTimeout(()=>{if(this.listeners.has(e)){const n=Math.round(r/1e3),s={transactionId:e,status:exports.SDKTransactionStatus.TIMEOUT,message:`Transaction monitoring timeout - no response after ${n} seconds`,timestamp:Date.now()};this.logger.debug(`📡 Transaction timeout for ${e} (${n}s)`),t(s),this.listeners.delete(e),this.timeouts.delete(e),this.socket?.off(e)}},r);if(this.timeouts.set(e,s),this.socket?.connected)this.socket.off(e),this.logger.debug(`📡 Listening for transaction updates: ${e}`),this.logger.debug(`📡 WebSocket connection ID: ${String(this.socket.id)}`),this.logger.debug(`📡 WebSocket URL: ${this.config.url}`),this.socket.on(e,n=>{this.processTransactionEvent(e,n,t)});else{const n={transactionId:e,status:exports.SDKTransactionStatus.FAILED,message:"WebSocket not connected - cannot monitor transaction",timestamp:Date.now()};t(n),this.listeners.delete(e),this.timeouts.delete(e)}await Promise.resolve()}processTransactionEvent(e,t,n){this.logger.debug(`📡 Socket.IO transaction update for ${e}:`,JSON.stringify(t,null,2));const r=t,s=r?.data,i=r?.status??r?.Status??s?.status??s?.Status;let o=r?.message??r?.Message??s?.message??s?.Message??r?.error??s?.error;Kn(o)||(o=i===jw.FAILED||i===jw.ERROR?"Transaction failed - check transaction details":i===jw.COMPLETED||i===jw.PROCESSED||i===jw.SUCCESS?"Transaction completed successfully":null!=i?`Transaction status: ${String(i)}`:"Unknown transaction status");const a=r?.blockHash??s?.blockHash,c=r?.gasUsed??s?.gasUsed,l=r?.Data??s?.Data,u={transactionId:e,status:this.mapSocketStatus(i),message:"string"==typeof o?o:"Transaction update received",timestamp:Date.now(),...null!=a?{blockHash:a}:{},...null!=c?{gasUsed:c}:{},...null!=l?{data:l}:{}};if(this.logger.debug(`📡 Mapped status for ${e}: ${String(i)} -> ${u.status}`),this.logger.debug(`📡 Final message: "${String(o)}"`),n(u),u.status===exports.SDKTransactionStatus.COMPLETED||u.status===exports.SDKTransactionStatus.FAILED){this.listeners.delete(e);const t=this.timeouts.get(e);t&&(clearTimeout(t),this.timeouts.delete(e)),this.socket?.off(e),this.logger.debug(`📡 Cleaned up listener for ${e} (${u.status})`)}}async waitForTransaction(e){return new Promise((t,n)=>{this.monitorTransaction(e,e=>{e.status===exports.SDKTransactionStatus.COMPLETED?t(e):e.status!==exports.SDKTransactionStatus.FAILED&&e.status!==exports.SDKTransactionStatus.TIMEOUT||n(new Error(`Transaction ${String(e.status)}: ${e.message}`))})})}mapSocketStatus(e){const t=e?.toUpperCase();return Yw[t]??exports.SDKTransactionStatus.PENDING}async handleReconnect(){this.reconnectionManager.shouldRetry()?(this.reconnectionManager.recordAttempt(),this.logger.debug(`🔄 Attempting Socket.IO reconnect ${this.reconnectionManager.getStatusString()}`),setTimeout(()=>{this.socket&&!this.socket.connected&&this.socket.connect()},this.reconnectionManager.getNextDelay())):this.logger.error("❌ Socket.IO max reconnection attempts reached")}disconnect(){this.socket&&(this.listeners.forEach((e,t)=>{this.socket?.off(t)}),this.listeners.clear(),this.timeouts.forEach(e=>{clearTimeout(e)}),this.timeouts.clear(),this.eventBuffer.clear(),this.logger.debug("🧹 Cleared event buffer"),this.hasOnAnyListener&&(this.socket.offAny(),this.hasOnAnyListener=!1,this.logger.debug("🧹 Removed onAny debug listener")),this.socket.disconnect(),this.socket=null,this.logger.debug("🔌 Socket.IO disconnected")),Qk.instances.delete(this)}static cleanupAll(e=!1){for(const e of Qk.instances)e.disconnect();Qk.instances.clear()}isConnected(){return this.socket?.connected??!1}getSocket(){return this.socket}}Qk.instances=new Set;class Zk extends rr{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 yt("limit must be between 1 and 50","limit","INVALID_LIMIT");this.logger.debug("Fetching weekly challenge leaderboard",{limit:t});const n={limit:String(t)},r=await this.http.get(Qe.GET_LEADERBOARD,n),s=this.extractData(r);return this.logger.debug("Fetched weekly challenge leaderboard",{count:s.count}),{leaderboard:s}}async getTokenHistory(e){const{vaultAddress:t}=e;if("string"!=typeof t||""===t.trim())throw new yt("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)),r=await this.http.get(n),s=this.extractData(r);return this.logger.debug("Fetched token weekly history",{count:s.length}),{snapshots:s}}}class eT extends ir{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 tT extends eT{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 nT extends LE{constructor(e,t=!1){super(e,t,"WrappableTokenService"),this.cache=new tT(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())})`),Ji(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 Ji(async()=>{const e=await async function(e){const{cache:t,fetchFn:n,logger:r,itemTypeName:s="items"}=e;if(t.has()){const e=t.getAll();return r&&r.debug(`Returning ${e.length} cached ${s}`),{items:e,fetchedAt:t.getFetchTimestamp()??Date.now(),itemCount:e.length}}r&&r.debug(`Fetching all ${s} (no cache)`);const i=await n();try{t.setAll(i)}catch(e){r&&r.error("Cache operation failed (non-fatal):",e)}return{items:i,fetchedAt:Date.now(),itemCount:i.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=OE(e),n=this.cache.getByTokenId(t);return n||(await Jk("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=OE(e);await Jk("wrappable:check",()=>this.fetchAllWrappableTokens(),{get:()=>this.cache.has()?{}:void 0,set:()=>{}},{logger:this.logger});const n=this.cache.getByTokenId(t),r=void 0!==n,s={isWrappable:r,tokenId:t};return r&&(s.wrapCounterpart=n.wrapCounterpart),s}getCacheStats(){return this.cache.getStats()}clearCache(){this.cache.clear()}}class rT extends sr{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 tA(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 St("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",r=t?"unwrapToken()":"wrapToken()",s=t?"ALREADY_ON_ASSET_CHANNEL":"NOT_ON_ASSET_CHANNEL";throw new yt(`Cannot ${t?"wrap":"unwrap"} ${n.symbol} - it's ${e}. Use ${r} instead.`,"tokenId",s)}const r=await this.getCounterpartOrThrow(e.tokenId,n.symbol);return this.executeChannelBridge({sourceToken:n,destinationToken:r,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 St("tokenId","Token identifier");if(0===t.length)throw St("amount");const r=await this.getWrappableTokenOrThrow(e);if(n?"asset"===r.channel:"asset"!==r.channel){const e=n?"already on asset channel":"not on asset channel",t=n?"ALREADY_ON_ASSET_CHANNEL":"NOT_ON_ASSET_CHANNEL";throw new yt(`Cannot ${n?"wrap":"unwrap"} ${r.symbol} - it's ${e}`,"tokenId",t)}const s=this.determineChannelRouting(r,n);return{fee:"0",feeToken:"GALA",authorizationType:s.authType,feeChannel:s.sourceChannel}}async executeChannelBridge(e){const{sourceToken:t,destinationToken:n,amount:r,recipient:s,isWrap:i}=e;if(void 0===this.nativeSigner||void 0===this.walletAddress||0===this.walletAddress.length)throw new yt("Wallet required for wrap/unwrap operations. Initialize SDK with a private key.","wallet","WALLET_REQUIRED");const o=this.walletAddress,a=this.determineChannelRouting(t,i),c=`galaswap-operation-${Pv()}`,l={quantity:r,tokenInstance:{collection:t.galaChainDescriptor.collection,category:t.galaChainDescriptor.category,type:t.galaChainDescriptor.type,additionalKey:t.galaChainDescriptor.additionalKey,instance:"0"},destinationChainId:a.destinationChannelId,recipient:s??o,wrap:!0,uniqueKey:c};return this.logger.debug(`[WrapService] ${i?"Wrap":"Unwrap"} message (pre-signing)`,{amount:r,uniqueKey:c,sourceChannel:a.sourceChannel}),this.executeWrapBridgeRequest({sourceToken:t,destinationToken:n,amount:r,message:l,routing:a,isWrap:i,senderAddress:o})}async executeWrapBridgeRequest(e){const{sourceToken:t,destinationToken:n,amount:r,message:s,routing:i,isWrap:o}=e;try{const e=await this.nativeSigner.signObject("RequestTokenBridgeOut",s);this.logger.debug(`[WrapService] ${o?"Wrap":"Unwrap"} request (signed)`,{sourceToken:t.symbol,destinationToken:n.symbol,amount:r,channel:i.sourceChannel});const a=await this.galaConnectClient.requestBridgeOut(e);if(this.logger.debug("[WrapService] RequestBridgeOut response",{status:a.Status,hasData:"Data"in a}),function(e){return"object"==typeof e&&null!==e&&"Status"in e&&"number"==typeof e.Status&&1!==e.Status}(a)){const e=`Status=${a.Status}`,s="string"==typeof a.Message&&a.Message.length>0?`: ${a.Message}`:"";return{success:!1,fromToken:t.symbol,toToken:n.symbol,amount:r,fromChannel:i.sourceChannel,toChannel:o?"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}(a)){const e=a.Data;this.logger.debug("[WrapService] Step 1 complete, bridgeRequestId:",e);const s={bridgeFromChannel:i.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:r,fromChannel:i.sourceChannel,toChannel:o?"asset":n.channel??"music",error:`BridgeTokenOut failed: status=${String(c.Status)}`}:{success:!0,transactionId:c.Hash??e,fromToken:t.symbol,toToken:n.symbol,amount:r,fromChannel:i.sourceChannel,toChannel:o?"asset":n.channel??"music",completedAt:Date.now()}}return{success:!1,fromToken:t.symbol,toToken:n.symbol,amount:r,fromChannel:i.sourceChannel,toChannel:o?"asset":n.channel??"music",error:`Unexpected response format from GalaChain (type=${typeof a})`}}catch(e){const s=at(e);return this.logger.error(`[WrapService] ${o?"Wrap":"Unwrap"} operation failed:`,s),{success:!1,fromToken:t.symbol,toToken:n.symbol,amount:r,fromChannel:i.sourceChannel,toChannel:o?"asset":n.channel??"music",error:s}}}determineChannelRouting(e,t){if(t){return{sourceChannel:e.channel??"music",destinationChannelId:co.ASSET,authType:"cross_channel_authorization"}}return{sourceChannel:"asset",destinationChannelId:co.MUSIC,authType:"automatic"}}async getCounterpartOrThrow(e,t){const n=await this.wrappableTokenService.getWrapCounterpart(e);if(null==n)throw new yt(`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 yt(`Token not found or not wrappable: ${this.formatTokenId(e)}`,"tokenId","TOKEN_NOT_WRAPPABLE");return t}formatTokenId(e){return"string"==typeof e?e:io(e)}}class sT 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 iT{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 oT{constructor(e){this.bundleBaseUrl=fT(e.bundleBaseUrl),this.launchpadBaseUrl=fT(e.launchpadBaseUrl),this.signer=e.signer,this.walletAddress=e.walletAddress,this.requestor=e.httpRequestor??fetch.bind(globalThis),this.socketFactory=e.socketFactory??(e=>a.io(e,{transports:["websocket"]}))}async submit(e){let t;try{t=await this.signer.signTypedData(e.method,e.dto)}catch(e){if(e instanceof sT)throw e;const t=e instanceof Error?e.message:"Launchpad signing failed.";throw new sT(t,"LAUNCHPAD_SIGNING_FAILED",{chainMessage:t})}const n=function(e){return Object.fromEntries(Object.entries(e).filter(([e])=>"prefix"!==e))}(t),r=`${this.bundleBaseUrl}/bundle`,s=await this.requestor(r,{method:"POST",headers:{"content-type":"application/json","X-Wallet-Address":this.walletAddress},body:JSON.stringify({stringsInstructions:e.stringsInstructions,method:e.method,signedDto:n})}),i=await hT(s);if(!s.ok)throw cT(s.status,i,r);const o=function(e){if("string"==typeof e&&""!==e)return e;if(!gT(e))throw new sT("Bundler returned no bundle id.","INVALID_BUNDLE_RESPONSE");const t=e.data,n=e.bundleId;if("string"==typeof t&&""!==t)return t;if(gT(t)&&"string"==typeof t.bundleId&&""!==t.bundleId)return t.bundleId;if("string"==typeof n&&""!==n)return n;throw new sT("Bundler returned no bundle id.","INVALID_BUNDLE_RESPONSE")}(i),a=dT(e.dto,"uniqueKey");return new iT({bundleId:o,uniqueKey:a,method:e.method,wait:t=>this.waitForResult(e,o,t)})}async waitForResult(e,t,n={}){const r=n.timeoutMs??6e4,s=n.pollIntervalMs??2500,i=Date.now();let o,a,c=!1,l=new Promise(()=>{});try{o=this.socketFactory(this.bundleBaseUrl),l=new Promise((e,n)=>{a=t=>{const r=function(e){if(!gT(e))return;const t=e.status;return"PROCESSED"!==t&&"FAILED"!==t?void 0:{status:t,data:e.data}}(t);void 0===r||c||(c=!0,"FAILED"===r.status?n(aT(r.data)):e(r))},o?.on(t,a)})}catch{o=void 0}const u=this.pollConfirmation(e,t,i,r,s);try{return await Promise.race([l,u])}finally{c=!0,void 0!==o&&(void 0!==a&&o.off(t,a),o.disconnect())}}async pollConfirmation(e,t,n,r,s){const i="CreateSale"===e.method,o=i?function(e,t){const n=dT(t,"tokenName");return`${e}/v1/tokens/${encodeURIComponent(n)}`}(this.launchpadBaseUrl,e.dto):`${this.bundleBaseUrl}/bundle?id=${encodeURIComponent(t)}`;for(;Date.now()-n<=r;){const e=await this.requestor(o,{method:"GET"}),t=await hT(e);if(i){if(e.ok)return{status:"PROCESSED",data:uT(t)};if(404!==e.status&&202!==e.status)throw cT(e.status,t,o)}else{if(!e.ok)throw cT(e.status,t,o);const n=gT(t)?t.status:void 0;if("COMPLETED"===n||"PROCESSED"===n)return{status:"PROCESSED",data:t};if("FAILED"===n)throw aT(t)}const a=r-(Date.now()-n);if(a<=0)break;await pT(Math.min(Math.max(0,s),a))}throw new sT(`Timed out waiting for bundle ${e.dto.uniqueKey}`,"BUNDLE_CONFIRMATION_TIMEOUT",{details:{method:e.method}})}}function aT(e){const t=lT(e)??"Launchpad bundle failed on chain.";return new sT(t,"BUNDLE_FAILED",{chainMessage:t})}function cT(e,t,n){const r=lT(t)??`Bundle request failed with HTTP ${e}`;return new sT(r,"BUNDLE_REQUEST_FAILED",{status:e,chainMessage:r,details:{body:t,url:n}})}function lT(e){if("string"==typeof e&&""!==e)return e;if(gT(e))for(const t of["chainMessage","message","Message","error"]){const n=e[t];if("string"==typeof n&&""!==n)return n;if(gT(n)){const e=lT(n);if(void 0!==e)return e}}}function uT(e){return gT(e)?e.data??e.Data??e:e}function dT(e,t){const n=e[t];if("string"!=typeof n||""===n)throw new sT(`Missing ${t} in launchpad DTO.`,"INVALID_LAUNCHPAD_DTO");return n}async function hT(e){try{return await e.json()}catch{return e.text()}}function gT(e){return"object"==typeof e&&null!==e}function fT(e){return e.replace(/\/$/u,"")}function pT(e){return new Promise(t=>setTimeout(t,e))}function mT(e){const[t,n]=e.split("|",2);if("service"!==t||void 0===n)throw new Error(`Invalid vaultAddress format (expected service|<collection>$<category>$<type>$<additionalKey>$launchpad): ${e}`);const[r,s,i,o,a,...c]=n.split("$");if(void 0===r||void 0===s||void 0===i||void 0===o||"launchpad"!==a||c.length>0||""===r||""===s||""===i||""===o)throw new Error(`Invalid vaultAddress format (expected service|<collection>$<category>$<type>$<additionalKey>$launchpad): ${e}`);return{collection:r,category:s,type:i,additionalKey:o}}function yT(e){const{collection:t,category:n,type:r}=mT(e),s=`${t}$${n}$${r}$none`,i="GALA$Unit$none$none";return[`$service$${s}$launchpad`,`$tokenBalance$${s}$${e}`,`$tokenBalance$${s}$${e}`,`$tokenBalance$${i}$${e}`,`$tokenBalance$${i}$${e}`]}function bT(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 vT{constructor(e){this.transport=e.transport,this.walletAddress=e.walletAddress}createSale(e){!function(e){const t=Ys(e);!t.success&&t.errors&&Li(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??wT(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:bT(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 r={vaultAddress:t.vaultAddress,...n,extraFees:t.extraFees??{maxAcceptableReverseBondingCurveFee:"0"},uniqueKey:t.uniqueKey??wT(this.walletAddress)};return this.transport.submit({method:e,dto:r,stringsInstructions:yT(t.vaultAddress)})}}function wT(e){return`galaswap-operation-${r.v4()}-${Date.now()}-${e}`}class ET{constructor(e){this.gatewayBaseUrl=e.gatewayBaseUrl.replace(/\/$/u,""),this.signer=e.signer,this.walletAddress=NT(e.walletAddress),this.requestor=e.httpRequestor??fetch.bind(globalThis)}transfer(e){const t=AT(e),n={from:this.walletAddress,to:NT(e.to),quantity:e.quantity,tokenInstance:t,uniqueKey:e.uniqueKey??CT(this.walletAddress)};return this.direct("TransferToken",n)}burn(e){const t={tokenInstances:[{quantity:e.quantity,tokenInstanceKey:AT(e)}],uniqueKey:e.uniqueKey??CT(this.walletAddress)};return this.direct("BurnTokens",t)}lock(e){const t={lockAuthority:e.lockAuthority??this.walletAddress,tokenInstances:[{owner:this.walletAddress,quantity:e.quantity,tokenInstanceKey:AT(e)}],uniqueKey:e.uniqueKey??CT(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:AT(e)}],uniqueKey:e.uniqueKey??CT(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),r=`${this.gatewayBaseUrl}/api/asset/token-contract/${e}`,s=await this.post(r,n),i=await async function(e){try{return await e.json()}catch{return e.text()}}(s),o=IT(i);if(!s.ok||void 0!==o?.Status&&1!==o.Status)throw function(e,t,n){const r=IT(t),s=TT(r,"Message")??TT(r,"message")??TT(r,"ErrorKey")??`Gateway request failed with HTTP ${e}`,i=TT(r,"ErrorKey")??"GATEWAY_REQUEST_FAILED";return new sT(s,i,{status:e,chainMessage:s,details:{body:t,url:n}})}(s.status,i,r);const a=IT(ST(i))?.mode??o?.mode;if(void 0!==a&&"sync"!==a){throw new sT(`Unsupported gateway transaction mode: ${"string"==typeof a?a:"non-sync"}`,"INVALID_GATEWAY_RESPONSE",{status:s.status,details:{body:i,url:r}})}const c=ST(i),l=_T(s,"x-transaction-id")??kT(c)??kT(i),u=function(e){const t=_T(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!==u&&{blockNumber:u}}}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 sT)throw e;const t=e instanceof Error?e.message:"Native GalaChain signing failed.";throw new sT(t,"NATIVE_SIGNING_FAILED",{chainMessage:t})}}}function AT(e){const t=e.tokenClassKey??e.symbol;if(void 0===t)throw new sT("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,r,s,i]=e.split(t);if(void 0===n||void 0===r||void 0===s||void 0===i||[n,r,s,i].some(e=>""===e))throw new sT(`Invalid token class key: ${e}`,"INVALID_TOKEN_IDENTIFIER");return{collection:n,category:r,type:s,additionalKey:i}}(t);return{...n,instance:e.instance??"0"}}function ST(e){const t=IT(e);return t?.Data??t?.data??e}function kT(e){if("string"==typeof e&&""!==e)return e;const t=IT(e);return TT(t,"transactionId")??TT(t,"txnId")??TT(t,"id")}function TT(e,t){const n=e?.[t];return"string"==typeof n&&""!==n?n:void 0}function IT(e){return"object"==typeof e&&null!==e?e:void 0}function CT(e){return`galaswap-operation-${r.v4()}-${Date.now()}-${e}`}function NT(e){return"eth|0x"===e.slice(0,6).toLowerCase()?`eth|${e.slice(6)}`:e}function _T(e,t){const n=e.headers;if(void 0===n)return;if("function"==typeof n.get)return xT(n.get(t));const r=t.toLowerCase();for(const[e,t]of Object.entries(n))if(e.toLowerCase()===r)return xT(t)}function xT(e){const t=e?.trim();return void 0===t||""===t?void 0:t}function RT(e,t=3e4){return c.create({baseURL:e,timeout:t,headers:{"Content-Type":"application/json"}})}const BT=new Set(["accesstoken","refreshtoken","token","password","privatekey","secret","apikey","api_key","rawkey","authorization","x-api-key","bearer","streamadminapikey","userapikey","signature","signedpayload"]);function DT(e,t=0){if(t>5)return"[...]";if(null==e)return e;if(Array.isArray(e))return e.map(e=>DT(e,t+1));if(e instanceof Map){const n={};for(const[r,s]of e.entries()){const e=String(r);n[e]=BT.has(e.toLowerCase())?"[REDACTED]":DT(s,t+1)}return n}if("object"==typeof e){const n={};for(const[r,s]of Object.entries(e))n[r]=BT.has(r.toLowerCase())?"[REDACTED]":DT(s,t+1);return n}return e}class OT{constructor(e,t={}){this.auth=e,this.debug=t.debug??!1,this.logger=new Jt({debug:this.debug,context:"HttpClient"});const n=t.baseUrl??so("stage").launchpadBaseUrl,r=t.timeout??6e4;this.axios=RT(n,r),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 Ji(async()=>{const t={method:e.method,url:e.url,data:e.data,...void 0!==e.params&&{params:Ai(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]":DT(e.data);this.logger.debug("Request:",{method:e.method,url:e.url?.split("?")[0],baseURL:this.axios.defaults.baseURL,params:DT(t.params),data:n,isFormData:e.data instanceof FormData,contentType:t.headers?.["Content-Type"]??"not set"});const r=await this.axios.request(t),s=function(e){const t={};if(null==e||"object"!=typeof e)return t;for(const[n,r]of Object.entries(e))"string"==typeof r?t[n.toLowerCase()]=r:"number"!=typeof r&&"boolean"!=typeof r||(t[n.toLowerCase()]=String(r));return t}(r.headers);return this.logger.debug("Response:",{status:r.status,data:DT(r.data),transactionId:s["x-transaction-id"],blockNumber:s["x-block-number"]}),{data:r.data,headers:s,status:r.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 Ji(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,r={message:n?.message??at(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=r,this.logger.error("Backend error:",r)}else void 0!==t.request?this.logger.error("Network error:",t.message??"Unknown error"):this.logger.error("Request setup error:",t.message??"Unknown error");return Promise.reject(e instanceof Error?e:new Error(String(e)))})}cleanup(){void 0!==this.requestInterceptorId&&(this.axios.interceptors.request.eject(this.requestInterceptorId),this.requestInterceptorId=void 0),void 0!==this.responseInterceptorId&&(this.axios.interceptors.response.eject(this.responseInterceptorId),this.responseInterceptorId=void 0),this.logger.debug("Interceptors cleaned up")}}class MT extends Error{constructor(e,t){super(e),this.cause=t,this.name="WebSocketError"}}class LT 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 UT(e,t){if(Hn(e))throw new MT(`Invalid WebSocket response received for transaction ${t}: response is null or undefined`);if("object"!=typeof e)throw new MT(`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 MT(`Invalid WebSocket response received for transaction ${t}: missing status field`)}function PT(e,t,n,r){UT(e,t);const s=e,i=s.data??{};if(!function(e){if(Hn(e)||"object"!=typeof e)return!1;const t=e;return!(void 0!==t.inputQuantity&&"string"!=typeof t.inputQuantity||void 0!==t.outputQuantity&&"string"!=typeof t.outputQuantity||void 0!==t.totalFees&&"string"!=typeof t.totalFees||void 0!==t.vaultAddress&&"string"!=typeof t.vaultAddress)}(i))throw new MT(`Invalid trade data received for transaction ${t}`);const o={transactionId:t,type:n,method:"native"===r.type?"native":"exact",inputAmount:i.inputQuantity??r.amount,outputAmount:i.outputQuantity??r.expectedAmount??"0",totalFees:i.totalFees??"0",tokenName:r.tokenName,vaultAddress:i.vaultAddress??"",timestamp:Date.now()};return void 0!==s.blockHash&&(o.blockHash=s.blockHash),void 0!==s.gasUsed&&(o.gasUsed=s.gasUsed),void 0!==r.slippageToleranceFactor&&(o.slippageTolerance=r.slippageToleranceFactor),o}function FT(e,t,n){return{types:{EIP712Domain:$T(e),...t},primaryType:Object.keys(t)[0],domain:KT(e),message:n}}function $T(e){const t=[];return void 0!==e.name&&t.push({name:"name",type:"string"}),void 0!==e.version&&t.push({name:"version",type:"string"}),void 0!==e.chainId&&t.push({name:"chainId",type:"uint256"}),void 0!==e.verifyingContract&&t.push({name:"verifyingContract",type:"address"}),void 0!==e.salt&&t.push({name:"salt",type:"bytes32"}),t}function KT(e){const t={};return void 0!==e.name&&(t.name=e.name),void 0!==e.version&&(t.version=e.version),void 0!==e.chainId&&(t.chainId="bigint"==typeof e.chainId||"number"==typeof e.chainId?`0x${e.chainId.toString(16)}`:e.chainId),void 0!==e.verifyingContract&&(t.verifyingContract=e.verifyingContract),void 0!==e.salt&&(t.salt=e.salt),t}function GT(e){return`0x${Buffer.from(e,"utf8").toString("hex")}`}class HT{constructor(t){this.connectedAddress=null,this.provider=t,this.eventHandlers=function(t,n,r){if(null==t||"function"!=typeof t.on)return{accountsChanged:null,disconnect:null};const s=t=>{const r=t[0];n(void 0===r?null:e.getAddress(r))},i=()=>r();return t.on("accountsChanged",s),t.on("disconnect",i),{accountsChanged:s,disconnect:i}}(t,e=>{this.connectedAddress=e},()=>{this.connectedAddress=null})}removeEventListeners(){!function(e,t){if("function"!=typeof e.removeListener)return;null!==t.accountsChanged&&e.removeListener("accountsChanged",t.accountsChanged);null!==t.disconnect&&e.removeListener("disconnect",t.disconnect)}(this.provider,this.eventHandlers)}}async function WT(e,t,n){try{return await e()}catch(e){if(e instanceof eo)throw e;return t(e,n)}}const qT=4001,zT=4100,VT=4900,jT=4901;class XT extends HT{constructor(e){if(super(e),this.providerType="external",null==e)throw new eo("EIP-1193 provider is required",ji.INVALID_CONFIG)}handleProviderError(e,t){const n=e;if(n.code===qT)throw new eo(`User rejected ${t}`,ji.USER_REJECTED,e instanceof Error?e:void 0);if(n.code===zT)throw new eo("Wallet is not authorized",ji.NOT_CONNECTED,e instanceof Error?e:void 0);if(n.code===VT||n.code===jT)throw this.connectedAddress=null,new eo("Wallet disconnected",ji.NOT_CONNECTED,e instanceof Error?e:void 0);throw new eo(n.message??`${t} failed`,t.includes("sign")?ji.SIGNING_FAILED:ji.UNKNOWN,e instanceof Error?e:void 0)}ensureConnected(){if(!this.connectedAddress)throw new eo("Wallet is not connected. Call connect() first.",ji.NOT_CONNECTED)}async connect(){try{const t=await this.provider.request({method:"eth_requestAccounts"});if(null==t||0===t.length)throw new eo("No accounts returned from wallet",ji.CONNECTION_FAILED);const n=t[0];if(void 0===n)throw new eo("No accounts returned from wallet",ji.CONNECTION_FAILED);return this.connectedAddress=e.getAddress(n),this.connectedAddress}catch(e){if(e instanceof eo)throw e;return this.handleProviderError(e,"connect")}}async disconnect(){this.connectedAddress=null,this.removeEventListeners();try{await this.provider.request({method:"wallet_revokePermissions",params:[{eth_accounts:{}}]})}catch{}}isConnected(){return null!==this.connectedAddress}async signMessage(e){return this.ensureConnected(),WT(()=>async function(e,t,n){return e.request({method:"personal_sign",params:[GT(n),t]})}(this.provider,this.connectedAddress,e),(e,t)=>this.handleProviderError(e,t),"sign message")}async signTypedData(e,t,n){return this.ensureConnected(),WT(()=>async function(e,t,n,r,s){return e.request({method:"eth_signTypedData_v4",params:[t,JSON.stringify(FT(n,r,s))]})}(this.provider,this.connectedAddress,e,t,n),(e,t)=>this.handleProviderError(e,t),"sign typed data")}async getAddress(){await Promise.resolve(),this.ensureConnected();const e=this.connectedAddress;if(null==e)throw new eo("Wallet is not connected",ji.NOT_CONNECTED);return e}async getGalaAddress(){return`eth|${(await this.getAddress()).slice(2)}`}async getPrivateKey(){return Promise.reject(new eo("Private key is not accessible with external wallet providers. Use PrivateKeyProvider if you need private key access for @gala-chain operations.",ji.PRIVATE_KEY_NOT_ACCESSIBLE))}getProvider(){return this.provider}}function YT(e){return"privateKey"===e.providerType}function JT(e){if(e&&YT(e))return e.getWallet()}function QT(e){return"object"==typeof e&&null!==e&&"request"in e&&"function"==typeof e.request}class ZT{constructor(e){let n,r;e.walletProvider?(n=e.walletProvider,r=JT(e.walletProvider)):e.wallet&&(r=e.wallet,n=to.fromWallet(e.wallet)),this.wallet=r;const s=e.env??"prod",i=so(s);this.environment=s,this.config={baseUrl:e.launchpadBaseUrl??i.launchpadBaseUrl,gatewayBaseUrl:i.gatewayBaseUrl,bundleBaseUrl:i.bundleBaseUrl,webSocketUrl:i.webSocketUrl,gdexWebSocketUrl:i.gdexWebSocketUrl,dexApiBaseUrl:i.dexApiBaseUrl,dexBackendBaseUrl:i.dexBackendBaseUrl,launchpadFrontendUrl:i.launchpadFrontendUrl,timeout:3e4,debug:!1,...e};const o=e.signer??(void 0!==r?new tA(r.privateKey):void 0),a=e.walletAddress??e.galaChainAddress??(void 0!==r?`eth|${r.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}(o)),c=o??{signObject:()=>Promise.reject(new Error("A signer is required for token writes.")),signTypedData:()=>Promise.reject(new Error("A signer is required for launchpad writes."))},l=a??"",u=new oT({bundleBaseUrl:this.config.bundleBaseUrl,launchpadBaseUrl:this.config.baseUrl,signer:c,walletAddress:l,...void 0!==e.httpRequestor&&{httpRequestor:e.httpRequestor}});if(this.launchpad=new vT({transport:u,walletAddress:l}),this.tokens=new ET({gatewayBaseUrl:this.config.gatewayBaseUrl,dexBackendBaseUrl:this.config.dexBackendBaseUrl,signer:c,walletAddress:l,...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?ZT.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR:this.parseSlippageToleranceFactor(e.slippageToleranceFactor),this.maxAcceptableReverseBondingCurveFeeSlippageFactor=void 0===e.maxAcceptableReverseBondingCurveFeeSlippageFactor?ZT.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR:this.parseFeeSlippageFactor(e.maxAcceptableReverseBondingCurveFeeSlippageFactor),this.calculateAmountMode=e.calculateAmountMode??ZT.DEFAULT_CALCULATE_AMOUNT_MODE,this.galaChainAddressOverride=e.galaChainAddress,this.signerWalletAddress=e.walletAddress??(void 0===r?a:void 0),this.auth=new no({wallet:r,walletProvider:n,messagePrefix:"Create a GalaChain Wallet"}),this.jwtAuth=new Yi,void 0!==e.accessToken&&""!==e.accessToken){const t=e.accessTokenExpiresIn??86400;this.jwtAuth.setToken(e.accessToken,t)}this.http=new OT(this.auth,this.config),this.sessionAuth=new Zi(this.http,this.auth,this.jwtAuth,e.debug??!1),this.galaChainHttp=new OT(this.auth,{...this.config,baseUrl:this.config.gatewayBaseUrl}),this.bundleHttp=new OT(this.auth,{...this.config,baseUrl:this.config.bundleBaseUrl}),this.dexApiHttp=new OT(this.auth,{...this.config,baseUrl:this.config.dexApiBaseUrl}),this.dexBackendHttp=new OT(this.auth,{...this.config,baseUrl:this.config.dexBackendBaseUrl}),this.galaChainPublicAxios=RT(this.config.gatewayBaseUrl,this.config.timeout??3e4),this.cache=new or(e.debug??!1),this.launchpadService=new OS(this.http,this.jwtAuth),this.tokenResolverService=new Vk(this.launchpadService.poolService),this.launchpadAPI=new Wi(this.http,this.tokenResolverService,this.logger,this.bundleHttp,this.galaChainHttp,this.dexApiHttp,this.calculateAmountMode,this.launchpad),this.galaChainService=new fS(this.galaChainHttp,r,this.tokenResolverService,e.debug??!1,this.galaChainPublicAxios),this.dexService=new _A(this.dexBackendHttp,this.cache,this.galaChainService,e.debug??!1),this.bundleService=new cA(this.bundleHttp,this.tokenResolverService,this.config.debug??!1,r,r?this.getAddress():void 0,this.slippageToleranceFactor,this.maxAcceptableReverseBondingCurveFeeSlippageFactor),this.websocketService=new Qk({url:this.config.webSocketUrl},this.config.debug),this.priceHistoryService=new Ak(this.dexBackendHttp,this.config.debug??!1,this.tokenResolverService);const d=e.signer??(void 0===r?void 0:new tA(r.privateKey)),h=e.walletAddress??(void 0===r?void 0:this.getAddress());this.dexClient=new t.GSwap({env:this.environment,...void 0===d?{}:{signer:d},...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 nk(this.galaChainHttp),this.tradingQuotesService=new jk(this.http,e.debug??!1)}createOverrideSdk(t){if(!Kn(t))throw It("Invalid privateKey: must be a non-empty string","privateKey");if(!t.match(/^0x[a-fA-F0-9]{64}$/))throw It('Invalid privateKey format: must be "0x" followed by 64 hexadecimal characters',"privateKey");const n=new e.Wallet(t),r={...this.config,wallet:n};return new ZT(r)}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 St("wallet","Wallet");return this.wallet}setWallet(e){if(null==e||"object"!=typeof e||!("address"in e))throw new yt("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?JT(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:r,streamAdminApiKey:s,userApiKey:i,accessToken:o,headers:a,...c}=this.config;return{...c,...void 0!==s&&{streamAdminApiKey:"[REDACTED]"},...void 0!==i&&{userApiKey:"[REDACTED]"},...void 0!==o&&{accessToken:"[REDACTED]"},...void 0!==a&&{headers:Object.fromEntries(Object.keys(a).map(e=>[e,"[REDACTED]"]))},environment:this.environment,slippageToleranceFactor:this.slippageToleranceFactor,maxAcceptableReverseBondingCurveFeeSlippageFactor:this.maxAcceptableReverseBondingCurveFeeSlippageFactor,calculateAmountMode:this.calculateAmountMode,gasFee:zt.GAS_FEE}}getVersion(){return Jw}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),r=Math.min(t,100);return n.holders.slice(0,r).map((e,t)=>({...e,rank:t+1}))}async getHolderCount(e){const t=await this.fetchTokenDistribution(e);return{count:t.totalHolders,totalBalance:t.totalSupply}}async getHolderRank(e,t){const n=await this.fetchTokenDistribution(e),r=n.holders.findIndex(e=>e.address.toLowerCase()===t.toLowerCase());if(-1===r)return null;const s=n.holders[r];return void 0===s?null:{rank:r+1,balance:s.balance,holderCount:n.totalHolders}}async getHoldersByBalance(e,t){const n=await this.fetchTokenDistribution(e),r=t?.minBalance??0,s=t?.maxBalance??1/0,i=Math.min(t?.limit??100,1e3),o=new Map;return n.holders.forEach((e,t)=>{o.set(e.address,t+1)}),n.holders.filter(e=>{const t=parseFloat(e.balance);return t>=r&&t<=s}).map(e=>({...e,rank:o.get(e.address)??0})).slice(0,i)}async getHolderHistory(e,t,n=20){return this.getTrades({tokenName:e,userAddress:t,pageSize:Math.min(n,100)})}async fetchUserHolderContext(e,t){return this.launchpadService.fetchUserHolderContext(e,t)}async fetchTokenPrice(e){const{tokenName:t,tokenId:n}=e,{hasA:r}=Vn(e,"tokenName","tokenId",{description:"token identifier"});if(r&&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(ut(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=Vt((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: ${at(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(pt(e));const n=(await this.galaChainService.fetchPoolDetails({vaultAddress:t})).Data,r=await this.launchpadAPI.fetchPoolDetailsForCalculation(e);return n.currentSupply=r.currentSupply,n.reverseBondingCurveMaxFeeFactor=r.reverseBondingCurveMaxFeeFactor,n.reverseBondingCurveMinFeeFactor=r.reverseBondingCurveMinFeeFactor,n.reverseBondingCurveNetFeeFactor=r.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 vr}),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 Vw({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 $E(this.dexApiHttp,this.config.debug??!1)),this._bridgeableTokenService}getWrappableTokenService(){return this._wrappableTokenService??(this._wrappableTokenService=new nT(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 Tw({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 rT({galaConnectClient:this.getGalaConnectClient(),wrappableTokenService:this.getWrappableTokenService(),...e&&{walletAddress:this.getAddress(),wallet:e}})}return this._wrapService}getStreamingService(){return this._streamingService??(this._streamingService=new Pk(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._streamingService}getStreamChatService(){return this._streamChatService??(this._streamChatService=new kk(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._streamChatService}getBanService(){return this._banService??(this._banService=new CE(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._banService}getTokenBanService(){return this._tokenBanService??(this._tokenBanService=new zk(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._tokenBanService}getAIModerationService(){return this._aiModerationService??(this._aiModerationService=new oE(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._aiModerationService}getWeeklyChallengeService(){return this._weeklyChallengeService??(this._weeklyChallengeService=new Zk(this.http,this.config.debug??!1)),this._weeklyChallengeService}getOEmbedService(){return this._oembedService??(this._oembedService=new sk(this.http,this.config.debug??!1)),this._oembedService}getPlatformStatsService(){return this._platformStatsService??(this._platformStatsService=new Ek(this.http,this.config.debug??!1)),this._platformStatsService}getNotificationService(){return this._notificationService??(this._notificationService=new rk(this.http,this.config.debug??!1,this.jwtAuth)),this._notificationService}getClientConfigService(){return this._clientConfigService??(this._clientConfigService=new lA(this.http,this.config.debug??!1)),this._clientConfigService}getApiKeyService(){return this._apiKeyService??(this._apiKeyService=new yE(this.http,this.jwtAuth,this.config.debug??!1)),this._apiKeyService}getModeratorService(){return this._moderatorService??(this._moderatorService=new XS(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._moderatorService}getFlagService(){return this._flagService??(this._flagService=new IA(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._flagService}getOverseerService(){return this._overseerService??(this._overseerService=new bk(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._overseerService}getWebSocketAdminService(){return this._websocketAdminService??(this._websocketAdminService=new Xk(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._websocketAdminService}getContentReactionService(){return this._contentReactionService??(this._contentReactionService=new NA(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 vr}),n=t(e);if(void 0===n)throw new yt(`Invalid address format: "${e}". Expected formats: eth|0x..., 0x..., or client|...`);return n}getMessagesService(){return this._messagesService??(this._messagesService=new MS(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._messagesService}getRestrictedNamesService(){return this._restrictedNamesService??(this._restrictedNamesService=new Sk(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.userApiKey)),this._restrictedNamesService}getPlatformConfigService(){return this._platformConfigService??(this._platformConfigService=new wk(this.http,this.jwtAuth,this.config.debug??!1)),this._platformConfigService}getEventsBatcherService(){return this._eventsBatcherService??(this._eventsBatcherService=new RA(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 $k({url:this.config.streamWebSocketUrl},this.config.debug??!1)}return this._streamWebSocketService}getGdexStreamService(){return this._gdexStreamService??(this._gdexStreamService=new yS({url:this.config.gdexWebSocketUrl})),this._gdexStreamService}getStreamingEventService(){return this._streamingEventService??(this._streamingEventService=new Tk(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 r=await n.getPinnedMessage(e);return{tokenName:e,pinnedMessage:null===r.message?null:this.toLegacyPinnedMessage(r.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 vr}),n=t(e.address);if(void 0!==e.tokenId&&""!==e.tokenId){const{normalizeToTokenInstanceKey:t}=await Promise.resolve().then(function(){return ME}),r=t(e.tokenId),{collection:s,category:i,type:o,additionalKey:a}=r;return this.galaChainService.fetchTokenBalance({owner:n,collection:s,category:i,additionalKey:a,type:o,instance:"0"},e.withExpired??!1)}if(void 0!==e.tokenName&&""!==e.tokenName){const t=Xt(e.tokenName);if("MUSIC"===t||"GMUSIC"===t){const r=`$${t}`;return this.galaChainService.fetchTokenBalance({owner:n,collection:r,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 r=t.collection??"Token",s={collection:r,category:"Unit",type:t.symbol,additionalKey:"none"};return{quantity:t.balance,collection:r,category:"Unit",tokenId:io(s)}}throw St("tokenId or tokenName","Either tokenId or tokenName")}async fetchLockedBalance(e){const t=await this.fetchTokenBalance(e);if(!t)return null;const n="lockedHolds"in t||"lockedQuantity"in t;return{tokenId:t.tokenId,lockedQuantity:n?t.lockedQuantity??"0":"0",lockedHolds:n?t.lockedHolds??[]:[]}}async fetchAvailableBalance(e){const t=await this.fetchTokenBalance(e);if(!t)return null;const n="availableQuantity"in t;return{tokenId:t.tokenId,availableQuantity:n?t.availableQuantity??String(t.quantity):String(t.quantity),totalQuantity:String(t.quantity)}}async calculateBuyAmount(e){return this.launchpadAPI.calculateBuyAmount(e)}async calculateSellAmount(e){return this.launchpadAPI.calculateSellAmount(e)}async calculateBuyAmountLocal(e){return this.launchpadAPI.calculateBuyAmountLocal(e)}async calculateSellAmountLocal(e){return this.launchpadAPI.calculateSellAmountLocal(e)}async calculateBuyAmountExternal(e){return this.launchpadAPI.calculateBuyAmountExternal(e)}async calculateSellAmountExternal(e){return this.launchpadAPI.calculateSellAmountExternal(e)}async calculateBuyAmountForGraduation(e){return this.launchpadAPI.calculateBuyAmountForGraduation(e)}async graduateToken(e){const{tokenName:t,slippageToleranceFactor:n,maxAcceptableReverseBondingCurveFeeSlippageFactor:r,privateKey:s,calculateAmountMode:i,currentSupply:o}=e;let a=t;void 0===i&&void 0===o||(a={tokenName:t,...void 0!==i&&{calculateAmountMode:i},...void 0!==o&&{currentSupply:o}});const c=await this.calculateBuyAmountForGraduation(a),l={tokenName:t,amount:c.amount,type:"exact",expectedAmount:c.amount,maxAcceptableReverseBondingCurveFee:c.reverseBondingCurveFee,slippageToleranceFactor:this.slippageToleranceFactor};return void 0!==n&&(l.slippageToleranceFactor=n),void 0!==r&&(l.maxAcceptableReverseBondingCurveFeeSlippageFactor=r),void 0!==s&&(l.privateKey=s),await this.buy(l)}async calculateInitialBuyAmount(e){const t={nativeTokenQuantity:e};return this.launchpadAPI.calculateInitialBuyAmount(t)}async buy(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...r}=e;return t.buy(r)}this.validateWallet(),await this.ensureWebSocketConnection();const t=(await this.bundleService.buyToken(e)).data,n=t?.transactionId;if(void 0===n||""===n)throw Ct("No transaction ID returned from buy operation");return this.waitForConfirmation(n,t=>PT(t,n,"buy",e))}async sell(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...r}=e;return t.sell(r)}this.validateWallet(),await this.ensureWebSocketConnection();const t=(await this.bundleService.sellToken(e)).data,n=t?.transactionId;if(void 0===n||""===n)throw Ct("No transaction ID returned from sell operation");return this.waitForConfirmation(n,t=>PT(t,n,"sell",e))}async getBundlerTransactionResult(e){return this.bundleService.getBundlerTransactionResult(e)}async launchToken(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...r}=e;return t.launchToken(r)}this.validateWallet(),await this.ensureWebSocketConnection();const t=await this.launchpadAPI.launchToken(e);return this.waitForConfirmation(t,n=>{UT(n,t);const r=n.data??{};if(!function(e){if(Hn(e)||"object"!=typeof e)return!1;const t=e;return!(void 0!==t.vaultAddress&&"string"!=typeof t.vaultAddress||void 0!==t.tokenStringKey&&"string"!=typeof t.tokenStringKey||void 0!==t.creatorAddress&&"string"!=typeof t.creatorAddress)}(r))throw new MT(`Invalid launch data received for transaction ${t}`);const s={transactionId:t,vaultAddress:r.vaultAddress??"",tokenStringKey:r.tokenStringKey??"",tokenName:e.tokenName,tokenSymbol:e.tokenSymbol,creatorAddress:r.creatorAddress??this.getAddress(),timestamp:Date.now(),...void 0!==n.blockHash&&""!==n.blockHash?{blockHash:n.blockHash}:{},...void 0!==n.gasUsed?{gasUsed:n.gasUsed}:{}};return"string"==typeof e.tokenImage&&(s.tokenImage=e.tokenImage),void 0!==e.preBuyQuantity&&(s.preBuyQuantity=e.preBuyQuantity),""!==s.vaultAddress&&this.tokenResolverService.set(e.tokenName,s.vaultAddress),s})}async uploadTokenImage(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...r}=e;return t.uploadTokenImage(r)}return this.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 vr}),n=t(e)??this.getAddress();return this.launchpadService.fetchProfile(n)}async fetchReferralUrl(){this.validateWallet();const e=this.getAddress();return await this.dexApiHttp.get(v,void 0,{"x-wallet-address":e})}async fetchReferrals(e){const t=await this.resolveReferralAddress(e?.address),n=e?.page??1,r=e?.limit??10,s={pageNumber:n,limit:r,sortBy:e?.sortBy??"joined",sortDir:e?.sortDir??"desc"},i=await this.dexApiHttp.get(w,s,{"x-wallet-address":t});if(!Array.isArray(i))throw new bt("Unexpected API response: expected array, got "+typeof i);return{referrals:i,page:n,limit:r,hasMore:i.length===r}}async fetchAllReferrals(e){const t=await _E((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(E,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 vr}),n={...e,address:t(e.address)};if(void 0!==n.privateKey&&""!==n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...r}=n;return e.updateProfile(r)}return this.validateWallet(),this.launchpadService.updateProfile(n)}async uploadProfileImage(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return vr}),n={...e,address:t(e.address)??this.getAddress()};if(void 0!==n.privateKey&&""!==n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...r}=n;return e.uploadProfileImage(r)}return this.validateWallet(),this.launchpadService.uploadProfileImage(n)}async fetchTokensHeld(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return vr}),n=t(e?.address)??this.getAddress(),r={pageSize:e?.pageSize??10,address:n,...void 0!==e?.cursor?{cursor:e.cursor}:{}};return void 0!==e?.tokenName&&""!==e.tokenName&&(r.tokenName=e.tokenName),void 0!==e?.search&&""!==e.search&&(r.search=e.search),this.launchpadService.fetchTokensHeld(r)}async fetchTokensCreated(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return vr}),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 vr}),n={...e,recipientAddress:t(e.recipientAddress)};if(void 0!==n.privateKey&&""!==n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...r}=n;return e.transferGala(r)}return this.validateWallet(),this.galaChainService.transferGala(n)}async transferToken(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return vr}),n={...e,to:t(e.to)};if(void 0!==n.privateKey&&""!==n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...r}=n;return e.transferToken(r)}return this.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 vr});return{...e,lockAuthority:t(e.lockAuthority)}}return e})),n={...e,tokens:t};if(void 0!==n.privateKey&&""!==n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...r}=n;return e.lockTokens(r)}return this.validateWallet(),this.galaChainService.lockTokens(n)}async unlockTokens(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...r}=e;return t.unlockTokens(r)}return this.validateWallet(),this.galaChainService.unlockTokens(e)}async burnTokens(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...r}=e;return t.burnTokens(r)}return this.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{On(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=In("string"==typeof e||"number"==typeof e?e:String(e),ZT.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR);return t<0||t>1?(this.logger.warn(`Invalid slippage tolerance factor: ${String(e)}, using default: ${ZT.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR}`),ZT.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR):t}parseFeeSlippageFactor(e){const t=In("string"==typeof e||"number"==typeof e?e:String(e),ZT.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: ${ZT.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR}`),ZT.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR):t}async ensureWebSocketConnection(){this.websocketService.isConnected()||(await this.websocketService.connect(),this.logger.debug("WebSocket connection established"))}async waitForConfirmation(e,t){this.logger.debug(`Waiting for confirmation of transaction: ${e}`);try{const n=await this.websocketService.waitForTransaction(e);if(n.status!==exports.SDKTransactionStatus.COMPLETED)throw new LT(e,n.status,n.message);let r;try{r=t(n)}catch(t){if(t instanceof MT)throw t;throw new MT(`Failed to transform WebSocket response for transaction ${e}`,ot(t)?t:new Error(at(t)))}return this.logger.debug(`Transaction confirmed: ${e}`,r),r}catch(t){if(this.logger.error(`Transaction confirmation failed: ${e}`,t),t instanceof LT||t instanceof MT)throw t;throw new MT(`WebSocket confirmation failed for transaction ${e}`,ot(t)?t:new Error(at(t)))}}async warmCacheFromPools(e){if(void 0===e||!Array.isArray(e))return;const{extractMetadataFromPoolData:t,isValidPoolForCaching:n}=await Promise.resolve().then(function(){return QI});e.forEach(e=>{if(!n(e))return;const r=t(e,this.logger);r&&this.launchpadAPI.warmCacheFromPoolData(e.tokenName,r)})}connectWebSocket(){this.websocketService.connect()}disconnectWebSocket(){this.websocketService.disconnect()}isWebSocketConnected(){return this.websocketService.isConnected()}subscribeToEvent(e,t){const n=this.websocketService.getSocket();return n?(n.on(e,t),()=>{n.off(e,t),this.logger.debug(`Unsubscribed from event: "${e}"`)}):(this.logger.warn(`⚠️ WebSocket not connected - subscribing to "${e}" without connection`),()=>{})}onLaunchpadTokenCreation(e,t){const n=1e3,r=Math.max(t?.intervalMs??3e4,n);null!=t?.intervalMs&&t.intervalMs<n&&this.logger.warn(`Poll interval ${t.intervalMs}ms is below minimum 1000ms. Using minimum interval instead.`);const s=t?.creatorAddress,i=new Map;let o=!0,a=null;let c=0;const l=async()=>{if(o){try{const t=await this.fetchPools({type:"recent",pageSize:20});c>0&&(this.logger.debug("Successfully recovered from polling errors"),c=0),t.items.forEach(t=>{i.has(t.tokenName)||((e=>{if(i.set(e,!0),i.size>1e3){const e=i.keys().next().value;void 0!==e&&i.delete(e)}})(t.tokenName),void 0!==s&&""!==s&&t.creatorAddress!==s||e(t))})}catch(e){c++;const t=at(e);c>=5?this.logger.error(`Polling for new launchpad tokens failed ${c} consecutive times. Last error: ${t}. Continuing to retry...`):c>1?this.logger.warn(`Error polling for new launchpad tokens (attempt ${c}/5): ${t}`):this.logger.debug(`Error polling for new launchpad tokens: ${t}`)}if(o){const e=Math.min(Math.max(c-1,0),2),t=r*Math.pow(2,e);a=setTimeout(()=>{l()},t)}}};return l(),()=>{o=!1,a&&clearTimeout(a),this.logger.debug("Stopped watching for launchpad token creation")}}matchesCreatorFilter(e,t){return void 0===t||""===t||e.creatorAddress===t}subscribeToTokenCreations(e,t){if(this.logger.debug("Subscribing to token creation broadcasts"+(void 0!==t?.creatorFilter&&""!==t.creatorFilter?` (filter: ${t.creatorFilter})`:"")),null===this.websocketService||void 0===this.websocketService)throw It("WebSocket service not initialized. Ensure websocketUrl is configured and the service is connected.","websocketService");let n=!1,r=null;const s=(n,...r)=>{try{if(r.length>0&&"object"==typeof r[0]&&null!==r[0]){const n=r[0].data;if(void 0!==n?.Data&&null!==n.Data&&"object"==typeof n.Data){const r=n.Data;if("CreateSale"===r.functionName){const n={tokenName:""!==r.tokenName?r.tokenName:"",symbol:""!==r.symbol?r.symbol:"",creatorAddress:""!==r.creatorAddress?r.creatorAddress:"",description:""!==r.description?r.description:"",image:""!==r.image?r.image:"",vaultAddress:""!==r.vaultAddress?r.vaultAddress:"",tokenStringKey:""!==r.tokenStringKey?r.tokenStringKey:"",preBuyQuantity:""!==r.initialBuyQuantity?r.initialBuyQuantity:"0",websiteUrl:""!==r.websiteUrl?r.websiteUrl:"",telegramUrl:""!==r.telegramUrl?r.telegramUrl:"",twitterUrl:""!==r.twitterUrl?r.twitterUrl:"",instagramUrl:""!==r.instagramUrl?r.instagramUrl:"",facebookUrl:""!==r.facebookUrl?r.facebookUrl:"",redditUrl:""!==r.redditUrl?r.redditUrl:"",tiktokUrl:""!==r.tiktokUrl?r.tiktokUrl:"",isFinalized:!1!==r.isFinalized&&null!==r.isFinalized&&void 0!==r.isFinalized&&r.isFinalized};this.matchesCreatorFilter(n,t?.creatorFilter)&&e(n)}}}}catch(e){this.logger.warn(`Error processing token creation broadcast: ${at(e)}`)}};let i=this.websocketService.getSocket();if(i)i.onAny(s),n=!0,this.logger.debug("Token creation broadcast listener registered");else{this.logger.debug("WebSocket not yet connected, initiating connection..."),this.websocketService.connect().catch(e=>{const n=new Error(`WebSocket connection failed: ${at(e)}`);this.logger.warn("Failed to establish WebSocket connection:",e),t?.onError&&t.onError(n)});let e=0;const o=()=>{if(i=this.websocketService.getSocket(),!i&&e<ZT.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS)return e++,void(r=setTimeout(()=>o(),ZT.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS));if(!i&&e>=ZT.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS){const e=new Error(`WebSocket not available after ${ZT.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS*ZT.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS}ms`);return this.logger.warn("Token creation broadcast subscription timeout:",e.message),void(t?.onError&&t.onError(e))}i&&(i.onAny(s),n=!0,this.logger.debug("Token creation broadcast listener registered"))};o()}return()=>{try{if(null!==r&&(clearTimeout(r),r=null,this.logger.debug("Cleared token creation broadcast polling timeout")),!n)return void this.logger.debug("Cleanup called before listener registration - no action needed");const e=this.websocketService.getSocket();e&&(e.offAny(s),n=!1,this.logger.debug("Stopped listening to token creation broadcasts"))}catch(e){this.logger.warn("Error removing token creation listener:",e)}}}getNftCollectionClaimFee(){return this.nftCollectionService.getCollectionClaimFee()}getNftTokenClassCreateFee(){return this.nftCollectionService.getTokenClassCreateFee()}estimateNftMintFee(e){return this.nftCollectionService.estimateMintFee(e)}estimateNftOperationFees(e){return this.nftCollectionService.estimateNftOperationFees(e)}claimNftCollection(e){return this.nftCollectionService.claimCollection(e)}fetchNftCollections(e){return this.nftCollectionService.fetchUserCollections(e)}isNftCollectionAvailable(e){return this.nftCollectionService.isCollectionAvailable(e)}createNftTokenClass(e){return this.nftCollectionService.createTokenClass(e)}fetchNftTokenClasses(e){return this.nftCollectionService.fetchTokenClasses(e)}mintNft(e){return this.nftCollectionService.mintNft(e)}fetchNftBalances(e,t){return this.nftCollectionService.fetchNftBalances(e,t)}async cleanup(){try{if(this.logger.debug("Starting cleanup..."),void 0!==this._eventsBatcherService)try{await this._eventsBatcherService.shutdown(5e3),this._eventsBatcherService=void 0}catch(e){this.logger.warn("Error during events shutdown:",e)}this.http.cleanup(),null!==this.websocketService&&void 0!==this.websocketService&&this.websocketService.disconnect(),void 0!==this._streamWebSocketService&&(this._streamWebSocketService.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..."),Qk.cleanupAll(e),t.debug("Global cleanup completed")}}function eI(){const e=globalThis;return e.process?.env??{}}ZT.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR=.15,ZT.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR=.01,ZT.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY=zt.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY,ZT.DEFAULT_CALCULATE_AMOUNT_MODE=it.LOCAL,ZT.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS=30,ZT.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS=100;let tI=0;class nI{constructor(){this.utilityInstance=!0,this.utilityInstance}static generateWallet(){try{const t=e.Wallet.createRandom();if(null===t.mnemonic?.phrase||void 0===t.mnemonic?.phrase||""===t.mnemonic.phrase)throw St("mnemonic","Mnemonic phrase");const n=nI.toGalaAddress(t.address);return{privateKey:t.privateKey,address:t.address,galaAddress:n,mnemonic:t.mnemonic.phrase,wallet:new e.Wallet(t.privateKey)}}catch(t){if("test"===eI().NODE_ENV){const t=`test-wallet-${Date.now()}-${++tI}`,n="0x"+Buffer.from(t).toString("hex").padStart(64,"1").slice(0,64),r=new e.Wallet(n),s=nI.toGalaAddress(r.address);return{privateKey:r.privateKey,address:r.address,galaAddress:s,mnemonic:"test test test test test test test test test test test junk",wallet:r}}throw t}}static fromPrivateKey(t){const n=new e.Wallet(t),r=nI.toGalaAddress(n.address);return{privateKey:n.privateKey,address:n.address,galaAddress:r,mnemonic:"",wallet:n}}static fromMnemonic(t,n=0){try{const r=e.Mnemonic.fromPhrase(t),s=e.HDNodeWallet.fromMnemonic(r,`m/44'/60'/0'/0/${n}`),i=new e.Wallet(s.privateKey),o=nI.toGalaAddress(i.address);return{privateKey:i.privateKey,address:i.address,galaAddress:o,mnemonic:t,wallet:i}}catch(r){if("test"===eI().NODE_ENV){const r=`test-mnemonic-index-${n}-${t}`,s="0x"+Buffer.from(r).toString("hex").padStart(64,"1").slice(0,64),i=new e.Wallet(s),o=nI.toGalaAddress(i.address);return{privateKey:i.privateKey,address:i.address,galaAddress:o,mnemonic:t,wallet:i}}throw r}}static toGalaAddress(t){const n=dr(t);if(!/^[a-fA-F0-9]{40}$/.test(n))throw kt("address","a valid Ethereum address (40 hex characters)");return`eth|${e.getAddress(`0x${n}`).slice(2)}`}static toEthereumAddress(e){try{return gr(e)}catch(t){const n=at(t);if(n.includes("required")||!e?.startsWith("eth|"))throw St("galaAddress","Gala address starting with eth|");if(n.includes("Invalid backend"))throw kt("galaAddress","Gala format (eth|{40-hex-chars})");throw t}}static isValidEthereumAddress(e){try{const t=dr(e);return/^[a-fA-F0-9]{40}$/.test(t)}catch{return!1}}static isValidGalaAddress(e){return""!==e&&"backend"===br(e)}static generateMultipleWallets(e=1){On(e,1,100,"count");const t=[];if("test"===eI().NODE_ENV)for(let n=0;n<e;n++){const e=`test-multi-${n}-${Date.now()}-${++tI}`,r="0x"+Buffer.from(e).toString("hex").padStart(64,"1").slice(0,64);t.push(nI.fromPrivateKey(r))}else for(let n=0;n<e;n++)t.push(nI.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 rI(e){if(void 0===e)return nI.generateWallet();const t=e.trim();if(!Kn(t))throw kt("input","a non-empty string");if(function(e){const t=dr(e);return/^[a-fA-F0-9]{64}$/.test(t)}(t))return nI.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 nI.fromMnemonic(t);throw kt("input","a private key (64 hex characters) or mnemonic (12/24 words)","Wallet input")}let sI=null;async function iI(){if(!1===sI)return null;try{const e=["@gala-chain","connect"].join("/"),t=await import(e);return sI=!0,t}catch{return sI=!1,null}}class oI{constructor(e){if(this.providerType="external",this.connectedAddress=null,!e)throw new eo("@gala-chain/connect client is required",ji.INVALID_CONFIG);if("function"!=typeof e.signMessage)throw new eo("Invalid @gala-chain/connect client: signMessage method is required",ji.INVALID_CONFIG);this.client=e}static async createBrowserClient(e){const t=await iI();if(null==t)throw new eo("Failed to create BrowserConnectClient: @gala-chain/connect is not installed. Install it with: npm install @gala-chain/connect",ji.PROVIDER_NOT_AVAILABLE);const{BrowserConnectClient:n}=t,r=n,s=e?new r(e):new r;return new oI(s)}static async createTrustWalletClient(){const e=await iI();if(null==e)throw new eo("Failed to create TrustWalletConnectClient: @gala-chain/connect is not installed. Install it with: npm install @gala-chain/connect",ji.PROVIDER_NOT_AVAILABLE);const{TrustWalletConnectClient:t}=e,n=new t;return new oI(n)}static async isAvailable(){return null!==await iI()}ensureConnected(){if(null===this.connectedAddress||void 0===this.connectedAddress)throw new eo("Wallet is not connected. Call connect() first.",ji.NOT_CONNECTED);return this.connectedAddress}async connect(){try{if("function"==typeof this.client.connect){const t=await this.client.connect();if(null!=t&&t.length>0)return this.connectedAddress=e.getAddress(t),this.connectedAddress}if("function"==typeof this.client.getAccount){const t=await this.client.getAccount();if(null!=t&&t.length>0)return this.connectedAddress=e.getAddress(t),this.connectedAddress}throw new eo("Failed to connect: no account returned",ji.CONNECTION_FAILED)}catch(e){if(e instanceof eo)throw e;const t=e instanceof Error?e.message:String(e);if(t.length>0&&(t.includes("rejected")||t.includes("denied")))throw new eo("User rejected connection",ji.USER_REJECTED,e instanceof Error?e:void 0);throw new eo("Failed to connect to wallet",ji.CONNECTION_FAILED,e instanceof Error?e:void 0)}}async disconnect(){"function"==typeof this.client.disconnect&&await this.client.disconnect(),this.connectedAddress=null}isConnected(){return null!==this.connectedAddress}async signMessage(e){this.ensureConnected();try{return await this.client.signMessage(e)}catch(e){const t=e instanceof Error?e.message:String(e);if(t.includes("rejected")||t.includes("denied"))throw new eo("User rejected signing",ji.USER_REJECTED,e instanceof Error?e:void 0);throw new eo("Failed to sign message",ji.SIGNING_FAILED,e instanceof Error?e:void 0)}}signTypedData(e,t,n){return Promise.reject(new eo("signTypedData is not supported by GalaChainConnectProvider. Use ExternalWalletProvider with the underlying EIP-1193 provider instead.",ji.SIGNING_FAILED))}async getAddress(){return await Promise.resolve(),this.ensureConnected()}async getGalaAddress(){return`eth|${(await this.getAddress()).slice(2)}`}getPrivateKey(){return Promise.reject(new eo("Private key is not accessible with @gala-chain/connect. Use PrivateKeyProvider if you need private key access.",ji.PRIVATE_KEY_NOT_ACCESSIBLE))}getClient(){return this.client}}const aI={METAMASK:"io.metamask",METAMASK_FLASK:"io.metamask.flask",COINBASE:"com.coinbase.wallet",TRUST_WALLET:"com.trustwallet.app",PHANTOM:"app.phantom",RAINBOW:"me.rainbow",OKX:"com.okex.wallet",RABBY:"io.rabby",BRAVE:"com.brave.wallet",FRAME:"sh.frame",LEDGER:"com.ledger",ZERION:"io.zerion.wallet",GALA:"com.gala.wallet"},cI={[aI.METAMASK]:"data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjQiIGhlaWdodD0iMjQiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0iTTIxLjU0IDQuMjJsLTguMzQgNi4yMSAxLjU0LTMuNjUtLTUuNTMtMi41MXoiIGZpbGw9IiNFMjc2MUIiLz48L3N2Zz4=",[aI.GALA]:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACkAAAApCAYAAACoYAD2AAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAjWSURBVHgBzZkLVI1ZG8f/pZKjq0uK0LglIiMKU5EuBkMxUgmjL6GFSZJ7QpJx+Ujpk1Eat3KJySXjTnIpVJRPhnTSxWVaSveL1Zlnv3WshnM67wlrzX+t3T5nv3vv99d+9/O8z36OAj5DIpGoM1W2VPSp6FJp03ipmkoRlVwq9xUUFDLwGVKCnCKwAVRNqa2rc8vOLeiRkpqpcO/hY7woeI3yikrUva9DG1VV6HXqiJHDv0Uvg66oqa0VqigrX6dxUQScCDmlwLcjwfWjKuhJdq5jVMwpxMRfQP7LN7zGttPWxARbC3i4OsDCzOQuNQUS7GnwlExIgmtH1ea0zCfugdsjFeMvJLI2tFSmA/sieMV82Fqa/UFfvQhWKGuMggzAYfX19dHBYdGGm8MPoKy8El9Knm4OWO83L6+DtmaAkpLSPrQEkgDH5eQVnnTxWqVyN/3/+Brqrq+H+H1bMdCo13pa0QDIA0mAM4R5hbu/d/MW/Pn8Bb6mdHXa42hEMCyGmqwh0EDwgSRAq5wXBZfsXBcqP88tAF+1VlGBj6crvunWGf5bIvCm6C3vsZoaarh6NByDjA0XEWgImoMkwG7FpWXJ5uPddZ/l5IGPVJSV4OJgj83+P0OnvTbXVkp7d2NIFGJPXSTX9IrXPHqdOiDp5J66b7p1sSDQlKbXFD/qG7g1/ABvQAd7K9w6HYXoHQHQUBNg0679WBTwXzKwcmxatQDX4nbT6k4D3VTmXC9fF2G230Zl+niEFksgsRNdmJKS9kik0MVMZrGY5Cm6k5ohEiv8t+MiA3OHD9cFPa1EO6OOiIpLSrnrtH1EP3mvFSnqm8ucOzg0mg1Z15RNoQlkhtXkucZJKelS/1vTAQ0+zsZyKPf9wvVk+ARsR1a2UGJ/Zr0L3Z3gPdsVrVopIutZLhas3oIrSXel3oM99swrMSXamhp96An8xdoUGwFtL95Ilgqor6eDvVtWIyUhGrZWZriZ8gAWjp4YO91bKiBTbv5LLAnciX6jpuJg3Dn07dUdl2LDcO5gCHM7Esewx74r+rgWffxJ3Cbekx6795+QejMbSzOMthzC7a3id6XYfzwBd1IzwVdPaY/P9F6LQXZuSLhyC+aD+2PqBFu0UlSU2P8AzV9ZWe0j/q5Aq6hWU1NbqNnXWr227v0nA9b4eNBq5eL2vQz8/B9nLJ7bYAhXb9/H4rXb8eDRU8irbl100ZE8wQLaCu4+6yX2uUIuadQIU0u6VxL7V4bEJVyWCMjE/F5seBBUVVvDb8NO9Bw+CcfOXIb1cFOknT+IqG3+0OnQDnxl0LUzAhbPRsrZfRg5bLDUfldu3WPVGPaHQdqkZjyRNfcHCxPSPnOetxL2rgvwPDcfs5x/QOr5/dyKqwkawkmHMSNxM34vlnrN+OB+BAJVrg/r6+48QaZbOnnuGqsMxZCmj58KIa8u3biL/tYumLN0I9oS3FrfOXhw6RAST+zBycjN5AmM0Fm3A1RUlOHqaM+tOutTXV0Lv8AQFL76q9n5CxquW4gh2wnz+b0VPlZ48DKU09vFmGBD9saiE72HKV7kjMPQ6kfEJVzlgA+FBaJrZx3s+DUG/aydsS3isMy5S96VoaysQo9sRoNF5uqv3hShJWL79XD4BpwjqMXrdmDPod+51bv/IAthQX5wHDsKAtrL56/dwdKgUGQ8fibX/BVV1VBXbytgK6laVlGFlmj2kiCcuZSEsaNH4PH1o7SKg5jrQPatE5g2aQz+JK8wxXMZ50/lBWSqe88ZszKDrNGiKKQlYlHSxFm+8F3XELj062NAlq4NbS0NRB89A8tJc3CiwQBapDb0FEhVDLLYQF8Xn6N7Dz8Nip8J81FR2bInxMSsX0NdjS1lKYMU9unRDf82ddHtyMLADIKtZZDJvb8wZDFZJjOWz5FJv96s4hw4g7xm/d1QmYO6UpDBR4l30tBjmCPu01lcmvR0OkBdrW2z84y35Vxkihgyy9LMJL9jey2JndneYjofE4oNy7zQjoyiObFVfFdWLvFaa3Lsc6Y74tG1WIIUUOAh+fzE9uOIISwHgSMcJHvmVI54uEyUOCAoZB/3GnxR+BorF85C+oWDcJ5oB3ll0r83kn7/Fbs3rUB9vQgrN4WDDnoS+7LMx0Cj3snEVchBNraHzXT6oUbaI2ABhdFIJ2ym4wGLXmKYA6eYsGd3fciSloY6Qjcswd2z0RhMQfOZi0noNWIyNoX9JjXJ4DXjR1ZtFX/nIFkWgQLS05PpDSFNNTV1WB68C8Y2rkhMTsOYUcOQTJFMgK+n1MP7NMcxeJoUh/mznOj0WAwb5/mY6O6LktIyqfcZYNQTThNs2YaOF7c1PT50p/2Ubmg5RavobQlkaabTODpKLCAjaM/dlK1YSGQsd5wYQFH39oBFGG0xFNU1NVj1y/8QceAkKquqZc57+3QkzL81HksL94e47UNoTI252praa3fSo+Gj/ccSYD5+FrbuPsgBimU9whQ3KBJigJeTUtDXaiq274nhBei/yIMBHm4K+A/IRoW6TLQ7tWTedPARy6ot3RAKE9tpeNj4btZQb8tZ92SPpbBzWcj73M0C4DU+s4X08RNrkpTBYA7xhrf/tj6h+45CHhn27M7lKCsoyGhu332sQcZ9kBgXUazWVmBKq5gDWZCNoAaUTUugk54RiwG/puzo9Bm5zb+MTqRsH96U1Ke5rBrzL/E7I48MXkFWXVVdgy+txXPdsHG5F8sC2xOg1BOdrPwke734ZQvzV09fuAbJaY/wJdRFVwcRvyzHOJvvLtPXaQTYbMqYVzqaYCdQ2UFZ3h6U7QVlfdESMec/d8Yk+M51e01gLCcZzmcc75x5I+wMquanZz4xjz52FiyhzwIJ5uglSYlSKz0IzMJ8ENwoUrccNjhLSVHxAF0KI8BS8JRckE1gzamyp/J94auiITl5BSpvS0rJsqu4Xx8E9OsDi9D19TrVUyovh+KFOOp7nsptgpM7Em4R5EfArdDwOw5L7rAsATvcFVMRskJQsr24DP0NVvGaoREi2pYAAAAASUVORK5CYII="};function lI(){return"undefined"!=typeof window&&"function"==typeof window.dispatchEvent}function uI(){if(!lI())return null;return window.ethereum??null}async function dI(e=500){const t=[],n=new Map;return lI()?new Promise(r=>{const s=new Set,i=e=>{const r=e,{info:i,provider:o}=r.detail;if(s.has(i.uuid))return;s.add(i.uuid);const a={id:i.rdns||i.uuid,name:i.name,rdns:i.rdns||i.uuid,icon:i.icon??cI[i.rdns||""]??"",provider:o,isInjected:!1};t.push(a),n.set(a.id,a)};window.addEventListener("eip6963:announceProvider",i),window.dispatchEvent(new Event("eip6963:requestProvider")),setTimeout(()=>{if(window.removeEventListener("eip6963:announceProvider",i),0===t.length){const e=uI();if(e){const r=window;let s="Browser Wallet",i="injected";r.ethereum?.isMetaMask?(s="MetaMask",i=aI.METAMASK):r.ethereum?.isCoinbaseWallet?(s="Coinbase Wallet",i=aI.COINBASE):r.ethereum?.isTrust&&(s="Trust Wallet",i=aI.TRUST_WALLET);const o={id:i,name:s,rdns:i,icon:cI[i]??"",provider:e,isInjected:!0};t.push(o),n.set(o.id,o)}}const e=window;if(e.gala?.request&&!n.has(aI.GALA)){const r={id:aI.GALA,name:"Gala Wallet",rdns:aI.GALA,icon:cI[aI.GALA]??"",provider:e.gala,isInjected:!0};t.push(r),n.set(r.id,r)}r({wallets:t,byId:n,hasWallets:t.length>0,...void 0===t[0]?{}:{primary:t[0]}})},e)}):{wallets:t,byId:n,hasWallets:!1}}async function hI(e,t){return(await dI(t)).byId.get(e)??null}function gI(){const e=globalThis;return e.process?.env??{}}function fI(e){const t={};return void 0!==e.cursor&&(t.cursor=e.cursor),void 0!==e.pageSize&&(t.pageSize=e.pageSize),t}function pI(e){return"string"==typeof e?e:"number"==typeof e||"boolean"==typeof e||"bigint"==typeof e?String(e):JSON.stringify(e)??""}function mI(e){if(null==e||"object"!=typeof e)return 0;const t=e;if("number"==typeof t.status)return t.status;if("number"==typeof t.statusCode)return t.statusCode;if("number"==typeof t.code)return t.code;const n=t.response;return n&&"number"==typeof n.status?n.status:0}function yI(e){const t=e.trim().toLowerCase();if(0===t.length)throw new Error("Token name cannot be empty");return t}function bI(e){if(void 0!==e&&e.length>0&&!/^[a-z0-9]+$/.test(e.toLowerCase()))throw new Error(`Invalid asset extension format: "${e}". Must contain only alphanumeric characters.`)}function vI(e,t){return`${e.replace(/\/$/,"")}${t}`}const wI=new Map;const EI={NEW_HOLDER:"NEW_HOLDER",EXITED_HOLDER:"EXITED_HOLDER",BALANCE_CHANGED:"BALANCE_CHANGED"},AI=vi({type:"string",userAddress:"string",balance:"string",rank:"number",previousRank:"optional-number"}),SI=vi({tokenName:"string",userAddress:"string",quantity:"optional-string",percentage:"optional-number",holderTier:"optional-object",isCreator:"boolean",rank:"optional-number"});on.MIN_LENGTH,on.MAX_LENGTH,on.PATTERN;qn({ENABLED:"ENABLED",DISABLED:"DISABLED",ADMIN_DISABLED:"ADMIN_DISABLED"});function kI(e){return"global"===e||"token"===e}function TI(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.messageId&&"string"==typeof t.content&&"string"==typeof t.userAddress&&"string"==typeof t.tokenName&&"string"==typeof t.createdAt}function II(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.messageId&&"string"==typeof t.content&&"string"==typeof t.userAddress&&"string"==typeof t.pinnedBy&&"string"==typeof t.pinnedAt}const CI=qn({RATE_LIMITED:"RATE_LIMITED",INVALID_EMOJI:"INVALID_EMOJI",NOT_AUTHENTICATED:"NOT_AUTHENTICATED",STREAM_NOT_LIVE:"STREAM_NOT_LIVE"});function NI(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.userAddress&&"string"==typeof t.fullName&&(void 0===t.profileImage||"string"==typeof t.profileImage)}var _I,xI,RI,BI,DI,OI;exports.AnalysisStatus=void 0,(_I=exports.AnalysisStatus||(exports.AnalysisStatus={})).PENDING="PENDING",_I.PROCESSING="PROCESSING",_I.COMPLETED="COMPLETED",_I.FAILED="FAILED",exports.AnalysisType=void 0,(xI=exports.AnalysisType||(exports.AnalysisType={})).TEXT="TEXT",xI.IMAGE="IMAGE",xI.VIDEO="VIDEO",exports.AIRecommendation=void 0,(RI=exports.AIRecommendation||(exports.AIRecommendation={})).NO_ACTION="NO_ACTION",RI.REVIEW_REQUIRED="REVIEW_REQUIRED",RI.DELETE_CONTENT="DELETE_CONTENT",RI.BAN_USER="BAN_USER",RI.DELETE_AND_BAN="DELETE_AND_BAN",exports.AnalysisCategory=void 0,(BI=exports.AnalysisCategory||(exports.AnalysisCategory={})).VIOLENCE="VIOLENCE",BI.HATE_SPEECH="HATE_SPEECH",BI.SEXUAL_CONTENT="SEXUAL_CONTENT",BI.HARASSMENT="HARASSMENT",BI.SPAM="SPAM",BI.SCAM="SCAM",BI.SELF_HARM="SELF_HARM",BI.ILLEGAL_ACTIVITY="ILLEGAL_ACTIVITY",BI.MISINFORMATION="MISINFORMATION",BI.COPYRIGHT="COPYRIGHT",BI.SAFE="SAFE",exports.AnalysisTier=void 0,(DI=exports.AnalysisTier||(exports.AnalysisTier={})).QUICK="QUICK",DI.DETAILED="DETAILED",exports.AIModerationMode=void 0,(OI=exports.AIModerationMode||(exports.AIModerationMode={})).DISABLED="DISABLED",OI.ADVISORY="ADVISORY";const MI={[exports.AnalysisStatus.PENDING]:"Pending",[exports.AnalysisStatus.PROCESSING]:"Processing",[exports.AnalysisStatus.COMPLETED]:"Completed",[exports.AnalysisStatus.FAILED]:"Failed"},LI={[exports.AIRecommendation.NO_ACTION]:"No Action Needed",[exports.AIRecommendation.REVIEW_REQUIRED]:"Human Review Required",[exports.AIRecommendation.DELETE_CONTENT]:"Delete Content",[exports.AIRecommendation.BAN_USER]:"Ban User",[exports.AIRecommendation.DELETE_AND_BAN]:"Delete & Ban"},UI={[exports.AnalysisCategory.VIOLENCE]:"Violence",[exports.AnalysisCategory.HATE_SPEECH]:"Hate Speech",[exports.AnalysisCategory.SEXUAL_CONTENT]:"Sexual Content",[exports.AnalysisCategory.HARASSMENT]:"Harassment",[exports.AnalysisCategory.SPAM]:"Spam",[exports.AnalysisCategory.SCAM]:"Scam",[exports.AnalysisCategory.SELF_HARM]:"Self Harm",[exports.AnalysisCategory.ILLEGAL_ACTIVITY]:"Illegal Activity",[exports.AnalysisCategory.MISINFORMATION]:"Misinformation",[exports.AnalysisCategory.COPYRIGHT]:"Copyright",[exports.AnalysisCategory.SAFE]:"Safe"},PI={[exports.AnalysisTier.QUICK]:"Quick Scan",[exports.AnalysisTier.DETAILED]:"Detailed Scan"},FI={[exports.AnalysisType.TEXT]:"Text",[exports.AnalysisType.IMAGE]:"Image",[exports.AnalysisType.VIDEO]:"Video"},$I={[exports.AIModerationMode.DISABLED]:"Disabled",[exports.AIModerationMode.ADVISORY]:"Advisory"},KI=qn(exports.AnalysisStatus),GI=qn(exports.AnalysisType),HI=qn(exports.AIRecommendation),WI=qn(exports.AnalysisCategory),qI=qn(exports.AnalysisTier),zI=qn(exports.AIModerationMode),VI=Yn([{field:"id",type:"number"},{field:"flagId",type:"number"},{field:"status",type:"string",validator:KI},{field:"analysisType",type:"string",validator:GI},{field:"provider",type:"string"}]),jI=Yn([{field:"enabled",type:"boolean"},{field:"mode",type:"string",validator:zI},{field:"provider",type:"string"}]);function XI(e){return null!==e.analysisTier}function YI(e){if(!Kn(e))throw St("content");if(0===e.trim().length)throw Ut("content","Content");if(e.length>fn.COMMENTS_V1.MAX_LENGTH)throw Lt("content",fn.COMMENTS_V1.MAX_LENGTH,e.length)}function JI(e){if(!Kn(e))throw St("content");if(0===e.trim().length)throw new yt("content cannot be empty","content",mt.REQUIRED);if(e.length>fn.CHAT_MESSAGES_V1.MAX_LENGTH)throw new yt(`content must be at most ${fn.CHAT_MESSAGES_V1.MAX_LENGTH} characters`,"content",mt.TOO_LONG)}var QI=Object.freeze({__proto__:null,extractMetadataFromPoolData:function(e,t){const n={};if(void 0!==e.vaultAddress&&(n.vaultAddress=e.vaultAddress),void 0!==e.reverseBondingCurveMinFeePortion){const r=In(e.reverseBondingCurveMinFeePortion,NaN);isNaN(r)?t&&t.debug(`Skipping invalid reverseBondingCurveMinFeePortion for ${e.tokenName}: "${e.reverseBondingCurveMinFeePortion}"`):n.reverseBondingCurveMinFeeFactor=r}if(void 0!==e.reverseBondingCurveMaxFeePortion){const r=In(e.reverseBondingCurveMaxFeePortion,NaN);isNaN(r)?t&&t.debug(`Skipping invalid reverseBondingCurveMaxFeePortion for ${e.tokenName}: "${e.reverseBondingCurveMaxFeePortion}"`):n.reverseBondingCurveMaxFeeFactor=r}return void 0!==n.reverseBondingCurveMaxFeeFactor&&void 0!==n.reverseBondingCurveMinFeeFactor&&(n.reverseBondingCurveNetFeeFactor=n.reverseBondingCurveMaxFeeFactor-n.reverseBondingCurveMinFeeFactor),Object.keys(n).length>0?n:null},isValidPoolForCaching:function(e){if(null===e||"object"!=typeof e)return!1;const t=e;return"tokenName"in t&&"string"==typeof t.tokenName&&t.tokenName.length>0}});Object.defineProperty(exports,"GSwap",{enumerable:!0,get:function(){return t.GSwap}}),exports.ACTIVE_USER_TYPE=bE,exports.AI_MODE_LABELS=$I,exports.AI_RECOMMENDATION_LABELS=LI,exports.ALL_PERMISSIONS=uE,exports.ANALYSIS_CATEGORY_LABELS=UI,exports.ANALYSIS_STATUS_LABELS=MI,exports.ANALYSIS_TIER_LABELS=PI,exports.ANALYSIS_TYPE_LABELS=FI,exports.API_KEY_PERMISSION={MANAGE_COMMENTS:"MANAGE_COMMENTS",MANAGE_CHAT:"MANAGE_CHAT",BAN_USERS:"BAN_USERS",UNBAN_USERS:"UNBAN_USERS",MANAGE_SIMULCAST:"MANAGE_SIMULCAST",GET_STREAM_KEY:"GET_STREAM_KEY",STOP_STREAM:"STOP_STREAM",RESET_STREAM_KEY:"RESET_STREAM_KEY",START_STREAM:"START_STREAM",DELETE_RECORDINGS:"DELETE_RECORDINGS",MANAGE_STREAM_SETTINGS:"MANAGE_STREAM_SETTINGS"},exports.API_KEY_ROLE=aE,exports.API_KEY_ROLES=cE,exports.API_KEY_ROLE_HIERARCHY=mE,exports.AddressFormatter=lr,exports.AgentConfig=class{constructor(){this.utilityInstance=!0,this.utilityInstance}static async quickSetup(e={}){const t=e.environment??this.detectEnvironment(),n=this.setupWallet(e.privateKey),r=this.buildSdkConfig(e,t,n),s=new ZT(r),i={sdk:s,wallet:n,config:r};if(!1!==e.autoValidate){const e=await this.validateSetup(s,n);return{...i,validation:e}}return i}static readOnlySetup(e={}){const t=e.environment??this.detectEnvironment(),n=this.buildSdkConfig(e,t),r=new ZT(n);return Promise.resolve({sdk:r,config:n})}static async validateSetup(e,t){const n=[],r=[],s={canTrade:!1,canCreateTokens:!1,hasBalance:!1,connectionHealthy:!1};try{const t=await e.fetchGalaBalance(e.getAddress());if(s.connectionHealthy=!0,void 0!==t?.quantity&&""!==t.quantity){const e=In(t.quantity,0);s.hasBalance=e>0,s.canTrade=e>=.1,s.canCreateTokens=e>=100,0===e?r.push("Wallet has zero GALA balance - cannot perform transactions"):e<.1?r.push("GALA balance too low for trading (minimum 0.1 GALA)"):e<100&&r.push("GALA balance too low for token creation (minimum 100 GALA)")}else n.push("Failed to fetch GALA balance: No balance returned")}catch(e){n.push(`Balance check error: ${at(e)}`)}try{const t=await e.fetchPools({type:"recent",pageSize:1});null!==t.items&&void 0!==t.items&&0!==t.items.length||r.push("Pool listing not accessible - some features may be limited")}catch(e){r.push(`Pool access test failed: ${at(e)}`)}return{ready:0===n.length&&s.connectionHealthy,sdk:e,wallet:t??nI.generateWallet(),issues:n,warnings:r,capabilities:s}}static getRecommendedConfig(e,t="general"){const n={environment:e,autoValidate:!0};switch(e){case"prod":Object.assign(n,{debug:!1,timeout:3e4});break;case"stage":Object.assign(n,{debug:!0,timeout:45e3})}switch(t){case"trading":n.timeout=1.5*(n.timeout??3e4);break;case"creation":n.timeout=2*(n.timeout??3e4);break;case"monitoring":n.timeout=.5*(n.timeout??3e4);break;case"general":break;default:throw new Error(`Unexpected useCase: ${String(t)}`)}return n}static async multiWalletSetup(e,t="stage"){const n={};for(const[r,s]of Object.entries(e)){const{sdk:e}=await this.quickSetup({environment:t,privateKey:s,agentId:`multi-wallet-${r}`,autoValidate:!1});n[r]=e}return n}static detectEnvironment(){return"stage"===(gI().LAUNCHPAD_ENV??gI().ENVIRONMENT)?"stage":"prod"}static setupWallet(e){if(void 0===e||""===e){const e=gI().PRIVATE_KEY;return void 0!==e&&""!==e?nI.fromPrivateKey(e):nI.generateWallet()}return"generate"===e?nI.generateWallet():nI.fromPrivateKey(e)}static buildSdkConfig(e,t,n){const r=e.galaChainAddress??gI().WALLET_ADDRESS;return{wallet:n?.wallet,baseUrl:e.baseUrl??this.getDefaultBaseUrl(t),timeout:e.timeout??this.getDefaultTimeout(t),debug:e.debug??"prod"!==t,...this.getEnvironmentDefaults(t),...e.config??{},...void 0!==r&&""!==r?{galaChainAddress:r}:{},env:t}}static getDefaultBaseUrl(e){return so(e).launchpadBaseUrl}static getDefaultTimeout(e){switch(e){case"prod":return 3e4;case"stage":return 45e3}}static getEnvironmentDefaults(e){const t=so(e);return{bundleBaseUrl:t.bundleBaseUrl,gatewayBaseUrl:t.gatewayBaseUrl}}},exports.AuthError=Xi,exports.BAN_DURATIONS={ONE_HOUR:3600,ONE_DAY:86400,ONE_WEEK:604800,ONE_MONTH:2592e3},exports.BRIDGE_CONTRACT_ABI=Eo,exports.BRIDGE_TOKEN_METADATA=vo,exports.BaseBridgeStrategy=Iw,exports.BridgeRateLimiter=Jv,exports.BrowserWalletSigner=rA,exports.BundleSubmission=iT,exports.BundlerTransport=oT,exports.BurnError=iS,exports.CALCULATION_MODES=it,exports.CHAIN_IDS=ao,exports.CONTENT_REACTION_TYPES=CA,exports.CONTENT_TYPE_LABELS=yA,exports.CROSS_RATE_TYPED_DATA_TYPES=qv,exports.ChartService=class extends rr{constructor(e,t=!1){super(e,t)}async getChart(e){if(null==e)throw St("options","Chart options");const{tokenName:t,from:n,to:r,resolution:s}=e;if(null==t||""===t)throw St("tokenName","Token name");if(null==n)throw St("from","Start timestamp");if(null==r)throw St("to","End timestamp");if(null==s)throw St("resolution","Data resolution interval");Ui(t);const i=173e6;if("number"!=typeof n||n<i)throw new yt("from must be a valid timestamp (min: 173000000)","from","INVALID_TIMESTAMP");if("number"!=typeof r||r<i)throw new yt("to must be a valid timestamp (min: 173000000)","to","INVALID_TIMESTAMP");if("number"!=typeof s||s<1)throw new yt("resolution must be a number >= 1","resolution","INVALID_RESOLUTION");const{adaptQueryParams:o}=await Promise.resolve().then(function(){return Si}),a=o({tokenName:t,from:n,to:r,resolution:s}),c=await Wt(()=>this.http.get(b.CHART,a),{errorContext:"Failed to fetch chart data"}),l=$t(c);if(null==l||"object"!=typeof l)throw Tt("Invalid API response: missing or invalid data",c.status??500);const u=l,d=u.data;if(!Array.isArray(d))throw Tt("Invalid API response: expected data array",c.status??500);const h={dataPoints:d.map(e=>{if("object"!=typeof e||null===e)throw Tt("Invalid API response: invalid data point structure",c.status??500);const t=e,n=t.startTime??t.timestamp,r=t.openPrice??t.value,s=t.closePrice??t.value,i=t.lowPrice??t.value,o=t.highPrice??t.value,a=t.volume??"0";return{startTime:"number"==typeof n?n:Number(n),openPrice:String(r),closePrice:String(s),lowPrice:String(i),highPrice:String(o),volume:String(a)}})};return"boolean"==typeof u.isPreviousData&&(h.isPreviousData=u.isPreviousData),h}},exports.ConfigurationError=vt,exports.DEFAULT_ETHEREUM_BRIDGE_CONTRACT=lo,exports.DEFAULT_ETHEREUM_RPC_URL="https://ethereum.publicnode.com",exports.DEFAULT_ETHEREUM_TOKENS=yo,exports.DEFAULT_EVENTS_CONFIG=xA,exports.DEFAULT_POLL_INTERVAL_MS=15e3,exports.DEFAULT_POLL_TIMEOUT_MS=27e5,exports.DEFAULT_PRICING_CONCURRENCY=5,exports.DEFAULT_RATE_LIMIT_RPS=12,exports.DEFAULT_SOLANA_BRIDGE_PROGRAM="AaE4dTnL75XqgUJpdxBKg6vS9sTJgBPJwBQRVhD29WwS",exports.DEFAULT_SOLANA_RPC_URL="https://api.mainnet-beta.solana.com",exports.DEFAULT_SOLANA_TOKENS=bo,exports.DEFAULT_WEBSOCKET_RECONNECT_ATTEMPTS=5,exports.ENVIRONMENT_URLS=ro,exports.ERC20_ABI=wo,exports.ERROR_CODES=mt,exports.ETHEREUM_BRIDGE_CONTRACT_SEPOLIA=uo,exports.ETHEREUM_TOKENS_PROD=go,exports.ETHEREUM_TOKENS_STAGE=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.EXTENDED_STREAM_ROLE=Ok,exports.EthereumBridgeStrategy=_w,exports.EventBufferWithAutoCleanup=class{constructor(e={},t){this.events=[],this.timeouts=new Map,this.maxSize=e.maxSize??100,this.defaultTtlMs=e.defaultTtlMs??3e4,this.logger=t}push(e){if(this.events.length>=this.maxSize){const e=0;this.events.shift();const t=this.timeouts.get(e);t&&(clearTimeout(t),this.timeouts.delete(e)),this.logger?.warn(`Buffer full (${this.maxSize}), dropped oldest event`)}this.events.push(e);const t=this.events.length-1,n=setTimeout(()=>{this.events[t]===e&&this.events.splice(t,1),this.timeouts.delete(t)},this.defaultTtlMs);this.timeouts.set(t,n)}getAll(){return[...this.events]}clear(){for(const e of this.timeouts.values())clearTimeout(e);this.events=[],this.timeouts.clear()}get size(){return this.events.length}},exports.EventsBatcherService=RA,exports.ExternalWalletProvider=XT,exports.FLAG_ACTION_LABELS=mA,exports.FLAG_DETAILS_MAX_LENGTH=500,exports.FLAG_REASON_LABELS=fA,exports.FLAG_STATUS_LABELS=pA,exports.FileValidationError=Di,exports.GALACHAIN_CHANNELS=co,exports.GALACONNECT_PRODUCTION_URL=ho,exports.GALA_BRIDGE_TYPED_DATA_DOMAIN=Fv,exports.GALA_DECIMALS=8,exports.GALA_TOKEN_CLASS_KEY={collection:"GALA",category:"Unit",type:"none",additionalKey:"none"},exports.GalaChainConnectProvider=oI,exports.GalaConnectClient=Tw,exports.GalaConnectHttpError=bw,exports.GalaWalletSigner=nA,exports.GdexStreamError=mS,exports.GdexStreamService=yS,exports.GlobalAndRoomCallbackDispatcher=class{constructor(e){this.globalCallbacks=[],this.roomCallbacks=new Map,this.logger=e}registerGlobalCallback(e){this.globalCallbacks.push(e)}registerRoomCallback(e,t){const n=this.roomCallbacks.get(e)??[];n.push(t),this.roomCallbacks.set(e,n)}dispatch(e,t){for(const e of this.globalCallbacks)try{e(t)}catch(e){this.logger?.error(`Error in global callback: ${at(e)}`)}const n=this.roomCallbacks.get(e);if(n)for(const r of n)try{r(t)}catch(t){this.logger?.error(`Error in room callback for ${e}: ${at(t)}`)}}clear(){this.globalCallbacks=[],this.roomCallbacks.clear()}clearRoom(e){this.roomCallbacks.delete(e)}},exports.HOLDER_DELTA_TYPES=EI,exports.IMAGE_EXTENSIONS=Vr,exports.INVITE_STATUS=$S,exports.INVITE_STATUSES=KS,exports.JWT_CONSTANTS=qi,exports.KNOWN_WALLET_RDNS=aI,exports.LAUNCHPAD_TOKEN_DECIMALS=18,exports.LEGACY_TYPED_DATA_TYPES=Wv,exports.LaunchpadSDK=ZT,exports.LaunchpadSDKError=sT,exports.LaunchpadWrites=vT,exports.ListenerCleanupManager=class{constructor(e){this.listeners=[],this.logger=e}register(e,t){this.listeners.push({id:e,cleanup:t})}async cleanup(){const e=[];for(let t=this.listeners.length-1;t>=0;t--){const n=this.listeners[t];if(void 0===n)continue;const{id:r,cleanup:s}=n;try{await s()}catch(t){const n=t instanceof Error?t:new Error(String(t));e.push(n),this.logger?.error(`Cleanup error for listener ${r}:`,n)}}return this.listeners=[],e}clear(){this.listeners=[]}get size(){return this.listeners.length}},exports.LockError=zA,exports.MAX_BURN_BATCH_SIZE=50,exports.MAX_CONCURRENT_POOL_FETCHES=5,exports.MAX_LOCK_BATCH_SIZE=100,exports.MAX_UNLOCK_BATCH_SIZE=100,exports.MESSAGES_CONSTRAINTS=AS,exports.MESSAGE_TYPES=ES,exports.MODERATOR_ROLE=LS,exports.MODERATOR_ROLES=US,exports.NFT_FEES=YS,exports.NetworkError=bt,exports.NftCollectionService=nk,exports.OEmbedService=sk,exports.OVERSEER_INVITE_STATUS=ok,exports.OVERSEER_STATUS=ak,exports.PAGINATION_DEFAULTS=Qw,exports.PERMISSION=lE,exports.POOL_FETCH_CONFIG={MAX_CONCURRENT_FETCHES:5,PAGE_SIZE:50,BACKEND_PAGE_SIZE:20},exports.POOL_TYPES={RECENT:"recent",POPULAR:"popular"},exports.PayloadWalkerWithDeduplication=class{constructor(e,t,n=50){this.seen=new Set,this.extractor=e,this.dedupeKeyFn=t,this.maxDepth=n}walk(e){const t=[],n=new WeakSet,r=(e,s=0)=>{if(s>this.maxDepth)return;if(null==e||"object"!=typeof e)return;if(n.has(e))return;n.add(e);const i=this.extractor(e);if(null!==i){const e=this.dedupeKeyFn(i);this.seen.has(e)||(this.seen.add(e),t.push(i))}for(const t of Object.values(e))r(t,s+1)};return r(e,0),t}reset(){this.seen.clear()}getSeenCount(){return this.seen.size}},exports.PendingSubscriptionTracker=class{constructor(){this.pending=new Map}addPending(e,t){this.removePending(e);const n=setTimeout(()=>{this.pending.delete(e)},t);this.pending.set(e,{timeoutId:n,addedAt:Date.now()})}removePending(e){const t=this.pending.get(e);t&&(clearTimeout(t.timeoutId),this.pending.delete(e))}isPending(e){return this.pending.has(e)}getPendingCount(){return this.pending.size}clearExpired(){for(const[e,t]of this.pending.entries())null==t&&this.pending.delete(e)}clear(){for(const e of this.pending.values())clearTimeout(e.timeoutId);this.pending.clear()}},exports.PlatformStatsService=Ek,exports.PrivateKeyProvider=to,exports.PrivateKeySigner=tA,exports.QUERY_FIELD_NAMES={PAGE:"page",LIMIT:"limit",TOKEN_NAME:"tokenName",VAULT_ADDRESS:"vaultAddress",USER_ADDRESS:"userAddress",TRADE_TYPE:"tradeType",POOL_TYPE:"type",SEARCH:"search",SORT_ORDER:"sortOrder",START_DATE:"startDate",END_DATE:"endDate"},exports.REACTION_EMOJI_MAP={heart:"❤️",fire:"🔥",laugh:"😂",wow:"😮",thumbs_up:"👍"},exports.RECORDING_STATUS=Ck,exports.ROLE_SOURCE=Dk,exports.RoomSubscriptionManager=class{constructor(){this.rooms=new Set}addRoom(e){this.rooms.add(e)}removeRoom(e){this.rooms.delete(e)}getRooms(){return Array.from(this.rooms)}isSubscribedTo(e){return this.rooms.has(e)}clear(){this.rooms.clear()}get size(){return this.rooms.size}},exports.SDK_VERSION=Jw,exports.SIMULATE_EVENT_TYPE={STREAM_STARTED:"stream.started",STREAM_STOPPED:"stream.stopped",RECORDING_READY:"recording.ready",SIMULCAST_ERROR:"simulcast.error"},exports.SIMULCAST_PLATFORM=Nk,exports.SIMULCAST_STATUS={ACTIVE:"ACTIVE",IDLE:"IDLE",ERRORED:"ERRORED",DISABLED:"DISABLED"},exports.SOLANA_COMPUTE={UNIT_LIMIT:2e5,UNIT_PRICE_MICROLAMPORTS:375e3},exports.SOLANA_DISCRIMINATORS=Ao,exports.STREAM_EVENTS=Fk,exports.STREAM_PERMISSION={MANAGE_COMMENTS:"MANAGE_COMMENTS",MANAGE_CHAT:"MANAGE_CHAT",BAN_USERS:"BAN_USERS",UNBAN_USERS:"UNBAN_USERS",MANAGE_SIMULCAST:"MANAGE_SIMULCAST",GET_STREAM_KEY:"GET_STREAM_KEY",STOP_STREAM:"STOP_STREAM",RESET_STREAM_KEY:"RESET_STREAM_KEY",START_STREAM:"START_STREAM",DELETE_RECORDINGS:"DELETE_RECORDINGS",MANAGE_STREAM_SETTINGS:"MANAGE_STREAM_SETTINGS"},exports.STREAM_ROLE=Bk,exports.STREAM_STATUS=Ik,exports.SelectiveEventForwarding=class{constructor(){this.filters=[]}addFilter(e){return this.filters.push(e),this}forward(e){for(const t of this.filters)if(!t(e))return!1;return!0}clearFilters(){this.filters=[]}get filterCount(){return this.filters.length}},exports.SolanaBridgeStrategy=Ww,exports.StreamWebSocketService=$k,exports.StreamingEventService=Tk,exports.TIME_CONSTANTS={ONE_SECOND_MS:1e3,ONE_MINUTE_MS:6e4,ONE_HOUR_MS:36e5,ONE_DAY_MS:864e5,ONE_WEEK_MS:6048e5,ONE_MONTH_MS:2592e6},exports.TRADES_QUERY_CONSTRAINTS=IS,exports.TRADING_TYPES=st,exports.TokenMetadataService=class extends sr{constructor(e=!1){super(e),this.cache={},this.cacheExpiry=36e5}resolveTokenMetadata(e){const t=this.getCacheKey(e),n=this.cache[t];if(null!=n&&!this.isCacheExpired(n.timestamp))return this.logger.debug(`Using cached metadata for token: ${t}`),n.data;const r=this.extractMetadata(e);return this.cache[t]={data:r,timestamp:Date.now()},r}getTokenSymbol(e){return this.resolveTokenMetadata(e).symbol}getTokenDecimals(e){return this.resolveTokenMetadata(e).decimals}clearCache(e){void 0!==e&&""!==e?(delete this.cache[e],this.logger.debug(`Cleared cache for token: ${e}`)):(this.cache={},this.logger.debug("Cleared all token metadata cache"))}getCacheStats(){const e=Object.keys(this.cache);return{size:e.length,entries:e}}getCacheKey(e){if("string"==typeof e)return Vt(e);const t=e;return Vt(`${t.type??t.symbol??"unknown"}|${t.additionalKey??"none"}`)}extractMetadata(e){let t,n,r="Token",s="Unit",i="none";if("string"==typeof e)if(dw(e)){const o=uw(e);"Token"===o.collection&&""!==o.type?(r=o.collection,s=""!==o.category?o.category:"Unit",t=o.type,i=""!==o.additionalKey?o.additionalKey:"none",n=t):(t=o.collection,n=t,s=""!==o.category?o.category:"Unit",i=""!==o.additionalKey?o.additionalKey:"none")}else t=e,n=e;else{const o=e;t=o.type??"unknown",r=o.collection??"Token",s=o.category??"Unit",i=o.additionalKey??"none";const a=o.symbol??("Token"===r?t:r);n=""!==a?a:"unknown"}const o=this.getDecimalsForToken(n);return{symbol:n.toUpperCase(),decimals:o,collection:r,category:s,type:t.toUpperCase(),additionalKey:i,verified:!1}}getDecimalsForToken(e){return{GALA:8,GUSDC:6,USDC:6,USDT:6,WETH:18,DAI:18}[e.toUpperCase()]??18}isCacheExpired(e){return sn(e)>this.cacheExpiry}setCacheExpiry(e){this.cacheExpiry=e,this.logger.debug(`Set token metadata cache expiry to ${e}ms`)}},exports.TokenRestrictedError=class extends yt{constructor(e){super(e,"token","TOKEN_RESTRICTED"),this.name="TokenRestrictedError"}},exports.TokenWrites=ET,exports.TradingQuotesService=jk,exports.TransactionError=wt,exports.TransactionFailedError=LT,exports.TypingIndicatorDebouncer=class{constructor(e={},t){this.pendingIndicators=new Map,this.activeIndicators=new Set,this.delayMs=e.delayMs??3e3,this.onTyping=e.onTyping,this.onStopTyping=e.onStopTyping}indicate(e,t){const n=`${e}:${t}`,r=this.pendingIndicators.get(n);r&&clearTimeout(r),this.activeIndicators.has(n)||(this.activeIndicators.add(n),this.onTyping?.(e,t));const s=setTimeout(()=>{this.activeIndicators.delete(n),this.pendingIndicators.delete(n),this.onStopTyping?.(e,t)},this.delayMs);this.pendingIndicators.set(n,s)}stopTyping(e,t){const n=`${e}:${t}`,r=this.pendingIndicators.get(n);r&&(clearTimeout(r),this.pendingIndicators.delete(n)),this.activeIndicators.has(n)&&(this.activeIndicators.delete(n),this.onStopTyping?.(e,t))}clear(){for(const e of this.pendingIndicators.values())clearTimeout(e);this.pendingIndicators.clear(),this.activeIndicators.clear()}get activeCount(){return this.activeIndicators.size}},exports.ValidationError=yt,exports.WebSocketError=MT,exports.WebSocketTimeoutError=class extends MT{constructor(e,t){super(`WebSocket confirmation timeout for transaction ${e} after ${t}ms`),this.name="WebSocketTimeoutError"}},exports.WeeklyChallengeService=Zk,exports.addCursorToPagination=function(e,t){return void 0===t?e:{...e,cursor:t}},exports.addressFormatSchema=Ir,exports.aggregateMultipleApiSources=async function(e,t,n){const r=n?.logger,s=n?.fetcher??(async e=>{const t=await fetch(e);if(!t.ok)throw new Error(`HTTP ${t.status}`);return t.json()});r?.debug(`Aggregating from ${e.length} endpoints`);const i=e.map(async(t,n)=>{try{const i=await s(t);return r?.debug(`Endpoint [${n+1}/${e.length}] succeeded: ${t}`),i}catch(s){return void r?.warn(`Endpoint [${n+1}/${e.length}] failed: ${t} - ${at(s)}`)}}),o=(await Promise.allSettled(i)).map(e=>{if("fulfilled"===e.status)return e.value});return r?.debug(`Aggregating ${o.filter(e=>void 0!==e).length} successful results`),t(o)},exports.amountMethodSchema=ls,exports.amountTypeSchema=cs,exports.assertValidWalletAddress=mr,exports.bidirectionalTokenMatch=function(e,t,n,r){return e===n&&t===r||e===r&&t===n},exports.browserFileSchema=Xr,exports.bufferFileSchema=Yr,exports.buildConcurrentBatchRequests=async function(e,t,n,r){const s=r?.logger,i=[];i.length=e.length;let o=0,a=0;s?.debug(`Starting concurrent batch requests: ${e.length} URLs, batch size: ${t}`);for(let r=0;r<e.length;r+=t){const c=e.slice(r,r+t),l=r;try{const t=c.map((t,r)=>{const c=l+r;return(async()=>{try{const r=await n(t);return i[c]=r,o++,s?.debug(`Fetched [${c+1}/${e.length}]: ${t}`),r}catch(n){throw a++,s?.warn(`Failed [${c+1}/${e.length}]: ${t} - ${at(n)}`),n}})()}),r=await Promise.allSettled(t);for(let e=0;e<r.length;e++){const t=r[e];"rejected"===t?.status&&s?.debug(`Promise rejected in batch at index ${l+e}`)}}catch(e){s?.error(`Batch processing error at index ${r}: ${at(e)}`)}}return s?.debug(`Batch complete: ${o} succeeded, ${a} failed`),i},exports.buildQueryParametersWithValidation=function(e){if(null==e||"object"!=typeof e)return"";const t=[];for(const[n,r]of Object.entries(e)){if(Gn(r))continue;let e;e="string"==typeof r?r:"number"==typeof r||"boolean"==typeof r?String(r):Array.isArray(r)?r.map(e=>pI(e)).join(","):pI(r);const s=encodeURIComponent(n),i=encodeURIComponent(e);t.push(`${s}=${i}`)}return t.length>0?`?${t.join("&")}`:""},exports.buildSafePaginationOptions=fI,exports.buyTokensDataSchema=Ss,exports.calculateLinearFeeInterpolation=function(e,t,n){const r="number"==typeof e?new o(e):e;if(r.isLessThan(0)||r.isGreaterThan(1))throw new Error(`Progress must be between 0 and 1, got: ${r.toString()}`);if(n<t)throw new Error(`maxFee must be >= minFee, got minFee: ${t}, maxFee: ${n}`);const s=n-t;return new o(t).plus(new o(s).multipliedBy(r))},exports.calculatePreMintDataSchema=xs,exports.calculateScaledFeeAmount=function(e,t){if(t<0)throw new Error(`feeFactor must be >= 0, got: ${t}`);return ki(e).multipliedBy(t).integerValue(o.ROUND_DOWN)},exports.calculateTotalPages=eE,exports.capitalize=Et,exports.caseInsensitiveTokenComparison=function(e,t){return e.toLowerCase()===t.toLowerCase()},exports.checkPoolOptionsSchema=as,exports.commonValidators=Jn,exports.compareAmounts=function(e,t){const n=ki(e),r=ki(t);return n.comparedTo(r)},exports.conditionalSpreadBuilder=function(e,t){const n={...e};for(const[e,r]of Object.entries(t))void 0!==r&&(n[e]=r);return n},exports.conditionalTrimAndValidateString=xS,exports.createLaunchpadSDK=function(t){Hn(t)&&(t={});const{wallet:n,env:r,config:s={},...i}=t,o={...{...i,...s}};delete o.wallet,delete o.env,delete o.config;const a=!Hn(o.signer)||!Hn(o.walletProvider);let c;if(Hn(n))c=a?void 0:rI().wallet;else if("string"==typeof n){c=rI(n).wallet}else{if(!(n instanceof e.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!==r?{env:r}:{},debug:!1,timeout:3e4,...o};return new ZT(l)},exports.createLimitSchema=Mr,exports.createOptionsValidator=function(e){return t=>{const n=[],r=t;for(const t of e){const{field:e,required:s,type:i,validator:o}=t,a=r[e];if(s){if(Hn(a)){n.push(`${e} is required`);continue}if("string"===i){if("string"!=typeof a){n.push(`${e} must be a string`);continue}if(0===a.trim().length){n.push(`${e} is required`);continue}}}if(!Hn(a))if(void 0===i||typeof a===i){if(void 0!==o){const e=o(a,r);null!=e&&""!==e&&n.push(e)}}else n.push(`${e} must be a ${i}`)}return n}},exports.createPaginatedResultSchema=function(e){return n.z.object({data:n.z.array(e),...bs})},exports.createPaginationQuery=function(e,t=Qw.DEFAULT_LIMIT){if("number"!=typeof e||!Number.isInteger(e)||e<0)throw Bt("offset","a non-negative integer",e);return Ln(t,"limit"),{offset:e,limit:t}},exports.createProviderFromEip1193=function(e){return new XT(e)},exports.createProviderFromWallet=function(e){return to.fromWallet(e)},exports.createSolanaWallet=function(){const e=nv.generate();return{privateKey:Gw.encode(e.secretKey),publicKey:e.publicKey.toBase58(),address:e.publicKey.toBase58()}},exports.createTradeDataSchema=As,exports.createWallet=rI,exports.createWalletProvider=function(e){if(null!==e.privateKey&&void 0!==e.privateKey&&e.privateKey.length>0)return new to(e.privateKey);if(null!==e.eip1193Provider&&void 0!==e.eip1193Provider)return new XT(e.eip1193Provider);throw new eo("Invalid wallet provider config: must provide either privateKey or eip1193Provider",ji.INVALID_CONFIG)},exports.decimalRoundingUp=function(e,t){if(t<0)throw new Error(`decimals must be >= 0, got: ${t}`);const n=ki(e),r=new o(10).pow(t);return n.multipliedBy(r).integerValue(o.ROUND_UP).dividedBy(r)},exports.deduplicateByKey=function(e,t,n=!0){const r=new Map;if(e.forEach((e,n)=>{const s=t(e);r.set(s,n)}),n){const n=new Set;return e.filter(e=>{const r=t(e);return!n.has(r)&&(n.add(r),!0)})}return e.filter((e,n)=>{const s=t(e);return r.get(s)===n})},exports.detectWallets=dI,exports.ensureConnected=async function(e){return e.isConnected()?e.getAddress():e.connect()},exports.errorMessageCaseNormalization=function(e){return e.toLowerCase()},exports.ethereumAddressSchema=Cr,exports.extractFieldWithFallbackPath=function(e,t,n=null){if(null==e||"object"!=typeof e)return n;const r=e;for(const e of t){const t=e.split(".");let n=r;for(const e of t){if(null==n||"object"!=typeof n){n=null;break}n=n[e]}if(Kn(n))return n;if(null!=n&&""!==n)return n}return n},exports.extractPaginationMetadata=function(e){const t={page:1,pageSize:20,totalCount:-1,hasMore:!1};if(null==e||"object"!=typeof e)return t;const n=e,r=Nn(pI(n.page??n.Page??n.current??1),t.page),s=Nn(pI(n.pageSize??n.limit??n.size??t.pageSize),t.pageSize),i=n.data,o=i?.meta;let a;a="number"==typeof n.totalCount?n.totalCount:"number"==typeof n.total?n.total:"number"==typeof o?.totalItems?o.totalItems:"number"==typeof i?.count?i.count:Nn(pI(n.totalCount??n.total??-1),t.totalCount);let c=t.hasMore;return"boolean"==typeof n.hasMore?c=n.hasMore:"boolean"==typeof n.has_more?c=n.has_more:"boolean"==typeof o?.hasMore&&(c=o.hasMore),{page:r,pageSize:s,totalCount:a,hasMore:c}},exports.fetchGalaBalanceOptionsSchema=Ms,exports.fetchPoolDetailsDataSchema=Rs,exports.fetchTokenBalanceOptionsSchema=Fs,exports.fileSizeSchema=Fr,exports.fileUploadSchema=jr,exports.filenameSchema=$r,exports.flexibleAddressSchema=Nr,exports.flexibleFileSchema=Jr,exports.formatGalaForDTO=Bn,exports.formatLaunchpadTokenForDTO=Dn,exports.formatTokenAmount=function(e,t=6){const n=ki(e);if(!n.isFinite())return"0";if(n.abs().lt(1e-6)&&!Ci(n))return n.toExponential(2);const r=Math.min(t,n.abs().lt(1)?t:n.abs().lt(100)?4:2);return n.toFixed(r).replace(/\.?0+$/,"")},exports.formatTokenDescriptor=function(e){return io(e)},exports.fromBackendAddressFormat=gr,exports.fromBaseUnits=mw,exports.fullNameSchema=Tr,exports.generateBuySellStringsInstructions=yT,exports.generateCreateSaleStringsInstructions=bT,exports.generateEIP712Types=YE,exports.generateUniqueKey=XE,exports.getAmountOptionsSchema=_s,exports.getEnv=function(e,t){return globalThis.process?.env[e]??t},exports.getEnvOrThrow=function(e,t){const n=globalThis.process?.env[e];if(en(n)||!Qt(n)){throw St(e,`${e} (${void 0!==t?`${t} (checked root .env and local .env)`:"checked root .env and local .env"})`)}return n},exports.getEnvironmentConfig=so,exports.getEthereumAddressFromPrivateKey=function(t){if(!t.match(/^0x[a-fA-F0-9]{64}$/))throw kt("privateKey","0x-prefixed 64 hexadecimal characters","Private key");return e.getAddress(e.computeAddress(t))},exports.getEthereumBridgeContractByEnvironment=mo,exports.getEthereumTokenConfig=function(e){const t=Xt(e);return yo.find(e=>Xt(e.symbol)===t||Xt(e.symbol)===`G${t}`)},exports.getEthereumTokensByEnvironment=po,exports.getGalaBridgeTypedDataTypes=zv,exports.getInjectedEip1193Provider=function(){if("undefined"==typeof window)return null;const e=window.ethereum;return QT(e)?e:null},exports.getIntervalRegistryStats=function(){const e=Array.from(wI.entries()).map(([e,t])=>({id:e,...t}));return{size:wI.size,entries:e}},exports.getLaunchTokenDataValidationErrors=gi,exports.getNftFeeAsNumber=function(e){return parseFloat(YS[e])},exports.getPublicKeyFromPrivateKey=function(t){if(!t.match(/^0x[a-fA-F0-9]{64}$/))throw kt("privateKey","0x-prefixed 64 hexadecimal characters","Private key");const n=new e.SigningKey(t);return{publicKey:n.publicKey,compressedPublicKey:n.compressedPublicKey}},exports.getRecordingAnimatedUrl=function(e,t,n,r="gif"){const s=yI(e),i=t.trim();if(0===i.length)throw new Error("Recording ID cannot be empty");return bI(r),vI(n,`/v1/tokens/${encodeURIComponent(s)}/recordings/${encodeURIComponent(i)}/assets/animated.${r.toLowerCase()}`)},exports.getRecordingAssetUrl=function(e,t,n,r,s){const i=yI(e),o=t.trim(),a=n.trim().toLowerCase();if(0===o.length)throw new Error("Recording ID cannot be empty");if(0===a.length)throw new Error("Asset type cannot be empty");bI(s);const c=void 0!==s&&s.length>0?`.${s.toLowerCase()}`:"";return vI(r,`/v1/tokens/${encodeURIComponent(i)}/recordings/${encodeURIComponent(o)}/assets/${encodeURIComponent(a)}${c}`)},exports.getRecordingPosterUrl=function(e,t,n){const r=yI(e),s=t.trim();if(0===s.length)throw new Error("Recording ID cannot be empty");return vI(n,`/v1/tokens/${encodeURIComponent(r)}/recordings/${encodeURIComponent(s)}/assets/poster.jpg`)},exports.getRecordingStoryboardUrl=function(e,t,n,r="vtt"){const s=yI(e),i=t.trim();if(0===i.length)throw new Error("Recording ID cannot be empty");return bI(r),vI(n,`/v1/tokens/${encodeURIComponent(s)}/recordings/${encodeURIComponent(i)}/assets/storyboard.${r.toLowerCase()}`)},exports.getRecordingStreamUrl=function(e,t,n){const r=yI(e),s=t.trim();if(0===s.length)throw new Error("Recording ID cannot be empty");return vI(n,`/v1/tokens/${encodeURIComponent(r)}/recordings/${encodeURIComponent(s)}/assets/stream.m3u8`)},exports.getRecordingThumbnailUrl=function(e,t,n,r="jpg"){const s=yI(e),i=t.trim();if(0===i.length)throw new Error("Recording ID cannot be empty");return bI(r),vI(n,`/v1/tokens/${encodeURIComponent(s)}/recordings/${encodeURIComponent(i)}/assets/thumbnail.${r.toLowerCase()}`)},exports.getSolanaTokenConfig=function(e){const t=Xt(e);return bo.find(e=>Xt(e.symbol)===t||Xt(e.symbol)===`G${t}`)},exports.getStaticTokenMetadata=function(e){const t=Xt(e),n=vo[t];if(void 0!==n)return n;if(!t.startsWith("G")){const e=vo[`G${t}`];if(void 0!==e)return e}},exports.getTieredModerationSavings=function(e,t){if(!XI(e)||null===e.tokensUsed)return 0;const n=1500*t.maxFrames;if(0===n)return 0;const r=(n-e.tokensUsed)/n*100;return Math.max(0,Math.round(r))},exports.getTokenAnimatedUrl=function(e,t,n="gif"){const r=yI(e);return bI(n),vI(t,`/v1/tokens/${encodeURIComponent(r)}/assets/animated.${n.toLowerCase()}`)},exports.getTokenAssetUrl=function(e,t,n,r){const s=yI(e),i=t.trim().toLowerCase();if(0===i.length)throw new Error("Asset type cannot be empty");bI(r);const o=void 0!==r&&r.length>0?`.${r.toLowerCase()}`:"";return vI(n,`/v1/tokens/${encodeURIComponent(s)}/assets/${encodeURIComponent(i)}${o}`)},exports.getTokenImageUrl=function(e,t){const n=yI(e);return vI(t,`/v1/tokens/${encodeURIComponent(n)}/assets/image`)},exports.getTokenLiveStreamUrl=function(e,t){const n=yI(e);return vI(t,`/v1/tokens/${encodeURIComponent(n)}/assets/live.m3u8`)},exports.getTokenPosterUrl=function(e,t){const n=yI(e);return vI(t,`/v1/tokens/${encodeURIComponent(n)}/assets/poster.jpg`)},exports.getTokenStoryboardUrl=function(e,t,n="vtt"){const r=yI(e);return bI(n),vI(t,`/v1/tokens/${encodeURIComponent(r)}/assets/storyboard.${n.toLowerCase()}`)},exports.getTokenThumbnailUrl=function(e,t,n="jpg"){const r=yI(e);return bI(n),vI(t,`/v1/tokens/${encodeURIComponent(r)}/assets/thumbnail.${n.toLowerCase()}`)},exports.getTradeOptionsSchema=Ts,exports.getWalletByRdns=hI,exports.graduateTokenOptionsSchema=ds,exports.graphDataOptionsSchema=us,exports.groupByKey=function(e,t){const n=new Map;for(const r of e){const e=t(r);n.has(e)||n.set(e,[]),n.get(e).push(r)}return n},exports.hasAnyWallet=function(){return null!==uI()},exports.hasMorePages=function(e,t,n){if("number"!=typeof e||!Number.isInteger(e))throw Bt("offset","a non-negative integer",e);if(e<0)throw _t("offset",0,1/0,e);return e+t<n},exports.hexStringExtractionAndNormalization=function(e){if(""===e||"string"!=typeof e)return null;if(e.includes("|")){const t=e.split("|");if(t.length>=2){const e=t[1];if(void 0!==e&&RS(e))return BS(e)}return null}return RS(e)?BS(e):null},exports.imageExtensionSchema=Qr,exports.imageFilenameSchema=Zr,exports.imageMimeTypeSchema=Kr,exports.imageUploadOptionsSchema=is,exports.isAIModerationData=VI,exports.isAIModerationMode=zI,exports.isAIModerationSettings=jI,exports.isAIRecommendation=HI,exports.isActiveUserType=vE,exports.isAnalysisCategory=WI,exports.isAnalysisStatus=KI,exports.isAnalysisTier=qI,exports.isAnalysisType=GI,exports.isBanData=wE,exports.isBanEnforcementEvent=SE,exports.isBurnTokenEntry=nS,exports.isBurnTokensData=rS,exports.isChatDisabledReason=kI,exports.isChatMessageItem=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.id&&"string"==typeof t.tokenName&&"string"==typeof t.userAddress&&"string"==typeof t.content&&"string"==typeof t.createdAt&&"number"==typeof t.flagCount&&"object"==typeof t.reactions},exports.isChatStatusResponse=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"boolean"==typeof t.enabled&&(void 0===t.reason||kI(t.reason))},exports.isClaimableInvite=function(e){if(e.status!==ok.PENDING)return!1;if(null!==e.expiresAt&&void 0!==e.expiresAt){if(nn(e.expiresAt)<=new Date)return!1}return!0},exports.isContentType=bA,exports.isEip1193Provider=QT,exports.isEmptyValue=Gn,exports.isExtendedStreamRole=Mk,exports.isExternalProvider=function(e){return"external"===e.providerType},exports.isFlagAction=EA,exports.isFlagData=AA,exports.isFlagReason=vA,exports.isFlagStatus=wA,exports.isHolderDelta=AI,exports.isHolderDeltaType=function(e){return"string"==typeof e&&(e===EI.NEW_HOLDER||e===EI.EXITED_HOLDER||e===EI.BALANCE_CHANGED)},exports.isLockTokenEntry=$A,exports.isLockTokensData=GA,exports.isMessage=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.id&&"string"==typeof t.type&&(t.type===ES.CHAT_MESSAGE||t.type===ES.COMMENT)&&"string"==typeof t.tokenName&&"string"==typeof t.userAddress&&"string"==typeof t.content&&"string"==typeof t.createdAt},exports.isMessageType=function(e){return e===ES.CHAT_MESSAGE||e===ES.COMMENT},exports.isModeratedToken=zS,exports.isModerationTiered=XI,exports.isModeratorInvite=qS,exports.isNonEmptyString=Kn,exports.isOverseerInviteStatus=ck,exports.isOverseerStatus=lk,exports.isPinnedMessage=II,exports.isPrivateKeyProvider=YT,exports.isPublicInviteInfo=VS,exports.isReactionErrorCode=CI,exports.isRecordingStatus=xk,exports.isSimulcastPlatform=Rk,exports.isStreamChatDeletedEvent=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.messageId&&"string"==typeof t.deletedAt},exports.isStreamChatErrorEvent=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.message},exports.isStreamChatMessage=TI,exports.isStreamChatMessageEvent=function(e){return TI(e)},exports.isStreamChatPinnedEvent=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&II(t.pinnedMessage)},exports.isStreamChatUnpinnedEvent=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.unpinnedMessageId},exports.isStreamReactionErrorEvent=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.message},exports.isStreamReactionEvent=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.emoji&&"number"==typeof t.timestamp&&"number"==typeof t.streamTime},exports.isStreamStatus=_k,exports.isStreamStatusEvent=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&_k(t.status)&&(null===t.playbackId||"string"==typeof t.playbackId)&&"boolean"==typeof t.isLive},exports.isStreamingEvent=function(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.type&&["stream_status","user_banned","user_unbanned","ban_enforcement","content_flagged","flag_resolved","stream_chat_message","stream_chat_updated","stream_chat_deleted","stream_chat_pinned","stream_chat_unpinned","chat_status_changed","viewer_count","recording_status","simulcast_status","download_ready","recordings_count_updated","user_typing","stream_reaction","content_reaction_added","content_reaction_removed","stream_countdown_updated","stream_language_updated","stream_control_status_changed","connection","authenticated","token_subscribed","token_unsubscribed","room_subscribed","room_left"].includes(t.type)},exports.isTokenAccessResult=function(e){if(null==e||"object"!=typeof e)return!1;const t=e,n=t.permissions;return Array.isArray(n)&&n.every(e=>"string"==typeof e)&&(null===t.source||"owner"===t.source||"moderator_invite"===t.source||"api_key"===t.source||"overseer"===t.source)&&(void 0===t.matchedPreset||null===t.matchedPreset||"MODERATOR"===t.matchedPreset||"TECHNICAL_PRODUCER"===t.matchedPreset||"MANAGER"===t.matchedPreset)&&"boolean"==typeof t.isOwner&&"boolean"==typeof t.isOverseer},exports.isTokenBanData=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"number"==typeof t.id&&"string"==typeof t.tokenName&&"string"==typeof t.bannedBy&&"string"==typeof t.createdAt&&(null===t.reason||"string"==typeof t.reason)},exports.isTypingIndicatorEvent=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&Array.isArray(t.typingUsers)&&t.typingUsers.every(NI)},exports.isTypingUser=NI,exports.isUnlockTokenEntry=KA,exports.isUnlockTokensData=HA,exports.isUserBannedEvent=EE,exports.isUserHoldingData=SI,exports.isUserUnbannedEvent=AE,exports.isValidAddress=pr,exports.isValidApiKeyRole=dE,exports.isValidBanDuration=TE,exports.isValidBanReason=kE,exports.isValidChatContent=function(e){return!!Kn(e)&&(e.length>=fn.CHAT_MESSAGE.MIN_LENGTH&&e.length<=fn.CHAT_MESSAGE.MAX_LENGTH)},exports.isValidChatTokenName=function(e){return!!Kn(e)&&on.PATTERN.test(e)},exports.isValidGalaChainChannel=function(e){return Object.values(co).includes(e)},exports.isValidInviteCode=WS,exports.isValidInviteStatus=HS,exports.isValidLaunchTokenData=function(e){return Ys(e).success},exports.isValidModeratorRole=GS,exports.isValidTokenBanReason=Kk,exports.isValidTokenName=function(e,t=on){if("string"!=typeof e)return!1;const n=e.trim();return 0!==n.length&&t.PATTERN.test(n)},exports.isViewerCountEvent=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"number"==typeof t.viewerCount},exports.isWalletAvailable=async function(e,t){return null!==await hI(e,t)},exports.isoDateStringSchema=Gr,exports.launchTokenDataSchema=ss,exports.loadEnvWithFallback=function(){const e=y.join(process.cwd(),"..","..",".env");m.existsSync(e)&&p.config({path:e});const t=y.join(process.cwd(),".env");m.existsSync(t)&&p.config({path:t})},exports.mergeSafePaginationOptions=function(e,t){return fI({...e,...t})},exports.nonNegativeDecimalStringSchema=Rr,exports.normalizeAddressInput=fr,exports.normalizeDataWithMapping=function(e,t){return e.map(e=>{const n={};for(const[r,s]of Object.entries(t)){const t=s(e);void 0!==t&&(n[r]=t)}return n})},exports.normalizeErrorMessage=function(e,t){return e.toLowerCase().includes(t.toLowerCase())},exports.normalizeLimit=Zw,exports.normalizeTokenKey=jt,exports.normalizeTokenName=Vt,exports.normalizeTokenSymbol=Xt,exports.optionalUrlSchema=Dr,exports.pageNumberSchema=Or,exports.paginationResultMetaSchema=vs,exports.parseHttpErrorResponse=function(e){const t={statusCode:0,errorMessage:"Unknown error",raw:e};if(null==e)return t;const n=e;let r=t.statusCode;"number"==typeof n.status?r=n.status:"number"==typeof n.statusCode?r=n.statusCode:"number"==typeof n.code&&(r=n.code);let s,i=t.errorMessage;"string"==typeof n.message?i=n.message:"string"==typeof n.error?i=n.error:e instanceof Error?i=e.message:"string"==typeof e&&(i=e);const o=n.response;if(o){const e=o.data;if("object"==typeof e&&null!==e){s=e;const t=e;"string"==typeof t.message?i=t.message:"string"==typeof t.error&&(i=t.error)}}const a={statusCode:r,errorMessage:i,raw:e};return null!=s&&(a.errorData=s),a},exports.parseLaunchpadVaultAddress=mT,exports.percentileIndexCalculation=function(e,t){if(0===e.length)return-1;if(t<0||t>100)throw new Error(`Percentile must be between 0 and 100, got: ${t}`);const n=(e.length-1)*(t/100),r=Math.floor(n);return Math.min(r,e.length-1)},exports.poolFetchTypeSchema=os,exports.poolPaginationSchema=ps,exports.positiveDecimalStringSchema=xr,exports.priceTickRangeMapping=function(e,t,n=60){const r=ki(e),s=ki(t);if(r.isLessThanOrEqualTo(0)||s.isLessThanOrEqualTo(0))throw new Error("Prices must be positive");if(r.isGreaterThanOrEqualTo(s))throw new Error(`minPrice must be < maxPrice, got: ${r.toString()} >= ${s.toString()}`);const i=Math.floor(Ii(r)),a=Math.ceil(Ii(s)),c=Math.floor(i/n)*n,l=Math.ceil(a/n)*n;return{minTick:c,maxTick:l,actualMinPrice:new o(1.0001).pow(c),actualMaxPrice:new o(1.0001).pow(l)}},exports.privateKeySchema=Wr,exports.providerToWallet=JT,exports.registerInterval=function(e,t){const n=e;return wI.set(n,{createdAt:Date.now(),label:t}),n},exports.requireNonNegative=function(...e){e.forEach(e=>{if(e.isNaN())throw Dt("value","NaN");if(!e.isFinite())throw Rt("value","finite");if(e.isLessThan(0))throw xt("value","0",e.toString())})},exports.requirePositive=_i,exports.requirePositiveWithContext=xi,exports.retryableHttpRequest=async function(e,t){const n=t?.maxRetries??3,r=t?.backoffMs??100,s=t?.retryableStatus??[429,503,504];let i,o=0;for(;o<=n;)try{return await e()}catch(e){i=e,o++;const t=mI(e),a=s.includes(t);if(o>n||!a)throw e;const c=r*Math.pow(2,o-1);await new Promise(e=>setTimeout(e,c))}throw i},exports.reverseBondingCurveConfigSchema=rs,exports.reverseBondingCurveConfigurationSchema=Bs,exports.roleHasSufficientPermission=function(e,t){return e===aE.MANAGER?t!==aE.OWNER:e===aE.OWNER||e===t},exports.roundTickBoundaries=function(e,t,n){if(e>=t)throw new Error(`tickLower must be < tickUpper, got: ${e} >= ${t}`);if(n<=0)throw new Error(`tickSpacing must be > 0, got: ${n}`);return{tickLower:Math.floor(e/n)*n,tickUpper:Math.ceil(t/n)*n}},exports.roundTickToSpacing=function(e,t){if(t<=0)throw new Error(`tickSpacing must be > 0, got: ${t}`);return Math.floor(e/t)*t},exports.safeDivideWithMinimum=function(e,t,n,r="0"){const s=ki(t);if(Ci(s))return ki(r);const i=ki(e).dividedBy(s);if(null!=n){const e=ki(n);if(e.isLessThan(0))throw new Error(`minimum must be >= 0, got: ${e.toString()}`);if(i.isLessThan(e))return e}return i},exports.searchQuerySchema=kr,exports.sellTokensDataSchema=ks,exports.standardLimitSchema=Lr,exports.standardPaginationSchema=hs,exports.stripHexPrefix=ar,exports.subscribeToWalletChanges=function(e){if(!lI())return()=>{};let t=!0,n={wallets:[],byId:new Map,hasWallets:!1};const r=r=>{if(!t)return;const s=r,{info:i,provider:o}=s.detail,a=i.rdns||i.uuid;if(n.byId.has(a))return;const c={id:a,name:i.name,rdns:a,icon:i.icon??"",provider:o,isInjected:!1},l=[...n.wallets,c],u=new Map(n.byId);u.set(c.id,c),n={wallets:l,byId:u,hasWallets:!0,...void 0===l[0]?{}:{primary:l[0]}},e(n)};return window.addEventListener("eip6963:announceProvider",r),dI().then(r=>{t&&(n=r,e(r))}),()=>{t=!1,window.removeEventListener("eip6963:announceProvider",r)}},exports.timestampSchema=Hr,exports.toBackendAddressFormat=hr,exports.toBackendAddressFromEthers=yr,exports.toBaseUnits=pw,exports.tokenCategorySchema=ts,exports.tokenCollectionSchema=ns,exports.tokenDescriptionSchema=Ar,exports.tokenHoldSchema=Ps,exports.tokenListOptionsSchema=Os,exports.tokenNameSchema=wr,exports.tokenSymbolSchema=Er,exports.tokenUrlsSchema=es,exports.tradeCalculationMethodSchema=Ns,exports.tradeCalculationTypeSchema=Cs,exports.tradeLimitSchema=Pr,exports.tradeListParamsSchema=Is,exports.tradePaginationSchema=fs,exports.tradePaginationWithFiltersSchema=ys,exports.tradeTypeBackendSchema=Es,exports.tradeTypeSchema=ws,exports.transactionIdSchema=qr,exports.transformRawApiTokenToDomainModel=function(e){if(null==e||"object"!=typeof e)throw new Error("Token must be an object");const t=e,n=(Kn(t.name)?t.name:void 0)??(Kn(t.tokenName)?t.tokenName:void 0)??"";if(!Kn(n))throw new Error("Token name is required and must be a non-empty string");const r=(Kn(t.symbol)?t.symbol:void 0)??(Kn(t.tokenSymbol)?t.tokenSymbol:void 0)??(Kn(t.collection)?t.collection:void 0)??"";if(!Kn(r))throw new Error("Token symbol is required and must be a non-empty string");let s=8;"number"==typeof t.decimals&&t.decimals>=0&&(s=Math.floor(t.decimals));const i={name:n,symbol:r,decimals:s};return Kn(t.address)&&(i.address=t.address),"boolean"==typeof t.verified&&(i.verified=t.verified),i},exports.trimmedLengthValidation=function(e){return null==e||"string"!=typeof e||0===e.trim().length},exports.uniqueKeySchema=zr,exports.unregisterAllIntervals=function(){const e=wI.size;return wI.clear(),e},exports.unregisterInterval=function(e){const t=e;wI.delete(t)},exports.updateProfileDataSchema=Ls,exports.uploadProfileImageOptionsSchema=Us,exports.urlSchema=Br,exports.userLimitSchema=Ur,exports.userPaginationSchema=gs,exports.userTokenNameSchema=Sr,exports.userTokenTypeSchema=Ds,exports.userTokensPaginationSchema=ms,exports.validateAddress=Ws,exports.validateAmountString=zs,exports.validateBanTokenOptions=Gk,exports.validateBuyTokensData=oi,exports.validateCalculatePreMintData=di,exports.validateChatMessageId=function(e){if(!Kn(e))throw St("id","Message ID");if(!pn.CHAT_MESSAGE.PATTERN.test(e))throw new yt("Invalid message ID format. Expected: chat-{timestamp}-{uuid}","id",mt.INVALID_FORMAT)},exports.validateCheckPoolOptions=Zs,exports.validateConstrainedEnumVariant=function(e,t,n){if(!t.includes(e))throw new yt(`${n} must be one of [${t.map(e=>String(e)).join(", ")}], received "${e}"`,n,"INVALID_ENUM_VALUE")},exports.validateCreateApiKeyOptions=hE,exports.validateCreateChatMessageOptions=function(e){if(!Kn(e.tokenName))throw St("tokenName");if(e.tokenName.length>cn.MAX_LENGTH)throw new yt(`tokenName must be at most ${cn.MAX_LENGTH} characters`,"tokenName",mt.TOO_LONG);JI(e.content)},exports.validateCreateCommentOptions=function(e){if(!Kn(e.tokenName))throw St("tokenName","Token name");const{MIN_LENGTH:t,MAX_LENGTH:n,PATTERN:r}=an;if(e.tokenName.length<t||e.tokenName.length>n||!r.test(e.tokenName))throw kt("tokenName",`${t}-${n} alphanumeric characters`,"Token name");YI(e.content)},exports.validateCreateMessageOptions=function(e){if(void 0===e.type||null===e.type)throw St("type");if(e.type!==ES.CHAT_MESSAGE&&e.type!==ES.COMMENT)throw new yt(`type must be one of: ${Object.values(ES).join(", ")}`,"type",mt.INVALID_VALUE);if(!Kn(e.tokenName))throw St("tokenName");if(e.tokenName.length>cn.MAX_LENGTH)throw new yt(`tokenName must be at most ${cn.MAX_LENGTH} characters`,"tokenName",mt.TOO_LONG);if(!Kn(e.content))throw St("content");if(0===e.content.trim().length)throw Ut("content","Content");const t=e.type===ES.CHAT_MESSAGE?AS.CONTENT.CHAT_MAX_LENGTH:AS.CONTENT.COMMENT_MAX_LENGTH;if(e.content.length>t)throw Lt("content",t,e.content.length)},exports.validateCreateModeratorInviteOptions=function(e){const t=[],n=e.inviteScope??PS.TOKEN;return void 0===e.inviteScope||jS(e.inviteScope)||gt(t,()=>{throw Ot("inviteScope",e.inviteScope,FS,"Invite scope")}),n===PS.TOKEN?gt(t,()=>{jn(e.tokenName??"","tokenName",on)}):n===PS.ALL_OWNER_TOKENS&&void 0!==e.tokenName&&""!==e.tokenName&&t.push("Token name should not be provided for ALL_OWNER_TOKENS scope invites"),GS(e.role)||gt(t,()=>{throw Ot("role",e.role,US,"Role")}),void 0!==e.description&&""!==e.description&>(t,()=>{Mn(e.description,fn.DESCRIPTION.MAX_LENGTH,"description")}),void 0===e.expiresAt||""===e.expiresAt||rn(e.expiresAt)||gt(t,()=>{throw function(e,t="a valid date",n){const r=Et(e,n);return new yt(`${r} must be ${t}`,e,"INVALID_DATE")}("expiresAt","ISO 8601 format")}),t},exports.validateCreateOverseerDirectOptions=yk,exports.validateCreateOverseerInviteOptions=uk,exports.validateCreateTradeData=ii,exports.validateDecimalRangeStrict=function(e,t,n,r){const s="string"==typeof e?parseFloat(e):e;if(!isFinite(s))throw new yt(`${r} must be a valid finite number between ${t} and ${n}`,r,"INVALID_NUMBER");if(s<t||s>n)throw _t(r,t,n,s,r)},exports.validateFeePortionConstraints=Fn,exports.validateFetchGalaBalanceOptions=ti,exports.validateFetchMessagesOptions=function(e){const t=void 0!==e.type,n=void 0!==e.tokenName&&""!==e.tokenName,r=void 0!==e.userAddress&&""!==e.userAddress;if(!t&&!n&&!r)throw Mt(["type","tokenName","userAddress"]);if(void 0!==e.type&&e.type!==ES.CHAT_MESSAGE&&e.type!==ES.COMMENT)throw new yt(`type must be one of: ${Object.values(ES).join(", ")}`,"type",mt.INVALID_VALUE);wS(e.tokenName,e.userAddress),void 0!==e.pageSize&&Wn(0,void 0,dn.MAX_LIMIT,e.pageSize)},exports.validateFetchPoolDetailsData=hi,exports.validateFetchTokenBalanceOptions=si,exports.validateFullName=Vs,exports.validateGetAmountOptions=ui,exports.validateGetChatMessagesOptions=function(e){if(!(void 0!==e.tokenName&&""!==e.tokenName||void 0!==e.userAddress&&""!==e.userAddress))throw new yt("At least one of tokenName or userAddress is required","options",mt.REQUIRED);wS(e.tokenName,e.userAddress),void 0!==e.pageSize&&Wn(0,void 0,dn.MAX_LIMIT,e.pageSize)},exports.validateGetCommentsOptions=function(e){if(!(void 0!==e.tokenName&&""!==e.tokenName||void 0!==e.userAddress&&""!==e.userAddress))throw Mt(["tokenName","userAddress"]);if(void 0!==e.tokenName&&""!==e.tokenName){const{MIN_LENGTH:t,MAX_LENGTH:n,PATTERN:r}=an;if(e.tokenName.length<t||e.tokenName.length>n||!r.test(e.tokenName))throw kt("tokenName",`${t}-${n} alphanumeric characters`,"Token name")}Wn(0,void 0,dn.MAX_LIMIT,e.pageSize,e.cursor)},exports.validateGetTokenBanOptions=qk,exports.validateGetTradeOptions=ci,exports.validateGetTradesOptions=CS,exports.validateImageUploadOptions=Qs,exports.validateInviteCode=function(e){const t=[];return Kn(e)?WS(e)||t.push("Invalid invite code format"):t.push(St("inviteCode","Invite code").message),t},exports.validateLaunchTokenData=fi,exports.validateListApiKeysOptions=pE,exports.validateListModeratorInvitesOptions=function(e){const t=[];return gt(t,()=>{jn(e.tokenName??"","tokenName",on)}),void 0===e.status||HS(e.status)||gt(t,()=>{throw Ot("status",e.status,KS,"Status")}),gt(t,()=>{Wn(0,void 0,ln,e.pageSize)}),t},exports.validateListOverseerInvitesOptions=dk,exports.validateListOverseersOptions=hk,exports.validateListTokenBansOptions=Wk,exports.validateListUsersOptions=mk,exports.validateMessageId=function(e){if(!Kn(e))throw St("id","Message ID");const t=pn.CHAT_MESSAGE.PATTERN.test(e),n=/^msg-\d{13}-[a-f0-9]{32}$/.test(e);if(!t&&!n)throw new yt("Invalid message ID format. Expected: chat-{timestamp}-{uuid} or msg-{timestamp}-{uuid}","id",mt.INVALID_FORMAT)},exports.validateMinMaxRelationship=function(e,t,n,r){const s="string"==typeof e?parseFloat(e):e,i="string"==typeof t?parseFloat(t):t;if(!isFinite(s))throw new yt(`${n} must be a valid finite number`,n,"INVALID_MIN_VALUE");if(!isFinite(i))throw new yt(`${r} must be a valid finite number`,r,"INVALID_MAX_VALUE");if(s>i)throw new yt(`${n} (${s}) must be less than or equal to ${r} (${i})`,n,"INVALID_RANGE")},exports.validateOptionalTokenName=function(e,t="tokenName",n=on){if(null==e)return;if("string"!=typeof e)throw Bt(t,"a string",e);const r=e.trim();if(0!==r.length&&!n.PATTERN.test(r))throw new yt(`${t} must be ${n.MIN_LENGTH}-${n.MAX_LENGTH} alphanumeric characters`,t,mt.INVALID_FORMAT)},exports.validateOverseerInviteCode=gk,exports.validateOverseerInviteId=pk,exports.validateOverseerWalletAddress=fk,exports.validatePaginationParams=function(e,t,n){if("number"!=typeof e||!Number.isInteger(e)||e<0)throw Bt("offset","a non-negative integer",e);Ln(t,"limit")},exports.validateSearchQuery=js,exports.validateSellTokensData=ai,exports.validateSortOrderDirection=Pn,exports.validateTokenDescription=Hs,exports.validateTokenListOptions=ei,exports.validateTokenName=Xn,exports.validateTokenSymbol=Gs,exports.validateTokenUrls=Js,exports.validateTradeListParams=li,exports.validateUnbanTokenOptions=Hk,exports.validateUpdateApiKeyOptions=gE,exports.validateUpdateChatMessageOptions=function(e){JI(e.content)},exports.validateUpdateCommentOptions=function(e){YI(e.content)},exports.validateUpdateMessageOptions=function(e){if(!Kn(e.content))throw St("content");if(0===e.content.trim().length)throw Ut("content","Content");const t=Math.max(AS.CONTENT.CHAT_MAX_LENGTH,AS.CONTENT.COMMENT_MAX_LENGTH);if(e.content.length>t)throw Lt("content",t,e.content.length)},exports.validateUpdatePlatformConfigOptions=vk,exports.validateUpdateProfileData=ni,exports.validateUpdateTokenConfigOptions=SS,exports.validateUploadProfileImageOptions=ri,exports.validateUserTokenName=Xs,exports.validateVaultAddress=qs,exports.vaultAddressSchema=_r,exports.walletToProvider=function(e){if(e)return to.fromWallet(e)},exports.wasModerationEscalated=function(e){return!0===e.escalatedFromQuick};
|
|
1
|
+
"use strict";var e=require("ethers"),t=require("@gala-chain/gswap-sdk"),n=require("zod"),r=require("uuid"),s=require("node:crypto"),i=require("@gala-chain/api"),o=require("bignumber.js"),a=require("socket.io-client"),c=require("axios"),l=require("dotenv"),u=require("fs"),d=require("path");function h(e){var t=Object.create(null);return e&&Object.keys(e).forEach(function(n){if("default"!==n){var r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:function(){return e[n]}})}}),t.default=e,Object.freeze(t)}var g=h(r),f=h(s),p=h(l),m=h(u),y=h(d);const b={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"},v="/v1/users/referrals/url",w="/v1/users/referrals",E="/v1/users/referrals/summary",A="/market/price-series",S="/v1/tokens/:tokenName/start-stream",k="/v1/tokens/:tokenName/stop-stream",T="/v1/tokens/:tokenName/stream/disable",I="/v1/tokens/:tokenName/stream/enable",N="/v1/tokens/:tokenName/reset-key",C="/v1/tokens/:tokenName/recordings",_="/v1/tokens/:tokenName/recordings/:assetId/download",x="/v1/tokens/:tokenName/recordings/:assetId",R="/v1/tokens/:tokenName/simulcasts",B="/v1/tokens/:tokenName/simulcasts",D="/v1/tokens/:tokenName/simulcasts/:targetId",O="/v1/config",M="/v1/config",L="/v1/config",U="/v1/tokens/:tokenName/role",P="/v1/roles",F="/v1/permissions",$="/v1/tokens/:tokenName/credentials",K="/auth/login",G="/auth/logout",W="/auth/refresh",H="/auth/session",q="/v1/tokens/:tokenName/bans",z="/v1/tokens/:tokenName/bans",V="/v1/tokens/:tokenName/bans/:userAddress",j="/v1/tokens/:tokenName/bans/:userAddress",X="/v1/tokens/:tokenName/active-users",Y="/v1/user-bans",J="/v1/user-bans",Q="/v1/user-bans/:userAddress",Z="/v1/user-bans/:userAddress",ee={CREATE:"/v1/api-keys",LIST:"/v1/api-keys",GET:"/v1/api-keys/:id",UPDATE:"/v1/api-keys/:id",REVOKE:"/v1/api-keys/:id"},te="/v1/moderator-invites",ne="/v1/moderator-invites/claim",re="/v1/moderated-tokens",se="/v1/moderator-invites",ie="/v1/moderator-invites/:id",oe="/v1/moderator-invites/:id/role",ae="/v1/moderator-invites/:id",ce="/v1/moderator-invites/code/:code",le={CREATE:"/v1/content-flags",LIST:"/v1/content-flags",DISMISS:"/v1/content-flags/:id/dismiss",ACTION:"/v1/content-flags/:id/action"},ue="/v1/overseer-invites",de="/v1/overseer-invites",he="/v1/overseer-invites/code/:code",ge="/v1/overseer-invites/claim",fe="/v1/overseer-invites/:id",pe="/v1/overseers",me="/v1/overseers",ye="/v1/overseers/:address",be="/v1/overseers/me",ve="/v1/overseer-summary",we="/v1/overseer-summary/bans",Ee="/v1/overseer-summary/token-bans",Ae="/v1/overseer-summary/invites",Se="/v1/overseer-summary/flags",ke="/v1/overseer-summary/users",Te="/v1/users",Ie="/v1/users/:address/summary",Ne="/v1/cache/flush/address/:address",Ce="/v1/cache/flush/token/:tokenName",_e="/v1/cache/flush/all",xe="/v1/cache/flush/wallet-aliases/:address",Re="/v1/cache/flush/wallet-aliases",Be="/v1/token-bans",De="/v1/token-bans",Oe="/v1/token-bans/:tokenName",Me="/v1/token-bans/:tokenName",Le="/v1/reactions",Ue="/v1/reactions",Pe="/v1/trades",Fe={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"},$e="/v1/restricted-token-names",Ke="/v1/restricted-token-names",Ge="/live/:tokenName/chat",We="/live/:tokenName/chat",He="/live/:tokenName/chat",qe="/live/:tokenName/chat/slow-mode",ze={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"},Ve="/v1/stats",je="/v1/trading/fee",Xe="/v1/trading/sale-details",Ye="/v1/trading/quote",Je="/v1/trading/premint-quote",Qe={GET_LEADERBOARD:"/weekly-challenge",GET_TOKEN_HISTORY:"/weekly-challenge/history/:vaultAddress"},Ze="/v1/notifications/register",et="/v1/notifications/unregister",tt="/v1/notifications/preferences",nt="/v1/notifications/preferences",rt="/v1/config/client-flags",st={NATIVE:"native",EXACT:"exact"},it={LOCAL:"local",EXTERNAL:"external"};function ot(e){return e instanceof Error}function at(e){return ot(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 ct(e){return ot(e)||"object"==typeof e&&null!==e&&"stack"in e&&"string"==typeof e.stack?e.stack:void 0}function lt(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 ut(e){return"object"==typeof e&&null!==e&&"message"in e&&("response"in e||"request"in e||"config"in e)}function dt(e,t){if(null==e||"object"!=typeof e)throw new Error(`${t}: No response - expected object, got ${typeof e}`);const n=e;if(!("Status"in n))throw new Error(`${t}: Response missing 'Status' property`);const r=n.Status;if("number"!=typeof r)throw new Error(`${t}: Response Status must be a number, got ${typeof r}`);if(1!==r)throw new Error(`${t}: Response status indicates failure (Status: ${r})`);return n}function ht(e){if(null==e||"object"!=typeof e)return"";const t=e.Message;return"string"==typeof t&&t.trim().length>0?` - ${t}`:""}function gt(e,t,n){try{t()}catch(t){if(!function(e){return e instanceof Error&&"ValidationError"===e.name}(t))throw t;{const n=t.message;e.push(n)}}}const ft="Token name is required and must be a string",pt=e=>`Could not find vault address for token: ${e}`,mt={REQUIRED:"REQUIRED",INVALID_TYPE:"INVALID_TYPE",INVALID_VALUE:"INVALID_VALUE",INVALID_FORMAT:"INVALID_FORMAT",TOO_SHORT:"TOO_SHORT",TOO_LONG:"TOO_LONG",TOO_LARGE:"TOO_LARGE",TOO_SMALL:"TOO_SMALL",EMPTY_ARRAY:"EMPTY_ARRAY",ARRAY_TOO_LARGE:"ARRAY_TOO_LARGE",ZERO_VALUE:"ZERO_VALUE",INVALID_TICK_SPACING:"INVALID_TICK_SPACING",INVALID_FEE_TIER:"INVALID_FEE_TIER",INVALID_RANGE:"INVALID_RANGE",INVALID_PARAMETERS:"INVALID_PARAMETERS",NOT_FOUND:"NOT_FOUND",INVALID_DATA:"INVALID_DATA"};class yt 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 vt extends Error{constructor(e,t){super(e),this.field=t,this.name="ConfigurationError"}}class wt 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 At(e,t){return new yt(`Token "${e}" not found. Please verify the token name is correct.`,"tokenName","TOKEN_NOT_FOUND")}function St(e,t){const n=Et(e,t);return new yt(`${n} is required`,e,"REQUIRED")}function kt(e,t,n){const r=Et(e,n);return new yt(`${r} must be ${t}`,e,"INVALID_FORMAT")}function Tt(e,t,n){return new bt(e,t,n)}function It(e,t){return new vt(e,t)}function Nt(e,t,n){return new wt(e,t,n)}function Ct(e,t,n,r){n&&n.error(`${t}:`,e);const s=ut(e)?e.response?.status:void 0;return Tt(`${t}: ${at(e)}`,s,ot(e)?e:void 0)}function _t(e,t,n,r,s){const i=Et(e,s);return new yt(`${i} must be between ${t} and ${n}${void 0!==r?`, received: ${r}`:""}`,e,"OUT_OF_RANGE")}function xt(e,t,n,r){const s=Et(e,r);return new yt(`${s} must be at least ${t}${void 0!==n?`, received: ${n}`:""}`,e,"TOO_SMALL")}function Rt(e,t,n,r){const s=Et(e,r);return new yt(`${s} must be at most ${t}${void 0!==n?`, received: ${n}`:""}`,e,"TOO_LARGE")}function Bt(e,t,n,r){const s=Et(e,r),i=void 0!==n?`, received: ${"object"==typeof n?"object":String(n)}`:"";return new yt(`${s} must be ${t}${i}`,e,"INVALID_TYPE")}function Dt(e,t,n){const r=Et(e,n);return new yt(`${r} must be a valid number${void 0!==t?`: "${t}"`:""}`,e,"INVALID_NUMBER")}function Ot(e,t,n,r){const s=Et(e,r);return new yt(`Invalid ${s}: ${t}. Must be one of: ${n.join(", ")}`,e,"INVALID_ENUM")}function Mt(e,t){if(e.length<2)return St(void 0!==e[0]&&""!==e[0]?e[0]:"field");let n;if(2===e.length)n=e.join(" or ");else{n=`${e.slice(0,-1).join(", ")} or ${e[e.length-1]??"field"}`}return new yt(`At least one of ${n} must be provided`,e[0],"REQUIRED")}function Lt(e,t,n,r){const s=Et(e,r);return new yt(`${s} must be at most ${t} characters${void 0!==n?`, received: ${n}`:""}`,e,"TOO_LONG")}function Ut(e,t){const n=Et(e,t);return new yt(`${n} cannot be empty`,e,"EMPTY_STRING")}function Pt(e){return null!=e&&"object"==typeof e&&"data"in e}function Ft(e,t,n=!1){const r=!0===e.error,s=n&&(null===e.data||void 0===e.data);if(r||s){const n=e?.statusCode??e.status??void 0;throw Tt(e?.message??t,n)}}function $t(e){if(Pt(e))return e.data}function Kt(e,t="No data found in response"){if(!Pt(e))throw Tt(t);const n=e.data;if(null==n)throw Tt(t);return n}async function Gt(e,t={}){return qt(e,t,e=>{if(void 0===e.data)throw new yt(`${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:r,debugLogEnabled:s=!1}=t;s&&r&&r.debug(`${n}: starting operation`);try{const t=await e();return s&&r&&r.debug(`${n}: completed successfully`),t}catch(e){throw r&&r.error(n,{error:e}),e}}async function Ht(e,t={}){return qt(e,t,e=>e)}async function qt(e,t,n){const{errorContext:r="Operation failed",logger:s,debugLogEnabled:i=!1}=t;i&&s&&s.debug(`${r}: starting operation`);try{const t=await e();if(null==t)throw new yt(`${r}: No response from server`,"response","NO_RESPONSE");return Ft(t,r,!0),i&&s&&s.debug(`${r}: completed successfully`),n(t)}catch(e){throw s&&s.error(r,{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 Vt(e){return e.trim().toLowerCase()}function jt(e){return e.trim().toUpperCase()}function Xt(e){return e.trim().toUpperCase()}var Yt;!function(e){e.DEBUG="DEBUG",e.INFO="INFO",e.WARN="WARN",e.ERROR="ERROR"}(Yt||(Yt={}));class Jt{constructor(e){this.levelPriority={[Yt.DEBUG]:0,[Yt.INFO]:1,[Yt.WARN]:2,[Yt.ERROR]:3},this.debugEnabled=e.debug,this.context=e.context??"SDK",this.minLevel=e.minLevel??(e.debug?Yt.DEBUG:Yt.INFO)}debug(e,t){this.log(Yt.DEBUG,e,t)}info(e,t){this.log(Yt.INFO,e,t)}warn(e,t){this.log(Yt.WARN,e,t)}error(e,t){this.log(Yt.ERROR,e,t)}log(e,t,n){if(this.levelPriority[e]<this.levelPriority[this.minLevel])return;if(e===Yt.DEBUG&&!this.debugEnabled)return;const r=`[${(new Date).toISOString()}] [${this.context}] [${e}]`,s=this.getConsoleMethod(e);void 0!==n?ot(n)?s(`${r} ${t}`,n.message,ct(n)??""):s(`${r} ${t}`,n):s(`${r} ${t}`)}getConsoleMethod(e){switch(e){case Yt.DEBUG:return console.debug;case Yt.INFO:return console.info;case Yt.WARN:return console.warn;case Yt.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[Yt.DEBUG]>=this.levelPriority[this.minLevel]}}function Qt(e){return"string"==typeof e&&e.trim().length>0}function Zt(e){return null==e||""===e}function en(e){return null==e}const tn=new Jt({debug:!1,context:"DateUtils"});function nn(e,t){if(null==e)return new Date;if(e instanceof Date)return isNaN(e.getTime())?new Date:e;try{const t=new Date(e);return isNaN(t.getTime())?(tn.warn(`Invalid date string received: "${e}". Using fallback.`),new Date):t}catch(t){return tn.warn(`Date parsing error for "${e}":`,t),new Date}}function rn(e){if(null==e)return!1;if(e instanceof Date)return!isNaN(e.getTime());if("string"!=typeof e)return!1;const t=new Date(e);return!isNaN(t.getTime())}function sn(e){return Date.now()-e}const on={MIN_LENGTH:3,MAX_LENGTH:20,PATTERN:/^[a-zA-Z0-9]{3,20}$/},an={MIN_LENGTH:2,MAX_LENGTH:20,PATTERN:/^[a-zA-Z0-9]+$/},cn={MIN_LENGTH:1,MAX_LENGTH:50},ln=100,un=20,dn={MAX_LIMIT:50,DEFAULT_OFFSET:0,DEFAULT_LIMIT:20},hn={PATTERN:/^(eth\|[0-9a-fA-F]{40}|client\|[a-zA-Z0-9_-]+)$/},gn={MAX_LENGTH:100},fn={COMMENTS_V1:{MAX_LENGTH:2e3},CHAT_MESSAGE:{MIN_LENGTH:1,MAX_LENGTH:500},CHAT_MESSAGES_V1:{MAX_LENGTH:500},BAN_REASON:{MAX_LENGTH:500},DESCRIPTION:{MAX_LENGTH:255},FLAG_DETAILS:{MAX_LENGTH:1e3},CONTENT_ID:{MAX_LENGTH:100}},pn={CHAT_MESSAGE:{PATTERN:/^chat-\d{13}-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i},CONTENT_REACTION:{MAX_LENGTH:64,PATTERN:/^(msg-\d{13}-[a-f0-9]{32}|chat-\d{13}-[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})$/}},mn=60,yn=31536e3,bn={MAX_LENGTH:64,PATTERN:/^(galaswap-operation-|galaconnect-operation-)/},vn={PATTERN:/^[a-fA-F0-9]{64}$/},wn={STREAM_URL_PATTERN:/^(rtmps?|srt):\/\/.+/},En=50,An=1,Sn=100,kn={FULL_NAME:{MIN_LENGTH:1,MAX_LENGTH:100,ALPHABETS_ONLY_PATTERN:/^[a-zA-Z]+(?:\s[a-zA-Z]+)?$/}};function Tn(e,t){if(Zt(e))return t;try{return JSON.parse(e)}catch{return t}}function In(e,t=0){if(Zt(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 Nn(e,t,n){if(en(e))return t;if("number"==typeof e)return isNaN(e)?t:e;const r=Number(e);return isNaN(r)?t:r}function Cn(e,t,n){if(en(e))return t;if("bigint"==typeof e)try{return Number(e)}catch{return t}if("number"==typeof e)return isNaN(e)?t:Math.floor(e);const r=parseInt(String(e),10);return isNaN(r)?t:r}function _n(e,t){if(en(e)||""===e)throw St(t);if(o.isBigNumber(e)){if(e.isNaN())throw Dt(t,"NaN");return e}try{const n=new o(e);if(n.isNaN())throw Dt(t,e);if(!n.isFinite())throw Dt(t,e);return n}catch(n){if(n instanceof yt)throw n;throw Dt(t,e)}}function xn(e,t=0){if(en(e))return t;if("number"==typeof e)return isNaN(e)?t:e;return In(String(e).replace("%","").trim(),t)}function Rn(e,t=18){const n=In(e,0);if(0===n)return"0";return n.toFixed(t).replace(/\.?0+$/,"")}function Bn(e){return Rn(e,8)}function Dn(e){return Rn(e,18)}function On(e,t,n,r){if("number"!=typeof e)throw Bt(r,"a number",e,r);if(e<t||e>n)throw _t(r,t,n,e)}function Mn(e,t,n){if("string"!=typeof e)throw Bt(n,"a string",e,n);if(e.length>t)throw Rt(n,t,e.length)}function Ln(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 xt(t,1,e,t)}function Un(e,t,n=!1){if("string"!=typeof e)throw Bt(t,"a string",e,t);if(!n&&0===e.trim().length)throw St(t,`${t} (non-empty string)`)}function Pn(e,t){if("ASC"!==e&&"DESC"!==e)throw new yt(`${t} must be either 'ASC' or 'DESC'`,t,"INVALID_ENUM_VALUE")}function Fn(e,t,n){const r="string"==typeof e?parseFloat(e):e,s="string"==typeof t?parseFloat(t):t;if(!isFinite(r))throw new yt(`${n} minFee must be a valid finite number`,n,"INVALID_FEE_MINIMUM");if(!isFinite(s))throw new yt(`${n} maxFee must be a valid finite number`,n,"INVALID_FEE_MAXIMUM");if(r<.1)throw new yt(`${n} minFee must be >= 0.1, received ${r}`,n,"INVALID_FEE_MINIMUM");if(s>.5)throw new yt(`${n} maxFee must be <= 0.5, received ${s}`,n,"INVALID_FEE_MAXIMUM");if(r>s)throw new yt(`${n} minFee (${r}) must be <= maxFee (${s})`,n,"INVALID_FEE_RANGE")}const $n={ETH_ADDRESS:/^0x[0-9a-fA-F]{40}$/,BACKEND_ADDRESS:/^eth\|(0x)?[0-9a-fA-F]{40}$/,CLIENT_ADDRESS:/^client\|[a-zA-Z0-9_-]+$/},Kn=Qt,Gn=Zt,Wn=en;function Hn(e,t,n=100,r,s){if(void 0!==s&&"string"!=typeof s)throw new yt("cursor must be a string","cursor",mt.INVALID_TYPE);const i=r??t,o=void 0!==r?"pageSize":"limit";if(void 0!==i&&(Ln(i,o),i>n))throw new yt(`${o} must be at most ${n}`,o,mt.TOO_LARGE)}function qn(e){const t=Object.values(e);return e=>"string"==typeof e&&t.includes(e)}function zn(e){return Object.values(e)}function Vn(e,t,n,r={}){const{description:s="parameter",treatEmptyAsNull:i=!0}=r,o=e[t],a=e[n],c=null!=o&&(!i||""!==o),l=null!=a&&(!i||""!==a);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 jn(e,t="tokenName",n=on){if(!Kn(e))throw St(t);const r=e.trim();if(0===r.length)throw St(t);if(r.length<n.MIN_LENGTH)throw _t(t,n.MIN_LENGTH,n.MAX_LENGTH,r.length,`${t} length`);if(r.length>n.MAX_LENGTH)throw _t(t,n.MIN_LENGTH,n.MAX_LENGTH,r.length,`${t} length`);if(!n.PATTERN.test(r))throw new yt(`${t} must contain only alphanumeric characters`,t,mt.INVALID_FORMAT)}function Xn(e,t="tokenName",n=on){if(null==e)throw St(t,t);if("string"!=typeof e)throw Bt(t,"a string",e);const r=e.trim();if(0===r.length)throw St(t,t);if(!n.PATTERN.test(r))throw new yt(`${t} must be ${n.MIN_LENGTH}-${n.MAX_LENGTH} alphanumeric characters`,t,mt.INVALID_FORMAT)}function Yn(e){return t=>{if(null==t||"object"!=typeof t)return!1;const n=t;for(const{field:t,type:r,nullable:s=!1,optional:i=!1,validator:o}of e){const e=n[t];if((!i||void 0!==e)&&(!s||null!==e)){if(typeof e!==r)return!1;if(o&&!o(e))return!1}}return!0}}const Jn={requiredString:e=>t=>Wn(t)?`${e} is required`:"string"!=typeof t?`${e} must be a string`:0===t.trim().length?`${e} cannot be empty`:void 0,maxLength:(e,t)=>n=>{if(!Gn(n))return"string"!=typeof n?`${e} must be a string`:n.length>t?`${e} must be at most ${t} characters`:void 0},positiveInteger:e=>t=>{if(!Wn(t))return"number"==typeof t&&Number.isInteger(t)?t<1?`${e} must be a positive integer`:void 0:`${e} must be an integer`},requiredPositiveInteger:e=>t=>Wn(t)?`${e} is required`:"number"==typeof t&&Number.isInteger(t)?t<1?`${e} must be a positive integer`:void 0:`${e} must be an integer`,enumValue:(e,t)=>n=>{if(!Wn(n))return t.includes(n)?void 0:`${e} must be one of: ${t.join(", ")}`},requiredEnumValue:(e,t)=>n=>Wn(n)?`${e} is required`:t.includes(n)?void 0:`${e} must be one of: ${t.join(", ")}`,isoDate:e=>t=>{if(!Wn(t))return"string"!=typeof t?`${e} must be a string`:rn(t)?void 0:`${e} must be a valid ISO 8601 date string`},walletAddress:(e,t=!1)=>n=>{if(Wn(n))return t?`${e} is required`:void 0;if("string"!=typeof n)return`${e} must be a string`;return $n.ETH_ADDRESS.test(n)||$n.BACKEND_ADDRESS.test(n)||$n.CLIENT_ADDRESS.test(n)?void 0:`${e} must be a valid wallet address`}};function Qn(e){return""===e||0===e.trim().length}function Zn(e,t,n){if(!Wn(e)){if("string"!=typeof e)throw Bt(t,"a string",e,t);if(e.length>n)throw new yt(`${t} must be at most ${n} characters`,t,mt.TOO_LARGE)}}function er(e,t){Wn(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 yt(`${t} must be a valid date`,t,mt.INVALID_FORMAT)}(e,t)}function tr(e,t,n){try{Ln(e,t)}catch{throw function(e,t,n,r="OPERATION_FAILED"){return new yt(`${e} failed: ${t}`,n,r)}(n,"must be a positive integer",t)}}function nr(e,t,n="status"){void 0!==e&&function(e,t,n){const r=Object.values(t);if(!r.includes(e))throw new yt(`${n} must be one of: ${r.join(", ")}`,n,mt.INVALID_FORMAT)}(e,t,n)}class rr{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 vt("JWT authentication required. Call sdk.login() first.")}return this.jwtAuth.getJwtHeaders()}isCalledFromUserCode(){const e=ct(new Error)??"";return!(!e.includes("expect")&&!e.includes("jest"))||!(!e.includes("tests/")&&!e.includes(".test.ts"))}validatePositiveInteger(e,t,n){tr(e,t,n)}}class sr{constructor(e=!1,t){this.logger=t||new Jt({debug:e,context:this.constructor.name})}}class ir extends sr{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 or extends ir{constructor(e=!1){super(e)}normalizeKey(e){return Vt(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>=or.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,r)=>{n.lastUpdated<e&&(e=n.lastUpdated);let s=0;s+=2*r.length,void 0!==n.reverseBondingCurveMinFeeFactor&&(s+=8),void 0!==n.reverseBondingCurveMaxFeeFactor&&(s+=8),void 0!==n.reverseBondingCurveNetFeeFactor&&(s+=8),s+=8,void 0!==n.vaultAddress&&""!==n.vaultAddress&&(s+=2*n.vaultAddress.length),void 0!==n.maxSupply&&""!==n.maxSupply&&(s+=2*n.maxSupply.length),void 0!==n.symbol&&""!==n.symbol&&(s+=2*n.symbol.length),s+=32,t+=s}),{cacheSize:t,oldestEntry:this.cache.size>0?e:0}}getByTokenId(e){const t=`token:${Vt(e)}`;return this.cache.get(t)??null}setByTokenId(e,t){const n=`token:${Vt(e)}`;this.updateCacheEntry(n,t)}hasByTokenId(e){const t=`token:${Vt(e)}`;return this.cache.has(t)}}function ar(e){return""===e?"":e.startsWith("0x")?e.slice(2):e}or.MAX_CACHE_SIZE=1e4;const cr={ETHEREUM:$n.ETH_ADDRESS,ETHEREUM_NO_PREFIX:/^[a-fA-F0-9]{40}$/,BACKEND:$n.BACKEND_ADDRESS,CLIENT:$n.CLIENT_ADDRESS};class lr{toBackendFormat(t){if(!Kn(t))throw new yt("Address is required and must be a string","address","REQUIRED");let n=t;if(t.startsWith("eth|")){if(n=t.slice(4),!/^[a-fA-F0-9]{40}$/.test(n))throw new yt(`Invalid Ethereum address format in backend address. Expected 40 hex characters after 'eth|'. Got: "${t}"`,"address","INVALID_FORMAT");return t}if(n=ar(t),!/^[a-fA-F0-9]{40}$/.test(n))throw new yt(`Invalid Ethereum address format. Expected 40 hex characters (with or without 0x prefix). Got: "${t}"`,"address","INVALID_FORMAT");return`eth|${e.getAddress(`0x${n}`).slice(2)}`}toEthereumFormat(e){if(!Kn(e))throw new yt("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 yt(`Invalid backend address format. Expected "eth|{40-hex-characters}" or "eth|0x{40-hex-characters}". Got: "${e}"`,"address","INVALID_FORMAT");const n=t[1],r=void 0!==n&&""!==n?6:4;return`0x${e.substring(r)}`}normalizeInput(e){if(void 0!==e&&""!==e){if(e.startsWith("client|")){if(!cr.CLIENT.test(e))throw new yt(`Invalid client address format: "${e}"`,"address","INVALID_FORMAT");return e}if(e.startsWith("eth|")){if(!cr.BACKEND.test(e))throw new yt(`Invalid backend address format: "${e}"`,"address","INVALID_FORMAT");return e}return this.toBackendFormat(e)}}isValid(e){return!!Kn(e)&&(!!cr.ETHEREUM.test(e)||(!!cr.ETHEREUM_NO_PREFIX.test(e)||(!!cr.BACKEND.test(e)||!!cr.CLIENT.test(e))))}assertValid(e,t="address"){if(!this.isValid(e))throw new yt(`${t} must be a valid wallet address (Ethereum or backend format)`,t,"INVALID_FORMAT")}detectFormat(e){return Kn(e)?cr.ETHEREUM.test(e)||cr.ETHEREUM_NO_PREFIX.test(e)?"ethereum":cr.BACKEND.test(e)?"backend":cr.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 ar(e).toLowerCase();if(/^[a-fA-F0-9]{40}$/.test(e))return e.toLowerCase();throw new yt(`Cannot extract hex from address: "${e}". Expected Ethereum or backend format.`,"address","INVALID_FORMAT")}}const ur=new lr,dr=ar;function hr(e){return ur.toBackendFormat(e)}function gr(e){return ur.toEthereumFormat(e)}function fr(e){return ur.normalizeInput(e)}function pr(e){return ur.isValid(e)}function mr(e,t="address"){ur.assertValid(e,t)}function yr(e){const t="string"==typeof e?e:e.address;return ur.toBackendFormat(t)}function br(e){return ur.detectFormat(e)}var vr=Object.freeze({__proto__:null,AddressFormatter:lr,assertValidWalletAddress:mr,detectFormat:br,fromBackendAddressFormat:gr,isValidAddress:pr,normalizeAddressInput:fr,stripHexPrefix:dr,toBackendAddressFormat:hr,toBackendAddressFromEthers:yr});const wr=n.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"),Er=n.z.string({message:"Token symbol is required"}).min(1,"Token symbol must be at least 1 character").max(8,"Token symbol must be at most 8 characters").regex(/^[A-Z]{1,8}$/,"Token symbol must be uppercase letters only"),Ar=n.z.string({message:"Token description is required"}).min(1,"Token description is required").max(500,"Token description must be at most 500 characters"),Sr=n.z.string().min(1,"Token name must be at least 1 character").max(50,"Token name must be at most 50 characters"),kr=n.z.string().min(1,"Search query must be at least 1 character").max(100,"Search query must be at most 100 characters"),Tr=n.z.string().min(1,"Full name is required").max(100,"Full name must be at most 100 characters").regex(/^[a-zA-Z\s]+$/,"Full name can only contain letters and spaces"),Ir=n.z.string().regex($n.BACKEND_ADDRESS,"Address must be in format: eth|[40-hex-chars]"),Nr=n.z.string().regex($n.ETH_ADDRESS,"Invalid Ethereum address format"),Cr=n.z.string().refine(e=>$n.BACKEND_ADDRESS.test(e)||$n.ETH_ADDRESS.test(e)||$n.CLIENT_ADDRESS.test(e),"Address must be eth|[40-hex], 0x[40-hex], or client|[identifier] format").transform(e=>(new lr).normalizeInput(e)??e),_r=n.z.string().refine(e=>$n.BACKEND_ADDRESS.test(e)||/^service\|Token\$Unit\$[A-Z0-9]+\$eth:[0-9a-fA-F]{40}\$launchpad$/.test(e),"Invalid vault address format"),xr=n.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>In(e,0)>0,"Amount must be greater than zero"),Rr=n.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>In(e,0)>=0,"Amount must be zero or greater"),Br=n.z.string().url("Must be a valid URL").regex(/^https?:\/\//,"URL must start with http:// or https://"),Dr=n.z.string().optional().refine(e=>void 0===e||""===e||/^https?:\/\/.+\..+/.test(e),"Must be a valid URL if provided"),Or=n.z.number().int("Page must be an integer").min(1,"Page must be at least 1").max(1e3,"Page must be at most 1000").default(1);function Mr(e=100){return n.z.number().int("Limit must be an integer").min(1,"Limit must be at least 1").max(e,`Limit must be at most ${e}`).default(10)}const Lr=Mr(100),Ur=Mr(20),Pr=Mr(20),Fr=n.z.number().int("File size must be an integer").min(1,"File must be at least 1 byte").max(10485760,"File must be at most 10MB"),$r=n.z.string().max(255,"Filename must be at most 255 characters"),Kr=n.z.enum(["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"]),Gr=n.z.string().datetime("Must be a valid ISO 8601 date string"),Wr=n.z.number().int("Timestamp must be an integer").min(0,"Timestamp must be non-negative"),Hr=n.z.string().regex(/^0x[a-fA-F0-9]{64}$/,"Private key must be format: 0x + 64 hex characters"),qr=n.z.string().regex(/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/,"Transaction ID must be in UUID format"),zr=n.z.string().regex(/^galaconnect-operation-[a-z0-9-]+$/,"Unique key must be format: galaconnect-operation-{unique-id}"),Vr=[".png",".jpg",".jpeg",".gif",".webp",".svg"],jr=n.z.object({file:n.z.union([n.z.instanceof(File),n.z.instanceof(Buffer)]),name:$r,size:Fr,type:Kr}),Xr=n.z.instanceof(File).refine(e=>e.size>=1&&e.size<=10485760,"File size must be between 1 byte and 10MB").refine(e=>["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"].includes(e.type),"File must be a valid image type (PNG, JPG, JPEG, GIF, WebP, or SVG)").refine(e=>e.name.length<=255,"Filename must be at most 255 characters"),Yr=n.z.instanceof(Buffer).refine(e=>e.length>=1&&e.length<=10485760,"Buffer size must be between 1 byte and 10MB"),Jr=n.z.union([Xr,Yr]),Qr=n.z.enum([".png",".jpg",".jpeg",".gif",".webp",".svg"]),Zr=$r.refine(e=>{const t=e.slice(e.lastIndexOf(".")).toLowerCase();return Vr.includes(t)},`Filename must end with one of: ${Vr.join(", ")}`),es=n.z.object({websiteUrl:Dr,telegramUrl:Dr,twitterUrl:Dr,instagramUrl:Dr,facebookUrl:Dr,redditUrl:Dr,tiktokUrl:Dr}).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"),ts=n.z.string().min(1,"Token category must not be empty").default("Unit"),ns=n.z.string().min(1,"Token collection must not be empty").default("Token"),rs=n.z.object({minFeePortion:n.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal string").refine(e=>In(e,0)>=.1,"Minimum fee must be >= 0.1").refine(e=>In(e,0)<=.5,"Minimum fee must be <= 0.5"),maxFeePortion:n.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal string").refine(e=>In(e,0)>=.1,"Maximum fee must be >= 0.1").refine(e=>In(e,0)<=.5,"Maximum fee must be <= 0.5")}).refine(e=>In(e.maxFeePortion,0)>=In(e.minFeePortion,0),{message:"Maximum fee must be >= minimum fee",path:["maxFeePortion"]}),ss=n.z.object({tokenName:wr,tokenSymbol:Er,tokenDescription:Ar,tokenImage:n.z.union([n.z.instanceof(File),n.z.instanceof(Buffer),n.z.string().url("Token image must be a valid URL")]).optional(),preBuyQuantity:Rr.default("0"),websiteUrl:Dr,telegramUrl:Dr,twitterUrl:Dr,instagramUrl:Dr,facebookUrl:Dr,redditUrl:Dr,tiktokUrl:Dr,tokenCategory:ts,tokenCollection:ns,reverseBondingCurveConfiguration:rs.optional(),saleStartTime:n.z.number().int().positive().optional(),privateKey:Hr.optional()}),is=n.z.object({file:n.z.union([n.z.instanceof(File),n.z.instanceof(Buffer)]),tokenName:wr}),os=n.z.enum(["RECENT","POPULAR"]),as=n.z.object({tokenName:wr.optional(),symbol:Er.optional()}).refine(e=>void 0!==e.tokenName||void 0!==e.symbol,"At least one of tokenName or symbol is required"),cs=n.z.enum(["NATIVE","MEME"]),ls=n.z.enum(["IN","OUT"]),us=n.z.object({from:n.z.number().int("From timestamp must be an integer").min(173e6,"From timestamp must be at least 173000000"),to:n.z.number().int("To timestamp must be an integer").min(173e6,"To timestamp must be at least 173000000"),resolution:n.z.number().int("Resolution must be an integer").min(1,"Resolution must be at least 1"),tokenName:wr}),ds=n.z.object({tokenName:wr,slippageToleranceFactor:n.z.number().min(0).max(1).optional(),maxAcceptableReverseBondingCurveFeeSlippageFactor:n.z.number().min(0).max(1).optional(),privateKey:Hr.optional()}),hs=n.z.object({offset:n.z.number().int().min(0).default(0),pageSize:n.z.number().int().min(1).max(100).default(10)}),gs=n.z.object({offset:n.z.number().int().min(0).default(0),pageSize:n.z.number().int().min(1).max(20).default(10)}),fs=n.z.object({offset:n.z.number().int().min(0).default(0),pageSize:n.z.number().int().min(1).max(20).default(10)}),ps=hs.extend({type:n.z.enum(["RECENT","POPULAR"]).optional(),tokenName:n.z.string().min(1).max(50).optional(),search:n.z.string().min(1).max(100).optional()}),ms=gs.extend({tokenName:n.z.string().min(1).max(50).optional(),search:n.z.string().min(1).max(100).optional()}),ys=fs.extend({tradeType:n.z.enum(["BUY","SELL"]).optional(),tokenName:n.z.string().min(1).max(50).optional(),userAddress:n.z.string().regex(/^(0x[a-fA-F0-9]{40}|eth\|[a-fA-F0-9]{40})$/).optional(),startDate:n.z.string().datetime().optional(),endDate:n.z.string().datetime().optional(),sortOrder:n.z.enum(["ASC","DESC"]).default("DESC")}),bs={page:n.z.number().int().min(1),limit:n.z.number().int().min(1),total:n.z.number().int().min(0),totalPages:n.z.number().int().min(0),hasNext:n.z.boolean(),hasPrevious:n.z.boolean()},vs=n.z.object(bs);const ws=n.z.enum(["buy","sell"]),Es=n.z.enum(["BUY","SELL"]),As=n.z.object({tradeType:ws,tokenAmount:xr,vaultAddress:_r,userAddress:Cr,slippageTolerance:xr.optional(),deadline:n.z.number().int().positive().optional()}),Ss=n.z.object({tokenSymbol:Er,nativeTokenQuantity:xr,expectedToken:xr,maxAcceptableReverseBondingCurveFee:Rr.default("0").optional()}),ks=n.z.object({tokenSymbol:Er,tokenQuantity:xr,expectedNativeToken:xr,maxAcceptableReverseBondingCurveFee:Rr.default("0").optional()}),Ts=fs.extend({tokenName:Sr.optional()}),Is=n.z.object({page:n.z.number().int().min(1).max(1e3).default(1).optional(),limit:n.z.number().int().min(1).max(20).default(10).optional()}),Ns=n.z.enum(["NATIVE","MEME"]),Cs=n.z.enum(["IN","OUT"]),_s=n.z.object({type:Ns,method:Cs,vaultAddress:_r,amount:xr}),xs=n.z.object({nativeTokenQuantity:xr}),Rs=n.z.object({vaultAddress:_r}),Bs=n.z.object({minFeePortion:xr,maxFeePortion:xr}),Ds=n.z.enum(["both","held","created"]),Os=gs.extend({type:Ds.optional(),address:Cr.optional(),search:kr.optional(),tokenName:Sr.optional()}),Ms=n.z.object({address:Cr.optional(),refresh:n.z.boolean().optional()}),Ls=n.z.object({profileImage:n.z.string(),fullName:Tr,address:Cr,privateKey:Hr.optional()}),Us=n.z.object({file:n.z.union([n.z.instanceof(File),n.z.instanceof(Buffer)]),address:Cr.optional(),privateKey:Hr.optional()}),Ps=n.z.object({created:n.z.number(),createdBy:n.z.string(),expires:n.z.number(),instanceId:n.z.string(),lockAuthority:n.z.string(),name:n.z.string(),quantity:n.z.string(),vestingPeriodStart:n.z.number()}),Fs=n.z.object({address:Cr,tokenId:n.z.union([n.z.string(),n.z.object({collection:n.z.string(),category:n.z.string(),type:n.z.string(),additionalKey:n.z.string()}),n.z.object({collection:n.z.string(),category:n.z.string(),type:n.z.string(),additionalKey:n.z.string(),instance:n.z.string()})]).optional(),tokenName:Sr.optional(),withExpired:n.z.boolean().optional()}).refine(e=>void 0!==e.tokenId||void 0!==e.tokenName,"At least one token identifier (tokenId or tokenName) is required");function $s(e){return t=>{const n=e.safeParse(t);return{success:n.success,data:n.success?n.data:void 0,errors:n.success?void 0:n.error.issues.map(e=>e.message)}}}const Ks=$s(wr),Gs=$s(Er),Ws=$s(Ar),Hs=$s(Cr),qs=$s(_r),zs=$s(xr),Vs=$s(Tr),js=$s(kr),Xs=$s(Sr),Ys=$s(ss),Js=$s(es),Qs=$s(is),Zs=$s(as),ei=$s(Os),ti=$s(Ms),ni=$s(Ls),ri=$s(Us),si=$s(Fs),ii=$s(As),oi=$s(Ss),ai=$s(ks),ci=$s(Ts),li=$s(Is),ui=$s(_s),di=$s(xs),hi=$s(Rs);function gi(e){const t=Ys(e);return t.success?[]:t.errors??["Unknown validation error"]}function fi(e){const t=gi(e);if(t.length>0)throw new Error(`LaunchTokenData validation failed:\n${t.map(e=>`- ${e}`).join("\n")}`)}function pi(e,t){return"string"==typeof e[t]}function mi(e,t){return void 0===e[t]||"string"==typeof e[t]}function yi(e,t){return void 0===e[t]||"number"==typeof e[t]}function bi(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 vi(e){return t=>{if(null==t||"object"!=typeof t||Array.isArray(t))return!1;const n=t;for(const[t,r]of Object.entries(e)){if(!bi(n[t],r))return!1}return!0}}qn({BUY:"buy",SELL:"sell"});const wi=vi({vaultAddress:"string"}),Ei=vi({nativeTokenQuantity:"string"});function Ai(e){if(Wn(e)||"object"!=typeof e)return{};const t={};for(const[n,r]of Object.entries(e))Wn(r)||(Kn(r)?t[n]=r:"number"==typeof r||"boolean"==typeof r?t[n]=r.toString():Array.isArray(r)?t[n]=r.join(","):t[n]="object"==typeof r?JSON.stringify(r):String(r));return t}var Si=Object.freeze({__proto__:null,adaptQueryParams:Ai});function ki(e,t="0"){return function(e,t="0"){if(Zt(e))return new o(t);if(o.isBigNumber(e))return e.isNaN()?new o(t):e;try{const n=new o(e);return n.isNaN()||!n.isFinite()?new o(t):n}catch{return new o(t)}}(e,t)}function Ti(e,t){return void 0!==t?ki(e).toFixed(t):ki(e).toFixed()}function Ii(e){const t=ki(e),n=Math.log(1.0001),r=t.toNumber();return Math.log(r)/n}function Ni(e){return ki(e).isZero()}function Ci(e,t){return ki(e).isLessThan(ki(t))}function _i(...e){e.forEach(e=>{if(e.isNaN())throw Dt("value","NaN");if(!e.isFinite())throw Rt("value","finite");if(e.isLessThanOrEqualTo(0))throw xt("value","0",e.toString())})}function xi(e,t,n){if(e.isNaN())throw Dt(t,"NaN");if(!e.isFinite())throw Rt(t,"finite");if(e.isLessThanOrEqualTo(0))throw xt(t,"0",e.toString())}function Ri(e,t,n="0"){const r=ki(t);return Ni(r)?ki(n):ki(e).dividedBy(r)}const Bi={calculateBuyWithExact(e,t){const n=In(e),r=In(t),{BASE_PRICE:s,PRICE_SCALING_FACTOR:i,TRADING_FEE_FACTOR:o,GAS_FEE:a}=zt,c=function(e,t){const n=Math.pow(10,t);return Math.ceil(e*n)/n}(s*(Math.exp((r+n)*i)-Math.exp(r*i))/i,8),l=Ti(ki(c).multipliedBy(o));return{amount:c.toString(),reverseBondingCurveFee:"0",transactionFee:l,gasFee:a}},calculateBuyWithNative(e,t){const n=In(e),r=In(t),{BASE_PRICE:s,PRICE_SCALING_FACTOR:i,TRADING_FEE_FACTOR:o,GAS_FEE:a}=zt,c=Math.log(n*i/s+Math.exp(r*i))/i-r,l=Ti(ki(c).multipliedBy(o));return{amount:c.toString(),reverseBondingCurveFee:"0",transactionFee:l,gasFee:a}},calculateSellWithExact(e,t,n,r,s){const i=In(e),o=In(t),a=In(n),{BASE_PRICE:c,PRICE_SCALING_FACTOR:l,TRADING_FEE_FACTOR:u,GAS_FEE:d}=zt,h=c*(Math.exp(o*l)-Math.exp((o-i)*l))/l,g=ki(h),f=r+o/a*(s-r),p=Ti(g.multipliedBy(f),8),m=Ti(g.multipliedBy(u));return{amount:h.toString(),reverseBondingCurveFee:p,transactionFee:m,gasFee:d}},calculateSellWithNative(e,t,n,r,s){const i=In(e),o=In(t),a=In(n),{BASE_PRICE:c,PRICE_SCALING_FACTOR:l,TRADING_FEE_FACTOR:u,GAS_FEE:d}=zt;if(i>=c*(Math.exp(o*l)-1)/l){const e=ki(i),t=r+o/a*(s-r),n=Ti(e.multipliedBy(t),8),c=Ti(e.multipliedBy(u));return{amount:o.toString(),reverseBondingCurveFee:n,transactionFee:c,gasFee:d}}const h=o-Math.log(Math.exp(o*l)-i*l/c)/l,g=ki(i),f=r+o/a*(s-r),p=Ti(g.multipliedBy(f),8),m=Ti(g.multipliedBy(u));return{amount:h.toString(),reverseBondingCurveFee:p,transactionFee:m,gasFee:d}}};class Di extends Error{constructor(e,t,n){super(e),this.filename=t,this.mimeType=n,this.name="FileValidationError"}}function Oi(e,t,n){if(null==e)throw new Di("File is required",t,n);if("undefined"!=typeof File&&e instanceof File){const t=Xr.safeParse(e);if(!t.success){const n=t.error.issues.map(e=>e.message).join("; ");throw new Di(n,e.name,e.type)}return}if(Buffer.isBuffer(e)){if(void 0===t||""===t)throw new Di("Filename is required when uploading Buffer objects",t,n);const r=Yr.safeParse(e);if(!r.success){const e=r.error.issues.map(e=>e.message).join("; ");throw new Di(e,t,n)}try{Mn(t,255,"filename")}catch(e){throw new Di(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 Di(`Invalid file type "${n}" is not allowed. Allowed types: ${s.join(", ")}`,t,n);const i=function(e){if(null==e||""===e)return"";const t=e.lastIndexOf(".");if(-1===t)return"";return e.substring(t).toLowerCase()}(t),o=[".png",".jpg",".jpeg",".gif",".webp",".svg"];if(!o.includes(i))throw new Di(`File extension "${i}" is not allowed. Allowed extensions: ${o.join(", ")}`,t,n);const a=function(e){switch(e.toLowerCase()){case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";case".gif":return"image/gif";case".webp":return"image/webp";case".svg":return"image/svg+xml";default:return"application/octet-stream"}}(i);if(a!==n&&"application/octet-stream"!==a)throw new Di(`File extension "${i}" does not match MIME type "${n}"`,t,n);return}throw new Di("File must be a File object (browser) or Buffer (Node.js)",t,n)}class Mi{validate(e,t={}){const{allowZero:n=!0,minimum:r,maximum:s,maxDecimals:i=Mi.MAX_DECIMAL_PLACES,fieldName:o="amount"}=t;if(!Kn(e))throw new yt(`${o} cannot be empty or whitespace-only. Provide a valid numeric string.`,o,"INVALID_NUMERIC_STRING");if(/[eE]/.test(e))throw new yt(`${o} cannot use scientific notation. Use standard decimal format (e.g., "1000" instead of "1e3").`,o,"INVALID_NUMERIC_STRING");const a=In(e,NaN);if(isNaN(a))throw new yt(`${o} must be a valid numeric string. Received: "${e}"`,o,"INVALID_NUMERIC_STRING");if(!isFinite(a))throw new yt(`${o} must be a finite number. Cannot be Infinity or -Infinity.`,o,"INVALID_NUMERIC_STRING");if(a<0)throw new yt(`${o} must be non-negative. Received: "${e}"`,o,"INVALID_NUMERIC_STRING");if(!n&&0===a)throw new yt(`${o} must be greater than zero. Received: "${e}"`,o,"INVALID_NUMERIC_STRING");const c=ki(e),l=c.decimalPlaces()??0;if(l>i)throw new yt(`${o} cannot exceed ${i} decimal places. Received: ${l} decimal places`,o,"PRECISION_EXCEEDED");if(void 0!==r&&Ci(c,r))throw new yt(`${o} must be at least ${r}. Received: "${e}"`,o,"BELOW_MINIMUM");if(void 0!==s&&(u=s,ki(c).isGreaterThan(ki(u))))throw new yt(`${o} cannot exceed ${s}. Received: "${e}"`,o,"EXCEEDS_MAXIMUM");var u}parseAmount(e,t="0"){return ki(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 Ti(e,t)}clampAmount(e,t,n){const r=ki(e),s=ki(t),i=ki(n);return function(e,t,n){const r=ki(e),s=ki(t),i=ki(n);return r.isGreaterThanOrEqualTo(s)&&r.isLessThanOrEqualTo(i)}(r,s,i)?Ti(r):Ci(r,s)?Ti(s):Ti(i)}}function Li(e,t){throw new yt(e.join("; "),t,"VALIDATION_ERROR")}function Ui(e){const t=Ks(e);!t.success&&t.errors&&Li(t.errors,"tokenName")}function Pi(e){const t=us.safeParse(e);var n;t.success||Li((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 Fi(e,t,n=!0){$i.validate(e,{fieldName:t,allowZero:n})}Mi.MAX_DECIMAL_PLACES=18,Mi.MIN_POSITIVE="0.00000000000000001";const $i=new Mi;function Ki(e,t,n=Ti){if(!Array.isArray(e))throw Tt("Invalid API response: expected array of holders",t);for(const n of e){if(!Gi(n))throw Tt("Invalid holder data: missing or invalid owner field",t);if(!Wi(n))throw Tt("Invalid holder data: missing or invalid quantity field",t);const e=In(n.quantity,NaN);if(isNaN(e)||!isFinite(e))throw Tt(`Invalid holder quantity: "${n.quantity}"`,t)}const r=e,s=r.reduce((e,t)=>e.plus(t.quantity),ki(0));return{holders:r.map(e=>({address:e.owner,balance:e.quantity,percentage:Ri(ki(e.quantity),s,ki(0)).multipliedBy(100).toNumber()})),totalSupply:n(s),totalHolders:r.length,lastUpdated:new Date}}function Gi(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.owner&&""!==t.owner}function Wi(e){return"string"==typeof e.quantity&&""!==e.quantity}class Hi{constructor(e,t,n,r,s,i,o="local",a){this.http=e,this.tokenResolver=t,this.logger=n,this.bundleHttp=r,this.galaChainHttp=s,this.dexApiHttp=i,this.defaultCalculateAmountMode=o,this.launchpadWrites=a,this.metadataCache=new or}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;Ui(t);const r=`${t}.png`;Oi(n.file,r,"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 kt("file","a File object (browser) or Buffer (Node.js)");{const r=`${void 0!==n.tokenName&&""!==n.tokenName?n.tokenName:t}.png`,s=new Blob([n.file],{type:"image/png"});e.append("image",s,r)}}const r=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===r.error||200!==r.status)throw Tt(void 0!==r.message&&""!==r.message?r.message:"Image upload failed - no URL returned",r.status);const s=$t(r);if(!s?.imageUrl)throw Tt("Image upload failed - no URL returned",r.status);return s.imageUrl}catch(e){if(ot(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&&Hn(0,void 0,100,e.pageSize),void 0!==e.tokenName&&""!==e.tokenName&&Ui(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=Ai(t),r=await this.http.get(b.FETCH_POOLS,n);if(!0===r.error||200!==r.status)throw Tt(void 0!==r.message&&""!==r.message?r.message:"Failed to fetch pools",r.status);const s=$t(r);if(null==s)throw Tt("Failed to fetch pools - no data returned",r.status);let i=[];if(s.tokens)if(Array.isArray(s.tokens))i=s.tokens.map(e=>this.normalizePoolData(e));else{const e=s.tokens;i=[this.normalizePoolData(e)]}else s.pools&&Array.isArray(s.pools)&&(i=s.pools.map(e=>this.normalizePoolData(e)));const{extractMetadataFromPoolData:o,isValidPoolForCaching:a}=await Promise.resolve().then(function(){return tN});i.forEach(e=>{if(!a(e))return void this.logger.debug("Skipping pool with invalid structure for caching",e);const t=o(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:i,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 kt("options","an options object");const{tokenName:t,amount:n,type:r,currentSupply:s}=e;return"external"===this.validateAmountCalculationInputs(t,n,r,e.mode,[st.NATIVE,st.EXACT],'"native" or "exact"')?this.calculateBuyAmountExternal({tokenName:t,amount:n,type:r}):this.calculateBuyAmountLocal(this.addIfDefined({tokenName:t,amount:n,type:r},"currentSupply",s))}async calculateBuyAmountExternal(e){const{tokenName:t,amount:n,type:r}=e;return this.validateExternalAmountInputs(t,n),"exact"===r?Gt(()=>this.http.get(Ye,{tokenName:t,amount:n,type:"MEME",method:"OUT"}),{errorContext:`Failed to calculate buy amount for ${t} (exact tokens)`}):Gt(()=>this.http.get(Ye,{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:r,currentSupply:s,maxSupply:i,reverseBondingCurveMaxFeeFactor:o,reverseBondingCurveMinFeeFactor:a}=e;if("external"===this.validateAmountCalculationInputs(t,n,r,e.mode,[st.EXACT,st.NATIVE],'"exact" or "native"'))return this.calculateSellAmountExternal({tokenName:t,amount:n,type:r});{const e={tokenName:t,amount:n,type:r,...void 0!==s&&{currentSupply:s},...void 0!==i&&{maxSupply:i},...void 0!==o&&{reverseBondingCurveMaxFeeFactor:o},...void 0!==a&&{reverseBondingCurveMinFeeFactor:a}};return this.calculateSellAmountLocal(e)}}async calculateSellAmountExternal(e){const{tokenName:t,amount:n,type:r}=e;return this.validateExternalAmountInputs(t,n),"exact"===r?Gt(()=>this.http.get(Ye,{tokenName:t,amount:n,type:"MEME",method:"IN"}),{errorContext:`Failed to calculate sell amount for ${t} (exact tokens)`}):Gt(()=>this.http.get(Ye,{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:r,currentSupply:s}=e;if(!Kn(n))throw St("amount","Amount");if(r!==st.NATIVE&&r!==st.EXACT)throw Bt("type",'"native" or "exact"',r);void 0!==s&&Fi(s,"currentSupply");const i=null==s||""===s;if(i&&(null==t||""===t))throw St("tokenName","Token name (required when currentSupply is not provided)");null!=t&&""!==t&&Ui(t);let o=s;if(i){o=(await this.fetchPoolDetailsForCalculation(t)).currentSupply}return r===st.EXACT?Bi.calculateBuyWithExact(n,o):Bi.calculateBuyWithNative(n,o)}async calculateSellAmountLocal(e){const{tokenName:t,amount:n,type:r,currentSupply:s,maxSupply:i,reverseBondingCurveMaxFeeFactor:o,reverseBondingCurveMinFeeFactor:a}=e;if(!Kn(n))throw St("amount","Amount");if(r!==st.EXACT&&r!==st.NATIVE)throw Bt("type",'"exact" or "native"',r);void 0!==s&&Fi(s,"currentSupply");const c=null==s||""===s||null==i||""===i||void 0===o||void 0===a;if(c&&(null==t||""===t))throw St("tokenName","Token name (required when currentSupply, maxSupply, or fee factors are not provided)");null!=t&&""!==t&&Ui(t);let l=s,u=i,d=o,h=a;if(c&&null!=t&&""!==t){const e=this.metadataCache.getByName(t);u=u??this.metadataCache.getMaxSupply(t),d=d??e?.reverseBondingCurveMaxFeeFactor,h=h??e?.reverseBondingCurveMinFeeFactor,null!=l&&""!==l||(l=await this.fetchCurrentSupply(t));if(void 0===d||void 0===h){const e=await this.fetchPoolDetailsForCalculation(t);d=d??e.reverseBondingCurveMaxFeeFactor,h=h??e.reverseBondingCurveMinFeeFactor}}return r===st.EXACT?Bi.calculateSellWithExact(n,l,u,h,d):Bi.calculateSellWithNative(n,l,u,h,d)}async calculateBuyAmountForGraduation(e){const t="string"==typeof e?{tokenName:e}:e;if("object"==typeof e&&!function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return pi(t,"tokenName")&&function(e){return void 0===e.calculateAmountMode||"local"===e.calculateAmountMode||"external"===e.calculateAmountMode}(t)&&mi(t,"currentSupply")}(e))throw Bt("options","CalculateBuyAmountForGraduationOptions or string (token name)",typeof e);const{tokenName:n,calculateAmountMode:r,currentSupply:s}=t;Ui(n);const i=await this.fetchSaleDetails(n),o=s??Ti(ki(i.maxSupply).minus(i.sellingTokenQuantity)),a=i.sellingTokenQuantity;if("0"===a)throw St("tokenName",`Token ${n} is already graduated (no tokens remaining in pool)`);const c={tokenName:n,amount:a,type:"exact",currentSupply:o,...void 0!==r&&{mode:r}};return{...await this.calculateBuyAmount(c),remainingTokens:a}}async launchToken(e){if(void 0!==this.launchpadWrites){return(await this.launchpadWrites.createSale(e)).bundleId}if(!this.bundleHttp)throw It("Bundle backend client not configured. LaunchToken requires bundleHttp client.","bundleHttp");fi(e);const t=void 0!==e.preBuyQuantity&&""!==e.preBuyQuantity?e.preBuyQuantity:"0",n=In(t);if(0===n&&"0"!==t)throw Dt("preBuyQuantity",t,"Pre-buy quantity");if(n<0)throw Dt("preBuyQuantity",t,"Pre-buy quantity");if(e.reverseBondingCurveConfiguration){const{minFeePortion:t,maxFeePortion:n}=e.reverseBondingCurveConfiguration;Fn(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 St("tokenName","Token name");Ui(e);const t=await this.http.get(`/holders/${e}`);if(!0===t.error||200!==t.status)throw Tt(void 0!==t.message&&""!==t.message?t.message:"Failed to fetch token distribution",t.status);const n=$t(t);if(null==n)throw Tt("Failed to fetch token distribution - no data returned",t.status);return Ki(n,t.status)}async calculateInitialBuyAmount(e){if(!Ei(e))throw kt("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,r=t.Data;if("number"!=typeof n||"object"!=typeof r||null===r)return!1;const s=r,i=s.calculatedQuantity,o=s.extraFees;if("string"!=typeof i||"object"!=typeof o||null===o)return!1;const a=o;return"string"==typeof a.reverseBondingCurve&&"string"==typeof a.transactionFees}(n))throw Tt("Malformed response data from GalaChain gateway");try{dt(n,"Pre-mint calculation")}catch(e){throw Tt(at(e),500)}const{calculatedQuantity:r,extraFees:s}=n.Data;return{amount:r,reverseBondingCurveFee:s.reverseBondingCurve,transactionFee:s.transactionFees,gasFee:"1"}}catch(e){if(ot(e)&&e instanceof bt)throw e;throw Tt(at(e),500)}}async fetchPoolDetailsForCalculation(e){const t=await this.fetchSaleDetails(e),n=Ti(ki(t.maxSupply).minus(t.sellingTokenQuantity)),r=t.sellingTokenQuantity,s=t.maxSupply;let i=.5,o=.1;const a=t.reverseBondingCurveConfiguration;null!=a?.maxFeePortion&&(i=xn(a.maxFeePortion,.5)),null!=a?.minFeePortion&&(o=xn(a.minFeePortion,.1)),void 0===a&&this.logger.debug(`Pool details missing reverse bonding curve configuration for token ${e}, using defaults (min: 0.1, max: 0.5)`);const c=i-o;return this.metadataCache.set(e,{maxSupply:s,reverseBondingCurveMaxFeeFactor:i,reverseBondingCurveMinFeeFactor:o,reverseBondingCurveNetFeeFactor:c}),{currentSupply:n,remainingTokens:r,maxSupply:s,reverseBondingCurveMaxFeeFactor:i,reverseBondingCurveMinFeeFactor:o,reverseBondingCurveNetFeeFactor:c}}async fetchCurrentSupply(e){Ui(e);const t=await this.fetchSaleDetails(e),n=Ti(ki(t.maxSupply).minus(t.sellingTokenQuantity)),r=t.maxSupply;return this.metadataCache.set(e,{maxSupply:r}),n}normalizePoolData(e){const t=e.reverseBondingCurveMinFeePortion??"0",n=e.reverseBondingCurveMaxFeePortion??"0";return{...e,reverseBondingCurveMinFeePortion:t,reverseBondingCurveMaxFeePortion:n,hasReverseBondingCurveFee:!Ni(t)||!Ni(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 yt(pt(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 Tt(`Failed to fetch pool details: Status ${n.Status}`,n.Status);return n.Data}validateAmountCalculationInputs(e,t,n,r,s,i){const o=r??this.defaultCalculateAmountMode;if("local"!==o&&"external"!==o)throw Bt("mode",'"local" or "external"',o);if(!Kn(e))throw St("tokenName","Token name");if(!Kn(t))throw St("amount","Amount");if("string"!=typeof n||!s.includes(n))throw Bt("type",i,n);return o}validateExternalAmountInputs(e,t){if("string"!=typeof e||""===e)throw new yt("Token name must be a non-empty string","tokenName","INVALID_TOKEN_NAME");if("string"!=typeof t||""===t)throw new yt("Amount must be a non-empty string","amount","INVALID_AMOUNT")}getAddress(){return this.http.getAddress()}formatAddressForBackend(e){return hr(e)}validateTokenName(e){return Ui(e)}validatePagination(e){void 0!==e.pageSize&&Hn(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 St("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 Tt(`Failed to fetch token prices: ${at(e)}`,void 0,ot(e)?e:void 0)}}warmCacheFromPoolData(e,t){this.metadataCache.warmFromPoolData(e,t)}getCacheStats(){return this.metadataCache.getStats()}clearCache(e){this.metadataCache.clear(e)}}const qi={REFRESH_THRESHOLD_MS:3e5,DEFAULT_EXPIRY_S:86400,LOGIN_MESSAGE_PREFIX:"Sign in to Launchpad t:",AUTH_HEADER:"Authorization",BEARER_PREFIX:"Bearer "};class zi{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 Vi,ji;exports.AuthErrorType=void 0,(Vi=exports.AuthErrorType||(exports.AuthErrorType={})).WALLET_NOT_CONNECTED="WALLET_NOT_CONNECTED",Vi.SIGNATURE_FAILED="SIGNATURE_FAILED",Vi.INVALID_ADDRESS="INVALID_ADDRESS",Vi.MESSAGE_GENERATION_FAILED="MESSAGE_GENERATION_FAILED";class Xi extends Error{constructor(e,t,n){super(t),this.type=e,this.originalError=n,this.name="AuthError"}}class Yi{constructor(e,t=qi.REFRESH_THRESHOLD_MS){this.tokenState=null,this.STORAGE_KEYS={ACCESS_TOKEN:"lpad_access_token",ACCESS_EXPIRES:"lpad_access_expires",REFRESH_TOKEN:"lpad_refresh_token",REFRESH_EXPIRES:"lpad_refresh_expires"},this.storage=e??new zi,this.refreshThresholdMs=t}setToken(e,t){if(!Kn(e))throw new Xi(exports.AuthErrorType.SIGNATURE_FAILED,"JWT token must be a non-empty string");if("number"!=typeof t)throw new Xi(exports.AuthErrorType.SIGNATURE_FAILED,"Token expiration must be a positive finite number (seconds)");if(!Number.isFinite(t))throw new Xi(exports.AuthErrorType.SIGNATURE_FAILED,"Token expiration must be a positive finite number (seconds)");if(t<=0)throw new Xi(exports.AuthErrorType.SIGNATURE_FAILED,"Token expiration must be a positive finite number (seconds)");const n=Date.now();this.tokenState={token:e.trim(),issuedAt:n,expiresAt:n+1e3*t},this.storage.set(this.STORAGE_KEYS.ACCESS_TOKEN,e.trim()),this.storage.set(this.STORAGE_KEYS.ACCESS_EXPIRES,String(this.tokenState.expiresAt))}async setTokens(e,t,n,r){if(this.setToken(e,t),n){const e=Date.now()+1e3*(r??7776e3);if(!this.tokenState)throw new Xi(exports.AuthErrorType.SIGNATURE_FAILED,"Access token must be set before refresh token");this.tokenState.refreshToken=n.trim(),this.tokenState.refreshExpiresAt=e,await this.storage.set(this.STORAGE_KEYS.REFRESH_TOKEN,n.trim()),await this.storage.set(this.STORAGE_KEYS.REFRESH_EXPIRES,String(e))}}getToken(){return this.tokenState?.token??null}hasToken(){return null!==this.tokenState}isExpired(){return!this.tokenState||Date.now()>=this.tokenState.expiresAt}shouldRefresh(e){if(!this.tokenState)return!1;const t=e??this.refreshThresholdMs,n=this.tokenState.expiresAt-Date.now();return n>0&&n<=t}getTimeUntilExpiry(){if(!this.tokenState)return 0;const e=this.tokenState.expiresAt-Date.now();return Math.max(0,e)}getExpiresAt(){return this.tokenState?.expiresAt??null}getAuthorizationHeader(){const e=this.getToken();return null===e||""===e?null:`${qi.BEARER_PREFIX}${e}`}getJwtHeaders(){const e=this.getAuthorizationHeader();if(null===e||""===e)throw new Xi(exports.AuthErrorType.WALLET_NOT_CONNECTED,"No JWT token available. Call login() first.");return{[qi.AUTH_HEADER]:e}}async getRefreshToken(){if(!this.tokenState?.refreshToken){const e=await this.storage.get(this.STORAGE_KEYS.REFRESH_TOKEN),t=await this.storage.get(this.STORAGE_KEYS.REFRESH_EXPIRES);if(e&&t){const n=Number(t);if(Number.isFinite(n)&&Date.now()<n)return e}return null}return null!==this.tokenState.refreshExpiresAt&&void 0!==this.tokenState.refreshExpiresAt&&(!Number.isFinite(this.tokenState.refreshExpiresAt)||Date.now()>=this.tokenState.refreshExpiresAt)?null:this.tokenState.refreshToken??null}async restoreFromStorage(){const e=await this.storage.get(this.STORAGE_KEYS.ACCESS_TOKEN),t=await this.storage.get(this.STORAGE_KEYS.ACCESS_EXPIRES);if(!e||!t)return!1;const n=Number(t);if(!Number.isFinite(n)||Date.now()>=n)return!1;const r=Date.now();this.tokenState={token:e,issuedAt:r,expiresAt:n};const s=await this.storage.get(this.STORAGE_KEYS.REFRESH_TOKEN),i=await this.storage.get(this.STORAGE_KEYS.REFRESH_EXPIRES);if(s&&i){const e=Number(i);Number.isFinite(e)&&Date.now()<e&&(this.tokenState.refreshToken=s,this.tokenState.refreshExpiresAt=e)}return!0}async clear(){this.tokenState=null,await this.storage.remove(this.STORAGE_KEYS.ACCESS_TOKEN),await this.storage.remove(this.STORAGE_KEYS.ACCESS_EXPIRES),await this.storage.remove(this.STORAGE_KEYS.REFRESH_TOKEN),await this.storage.remove(this.STORAGE_KEYS.REFRESH_EXPIRES)}isValid(){return this.hasToken()&&!this.isExpired()}getDebugInfo(){return{hasToken:this.hasToken(),isExpired:this.isExpired(),shouldRefresh:this.shouldRefresh(),timeUntilExpiryMs:this.getTimeUntilExpiry(),expiresAt:this.tokenState?new Date(this.tokenState.expiresAt):null}}}async function Ji(e,t,n,r){try{return await e()}catch(e){throw r?(r(e,t,n),new Error("Unreachable after error handler")):(n&&n.error(`${t}:`,e),Ct(e,t,n))}}function Qi(e,t,n,r){try{return e()}catch(e){throw r?(r(e,t,n),new Error("Unreachable after error handler")):(n&&n.error(`${t}:`,e),Ct(e,t,n))}}class Zi{constructor(e,t,n,r=!1){this.http=e,this.signatureAuth=t,this.jwtAuth=n,this.refreshPromise=null,this.loginPromise=null,this.logger=new Jt({debug:r,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 Xi(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Wallet is required for login. Configure privateKey in SDK.");this.loginPromise=this.performLogin();try{return await this.loginPromise}finally{this.loginPromise=null}}async performLogin(){return Ji(async()=>{const e=Date.now(),t=`${qi.LOGIN_MESSAGE_PREFIX}${e}`;this.logger.debug("Generating login signature",{message:t,timestamp:e});const n=await this.signatureAuth.signMessage(t),r=this.signatureAuth.getAddress();mr(r,"address");const s={address:r,message:t,signature:n.signature};let i;try{this.logger.debug("Sending login request with refresh token support",{address:r,message:t}),i=await this.http.post(K,{...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)"),i=await this.http.post(K,s)}const o=this.extractLoginData(i);return await this.jwtAuth.setTokens(o.accessToken,o.expiresIn,o.refreshToken,o.refreshExpiresIn),this.logger.debug("Login successful",{address:o.address,expiresIn:o.expiresIn,hasRefreshToken:!!o.refreshToken}),o},"SessionAuthService.performLogin",this.logger,e=>{if(e instanceof Xi)throw e;throw new Xi(exports.AuthErrorType.SIGNATURE_FAILED,`Login failed: ${at(e)}`,ot(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 Xi(exports.AuthErrorType.WALLET_NOT_CONNECTED,"No token to refresh. Call login() first.");this.refreshPromise=this.performRefresh();try{return await this.refreshPromise}finally{this.refreshPromise=null}}async performRefresh(){return Ji(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(W,{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(W,{},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 Xi)throw e;throw new Xi(exports.AuthErrorType.SIGNATURE_FAILED,`Token refresh failed: ${at(e)}`,ot(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(G,{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): ${at(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 Xi(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Not authenticated. Call login() first.");return Ji(async()=>{const e=await this.http.get(H,void 0,this.jwtAuth.getJwtHeaders());return this.extractSessionData(e)},"SessionAuthService.getSession",this.logger,e=>{if(e instanceof Xi)throw e;throw new Xi(exports.AuthErrorType.SIGNATURE_FAILED,`Failed to get session: ${at(e)}`,ot(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 Xi(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Not authenticated. Call login() first.");if(this.jwtAuth.isExpired()){if(await this.jwtAuth.getRefreshToken()){this.logger.debug("Token expired - refresh token available, attempting refresh");try{return(await this.refresh()).accessToken}catch(e){this.logger.warn(`Refresh failed after expiry: ${at(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 Xi(exports.AuthErrorType.SIGNATURE_FAILED,""!==at(e)?at(e):"Authentication failed");const t=Kt(e,"No data in authentication response"),{accessToken:n,expiresIn:r,address:s,refreshToken:i,refreshExpiresIn:o}=t;if(!Kn(n))throw new Xi(exports.AuthErrorType.SIGNATURE_FAILED,"Invalid access token in response");if("number"!=typeof r||r<=0)throw new Xi(exports.AuthErrorType.SIGNATURE_FAILED,"Invalid expiration in response");return{accessToken:n,expiresIn:r,address:s,...void 0!==i&&{refreshToken:i},...void 0!==o&&{refreshExpiresIn:o}}}extractSessionData(e){if(e.error)throw new Xi(exports.AuthErrorType.SIGNATURE_FAILED,""!==at(e)?at(e):"Failed to get session");return Kt(e,"No data in session response")}}class eo 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"}(ji||(ji={}));class to{constructor(t){this.providerType="privateKey",this.connected=!0;try{this.wallet=new e.Wallet(t)}catch(e){throw new eo("Invalid private key provided",ji.INVALID_CONFIG,e instanceof Error?e:void 0)}}static fromWallet(e){return new to(e.privateKey)}async signMessage(e){try{return await this.wallet.signMessage(e)}catch(e){throw new eo("Failed to sign message",ji.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 eo("Failed to sign typed data",ji.SIGNING_FAILED,e instanceof Error?e:void 0)}}getAddress(){return Promise.resolve(e.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 no{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{Un(e.messagePrefix,"messagePrefix",!1)}catch{throw new Xi(exports.AuthErrorType.SIGNATURE_FAILED,"Message prefix cannot be empty")}}hasWallet(){return void 0!==this.walletProvider||void 0!==this.wallet}ensureWalletProvider(){if(this.wallet&&!this.walletProvider)try{this.walletProvider=to.fromWallet(this.wallet),this.cachedAddress=this.wallet.address,this.cachedGalaAddress=hr(this.wallet.address)}catch(e){if(e instanceof Xi)throw e;if(e instanceof yt&&("INVALID_ADDRESS"===e.code||"INVALID_FORMAT"===e.code||"address"===e.field))throw new Xi(exports.AuthErrorType.INVALID_ADDRESS,e.message);if(null!==e&&"object"==typeof e&&"message"in e)throw new Xi(exports.AuthErrorType.WALLET_NOT_CONNECTED,e.message);throw e}}setWallet(e){if(void 0!==e){if("object"!=typeof e||!("address"in e))throw new Xi(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Invalid wallet: must be an ethers Wallet instance or undefined");if("string"!=typeof e.address||""===e.address)throw new Xi(exports.AuthErrorType.INVALID_ADDRESS,"Wallet address is not available");this.walletProvider=to.fromWallet(e),this.cachedAddress=e.address,this.cachedGalaAddress=hr(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 Xi)throw e;throw new Xi(exports.AuthErrorType.SIGNATURE_FAILED,"Failed to generate signature for authentication",ot(e)?e:new Error(at(e)))}}getAddress(){if(this.validateWallet(),this.cachedGalaAddress)return this.cachedGalaAddress;if(this.wallet)return this.formatAddress(this.wallet.address);throw new Xi(exports.AuthErrorType.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 Xi(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Address not available. For external wallets, call cacheAddress() after connecting.")}async getEthereumAddressAsync(){return await this.validateWalletAsync(),this.walletProvider.getAddress()}getPrivateKey(){if(this.validateWallet(),this.wallet){if(""===this.wallet.privateKey||null===this.wallet.privateKey||void 0===this.wallet.privateKey)throw new Xi(exports.AuthErrorType.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 Xi(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Private key not available. External wallet providers cannot access private keys. Use PrivateKeyProvider for @gala-chain signing operations.")}async getPrivateKeyAsync(){if(await this.validateWalletAsync(),!this.walletProvider.getPrivateKey)throw new Xi(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Private key not available with this wallet provider");try{return await this.walletProvider.getPrivateKey()}catch(e){throw new Xi(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Private key not available. External wallet providers cannot access private keys. Use PrivateKeyProvider for @gala-chain signing operations.",ot(e)?e:void 0)}}formatAddress(e){try{return hr(e)}catch{throw new Xi(exports.AuthErrorType.INVALID_ADDRESS,`Invalid Ethereum address format: ${e}`)}}async signMessage(e){await this.validateWalletAsync();try{const t=await this.walletProvider.signMessage(e);return{message:e,signature:t,address:await this.walletProvider.getAddress(),timestamp:Date.now()}}catch(e){if(e instanceof Xi)throw e;throw new Xi(exports.AuthErrorType.SIGNATURE_FAILED,at(e),ot(e)?e:new Error(at(e)))}}async generateAuthHeaders(e,t){await this.validateWalletAsync();try{const n=Date.now(),r=`${this.messagePrefix} ${t.toUpperCase()} ${e} ${n}`,s=await this.walletProvider.signMessage(r);return{"x-signature":s,"x-address":await this.walletProvider.getGalaAddress(),"x-message":r,"x-timestamp":n.toString()}}catch(e){if(e instanceof Xi)throw e;throw new Xi(exports.AuthErrorType.SIGNATURE_FAILED,"Failed to generate authentication headers",ot(e)?e:new Error(at(e)))}}async signTypedData(e,t,n){await this.validateWalletAsync();try{const r={};for(const[e,n]of Object.entries(t))r[e]=n.map(e=>({name:e.name,type:e.type}));return await this.walletProvider.signTypedData(e,r,n)}catch(e){if(e instanceof Xi)throw e;throw new Xi(exports.AuthErrorType.SIGNATURE_FAILED,"Failed to sign typed data",ot(e)?e:new Error(at(e)))}}async generateCustomSignature(e){if(!Kn(e))throw new Xi(exports.AuthErrorType.SIGNATURE_FAILED,"Custom message must be a non-empty string");await this.validateWalletAsync();try{const t=await this.walletProvider.signMessage(e);return{message:e,signature:t,address:await this.walletProvider.getGalaAddress(),timestamp:Date.now()}}catch(e){if(e instanceof Xi)throw e;throw new Xi(exports.AuthErrorType.SIGNATURE_FAILED,"Failed to generate custom message signature",ot(e)?e:new Error(at(e)))}}validateWallet(){if(this.ensureWalletProvider(),!this.walletProvider)throw new Xi(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Wallet is required for authentication")}async validateWalletAsync(){if(this.ensureWalletProvider(),!this.walletProvider)throw new Xi(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Wallet is required for authentication");if(!this.walletProvider.isConnected())throw new Xi(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Wallet is not connected. Call connect() on the wallet provider first.")}}const ro={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 so(e){return ro[e]}function io(e){return`${e.collection}|${e.category}|${e.type}|${e.additionalKey}`}function oo(e){return`${e.collection}$${e.category}$${e.type}$${e.additionalKey}`}const ao={GALA_CHAIN:1,ETHEREUM:2,SOLANA:1002},co={ASSET:1,MUSIC:3};const lo="0x9f452b7cC24e6e6FA690fe77CF5dD2ba3DbF1ED9",uo="0x6a1734E09f3099a3675645D214ce547080ea67e0",ho="https://dex-api-platform-dex-prod-gala.gala.com",go=[{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}],fo=[{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 po(e){return"prod"===e?go:fo}function mo(e){return"prod"===e?lo:uo}const yo=go,bo=[{symbol:"GALA",amount:"1",mintAddress:"eEUiUs4JWYZrp72djAGF1A8PhpR6rHphGeGN7GbVLp6",isNative:!1,decimals:8},{symbol:"GSOL",amount:"0.001",mintAddress:"So11111111111111111111111111111111111111111",isNative:!0,decimals:9}],vo={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"}},wo=["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)"],Eo=["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"],Ao={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 So(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function ko(e){if(Object.prototype.hasOwnProperty.call(e,"__esModule"))return e;var t=e.default;if("function"==typeof t){var n=function e(){var n=!1;try{n=this instanceof e}catch(e){}return n?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};n.prototype=t.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(e).forEach(function(t){var r=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(n,t,r.get?r:{enumerable:!0,get:function(){return e[t]}})}),n}var To,Io={},No={};function Co(){if(To)return No;To=1,No.byteLength=function(e){var t=i(e),n=t[0],r=t[1];return 3*(n+r)/4-r},No.toByteArray=function(e){var r,s,o=i(e),a=o[0],c=o[1],l=new n(function(e,t,n){return 3*(t+n)/4-n}(0,a,c)),u=0,d=c>0?a-4:a;for(s=0;s<d;s+=4)r=t[e.charCodeAt(s)]<<18|t[e.charCodeAt(s+1)]<<12|t[e.charCodeAt(s+2)]<<6|t[e.charCodeAt(s+3)],l[u++]=r>>16&255,l[u++]=r>>8&255,l[u++]=255&r;2===c&&(r=t[e.charCodeAt(s)]<<2|t[e.charCodeAt(s+1)]>>4,l[u++]=255&r);1===c&&(r=t[e.charCodeAt(s)]<<10|t[e.charCodeAt(s+1)]<<4|t[e.charCodeAt(s+2)]>>2,l[u++]=r>>8&255,l[u++]=255&r);return l},No.fromByteArray=function(t){for(var n,r=t.length,s=r%3,i=[],o=16383,c=0,l=r-s;c<l;c+=o)i.push(a(t,c,c+o>l?l:c+o));1===s?(n=t[r-1],i.push(e[n>>2]+e[n<<4&63]+"==")):2===s&&(n=(t[r-2]<<8)+t[r-1],i.push(e[n>>10]+e[n>>4&63]+e[n<<2&63]+"="));return i.join("")};for(var e=[],t=[],n="undefined"!=typeof Uint8Array?Uint8Array:Array,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s=0;s<64;++s)e[s]=r[s],t[r.charCodeAt(s)]=s;function i(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var n=e.indexOf("=");return-1===n&&(n=t),[n,n===t?0:4-n%4]}function o(t){return e[t>>18&63]+e[t>>12&63]+e[t>>6&63]+e[63&t]}function a(e,t,n){for(var r,s=[],i=t;i<n;i+=3)r=(e[i]<<16&16711680)+(e[i+1]<<8&65280)+(255&e[i+2]),s.push(o(r));return s.join("")}return t["-".charCodeAt(0)]=62,t["_".charCodeAt(0)]=63,No}var _o,xo,Ro={};function Bo(){return _o||(_o=1,Ro.read=function(e,t,n,r,s){var i,o,a=8*s-r-1,c=(1<<a)-1,l=c>>1,u=-7,d=n?s-1:0,h=n?-1:1,g=e[t+d];for(d+=h,i=g&(1<<-u)-1,g>>=-u,u+=a;u>0;i=256*i+e[t+d],d+=h,u-=8);for(o=i&(1<<-u)-1,i>>=-u,u+=r;u>0;o=256*o+e[t+d],d+=h,u-=8);if(0===i)i=1-l;else{if(i===c)return o?NaN:1/0*(g?-1:1);o+=Math.pow(2,r),i-=l}return(g?-1:1)*o*Math.pow(2,i-r)},Ro.write=function(e,t,n,r,s,i){var o,a,c,l=8*i-s-1,u=(1<<l)-1,d=u>>1,h=23===s?Math.pow(2,-24)-Math.pow(2,-77):0,g=r?0:i-1,f=r?1:-1,p=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,o=u):(o=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-o))<1&&(o--,c*=2),(t+=o+d>=1?h/c:h*Math.pow(2,1-d))*c>=2&&(o++,c/=2),o+d>=u?(a=0,o=u):o+d>=1?(a=(t*c-1)*Math.pow(2,s),o+=d):(a=t*Math.pow(2,d-1)*Math.pow(2,s),o=0));s>=8;e[n+g]=255&a,g+=f,a/=256,s-=8);for(o=o<<s|a,l+=s;l>0;e[n+g]=255&o,g+=f,o/=256,l-=8);e[n+g-f]|=128*p}),Ro}function Do(){return xo||(xo=1,function(e){const t=Co(),n=Bo(),r="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;e.Buffer=o,e.SlowBuffer=function(e){+e!=e&&(e=0);return o.alloc(+e)},e.INSPECT_MAX_BYTES=50;const s=2147483647;function i(e){if(e>s)throw new RangeError('The value "'+e+'" is invalid for option "size"');const t=new Uint8Array(e);return Object.setPrototypeOf(t,o.prototype),t}function o(e,t,n){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return l(e)}return a(e,t,n)}function a(e,t,n){if("string"==typeof e)return function(e,t){"string"==typeof t&&""!==t||(t="utf8");if(!o.isEncoding(t))throw new TypeError("Unknown encoding: "+t);const n=0|g(e,t);let r=i(n);const s=r.write(e,t);s!==n&&(r=r.slice(0,s));return r}(e,t);if(ArrayBuffer.isView(e))return function(e){if(V(e,Uint8Array)){const t=new Uint8Array(e);return d(t.buffer,t.byteOffset,t.byteLength)}return u(e)}(e);if(null==e)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(V(e,ArrayBuffer)||e&&V(e.buffer,ArrayBuffer))return d(e,t,n);if("undefined"!=typeof SharedArrayBuffer&&(V(e,SharedArrayBuffer)||e&&V(e.buffer,SharedArrayBuffer)))return d(e,t,n);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');const r=e.valueOf&&e.valueOf();if(null!=r&&r!==e)return o.from(r,t,n);const s=function(e){if(o.isBuffer(e)){const t=0|h(e.length),n=i(t);return 0===n.length||e.copy(n,0,0,t),n}if(void 0!==e.length)return"number"!=typeof e.length||j(e.length)?i(0):u(e);if("Buffer"===e.type&&Array.isArray(e.data))return u(e.data)}(e);if(s)return s;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return o.from(e[Symbol.toPrimitive]("string"),t,n);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function c(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function l(e){return c(e),i(e<0?0:0|h(e))}function u(e){const t=e.length<0?0:0|h(e.length),n=i(t);for(let r=0;r<t;r+=1)n[r]=255&e[r];return n}function d(e,t,n){if(t<0||e.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(n||0))throw new RangeError('"length" is outside of buffer bounds');let r;return r=void 0===t&&void 0===n?new Uint8Array(e):void 0===n?new Uint8Array(e,t):new Uint8Array(e,t,n),Object.setPrototypeOf(r,o.prototype),r}function h(e){if(e>=s)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s.toString(16)+" bytes");return 0|e}function g(e,t){if(o.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||V(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);const n=e.length,r=arguments.length>2&&!0===arguments[2];if(!r&&0===n)return 0;let s=!1;for(;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":return H(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return q(e).length;default:if(s)return r?-1:H(e).length;t=(""+t).toLowerCase(),s=!0}}function f(e,t,n){let r=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if((n>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return C(this,t,n);case"utf8":case"utf-8":return k(this,t,n);case"ascii":return I(this,t,n);case"latin1":case"binary":return N(this,t,n);case"base64":return S(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return _(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function p(e,t,n){const r=e[t];e[t]=e[n],e[n]=r}function m(e,t,n,r,s){if(0===e.length)return-1;if("string"==typeof n?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),j(n=+n)&&(n=s?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(s)return-1;n=e.length-1}else if(n<0){if(!s)return-1;n=0}if("string"==typeof t&&(t=o.from(t,r)),o.isBuffer(t))return 0===t.length?-1:y(e,t,n,r,s);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?s?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):y(e,[t],n,r,s);throw new TypeError("val must be string, number or Buffer")}function y(e,t,n,r,s){let i,o=1,a=e.length,c=t.length;if(void 0!==r&&("ucs2"===(r=String(r).toLowerCase())||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(e.length<2||t.length<2)return-1;o=2,a/=2,c/=2,n/=2}function l(e,t){return 1===o?e[t]:e.readUInt16BE(t*o)}if(s){let r=-1;for(i=n;i<a;i++)if(l(e,i)===l(t,-1===r?0:i-r)){if(-1===r&&(r=i),i-r+1===c)return r*o}else-1!==r&&(i-=i-r),r=-1}else for(n+c>a&&(n=a-c),i=n;i>=0;i--){let n=!0;for(let r=0;r<c;r++)if(l(e,i+r)!==l(t,r)){n=!1;break}if(n)return i}return-1}function b(e,t,n,r){n=Number(n)||0;const s=e.length-n;r?(r=Number(r))>s&&(r=s):r=s;const i=t.length;let o;for(r>i/2&&(r=i/2),o=0;o<r;++o){const r=parseInt(t.substr(2*o,2),16);if(j(r))return o;e[n+o]=r}return o}function v(e,t,n,r){return z(H(t,e.length-n),e,n,r)}function w(e,t,n,r){return z(function(e){const t=[];for(let n=0;n<e.length;++n)t.push(255&e.charCodeAt(n));return t}(t),e,n,r)}function E(e,t,n,r){return z(q(t),e,n,r)}function A(e,t,n,r){return z(function(e,t){let n,r,s;const i=[];for(let o=0;o<e.length&&!((t-=2)<0);++o)n=e.charCodeAt(o),r=n>>8,s=n%256,i.push(s),i.push(r);return i}(t,e.length-n),e,n,r)}function S(e,n,r){return 0===n&&r===e.length?t.fromByteArray(e):t.fromByteArray(e.slice(n,r))}function k(e,t,n){n=Math.min(e.length,n);const r=[];let s=t;for(;s<n;){const t=e[s];let i=null,o=t>239?4:t>223?3:t>191?2:1;if(s+o<=n){let n,r,a,c;switch(o){case 1:t<128&&(i=t);break;case 2:n=e[s+1],128==(192&n)&&(c=(31&t)<<6|63&n,c>127&&(i=c));break;case 3:n=e[s+1],r=e[s+2],128==(192&n)&&128==(192&r)&&(c=(15&t)<<12|(63&n)<<6|63&r,c>2047&&(c<55296||c>57343)&&(i=c));break;case 4:n=e[s+1],r=e[s+2],a=e[s+3],128==(192&n)&&128==(192&r)&&128==(192&a)&&(c=(15&t)<<18|(63&n)<<12|(63&r)<<6|63&a,c>65535&&c<1114112&&(i=c))}}null===i?(i=65533,o=1):i>65535&&(i-=65536,r.push(i>>>10&1023|55296),i=56320|1023&i),r.push(i),s+=o}return function(e){const t=e.length;if(t<=T)return String.fromCharCode.apply(String,e);let n="",r=0;for(;r<t;)n+=String.fromCharCode.apply(String,e.slice(r,r+=T));return n}(r)}e.kMaxLength=s,o.TYPED_ARRAY_SUPPORT=function(){try{const e=new Uint8Array(1),t={foo:function(){return 42}};return Object.setPrototypeOf(t,Uint8Array.prototype),Object.setPrototypeOf(e,t),42===e.foo()}catch(e){return!1}}(),!o.TYPED_ARRAY_SUPPORT&&"undefined"!=typeof console&&console.error,Object.defineProperty(o.prototype,"parent",{enumerable:!0,get:function(){if(o.isBuffer(this))return this.buffer}}),Object.defineProperty(o.prototype,"offset",{enumerable:!0,get:function(){if(o.isBuffer(this))return this.byteOffset}}),o.poolSize=8192,o.from=function(e,t,n){return a(e,t,n)},Object.setPrototypeOf(o.prototype,Uint8Array.prototype),Object.setPrototypeOf(o,Uint8Array),o.alloc=function(e,t,n){return function(e,t,n){return c(e),e<=0?i(e):void 0!==t?"string"==typeof n?i(e).fill(t,n):i(e).fill(t):i(e)}(e,t,n)},o.allocUnsafe=function(e){return l(e)},o.allocUnsafeSlow=function(e){return l(e)},o.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==o.prototype},o.compare=function(e,t){if(V(e,Uint8Array)&&(e=o.from(e,e.offset,e.byteLength)),V(t,Uint8Array)&&(t=o.from(t,t.offset,t.byteLength)),!o.isBuffer(e)||!o.isBuffer(t))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;let n=e.length,r=t.length;for(let s=0,i=Math.min(n,r);s<i;++s)if(e[s]!==t[s]){n=e[s],r=t[s];break}return n<r?-1:r<n?1:0},o.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},o.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return o.alloc(0);let n;if(void 0===t)for(t=0,n=0;n<e.length;++n)t+=e[n].length;const r=o.allocUnsafe(t);let s=0;for(n=0;n<e.length;++n){let t=e[n];if(V(t,Uint8Array))s+t.length>r.length?(o.isBuffer(t)||(t=o.from(t)),t.copy(r,s)):Uint8Array.prototype.set.call(r,t,s);else{if(!o.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(r,s)}s+=t.length}return r},o.byteLength=g,o.prototype._isBuffer=!0,o.prototype.swap16=function(){const e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let t=0;t<e;t+=2)p(this,t,t+1);return this},o.prototype.swap32=function(){const e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let t=0;t<e;t+=4)p(this,t,t+3),p(this,t+1,t+2);return this},o.prototype.swap64=function(){const e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let t=0;t<e;t+=8)p(this,t,t+7),p(this,t+1,t+6),p(this,t+2,t+5),p(this,t+3,t+4);return this},o.prototype.toString=function(){const e=this.length;return 0===e?"":0===arguments.length?k(this,0,e):f.apply(this,arguments)},o.prototype.toLocaleString=o.prototype.toString,o.prototype.equals=function(e){if(!o.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===o.compare(this,e)},o.prototype.inspect=function(){let t="";const n=e.INSPECT_MAX_BYTES;return t=this.toString("hex",0,n).replace(/(.{2})/g,"$1 ").trim(),this.length>n&&(t+=" ... "),"<Buffer "+t+">"},r&&(o.prototype[r]=o.prototype.inspect),o.prototype.compare=function(e,t,n,r,s){if(V(e,Uint8Array)&&(e=o.from(e,e.offset,e.byteLength)),!o.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===r&&(r=0),void 0===s&&(s=this.length),t<0||n>e.length||r<0||s>this.length)throw new RangeError("out of range index");if(r>=s&&t>=n)return 0;if(r>=s)return-1;if(t>=n)return 1;if(this===e)return 0;let i=(s>>>=0)-(r>>>=0),a=(n>>>=0)-(t>>>=0);const c=Math.min(i,a),l=this.slice(r,s),u=e.slice(t,n);for(let e=0;e<c;++e)if(l[e]!==u[e]){i=l[e],a=u[e];break}return i<a?-1:a<i?1:0},o.prototype.includes=function(e,t,n){return-1!==this.indexOf(e,t,n)},o.prototype.indexOf=function(e,t,n){return m(this,e,t,n,!0)},o.prototype.lastIndexOf=function(e,t,n){return m(this,e,t,n,!1)},o.prototype.write=function(e,t,n,r){if(void 0===t)r="utf8",n=this.length,t=0;else if(void 0===n&&"string"==typeof t)r=t,n=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t>>>=0,isFinite(n)?(n>>>=0,void 0===r&&(r="utf8")):(r=n,n=void 0)}const s=this.length-t;if((void 0===n||n>s)&&(n=s),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");let i=!1;for(;;)switch(r){case"hex":return b(this,e,t,n);case"utf8":case"utf-8":return v(this,e,t,n);case"ascii":case"latin1":case"binary":return w(this,e,t,n);case"base64":return E(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return A(this,e,t,n);default:if(i)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),i=!0}},o.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const T=4096;function I(e,t,n){let r="";n=Math.min(e.length,n);for(let s=t;s<n;++s)r+=String.fromCharCode(127&e[s]);return r}function N(e,t,n){let r="";n=Math.min(e.length,n);for(let s=t;s<n;++s)r+=String.fromCharCode(e[s]);return r}function C(e,t,n){const r=e.length;(!t||t<0)&&(t=0),(!n||n<0||n>r)&&(n=r);let s="";for(let r=t;r<n;++r)s+=X[e[r]];return s}function _(e,t,n){const r=e.slice(t,n);let s="";for(let e=0;e<r.length-1;e+=2)s+=String.fromCharCode(r[e]+256*r[e+1]);return s}function x(e,t,n){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>n)throw new RangeError("Trying to access beyond buffer length")}function R(e,t,n,r,s,i){if(!o.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>s||t<i)throw new RangeError('"value" argument is out of bounds');if(n+r>e.length)throw new RangeError("Index out of range")}function B(e,t,n,r,s){$(t,r,s,e,n,7);let i=Number(t&BigInt(4294967295));e[n++]=i,i>>=8,e[n++]=i,i>>=8,e[n++]=i,i>>=8,e[n++]=i;let o=Number(t>>BigInt(32)&BigInt(4294967295));return e[n++]=o,o>>=8,e[n++]=o,o>>=8,e[n++]=o,o>>=8,e[n++]=o,n}function D(e,t,n,r,s){$(t,r,s,e,n,7);let i=Number(t&BigInt(4294967295));e[n+7]=i,i>>=8,e[n+6]=i,i>>=8,e[n+5]=i,i>>=8,e[n+4]=i;let o=Number(t>>BigInt(32)&BigInt(4294967295));return e[n+3]=o,o>>=8,e[n+2]=o,o>>=8,e[n+1]=o,o>>=8,e[n]=o,n+8}function O(e,t,n,r,s,i){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function M(e,t,r,s,i){return t=+t,r>>>=0,i||O(e,0,r,4),n.write(e,t,r,s,23,4),r+4}function L(e,t,r,s,i){return t=+t,r>>>=0,i||O(e,0,r,8),n.write(e,t,r,s,52,8),r+8}o.prototype.slice=function(e,t){const n=this.length;(e=~~e)<0?(e+=n)<0&&(e=0):e>n&&(e=n),(t=void 0===t?n:~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),t<e&&(t=e);const r=this.subarray(e,t);return Object.setPrototypeOf(r,o.prototype),r},o.prototype.readUintLE=o.prototype.readUIntLE=function(e,t,n){e>>>=0,t>>>=0,n||x(e,t,this.length);let r=this[e],s=1,i=0;for(;++i<t&&(s*=256);)r+=this[e+i]*s;return r},o.prototype.readUintBE=o.prototype.readUIntBE=function(e,t,n){e>>>=0,t>>>=0,n||x(e,t,this.length);let r=this[e+--t],s=1;for(;t>0&&(s*=256);)r+=this[e+--t]*s;return r},o.prototype.readUint8=o.prototype.readUInt8=function(e,t){return e>>>=0,t||x(e,1,this.length),this[e]},o.prototype.readUint16LE=o.prototype.readUInt16LE=function(e,t){return e>>>=0,t||x(e,2,this.length),this[e]|this[e+1]<<8},o.prototype.readUint16BE=o.prototype.readUInt16BE=function(e,t){return e>>>=0,t||x(e,2,this.length),this[e]<<8|this[e+1]},o.prototype.readUint32LE=o.prototype.readUInt32LE=function(e,t){return e>>>=0,t||x(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},o.prototype.readUint32BE=o.prototype.readUInt32BE=function(e,t){return e>>>=0,t||x(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},o.prototype.readBigUInt64LE=Y(function(e){K(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||G(e,this.length-8);const r=t+256*this[++e]+65536*this[++e]+this[++e]*2**24,s=this[++e]+256*this[++e]+65536*this[++e]+n*2**24;return BigInt(r)+(BigInt(s)<<BigInt(32))}),o.prototype.readBigUInt64BE=Y(function(e){K(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||G(e,this.length-8);const r=t*2**24+65536*this[++e]+256*this[++e]+this[++e],s=this[++e]*2**24+65536*this[++e]+256*this[++e]+n;return(BigInt(r)<<BigInt(32))+BigInt(s)}),o.prototype.readIntLE=function(e,t,n){e>>>=0,t>>>=0,n||x(e,t,this.length);let r=this[e],s=1,i=0;for(;++i<t&&(s*=256);)r+=this[e+i]*s;return s*=128,r>=s&&(r-=Math.pow(2,8*t)),r},o.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||x(e,t,this.length);let r=t,s=1,i=this[e+--r];for(;r>0&&(s*=256);)i+=this[e+--r]*s;return s*=128,i>=s&&(i-=Math.pow(2,8*t)),i},o.prototype.readInt8=function(e,t){return e>>>=0,t||x(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},o.prototype.readInt16LE=function(e,t){e>>>=0,t||x(e,2,this.length);const n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},o.prototype.readInt16BE=function(e,t){e>>>=0,t||x(e,2,this.length);const n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},o.prototype.readInt32LE=function(e,t){return e>>>=0,t||x(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},o.prototype.readInt32BE=function(e,t){return e>>>=0,t||x(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},o.prototype.readBigInt64LE=Y(function(e){K(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||G(e,this.length-8);const r=this[e+4]+256*this[e+5]+65536*this[e+6]+(n<<24);return(BigInt(r)<<BigInt(32))+BigInt(t+256*this[++e]+65536*this[++e]+this[++e]*2**24)}),o.prototype.readBigInt64BE=Y(function(e){K(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||G(e,this.length-8);const r=(t<<24)+65536*this[++e]+256*this[++e]+this[++e];return(BigInt(r)<<BigInt(32))+BigInt(this[++e]*2**24+65536*this[++e]+256*this[++e]+n)}),o.prototype.readFloatLE=function(e,t){return e>>>=0,t||x(e,4,this.length),n.read(this,e,!0,23,4)},o.prototype.readFloatBE=function(e,t){return e>>>=0,t||x(e,4,this.length),n.read(this,e,!1,23,4)},o.prototype.readDoubleLE=function(e,t){return e>>>=0,t||x(e,8,this.length),n.read(this,e,!0,52,8)},o.prototype.readDoubleBE=function(e,t){return e>>>=0,t||x(e,8,this.length),n.read(this,e,!1,52,8)},o.prototype.writeUintLE=o.prototype.writeUIntLE=function(e,t,n,r){if(e=+e,t>>>=0,n>>>=0,!r){R(this,e,t,n,Math.pow(2,8*n)-1,0)}let s=1,i=0;for(this[t]=255&e;++i<n&&(s*=256);)this[t+i]=e/s&255;return t+n},o.prototype.writeUintBE=o.prototype.writeUIntBE=function(e,t,n,r){if(e=+e,t>>>=0,n>>>=0,!r){R(this,e,t,n,Math.pow(2,8*n)-1,0)}let s=n-1,i=1;for(this[t+s]=255&e;--s>=0&&(i*=256);)this[t+s]=e/i&255;return t+n},o.prototype.writeUint8=o.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||R(this,e,t,1,255,0),this[t]=255&e,t+1},o.prototype.writeUint16LE=o.prototype.writeUInt16LE=function(e,t,n){return e=+e,t>>>=0,n||R(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},o.prototype.writeUint16BE=o.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||R(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},o.prototype.writeUint32LE=o.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||R(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},o.prototype.writeUint32BE=o.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||R(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},o.prototype.writeBigUInt64LE=Y(function(e,t=0){return B(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),o.prototype.writeBigUInt64BE=Y(function(e,t=0){return D(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),o.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t>>>=0,!r){const r=Math.pow(2,8*n-1);R(this,e,t,n,r-1,-r)}let s=0,i=1,o=0;for(this[t]=255&e;++s<n&&(i*=256);)e<0&&0===o&&0!==this[t+s-1]&&(o=1),this[t+s]=(e/i|0)-o&255;return t+n},o.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t>>>=0,!r){const r=Math.pow(2,8*n-1);R(this,e,t,n,r-1,-r)}let s=n-1,i=1,o=0;for(this[t+s]=255&e;--s>=0&&(i*=256);)e<0&&0===o&&0!==this[t+s+1]&&(o=1),this[t+s]=(e/i|0)-o&255;return t+n},o.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||R(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},o.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||R(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},o.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||R(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},o.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||R(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},o.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||R(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},o.prototype.writeBigInt64LE=Y(function(e,t=0){return B(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),o.prototype.writeBigInt64BE=Y(function(e,t=0){return D(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),o.prototype.writeFloatLE=function(e,t,n){return M(this,e,t,!0,n)},o.prototype.writeFloatBE=function(e,t,n){return M(this,e,t,!1,n)},o.prototype.writeDoubleLE=function(e,t,n){return L(this,e,t,!0,n)},o.prototype.writeDoubleBE=function(e,t,n){return L(this,e,t,!1,n)},o.prototype.copy=function(e,t,n,r){if(!o.isBuffer(e))throw new TypeError("argument should be a Buffer");if(n||(n=0),r||0===r||(r=this.length),t>=e.length&&(t=e.length),t||(t=0),r>0&&r<n&&(r=n),r===n)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(n<0||n>=this.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-t<r-n&&(r=e.length-t+n);const s=r-n;return this===e&&"function"==typeof Uint8Array.prototype.copyWithin?this.copyWithin(t,n,r):Uint8Array.prototype.set.call(e,this.subarray(n,r),t),s},o.prototype.fill=function(e,t,n,r){if("string"==typeof e){if("string"==typeof t?(r=t,t=0,n=this.length):"string"==typeof n&&(r=n,n=this.length),void 0!==r&&"string"!=typeof r)throw new TypeError("encoding must be a string");if("string"==typeof r&&!o.isEncoding(r))throw new TypeError("Unknown encoding: "+r);if(1===e.length){const t=e.charCodeAt(0);("utf8"===r&&t<128||"latin1"===r)&&(e=t)}}else"number"==typeof e?e&=255:"boolean"==typeof e&&(e=Number(e));if(t<0||this.length<t||this.length<n)throw new RangeError("Out of range index");if(n<=t)return this;let s;if(t>>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(s=t;s<n;++s)this[s]=e;else{const i=o.isBuffer(e)?e:o.from(e,r),a=i.length;if(0===a)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(s=0;s<n-t;++s)this[s+t]=i[s%a]}return this};const U={};function P(e,t,n){U[e]=class extends n{constructor(){super(),Object.defineProperty(this,"message",{value:t.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${e}]`,this.stack,delete this.name}get code(){return e}set code(e){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:e,writable:!0})}toString(){return`${this.name} [${e}]: ${this.message}`}}}function F(e){let t="",n=e.length;const r="-"===e[0]?1:0;for(;n>=r+4;n-=3)t=`_${e.slice(n-3,n)}${t}`;return`${e.slice(0,n)}${t}`}function $(e,t,n,r,s,i){if(e>n||e<t){const n="bigint"==typeof t?"n":"";let r;throw r=0===t||t===BigInt(0)?`>= 0${n} and < 2${n} ** ${8*(i+1)}${n}`:`>= -(2${n} ** ${8*(i+1)-1}${n}) and < 2 ** ${8*(i+1)-1}${n}`,new U.ERR_OUT_OF_RANGE("value",r,e)}!function(e,t,n){K(t,"offset"),void 0!==e[t]&&void 0!==e[t+n]||G(t,e.length-(n+1))}(r,s,i)}function K(e,t){if("number"!=typeof e)throw new U.ERR_INVALID_ARG_TYPE(t,"number",e)}function G(e,t,n){if(Math.floor(e)!==e)throw K(e,n),new U.ERR_OUT_OF_RANGE("offset","an integer",e);if(t<0)throw new U.ERR_BUFFER_OUT_OF_BOUNDS;throw new U.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${t}`,e)}P("ERR_BUFFER_OUT_OF_BOUNDS",function(e){return e?`${e} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),P("ERR_INVALID_ARG_TYPE",function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`},TypeError),P("ERR_OUT_OF_RANGE",function(e,t,n){let r=`The value of "${e}" is out of range.`,s=n;return Number.isInteger(n)&&Math.abs(n)>2**32?s=F(String(n)):"bigint"==typeof n&&(s=String(n),(n>BigInt(2)**BigInt(32)||n<-(BigInt(2)**BigInt(32)))&&(s=F(s)),s+="n"),r+=` It must be ${t}. Received ${s}`,r},RangeError);const W=/[^+/0-9A-Za-z-_]/g;function H(e,t){let n;t=t||1/0;const r=e.length;let s=null;const i=[];for(let o=0;o<r;++o){if(n=e.charCodeAt(o),n>55295&&n<57344){if(!s){if(n>56319){(t-=3)>-1&&i.push(239,191,189);continue}if(o+1===r){(t-=3)>-1&&i.push(239,191,189);continue}s=n;continue}if(n<56320){(t-=3)>-1&&i.push(239,191,189),s=n;continue}n=65536+(s-55296<<10|n-56320)}else s&&(t-=3)>-1&&i.push(239,191,189);if(s=null,n<128){if((t-=1)<0)break;i.push(n)}else if(n<2048){if((t-=2)<0)break;i.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;i.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;i.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return i}function q(e){return t.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(W,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function z(e,t,n,r){let s;for(s=0;s<r&&!(s+n>=t.length||s>=e.length);++s)t[s+n]=e[s];return s}function V(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function j(e){return e!=e}const X=function(){const e="0123456789abcdef",t=new Array(256);for(let n=0;n<16;++n){const r=16*n;for(let s=0;s<16;++s)t[r+s]=e[n]+e[s]}return t}();function Y(e){return"undefined"==typeof BigInt?J:e}function J(){throw new Error("BigInt not supported")}}(Io)),Io}var Oo=Do();const Mo="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0;function Lo(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function Uo(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function Po(e,...t){if(!Lo(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function Fo(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.createHasher");Uo(e.outputLen),Uo(e.blockLen)}function $o(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function Ko(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Go(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Wo(e,t){return e<<32-t|e>>>t}const Ho=(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)(),qo=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function zo(e){if(Po(e),Ho)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=qo[e[n]];return t}const Vo=48,jo=57,Xo=65,Yo=70,Jo=97,Qo=102;function Zo(e){return e>=Vo&&e<=jo?e-Vo:e>=Xo&&e<=Yo?e-(Xo-10):e>=Jo&&e<=Qo?e-(Jo-10):void 0}function ea(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);if(Ho)return Uint8Array.fromHex(e);const t=e.length,n=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);const r=new Uint8Array(n);for(let t=0,s=0;t<n;t++,s+=2){const n=Zo(e.charCodeAt(s)),i=Zo(e.charCodeAt(s+1));if(void 0===n||void 0===i){const t=e[s]+e[s+1];throw new Error('hex string expected, got non-hex character "'+t+'" at index '+s)}r[t]=16*n+i}return r}function ta(e){return"string"==typeof e&&(e=function(e){if("string"!=typeof e)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(e))}(e)),Po(e),e}function na(...e){let t=0;for(let n=0;n<e.length;n++){const r=e[n];Po(r),t+=r.length}const n=new Uint8Array(t);for(let t=0,r=0;t<e.length;t++){const s=e[t];n.set(s,r),r+=s.length}return n}class ra{}function sa(e){const t=t=>e().update(ta(t)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function ia(e=32){if(Mo&&"function"==typeof Mo.getRandomValues)return Mo.getRandomValues(new Uint8Array(e));if(Mo&&"function"==typeof Mo.randomBytes)return Uint8Array.from(Mo.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}function oa(e,t,n){return e&t^~e&n}function aa(e,t,n){return e&t^e&n^t&n}class ca extends ra{constructor(e,t,n,r){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(e),this.view=Go(this.buffer)}update(e){$o(this),Po(e=ta(e));const{view:t,buffer:n,blockLen:r}=this,s=e.length;for(let i=0;i<s;){const o=Math.min(r-this.pos,s-i);if(o===r){const t=Go(e);for(;r<=s-i;i+=r)this.process(t,i);continue}n.set(e.subarray(i,i+o),this.pos),this.pos+=o,i+=o,this.pos===r&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){$o(this),function(e,t){Po(e);const n=t.outputLen;if(e.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}(e,this),this.finished=!0;const{buffer:t,view:n,blockLen:r,isLE:s}=this;let{pos:i}=this;t[i++]=128,Ko(this.buffer.subarray(i)),this.padOffset>r-i&&(this.process(n,0),i=0);for(let e=i;e<r;e++)t[e]=0;!function(e,t,n,r){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,n,r);const s=BigInt(32),i=BigInt(4294967295),o=Number(n>>s&i),a=Number(n&i),c=r?4:0,l=r?0:4;e.setUint32(t+c,o,r),e.setUint32(t+l,a,r)}(n,r-8,BigInt(8*this.length),s),this.process(n,0);const o=Go(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const c=a/4,l=this.get();if(c>l.length)throw new Error("_sha2: outputLen bigger than state");for(let e=0;e<c;e++)o.setUint32(4*e,l[e],s)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:n,length:r,finished:s,destroyed:i,pos:o}=this;return e.destroyed=i,e.finished=s,e.length=r,e.pos=o,r%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}}const la=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ua=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),da=BigInt(2**32-1),ha=BigInt(32);function ga(e,t=!1){return t?{h:Number(e&da),l:Number(e>>ha&da)}:{h:0|Number(e>>ha&da),l:0|Number(e&da)}}const fa=(e,t,n)=>e>>>n,pa=(e,t,n)=>e<<32-n|t>>>n,ma=(e,t,n)=>e>>>n|t<<32-n,ya=(e,t,n)=>e<<32-n|t>>>n,ba=(e,t,n)=>e<<64-n|t>>>n-32,va=(e,t,n)=>e>>>n-32|t<<64-n;function wa(e,t,n,r){const s=(t>>>0)+(r>>>0);return{h:e+n+(s/2**32|0)|0,l:0|s}}const Ea=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),Aa=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,Sa=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),ka=(e,t,n,r,s)=>t+n+r+s+(e/2**32|0)|0,Ta=(e,t,n,r,s)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(s>>>0),Ia=(e,t,n,r,s,i)=>t+n+r+s+i+(e/2**32|0)|0,Na=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Ca=new Uint32Array(64);class _a extends ca{constructor(e=32){super(64,e,8,!1),this.A=0|la[0],this.B=0|la[1],this.C=0|la[2],this.D=0|la[3],this.E=0|la[4],this.F=0|la[5],this.G=0|la[6],this.H=0|la[7]}get(){const{A:e,B:t,C:n,D:r,E:s,F:i,G:o,H:a}=this;return[e,t,n,r,s,i,o,a]}set(e,t,n,r,s,i,o,a){this.A=0|e,this.B=0|t,this.C=0|n,this.D=0|r,this.E=0|s,this.F=0|i,this.G=0|o,this.H=0|a}process(e,t){for(let n=0;n<16;n++,t+=4)Ca[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){const t=Ca[e-15],n=Ca[e-2],r=Wo(t,7)^Wo(t,18)^t>>>3,s=Wo(n,17)^Wo(n,19)^n>>>10;Ca[e]=s+Ca[e-7]+r+Ca[e-16]|0}let{A:n,B:r,C:s,D:i,E:o,F:a,G:c,H:l}=this;for(let e=0;e<64;e++){const t=l+(Wo(o,6)^Wo(o,11)^Wo(o,25))+oa(o,a,c)+Na[e]+Ca[e]|0,u=(Wo(n,2)^Wo(n,13)^Wo(n,22))+aa(n,r,s)|0;l=c,c=a,a=o,o=i+t|0,i=s,s=r,r=n,n=t+u|0}n=n+this.A|0,r=r+this.B|0,s=s+this.C|0,i=i+this.D|0,o=o+this.E|0,a=a+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(n,r,s,i,o,a,c,l)}roundClean(){Ko(Ca)}destroy(){this.set(0,0,0,0,0,0,0,0),Ko(this.buffer)}}const xa=(()=>function(e,t=!1){const n=e.length;let r=new Uint32Array(n),s=new Uint32Array(n);for(let i=0;i<n;i++){const{h:n,l:o}=ga(e[i],t);[r[i],s[i]]=[n,o]}return[r,s]}(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))))(),Ra=(()=>xa[0])(),Ba=(()=>xa[1])(),Da=new Uint32Array(80),Oa=new Uint32Array(80);class Ma extends ca{constructor(e=64){super(128,e,16,!1),this.Ah=0|ua[0],this.Al=0|ua[1],this.Bh=0|ua[2],this.Bl=0|ua[3],this.Ch=0|ua[4],this.Cl=0|ua[5],this.Dh=0|ua[6],this.Dl=0|ua[7],this.Eh=0|ua[8],this.El=0|ua[9],this.Fh=0|ua[10],this.Fl=0|ua[11],this.Gh=0|ua[12],this.Gl=0|ua[13],this.Hh=0|ua[14],this.Hl=0|ua[15]}get(){const{Ah:e,Al:t,Bh:n,Bl:r,Ch:s,Cl:i,Dh:o,Dl:a,Eh:c,El:l,Fh:u,Fl:d,Gh:h,Gl:g,Hh:f,Hl:p}=this;return[e,t,n,r,s,i,o,a,c,l,u,d,h,g,f,p]}set(e,t,n,r,s,i,o,a,c,l,u,d,h,g,f,p){this.Ah=0|e,this.Al=0|t,this.Bh=0|n,this.Bl=0|r,this.Ch=0|s,this.Cl=0|i,this.Dh=0|o,this.Dl=0|a,this.Eh=0|c,this.El=0|l,this.Fh=0|u,this.Fl=0|d,this.Gh=0|h,this.Gl=0|g,this.Hh=0|f,this.Hl=0|p}process(e,t){for(let n=0;n<16;n++,t+=4)Da[n]=e.getUint32(t),Oa[n]=e.getUint32(t+=4);for(let e=16;e<80;e++){const t=0|Da[e-15],n=0|Oa[e-15],r=ma(t,n,1)^ma(t,n,8)^fa(t,0,7),s=ya(t,n,1)^ya(t,n,8)^pa(t,n,7),i=0|Da[e-2],o=0|Oa[e-2],a=ma(i,o,19)^ba(i,o,61)^fa(i,0,6),c=ya(i,o,19)^va(i,o,61)^pa(i,o,6),l=Sa(s,c,Oa[e-7],Oa[e-16]),u=ka(l,r,a,Da[e-7],Da[e-16]);Da[e]=0|u,Oa[e]=0|l}let{Ah:n,Al:r,Bh:s,Bl:i,Ch:o,Cl:a,Dh:c,Dl:l,Eh:u,El:d,Fh:h,Fl:g,Gh:f,Gl:p,Hh:m,Hl:y}=this;for(let e=0;e<80;e++){const t=ma(u,d,14)^ma(u,d,18)^ba(u,d,41),b=ya(u,d,14)^ya(u,d,18)^va(u,d,41),v=u&h^~u&f,w=Ta(y,b,d&g^~d&p,Ba[e],Oa[e]),E=Ia(w,m,t,v,Ra[e],Da[e]),A=0|w,S=ma(n,r,28)^ba(n,r,34)^ba(n,r,39),k=ya(n,r,28)^va(n,r,34)^va(n,r,39),T=n&s^n&o^s&o,I=r&i^r&a^i&a;m=0|f,y=0|p,f=0|h,p=0|g,h=0|u,g=0|d,({h:u,l:d}=wa(0|c,0|l,0|E,0|A)),c=0|o,l=0|a,o=0|s,a=0|i,s=0|n,i=0|r;const N=Ea(A,k,I);n=Aa(N,E,S,T),r=0|N}({h:n,l:r}=wa(0|this.Ah,0|this.Al,0|n,0|r)),({h:s,l:i}=wa(0|this.Bh,0|this.Bl,0|s,0|i)),({h:o,l:a}=wa(0|this.Ch,0|this.Cl,0|o,0|a)),({h:c,l:l}=wa(0|this.Dh,0|this.Dl,0|c,0|l)),({h:u,l:d}=wa(0|this.Eh,0|this.El,0|u,0|d)),({h:h,l:g}=wa(0|this.Fh,0|this.Fl,0|h,0|g)),({h:f,l:p}=wa(0|this.Gh,0|this.Gl,0|f,0|p)),({h:m,l:y}=wa(0|this.Hh,0|this.Hl,0|m,0|y)),this.set(n,r,s,i,o,a,c,l,u,d,h,g,f,p,m,y)}roundClean(){Ko(Da,Oa)}destroy(){Ko(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const La=sa(()=>new _a),Ua=sa(()=>new Ma),Pa=BigInt(0),Fa=BigInt(1);function $a(e,t=""){if("boolean"!=typeof e){throw new Error((t&&`"${t}"`)+"expected boolean, got type="+typeof e)}return e}function Ka(e,t,n=""){const r=Lo(e),s=e?.length,i=void 0!==t;if(!r||i&&s!==t){throw new Error((n&&`"${n}" `)+"expected Uint8Array"+(i?` of length ${t}`:"")+", got "+(r?`length=${s}`:"type="+typeof e))}return e}function Ga(e){const t=e.toString(16);return 1&t.length?"0"+t:t}function Wa(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);return""===e?Pa:BigInt("0x"+e)}function Ha(e){return Wa(zo(e))}function qa(e){return Po(e),Wa(zo(Uint8Array.from(e).reverse()))}function za(e,t){return ea(e.toString(16).padStart(2*t,"0"))}function Va(e,t){return za(e,t).reverse()}function ja(e,t,n){let r;if("string"==typeof t)try{r=ea(t)}catch(t){throw new Error(e+" must be hex string or Uint8Array, cause: "+t)}else{if(!Lo(t))throw new Error(e+" must be hex string or Uint8Array");r=Uint8Array.from(t)}const s=r.length;if("number"==typeof n&&s!==n)throw new Error(e+" of length "+n+" expected, got "+s);return r}function Xa(e){return Uint8Array.from(e)}const Ya=e=>"bigint"==typeof e&&Pa<=e;function Ja(e,t,n,r){if(!function(e,t,n){return Ya(e)&&Ya(t)&&Ya(n)&&t<=e&&e<n}(t,n,r))throw new Error("expected valid "+e+": "+n+" <= n < "+r+", got "+t)}function Qa(e){let t;for(t=0;e>Pa;e>>=Fa,t+=1);return t}const Za=e=>(Fa<<BigInt(e))-Fa;function ec(e,t,n={}){if(!e||"object"!=typeof e)throw new Error("expected valid options object");function r(t,n,r){const s=e[t];if(r&&void 0===s)return;const i=typeof s;if(i!==n||null===s)throw new Error(`param "${t}" is invalid: expected ${n}, got ${i}`)}Object.entries(t).forEach(([e,t])=>r(e,t,!1)),Object.entries(n).forEach(([e,t])=>r(e,t,!0))}function tc(e){const t=new WeakMap;return(n,...r)=>{const s=t.get(n);if(void 0!==s)return s;const i=e(n,...r);return t.set(n,i),i}}const nc=BigInt(0),rc=BigInt(1),sc=BigInt(2),ic=BigInt(3),oc=BigInt(4),ac=BigInt(5),cc=BigInt(7),lc=BigInt(8),uc=BigInt(9),dc=BigInt(16);function hc(e,t){const n=e%t;return n>=nc?n:t+n}function gc(e,t,n){let r=e;for(;t-- >nc;)r*=r,r%=n;return r}function fc(e,t){if(e===nc)throw new Error("invert: expected non-zero number");if(t<=nc)throw new Error("invert: expected positive modulus, got "+t);let n=hc(e,t),r=t,s=nc,i=rc;for(;n!==nc;){const e=r%n,t=s-i*(r/n);r=n,n=e,s=i,i=t}if(r!==rc)throw new Error("invert: does not exist");return hc(s,t)}function pc(e,t,n){if(!e.eql(e.sqr(t),n))throw new Error("Cannot find square root")}function mc(e,t){const n=(e.ORDER+rc)/oc,r=e.pow(t,n);return pc(e,r,t),r}function yc(e,t){const n=(e.ORDER-ac)/lc,r=e.mul(t,sc),s=e.pow(r,n),i=e.mul(t,s),o=e.mul(e.mul(i,sc),s),a=e.mul(i,e.sub(o,e.ONE));return pc(e,a,t),a}function bc(e){if(e<ic)throw new Error("sqrt is not defined for small field");let t=e-rc,n=0;for(;t%sc===nc;)t/=sc,n++;let r=sc;const s=kc(e);for(;1===Ac(s,r);)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(1===n)return mc;let i=s.pow(r,t);const o=(t+rc)/sc;return function(e,r){if(e.is0(r))return r;if(1!==Ac(e,r))throw new Error("Cannot find square root");let s=n,a=e.mul(e.ONE,i),c=e.pow(r,t),l=e.pow(r,o);for(;!e.eql(c,e.ONE);){if(e.is0(c))return e.ZERO;let t=1,n=e.sqr(c);for(;!e.eql(n,e.ONE);)if(t++,n=e.sqr(n),t===s)throw new Error("Cannot find square root");const r=rc<<BigInt(s-t-1),i=e.pow(a,r);s=t,a=e.sqr(i),c=e.mul(c,a),l=e.mul(l,i)}return l}}function vc(e){return e%oc===ic?mc:e%lc===ac?yc:e%dc===uc?function(e){const t=kc(e),n=bc(e),r=n(t,t.neg(t.ONE)),s=n(t,r),i=n(t,t.neg(r)),o=(e+cc)/dc;return(e,t)=>{let n=e.pow(t,o),a=e.mul(n,r);const c=e.mul(n,s),l=e.mul(n,i),u=e.eql(e.sqr(a),t),d=e.eql(e.sqr(c),t);n=e.cmov(n,a,u),a=e.cmov(l,c,d);const h=e.eql(e.sqr(a),t),g=e.cmov(n,a,h);return pc(e,g,t),g}}(e):bc(e)}const wc=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Ec(e,t,n=!1){const r=new Array(t.length).fill(n?e.ZERO:void 0),s=t.reduce((t,n,s)=>e.is0(n)?t:(r[s]=t,e.mul(t,n)),e.ONE),i=e.inv(s);return t.reduceRight((t,n,s)=>e.is0(n)?t:(r[s]=e.mul(t,r[s]),e.mul(t,n)),i),r}function Ac(e,t){const n=(e.ORDER-rc)/sc,r=e.pow(t,n),s=e.eql(r,e.ONE),i=e.eql(r,e.ZERO),o=e.eql(r,e.neg(e.ONE));if(!s&&!i&&!o)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function Sc(e,t){void 0!==t&&Uo(t);const n=void 0!==t?t:e.toString(2).length;return{nBitLength:n,nByteLength:Math.ceil(n/8)}}function kc(e,t,n=!1,r={}){if(e<=nc)throw new Error("invalid field: expected ORDER > 0, got "+e);let s,i,o,a=!1;if("object"==typeof t&&null!=t){if(r.sqrt||n)throw new Error("cannot specify opts in two arguments");const e=t;e.BITS&&(s=e.BITS),e.sqrt&&(i=e.sqrt),"boolean"==typeof e.isLE&&(n=e.isLE),"boolean"==typeof e.modFromBytes&&(a=e.modFromBytes),o=e.allowedLengths}else"number"==typeof t&&(s=t),r.sqrt&&(i=r.sqrt);const{nBitLength:c,nByteLength:l}=Sc(e,s);if(l>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let u;const d=Object.freeze({ORDER:e,isLE:n,BITS:c,BYTES:l,MASK:Za(c),ZERO:nc,ONE:rc,allowedLengths:o,create:t=>hc(t,e),isValid:t=>{if("bigint"!=typeof t)throw new Error("invalid field element: expected bigint, got "+typeof t);return nc<=t&&t<e},is0:e=>e===nc,isValidNot0:e=>!d.is0(e)&&d.isValid(e),isOdd:e=>(e&rc)===rc,neg:t=>hc(-t,e),eql:(e,t)=>e===t,sqr:t=>hc(t*t,e),add:(t,n)=>hc(t+n,e),sub:(t,n)=>hc(t-n,e),mul:(t,n)=>hc(t*n,e),pow:(e,t)=>function(e,t,n){if(n<nc)throw new Error("invalid exponent, negatives unsupported");if(n===nc)return e.ONE;if(n===rc)return t;let r=e.ONE,s=t;for(;n>nc;)n&rc&&(r=e.mul(r,s)),s=e.sqr(s),n>>=rc;return r}(d,e,t),div:(t,n)=>hc(t*fc(n,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>fc(t,e),sqrt:i||(t=>(u||(u=vc(e)),u(d,t))),toBytes:e=>n?Va(e,l):za(e,l),fromBytes:(t,r=!0)=>{if(o){if(!o.includes(t.length)||t.length>l)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+t.length);const e=new Uint8Array(l);e.set(t,n?0:e.length-t.length),t=e}if(t.length!==l)throw new Error("Field.fromBytes: expected "+l+" bytes, got "+t.length);let s=n?qa(t):Ha(t);if(a&&(s=hc(s,e)),!r&&!d.isValid(s))throw new Error("invalid field element: outside of range 0..ORDER");return s},invertBatch:e=>Ec(d,e),cmov:(e,t,n)=>n?t:e});return Object.freeze(d)}function Tc(e){if("bigint"!=typeof e)throw new Error("field order must be bigint");const t=e.toString(2).length;return Math.ceil(t/8)}function Ic(e){const t=Tc(e);return t+Math.ceil(t/2)}const Nc=BigInt(0),Cc=BigInt(1);function _c(e,t){const n=t.negate();return e?n:t}function xc(e,t){const n=Ec(e.Fp,t.map(e=>e.Z));return t.map((t,r)=>e.fromAffine(t.toAffine(n[r])))}function Rc(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function Bc(e,t){Rc(e,t);const n=2**e;return{windows:Math.ceil(t/e)+1,windowSize:2**(e-1),mask:Za(e),maxNumber:n,shiftBy:BigInt(e)}}function Dc(e,t,n){const{windowSize:r,mask:s,maxNumber:i,shiftBy:o}=n;let a=Number(e&s),c=e>>o;a>r&&(a-=i,c+=Cc);const l=t*r;return{nextN:c,offset:l+Math.abs(a)-1,isZero:0===a,isNeg:a<0,isNegF:t%2!=0,offsetF:l}}const Oc=new WeakMap,Mc=new WeakMap;function Lc(e){return Mc.get(e)||1}function Uc(e){if(e!==Nc)throw new Error("invalid wNAF")}class Pc{constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,n=this.ZERO){let r=e;for(;t>Nc;)t&Cc&&(n=n.add(r)),r=r.double(),t>>=Cc;return n}precomputeWindow(e,t){const{windows:n,windowSize:r}=Bc(t,this.bits),s=[];let i=e,o=i;for(let e=0;e<n;e++){o=i,s.push(o);for(let e=1;e<r;e++)o=o.add(i),s.push(o);i=o.double()}return s}wNAF(e,t,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let r=this.ZERO,s=this.BASE;const i=Bc(e,this.bits);for(let e=0;e<i.windows;e++){const{nextN:o,offset:a,isZero:c,isNeg:l,isNegF:u,offsetF:d}=Dc(n,e,i);n=o,c?s=s.add(_c(u,t[d])):r=r.add(_c(l,t[a]))}return Uc(n),{p:r,f:s}}wNAFUnsafe(e,t,n,r=this.ZERO){const s=Bc(e,this.bits);for(let e=0;e<s.windows&&n!==Nc;e++){const{nextN:i,offset:o,isZero:a,isNeg:c}=Dc(n,e,s);if(n=i,!a){const e=t[o];r=r.add(c?e.negate():e)}}return Uc(n),r}getPrecomputes(e,t,n){let r=Oc.get(t);return r||(r=this.precomputeWindow(t,e),1!==e&&("function"==typeof n&&(r=n(r)),Oc.set(t,r))),r}cached(e,t,n){const r=Lc(e);return this.wNAF(r,this.getPrecomputes(r,e,n),t)}unsafe(e,t,n,r){const s=Lc(e);return 1===s?this._unsafeLadder(e,t,r):this.wNAFUnsafe(s,this.getPrecomputes(s,e,n),t,r)}createCache(e,t){Rc(t,this.bits),Mc.set(e,t),Oc.delete(e)}hasCache(e){return 1!==Lc(e)}}function Fc(e,t,n,r){!function(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach((e,n)=>{if(!(e instanceof t))throw new Error("invalid point at index "+n)})}(n,e),function(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((e,n)=>{if(!t.isValid(e))throw new Error("invalid scalar at index "+n)})}(r,t);const s=n.length,i=r.length;if(s!==i)throw new Error("arrays of points and scalars must have equal length");const o=e.ZERO,a=Qa(BigInt(s));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const l=Za(c),u=new Array(Number(l)+1).fill(o);let d=o;for(let e=Math.floor((t.BITS-1)/c)*c;e>=0;e-=c){u.fill(o);for(let t=0;t<i;t++){const s=r[t],i=Number(s>>BigInt(e)&l);u[i]=u[i].add(n[t])}let t=o;for(let e=u.length-1,n=o;e>0;e--)n=n.add(u[e]),t=t.add(n);if(d=d.add(t),0!==e)for(let e=0;e<c;e++)d=d.double()}return d}function $c(e,t,n){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return function(e){ec(e,wc.reduce((e,t)=>(e[t]="function",e),{ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"}))}(t),t}return kc(e,{isLE:n})}function Kc(e,t,n={},r){if(void 0===r&&(r="edwards"===e),!t||"object"!=typeof t)throw new Error(`expected valid ${e} CURVE object`);for(const e of["p","n","h"]){const n=t[e];if(!("bigint"==typeof n&&n>Nc))throw new Error(`CURVE.${e} must be positive bigint`)}const s=$c(t.p,n.Fp,r),i=$c(t.n,n.Fn,r),o=["Gx","Gy","a","weierstrass"===e?"b":"d"];for(const e of o)if(!s.isValid(t[e]))throw new Error(`CURVE.${e} must be valid field element of CURVE.Fp`);return{CURVE:t=Object.freeze(Object.assign({},t)),Fp:s,Fn:i}}const Gc=BigInt(0),Wc=BigInt(1),Hc=BigInt(2),qc=BigInt(8);function zc(e,t,n={}){if("function"!=typeof t)throw new Error('"hash" function param is required');ec(n,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});const{prehash:r}=n,{BASE:s,Fp:i,Fn:o}=e,a=n.randomBytes||ia,c=n.adjustScalarBytes||(e=>e),l=n.domain||((e,t,n)=>{if($a(n,"phflag"),t.length||n)throw new Error("Contexts/pre-hash are not supported");return e});function u(e){return o.create(qa(e))}function d(e){const{head:n,prefix:r,scalar:i}=function(e){const n=m.secretKey;e=ja("private key",e,n);const r=ja("hashed private key",t(e),2*n),s=c(r.slice(0,n));return{head:s,prefix:r.slice(n,2*n),scalar:u(s)}}(e),o=s.multiply(i),a=o.toBytes();return{head:n,prefix:r,scalar:i,point:o,pointBytes:a}}function h(e){return d(e).pointBytes}function g(e=Uint8Array.of(),...n){const s=na(...n);return u(t(l(s,ja("context",e),!!r)))}const f={zip215:!0};const p=i.BYTES,m={secretKey:p,publicKey:p,signature:2*p,seed:p};function y(e=a(m.seed)){return Ka(e,m.seed,"seed")}const b={getExtendedPublicKey:d,randomSecretKey:y,isValidSecretKey:function(e){return Lo(e)&&e.length===o.BYTES},isValidPublicKey:function(t,n){try{return!!e.fromBytes(t,n)}catch(e){return!1}},toMontgomery(t){const{y:n}=e.fromBytes(t),r=m.publicKey,s=32===r;if(!s&&57!==r)throw new Error("only defined for 25519 and 448");const o=s?i.div(Wc+n,Wc-n):i.div(n-Wc,n+Wc);return i.toBytes(o)},toMontgomerySecret(e){const n=m.secretKey;Ka(e,n);const r=t(e.subarray(0,n));return c(r).subarray(0,n)},randomPrivateKey:y,precompute:(t=8,n=e.BASE)=>n.precompute(t,!1)};return Object.freeze({keygen:function(e){const t=b.randomSecretKey(e);return{secretKey:t,publicKey:h(t)}},getPublicKey:h,sign:function(e,t,n={}){e=ja("message",e),r&&(e=r(e));const{prefix:i,scalar:a,pointBytes:c}=d(t),l=g(n.context,i,e),u=s.multiply(l).toBytes(),h=g(n.context,u,c,e),f=o.create(l+h*a);if(!o.isValid(f))throw new Error("sign failed: invalid s");return Ka(na(u,o.toBytes(f)),m.signature,"result")},verify:function(t,n,i,o=f){const{context:a,zip215:c}=o,l=m.signature;t=ja("signature",t,l),n=ja("message",n),i=ja("publicKey",i,m.publicKey),void 0!==c&&$a(c,"zip215"),r&&(n=r(n));const u=l/2,d=t.subarray(0,u),h=qa(t.subarray(u,l));let p,y,b;try{p=e.fromBytes(i,c),y=e.fromBytes(d,c),b=s.multiplyUnsafe(h)}catch(e){return!1}if(!c&&p.isSmallOrder())return!1;const v=g(a,y.toBytes(),p.toBytes(),n);return y.add(p.multiplyUnsafe(v)).subtract(b).clearCofactor().is0()},utils:b,Point:e,lengths:m})}function Vc(e){const{CURVE:t,curveOpts:n,hash:r,eddsaOpts:s}=function(e){const t={a:e.a,d:e.d,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},n={Fp:e.Fp,Fn:kc(t.n,e.nBitLength,!0),uvRatio:e.uvRatio},r={randomBytes:e.randomBytes,adjustScalarBytes:e.adjustScalarBytes,domain:e.domain,prehash:e.prehash,mapToCurve:e.mapToCurve};return{CURVE:t,curveOpts:n,hash:e.hash,eddsaOpts:r}}(e),i=function(e,t={}){const n=Kc("edwards",e,t,t.FpFnLE),{Fp:r,Fn:s}=n;let i=n.CURVE;const{h:o}=i;ec(t,{},{uvRatio:"function"});const a=Hc<<BigInt(8*s.BYTES)-Wc,c=e=>r.create(e),l=t.uvRatio||((e,t)=>{try{return{isValid:!0,value:r.sqrt(r.div(e,t))}}catch(e){return{isValid:!1,value:Gc}}});if(!function(e,t,n,r){const s=e.sqr(n),i=e.sqr(r),o=e.add(e.mul(t.a,s),i),a=e.add(e.ONE,e.mul(t.d,e.mul(s,i)));return e.eql(o,a)}(r,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");function u(e,t,n=!1){return Ja("coordinate "+e,t,n?Wc:Gc,a),t}function d(e){if(!(e instanceof f))throw new Error("ExtendedPoint expected")}const h=tc((e,t)=>{const{X:n,Y:s,Z:i}=e,o=e.is0();null==t&&(t=o?qc:r.inv(i));const a=c(n*t),l=c(s*t),u=r.mul(i,t);if(o)return{x:Gc,y:Wc};if(u!==Wc)throw new Error("invZ was invalid");return{x:a,y:l}}),g=tc(e=>{const{a:t,d:n}=i;if(e.is0())throw new Error("bad point: ZERO");const{X:r,Y:s,Z:o,T:a}=e,l=c(r*r),u=c(s*s),d=c(o*o),h=c(d*d),g=c(l*t);if(c(d*c(g+u))!==c(h+c(n*c(l*u))))throw new Error("bad point: equation left != right (1)");if(c(r*s)!==c(o*a))throw new Error("bad point: equation left != right (2)");return!0});class f{constructor(e,t,n,r){this.X=u("x",e),this.Y=u("y",t),this.Z=u("z",n,!0),this.T=u("t",r),Object.freeze(this)}static CURVE(){return i}static fromAffine(e){if(e instanceof f)throw new Error("extended point not allowed");const{x:t,y:n}=e||{};return u("x",t),u("y",n),new f(t,n,Wc,c(t*n))}static fromBytes(e,t=!1){const n=r.BYTES,{a:s,d:o}=i;e=Xa(Ka(e,n,"point")),$a(t,"zip215");const u=Xa(e),d=e[n-1];u[n-1]=-129&d;const h=qa(u),g=t?a:r.ORDER;Ja("point.y",h,Gc,g);const p=c(h*h),m=c(p-Wc),y=c(o*p-s);let{isValid:b,value:v}=l(m,y);if(!b)throw new Error("bad point: invalid y coordinate");const w=(v&Wc)===Wc,E=!!(128&d);if(!t&&v===Gc&&E)throw new Error("bad point: x=0 and x_0=1");return E!==w&&(v=c(-v)),f.fromAffine({x:v,y:h})}static fromHex(e,t=!1){return f.fromBytes(ja("point",e),t)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(e=8,t=!0){return p.createCache(this,e),t||this.multiply(Hc),this}assertValidity(){g(this)}equals(e){d(e);const{X:t,Y:n,Z:r}=this,{X:s,Y:i,Z:o}=e,a=c(t*o),l=c(s*r),u=c(n*o),h=c(i*r);return a===l&&u===h}is0(){return this.equals(f.ZERO)}negate(){return new f(c(-this.X),this.Y,this.Z,c(-this.T))}double(){const{a:e}=i,{X:t,Y:n,Z:r}=this,s=c(t*t),o=c(n*n),a=c(Hc*c(r*r)),l=c(e*s),u=t+n,d=c(c(u*u)-s-o),h=l+o,g=h-a,p=l-o,m=c(d*g),y=c(h*p),b=c(d*p),v=c(g*h);return new f(m,y,v,b)}add(e){d(e);const{a:t,d:n}=i,{X:r,Y:s,Z:o,T:a}=this,{X:l,Y:u,Z:h,T:g}=e,p=c(r*l),m=c(s*u),y=c(a*n*g),b=c(o*h),v=c((r+s)*(l+u)-p-m),w=b-y,E=b+y,A=c(m-t*p),S=c(v*w),k=c(E*A),T=c(v*A),I=c(w*E);return new f(S,k,I,T)}subtract(e){return this.add(e.negate())}multiply(e){if(!s.isValidNot0(e))throw new Error("invalid scalar: expected 1 <= sc < curve.n");const{p:t,f:n}=p.cached(this,e,e=>xc(f,e));return xc(f,[t,n])[0]}multiplyUnsafe(e,t=f.ZERO){if(!s.isValid(e))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return e===Gc?f.ZERO:this.is0()||e===Wc?this:p.unsafe(this,e,e=>xc(f,e),t)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}isTorsionFree(){return p.unsafe(this,i.n).is0()}toAffine(e){return h(this,e)}clearCofactor(){return o===Wc?this:this.multiplyUnsafe(o)}toBytes(){const{x:e,y:t}=this.toAffine(),n=r.toBytes(t);return n[n.length-1]|=e&Wc?128:0,n}toHex(){return zo(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get ex(){return this.X}get ey(){return this.Y}get ez(){return this.Z}get et(){return this.T}static normalizeZ(e){return xc(f,e)}static msm(e,t){return Fc(f,s,e,t)}_setWindowSize(e){this.precompute(e)}toRawBytes(){return this.toBytes()}}f.BASE=new f(i.Gx,i.Gy,Wc,c(i.Gx*i.Gy)),f.ZERO=new f(Gc,Wc,Wc,Gc),f.Fp=r,f.Fn=s;const p=new Pc(f,s.BITS);return f.BASE.precompute(8),f}(t,n);return function(e,t){const n=t.Point;return Object.assign({},t,{ExtendedPoint:n,CURVE:e,nBitLength:n.Fn.BITS,nByteLength:n.Fn.BYTES})}(e,zc(i,r,s))}const jc=BigInt(1),Xc=BigInt(2);BigInt(3);const Yc=BigInt(5),Jc=BigInt(8),Qc=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Zc=(()=>({p:Qc,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Jc,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")}))();function el(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}const tl=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function nl(e,t){const n=Qc,r=hc(t*t*t,n),s=function(e){const t=BigInt(10),n=BigInt(20),r=BigInt(40),s=BigInt(80),i=Qc,o=e*e%i*e%i,a=gc(o,Xc,i)*o%i,c=gc(a,jc,i)*e%i,l=gc(c,Yc,i)*c%i,u=gc(l,t,i)*l%i,d=gc(u,n,i)*u%i,h=gc(d,r,i)*d%i,g=gc(h,s,i)*h%i,f=gc(g,s,i)*h%i,p=gc(f,t,i)*l%i;return{pow_p_5_8:gc(p,Xc,i)*e%i,b2:o}}(e*hc(r*r*t,n)).pow_p_5_8;let i=hc(e*r*s,n);const o=hc(t*i*i,n),a=i,c=hc(i*tl,n),l=o===e,u=o===hc(-e,n),d=o===hc(-e*tl,n);return l&&(i=a),(u||d)&&(i=c),(hc(i,n)&rc)===rc&&(i=hc(-i,n)),{isValid:l||u,value:i}}const rl=(()=>kc(Zc.p,{isLE:!0}))(),sl=(()=>({...Zc,Fp:rl,hash:Ua,adjustScalarBytes:el,uvRatio:nl}))(),il=(()=>Vc(sl))();var ol,al={exports:{}},cl=ko(Object.freeze({__proto__:null,default:{}})),ll=al.exports;function ul(){return ol||(ol=1,function(e,t){function n(e,t){if(!e)throw new Error(t||"Assertion failed")}function r(e,t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}function s(e,t,n){if(s.isBN(e))return e;this.negative=0,this.words=null,this.length=0,this.red=null,null!==e&&("le"!==t&&"be"!==t||(n=t,t=10),this._init(e||0,t||10,n||"be"))}var i;"object"==typeof e?e.exports=s:t.BN=s,s.BN=s,s.wordSize=26;try{i="undefined"!=typeof window&&void 0!==window.Buffer?window.Buffer:cl.Buffer}catch(e){}function o(e,t){var r=e.charCodeAt(t);return r>=48&&r<=57?r-48:r>=65&&r<=70?r-55:r>=97&&r<=102?r-87:void n(!1,"Invalid character in "+e)}function a(e,t,n){var r=o(e,n);return n-1>=t&&(r|=o(e,n-1)<<4),r}function c(e,t,r,s){for(var i=0,o=0,a=Math.min(e.length,r),c=t;c<a;c++){var l=e.charCodeAt(c)-48;i*=s,o=l>=49?l-49+10:l>=17?l-17+10:l,n(l>=0&&o<s,"Invalid character"),i+=o}return i}function l(e,t){e.words=t.words,e.length=t.length,e.negative=t.negative,e.red=t.red}if(s.isBN=function(e){return e instanceof s||null!==e&&"object"==typeof e&&e.constructor.wordSize===s.wordSize&&Array.isArray(e.words)},s.max=function(e,t){return e.cmp(t)>0?e:t},s.min=function(e,t){return e.cmp(t)<0?e:t},s.prototype._init=function(e,t,r){if("number"==typeof e)return this._initNumber(e,t,r);if("object"==typeof e)return this._initArray(e,t,r);"hex"===t&&(t=16),n(t===(0|t)&&t>=2&&t<=36);var s=0;"-"===(e=e.toString().replace(/\s+/g,""))[0]&&(s++,this.negative=1),s<e.length&&(16===t?this._parseHex(e,s,r):(this._parseBase(e,t,s),"le"===r&&this._initArray(this.toArray(),t,r)))},s.prototype._initNumber=function(e,t,r){e<0&&(this.negative=1,e=-e),e<67108864?(this.words=[67108863&e],this.length=1):e<4503599627370496?(this.words=[67108863&e,e/67108864&67108863],this.length=2):(n(e<9007199254740992),this.words=[67108863&e,e/67108864&67108863,1],this.length=3),"le"===r&&this._initArray(this.toArray(),t,r)},s.prototype._initArray=function(e,t,r){if(n("number"==typeof e.length),e.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(e.length/3),this.words=new Array(this.length);for(var s=0;s<this.length;s++)this.words[s]=0;var i,o,a=0;if("be"===r)for(s=e.length-1,i=0;s>=0;s-=3)o=e[s]|e[s-1]<<8|e[s-2]<<16,this.words[i]|=o<<a&67108863,this.words[i+1]=o>>>26-a&67108863,(a+=24)>=26&&(a-=26,i++);else if("le"===r)for(s=0,i=0;s<e.length;s+=3)o=e[s]|e[s+1]<<8|e[s+2]<<16,this.words[i]|=o<<a&67108863,this.words[i+1]=o>>>26-a&67108863,(a+=24)>=26&&(a-=26,i++);return this._strip()},s.prototype._parseHex=function(e,t,n){this.length=Math.ceil((e.length-t)/6),this.words=new Array(this.length);for(var r=0;r<this.length;r++)this.words[r]=0;var s,i=0,o=0;if("be"===n)for(r=e.length-1;r>=t;r-=2)s=a(e,t,r)<<i,this.words[o]|=67108863&s,i>=18?(i-=18,o+=1,this.words[o]|=s>>>26):i+=8;else for(r=(e.length-t)%2==0?t+1:t;r<e.length;r+=2)s=a(e,t,r)<<i,this.words[o]|=67108863&s,i>=18?(i-=18,o+=1,this.words[o]|=s>>>26):i+=8;this._strip()},s.prototype._parseBase=function(e,t,n){this.words=[0],this.length=1;for(var r=0,s=1;s<=67108863;s*=t)r++;r--,s=s/t|0;for(var i=e.length-n,o=i%r,a=Math.min(i,i-o)+n,l=0,u=n;u<a;u+=r)l=c(e,u,u+r,t),this.imuln(s),this.words[0]+l<67108864?this.words[0]+=l:this._iaddn(l);if(0!==o){var d=1;for(l=c(e,u,e.length,t),u=0;u<o;u++)d*=t;this.imuln(d),this.words[0]+l<67108864?this.words[0]+=l:this._iaddn(l)}this._strip()},s.prototype.copy=function(e){e.words=new Array(this.length);for(var t=0;t<this.length;t++)e.words[t]=this.words[t];e.length=this.length,e.negative=this.negative,e.red=this.red},s.prototype._move=function(e){l(e,this)},s.prototype.clone=function(){var e=new s(null);return this.copy(e),e},s.prototype._expand=function(e){for(;this.length<e;)this.words[this.length++]=0;return this},s.prototype._strip=function(){for(;this.length>1&&0===this.words[this.length-1];)this.length--;return this._normSign()},s.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},"undefined"!=typeof Symbol&&"function"==typeof Symbol.for)try{s.prototype[Symbol.for("nodejs.util.inspect.custom")]=u}catch(e){s.prototype.inspect=u}else s.prototype.inspect=u;function u(){return(this.red?"<BN-R: ":"<BN: ")+this.toString(16)+">"}var d=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],h=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],g=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];function f(e,t,n){n.negative=t.negative^e.negative;var r=e.length+t.length|0;n.length=r,r=r-1|0;var s=0|e.words[0],i=0|t.words[0],o=s*i,a=67108863&o,c=o/67108864|0;n.words[0]=a;for(var l=1;l<r;l++){for(var u=c>>>26,d=67108863&c,h=Math.min(l,t.length-1),g=Math.max(0,l-e.length+1);g<=h;g++){var f=l-g|0;u+=(o=(s=0|e.words[f])*(i=0|t.words[g])+d)/67108864|0,d=67108863&o}n.words[l]=0|d,c=0|u}return 0!==c?n.words[l]=0|c:n.length--,n._strip()}s.prototype.toString=function(e,t){var r;if(t=0|t||1,16===(e=e||10)||"hex"===e){r="";for(var s=0,i=0,o=0;o<this.length;o++){var a=this.words[o],c=(16777215&(a<<s|i)).toString(16);i=a>>>24-s&16777215,(s+=2)>=26&&(s-=26,o--),r=0!==i||o!==this.length-1?d[6-c.length]+c+r:c+r}for(0!==i&&(r=i.toString(16)+r);r.length%t!==0;)r="0"+r;return 0!==this.negative&&(r="-"+r),r}if(e===(0|e)&&e>=2&&e<=36){var l=h[e],u=g[e];r="";var f=this.clone();for(f.negative=0;!f.isZero();){var p=f.modrn(u).toString(e);r=(f=f.idivn(u)).isZero()?p+r:d[l-p.length]+p+r}for(this.isZero()&&(r="0"+r);r.length%t!==0;)r="0"+r;return 0!==this.negative&&(r="-"+r),r}n(!1,"Base should be between 2 and 36")},s.prototype.toNumber=function(){var e=this.words[0];return 2===this.length?e+=67108864*this.words[1]:3===this.length&&1===this.words[2]?e+=4503599627370496+67108864*this.words[1]:this.length>2&&n(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-e:e},s.prototype.toJSON=function(){return this.toString(16,2)},i&&(s.prototype.toBuffer=function(e,t){return this.toArrayLike(i,e,t)}),s.prototype.toArray=function(e,t){return this.toArrayLike(Array,e,t)},s.prototype.toArrayLike=function(e,t,r){this._strip();var s=this.byteLength(),i=r||Math.max(1,s);n(s<=i,"byte array longer than desired length"),n(i>0,"Requested array length <= 0");var o=function(e,t){return e.allocUnsafe?e.allocUnsafe(t):new e(t)}(e,i);return this["_toArrayLike"+("le"===t?"LE":"BE")](o,s),o},s.prototype._toArrayLikeLE=function(e,t){for(var n=0,r=0,s=0,i=0;s<this.length;s++){var o=this.words[s]<<i|r;e[n++]=255&o,n<e.length&&(e[n++]=o>>8&255),n<e.length&&(e[n++]=o>>16&255),6===i?(n<e.length&&(e[n++]=o>>24&255),r=0,i=0):(r=o>>>24,i+=2)}if(n<e.length)for(e[n++]=r;n<e.length;)e[n++]=0},s.prototype._toArrayLikeBE=function(e,t){for(var n=e.length-1,r=0,s=0,i=0;s<this.length;s++){var o=this.words[s]<<i|r;e[n--]=255&o,n>=0&&(e[n--]=o>>8&255),n>=0&&(e[n--]=o>>16&255),6===i?(n>=0&&(e[n--]=o>>24&255),r=0,i=0):(r=o>>>24,i+=2)}if(n>=0)for(e[n--]=r;n>=0;)e[n--]=0},Math.clz32?s.prototype._countBits=function(e){return 32-Math.clz32(e)}:s.prototype._countBits=function(e){var t=e,n=0;return t>=4096&&(n+=13,t>>>=13),t>=64&&(n+=7,t>>>=7),t>=8&&(n+=4,t>>>=4),t>=2&&(n+=2,t>>>=2),n+t},s.prototype._zeroBits=function(e){if(0===e)return 26;var t=e,n=0;return 8191&t||(n+=13,t>>>=13),127&t||(n+=7,t>>>=7),15&t||(n+=4,t>>>=4),3&t||(n+=2,t>>>=2),1&t||n++,n},s.prototype.bitLength=function(){var e=this.words[this.length-1],t=this._countBits(e);return 26*(this.length-1)+t},s.prototype.zeroBits=function(){if(this.isZero())return 0;for(var e=0,t=0;t<this.length;t++){var n=this._zeroBits(this.words[t]);if(e+=n,26!==n)break}return e},s.prototype.byteLength=function(){return Math.ceil(this.bitLength()/8)},s.prototype.toTwos=function(e){return 0!==this.negative?this.abs().inotn(e).iaddn(1):this.clone()},s.prototype.fromTwos=function(e){return this.testn(e-1)?this.notn(e).iaddn(1).ineg():this.clone()},s.prototype.isNeg=function(){return 0!==this.negative},s.prototype.neg=function(){return this.clone().ineg()},s.prototype.ineg=function(){return this.isZero()||(this.negative^=1),this},s.prototype.iuor=function(e){for(;this.length<e.length;)this.words[this.length++]=0;for(var t=0;t<e.length;t++)this.words[t]=this.words[t]|e.words[t];return this._strip()},s.prototype.ior=function(e){return n(0===(this.negative|e.negative)),this.iuor(e)},s.prototype.or=function(e){return this.length>e.length?this.clone().ior(e):e.clone().ior(this)},s.prototype.uor=function(e){return this.length>e.length?this.clone().iuor(e):e.clone().iuor(this)},s.prototype.iuand=function(e){var t;t=this.length>e.length?e:this;for(var n=0;n<t.length;n++)this.words[n]=this.words[n]&e.words[n];return this.length=t.length,this._strip()},s.prototype.iand=function(e){return n(0===(this.negative|e.negative)),this.iuand(e)},s.prototype.and=function(e){return this.length>e.length?this.clone().iand(e):e.clone().iand(this)},s.prototype.uand=function(e){return this.length>e.length?this.clone().iuand(e):e.clone().iuand(this)},s.prototype.iuxor=function(e){var t,n;this.length>e.length?(t=this,n=e):(t=e,n=this);for(var r=0;r<n.length;r++)this.words[r]=t.words[r]^n.words[r];if(this!==t)for(;r<t.length;r++)this.words[r]=t.words[r];return this.length=t.length,this._strip()},s.prototype.ixor=function(e){return n(0===(this.negative|e.negative)),this.iuxor(e)},s.prototype.xor=function(e){return this.length>e.length?this.clone().ixor(e):e.clone().ixor(this)},s.prototype.uxor=function(e){return this.length>e.length?this.clone().iuxor(e):e.clone().iuxor(this)},s.prototype.inotn=function(e){n("number"==typeof e&&e>=0);var t=0|Math.ceil(e/26),r=e%26;this._expand(t),r>0&&t--;for(var s=0;s<t;s++)this.words[s]=67108863&~this.words[s];for(r>0&&(this.words[s]=~this.words[s]&67108863>>26-r,s++);s<this.length;s++)this.words[s]=0;return this._strip()},s.prototype.notn=function(e){return this.clone().inotn(e)},s.prototype.setn=function(e,t){n("number"==typeof e&&e>=0);var r=e/26|0,s=e%26;return this._expand(r+1),this.words[r]=t?this.words[r]|1<<s:this.words[r]&~(1<<s),this._strip()},s.prototype.iadd=function(e){var t,n,r;if(0!==this.negative&&0===e.negative)return this.negative=0,t=this.isub(e),this.negative^=1,this._normSign();if(0===this.negative&&0!==e.negative)return e.negative=0,t=this.isub(e),e.negative=1,t._normSign();this.length>e.length?(n=this,r=e):(n=e,r=this);for(var s=0,i=0;i<r.length;i++)t=(0|n.words[i])+(0|r.words[i])+s,this.words[i]=67108863&t,s=t>>>26;for(;0!==s&&i<n.length;i++)t=(0|n.words[i])+s,this.words[i]=67108863&t,s=t>>>26;if(this.length=n.length,0!==s)this.words[this.length]=s,this.length++;else if(n!==this)for(;i<n.length;i++)this.words[i]=n.words[i];return this},s.prototype.add=function(e){var t;return 0!==e.negative&&0===this.negative?(e.negative=0,t=this.sub(e),e.negative^=1,t):0===e.negative&&0!==this.negative?(this.negative=0,t=e.sub(this),this.negative=1,t):this.length>e.length?this.clone().iadd(e):e.clone().iadd(this)},s.prototype.isub=function(e){if(0!==e.negative){e.negative=0;var t=this.iadd(e);return e.negative=1,t._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(e),this.negative=1,this._normSign();var n,r,s=this.cmp(e);if(0===s)return this.negative=0,this.length=1,this.words[0]=0,this;s>0?(n=this,r=e):(n=e,r=this);for(var i=0,o=0;o<r.length;o++)i=(t=(0|n.words[o])-(0|r.words[o])+i)>>26,this.words[o]=67108863&t;for(;0!==i&&o<n.length;o++)i=(t=(0|n.words[o])+i)>>26,this.words[o]=67108863&t;if(0===i&&o<n.length&&n!==this)for(;o<n.length;o++)this.words[o]=n.words[o];return this.length=Math.max(this.length,o),n!==this&&(this.negative=1),this._strip()},s.prototype.sub=function(e){return this.clone().isub(e)};var p=function(e,t,n){var r,s,i,o=e.words,a=t.words,c=n.words,l=0,u=0|o[0],d=8191&u,h=u>>>13,g=0|o[1],f=8191&g,p=g>>>13,m=0|o[2],y=8191&m,b=m>>>13,v=0|o[3],w=8191&v,E=v>>>13,A=0|o[4],S=8191&A,k=A>>>13,T=0|o[5],I=8191&T,N=T>>>13,C=0|o[6],_=8191&C,x=C>>>13,R=0|o[7],B=8191&R,D=R>>>13,O=0|o[8],M=8191&O,L=O>>>13,U=0|o[9],P=8191&U,F=U>>>13,$=0|a[0],K=8191&$,G=$>>>13,W=0|a[1],H=8191&W,q=W>>>13,z=0|a[2],V=8191&z,j=z>>>13,X=0|a[3],Y=8191&X,J=X>>>13,Q=0|a[4],Z=8191&Q,ee=Q>>>13,te=0|a[5],ne=8191&te,re=te>>>13,se=0|a[6],ie=8191&se,oe=se>>>13,ae=0|a[7],ce=8191&ae,le=ae>>>13,ue=0|a[8],de=8191&ue,he=ue>>>13,ge=0|a[9],fe=8191&ge,pe=ge>>>13;n.negative=e.negative^t.negative,n.length=19;var me=(l+(r=Math.imul(d,K))|0)+((8191&(s=(s=Math.imul(d,G))+Math.imul(h,K)|0))<<13)|0;l=((i=Math.imul(h,G))+(s>>>13)|0)+(me>>>26)|0,me&=67108863,r=Math.imul(f,K),s=(s=Math.imul(f,G))+Math.imul(p,K)|0,i=Math.imul(p,G);var ye=(l+(r=r+Math.imul(d,H)|0)|0)+((8191&(s=(s=s+Math.imul(d,q)|0)+Math.imul(h,H)|0))<<13)|0;l=((i=i+Math.imul(h,q)|0)+(s>>>13)|0)+(ye>>>26)|0,ye&=67108863,r=Math.imul(y,K),s=(s=Math.imul(y,G))+Math.imul(b,K)|0,i=Math.imul(b,G),r=r+Math.imul(f,H)|0,s=(s=s+Math.imul(f,q)|0)+Math.imul(p,H)|0,i=i+Math.imul(p,q)|0;var be=(l+(r=r+Math.imul(d,V)|0)|0)+((8191&(s=(s=s+Math.imul(d,j)|0)+Math.imul(h,V)|0))<<13)|0;l=((i=i+Math.imul(h,j)|0)+(s>>>13)|0)+(be>>>26)|0,be&=67108863,r=Math.imul(w,K),s=(s=Math.imul(w,G))+Math.imul(E,K)|0,i=Math.imul(E,G),r=r+Math.imul(y,H)|0,s=(s=s+Math.imul(y,q)|0)+Math.imul(b,H)|0,i=i+Math.imul(b,q)|0,r=r+Math.imul(f,V)|0,s=(s=s+Math.imul(f,j)|0)+Math.imul(p,V)|0,i=i+Math.imul(p,j)|0;var ve=(l+(r=r+Math.imul(d,Y)|0)|0)+((8191&(s=(s=s+Math.imul(d,J)|0)+Math.imul(h,Y)|0))<<13)|0;l=((i=i+Math.imul(h,J)|0)+(s>>>13)|0)+(ve>>>26)|0,ve&=67108863,r=Math.imul(S,K),s=(s=Math.imul(S,G))+Math.imul(k,K)|0,i=Math.imul(k,G),r=r+Math.imul(w,H)|0,s=(s=s+Math.imul(w,q)|0)+Math.imul(E,H)|0,i=i+Math.imul(E,q)|0,r=r+Math.imul(y,V)|0,s=(s=s+Math.imul(y,j)|0)+Math.imul(b,V)|0,i=i+Math.imul(b,j)|0,r=r+Math.imul(f,Y)|0,s=(s=s+Math.imul(f,J)|0)+Math.imul(p,Y)|0,i=i+Math.imul(p,J)|0;var we=(l+(r=r+Math.imul(d,Z)|0)|0)+((8191&(s=(s=s+Math.imul(d,ee)|0)+Math.imul(h,Z)|0))<<13)|0;l=((i=i+Math.imul(h,ee)|0)+(s>>>13)|0)+(we>>>26)|0,we&=67108863,r=Math.imul(I,K),s=(s=Math.imul(I,G))+Math.imul(N,K)|0,i=Math.imul(N,G),r=r+Math.imul(S,H)|0,s=(s=s+Math.imul(S,q)|0)+Math.imul(k,H)|0,i=i+Math.imul(k,q)|0,r=r+Math.imul(w,V)|0,s=(s=s+Math.imul(w,j)|0)+Math.imul(E,V)|0,i=i+Math.imul(E,j)|0,r=r+Math.imul(y,Y)|0,s=(s=s+Math.imul(y,J)|0)+Math.imul(b,Y)|0,i=i+Math.imul(b,J)|0,r=r+Math.imul(f,Z)|0,s=(s=s+Math.imul(f,ee)|0)+Math.imul(p,Z)|0,i=i+Math.imul(p,ee)|0;var Ee=(l+(r=r+Math.imul(d,ne)|0)|0)+((8191&(s=(s=s+Math.imul(d,re)|0)+Math.imul(h,ne)|0))<<13)|0;l=((i=i+Math.imul(h,re)|0)+(s>>>13)|0)+(Ee>>>26)|0,Ee&=67108863,r=Math.imul(_,K),s=(s=Math.imul(_,G))+Math.imul(x,K)|0,i=Math.imul(x,G),r=r+Math.imul(I,H)|0,s=(s=s+Math.imul(I,q)|0)+Math.imul(N,H)|0,i=i+Math.imul(N,q)|0,r=r+Math.imul(S,V)|0,s=(s=s+Math.imul(S,j)|0)+Math.imul(k,V)|0,i=i+Math.imul(k,j)|0,r=r+Math.imul(w,Y)|0,s=(s=s+Math.imul(w,J)|0)+Math.imul(E,Y)|0,i=i+Math.imul(E,J)|0,r=r+Math.imul(y,Z)|0,s=(s=s+Math.imul(y,ee)|0)+Math.imul(b,Z)|0,i=i+Math.imul(b,ee)|0,r=r+Math.imul(f,ne)|0,s=(s=s+Math.imul(f,re)|0)+Math.imul(p,ne)|0,i=i+Math.imul(p,re)|0;var Ae=(l+(r=r+Math.imul(d,ie)|0)|0)+((8191&(s=(s=s+Math.imul(d,oe)|0)+Math.imul(h,ie)|0))<<13)|0;l=((i=i+Math.imul(h,oe)|0)+(s>>>13)|0)+(Ae>>>26)|0,Ae&=67108863,r=Math.imul(B,K),s=(s=Math.imul(B,G))+Math.imul(D,K)|0,i=Math.imul(D,G),r=r+Math.imul(_,H)|0,s=(s=s+Math.imul(_,q)|0)+Math.imul(x,H)|0,i=i+Math.imul(x,q)|0,r=r+Math.imul(I,V)|0,s=(s=s+Math.imul(I,j)|0)+Math.imul(N,V)|0,i=i+Math.imul(N,j)|0,r=r+Math.imul(S,Y)|0,s=(s=s+Math.imul(S,J)|0)+Math.imul(k,Y)|0,i=i+Math.imul(k,J)|0,r=r+Math.imul(w,Z)|0,s=(s=s+Math.imul(w,ee)|0)+Math.imul(E,Z)|0,i=i+Math.imul(E,ee)|0,r=r+Math.imul(y,ne)|0,s=(s=s+Math.imul(y,re)|0)+Math.imul(b,ne)|0,i=i+Math.imul(b,re)|0,r=r+Math.imul(f,ie)|0,s=(s=s+Math.imul(f,oe)|0)+Math.imul(p,ie)|0,i=i+Math.imul(p,oe)|0;var Se=(l+(r=r+Math.imul(d,ce)|0)|0)+((8191&(s=(s=s+Math.imul(d,le)|0)+Math.imul(h,ce)|0))<<13)|0;l=((i=i+Math.imul(h,le)|0)+(s>>>13)|0)+(Se>>>26)|0,Se&=67108863,r=Math.imul(M,K),s=(s=Math.imul(M,G))+Math.imul(L,K)|0,i=Math.imul(L,G),r=r+Math.imul(B,H)|0,s=(s=s+Math.imul(B,q)|0)+Math.imul(D,H)|0,i=i+Math.imul(D,q)|0,r=r+Math.imul(_,V)|0,s=(s=s+Math.imul(_,j)|0)+Math.imul(x,V)|0,i=i+Math.imul(x,j)|0,r=r+Math.imul(I,Y)|0,s=(s=s+Math.imul(I,J)|0)+Math.imul(N,Y)|0,i=i+Math.imul(N,J)|0,r=r+Math.imul(S,Z)|0,s=(s=s+Math.imul(S,ee)|0)+Math.imul(k,Z)|0,i=i+Math.imul(k,ee)|0,r=r+Math.imul(w,ne)|0,s=(s=s+Math.imul(w,re)|0)+Math.imul(E,ne)|0,i=i+Math.imul(E,re)|0,r=r+Math.imul(y,ie)|0,s=(s=s+Math.imul(y,oe)|0)+Math.imul(b,ie)|0,i=i+Math.imul(b,oe)|0,r=r+Math.imul(f,ce)|0,s=(s=s+Math.imul(f,le)|0)+Math.imul(p,ce)|0,i=i+Math.imul(p,le)|0;var ke=(l+(r=r+Math.imul(d,de)|0)|0)+((8191&(s=(s=s+Math.imul(d,he)|0)+Math.imul(h,de)|0))<<13)|0;l=((i=i+Math.imul(h,he)|0)+(s>>>13)|0)+(ke>>>26)|0,ke&=67108863,r=Math.imul(P,K),s=(s=Math.imul(P,G))+Math.imul(F,K)|0,i=Math.imul(F,G),r=r+Math.imul(M,H)|0,s=(s=s+Math.imul(M,q)|0)+Math.imul(L,H)|0,i=i+Math.imul(L,q)|0,r=r+Math.imul(B,V)|0,s=(s=s+Math.imul(B,j)|0)+Math.imul(D,V)|0,i=i+Math.imul(D,j)|0,r=r+Math.imul(_,Y)|0,s=(s=s+Math.imul(_,J)|0)+Math.imul(x,Y)|0,i=i+Math.imul(x,J)|0,r=r+Math.imul(I,Z)|0,s=(s=s+Math.imul(I,ee)|0)+Math.imul(N,Z)|0,i=i+Math.imul(N,ee)|0,r=r+Math.imul(S,ne)|0,s=(s=s+Math.imul(S,re)|0)+Math.imul(k,ne)|0,i=i+Math.imul(k,re)|0,r=r+Math.imul(w,ie)|0,s=(s=s+Math.imul(w,oe)|0)+Math.imul(E,ie)|0,i=i+Math.imul(E,oe)|0,r=r+Math.imul(y,ce)|0,s=(s=s+Math.imul(y,le)|0)+Math.imul(b,ce)|0,i=i+Math.imul(b,le)|0,r=r+Math.imul(f,de)|0,s=(s=s+Math.imul(f,he)|0)+Math.imul(p,de)|0,i=i+Math.imul(p,he)|0;var Te=(l+(r=r+Math.imul(d,fe)|0)|0)+((8191&(s=(s=s+Math.imul(d,pe)|0)+Math.imul(h,fe)|0))<<13)|0;l=((i=i+Math.imul(h,pe)|0)+(s>>>13)|0)+(Te>>>26)|0,Te&=67108863,r=Math.imul(P,H),s=(s=Math.imul(P,q))+Math.imul(F,H)|0,i=Math.imul(F,q),r=r+Math.imul(M,V)|0,s=(s=s+Math.imul(M,j)|0)+Math.imul(L,V)|0,i=i+Math.imul(L,j)|0,r=r+Math.imul(B,Y)|0,s=(s=s+Math.imul(B,J)|0)+Math.imul(D,Y)|0,i=i+Math.imul(D,J)|0,r=r+Math.imul(_,Z)|0,s=(s=s+Math.imul(_,ee)|0)+Math.imul(x,Z)|0,i=i+Math.imul(x,ee)|0,r=r+Math.imul(I,ne)|0,s=(s=s+Math.imul(I,re)|0)+Math.imul(N,ne)|0,i=i+Math.imul(N,re)|0,r=r+Math.imul(S,ie)|0,s=(s=s+Math.imul(S,oe)|0)+Math.imul(k,ie)|0,i=i+Math.imul(k,oe)|0,r=r+Math.imul(w,ce)|0,s=(s=s+Math.imul(w,le)|0)+Math.imul(E,ce)|0,i=i+Math.imul(E,le)|0,r=r+Math.imul(y,de)|0,s=(s=s+Math.imul(y,he)|0)+Math.imul(b,de)|0,i=i+Math.imul(b,he)|0;var Ie=(l+(r=r+Math.imul(f,fe)|0)|0)+((8191&(s=(s=s+Math.imul(f,pe)|0)+Math.imul(p,fe)|0))<<13)|0;l=((i=i+Math.imul(p,pe)|0)+(s>>>13)|0)+(Ie>>>26)|0,Ie&=67108863,r=Math.imul(P,V),s=(s=Math.imul(P,j))+Math.imul(F,V)|0,i=Math.imul(F,j),r=r+Math.imul(M,Y)|0,s=(s=s+Math.imul(M,J)|0)+Math.imul(L,Y)|0,i=i+Math.imul(L,J)|0,r=r+Math.imul(B,Z)|0,s=(s=s+Math.imul(B,ee)|0)+Math.imul(D,Z)|0,i=i+Math.imul(D,ee)|0,r=r+Math.imul(_,ne)|0,s=(s=s+Math.imul(_,re)|0)+Math.imul(x,ne)|0,i=i+Math.imul(x,re)|0,r=r+Math.imul(I,ie)|0,s=(s=s+Math.imul(I,oe)|0)+Math.imul(N,ie)|0,i=i+Math.imul(N,oe)|0,r=r+Math.imul(S,ce)|0,s=(s=s+Math.imul(S,le)|0)+Math.imul(k,ce)|0,i=i+Math.imul(k,le)|0,r=r+Math.imul(w,de)|0,s=(s=s+Math.imul(w,he)|0)+Math.imul(E,de)|0,i=i+Math.imul(E,he)|0;var Ne=(l+(r=r+Math.imul(y,fe)|0)|0)+((8191&(s=(s=s+Math.imul(y,pe)|0)+Math.imul(b,fe)|0))<<13)|0;l=((i=i+Math.imul(b,pe)|0)+(s>>>13)|0)+(Ne>>>26)|0,Ne&=67108863,r=Math.imul(P,Y),s=(s=Math.imul(P,J))+Math.imul(F,Y)|0,i=Math.imul(F,J),r=r+Math.imul(M,Z)|0,s=(s=s+Math.imul(M,ee)|0)+Math.imul(L,Z)|0,i=i+Math.imul(L,ee)|0,r=r+Math.imul(B,ne)|0,s=(s=s+Math.imul(B,re)|0)+Math.imul(D,ne)|0,i=i+Math.imul(D,re)|0,r=r+Math.imul(_,ie)|0,s=(s=s+Math.imul(_,oe)|0)+Math.imul(x,ie)|0,i=i+Math.imul(x,oe)|0,r=r+Math.imul(I,ce)|0,s=(s=s+Math.imul(I,le)|0)+Math.imul(N,ce)|0,i=i+Math.imul(N,le)|0,r=r+Math.imul(S,de)|0,s=(s=s+Math.imul(S,he)|0)+Math.imul(k,de)|0,i=i+Math.imul(k,he)|0;var Ce=(l+(r=r+Math.imul(w,fe)|0)|0)+((8191&(s=(s=s+Math.imul(w,pe)|0)+Math.imul(E,fe)|0))<<13)|0;l=((i=i+Math.imul(E,pe)|0)+(s>>>13)|0)+(Ce>>>26)|0,Ce&=67108863,r=Math.imul(P,Z),s=(s=Math.imul(P,ee))+Math.imul(F,Z)|0,i=Math.imul(F,ee),r=r+Math.imul(M,ne)|0,s=(s=s+Math.imul(M,re)|0)+Math.imul(L,ne)|0,i=i+Math.imul(L,re)|0,r=r+Math.imul(B,ie)|0,s=(s=s+Math.imul(B,oe)|0)+Math.imul(D,ie)|0,i=i+Math.imul(D,oe)|0,r=r+Math.imul(_,ce)|0,s=(s=s+Math.imul(_,le)|0)+Math.imul(x,ce)|0,i=i+Math.imul(x,le)|0,r=r+Math.imul(I,de)|0,s=(s=s+Math.imul(I,he)|0)+Math.imul(N,de)|0,i=i+Math.imul(N,he)|0;var _e=(l+(r=r+Math.imul(S,fe)|0)|0)+((8191&(s=(s=s+Math.imul(S,pe)|0)+Math.imul(k,fe)|0))<<13)|0;l=((i=i+Math.imul(k,pe)|0)+(s>>>13)|0)+(_e>>>26)|0,_e&=67108863,r=Math.imul(P,ne),s=(s=Math.imul(P,re))+Math.imul(F,ne)|0,i=Math.imul(F,re),r=r+Math.imul(M,ie)|0,s=(s=s+Math.imul(M,oe)|0)+Math.imul(L,ie)|0,i=i+Math.imul(L,oe)|0,r=r+Math.imul(B,ce)|0,s=(s=s+Math.imul(B,le)|0)+Math.imul(D,ce)|0,i=i+Math.imul(D,le)|0,r=r+Math.imul(_,de)|0,s=(s=s+Math.imul(_,he)|0)+Math.imul(x,de)|0,i=i+Math.imul(x,he)|0;var xe=(l+(r=r+Math.imul(I,fe)|0)|0)+((8191&(s=(s=s+Math.imul(I,pe)|0)+Math.imul(N,fe)|0))<<13)|0;l=((i=i+Math.imul(N,pe)|0)+(s>>>13)|0)+(xe>>>26)|0,xe&=67108863,r=Math.imul(P,ie),s=(s=Math.imul(P,oe))+Math.imul(F,ie)|0,i=Math.imul(F,oe),r=r+Math.imul(M,ce)|0,s=(s=s+Math.imul(M,le)|0)+Math.imul(L,ce)|0,i=i+Math.imul(L,le)|0,r=r+Math.imul(B,de)|0,s=(s=s+Math.imul(B,he)|0)+Math.imul(D,de)|0,i=i+Math.imul(D,he)|0;var Re=(l+(r=r+Math.imul(_,fe)|0)|0)+((8191&(s=(s=s+Math.imul(_,pe)|0)+Math.imul(x,fe)|0))<<13)|0;l=((i=i+Math.imul(x,pe)|0)+(s>>>13)|0)+(Re>>>26)|0,Re&=67108863,r=Math.imul(P,ce),s=(s=Math.imul(P,le))+Math.imul(F,ce)|0,i=Math.imul(F,le),r=r+Math.imul(M,de)|0,s=(s=s+Math.imul(M,he)|0)+Math.imul(L,de)|0,i=i+Math.imul(L,he)|0;var Be=(l+(r=r+Math.imul(B,fe)|0)|0)+((8191&(s=(s=s+Math.imul(B,pe)|0)+Math.imul(D,fe)|0))<<13)|0;l=((i=i+Math.imul(D,pe)|0)+(s>>>13)|0)+(Be>>>26)|0,Be&=67108863,r=Math.imul(P,de),s=(s=Math.imul(P,he))+Math.imul(F,de)|0,i=Math.imul(F,he);var De=(l+(r=r+Math.imul(M,fe)|0)|0)+((8191&(s=(s=s+Math.imul(M,pe)|0)+Math.imul(L,fe)|0))<<13)|0;l=((i=i+Math.imul(L,pe)|0)+(s>>>13)|0)+(De>>>26)|0,De&=67108863;var Oe=(l+(r=Math.imul(P,fe))|0)+((8191&(s=(s=Math.imul(P,pe))+Math.imul(F,fe)|0))<<13)|0;return l=((i=Math.imul(F,pe))+(s>>>13)|0)+(Oe>>>26)|0,Oe&=67108863,c[0]=me,c[1]=ye,c[2]=be,c[3]=ve,c[4]=we,c[5]=Ee,c[6]=Ae,c[7]=Se,c[8]=ke,c[9]=Te,c[10]=Ie,c[11]=Ne,c[12]=Ce,c[13]=_e,c[14]=xe,c[15]=Re,c[16]=Be,c[17]=De,c[18]=Oe,0!==l&&(c[19]=l,n.length++),n};function m(e,t,n){n.negative=t.negative^e.negative,n.length=e.length+t.length;for(var r=0,s=0,i=0;i<n.length-1;i++){var o=s;s=0;for(var a=67108863&r,c=Math.min(i,t.length-1),l=Math.max(0,i-e.length+1);l<=c;l++){var u=i-l,d=(0|e.words[u])*(0|t.words[l]),h=67108863&d;a=67108863&(h=h+a|0),s+=(o=(o=o+(d/67108864|0)|0)+(h>>>26)|0)>>>26,o&=67108863}n.words[i]=a,r=o,o=s}return 0!==r?n.words[i]=r:n.length--,n._strip()}function y(e,t,n){return m(e,t,n)}Math.imul||(p=f),s.prototype.mulTo=function(e,t){var n=this.length+e.length;return 10===this.length&&10===e.length?p(this,e,t):n<63?f(this,e,t):n<1024?m(this,e,t):y(this,e,t)},s.prototype.mul=function(e){var t=new s(null);return t.words=new Array(this.length+e.length),this.mulTo(e,t)},s.prototype.mulf=function(e){var t=new s(null);return t.words=new Array(this.length+e.length),y(this,e,t)},s.prototype.imul=function(e){return this.clone().mulTo(e,this)},s.prototype.imuln=function(e){var t=e<0;t&&(e=-e),n("number"==typeof e),n(e<67108864);for(var r=0,s=0;s<this.length;s++){var i=(0|this.words[s])*e,o=(67108863&i)+(67108863&r);r>>=26,r+=i/67108864|0,r+=o>>>26,this.words[s]=67108863&o}return 0!==r&&(this.words[s]=r,this.length++),0===e&&(this.length=1,this._normSign()),t?this.ineg():this},s.prototype.muln=function(e){return this.clone().imuln(e)},s.prototype.sqr=function(){return this.mul(this)},s.prototype.isqr=function(){return this.imul(this.clone())},s.prototype.pow=function(e){var t=function(e){for(var t=new Array(e.bitLength()),n=0;n<t.length;n++){var r=n/26|0,s=n%26;t[n]=e.words[r]>>>s&1}return t}(e);if(0===t.length)return new s(1);for(var n=this,r=0;r<t.length&&0===t[r];r++,n=n.sqr());if(++r<t.length)for(var i=n.sqr();r<t.length;r++,i=i.sqr())0!==t[r]&&(n=n.mul(i));return n},s.prototype.iushln=function(e){n("number"==typeof e&&e>=0);var t,r=e%26,s=(e-r)/26,i=67108863>>>26-r<<26-r;if(0!==r){var o=0;for(t=0;t<this.length;t++){var a=this.words[t]&i,c=(0|this.words[t])-a<<r;this.words[t]=c|o,o=a>>>26-r}o&&(this.words[t]=o,this.length++)}if(0!==s){for(t=this.length-1;t>=0;t--)this.words[t+s]=this.words[t];for(t=0;t<s;t++)this.words[t]=0;this.length+=s}return this._strip()},s.prototype.ishln=function(e){return n(0===this.negative),this.iushln(e)},s.prototype.iushrn=function(e,t,r){var s;n("number"==typeof e&&e>=0),s=t?(t-t%26)/26:0;var i=e%26,o=Math.min((e-i)/26,this.length),a=67108863^67108863>>>i<<i,c=r;if(s-=o,s=Math.max(0,s),c){for(var l=0;l<o;l++)c.words[l]=this.words[l];c.length=o}if(0===o);else if(this.length>o)for(this.length-=o,l=0;l<this.length;l++)this.words[l]=this.words[l+o];else this.words[0]=0,this.length=1;var u=0;for(l=this.length-1;l>=0&&(0!==u||l>=s);l--){var d=0|this.words[l];this.words[l]=u<<26-i|d>>>i,u=d&a}return c&&0!==u&&(c.words[c.length++]=u),0===this.length&&(this.words[0]=0,this.length=1),this._strip()},s.prototype.ishrn=function(e,t,r){return n(0===this.negative),this.iushrn(e,t,r)},s.prototype.shln=function(e){return this.clone().ishln(e)},s.prototype.ushln=function(e){return this.clone().iushln(e)},s.prototype.shrn=function(e){return this.clone().ishrn(e)},s.prototype.ushrn=function(e){return this.clone().iushrn(e)},s.prototype.testn=function(e){n("number"==typeof e&&e>=0);var t=e%26,r=(e-t)/26,s=1<<t;return!(this.length<=r||!(this.words[r]&s))},s.prototype.imaskn=function(e){n("number"==typeof e&&e>=0);var t=e%26,r=(e-t)/26;if(n(0===this.negative,"imaskn works only with positive numbers"),this.length<=r)return this;if(0!==t&&r++,this.length=Math.min(r,this.length),0!==t){var s=67108863^67108863>>>t<<t;this.words[this.length-1]&=s}return 0===this.length&&(this.words[0]=0,this.length=1),this._strip()},s.prototype.maskn=function(e){return this.clone().imaskn(e)},s.prototype.iaddn=function(e){return n("number"==typeof e),n(e<67108864),e<0?this.isubn(-e):0!==this.negative?1===this.length&&(0|this.words[0])<=e?(this.words[0]=e-(0|this.words[0]),this.negative=0,this):(this.negative=0,this.isubn(e),this.negative=1,this):this._iaddn(e)},s.prototype._iaddn=function(e){this.words[0]+=e;for(var t=0;t<this.length&&this.words[t]>=67108864;t++)this.words[t]-=67108864,t===this.length-1?this.words[t+1]=1:this.words[t+1]++;return this.length=Math.max(this.length,t+1),this},s.prototype.isubn=function(e){if(n("number"==typeof e),n(e<67108864),e<0)return this.iaddn(-e);if(0!==this.negative)return this.negative=0,this.iaddn(e),this.negative=1,this;if(this.words[0]-=e,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var t=0;t<this.length&&this.words[t]<0;t++)this.words[t]+=67108864,this.words[t+1]-=1;return this._strip()},s.prototype.addn=function(e){return this.clone().iaddn(e)},s.prototype.subn=function(e){return this.clone().isubn(e)},s.prototype.iabs=function(){return this.negative=0,this},s.prototype.abs=function(){return this.clone().iabs()},s.prototype._ishlnsubmul=function(e,t,r){var s,i,o=e.length+r;this._expand(o);var a=0;for(s=0;s<e.length;s++){i=(0|this.words[s+r])+a;var c=(0|e.words[s])*t;a=((i-=67108863&c)>>26)-(c/67108864|0),this.words[s+r]=67108863&i}for(;s<this.length-r;s++)a=(i=(0|this.words[s+r])+a)>>26,this.words[s+r]=67108863&i;if(0===a)return this._strip();for(n(-1===a),a=0,s=0;s<this.length;s++)a=(i=-(0|this.words[s])+a)>>26,this.words[s]=67108863&i;return this.negative=1,this._strip()},s.prototype._wordDiv=function(e,t){var n=(this.length,e.length),r=this.clone(),i=e,o=0|i.words[i.length-1];0!=(n=26-this._countBits(o))&&(i=i.ushln(n),r.iushln(n),o=0|i.words[i.length-1]);var a,c=r.length-i.length;if("mod"!==t){(a=new s(null)).length=c+1,a.words=new Array(a.length);for(var l=0;l<a.length;l++)a.words[l]=0}var u=r.clone()._ishlnsubmul(i,1,c);0===u.negative&&(r=u,a&&(a.words[c]=1));for(var d=c-1;d>=0;d--){var h=67108864*(0|r.words[i.length+d])+(0|r.words[i.length+d-1]);for(h=Math.min(h/o|0,67108863),r._ishlnsubmul(i,h,d);0!==r.negative;)h--,r.negative=0,r._ishlnsubmul(i,1,d),r.isZero()||(r.negative^=1);a&&(a.words[d]=h)}return a&&a._strip(),r._strip(),"div"!==t&&0!==n&&r.iushrn(n),{div:a||null,mod:r}},s.prototype.divmod=function(e,t,r){return n(!e.isZero()),this.isZero()?{div:new s(0),mod:new s(0)}:0!==this.negative&&0===e.negative?(a=this.neg().divmod(e,t),"mod"!==t&&(i=a.div.neg()),"div"!==t&&(o=a.mod.neg(),r&&0!==o.negative&&o.iadd(e)),{div:i,mod:o}):0===this.negative&&0!==e.negative?(a=this.divmod(e.neg(),t),"mod"!==t&&(i=a.div.neg()),{div:i,mod:a.mod}):0!==(this.negative&e.negative)?(a=this.neg().divmod(e.neg(),t),"div"!==t&&(o=a.mod.neg(),r&&0!==o.negative&&o.isub(e)),{div:a.div,mod:o}):e.length>this.length||this.cmp(e)<0?{div:new s(0),mod:this}:1===e.length?"div"===t?{div:this.divn(e.words[0]),mod:null}:"mod"===t?{div:null,mod:new s(this.modrn(e.words[0]))}:{div:this.divn(e.words[0]),mod:new s(this.modrn(e.words[0]))}:this._wordDiv(e,t);var i,o,a},s.prototype.div=function(e){return this.divmod(e,"div",!1).div},s.prototype.mod=function(e){return this.divmod(e,"mod",!1).mod},s.prototype.umod=function(e){return this.divmod(e,"mod",!0).mod},s.prototype.divRound=function(e){var t=this.divmod(e);if(t.mod.isZero())return t.div;var n=t.mod.abs(),r=e.abs().iushrn(1),i=1&e.words[0],o=n.cmp(r);if(o<0||1===i&&0===o)return t.div;var a=new s(1);return a.negative=this.negative^e.negative,t.div.iadd(a)},s.prototype.modrn=function(e){var t=e<0;t&&(e=-e),n(e<=67108863);for(var r=(1<<26)%e,s=0,i=this.length-1;i>=0;i--)s=(r*s+(0|this.words[i]))%e;return t?-s:s},s.prototype.modn=function(e){return this.modrn(e)},s.prototype.idivn=function(e){var t=e<0;t&&(e=-e),n(e<=67108863);for(var r=0,s=this.length-1;s>=0;s--){var i=(0|this.words[s])+67108864*r;this.words[s]=i/e|0,r=i%e}return this._strip(),t?this.ineg():this},s.prototype.divn=function(e){return this.clone().idivn(e)},s.prototype.egcd=function(e){n(0===e.negative),n(!e.isZero());var t=this,r=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var i=new s(1),o=new s(0),a=new s(0),c=new s(1),l=0;t.isEven()&&r.isEven();)t.iushrn(1),r.iushrn(1),++l;for(var u=r.clone(),d=t.clone();!t.isZero();){for(var h=0,g=1;0===(t.words[0]&g)&&h<26;++h,g<<=1);if(h>0)for(t.iushrn(h);h-- >0;)(i.isOdd()||o.isOdd())&&(i.iadd(u),o.isub(d)),i.iushrn(1),o.iushrn(1);for(var f=0,p=1;0===(r.words[0]&p)&&f<26;++f,p<<=1);if(f>0)for(r.iushrn(f);f-- >0;)(a.isOdd()||c.isOdd())&&(a.iadd(u),c.isub(d)),a.iushrn(1),c.iushrn(1);t.cmp(r)>=0?(t.isub(r),i.isub(a),o.isub(c)):(r.isub(t),a.isub(i),c.isub(o))}return{a:a,b:c,gcd:r.iushln(l)}},s.prototype._invmp=function(e){n(0===e.negative),n(!e.isZero());var t=this,r=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var i,o=new s(1),a=new s(0),c=r.clone();t.cmpn(1)>0&&r.cmpn(1)>0;){for(var l=0,u=1;0===(t.words[0]&u)&&l<26;++l,u<<=1);if(l>0)for(t.iushrn(l);l-- >0;)o.isOdd()&&o.iadd(c),o.iushrn(1);for(var d=0,h=1;0===(r.words[0]&h)&&d<26;++d,h<<=1);if(d>0)for(r.iushrn(d);d-- >0;)a.isOdd()&&a.iadd(c),a.iushrn(1);t.cmp(r)>=0?(t.isub(r),o.isub(a)):(r.isub(t),a.isub(o))}return(i=0===t.cmpn(1)?o:a).cmpn(0)<0&&i.iadd(e),i},s.prototype.gcd=function(e){if(this.isZero())return e.abs();if(e.isZero())return this.abs();var t=this.clone(),n=e.clone();t.negative=0,n.negative=0;for(var r=0;t.isEven()&&n.isEven();r++)t.iushrn(1),n.iushrn(1);for(;;){for(;t.isEven();)t.iushrn(1);for(;n.isEven();)n.iushrn(1);var s=t.cmp(n);if(s<0){var i=t;t=n,n=i}else if(0===s||0===n.cmpn(1))break;t.isub(n)}return n.iushln(r)},s.prototype.invm=function(e){return this.egcd(e).a.umod(e)},s.prototype.isEven=function(){return!(1&this.words[0])},s.prototype.isOdd=function(){return!(1&~this.words[0])},s.prototype.andln=function(e){return this.words[0]&e},s.prototype.bincn=function(e){n("number"==typeof e);var t=e%26,r=(e-t)/26,s=1<<t;if(this.length<=r)return this._expand(r+1),this.words[r]|=s,this;for(var i=s,o=r;0!==i&&o<this.length;o++){var a=0|this.words[o];i=(a+=i)>>>26,a&=67108863,this.words[o]=a}return 0!==i&&(this.words[o]=i,this.length++),this},s.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},s.prototype.cmpn=function(e){var t,r=e<0;if(0!==this.negative&&!r)return-1;if(0===this.negative&&r)return 1;if(this._strip(),this.length>1)t=1;else{r&&(e=-e),n(e<=67108863,"Number is too big");var s=0|this.words[0];t=s===e?0:s<e?-1:1}return 0!==this.negative?0|-t:t},s.prototype.cmp=function(e){if(0!==this.negative&&0===e.negative)return-1;if(0===this.negative&&0!==e.negative)return 1;var t=this.ucmp(e);return 0!==this.negative?0|-t:t},s.prototype.ucmp=function(e){if(this.length>e.length)return 1;if(this.length<e.length)return-1;for(var t=0,n=this.length-1;n>=0;n--){var r=0|this.words[n],s=0|e.words[n];if(r!==s){r<s?t=-1:r>s&&(t=1);break}}return t},s.prototype.gtn=function(e){return 1===this.cmpn(e)},s.prototype.gt=function(e){return 1===this.cmp(e)},s.prototype.gten=function(e){return this.cmpn(e)>=0},s.prototype.gte=function(e){return this.cmp(e)>=0},s.prototype.ltn=function(e){return-1===this.cmpn(e)},s.prototype.lt=function(e){return-1===this.cmp(e)},s.prototype.lten=function(e){return this.cmpn(e)<=0},s.prototype.lte=function(e){return this.cmp(e)<=0},s.prototype.eqn=function(e){return 0===this.cmpn(e)},s.prototype.eq=function(e){return 0===this.cmp(e)},s.red=function(e){return new k(e)},s.prototype.toRed=function(e){return n(!this.red,"Already a number in reduction context"),n(0===this.negative,"red works only with positives"),e.convertTo(this)._forceRed(e)},s.prototype.fromRed=function(){return n(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},s.prototype._forceRed=function(e){return this.red=e,this},s.prototype.forceRed=function(e){return n(!this.red,"Already a number in reduction context"),this._forceRed(e)},s.prototype.redAdd=function(e){return n(this.red,"redAdd works only with red numbers"),this.red.add(this,e)},s.prototype.redIAdd=function(e){return n(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,e)},s.prototype.redSub=function(e){return n(this.red,"redSub works only with red numbers"),this.red.sub(this,e)},s.prototype.redISub=function(e){return n(this.red,"redISub works only with red numbers"),this.red.isub(this,e)},s.prototype.redShl=function(e){return n(this.red,"redShl works only with red numbers"),this.red.shl(this,e)},s.prototype.redMul=function(e){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.mul(this,e)},s.prototype.redIMul=function(e){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.imul(this,e)},s.prototype.redSqr=function(){return n(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},s.prototype.redISqr=function(){return n(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},s.prototype.redSqrt=function(){return n(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},s.prototype.redInvm=function(){return n(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},s.prototype.redNeg=function(){return n(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},s.prototype.redPow=function(e){return n(this.red&&!e.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,e)};var b={k256:null,p224:null,p192:null,p25519:null};function v(e,t){this.name=e,this.p=new s(t,16),this.n=this.p.bitLength(),this.k=new s(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function w(){v.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function E(){v.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function A(){v.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function S(){v.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function k(e){if("string"==typeof e){var t=s._prime(e);this.m=t.p,this.prime=t}else n(e.gtn(1),"modulus must be greater than 1"),this.m=e,this.prime=null}function T(e){k.call(this,e),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new s(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}v.prototype._tmp=function(){var e=new s(null);return e.words=new Array(Math.ceil(this.n/13)),e},v.prototype.ireduce=function(e){var t,n=e;do{this.split(n,this.tmp),t=(n=(n=this.imulK(n)).iadd(this.tmp)).bitLength()}while(t>this.n);var r=t<this.n?-1:n.ucmp(this.p);return 0===r?(n.words[0]=0,n.length=1):r>0?n.isub(this.p):void 0!==n.strip?n.strip():n._strip(),n},v.prototype.split=function(e,t){e.iushrn(this.n,0,t)},v.prototype.imulK=function(e){return e.imul(this.k)},r(w,v),w.prototype.split=function(e,t){for(var n=4194303,r=Math.min(e.length,9),s=0;s<r;s++)t.words[s]=e.words[s];if(t.length=r,e.length<=9)return e.words[0]=0,void(e.length=1);var i=e.words[9];for(t.words[t.length++]=i&n,s=10;s<e.length;s++){var o=0|e.words[s];e.words[s-10]=(o&n)<<4|i>>>22,i=o}i>>>=22,e.words[s-10]=i,0===i&&e.length>10?e.length-=10:e.length-=9},w.prototype.imulK=function(e){e.words[e.length]=0,e.words[e.length+1]=0,e.length+=2;for(var t=0,n=0;n<e.length;n++){var r=0|e.words[n];t+=977*r,e.words[n]=67108863&t,t=64*r+(t/67108864|0)}return 0===e.words[e.length-1]&&(e.length--,0===e.words[e.length-1]&&e.length--),e},r(E,v),r(A,v),r(S,v),S.prototype.imulK=function(e){for(var t=0,n=0;n<e.length;n++){var r=19*(0|e.words[n])+t,s=67108863&r;r>>>=26,e.words[n]=s,t=r}return 0!==t&&(e.words[e.length++]=t),e},s._prime=function(e){if(b[e])return b[e];var t;if("k256"===e)t=new w;else if("p224"===e)t=new E;else if("p192"===e)t=new A;else{if("p25519"!==e)throw new Error("Unknown prime "+e);t=new S}return b[e]=t,t},k.prototype._verify1=function(e){n(0===e.negative,"red works only with positives"),n(e.red,"red works only with red numbers")},k.prototype._verify2=function(e,t){n(0===(e.negative|t.negative),"red works only with positives"),n(e.red&&e.red===t.red,"red works only with red numbers")},k.prototype.imod=function(e){return this.prime?this.prime.ireduce(e)._forceRed(this):(l(e,e.umod(this.m)._forceRed(this)),e)},k.prototype.neg=function(e){return e.isZero()?e.clone():this.m.sub(e)._forceRed(this)},k.prototype.add=function(e,t){this._verify2(e,t);var n=e.add(t);return n.cmp(this.m)>=0&&n.isub(this.m),n._forceRed(this)},k.prototype.iadd=function(e,t){this._verify2(e,t);var n=e.iadd(t);return n.cmp(this.m)>=0&&n.isub(this.m),n},k.prototype.sub=function(e,t){this._verify2(e,t);var n=e.sub(t);return n.cmpn(0)<0&&n.iadd(this.m),n._forceRed(this)},k.prototype.isub=function(e,t){this._verify2(e,t);var n=e.isub(t);return n.cmpn(0)<0&&n.iadd(this.m),n},k.prototype.shl=function(e,t){return this._verify1(e),this.imod(e.ushln(t))},k.prototype.imul=function(e,t){return this._verify2(e,t),this.imod(e.imul(t))},k.prototype.mul=function(e,t){return this._verify2(e,t),this.imod(e.mul(t))},k.prototype.isqr=function(e){return this.imul(e,e.clone())},k.prototype.sqr=function(e){return this.mul(e,e)},k.prototype.sqrt=function(e){if(e.isZero())return e.clone();var t=this.m.andln(3);if(n(t%2==1),3===t){var r=this.m.add(new s(1)).iushrn(2);return this.pow(e,r)}for(var i=this.m.subn(1),o=0;!i.isZero()&&0===i.andln(1);)o++,i.iushrn(1);n(!i.isZero());var a=new s(1).toRed(this),c=a.redNeg(),l=this.m.subn(1).iushrn(1),u=this.m.bitLength();for(u=new s(2*u*u).toRed(this);0!==this.pow(u,l).cmp(c);)u.redIAdd(c);for(var d=this.pow(u,i),h=this.pow(e,i.addn(1).iushrn(1)),g=this.pow(e,i),f=o;0!==g.cmp(a);){for(var p=g,m=0;0!==p.cmp(a);m++)p=p.redSqr();n(m<f);var y=this.pow(d,new s(1).iushln(f-m-1));h=h.redMul(y),d=y.redSqr(),g=g.redMul(d),f=m}return h},k.prototype.invm=function(e){var t=e._invmp(this.m);return 0!==t.negative?(t.negative=0,this.imod(t).redNeg()):this.imod(t)},k.prototype.pow=function(e,t){if(t.isZero())return new s(1).toRed(this);if(0===t.cmpn(1))return e.clone();var n=new Array(16);n[0]=new s(1).toRed(this),n[1]=e;for(var r=2;r<n.length;r++)n[r]=this.mul(n[r-1],e);var i=n[0],o=0,a=0,c=t.bitLength()%26;for(0===c&&(c=26),r=t.length-1;r>=0;r--){for(var l=t.words[r],u=c-1;u>=0;u--){var d=l>>u&1;i!==n[0]&&(i=this.sqr(i)),0!==d||0!==o?(o<<=1,o|=d,(4===++a||0===r&&0===u)&&(i=this.mul(i,n[o]),a=0,o=0)):a=0}c=26}return i},k.prototype.convertTo=function(e){var t=e.umod(this.m);return t===e?t.clone():t},k.prototype.convertFrom=function(e){var t=e.clone();return t.red=null,t},s.mont=function(e){return new T(e)},r(T,k),T.prototype.convertTo=function(e){return this.imod(e.ushln(this.shift))},T.prototype.convertFrom=function(e){var t=this.imod(e.mul(this.rinv));return t.red=null,t},T.prototype.imul=function(e,t){if(e.isZero()||t.isZero())return e.words[0]=0,e.length=1,e;var n=e.imul(t),r=n.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),s=n.isub(r).iushrn(this.shift),i=s;return s.cmp(this.m)>=0?i=s.isub(this.m):s.cmpn(0)<0&&(i=s.iadd(this.m)),i._forceRed(this)},T.prototype.mul=function(e,t){if(e.isZero()||t.isZero())return new s(0)._forceRed(this);var n=e.mul(t),r=n.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=n.isub(r).iushrn(this.shift),o=i;return i.cmp(this.m)>=0?o=i.isub(this.m):i.cmpn(0)<0&&(o=i.iadd(this.m)),o._forceRed(this)},T.prototype.invm=function(e){return this.imod(e._invmp(this.m).mul(this.r2))._forceRed(this)}}(al,ll)),al.exports}var dl,hl,gl,fl,pl,ml=So(ul()),yl={exports:{}};function bl(){return dl||(dl=1,function(e,t){var n=Do(),r=n.Buffer;function s(e,t){for(var n in e)t[n]=e[n]}function i(e,t,n){return r(e,t,n)}r.from&&r.alloc&&r.allocUnsafe&&r.allocUnsafeSlow?e.exports=n:(s(n,t),t.Buffer=i),i.prototype=Object.create(r.prototype),s(r,i),i.from=function(e,t,n){if("number"==typeof e)throw new TypeError("Argument must not be a number");return r(e,t,n)},i.alloc=function(e,t,n){if("number"!=typeof e)throw new TypeError("Argument must be a number");var s=r(e);return void 0!==t?"string"==typeof n?s.fill(t,n):s.fill(t):s.fill(0),s},i.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return r(e)},i.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return n.SlowBuffer(e)}}(yl,yl.exports)),yl.exports}function vl(){if(gl)return hl;gl=1;var e=bl().Buffer;return hl=function(t){if(t.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),r=0;r<n.length;r++)n[r]=255;for(var s=0;s<t.length;s++){var i=t.charAt(s),o=i.charCodeAt(0);if(255!==n[o])throw new TypeError(i+" is ambiguous");n[o]=s}var a=t.length,c=t.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(t){if("string"!=typeof t)throw new TypeError("Expected String");if(0===t.length)return e.alloc(0);for(var r=0,s=0,i=0;t[r]===c;)s++,r++;for(var o=(t.length-r)*l+1>>>0,u=new Uint8Array(o);r<t.length;){var d=t.charCodeAt(r);if(d>255)return;var h=n[d];if(255===h)return;for(var g=0,f=o-1;(0!==h||g<i)&&-1!==f;f--,g++)h+=a*u[f]>>>0,u[f]=h%256>>>0,h=h/256>>>0;if(0!==h)throw new Error("Non-zero carry");i=g,r++}for(var p=o-i;p!==o&&0===u[p];)p++;var m=e.allocUnsafe(s+(o-p));m.fill(0,0,s);for(var y=s;p!==o;)m[y++]=u[p++];return m}return{encode:function(n){if((Array.isArray(n)||n instanceof Uint8Array)&&(n=e.from(n)),!e.isBuffer(n))throw new TypeError("Expected Buffer");if(0===n.length)return"";for(var r=0,s=0,i=0,o=n.length;i!==o&&0===n[i];)i++,r++;for(var l=(o-i)*u+1>>>0,d=new Uint8Array(l);i!==o;){for(var h=n[i],g=0,f=l-1;(0!==h||g<s)&&-1!==f;f--,g++)h+=256*d[f]>>>0,d[f]=h%a>>>0,h=h/a>>>0;if(0!==h)throw new Error("Non-zero carry");s=g,i++}for(var p=l-s;p!==l&&0===d[p];)p++;for(var m=c.repeat(r);p<l;++p)m+=t.charAt(d[p]);return m},decodeUnsafe:d,decode:function(e){var t=d(e);if(t)return t;throw new Error("Non-base"+a+" character")}}},hl}function wl(){if(pl)return fl;pl=1;return fl=vl()("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")}var El=So(wl());const Al=La;var Sl={};function kl(e,t,n){return t<=e&&e<=n}function Tl(e){if(void 0===e)return{};if(e===Object(e))return e;throw TypeError("Could not convert argument to dictionary")}function Il(e){this.tokens=[].slice.call(e)}Il.prototype={endOfStream:function(){return!this.tokens.length},read:function(){return this.tokens.length?this.tokens.shift():-1},prepend:function(e){if(Array.isArray(e))for(var t=e;t.length;)this.tokens.unshift(t.pop());else this.tokens.unshift(e)},push:function(e){if(Array.isArray(e))for(var t=e;t.length;)this.tokens.push(t.shift());else this.tokens.push(e)}};var Nl=-1;function Cl(e,t){if(e)throw TypeError("Decoder error");return t||65533}var _l="utf-8";function xl(e,t){if(!(this instanceof xl))return new xl(e,t);if((e=void 0!==e?String(e).toLowerCase():_l)!==_l)throw new Error("Encoding not supported. Only utf-8 is supported");t=Tl(t),this._streaming=!1,this._BOMseen=!1,this._decoder=null,this._fatal=Boolean(t.fatal),this._ignoreBOM=Boolean(t.ignoreBOM),Object.defineProperty(this,"encoding",{value:"utf-8"}),Object.defineProperty(this,"fatal",{value:this._fatal}),Object.defineProperty(this,"ignoreBOM",{value:this._ignoreBOM})}function Rl(e,t){if(!(this instanceof Rl))return new Rl(e,t);if((e=void 0!==e?String(e).toLowerCase():_l)!==_l)throw new Error("Encoding not supported. Only utf-8 is supported");t=Tl(t),this._streaming=!1,this._encoder=null,this._options={fatal:Boolean(t.fatal)},Object.defineProperty(this,"encoding",{value:"utf-8"})}function Bl(e){var t=e.fatal,n=0,r=0,s=0,i=128,o=191;this.handler=function(e,a){if(-1===a&&0!==s)return s=0,Cl(t);if(-1===a)return Nl;if(0===s){if(kl(a,0,127))return a;if(kl(a,194,223))s=1,n=a-192;else if(kl(a,224,239))224===a&&(i=160),237===a&&(o=159),s=2,n=a-224;else{if(!kl(a,240,244))return Cl(t);240===a&&(i=144),244===a&&(o=143),s=3,n=a-240}return n<<=6*s,null}if(!kl(a,i,o))return n=s=r=0,i=128,o=191,e.prepend(a),Cl(t);if(i=128,o=191,n+=a-128<<6*(s-(r+=1)),r!==s)return null;var c=n;return n=s=r=0,c}}function Dl(e){e.fatal,this.handler=function(e,t){if(-1===t)return Nl;if(kl(t,0,127))return t;var n,r;kl(t,128,2047)?(n=1,r=192):kl(t,2048,65535)?(n=2,r=224):kl(t,65536,1114111)&&(n=3,r=240);for(var s=[(t>>6*n)+r];n>0;){var i=t>>6*(n-1);s.push(128|63&i),n-=1}return s}}xl.prototype={decode:function(e,t){var n;n="object"==typeof e&&e instanceof ArrayBuffer?new Uint8Array(e):"object"==typeof e&&"buffer"in e&&e.buffer instanceof ArrayBuffer?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(0),t=Tl(t),this._streaming||(this._decoder=new Bl({fatal:this._fatal}),this._BOMseen=!1),this._streaming=Boolean(t.stream);for(var r,s=new Il(n),i=[];!s.endOfStream()&&(r=this._decoder.handler(s,s.read()))!==Nl;)null!==r&&(Array.isArray(r)?i.push.apply(i,r):i.push(r));if(!this._streaming){do{if((r=this._decoder.handler(s,s.read()))===Nl)break;null!==r&&(Array.isArray(r)?i.push.apply(i,r):i.push(r))}while(!s.endOfStream());this._decoder=null}return i.length&&(-1===["utf-8"].indexOf(this.encoding)||this._ignoreBOM||this._BOMseen||(65279===i[0]?(this._BOMseen=!0,i.shift()):this._BOMseen=!0)),function(e){for(var t="",n=0;n<e.length;++n){var r=e[n];r<=65535?t+=String.fromCharCode(r):(r-=65536,t+=String.fromCharCode(55296+(r>>10),56320+(1023&r)))}return t}(i)}},Rl.prototype={encode:function(e,t){e=e?String(e):"",t=Tl(t),this._streaming||(this._encoder=new Dl(this._options)),this._streaming=Boolean(t.stream);for(var n,r=[],s=new Il(function(e){for(var t=String(e),n=t.length,r=0,s=[];r<n;){var i=t.charCodeAt(r);if(i<55296||i>57343)s.push(i);else if(56320<=i&&i<=57343)s.push(65533);else if(55296<=i&&i<=56319)if(r===n-1)s.push(65533);else{var o=e.charCodeAt(r+1);if(56320<=o&&o<=57343){var a=1023&i,c=1023&o;s.push(65536+(a<<10)+c),r+=1}else s.push(65533)}r+=1}return s}(e));!s.endOfStream()&&(n=this._encoder.handler(s,s.read()))!==Nl;)Array.isArray(n)?r.push.apply(r,n):r.push(n);if(!this._streaming){for(;(n=this._encoder.handler(s,s.read()))!==Nl;)Array.isArray(n)?r.push.apply(r,n):r.push(n);this._encoder=null}return new Uint8Array(r)}};var Ol,Ml=ko(Object.freeze({__proto__:null,TextDecoder:xl,TextEncoder:Rl}));function Ll(){if(Ol)return Sl;Ol=1;var e=Sl&&Sl.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),t=Sl&&Sl.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=Sl&&Sl.__decorate||function(e,t,n,r){var s,i=arguments.length,o=i<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(s=e[a])&&(o=(i<3?s(o):i>3?s(t,n,o):s(t,n))||o);return i>3&&o&&Object.defineProperty(t,n,o),o},r=Sl&&Sl.__importStar||function(n){if(n&&n.__esModule)return n;var r={};if(null!=n)for(var s in n)"default"!==s&&Object.hasOwnProperty.call(n,s)&&e(r,n,s);return t(r,n),r},s=Sl&&Sl.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Sl,"__esModule",{value:!0}),Sl.deserializeUnchecked=Sl.deserialize=Sl.serialize=Sl.BinaryReader=Sl.BinaryWriter=Sl.BorshError=Sl.baseDecode=Sl.baseEncode=void 0;const i=s(ul()),o=s(wl()),a=r(Ml),c=new("function"!=typeof TextDecoder?a.TextDecoder:TextDecoder)("utf-8",{fatal:!0});Sl.baseEncode=function(e){return"string"==typeof e&&(e=Buffer.from(e,"utf8")),o.default.encode(Buffer.from(e))},Sl.baseDecode=function(e){return Buffer.from(o.default.decode(e))};const l=1024;class u extends Error{constructor(e){super(e),this.fieldPath=[],this.originalMessage=e}addToFieldPath(e){this.fieldPath.splice(0,0,e),this.message=this.originalMessage+": "+this.fieldPath.join(".")}}Sl.BorshError=u;class d{constructor(){this.buf=Buffer.alloc(l),this.length=0}maybeResize(){this.buf.length<16+this.length&&(this.buf=Buffer.concat([this.buf,Buffer.alloc(l)]))}writeU8(e){this.maybeResize(),this.buf.writeUInt8(e,this.length),this.length+=1}writeU16(e){this.maybeResize(),this.buf.writeUInt16LE(e,this.length),this.length+=2}writeU32(e){this.maybeResize(),this.buf.writeUInt32LE(e,this.length),this.length+=4}writeU64(e){this.maybeResize(),this.writeBuffer(Buffer.from(new i.default(e).toArray("le",8)))}writeU128(e){this.maybeResize(),this.writeBuffer(Buffer.from(new i.default(e).toArray("le",16)))}writeU256(e){this.maybeResize(),this.writeBuffer(Buffer.from(new i.default(e).toArray("le",32)))}writeU512(e){this.maybeResize(),this.writeBuffer(Buffer.from(new i.default(e).toArray("le",64)))}writeBuffer(e){this.buf=Buffer.concat([Buffer.from(this.buf.subarray(0,this.length)),e,Buffer.alloc(l)]),this.length+=e.length}writeString(e){this.maybeResize();const t=Buffer.from(e,"utf8");this.writeU32(t.length),this.writeBuffer(t)}writeFixedArray(e){this.writeBuffer(Buffer.from(e))}writeArray(e,t){this.maybeResize(),this.writeU32(e.length);for(const n of e)this.maybeResize(),t(n)}toArray(){return this.buf.subarray(0,this.length)}}function h(e,t,n){const r=n.value;n.value=function(...e){try{return r.apply(this,e)}catch(e){if(e instanceof RangeError){const t=e.code;if(["ERR_BUFFER_OUT_OF_BOUNDS","ERR_OUT_OF_RANGE"].indexOf(t)>=0)throw new u("Reached the end of buffer when deserializing")}throw e}}}Sl.BinaryWriter=d;class g{constructor(e){this.buf=e,this.offset=0}readU8(){const e=this.buf.readUInt8(this.offset);return this.offset+=1,e}readU16(){const e=this.buf.readUInt16LE(this.offset);return this.offset+=2,e}readU32(){const e=this.buf.readUInt32LE(this.offset);return this.offset+=4,e}readU64(){const e=this.readBuffer(8);return new i.default(e,"le")}readU128(){const e=this.readBuffer(16);return new i.default(e,"le")}readU256(){const e=this.readBuffer(32);return new i.default(e,"le")}readU512(){const e=this.readBuffer(64);return new i.default(e,"le")}readBuffer(e){if(this.offset+e>this.buf.length)throw new u(`Expected buffer length ${e} isn't within bounds`);const t=this.buf.slice(this.offset,this.offset+e);return this.offset+=e,t}readString(){const e=this.readU32(),t=this.readBuffer(e);try{return c.decode(t)}catch(e){throw new u(`Error decoding UTF-8 string: ${e}`)}}readFixedArray(e){return new Uint8Array(this.readBuffer(e))}readArray(e){const t=this.readU32(),n=Array();for(let r=0;r<t;++r)n.push(e());return n}}function f(e){return e.charAt(0).toUpperCase()+e.slice(1)}function p(e,t,n,r,s){try{if("string"==typeof r)s[`write${f(r)}`](n);else if(r instanceof Array)if("number"==typeof r[0]){if(n.length!==r[0])throw new u(`Expecting byte array of length ${r[0]}, but got ${n.length} bytes`);s.writeFixedArray(n)}else if(2===r.length&&"number"==typeof r[1]){if(n.length!==r[1])throw new u(`Expecting byte array of length ${r[1]}, but got ${n.length} bytes`);for(let t=0;t<r[1];t++)p(e,null,n[t],r[0],s)}else s.writeArray(n,n=>{p(e,t,n,r[0],s)});else if(void 0!==r.kind)switch(r.kind){case"option":null==n?s.writeU8(0):(s.writeU8(1),p(e,t,n,r.type,s));break;case"map":s.writeU32(n.size),n.forEach((n,i)=>{p(e,t,i,r.key,s),p(e,t,n,r.value,s)});break;default:throw new u(`FieldType ${r} unrecognized`)}else m(e,n,s)}catch(e){throw e instanceof u&&e.addToFieldPath(t),e}}function m(e,t,n){if("function"==typeof t.borshSerialize)return void t.borshSerialize(n);const r=e.get(t.constructor);if(!r)throw new u(`Class ${t.constructor.name} is missing in schema`);if("struct"===r.kind)r.fields.map(([r,s])=>{p(e,r,t[r],s,n)});else{if("enum"!==r.kind)throw new u(`Unexpected schema kind: ${r.kind} for ${t.constructor.name}`);{const s=t[r.field];for(let i=0;i<r.values.length;++i){const[o,a]=r.values[i];if(o===s){n.writeU8(i),p(e,o,t[o],a,n);break}}}}}function y(e,t,n,r){try{if("string"==typeof n)return r[`read${f(n)}`]();if(n instanceof Array){if("number"==typeof n[0])return r.readFixedArray(n[0]);if("number"==typeof n[1]){const t=[];for(let s=0;s<n[1];s++)t.push(y(e,null,n[0],r));return t}return r.readArray(()=>y(e,t,n[0],r))}if("option"===n.kind){return r.readU8()?y(e,t,n.type,r):void 0}if("map"===n.kind){let s=new Map;const i=r.readU32();for(let o=0;o<i;o++){const i=y(e,t,n.key,r),o=y(e,t,n.value,r);s.set(i,o)}return s}return b(e,n,r)}catch(e){throw e instanceof u&&e.addToFieldPath(t),e}}function b(e,t,n){if("function"==typeof t.borshDeserialize)return t.borshDeserialize(n);const r=e.get(t);if(!r)throw new u(`Class ${t.name} is missing in schema`);if("struct"===r.kind){const r={};for(const[s,i]of e.get(t).fields)r[s]=y(e,s,i,n);return new t(r)}if("enum"===r.kind){const s=n.readU8();if(s>=r.values.length)throw new u(`Enum index: ${s} is out of range`);const[i,o]=r.values[s],a=y(e,i,o,n);return new t({[i]:a})}throw new u(`Unexpected schema kind: ${r.kind} for ${t.constructor.name}`)}return n([h],g.prototype,"readU8",null),n([h],g.prototype,"readU16",null),n([h],g.prototype,"readU32",null),n([h],g.prototype,"readU64",null),n([h],g.prototype,"readU128",null),n([h],g.prototype,"readU256",null),n([h],g.prototype,"readU512",null),n([h],g.prototype,"readString",null),n([h],g.prototype,"readFixedArray",null),n([h],g.prototype,"readArray",null),Sl.BinaryReader=g,Sl.serialize=function(e,t,n=d){const r=new n;return m(e,t,r),r.toArray()},Sl.deserialize=function(e,t,n,r=g){const s=new r(n),i=b(e,t,s);if(s.offset<n.length)throw new u(`Unexpected ${n.length-s.offset} bytes after deserialized data`);return i},Sl.deserializeUnchecked=function(e,t,n,r=g){return b(e,t,new r(n))},Sl}var Ul,Pl=Ll(),Fl={};function $l(){if(Ul)return Fl;Ul=1,Object.defineProperty(Fl,"__esModule",{value:!0}),Fl.s16=Fl.s8=Fl.nu64be=Fl.u48be=Fl.u40be=Fl.u32be=Fl.u24be=Fl.u16be=Fl.nu64=Fl.u48=Fl.u40=Fl.u32=Fl.u24=Fl.u16=Fl.u8=Fl.offset=Fl.greedy=Fl.Constant=Fl.UTF8=Fl.CString=Fl.Blob=Fl.Boolean=Fl.BitField=Fl.BitStructure=Fl.VariantLayout=Fl.Union=Fl.UnionLayoutDiscriminator=Fl.UnionDiscriminator=Fl.Structure=Fl.Sequence=Fl.DoubleBE=Fl.Double=Fl.FloatBE=Fl.Float=Fl.NearInt64BE=Fl.NearInt64=Fl.NearUInt64BE=Fl.NearUInt64=Fl.IntBE=Fl.Int=Fl.UIntBE=Fl.UInt=Fl.OffsetLayout=Fl.GreedyCount=Fl.ExternalLayout=Fl.bindConstructorLayout=Fl.nameWithProperty=Fl.Layout=Fl.uint8ArrayToBuffer=Fl.checkUint8Array=void 0,Fl.constant=Fl.utf8=Fl.cstr=Fl.blob=Fl.unionLayoutDiscriminator=Fl.union=Fl.seq=Fl.bits=Fl.struct=Fl.f64be=Fl.f64=Fl.f32be=Fl.f32=Fl.ns64be=Fl.s48be=Fl.s40be=Fl.s32be=Fl.s24be=Fl.s16be=Fl.ns64=Fl.s48=Fl.s40=Fl.s32=Fl.s24=void 0;const e=Do();function t(e){if(!(e instanceof Uint8Array))throw new TypeError("b must be a Uint8Array")}function n(n){return t(n),e.Buffer.from(n.buffer,n.byteOffset,n.length)}Fl.checkUint8Array=t,Fl.uint8ArrayToBuffer=n;let r=class{constructor(e,t){if(!Number.isInteger(e))throw new TypeError("span must be an integer");this.span=e,this.property=t}makeDestinationObject(){return{}}getSpan(e,t){if(0>this.span)throw new RangeError("indeterminate span");return this.span}replicate(e){const t=Object.create(this.constructor.prototype);return Object.assign(t,this),t.property=e,t}fromArray(e){}};function s(e,t){return t.property?e+"["+t.property+"]":e}Fl.Layout=r,Fl.nameWithProperty=s,Fl.bindConstructorLayout=function(e,t){if("function"!=typeof e)throw new TypeError("Class must be constructor");if(Object.prototype.hasOwnProperty.call(e,"layout_"))throw new Error("Class is already bound to a layout");if(!(t&&t instanceof r))throw new TypeError("layout must be a Layout");if(Object.prototype.hasOwnProperty.call(t,"boundConstructor_"))throw new Error("layout is already bound to a constructor");e.layout_=t,t.boundConstructor_=e,t.makeDestinationObject=()=>new e,Object.defineProperty(e.prototype,"encode",{value(e,n){return t.encode(this,e,n)},writable:!0}),Object.defineProperty(e,"decode",{value:(e,n)=>t.decode(e,n),writable:!0})};class i extends r{isCount(){throw new Error("ExternalLayout is abstract")}}Fl.ExternalLayout=i;class o extends i{constructor(e=1,t){if(!Number.isInteger(e)||0>=e)throw new TypeError("elementSpan must be a (positive) integer");super(-1,t),this.elementSpan=e}isCount(){return!0}decode(e,n=0){t(e);const r=e.length-n;return Math.floor(r/this.elementSpan)}encode(e,t,n){return 0}}Fl.GreedyCount=o;class a extends i{constructor(e,t=0,n){if(!(e instanceof r))throw new TypeError("layout must be a Layout");if(!Number.isInteger(t))throw new TypeError("offset must be integer or undefined");super(e.span,n||e.property),this.layout=e,this.offset=t}isCount(){return this.layout instanceof c||this.layout instanceof l}decode(e,t=0){return this.layout.decode(e,t+this.offset)}encode(e,t,n=0){return this.layout.encode(e,t,n+this.offset)}}Fl.OffsetLayout=a;class c extends r{constructor(e,t){if(super(e,t),6<this.span)throw new RangeError("span must not exceed 6 bytes")}decode(e,t=0){return n(e).readUIntLE(t,this.span)}encode(e,t,r=0){return n(t).writeUIntLE(e,r,this.span),this.span}}Fl.UInt=c;class l extends r{constructor(e,t){if(super(e,t),6<this.span)throw new RangeError("span must not exceed 6 bytes")}decode(e,t=0){return n(e).readUIntBE(t,this.span)}encode(e,t,r=0){return n(t).writeUIntBE(e,r,this.span),this.span}}Fl.UIntBE=l;class u extends r{constructor(e,t){if(super(e,t),6<this.span)throw new RangeError("span must not exceed 6 bytes")}decode(e,t=0){return n(e).readIntLE(t,this.span)}encode(e,t,r=0){return n(t).writeIntLE(e,r,this.span),this.span}}Fl.Int=u;class d extends r{constructor(e,t){if(super(e,t),6<this.span)throw new RangeError("span must not exceed 6 bytes")}decode(e,t=0){return n(e).readIntBE(t,this.span)}encode(e,t,r=0){return n(t).writeIntBE(e,r,this.span),this.span}}Fl.IntBE=d;const h=Math.pow(2,32);function g(e){const t=Math.floor(e/h);return{hi32:t,lo32:e-t*h}}function f(e,t){return e*h+t}class p extends r{constructor(e){super(8,e)}decode(e,t=0){const r=n(e),s=r.readUInt32LE(t);return f(r.readUInt32LE(t+4),s)}encode(e,t,r=0){const s=g(e),i=n(t);return i.writeUInt32LE(s.lo32,r),i.writeUInt32LE(s.hi32,r+4),8}}Fl.NearUInt64=p;class m extends r{constructor(e){super(8,e)}decode(e,t=0){const r=n(e);return f(r.readUInt32BE(t),r.readUInt32BE(t+4))}encode(e,t,r=0){const s=g(e),i=n(t);return i.writeUInt32BE(s.hi32,r),i.writeUInt32BE(s.lo32,r+4),8}}Fl.NearUInt64BE=m;class y extends r{constructor(e){super(8,e)}decode(e,t=0){const r=n(e),s=r.readUInt32LE(t);return f(r.readInt32LE(t+4),s)}encode(e,t,r=0){const s=g(e),i=n(t);return i.writeUInt32LE(s.lo32,r),i.writeInt32LE(s.hi32,r+4),8}}Fl.NearInt64=y;class b extends r{constructor(e){super(8,e)}decode(e,t=0){const r=n(e);return f(r.readInt32BE(t),r.readUInt32BE(t+4))}encode(e,t,r=0){const s=g(e),i=n(t);return i.writeInt32BE(s.hi32,r),i.writeUInt32BE(s.lo32,r+4),8}}Fl.NearInt64BE=b;class v extends r{constructor(e){super(4,e)}decode(e,t=0){return n(e).readFloatLE(t)}encode(e,t,r=0){return n(t).writeFloatLE(e,r),4}}Fl.Float=v;class w extends r{constructor(e){super(4,e)}decode(e,t=0){return n(e).readFloatBE(t)}encode(e,t,r=0){return n(t).writeFloatBE(e,r),4}}Fl.FloatBE=w;class E extends r{constructor(e){super(8,e)}decode(e,t=0){return n(e).readDoubleLE(t)}encode(e,t,r=0){return n(t).writeDoubleLE(e,r),8}}Fl.Double=E;class A extends r{constructor(e){super(8,e)}decode(e,t=0){return n(e).readDoubleBE(t)}encode(e,t,r=0){return n(t).writeDoubleBE(e,r),8}}Fl.DoubleBE=A;class S extends r{constructor(e,t,n){if(!(e instanceof r))throw new TypeError("elementLayout must be a Layout");if(!(t instanceof i&&t.isCount()||Number.isInteger(t)&&0<=t))throw new TypeError("count must be non-negative integer or an unsigned integer ExternalLayout");let s=-1;!(t instanceof i)&&0<e.span&&(s=t*e.span),super(s,n),this.elementLayout=e,this.count=t}getSpan(e,t=0){if(0<=this.span)return this.span;let n=0,r=this.count;if(r instanceof i&&(r=r.decode(e,t)),0<this.elementLayout.span)n=r*this.elementLayout.span;else{let s=0;for(;s<r;)n+=this.elementLayout.getSpan(e,t+n),++s}return n}decode(e,t=0){const n=[];let r=0,s=this.count;for(s instanceof i&&(s=s.decode(e,t));r<s;)n.push(this.elementLayout.decode(e,t)),t+=this.elementLayout.getSpan(e,t),r+=1;return n}encode(e,t,n=0){const r=this.elementLayout,s=e.reduce((e,s)=>e+r.encode(s,t,n+e),0);return this.count instanceof i&&this.count.encode(e.length,t,n),s}}Fl.Sequence=S;class k extends r{constructor(e,t,n){if(!Array.isArray(e)||!e.reduce((e,t)=>e&&t instanceof r,!0))throw new TypeError("fields must be array of Layout instances");"boolean"==typeof t&&void 0===n&&(n=t,t=void 0);for(const t of e)if(0>t.span&&void 0===t.property)throw new Error("fields cannot contain unnamed variable-length layout");let s=-1;try{s=e.reduce((e,t)=>e+t.getSpan(),0)}catch(e){}super(s,t),this.fields=e,this.decodePrefixes=!!n}getSpan(e,t=0){if(0<=this.span)return this.span;let n=0;try{n=this.fields.reduce((n,r)=>{const s=r.getSpan(e,t);return t+=s,n+s},0)}catch(e){throw new RangeError("indeterminate span")}return n}decode(e,n=0){t(e);const r=this.makeDestinationObject();for(const t of this.fields)if(void 0!==t.property&&(r[t.property]=t.decode(e,n)),n+=t.getSpan(e,n),this.decodePrefixes&&e.length===n)break;return r}encode(e,t,n=0){const r=n;let s=0,i=0;for(const r of this.fields){let o=r.span;if(i=0<o?o:0,void 0!==r.property){const s=e[r.property];void 0!==s&&(i=r.encode(s,t,n),0>o&&(o=r.getSpan(t,n)))}s=n,n+=o}return s+i-r}fromArray(e){const t=this.makeDestinationObject();for(const n of this.fields)void 0!==n.property&&0<e.length&&(t[n.property]=e.shift());return t}layoutFor(e){if("string"!=typeof e)throw new TypeError("property must be string");for(const t of this.fields)if(t.property===e)return t}offsetOf(e){if("string"!=typeof e)throw new TypeError("property must be string");let t=0;for(const n of this.fields){if(n.property===e)return t;0>n.span?t=-1:0<=t&&(t+=n.span)}}}Fl.Structure=k;class T{constructor(e){this.property=e}decode(e,t){throw new Error("UnionDiscriminator is abstract")}encode(e,t,n){throw new Error("UnionDiscriminator is abstract")}}Fl.UnionDiscriminator=T;class I extends T{constructor(e,t){if(!(e instanceof i&&e.isCount()))throw new TypeError("layout must be an unsigned integer ExternalLayout");super(t||e.property||"variant"),this.layout=e}decode(e,t){return this.layout.decode(e,t)}encode(e,t,n){return this.layout.encode(e,t,n)}}Fl.UnionLayoutDiscriminator=I;class N extends r{constructor(e,t,n){let s;if(e instanceof c||e instanceof l)s=new I(new a(e));else if(e instanceof i&&e.isCount())s=new I(e);else{if(!(e instanceof T))throw new TypeError("discr must be a UnionDiscriminator or an unsigned integer layout");s=e}if(void 0===t&&(t=null),!(null===t||t instanceof r))throw new TypeError("defaultLayout must be null or a Layout");if(null!==t){if(0>t.span)throw new Error("defaultLayout must have constant span");void 0===t.property&&(t=t.replicate("content"))}let o=-1;t&&(o=t.span,0<=o&&(e instanceof c||e instanceof l)&&(o+=s.layout.span)),super(o,n),this.discriminator=s,this.usesPrefixDiscriminator=e instanceof c||e instanceof l,this.defaultLayout=t,this.registry={};let u=this.defaultGetSourceVariant.bind(this);this.getSourceVariant=function(e){return u(e)},this.configGetSourceVariant=function(e){u=e.bind(this)}}getSpan(e,t=0){if(0<=this.span)return this.span;const n=this.getVariant(e,t);if(!n)throw new Error("unable to determine span for unrecognized variant");return n.getSpan(e,t)}defaultGetSourceVariant(e){if(Object.prototype.hasOwnProperty.call(e,this.discriminator.property)){if(this.defaultLayout&&this.defaultLayout.property&&Object.prototype.hasOwnProperty.call(e,this.defaultLayout.property))return;const t=this.registry[e[this.discriminator.property]];if(t&&(!t.layout||t.property&&Object.prototype.hasOwnProperty.call(e,t.property)))return t}else for(const t in this.registry){const n=this.registry[t];if(n.property&&Object.prototype.hasOwnProperty.call(e,n.property))return n}throw new Error("unable to infer src variant")}decode(e,t=0){let n;const r=this.discriminator,s=r.decode(e,t),i=this.registry[s];if(void 0===i){const i=this.defaultLayout;let o=0;this.usesPrefixDiscriminator&&(o=r.layout.span),n=this.makeDestinationObject(),n[r.property]=s,n[i.property]=i.decode(e,t+o)}else n=i.decode(e,t);return n}encode(e,t,n=0){const r=this.getSourceVariant(e);if(void 0===r){const r=this.discriminator,s=this.defaultLayout;let i=0;return this.usesPrefixDiscriminator&&(i=r.layout.span),r.encode(e[r.property],t,n),i+s.encode(e[s.property],t,n+i)}return r.encode(e,t,n)}addVariant(e,t,n){const r=new C(this,e,t,n);return this.registry[e]=r,r}getVariant(e,t=0){let n;return n=e instanceof Uint8Array?this.discriminator.decode(e,t):e,this.registry[n]}}Fl.Union=N;class C extends r{constructor(e,t,n,s){if(!(e instanceof N))throw new TypeError("union must be a Union");if(!Number.isInteger(t)||0>t)throw new TypeError("variant must be a (non-negative) integer");if("string"==typeof n&&void 0===s&&(s=n,n=null),n){if(!(n instanceof r))throw new TypeError("layout must be a Layout");if(null!==e.defaultLayout&&0<=n.span&&n.span>e.defaultLayout.span)throw new Error("variant span exceeds span of containing union");if("string"!=typeof s)throw new TypeError("variant must have a String property")}let i=e.span;0>e.span&&(i=n?n.span:0,0<=i&&e.usesPrefixDiscriminator&&(i+=e.discriminator.layout.span)),super(i,s),this.union=e,this.variant=t,this.layout=n||null}getSpan(e,t=0){if(0<=this.span)return this.span;let n=0;this.union.usesPrefixDiscriminator&&(n=this.union.discriminator.layout.span);let r=0;return this.layout&&(r=this.layout.getSpan(e,t+n)),n+r}decode(e,t=0){const n=this.makeDestinationObject();if(this!==this.union.getVariant(e,t))throw new Error("variant mismatch");let r=0;return this.union.usesPrefixDiscriminator&&(r=this.union.discriminator.layout.span),this.layout?n[this.property]=this.layout.decode(e,t+r):this.property?n[this.property]=!0:this.union.usesPrefixDiscriminator&&(n[this.union.discriminator.property]=this.variant),n}encode(e,t,n=0){let r=0;if(this.union.usesPrefixDiscriminator&&(r=this.union.discriminator.layout.span),this.layout&&!Object.prototype.hasOwnProperty.call(e,this.property))throw new TypeError("variant lacks property "+this.property);this.union.discriminator.encode(this.variant,t,n);let s=r;if(this.layout&&(this.layout.encode(e[this.property],t,n+r),s+=this.layout.getSpan(t,n+r),0<=this.union.span&&s>this.union.span))throw new Error("encoded variant overruns containing union");return s}fromArray(e){if(this.layout)return this.layout.fromArray(e)}}function _(e){return 0>e&&(e+=4294967296),e}Fl.VariantLayout=C;class x extends r{constructor(e,t,n){if(!(e instanceof c||e instanceof l))throw new TypeError("word must be a UInt or UIntBE layout");if("string"==typeof t&&void 0===n&&(n=t,t=!1),4<e.span)throw new RangeError("word cannot exceed 32 bits");super(e.span,n),this.word=e,this.msb=!!t,this.fields=[];let r=0;this._packedSetValue=function(e){return r=_(e),this},this._packedGetValue=function(){return r}}decode(e,t=0){const n=this.makeDestinationObject(),r=this.word.decode(e,t);this._packedSetValue(r);for(const t of this.fields)void 0!==t.property&&(n[t.property]=t.decode(e));return n}encode(e,t,n=0){const r=this.word.decode(t,n);this._packedSetValue(r);for(const t of this.fields)if(void 0!==t.property){const n=e[t.property];void 0!==n&&t.encode(n)}return this.word.encode(this._packedGetValue(),t,n)}addField(e,t){const n=new R(this,e,t);return this.fields.push(n),n}addBoolean(e){const t=new B(this,e);return this.fields.push(t),t}fieldFor(e){if("string"!=typeof e)throw new TypeError("property must be string");for(const t of this.fields)if(t.property===e)return t}}Fl.BitStructure=x;class R{constructor(e,t,n){if(!(e instanceof x))throw new TypeError("container must be a BitStructure");if(!Number.isInteger(t)||0>=t)throw new TypeError("bits must be positive integer");const r=8*e.span,s=e.fields.reduce((e,t)=>e+t.bits,0);if(t+s>r)throw new Error("bits too long for span remainder ("+(r-s)+" of "+r+" remain)");this.container=e,this.bits=t,this.valueMask=(1<<t)-1,32===t&&(this.valueMask=4294967295),this.start=s,this.container.msb&&(this.start=r-s-t),this.wordMask=_(this.valueMask<<this.start),this.property=n}decode(e,t){return _(this.container._packedGetValue()&this.wordMask)>>>this.start}encode(e){if("number"!=typeof e||!Number.isInteger(e)||e!==_(e&this.valueMask))throw new TypeError(s("BitField.encode",this)+" value must be integer not exceeding "+this.valueMask);const t=this.container._packedGetValue(),n=_(e<<this.start);this.container._packedSetValue(_(t&~this.wordMask)|n)}}Fl.BitField=R;class B extends R{constructor(e,t){super(e,1,t)}decode(e,t){return!!super.decode(e,t)}encode(e){"boolean"==typeof e&&(e=+e),super.encode(e)}}Fl.Boolean=B;class D extends r{constructor(e,t){if(!(e instanceof i&&e.isCount()||Number.isInteger(e)&&0<=e))throw new TypeError("length must be positive integer or an unsigned integer ExternalLayout");let n=-1;e instanceof i||(n=e),super(n,t),this.length=e}getSpan(e,t){let n=this.span;return 0>n&&(n=this.length.decode(e,t)),n}decode(e,t=0){let r=this.span;return 0>r&&(r=this.length.decode(e,t)),n(e).slice(t,t+r)}encode(e,t,r){let o=this.length;if(this.length instanceof i&&(o=e.length),!(e instanceof Uint8Array&&o===e.length))throw new TypeError(s("Blob.encode",this)+" requires (length "+o+") Uint8Array as src");if(r+o>t.length)throw new RangeError("encoding overruns Uint8Array");const a=n(e);return n(t).write(a.toString("hex"),r,o,"hex"),this.length instanceof i&&this.length.encode(o,t,r),o}}Fl.Blob=D;class O extends r{constructor(e){super(-1,e)}getSpan(e,n=0){t(e);let r=n;for(;r<e.length&&0!==e[r];)r+=1;return 1+r-n}decode(e,t=0){const r=this.getSpan(e,t);return n(e).slice(t,t+r-1).toString("utf-8")}encode(t,r,s=0){"string"!=typeof t&&(t=String(t));const i=e.Buffer.from(t,"utf8"),o=i.length;if(s+o>r.length)throw new RangeError("encoding overruns Buffer");const a=n(r);return i.copy(a,s),a[s+o]=0,o+1}}Fl.CString=O;class M extends r{constructor(e,t){if("string"==typeof e&&void 0===t&&(t=e,e=void 0),void 0===e)e=-1;else if(!Number.isInteger(e))throw new TypeError("maxSpan must be an integer");super(-1,t),this.maxSpan=e}getSpan(e,n=0){return t(e),e.length-n}decode(e,t=0){const r=this.getSpan(e,t);if(0<=this.maxSpan&&this.maxSpan<r)throw new RangeError("text length exceeds maxSpan");return n(e).slice(t,t+r).toString("utf-8")}encode(t,r,s=0){"string"!=typeof t&&(t=String(t));const i=e.Buffer.from(t,"utf8"),o=i.length;if(0<=this.maxSpan&&this.maxSpan<o)throw new RangeError("text length exceeds maxSpan");if(s+o>r.length)throw new RangeError("encoding overruns Buffer");return i.copy(n(r),s),o}}Fl.UTF8=M;class L extends r{constructor(e,t){super(0,t),this.value=e}decode(e,t){return this.value}encode(e,t,n){return 0}}return Fl.Constant=L,Fl.greedy=(e,t)=>new o(e,t),Fl.offset=(e,t,n)=>new a(e,t,n),Fl.u8=e=>new c(1,e),Fl.u16=e=>new c(2,e),Fl.u24=e=>new c(3,e),Fl.u32=e=>new c(4,e),Fl.u40=e=>new c(5,e),Fl.u48=e=>new c(6,e),Fl.nu64=e=>new p(e),Fl.u16be=e=>new l(2,e),Fl.u24be=e=>new l(3,e),Fl.u32be=e=>new l(4,e),Fl.u40be=e=>new l(5,e),Fl.u48be=e=>new l(6,e),Fl.nu64be=e=>new m(e),Fl.s8=e=>new u(1,e),Fl.s16=e=>new u(2,e),Fl.s24=e=>new u(3,e),Fl.s32=e=>new u(4,e),Fl.s40=e=>new u(5,e),Fl.s48=e=>new u(6,e),Fl.ns64=e=>new y(e),Fl.s16be=e=>new d(2,e),Fl.s24be=e=>new d(3,e),Fl.s32be=e=>new d(4,e),Fl.s40be=e=>new d(5,e),Fl.s48be=e=>new d(6,e),Fl.ns64be=e=>new b(e),Fl.f32=e=>new v(e),Fl.f32be=e=>new w(e),Fl.f64=e=>new E(e),Fl.f64be=e=>new A(e),Fl.struct=(e,t,n)=>new k(e,t,n),Fl.bits=(e,t,n)=>new x(e,t,n),Fl.seq=(e,t,n)=>new S(e,t,n),Fl.union=(e,t,n)=>new N(e,t,n),Fl.unionLayoutDiscriminator=(e,t)=>new I(e,t),Fl.blob=(e,t)=>new D(e,t),Fl.cstr=e=>new O(e),Fl.utf8=(e,t)=>new M(e,t),Fl.constant=(e,t)=>new L(e,t),Fl}var Kl=$l(),Gl=1,Wl=2,Hl=3,ql=4,zl=5,Vl=6,jl=7,Xl=8,Yl=9,Jl=10,Ql=-32700,Zl=-32603,eu=-32602,tu=-32601,nu=-32600,ru=-32019,su=-32018,iu=-32017,ou=-32016,au=-32015,cu=-32014,lu=-32013,uu=-32012,du=-32011,hu=-32010,gu=-32009,fu=-32008,pu=-32007,mu=-32006,yu=-32005,bu=-32004,vu=-32003,wu=-32002,Eu=-32001,Au=28e5,Su=2800001,ku=2800002,Tu=2800003,Iu=2800004,Nu=2800005,Cu=2800006,_u=2800007,xu=2800008,Ru=2800009,Bu=2800010,Du=2800011,Ou=323e4,Mu=32300001,Lu=3230002,Uu=3230003,Pu=3230004,Fu=361e4,$u=3610001,Ku=3610002,Gu=3610003,Wu=3610004,Hu=3610005,qu=3610006,zu=3610007,Vu=3611e3,ju=3704e3,Xu=3704001,Yu=3704002,Ju=3704003,Qu=3704004,Zu=4128e3,ed=4128001,td=4128002,nd=4615e3,rd=4615001,sd=4615002,id=4615003,od=4615004,ad=4615005,cd=4615006,ld=4615007,ud=4615008,dd=4615009,hd=4615010,gd=4615011,fd=4615012,pd=4615013,md=4615014,yd=4615015,bd=4615016,vd=4615017,wd=4615018,Ed=4615019,Ad=4615020,Sd=4615021,kd=4615022,Td=4615023,Id=4615024,Nd=4615025,Cd=4615026,_d=4615027,xd=4615028,Rd=4615029,Bd=4615030,Dd=4615031,Od=4615032,Md=4615033,Ld=4615034,Ud=4615035,Pd=4615036,Fd=4615037,$d=4615038,Kd=4615039,Gd=4615040,Wd=4615041,Hd=4615042,qd=4615043,zd=4615044,Vd=4615045,jd=4615046,Xd=4615047,Yd=4615048,Jd=4615049,Qd=4615050,Zd=4615051,eh=4615052,th=4615053,nh=4615054,rh=5508e3,sh=5508001,ih=5508002,oh=5508003,ah=5508004,ch=5508005,lh=5508006,uh=5508007,dh=5508008,hh=5508009,gh=5508010,fh=5508011,ph=5607e3,mh=5607001,yh=5607002,bh=5607003,vh=5607004,wh=5607005,Eh=5607006,Ah=5607007,Sh=5607008,kh=5607009,Th=5607010,Ih=5607011,Nh=5607012,Ch=5607013,_h=5607014,xh=5607015,Rh=5607016,Bh=5607017,Dh=5663e3,Oh=5663001,Mh=5663002,Lh=5663003,Uh=5663004,Ph=5663005,Fh=5663006,$h=5663007,Kh=5663008,Gh=5663009,Wh=5663010,Hh=5663011,qh=5663012,zh=5663013,Vh=5663014,jh=5663015,Xh=5663016,Yh=5663017,Jh=5663018,Qh=5663019,Zh=5663020,eg=5663021,tg=5663022,ng=705e4,rg=7050001,sg=7050002,ig=7050003,og=7050004,ag=7050005,cg=7050006,lg=7050007,ug=7050008,dg=7050009,hg=7050010,gg=7050011,fg=7050012,pg=7050013,mg=7050014,yg=7050015,bg=7050016,vg=7050017,wg=7050018,Eg=7050019,Ag=7050020,Sg=7050021,kg=7050022,Tg=7050023,Ig=7050024,Ng=7050025,Cg=7050026,_g=7050027,xg=7050028,Rg=7050029,Bg=7050030,Dg=7050031,Og=7050032,Mg=7050033,Lg=7050034,Ug=7050035,Pg=7050036,Fg=7618e3,$g=7618001,Kg=7618002,Gg=7618003,Wg=7618004,Hg=7618005,qg=7618006,zg=7618007,Vg=7618008,jg=7618009,Xg=8078e3,Yg=8078001,Jg=8078002,Qg=8078003,Zg=8078004,ef=8078005,tf=8078006,nf=8078007,rf=8078008,sf=8078009,of=8078010,af=8078011,cf=8078012,lf=8078013,uf=8078014,df=8078015,hf=8078016,gf=8078017,ff=8078018,pf=8078019,mf=8078020,yf=8078021,bf=8078022,vf=8078023,wf=81e5,Ef=8100001,Af=8100002,Sf=8100003,kf=819e4,Tf=8190001,If=8190002,Nf=8190003,Cf=8190004,_f=99e5,xf=9900001,Rf=9900002,Bf=9900003,Df=9900004,Of=9900005,Mf=9900006;function Lf(e){if(Array.isArray(e)){return"%5B"+e.map(Lf).join("%2C%20")+"%5D"}return"bigint"==typeof e?`${e}n`:encodeURIComponent(String(null!=e&&null===Object.getPrototypeOf(e)?{...e}:e))}function Uf([e,t]){return`${e}=${Lf(t)}`}var Pf={[Ou]:"Account not found at address: $address",[Pu]:"Not all accounts were decoded. Encoded accounts found at addresses: $addresses.",[Uu]:"Expected decoded account at address: $address",[Lu]:"Failed to decode account data at address: $address",[Mu]:"Accounts not found at addresses: $addresses",[Ru]:"Unable to find a viable program address bump seed.",[ku]:"$putativeAddress is not a base58-encoded address.",[Au]:"Expected base58 encoded address to decode to a byte array of length 32. Actual length: $actualLength.",[Tu]:"The `CryptoKey` must be an `Ed25519` public key.",[Du]:"$putativeOffCurveAddress is not a base58-encoded off-curve address.",[xu]:"Invalid seeds; point must fall off the Ed25519 curve.",[Iu]:"Expected given program derived address to have the following format: [Address, ProgramDerivedAddressBump].",[Cu]:"A maximum of $maxSeeds seeds, including the bump seed, may be supplied when creating an address. Received: $actual.",[_u]:"The seed at index $index with length $actual exceeds the maximum length of $maxSeedLength bytes.",[Nu]:"Expected program derived address bump to be in the range [0, 255], got: $bump.",[Bu]:"Program address cannot end with PDA marker.",[Su]:"Expected base58-encoded address string of length in the range [32, 44]. Actual length: $actualLength.",[ql]:"Expected base58-encoded blockash string of length in the range [32, 44]. Actual length: $actualLength.",[Gl]:"The network has progressed past the last block for which this transaction could have been committed.",[Xg]:"Codec [$codecDescription] cannot decode empty byte arrays.",[bf]:"Enum codec cannot use lexical values [$stringValues] as discriminators. Either remove all lexical values or set `useValuesAsDiscriminators` to `false`.",[mf]:"Sentinel [$hexSentinel] must not be present in encoded bytes [$hexEncodedBytes].",[ef]:"Encoder and decoder must have the same fixed size, got [$encoderFixedSize] and [$decoderFixedSize].",[tf]:"Encoder and decoder must have the same max size, got [$encoderMaxSize] and [$decoderMaxSize].",[Zg]:"Encoder and decoder must either both be fixed-size or variable-size.",[rf]:"Enum discriminator out of range. Expected a number in [$formattedValidDiscriminators], got $discriminator.",[Jg]:"Expected a fixed-size codec, got a variable-size one.",[lf]:"Codec [$codecDescription] expected a positive byte length, got $bytesLength.",[Qg]:"Expected a variable-size codec, got a fixed-size one.",[pf]:"Codec [$codecDescription] expected zero-value [$hexZeroValue] to have the same size as the provided fixed-size item [$expectedSize bytes].",[Yg]:"Codec [$codecDescription] expected $expected bytes, got $bytesLength.",[ff]:"Expected byte array constant [$hexConstant] to be present in data [$hexData] at offset [$offset].",[sf]:"Invalid discriminated union variant. Expected one of [$variants], got $value.",[of]:"Invalid enum variant. Expected one of [$stringValues] or a number in [$formattedNumericalValues], got $variant.",[df]:"Invalid literal union variant. Expected one of [$variants], got $value.",[nf]:"Expected [$codecDescription] to have $expected items, got $actual.",[cf]:"Invalid value $value for base $base with alphabet $alphabet.",[hf]:"Literal union discriminator out of range. Expected a number between $minRange and $maxRange, got $discriminator.",[af]:"Codec [$codecDescription] expected number to be in the range [$min, $max], got $value.",[uf]:"Codec [$codecDescription] expected offset to be in the range [0, $bytesLength], got $offset.",[yf]:"Expected sentinel [$hexSentinel] to be present in decoded bytes [$hexDecodedBytes].",[gf]:"Union variant out of range. Expected an index between $minRange and $maxRange, got $variant.",[vf]:"This decoder expected a byte array of exactly $expectedLength bytes, but $numExcessBytes unexpected excess bytes remained after decoding. Are you sure that you have chosen the correct decoder for this data?",[Vu]:"No random values implementation could be found.",[dd]:"instruction requires an uninitialized account",[Td]:"instruction tries to borrow reference for an account which is already borrowed",[Id]:"instruction left account with an outstanding borrowed reference",[Sd]:"program other than the account's owner changed the size of the account data",[ad]:"account data too small for instruction",[kd]:"instruction expected an executable account",[jd]:"An account does not have enough lamports to be rent-exempt",[Yd]:"Program arithmetic overflowed",[Vd]:"Failed to serialize or deserialize account data: $encodedData",[nh]:"Builtin programs must consume compute units",[Od]:"Cross-program invocation call depth too deep",[$d]:"Computational budget exceeded",[Cd]:"custom program error: #$code",[vd]:"instruction contains duplicate accounts",[Nd]:"instruction modifications of multiply-passed account differ",[Bd]:"executable accounts must be rent exempt",[xd]:"instruction changed executable accounts data",[Rd]:"instruction changed the balance of an executable account",[wd]:"instruction changed executable bit of an account",[md]:"instruction modified data of an account it does not own",[pd]:"instruction spent from the balance of an account it does not own",[rd]:"generic instruction error",[Qd]:"Provided owner is not allowed",[qd]:"Account is immutable",[zd]:"Incorrect authority provided",[ld]:"incorrect program id for instruction",[cd]:"insufficient funds for instruction",[od]:"invalid account data for instruction",[Xd]:"Invalid account owner",[sd]:"invalid program argument",[_d]:"program returned invalid error code",[id]:"invalid instruction data",[Fd]:"Failed to reallocate account data",[Pd]:"Provided seeds do not result in a valid address",[Zd]:"Accounts data allocations exceeded the maximum allowed per transaction",[eh]:"Max accounts exceeded",[th]:"Max instruction trace length exceeded",[Ud]:"Length of the seed is too long for address generation",[Md]:"An account required by the instruction is missing",[ud]:"missing required signature for instruction",[fd]:"instruction illegally modified the program id of an account",[Ad]:"insufficient account keys for instruction",[Kd]:"Cross-program invocation with unauthorized signer or writable account",[Gd]:"Failed to create program execution environment",[Hd]:"Program failed to compile",[Wd]:"Program failed to complete",[bd]:"instruction modified data of a read-only account",[yd]:"instruction changed the balance of a read-only account",[Ld]:"Cross-program invocation reentrancy not allowed for this instruction",[Ed]:"instruction modified rent epoch of an account",[gd]:"sum of account balances before and after instruction do not match",[hd]:"instruction requires an initialized account",[nd]:"",[Dd]:"Unsupported program id",[Jd]:"Unsupported sysvar",[Of]:"Invalid instruction plan kind: $kind.",[Kg]:"The provided instruction plan is empty.",[Hg]:"No failed transaction plan result was found in the provided transaction plan result.",[Wg]:"This transaction plan executor does not support non-divisible sequential plans. To support them, you may create your own executor such that multi-transaction atomicity is preserved — e.g. by targetting RPCs that support transaction bundles.",[Gg]:"The provided transaction plan failed to execute. See the `transactionPlanResult` attribute for more details. Note that the `cause` property is deprecated, and a future version will not set it.",[Fg]:"The provided message has insufficient capacity to accommodate the next instruction(s) in this plan. Expected at least $numBytesRequired free byte(s), got $numFreeBytes byte(s).",[Mf]:"Invalid transaction plan kind: $kind.",[$g]:"No more instructions to pack; the message packer has completed the instruction plan.",[qg]:"Unexpected instruction plan. Expected $expectedKind plan, got $actualKind plan.",[zg]:"Unexpected transaction plan. Expected $expectedKind plan, got $actualKind plan.",[Vg]:"Unexpected transaction plan result. Expected $expectedKind plan, got $actualKind plan.",[jg]:"Expected a successful transaction plan result. I.e. there is at least one failed or cancelled transaction in the plan.",[Zu]:"The instruction does not have any accounts.",[ed]:"The instruction does not have any data.",[td]:"Expected instruction to have progress address $expectedProgramAddress, got $actualProgramAddress.",[zl]:"Expected base58 encoded blockhash to decode to a byte array of length 32. Actual length: $actualLength.",[Wl]:"The nonce `$expectedNonceValue` is no longer valid. It has advanced to `$actualNonceValue`",[Rf]:"Invariant violation: Found no abortable iterable cache entry for key `$cacheKey`. It should be impossible to hit this error; please file an issue at https://sola.na/web3invariant",[Df]:"Invariant violation: This data publisher does not publish to the channel named `$channelName`. Supported channels include $supportedChannelNames.",[xf]:"Invariant violation: WebSocket message iterator state is corrupt; iterated without first resolving existing message promise. It should be impossible to hit this error; please file an issue at https://sola.na/web3invariant",[_f]:"Invariant violation: WebSocket message iterator is missing state storage. It should be impossible to hit this error; please file an issue at https://sola.na/web3invariant",[Bf]:"Invariant violation: Switch statement non-exhaustive. Received unexpected value `$unexpectedValue`. It should be impossible to hit this error; please file an issue at https://sola.na/web3invariant",[Zl]:"JSON-RPC error: Internal JSON-RPC error ($__serverMessage)",[eu]:"JSON-RPC error: Invalid method parameter(s) ($__serverMessage)",[nu]:"JSON-RPC error: The JSON sent is not a valid `Request` object ($__serverMessage)",[tu]:"JSON-RPC error: The method does not exist / is not available ($__serverMessage)",[Ql]:"JSON-RPC error: An error occurred on the server while parsing the JSON text ($__serverMessage)",[uu]:"$__serverMessage",[Eu]:"$__serverMessage",[bu]:"$__serverMessage",[cu]:"$__serverMessage",[iu]:"Epoch rewards period still active at slot $slot",[hu]:"$__serverMessage",[gu]:"$__serverMessage",[ru]:"Failed to query long-term storage; please try again",[ou]:"Minimum context slot has not been reached",[yu]:"Node is unhealthy; behind by $numSlotsBehind slots",[fu]:"No snapshot",[wu]:"Transaction simulation failed",[su]:"Rewards cannot be found because slot $slot is not the epoch boundary. This may be due to gap in the queried node's local ledger or long-term storage",[pu]:"$__serverMessage",[du]:"Transaction history is not available from this node",[mu]:"$__serverMessage",[lu]:"Transaction signature length mismatch",[vu]:"Transaction signature verification failure",[au]:"$__serverMessage",[ju]:"Key pair bytes must be of length 64, got $byteLength.",[Xu]:"Expected private key bytes with length 32. Actual length: $actualLength.",[Yu]:"Expected base58-encoded signature to decode to a byte array of length 64. Actual length: $actualLength.",[Qu]:"The provided private key does not match the provided public key.",[Ju]:"Expected base58-encoded signature string of length in the range [64, 88]. Actual length: $actualLength.",[Vl]:"Lamports value must be in the range [0, 2e64-1]",[jl]:"`$value` cannot be parsed as a `BigInt`",[Jl]:"$message",[Xl]:"`$value` cannot be parsed as a `Number`",[Hl]:"No nonce account could be found at address `$nonceAccountAddress`",[bh]:"Expected base58 encoded application domain to decode to a byte array of length 32. Actual length: $actualLength.",[Ch]:"Attempted to sign an offchain message with an address that is not a signer for it",[yh]:"Expected base58-encoded application domain string of length in the range [32, 44]. Actual length: $actualLength.",[Nh]:"The signer addresses in this offchain message envelope do not match the list of required signers in the message preamble. These unexpected signers were present in the envelope: `[$unexpectedSigners]`. These required signers were missing from the envelope `[$missingSigners]`.",[ph]:"The message body provided has a byte-length of $actualBytes. The maximum allowable byte-length is $maxBytes",[Ah]:"Expected message format $expectedMessageFormat, got $actualMessageFormat",[Sh]:"The message length specified in the message preamble is $specifiedLength bytes. The actual length of the message is $actualLength bytes.",[kh]:"Offchain message content must be non-empty",[wh]:"Offchain message must specify the address of at least one required signer",[Th]:"Offchain message envelope must reserve space for at least one signature",[vh]:"The offchain message preamble specifies $numRequiredSignatures required signature(s), got $signaturesLength.",[xh]:"The signatories of this offchain message must be listed in lexicographical order",[Rh]:"An address must be listed no more than once among the signatories of an offchain message",[Ih]:"Offchain message is missing signatures for addresses: $addresses.",[Bh]:"Offchain message signature verification failed. Signature mismatch for required signatories [$signatoriesWithInvalidSignatures]. Missing signatures for signatories [$signatoriesWithMissingSignatures]",[mh]:"The message body provided contains characters whose codes fall outside the allowed range. In order to ensure clear-signing compatiblity with hardware wallets, the message may only contain line feeds and characters in the range [\\x20-\\x7e].",[_h]:"Expected offchain message version $expectedVersion. Got $actualVersion.",[Eh]:"This version of Kit does not support decoding offchain messages with version $unsupportedVersion. The current max supported version is 0.",[kf]:"The notification name must end in 'Notifications' and the API must supply a subscription plan creator function for the notification '$notificationName'.",[If]:"WebSocket was closed before payload could be added to the send buffer",[Nf]:"WebSocket connection closed",[Cf]:"WebSocket failed to connect",[Tf]:"Failed to obtain a subscription id from the server",[Sf]:"Could not find an API plan for RPC method: `$method`",[wf]:"The $argumentLabel argument to the `$methodName` RPC method$optionalPathLabel was `$value`. This number is unsafe for use with the Solana JSON-RPC because it exceeds `Number.MAX_SAFE_INTEGER`.",[Af]:"HTTP error ($statusCode): $message",[Ef]:"HTTP header(s) forbidden: $headers. Learn more at https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name.",[rh]:"Multiple distinct signers were identified for address `$address`. Please ensure that you are using the same signer instance for each address.",[sh]:"The provided value does not implement the `KeyPairSigner` interface",[oh]:"The provided value does not implement the `MessageModifyingSigner` interface",[ah]:"The provided value does not implement the `MessagePartialSigner` interface",[ih]:"The provided value does not implement any of the `MessageSigner` interfaces",[lh]:"The provided value does not implement the `TransactionModifyingSigner` interface",[uh]:"The provided value does not implement the `TransactionPartialSigner` interface",[dh]:"The provided value does not implement the `TransactionSendingSigner` interface",[ch]:"The provided value does not implement any of the `TransactionSigner` interfaces",[hh]:"More than one `TransactionSendingSigner` was identified.",[gh]:"No `TransactionSendingSigner` was identified. Please provide a valid `TransactionWithSingleSendingSigner` transaction.",[fh]:"Wallet account signers do not support signing multiple messages/transactions in a single operation",[zu]:"Cannot export a non-extractable key.",[$u]:"No digest implementation could be found.",[Fu]:"Cryptographic operations are only allowed in secure browser contexts. Read more here: https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts.",[Ku]:"This runtime does not support the generation of Ed25519 key pairs.\n\nInstall @solana/webcrypto-ed25519-polyfill and call its `install` function before generating keys in environments that do not support Ed25519.\n\nFor a list of runtimes that currently support Ed25519 operations, visit https://github.com/WICG/webcrypto-secure-curves/issues/20.",[Gu]:"No signature verification implementation could be found.",[Wu]:"No key generation implementation could be found.",[Hu]:"No signing implementation could be found.",[qu]:"No key export implementation could be found.",[Yl]:"Timestamp value must be in the range [-(2n ** 63n), (2n ** 63n) - 1]. `$value` given",[bg]:"Transaction processing left an account with an outstanding borrowed reference",[rg]:"Account in use",[sg]:"Account loaded twice",[ig]:"Attempt to debit an account but found no record of a prior credit.",[Tg]:"Transaction loads an address table account that doesn't exist",[lg]:"This transaction has already been processed",[ug]:"Blockhash not found",[dg]:"Loader call chain is too deep",[yg]:"Transactions are currently disabled due to cluster maintenance",[Bg]:"Transaction contains a duplicate instruction ($index) that is not allowed",[ag]:"Insufficient funds for fee",[Dg]:"Transaction results in an account ($accountIndex) with insufficient funds for rent",[cg]:"This account may not be used to pay transaction fees",[gg]:"Transaction contains an invalid account reference",[Ng]:"Transaction loads an address table account with invalid data",[Cg]:"Transaction address table lookup uses an invalid index",[Ig]:"Transaction loads an address table account with an invalid owner",[Mg]:"LoadedAccountsDataSizeLimit set for transaction must be greater than 0.",[pg]:"This program may not be used for executing instructions",[_g]:"Transaction leaves an account with a lower balance than rent-exempt minimum",[Eg]:"Transaction loads a writable account that cannot be written",[Og]:"Transaction exceeded max loaded accounts data size cap",[hg]:"Transaction requires a fee but has no signature present",[og]:"Attempt to load a program that does not exist",[Ug]:"Execution of the program referenced by account at index $accountIndex is temporarily restricted.",[Lg]:"ResanitizationNeeded",[mg]:"Transaction failed to sanitize accounts offsets correctly",[fg]:"Transaction did not pass signature verification",[kg]:"Transaction locked too many accounts",[Pg]:"Sum of account balances before and after transaction do not match",[ng]:"The transaction failed with the error `$errorName`",[wg]:"Transaction version is unsupported",[Sg]:"Transaction would exceed account data limit within the block",[Rg]:"Transaction would exceed total account data limit",[Ag]:"Transaction would exceed max account limit within the block",[vg]:"Transaction would exceed max Block Cost Limit",[xg]:"Transaction would exceed max Vote Cost Limit",[jh]:"Attempted to sign a transaction with an address that is not a signer for it",[Wh]:"Transaction is missing an address at index: $index.",[Xh]:"Transaction has no expected signers therefore it cannot be encoded",[Zh]:"Transaction size $transactionSize exceeds limit of $transactionSizeLimit bytes",[Mh]:"Transaction does not have a blockhash lifetime",[Lh]:"Transaction is not a durable nonce transaction",[Ph]:"Contents of these address lookup tables unknown: $lookupTableAddresses",[Fh]:"Lookup of address at index $highestRequestedIndex failed for lookup table `$lookupTableAddress`. Highest known index is $highestKnownIndex. The lookup table may have been extended since its contents were retrieved",[Kh]:"No fee payer set in CompiledTransaction",[$h]:"Could not find program address at index $index",[Jh]:"Failed to estimate the compute unit consumption for this transaction message. This is likely because simulating the transaction failed. Inspect the `cause` property of this error to learn more",[Qh]:"Transaction failed when it was simulated in order to estimate the compute unit consumption. The compute unit estimate provided is for a transaction that failed when simulated and may not be representative of the compute units this transaction would consume if successful. Inspect the `cause` property of this error to learn more",[Hh]:"Transaction is missing a fee payer.",[qh]:"Could not determine this transaction's signature. Make sure that the transaction has been signed by its fee payer.",[Vh]:"Transaction first instruction is not advance nonce account instruction.",[zh]:"Transaction with no instructions cannot be durable nonce transaction.",[Dh]:"This transaction includes an address (`$programAddress`) which is both invoked and set as the fee payer. Program addresses may not pay fees",[Oh]:"This transaction includes an address (`$programAddress`) which is both invoked and marked writable. Program addresses may not be writable",[Yh]:"The transaction message expected the transaction to have $numRequiredSignatures signatures, got $signaturesLength.",[Gh]:"Transaction is missing signatures for addresses: $addresses.",[Uh]:"Transaction version must be in the range [0, 127]. `$actualVersion` given",[eg]:"This version of Kit does not support decoding transactions with version $unsupportedVersion. The current max supported version is 0.",[tg]:"The transaction has a durable nonce lifetime (with nonce `$nonce`), but the nonce account address is in a lookup table. The lifetime constraint cannot be constructed without fetching the lookup tables for the transaction."},Ff="i",$f="t";function Kf(e,t={}){if("production"!==process.env.NODE_ENV)return function(e,t={}){const n=Pf[e];if(0===n.length)return"";let r;function s(e){if(2===r[$f]){const s=n.slice(r[Ff]+1,e);i.push(s in t?`${t[s]}`:`$${s}`)}else 1===r[$f]&&i.push(n.slice(r[Ff],e))}const i=[];return n.split("").forEach((e,t)=>{if(0===t)return void(r={[Ff]:0,[$f]:"\\"===n[0]?0:"$"===n[0]?2:1});let i;switch(r[$f]){case 0:i={[Ff]:t,[$f]:1};break;case 1:"\\"===e?i={[Ff]:t,[$f]:0}:"$"===e&&(i={[Ff]:t,[$f]:2});break;case 2:"\\"===e?i={[Ff]:t,[$f]:0}:"$"===e?i={[Ff]:t,[$f]:2}:e.match(/\w/)||(i={[Ff]:t,[$f]:1})}i&&(r!==i&&s(t),r=i)}),s(),i.join("")}(e,t);{let n=`Solana error #${e}; Decode this error by running \`npx @solana/errors decode -- ${e}`;return Object.keys(t).length&&(n+=` '${function(e){const t=Object.entries(e).map(Uf).join("&");return btoa(t)}(t)}'`),`${n}\``}}var Gf=class extends Error{cause=this.cause;context;constructor(...[e,t]){let n,r;t&&Object.entries(Object.getOwnPropertyDescriptors(t)).forEach(([t,s])=>{"cause"===t?r={cause:s.value}:(void 0===n&&(n={__code:e}),Object.defineProperty(n,t,s))});super(Kf(e,n),r),this.context=Object.freeze(void 0===n?{__code:e}:n),this.name="SolanaError"}};function Wf(e){return"fixedSize"in e&&"number"==typeof e.fixedSize}function Hf(e){return 1!==e?.endian}function qf(e){return t={fixedSize:e.size,write(t,n,r){e.range&&function(e,t,n,r){if(r<t||r>n)throw new Gf(af,{codecDescription:e,max:n,min:t,value:r})}(e.name,e.range[0],e.range[1],t);const s=new ArrayBuffer(e.size);return e.set(new DataView(s),t,Hf(e.config)),n.set(new Uint8Array(s),r),r+e.size}},Object.freeze({...t,encode:e=>{const n=new Uint8Array(function(e,t){return"fixedSize"in t?t.fixedSize:t.getSizeFromValue(e)}(e,t));return t.write(e,n,0),n}});var t}function zf(e){return t={fixedSize:e.size,read(t,n=0){!function(e,t,n=0){if(t.length-n<=0)throw new Gf(Xg,{codecDescription:e})}(e.name,t,n),function(e,t,n,r=0){const s=n.length-r;if(s<t)throw new Gf(Yg,{bytesLength:s,codecDescription:e,expected:t})}(e.name,e.size,t,n);const r=new DataView(function(e,t,n){const r=e.byteOffset+(t??0),s=n??e.byteLength;let i;return"undefined"==typeof SharedArrayBuffer?i=e.buffer:e.buffer instanceof SharedArrayBuffer?(i=new ArrayBuffer(e.length),new Uint8Array(i).set(new Uint8Array(e))):i=e.buffer,0!==r&&r!==-e.byteLength||s!==e.byteLength?i.slice(r,r+s):i}(t,n,e.size));return[e.get(r,Hf(e.config)),n+e.size]}},Object.freeze({...t,decode:(e,n=0)=>t.read(e,n)[0]});var t}var Vf=(e={})=>function(e,t){if(Wf(e)!==Wf(t))throw new Gf(Zg);if(Wf(e)&&Wf(t)&&e.fixedSize!==t.fixedSize)throw new Gf(ef,{decoderFixedSize:t.fixedSize,encoderFixedSize:e.fixedSize});if(!Wf(e)&&!Wf(t)&&e.maxSize!==t.maxSize)throw new Gf(tf,{decoderMaxSize:t.maxSize,encoderMaxSize:e.maxSize});return{...t,...e,decode:t.decode,encode:e.encode,read:t.read,write:e.write}}(((e={})=>qf({config:e,name:"u64",range:[0n,BigInt("0xffffffffffffffff")],set:(e,t,n)=>e.setBigUint64(0,BigInt(t),n),size:8}))(e),((e={})=>zf({config:e,get:(e,t)=>e.getBigUint64(0,t),name:"u64",size:8}))(e));class jf extends TypeError{constructor(e,t){let n;const{message:r,explanation:s,...i}=e,{path:o}=e,a=0===o.length?r:`At path: ${o.join(".")} -- ${r}`;super(s??a),null!=s&&(this.cause=a),Object.assign(this,i),this.name=this.constructor.name,this.failures=()=>n??(n=[e,...t()])}}function Xf(e){return"object"==typeof e&&null!=e}function Yf(e){return Xf(e)&&!Array.isArray(e)}function Jf(e){return"symbol"==typeof e?e.toString():"string"==typeof e?JSON.stringify(e):`${e}`}function Qf(e,t,n,r){if(!0===e)return;!1===e?e={}:"string"==typeof e&&(e={message:e});const{path:s,branch:i}=t,{type:o}=n,{refinement:a,message:c=`Expected a value of type \`${o}\`${a?` with refinement \`${a}\``:""}, but received: \`${Jf(r)}\``}=e;return{value:r,type:o,refinement:a,key:s[s.length-1],path:s,branch:i,...e,message:c}}function*Zf(e,t,n,r){var s;Xf(s=e)&&"function"==typeof s[Symbol.iterator]||(e=[e]);for(const s of e){const e=Qf(s,t,n,r);e&&(yield e)}}function*ep(e,t,n={}){const{path:r=[],branch:s=[e],coerce:i=!1,mask:o=!1}=n,a={path:r,branch:s,mask:o};i&&(e=t.coercer(e,a));let c="valid";for(const r of t.validator(e,a))r.explanation=n.message,c="not_valid",yield[r,void 0];for(let[l,u,d]of t.entries(e,a)){const t=ep(u,d,{path:void 0===l?r:[...r,l],branch:void 0===l?s:[...s,u],coerce:i,mask:o,message:n.message});for(const n of t)n[0]?(c=null!=n[0].refinement?"not_refined":"not_valid",yield[n[0],void 0]):i&&(u=n[1],void 0===l?e=u:e instanceof Map?e.set(l,u):e instanceof Set?e.add(u):Xf(e)&&(void 0!==u||l in e)&&(e[l]=u))}if("not_valid"!==c)for(const r of t.refiner(e,a))r.explanation=n.message,c="not_refined",yield[r,void 0];"valid"===c&&(yield[void 0,e])}let tp=class{constructor(e){const{type:t,schema:n,validator:r,refiner:s,coercer:i=e=>e,entries:o=function*(){}}=e;this.type=t,this.schema=n,this.entries=o,this.coercer=i,this.validator=r?(e,t)=>Zf(r(e,t),t,this,e):()=>[],this.refiner=s?(e,t)=>Zf(s(e,t),t,this,e):()=>[]}assert(e,t){return function(e,t,n){const r=sp(e,t,{message:n});if(r[0])throw r[0]}(e,this,t)}create(e,t){return np(e,this,t)}is(e){return rp(e,this)}mask(e,t){return function(e,t,n){const r=sp(e,t,{coerce:!0,mask:!0,message:n});if(r[0])throw r[0];return r[1]}(e,this,t)}validate(e,t={}){return sp(e,this,t)}};function np(e,t,n){const r=sp(e,t,{coerce:!0,message:n});if(r[0])throw r[0];return r[1]}function rp(e,t){return!sp(e,t)[0]}function sp(e,t,n={}){const r=ep(e,t,n),s=function(e){const{done:t,value:n}=e.next();return t?void 0:n}(r);if(s[0]){return[new jf(s[0],function*(){for(const e of r)e[0]&&(yield e[0])}),void 0]}return[void 0,s[1]]}function ip(e,t){return new tp({type:e,schema:null,validator:t})}function op(e){return new tp({type:"array",schema:e,*entries(t){if(e&&Array.isArray(t))for(const[n,r]of t.entries())yield[n,r,e]},coercer:e=>Array.isArray(e)?e.slice():e,validator:e=>Array.isArray(e)||`Expected an array value, but received: ${Jf(e)}`})}function ap(){return ip("boolean",e=>"boolean"==typeof e)}function cp(e){return ip("instance",t=>t instanceof e||`Expected a \`${e.name}\` instance, but received: ${Jf(t)}`)}function lp(e){const t=Jf(e),n=typeof e;return new tp({type:"literal",schema:"string"===n||"number"===n||"boolean"===n?e:null,validator:n=>n===e||`Expected the literal \`${t}\`, but received: ${Jf(n)}`})}function up(e){return new tp({...e,validator:(t,n)=>null===t||e.validator(t,n),refiner:(t,n)=>null===t||e.refiner(t,n)})}function dp(){return ip("number",e=>"number"==typeof e&&!isNaN(e)||`Expected a number, but received: ${Jf(e)}`)}function hp(e){return new tp({...e,validator:(t,n)=>void 0===t||e.validator(t,n),refiner:(t,n)=>void 0===t||e.refiner(t,n)})}function gp(e,t){return new tp({type:"record",schema:null,*entries(n){if(Xf(n))for(const r in n){const s=n[r];yield[r,r,e],yield[r,s,t]}},validator:e=>Yf(e)||`Expected an object, but received: ${Jf(e)}`,coercer:e=>Yf(e)?{...e}:e})}function fp(){return ip("string",e=>"string"==typeof e||`Expected a string, but received: ${Jf(e)}`)}function pp(e){const t=ip("never",()=>!1);return new tp({type:"tuple",schema:null,*entries(n){if(Array.isArray(n)){const r=Math.max(e.length,n.length);for(let s=0;s<r;s++)yield[s,n[s],e[s]||t]}},validator:e=>Array.isArray(e)||`Expected an array, but received: ${Jf(e)}`,coercer:e=>Array.isArray(e)?e.slice():e})}function mp(e){const t=Object.keys(e);return new tp({type:"type",schema:e,*entries(n){if(Xf(n))for(const r of t)yield[r,n[r],e[r]]},validator:e=>Yf(e)||`Expected an object, but received: ${Jf(e)}`,coercer:e=>Yf(e)?{...e}:e})}function yp(e){const t=e.map(e=>e.type).join(" | ");return new tp({type:"union",schema:null,coercer(t,n){for(const r of e){const[e,s]=r.validate(t,{coerce:!0,mask:n.mask});if(!e)return s}return t},validator(n,r){const s=[];for(const t of e){const[...e]=ep(n,t,r),[i]=e;if(!i[0])return[];for(const[t]of e)t&&s.push(t)}return[`Expected the value to satisfy a union of \`${t}\`, but received: ${Jf(n)}`,...s]}})}function bp(){return ip("unknown",()=>!0)}function vp(e,t,n){return new tp({...e,coercer:(r,s)=>rp(r,t)?e.coercer(n(r,s),s):e.coercer(r,s)})}var wp,Ep,Ap,Sp,kp=ko(g);function Tp(){if(Ep)return wp;Ep=1;const e=kp.v4;return wp=function(t,n,r,s){if("string"!=typeof t)throw new TypeError(t+" must be a string");const i="number"==typeof(s=s||{}).version?s.version:2;if(1!==i&&2!==i)throw new TypeError(i+" must be 1 or 2");const o={method:t};if(2===i&&(o.jsonrpc="2.0"),n){if("object"!=typeof n&&!Array.isArray(n))throw new TypeError(n+" must be an object, array or omitted");o.params=n}if(void 0===r){const t="function"==typeof s.generator?s.generator:function(){return e()};o.id=t(o,s)}else 2===i&&null===r?s.notificationIdNull&&(o.id=null):o.id=r;return o}}function Ip(){if(Sp)return Ap;Sp=1;const e=kp.v4,t=Tp(),n=function(t,r){if(!(this instanceof n))return new n(t,r);r||(r={}),this.options={reviver:void 0!==r.reviver?r.reviver:null,replacer:void 0!==r.replacer?r.replacer:null,generator:void 0!==r.generator?r.generator:function(){return e()},version:void 0!==r.version?r.version:2,notificationIdNull:"boolean"==typeof r.notificationIdNull&&r.notificationIdNull},this.callServer=t};return Ap=n,n.prototype.request=function(e,n,r,s){const i=this;let o=null;const a=Array.isArray(e)&&"function"==typeof n;if(1===this.options.version&&a)throw new TypeError("JSON-RPC 1.0 does not support batching");if(a||!a&&e&&"object"==typeof e&&"function"==typeof n)s=n,o=e;else{"function"==typeof r&&(s=r,r=void 0);const i="function"==typeof s;try{o=t(e,n,r,{generator:this.options.generator,version:this.options.version,notificationIdNull:this.options.notificationIdNull})}catch(e){if(i)return void s(e);throw e}if(!i)return o}let c;try{c=JSON.stringify(o,this.options.replacer)}catch(e){return void s(e)}return this.callServer(c,function(e,t){i._parseResponse(e,t,s)}),o},n.prototype._parseResponse=function(e,t,n){if(e)return void n(e);if(!t)return void n();let r;try{r=JSON.parse(t,this.options.reviver)}catch(e){return void n(e)}if(3!==n.length)n(null,r);else{if(Array.isArray(r)){const e=function(e){return void 0!==e.error},t=function(t){return!e(t)};return void n(null,r.filter(e),r.filter(t))}n(null,r.error,r.result)}},Ap}var Np,Cp=So(Ip()),_p={exports:{}};function xp(){return Np||(Np=1,function(e){var t=Object.prototype.hasOwnProperty,n="~";function r(){}function s(e,t,n){this.fn=e,this.context=t,this.once=n||!1}function i(e,t,r,i,o){if("function"!=typeof r)throw new TypeError("The listener must be a function");var a=new s(r,i||e,o),c=n?n+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],a]:e._events[c].push(a):(e._events[c]=a,e._eventsCount++),e}function o(e,t){0===--e._eventsCount?e._events=new r:delete e._events[t]}function a(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=Object.create(null),(new r).__proto__||(n=!1)),a.prototype.eventNames=function(){var e,r,s=[];if(0===this._eventsCount)return s;for(r in e=this._events)t.call(e,r)&&s.push(n?r.slice(1):r);return Object.getOwnPropertySymbols?s.concat(Object.getOwnPropertySymbols(e)):s},a.prototype.listeners=function(e){var t=n?n+e:e,r=this._events[t];if(!r)return[];if(r.fn)return[r.fn];for(var s=0,i=r.length,o=new Array(i);s<i;s++)o[s]=r[s].fn;return o},a.prototype.listenerCount=function(e){var t=n?n+e:e,r=this._events[t];return r?r.fn?1:r.length:0},a.prototype.emit=function(e,t,r,s,i,o){var a=n?n+e:e;if(!this._events[a])return!1;var c,l,u=this._events[a],d=arguments.length;if(u.fn){switch(u.once&&this.removeListener(e,u.fn,void 0,!0),d){case 1:return u.fn.call(u.context),!0;case 2:return u.fn.call(u.context,t),!0;case 3:return u.fn.call(u.context,t,r),!0;case 4:return u.fn.call(u.context,t,r,s),!0;case 5:return u.fn.call(u.context,t,r,s,i),!0;case 6:return u.fn.call(u.context,t,r,s,i,o),!0}for(l=1,c=new Array(d-1);l<d;l++)c[l-1]=arguments[l];u.fn.apply(u.context,c)}else{var h,g=u.length;for(l=0;l<g;l++)switch(u[l].once&&this.removeListener(e,u[l].fn,void 0,!0),d){case 1:u[l].fn.call(u[l].context);break;case 2:u[l].fn.call(u[l].context,t);break;case 3:u[l].fn.call(u[l].context,t,r);break;case 4:u[l].fn.call(u[l].context,t,r,s);break;default:if(!c)for(h=1,c=new Array(d-1);h<d;h++)c[h-1]=arguments[h];u[l].fn.apply(u[l].context,c)}}return!0},a.prototype.on=function(e,t,n){return i(this,e,t,n,!1)},a.prototype.once=function(e,t,n){return i(this,e,t,n,!0)},a.prototype.removeListener=function(e,t,r,s){var i=n?n+e:e;if(!this._events[i])return this;if(!t)return o(this,i),this;var a=this._events[i];if(a.fn)a.fn!==t||s&&!a.once||r&&a.context!==r||o(this,i);else{for(var c=0,l=[],u=a.length;c<u;c++)(a[c].fn!==t||s&&!a[c].once||r&&a[c].context!==r)&&l.push(a[c]);l.length?this._events[i]=1===l.length?l[0]:l:o(this,i)}return this},a.prototype.removeAllListeners=function(e){var t;return e?(t=n?n+e:e,this._events[t]&&o(this,t)):(this._events=new r,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=n,a.EventEmitter=a,e.exports=a}(_p)),_p.exports}var Rp=So(xp()),Bp=class extends Rp{socket;constructor(e,t){super(),this.socket=new window.WebSocket(e,t.protocols),this.socket.onopen=()=>this.emit("open"),this.socket.onmessage=e=>this.emit("message",e.data),this.socket.onerror=e=>this.emit("error",e),this.socket.onclose=e=>{this.emit("close",e.code,e.reason)}}send(e,t,n){const r=n||t;try{this.socket.send(e),r()}catch(e){r(e)}}close(e,t){this.socket.close(e,t)}addEventListener(e,t,n){this.socket.addEventListener(e,t,n)}};var Dp=class{encode(e){return JSON.stringify(e)}decode(e){return JSON.parse(e)}},Op=class extends Rp{address;rpc_id;queue;options;autoconnect;ready;reconnect;reconnect_timer_id;reconnect_interval;max_reconnects;rest_options;current_reconnects;generate_request_id;socket;webSocketFactory;dataPack;constructor(e,t="ws://localhost:8080",{autoconnect:n=!0,reconnect:r=!0,reconnect_interval:s=1e3,max_reconnects:i=5,...o}={},a,c){super(),this.webSocketFactory=e,this.queue={},this.rpc_id=0,this.address=t,this.autoconnect=n,this.ready=!1,this.reconnect=r,this.reconnect_timer_id=void 0,this.reconnect_interval=s,this.max_reconnects=i,this.rest_options=o,this.current_reconnects=0,this.generate_request_id=a||(()=>"number"==typeof this.rpc_id?++this.rpc_id:Number(this.rpc_id)+1),this.dataPack=c||new Dp,this.autoconnect&&this._connect(this.address,{autoconnect:this.autoconnect,reconnect:this.reconnect,reconnect_interval:this.reconnect_interval,max_reconnects:this.max_reconnects,...this.rest_options})}connect(){this.socket||this._connect(this.address,{autoconnect:this.autoconnect,reconnect:this.reconnect,reconnect_interval:this.reconnect_interval,max_reconnects:this.max_reconnects,...this.rest_options})}call(e,t,n,r){return r||"object"!=typeof n||(r=n,n=null),new Promise((s,i)=>{if(!this.ready)return i(new Error("socket not ready"));const o=this.generate_request_id(e,t),a={jsonrpc:"2.0",method:e,params:t||void 0,id:o};this.socket.send(this.dataPack.encode(a),r,e=>{if(e)return i(e);this.queue[o]={promise:[s,i]},n&&(this.queue[o].timeout=setTimeout(()=>{delete this.queue[o],i(new Error("reply timeout"))},n))})})}async login(e){const t=await this.call("rpc.login",e);if(!t)throw new Error("authentication failed");return t}async listMethods(){return await this.call("__listMethods")}notify(e,t){return new Promise((n,r)=>{if(!this.ready)return r(new Error("socket not ready"));const s={jsonrpc:"2.0",method:e,params:t};this.socket.send(this.dataPack.encode(s),e=>{if(e)return r(e);n()})})}async subscribe(e){"string"==typeof e&&(e=[e]);const t=await this.call("rpc.on",e);if("string"==typeof e&&"ok"!==t[e])throw new Error("Failed subscribing to an event '"+e+"' with: "+t[e]);return t}async unsubscribe(e){"string"==typeof e&&(e=[e]);const t=await this.call("rpc.off",e);if("string"==typeof e&&"ok"!==t[e])throw new Error("Failed unsubscribing from an event with: "+t);return t}close(e,t){this.socket&&this.socket.close(e||1e3,t)}setAutoReconnect(e){this.reconnect=e}setReconnectInterval(e){this.reconnect_interval=e}setMaxReconnects(e){this.max_reconnects=e}getCurrentReconnects(){return this.current_reconnects}getMaxReconnects(){return this.max_reconnects}isReconnecting(){return void 0!==this.reconnect_timer_id}willReconnect(){return this.reconnect&&(0===this.max_reconnects||this.current_reconnects<this.max_reconnects)}_connect(e,t){clearTimeout(this.reconnect_timer_id),this.socket=this.webSocketFactory(e,t),this.socket.addEventListener("open",()=>{this.ready=!0,this.emit("open"),this.current_reconnects=0}),this.socket.addEventListener("message",({data:e})=>{e instanceof ArrayBuffer&&(e=Oo.Buffer.from(e).toString());try{e=this.dataPack.decode(e)}catch(e){return}if(e.notification&&this.listeners(e.notification).length){if(!Object.keys(e.params).length)return this.emit(e.notification);const t=[e.notification];if(e.params.constructor===Object)t.push(e.params);else for(let n=0;n<e.params.length;n++)t.push(e.params[n]);return Promise.resolve().then(()=>{this.emit.apply(this,t)})}if(!this.queue[e.id])return e.method?Promise.resolve().then(()=>{this.emit(e.method,e?.params)}):void 0;"error"in e=="result"in e&&this.queue[e.id].promise[1](new Error('Server response malformed. Response must include either "result" or "error", but not both.')),this.queue[e.id].timeout&&clearTimeout(this.queue[e.id].timeout),e.error?this.queue[e.id].promise[1](e.error):this.queue[e.id].promise[0](e.result),delete this.queue[e.id]}),this.socket.addEventListener("error",e=>this.emit("error",e)),this.socket.addEventListener("close",({code:n,reason:r})=>{this.ready&&setTimeout(()=>this.emit("close",n,r),0),this.ready=!1,this.socket=void 0,1e3!==n&&(this.current_reconnects++,this.reconnect&&(this.max_reconnects>this.current_reconnects||0===this.max_reconnects)?this.reconnect_timer_id=setTimeout(()=>this._connect(e,t),this.reconnect_interval):this.reconnect&&this.max_reconnects>0&&this.current_reconnects>=this.max_reconnects&&setTimeout(()=>this.emit("max_reconnects_reached",n,r),1))})}};class Mp extends ra{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,Fo(e);const n=ta(t);if(this.iHash=e.create(),"function"!=typeof this.iHash.update)throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const r=this.blockLen,s=new Uint8Array(r);s.set(n.length>r?e.create().update(n).digest():n);for(let e=0;e<s.length;e++)s[e]^=54;this.iHash.update(s),this.oHash=e.create();for(let e=0;e<s.length;e++)s[e]^=106;this.oHash.update(s),Ko(s)}update(e){return $o(this),this.iHash.update(e),this}digestInto(e){$o(this),Po(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:t,iHash:n,finished:r,destroyed:s,blockLen:i,outputLen:o}=this;return e.finished=r,e.destroyed=s,e.blockLen=i,e.outputLen=o,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Lp=(e,t,n)=>new Mp(e,t).update(n).digest();Lp.create=(e,t)=>new Mp(e,t);const Up=(e,t)=>(e+(e>=0?t:-t)/Hp)/t;function Pp(e){if(!["compact","recovered","der"].includes(e))throw new Error('Signature format must be "compact", "recovered", or "der"');return e}function Fp(e,t){const n={};for(let r of Object.keys(t))n[r]=void 0===e[r]?t[r]:e[r];return $a(n.lowS,"lowS"),$a(n.prehash,"prehash"),void 0!==n.format&&Pp(n.format),n}class $p extends Error{constructor(e=""){super(e)}}const Kp={Err:$p,_tlv:{encode:(e,t)=>{const{Err:n}=Kp;if(e<0||e>256)throw new n("tlv.encode: wrong tag");if(1&t.length)throw new n("tlv.encode: unpadded data");const r=t.length/2,s=Ga(r);if(s.length/2&128)throw new n("tlv.encode: long form length too big");const i=r>127?Ga(s.length/2|128):"";return Ga(e)+i+s+t},decode(e,t){const{Err:n}=Kp;let r=0;if(e<0||e>256)throw new n("tlv.encode: wrong tag");if(t.length<2||t[r++]!==e)throw new n("tlv.decode: wrong tlv");const s=t[r++];let i=0;if(!!(128&s)){const e=127&s;if(!e)throw new n("tlv.decode(long): indefinite length not supported");if(e>4)throw new n("tlv.decode(long): byte length is too big");const o=t.subarray(r,r+e);if(o.length!==e)throw new n("tlv.decode: length bytes not complete");if(0===o[0])throw new n("tlv.decode(long): zero leftmost byte");for(const e of o)i=i<<8|e;if(r+=e,i<128)throw new n("tlv.decode(long): not minimal encoding")}else i=s;const o=t.subarray(r,r+i);if(o.length!==i)throw new n("tlv.decode: wrong value length");return{v:o,l:t.subarray(r+i)}}},_int:{encode(e){const{Err:t}=Kp;if(e<Gp)throw new t("integer: negative integers are not allowed");let n=Ga(e);if(8&Number.parseInt(n[0],16)&&(n="00"+n),1&n.length)throw new t("unexpected DER parsing assertion: unpadded hex");return n},decode(e){const{Err:t}=Kp;if(128&e[0])throw new t("invalid signature integer: negative");if(0===e[0]&&!(128&e[1]))throw new t("invalid signature integer: unnecessary leading zero");return Ha(e)}},toSig(e){const{Err:t,_int:n,_tlv:r}=Kp,s=ja("signature",e),{v:i,l:o}=r.decode(48,s);if(o.length)throw new t("invalid signature: left bytes after parsing");const{v:a,l:c}=r.decode(2,i),{v:l,l:u}=r.decode(2,c);if(u.length)throw new t("invalid signature: left bytes after parsing");return{r:n.decode(a),s:n.decode(l)}},hexFromSig(e){const{_tlv:t,_int:n}=Kp,r=t.encode(2,n.encode(e.r))+t.encode(2,n.encode(e.s));return t.encode(48,r)}},Gp=BigInt(0),Wp=BigInt(1),Hp=BigInt(2),qp=BigInt(3),zp=BigInt(4);function Vp(e,t){const{BYTES:n}=e;let r;if("bigint"==typeof t)r=t;else{let s=ja("private key",t);try{r=e.fromBytes(s)}catch(e){throw new Error(`invalid private key: expected ui8a of size ${n}, got ${typeof t}`)}}if(!e.isValidNot0(r))throw new Error("invalid private key: out of range [1..N-1]");return r}function jp(e,t={}){const n=Kc("weierstrass",e,t),{Fp:r,Fn:s}=n;let i=n.CURVE;const{h:o,n:a}=i;ec(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:c}=t;if(c&&(!r.is0(i.a)||"bigint"!=typeof c.beta||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const l=Yp(r,s);function u(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}const d=t.toBytes||function(e,t,n){const{x:s,y:i}=t.toAffine(),o=r.toBytes(s);if($a(n,"isCompressed"),n){u();return na(Xp(!r.isOdd(i)),o)}return na(Uint8Array.of(4),o,r.toBytes(i))},h=t.fromBytes||function(e){Ka(e,void 0,"Point");const{publicKey:t,publicKeyUncompressed:n}=l,s=e.length,i=e[0],o=e.subarray(1);if(s!==t||2!==i&&3!==i){if(s===n&&4===i){const e=r.BYTES,t=r.fromBytes(o.subarray(0,e)),n=r.fromBytes(o.subarray(e,2*e));if(!f(t,n))throw new Error("bad point: is not on curve");return{x:t,y:n}}throw new Error(`bad point: got length ${s}, expected compressed=${t} or uncompressed=${n}`)}{const e=r.fromBytes(o);if(!r.isValid(e))throw new Error("bad point: is not on curve, wrong x");const t=g(e);let n;try{n=r.sqrt(t)}catch(e){const t=e instanceof Error?": "+e.message:"";throw new Error("bad point: is not on curve, sqrt error"+t)}u();return!(1&~i)!==r.isOdd(n)&&(n=r.neg(n)),{x:e,y:n}}};function g(e){const t=r.sqr(e),n=r.mul(t,e);return r.add(r.add(n,r.mul(e,i.a)),i.b)}function f(e,t){const n=r.sqr(t),s=g(e);return r.eql(n,s)}if(!f(i.Gx,i.Gy))throw new Error("bad curve params: generator point");const p=r.mul(r.pow(i.a,qp),zp),m=r.mul(r.sqr(i.b),BigInt(27));if(r.is0(r.add(p,m)))throw new Error("bad curve params: a or b");function y(e,t,n=!1){if(!r.isValid(t)||n&&r.is0(t))throw new Error(`bad point coordinate ${e}`);return t}function b(e){if(!(e instanceof S))throw new Error("ProjectivePoint expected")}function v(e){if(!c||!c.basises)throw new Error("no endo");return function(e,t,n){const[[r,s],[i,o]]=t,a=Up(o*e,n),c=Up(-s*e,n);let l=e-a*r-c*i,u=-a*s-c*o;const d=l<Gp,h=u<Gp;d&&(l=-l),h&&(u=-u);const g=Za(Math.ceil(Qa(n)/2))+Wp;if(l<Gp||l>=g||u<Gp||u>=g)throw new Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:d,k1:l,k2neg:h,k2:u}}(e,c.basises,s.ORDER)}const w=tc((e,t)=>{const{X:n,Y:s,Z:i}=e;if(r.eql(i,r.ONE))return{x:n,y:s};const o=e.is0();null==t&&(t=o?r.ONE:r.inv(i));const a=r.mul(n,t),c=r.mul(s,t),l=r.mul(i,t);if(o)return{x:r.ZERO,y:r.ZERO};if(!r.eql(l,r.ONE))throw new Error("invZ was invalid");return{x:a,y:c}}),E=tc(e=>{if(e.is0()){if(t.allowInfinityPoint&&!r.is0(e.Y))return;throw new Error("bad point: ZERO")}const{x:n,y:s}=e.toAffine();if(!r.isValid(n)||!r.isValid(s))throw new Error("bad point: x or y not field elements");if(!f(n,s))throw new Error("bad point: equation left != right");if(!e.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function A(e,t,n,s,i){return n=new S(r.mul(n.X,e),n.Y,n.Z),t=_c(s,t),n=_c(i,n),t.add(n)}class S{constructor(e,t,n){this.X=y("x",e),this.Y=y("y",t,!0),this.Z=y("z",n),Object.freeze(this)}static CURVE(){return i}static fromAffine(e){const{x:t,y:n}=e||{};if(!e||!r.isValid(t)||!r.isValid(n))throw new Error("invalid affine point");if(e instanceof S)throw new Error("projective point not allowed");return r.is0(t)&&r.is0(n)?S.ZERO:new S(t,n,r.ONE)}static fromBytes(e){const t=S.fromAffine(h(Ka(e,void 0,"point")));return t.assertValidity(),t}static fromHex(e){return S.fromBytes(ja("pointHex",e))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(e=8,t=!0){return T.createCache(this,e),t||this.multiply(qp),this}assertValidity(){E(this)}hasEvenY(){const{y:e}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(e)}equals(e){b(e);const{X:t,Y:n,Z:s}=this,{X:i,Y:o,Z:a}=e,c=r.eql(r.mul(t,a),r.mul(i,s)),l=r.eql(r.mul(n,a),r.mul(o,s));return c&&l}negate(){return new S(this.X,r.neg(this.Y),this.Z)}double(){const{a:e,b:t}=i,n=r.mul(t,qp),{X:s,Y:o,Z:a}=this;let c=r.ZERO,l=r.ZERO,u=r.ZERO,d=r.mul(s,s),h=r.mul(o,o),g=r.mul(a,a),f=r.mul(s,o);return f=r.add(f,f),u=r.mul(s,a),u=r.add(u,u),c=r.mul(e,u),l=r.mul(n,g),l=r.add(c,l),c=r.sub(h,l),l=r.add(h,l),l=r.mul(c,l),c=r.mul(f,c),u=r.mul(n,u),g=r.mul(e,g),f=r.sub(d,g),f=r.mul(e,f),f=r.add(f,u),u=r.add(d,d),d=r.add(u,d),d=r.add(d,g),d=r.mul(d,f),l=r.add(l,d),g=r.mul(o,a),g=r.add(g,g),d=r.mul(g,f),c=r.sub(c,d),u=r.mul(g,h),u=r.add(u,u),u=r.add(u,u),new S(c,l,u)}add(e){b(e);const{X:t,Y:n,Z:s}=this,{X:o,Y:a,Z:c}=e;let l=r.ZERO,u=r.ZERO,d=r.ZERO;const h=i.a,g=r.mul(i.b,qp);let f=r.mul(t,o),p=r.mul(n,a),m=r.mul(s,c),y=r.add(t,n),v=r.add(o,a);y=r.mul(y,v),v=r.add(f,p),y=r.sub(y,v),v=r.add(t,s);let w=r.add(o,c);return v=r.mul(v,w),w=r.add(f,m),v=r.sub(v,w),w=r.add(n,s),l=r.add(a,c),w=r.mul(w,l),l=r.add(p,m),w=r.sub(w,l),d=r.mul(h,v),l=r.mul(g,m),d=r.add(l,d),l=r.sub(p,d),d=r.add(p,d),u=r.mul(l,d),p=r.add(f,f),p=r.add(p,f),m=r.mul(h,m),v=r.mul(g,v),p=r.add(p,m),m=r.sub(f,m),m=r.mul(h,m),v=r.add(v,m),f=r.mul(p,v),u=r.add(u,f),f=r.mul(w,v),l=r.mul(y,l),l=r.sub(l,f),f=r.mul(y,p),d=r.mul(w,d),d=r.add(d,f),new S(l,u,d)}subtract(e){return this.add(e.negate())}is0(){return this.equals(S.ZERO)}multiply(e){const{endo:n}=t;if(!s.isValidNot0(e))throw new Error("invalid scalar: out of range");let r,i;const o=e=>T.cached(this,e,e=>xc(S,e));if(n){const{k1neg:t,k1:s,k2neg:a,k2:c}=v(e),{p:l,f:u}=o(s),{p:d,f:h}=o(c);i=u.add(h),r=A(n.beta,l,d,t,a)}else{const{p:t,f:n}=o(e);r=t,i=n}return xc(S,[r,i])[0]}multiplyUnsafe(e){const{endo:n}=t,r=this;if(!s.isValid(e))throw new Error("invalid scalar: out of range");if(e===Gp||r.is0())return S.ZERO;if(e===Wp)return r;if(T.hasCache(this))return this.multiply(e);if(n){const{k1neg:t,k1:s,k2neg:i,k2:o}=v(e),{p1:a,p2:c}=function(e,t,n,r){let s=t,i=e.ZERO,o=e.ZERO;for(;n>Nc||r>Nc;)n&Cc&&(i=i.add(s)),r&Cc&&(o=o.add(s)),s=s.double(),n>>=Cc,r>>=Cc;return{p1:i,p2:o}}(S,r,s,o);return A(n.beta,a,c,t,i)}return T.unsafe(r,e)}multiplyAndAddUnsafe(e,t,n){const r=this.multiplyUnsafe(t).add(e.multiplyUnsafe(n));return r.is0()?void 0:r}toAffine(e){return w(this,e)}isTorsionFree(){const{isTorsionFree:e}=t;return o===Wp||(e?e(S,this):T.unsafe(this,a).is0())}clearCofactor(){const{clearCofactor:e}=t;return o===Wp?this:e?e(S,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(e=!0){return $a(e,"isCompressed"),this.assertValidity(),d(S,this,e)}toHex(e=!0){return zo(this.toBytes(e))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(e=!0){return this.toBytes(e)}_setWindowSize(e){this.precompute(e)}static normalizeZ(e){return xc(S,e)}static msm(e,t){return Fc(S,s,e,t)}static fromPrivateKey(e){return S.BASE.multiply(Vp(s,e))}}S.BASE=new S(i.Gx,i.Gy,r.ONE),S.ZERO=new S(r.ZERO,r.ONE,r.ZERO),S.Fp=r,S.Fn=s;const k=s.BITS,T=new Pc(S,t.endo?Math.ceil(k/2):k);return S.BASE.precompute(8),S}function Xp(e){return Uint8Array.of(e?2:3)}function Yp(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function Jp(e,t={}){const{Fn:n}=e,r=t.randomBytes||ia,s=Object.assign(Yp(e.Fp,n),{seed:Ic(n.ORDER)});function i(e){try{return!!Vp(n,e)}catch(e){return!1}}function o(e=r(s.seed)){return function(e,t,n=!1){const r=e.length,s=Tc(t),i=Ic(t);if(r<16||r<i||r>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+r);const o=hc(n?qa(e):Ha(e),t-rc)+rc;return n?Va(o,s):za(o,s)}(Ka(e,s.seed,"seed"),n.ORDER)}function a(t,r=!0){return e.BASE.multiply(Vp(n,t)).toBytes(r)}function c(t){if("bigint"==typeof t)return!1;if(t instanceof e)return!0;const{secretKey:r,publicKey:i,publicKeyUncompressed:o}=s;if(n.allowedLengths||r===i)return;const a=ja("key",t).length;return a===i||a===o}const l={isValidSecretKey:i,isValidPublicKey:function(t,n){const{publicKey:r,publicKeyUncompressed:i}=s;try{const s=t.length;return(!0!==n||s===r)&&((!1!==n||s===i)&&!!e.fromBytes(t))}catch(e){return!1}},randomSecretKey:o,isValidPrivateKey:i,randomPrivateKey:o,normPrivateKeyToScalar:e=>Vp(n,e),precompute:(t=8,n=e.BASE)=>n.precompute(t,!1)};return Object.freeze({getPublicKey:a,getSharedSecret:function(t,r,s=!0){if(!0===c(t))throw new Error("first arg must be private key");if(!1===c(r))throw new Error("second arg must be public key");const i=Vp(n,t);return e.fromHex(r).multiply(i).toBytes(s)},keygen:function(e){const t=o(e);return{secretKey:t,publicKey:a(t)}},Point:e,utils:l,lengths:s})}function Qp(e,t,n={}){Fo(t),ec(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const r=n.randomBytes||ia,s=n.hmac||((e,...n)=>Lp(t,e,na(...n))),{Fp:i,Fn:o}=e,{ORDER:a,BITS:c}=o,{keygen:l,getPublicKey:u,getSharedSecret:d,utils:h,lengths:g}=Jp(e,n),f={prehash:!1,lowS:"boolean"==typeof n.lowS&&n.lowS,format:void 0,extraEntropy:!1},p="compact";function m(e){return e>a>>Wp}function y(e,t){if(!o.isValidNot0(t))throw new Error(`invalid signature ${e}: out of range 1..Point.Fn.ORDER`);return t}class b{constructor(e,t,n){this.r=y("r",e),this.s=y("s",t),null!=n&&(this.recovery=n),Object.freeze(this)}static fromBytes(e,t=p){let n;if(function(e,t){Pp(t);const n=g.signature;Ka(e,"compact"===t?n:"recovered"===t?n+1:void 0,`${t} signature`)}(e,t),"der"===t){const{r:t,s:n}=Kp.toSig(Ka(e));return new b(t,n)}"recovered"===t&&(n=e[0],t="compact",e=e.subarray(1));const r=o.BYTES,s=e.subarray(0,r),i=e.subarray(r,2*r);return new b(o.fromBytes(s),o.fromBytes(i),n)}static fromHex(e,t){return this.fromBytes(ea(e),t)}addRecoveryBit(e){return new b(this.r,this.s,e)}recoverPublicKey(t){const n=i.ORDER,{r:r,s:s,recovery:c}=this;if(null==c||![0,1,2,3].includes(c))throw new Error("recovery id invalid");if(a*Hp<n&&c>1)throw new Error("recovery id is ambiguous for h>1 curve");const l=2===c||3===c?r+a:r;if(!i.isValid(l))throw new Error("recovery id 2 or 3 invalid");const u=i.toBytes(l),d=e.fromBytes(na(Xp(!(1&c)),u)),h=o.inv(l),g=w(ja("msgHash",t)),f=o.create(-g*h),p=o.create(s*h),m=e.BASE.multiplyUnsafe(f).add(d.multiplyUnsafe(p));if(m.is0())throw new Error("point at infinify");return m.assertValidity(),m}hasHighS(){return m(this.s)}toBytes(e=p){if(Pp(e),"der"===e)return ea(Kp.hexFromSig(this));const t=o.toBytes(this.r),n=o.toBytes(this.s);if("recovered"===e){if(null==this.recovery)throw new Error("recovery bit must be present");return na(Uint8Array.of(this.recovery),t,n)}return na(t,n)}toHex(e){return zo(this.toBytes(e))}assertValidity(){}static fromCompact(e){return b.fromBytes(ja("sig",e),"compact")}static fromDER(e){return b.fromBytes(ja("sig",e),"der")}normalizeS(){return this.hasHighS()?new b(this.r,o.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return zo(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return zo(this.toBytes("compact"))}}const v=n.bits2int||function(e){if(e.length>8192)throw new Error("input is too large");const t=Ha(e),n=8*e.length-c;return n>0?t>>BigInt(n):t},w=n.bits2int_modN||function(e){return o.create(v(e))},E=Za(c);function A(e){return Ja("num < 2^"+c,e,Gp,E),o.toBytes(e)}function S(e,n){return Ka(e,void 0,"message"),n?Ka(t(e),void 0,"prehashed message"):e}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:d,utils:h,lengths:g,Point:e,sign:function(n,i,a={}){n=ja("message",n);const{seed:c,k2sig:l}=function(t,n,s){if(["recovered","canonical"].some(e=>e in s))throw new Error("sign() legacy options not supported");const{lowS:i,prehash:a,extraEntropy:c}=Fp(s,f);t=S(t,a);const l=w(t),u=Vp(o,n),d=[A(u),A(l)];if(null!=c&&!1!==c){const e=!0===c?r(g.secretKey):c;d.push(ja("extraEntropy",e))}const h=na(...d),p=l;return{seed:h,k2sig:function(t){const n=v(t);if(!o.isValidNot0(n))return;const r=o.inv(n),s=e.BASE.multiply(n).toAffine(),a=o.create(s.x);if(a===Gp)return;const c=o.create(r*o.create(p+a*u));if(c===Gp)return;let l=(s.x===a?0:2)|Number(s.y&Wp),d=c;return i&&m(c)&&(d=o.neg(c),l^=1),new b(a,d,l)}}}(n,i,a);return function(e,t,n){if("number"!=typeof e||e<2)throw new Error("hashLen must be a number");if("number"!=typeof t||t<2)throw new Error("qByteLen must be a number");if("function"!=typeof n)throw new Error("hmacFn must be a function");const r=e=>new Uint8Array(e),s=e=>Uint8Array.of(e);let i=r(e),o=r(e),a=0;const c=()=>{i.fill(1),o.fill(0),a=0},l=(...e)=>n(o,i,...e),u=(e=r(0))=>{o=l(s(0),e),i=l(),0!==e.length&&(o=l(s(1),e),i=l())},d=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let e=0;const n=[];for(;e<t;){i=l();const t=i.slice();n.push(t),e+=i.length}return na(...n)};return(e,t)=>{let n;for(c(),u(e);!(n=t(d()));)u();return c(),n}}(t.outputLen,o.BYTES,s)(c,l)},verify:function(t,n,r,s={}){const{lowS:i,prehash:a,format:c}=Fp(s,f);if(r=ja("publicKey",r),n=S(ja("message",n),a),"strict"in s)throw new Error("options.strict was renamed to lowS");const l=void 0===c?function(e){let t;const n="string"==typeof e||Lo(e),r=!n&&null!==e&&"object"==typeof e&&"bigint"==typeof e.r&&"bigint"==typeof e.s;if(!n&&!r)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(r)t=new b(e.r,e.s);else if(n){try{t=b.fromBytes(ja("sig",e),"der")}catch(e){if(!(e instanceof Kp.Err))throw e}if(!t)try{t=b.fromBytes(ja("sig",e),"compact")}catch(e){return!1}}return t||!1}(t):b.fromBytes(ja("sig",t),c);if(!1===l)return!1;try{const t=e.fromBytes(r);if(i&&l.hasHighS())return!1;const{r:s,s:a}=l,c=w(n),u=o.inv(a),d=o.create(c*u),h=o.create(s*u),g=e.BASE.multiplyUnsafe(d).add(t.multiplyUnsafe(h));if(g.is0())return!1;return o.create(g.x)===s}catch(e){return!1}},recoverPublicKey:function(e,t,n={}){const{prehash:r}=Fp(n,f);return t=S(t,r),b.fromBytes(e,"recovered").recoverPublicKey(t).toBytes()},Signature:b,hash:t})}function Zp(e){const{CURVE:t,curveOpts:n}=function(e){const t={a:e.a,b:e.b,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},n=e.Fp;let r=e.allowedPrivateKeyLengths?Array.from(new Set(e.allowedPrivateKeyLengths.map(e=>Math.ceil(e/2)))):void 0;return{CURVE:t,curveOpts:{Fp:n,Fn:kc(t.n,{BITS:e.nBitLength,allowedLengths:r,modFromBytes:e.wrapPrivateKey}),allowInfinityPoint:e.allowInfinityPoint,endo:e.endo,isTorsionFree:e.isTorsionFree,clearCofactor:e.clearCofactor,fromBytes:e.fromBytes,toBytes:e.toBytes}}}(e),r={hmac:e.hmac,randomBytes:e.randomBytes,lowS:e.lowS,bits2int:e.bits2int,bits2int_modN:e.bits2int_modN};return{CURVE:t,curveOpts:n,hash:e.hash,ecdsaOpts:r}}function em(e){const{CURVE:t,curveOpts:n,hash:r,ecdsaOpts:s}=Zp(e);return function(e,t){const n=t.Point;return Object.assign({},t,{ProjectivePoint:n,CURVE:Object.assign({},e,Sc(n.Fn.ORDER,n.Fn.BITS))})}(e,Qp(jp(t,n),r,s))}const tm={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},nm={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},rm=BigInt(2);const sm=kc(tm.p,{sqrt:function(e){const t=tm.p,n=BigInt(3),r=BigInt(6),s=BigInt(11),i=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),l=e*e*e%t,u=l*l*e%t,d=gc(u,n,t)*u%t,h=gc(d,n,t)*u%t,g=gc(h,rm,t)*l%t,f=gc(g,s,t)*g%t,p=gc(f,i,t)*f%t,m=gc(p,a,t)*p%t,y=gc(m,c,t)*m%t,b=gc(y,a,t)*p%t,v=gc(b,n,t)*u%t,w=gc(v,o,t)*f%t,E=gc(w,r,t)*l%t,A=gc(E,rm,t);if(!sm.eql(sm.sqr(A),e))throw new Error("Cannot find square root");return A}}),im=function(e,t){const n=t=>em({...e,hash:t});return{...n(t),create:n}}({...tm,Fp:sm,lowS:!0,endo:nm},La);il.utils.randomPrivateKey;const om=()=>{const e=il.utils.randomPrivateKey(),t=am(e),n=new Uint8Array(64);return n.set(e),n.set(t,32),{publicKey:t,secretKey:n}},am=il.getPublicKey;function cm(e){try{return il.ExtendedPoint.fromHex(e),!0}catch{return!1}}const lm=il.verify,um=e=>Oo.Buffer.isBuffer(e)?e:e instanceof Uint8Array?Oo.Buffer.from(e.buffer,e.byteOffset,e.byteLength):Oo.Buffer.from(e);class dm{constructor(e){Object.assign(this,e)}encode(){return Oo.Buffer.from(Pl.serialize(hm,this))}static decode(e){return Pl.deserialize(hm,this,e)}static decodeUnchecked(e){return Pl.deserializeUnchecked(hm,this,e)}}const hm=new Map;var gm;const fm=32;let pm=1;class mm extends dm{constructor(e){if(super({}),this._bn=void 0,function(e){return void 0!==e._bn}(e))this._bn=e._bn;else{if("string"==typeof e){const t=El.decode(e);if(t.length!=fm)throw new Error("Invalid public key input");this._bn=new ml(t)}else this._bn=new ml(e);if(this._bn.byteLength()>fm)throw new Error("Invalid public key input")}}static unique(){const e=new mm(pm);return pm+=1,new mm(e.toBuffer())}equals(e){return this._bn.eq(e._bn)}toBase58(){return El.encode(this.toBytes())}toJSON(){return this.toBase58()}toBytes(){const e=this.toBuffer();return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}toBuffer(){const e=this._bn.toArrayLike(Oo.Buffer);if(e.length===fm)return e;const t=Oo.Buffer.alloc(32);return e.copy(t,32-e.length),t}get[Symbol.toStringTag](){return`PublicKey(${this.toString()})`}toString(){return this.toBase58()}static async createWithSeed(e,t,n){const r=Oo.Buffer.concat([e.toBuffer(),Oo.Buffer.from(t),n.toBuffer()]),s=Al(r);return new mm(s)}static createProgramAddressSync(e,t){let n=Oo.Buffer.alloc(0);e.forEach(function(e){if(e.length>32)throw new TypeError("Max seed length exceeded");n=Oo.Buffer.concat([n,um(e)])}),n=Oo.Buffer.concat([n,t.toBuffer(),Oo.Buffer.from("ProgramDerivedAddress")]);const r=Al(n);if(cm(r))throw new Error("Invalid seeds, address must fall off the curve");return new mm(r)}static async createProgramAddress(e,t){return this.createProgramAddressSync(e,t)}static findProgramAddressSync(e,t){let n,r=255;for(;0!=r;){try{const s=e.concat(Oo.Buffer.from([r]));n=this.createProgramAddressSync(s,t)}catch(e){if(e instanceof TypeError)throw e;r--;continue}return[n,r]}throw new Error("Unable to find a viable program address nonce")}static async findProgramAddress(e,t){return this.findProgramAddressSync(e,t)}static isOnCurve(e){return cm(new mm(e).toBytes())}}gm=mm,mm.default=new gm("11111111111111111111111111111111"),hm.set(mm,{kind:"struct",fields:[["_bn","u256"]]}),new mm("BPFLoader1111111111111111111111111111111111");const ym=1232;class bm extends Error{constructor(e){super(`Signature ${e} has expired: block height exceeded.`),this.signature=void 0,this.signature=e}}Object.defineProperty(bm.prototype,"name",{value:"TransactionExpiredBlockheightExceededError"});class vm extends Error{constructor(e,t){super(`Transaction was not confirmed in ${t.toFixed(2)} seconds. It is unknown if it succeeded or failed. Check signature ${e} using the Solana Explorer or CLI tools.`),this.signature=void 0,this.signature=e}}Object.defineProperty(vm.prototype,"name",{value:"TransactionExpiredTimeoutError"});class wm extends Error{constructor(e){super(`Signature ${e} has expired: the nonce is no longer valid.`),this.signature=void 0,this.signature=e}}Object.defineProperty(wm.prototype,"name",{value:"TransactionExpiredNonceInvalidError"});class Em{constructor(e,t){this.staticAccountKeys=void 0,this.accountKeysFromLookups=void 0,this.staticAccountKeys=e,this.accountKeysFromLookups=t}keySegments(){const e=[this.staticAccountKeys];return this.accountKeysFromLookups&&(e.push(this.accountKeysFromLookups.writable),e.push(this.accountKeysFromLookups.readonly)),e}get(e){for(const t of this.keySegments()){if(e<t.length)return t[e];e-=t.length}}get length(){return this.keySegments().flat().length}compileInstructions(e){if(this.length>256)throw new Error("Account index overflow encountered during compilation");const t=new Map;this.keySegments().flat().forEach((e,n)=>{t.set(e.toBase58(),n)});const n=e=>{const n=t.get(e.toBase58());if(void 0===n)throw new Error("Encountered an unknown instruction account key during compilation");return n};return e.map(e=>({programIdIndex:n(e.programId),accountKeyIndexes:e.keys.map(e=>n(e.pubkey)),data:e.data}))}}const Am=(e="publicKey")=>Kl.blob(32,e),Sm=(e="string")=>{const t=Kl.struct([Kl.u32("length"),Kl.u32("lengthPadding"),Kl.blob(Kl.offset(Kl.u32(),-8),"chars")],e),n=t.decode.bind(t),r=t.encode.bind(t),s=t;return s.decode=(e,t)=>n(e,t).chars.toString(),s.encode=(e,t,n)=>{const s={chars:Oo.Buffer.from(e,"utf8")};return r(s,t,n)},s.alloc=e=>Kl.u32().span+Kl.u32().span+Oo.Buffer.from(e,"utf8").length,s};function km(e,t){const n=e=>{if(e.span>=0)return e.span;if("function"==typeof e.alloc)return e.alloc(t[e.property]);if("count"in e&&"elementLayout"in e){const r=t[e.property];if(Array.isArray(r))return r.length*n(e.elementLayout)}else if("fields"in e)return km({layout:e},t[e.property]);return 0};let r=0;return e.layout.fields.forEach(e=>{r+=n(e)}),r}function Tm(e){let t=0,n=0;for(;;){let r=e.shift();if(t|=(127&r)<<7*n,n+=1,!(128&r))break}return t}function Im(e,t){let n=t;for(;;){let t=127&n;if(n>>=7,0==n){e.push(t);break}t|=128,e.push(t)}}function Nm(e,t){if(!e)throw new Error(t||"Assertion failed")}class Cm{constructor(e,t){this.payer=void 0,this.keyMetaMap=void 0,this.payer=e,this.keyMetaMap=t}static compile(e,t){const n=new Map,r=e=>{const t=e.toBase58();let r=n.get(t);return void 0===r&&(r={isSigner:!1,isWritable:!1,isInvoked:!1},n.set(t,r)),r},s=r(t);s.isSigner=!0,s.isWritable=!0;for(const t of e){r(t.programId).isInvoked=!0;for(const e of t.keys){const t=r(e.pubkey);t.isSigner||=e.isSigner,t.isWritable||=e.isWritable}}return new Cm(t,n)}getMessageComponents(){const e=[...this.keyMetaMap.entries()];Nm(e.length<=256,"Max static account keys length exceeded");const t=e.filter(([,e])=>e.isSigner&&e.isWritable),n=e.filter(([,e])=>e.isSigner&&!e.isWritable),r=e.filter(([,e])=>!e.isSigner&&e.isWritable),s=e.filter(([,e])=>!e.isSigner&&!e.isWritable),i={numRequiredSignatures:t.length+n.length,numReadonlySignedAccounts:n.length,numReadonlyUnsignedAccounts:s.length};{Nm(t.length>0,"Expected at least one writable signer key");const[e]=t[0];Nm(e===this.payer.toBase58(),"Expected first writable signer key to be the fee payer")}return[i,[...t.map(([e])=>new mm(e)),...n.map(([e])=>new mm(e)),...r.map(([e])=>new mm(e)),...s.map(([e])=>new mm(e))]]}extractTableLookup(e){const[t,n]=this.drainKeysFoundInLookupTable(e.state.addresses,e=>!e.isSigner&&!e.isInvoked&&e.isWritable),[r,s]=this.drainKeysFoundInLookupTable(e.state.addresses,e=>!e.isSigner&&!e.isInvoked&&!e.isWritable);if(0!==t.length||0!==r.length)return[{accountKey:e.key,writableIndexes:t,readonlyIndexes:r},{writable:n,readonly:s}]}drainKeysFoundInLookupTable(e,t){const n=new Array,r=new Array;for(const[s,i]of this.keyMetaMap.entries())if(t(i)){const t=new mm(s),i=e.findIndex(e=>e.equals(t));i>=0&&(Nm(i<256,"Max lookup table index exceeded"),n.push(i),r.push(t),this.keyMetaMap.delete(s))}return[n,r]}}const _m="Reached end of buffer unexpectedly";function xm(e){if(0===e.length)throw new Error(_m);return e.shift()}function Rm(e,...t){const[n]=t;if(2===t.length?n+(t[1]??0)>e.length:n>=e.length)throw new Error(_m);return e.splice(...t)}class Bm{constructor(e){this.header=void 0,this.accountKeys=void 0,this.recentBlockhash=void 0,this.instructions=void 0,this.indexToProgramIds=new Map,this.header=e.header,this.accountKeys=e.accountKeys.map(e=>new mm(e)),this.recentBlockhash=e.recentBlockhash,this.instructions=e.instructions,this.instructions.forEach(e=>this.indexToProgramIds.set(e.programIdIndex,this.accountKeys[e.programIdIndex]))}get version(){return"legacy"}get staticAccountKeys(){return this.accountKeys}get compiledInstructions(){return this.instructions.map(e=>({programIdIndex:e.programIdIndex,accountKeyIndexes:e.accounts,data:El.decode(e.data)}))}get addressTableLookups(){return[]}getAccountKeys(){return new Em(this.staticAccountKeys)}static compile(e){const t=Cm.compile(e.instructions,e.payerKey),[n,r]=t.getMessageComponents(),s=new Em(r).compileInstructions(e.instructions).map(e=>({programIdIndex:e.programIdIndex,accounts:e.accountKeyIndexes,data:El.encode(e.data)}));return new Bm({header:n,accountKeys:r,recentBlockhash:e.recentBlockhash,instructions:s})}isAccountSigner(e){return e<this.header.numRequiredSignatures}isAccountWritable(e){const t=this.header.numRequiredSignatures;if(e>=this.header.numRequiredSignatures){return e-t<this.accountKeys.length-t-this.header.numReadonlyUnsignedAccounts}return e<t-this.header.numReadonlySignedAccounts}isProgramId(e){return this.indexToProgramIds.has(e)}programIds(){return[...this.indexToProgramIds.values()]}nonProgramIds(){return this.accountKeys.filter((e,t)=>!this.isProgramId(t))}serialize(){const e=this.accountKeys.length;let t=[];Im(t,e);const n=this.instructions.map(e=>{const{accounts:t,programIdIndex:n}=e,r=Array.from(El.decode(e.data));let s=[];Im(s,t.length);let i=[];return Im(i,r.length),{programIdIndex:n,keyIndicesCount:Oo.Buffer.from(s),keyIndices:t,dataLength:Oo.Buffer.from(i),data:r}});let r=[];Im(r,n.length);let s=Oo.Buffer.alloc(ym);Oo.Buffer.from(r).copy(s);let i=r.length;n.forEach(e=>{const t=Kl.struct([Kl.u8("programIdIndex"),Kl.blob(e.keyIndicesCount.length,"keyIndicesCount"),Kl.seq(Kl.u8("keyIndex"),e.keyIndices.length,"keyIndices"),Kl.blob(e.dataLength.length,"dataLength"),Kl.seq(Kl.u8("userdatum"),e.data.length,"data")]).encode(e,s,i);i+=t}),s=s.slice(0,i);const o=Kl.struct([Kl.blob(1,"numRequiredSignatures"),Kl.blob(1,"numReadonlySignedAccounts"),Kl.blob(1,"numReadonlyUnsignedAccounts"),Kl.blob(t.length,"keyCount"),Kl.seq(Am("key"),e,"keys"),Am("recentBlockhash")]),a={numRequiredSignatures:Oo.Buffer.from([this.header.numRequiredSignatures]),numReadonlySignedAccounts:Oo.Buffer.from([this.header.numReadonlySignedAccounts]),numReadonlyUnsignedAccounts:Oo.Buffer.from([this.header.numReadonlyUnsignedAccounts]),keyCount:Oo.Buffer.from(t),keys:this.accountKeys.map(e=>um(e.toBytes())),recentBlockhash:El.decode(this.recentBlockhash)};let c=Oo.Buffer.alloc(2048);const l=o.encode(a,c);return s.copy(c,l),c.slice(0,l+s.length)}static from(e){let t=[...e];const n=xm(t);if(n!==(127&n))throw new Error("Versioned messages must be deserialized with VersionedMessage.deserialize()");const r=xm(t),s=xm(t),i=Tm(t);let o=[];for(let e=0;e<i;e++){const e=Rm(t,0,fm);o.push(new mm(Oo.Buffer.from(e)))}const a=Rm(t,0,fm),c=Tm(t);let l=[];for(let e=0;e<c;e++){const e=xm(t),n=Rm(t,0,Tm(t)),r=Rm(t,0,Tm(t)),s=El.encode(Oo.Buffer.from(r));l.push({programIdIndex:e,accounts:n,data:s})}const u={header:{numRequiredSignatures:n,numReadonlySignedAccounts:r,numReadonlyUnsignedAccounts:s},recentBlockhash:El.encode(Oo.Buffer.from(a)),accountKeys:o,instructions:l};return new Bm(u)}}class Dm{constructor(e){this.header=void 0,this.staticAccountKeys=void 0,this.recentBlockhash=void 0,this.compiledInstructions=void 0,this.addressTableLookups=void 0,this.header=e.header,this.staticAccountKeys=e.staticAccountKeys,this.recentBlockhash=e.recentBlockhash,this.compiledInstructions=e.compiledInstructions,this.addressTableLookups=e.addressTableLookups}get version(){return 0}get numAccountKeysFromLookups(){let e=0;for(const t of this.addressTableLookups)e+=t.readonlyIndexes.length+t.writableIndexes.length;return e}getAccountKeys(e){let t;if(e&&"accountKeysFromLookups"in e&&e.accountKeysFromLookups){if(this.numAccountKeysFromLookups!=e.accountKeysFromLookups.writable.length+e.accountKeysFromLookups.readonly.length)throw new Error("Failed to get account keys because of a mismatch in the number of account keys from lookups");t=e.accountKeysFromLookups}else if(e&&"addressLookupTableAccounts"in e&&e.addressLookupTableAccounts)t=this.resolveAddressTableLookups(e.addressLookupTableAccounts);else if(this.addressTableLookups.length>0)throw new Error("Failed to get account keys because address table lookups were not resolved");return new Em(this.staticAccountKeys,t)}isAccountSigner(e){return e<this.header.numRequiredSignatures}isAccountWritable(e){const t=this.header.numRequiredSignatures,n=this.staticAccountKeys.length;if(e>=n){return e-n<this.addressTableLookups.reduce((e,t)=>e+t.writableIndexes.length,0)}if(e>=this.header.numRequiredSignatures){return e-t<n-t-this.header.numReadonlyUnsignedAccounts}return e<t-this.header.numReadonlySignedAccounts}resolveAddressTableLookups(e){const t={writable:[],readonly:[]};for(const n of this.addressTableLookups){const r=e.find(e=>e.key.equals(n.accountKey));if(!r)throw new Error(`Failed to find address lookup table account for table key ${n.accountKey.toBase58()}`);for(const e of n.writableIndexes){if(!(e<r.state.addresses.length))throw new Error(`Failed to find address for index ${e} in address lookup table ${n.accountKey.toBase58()}`);t.writable.push(r.state.addresses[e])}for(const e of n.readonlyIndexes){if(!(e<r.state.addresses.length))throw new Error(`Failed to find address for index ${e} in address lookup table ${n.accountKey.toBase58()}`);t.readonly.push(r.state.addresses[e])}}return t}static compile(e){const t=Cm.compile(e.instructions,e.payerKey),n=new Array,r={writable:new Array,readonly:new Array},s=e.addressLookupTableAccounts||[];for(const e of s){const s=t.extractTableLookup(e);if(void 0!==s){const[e,{writable:t,readonly:i}]=s;n.push(e),r.writable.push(...t),r.readonly.push(...i)}}const[i,o]=t.getMessageComponents(),a=new Em(o,r).compileInstructions(e.instructions);return new Dm({header:i,staticAccountKeys:o,recentBlockhash:e.recentBlockhash,compiledInstructions:a,addressTableLookups:n})}serialize(){const e=Array();Im(e,this.staticAccountKeys.length);const t=this.serializeInstructions(),n=Array();Im(n,this.compiledInstructions.length);const r=this.serializeAddressTableLookups(),s=Array();Im(s,this.addressTableLookups.length);const i=Kl.struct([Kl.u8("prefix"),Kl.struct([Kl.u8("numRequiredSignatures"),Kl.u8("numReadonlySignedAccounts"),Kl.u8("numReadonlyUnsignedAccounts")],"header"),Kl.blob(e.length,"staticAccountKeysLength"),Kl.seq(Am(),this.staticAccountKeys.length,"staticAccountKeys"),Am("recentBlockhash"),Kl.blob(n.length,"instructionsLength"),Kl.blob(t.length,"serializedInstructions"),Kl.blob(s.length,"addressTableLookupsLength"),Kl.blob(r.length,"serializedAddressTableLookups")]),o=new Uint8Array(ym),a=i.encode({prefix:128,header:this.header,staticAccountKeysLength:new Uint8Array(e),staticAccountKeys:this.staticAccountKeys.map(e=>e.toBytes()),recentBlockhash:El.decode(this.recentBlockhash),instructionsLength:new Uint8Array(n),serializedInstructions:t,addressTableLookupsLength:new Uint8Array(s),serializedAddressTableLookups:r},o);return o.slice(0,a)}serializeInstructions(){let e=0;const t=new Uint8Array(ym);for(const n of this.compiledInstructions){const r=Array();Im(r,n.accountKeyIndexes.length);const s=Array();Im(s,n.data.length);e+=Kl.struct([Kl.u8("programIdIndex"),Kl.blob(r.length,"encodedAccountKeyIndexesLength"),Kl.seq(Kl.u8(),n.accountKeyIndexes.length,"accountKeyIndexes"),Kl.blob(s.length,"encodedDataLength"),Kl.blob(n.data.length,"data")]).encode({programIdIndex:n.programIdIndex,encodedAccountKeyIndexesLength:new Uint8Array(r),accountKeyIndexes:n.accountKeyIndexes,encodedDataLength:new Uint8Array(s),data:n.data},t,e)}return t.slice(0,e)}serializeAddressTableLookups(){let e=0;const t=new Uint8Array(ym);for(const n of this.addressTableLookups){const r=Array();Im(r,n.writableIndexes.length);const s=Array();Im(s,n.readonlyIndexes.length);e+=Kl.struct([Am("accountKey"),Kl.blob(r.length,"encodedWritableIndexesLength"),Kl.seq(Kl.u8(),n.writableIndexes.length,"writableIndexes"),Kl.blob(s.length,"encodedReadonlyIndexesLength"),Kl.seq(Kl.u8(),n.readonlyIndexes.length,"readonlyIndexes")]).encode({accountKey:n.accountKey.toBytes(),encodedWritableIndexesLength:new Uint8Array(r),writableIndexes:n.writableIndexes,encodedReadonlyIndexesLength:new Uint8Array(s),readonlyIndexes:n.readonlyIndexes},t,e)}return t.slice(0,e)}static deserialize(e){let t=[...e];const n=xm(t),r=127&n;Nm(n!==r,"Expected versioned message but received legacy message");Nm(0===r,`Expected versioned message with version 0 but found version ${r}`);const s={numRequiredSignatures:xm(t),numReadonlySignedAccounts:xm(t),numReadonlyUnsignedAccounts:xm(t)},i=[],o=Tm(t);for(let e=0;e<o;e++)i.push(new mm(Rm(t,0,fm)));const a=El.encode(Rm(t,0,fm)),c=Tm(t),l=[];for(let e=0;e<c;e++){const e=xm(t),n=Rm(t,0,Tm(t)),r=Tm(t),s=new Uint8Array(Rm(t,0,r));l.push({programIdIndex:e,accountKeyIndexes:n,data:s})}const u=Tm(t),d=[];for(let e=0;e<u;e++){const e=new mm(Rm(t,0,fm)),n=Rm(t,0,Tm(t)),r=Rm(t,0,Tm(t));d.push({accountKey:e,writableIndexes:n,readonlyIndexes:r})}return new Dm({header:s,staticAccountKeys:i,recentBlockhash:a,compiledInstructions:l,addressTableLookups:d})}}function Om(e){const t=Rm(e,0,4);return t[0]+256*t[1]+65536*t[2]+t[3]*2**24}class Mm{constructor(e){this.header=void 0,this.staticAccountKeys=void 0,this.recentBlockhash=void 0,this.compiledInstructions=void 0,this.transactionConfig=void 0,this.header=e.header,this.staticAccountKeys=e.staticAccountKeys,this.recentBlockhash=e.recentBlockhash,this.compiledInstructions=e.compiledInstructions,this.transactionConfig=e.transactionConfig??{computeUnitLimit:null,heapSize:null,loadedAccountsDataSizeLimit:null,priorityFee:null}}get version(){return 1}get addressTableLookups(){return[]}getAccountKeys(){return new Em(this.staticAccountKeys)}isAccountSigner(e){return e<this.header.numRequiredSignatures}isAccountWritable(e){const t=this.header.numRequiredSignatures,n=this.staticAccountKeys.length;if(e>=n)return!1;if(e>=this.header.numRequiredSignatures){return e-t<n-t-this.header.numReadonlyUnsignedAccounts}return e<t-this.header.numReadonlySignedAccounts}serialize(){throw new Error("Serialization of version 1 transaction messages is not supported")}static deserialize(e){let t=[...e];const n=xm(t),r=127&n;Nm(n!==r,"Expected versioned message but received legacy message");Nm(1===r,`Expected versioned message with version 1 but found version ${r}`);const s={numRequiredSignatures:xm(t),numReadonlySignedAccounts:xm(t),numReadonlyUnsignedAccounts:xm(t)},i=Om(t);Nm(!(-32&i),"Unexpected bits set in the transaction config mask");const o=3&i;Nm(0===o||3===o,"Expected both or neither of the priority fee bits to be set in the transaction config mask");const a=El.encode(Rm(t,0,fm)),c=xm(t),l=xm(t),u=[];for(let e=0;e<l;e++)u.push(new mm(Rm(t,0,fm)));const d={computeUnitLimit:null,heapSize:null,loadedAccountsDataSizeLimit:null,priorityFee:null};0!==o&&(d.priorityFee=function(e){const t=Rm(e,0,8);let n=BigInt(0);for(let e=t.length-1;e>=0;e--)n=n<<BigInt(8)|BigInt(t[e]);return Nm(n<=BigInt(Number.MAX_SAFE_INTEGER),"Expected u64 value to be within the safe integer range"),Number(n)}(t)),4&i&&(d.computeUnitLimit=Om(t)),8&i&&(d.loadedAccountsDataSizeLimit=Om(t)),16&i&&(d.heapSize=Om(t));const h=[];for(let e=0;e<c;e++){const e=xm(t),n=xm(t),r=xm(t)+256*xm(t);h.push({accountKeyIndexesLength:n,dataLength:r,programIdIndex:e})}const g=[];for(const e of h)g.push({programIdIndex:e.programIdIndex,accountKeyIndexes:Rm(t,0,e.accountKeyIndexesLength),data:new Uint8Array(Rm(t,0,e.dataLength))});return Nm(0===t.length,"Expected no bytes to remain after deserializing a version 1 message"),new Mm({header:s,staticAccountKeys:u,recentBlockhash:a,compiledInstructions:g,transactionConfig:d})}}let Lm=function(e){return e[e.BLOCKHEIGHT_EXCEEDED=0]="BLOCKHEIGHT_EXCEEDED",e[e.PROCESSED=1]="PROCESSED",e[e.TIMED_OUT=2]="TIMED_OUT",e[e.NONCE_INVALID=3]="NONCE_INVALID",e}({});const Um=Oo.Buffer.alloc(64).fill(0);class Pm{constructor(e){this.keys=void 0,this.programId=void 0,this.data=Oo.Buffer.alloc(0),this.programId=e.programId,this.keys=e.keys,e.data&&(this.data=e.data)}toJSON(){return{keys:this.keys.map(({pubkey:e,isSigner:t,isWritable:n})=>({pubkey:e.toJSON(),isSigner:t,isWritable:n})),programId:this.programId.toJSON(),data:[...this.data]}}}class Fm{get signature(){return this.signatures.length>0?this.signatures[0].signature:null}constructor(e){if(this.signatures=[],this.feePayer=void 0,this.instructions=[],this.recentBlockhash=void 0,this.lastValidBlockHeight=void 0,this.nonceInfo=void 0,this.minNonceContextSlot=void 0,this._message=void 0,this._json=void 0,e)if(e.feePayer&&(this.feePayer=e.feePayer),e.signatures&&(this.signatures=e.signatures),Object.prototype.hasOwnProperty.call(e,"nonceInfo")){const{minContextSlot:t,nonceInfo:n}=e;this.minNonceContextSlot=t,this.nonceInfo=n}else if(Object.prototype.hasOwnProperty.call(e,"lastValidBlockHeight")){const{blockhash:t,lastValidBlockHeight:n}=e;this.recentBlockhash=t,this.lastValidBlockHeight=n}else{const{recentBlockhash:t,nonceInfo:n}=e;n&&(this.nonceInfo=n),this.recentBlockhash=t}}toJSON(){return{recentBlockhash:this.recentBlockhash||null,feePayer:this.feePayer?this.feePayer.toJSON():null,nonceInfo:this.nonceInfo?{nonce:this.nonceInfo.nonce,nonceInstruction:this.nonceInfo.nonceInstruction.toJSON()}:null,instructions:this.instructions.map(e=>e.toJSON()),signers:this.signatures.map(({publicKey:e})=>e.toJSON())}}add(...e){if(0===e.length)throw new Error("No instructions");return e.forEach(e=>{"instructions"in e?this.instructions=this.instructions.concat(e.instructions):"data"in e&&"programId"in e&&"keys"in e?this.instructions.push(e):this.instructions.push(new Pm(e))}),this}compileMessage(){if(this._message&&JSON.stringify(this.toJSON())===JSON.stringify(this._json))return this._message;let e,t,n;if(this.nonceInfo?(e=this.nonceInfo.nonce,t=this.instructions[0]!=this.nonceInfo.nonceInstruction?[this.nonceInfo.nonceInstruction,...this.instructions]:this.instructions):(e=this.recentBlockhash,t=this.instructions),!e)throw new Error("Transaction recentBlockhash required");if(t.length,this.feePayer)n=this.feePayer;else{if(!(this.signatures.length>0&&this.signatures[0].publicKey))throw new Error("Transaction fee payer required");n=this.signatures[0].publicKey}for(let e=0;e<t.length;e++)if(void 0===t[e].programId)throw new Error(`Transaction instruction index ${e} has undefined program id`);const r=[],s=[];t.forEach(e=>{e.keys.forEach(e=>{s.push({...e})});const t=e.programId.toString();r.includes(t)||r.push(t)}),r.forEach(e=>{s.push({pubkey:new mm(e),isSigner:!1,isWritable:!1})});const i=[];s.forEach(e=>{const t=e.pubkey.toString(),n=i.findIndex(e=>e.pubkey.toString()===t);n>-1?(i[n].isWritable=i[n].isWritable||e.isWritable,i[n].isSigner=i[n].isSigner||e.isSigner):i.push(e)}),i.sort(function(e,t){if(e.isSigner!==t.isSigner)return e.isSigner?-1:1;if(e.isWritable!==t.isWritable)return e.isWritable?-1:1;return e.pubkey.toBase58().localeCompare(t.pubkey.toBase58(),"en",{localeMatcher:"best fit",usage:"sort",sensitivity:"variant",ignorePunctuation:!1,numeric:!1,caseFirst:"lower"})});const o=i.findIndex(e=>e.pubkey.equals(n));if(o>-1){const[e]=i.splice(o,1);e.isSigner=!0,e.isWritable=!0,i.unshift(e)}else i.unshift({pubkey:n,isSigner:!0,isWritable:!0});for(const e of this.signatures){const t=i.findIndex(t=>t.pubkey.equals(e.publicKey));if(!(t>-1))throw new Error(`unknown signer: ${e.publicKey.toString()}`);i[t].isSigner||(i[t].isSigner=!0)}let a=0,c=0,l=0;const u=[],d=[];i.forEach(({pubkey:e,isSigner:t,isWritable:n})=>{t?(u.push(e.toString()),a+=1,n||(c+=1)):(d.push(e.toString()),n||(l+=1))});const h=u.concat(d),g=t.map(e=>{const{data:t,programId:n}=e;return{programIdIndex:h.indexOf(n.toString()),accounts:e.keys.map(e=>h.indexOf(e.pubkey.toString())),data:El.encode(t)}});return g.forEach(e=>{Nm(e.programIdIndex>=0),e.accounts.forEach(e=>Nm(e>=0))}),new Bm({header:{numRequiredSignatures:a,numReadonlySignedAccounts:c,numReadonlyUnsignedAccounts:l},accountKeys:h,recentBlockhash:e,instructions:g})}_compile(){const e=this.compileMessage(),t=e.accountKeys.slice(0,e.header.numRequiredSignatures);if(this.signatures.length===t.length){if(this.signatures.every((e,n)=>t[n].equals(e.publicKey)))return e}return this.signatures=t.map(e=>({signature:null,publicKey:e})),e}serializeMessage(){return this._compile().serialize()}async getEstimatedFee(e){return(await e.getFeeForMessage(this.compileMessage())).value}setSigners(...e){if(0===e.length)throw new Error("No signers");const t=new Set;this.signatures=e.filter(e=>{const n=e.toString();return!t.has(n)&&(t.add(n),!0)}).map(e=>({signature:null,publicKey:e}))}sign(...e){if(0===e.length)throw new Error("No signers");const t=new Set,n=[];for(const r of e){const e=r.publicKey.toString();t.has(e)||(t.add(e),n.push(r))}this.signatures=n.map(e=>({signature:null,publicKey:e.publicKey}));const r=this._compile();this._partialSign(r,...n)}partialSign(...e){if(0===e.length)throw new Error("No signers");const t=new Set,n=[];for(const r of e){const e=r.publicKey.toString();t.has(e)||(t.add(e),n.push(r))}const r=this._compile();this._partialSign(r,...n)}_partialSign(e,...t){const n=e.serialize();t.forEach(e=>{const t=((e,t)=>il.sign(e,t.slice(0,32)))(n,e.secretKey);this._addSignature(e.publicKey,um(t))})}addSignature(e,t){this._compile(),this._addSignature(e,t)}_addSignature(e,t){Nm(64===t.length);const n=this.signatures.findIndex(t=>e.equals(t.publicKey));if(n<0)throw new Error(`unknown signer: ${e.toString()}`);this.signatures[n].signature=Oo.Buffer.from(t)}verifySignatures(e=!0){return!this._getMessageSignednessErrors(this.serializeMessage(),e)}_getMessageSignednessErrors(e,t){const n={};for(const{signature:r,publicKey:s}of this.signatures)null===r?t&&(n.missing||=[]).push(s):lm(r,e,s.toBytes())||(n.invalid||=[]).push(s);return n.invalid||n.missing?n:void 0}serialize(e){const{requireAllSignatures:t,verifySignatures:n}=Object.assign({requireAllSignatures:!0,verifySignatures:!0},e),r=this.serializeMessage();if(n){const e=this._getMessageSignednessErrors(r,t);if(e){let t="Signature verification failed.";throw e.invalid&&(t+=`\nInvalid signature for public key${1===e.invalid.length?"":"(s)"} [\`${e.invalid.map(e=>e.toBase58()).join("`, `")}\`].`),e.missing&&(t+=`\nMissing signature for public key${1===e.missing.length?"":"(s)"} [\`${e.missing.map(e=>e.toBase58()).join("`, `")}\`].`),new Error(t)}}return this._serialize(r)}_serialize(e){const{signatures:t}=this,n=[];Im(n,t.length);const r=n.length+64*t.length+e.length,s=Oo.Buffer.alloc(r);return Nm(t.length<256),Oo.Buffer.from(n).copy(s,0),t.forEach(({signature:e},t)=>{null!==e&&(Nm(64===e.length,"signature has invalid length"),Oo.Buffer.from(e).copy(s,n.length+64*t))}),e.copy(s,n.length+64*t.length),Nm(s.length<=ym,`Transaction too large: ${s.length} > 1232`),s}get keys(){return Nm(1===this.instructions.length),this.instructions[0].keys.map(e=>e.pubkey)}get programId(){return Nm(1===this.instructions.length),this.instructions[0].programId}get data(){return Nm(1===this.instructions.length),this.instructions[0].data}static from(e){let t=[...e];const n=Tm(t);let r=[];for(let e=0;e<n;e++){const e=Rm(t,0,64);r.push(El.encode(Oo.Buffer.from(e)))}return Fm.populate(Bm.from(t),r)}static populate(e,t=[]){const n=new Fm;return n.recentBlockhash=e.recentBlockhash,e.header.numRequiredSignatures>0&&(n.feePayer=e.accountKeys[0]),t.forEach((t,r)=>{const s={signature:t==El.encode(Um)?null:El.decode(t),publicKey:e.accountKeys[r]};n.signatures.push(s)}),e.instructions.forEach(t=>{const r=t.accounts.map(t=>{const r=e.accountKeys[t];return{pubkey:r,isSigner:n.signatures.some(e=>e.publicKey.toString()===r.toString())||e.isAccountSigner(t),isWritable:e.isAccountWritable(t)}});n.instructions.push(new Pm({keys:r,programId:e.accountKeys[t.programIdIndex],data:El.decode(t.data)}))}),n._message=e,n._json=n.toJSON(),n}}new mm("SysvarC1ock11111111111111111111111111111111"),new mm("SysvarEpochSchedu1e111111111111111111111111"),new mm("Sysvar1nstructions1111111111111111111111111");const $m=new mm("SysvarRecentB1ockHashes11111111111111111111"),Km=new mm("SysvarRent111111111111111111111111111111111");new mm("SysvarRewards111111111111111111111111111111"),new mm("SysvarS1otHashes111111111111111111111111111"),new mm("SysvarS1otHistory11111111111111111111111111"),new mm("SysvarStakeHistory1111111111111111111111111");class Gm extends Error{constructor({action:e,signature:t,transactionMessage:n,logs:r}){const s=r?`Logs: \n${JSON.stringify(r.slice(-10),null,2)}. `:"",i="\nCatch the `SendTransactionError` and call `getLogs()` on it for full details.";let o;switch(e){case"send":o=`Transaction ${t} resulted in an error. \n${n}. `+s+i;break;case"simulate":o=`Simulation failed. \nMessage: ${n}. \n`+s+i;break;default:o=`Unknown action '${e}'`}super(o),this.signature=void 0,this.transactionMessage=void 0,this.transactionLogs=void 0,this.signature=t,this.transactionMessage=n,this.transactionLogs=r||void 0}get transactionError(){return{message:this.transactionMessage,logs:Array.isArray(this.transactionLogs)?this.transactionLogs:void 0}}get logs(){const e=this.transactionLogs;if(null==e||"object"!=typeof e||!("then"in e))return e}async getLogs(e){return Array.isArray(this.transactionLogs)||(this.transactionLogs=new Promise((t,n)=>{e.getTransaction(this.signature).then(e=>{if(e&&e.meta&&e.meta.logMessages){const n=e.meta.logMessages;this.transactionLogs=n,t(n)}else n(new Error("Log messages not found"))}).catch(n)})),await this.transactionLogs}}class Wm extends Error{constructor({code:e,message:t,data:n},r){super(null!=r?`${r}: ${t}`:t),this.code=void 0,this.data=void 0,this.code=e,this.data=n,this.name="SolanaJSONRPCError"}}function Hm(e){return new Promise(t=>setTimeout(t,e))}function qm(e,t){const n=e.layout.span>=0?e.layout.span:km(e,t),r=Oo.Buffer.alloc(n),s=Object.assign({instruction:e.index},t);return e.layout.encode(s,r),r}const zm=Kl.nu64("lamportsPerSignature"),Vm=Kl.struct([Kl.u32("version"),Kl.u32("state"),Am("authorizedPubkey"),Am("nonce"),Kl.struct([zm],"feeCalculator")]),jm=Vm.span;class Xm{constructor(e){this.authorizedPubkey=void 0,this.nonce=void 0,this.feeCalculator=void 0,this.authorizedPubkey=e.authorizedPubkey,this.nonce=e.nonce,this.feeCalculator=e.feeCalculator}static fromAccountData(e){const t=Vm.decode(um(e),0);return new Xm({authorizedPubkey:new mm(t.authorizedPubkey),nonce:new mm(t.nonce).toString(),feeCalculator:t.feeCalculator})}}function Ym(e){const t=Kl.blob(8,e),n=t.decode.bind(t),r=t.encode.bind(t),s=t,i=Vf();return s.decode=(e,t)=>{const r=n(e,t);return i.decode(r)},s.encode=(e,t,n)=>{const s=i.encode(e);return r(s,t,n)},s}const Jm=Object.freeze({Create:{index:0,layout:Kl.struct([Kl.u32("instruction"),Kl.ns64("lamports"),Kl.ns64("space"),Am("programId")])},Assign:{index:1,layout:Kl.struct([Kl.u32("instruction"),Am("programId")])},Transfer:{index:2,layout:Kl.struct([Kl.u32("instruction"),Ym("lamports")])},CreateWithSeed:{index:3,layout:Kl.struct([Kl.u32("instruction"),Am("base"),Sm("seed"),Kl.ns64("lamports"),Kl.ns64("space"),Am("programId")])},AdvanceNonceAccount:{index:4,layout:Kl.struct([Kl.u32("instruction")])},WithdrawNonceAccount:{index:5,layout:Kl.struct([Kl.u32("instruction"),Kl.ns64("lamports")])},InitializeNonceAccount:{index:6,layout:Kl.struct([Kl.u32("instruction"),Am("authorized")])},AuthorizeNonceAccount:{index:7,layout:Kl.struct([Kl.u32("instruction"),Am("authorized")])},Allocate:{index:8,layout:Kl.struct([Kl.u32("instruction"),Kl.ns64("space")])},AllocateWithSeed:{index:9,layout:Kl.struct([Kl.u32("instruction"),Am("base"),Sm("seed"),Kl.ns64("space"),Am("programId")])},AssignWithSeed:{index:10,layout:Kl.struct([Kl.u32("instruction"),Am("base"),Sm("seed"),Am("programId")])},TransferWithSeed:{index:11,layout:Kl.struct([Kl.u32("instruction"),Ym("lamports"),Sm("seed"),Am("programId")])},UpgradeNonceAccount:{index:12,layout:Kl.struct([Kl.u32("instruction")])}});class Qm{constructor(){}static createAccount(e){const t=qm(Jm.Create,{lamports:e.lamports,space:e.space,programId:um(e.programId.toBuffer())});return new Pm({keys:[{pubkey:e.fromPubkey,isSigner:!0,isWritable:!0},{pubkey:e.newAccountPubkey,isSigner:!0,isWritable:!0}],programId:this.programId,data:t})}static transfer(e){let t,n;if("basePubkey"in e){t=qm(Jm.TransferWithSeed,{lamports:BigInt(e.lamports),seed:e.seed,programId:um(e.programId.toBuffer())}),n=[{pubkey:e.fromPubkey,isSigner:!1,isWritable:!0},{pubkey:e.basePubkey,isSigner:!0,isWritable:!1},{pubkey:e.toPubkey,isSigner:!1,isWritable:!0}]}else{t=qm(Jm.Transfer,{lamports:BigInt(e.lamports)}),n=[{pubkey:e.fromPubkey,isSigner:!0,isWritable:!0},{pubkey:e.toPubkey,isSigner:!1,isWritable:!0}]}return new Pm({keys:n,programId:this.programId,data:t})}static assign(e){let t,n;if("basePubkey"in e){t=qm(Jm.AssignWithSeed,{base:um(e.basePubkey.toBuffer()),seed:e.seed,programId:um(e.programId.toBuffer())}),n=[{pubkey:e.accountPubkey,isSigner:!1,isWritable:!0},{pubkey:e.basePubkey,isSigner:!0,isWritable:!1}]}else{t=qm(Jm.Assign,{programId:um(e.programId.toBuffer())}),n=[{pubkey:e.accountPubkey,isSigner:!0,isWritable:!0}]}return new Pm({keys:n,programId:this.programId,data:t})}static createAccountWithSeed(e){const t=qm(Jm.CreateWithSeed,{base:um(e.basePubkey.toBuffer()),seed:e.seed,lamports:e.lamports,space:e.space,programId:um(e.programId.toBuffer())});let n=[{pubkey:e.fromPubkey,isSigner:!0,isWritable:!0},{pubkey:e.newAccountPubkey,isSigner:!1,isWritable:!0}];return e.basePubkey.equals(e.fromPubkey)||n.push({pubkey:e.basePubkey,isSigner:!0,isWritable:!1}),new Pm({keys:n,programId:this.programId,data:t})}static createNonceAccount(e){const t=new Fm;"basePubkey"in e&&"seed"in e?t.add(Qm.createAccountWithSeed({fromPubkey:e.fromPubkey,newAccountPubkey:e.noncePubkey,basePubkey:e.basePubkey,seed:e.seed,lamports:e.lamports,space:jm,programId:this.programId})):t.add(Qm.createAccount({fromPubkey:e.fromPubkey,newAccountPubkey:e.noncePubkey,lamports:e.lamports,space:jm,programId:this.programId}));const n={noncePubkey:e.noncePubkey,authorizedPubkey:e.authorizedPubkey};return t.add(this.nonceInitialize(n)),t}static nonceInitialize(e){const t=qm(Jm.InitializeNonceAccount,{authorized:um(e.authorizedPubkey.toBuffer())}),n={keys:[{pubkey:e.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:$m,isSigner:!1,isWritable:!1},{pubkey:Km,isSigner:!1,isWritable:!1}],programId:this.programId,data:t};return new Pm(n)}static nonceAdvance(e){const t=qm(Jm.AdvanceNonceAccount),n={keys:[{pubkey:e.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:$m,isSigner:!1,isWritable:!1},{pubkey:e.authorizedPubkey,isSigner:!0,isWritable:!1}],programId:this.programId,data:t};return new Pm(n)}static nonceWithdraw(e){const t=qm(Jm.WithdrawNonceAccount,{lamports:e.lamports});return new Pm({keys:[{pubkey:e.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:e.toPubkey,isSigner:!1,isWritable:!0},{pubkey:$m,isSigner:!1,isWritable:!1},{pubkey:Km,isSigner:!1,isWritable:!1},{pubkey:e.authorizedPubkey,isSigner:!0,isWritable:!1}],programId:this.programId,data:t})}static nonceAuthorize(e){const t=qm(Jm.AuthorizeNonceAccount,{authorized:um(e.newAuthorizedPubkey.toBuffer())});return new Pm({keys:[{pubkey:e.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:e.authorizedPubkey,isSigner:!0,isWritable:!1}],programId:this.programId,data:t})}static allocate(e){let t,n;if("basePubkey"in e){t=qm(Jm.AllocateWithSeed,{base:um(e.basePubkey.toBuffer()),seed:e.seed,space:e.space,programId:um(e.programId.toBuffer())}),n=[{pubkey:e.accountPubkey,isSigner:!1,isWritable:!0},{pubkey:e.basePubkey,isSigner:!0,isWritable:!1}]}else{t=qm(Jm.Allocate,{space:e.space}),n=[{pubkey:e.accountPubkey,isSigner:!0,isWritable:!0}]}return new Pm({keys:n,programId:this.programId,data:t})}}function Zm(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var ey,ty;function ny(){if(ty)return ey;ty=1;var e=Object.prototype.toString,t=Object.keys||function(e){var t=[];for(var n in e)t.push(n);return t};function n(r,s){var i,o,a,c,l,u,d;if(!0===r)return"true";if(!1===r)return"false";switch(typeof r){case"object":if(null===r)return null;if(r.toJSON&&"function"==typeof r.toJSON)return n(r.toJSON(),s);if("[object Array]"===(d=e.call(r))){for(a="[",o=r.length-1,i=0;i<o;i++)a+=n(r[i],!0)+",";return o>-1&&(a+=n(r[i],!0)),a+"]"}if("[object Object]"===d){for(o=(c=t(r).sort()).length,a="",i=0;i<o;)void 0!==(u=n(r[l=c[i]],!1))&&(a&&(a+=","),a+=JSON.stringify(l)+":"+u),i++;return"{"+a+"}"}return JSON.stringify(r);case"function":case"undefined":return s?null:void 0;case"string":return JSON.stringify(r);default:return isFinite(r)?r:null}}return ey=function(e){var t=n(e,!1);if(void 0!==t)return""+t}}Qm.programId=new mm("11111111111111111111111111111111"),new mm("BPFLoader2111111111111111111111111111111111");var ry=Zm(ny());function sy(e){let t=0;for(;e>1;)e/=2,t++;return t}class iy{constructor(e,t,n,r,s){this.slotsPerEpoch=void 0,this.leaderScheduleSlotOffset=void 0,this.warmup=void 0,this.firstNormalEpoch=void 0,this.firstNormalSlot=void 0,this.slotsPerEpoch=e,this.leaderScheduleSlotOffset=t,this.warmup=n,this.firstNormalEpoch=r,this.firstNormalSlot=s}getEpoch(e){return this.getEpochAndSlotIndex(e)[0]}getEpochAndSlotIndex(e){if(e<this.firstNormalSlot){const n=sy(0===(t=e+32+1)?1:(t--,t|=t>>1,t|=t>>2,t|=t>>4,t|=t>>8,t|=t>>16,1+(t|=t>>32)))-sy(32)-1;return[n,e-(this.getSlotsInEpoch(n)-32)]}{const t=e-this.firstNormalSlot,n=Math.floor(t/this.slotsPerEpoch);return[this.firstNormalEpoch+n,t%this.slotsPerEpoch]}var t}getFirstSlotInEpoch(e){return e<=this.firstNormalEpoch?32*(Math.pow(2,e)-1):(e-this.firstNormalEpoch)*this.slotsPerEpoch+this.firstNormalSlot}getLastSlotInEpoch(e){return this.getFirstSlotInEpoch(e)+this.getSlotsInEpoch(e)-1}getSlotsInEpoch(e){return e<this.firstNormalEpoch?Math.pow(2,e+sy(32)):this.slotsPerEpoch}}var oy=globalThis.fetch;class ay extends Op{constructor(e,t,n){super(e=>{const n=function(e,t){return new Bp(e,t)}(e,{autoconnect:!0,max_reconnects:5,reconnect:!0,reconnect_interval:1e3,...t});return this.underlyingSocket="socket"in n?n.socket:n,n},e,t,n),this.underlyingSocket=void 0}call(...e){const t=this.underlyingSocket?.readyState;return 1===t?super.call(...e):Promise.reject(new Error("Tried to call a JSON-RPC method `"+e[0]+"` but the socket was not `CONNECTING` or `OPEN` (`readyState` was "+t+")"))}notify(...e){const t=this.underlyingSocket?.readyState;return 1===t?super.notify(...e):Promise.reject(new Error("Tried to send a JSON-RPC notification `"+e[0]+"` but the socket was not `CONNECTING` or `OPEN` (`readyState` was "+t+")"))}}class cy{constructor(e){this.key=void 0,this.state=void 0,this.key=e.key,this.state=e.state}isActive(){const e=BigInt("0xffffffffffffffff");return this.state.deactivationSlot===e}static deserialize(e){const t=function(e,t){let n;try{n=e.layout.decode(t)}catch(e){throw new Error("invalid instruction; "+e)}if(n.typeIndex!==e.index)throw new Error(`invalid account data; account type mismatch ${n.typeIndex} != ${e.index}`);return n}(ly,e),n=e.length-56;Nm(n>=0,"lookup table is invalid"),Nm(n%32==0,"lookup table is invalid");const r=n/32,{addresses:s}=Kl.struct([Kl.seq(Am(),r,"addresses")]).decode(e.slice(56));return{deactivationSlot:t.deactivationSlot,lastExtendedSlot:t.lastExtendedSlot,lastExtendedSlotStartIndex:t.lastExtendedStartIndex,authority:0!==t.authority.length?new mm(t.authority[0]):void 0,addresses:s.map(e=>new mm(e))}}}const ly={index:1,layout:Kl.struct([Kl.u32("typeIndex"),Ym("deactivationSlot"),Kl.nu64("lastExtendedSlot"),Kl.u8("lastExtendedStartIndex"),Kl.u8(),Kl.seq(Am(),Kl.offset(Kl.u8(),-1),"authority")])},uy=/^[^:]+:\/\/([^:[]+|\[[^\]]+\])(:\d+)?(.*)/i;const dy=vp(cp(mm),fp(),e=>new mm(e)),hy=pp([fp(),lp("base64")]),gy=vp(cp(Oo.Buffer),hy,e=>Oo.Buffer.from(e[0],"base64"));function fy(e){let t,n;if("string"==typeof e)t=e;else if(e){const{commitment:r,...s}=e;t=r,n=s}return{commitment:t,config:n}}function py(e){return e.map(e=>"memcmp"in e?{...e,memcmp:{...e.memcmp,encoding:e.memcmp.encoding??"base58"}}:e)}function my(e){return yp([mp({jsonrpc:lp("2.0"),id:fp(),result:e}),mp({jsonrpc:lp("2.0"),id:fp(),error:mp({code:bp(),message:fp(),data:hp(ip("any",()=>!0))})})])}const yy=my(bp());function by(e){return vp(my(e),yy,t=>"error"in t?t:{...t,result:np(t.result,e)})}function vy(e){return by(mp({context:mp({slot:dp()}),value:e}))}function wy(e){return mp({context:mp({slot:dp()}),value:e})}function Ey(e,t){if(0===e)return new Dm({header:t.header,staticAccountKeys:t.accountKeys.map(e=>new mm(e)),recentBlockhash:t.recentBlockhash,compiledInstructions:t.instructions.map(e=>({programIdIndex:e.programIdIndex,accountKeyIndexes:e.accounts,data:El.decode(e.data)})),addressTableLookups:t.addressTableLookups});if(1===e){const e=t.transactionConfig;if(null==e)throw new Error("Expected a version 1 transaction message response to have a `transactionConfig`");return new Mm({header:t.header,staticAccountKeys:t.accountKeys.map(e=>new mm(e)),recentBlockhash:t.recentBlockhash,compiledInstructions:t.instructions.map(e=>({programIdIndex:e.programIdIndex,accountKeyIndexes:e.accounts,data:El.decode(e.data)})),transactionConfig:e})}return new Bm(t)}const Ay=mp({foundation:dp(),foundationTerm:dp(),initial:dp(),taper:dp(),terminal:dp()}),Sy=by(op(up(mp({epoch:dp(),effectiveSlot:dp(),amount:dp(),postBalance:dp(),commission:hp(up(dp()))})))),ky=op(mp({slot:dp(),prioritizationFee:dp()})),Ty=mp({total:dp(),validator:dp(),foundation:dp(),epoch:dp()}),Iy=mp({epoch:dp(),slotIndex:dp(),slotsInEpoch:dp(),absoluteSlot:dp(),blockHeight:hp(dp()),transactionCount:hp(dp())}),Ny=mp({slotsPerEpoch:dp(),leaderScheduleSlotOffset:dp(),warmup:ap(),firstNormalEpoch:dp(),firstNormalSlot:dp()}),Cy=gp(fp(),op(dp())),_y=up(yp([mp({}),fp()])),xy=mp({err:_y}),Ry=lp("receivedSignature"),By=mp({"solana-core":fp(),"feature-set":hp(dp())}),Dy=mp({program:fp(),programId:dy,parsed:bp()}),Oy=mp({programId:dy,accounts:op(dy),data:fp()}),My=vy(mp({err:up(yp([mp({}),fp()])),logs:up(op(fp())),accounts:hp(up(op(up(mp({executable:ap(),owner:fp(),lamports:dp(),data:op(fp()),rentEpoch:hp(dp())}))))),unitsConsumed:hp(dp()),returnData:hp(up(mp({programId:fp(),data:pp([fp(),lp("base64")])}))),innerInstructions:hp(up(op(mp({index:dp(),instructions:op(yp([Dy,Oy]))}))))})),Ly=vy(mp({byIdentity:gp(fp(),op(dp())),range:mp({firstSlot:dp(),lastSlot:dp()})}));const Uy=by(Ay),Py=by(Ty),Fy=by(ky),$y=by(Iy),Ky=by(Ny),Gy=by(Cy),Wy=by(dp()),Hy=vy(mp({total:dp(),circulating:dp(),nonCirculating:dp(),nonCirculatingAccounts:op(dy)})),qy=mp({amount:fp(),uiAmount:up(dp()),decimals:dp(),uiAmountString:hp(fp())}),zy=vy(op(mp({address:dy,amount:fp(),uiAmount:up(dp()),decimals:dp(),uiAmountString:hp(fp())}))),Vy=vy(op(mp({pubkey:dy,account:mp({executable:ap(),owner:dy,lamports:dp(),data:gy,rentEpoch:dp()})}))),jy=mp({program:fp(),parsed:bp(),space:dp()}),Xy=vy(op(mp({pubkey:dy,account:mp({executable:ap(),owner:dy,lamports:dp(),data:jy,rentEpoch:dp()})}))),Yy=vy(op(mp({lamports:dp(),address:dy}))),Jy=mp({executable:ap(),owner:dy,lamports:dp(),data:gy,rentEpoch:dp()}),Qy=mp({pubkey:dy,account:Jy}),Zy=vp(yp([cp(Oo.Buffer),jy]),yp([hy,jy]),e=>Array.isArray(e)?np(e,gy):e),eb=mp({executable:ap(),owner:dy,lamports:dp(),data:Zy,rentEpoch:dp()}),tb=mp({pubkey:dy,account:eb}),nb=mp({state:yp([lp("active"),lp("inactive"),lp("activating"),lp("deactivating")]),active:dp(),inactive:dp()}),rb=by(op(mp({signature:fp(),slot:dp(),err:_y,memo:up(fp()),blockTime:hp(up(dp()))}))),sb=by(op(mp({signature:fp(),slot:dp(),err:_y,memo:up(fp()),blockTime:hp(up(dp()))}))),ib=mp({subscription:dp(),result:wy(Jy)}),ob=mp({pubkey:dy,account:Jy}),ab=mp({subscription:dp(),result:wy(ob)}),cb=mp({parent:dp(),slot:dp(),root:dp()}),lb=mp({subscription:dp(),result:cb}),ub=yp([mp({type:yp([lp("firstShredReceived"),lp("completed"),lp("optimisticConfirmation"),lp("root")]),slot:dp(),timestamp:dp()}),mp({type:lp("createdBank"),parent:dp(),slot:dp(),timestamp:dp()}),mp({type:lp("frozen"),slot:dp(),timestamp:dp(),stats:mp({numTransactionEntries:dp(),numSuccessfulTransactions:dp(),numFailedTransactions:dp(),maxTransactionsPerEntry:dp()})}),mp({type:lp("dead"),slot:dp(),timestamp:dp(),err:fp()})]),db=mp({subscription:dp(),result:ub}),hb=mp({subscription:dp(),result:wy(yp([xy,Ry]))}),gb=mp({subscription:dp(),result:dp()}),fb=mp({pubkey:fp(),gossip:up(fp()),tpu:up(fp()),rpc:up(fp()),version:up(fp())}),pb=mp({votePubkey:fp(),nodePubkey:fp(),activatedStake:dp(),epochVoteAccount:ap(),epochCredits:op(pp([dp(),dp(),dp()])),commission:dp(),lastVote:dp(),rootSlot:up(dp())}),mb=by(mp({current:op(pb),delinquent:op(pb)})),yb=yp([lp("processed"),lp("confirmed"),lp("finalized")]),bb=mp({slot:dp(),confirmations:up(dp()),err:_y,confirmationStatus:hp(yb)}),vb=vy(op(up(bb))),wb=by(dp()),Eb=mp({accountKey:dy,writableIndexes:op(dp()),readonlyIndexes:op(dp())}),Ab=mp({computeUnitLimit:up(dp()),heapSize:up(dp()),loadedAccountsDataSizeLimit:up(dp()),priorityFee:up(dp())}),Sb=mp({signatures:op(fp()),message:mp({accountKeys:op(fp()),header:mp({numRequiredSignatures:dp(),numReadonlySignedAccounts:dp(),numReadonlyUnsignedAccounts:dp()}),instructions:op(mp({accounts:op(dp()),data:fp(),programIdIndex:dp()})),recentBlockhash:fp(),addressTableLookups:hp(op(Eb)),transactionConfig:hp(up(Ab))})}),kb=mp({pubkey:dy,signer:ap(),writable:ap(),source:hp(yp([lp("transaction"),lp("lookupTable")]))}),Tb=mp({accountKeys:op(kb),signatures:op(fp())}),Ib=mp({parsed:bp(),program:fp(),programId:dy}),Nb=mp({accounts:op(dy),data:fp(),programId:dy}),Cb=vp(yp([Nb,Ib]),yp([mp({parsed:bp(),program:fp(),programId:fp()}),mp({accounts:op(fp()),data:fp(),programId:fp()})]),e=>np(e,"accounts"in e?Nb:Ib)),_b=mp({signatures:op(fp()),message:mp({accountKeys:op(kb),instructions:op(Cb),recentBlockhash:fp(),addressTableLookups:hp(up(op(Eb))),transactionConfig:hp(up(Ab))})}),xb=mp({accountIndex:dp(),mint:fp(),owner:hp(fp()),programId:hp(fp()),uiTokenAmount:qy}),Rb=mp({writable:op(dy),readonly:op(dy)}),Bb=mp({err:_y,fee:dp(),innerInstructions:hp(up(op(mp({index:dp(),instructions:op(mp({accounts:op(dp()),data:fp(),programIdIndex:dp()}))})))),preBalances:op(dp()),postBalances:op(dp()),logMessages:hp(up(op(fp()))),preTokenBalances:hp(up(op(xb))),postTokenBalances:hp(up(op(xb))),loadedAddresses:hp(Rb),computeUnitsConsumed:hp(dp()),costUnits:hp(dp())}),Db=mp({err:_y,fee:dp(),innerInstructions:hp(up(op(mp({index:dp(),instructions:op(Cb)})))),preBalances:op(dp()),postBalances:op(dp()),logMessages:hp(up(op(fp()))),preTokenBalances:hp(up(op(xb))),postTokenBalances:hp(up(op(xb))),loadedAddresses:hp(Rb),computeUnitsConsumed:hp(dp()),costUnits:hp(dp())}),Ob=yp([lp(0),lp(1),lp("legacy")]),Mb=mp({pubkey:fp(),lamports:dp(),postBalance:up(dp()),rewardType:up(fp()),commission:hp(up(dp()))}),Lb=by(up(mp({blockhash:fp(),previousBlockhash:fp(),parentSlot:dp(),transactions:op(mp({transaction:Sb,meta:up(Bb),version:hp(Ob)})),rewards:hp(op(Mb)),blockTime:up(dp()),blockHeight:up(dp())}))),Ub=by(up(mp({blockhash:fp(),previousBlockhash:fp(),parentSlot:dp(),rewards:hp(op(Mb)),blockTime:up(dp()),blockHeight:up(dp())}))),Pb=by(up(mp({blockhash:fp(),previousBlockhash:fp(),parentSlot:dp(),transactions:op(mp({transaction:Tb,meta:up(Bb),version:hp(Ob)})),rewards:hp(op(Mb)),blockTime:up(dp()),blockHeight:up(dp())}))),Fb=by(up(mp({blockhash:fp(),previousBlockhash:fp(),parentSlot:dp(),transactions:op(mp({transaction:_b,meta:up(Db),version:hp(Ob)})),rewards:hp(op(Mb)),blockTime:up(dp()),blockHeight:up(dp())}))),$b=by(up(mp({blockhash:fp(),previousBlockhash:fp(),parentSlot:dp(),transactions:op(mp({transaction:Tb,meta:up(Db),version:hp(Ob)})),rewards:hp(op(Mb)),blockTime:up(dp()),blockHeight:up(dp())}))),Kb=by(up(mp({blockhash:fp(),previousBlockhash:fp(),parentSlot:dp(),rewards:hp(op(Mb)),blockTime:up(dp()),blockHeight:up(dp())}))),Gb=by(up(mp({blockhash:fp(),previousBlockhash:fp(),parentSlot:dp(),transactions:op(mp({transaction:Sb,meta:up(Bb)})),rewards:hp(op(Mb)),blockTime:up(dp())}))),Wb=by(up(mp({blockhash:fp(),previousBlockhash:fp(),parentSlot:dp(),signatures:op(fp()),blockTime:up(dp())}))),Hb=by(up(mp({slot:dp(),meta:up(Bb),blockTime:hp(up(dp())),transaction:Sb,version:hp(Ob)}))),qb=by(up(mp({slot:dp(),transaction:_b,meta:up(Db),blockTime:hp(up(dp())),version:hp(Ob)}))),zb=vy(mp({blockhash:fp(),lastValidBlockHeight:dp()})),Vb=vy(ap()),jb=by(op(mp({slot:dp(),numTransactions:dp(),numSlots:dp(),samplePeriodSecs:dp()}))),Xb=vy(up(mp({feeCalculator:mp({lamportsPerSignature:dp()})}))),Yb=by(fp()),Jb=by(fp()),Qb=mp({err:_y,logs:op(fp()),signature:fp()}),Zb=mp({result:wy(Qb),subscription:dp()}),ev={"solana-client":"js/1.99.0"};class tv{constructor(e,t){let n,r,s,i,o,a;var c;this._commitment=void 0,this._confirmTransactionInitialTimeout=void 0,this._rpcEndpoint=void 0,this._rpcWsEndpoint=void 0,this._rpcClient=void 0,this._rpcRequest=void 0,this._rpcBatchRequest=void 0,this._rpcWebSocket=void 0,this._rpcWebSocketConnected=!1,this._rpcWebSocketHeartbeat=null,this._rpcWebSocketIdleTimeout=null,this._rpcWebSocketGeneration=0,this._disableBlockhashCaching=!1,this._pollingBlockhash=!1,this._blockhashInfo={latestBlockhash:null,lastFetch:0,transactionSignatures:[],simulatedSignatures:[]},this._nextClientSubscriptionId=0,this._subscriptionDisposeFunctionsByClientSubscriptionId={},this._subscriptionHashByClientSubscriptionId={},this._subscriptionStateChangeCallbacksByHash={},this._subscriptionCallbacksByServerSubscriptionId={},this._subscriptionsByHash={},this._subscriptionsAutoDisposedByRpc=new Set,this.getBlockHeight=(()=>{const e={};return async t=>{const{commitment:n,config:r}=fy(t),s=this._buildArgs([],n,void 0,r),i=ry(s);return e[i]=e[i]??(async()=>{try{const e=np(await this._rpcRequest("getBlockHeight",s),by(dp()));if("error"in e)throw new Wm(e.error,"failed to get block height information");return e.result}finally{delete e[i]}})(),await e[i]}})(),t&&"string"==typeof t?this._commitment=t:t&&(this._commitment=t.commitment,this._confirmTransactionInitialTimeout=t.confirmTransactionInitialTimeout,n=t.wsEndpoint,r=t.httpHeaders,s=t.fetch,i=t.fetchMiddleware,o=t.disableRetryOnRateLimit,a=t.httpAgent),this._rpcEndpoint=function(e){if(!1===/^https?:/.test(e))throw new TypeError("Endpoint URL must start with `http:` or `https:`.");return e}(e),this._rpcWsEndpoint=n||function(e){const t=e.match(uy);if(null==t)throw TypeError(`Failed to validate endpoint URL \`${e}\``);const[n,r,s,i]=t,o=e.startsWith("https:")?"wss:":"ws:",a=null==s?null:parseInt(s.slice(1),10);return`${o}//${r}${null==a?"":`:${a+1}`}${i}`}(e),this._rpcClient=function(e,t,n,r,s){const i=n||oy;let o;return r&&(o=async(e,t)=>{const n=await new Promise((n,s)=>{try{r(e,t,(e,t)=>n([e,t]))}catch(e){s(e)}});return await i(...n)}),new Cp(async(n,r)=>{const a={method:"POST",body:n,agent:void 0,headers:Object.assign({"Content-Type":"application/json"},t||{},ev)};try{let t,n=5,c=500;for(;t=o?await o(e,a):await i(e,a),429===t.status&&!0!==s&&(n-=1,0!==n);)await Hm(c),c*=2;const l=await t.text();t.ok?r(null,l):r(new Error(`${t.status} ${t.statusText}: ${l}`))}catch(e){e instanceof Error&&r(e)}},{})}(e,r,s,i,o),this._rpcRequest=(c=this._rpcClient,(e,t)=>new Promise((n,r)=>{c.request(e,t,(e,t)=>{e?r(e):n(t)})})),this._rpcBatchRequest=function(e){return t=>new Promise((n,r)=>{0===t.length&&n([]);const s=t.map(t=>e.request(t.methodName,t.args));e.request(s,(e,t)=>{e?r(e):n(t)})})}(this._rpcClient),this._rpcWebSocket=new ay(this._rpcWsEndpoint,{autoconnect:!1,max_reconnects:1/0}),this._rpcWebSocket.on("open",this._wsOnOpen.bind(this)),this._rpcWebSocket.on("error",this._wsOnError.bind(this)),this._rpcWebSocket.on("close",this._wsOnClose.bind(this)),this._rpcWebSocket.on("accountNotification",this._wsOnAccountNotification.bind(this)),this._rpcWebSocket.on("programNotification",this._wsOnProgramAccountNotification.bind(this)),this._rpcWebSocket.on("slotNotification",this._wsOnSlotNotification.bind(this)),this._rpcWebSocket.on("slotsUpdatesNotification",this._wsOnSlotUpdatesNotification.bind(this)),this._rpcWebSocket.on("signatureNotification",this._wsOnSignatureNotification.bind(this)),this._rpcWebSocket.on("rootNotification",this._wsOnRootNotification.bind(this)),this._rpcWebSocket.on("logsNotification",this._wsOnLogsNotification.bind(this))}get commitment(){return this._commitment}get rpcEndpoint(){return this._rpcEndpoint}async getBalanceAndContext(e,t){const{commitment:n,config:r}=fy(t),s=this._buildArgs([e.toBase58()],n,void 0,r),i=np(await this._rpcRequest("getBalance",s),vy(dp()));if("error"in i)throw new Wm(i.error,`failed to get balance for ${e.toBase58()}`);return i.result}async getBalance(e,t){return await this.getBalanceAndContext(e,t).then(e=>e.value).catch(t=>{throw new Error("failed to get balance of account "+e.toBase58()+": "+t)})}async getBlockTime(e){const t=np(await this._rpcRequest("getBlockTime",[e]),by(up(dp())));if("error"in t)throw new Wm(t.error,`failed to get block time for slot ${e}`);return t.result}async getMinimumLedgerSlot(){const e=np(await this._rpcRequest("minimumLedgerSlot",[]),by(dp()));if("error"in e)throw new Wm(e.error,"failed to get minimum ledger slot");return e.result}async getFirstAvailableBlock(){const e=np(await this._rpcRequest("getFirstAvailableBlock",[]),Wy);if("error"in e)throw new Wm(e.error,"failed to get first available block");return e.result}async getSupply(e){let t={};t="string"==typeof e?{commitment:e}:e?{...e,commitment:e&&e.commitment||this.commitment}:{commitment:this.commitment};const n=np(await this._rpcRequest("getSupply",[t]),Hy);if("error"in n)throw new Wm(n.error,"failed to get supply");return n.result}async getTokenSupply(e,t){const n=this._buildArgs([e.toBase58()],t),r=np(await this._rpcRequest("getTokenSupply",n),vy(qy));if("error"in r)throw new Wm(r.error,"failed to get token supply");return r.result}async getTokenAccountBalance(e,t){const n=this._buildArgs([e.toBase58()],t),r=np(await this._rpcRequest("getTokenAccountBalance",n),vy(qy));if("error"in r)throw new Wm(r.error,"failed to get token account balance");return r.result}async getTokenAccountsByOwner(e,t,n){const{commitment:r,config:s}=fy(n);let i=[e.toBase58()];"mint"in t?i.push({mint:t.mint.toBase58()}):i.push({programId:t.programId.toBase58()});const o=this._buildArgs(i,r,"base64",s),a=np(await this._rpcRequest("getTokenAccountsByOwner",o),Vy);if("error"in a)throw new Wm(a.error,`failed to get token accounts owned by account ${e.toBase58()}`);return a.result}async getParsedTokenAccountsByOwner(e,t,n){let r=[e.toBase58()];"mint"in t?r.push({mint:t.mint.toBase58()}):r.push({programId:t.programId.toBase58()});const s=this._buildArgs(r,n,"jsonParsed"),i=np(await this._rpcRequest("getTokenAccountsByOwner",s),Xy);if("error"in i)throw new Wm(i.error,`failed to get token accounts owned by account ${e.toBase58()}`);return i.result}async getLargestAccounts(e){const t={...e,commitment:e&&e.commitment||this.commitment},n=t.filter||t.commitment?[t]:[],r=np(await this._rpcRequest("getLargestAccounts",n),Yy);if("error"in r)throw new Wm(r.error,"failed to get largest accounts");return r.result}async getTokenLargestAccounts(e,t){const n=this._buildArgs([e.toBase58()],t),r=np(await this._rpcRequest("getTokenLargestAccounts",n),zy);if("error"in r)throw new Wm(r.error,"failed to get token largest accounts");return r.result}async getAccountInfoAndContext(e,t){const{commitment:n,config:r}=fy(t),s=this._buildArgs([e.toBase58()],n,"base64",r),i=np(await this._rpcRequest("getAccountInfo",s),vy(up(Jy)));if("error"in i)throw new Wm(i.error,`failed to get info about account ${e.toBase58()}`);return i.result}async getParsedAccountInfo(e,t){const{commitment:n,config:r}=fy(t),s=this._buildArgs([e.toBase58()],n,"jsonParsed",r),i=np(await this._rpcRequest("getAccountInfo",s),vy(up(eb)));if("error"in i)throw new Wm(i.error,`failed to get info about account ${e.toBase58()}`);return i.result}async getAccountInfo(e,t){try{return(await this.getAccountInfoAndContext(e,t)).value}catch(t){throw new Error("failed to get info about account "+e.toBase58()+": "+t)}}async getMultipleParsedAccounts(e,t){const{commitment:n,config:r}=fy(t),s=e.map(e=>e.toBase58()),i=this._buildArgs([s],n,"jsonParsed",r),o=np(await this._rpcRequest("getMultipleAccounts",i),vy(op(up(eb))));if("error"in o)throw new Wm(o.error,`failed to get info for accounts ${s}`);return o.result}async getMultipleAccountsInfoAndContext(e,t){const{commitment:n,config:r}=fy(t),s=e.map(e=>e.toBase58()),i=this._buildArgs([s],n,"base64",r),o=np(await this._rpcRequest("getMultipleAccounts",i),vy(op(up(Jy))));if("error"in o)throw new Wm(o.error,`failed to get info for accounts ${s}`);return o.result}async getMultipleAccountsInfo(e,t){return(await this.getMultipleAccountsInfoAndContext(e,t)).value}async getStakeActivation(e,t,n){const{commitment:r,config:s}=fy(t),i=this._buildArgs([e.toBase58()],r,void 0,{...s,epoch:null!=n?n:s?.epoch}),o=np(await this._rpcRequest("getStakeActivation",i),by(nb));if("error"in o)throw new Wm(o.error,`failed to get Stake Activation ${e.toBase58()}`);return o.result}async getProgramAccounts(e,t){const{commitment:n,config:r}=fy(t),{encoding:s,...i}=r||{},o=this._buildArgs([e.toBase58()],n,s||"base64",{...i,...i.filters?{filters:py(i.filters)}:null}),a=await this._rpcRequest("getProgramAccounts",o),c=op(Qy),l=!0===i.withContext?np(a,vy(c)):np(a,by(c));if("error"in l)throw new Wm(l.error,`failed to get accounts owned by program ${e.toBase58()}`);return l.result}async getParsedProgramAccounts(e,t){const{commitment:n,config:r}=fy(t),s=this._buildArgs([e.toBase58()],n,"jsonParsed",r),i=np(await this._rpcRequest("getProgramAccounts",s),by(op(tb)));if("error"in i)throw new Wm(i.error,`failed to get accounts owned by program ${e.toBase58()}`);return i.result}async confirmTransaction(e,t){let n,r;if("string"==typeof e)n=e;else{const t=e;if(t.abortSignal?.aborted)return Promise.reject(t.abortSignal.reason);n=t.signature}try{r=El.decode(n)}catch(e){throw new Error("signature must be base58 encoded: "+n)}return Nm(64===r.length,"signature has invalid length"),"string"==typeof e?await this.confirmTransactionUsingLegacyTimeoutStrategy({commitment:t||this.commitment,signature:n}):"lastValidBlockHeight"in e?await this.confirmTransactionUsingBlockHeightExceedanceStrategy({commitment:t||this.commitment,strategy:e}):await this.confirmTransactionUsingDurableNonceStrategy({commitment:t||this.commitment,strategy:e})}getCancellationPromise(e){return new Promise((t,n)=>{null!=e&&(e.aborted?n(e.reason):e.addEventListener("abort",()=>{n(e.reason)}))})}getTransactionConfirmationPromise({commitment:e,signature:t}){let n,r,s=!1;return{abortConfirmation:()=>{r&&(r(),r=void 0),null!=n&&(this.removeSignatureListener(n),n=void 0)},confirmationPromise:new Promise((i,o)=>{try{n=this.onSignature(t,(e,t)=>{n=void 0;const r={context:t,value:e};i({__type:Lm.PROCESSED,response:r})},e);const a=new Promise(e=>{null==n?e():r=this._onSubscriptionStateChange(n,t=>{"subscribed"===t&&e()})});(async()=>{if(await a,s)return;const n=await this.getSignatureStatus(t);if(s)return;if(null==n)return;const{context:r,value:c}=n;if(null!=c)if(c?.err)o(c.err);else{switch(e){case"confirmed":case"single":case"singleGossip":if("processed"===c.confirmationStatus)return;break;case"finalized":case"max":case"root":if("processed"===c.confirmationStatus||"confirmed"===c.confirmationStatus)return}s=!0,i({__type:Lm.PROCESSED,response:{context:r,value:c}})}})()}catch(e){o(e)}})}}async confirmTransactionUsingBlockHeightExceedanceStrategy({commitment:e,strategy:{abortSignal:t,lastValidBlockHeight:n,signature:r}}){let s=!1;const i=new Promise(t=>{const r=async()=>{try{return await this.getBlockHeight(e)}catch(e){return-1}};(async()=>{let e=await r();if(!s){for(;e<=n;){if(await Hm(1e3),s)return;if(e=await r(),s)return}t({__type:Lm.BLOCKHEIGHT_EXCEEDED})}})()}),{abortConfirmation:o,confirmationPromise:a}=this.getTransactionConfirmationPromise({commitment:e,signature:r}),c=this.getCancellationPromise(t);let l;try{const e=await Promise.race([c,a,i]);if(e.__type!==Lm.PROCESSED)throw new bm(r);l=e.response}finally{s=!0,o()}return l}async confirmTransactionUsingDurableNonceStrategy({commitment:e,strategy:{abortSignal:t,minContextSlot:n,nonceAccountPubkey:r,nonceValue:s,signature:i}}){let o=!1;const a=new Promise(t=>{let i=s,a=null;const c=async()=>{try{const{context:t,value:s}=await this.getNonceAndContext(r,{commitment:e,minContextSlot:n});return a=t.slot,s?.nonce}catch(e){return i}};(async()=>{if(i=await c(),!o)for(;;){if(s!==i)return void t({__type:Lm.NONCE_INVALID,slotInWhichNonceDidAdvance:a});if(await Hm(2e3),o)return;if(i=await c(),o)return}})()}),{abortConfirmation:c,confirmationPromise:l}=this.getTransactionConfirmationPromise({commitment:e,signature:i}),u=this.getCancellationPromise(t);let d;try{const t=await Promise.race([u,l,a]);if(t.__type===Lm.PROCESSED)d=t.response;else{let r;for(;;){const e=await this.getSignatureStatus(i);if(null==e)break;if(!(e.context.slot<(t.slotInWhichNonceDidAdvance??n))){r=e;break}await Hm(400)}if(!r?.value)throw new wm(i);{const t=e||"finalized",{confirmationStatus:n}=r.value;switch(t){case"processed":case"recent":if("processed"!==n&&"confirmed"!==n&&"finalized"!==n)throw new wm(i);break;case"confirmed":case"single":case"singleGossip":if("confirmed"!==n&&"finalized"!==n)throw new wm(i);break;case"finalized":case"max":case"root":if("finalized"!==n)throw new wm(i)}d={context:r.context,value:{err:r.value.err}}}}}finally{o=!0,c()}return d}async confirmTransactionUsingLegacyTimeoutStrategy({commitment:e,signature:t}){let n;const r=new Promise(t=>{let r=this._confirmTransactionInitialTimeout||6e4;switch(e){case"processed":case"recent":case"single":case"confirmed":case"singleGossip":r=this._confirmTransactionInitialTimeout||3e4}n=setTimeout(()=>t({__type:Lm.TIMED_OUT,timeoutMs:r}),r)}),{abortConfirmation:s,confirmationPromise:i}=this.getTransactionConfirmationPromise({commitment:e,signature:t});let o;try{const e=await Promise.race([i,r]);if(e.__type!==Lm.PROCESSED)throw new vm(t,e.timeoutMs/1e3);o=e.response}finally{clearTimeout(n),s()}return o}async getClusterNodes(){const e=np(await this._rpcRequest("getClusterNodes",[]),by(op(fb)));if("error"in e)throw new Wm(e.error,"failed to get cluster nodes");return e.result}async getVoteAccounts(e){const t=this._buildArgs([],e),n=np(await this._rpcRequest("getVoteAccounts",t),mb);if("error"in n)throw new Wm(n.error,"failed to get vote accounts");return n.result}async getSlot(e){const{commitment:t,config:n}=fy(e),r=this._buildArgs([],t,void 0,n),s=np(await this._rpcRequest("getSlot",r),by(dp()));if("error"in s)throw new Wm(s.error,"failed to get slot");return s.result}async getSlotLeader(e){const{commitment:t,config:n}=fy(e),r=this._buildArgs([],t,void 0,n),s=np(await this._rpcRequest("getSlotLeader",r),by(fp()));if("error"in s)throw new Wm(s.error,"failed to get slot leader");return s.result}async getSlotLeaders(e,t){const n=[e,t],r=np(await this._rpcRequest("getSlotLeaders",n),by(op(dy)));if("error"in r)throw new Wm(r.error,"failed to get slot leaders");return r.result}async getSignatureStatus(e,t){const{context:n,value:r}=await this.getSignatureStatuses([e],t);Nm(1===r.length);return{context:n,value:r[0]}}async getSignatureStatuses(e,t){const n=[e];t&&n.push(t);const r=np(await this._rpcRequest("getSignatureStatuses",n),vb);if("error"in r)throw new Wm(r.error,"failed to get signature status");return r.result}async getTransactionCount(e){const{commitment:t,config:n}=fy(e),r=this._buildArgs([],t,void 0,n),s=np(await this._rpcRequest("getTransactionCount",r),by(dp()));if("error"in s)throw new Wm(s.error,"failed to get transaction count");return s.result}async getTotalSupply(e){return(await this.getSupply({commitment:e,excludeNonCirculatingAccountsList:!0})).value.total}async getInflationGovernor(e){const t=this._buildArgs([],e),n=np(await this._rpcRequest("getInflationGovernor",t),Uy);if("error"in n)throw new Wm(n.error,"failed to get inflation");return n.result}async getInflationReward(e,t,n){const{commitment:r,config:s}=fy(n),i=this._buildArgs([e.map(e=>e.toBase58())],r,void 0,{...s,epoch:null!=t?t:s?.epoch}),o=np(await this._rpcRequest("getInflationReward",i),Sy);if("error"in o)throw new Wm(o.error,"failed to get inflation reward");return o.result}async getInflationRate(){const e=np(await this._rpcRequest("getInflationRate",[]),Py);if("error"in e)throw new Wm(e.error,"failed to get inflation rate");return e.result}async getEpochInfo(e){const{commitment:t,config:n}=fy(e),r=this._buildArgs([],t,void 0,n),s=np(await this._rpcRequest("getEpochInfo",r),$y);if("error"in s)throw new Wm(s.error,"failed to get epoch info");return s.result}async getEpochSchedule(){const e=np(await this._rpcRequest("getEpochSchedule",[]),Ky);if("error"in e)throw new Wm(e.error,"failed to get epoch schedule");const t=e.result;return new iy(t.slotsPerEpoch,t.leaderScheduleSlotOffset,t.warmup,t.firstNormalEpoch,t.firstNormalSlot)}async getLeaderSchedule(){const e=np(await this._rpcRequest("getLeaderSchedule",[]),Gy);if("error"in e)throw new Wm(e.error,"failed to get leader schedule");return e.result}async getMinimumBalanceForRentExemption(e,t){const n=this._buildArgs([e],t),r=np(await this._rpcRequest("getMinimumBalanceForRentExemption",n),wb);return"error"in r?0:r.result}async getRecentBlockhashAndContext(e){const{context:t,value:{blockhash:n}}=await this.getLatestBlockhashAndContext(e);return{context:t,value:{blockhash:n,feeCalculator:{get lamportsPerSignature(){throw new Error("The capability to fetch `lamportsPerSignature` using the `getRecentBlockhash` API is no longer offered by the network. Use the `getFeeForMessage` API to obtain the fee for a given message.")},toJSON:()=>({})}}}}async getRecentPerformanceSamples(e){const t=np(await this._rpcRequest("getRecentPerformanceSamples",e?[e]:[]),jb);if("error"in t)throw new Wm(t.error,"failed to get recent performance samples");return t.result}async getFeeCalculatorForBlockhash(e,t){const n=this._buildArgs([e],t),r=np(await this._rpcRequest("getFeeCalculatorForBlockhash",n),Xb);if("error"in r)throw new Wm(r.error,"failed to get fee calculator");const{context:s,value:i}=r.result;return{context:s,value:null!==i?i.feeCalculator:null}}async getFeeForMessage(e,t){const n=um(e.serialize()).toString("base64"),r=this._buildArgs([n],t),s=np(await this._rpcRequest("getFeeForMessage",r),vy(up(dp())));if("error"in s)throw new Wm(s.error,"failed to get fee for message");if(null===s.result)throw new Error("invalid blockhash");return s.result}async getRecentPrioritizationFees(e){const t=e?.lockedWritableAccounts?.map(e=>e.toBase58()),n=t?.length?[t]:[],r=np(await this._rpcRequest("getRecentPrioritizationFees",n),Fy);if("error"in r)throw new Wm(r.error,"failed to get recent prioritization fees");return r.result}async getRecentBlockhash(e){try{return(await this.getRecentBlockhashAndContext(e)).value}catch(e){throw new Error("failed to get recent blockhash: "+e)}}async getLatestBlockhash(e){try{return(await this.getLatestBlockhashAndContext(e)).value}catch(e){throw new Error("failed to get recent blockhash: "+e)}}async getLatestBlockhashAndContext(e){const{commitment:t,config:n}=fy(e),r=this._buildArgs([],t,void 0,n),s=np(await this._rpcRequest("getLatestBlockhash",r),zb);if("error"in s)throw new Wm(s.error,"failed to get latest blockhash");return s.result}async isBlockhashValid(e,t){const{commitment:n,config:r}=fy(t),s=this._buildArgs([e],n,void 0,r),i=np(await this._rpcRequest("isBlockhashValid",s),Vb);if("error"in i)throw new Wm(i.error,"failed to determine if the blockhash `"+e+"`is valid");return i.result}async getVersion(){const e=np(await this._rpcRequest("getVersion",[]),by(By));if("error"in e)throw new Wm(e.error,"failed to get version");return e.result}async getGenesisHash(){const e=np(await this._rpcRequest("getGenesisHash",[]),by(fp()));if("error"in e)throw new Wm(e.error,"failed to get genesis hash");return e.result}async getBlock(e,t){const{commitment:n,config:r}=fy(t),s=this._buildArgsAtLeastConfirmed([e],n,void 0,r),i=await this._rpcRequest("getBlock",s);try{switch(r?.transactionDetails){case"accounts":{const e=np(i,Pb);if("error"in e)throw e.error;return e.result}case"none":{const e=np(i,Ub);if("error"in e)throw e.error;return e.result}default:{const e=np(i,Lb);if("error"in e)throw e.error;const{result:t}=e;return t?{...t,transactions:t.transactions.map(({transaction:e,meta:t,version:n})=>({meta:t,transaction:{...e,message:Ey(n,e.message)},version:n}))}:null}}}catch(e){throw new Wm(e,"failed to get confirmed block")}}async getParsedBlock(e,t){const{commitment:n,config:r}=fy(t),s=this._buildArgsAtLeastConfirmed([e],n,"jsonParsed",r),i=await this._rpcRequest("getBlock",s);try{switch(r?.transactionDetails){case"accounts":{const e=np(i,$b);if("error"in e)throw e.error;return e.result}case"none":{const e=np(i,Kb);if("error"in e)throw e.error;return e.result}default:{const e=np(i,Fb);if("error"in e)throw e.error;return e.result}}}catch(e){throw new Wm(e,"failed to get block")}}async getBlockProduction(e){let t,n;if("string"==typeof e)n=e;else if(e){const{commitment:r,...s}=e;n=r,t=s}const r=this._buildArgs([],n,"base64",t),s=np(await this._rpcRequest("getBlockProduction",r),Ly);if("error"in s)throw new Wm(s.error,"failed to get block production information");return s.result}async getTransaction(e,t){const{commitment:n,config:r}=fy(t),s=this._buildArgsAtLeastConfirmed([e],n,void 0,r),i=np(await this._rpcRequest("getTransaction",s),Hb);if("error"in i)throw new Wm(i.error,"failed to get transaction");const o=i.result;return o?{...o,transaction:{...o.transaction,message:Ey(o.version,o.transaction.message)}}:o}async getParsedTransaction(e,t){const{commitment:n,config:r}=fy(t),s=this._buildArgsAtLeastConfirmed([e],n,"jsonParsed",r),i=np(await this._rpcRequest("getTransaction",s),qb);if("error"in i)throw new Wm(i.error,"failed to get transaction");return i.result}async getParsedTransactions(e,t){const{commitment:n,config:r}=fy(t),s=e.map(e=>({methodName:"getTransaction",args:this._buildArgsAtLeastConfirmed([e],n,"jsonParsed",r)}));return(await this._rpcBatchRequest(s)).map(e=>{const t=np(e,qb);if("error"in t)throw new Wm(t.error,"failed to get transactions");return t.result})}async getTransactions(e,t){const{commitment:n,config:r}=fy(t),s=e.map(e=>({methodName:"getTransaction",args:this._buildArgsAtLeastConfirmed([e],n,void 0,r)}));return(await this._rpcBatchRequest(s)).map(e=>{const t=np(e,Hb);if("error"in t)throw new Wm(t.error,"failed to get transactions");const n=t.result;return n?{...n,transaction:{...n.transaction,message:Ey(n.version,n.transaction.message)}}:n})}async getConfirmedBlock(e,t){const n=this._buildArgsAtLeastConfirmed([e],t),r=np(await this._rpcRequest("getBlock",n),Gb);if("error"in r)throw new Wm(r.error,"failed to get confirmed block");const s=r.result;if(!s)throw new Error("Confirmed block "+e+" not found");const i={...s,transactions:s.transactions.map(({transaction:e,meta:t})=>{const n=new Bm(e.message);return{meta:t,transaction:{...e,message:n}}})};return{...i,transactions:i.transactions.map(({transaction:e,meta:t})=>({meta:t,transaction:Fm.populate(e.message,e.signatures)}))}}async getBlocks(e,t,n){const r=this._buildArgsAtLeastConfirmed(void 0!==t?[e,t]:[e],n),s=np(await this._rpcRequest("getBlocks",r),by(op(dp())));if("error"in s)throw new Wm(s.error,"failed to get blocks");return s.result}async getBlockSignatures(e,t){const n=this._buildArgsAtLeastConfirmed([e],t,void 0,{transactionDetails:"signatures",rewards:!1}),r=np(await this._rpcRequest("getBlock",n),Wb);if("error"in r)throw new Wm(r.error,"failed to get block");const s=r.result;if(!s)throw new Error("Block "+e+" not found");return s}async getConfirmedBlockSignatures(e,t){const n=this._buildArgsAtLeastConfirmed([e],t,void 0,{transactionDetails:"signatures",rewards:!1}),r=np(await this._rpcRequest("getBlock",n),Wb);if("error"in r)throw new Wm(r.error,"failed to get confirmed block");const s=r.result;if(!s)throw new Error("Confirmed block "+e+" not found");return s}async getConfirmedTransaction(e,t){const n=this._buildArgsAtLeastConfirmed([e],t),r=np(await this._rpcRequest("getTransaction",n),Hb);if("error"in r)throw new Wm(r.error,"failed to get transaction");const s=r.result;if(!s)return s;const i=new Bm(s.transaction.message),o=s.transaction.signatures;return{...s,transaction:Fm.populate(i,o)}}async getParsedConfirmedTransaction(e,t){const n=this._buildArgsAtLeastConfirmed([e],t,"jsonParsed"),r=np(await this._rpcRequest("getTransaction",n),qb);if("error"in r)throw new Wm(r.error,"failed to get confirmed transaction");return r.result}async getParsedConfirmedTransactions(e,t){const n=e.map(e=>({methodName:"getTransaction",args:this._buildArgsAtLeastConfirmed([e],t,"jsonParsed")}));return(await this._rpcBatchRequest(n)).map(e=>{const t=np(e,qb);if("error"in t)throw new Wm(t.error,"failed to get confirmed transactions");return t.result})}async getConfirmedSignaturesForAddress(e,t,n){let r={},s=await this.getFirstAvailableBlock();for(;!("until"in r)&&!(--t<=0||t<s);)try{const e=await this.getConfirmedBlockSignatures(t,"finalized");e.signatures.length>0&&(r.until=e.signatures[e.signatures.length-1].toString())}catch(e){if(e instanceof Error&&e.message.includes("skipped"))continue;throw e}let i=await this.getSlot("finalized");for(;!("before"in r||++n>i);)try{const e=await this.getConfirmedBlockSignatures(n);e.signatures.length>0&&(r.before=e.signatures[e.signatures.length-1].toString())}catch(e){if(e instanceof Error&&e.message.includes("skipped"))continue;throw e}return(await this.getConfirmedSignaturesForAddress2(e,r)).map(e=>e.signature)}async getConfirmedSignaturesForAddress2(e,t,n){const r=this._buildArgsAtLeastConfirmed([e.toBase58()],n,void 0,t),s=np(await this._rpcRequest("getConfirmedSignaturesForAddress2",r),rb);if("error"in s)throw new Wm(s.error,"failed to get confirmed signatures for address");return s.result}async getSignaturesForAddress(e,t,n){const r=this._buildArgsAtLeastConfirmed([e.toBase58()],n,void 0,t),s=np(await this._rpcRequest("getSignaturesForAddress",r),sb);if("error"in s)throw new Wm(s.error,"failed to get signatures for address");return s.result}async getAddressLookupTable(e,t){const{context:n,value:r}=await this.getAccountInfoAndContext(e,t);let s=null;return null!==r&&(s=new cy({key:e,state:cy.deserialize(r.data)})),{context:n,value:s}}async getNonceAndContext(e,t){const{context:n,value:r}=await this.getAccountInfoAndContext(e,t);let s=null;return null!==r&&(s=Xm.fromAccountData(r.data)),{context:n,value:s}}async getNonce(e,t){return await this.getNonceAndContext(e,t).then(e=>e.value).catch(t=>{throw new Error("failed to get nonce for account "+e.toBase58()+": "+t)})}async requestAirdrop(e,t){const n=np(await this._rpcRequest("requestAirdrop",[e.toBase58(),t]),Yb);if("error"in n)throw new Wm(n.error,`airdrop to ${e.toBase58()} failed`);return n.result}async _blockhashWithExpiryBlockHeight(e){if(!e){for(;this._pollingBlockhash;)await Hm(100);const e=Date.now()-this._blockhashInfo.lastFetch>=3e4;if(null!==this._blockhashInfo.latestBlockhash&&!e)return this._blockhashInfo.latestBlockhash}return await this._pollNewBlockhash()}async _pollNewBlockhash(){this._pollingBlockhash=!0;try{const e=Date.now(),t=this._blockhashInfo.latestBlockhash,n=t?t.blockhash:null;for(let e=0;e<50;e++){const e=await this.getLatestBlockhash("finalized");if(n!==e.blockhash)return this._blockhashInfo={latestBlockhash:e,lastFetch:Date.now(),transactionSignatures:[],simulatedSignatures:[]},e;await Hm(200)}throw new Error(`Unable to obtain a new blockhash after ${Date.now()-e}ms`)}finally{this._pollingBlockhash=!1}}async getStakeMinimumDelegation(e){const{commitment:t,config:n}=fy(e),r=this._buildArgs([],t,"base64",n),s=np(await this._rpcRequest("getStakeMinimumDelegation",r),vy(dp()));if("error"in s)throw new Wm(s.error,"failed to get stake minimum delegation");return s.result}async simulateTransaction(e,t,n){if("message"in e){const r=e.serialize(),s=Oo.Buffer.from(r).toString("base64");if(Array.isArray(t)||void 0!==n)throw new Error("Invalid arguments");const i=t||{};i.encoding="base64","commitment"in i||(i.commitment=this.commitment),t&&"object"==typeof t&&"innerInstructions"in t&&(i.innerInstructions=t.innerInstructions);const o=[s,i],a=np(await this._rpcRequest("simulateTransaction",o),My);if("error"in a)throw new Error("failed to simulate transaction: "+a.error.message);return a.result}let r;if(e instanceof Fm){let t=e;r=new Fm,r.feePayer=t.feePayer,r.instructions=e.instructions,r.nonceInfo=t.nonceInfo,r.signatures=t.signatures}else r=Fm.populate(e),r._message=r._json=void 0;if(void 0!==t&&!Array.isArray(t))throw new Error("Invalid arguments");const s=t;if(r.nonceInfo&&s)r.sign(...s);else{let e=this._disableBlockhashCaching;for(;;){const t=await this._blockhashWithExpiryBlockHeight(e);if(r.lastValidBlockHeight=t.lastValidBlockHeight,r.recentBlockhash=t.blockhash,!s)break;if(r.sign(...s),!r.signature)throw new Error("!signature");const n=r.signature.toString("base64");if(!this._blockhashInfo.simulatedSignatures.includes(n)&&!this._blockhashInfo.transactionSignatures.includes(n)){this._blockhashInfo.simulatedSignatures.push(n);break}e=!0}}const i=r._compile(),o=i.serialize(),a=r._serialize(o).toString("base64"),c={encoding:"base64",commitment:this.commitment};if(n){const e=(Array.isArray(n)?n:i.nonProgramIds()).map(e=>e.toBase58());c.accounts={encoding:"base64",addresses:e}}s&&(c.sigVerify=!0),t&&"object"==typeof t&&"innerInstructions"in t&&(c.innerInstructions=t.innerInstructions);const l=[a,c],u=np(await this._rpcRequest("simulateTransaction",l),My);if("error"in u){let e;if("data"in u.error&&(e=u.error.data.logs,e&&Array.isArray(e))){const t="\n ";e.join(t)}throw new Gm({action:"simulate",signature:"",transactionMessage:u.error.message,logs:e})}return u.result}async sendTransaction(e,t,n){if("version"in e){if(t&&Array.isArray(t))throw new Error("Invalid arguments");const n=e.serialize();return await this.sendRawTransaction(n,t)}if(void 0===t||!Array.isArray(t))throw new Error("Invalid arguments");const r=t;if(e.nonceInfo)e.sign(...r);else{let t=this._disableBlockhashCaching;for(;;){const n=await this._blockhashWithExpiryBlockHeight(t);if(e.lastValidBlockHeight=n.lastValidBlockHeight,e.recentBlockhash=n.blockhash,e.sign(...r),!e.signature)throw new Error("!signature");const s=e.signature.toString("base64");if(!this._blockhashInfo.transactionSignatures.includes(s)){this._blockhashInfo.transactionSignatures.push(s);break}t=!0}}const s=e.serialize();return await this.sendRawTransaction(s,n)}async sendRawTransaction(e,t){const n=um(e).toString("base64");return await this.sendEncodedTransaction(n,t)}async sendEncodedTransaction(e,t){const n={encoding:"base64"},r=t&&t.skipPreflight,s=!0===r?"processed":t&&t.preflightCommitment||this.commitment;t&&null!=t.maxRetries&&(n.maxRetries=t.maxRetries),t&&null!=t.minContextSlot&&(n.minContextSlot=t.minContextSlot),r&&(n.skipPreflight=r),s&&(n.preflightCommitment=s);const i=[e,n],o=np(await this._rpcRequest("sendTransaction",i),Jb);if("error"in o){let e;throw"data"in o.error&&(e=o.error.data.logs),new Gm({action:r?"send":"simulate",signature:"",transactionMessage:o.error.message,logs:e})}return o.result}_wsOnOpen(){this._rpcWebSocketConnected=!0,this._rpcWebSocketHeartbeat=setInterval(()=>{(async()=>{try{await this._rpcWebSocket.notify("ping")}catch{}})()},5e3),this._updateSubscriptions()}_wsOnError(e){this._rpcWebSocketConnected=!1}_wsOnClose(e){this._rpcWebSocketConnected=!1,this._rpcWebSocketGeneration=(this._rpcWebSocketGeneration+1)%Number.MAX_SAFE_INTEGER,this._rpcWebSocketIdleTimeout&&(clearTimeout(this._rpcWebSocketIdleTimeout),this._rpcWebSocketIdleTimeout=null),this._rpcWebSocketHeartbeat&&(clearInterval(this._rpcWebSocketHeartbeat),this._rpcWebSocketHeartbeat=null),1e3!==e?(this._subscriptionCallbacksByServerSubscriptionId={},Object.entries(this._subscriptionsByHash).forEach(([e,t])=>{this._setSubscription(e,{...t,state:"pending"})})):this._updateSubscriptions()}_setSubscription(e,t){const n=this._subscriptionsByHash[e]?.state;if(this._subscriptionsByHash[e]=t,n!==t.state){const n=this._subscriptionStateChangeCallbacksByHash[e];n&&n.forEach(e=>{try{e(t.state)}catch{}})}}_onSubscriptionStateChange(e,t){const n=this._subscriptionHashByClientSubscriptionId[e];if(null==n)return()=>{};const r=this._subscriptionStateChangeCallbacksByHash[n]||=new Set;return r.add(t),()=>{r.delete(t),0===r.size&&delete this._subscriptionStateChangeCallbacksByHash[n]}}async _updateSubscriptions(){if(0===Object.keys(this._subscriptionsByHash).length)return void(this._rpcWebSocketConnected&&(this._rpcWebSocketConnected=!1,this._rpcWebSocketIdleTimeout=setTimeout(()=>{this._rpcWebSocketIdleTimeout=null;try{this._rpcWebSocket.close()}catch(e){Error}},500)));if(null!==this._rpcWebSocketIdleTimeout&&(clearTimeout(this._rpcWebSocketIdleTimeout),this._rpcWebSocketIdleTimeout=null,this._rpcWebSocketConnected=!0),!this._rpcWebSocketConnected)return void this._rpcWebSocket.connect();const e=this._rpcWebSocketGeneration,t=()=>e===this._rpcWebSocketGeneration;await Promise.all(Object.keys(this._subscriptionsByHash).map(async e=>{const n=this._subscriptionsByHash[e];if(void 0!==n)switch(n.state){case"pending":case"unsubscribed":if(0===n.callbacks.size)return delete this._subscriptionsByHash[e],"unsubscribed"===n.state&&delete this._subscriptionCallbacksByServerSubscriptionId[n.serverSubscriptionId],void await this._updateSubscriptions();await(async()=>{const{args:r,method:s}=n;try{this._setSubscription(e,{...n,state:"subscribing"});const t=await this._rpcWebSocket.call(s,r);this._setSubscription(e,{...n,serverSubscriptionId:t,state:"subscribed"}),this._subscriptionCallbacksByServerSubscriptionId[t]=n.callbacks,await this._updateSubscriptions()}catch(r){if(!t())return;this._setSubscription(e,{...n,state:"pending"}),await this._updateSubscriptions()}})();break;case"subscribed":0===n.callbacks.size&&await(async()=>{const{serverSubscriptionId:r,unsubscribeMethod:s}=n;if(this._subscriptionsAutoDisposedByRpc.has(r))this._subscriptionsAutoDisposedByRpc.delete(r);else{this._setSubscription(e,{...n,state:"unsubscribing"}),this._setSubscription(e,{...n,state:"unsubscribing"});try{await this._rpcWebSocket.call(s,[r])}catch(r){if(Error,!t())return;return this._setSubscription(e,{...n,state:"subscribed"}),void await this._updateSubscriptions()}}this._setSubscription(e,{...n,state:"unsubscribed"}),await this._updateSubscriptions()})()}}))}_handleServerNotification(e,t){const n=this._subscriptionCallbacksByServerSubscriptionId[e];void 0!==n&&n.forEach(e=>{try{e(...t)}catch(e){}})}_wsOnAccountNotification(e){const{result:t,subscription:n}=np(e,ib);this._handleServerNotification(n,[t.value,t.context])}_makeSubscription(e,t){const n=this._nextClientSubscriptionId++,r=ry([e.method,t]),s=this._subscriptionsByHash[r];return void 0===s?this._subscriptionsByHash[r]={...e,args:t,callbacks:new Set([e.callback]),state:"pending"}:s.callbacks.add(e.callback),this._subscriptionHashByClientSubscriptionId[n]=r,this._subscriptionDisposeFunctionsByClientSubscriptionId[n]=async()=>{delete this._subscriptionDisposeFunctionsByClientSubscriptionId[n],delete this._subscriptionHashByClientSubscriptionId[n];const t=this._subscriptionsByHash[r];Nm(void 0!==t,`Could not find a \`Subscription\` when tearing down client subscription #${n}`),t.callbacks.delete(e.callback),await this._updateSubscriptions()},this._updateSubscriptions(),n}onAccountChange(e,t,n){const{commitment:r,config:s}=fy(n),i=this._buildArgs([e.toBase58()],r||this._commitment||"finalized","base64",s);return this._makeSubscription({callback:t,method:"accountSubscribe",unsubscribeMethod:"accountUnsubscribe"},i)}async removeAccountChangeListener(e){await this._unsubscribeClientSubscription(e,"account change")}_wsOnProgramAccountNotification(e){const{result:t,subscription:n}=np(e,ab);this._handleServerNotification(n,[{accountId:t.value.pubkey,accountInfo:t.value.account},t.context])}onProgramAccountChange(e,t,n,r){const{commitment:s,config:i}=fy(n),o=this._buildArgs([e.toBase58()],s||this._commitment||"finalized","base64",i||(r?{filters:py(r)}:void 0));return this._makeSubscription({callback:t,method:"programSubscribe",unsubscribeMethod:"programUnsubscribe"},o)}async removeProgramAccountChangeListener(e){await this._unsubscribeClientSubscription(e,"program account change")}onLogs(e,t,n){const r=this._buildArgs(["object"==typeof e?{mentions:[e.toString()]}:e],n||this._commitment||"finalized");return this._makeSubscription({callback:t,method:"logsSubscribe",unsubscribeMethod:"logsUnsubscribe"},r)}async removeOnLogsListener(e){await this._unsubscribeClientSubscription(e,"logs")}_wsOnLogsNotification(e){const{result:t,subscription:n}=np(e,Zb);this._handleServerNotification(n,[t.value,t.context])}_wsOnSlotNotification(e){const{result:t,subscription:n}=np(e,lb);this._handleServerNotification(n,[t])}onSlotChange(e){return this._makeSubscription({callback:e,method:"slotSubscribe",unsubscribeMethod:"slotUnsubscribe"},[])}async removeSlotChangeListener(e){await this._unsubscribeClientSubscription(e,"slot change")}_wsOnSlotUpdatesNotification(e){const{result:t,subscription:n}=np(e,db);this._handleServerNotification(n,[t])}onSlotUpdate(e){return this._makeSubscription({callback:e,method:"slotsUpdatesSubscribe",unsubscribeMethod:"slotsUpdatesUnsubscribe"},[])}async removeSlotUpdateListener(e){await this._unsubscribeClientSubscription(e,"slot update")}async _unsubscribeClientSubscription(e,t){const n=this._subscriptionDisposeFunctionsByClientSubscriptionId[e];n&&await n()}_buildArgs(e,t,n,r){const s=t||this._commitment;if(s||n||r){let t={};n&&(t.encoding=n),s&&(t.commitment=s),r&&(t=Object.assign(t,r)),e.push(t)}return e}_buildArgsAtLeastConfirmed(e,t,n,r){const s=t||this._commitment;if(s&&!["confirmed","finalized"].includes(s))throw new Error("Using Connection with default commitment: `"+this._commitment+"`, but method requires at least `confirmed`");return this._buildArgs(e,t,n,r)}_wsOnSignatureNotification(e){const{result:t,subscription:n}=np(e,hb);"receivedSignature"!==t.value&&this._subscriptionsAutoDisposedByRpc.add(n),this._handleServerNotification(n,"receivedSignature"===t.value?[{type:"received"},t.context]:[{type:"status",result:t.value},t.context])}onSignature(e,t,n){const r=this._buildArgs([e],n||this._commitment||"finalized"),s=this._makeSubscription({callback:(e,n)=>{if("status"===e.type){t(e.result,n);try{this.removeSignatureListener(s)}catch(e){}}},method:"signatureSubscribe",unsubscribeMethod:"signatureUnsubscribe"},r);return s}onSignatureWithOptions(e,t,n){const{commitment:r,...s}={...n,commitment:n&&n.commitment||this._commitment||"finalized"},i=this._buildArgs([e],r,void 0,s),o=this._makeSubscription({callback:(e,n)=>{t(e,n);try{this.removeSignatureListener(o)}catch(e){}},method:"signatureSubscribe",unsubscribeMethod:"signatureUnsubscribe"},i);return o}async removeSignatureListener(e){await this._unsubscribeClientSubscription(e,"signature result")}_wsOnRootNotification(e){const{result:t,subscription:n}=np(e,gb);this._handleServerNotification(n,[t])}onRootChange(e){return this._makeSubscription({callback:e,method:"rootSubscribe",unsubscribeMethod:"rootUnsubscribe"},[])}async removeRootChangeListener(e){await this._unsubscribeClientSubscription(e,"root change")}}class nv{constructor(e){this._keypair=void 0,this._keypair=e??om()}static generate(){return new nv(om())}static fromSecretKey(e,t){if(64!==e.byteLength)throw new Error("bad secret key size");const n=e.slice(32,64);if(!t||!t.skipValidation){const t=e.slice(0,32),r=am(t);for(let e=0;e<32;e++)if(n[e]!==r[e])throw new Error("provided secretKey is invalid")}return new nv({publicKey:n,secretKey:e})}static fromSeed(e){const t=am(e),n=new Uint8Array(64);return n.set(e),n.set(t,32),new nv({publicKey:t,secretKey:n})}get publicKey(){return new mm(this._keypair.publicKey)}get secretKey(){return new Uint8Array(this._keypair.secretKey)}}Object.freeze({CreateLookupTable:{index:0,layout:Kl.struct([Kl.u32("instruction"),Ym("recentSlot"),Kl.u8("bumpSeed")])},FreezeLookupTable:{index:1,layout:Kl.struct([Kl.u32("instruction")])},ExtendLookupTable:{index:2,layout:Kl.struct([Kl.u32("instruction"),Ym(),Kl.seq(Am(),Kl.offset(Kl.u32(),-8),"addresses")])},DeactivateLookupTable:{index:3,layout:Kl.struct([Kl.u32("instruction")])},CloseLookupTable:{index:4,layout:Kl.struct([Kl.u32("instruction")])}}),new mm("AddressLookupTab1e1111111111111111111111111");const rv=Object.freeze({RequestUnits:{index:0,layout:Kl.struct([Kl.u8("instruction"),Kl.u32("units"),Kl.u32("additionalFee")])},RequestHeapFrame:{index:1,layout:Kl.struct([Kl.u8("instruction"),Kl.u32("bytes")])},SetComputeUnitLimit:{index:2,layout:Kl.struct([Kl.u8("instruction"),Kl.u32("units")])},SetComputeUnitPrice:{index:3,layout:Kl.struct([Kl.u8("instruction"),Ym("microLamports")])}});class sv{constructor(){}static requestUnits(e){const t=qm(rv.RequestUnits,e);return new Pm({keys:[],programId:this.programId,data:t})}static requestHeapFrame(e){const t=qm(rv.RequestHeapFrame,e);return new Pm({keys:[],programId:this.programId,data:t})}static setComputeUnitLimit(e){const t=qm(rv.SetComputeUnitLimit,e);return new Pm({keys:[],programId:this.programId,data:t})}static setComputeUnitPrice(e){const t=qm(rv.SetComputeUnitPrice,{microLamports:BigInt(e.microLamports)});return new Pm({keys:[],programId:this.programId,data:t})}}var iv;sv.programId=new mm("ComputeBudget111111111111111111111111111111"),Kl.struct([Kl.u8("numSignatures"),Kl.u8("padding"),Kl.u16("signatureOffset"),Kl.u16("signatureInstructionIndex"),Kl.u16("publicKeyOffset"),Kl.u16("publicKeyInstructionIndex"),Kl.u16("messageDataOffset"),Kl.u16("messageDataSize"),Kl.u16("messageInstructionIndex")]),new mm("Ed25519SigVerify111111111111111111111111111"),im.utils.isValidPrivateKey,Kl.struct([Kl.u8("numSignatures"),Kl.u16("signatureOffset"),Kl.u8("signatureInstructionIndex"),Kl.u16("ethAddressOffset"),Kl.u8("ethAddressInstructionIndex"),Kl.u16("messageDataOffset"),Kl.u16("messageDataSize"),Kl.u8("messageInstructionIndex"),Kl.blob(20,"ethAddress"),Kl.blob(64,"signature"),Kl.u8("recoveryId")]),new mm("KeccakSecp256k11111111111111111111111111111"),new mm("StakeConfig11111111111111111111111111111111");class ov{constructor(e,t,n){this.unixTimestamp=void 0,this.epoch=void 0,this.custodian=void 0,this.unixTimestamp=e,this.epoch=t,this.custodian=n}}iv=ov,ov.default=new iv(0,0,mm.default),Object.freeze({Initialize:{index:0,layout:Kl.struct([Kl.u32("instruction"),((e="authorized")=>Kl.struct([Am("staker"),Am("withdrawer")],e))(),((e="lockup")=>Kl.struct([Kl.ns64("unixTimestamp"),Kl.ns64("epoch"),Am("custodian")],e))()])},Authorize:{index:1,layout:Kl.struct([Kl.u32("instruction"),Am("newAuthorized"),Kl.u32("stakeAuthorizationType")])},Delegate:{index:2,layout:Kl.struct([Kl.u32("instruction")])},Split:{index:3,layout:Kl.struct([Kl.u32("instruction"),Kl.ns64("lamports")])},Withdraw:{index:4,layout:Kl.struct([Kl.u32("instruction"),Kl.ns64("lamports")])},Deactivate:{index:5,layout:Kl.struct([Kl.u32("instruction")])},Merge:{index:7,layout:Kl.struct([Kl.u32("instruction")])},AuthorizeWithSeed:{index:8,layout:Kl.struct([Kl.u32("instruction"),Am("newAuthorized"),Kl.u32("stakeAuthorizationType"),Sm("authoritySeed"),Am("authorityOwner")])}}),new mm("Stake11111111111111111111111111111111111111"),Object.freeze({InitializeAccount:{index:0,layout:Kl.struct([Kl.u32("instruction"),((e="voteInit")=>Kl.struct([Am("nodePubkey"),Am("authorizedVoter"),Am("authorizedWithdrawer"),Kl.u8("commission")],e))()])},Authorize:{index:1,layout:Kl.struct([Kl.u32("instruction"),Am("newAuthorized"),Kl.u32("voteAuthorizationType")])},Withdraw:{index:3,layout:Kl.struct([Kl.u32("instruction"),Kl.ns64("lamports")])},UpdateValidatorIdentity:{index:4,layout:Kl.struct([Kl.u32("instruction")])},AuthorizeWithSeed:{index:10,layout:Kl.struct([Kl.u32("instruction"),((e="voteAuthorizeWithSeedArgs")=>Kl.struct([Kl.u32("voteAuthorizationType"),Am("currentAuthorityDerivedKeyOwnerPubkey"),Sm("currentAuthorityDerivedKeySeed"),Am("newAuthorized")],e))()])}}),new mm("Vote111111111111111111111111111111111111111"),new mm("Va1idator1nfo111111111111111111111111111111"),mp({name:fp(),website:hp(fp()),details:hp(fp()),iconUrl:hp(fp()),keybaseUsername:hp(fp())}),new mm("Vote111111111111111111111111111111111111111"),Kl.struct([Am("nodePubkey"),Am("authorizedWithdrawer"),Kl.u8("commission"),Kl.nu64(),Kl.seq(Kl.struct([Kl.nu64("slot"),Kl.u32("confirmationCount")]),Kl.offset(Kl.u32(),-8),"votes"),Kl.u8("rootSlotValid"),Kl.nu64("rootSlot"),Kl.nu64(),Kl.seq(Kl.struct([Kl.nu64("epoch"),Am("authorizedVoter")]),Kl.offset(Kl.u32(),-8),"authorizedVoters"),Kl.struct([Kl.seq(Kl.struct([Am("authorizedPubkey"),Kl.nu64("epochOfLastAuthorizedSwitch"),Kl.nu64("targetEpoch")]),32,"buf"),Kl.nu64("idx"),Kl.u8("isEmpty")],"priorVoters"),Kl.nu64(),Kl.seq(Kl.struct([Kl.nu64("epoch"),Kl.nu64("credits"),Kl.nu64("prevCredits")]),Kl.offset(Kl.u32(),-8),"epochCredits"),Kl.struct([Kl.nu64("slot"),Kl.nu64("timestamp")],"lastTimestamp")]);function av(e){return/^0x[a-fA-F0-9]{64}$/.test(e)}function cv(e){const t=new Map;for(const n of e)t.set(jt(n.symbol),n);return t}function lv(e,t,n){const r=function(e,t){return e.get(jt(t))}(e,t);if(!r){throw It(`Token ${t} not supported for ${n}. Supported: ${Array.from(e.keys()).join(", ")}`,"tokenSymbol")}return r}function uv(e){if(null==e||!av(e))throw kt("privateKey","a 0x-prefixed 64-character hex string (e.g., 0x1234...abcd)","Ethereum private key")}function dv(e,t,n){return{symbol:e,quantity:t,decimals:n,contractAddress:null,isNative:!0}}function hv(e,t){return{symbol:e.symbol,quantity:t,decimals:e.decimals??18,contractAddress:e.contractAddress,isNative:!1}}function gv(e,t){return{symbol:e.symbol,quantity:t,decimals:e.decimals??9,contractAddress:e.mintAddress,isNative:e.isNative??!1}}function fv(e,t,n){const r=e.find(e=>e.symbol===t);if(!r){const r=e.map(e=>e.symbol).join(", ");throw St("tokenSymbol",`Unsupported ${n} token: ${t}. Supported: ${r}`)}return r}const pv={Ethereum:"Ethereum bridging not configured. Provide ethereumPrivateKey in config.",Solana:"Solana bridging not configured. Provide solanaPrivateKey in config."};function mv(e,t,n){if(void 0===e)throw It(n??pv[t],`${t.toLowerCase()}Strategy`);return e}function yv(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 bv="Token symbol resolution failed. This is an internal error - BridgeService should resolve tokenId to symbol before calling strategy.",vv="Bridge request ID missing from RequestTokenBridgeOut response",wv="BridgeTokenOut response missing transaction hash";function Ev(e){if(void 0===e||""===e)throw It(bv,"tokenSymbol");return e}function Av(t,n){if(!e.isAddress(t)){throw kt(n??"address","a valid 0x-prefixed Ethereum address",t)}}function Sv(e,t){try{return new mm(e)}catch{throw kt(t??"address","a valid Solana address (base58)",e)}}function kv(e){try{return new mm(e)}catch{throw kt("address","a valid Solana address (base58)",e)}}function Tv(e){const t={};for(const[n,r]of Object.entries(e))void 0!==r&&(r&&"object"==typeof r&&!Array.isArray(r)?t[n]=Tv(r):t[n]=r);return t}function Iv(e,t){const n=In(e,-1);if(n<=0)throw new Error(`Invalid bridge amount for ${t}: "${e}". Amount must be a positive number.`);return n}var Nv,Cv,_v,xv,Rv,Bv;function Dv(){return Cv?Nv:(Cv=1,Nv={space:"",cycles:!1,replacer:(e,t)=>t,stringify:JSON.stringify})}function Ov(){return xv?_v:(xv=1,_v={isArray:Array.isArray,assign:Object.assign,isObject:e=>"object"==typeof e,isFunction:e=>"function"==typeof e,isBoolean:e=>"boolean"==typeof e,isRegex:e=>e instanceof RegExp,keys:Object.keys})}function Mv(){if(Bv)return Rv;Bv=1;const e=Dv(),t=Ov().isFunction,n=Ov().isBoolean,r=Ov().isObject,s=Ov().isArray,i=Ov().isRegex,o=Ov().assign,a=Ov().keys;return Rv=function(c,l){l=l||o({},e),t(l)&&(l={compare:l});const u=l.space||e.space,d=n(l.cycles)?l.cycles:e.cycles,h=l.replacer||e.replacer,g=l.stringify||e.stringify,f=l.compare&&(p=l.compare,function(e){return function(t,n){const r={key:t,value:e[t]},s={key:n,value:e[n]};return p(r,s)}});var p;d||g(c);const m=[];return function e(t,n,o,c){const l=u?"\n"+new Array(c+1).join(u):"",p=u?": ":":";if(o=function(e){return null==e?e:i(e)?e.toString():e.toJSON?e.toJSON():e}(o),void 0!==(o=h.call(t,n,o))){if(!r(o)||null===o)return g(o);if(s(o)){const t=[];for(let n=0;n<o.length;n++){const r=e(o,n,o[n],c+1)||g(null);t.push(l+u+r)}return"["+t.join(",")+l+"]"}{if(d){if(-1!==m.indexOf(o))return g("[Circular]");m.push(o)}const t=a(o).sort(f&&f(o)),n=[];for(let r=0;r<t.length;r++){const s=t[r],i=e(o,s,o[s],c+1);if(!i)continue;const a=g(s)+p+i;n.push(l+u+a)}return m.splice(m.indexOf(o),1),"{"+n.join(",")+l+"}"}}}({"":c},"",c,0)},Rv}var Lv=So(Mv());let Uv=null;if("undefined"==typeof window&&"undefined"!=typeof require)try{Uv=f}catch{}function Pv(){if(void 0!==Uv?.randomUUID)try{return Uv.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 Fv={name:"GalaConnect",chainId:1},$v=[{name:"destinationChainId",type:"uint256"},{name:"destinationChainTxFee",type:"destinationChainTxFee"},{name:"quantity",type:"string"},{name:"recipient",type:"string"},{name:"tokenInstance",type:"tokenInstance"},{name:"uniqueKey",type:"string"}],Kv=[{name:"collection",type:"string"},{name:"category",type:"string"},{name:"type",type:"string"},{name:"additionalKey",type:"string"}],Gv=[{name:"collection",type:"string"},{name:"category",type:"string"},{name:"type",type:"string"},{name:"additionalKey",type:"string"},{name:"instance",type:"string"}],Wv=[{name:"name",type:"string"},{name:"symbol",type:"string"}],Hv={GalaTransaction:$v,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:Kv,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:Gv,externalQuoteToken:Wv,tokenInstance:Gv},qv={GalaTransaction:$v,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:Kv,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:Wv,externalQuoteToken:Wv,externalCrossRateToken:Wv,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:Gv,tokenInstance:Gv};function zv(e){return e?qv:Hv}async function Vv(e,t){const{wallet:n}=t,r=e.uniqueKey??`galaconnect-operation-${Pv()}`,s="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),a={destinationChainId:s,destinationChainTxFee:Tv(o?{...i,galaExchangeRate:void 0}:{...i,galaExchangeCrossRate:void 0}),quantity:e.quantity,recipient:e.recipient,tokenInstance:e.tokenInstance,uniqueKey:r},c=zv(o),l=await n.signTypedData(Fv,c,a),u=`Ethereum Signed Message:\n${Lv({domain:Fv,message:a,primaryType:"GalaTransaction",types:c}).length}`;return{...a,signature:l,prefix:u,types:c,domain:Fv}}async function jv(e,t){const{amount:n,recipientAddress:r,tokenSymbol:s}=e,{galaConnectClient:i,tokenMetadataResolver:o,ethereumWallet:a,destinationChainId:c,destinationChain:l,validateRecipientAddress:u}=t,d=Ev(s);Iv(n,d),u(r,"recipient");const h=await o.getTokenMetadata(d),g=await i.fetchBridgeFee({chainId:l,bridgeToken:h.descriptor}),f=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:r,tokenDescriptor:h.descriptor}),p=await Vv(f,{wallet:a}),m=function(e){if(void 0===e||""===e)throw It(vv,"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 i.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(wv,"transactionHash");return t}(await i.bridgeTokenOut({bridgeFromChannel:"asset",bridgeRequestId:m})),tokenSymbol:d,amount:n,feePaid:g.estimatedTotalTxFeeInGala,baseUrl:i.getBaseUrl()})}var Xv;exports.BridgeStatusCode=void 0,(Xv=exports.BridgeStatusCode||(exports.BridgeStatusCode={}))[Xv.PENDING=0]="PENDING",Xv[Xv.SUBMITTED=1]="SUBMITTED",Xv[Xv.CONFIRMED=2]="CONFIRMED",Xv[Xv.PROCESSING=3]="PROCESSING",Xv[Xv.FINALIZING=4]="FINALIZING",Xv[Xv.COMPLETED=5]="COMPLETED",Xv[Xv.FAILED=6]="FAILED",Xv[Xv.DELIVERY_FAILED=7]="DELIVERY_FAILED";const Yv={COMPLETED:exports.BridgeStatusCode.COMPLETED,FAILED:exports.BridgeStatusCode.FAILED,DELIVERY_FAILED:exports.BridgeStatusCode.DELIVERY_FAILED};class Jv{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 r=new Promise((e,r)=>{t=e,n=r});if(this.pendingPromise=this.pendingPromise.then(async()=>{const r=Date.now()-this.lastTimestamp,s=Math.max(0,this.minIntervalMs-r);s>0&&await new Promise(e=>setTimeout(e,s)),this.lastTimestamp=Date.now();try{const n=await e();t(n)}catch(e){n(ot(e)?e:new Error(at(e)))}}),this.chainLength++,this.chainLength>=this.maxChainLength){this.chainLength=0;const e=this.pendingPromise;this.pendingPromise=e.then(()=>Promise.resolve())}return r}}const Qv={maxRetries:3,initialDelayMs:1e3,maxDelayMs:3e4,backoffMultiplier:2,jitterFactor:.1},Zv=new Set([408,429,500,502,503,504]),ew=[/ECONNRESET/i,/ECONNREFUSED/i,/ETIMEDOUT/i,/ENOTFOUND/i,/EAI_AGAIN/i,/socket hang up/i,/network/i,/timeout/i,/aborted/i];function tw(e){if(null!=e&&"object"==typeof e){const t=e;if("number"==typeof t.status)return Zv.has(t.status);if("number"==typeof t.statusCode)return Zv.has(t.statusCode);const n=lt(e);if("string"==typeof n&&("ECONNRESET"===n||"ECONNREFUSED"===n||"ETIMEDOUT"===n||"ENOTFOUND"===n||"EAI_AGAIN"===n))return!0}const t=at(e);return ew.some(e=>e.test(t))}function nw(e,t){const n=t.initialDelayMs*Math.pow(t.backoffMultiplier,e-1),r=Math.min(n,t.maxDelayMs),s=r*t.jitterFactor*Math.random();return Math.floor(r+s)}function rw(e){return new Promise(t=>setTimeout(t,e))}function sw(e,t){return mv(e.get("Ethereum"),"Ethereum",t)}function iw(e,t){return mv(e.get("Solana"),"Solana",t)}function ow(e,t){return e??t.getWalletAddress()}async function aw(e,t,n,r,s){const i=await t.getTokenMetadata(r);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:i.descriptor}))}async function cw(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===Number(Yv.COMPLETED),isFailed:t===Number(Yv.FAILED)||t===Number(Yv.DELIVERY_FAILED)}}(await e.getBridgeStatus(t))}function lw(e,t){if(!Kn(e))throw new Error("Input must be a non-empty string");const n=e.split(t);if(n.length<4)throw new Error(`Invalid ${"|"===t?"pipe":"dollar"}-delimited token format. Expected 4+ parts separated by ${t}, got ${n.length}`);return n}function uw(e,t,n,r){const s=e?.split?.(t)??[],i=void 0!==n?` (${n})`:"";return new yt(`Invalid ${"|"===t?"pipe":"dollar"}-delimited token: "${e}" (${s.length} parts)${i}. Expected format: "collection${t}category${t}type${t}additionalKey" (4 parts minimum). Received: [${s.map(e=>`"${e}"`).join(", ")}]. Error: ${at(r)}`,"token",`INVALID_${"|"===t?"PIPE":"DOLLAR"}_DELIMITED_TOKEN`)}function dw(e,t,n){try{const n=lw(e,t),r=n[n.length-1],s=n[n.length-2],i=n[n.length-3],o=n.slice(0,n.length-3).join(t);if(void 0===o||void 0===i||void 0===s||void 0===r||""===r||""===o||""===i||""===s)throw new Error("All components (collection, category, type, additionalKey) must be non-empty");return{collection:o,category:i,type:s,additionalKey:r}}catch(r){throw uw(e,t,n,r)}}function hw(e){if("object"==typeof e&&null!==e)return function(e){if(null===e||"object"!=typeof e)throw new yt("Token object must be a non-null object, got "+typeof e,"token","INVALID_TOKEN_OBJECT");const{collection:t,category:n,type:r,additionalKey:s}=e;if(!Kn(t))throw new yt("Token.collection must be a non-empty string, got "+typeof t,"token.collection","MISSING_OR_INVALID_COLLECTION");if(!Kn(n))throw new yt("Token.category must be a non-empty string, got "+typeof n,"token.category","MISSING_OR_INVALID_CATEGORY");if(!Kn(r))throw new yt("Token.type must be a non-empty string, got "+typeof r,"token.type","MISSING_OR_INVALID_TYPE");if(!Kn(s))throw new yt("Token.additionalKey must be a non-empty string, got "+typeof s,"token.additionalKey","MISSING_OR_INVALID_ADDITIONAL_KEY");return{collection:t,category:n,type:r,additionalKey:s}}(e);if(null==e)throw new yt(`Token cannot be null, undefined, or empty. Received: ${JSON.stringify(e)}`,"token","EMPTY_TOKEN");if("string"!=typeof e)throw new yt("Token must be a string or TokenClassKey object, got "+typeof e,"token","INVALID_TOKEN_TYPE");if(pw(e))return gw(e);if(mw(e))return fw(e);throw new yt(`Plain token string "${e}" (length: ${e.length}) is not allowed - tokens must be delimited with | or $. Expected format: "GALA|Unit|none|none" or "GALA$Unit$none$none". Input: "${e}"`,"token","PLAIN_STRING_NOT_ALLOWED")}function gw(e){return function(e,t,n){try{const n=lw(e,t),[r,s,i,...o]=n;if(""===r||""===s||""===i)throw new Error("Collection, category, and type must be non-empty");const a=o.join(t);if(void 0===r||void 0===s||void 0===i||""===a)throw new Error("AdditionalKey must be non-empty");return{collection:r,category:s,type:i,additionalKey:a}}catch(r){throw uw(e,t,n,r)}}(e,"|","pipe-delimited token")}function fw(e){return dw(e,"$","dollar-delimited token")}function pw(e){return Kn(e)&&e.includes("|")}function mw(e){return"string"==typeof e&&e.includes("$")}function yw(e){if("object"!=typeof e||null===e)return!1;const t=e,n=t.collection,r=t.category,s=t.type,i=t.additionalKey;return"string"==typeof n&&"string"==typeof r&&"string"==typeof s&&"string"==typeof i&&n.length>0&&r.length>0&&s.length>0&&i.length>0}function bw(e){let t;if("string"==typeof e)t=gw(e);else{if(!yw(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:io(t)}}function vw(e,t){let n;try{n=_n(e,"amount")}catch(t){throw Dt("amount",`${e} (${at(t)})`)}if(!n.isFinite())throw Dt("amount",e);const r=n.multipliedBy(ki(10).pow(t));if(!r.isInteger())throw Dt("amount",`${e} (cannot be represented with ${t} decimals)`);return BigInt(r.toFixed(0))}function ww(e,t){return ki(e.toString()).dividedBy(ki(10).pow(t)).toFixed(t).replace(/\.?0+$/,"")}class Ew{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 r=vo[t];if(void 0!==r)return this.cache.set(t,r),r;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 vo}clearCache(){this.cache.clear()}async fetchFromApi(e){const t=(await this.galaConnectClient.getBridgeConfigurations(e)).find(t=>Xt(t.symbol)===Xt(e)&&t.verified);if(!t)throw new Error(`Unable to locate token metadata for ${e}`);return n={collection:t.collection,category:t.category,type:t.type,additionalKey:t.additionalKey},r=t.decimals,s=t.channel,{descriptor:{collection:n.collection,category:n.category,type:n.type,additionalKey:n.additionalKey},decimals:r,...void 0!==s?{channel:s}:{}};var n,r,s}}class Aw 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 Sw=ho,kw="https://galachain-gateway-chain-platform-galachain-mainnet.gala.com",Tw=12,Iw=!0,Nw=3,Cw=1e3;class _w{constructor(e){this.baseUrl=e.baseUrl??Sw,this.galachainBaseUrl=e.galachainBaseUrl??kw,this.walletAddress=e.walletAddress,this.rateLimiter=new Jv(e.requestsPerSecond??Tw),this.defaultHeaders={"Content-Type":"application/json","X-Wallet-Address":this.walletAddress};const t=e.enableRetry??Iw;this.retryOptions=t?{maxRetries:e.maxRetries??Nw,initialDelayMs:e.retryInitialDelayMs??Cw,...e.onRetry&&{onRetry:e.onRetry},shouldRetry:e=>tw(e instanceof Aw?{status:e.status}:e)}:null}getBaseUrl(){return this.baseUrl}async getBridgeConfigurations(e){return Ji(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?Tn(e,{rawBody:e}):{message:"Failed to fetch bridge configurations"},new Aw(n.status,"/v1/connect/bridge-configurations",t)}return(await n.json()).data.tokens},"GalaConnectClient.getBridgeConfigurations",void 0,e=>{if(e instanceof Aw)throw e;throw Ct(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 Ji(async()=>{const r=n.baseUrl??this.baseUrl,s=new URL(e,r),i=n.skipWalletHeader?{"Content-Type":"application/json","X-Wallet-Address":""}:this.defaultHeaders,o=await this.request(s.toString(),{method:"POST",headers:i,body:JSON.stringify(t,(e,t)=>"bigint"==typeof t?t.toString():t)});if(!o.ok){const t=await o.text(),n=500,r=Tn(t,{rawBody:t.slice(0,n)});throw new Aw(o.status,e,r)}const a=await o.text();if(""!==a){const t=function(e){if(Zt(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: ${at(e)}`}}}(a);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 Aw)throw e;throw Ct(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 r=await fetch(e,{...t,headers:n});if(this.retryOptions&&!r.ok){const t=r.status;if(429===t||t>=500){const n=r.clone(),s=await this.safeParseJson(n);throw new Aw(t,e,s)}}return r});return this.retryOptions?async function(e,t={}){const n={...Qv,...t},r=t.shouldRetry??(e=>tw(e));let s;for(let i=1;i<=n.maxRetries+1;i++)try{return await e()}catch(e){if(s=e,i>n.maxRetries)break;if(!r(e,i))break;const o=nw(i,n);t.onRetry&&t.onRetry(e,i,o),await new Promise(e=>setTimeout(e,o))}throw s}(n,this.retryOptions):n()}async safeParseJson(e){const t=await e.text();try{return JSON.parse(t)}catch{return{rawBody:t}}}}class xw{async waitForCompletion(e,t={}){const{pollInterval:n=15e3,timeout:r=27e5,onStatusUpdate:s}=t,i=Date.now();for(;;){const t=await this.getStatus(e);if(s&&s(t),t.status===exports.BridgeStatusCode.COMPLETED||t.status===exports.BridgeStatusCode.FAILED||t.status===exports.BridgeStatusCode.DELIVERY_FAILED)return t;if(sn(i)>r)throw Nt(`Bridge transaction timed out after ${r}ms. Last status: ${t.status}`,e,"TIMEOUT");await new Promise(e=>setTimeout(e,n))}}}class Rw extends xw{constructor(e,t){super(),this.galaConnectClient=e,this.tokenConfigs=t}async getStatus(e){return cw(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 Bw(e,t,...n){const r=e[t];return"function"==typeof r?await r(...n):await e.getFunction(t)(...n)}class Dw extends Rw{constructor(t){const n=t.tokenConfigs??yo;super(t.galaConnectClient,cv(n)),this.network="Ethereum",this.galaChainWalletAddress=t.galaChainWalletAddress,uv(t.ethereumPrivateKey);const r=t.ethereumRpcUrl??"https://ethereum.publicnode.com";this.ethereumProvider=new e.JsonRpcProvider(r),this.ethereumWallet=new e.Wallet(t.ethereumPrivateKey,this.ethereumProvider),this.ethereumWalletAddress=t.ethereumWalletAddress??this.ethereumWallet.address,this.ethereumBridgeContract=t.ethereumBridgeContract??"0x3F98b5A26EF3f04E1DA3B0B41dD350E8C8F3A7c2",this.tokenMetadataResolver=new Ew({galaConnectClient:this.galaConnectClient})}async estimateFee(e,t){return aw(this.galaConnectClient,this.tokenMetadataResolver,"Ethereum",e)}async bridgeOut(e){return jv(e,{galaConnectClient:this.galaConnectClient,tokenMetadataResolver:this.tokenMetadataResolver,ethereumWallet:this.ethereumWallet,destinationChainId:ao.ETHEREUM,destinationChain:"Ethereum",validateRecipientAddress:Av})}async bridgeIn(t){const{amount:n,sourcePrivateKey:r,recipientAddress:s,tokenSymbol:i}=t,o=Ev(i);if(Iv(n,o),void 0!==r&&""!==r&&!av(r))throw kt("sourcePrivateKey","0x-prefixed 64-character hex string",r.slice(0,10)+"...");const a=void 0!==r&&""!==r?new e.Wallet(r,this.ethereumProvider):this.ethereumWallet,c=lv(this.tokenConfigs,o,"Ethereum bridge"),l=await this.tokenMetadataResolver.getTokenMetadata(o),u=new e.Contract(c.contractAddress,wo,a),d=await Bw(u,"decimals"),h=Cn("string"==typeof d||"number"==typeof d||"bigint"==typeof d?d:void 0,18),g=vw(n,h),f=await Bw(u,"balanceOf",a.address);if("bigint"!=typeof f)throw new Error("Ethereum balance response was not a bigint");const p=f;if(p<g){throw It(`Insufficient ${o} balance on Ethereum. Needed ${ww(g,h)}, have ${ww(p,h)}`,"amount")}const m=function(t){const n=new lr;if("client"===n.detectFormat(t))return t;const r=n.normalizeInput(t);if(null==r)throw kt("address","a valid GalaChain address (eth|0x{40-hex}, 0x{40-hex}, or {40-hex})","GalaChain address");const s=n.extractHex(r);return`eth|${e.getAddress("0x"+s).slice(2)}`}(s??this.galaChainWalletAddress);return yv({fromChain:"Ethereum",transactionHash:(await this.executeBridgeDeposit({wallet:a,tokenContract:u,tokenConfig:c,amountBaseUnits:g,decimals:h,recipient:m,metadata:l})).txHash,tokenSymbol:o,amount:n,baseUrl:this.galaConnectClient.getBaseUrl()})}isValidAddress(e){return $n.ETH_ADDRESS.test(e)}getWalletAddress(){return this.ethereumWalletAddress}async getEthereumTokenBalance(t,n){const r=lv(this.tokenConfigs,t,"Ethereum"),s=n??this.ethereumWalletAddress;Av(s);const i=new e.Contract(r.contractAddress,wo,this.ethereumProvider),o=await Bw(i,"balanceOf",s);if("bigint"!=typeof o)throw new Error("Ethereum balance response was not a bigint");return ww(o,r.decimals??18)}async getEthereumNativeBalance(e){const t=e??this.ethereumWalletAddress;Av(t);return ww(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 kt("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>=Dw.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: ${at(e)}`}}}async executeBridgeDeposit(t){const n=new e.Contract(this.ethereumBridgeContract,Eo,t.wallet),r=(new TextEncoder).encode(t.recipient);let s;s=t.tokenConfig.bridgeUsesPermit?await this.bridgeWithPermit(t.wallet,t.tokenContract,t.tokenConfig,n,t.amountBaseUnits,r):await this.bridgeWithApproval(t.wallet,t.tokenContract,n,t.tokenConfig,t.amountBaseUnits,r);if(!await s.wait())throw It("Bridge transaction receipt not available","ethereumRpcUrl");await rw(3e4);const i={collection:t.metadata.descriptor.collection,category:t.metadata.descriptor.category,type:t.metadata.descriptor.type,additionalKey:t.metadata.descriptor.additionalKey,instance:"0"};return await this.galaConnectClient.registerBridgeTransaction({quantity:ww(t.amountBaseUnits,t.decimals),tokenInstance:i,fromChain:"Ethereum",toChain:"GC",hash:s.hash}),{txHash:s.hash}}async bridgeWithPermit(t,n,r,s,i,o){const a=await this.ethereumProvider.getNetwork(),c=await Bw(n,"name");if("string"!=typeof c)throw new Error("Ethereum token name response was not a string");const l=c,u=await Bw(n,"nonces",t.address);if("bigint"!=typeof u)throw new Error("Ethereum token nonce response was not a bigint");const d=u,h=BigInt(Math.floor(Date.now()/1e3)+3600),g=await t.signTypedData({name:l,version:"1",chainId:Cn(a.chainId,1),verifyingContract:r.contractAddress},{Permit:[{name:"owner",type:"address"},{name:"spender",type:"address"},{name:"value",type:"uint256"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}]},{owner:t.address,spender:this.ethereumBridgeContract,value:i,nonce:d,deadline:h}),f=e.Signature.from(g);return await Bw(s,"bridgeOutWithPermit",r.contractAddress,i,ao.GALA_CHAIN,o,h,f.v,f.r,f.s)}async bridgeWithApproval(e,t,n,r,s,i){const o=await Bw(t,"allowance",e.address,this.ethereumBridgeContract);if("bigint"!=typeof o)throw new Error("Ethereum allowance response was not a bigint");if(BigInt(o)<s){const e=await Bw(t,"approve",this.ethereumBridgeContract,s);await e.wait()}return await Bw(n,"bridgeOut",r.contractAddress,s,0,ao.GALA_CHAIN,i)}}Dw.ETHEREUM_FINALITY_THRESHOLD=12;const Ow=new mm("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA");new mm("TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb");const Mw=new mm("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL");new mm("So11111111111111111111111111111111111111112"),new mm("9pan9bMn5HatX4EJdBwg9VgCa7Uz5HL8N1m5D3NdXejP");const Lw=e=>({decode:e.decode.bind(e),encode:e.encode.bind(e)});var Uw,Pw={};function Fw(){if(Uw)return Pw;return Uw=1,Object.defineProperty(Pw,"__esModule",{value:!0}),Pw.toBigIntLE=function(e){{const t=Buffer.from(e);t.reverse();const n=t.toString("hex");return 0===n.length?BigInt(0):BigInt(`0x${n}`)}},Pw.toBigIntBE=function(e){{const t=e.toString("hex");return 0===t.length?BigInt(0):BigInt(`0x${t}`)}},Pw.toBufferLE=function(e,t){{const n=e.toString(16),r=Buffer.from(n.padStart(2*t,"0").slice(0,2*t),"hex");return r.reverse(),r}},Pw.toBufferBE=function(e,t){{const n=e.toString(16);return Buffer.from(n.padStart(2*t,"0").slice(0,2*t),"hex")}},Pw}var $w=Fw();const Kw=function(e,t){return n=>{const r=Kl.blob(t,n),{encode:s,decode:i}=Lw(r),o=r;return o.decode=(t,n)=>{const r=i(t,n);return e?$w.toBigIntLE(Oo.Buffer.from(r)):$w.toBigIntBE(Oo.Buffer.from(r))},o.encode=(n,r,i)=>{let o;return function(e){if("bigint"!=typeof e)throw new Error("Expected a `BigInt`")}(n),o=0===t?Oo.Buffer.alloc(0):e?$w.toBufferLE(n,t):$w.toBufferBE(n,t),s(o,r,i)},o}}.bind(null,!0),Gw=Kw(8),Ww=e=>{const t=Kl.blob(32,e),{encode:n,decode:r}=Lw(t),s=t;return s.decode=(e,t)=>{const n=r(e,t);return new mm(n)},s.encode=(e,t,r)=>{const s=e.toBuffer();return n(s,t,r)},s};var Hw;!function(e){e[e.Uninitialized=0]="Uninitialized",e[e.Initialized=1]="Initialized",e[e.Frozen=2]="Frozen"}(Hw||(Hw={}));const qw=Kl.struct([Ww("mint"),Ww("owner"),Gw("amount"),Kl.u32("delegateOption"),Ww("delegate"),Kl.u8("state"),Kl.u32("isNativeOption"),Gw("isNative"),Gw("delegatedAmount"),Kl.u32("closeAuthorityOption"),Ww("closeAuthority")]);qw.span;var zw=function(e){if(e.length>=255)throw new TypeError("Alphabet too long");const t=new Uint8Array(256);for(let e=0;e<t.length;e++)t[e]=255;for(let n=0;n<e.length;n++){const r=e.charAt(n),s=r.charCodeAt(0);if(255!==t[s])throw new TypeError(r+" is ambiguous");t[s]=n}const n=e.length,r=e.charAt(0),s=Math.log(n)/Math.log(256),i=Math.log(256)/Math.log(n);function o(e){if("string"!=typeof e)throw new TypeError("Expected String");if(0===e.length)return new Uint8Array;let i=0,o=0,a=0;for(;e[i]===r;)o++,i++;const c=(e.length-i)*s+1>>>0,l=new Uint8Array(c);for(;i<e.length;){const r=e.charCodeAt(i);if(r>255)return;let s=t[r];if(255===s)return;let o=0;for(let e=c-1;(0!==s||o<a)&&-1!==e;e--,o++)s+=n*l[e]>>>0,l[e]=s%256>>>0,s=s/256>>>0;if(0!==s)throw new Error("Non-zero carry");a=o,i++}let u=c-a;for(;u!==c&&0===l[u];)u++;const d=new Uint8Array(o+(c-u));let h=o;for(;u!==c;)d[h++]=l[u++];return d}return{encode:function(t){if(t instanceof Uint8Array||(ArrayBuffer.isView(t)?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Array.isArray(t)&&(t=Uint8Array.from(t))),!(t instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(0===t.length)return"";let s=0,o=0,a=0;const c=t.length;for(;a!==c&&0===t[a];)a++,s++;const l=(c-a)*i+1>>>0,u=new Uint8Array(l);for(;a!==c;){let e=t[a],r=0;for(let t=l-1;(0!==e||r<o)&&-1!==t;t--,r++)e+=256*u[t]>>>0,u[t]=e%n>>>0,e=e/n>>>0;if(0!==e)throw new Error("Non-zero carry");o=r,a++}let d=l-o;for(;d!==l&&0===u[d];)d++;let h=r.repeat(s);for(;d<l;++d)h+=e.charAt(u[d]);return h},decodeUnsafe:o,decode:function(e){const t=o(e);if(t)return t;throw new Error("Non-base"+n+" character")}}}("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");function Vw(e,t,n,r,s){const[i]=mm.findProgramAddressSync([t.toBuffer(),r.toBuffer(),e.toBuffer()],s);return i}class jw extends Rw{constructor(t){const n=t.tokenConfigs??bo;super(t.galaConnectClient,cv(n)),this.network="Solana",this.solanaBridgeAccountCache=new Map,this.galaChainWalletAddress=t.galaChainWalletAddress,uv(t.ethereumPrivateKey);const r=new e.JsonRpcProvider("https://ethereum.publicnode.com");this.ethereumWallet=new e.Wallet(t.ethereumPrivateKey,r);const s=t.solanaRpcUrl??"https://api.mainnet-beta.solana.com";let i;this.solanaConnection=new tv(s,"confirmed");try{i=zw.decode(t.solanaPrivateKeyBase58)}catch{throw kt("solanaPrivateKeyBase58","base58-encoded string",t.solanaPrivateKeyBase58.slice(0,20)+"...")}if(64!==i.length)throw kt("solanaPrivateKeyBase58","64 bytes when decoded",`${i.length} bytes`);this.solanaKeypair=nv.fromSecretKey(i);const o=t.solanaBridgeProgram??"AaE4dTnL75XqgUJpdxBKg6vS9sTJgBPJwBQRVhD29WwS";this.solanaBridgeProgramId=new mm(o),[this.solanaBridgeTokenAuthority]=mm.findProgramAddressSync([Buffer.from("bridge_token_authority")],this.solanaBridgeProgramId),[this.solanaBridgeConfigPda]=mm.findProgramAddressSync([Buffer.from("configv1")],this.solanaBridgeProgramId),[this.solanaNativeBridgePda]=mm.findProgramAddressSync([Buffer.from("native_sol_bridge")],this.solanaBridgeProgramId),this.tokenMetadataResolver=new Ew({galaConnectClient:this.galaConnectClient})}async estimateFee(e,t){return aw(this.galaConnectClient,this.tokenMetadataResolver,"Solana",e)}async bridgeOut(e){return jv(e,{galaConnectClient:this.galaConnectClient,tokenMetadataResolver:this.tokenMetadataResolver,ethereumWallet:this.ethereumWallet,destinationChainId:ao.SOLANA,destinationChain:"Solana",validateRecipientAddress:Sv})}async bridgeIn(e){const{amount:t,sourcePrivateKey:n,recipientAddress:r,tokenSymbol:s}=e,i=Ev(s);Iv(t,i);let o=this.solanaKeypair;if(void 0!==n&&""!==n){let e;try{e=zw.decode(n)}catch{throw kt("sourcePrivateKey","base58-encoded string",n.slice(0,20)+"...")}if(64!==e.length)throw kt("sourcePrivateKey","64 bytes when decoded",`${e.length} bytes`);o=nv.fromSecretKey(e)}const a=lv(this.tokenConfigs,i,"Solana bridge"),c=await this.tokenMetadataResolver.getTokenMetadata(i),l=vw(t,c.decimals),u=r??this.galaChainWalletAddress;return yv({fromChain:"Solana",transactionHash:await this.executeSolanaBridgeOut({keypair:o,tokenConfig:a,metadata:c,amountBaseUnits:l,recipient:u,amount:t}),tokenSymbol:i,amount:t,baseUrl:this.galaConnectClient.getBaseUrl()})}isValidAddress(e){try{return new mm(e),!0}catch{return!1}}getWalletAddress(){return this.solanaKeypair.publicKey.toBase58()}async getSolanaTokenBalance(e,t){const n=lv(this.tokenConfigs,e,"Solana");if(n.isNative)return this.getSolanaNativeBalance(t);const r=t??this.solanaKeypair.publicKey.toBase58(),s=kv(r),i=Vw(new mm(n.mintAddress),s,0,Ow,Mw);try{const e=await async function(e,t,n,r){const s=await e.getAccountInfo(t);if(!s)throw new Error(`could not find account ${t.toBase58()}`);if(!s.owner.equals(r))throw new Error(`account owner mismatch: expected ${r.toBase58()}, got ${s.owner.toBase58()}`);return{amount:qw.decode(s.data).amount,decimals:0}}(this.solanaConnection,i,0,Ow),t=n.decimals??8;return ww(e.amount,t)}catch(t){if(ot(t)&&t.message.includes("could not find")){return ww(0n,n.decimals??8)}throw It(`Failed to fetch ${e} balance for ${r}: ${at(t)}`,`${e}Account`)}}async getSolanaNativeBalance(e){const t=kv(e??this.solanaKeypair.publicKey.toBase58()),n=await this.solanaConnection.getBalance(t,"confirmed");return ww(BigInt(n),9)}async requestDevnetAirdrop(e=1,t){On(e,1e-5,2,"amount");const n=void 0!==t&&""!==t?kv(t):this.solanaKeypair.publicKey,r=this.solanaConnection.rpcEndpoint;if(!r.includes("devnet"))throw It(`Solana devnet faucet only available on devnet. Current RPC: ${r}. Ensure SDK is configured with environment='stage' for devnet access.`,"solanaRpcUrl");const s=Math.floor(1e9*e);return await this.solanaConnection.requestAirdrop(n,s)}async getSolanaTransactionStatus(e){if(!Kn(e))throw kt("signature","a non-empty string");if(!/^[1-9A-HJ-NP-Za-km-z]{80,90}$/.test(e))throw kt("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 mm(e.tokenConfig.mintAddress),n=Boolean(e.tokenConfig.isNative),r=n?void 0:await this.getSolanaBridgeAccounts(t),s=n?void 0:Vw(t,e.keypair.publicKey,0,Ow,Mw),i=Buffer.from(e.recipient,"utf8"),o=Buffer.alloc(8);o.writeBigUInt64LE(e.amountBaseUnits);const a=Buffer.alloc(4);a.writeUInt32LE(i.length);const c=n?this.buildNativeBridgeInstruction(e.keypair.publicKey,o,a,i):this.buildTokenBridgeInstruction(e.keypair.publicKey,s,t,r,o,a,i),l=new Fm;l.add(sv.setComputeUnitPrice({microLamports:375e3}),sv.setComputeUnitLimit({units:2e5}),c),l.feePayer=e.keypair.publicKey;const u=await this.sendAndConfirmWithFallback(l,e.keypair),d={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:d,fromChain:"Solana",toChain:"GC",hash:u}),u}async sendAndConfirmWithFallback(e,t,n=3){let r=null;for(let s=1;s<=n;s++){try{const i=await this.solanaConnection.getLatestBlockhash("confirmed");e.recentBlockhash=i.blockhash,e.feePayer=t.publicKey,e.signatures=[],e.sign(t);const o=await this.solanaConnection.sendRawTransaction(e.serialize(),{skipPreflight:!1,preflightCommitment:"confirmed"});try{return await this.solanaConnection.confirmTransaction({signature:o,blockhash:i.blockhash,lastValidBlockHeight:i.lastValidBlockHeight},"confirmed"),o}catch(e){const t=ot(e)?e.message.toLowerCase():"";if(!(t.includes("block height exceeded")||t.includes("blockhash not found")||t.includes("expired")))throw e;const i=await this.solanaConnection.getSignatureStatuses([o]);if("confirmed"===i.value[0]?.confirmationStatus||"finalized"===i.value[0]?.confirmationStatus)return o;r=new Error(`Transaction ${o} not confirmed - block height exceeded (attempt ${s}/${n})`)}}catch(e){r=ot(e)?e:new Error(at(e));const t=r.message.toLowerCase();if(!(t.includes("block height exceeded")||t.includes("blockhash not found")||t.includes("timeout")||t.includes("expired"))||s===n)throw r}const i=Math.min(1e3*Math.pow(2,s-1),5e3);await rw(i)}throw r??new Error("Transaction confirmation failed after max retries")}buildNativeBridgeInstruction(e,t,n,r){const s=Buffer.concat([Ao.BRIDGE_OUT_NATIVE,t,n,r]);return new Pm({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:Qm.programId,isSigner:!1,isWritable:!1}],data:s})}buildTokenBridgeInstruction(e,t,n,r,s,i,o){const a=Buffer.concat([Ao.BRIDGE_OUT,s,i,o]);return new Pm({programId:this.solanaBridgeProgramId,keys:[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!0},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:r.mintLookup,isSigner:!1,isWritable:!1},{pubkey:r.tokenBridge,isSigner:!1,isWritable:!1},{pubkey:r.bridgeTokenAccount,isSigner:!1,isWritable:!0},{pubkey:this.solanaBridgeTokenAuthority,isSigner:!1,isWritable:!1},{pubkey:this.solanaBridgeConfigPda,isSigner:!1,isWritable:!0},{pubkey:Qm.programId,isSigner:!1,isWritable:!1},{pubkey:Ow,isSigner:!1,isWritable:!1}],data:a})}async getSolanaBridgeAccounts(e){const t=e.toBase58(),n=this.solanaBridgeAccountCache.get(t);if(n)return n;const[r]=mm.findProgramAddressSync([Buffer.from("mint_lookup_v1"),e.toBuffer()],this.solanaBridgeProgramId),s=await this.solanaConnection.getAccountInfo(r,"confirmed");if(!s)throw It(`Mint lookup account not found for ${r.toBase58()}`,"solanaBridgeProgram");if(!s.owner.equals(this.solanaBridgeProgramId))throw It("Mint lookup account owner mismatch for Solana bridge program","solanaBridgeProgram");if(s.data.length<40)throw It("Mint lookup account data is unexpectedly short","solanaBridgeProgram");const i={mintLookup:r,tokenBridge:new mm(s.data.slice(8,40)),bridgeTokenAccount:Vw(e,this.solanaBridgeTokenAuthority,0,Ow,Mw)};return this.solanaBridgeAccountCache.set(t,i),i}}const Xw={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"}},Yw={solanaBridgeProgram:"AaE4dTnL75XqgUJpdxBKg6vS9sTJgBPJwBQRVhD29WwS",rateLimit:12,pollInterval:15e3,pollTimeout:27e5};function Jw(e){const t=vo[e];if(void 0===t)throw new yt(`Bridge token ${e} has no explicit GalaChain class key in STATIC_TOKEN_METADATA; a class key cannot be derived from a symbol.`,"symbol","CLASS_KEY_NOT_DERIVABLE_FROM_SYMBOL");return{...t.descriptor}}class Qw{static normalizeGalaChainAddress(e){const t=new lr;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 r=t.normalizeInput(n);if(!r)throw It(`Invalid GalaChain address format: ${e}`,"galaChainWalletAddress");const s=t.extractHex(r);return`eth|${Qw.checksumAddress(s)}`}static checksumAddress(t){const n=t.toLowerCase(),r=ar(e.keccak256(e.toUtf8Bytes(n)));let s="";for(let e=0;e<n.length;e++){const t=n[e],i=r[e];void 0!==t&&void 0!==i&&parseInt(i,16)>=8?s+=t.toUpperCase():s+=t??""}return s}constructor(e){const t=Qw.normalizeGalaChainAddress(e.galaChainWalletAddress),n=e.environment??"prod",r=ro["stage"===n?"stage":"prod"],s=Xw[n],i={galaConnectBaseUrl:e.galaConnectBaseUrl??r.dexApiBaseUrl,galaChainApiBaseUrl:e.galaChainApiBaseUrl??r.gatewayBaseUrl,ethereumRpcUrl:e.ethereumRpcUrl??s.ethereum,solanaRpcUrl:e.solanaRpcUrl??s.solana,ethereumBridgeContract:e.ethereumBridgeContract??mo(n),solanaBridgeProgram:e.solanaBridgeProgram??Yw.solanaBridgeProgram,rateLimit:e.rateLimit??Yw.rateLimit,pollInterval:e.pollInterval??Yw.pollInterval,pollTimeout:e.pollTimeout??Yw.pollTimeout,galaChainWalletAddress:t,ethereumPrivateKey:e.ethereumPrivateKey,environment:n};this.config=e.solanaPrivateKey?{...i,solanaPrivateKey:e.solanaPrivateKey}:i,this.galaConnectClient=new _w({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=po(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 Dw(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:bo};this.strategies.set("Solana",new jw(e))}}async resolveTokenSymbol(e,t){return Ji(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=bw(e).stringified,r="Ethereum"===t?"ETHEREUM":"SOLANA",s=await this.bridgeableTokenService.getTokenByTokenId(n,r);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('${r}')`," - 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 Ji(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 Ji(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 Ji(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 Ji(async()=>{if(null!=t){const n=this.strategies.get(t);if(n)return n.getStatus(e)}const n=this.strategies.get("Ethereum");let r;if(n)try{return await n.getStatus(e)}catch(e){r=ot(e)?e:new Error(at(e))}const s=this.strategies.get("Solana");if(s)try{return await s.getStatus(e)}catch(e){r=ot(e)?e:new Error(at(e))}const i=r?` (last error: ${r.message})`:"";throw Nt(`Unable to get status for transaction ${e}${i}`,e)},"BridgeService.getBridgeStatus")}async waitForBridgeCompletion(e,t){return Ji(async()=>{const n={pollInterval:t?.pollInterval??this.config.pollInterval,timeout:t?.timeout??this.config.pollTimeout,...t?.onStatusUpdate&&{onStatusUpdate:t.onStatusUpdate}},r=this.strategies.get("Ethereum");if(r)try{return await r.getStatus(e),r.waitForCompletion(e,n)}catch{}const s=this.strategies.get("Solana");if(s)return s.waitForCompletion(e,n);throw Nt(`Unable to wait for transaction ${e}: no suitable strategy found`,e)},"BridgeService.waitForBridgeCompletion")}getSupportedBridgeTokens(e){const t=[],n=po(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:Jw(e.symbol),externalAddresses:{ethereum:e.contractAddress}});if(null==e||"Solana"===e)for(const e of bo){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:Jw(e.symbol),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 Ji(async()=>sw(this.strategies).getEthereumTokenBalance(e,t),"BridgeService.getEthereumTokenBalance")}async getEthereumNativeBalance(e){return Ji(async()=>sw(this.strategies).getEthereumNativeBalance(e),"BridgeService.getEthereumNativeBalance")}async getSolanaTokenBalance(e,t){return Ji(async()=>iw(this.strategies).getSolanaTokenBalance(e,t),"BridgeService.getSolanaTokenBalance")}async getSolanaNativeBalance(e){return Ji(async()=>iw(this.strategies).getSolanaNativeBalance(e),"BridgeService.getSolanaNativeBalance")}async fetchEthereumWalletTokenBalance(e,t){return Ji(async()=>{const n=sw(this.strategies),r=fv(po(this.config.environment),e,"Ethereum"),s=ow(t,n);return hv(r,await n.getEthereumTokenBalance(e,s))},"BridgeService.fetchEthereumWalletTokenBalance")}async fetchEthereumWalletNativeBalance(e){return Ji(async()=>{const t=sw(this.strategies),n=ow(e,t);return dv("ETH",await t.getEthereumNativeBalance(n),18)},"BridgeService.fetchEthereumWalletNativeBalance")}async fetchSolanaWalletTokenBalance(e,t){return Ji(async()=>{const n=iw(this.strategies),r=fv(bo,e,"Solana"),s=ow(t,n);return gv(r,await n.getSolanaTokenBalance(e,s))},"BridgeService.fetchSolanaWalletTokenBalance")}async fetchSolanaWalletNativeBalance(e){return Ji(async()=>{const t=iw(this.strategies),n=ow(e,t);return dv("SOL",await t.getSolanaNativeBalance(n),9)},"BridgeService.fetchSolanaWalletNativeBalance")}async requestSolanaDevnetAirdrop(e,t){return Ji(async()=>iw(this.strategies).requestDevnetAirdrop(e,t),"BridgeService.requestSolanaDevnetAirdrop")}async getSolanaTransactionStatus(e){return Ji(async()=>iw(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 Ji(async()=>sw(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 Ji(async()=>{const t=sw(this.strategies),n=ow(e,t),r=po(this.config.environment),[s,...i]=await Promise.all([t.getEthereumNativeBalance(n),...r.map(async e=>hv(e,await t.getEthereumTokenBalance(e.symbol,n)))]);return{address:n,native:dv("ETH",s,18),tokens:i,timestamp:Date.now()}},"BridgeService.fetchEthereumWalletAllBalances")}async fetchSolanaWalletAllBalances(e){return Ji(async()=>{const t=iw(this.strategies),n=ow(e,t),[r,...s]=await Promise.all([t.getSolanaNativeBalance(n),...bo.map(async e=>gv(e,await t.getSolanaTokenBalance(e.symbol,n)))]);return{address:n,native:dv("SOL",r,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 Zw,eE;!function(e){e.PROCESSED="PROCESSED",e.COMPLETED="COMPLETED",e.SUCCESS="SUCCESS",e.FAILED="FAILED",e.ERROR="ERROR",e.PROCESSING="PROCESSING",e.PENDING="PENDING"}(Zw||(Zw={})),exports.SDKTransactionStatus=void 0,(eE=exports.SDKTransactionStatus||(exports.SDKTransactionStatus={})).PENDING="pending",eE.PROCESSING="processing",eE.COMPLETED="completed",eE.FAILED="failed",eE.TIMEOUT="timeout";const tE={[Zw.PROCESSED]:exports.SDKTransactionStatus.COMPLETED,[Zw.COMPLETED]:exports.SDKTransactionStatus.COMPLETED,[Zw.SUCCESS]:exports.SDKTransactionStatus.COMPLETED,[Zw.FAILED]:exports.SDKTransactionStatus.FAILED,[Zw.ERROR]:exports.SDKTransactionStatus.FAILED,[Zw.PROCESSING]:exports.SDKTransactionStatus.PROCESSING,[Zw.PENDING]:exports.SDKTransactionStatus.PENDING},nE="7.0.0",rE={DEFAULT_PAGE_SIZE:50,MAX_PAGE_SIZE:1e3,SAFETY_MAX_PAGES:1e4,DEFAULT_OFFSET:0,DEFAULT_LIMIT:10,BACKEND_MAX_PAGE_SIZE:20};function sE(e,t=1,n=rE.BACKEND_MAX_PAGE_SIZE){return Math.max(t,Math.min(n,Math.ceil(e??t)))}function iE(e,t){if("number"!=typeof e||!Number.isInteger(e))throw Bt("total","a non-negative integer",e);if(e<0)throw _t("total",0,1/0,e);if("number"!=typeof t||!Number.isInteger(t))throw Bt("limit","a non-negative integer",t);if(t<0)throw _t("limit",0,1/0,t);return 0===t?1:0===e?0:Math.ceil(e/t)}function oE(e){return"string"==typeof e?e:"number"==typeof e||"boolean"==typeof e||"bigint"==typeof e?String(e):JSON.stringify(e)??""}function aE(e,t){const n={};void 0!==e.cursor&&(n.cursor=e.cursor);const r=void 0!==e.pageSize?Math.min(e.pageSize,t):t;return n.pageSize=String(r),n}function cE(e,t,n){for(const r of n){const n=t[r];null!=n&&""!==n&&(e[r]=oE(n))}return e}const lE="x-api-key";class uE extends rr{constructor(e,t,n,r=!1,s){super(e,r),this.adminApiKey=t??void 0,this.jwtAuth=n,this.userApiKey=s??void 0}setJwtAuth(e){this.jwtAuth=e}validateTokenName(e,t){!function(e,t){if(!Kn(e))throw St("tokenName","Token name");const n=Vt(e);if(!t.PATTERN.test(n))throw kt("tokenName",`${t.MIN_LENGTH}-${t.MAX_LENGTH} alphanumeric characters`,"Token name")}(e,t)}validateRequiredString(e,t,n){!function(e,t,n){if(!Kn(e))throw St(t,n)}(e,t,n)}validateOptionalString(e,t,n,r){!function(e,t,n,r){if(null!=e){if("string"!=typeof e)throw Bt(t,"string",typeof e,n);if(e.length>r)throw Rt(t,r,e.length,n)}}(e,t,n,r)}validateOptionalNumber(e,t,n,r,s,i,o){!function(e,t,n,r,s){if(null!=e){if("number"!=typeof e)throw Bt(t,"number",typeof e,n);if(e<r||e>s)throw _t(t,r,s,e,n)}}(e,t,n,r,s)}validateOptionalDate(e,t,n){!function(e,t,n){if(null!=e&&!rn(e))throw kt(t,"a valid ISO 8601 date string",n)}(e,t,n)}validatePositiveInteger(e,t,n){tr(e,t,n)}validateStatusFilter(e,t,n="status"){nr(e,t,n)}buildPaginationParams(e,t){return aE(e,t)}addOptionalFilterParams(e,t,n){return cE(e,t,n)}buildEndpoint(e,t){return function(e,t){let n=e;for(const[e,r]of Object.entries(t))n=n.replace(`:${e}`,encodeURIComponent(r.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 vt("Admin API key required for this operation. Set streamAdminApiKey in SDK config.");return{[lE]:this.adminApiKey}}getJwtHeaders(){if(!this.jwtAuth)throw new vt("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?{[lE]:this.userApiKey}:this.getJwtHeaders()}extractData(e){return Ft(e,"Backend request failed",!0),Kt(e,"No data in backend response")}extractDataOrNull(e){return Ft(e,"Backend request failed",!1),e.data??null}async toggleFeature(e,t,n){this.validateTokenName(e,n);const r=this.buildEndpoint(t,{tokenName:e}),s=await this.http.post(r,{},this.getAdminHeaders()),i=this.extractData(s);return{enabled:i.enabled,tokenName:i.tokenName??Vt(e)}}}class dE extends uE{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async getSettings(){return{settings:(await this.http.get(ze.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(ze.UPDATE_SETTINGS,t,this.getDualAuthHeaders())).settings}}async getModeration(e){this.validatePositiveInteger(e.flagId,"flagId","Flag ID");const t=ze.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=ze.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(ze.GET_STATUS,{},this.getDualAuthHeaders())).status}}}const hE={MODERATOR:"MODERATOR",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MANAGER:"MANAGER",OWNER:"OWNER"},gE=zn(hE),fE={MANAGE_COMMUNITY:"MANAGE_COMMUNITY",MANAGE_STREAM:"MANAGE_STREAM",MANAGE_SETTINGS:"MANAGE_SETTINGS",MANAGE_RECORDINGS:"MANAGE_RECORDINGS",VIEW_ANALYTICS:"VIEW_ANALYTICS"},pE=Object.values(fE);function mE(e){return gE.includes(e)}function yE(e){const t=[];return void 0===e.role||null===e.role?t.push("Role is required"):mE(e.role)||t.push(`Invalid role. Must be one of: ${gE.join(", ")}`),vE(e,t),t}function bE(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||mE(e.role)||t.push(`Invalid role. Must be one of: ${gE.join(", ")}`),vE(e,t,!0),t}function vE(e,t,n=!1){const r=t.length;if(gt(t,()=>{Zn(e.description,"description",255)}),t.length>r&&(t[r]="Description must be 255 characters or less"),void 0!==e.tokenNames){const n=t.length;gt(t,()=>{if(!Array.isArray(e.tokenNames))throw 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;gt(t,()=>{er(e.expiresAt,"expiresAt")}),t.length>n&&(t[n]="expiresAt must be a valid ISO 8601 date string")}}function wE(e){if(void 0!==e.pageSize&&("number"!=typeof e.pageSize||e.pageSize<1||e.pageSize>ln))throw Bt("pageSize",`number between 1 and ${ln}`,typeof e.pageSize);if(void 0!==e.cursor&&("string"!=typeof e.cursor||""===e.cursor.trim()))throw Bt("cursor","non-empty string",typeof e.cursor)}const EE={[hE.MODERATOR]:1,[hE.TECHNICAL_PRODUCER]:1,[hE.MANAGER]:2,[hE.OWNER]:3};class AE extends rr{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),Ft(n,"API key operation failed",!0),e.data}validateApiKeyId(e){this.validatePositiveInteger(e,"id","API key ID")}async create(e){const t=yE(e);if(t.length>0)throw new yt(t.join("; "),"options","VALIDATION_FAILED");this.logger.debug("Creating API key",{role:e.role,delegateAllTokens:e.delegateAllTokens});const n={role:e.role};void 0!==e.description&&(n.description=e.description),void 0!==e.delegateAllTokens&&(n.delegateAllTokens=e.delegateAllTokens),void 0!==e.tokenNames&&e.tokenNames.length>0&&(n.tokenNames=e.tokenNames),void 0!==e.expiresAt&&(n.expiresAt=e.expiresAt),void 0!==e.tokenPermissions&&(n.tokenPermissions=e.tokenPermissions);const r=await this.http.post(ee.CREATE,n,this.getJwtHeaders()),s=this.extractData(r);return this.logger.debug("API key created",{id:s.id,keyPrefix:s.keyPrefix}),s}async findAll(e={}){wE(e),this.logger.debug("Listing API keys",e);const t=aE(e,ln),n=await this.http.get(ee.LIST,t,this.getJwtHeaders()),r=this.extractData(n);return this.logger.debug("Listed API keys",{count:r.apiKeys.length,total:r.pageInfo.totalCount}),r}async findOne(e){this.validateApiKeyId(e),this.logger.debug("Getting API key",{id:e});const t=ee.GET.replace(":id",String(e)),n=await this.http.get(t,{},this.getJwtHeaders()),r=this.extractData(n);return this.logger.debug("Got API key",{id:r.id,keyPrefix:r.keyPrefix}),r}async update(e,t){this.validateApiKeyId(e);const n=bE(t);if(n.length>0)throw new yt(n.join("; "),"options","VALIDATION_FAILED");this.logger.debug("Updating API key",{id:e,options:t});const r={};void 0!==t.role&&(r.role=t.role),void 0!==t.description&&(r.description=t.description),void 0!==t.delegateAllTokens&&(r.delegateAllTokens=t.delegateAllTokens),void 0!==t.tokenNames&&(r.tokenNames=t.tokenNames),void 0!==t.expiresAt&&(r.expiresAt=t.expiresAt),void 0!==t.tokenPermissions&&(r.tokenPermissions=t.tokenPermissions);const s=ee.UPDATE.replace(":id",String(e)),i=await this.http.patch(s,r,this.getJwtHeaders()),o=this.extractData(i);return this.logger.debug("Updated API key",{id:o.id,keyPrefix:o.keyPrefix}),o}async revoke(e){this.validateApiKeyId(e),this.logger.debug("Revoking API key",{id:e});const t=ee.REVOKE.replace(":id",String(e));await this.http.delete(t,{},this.getJwtHeaders()),this.logger.debug("API key revoked",{id:e})}getRoles(){return[...gE]}}const SE={VIEWERS:"viewers",CHAT_PARTICIPANTS:"chat_participants"},kE=qn(SE),TE=Yn([{field:"id",type:"number"},{field:"userAddress",type:"string"},{field:"bannedBy",type:"string"},{field:"createdAt",type:"string"},{field:"isPermanent",type:"boolean"},{field:"tokenName",type:"string",nullable:!0},{field:"reason",type:"string",nullable:!0},{field:"expiresAt",type:"string",nullable:!0}]),IE=Yn([{field:"userAddress",type:"string"},{field:"isPermanent",type:"boolean"}]),NE=Yn([{field:"userAddress",type:"string"}]),CE=Yn([{field:"tokenName",type:"string"},{field:"action",type:"string",validator:e=>"CHAT_MESSAGE"===e||"COMMENT"===e||"REACTION"===e}]);function _E(e){return null==e||""===e||"string"==typeof e&&(!Qn(e)&&e.length<=fn.BAN_REASON.MAX_LENGTH)}function xE(e){return!!Wn(e)||"number"==typeof e&&(e>=mn&&e<=yn)}function RE(e){if(!Kn(e.userAddress))throw St("userAddress");if(!_E(e.reason))throw new yt(`reason must be at most ${fn.BAN_REASON.MAX_LENGTH} characters`,"reason","TOO_LONG");if(!xE(e.durationSeconds))throw new yt(`durationSeconds must be between ${mn} and ${yn} seconds`,"durationSeconds","OUT_OF_RANGE")}class BE extends uE{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async createBan(e){!function(e){jn(e.tokenName,"tokenName",on),RE(e)}(e);const t=this.buildEndpoint(q,{tokenName:e.tokenName}),n=DE(e),r=await this.http.post(t,n,this.getMultiAuthHeaders());return{ban:this.extractData(r),tokenName:Vt(e.tokenName)}}async removeBan(e){!function(e){if(jn(e.tokenName,"tokenName",on),!Kn(e.userAddress))throw St("userAddress")}(e);const t=this.buildEndpoint(j,{tokenName:e.tokenName,userAddress:e.userAddress}),n=await this.http.delete(t,{},this.getMultiAuthHeaders()),r=this.extractDataOrNull(n);return{removed:r?.removed??!0,tokenName:Vt(e.tokenName),userAddress:r?.userAddress??e.userAddress.toLowerCase()}}async listBans(e){!function(e){jn(e.tokenName,"tokenName",on),Hn(0,void 0,ln,e.pageSize)}(e);const t=this.buildEndpoint(z,{tokenName:e.tokenName}),n=this.buildPaginationParams(e,ln);this.addOptionalFilterParams(n,e,["search","name","userAddress"]);const r=await this.http.get(t,n,this.getMultiAuthHeaders()),s=this.extractData(r);return{items:s.bans,pageInfo:s.pageInfo}}async getBanStatus(e){!function(e){if(jn(e.tokenName,"tokenName",on),!Kn(e.userAddress))throw St("userAddress")}(e);const t=this.buildEndpoint(V,{tokenName:e.tokenName,userAddress:e.userAddress}),n=await this.http.get(t,{},this.getMultiAuthHeaders()),r=this.extractDataOrNull(n);return{banned:null!==r,...null!==r&&{ban:r},tokenName:Vt(e.tokenName),userAddress:e.userAddress.toLowerCase()}}async getActiveUsers(e){!function(e){if(jn(e.tokenName,"tokenName",on),void 0!==e.type&&!kE(e.type))throw new yt(`type must be one of: ${Object.values(SE).join(", ")}`,"type",mt.INVALID_VALUE)}(e);const t=this.buildEndpoint(X,{tokenName:e.tokenName}),n={};this.addOptionalFilterParams(n,e,["type","search","name","userAddress"]);const r=await this.http.get(t,n,this.getMultiAuthHeaders());return this.extractData(r)}async createGlobalBan(e){!function(e){RE(e)}(e);const t=DE(e),n=await this.http.post(Y,t,this.getDualAuthHeaders());return{ban:this.extractData(n)}}async removeGlobalBan(e){!function(e){if(!Kn(e.userAddress))throw St("userAddress")}(e);const t=this.buildEndpoint(Z,{userAddress:e.userAddress}),n=await this.http.delete(t,{},this.getDualAuthHeaders()),r=this.extractDataOrNull(n);return{removed:r?.removed??!0,userAddress:r?.userAddress??e.userAddress.toLowerCase()}}async listGlobalBans(e){const t=e??{pageSize:20};!function(e){Hn(0,void 0,ln,e.pageSize)}(t);const n=this.buildPaginationParams(t,ln);this.addOptionalFilterParams(n,t,["search","name","userAddress"]);const r=await this.http.get(J,n,this.getDualAuthHeaders()),s=this.extractData(r);return{items:s.bans,pageInfo:s.pageInfo}}async getGlobalBan(e){!function(e){if(!Kn(e.userAddress))throw St("userAddress")}(e);const t=this.buildEndpoint(Q,{userAddress:e.userAddress}),n=await this.http.get(t,{},this.getDualAuthHeaders()),r=this.extractDataOrNull(n);return{banned:null!==r,...null!==r&&{ban:r},userAddress:e.userAddress.toLowerCase()}}}function DE(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 OE(e,t={}){const{maxPages:n=1e4,logger:r,pageSize:s=20,concurrency:i=1,startPage:o=1}=t,a=[];let c=o;const l=o+n-1;let u=!0,d=0;if(i<=1)for(;u&&c<=l;){r&&r.debug(`Auto-pagination: fetching page ${c} with limit ${s}`);const t=await e(c,s);if(null==t||!Array.isArray(t.items)){r&&r.warn("Auto-pagination: received invalid result structure, stopping");break}if(a.push(...t.items),d=t.total,r&&r.debug(`Auto-pagination: page ${c} returned ${t.items.length} items, hasNext: ${String(t.hasNext)}`),0===t.items.length){r&&r.debug(`Auto-pagination: no items returned on page ${c}, exiting loop`);break}u=t.hasNext,c++}else for(r&&r.debug(`Auto-pagination: using concurrent mode with concurrency=${i}`);u&&c<=l;){const t=[];for(let e=0;e<i&&c+e<=l;e++)t.push(c+e);r&&r.debug(`Auto-pagination: fetching pages ${t.join(", ")} concurrently`);const n=t.map(t=>e(t,s).catch(e=>{const n=e,i=n.statusCode??n.response?.status??n.originalError?.response?.status??n.status??n.launchpadError?.statusCode;if(400===i||404===i)return r&&r.debug(`Auto-pagination: page ${t} returned ${i} (end of pagination)`,{statusCode:i}),{items:[],total:0,totalPages:0,page:t,limit:s,hasNext:!1,hasPrevious:!1};throw e})),o=await Promise.all(n);for(const e of o){if(null==e||!Array.isArray(e.items)){r&&r.warn("Auto-pagination: received invalid result structure in batch, stopping"),u=!1;break}if(0===e.items.length){r&&r.debug("Auto-pagination: empty page in batch, reached end of results"),u=!1;break}if(a.push(...e.items),d=e.total,!e.hasNext){u=!1;break}}c+=t.length,r&&r.debug(`Auto-pagination: batch complete, total items so far: ${a.length}`)}return c>l&&r&&r.warn(`Auto-pagination: exceeded maxPages limit of ${n} (maxPage=${l}), stopping iteration`),r&&r.debug(`Auto-pagination: completed with total items: ${a.length}, total count: ${d}`),{items:a,total:d}}function ME(e){if("string"==typeof e){if(!pw(e))throw new yt(`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 t=e.split("|");if(t.length>=5){const e=gw(t.slice(0,4).join("|")),n=t[4]??"0";return{...e,instance:n.length>0?n:"0"}}return{...gw(e),instance:"0"}}if("object"==typeof e&&null!==e){if("instance"in e&&void 0!==e.instance&&"string"==typeof e.instance&&e.instance.length>0){if(!yw(e))throw new yt("Invalid tokenId object format. All fields (collection, category, type, additionalKey) must be non-empty strings","tokenId","INVALID_TOKEN_ID_FORMAT");return e}if(!yw(e))throw new yt("Invalid tokenId object format. All fields (collection, category, type, additionalKey) are required","tokenId","INVALID_TOKEN_ID_FORMAT");return{...e,instance:"0"}}throw new yt(`Invalid tokenId type: ${typeof e}. Expected string, TokenClassKey, or TokenInstanceKey`,"tokenId","INVALID_TOKEN_ID_TYPE")}function LE(e){return function(e){try{if(!Kn(e))throw new Error("Vault address must be a non-empty string");const t=e.split("|")[1];if(""===t||void 0===t)throw new Error("Missing token part after service prefix");const n=t.split("$");return dw((n.length>=5&&"launchpad"===n[n.length-1]?n.slice(0,-1):n).join("$"),"$","vault address")}catch(t){throw new yt(`Invalid vault address: "${e}". Expected format: "service|Token$Unit$SYMBOL$additionalKey$launchpad". Error: ${at(t)}`,"vaultAddress","INVALID_VAULT_ADDRESS_FORMAT")}}(e)}function UE(e){return{...LE(e),instance:"0"}}function PE(e){const t=LE(e);if("Token"!==t.collection)throw new yt(`Cannot extract a token symbol from vault address "${e}": collection "${t.collection}" is not the launchpad "Token" collection, and a symbol cannot be derived from a class key.`,"vaultAddress","SYMBOL_NOT_DERIVABLE_FROM_KEY");return t.type}function FE(e){return io(ME(e))}var $E=Object.freeze({__proto__:null,extractTokenSymbolFromVault:PE,isTokenClassKeyStrict:yw,normalizeToTokenInstanceKey:ME,normalizeTokenIdToString:FE,parseVaultAddressToTokenClassKey:LE,parseVaultAddressToTokenInstance:UE});class KE{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 r=Math.min(t,this.getMaxLimit()),s=this.buildApiParams(n),i=await this.dexApiHttp.request({method:"GET",url:this.getApiEndpoint(),params:{...s,pageSize:r,offset:e}});if(Wn(i)||!Array.isArray(i.tokens))throw new yt("Invalid API response: expected { tokens: array }","response","INVALID_RESPONSE");return{items:this.transformApiResponse(i.tokens),rawCount:i.tokens.length}}async autoPaginateFetch(e){return async function(e,t){const{maxLimit:n,logger:r,maxPages:s=1e4}=t,i=[];let o=0,a=!0,c=0;for(;a&&c<s;){r&&r.debug(`Auto-pagination (offset): fetching at offset ${o} with limit ${n}`);const t=await e(o,n);if(null==t||!Array.isArray(t.items)){r&&r.warn("Auto-pagination (offset): received invalid result structure, stopping");break}i.push(...t.items),a=t.rawCount===n,o+=n,c++,r&&r.debug(`Auto-pagination (offset): fetched ${i.length} items so far (hasMore=${String(a)})`)}return c>=s&&r&&r.warn(`Auto-pagination (offset): exceeded maxPages limit of ${s}, stopping`),r&&r.debug(`Auto-pagination (offset): completed with total items: ${i.length}`),i}(async(t,n)=>this.executePaginatedRequest(t,n,e),{maxLimit:this.getMaxLimit(),logger:this.logger})}handleError(e,t){throw Ct(e,t,this.logger)}}class GE extends sr{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,r=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));r.set(s,e)}this.primaryIndex.set(e,n),this.secondaryIndex.set(e,r),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 r=this.secondaryIndex.get(e);r||(r=new Map,this.secondaryIndex.set(e,r));for(const e of t){const t=this.normalizeKey(this.extractPrimaryKey(e));n.set(t,e);const s=this.normalizeKey(this.extractSecondaryKey(e));r.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 r={},s={};for(const t of e)r[t]=0;for(const[e,i]of this.primaryIndex){t.push(e),n+=i.size,r[e]=i.size;const o=this.fetchTimestamps.get(e);void 0!==o&&(s[e]=o)}return{networks:t,totalItems:n,itemsByNetwork:r,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 WE=["ETHEREUM","SOLANA"];class HE extends GE{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(WE);return{...e,totalTokens:e.totalItems,tokensByNetwork:e.itemsByNetwork}}}class qE extends KE{constructor(e,t=!1){super(e,t,"BridgeableTokenService"),this.cache=new HE(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),r=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:r};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:r=this.getDefaultLimit()}=e,s=Math.min(r,this.getMaxLimit());return this.logger.debug(`Fetching bridgeable tokens for ${t} (offset=${n}, limit=${s})`),Ji(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 Ji(async()=>{const t=await async function(e){const{network:t,cache:n,fetchFn:r,logger:s,itemTypeName:i="items"}=e;if(n.has(t)){const e=n.getAll(t);return s&&s.debug(`Returning ${e.length} cached ${i} for ${t}`),{items:e,fetchedAt:n.getFetchTimestamp(t)??Date.now(),itemCount:e.length}}s&&s.debug(`Fetching all ${i} for ${t} (no cache)`);const o=await r();return n.set(t,o),{items:o,fetchedAt:Date.now(),itemCount:o.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,r=FE(t);this.cache.has(n)||await this.fetchAllBridgeableTokensByNetwork(n);const s=this.cache.getByTokenId(n,r),i=void 0!==s,o=i?"ETHEREUM"===n?s.ethereumContractAddress:s.solanaContractAddress:void 0,a={isBridgeable:i,network:n};return void 0!==s?.symbol&&(a.tokenSymbol=s.symbol),void 0!==o&&(a.contractAddress=o),a}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 zE(e){return{maxAcceptableReverseBondingCurveFee:Bn(e.maxAcceptableReverseBondingCurveFee)}}class VE extends i.ChainCallDTO{constructor(e,t,n="0",r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=Bn(t),this.expectedToken=Dn(n),this.extraFees=zE(r)}}class jE extends i.ChainCallDTO{constructor(e,t,n,r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=Dn(t),this.expectedNativeToken=Bn(n),this.extraFees=zE(r)}}class XE extends i.ChainCallDTO{constructor(e,t,n="0",r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=Dn(t),this.expectedNativeToken=Bn(n),this.extraFees=zE(r)}}class YE extends i.ChainCallDTO{constructor(e,t,n,r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=Bn(t),this.expectedToken=Dn(n),this.extraFees=zE(r)}}const JE={BuyNativeDto:VE,BuyExactDto:jE,SellExactDto:XE,SellNativeDto:YE};function QE(e,t,n){let r;On(t,0,1,"slippageToleranceFactor");try{r=_n(e,"expectedAmount")}catch{throw new Error(`Invalid expected amount: ${e}. Must be a valid number`)}if(0===t)return e;const s=r.multipliedBy(t);let i;switch(n){case"buy-native":case"sell-exact":i=r.minus(s);break;case"buy-exact":case"sell-native":i=r.plus(s);break;default:throw new Error(`Unknown operation type: ${n}`)}return ki(i).isLessThan(0)&&(i=ki(0)),Ti(i)}function ZE(e){return`${e}-${Date.now()}_${r.v4().replace(/-/gu,"").substring(0,26)}`}function eA(){return ZE("galaconnect-operation")}function tA(e,t){const n={[e]:[]},r=new Set;function s(e){const t=n[e];if(void 0===t)throw new Error("Missing EIP-712 type "+e);return t}function i(e,t,o,a=!1){if(void 0===t)return;if(Array.isArray(t)){const n=i(e,t[0],o,!0);return a||(r.add(e),s(o).push({name:e,type:(n??e)+"[]"})),void 0===n?void 0:n+"[]"}if("object"==typeof t&&null!==t){if(void 0!==n[e]||r.has(e))throw new Error("Name collisions not yet supported");n[e]=[];for(const[n,s]of Object.entries(t)){if(r.has(n))throw new Error("Name collisions not yet supported");i(n,s,e)}return a||(r.add(e),s(o).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 a||(r.add(e),s(o).push({name:e,type:c})),c}for(const[n,r]of Object.entries(t))i(n,r,e);return n}const nA={name:"GalaChain"},rA={name:"ethereum",chainId:1};function sA(e){if("string"!=typeof e)throw new Error("Wallet returned an invalid signature");return e}function iA(e,t,n,r){return{...e,signature:t,types:n,domain:r}}class oA extends t.PrivateKeySigner{constructor(t){super(t),this.typedDataWallet=new e.Wallet(t),this.walletAddress=`eth|${this.typedDataWallet.address.slice(2)}`}async signTypedData(e,t){const n=tA(e,t);return iA(t,await this.typedDataWallet.signTypedData(nA,n,t),n,nA)}}class aA extends t.GalaWalletSigner{async signTypedData(e,t){const n=tA(e,t),r={domain:rA,types:n,message:t,Primary_type:e};return iA(t,sA(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(r),this.walletAddress]})),n,rA)}}class cA extends t.BrowserWalletSigner{constructor(e,t){super(e,t),this.typedDataProvider=e}async signTypedData(e,t){const n=this.typedDataProvider,r=await n.getNetwork(),s={name:r.name,chainId:Number(r.chainId)},i=tA(e,t),o=await n.getSigner();return iA(t,sA(await o.signTypedData(s,i,t)),i,s)}}function lA(e){const[t,n]=e.split("|",2);if("service"!==t||void 0===n)throw new Error(`Invalid vaultAddress format (expected service|<collection>$<category>$<type>$<additionalKey>$launchpad): ${e}`);const r=n.split("$"),s=r[r.length-1],i=r.slice(0,-1),o=i.slice(0,-3).join("$"),[a,c,l]=i.slice(-3);if("launchpad"!==s||i.length<4||""===o||void 0===a||void 0===c||void 0===l||""===a||""===c||""===l)throw new Error(`Invalid vaultAddress format (expected service|<collection>$<category>$<type>$<additionalKey>$launchpad): ${e}`);return{collection:o,category:a,type:c,additionalKey:l}}function uA(e){const{collection:t,category:n,type:r}=lA(e),s=`${t}$${n}$${r}$none`,i="GALA$Unit$none$none";return[`$service$${s}$launchpad`,`$tokenBalance$${s}$${e}`,`$tokenBalance$${s}$${e}`,`$tokenBalance$${i}$${e}`,`$tokenBalance$${i}$${e}`]}function dA(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 hA extends sr{constructor(e=!1){super(e)}generateStringsInstructions(e){try{this.logger.debug("🔧 Generating stringsInstructions for:",e);const t=uA(e);return this.logger.debug("✅ Generated stringsInstructions:",t),t}catch(e){this.logger.error("❌ Failed to generate stringsInstructions:",e);const t=at(e);throw new yt(`Failed to generate stringsInstructions: ${t}`,"vaultAddress","INVALID_VAULT_ADDRESS")}}createGalaInstance(){const e=new i.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(!Kn(e))throw St("vaultAddress","Vault address");try{const t=PE(e);return this.logger.debug("🔍 Extracted token symbol:",{vaultAddress:e,tokenSymbol:t}),t}catch(e){if(e instanceof yt)throw kt("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad");throw e}}validateVaultAddress(e){if(!Kn(e))throw St("vaultAddress","Vault address");if(!e.startsWith("service|Token$Unit$"))throw kt("vaultAddress",'starting with "service|Token$Unit$"');if(!e.endsWith("$launchpad"))throw kt("vaultAddress",'ending with "$launchpad"');const t=function(e){if(!Kn(e))return null;const t=e.match(/^service\|Token\$Unit\$([^$]+)\$eth:([a-fA-F0-9]{40})\$launchpad$/);if(!t)return null;const n=t[1],r=t[2];return void 0===n||void 0===r?null:{tokenSymbol:n,creatorAddress:r.toLowerCase()}}(e);if(!t)throw kt("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 kt("vaultAddress","containing a 1-10 letter token symbol (case insensitive)");return this.logger.debug("✅ Vault address validation passed:",e),!0}generateTokenClassKeyString(e,t,n,r){return`${e}$${t}$${n}$${r}`}parseTokenClassKeyString(e){try{return fw(e)}catch(e){if(e instanceof yt)throw kt("stringKey","format: collection$category$type$additionalKey (4 parts)");throw e}}}function gA(e){return"object"==typeof e&&null!==e?e:void 0}class fA extends rr{constructor(e,t,n=!1,r,s,i=.05,o=.01){if(super(e,n),this.tokenResolver=t,this._walletProvider=r,this.userAddress=s,this.defaultSlippageToleranceFactor=i,this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor=o,this.bundleEndpoint="/bundle",null!==this._walletProvider&&void 0!==this._walletProvider&&null!=s){const e=gA(this._walletProvider),t=e?.privateKey;"string"==typeof t?this.signer=new oA(t):function(e){const t=gA(e);return"function"==typeof t?.request}(this._walletProvider)&&void 0!==this.userAddress&&(this.signer=new cA(this._walletProvider,this.userAddress)),this.tokenKeyService=new hA(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:Pt(n),error:n.error}),this.handleBundleResponse(n))}catch(e){if(e instanceof yt)return{success:!1,error:at(e)};throw e}}validateBundleData(e){if(null==e)throw St("bundleData","Bundle data");if(null===e.signedDto||void 0===e.signedDto)throw St("signedDto","Signed DTO");if(!Kn(e.method))throw St("method","Method name");if(!Array.isArray(e.stringsInstructions))throw kt("stringsInstructions","an array of resource tracking strings");if(0===e.stringsInstructions.length)throw new yt("stringsInstructions cannot be empty","stringsInstructions","EMPTY_ARRAY");const t=["BuyWithNative","BuyExactToken","SellExactToken","SellWithNative"];if(!t.includes(e.method))throw kt("method",`one of: ${t.join(", ")}`);e.stringsInstructions.forEach((e,t)=>{if(!Kn(e))throw new yt(`stringsInstructions[${t}] must be a non-empty string`,`stringsInstructions[${t}]`,"INVALID_INSTRUCTION");if(!mw(e))throw new yt(`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(ut(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 at(e)??"Unknown bundle transaction error"}async getBundlerTransactionResult(e){try{if(!Kn(e))throw St("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 yt)return{success:!1,error:at(e)};throw e}}async cancelTransaction(e){try{if(!Kn(e))throw St("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 yt)return{success:!1,error:at(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:r,expectedAmount:s}=e,{effectiveSlippageFactor:i,effectiveMaxFee:o,vaultAddress:a}=await this.prepareTradingOperation(t,e.maxAcceptableReverseBondingCurveFee,e.maxAcceptableReverseBondingCurveFeeSlippageFactor,e.slippageToleranceFactor);if("native"===r){if(null==s||""===s)throw new yt("expectedAmount is required for native buy operations. Use getBuyTokenAmount() first to calculate expected tokens.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=QE(s,i,"buy-native");this.logger.debug("BuyNative slippage applied:",{originalExpectedTokens:s,slippageFactor:i,adjustedMinTokens:e});const t=new JE.BuyNativeDto(a,n,e,{maxAcceptableReverseBondingCurveFee:o});return await this.executeBundleTransaction(t,"BuyWithNative",a)}{if(null==s||""===s)throw new yt("expectedAmount is required for exact buy operations. Use getBuyTokenAmount() first to calculate expected GALA cost.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=QE(s,i,"buy-exact");this.logger.debug("BuyExact slippage applied:",{originalExpectedGalaCost:s,slippageFactor:i,adjustedMaxGalaCost:e});const t=new JE.BuyExactDto(a,n,e,{maxAcceptableReverseBondingCurveFee:o});return await this.executeBundleTransaction(t,"BuyExactToken",a)}}async sellToken(e){this.ensureTradingServicesAvailable();const{tokenName:t,amount:n,type:r,expectedAmount:s}=e,{effectiveSlippageFactor:i,effectiveMaxFee:o,vaultAddress:a}=await this.prepareTradingOperation(t,e.maxAcceptableReverseBondingCurveFee,e.maxAcceptableReverseBondingCurveFeeSlippageFactor,e.slippageToleranceFactor);if("exact"===r){if(null==s||""===s)throw new yt("expectedAmount is required for exact sell operations. Use getSellTokenAmount() first to calculate expected GALA.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=QE(s,i,"sell-exact");this.logger.debug("SellExact slippage applied:",{originalExpectedGala:s,slippageFactor:i,adjustedMinGala:e});const t=new JE.SellExactDto(a,n,e,{maxAcceptableReverseBondingCurveFee:o});return await this.executeBundleTransaction(t,"SellExactToken",a)}{if(null==s||""===s)throw new yt("expectedAmount is required for native sell operations. Use getSellTokenAmount() first to calculate tokens to sell.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=QE(s,i,"sell-native");this.logger.debug("SellNative slippage applied:",{originalExpectedTokensToSell:s,slippageFactor:i,adjustedMaxTokensToSell:e});const t=new JE.SellNativeDto(a,n,e,{maxAcceptableReverseBondingCurveFee:o});return await this.executeBundleTransaction(t,"SellWithNative",a)}}async prepareTradingOperation(e,t,n,r){const{effectiveSlippageFactor:s,effectiveMaxFee:i}=this.calculateEffectiveSlippage(t,n,r),o=await this.resolveTokenNameToVault(e);if(null==o)throw At(e);return{effectiveSlippageFactor:s,effectiveMaxFee:i,vaultAddress:o}}calculateEffectiveSlippage(e,t,n){const r=n??this.defaultSlippageToleranceFactor,s=t??this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor;let i=e??"0";return null!=e&&(i=QE(e,s,"buy-exact"),this.logger.debug("Reverse bonding curve fee slippage applied:",{baseFee:e,slippageFactor:s,adjustedMaxFee:i})),{effectiveSlippageFactor:r,effectiveFeeSlippageFactor:s,effectiveMaxFee:i}}ensureTradingServicesAvailable(){if(!this.signer||!this.tokenKeyService)throw It("Trading services not available. BundleService requires walletProvider and userAddress for trading operations.","walletProvider");if(null===this.userAddress||void 0===this.userAddress)throw St("userAddress","User address")}async executeBundleTransaction(e,t,n){this.ensureTradingServicesAvailable();try{e.uniqueKey=ZE("galaswap-operation");const r=await this.signer.signObject(t,e),s=this.tokenKeyService.generateStringsInstructions(n),i={stringsInstructions:s,method:t,signedDto:r};this.logger.debug("📦 Bundle transaction data:",{method:t,stringsInstructions:s,dtoKeys:Object.keys(r)});const o=await this.submitTransaction(i);if(o.success){const e=$t(o);if(null!=e)return this.logger.debug("✅ Bundle transaction submitted:",e),{success:!0,data:{transactionId:e,message:"Transaction submitted successfully. Monitor WebSocket for completion."}}}const a=o.error;throw new wt("string"==typeof a?a:"Bundle transaction failed",void 0,"BUNDLE_FAILED")}catch(e){throw this.logger.error("❌ Bundle transaction error:",e),e}}async resolveTokenNameToVault(e){return await this.tokenResolver.resolveTokenToVault(e)}}class pA extends rr{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(rt),t=this.extractData(e);return this.logger.debug("Fetched client feature flags",{flagCount:Object.keys(t.flags).length}),{flags:t.flags}}}var mA,yA,bA,vA;exports.ContentType=void 0,(mA=exports.ContentType||(exports.ContentType={})).CHAT_MESSAGE="CHAT_MESSAGE",mA.COMMENT="COMMENT",mA.STREAM="STREAM",mA.RECORDING="RECORDING",exports.FlagReason=void 0,(yA=exports.FlagReason||(exports.FlagReason={})).INAPPROPRIATE_CONTENT="INAPPROPRIATE_CONTENT",yA.SPAM="SPAM",yA.HARASSMENT="HARASSMENT",yA.SCAM="SCAM",yA.OTHER="OTHER",exports.FlagStatus=void 0,(bA=exports.FlagStatus||(exports.FlagStatus={})).PENDING="PENDING",bA.DISMISSED="DISMISSED",bA.ACTIONED="ACTIONED",exports.FlagAction=void 0,(vA=exports.FlagAction||(exports.FlagAction={})).DELETE_CONTENT="DELETE_CONTENT",vA.BAN_USER="BAN_USER",vA.DELETE_AND_BAN="DELETE_AND_BAN";const wA={[exports.FlagReason.INAPPROPRIATE_CONTENT]:"Inappropriate Content",[exports.FlagReason.SPAM]:"Spam",[exports.FlagReason.HARASSMENT]:"Harassment",[exports.FlagReason.SCAM]:"Scam",[exports.FlagReason.OTHER]:"Other"},EA={[exports.FlagStatus.PENDING]:"Pending",[exports.FlagStatus.DISMISSED]:"Dismissed",[exports.FlagStatus.ACTIONED]:"Actioned"},AA={[exports.FlagAction.DELETE_CONTENT]:"Delete Content",[exports.FlagAction.BAN_USER]:"Ban User",[exports.FlagAction.DELETE_AND_BAN]:"Delete & Ban"},SA={[exports.ContentType.CHAT_MESSAGE]:"Chat Message",[exports.ContentType.COMMENT]:"Comment",[exports.ContentType.STREAM]:"Stream",[exports.ContentType.RECORDING]:"Recording"},kA=qn(exports.ContentType),TA=qn(exports.FlagReason),IA=qn(exports.FlagStatus),NA=qn(exports.FlagAction),CA=Yn([{field:"id",type:"number"},{field:"tokenName",type:"string"},{field:"contentType",type:"string",validator:kA},{field:"contentId",type:"string"},{field:"reporterAddress",type:"string"},{field:"reportedUserAddress",type:"string"},{field:"status",type:"string",validator:IA}]),_A={TOKEN_NAME:an,CONTENT_ID:fn.CONTENT_ID,DETAILS:fn.FLAG_DETAILS,PAGINATION:{MAX_LIMIT:ln}};function xA(e,t="tokenName"){jn(e,t,_A.TOKEN_NAME)}function RA(e){if(void 0!==e.contentType&&!kA(e.contentType))throw kt("contentType",`one of: ${Object.values(exports.ContentType).join(", ")}`,"Content type");if(void 0!==e.status&&!IA(e.status))throw kt("status",`one of: ${Object.values(exports.FlagStatus).join(", ")}`);if(void 0!==e.reason&&!TA(e.reason))throw kt("reason",`one of: ${Object.values(exports.FlagReason).join(", ")}`);if(void 0!==e.reporterAddress&&!Kn(e.reporterAddress))throw Bt("reporterAddress","a non-empty string",typeof e.reporterAddress);if(void 0!==e.reporterAddress&&mr(e.reporterAddress,"reporterAddress"),void 0!==e.reportedUserAddress&&!Kn(e.reportedUserAddress))throw Bt("reportedUserAddress","a non-empty string",typeof e.reportedUserAddress);void 0!==e.reportedUserAddress&&mr(e.reportedUserAddress,"reportedUserAddress"),Hn(0,void 0,_A.PAGINATION.MAX_LIMIT,e.pageSize)}class BA extends uE{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async createFlag(e){!function(e){if(xA(e.tokenName),void 0===e.contentType)throw St("contentType","Content type");if(!kA(e.contentType))throw kt("contentType",`one of: ${Object.values(exports.ContentType).join(", ")}`,"Content type");if(!Kn(e.contentId))throw St("contentId","Content ID");if(e.contentId.length>_A.CONTENT_ID.MAX_LENGTH)throw Rt("contentId",_A.CONTENT_ID.MAX_LENGTH,e.contentId.length,"Content ID");if(!Kn(e.reportedUserAddress))throw St("reportedUserAddress","Reported user address");if(mr(e.reportedUserAddress,"reportedUserAddress"),!(e.contentType!==exports.ContentType.STREAM&&e.contentType!==exports.ContentType.RECORDING||void 0!==e.reason&&null!==e.reason))throw St("reason","Reason");if(void 0!==e.reason&&!TA(e.reason))throw kt("reason",`one of: ${Object.values(exports.FlagReason).join(", ")}`,"Reason");if(void 0!==e.details&&!Kn(e.details))throw Bt("details","a non-empty string",typeof e.details);if(void 0!==e.details&&e.details.length>_A.DETAILS.MAX_LENGTH)throw Rt("details",_A.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(le.CREATE,t,this.getMultiAuthHeaders());return{flag:this.extractData(n).flag}}async listFlags(e){return function(e){xA(e.tokenName),RA(e)}(e),this.fetchFlagList(e)}async listGlobalFlags(e={}){return function(e){void 0!==e.tokenName&&xA(e.tokenName),RA(e)}(e),this.fetchFlagList(e)}async dismissFlag(e){!function(e){if(void 0===e.flagId||null===e.flagId)throw St("flagId","Flag ID");try{Ln(e.flagId,"flagId")}catch{throw kt("flagId","a positive integer","Flag ID")}}(e);const t=le.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 St("flagId","Flag ID");try{Ln(e.flagId,"flagId")}catch{throw kt("flagId","a positive integer","Flag ID")}if(void 0===e.action)throw St("action","Action");if(!NA(e.action))throw kt("action",`one of: ${Object.values(exports.FlagAction).join(", ")}`,"Action")}(e);const t=le.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=aE(e,ln);cE(t,e,["tokenName","contentType","status","reason","reporterAddress","reportedUserAddress"]);const n=await this.http.get(le.LIST,t,this.getMultiAuthHeaders()),r=this.extractData(n);return{items:r.flags,pageInfo:r.pageInfo}}}const DA=["heart","fire","laugh","wow","thumbs_up"];class OA extends uE{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}validateReactionTokenName(e){this.validateTokenName(e,an)}validateMessageId(e){if(!Kn(e))throw St("messageId","Message ID");if(Mn(e,pn.CONTENT_REACTION.MAX_LENGTH,"messageId"),!pn.CONTENT_REACTION.PATTERN.test(e))throw kt("messageId","msg-{timestamp}-{uuid} or chat-{timestamp}-{uuid} format","Message ID")}validateReactionType(e){if(!Kn(e))throw St("reactionType","Reaction type");if(!DA.includes(e))throw kt("reactionType",`one of: ${DA.join(", ")}`,"Reaction type")}async addContentReaction(e){void 0!==e.tokenName&&this.validateReactionTokenName(e.tokenName),this.validateMessageId(e.messageId),this.validateReactionType(e.reactionType);const t=Le,n={messageId:e.messageId,reactionType:e.reactionType};void 0!==e.tokenName&&(n.tokenName=Vt(e.tokenName));const r=await this.http.post(t,n,this.getMultiAuthHeaders()),s=this.extractData(r),{created:i,...o}=s;return{data:o,created:i}}async removeContentReaction(e){void 0!==e.tokenName&&this.validateReactionTokenName(e.tokenName),this.validateMessageId(e.messageId),this.validateReactionType(e.reactionType);const t=`${Ue}?${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)}}function MA(e){if(!Kn(e))throw new Error("Invalid token format: token must be a non-empty string");return e.replace(/\|/g,"$")}class LA extends sr{constructor(e,t,n,r=!1){super(r),this.dexBackendHttp=e,this.cache=t,this.galaChainService=n}async fetchTokenPrice(e){const{tokenId:t}=e,{hasB:n}=Vn(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 yt("tokenName parameter requires LaunchpadSDK routing - call LaunchpadSDK.fetchTokenPrice({tokenName}) instead","tokenName","INVALID_PARAMS")}async resolveAuthoritativeSymbol(e,t){if("GALA|Unit|none|none"===t)return"GALA";const n=this.cache?.getByTokenId(t);if(null!=n?.symbol&&""!==n.symbol)return n.symbol;let r;this.logger.debug(`Symbol cache miss for ${t}, fetching from API`);try{r=(await this.fetchTokenDetails(e)).symbol}catch(e){throw Tt(`Could not resolve the symbol for ${t} from the token class, and a symbol cannot be derived from the class key: ${at(e)}`)}if(""===r)throw Tt(`Token class for ${t} has no symbol`);return this.cache?.setByTokenId(t,{symbol:r}),this.logger.debug(`Cached symbol for ${t}: ${r}`),r}async _fetchDexTokenSpotPrice(e){if(null==e)throw St("tokenId","Token ID");try{const t=io(ME(e)),n=MA(t);if(this.logger.debug(`Fetching DEX spot price for token: ${n}`),!this.dexBackendHttp)throw Tt("DEX Backend API client not configured");const r=t,s=await this.resolveAuthoritativeSymbol(e,r),i=await this.dexBackendHttp.request({method:"GET",url:"/market/price",params:{assetIds:n}}),o=null!==i&&"object"==typeof i?i:{},a=Object.keys(o).find(e=>e.toUpperCase()===s.toUpperCase()),c=void 0!==a?o[a]:1===Object.keys(o).length?Object.values(o)[0]:void 0,l=c?.price;if("number"!=typeof l||!Number.isFinite(l))throw new yt(`Invalid price response: no market price for ${n}`,"data","INVALID_RESPONSE");return this.logger.debug(`DEX spot price for ${s}: $${l}`),{symbol:s,price:l}}catch(e){if(e instanceof yt)throw e;throw Tt(`Failed to fetch DEX spot price: ${at(e)}`)}}async fetchLaunchpadTokenSpotPrice(e,t,n){if(!Kn(e))throw new yt(ft,"tokenName",mt.REQUIRED);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=io(t.sellingToken);return this._fetchDexTokenSpotPrice(n)}}catch(t){this.logger.debug(`Could not determine graduation status for ${e}, falling back to bonding curve: ${at(t)}`)}this.logger.debug(`Using bonding curve calculation for token: ${e}`);const r=await t({tokenName:e,amount:"1",type:"native"}),s=await this._fetchDexTokenSpotPrice({collection:"GALA",category:"Unit",type:"none",additionalKey:"none"});if(null==s)throw Tt("GALA price not available");const i=In(r.amount,0)/1e18;if(i<=0)throw new yt(`Invalid token amount calculation: ${i}`,"amount","INVALID_CALCULATION");const o=s.price/i;return{symbol:Xt(e),price:o}}catch(t){if(ot(t))throw Tt(`Failed to calculate launchpad token spot price for ${e}: ${at(t)}`);throw Tt(`Failed to calculate launchpad token spot price for ${e}: ${at(t)}`)}}async fetchTokenDetails(e){this.logger.debug("Fetching token details from GalaChain for tokenId:",e);try{if(!this.galaChainService)throw Tt("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 yt||ot(t))&&("NetworkError"===t.name||at(t).includes("Token not found")))throw t;throw Tt(`Failed to fetch token details from GalaChain for ${String(e)}: ${at(t)}`,500)}}async fetchAllDexSeasons(){try{if(!this.dexBackendHttp)throw Tt("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:nn(t?.start??null),end:nn(t?.end??null),rulesId:t?.rules_id??0}});return this.logger.debug(`Fetched ${n.length} DEX seasons`),n}catch(e){if(ot(e)&&at(e).includes("not configured"))throw e;if(ut(e)&&404===e.response?.status)return this.logger.warn("Seasons endpoint not available"),[];throw Tt(`Failed to fetch DEX seasons: ${at(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{Ln(e,"seasonId")}catch{throw St("seasonId","Season ID must be a positive number")}try{if(!this.dexBackendHttp)throw Tt("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 r=$t(t);if(null!=r&&"object"==typeof r&&Array.isArray(r.leaderboard))n=r.leaderboard;else if(Array.isArray(t.leaderboard))n=t.leaderboard;else{if(!Array.isArray(r))return this.logger.warn("Leaderboard endpoint returned unexpected structure:",t),{entries:[],seasonId:e,totalEntries:0};n=r}}}const r=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 ${r.length} entries`),{entries:r,seasonId:e,totalEntries:r.length}}catch(t){if(ot(t)&&at(t).includes("must be a positive number"))throw t;throw Tt(`Failed to fetch DEX leaderboard for season ${e}: ${at(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 Tt("DEX Backend API client not configured");const e=$t(await this.dexBackendHttp.request({method:"GET",url:"/v2/trade/volume"}));if(!e)throw Tt("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 Tt(`Failed to fetch DEX volume summary: ${at(e)}`)}}}const UA={BATCH_SIZE:20,FLUSH_INTERVAL_MS:3e3,MAX_QUEUE_SIZE:1e3,FLUSH_ON_PAGE_HIDE:!0,FLUSH_ON_PAGE_UNLOAD:!0,DEBUG:!1};class PA{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??UA.BATCH_SIZE,flushIntervalMs:t.flushIntervalMs??UA.FLUSH_INTERVAL_MS,maxQueueSize:t.maxQueueSize??UA.MAX_QUEUE_SIZE,flushOnPageHide:t.flushOnPageHide??UA.FLUSH_ON_PAGE_HIDE,flushOnPageUnload:t.flushOnPageUnload??UA.FLUSH_ON_PAGE_UNLOAD,debug:t.debug??UA.DEBUG},this.setupPageLifecycleListeners()}track(e,t,n){if(this.isShuttingDown)return void this.logger.warn("EventsBatcher is shutting down, ignoring track call");const r={eventType:e,payload:t,clientTimestamp:(new Date).toISOString(),...void 0!==n?.userAddress&&""!==n.userAddress&&{userAddress:n.userAddress},...void 0!==n?.tokenName&&""!==n.tokenName&&{tokenName:n.tokenName},...void 0!==n?.sessionId&&""!==n.sessionId&&{sessionId:n.sessionId}};this.buffer(r),n?.immediate&&this.scheduleFlush(0)}async flush(){if(0===this.eventBuffer.length)return;this.cancelFlushTimer();const e=this.eventBuffer.splice(0);this.logger.debug(`Flushing ${e.length} events`);try{const t=await this.submitEvents(e);this.totalFlushed+=t.accepted,this.lastFlushTime=Date.now(),this.lastError=void 0,this.logger.debug(`Flush successful, accepted ${t.accepted} events`)}catch(t){throw this.eventBuffer.unshift(...e),this.lastError=t instanceof Error?t.message:String(t),this.logger.error(`Flush failed: ${this.lastError}`),t}}getStats(){const e={bufferedCount:this.eventBuffer.length,totalQueued:this.totalQueued,totalFlushed:this.totalFlushed,totalDropped:this.totalDropped};return void 0!==this.lastFlushTime&&(e.lastFlushTime=this.lastFlushTime),void 0!==this.lastError&&(e.lastError=this.lastError),e}configure(e){void 0!==e.batchSize&&(this.config.batchSize=e.batchSize),void 0!==e.flushIntervalMs&&(this.config.flushIntervalMs=e.flushIntervalMs),void 0!==e.maxQueueSize&&(this.config.maxQueueSize=e.maxQueueSize),void 0!==e.flushOnPageHide&&(this.config.flushOnPageHide=e.flushOnPageHide),void 0!==e.flushOnPageUnload&&(this.config.flushOnPageUnload=e.flushOnPageUnload)}async shutdown(e=5e3){if(this.isShuttingDown=!0,this.removePageLifecycleListeners(),0!==this.eventBuffer.length)try{await Promise.race([this.flush(),new Promise((t,n)=>setTimeout(()=>n(new Error("Flush timeout during shutdown")),e))])}catch(e){this.logger.error(`Shutdown flush failed: ${e instanceof Error?e.message:String(e)}`)}}buffer(e){this.eventBuffer.length>=this.config.maxQueueSize&&(this.eventBuffer.shift(),this.totalDropped++,this.logger.warn("Event buffer full, dropped oldest event")),this.eventBuffer.push(e),this.totalQueued++,this.eventBuffer.length>=this.config.batchSize?this.scheduleFlush(0):this.scheduleFlush(this.config.flushIntervalMs)}scheduleFlush(e){null===this.flushTimer&&(this.flushTimer=setTimeout(()=>{this.flushTimer=null,this.flush().catch(e=>{this.logger.error(`Scheduled flush failed: ${e instanceof Error?e.message:String(e)}`)})},e))}cancelFlushTimer(){null!==this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null)}async submitEvents(e){return await this.httpClient.post("/v1/events",{events:e})}setupPageLifecycleListeners(){"undefined"!=typeof document&&(this.config.flushOnPageHide&&document.addEventListener("visibilitychange",this.handleVisibilityChange),this.config.flushOnPageUnload&&window.addEventListener("beforeunload",this.handleBeforeUnload))}removePageLifecycleListeners(){"undefined"!=typeof document&&(this.config.flushOnPageHide&&document.removeEventListener("visibilitychange",this.handleVisibilityChange),this.config.flushOnPageUnload&&window.removeEventListener("beforeunload",this.handleBeforeUnload))}flushWithBeacon(){if("undefined"==typeof navigator||!navigator.sendBeacon)return;const e=this.eventBuffer.splice(0),t=JSON.stringify({events:e});try{const n=this.getBaseUrl();navigator.sendBeacon(`${n}/v1/events`,t)?(this.totalFlushed+=e.length,this.lastFlushTime=Date.now()):(this.eventBuffer.unshift(...e),this.logger.warn("sendBeacon returned false, events re-buffered"))}catch(t){this.eventBuffer.unshift(...e),this.logger.error(`sendBeacon failed: ${t instanceof Error?t.message:String(t)}`)}}getBaseUrl(){const e=this.httpClient.config;return e?.baseUrl??""}}function FA(e){return 0===(e?.length??0)?"0":e.reduce((e,t)=>o(e).plus(t.quantity).toString(),"0")}function $A(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 KA extends rr{constructor(e,t=!1){super(e,t)}getChannelForCollection(e){return"MUSIC"===(mw(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`,r=await this.http.post(n,e);if(null==r)return null;try{dt(r,"Fetch balances")}catch{return null}if(0===(r.Data?.length??0))return null;const s=r.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 i=io(s),a={quantity:s.quantity,collection:s.collection,category:s.category,tokenId:i};if((s.inUseHolds?.length??0)>0){const e=$A(s.inUseHolds??[],t);e.length>0&&(a.inUseHolds=e,a.inUseQuantity=FA(e))}if((s.lockedHolds?.length??0)>0){const e=$A(s.lockedHolds??[],t);e.length>0&&(a.lockedHolds=e,a.lockedQuantity=FA(e))}return void 0===a.lockedQuantity&&void 0===a.inUseQuantity||(a.availableQuantity=function(e,t="0",n="0"){return o(e).minus(t).minus(n).toString()}(a.quantity,a.lockedQuantity,a.inUseQuantity)),a}catch(e){throw Tt(`Failed to fetch token balance from GalaChain: ${at(e)}`,void 0,ot(e)?e:void 0)}}}function GA(e){return"string"==typeof e?{...fw(e),instance:"0"}:{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey,instance:"0"}}function WA(e){return oo(e)}function HA(e){const t=e[0];return void 0===t?void 0:WA(t.tokenInstanceKey)}class qA extends i.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,r,s){const i=GA(r);return new qA({lockAuthority:t??e,tokenInstances:[{owner:e,quantity:n,tokenInstanceKey:i}],...void 0!==s?.expires&&{expires:s.expires},...void 0!==s?.name&&{name:s.name},uniqueKey:s?.uniqueKey??eA()})}static forGALA(e,t,n,r){return new qA({lockAuthority:t??e,tokenInstances:[{owner:e,quantity:n,tokenInstanceKey:{collection:"GALA",category:"Unit",type:"none",additionalKey:"none",instance:"0"}}],...void 0!==r?.expires&&{expires:r.expires},...void 0!==r?.name&&{name:r.name},uniqueKey:r?.uniqueKey??eA()})}getTokenClassKey(){return HA(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 zA extends i.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,r){const s=GA(n);return new zA({tokenInstances:[{owner:e,quantity:t,tokenInstanceKey:s}],...void 0!==r?.name&&{name:r.name},uniqueKey:r?.uniqueKey??eA()})}static forGALA(e,t,n){return new zA({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??eA()})}getTokenClassKey(){return HA(this.tokenInstances)}toSigningPayload(){return{tokenInstances:this.tokenInstances,...void 0!==this.name&&{name:this.name},uniqueKey:this.uniqueKey}}}function VA(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Kn(t.amount)&&(void 0!==t.tokenId||Kn(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 jA(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Kn(t.amount)&&(void 0!==t.tokenId||Kn(t.tokenName))&&(void 0===t.name||"string"==typeof t.name)}function XA(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every(VA)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}function YA(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every(jA)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}var JA,QA;exports.LockErrorType=void 0,(JA=exports.LockErrorType||(exports.LockErrorType={})).TOKEN_NOT_FOUND="TOKEN_NOT_FOUND",JA.INVALID_AMOUNT="INVALID_AMOUNT",JA.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",JA.SIGNATURE_FAILED="SIGNATURE_FAILED",JA.NETWORK_ERROR="NETWORK_ERROR",JA.WALLET_REQUIRED="WALLET_REQUIRED",JA.VALIDATION_ERROR="VALIDATION_ERROR",JA.LOCK_NOT_FOUND="LOCK_NOT_FOUND",JA.LOCK_EXPIRED="LOCK_EXPIRED",JA.INSUFFICIENT_LOCKED_BALANCE="INSUFFICIENT_LOCKED_BALANCE",JA.NOT_LOCK_AUTHORITY="NOT_LOCK_AUTHORITY",JA.LOCK_NAME_MISMATCH="LOCK_NAME_MISMATCH";class ZA 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"}(QA||(QA={}));class eS extends Error{constructor(e,t,n){super(e),this.type=t,this.details=n,this.name="TransferError"}}function tS(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 nS(e,t,n,r="[DEBUG] Token resolution (launchpad)"){const s=await t.resolveTokenToVault(e);if(null!==s){const t=UE(s);return n.debug(r,{tokenName:e,vaultAddress:s,tokenInstance:{collection:t.collection,category:t.category,type:t.type,instance:t.instance}}),t}throw new yt(`Token "${e}" is not a launchpad token (no vault address found), and a token class key cannot be derived from a name. Pass an explicit tokenId (collection|category|type|additionalKey) for standard GalaChain tokens.`,"tokenName","TOKEN_CLASS_KEY_NOT_DERIVABLE")}const rS=100,sS=100;class iS extends rr{constructor(e,t,n,r=!1){super(e,r),this.wallet=t,this.tokenResolver=n,this.nativeSigner=t?new oA(t.privateKey):void 0}async lockTokens(e){if(this.validateLockTokensData(e),!this.wallet||!this.nativeSigner)throw new ZA("Wallet required for token lock operations",exports.LockErrorType.WALLET_REQUIRED);return Ji(async()=>{const{ownerAddress:t,tokenInstances:n}=this.createTokenOperationContext(),r=[];let s=t;const i=e.tokens.find(e=>void 0!==e.lockAuthority);void 0!==i?.lockAuthority&&(s=hr(i.lockAuthority));const o=e.tokens.find(e=>void 0!==e.expires),a=e.tokens.find(e=>void 0!==e.name);for(const i of e.tokens){const e=await this.resolveTokenEntry(i);n.push({owner:t,quantity:i.amount,tokenInstanceKey:e}),r.push({tokenClassKey:{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey},quantity:i.amount,lockAuthority:void 0!==i.lockAuthority?hr(i.lockAuthority):s})}const c=new qA({lockAuthority:s,tokenInstances:n,...void 0!==o?.expires&&{expires:o.expires},...void 0!==a?.name&&{name:a.name},uniqueKey:e.uniqueKey??eA()}),l=await this.nativeSigner.signObject("LockToken",c.toSigningPayload()),u=new qA({...c.toSigningPayload(),signedPayload:l}),d=await this.http.post("/api/asset/token-contract/LockToken",u);try{dt(d,"Token lock failed")}catch(e){const t=ht(d);throw new ZA(`${at(e)}${t}`,exports.LockErrorType.NETWORK_ERROR)}return this.extractLockResult(d,r)},"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 ZA("Wallet required for token unlock operations",exports.LockErrorType.WALLET_REQUIRED);return Ji(async()=>{const{ownerAddress:t,tokenInstances:n}=this.createTokenOperationContext(),r=[],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}),r.push({tokenClassKey:{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey},quantity:s.amount})}const i=new zA({tokenInstances:n,...void 0!==s?.name&&{name:s.name},uniqueKey:e.uniqueKey??eA()}),o=await this.nativeSigner.signObject("UnlockToken",i.toSigningPayload()),a=new zA({...i.toSigningPayload(),signedPayload:o}),c=await this.http.post("/api/asset/token-contract/UnlockToken",a);try{dt(c,"Token unlock failed")}catch(e){const t=ht(c);throw new ZA(`${at(e)}${t}`,exports.LockErrorType.NETWORK_ERROR)}return this.extractUnlockResult(c,r)},"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 ZA("Must provide either tokenId or tokenName for token identification",exports.LockErrorType.TOKEN_NOT_FOUND);if(void 0!==e.tokenName)try{Xn(e.tokenName,"tokenName")}catch{throw new ZA("Invalid token name format",exports.LockErrorType.TOKEN_NOT_FOUND,{tokenName:e.tokenName})}try{_i(ki(e.amount))}catch{throw new ZA(kt(t,"a positive number",n).message,exports.LockErrorType.INVALID_AMOUNT,{amount:e.amount})}}validateLockTokensData(e){if(!XA(e))throw new ZA("Invalid lock data: missing required fields",exports.LockErrorType.VALIDATION_ERROR);if(e.tokens.length>rS)throw new ZA(`Batch size exceeds maximum limit of ${rS} tokens per lock operation`,exports.LockErrorType.VALIDATION_ERROR);for(const t of e.tokens){if(this.validateSharedTokenEntry(t,"lockAmount","Lock amount"),void 0!==t.lockAuthority&&!pr(t.lockAuthority))throw new ZA("Invalid lock authority address format",exports.LockErrorType.VALIDATION_ERROR,{lockAuthority:t.lockAuthority});if(void 0!==t.expires)try{Ln(t.expires,"expires")}catch{throw new ZA(kt("expires","a positive integer (epoch milliseconds)","Expires").message,exports.LockErrorType.VALIDATION_ERROR)}}}validateUnlockTokensData(e){if(!YA(e))throw new ZA("Invalid unlock data: missing required fields",exports.LockErrorType.VALIDATION_ERROR);if(e.tokens.length>sS)throw new ZA(`Batch size exceeds maximum limit of ${sS} tokens per unlock operation`,exports.LockErrorType.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 r=e.Data[0];if(void 0===r)return{locked:t};n=r.transactionId??r.txnId??r.TxnId??r.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 r=e.Data[0];if(void 0===r)return{unlocked:t};n=r.transactionId??r.txnId??r.TxnId??r.id??void 0}return{...void 0!==n&&{transactionId:n},unlocked:t}}handleLockError(e,t,n){if(e instanceof ZA)return e;let r=t,s=exports.LockErrorType.NETWORK_ERROR;if(ut(e)){const n=e.response?.data;if("object"==typeof n&&null!==n){const e=n.Message;"string"==typeof e&&e.length>0&&(r=`${t}: ${e}`);const i="string"==typeof e?e.toLowerCase():"";i.includes("insufficient")||i.includes("balance")?s=exports.LockErrorType.INSUFFICIENT_BALANCE:i.includes("lock")&&i.includes("not found")?s=exports.LockErrorType.LOCK_NOT_FOUND:i.includes("not found")||i.includes("token")?s=exports.LockErrorType.TOKEN_NOT_FOUND:i.includes("authority")?s=exports.LockErrorType.NOT_LOCK_AUTHORITY:i.includes("expired")&&(s=exports.LockErrorType.LOCK_EXPIRED)}}else ot(e)&&(r=`${t}: ${at(e)}`);return new ZA(r,s,tS(n))}async resolveTokenInstance(e){return Ji(async()=>nS(e,this.tokenResolver,this.logger),`Failed to resolve token '${e}'`,this.logger,t=>{if(t instanceof eS)throw new ZA(at(t),exports.LockErrorType.TOKEN_NOT_FOUND);throw new ZA(`Failed to resolve token '${e}': ${at(t)}`,exports.LockErrorType.TOKEN_NOT_FOUND,{tokenName:e})})}async resolveTokenEntry(e){if(void 0!==e.tokenId){const t=ME(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 ZA("Must provide either tokenId or tokenName for token identification",exports.LockErrorType.TOKEN_NOT_FOUND)}createTokenOperationContext(){return{ownerAddress:hr(this.wallet.address),tokenInstances:[]}}}class oS extends rr{constructor(e,t=!1,n){super(e,t),this.publicAxios=n}async fetchTokenClassFromChain(e){try{const t="string"==typeof e?ME(e):e,n={tokenClasses:[{collection:t.collection,category:t.category,type:t.type,additionalKey:t.additionalKey}]};if(!this.publicAxios)throw St("publicAxios","Public Axios instance");const r=(await this.publicAxios.post("/api/asset/token-contract/FetchTokenClasses",n)).data;if(dt(r,"Failed to fetch token class from GalaChain"),null===r.Data||void 0===r.Data||0===r.Data.length)throw Tt(`Token not found on GalaChain: ${io(t)}`,404);const s=r.Data[0];if(void 0===s)throw Tt(`Token not found on GalaChain: ${io(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 St("tokenClasses","Token classes array");const t={tokenClasses:e};if(!this.publicAxios)throw St("publicAxios","Public Axios instance");const n=(await this.publicAxios.post("/api/asset/token-contract/FetchTokenClassesWithSupply",t)).data;if(dt(n,"Failed to fetch token classes with supply from GalaChain"),!n.Data||0===n.Data.length)throw Tt("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 yt)throw e;if(ut(e)&&404===e.response?.status)throw Tt(t,404,ot(e)?e:void 0);if(ot(e)&&"Error"===e.name&&at(e).includes("status indicates failure"))throw Tt(at(e),400,ot(e)?e:void 0);const r=at(e);if(r.includes("Token not found")){if(e instanceof Error)throw e;throw new Error(r)}throw Tt(`${n}: ${r}`,void 0,ot(e)?e:void 0)}}class aS extends i.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=GA(e.tokenClassKey);return{quantity:e.quantity,tokenInstanceKey:t}});return new aS({tokenInstances:n,uniqueKey:t?.uniqueKey??eA()})}static fromTokenClassKey(e,t,n){return aS.fromTokens([{tokenClassKey:t,quantity:e}],n)}static forGALA(e,t){return new aS({tokenInstances:[{quantity:e,tokenInstanceKey:{collection:"GALA",category:"Unit",type:"none",additionalKey:"none",instance:"0"}}],uniqueKey:t?.uniqueKey??eA()})}getTokenClassKey(){if(0===this.tokenInstances.length)return;const e=this.tokenInstances[0];return void 0!==e?WA(e.tokenInstanceKey):void 0}toSigningPayload(){return{tokenInstances:this.tokenInstances,uniqueKey:this.uniqueKey}}}class cS extends i.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,r,s){let i;if("string"==typeof r){i={...fw(r),instance:"0"}}else i={collection:r.collection,category:r.category,type:r.type,additionalKey:r.additionalKey,instance:"0"};return new cS({from:e,to:t,quantity:n,tokenInstance:i,uniqueKey:s??eA()})}static forGALA(e,t,n,r){return new cS({from:e,to:t,quantity:n,tokenInstance:{collection:"GALA",category:"Unit",type:"none",additionalKey:"none",instance:"0"},uniqueKey:r??eA()})}getTokenClassKey(){return oo(this.tokenInstance)}toSigningPayload(){return{from:this.from,to:this.to,quantity:this.quantity,tokenInstance:this.tokenInstance,uniqueKey:this.uniqueKey}}}function lS(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Kn(t.amount)&&(void 0!==t.tokenId||Kn(t.tokenName))}function uS(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every(lS)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}var dS;exports.BurnErrorType=void 0,(dS=exports.BurnErrorType||(exports.BurnErrorType={})).TOKEN_NOT_FOUND="TOKEN_NOT_FOUND",dS.INVALID_AMOUNT="INVALID_AMOUNT",dS.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",dS.SIGNATURE_FAILED="SIGNATURE_FAILED",dS.NETWORK_ERROR="NETWORK_ERROR",dS.WALLET_REQUIRED="WALLET_REQUIRED",dS.VALIDATION_ERROR="VALIDATION_ERROR";class hS extends Error{constructor(e,t,n){super(e),this.type=t,this.details=n,this.name="BurnError"}}const gS={validateAmount(e){const t=ki(e);try{xi(t,"amount")}catch(t){throw new eS(t.message,QA.INVALID_AMOUNT,{amount:e})}},validateUniqueKey(e){if(!Wn(e)&&Kn(e)){if(e.length>bn.MAX_LENGTH)throw new yt(`Unique key too long. Maximum length: ${bn.MAX_LENGTH}`);if(!bn.PATTERN.test(e))throw new eS('Invalid unique key format. Must start with "galaswap-operation-" or "galaconnect-operation-"',QA.INVALID_AMOUNT,{uniqueKey:e})}}},fS="gala-transfer-successful",pS="token-transfer-successful",mS="token-locked-successfully",yS="token-unlocked-successfully",bS="transfer-successful-no-id",vS=50;class wS extends rr{constructor(e,t,n,r=!1){super(e,r),this.wallet=t,this.tokenResolver=n,this.nativeSigner=t?new oA(t.privateKey):void 0}async transferGala(e){if(this.validateTransferGalaData(e),!this.wallet||!this.nativeSigner)throw new eS("Wallet required for GALA transfer operations",QA.WALLET_REQUIRED);try{const t=hr(e.recipientAddress),n=hr(this.wallet.address),r=cS.forGALA(n,t,e.amount,e.uniqueKey),s=await this.nativeSigner.signObject("TransferToken",r.toSigningPayload()),i=new cS({...r.toSigningPayload(),signedPayload:s}),{data:o,headers:a}=await this.http.postWithMeta("/api/asset/token-contract/TransferToken",i);if(null==o)throw new eS("No response from GalaChain transfer service",QA.NETWORK_ERROR);return this.extractTransferResult(o,a,"gala")}catch(t){throw this.handleTransferError(t,"GALA transfer failed",e)}}async transferToken(e){if(this.validateTransferTokenData(e),!this.wallet||!this.nativeSigner)throw new eS("Wallet required for token transfer operations",QA.WALLET_REQUIRED);try{const t=hr(e.to),n=hr(this.wallet.address);let r;if(null!==e.tokenId&&void 0!==e.tokenId)r=ME(e.tokenId),this.logger.debug("[DEBUG] Using provided tokenId:",e.tokenId),this.logger.debug("[DEBUG] Normalized Token Instance:",{collection:r.collection,category:r.category,type:r.type,instance:r.instance});else{if(null===e.tokenName||void 0===e.tokenName)throw new eS("Must provide either tokenId or tokenName for token identification",QA.TOKEN_NOT_FOUND);r=await this.resolveTokenInstance(e.tokenName)}const s=new cS({from:n,to:t,quantity:e.amount,tokenInstance:r,uniqueKey:e.uniqueKey??eA()}),i=await this.nativeSigner.signObject("TransferToken",s.toSigningPayload()),o=new cS({...s.toSigningPayload(),signedPayload:i}),{data:a,headers:c}=await this.http.postWithMeta("/api/asset/token-contract/TransferToken",o);if(null==a)throw new eS("No response from GalaChain transfer service",QA.NETWORK_ERROR);return this.extractTransferResult(a,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 eS)throw t;throw new eS(`Failed to resolve token class key for '${e}': ${at(t)}`,QA.TOKEN_NOT_FOUND,{tokenName:e})}}async burnTokens(e){if(this.validateBurnTokensData(e),!this.wallet||!this.nativeSigner)throw new hS("Wallet required for token burn operations",exports.BurnErrorType.WALLET_REQUIRED);try{const t=[];for(const n of e.tokens){let e;if(null!==n.tokenId&&void 0!==n.tokenId)e=ME(n.tokenId),this.logger.debug("[DEBUG] Using provided tokenId:",n.tokenId);else{if(null===n.tokenName||void 0===n.tokenName)throw new hS("Must provide either tokenId or tokenName for token identification",exports.BurnErrorType.TOKEN_NOT_FOUND);e=await this.resolveTokenInstance(n.tokenName)}t.push({quantity:n.amount,tokenInstanceKey:e})}const n=new aS({tokenInstances:t,uniqueKey:e.uniqueKey??eA()}),r=await this.nativeSigner.signObject("BurnTokens",n.toSigningPayload()),s=new aS({...n.toSigningPayload(),signedPayload:r}),i=await this.http.post("/api/asset/token-contract/BurnTokens",s);if(null==i)throw new hS("No response from GalaChain burn service",exports.BurnErrorType.NETWORK_ERROR);try{dt(i,"Token burn operation")}catch(e){throw new bt(at(e),500)}return this.extractBurnResult(i)}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 Kn(t.recipientAddress)&&Kn(t.amount)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)}(e))throw new yt("Invalid GALA transfer data: missing required fields");if(!pr(e.recipientAddress))throw new eS("Invalid recipient address format",QA.INVALID_RECIPIENT,{recipientAddress:e.recipientAddress});gS.validateAmount(e.amount),gS.validateUniqueKey(e.uniqueKey)}validateTransferTokenData(e){if(!function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Kn(t.to)&&Kn(t.amount)&&(void 0!==t.tokenId||Kn(t.tokenName))&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)}(e))throw new yt("Invalid token transfer data: missing required fields");if(!pr(e.to))throw new eS("Invalid recipient address format",QA.INVALID_RECIPIENT,{recipientAddress:e.to});if(!(null!==e.tokenId&&void 0!==e.tokenId||null!==e.tokenName&&void 0!==e.tokenName))throw new eS("Must provide either tokenId or tokenName for token identification",QA.TOKEN_NOT_FOUND);if(null!==e.tokenName&&void 0!==e.tokenName)try{Xn(e.tokenName,"tokenName")}catch{throw new eS("Invalid token name format",QA.TOKEN_NOT_FOUND,{tokenName:e.tokenName})}gS.validateAmount(e.amount),gS.validateUniqueKey(e.uniqueKey)}validateBurnTokensData(e){if(!uS(e))throw new hS("Invalid burn data: missing required fields",exports.BurnErrorType.VALIDATION_ERROR);if(e.tokens.length>vS)throw new hS(`Batch size exceeds maximum limit of ${vS} tokens per burn operation`,exports.BurnErrorType.VALIDATION_ERROR);for(const t of e.tokens){if(!(null!==t.tokenId&&void 0!==t.tokenId||null!==t.tokenName&&void 0!==t.tokenName))throw new hS("Must provide either tokenId or tokenName for token identification",exports.BurnErrorType.TOKEN_NOT_FOUND);const e=ki(t.amount);try{_i(e)}catch{throw new hS("Burn amount must be a positive number",exports.BurnErrorType.INVALID_AMOUNT,{amount:t.amount})}}}async resolveTokenInstance(e){try{return await nS(e,this.tokenResolver,this.logger,`[DEBUG] Token resolution for '${e}' (launchpad):`)}catch(t){if(t instanceof eS)throw t;throw new eS(`Failed to resolve token '${e}': ${at(t)}`,QA.TOKEN_NOT_FOUND,{tokenName:e})}}extractTransferResult(e,t,n){const r=this.readHeaderValue(t,"x-transaction-id"),s=this.readBlockNumberHeader(t),i=null!=e&&"object"==typeof e&&"Status"in e;i&&dt(e,"Extract transaction ID");const o=i&&"Data"in e;if(void 0!==r&&r.length>0)return{transactionId:r,...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(o){const t=e;if(Array.isArray(t.Data)){for(const e of t.Data)if(null!=e&&"object"==typeof e){const t=e;for(const e of["transactionId","txnId","TxnId","id","txId"]){const n=t[e];if("string"==typeof n&&n.length>0)return{transactionId:n,...void 0!==s?{blockNumber:s}:{}}}}let e=bS;if(t.Data.length>0)switch(n){case"gala":e=fS;break;case"token":e=pS;break;case"lock":e=mS;break;case"unlock":e=yS}return{transactionId:e,...void 0!==s?{blockNumber:s}:{}}}}}throw new eS("Operation succeeded but transaction ID could not be extracted (missing x-transaction-id header and body fields)",QA.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 r=e.Data[0];if(void 0===r)return{burned:t};n=r.transactionId??r.txnId??r.TxnId??r.id??void 0}return{...void 0!==n&&{transactionId:n},burned:t}}handleTransferError(e,t,n){if(e instanceof eS)return e;if(e instanceof yt)return new eS(at(e),QA.INVALID_AMOUNT);if(ut(e)&&e.response){const t=e.response.status,r=e.response.data;if(400===t){const e=r?.message;return new eS(("string"==typeof e?e:void 0)??"Invalid transfer request",QA.INVALID_AMOUNT)}if(403===t)return new eS("Insufficient balance for transfer",QA.INSUFFICIENT_BALANCE);if(404===t){const e={};return"tokenName"in n&&(e.tokenName=n.tokenName),new eS("Token not found",QA.TOKEN_NOT_FOUND,e)}}if("object"==typeof e&&null!==e&&"code"in e&&("ECONNABORTED"===lt(e)||"ETIMEDOUT"===lt(e)))return new eS("Transfer request timed out",QA.NETWORK_ERROR);const r=""!==at(e)?at(e):t;return new eS(r,QA.NETWORK_ERROR)}handleBurnError(e,t,n){if(e instanceof hS)return e;let r=t,s=exports.BurnErrorType.NETWORK_ERROR;if(ut(e)){const n=e.response?.data;if("object"==typeof n){const e=n.Message;if("string"==typeof e&&e.length>0){r=`${t}: ${e}`;const n=e.toLowerCase();n.includes("insufficient")||n.includes("balance")?s=exports.BurnErrorType.INSUFFICIENT_BALANCE:(n.includes("not found")||n.includes("token"))&&(s=exports.BurnErrorType.TOKEN_NOT_FOUND)}}}else ot(e)&&(r=`${t}: ${at(e)}`);return new hS(r,s,tS(n))}}class ES extends rr{constructor(e,t,n,r=!1,s){super(e,r),this.balanceService=new KA(e,r),this.tokenService=new oS(e,r,s),this.lockService=new iS(e,t,n,r),this.transferService=new wS(e,t,n,r)}async fetchPoolDetails(e){this.validateFetchPoolDetailsData(e);const t=await this.http.post("/api/asset/launchpad-contract/FetchSaleDetails",e);Qi(()=>dt(t,"Failed to fetch pool details"),"Failed to fetch pool details",this.logger,e=>{throw Tt(at(e),500)});const n=t.Data.reverseBondingCurveConfiguration,r=n?.minFeePortion??"0",s=n?.maxFeePortion??"0",i=!Ni(r)||!Ni(s),o=t.Data;return o.reverseBondingCurveMinFeePortion=r,o.reverseBondingCurveMaxFeePortion=s,o.hasReverseBondingCurveFee=i,o.isGraduated="Finished"===t.Data.saleStatus,delete o.reverseBondingCurveConfiguration,t}async fetchLaunchTokenFee(){const e=await this.http.post("/api/asset/launchpad-contract/FetchLaunchpadFeeAmount",{});return Qi(()=>dt(e,"Failed to fetch launch token fee"),"Failed to fetch launch token fee",this.logger,e=>{throw Tt(at(e),500)}),e.Data.feeAmount}validateFetchPoolDetailsData(e){if(!wi(e))throw St("data","Fetch pool details data");if("string"!=typeof e.vaultAddress||""===e.vaultAddress)throw St("vaultAddress","Vault address");if(!e.vaultAddress.startsWith("service|Token$Unit$"))throw new yt("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 AS{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 SS extends Error{constructor(e,t,n){super(t),this.name="GdexStreamError",this.code=e,void 0!==n&&(this.data=n)}}class kS extends sr{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??so("prod").gdexWebSocketUrl,this.requestTimeoutMs=e.requestTimeoutMs??15e3,this.reconnectionManager=new AS({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,r={jsonrpc:"2.0",id:n,method:e};return void 0!==t&&(r.params=t),new Promise((t,s)=>{const i=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:i});try{this.socket?.send(JSON.stringify(r))}catch(e){clearTimeout(i),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 r=new this.webSocketConstructor(this.url,"gdex.jsonrpc.v1");this.socket=r,r.onopen=()=>{this.socket===r&&(n=!0,this.connectPromise=void 0,this.reconnecting||this.reconnectionManager.reset(),this.logger.info("Connected to GDEX stream"),e())},r.onmessage=e=>this.handleMessage(e.data),r.onerror=()=>{n||t(new Error(`Failed to connect to GDEX stream at ${this.url}`))},r.onclose=e=>{this.socket===r&&(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,r="string"==typeof t.error.message?t.error.message:"GDEX request failed";e.reject(new SS(n,r,t.error.data))}else e.resolve(t.result);return}if("gdex_subscription"!==t.method||!this.isRecord(t.params))return;const n=t.params.subscription,r=t.params.result;if("string"!=typeof n||!this.isRecord(r))return;const s=this.subscriptionsByServerId.get(n);if(s?.active)try{s.callback(r)}catch(e){this.logger.error("GDEX subscription callback failed",e)}}async subscribe(e,t,n){const r={channel:e,...n},s=await this.request("gdex_subscribe",r);let i;const o={subscriptionId:s.subscriptionId,unsubscribe:async()=>this.unsubscribe(i)};return i={serverId:s.subscriptionId,params:r,callback:t,handle:o,active:!0},this.activeSubscriptions.add(i),this.subscriptionsByServerId.set(i.serverId,i),o}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 SS)||-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 TS(e,t="image",n){const r=new FormData;if("undefined"!=typeof File&&e instanceof File)r.append(t,e);else{if(!Buffer.isBuffer(e))throw kt("file","a File object (browser) or Buffer (Node.js)");{const s=new Blob([e],{type:"image/png"});r.append(t,s,n)}}return r}class IS extends rr{constructor(e,t,n=!1){super(e,n,t)}async uploadImageByTokenName(e){const{tokenName:t,options:n}=e;Ui(t);const r=`${t}.png`;Oi(n.file,r,"image/png");try{const e=`${n.tokenName??t}.png`,r=TS(n.file,"image",e),s=await Gt(()=>this.http.request({method:"POST",url:`${b.UPLOAD_IMAGE}?tokenName=${encodeURIComponent(n.tokenName??t)}`,data:r,headers:this.getJwtHeaders()}),{errorContext:"Image upload failed"});return"string"==typeof s?s:""}catch(e){if(e instanceof vt)throw e;if(ot(e)&&at(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}}}function NS(e,t){if(void 0!==e){if(!Kn(e))throw Bt("tokenName","string");if(e.length>cn.MAX_LENGTH)throw new yt(`tokenName must be at most ${cn.MAX_LENGTH} characters`,"tokenName",mt.TOO_LONG)}if(void 0!==t){if(!Kn(t))throw Bt("userAddress","string");if(t.length>gn.MAX_LENGTH)throw new yt(`userAddress must be at most ${gn.MAX_LENGTH} characters`,"userAddress",mt.TOO_LONG)}}const CS={CHAT_MESSAGE:"CHAT_MESSAGE",COMMENT:"COMMENT"},_S={PAGINATION:{MAX_LIMIT:dn.MAX_LIMIT},CONTENT:{CHAT_MAX_LENGTH:fn.CHAT_MESSAGES_V1.MAX_LENGTH,COMMENT_MAX_LENGTH:fn.COMMENTS_V1.MAX_LENGTH}};function xS(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 yt("At least one config option must be provided (messagesEnabled, commentsEnabled, streamingEnabled, nextLiveStreamAt, streamLanguage, or social URLs)","options",mt.REQUIRED);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 yt("nextLiveStreamAt must be a valid ISO date string","nextLiveStreamAt",mt.INVALID_FORMAT)}}function RS(e,t){if(null==e)return[];if(Array.isArray(e))return e;const n=e[t];return Array.isArray(n)?n:[]}class BS extends rr{constructor(e,t,n=!1){super(e,n,t)}buildPoolFilters(e){return{...!Wn(e.search)&&{search:e.search},...!Wn(e.tokenName)&&{tokenName:e.tokenName},...!Wn(e.type)&&{type:e.type},...!Wn(e.hasUpcomingShows)&&{hasUpcomingShows:e.hasUpcomingShows},...!Wn(e.language)&&{language:e.language},...!Wn(e.recentlyStreamed)&&{recentlyStreamed:e.recentlyStreamed},...!Wn(e.hasRecordings)&&{hasRecordings:e.hasRecordings},...!Wn(e.streamStatus)&&{streamStatus:e.streamStatus}}}async fetchSinglePage(e){const t=Math.min(e.pageSize,20),n=e.cursor,r={pageSize:String(t)};void 0!==n&&(r.cursor=n),Wn(e.type)||(r.type=e.type),Wn(e.tokenName)||(r.tokenName=e.tokenName),Wn(e.search)||(r.search=e.search),Wn(e.hasUpcomingShows)||(r.hasUpcomingShows=e.hasUpcomingShows.toString()),Wn(e.language)||(r.language=e.language),Wn(e.recentlyStreamed)||(r.recentlyStreamed=e.recentlyStreamed.toString()),Wn(e.hasRecordings)||(r.hasRecordings=e.hasRecordings.toString()),Wn(e.streamStatus)||(r.streamStatus=e.streamStatus);const s=Ai(r),i=$t(await Ht(()=>this.http.get(b.FETCH_POOLS,s),{errorContext:"Failed to fetch pools"})),o=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}(i),a={hasNextPage:i.hasNextPage??i.pageInfo?.hasNextPage??!1},c=i.count??i.total;void 0!==c&&(a.totalCount=c);const l=i.nextCursor??i.pageInfo?.endCursor;null!=l&&(a.nextCursor=l);const u=i.prevCursor??i.pageInfo?.startCursor;null!=u&&(a.prevCursor=u);const d=i.hasPrevPage??i.pageInfo?.hasPreviousPage;return void 0!==d&&(a.hasPrevPage=d),{items:o,pageInfo:a}}async fetchPools(e){const t=e?.cursor,n=e?.pageSize??rE.DEFAULT_LIMIT;Kn(e?.tokenName)&&Ui(e.tokenName);const r=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,i={...this.buildPoolFilters({search:e?.search,tokenName:e?.tokenName,type:r,hasUpcomingShows:e?.hasUpcomingShows,language:e?.language,recentlyStreamed:e?.recentlyStreamed,hasRecordings:e?.hasRecordings,streamStatus:s}),pageSize:n,...void 0!==t&&{cursor:t}},o=await this.fetchSinglePage(i);return{items:o.items,pageInfo:o.pageInfo}}async fetchAllPools(e){const t=[];let n;const r=rE.BACKEND_MAX_PAGE_SIZE;for(;;){const s={...e,pageSize:r,...void 0!==n&&{cursor:n}},i=await this.fetchPools(s);if(t.push(...i.items),0===i.items.length)break;if(!i.pageInfo.hasNextPage)break;n=i.pageInfo.nextCursor}return{items:t,pageInfo:{hasNextPage:!1,totalCount:t.length}}}async checkPool(e){!function(e){const t=Zs(e);!t.success&&t.errors&&Li(t.errors,"options")}(e),Kn(e.tokenName)&&Ui(e.tokenName);try{const t=await this.http.post(b.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===Kn(e.symbol)){return!n.symbolAvailable}if(!0===Kn(e.tokenName)){return!n.nameAvailable}return!1}catch(e){const t=String(e),n=e,r="string"==typeof n.message?n.message:"";if(t.includes("404")||t.includes("Pool not found")||r.includes("404")||r.includes("Pool not found"))return!1;const s="number"==typeof n.statusCode?n.statusCode:null;if(404===s)return!1;if(t.includes("400")||t.includes("Missing required pool identifier")||r.includes("400")||r.includes("Missing required pool identifier"))return!1;if(400===s&&r.includes("Missing required pool identifier"))return!1;throw e}}async isTokenNameAvailable(e){try{return!await this.checkPool({tokenName:e})}catch{return!1}}async isTokenSymbolAvailable(e){try{return!await this.checkPool({symbol:e})}catch{return!1}}async fetchVolumeData(e){if(!function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return pi(t,"tokenName")&&yi(t,"from")&&yi(t,"to")&&yi(t,"resolution")}(e))throw new yt("Invalid options provided. Expected { tokenName: string, from?: number, to?: number, resolution?: number }","options","INVALID_OPTIONS");const{tokenName:t,from:n,to:r,resolution:s}=e;if(Ui(t),null==n||null==r||null==s)throw new yt("Graph options (from, to, resolution) are required","options","MISSING_GRAPH_OPTIONS");const i={tokenName:t,from:n,to:r,resolution:s};Pi(i);const o=Ai(i);return{dataPoints:await Gt(()=>this.http.get(b.CHART,o),{errorContext:"Failed to fetch graph data"})}}async fetchTokenDistribution(e){if(""===e||null==e)throw St("tokenName","Token name");let t;Ui(e);try{t=await Ht(()=>this.http.get(`${b.GET_TOKEN_DISTRIBUTION}?tokenName=${e}`),{errorContext:"Failed to fetch token distribution"})}catch(t){if(ut(t)&&500===t.response?.status)throw Tt(`Token distribution data temporarily unavailable for ${e}. This is a backend issue - please try again later.`,500);throw t}return Ki($t(t),t.status,e=>e.toFixed())}async fetchUserHolderContext(e,t){if(""===e||null==e)throw St("tokenName","Token name");if(""===t||null==t)throw St("userAddress","User address");return Ui(e),Gt(()=>this.http.get(`${b.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");Ui(e);try{const t=b.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&&Ui(e.tokenName);try{const t=await this.http.post(b.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(!Kn(e))throw St("tokenName","Token name");Ui(e);const t=b.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 St("tokenName","Token name");Ui(e),xS(t);const n=b.UPDATE_TOKEN_CONFIG.replace(":tokenName",e.toLowerCase().trim()),r={};void 0!==t.messagesEnabled&&(r.messagesEnabled=t.messagesEnabled),void 0!==t.commentsEnabled&&(r.commentsEnabled=t.commentsEnabled),void 0!==t.streamingEnabled&&(r.streamingEnabled=t.streamingEnabled),void 0!==t.nextLiveStreamAt&&(r.nextLiveStreamAt=t.nextLiveStreamAt),void 0!==t.streamLanguage&&(r.streamLanguage=t.streamLanguage),void 0!==t.websiteUrl&&(r.websiteUrl=t.websiteUrl),void 0!==t.telegramUrl&&(r.telegramUrl=t.telegramUrl),void 0!==t.twitterUrl&&(r.twitterUrl=t.twitterUrl),void 0!==t.instagramUrl&&(r.instagramUrl=t.instagramUrl),void 0!==t.facebookUrl&&(r.facebookUrl=t.facebookUrl),void 0!==t.redditUrl&&(r.redditUrl=t.redditUrl),void 0!==t.tiktokUrl&&(r.tiktokUrl=t.tiktokUrl),await this.http.patch(n,r,this.getJwtHeaders())}async getTokenConfig(e){if(!Kn(e))throw St("tokenName","Token name");Ui(e);const t=b.UPDATE_TOKEN_CONFIG.replace(":tokenName",e.toLowerCase().trim()),n=$t(await this.http.get(t));if(void 0===n)throw new Error(`Invalid response: missing token config data for "${e}"`);return n}}const DS={PAGINATION:dn,TOKEN_NAME:cn,USER_ADDRESS:gn};function OS(e){if(void 0!==e.tokenName){if(!Kn(e.tokenName))throw Bt("tokenName","a non-empty string",typeof e.tokenName);if(e.tokenName.length>DS.TOKEN_NAME.MAX_LENGTH)throw Rt("tokenName",DS.TOKEN_NAME.MAX_LENGTH,e.tokenName.length)}if(void 0!==e.userAddress){if(!Kn(e.userAddress))throw Bt("userAddress","a non-empty string",typeof e.userAddress);if(e.userAddress.length>DS.USER_ADDRESS.MAX_LENGTH)throw Rt("userAddress",DS.USER_ADDRESS.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 Rt("search",256,e.search.length)}if(Hn(0,void 0,DS.PAGINATION.MAX_LIMIT,e.pageSize),void 0!==e.txnType&&"BUY"!==e.txnType&&"SELL"!==e.txnType)throw kt("txnType",'"BUY" or "SELL"');if(void 0!==e.startDate){if(!Kn(e.startDate))throw Bt("startDate","a non-empty string",typeof e.startDate);if(isNaN(Date.parse(e.startDate)))throw kt("startDate","a valid ISO 8601 date")}if(void 0!==e.endDate){if(!Kn(e.endDate))throw Bt("endDate","a non-empty string",typeof e.endDate);if(isNaN(Date.parse(e.endDate)))throw kt("endDate","a valid ISO 8601 date")}if(void 0!==e.minAmount)try{On(e.minAmount,0,Number.MAX_SAFE_INTEGER,"minAmount")}catch{throw kt("minAmount","a non-negative number")}if(void 0!==e.maxAmount)try{On(e.maxAmount,0,Number.MAX_SAFE_INTEGER,"maxAmount")}catch{throw kt("maxAmount","a non-negative number")}void 0!==e.minAmount&&void 0!==e.maxAmount&&function(e,t,n="range"){const r="number"==typeof e?e:Number(e),s="number"==typeof t?t:Number(t);if(isNaN(r)||isNaN(s))throw Bt(n,"numeric values",void 0,n);if(r>s)throw new yt(`Minimum value (${r}) must be less than or equal to maximum value (${s}) for ${n}`,n,mt.INVALID_RANGE)}(e.minAmount,e.maxAmount,"amountRange")}class MS extends rr{constructor(e,t=!1){super(e,t)}async fetchTrades(e){if(!function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return pi(t,"tokenName")&&(void 0===t.tradeType||"buy"===t.tradeType||"sell"===t.tradeType)&&mi(t,"userAddress")&&yi(t,"offset")&&yi(t,"pageSize")&&yi(t,"page")&&yi(t,"limit")}(e))throw new yt("Invalid options provided. Expected { tokenName: string, tradeType?: string, userAddress?: string, cursor?: string, pageSize?: number, startDate?: Date, endDate?: Date, sortOrder?: string }","options","INVALID_OPTIONS");const{tokenName:t,cursor:n,pageSize:r=rE.DEFAULT_LIMIT}=e;if(!Kn(t))throw St("tokenName","Token name");const s={pageSize:String(Math.min(r,un))};void 0!==n&&(s.cursor=n);const i={...s};i.tokenName=t;const o=await this.http.get(b.GET_TRADES,i);if(null==o)throw new yt("No response from trade service","response","NO_RESPONSE");const a=$t(o),c=RS(a,"trades"),l=a?.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=Vt(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?sE(e.pageSize,1,DS.PAGINATION.MAX_LIMIT):DS.PAGINATION.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){OS(e);const t=this.buildTradesQueryParams(e);return Gt(()=>this.http.get(Pe,t),{errorContext:"Failed to fetch trades"})}}function LS(e){return!!Kn(e)&&hn.PATTERN.test(e)}function US(e,t,n=1){if(null==e||""===e)return null;if("string"!=typeof e)return null;const r=e.trim();return r.length<n?null:r}function PS(e){if(""===e||"string"!=typeof e)return!1;const t=e.startsWith("0x")?e.slice(2):e;return/^[0-9a-fA-F]{40}$/.test(t)}function FS(e){return e.startsWith("0x")?e.slice(2):e}qn({BOTH:"both",HELD:"held",CREATED:"created"});class $S extends rr{constructor(e,t,n=!1){super(e,n,t)}async fetchProfile(e){const t=e??this.http.getAddress();if(""===t||null==t||!LS(t))throw kt("address","eth|[40-hex-chars] or client|[identifier]","Address");const n=null==e,r=n?b.GET_CURRENT_USER:b.GET_PROFILE.replace(":address",t),s=await this.http.get(r,void 0,n?this.getJwtHeaders():void 0);if(null==s)throw new yt("No response from user service","response","NO_RESPONSE");return s}async updateProfile(e){this.validateUpdateProfileData(e);let t=e.profileImage;if(!Kn(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(b.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 yt("Wallet address not available - wallet not configured","address","NO_WALLET");try{const n=`profile-image-${t}.png`,r=TS(e.file,"image",n),s=await Gt(()=>this.http.request({method:"POST",url:`${b.UPLOAD_IMAGE}?tokenName=${encodeURIComponent(t)}`,data:r,headers:this.getJwtHeaders()}),{errorContext:"Image upload failed"});return"string"==typeof s?s:""}catch(e){if(e instanceof yt||e instanceof vt)throw e;throw new yt(`Profile image upload failed: ${at(e)}`,"file","UPLOAD_FAILED")}}async fetchTokenList(e){if(void 0!==e.status&&"created"!==e.type)throw new yt("status filters only apply when type=created","status","INVALID_FILTER");const t=e.tokenName,n={...e},r="created"===e.type;r&&(delete n.tokenName,void 0!==t&&void 0===n.search&&(n.search=t));const s=await this.buildFetchRequest(b.GET_TOKEN_LIST,n,{includeType:!0,requestType:e.type??"both",responseKey:r?"launches":"token",errorMessage:"Failed to fetch token list"});return r&&void 0!==t?{...s,tokens:s.tokens.filter(e=>e.tokenName===t||e.name===t)}:s}async fetchTokensHeld(e){if(void 0!==e.type&&"held"!==e.type)throw new yt("fetchTokensHeld only supports type=held","type","INVALID_TYPE");if(void 0!==e.status)throw new yt("status filters only apply when type=created","status","INVALID_FILTER");return this.buildFetchRequest(b.GET_TOKENS_HELD,e,{includeType:!0,requestType:"held",responseKey:"token",errorMessage:"Failed to fetch tokens held"})}async fetchTokensCreated(e){const{cursor:t,pageSize:n,search:r,tokenName:s,status:i}=e??{};if(void 0!==e?.type&&"created"!==e.type)throw new yt("fetchTokensCreated only supports type=created","type","INVALID_TYPE");const o=e?.address??this.http.getAddress();if(null==o||""===o)throw new yt("Wallet address not available - wallet not configured","address","NO_WALLET");const a={type:"created",address:o,pageSize:n??rE.DEFAULT_LIMIT};return void 0!==t&&(a.cursor=t),void 0!==r&&(a.search=r),void 0!==s&&void 0===r&&(a.search=s),void 0!==s&&(a.tokenName=s),void 0!==i&&(a.status=i),this.fetchTokenList(a)}async getManagedTokens(e={}){const t=aE({pageSize:e.pageSize??rE.DEFAULT_LIMIT,...void 0!==e.cursor&&{cursor:e.cursor}},un);return Gt(()=>this.http.get(b.GET_MANAGED_TOKENS,t,this.getJwtHeaders()),{errorContext:"Failed to fetch managed tokens"})}async buildFetchRequest(e,t,n){this.validateGetTokenListOptions(t);const r=aE({pageSize:t.pageSize??rE.DEFAULT_LIMIT,...void 0!==t.cursor&&{cursor:t.cursor}},un);cE(r,t,["address","search","tokenName","status"]),n.includeType&&!e.includes("?type=")&&(r.type=n.requestType);let s=e;const i=t.address??this.http.getAddress();if(e.includes(":address")){if(0===i.length)throw St("address","User address");s=e.replace(":address",i),delete r.address}const o=$t(await Ht(()=>this.http.get(s,r),{errorContext:n.errorMessage})),a=RS(o,n.responseKey).map(e=>{const t="string"==typeof e.tokenName?e.tokenName:"",r="string"==typeof e.name?e.name:t,s="string"==typeof e.createdAt?e.createdAt:"",o=e.metadata,a={...e};return delete a.metadata,{...a,id:"string"==typeof e.id?e.id:t,name:r,symbol:"string"==typeof e.symbol?e.symbol:"",type:n.requestType,address:i,balance:"string"==typeof e.balance?e.balance:"string"==typeof e.quantity?e.quantity:"0",decimals:"number"==typeof e.decimals?e.decimals:0,...null!==o&&"object"==typeof o?{metadata:o}:{},createdAt:s,updatedAt:"string"==typeof e.updatedAt?e.updatedAt:s}}),c={hasNextPage:o.hasNextPage??!1},l=o.pageInfo,u=o.count??o.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!==u&&(c.totalCount=u),void 0!==o.nextCursor&&(c.nextCursor=o.nextCursor),void 0!==o.prevCursor&&(c.prevCursor=o.prevCursor),void 0!==o.hasPrevPage&&(c.hasPrevPage=o.hasPrevPage);const d={tokens:a,pageInfo:c};return void 0!==u&&(d.total=u),d}validateGetTokenListOptions(e){const t=e.pageSize??rE.DEFAULT_LIMIT;if(t<1||t>un)throw new yt(`pageSize must be between 1 and ${un}`,"pageSize","OUT_OF_RANGE");if(void 0!==e.address&&!LS(e.address))throw kt("address","eth|[40-hex-chars] or client|[identifier]","Address");const n=US(e.search);if(null!==n&&!(Kn(r=n)&&r.length>=An&&r.length<=Sn))throw _t("search",An,Sn,n.length,"Search query");var r;const s=US(e.tokenName);if(null!==s&&!(Kn(i=s)&&i.length>=cn.MIN_LENGTH&&i.length<=cn.MAX_LENGTH))throw _t("tokenName",cn.MIN_LENGTH,cn.MAX_LENGTH,s.length,"Token name");var i}validateUpdateProfileData(e){if(!LS(e.address))throw kt("address","eth|[40-hex-chars] or client|[identifier]","Address");if(t=e.fullName,!(Kn(t)&&t.length>=kn.FULL_NAME.MIN_LENGTH&&t.length<=kn.FULL_NAME.MAX_LENGTH&&kn.FULL_NAME.ALPHABETS_ONLY_PATTERN.test(t)))throw _t("fullName",kn.FULL_NAME.MIN_LENGTH,kn.FULL_NAME.MAX_LENGTH,e.fullName.length,"Full name");var t}validateUploadProfileImageOptions(e){if(void 0!==e.address&&!LS(e.address))throw kt("address","eth|[40-hex-chars] or client|[identifier]","Address")}}class KS{constructor(e,t,n=!1){this.http=e,this.poolService=new BS(e,t,n),this.tradeService=new MS(e,n),this.userService=new $S(e,t,n),this.imageService=new IS(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 Ui(e)}async fetchToken(e){return this.poolService.fetchToken(e)}async validateToken(e){return this.poolService.validateToken(e)}async fetchTokenStats(e){return this.poolService.fetchTokenStats(e)}async updateTokenConfig(e,t){return this.poolService.updateTokenConfig(e,t)}async getTokenConfig(e){return this.poolService.getTokenConfig(e)}}class GS extends uE{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}validateContent(e,t){if(!Kn(e))throw St("content","Message content");if(0===e.trim().length)throw St("content","Message content");Mn(e,t===CS.CHAT_MESSAGE?fn.CHAT_MESSAGES_V1.MAX_LENGTH:fn.COMMENTS_V1.MAX_LENGTH,"content")}validateMessageId(e){if(!Kn(e))throw St("id","Message ID");if(e.length<10||e.length>64)throw kt("id","valid message ID format","Message ID")}validateMessageType(e){if(e!==CS.CHAT_MESSAGE&&e!==CS.COMMENT)throw new yt(`type must be one of: ${Object.values(CS).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,an);const r={};void 0!==e.cursor&&(r.cursor=e.cursor),r.pageSize=e.pageSize??rE.DEFAULT_LIMIT;const s=aE(r,dn.MAX_LIMIT),i={};void 0!==s.pageSize&&(i.pageSize=s.pageSize),void 0!==s.cursor&&(i.cursor=s.cursor),t&&(i.type=e.type.toUpperCase()),n&&(i.tokenName=Vt(e.tokenName)),void 0!==e.userAddress&&""!==e.userAddress&&(i.userAddress=e.userAddress),void 0!==e.search&&""!==e.search&&(i.search=e.search);const o=await this.http.get(Fe.GET_MESSAGES,i),a=this.extractData(o);return{messages:a.messages,pageInfo:a.pageInfo}}async createMessage(e){this.validateMessageType(e.type),this.validateTokenName(e.tokenName,an),this.validateContent(e.content,e.type);const t={type:e.type,tokenName:Vt(e.tokenName),content:e.content.trim()},n=await this.http.post(Fe.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(Fe.UPDATE_MESSAGE,e),r={content:t.content.trim()},s=await this.http.put(n,r,this.getJwtHeaders());return{message:this.extractData(s)}}async deleteMessage(e){this.validateMessageId(e);const t=this.buildEndpointWithId(Fe.DELETE_MESSAGE,e);return await this.http.delete(t,void 0,this.getDualAuthHeaders()),{success:!0}}async getPinnedMessage(e){this.validateTokenName(e,an);const t=await this.http.get(Fe.GET_PINNED,{tokenName:Vt(e)});return{message:this.extractData(t)}}async pinMessage(e){this.validateMessageId(e);const t=Fe.PIN_MESSAGE.replace(":id",e);return await this.http.post(t,{},this.getDualAuthHeaders()),{success:!0}}async unpinMessage(e){this.validateMessageId(e);const t=Fe.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(Fe.GET_MESSAGE_STATS,void 0,this.getDualAuthHeaders());return this.extractData(e)}}const WS={MODERATOR:"MODERATOR",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MANAGER:"MANAGER"},HS=zn(WS),qS={TOKEN:"TOKEN",ALL_OWNER_TOKENS:"ALL_OWNER_TOKENS"},zS=zn(qS),VS={PENDING:"PENDING",CLAIMED:"CLAIMED",REVOKED:"REVOKED",EXPIRED:"EXPIRED"},jS=zn(VS);function XS(e){return HS.includes(e)}function YS(e){return jS.includes(e)}function JS(e){return vn.PATTERN.test(e)}const QS=Yn([{field:"id",type:"number"},{field:"inviteScope",type:"string"},{field:"tokenName",type:"string",nullable:!0},{field:"role",type:"string"},{field:"inviteCode",type:"string"},{field:"inviteUrl",type:"string"},{field:"status",type:"string"},{field:"createdAt",type:"string"}]),ZS=Yn([{field:"tokenName",type:"string"},{field:"tokenSymbol",type:"string"},{field:"role",type:"string"},{field:"inviteScope",type:"string"},{field:"creatorAddress",type:"string"},{field:"claimedAt",type:"string"}]),ek=Yn([{field:"inviteScope",type:"string"},{field:"tokenName",type:"string",nullable:!0},{field:"tokenSymbol",type:"string",nullable:!0},{field:"role",type:"string"},{field:"status",type:"string"},{field:"invitedBy",type:"string"}]);function tk(e){return zS.includes(e)}class nk extends uE{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}validateRole(e){if(!Kn(e))throw St("role","Role");if(!XS(e))throw kt("role",`one of: ${HS.join(", ")}`,"Role")}validateInviteCodeFormat(e){if(!Kn(e))throw St("inviteCode","Invite code");if(!JS(e))throw kt("inviteCode","valid invite code format","Invite code")}validateInviteScope(e){if(void 0!==e&&!tk(e))throw new yt(`Invalid invite scope. Must be one of: ${zS.join(", ")}`,"inviteScope","INVALID_VALUE")}async createInvite(e){this.validateInviteScope(e.inviteScope);const t=e.inviteScope??qS.TOKEN;if(t===qS.TOKEN){if(void 0===e.tokenName||""===e.tokenName)throw new yt("Token name is required for TOKEN scope invites","tokenName","REQUIRED");this.validateTokenName(e.tokenName,on)}else if(t===qS.ALL_OWNER_TOKENS&&e.tokenName)throw new yt("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",fn.DESCRIPTION.MAX_LENGTH),this.validateOptionalDate(e.expiresAt,"expiresAt","Expiration date");const n=te,r={inviteScope:t,role:e.role};t===qS.TOKEN&&null!==e.tokenName&&void 0!==e.tokenName&&""!==e.tokenName&&(r.tokenName=Vt(e.tokenName)),void 0!==e.description&&(r.description=e.description),void 0!==e.expiresAt&&(r.expiresAt=e.expiresAt);const s=await this.http.post(n,r,this.getMultiAuthHeaders());return{invite:this.extractData(s)}}async listInvites(e){void 0!==e.tokenName&&""!==e.tokenName&&this.validateTokenName(e.tokenName,on),this.validateStatusFilter(e.status,VS);const t=se,n={...this.buildPaginationParams(e,dn.MAX_LIMIT)};void 0!==e.tokenName&&""!==e.tokenName&&(n.tokenName=Vt(e.tokenName)),void 0!==e.status&&(n.status=e.status);const r=await this.http.get(t,n,this.getMultiAuthHeaders()),s=this.extractData(r);return{items:s.invites,pageInfo:s.pageInfo}}async revokeInvite(e){this.validatePositiveInteger(e,"inviteId","Invite ID");const t=this.buildEndpoint(ie,{id:String(e)});Ft(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(oe,{id:String(e.inviteId)}),n={role:e.role},r=await this.http.patch(t,n,this.getMultiAuthHeaders());return{invite:this.extractData(r)}}async updateInvite(e){if(this.validatePositiveInteger(e.inviteId,"inviteId","Invite ID"),void 0===e.role&&(void 0===e.description||""===e.description))throw new yt("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",fn.DESCRIPTION.MAX_LENGTH);const t=this.buildEndpoint(ae,{id:String(e.inviteId)}),n={};void 0!==e.role&&(n.role=e.role),void 0!==e.description&&(n.description=e.description);const r=await this.http.patch(t,n,this.getMultiAuthHeaders());return{invite:this.extractData(r)}}async claimInvite(e){this.validateInviteCodeFormat(e.inviteCode);const t=ne,n={inviteCode:e.inviteCode},r=await this.http.post(t,n,this.getMultiAuthHeaders()),s=this.extractData(r);return"tokenName"in s&&void 0!==s.tokenName?{token:s}:{blanketAccess:s}}async getModeratedTokens(e){const t=re,n=this.buildPaginationParams(e??{},dn.MAX_LIMIT),r=await this.http.get(t,n,this.getMultiAuthHeaders()),s=this.extractData(r);return{items:s.tokens,pageInfo:s.pageInfo}}async getInviteByCode(e){this.validateInviteCodeFormat(e);const t=this.buildEndpoint(ce,{code:e}),n=await this.http.get(t,{});return this.extractData(n)}}const rk={COLLECTION_CLAIM_FEE:"10000",TOKEN_CLASS_CREATE_FEE:"1000",DESCRIPTIONS:{COLLECTION_CLAIM:"10,000 GALA to claim a collection name",TOKEN_CLASS_CREATE:"1,000 GALA to create a token class",MINT:"Dynamic fee estimated via DryRun endpoint"}};function sk(e){return`${e}-${Date.now()}-${Math.random().toString(36).substring(2,11)}`}function ik(){return Date.now()+6e4}function ok(e){return""!==e&&"string"==typeof e&&/^[a-zA-Z0-9]{3,50}$/.test(e)}function ak(e){try{return Math.floor(parseFloat(String(e))??0).toString()}catch{return"0"}}function ck(e){return""!==e&&"string"==typeof e&&/^eth\|[0-9a-fA-F]{40}$/.test(e)}class lk extends rr{constructor(e){super(e)}getCollectionClaimFee(){return rk.COLLECTION_CLAIM_FEE}getTokenClassCreateFee(){return rk.TOKEN_CLASS_CREATE_FEE}async estimateMintFee(e){try{if(this.logger.debug("Estimating mint fee",e),0===e.collection.length||0===e.type.length||0===e.category.length||0===e.quantity.length)throw new Error("Missing required parameters for mint fee estimation");if(!ck(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=rk.COLLECTION_CLAIM_FEE;n.collectionClaim=e,t=String(BigInt(t)+BigInt(e))}if((e.createTokenClasses??0)>0){const r=rk.TOKEN_CLASS_CREATE_FEE,s=String(BigInt(r)*BigInt(e.createTokenClasses));n.tokenClassCreate=r,n.tokenClassCount=e.createTokenClasses,t=String(BigInt(t)+BigInt(s))}return{totalFee:t,breakdown:n}}async claimCollection(e){try{if(this.logger.debug("Claiming NFT collection",e.collectionName),!ok(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:ik(),uniqueKey:sk("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),!ck(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),!ok(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(!ok(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?ak(e.maxSupply):void 0,maxCapacity:void 0!==e.maxCapacity?ak(e.maxCapacity):void 0,additionalKey:e.additionalKey,expiresAt:ik(),uniqueKey:sk("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),!ok(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(!ck(e.ownerAddress))throw new Error(`Invalid owner address: ${e.ownerAddress}`);const n=this.estimateMintFee({collection:e.collection,type:e.type,category:e.category,quantity:e.quantity,ownerAddress:e.ownerAddress});this.logger.debug("Estimated mint fee:",n);const r={collection:e.collection,type:e.type,category:e.category,quantity:e.quantity,owner:e.ownerAddress,additionalKey:e.additionalKey??"none",expiresAt:ik(),uniqueKey:sk("mint")};this.logger.debug("Built mint DTO",r);const s=`mint-${Date.now()}`,i=Array.from({length:t},(e,t)=>t+1);return{transactionId:s,mintedQuantity:e.quantity,owner:e.ownerAddress,tokenInstances:i,tokenClass:{collection:e.collection,type:e.type,category:e.category}}}catch(e){throw this.logger.error("Failed to mint NFT",e),e}}async fetchNftBalances(e,t){try{if(this.logger.debug("Fetching NFT balances for",{ownerAddress:e,collectionFilter:t}),!ck(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 uk extends rr{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(Ze,{token:e.token,platform:e.platform,...void 0!==e.deviceId?{deviceId:e.deviceId}:{}},t),r=this.extractData(n);return this.logger.debug("Push token registered",{registered:r.registered}),r}async unregisterPushToken(e){this.logger.debug("Unregistering push token");const t=this.getJwtHeaders(),n=await this.http.request({method:"DELETE",url:et,data:{token:e},headers:t}),r=this.extractData(n);return this.logger.debug("Push token unregistered",{unregistered:r.unregistered}),r}async getPreferences(){this.logger.debug("Fetching notification preferences");const e=this.getJwtHeaders(),t=await this.http.get(tt,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(nt,e,t),r=this.extractData(n);return this.logger.debug("Updated notification preferences",{tradesEnabled:r.tradesEnabled,streamsEnabled:r.streamsEnabled}),{preferences:r}}}class dk extends rr{constructor(e,t=!1){super(e,t)}async getHomeOEmbedJson(e={}){this.logger.debug("Fetching home oEmbed (JSON)");const t=await this.http.get(b.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(b.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 yt("tokenName is required","tokenName","REQUIRED_FIELD");this.logger.debug("Fetching pool oEmbed (JSON)",{tokenName:t});const n=b.OEMBED_BUY_SELL.replace(":tokenName",t.toLowerCase().trim()),r=await this.http.get(n,{format:"json"});return this.logger.debug("Fetched pool oEmbed (JSON)",{tokenName:t,title:r.title}),{oembed:r}}async getPoolOEmbedHtml(e){const{tokenName:t}=e;if(null==t||"string"!=typeof t||""===t.trim())throw new yt("tokenName is required","tokenName","REQUIRED_FIELD");this.logger.debug("Fetching pool oEmbed (HTML)",{tokenName:t});const n=b.OEMBED_BUY_SELL.replace(":tokenName",t.toLowerCase().trim()),r=await this.http.get(n,{},{responseType:"text"});return this.logger.debug("Fetched pool oEmbed (HTML)",{tokenName:t}),{html:r}}async getProfileOEmbedJson(e){const{address:t}=e;if(null==t||"string"!=typeof t||""===t.trim())throw new yt("address is required","address","REQUIRED_FIELD");this.logger.debug("Fetching profile oEmbed (JSON)",{address:t});const n=b.OEMBED_PROFILE.replace(":address",encodeURIComponent(t.toLowerCase().trim())),r=await this.http.get(n,{format:"json"});return this.logger.debug("Fetched profile oEmbed (JSON)",{address:t,title:r.title}),{oembed:r}}async getProfileOEmbedHtml(e){const{address:t}=e;if(null==t||"string"!=typeof t||""===t.trim())throw new yt("address is required","address","REQUIRED_FIELD");this.logger.debug("Fetching profile oEmbed (HTML)",{address:t});const n=b.OEMBED_PROFILE.replace(":address",encodeURIComponent(t.toLowerCase().trim())),r=await this.http.get(n,{},{responseType:"text"});return this.logger.debug("Fetched profile oEmbed (HTML)",{address:t}),{html:r}}}function hk(e){if(!Kn(e))throw St("address","Address")}const gk={PENDING:"PENDING",CLAIMED:"CLAIMED",REVOKED:"REVOKED",EXPIRED:"EXPIRED"},fk={ACTIVE:"ACTIVE",REVOKED:"REVOKED"},pk=qn(gk),mk=qn(fk);function yk(e){try{Zn(e.description,"description",255)}catch(e){if(e instanceof yt){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(!Kn(e.expiresAt))throw new Error("expiresAt must be a non-empty string");try{er(e.expiresAt,"expiresAt")}catch(e){if(e instanceof yt)throw new Error("expiresAt must be a valid ISO 8601 date string");throw e}if(rn(e.expiresAt)){if(nn(e.expiresAt)<=new Date)throw new Error("expiresAt must be in the future")}}}function bk(e){if(void 0!==e.status&&!pk(e.status))throw Ot("status",e.status,Object.values(gk),"status");Hn(0,void 0,50,e.pageSize,e.cursor)}function vk(e){if(void 0!==e.status&&!mk(e.status))throw Ot("status",e.status,Object.values(fk),"status");Hn(0,void 0,50,e.pageSize,e.cursor)}function wk(e){if(!Kn(e))throw new Error("Invite code must be a non-empty string");Mn(e,100,"code")}function Ek(e){if(!Kn(e))throw new Error("Address must be a non-empty string");try{mr(e,"address")}catch{throw new Error("Invalid wallet address format. Must be eth|..., 0x..., or client|... format")}}function Ak(e){try{Ln(e,"id")}catch(e){if(e instanceof yt)throw new Error("Invite ID must be a positive integer");throw e}}function Sk(e){if(null==e||"object"!=typeof e)throw new yt("Options are required");if(void 0!==e.search){if("string"!=typeof e.search)throw new yt("Search must be a string");if(0===e.search.length)throw new yt("Search query cannot be empty string")}if(void 0!==e.sortBy){if("string"!=typeof e.sortBy)throw new yt("Sort field must be a string");if(0===e.sortBy.length)throw new yt("Sort field cannot be empty string")}if(void 0!==e.sortOrder&&"asc"!==e.sortOrder&&"desc"!==e.sortOrder)throw new yt('Sort order must be "asc" or "desc"')}function kk(e){if(null==e||"object"!=typeof e)throw new yt("Options are required");if(!Kn(e.userAddress))throw new yt("userAddress is required and must be a non-empty string");try{mr(e.userAddress,"userAddress")}catch{throw new yt("Invalid wallet address format. Must be eth|..., 0x..., or client|... format")}if(void 0!==e.description){if("string"!=typeof e.description)throw new yt("description must be a string");if(e.description.length>255)throw new yt("description must be at most 255 characters")}}class Tk extends uE{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}validateInviteCodeFormat(e){if(!Kn(e))throw St("inviteCode","Invite code");wk(e)}validateWalletAddressFormat(e){if(!Kn(e))throw St("address","Address");Ek(e)}async createInvite(e={}){yk(e),this.validateOptionalString(e.description,"description","Description",fn.DESCRIPTION.MAX_LENGTH),this.validateOptionalDate(e.expiresAt,"expiresAt","Expiration date");const t=ue,n={};void 0!==e.description&&(n.description=e.description),void 0!==e.expiresAt&&(n.expiresAt=e.expiresAt);const r=await this.http.post(t,n,this.getDualAuthHeaders());return{invite:this.extractData(r)}}async listInvites(e={}){bk(e),this.validateStatusFilter(e.status,gk);const t=de,n={...this.buildPaginationParams(e,dn.MAX_LIMIT)};void 0!==e.status&&(n.status=e.status);const r=await this.http.get(t,n,this.getDualAuthHeaders()),s=this.extractData(r);return{items:s.invites,pageInfo:s.pageInfo}}async getInviteByCode(e){this.validateInviteCodeFormat(e);const t=this.buildEndpoint(he,{code:e}),n=await this.http.get(t,{});return this.extractData(n)}async revokeInvite(e){Ak(e);const t=this.buildEndpoint(fe,{id:String(e)});Ft(await this.http.delete(t,this.getDualAuthHeaders()),"Failed to revoke invite")}async claimInvite(e){this.validateInviteCodeFormat(e);const t=ge,n={inviteCode:e},r=await this.http.post(t,n,this.getJwtHeaders());return{invite:this.extractData(r)}}async listOverseers(e={}){vk(e),this.validateStatusFilter(e.status,fk);const t=pe,n={...this.buildPaginationParams(e,dn.MAX_LIMIT)};void 0!==e.status&&(n.status=e.status);const r=await this.http.get(t,n,this.getDualAuthHeaders()),s=this.extractData(r);return{items:s.overseers,pageInfo:s.pageInfo}}async createOverseerDirect(e){kk(e),this.validateWalletAddressFormat(e.userAddress),this.validateOptionalString(e.description,"description","Description",fn.DESCRIPTION.MAX_LENGTH);const t=me,n={userAddress:e.userAddress};void 0!==e.description&&(n.description=e.description);const r=await this.http.post(t,n,this.getDualAuthHeaders());return{overseer:this.extractData(r)}}async revokeOverseer(e){this.validateWalletAddressFormat(e);const t=this.buildEndpoint(ye,{address:e});Ft(await this.http.delete(t,this.getDualAuthHeaders()),"Failed to revoke overseer")}async getMyStatus(){const e=be,t=await this.http.get(e,{},this.getJwtHeaders());return this.extractData(t)}async getSummary(){const e=ve,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getBanStats(){const e=we,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getTokenBanStats(){const e=Ee,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getInviteStats(){const e=Ae,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getFlagStats(){const e=Se,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getUserStats(){const e=ke,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async listOverseerUsers(e){const t=e??{};Object.keys(t).length>0&&Sk(t);const n=Te,r=this.buildPaginationParams(t,dn.MAX_LIMIT);void 0!==t.search&&""!==t.search&&(r.search=t.search),void 0!==t.sortBy&&""!==t.sortBy&&(r.sortBy=t.sortBy),void 0!==t.sortOrder&&(r.sortOrder=t.sortOrder);const s=await this.http.get(n,r,this.getDualAuthHeaders()),i=this.extractData(s);return{items:i.users,pageInfo:i.pageInfo}}async getOverseerUserSummary(e){if(!Kn(e))throw St("address","User address");Ek(e);const t=this.buildEndpoint(Ie,{address:e}),n=await this.http.get(t,{},this.getDualAuthHeaders());return this.extractData(n)}async flushCacheByAddress(e){hk(e);const t=this.buildEndpoint(Ne,{address:e}),n=await this.http.delete(t,void 0,this.getDualAuthHeaders());return this.extractData(n)}async flushCacheByToken(e){!function(e){if(!Kn(e))throw St("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 yt("Safety confirmation required: must pass confirm=true to flush all cache","confirm","CONFIRMATION_REQUIRED")}(e);const t=_e,n=await this.http.delete(t,{confirm:"true"},this.getDualAuthHeaders());return this.extractData(n)}async flushWalletAliasCache(e){if(void 0!==e){hk(e);const t=this.buildEndpoint(xe,{address:e}),n=await this.http.delete(t,void 0,this.getDualAuthHeaders());return this.extractData(n)}const t=Re,n=await this.http.delete(t,{confirm:"true"},this.getDualAuthHeaders());return this.extractData(n)}}function Ik(e){const t=[];return 0===Object.keys(e).length&&t.push("At least one field (streamingEnabled, chatEnabled, commentsEnabled, webhooksEnabled, aiModerationEnabled) must be provided"),void 0!==e.streamingEnabled&&"boolean"!=typeof e.streamingEnabled&&t.push("streamingEnabled must be a boolean"),void 0!==e.chatEnabled&&"boolean"!=typeof e.chatEnabled&&t.push("chatEnabled must be a boolean"),void 0!==e.commentsEnabled&&"boolean"!=typeof e.commentsEnabled&&t.push("commentsEnabled must be a boolean"),void 0!==e.webhooksEnabled&&"boolean"!=typeof e.webhooksEnabled&&t.push("webhooksEnabled must be a boolean"),void 0!==e.aiModerationEnabled&&"boolean"!=typeof e.aiModerationEnabled&&t.push("aiModerationEnabled must be a boolean"),t}class Nk extends rr{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),Ft(t,"Platform config operation failed",!0),e.data}async getPlatformConfig(){const e=await this.http.get(O);return this.extractData(e)}async updatePlatformConfig(e){const t=Ik(e);if(t.length>0)throw new yt(t.join("; "),"options","VALIDATION_FAILED");const n=await this.http.put(M,e,this.getJwtHeaders());return this.extractData(n)}async getAvailableRoles(){const e=await this.http.get(P);return this.extractData(e)}}class Ck extends rr{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(Ve),t=this.extractData(e);return this.logger.debug("Fetched platform stats",{totalTokens:t.totalTokens,timestamp:t.timestamp}),{stats:t}}}class _k extends rr{constructor(e,t=!1,n){super(e,t),this.tokenResolverService=n}async fetchTokenClassKeyByTokenName(e){if(""===e)throw St("tokenName","Token name");if(!this.tokenResolverService)throw It("TokenResolverService is required for token name resolution. Ensure it is passed to PriceHistoryService constructor.","tokenResolverService");try{jn(e)}catch(e){throw It(at(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=io(LE(t));return this.logger.debug(`Extracted token class key: ${n}`),n}catch(t){if(ot(t)&&at(t).includes("ConfigurationError"))throw t;throw Tt(`Failed to resolve token name '${e}': ${at(t)}`,500)}}async fetchPriceHistory(e){if(null==e)throw St("options","Fetch options");return this.logger.debug("Fetching price history from DEX Backend API with options:",e),this.validateOptions(e),await Ji(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 $E}),r=MA(io(n(t))),{from:s,to:i,sortOrder:o="DESC"}=e,a=e.timeframe??this.inferTimeframe(s,i),c={token:r,timeframe:a};this.logger.debug(`Querying price series for token ${r}, timeframe ${a}`);const l=await this.http.get(A,c);if(null==l)throw Tt("No response from price history service",500);const u=this.transformApiResponseToPriceHistory(l,e,o);return this.logger.debug(`Found ${u.snapshots.length} price snapshots, total ${u.total}`),u},"Failed to fetch price history",this.logger)}transformApiResponseToPriceHistory(e,t,n){if(!Array.isArray(e.prices))throw Tt("Invalid API response: missing price series",500);const r="string"==typeof t.tokenId?t.tokenId:t.tokenName??io(t.tokenId),s=t.from?.getTime(),i=t.to?.getTime(),o=e.prices.filter(e=>"number"==typeof e.time&&"number"==typeof e.price).filter(e=>(void 0===s||1e3*e.time>=s)&&(void 0===i||1e3*e.time<=i)).sort((e,t)=>"ASC"===n?e.time-t.time:t.time-e.time),a=Nn(t.offset,0),c=Nn(t.pageSize??t.limit,10),l=o.slice(a,a+c).map(e=>({price:String(e.price),timestamp:new Date(1e3*e.time),tokenId:r})),u=Math.max(1,Math.ceil(o.length/c)),d=Math.floor(a/c)+1;return{snapshots:l,page:d,limit:c,total:o.length,totalPages:u,hasNext:d<u,hasPrevious:d>1}}async fetchAllPriceHistory(e){if(null==e)throw St("options","Fetch options");return this.logger.debug("Fetching all price history with options:",e),Ji(async()=>{const t=await OE((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 r=e.length;return{offset:0,limit:r,total:t,totalPages:0!==r?iE(t,r):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:r}=e;if(Vn(e,"tokenName","tokenId",{description:"token identifier"}),t&&!rn(t))throw It("from must be a valid Date","from");if(void 0!==n&&!rn(n))throw It("to must be a valid Date","to");null!=r&&Pn(r,"sortOrder"),Hn(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 xk extends uE{constructor(e,t,n,r){super(e,t,n,!1,r)}async getRestrictedNames(){try{return{success:!0,data:(await this.http.get($e)).data}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}async updateRestrictedNames(e){try{if(!Kn(e.content))throw new yt("Content is required");return{success:!0,data:(await this.http.put(Ke,e)).data}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}}class Rk extends uE{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async getChatStatus(e){if(null==e||""===e)throw St("tokenName","Token name");return this.validateTokenName(e,on),Ji(async()=>{const t=this.buildEndpoint(Ge,{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 St("tokenName","Token name");return this.validateTokenName(e,on),Ji(async()=>{const t=this.buildEndpoint(He,{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 St("tokenName","Token name");return this.validateTokenName(e,on),Ji(async()=>{const t=this.buildEndpoint(We,{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??Vt(e)};return void 0!==t.status&&null!==t.status&&(n.status=t.status),n}async setSlowMode(e,t){if(null==e||""===e)throw St("tokenName","Token name");if(this.validateTokenName(e,on),"number"!=typeof t||t<0||t>600)throw new Error("slowModeSeconds must be a number between 0 and 600");return Ji(async()=>{const n=this.buildEndpoint(qe,{tokenName:e}),r=await this.http.patch(n,{slowModeSeconds:t},this.getDualAuthHeaders());return this.extractData(r)},`Failed to set slow mode for token: ${e}`,this.logger)}}class Bk extends sr{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 r of n)try{const e=r(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)}}const Dk={IDLE:"IDLE",ACTIVE:"ACTIVE",DISABLED:"DISABLED"},Ok={READY:"READY",PROCESSING:"PROCESSING",ERRORED:"ERRORED",DELETED:"DELETED"},Mk={YOUTUBE:"YOUTUBE",TWITCH:"TWITCH",FACEBOOK:"FACEBOOK",CUSTOM:"CUSTOM"},Lk=qn(Dk),Uk=qn(Ok),Pk=qn(Mk);const Fk={OWNER:"OWNER",MANAGER:"MANAGER",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MODERATOR:"MODERATOR"},$k={OWNER:"OWNER",MODERATOR:"MODERATOR"};qn(Fk),qn($k);const Kk={...Fk,OVERSEER:"OVERSEER"},Gk=qn(Kk);function Wk(e,t="tokenName"){jn(e,t,on)}function Hk(e){if(Wk(e.tokenName),!Kn(e.language))throw St("language");if(t=e.language,!Kn(t)||!/^[a-z]{2}(-[A-Z]{2})?$/.test(t))throw new yt('language must be a valid ISO 639-1 code (e.g., "en", "es", "zh-CN")',"language",mt.INVALID_FORMAT);var t}class qk extends uE{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async startStream(e){this.validateTokenName(e,on);const t=this.buildEndpoint(S,{tokenName:e}),n=await this.http.post(t,{},this.getJwtHeaders());return this.extractData(n)}async stopStream(e){this.validateTokenName(e,on);const t=this.buildEndpoint(k,{tokenName:e});await this.http.post(t,{},this.getJwtHeaders())}async disableStream(e){return this.toggleFeature(e,T,on)}async enableStream(e){return this.toggleFeature(e,I,on)}async resetStreamKey(e){this.validateTokenName(e,on);const t=this.buildEndpoint(N,{tokenName:e}),n=await this.http.post(t,{},this.getJwtHeaders());return this.extractData(n)}async getStreamCredentials(e){this.validateTokenName(e,on);const t=this.buildEndpoint($,{tokenName:e}),n=await this.http.get(t,{},this.getJwtHeaders());return this.extractData(n)}async getRecordings(e){!function(e){Wk(e.tokenName),Hn(0,void 0,En,e.pageSize)}(e);const t=this.buildEndpoint(C,{tokenName:e.tokenName}),n=this.buildPaginationParams(e,En),r=e.offset;"number"==typeof r&&(n.offset=String(r));const s=await this.http.get(t,n),i=this.extractData(s),o=e,a=i.pageSize??i.limit??e.pageSize??("number"==typeof o.limit?o.limit:20),c="number"==typeof o.offset?o.offset:0,l=Math.floor(c/a)+1;return{recordings:i.recordings,tokenName:Vt(e.tokenName),page:i.page??l,limit:a,total:i.total,hasNext:i.recordings.length===a}}async getRecordingDownload(e,t){this.validateTokenName(e,on),this.validateRequiredString(t,"assetId","Asset ID");const n=this.buildEndpoint(_,{tokenName:e,assetId:t}),r=await this.http.get(n,{},this.getJwtHeaders());return this.extractData(r)}async deleteRecording(e,t){this.validateTokenName(e,on),this.validateRequiredString(t,"assetId","Asset ID");const n=this.buildEndpoint(x,{tokenName:e,assetId:t});await this.http.delete(n,void 0,this.getJwtHeaders())}async getSimulcastTargets(e){this.validateTokenName(e,on);const t=this.buildEndpoint(R,{tokenName:e}),n=await this.http.get(t);return this.extractData(n)}async addSimulcastTarget(e){!function(e){if(Wk(e.tokenName),!Kn(e.platform))throw St("platform");if(!Pk(e.platform))throw new yt("platform must be one of: 'YOUTUBE', 'TWITCH', 'FACEBOOK', 'CUSTOM'","platform",mt.INVALID_VALUE);if(!Kn(e.rtmpUrl))throw St("rtmpUrl");if(!wn.STREAM_URL_PATTERN.test(e.rtmpUrl))throw new yt("rtmpUrl must be a valid RTMP, RTMPS, or SRT URL","rtmpUrl",mt.INVALID_FORMAT);if(!Kn(e.streamKey))throw St("streamKey");if(void 0!==e.name&&"string"!=typeof e.name)throw new yt("name must be a string","name",mt.INVALID_TYPE)}(e);const t=this.buildEndpoint(B,{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,on),this.validateRequiredString(t,"targetId","Target ID");const n=this.buildEndpoint(D,{tokenName:e,targetId:t});await this.http.delete(n,void 0,this.getJwtHeaders())}async getGlobalStreamingStatus(){const e=await this.http.get(O);return this.extractData(e)}async disableGlobalStreaming(){const e=await this.http.put(M,{},this.getAdminHeaders());return this.extractData(e)}async enableGlobalStreaming(){const e=await this.http.put(L,{},this.getAdminHeaders());return this.extractData(e)}async setNextLiveStream(e){let t;!function(e){if(Wk(e.tokenName),null!==e.nextLiveStreamAt){if(!(e.nextLiveStreamAt instanceof Date||Kn(e.nextLiveStreamAt)))throw new yt("nextLiveStreamAt must be a Date, ISO 8601 string, or null","nextLiveStreamAt",mt.INVALID_TYPE);if("string"==typeof e.nextLiveStreamAt){const t=Date.parse(e.nextLiveStreamAt);if(isNaN(t))throw new yt("nextLiveStreamAt must be a valid ISO 8601 date string","nextLiveStreamAt",mt.INVALID_FORMAT)}}}(e),t=null===e.nextLiveStreamAt?null:e.nextLiveStreamAt instanceof Date?e.nextLiveStreamAt.toISOString():e.nextLiveStreamAt;const n=`/v1/tokens/${e.tokenName.toLowerCase().trim()}`;await this.http.patch(n,{nextLiveStreamAt:t},this.getJwtHeaders())}async clearNextLiveStream(e){this.validateTokenName(e,on);const t=`/v1/tokens/${e.toLowerCase().trim()}`;await this.http.patch(t,{nextLiveStreamAt:null},this.getJwtHeaders())}async setStreamLanguage(e){Hk(e);const t=`/v1/tokens/${e.tokenName.toLowerCase().trim()}`;await this.http.patch(t,{streamLanguage:e.language},this.getJwtHeaders())}async getStreamRole(e){!function(e){Wk(e.tokenName)}(e);const t=this.buildEndpoint(U,{tokenName:e.tokenName}),n=this.jwtAuth?this.getJwtHeaders():{},r=await this.http.get(t,{},n);return this.extractData(r)}async getAvailableRoles(){const e=await this.http.get(P);return this.extractData(e)}async getTokenAccess(e){!function(e){Wk(e.tokenName)}(e);const t=await this.http.get(F,{tokenName:Vt(e.tokenName)},this.getJwtHeaders());return this.extractData(t)}async setNextLiveStreamCountdown(e,t){return this.setNextLiveStream({tokenName:e,nextLiveStreamAt:t})}}const zk={SUBSCRIBE:"subscribe_token",UNSUBSCRIBE:"unsubscribe_token",AUTHENTICATE:"authenticate",SEND_CHAT:"send_stream_chat",SEND_REACTION:"SEND_STREAM_REACTION",TYPING_START:"typing_start",TYPING_STOP:"typing_stop",STREAM_STATUS:"STREAM_STATUS",RECORDING_STATUS:"RECORDING_STATUS",RECORDINGS_COUNT_UPDATED:"RECORDINGS_COUNT_UPDATED",SIMULCAST_STATUS:"SIMULCAST_STATUS",DOWNLOAD_READY:"DOWNLOAD_READY",STREAM_COUNTDOWN_UPDATED:"STREAM_COUNTDOWN_UPDATED",STREAM_LANGUAGE_UPDATED:"STREAM_LANGUAGE_UPDATED",VIEWER_COUNT:"VIEWER_COUNT",STREAM_SUBSCRIBED:"token_subscribed",STREAM_UNSUBSCRIBED:"token_unsubscribed",STREAM_GLOBAL_STATUS:"STREAM_GLOBAL_STATUS",ENGAGEMENT_STATS_UPDATED:"ENGAGEMENT_STATS_UPDATED",CHAT_MESSAGE:"STREAM_CHAT_MESSAGE",CHAT_SENT:"STREAM_CHAT_SENT",CHAT_UPDATED:"STREAM_CHAT_UPDATED",CHAT_DELETED:"STREAM_CHAT_DELETED",CHAT_ERROR:"stream_chat_error",CHAT_STATUS:"CHAT_STATUS_CHANGED",CHAT_GLOBAL_STATUS:"STREAM_CHAT_GLOBAL_STATUS",CHAT_AUTHENTICATED:"authenticated",CHAT_AUTH_ERROR:"stream_chat_auth_error",STREAM_CONTROL_STATUS_CHANGED:"STREAM_CONTROL_STATUS_CHANGED",REACTION:"STREAM_REACTION",CONTENT_REACTION_ADDED:"CONTENT_REACTION_ADDED",CONTENT_REACTION_REMOVED:"CONTENT_REACTION_REMOVED",REACTION_ERROR:"stream_reaction_error",USER_TYPING:"USER_TYPING",CHAT_PINNED:"STREAM_CHAT_PINNED",CHAT_UNPINNED:"STREAM_CHAT_UNPINNED",COMMENT_CREATED:"COMMENT_CREATED",COMMENT_UPDATED:"COMMENT_UPDATED",COMMENT_DELETED:"COMMENT_DELETED",USER_BANNED:"USER_BANNED",USER_UNBANNED:"USER_UNBANNED",BAN_ENFORCEMENT:"BAN_ENFORCEMENT",TOKEN_BANNED:"TOKEN_BANNED",TOKEN_UNBANNED:"TOKEN_UNBANNED",CONTENT_FLAGGED:"CONTENT_FLAGGED",FLAG_RESOLVED:"FLAG_RESOLVED",MODERATOR_INVITE_CREATED:"MODERATOR_INVITE_CREATED",MODERATOR_ADDED:"MODERATOR_ADDED",MODERATOR_REMOVED:"MODERATOR_REMOVED",MODERATOR_ROLE_UPDATED:"MODERATOR_ROLE_UPDATED",OVERSEER_ADDED:"OVERSEER_ADDED",OVERSEER_REMOVED:"OVERSEER_REMOVED",TRADE_EXECUTED:"TRADE_EXECUTED",BALANCE_UPDATED:"BALANCE_UPDATED",STATS_UPDATED:"STATS_UPDATED",POOL_METADATA_UPDATED:"POOL_METADATA_UPDATED",POOL_SOCIAL_LINKS_UPDATED:"POOL_SOCIAL_LINKS_UPDATED",POOL_BADGE_ASSIGNED:"POOL_BADGE_ASSIGNED",HOLDER_COUNT_UPDATED:"HOLDER_COUNT_UPDATED",USER_PROFILE_UPDATED:"USER_PROFILE_UPDATED",API_KEY_CREATED:"API_KEY_CREATED",API_KEY_UPDATED:"API_KEY_UPDATED",API_KEY_REVOKED:"API_KEY_REVOKED",TOKEN_CONFIG_UPDATED:"TOKEN_CONFIG_UPDATED",SITE_CONFIG_CHANGED:"SITE_CONFIG_CHANGED",COMMENTS_GLOBAL_STATUS:"COMMENTS_GLOBAL_STATUS",WEBHOOKS_GLOBAL_STATUS:"WEBHOOKS_GLOBAL_STATUS",SUBSCRIBE_GLOBAL_FEED:"subscribe_global_feed",UNSUBSCRIBE_GLOBAL_FEED:"unsubscribe_global_feed",GLOBAL_FEED_SUBSCRIBED:"global_feed_subscribed",GLOBAL_FEED_UNSUBSCRIBED:"global_feed_unsubscribed"};class Vk extends sr{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 vt("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 AS({maxAttempts:this.config.reconnectAttempts,baseDelayMs:this.config.reconnectDelay}),this.isSocketIOAvailable=this.checkSocketIOAvailability()}checkSocketIOAvailability(){try{return"function"==typeof a.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:",at(e)),!1}}getRoomName(e){return`token:${Vt(e)}`}bufferEvent(e,t,n){const r=`${e}:${t}`;let s=this.eventBuffer.get(r);s||(s=[],this.eventBuffer.set(r,s)),s.length>=this.MAX_BUFFER_SIZE&&(s.shift(),this.logger.warn(`⚠️ [Stream Buffer] Event buffer overflow for ${r} - dropping oldest event. Consider processing events faster or increasing buffer size.`)),s.push(n);const i=this.eventBufferTimeouts.get(r);i&&clearTimeout(i);const o=setTimeout(()=>{this.eventBuffer.delete(r),this.eventBufferTimeouts.delete(r),this.logger.debug(`📡 [Stream Buffer] Cleaned up buffer for ${r}`)},this.BUFFER_CLEANUP_MS);this.eventBufferTimeouts.set(r,o)}processBufferedEvents(e,t){const n=Vt(e),r=[{key:`${zk.STREAM_STATUS}:${n}`,callback:t.onStreamStatus},{key:`${zk.VIEWER_COUNT}:${n}`,callback:t.onViewerCount},{key:`${zk.CHAT_MESSAGE}:${n}`,callback:t.onChatMessage},{key:`${zk.CHAT_STATUS}:${n}`,callback:t.onChatStatus},{key:`${zk.CHAT_PINNED}:${n}`,callback:t.onChatPinned},{key:`${zk.CHAT_UNPINNED}:${n}`,callback:t.onChatUnpinned},{key:`${zk.STREAM_COUNTDOWN_UPDATED}:${n}`,callback:t.onCountdownUpdated},{key:`${zk.STREAM_LANGUAGE_UPDATED}:${n}`,callback:t.onLanguageUpdated},{key:`${zk.TOKEN_BANNED}:${n}`,callback:t.onTokenBanned},{key:`${zk.TOKEN_UNBANNED}:${n}`,callback:t.onTokenUnbanned},{key:`${zk.MODERATOR_INVITE_CREATED}:${n}`,callback:t.onModeratorInviteCreated},{key:`${zk.MODERATOR_ADDED}:${n}`,callback:t.onModeratorAdded},{key:`${zk.MODERATOR_REMOVED}:${n}`,callback:t.onModeratorRemoved},{key:`${zk.MODERATOR_ROLE_UPDATED}:${n}`,callback:t.onModeratorRoleUpdated},{key:`${zk.TRADE_EXECUTED}:${n}`,callback:t.onTradeExecuted},{key:`${zk.BALANCE_UPDATED}:${n}`,callback:t.onBalanceUpdated},{key:`${zk.POOL_METADATA_UPDATED}:${n}`,callback:t.onPoolMetadataUpdated},{key:`${zk.POOL_SOCIAL_LINKS_UPDATED}:${n}`,callback:t.onPoolSocialLinksUpdated},{key:`${zk.POOL_BADGE_ASSIGNED}:${n}`,callback:t.onPoolBadgeAssigned},{key:`${zk.HOLDER_COUNT_UPDATED}:${n}`,callback:t.onHolderCountUpdated},{key:`${zk.COMMENT_CREATED}:${n}`,callback:t.onCommentCreated}];for(const{key:e,callback:t}of r){const n=this.eventBuffer.get(e);if(n&&t){this.logger.debug(`📡 [Stream Buffer] Delivering ${n.length} buffered events for ${e}`);for(const r of n)try{t(r)}catch(t){this.logger.error(`Error delivering buffered event for ${e}:`,t)}this.eventBuffer.delete(e);const r=this.eventBufferTimeouts.get(e);r&&(clearTimeout(r),this.eventBufferTimeouts.delete(e))}}}setupGlobalListeners(){this.socket&&(this.socket.on(zk.STREAM_STATUS,e=>{this.logger.debug(`📡 [Stream Status] ${e.tokenName}: ${e.status}`),this.bufferEvent(zk.STREAM_STATUS,e.tokenName,e);const t=this.roomCallbacks.get(Vt(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(zk.STREAM_SUBSCRIBED,e=>{this.logger.debug(`📡 [Subscribed] ${e.tokenName}`);const t=Vt(e.tokenName),n=this.pendingSubscriptions.get(t);n&&(clearTimeout(n.timeoutId),this.pendingSubscriptions.delete(t),n.resolve(e));const r=this.roomCallbacks.get(t);r?.onStreamSubscribed&&r.onStreamSubscribed(e)}),this.socket.on(zk.STREAM_UNSUBSCRIBED,e=>{const t=e.room.replace("token:","");this.logger.debug(`📡 [Unsubscribed] ${t}`);const n=this.roomCallbacks.get(Vt(t));n?.onStreamUnsubscribed&&n.onStreamUnsubscribed(e)}),this.socket.on(zk.VIEWER_COUNT,e=>{this.logger.debug(`📡 [Viewer Count] ${e.tokenName}: ${e.viewerCount}`),this.bufferEvent(zk.VIEWER_COUNT,e.tokenName,e);const t=this.roomCallbacks.get(Vt(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(zk.STREAM_GLOBAL_STATUS,e=>{this.logger.debug(`📡 [Global Stream Status] enabled: ${String(e.enabled)}`),this.globalCallbacks.onStreamGlobalStatus&&this.globalCallbacks.onStreamGlobalStatus(e)}),this.socket.on(zk.CHAT_MESSAGE,e=>{this.logger.debug(`📡 [Chat Message] ${e.tokenName}: ${e.content.slice(0,50)}...`),this.bufferEvent(zk.CHAT_MESSAGE,e.tokenName,e);const t=this.roomCallbacks.get(Vt(e.tokenName));t?.onChatMessage&&t.onChatMessage(e),this.globalCallbacks.onChatMessage&&this.globalCallbacks.onChatMessage(e)}),this.socket.on(zk.CHAT_SENT,e=>{this.logger.debug(`📡 [Chat Sent] ${e.tokenName}: ${e.messageId}`);const t=this.roomCallbacks.get(Vt(e.tokenName));t?.onChatSent&&t.onChatSent(e)}),this.socket.on(zk.CHAT_ERROR,e=>{this.logger.error(`📡 [Chat Error] ${e.tokenName}: ${e.message}`);const t=this.roomCallbacks.get(Vt(e.tokenName));t?.onChatError&&t.onChatError(e),this.globalCallbacks.onChatError&&this.globalCallbacks.onChatError(e)}),this.socket.on(zk.CHAT_STATUS,e=>{this.logger.debug(`📡 [Chat Status] ${e.tokenName}: ${String(e.enabled)}`),this.bufferEvent(zk.CHAT_STATUS,e.tokenName,e);const t=this.roomCallbacks.get(Vt(e.tokenName));t?.onChatStatus&&t.onChatStatus(e),this.globalCallbacks.onChatStatus&&this.globalCallbacks.onChatStatus(e)}),this.socket.on(zk.CHAT_GLOBAL_STATUS,e=>{this.logger.debug(`📡 [Global Chat Status] enabled: ${String(e.enabled)}`),this.globalCallbacks.onChatGlobalStatus&&this.globalCallbacks.onChatGlobalStatus(e)}),this.socket.on(zk.CHAT_AUTHENTICATED,e=>{this.logger.debug(`📡 [Authenticated] ${e.address}`),this.isAuthenticated=!0,this.globalCallbacks.onChatAuthenticated&&this.globalCallbacks.onChatAuthenticated(e)}),this.socket.on(zk.CHAT_AUTH_ERROR,e=>{this.logger.error(`📡 [Auth Error] ${e.message}`),this.isAuthenticated=!1,this.globalCallbacks.onChatAuthError&&this.globalCallbacks.onChatAuthError(e)}),this.socket.on(zk.REACTION,e=>{this.logger.debug(`📡 [Reaction] ${e.tokenName}: ${e.emoji}`);const t=this.roomCallbacks.get(Vt(e.tokenName));t?.onReaction&&t.onReaction(e),this.globalCallbacks.onReaction&&this.globalCallbacks.onReaction(e)}),this.socket.on(zk.REACTION_ERROR,e=>{this.logger.error(`📡 [Reaction Error] ${e.tokenName}: ${e.message}`);const t=this.roomCallbacks.get(Vt(e.tokenName));t?.onReactionError&&t.onReactionError(e),this.globalCallbacks.onReactionError&&this.globalCallbacks.onReactionError(e)}),this.socket.on(zk.USER_TYPING,e=>{const t=e.typingUsers.length;this.logger.debug(`📡 [Typing] ${e.tokenName}: ${t} user(s) typing`);const n=this.roomCallbacks.get(Vt(e.tokenName));n?.onTypingIndicator&&n.onTypingIndicator(e),this.globalCallbacks.onTypingIndicator&&this.globalCallbacks.onTypingIndicator(e)}),this.socket.on(zk.CHAT_PINNED,e=>{this.logger.debug(`📡 [Chat Pinned] ${e.tokenName}: ${e.pinnedMessage.messageId}`),this.bufferEvent(zk.CHAT_PINNED,e.tokenName,e);const t=this.roomCallbacks.get(Vt(e.tokenName));t?.onChatPinned&&t.onChatPinned(e),this.globalCallbacks.onChatPinned&&this.globalCallbacks.onChatPinned(e)}),this.socket.on(zk.CHAT_UNPINNED,e=>{this.logger.debug(`📡 [Chat Unpinned] ${e.tokenName}: ${e.unpinnedMessageId}`),this.bufferEvent(zk.CHAT_UNPINNED,e.tokenName,e);const t=this.roomCallbacks.get(Vt(e.tokenName));t?.onChatUnpinned&&t.onChatUnpinned(e),this.globalCallbacks.onChatUnpinned&&this.globalCallbacks.onChatUnpinned(e)}),this.socket.on(zk.STREAM_COUNTDOWN_UPDATED,e=>{const t=e.nextLiveStreamAt??"cleared";this.logger.debug(`📡 [Countdown Updated] ${e.tokenName}: ${t}`),this.bufferEvent(zk.STREAM_COUNTDOWN_UPDATED,e.tokenName,e);const n=this.roomCallbacks.get(Vt(e.tokenName));n?.onCountdownUpdated&&n.onCountdownUpdated(e),this.globalCallbacks.onCountdownUpdated&&this.globalCallbacks.onCountdownUpdated(e)}),this.socket.on(zk.STREAM_LANGUAGE_UPDATED,e=>{this.logger.debug(`📡 [Language Updated] ${e.tokenName}: ${e.language}`),this.bufferEvent(zk.STREAM_LANGUAGE_UPDATED,e.tokenName,e);const t=this.roomCallbacks.get(Vt(e.tokenName));t?.onLanguageUpdated&&t.onLanguageUpdated(e),this.globalCallbacks.onLanguageUpdated&&this.globalCallbacks.onLanguageUpdated(e)}),this.socket.on(zk.TOKEN_BANNED,e=>{this.logger.debug(`📡 [Token Banned] ${e.tokenName}`),this.bufferEvent(zk.TOKEN_BANNED,e.tokenName,e);const t=this.roomCallbacks.get(Vt(e.tokenName));t?.onTokenBanned&&t.onTokenBanned(e),this.globalCallbacks.onTokenBanned&&this.globalCallbacks.onTokenBanned(e)}),this.socket.on(zk.TOKEN_UNBANNED,e=>{this.logger.debug(`📡 [Token Unbanned] ${e.tokenName}`),this.bufferEvent(zk.TOKEN_UNBANNED,e.tokenName,e);const t=this.roomCallbacks.get(Vt(e.tokenName));t?.onTokenUnbanned&&t.onTokenUnbanned(e),this.globalCallbacks.onTokenUnbanned&&this.globalCallbacks.onTokenUnbanned(e)}),this.socket.on(zk.USER_BANNED,e=>{this.logger.debug(`📡 [User Banned] ${e.tokenName}: ${e.userAddress}`),this.streamingEventService?.emitUserBanned(e)}),this.socket.on(zk.USER_UNBANNED,e=>{this.logger.debug(`📡 [User Unbanned] ${e.tokenName}: ${e.userAddress}`),this.streamingEventService?.emitUserUnbanned(e)}),this.socket.on(zk.BAN_ENFORCEMENT,e=>{this.logger.debug(`📡 [Ban Enforcement] ${e.tokenName}: ${e.action}`),this.streamingEventService?.emitBanEnforcement(e)}),this.socket.on(zk.MODERATOR_INVITE_CREATED,e=>{this.logger.debug(`📡 [Moderator Invite Created] ${e.tokenName}: by ${e.invitedBy}`),this.bufferEvent(zk.MODERATOR_INVITE_CREATED,e.tokenName,e);const t=this.roomCallbacks.get(Vt(e.tokenName));t?.onModeratorInviteCreated&&t.onModeratorInviteCreated(e)}),this.socket.on(zk.MODERATOR_ADDED,e=>{this.logger.debug(`📡 [Moderator Added] ${e.tokenName}: ${e.userAddress}`),this.bufferEvent(zk.MODERATOR_ADDED,e.tokenName,e);const t=this.roomCallbacks.get(Vt(e.tokenName));t?.onModeratorAdded&&t.onModeratorAdded(e)}),this.socket.on(zk.MODERATOR_REMOVED,e=>{this.logger.debug(`📡 [Moderator Removed] ${e.tokenName}: ${e.userAddress}`),this.bufferEvent(zk.MODERATOR_REMOVED,e.tokenName,e);const t=this.roomCallbacks.get(Vt(e.tokenName));t?.onModeratorRemoved&&t.onModeratorRemoved(e)}),this.socket.on(zk.MODERATOR_ROLE_UPDATED,e=>{this.logger.debug(`📡 [Moderator Role Updated] ${e.tokenName}: ${e.userAddress}`),this.bufferEvent(zk.MODERATOR_ROLE_UPDATED,e.tokenName,e);const t=this.roomCallbacks.get(Vt(e.tokenName));t?.onModeratorRoleUpdated&&t.onModeratorRoleUpdated(e)}),this.socket.on(zk.OVERSEER_ADDED,e=>{this.logger.debug(`📡 [Overseer Added] ${e.userAddress}`),this.globalCallbacks.onOverseerAdded&&this.globalCallbacks.onOverseerAdded(e)}),this.socket.on(zk.OVERSEER_REMOVED,e=>{this.logger.debug(`📡 [Overseer Removed] ${e.userAddress}`),this.globalCallbacks.onOverseerRemoved&&this.globalCallbacks.onOverseerRemoved(e)}),this.socket.on(zk.TRADE_EXECUTED,e=>{this.logger.debug(`📡 [Trade Executed] ${e.tokenName}: ${e.tradeType}`),this.bufferEvent(zk.TRADE_EXECUTED,e.tokenName,e);const t=this.roomCallbacks.get(Vt(e.tokenName));t?.onTradeExecuted&&t.onTradeExecuted(e),this.isGlobalFeedSubscribed&&!t&&this.globalFeedCallbacks.onTradeExecuted&&this.globalFeedCallbacks.onTradeExecuted(e)}),this.socket.on(zk.BALANCE_UPDATED,e=>{this.logger.debug(`📡 [Balance Updated] ${e.tokenName}: ${e.tradeType}`),this.bufferEvent(zk.BALANCE_UPDATED,e.tokenName,e);const t=this.roomCallbacks.get(Vt(e.tokenName));t?.onBalanceUpdated&&t.onBalanceUpdated(e)}),this.socket.on(zk.POOL_METADATA_UPDATED,e=>{this.logger.debug(`📡 [Pool Metadata Updated] ${e.tokenName}`),this.bufferEvent(zk.POOL_METADATA_UPDATED,e.tokenName,e);const t=this.roomCallbacks.get(Vt(e.tokenName));t?.onPoolMetadataUpdated&&t.onPoolMetadataUpdated(e)}),this.socket.on(zk.POOL_SOCIAL_LINKS_UPDATED,e=>{this.logger.debug(`📡 [Pool Social Links Updated] ${e.tokenName}`),this.bufferEvent(zk.POOL_SOCIAL_LINKS_UPDATED,e.tokenName,e);const t=this.roomCallbacks.get(Vt(e.tokenName));t?.onPoolSocialLinksUpdated&&t.onPoolSocialLinksUpdated(e)}),this.socket.on(zk.POOL_BADGE_ASSIGNED,e=>{this.logger.debug(`📡 [Pool Badge Assigned] ${e.tokenName}: ${e.badge}`),this.bufferEvent(zk.POOL_BADGE_ASSIGNED,e.tokenName,e);const t=this.roomCallbacks.get(Vt(e.tokenName));t?.onPoolBadgeAssigned&&t.onPoolBadgeAssigned(e),this.isGlobalFeedSubscribed&&!t&&this.globalFeedCallbacks.onPoolBadgeAssigned&&this.globalFeedCallbacks.onPoolBadgeAssigned(e)}),this.socket.on(zk.HOLDER_COUNT_UPDATED,e=>{this.logger.debug(`📡 [Holder Count Updated] ${e.tokenName}: ${e.holderCount}`),this.bufferEvent(zk.HOLDER_COUNT_UPDATED,e.tokenName,e);const t=this.roomCallbacks.get(Vt(e.tokenName));t?.onHolderCountUpdated&&t.onHolderCountUpdated(e),this.isGlobalFeedSubscribed&&!t&&this.globalFeedCallbacks.onHolderCountUpdated&&this.globalFeedCallbacks.onHolderCountUpdated(e)}),this.socket.on(zk.COMMENT_CREATED,e=>{this.logger.debug(`📡 [Comment Created] ${e.tokenName}: ID ${e.id}`),this.bufferEvent(zk.COMMENT_CREATED,e.tokenName,e);const t=this.roomCallbacks.get(Vt(e.tokenName));t?.onCommentCreated&&t.onCommentCreated(e)}),this.socket.on(zk.USER_PROFILE_UPDATED,e=>{this.logger.debug(`📡 [User Profile Updated] ${e.userAddress}`),this.globalCallbacks.onUserProfileUpdated&&this.globalCallbacks.onUserProfileUpdated(e)}),this.socket.on(zk.API_KEY_CREATED,e=>{this.logger.debug(`📡 [API Key Created] ${e.keyId}`),this.globalCallbacks.onApiKeyCreated&&this.globalCallbacks.onApiKeyCreated(e)}),this.socket.on(zk.API_KEY_UPDATED,e=>{this.logger.debug(`📡 [API Key Updated] ${e.keyId}`),this.globalCallbacks.onApiKeyUpdated&&this.globalCallbacks.onApiKeyUpdated(e)}),this.socket.on(zk.API_KEY_REVOKED,e=>{this.logger.debug(`📡 [API Key Revoked] ${e.keyId}`),this.globalCallbacks.onApiKeyRevoked&&this.globalCallbacks.onApiKeyRevoked(e)}),this.socket.on(zk.TOKEN_CONFIG_UPDATED,e=>{this.logger.debug(`📡 [Token Config Updated] ${e.tokenName}`),this.bufferEvent(zk.TOKEN_CONFIG_UPDATED,e.tokenName,e);const t=this.roomCallbacks.get(Vt(e.tokenName));t?.onTokenConfigUpdated&&t.onTokenConfigUpdated(e),this.isGlobalFeedSubscribed&&!t&&this.globalFeedCallbacks.onTokenConfigUpdated&&this.globalFeedCallbacks.onTokenConfigUpdated(e)}),this.socket.on(zk.STATS_UPDATED,e=>{this.logger.debug(`📡 [Stats Updated] ${e.tokenName} price=${e.galaPrice}`),this.bufferEvent(zk.STATS_UPDATED,e.tokenName,e);const t=this.roomCallbacks.get(Vt(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(zk.ENGAGEMENT_STATS_UPDATED,e=>{this.logger.debug(`📡 [Engagement Stats Updated] ${e.tokenName} chatters=${e.chat.uniqueChatters}`),this.bufferEvent(zk.ENGAGEMENT_STATS_UPDATED,e.tokenName,e);const t=this.roomCallbacks.get(Vt(e.tokenName));t?.onEngagementStatsUpdated&&t.onEngagementStatsUpdated(e),this.globalCallbacks.onEngagementStatsUpdated&&this.globalCallbacks.onEngagementStatsUpdated(e)}),this.socket.on(zk.GLOBAL_FEED_SUBSCRIBED,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(zk.GLOBAL_FEED_UNSUBSCRIBED,e=>{this.logger.debug("📡 [Global Feed Unsubscribed]"),this.isGlobalFeedSubscribed=!1,this.globalFeedCallbacks.onGlobalFeedUnsubscribed&&this.globalFeedCallbacks.onGlobalFeedUnsubscribed(e)}),this.socket.on(zk.SITE_CONFIG_CHANGED,e=>{this.logger.debug(`📡 [Site Config Changed] ${e.key}`),this.globalFeedCallbacks.onSiteConfigChanged&&this.globalFeedCallbacks.onSiteConfigChanged(e)}),this.socket.on(zk.STREAM_GLOBAL_STATUS,e=>{this.logger.debug(`📡 [Stream Global Status] enabled=${String(e.enabled)}`),this.globalFeedCallbacks.onStreamGlobalStatus&&this.globalFeedCallbacks.onStreamGlobalStatus(e)}),this.socket.on(zk.CHAT_GLOBAL_STATUS,e=>{this.logger.debug(`📡 [Chat Global Status] enabled=${String(e.enabled)}`),this.globalFeedCallbacks.onStreamChatGlobalStatus&&this.globalFeedCallbacks.onStreamChatGlobalStatus(e)}),this.socket.on(zk.COMMENTS_GLOBAL_STATUS,e=>{this.logger.debug(`📡 [Comments Global Status] enabled=${String(e.enabled)}`),this.globalFeedCallbacks.onCommentsGlobalStatus&&this.globalFeedCallbacks.onCommentsGlobalStatus(e)}),this.socket.on(zk.WEBHOOKS_GLOBAL_STATUS,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(zk.SUBSCRIBE,{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(zk.SUBSCRIBE_GLOBAL_FEED)}catch(e){this.logger.error("Failed to re-subscribe to global feed:",e)}}setStreamingEventService(e){this.streamingEventService=e}async connect(){return new Promise((e,t)=>{Ji(async()=>{if(!this.isSocketIOAvailable)throw new vt('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=a.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 yt("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(""===e)throw St("token","Authentication token");this.logger.debug("📡 Authenticating with stream server"),this.socket.emit(zk.AUTHENTICATE,{token:e}),this.config.authToken=e}async subscribeToStream(e,t={}){if(""===e)throw St("tokenName","Token name");if(!this.socket?.connected)throw new yt("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");const n=Vt(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((r,s)=>{const i=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:r,reject:s,timeoutId:i}),this.roomCallbacks.set(n,t),this.subscribedRooms.set(n,{tokenName:n,subscribedAt:Date.now()}),this.logger.debug(`📡 Subscribing to stream: ${n}`),this.socket.emit(zk.SUBSCRIBE,{tokenName:n})})}unsubscribeFromStream(e){const t=Vt(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(zk.UNSUBSCRIBE,{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 St("tokenName","Token name");if(""===t)throw St("content","Message content");if(!this.socket?.connected)throw new yt("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(!this.isAuthenticated)throw new yt("Not authenticated. Call authenticate() first.","auth","NOT_AUTHENTICATED");const n=Vt(e);this.logger.debug(`📡 Sending chat message to ${n}: ${t.slice(0,30)}...`),this.socket.emit(zk.SEND_CHAT,{tokenName:n,content:t})}sendReaction(e,t,n=0){if(""===e)throw St("tokenName","Token name");if(""===t)throw St("emoji");if(!this.socket?.connected)throw new yt("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(!this.isAuthenticated)throw new yt("Not authenticated. Call authenticate() first.","auth","NOT_AUTHENTICATED");const r=Vt(e);this.logger.debug(`📡 Sending reaction to ${r}: ${t}`),this.socket.emit(zk.SEND_REACTION,{tokenName:r,emoji:t,streamTime:n})}sendTypingStart(e){this.sendTypingEvent(e,zk.TYPING_START,"typing_start")}sendTypingStop(e){this.sendTypingEvent(e,zk.TYPING_STOP,"typing_stop")}sendTypingEvent(e,t,n){if(""===e)throw St("tokenName","Token name");if(!this.socket?.connected)throw new yt("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(!this.isAuthenticated)throw new yt("Not authenticated. Call authenticate() first.","auth","NOT_AUTHENTICATED");const r=Vt(e);this.logger.debug(`📡 Sending ${n} to ${r}`),this.socket.emit(t,{tokenName:r})}subscribeTokenBanned(e,t){const n=Vt(e),r={onTokenBanned:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...r}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onTokenBanned,this.roomCallbacks.set(n,t)}}}subscribeTokenUnbanned(e,t){const n=Vt(e),r={onTokenUnbanned:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...r}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onTokenUnbanned,this.roomCallbacks.set(n,t)}}}subscribeModeratorInviteCreated(e,t){const n=Vt(e),r={onModeratorInviteCreated:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...r}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onModeratorInviteCreated,this.roomCallbacks.set(n,t)}}}subscribeModeratorAdded(e,t){const n=Vt(e),r={onModeratorAdded:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...r}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onModeratorAdded,this.roomCallbacks.set(n,t)}}}subscribeModeratorRemoved(e,t){const n=Vt(e),r={onModeratorRemoved:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...r}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onModeratorRemoved,this.roomCallbacks.set(n,t)}}}subscribeModeratorRoleUpdated(e,t){const n=Vt(e),r={onModeratorRoleUpdated:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...r}),()=>{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=Vt(e),r={onTradeExecuted:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...r}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onTradeExecuted,this.roomCallbacks.set(n,t)}}}subscribePoolMetadataUpdated(e,t){const n=Vt(e),r={onPoolMetadataUpdated:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...r}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onPoolMetadataUpdated,this.roomCallbacks.set(n,t)}}}subscribePoolSocialLinksUpdated(e,t){const n=Vt(e),r={onPoolSocialLinksUpdated:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...r}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onPoolSocialLinksUpdated,this.roomCallbacks.set(n,t)}}}subscribePoolBadgeAssigned(e,t){const n=Vt(e),r={onPoolBadgeAssigned:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...r}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onPoolBadgeAssigned,this.roomCallbacks.set(n,t)}}}subscribeHolderCountUpdated(e,t){const n=Vt(e),r={onHolderCountUpdated:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...r}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onHolderCountUpdated,this.roomCallbacks.set(n,t)}}}subscribeCommentCreated(e,t){const n=Vt(e),r={onCommentCreated:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...r}),()=>{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 yt("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 r=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:r},e&&(this.globalFeedCallbacks=e),this.logger.debug("📡 Subscribing to global feed"),this.socket.emit(zk.SUBSCRIBE_GLOBAL_FEED)})}unsubscribeFromGlobalFeed(){this.isGlobalFeedSubscribed?(this.logger.debug("📡 Unsubscribing from global feed"),this.socket?.connected&&this.socket.emit(zk.UNSUBSCRIBE_GLOBAL_FEED),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 jk(e){return null==e||""===e||"string"==typeof e&&(!Qn(e)&&e.length<=fn.BAN_REASON.MAX_LENGTH)}function Xk(e){if(jn(e.tokenName,"tokenName",on),!jk(e.reason))throw new yt(`reason must be at most ${fn.BAN_REASON.MAX_LENGTH} characters`,"reason","TOO_LONG")}function Yk(e){jn(e.tokenName,"tokenName",on)}function Jk(e){Hn(0,void 0,ln,e.pageSize)}function Qk(e){jn(e.tokenName,"tokenName",on)}class Zk extends uE{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async banToken(e){Xk(e);const t=Be,n={tokenName:Vt(e.tokenName)};if(void 0!==e.reason)try{Un(e.reason,"reason",!0),e.reason.trim().length>0&&(n.reason=e.reason)}catch{}const r=await this.http.post(t,n,this.getDualAuthHeaders());return{ban:this.extractData(r),tokenName:Vt(e.tokenName)}}async unbanToken(e){Yk(e);const t=this.buildEndpoint(Me,{tokenName:e.tokenName});return Ft(await this.http.delete(t,void 0,this.getDualAuthHeaders()),"Failed to unban token",!1),{tokenName:Vt(e.tokenName)}}async listTokenBans(e={}){Jk(e);const t=De,n=this.buildPaginationParams(e,ln);this.addOptionalFilterParams(n,e,["search"]);const r=await this.http.get(t,n,this.getDualAuthHeaders()),s=this.extractData(r);return{items:s.bans,pageInfo:s.pageInfo}}async getTokenBan(e){Qk(e);const t=this.buildEndpoint(Oe,{tokenName:e.tokenName}),n=await this.http.get(t,{},this.getDualAuthHeaders()),r=this.extractDataOrNull(n);return{banned:null!==r,...null!==r&&{ban:r},tokenName:Vt(e.tokenName)}}async isTokenBanned(e){return this.getTokenBan(e)}}class eT extends sr{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(!Kn(e))throw St("tokenName","Token name");const t=Vt(e),n=this.getCacheEntry(t);if(null!==n)return this.cacheHits++,this.updateAccessOrder(t),n.vaultAddress;this.cacheMisses++;const r=await this.poolService.resolveTokenNameToVault(e);if(null!==r&&""!==r){const e=this.parseVaultAddressToTokenClassKey(r);this.setCacheEntry(t,{vaultAddress:r,tokenClassKey:e,cachedAt:Date.now()})}return r}async resolveTokenClassKey(e){if(!Kn(e))throw St("tokenName","Token name");const t=Vt(e),n=this.getCacheEntry(t);if(null!==n)return this.cacheHits++,this.updateAccessOrder(t),n.tokenClassKey;this.cacheMisses++;const r=await this.poolService.resolveTokenNameToVault(e);if(null===r||""===r)throw At(e);const s=this.parseVaultAddressToTokenClassKey(r);return this.setCacheEntry(t,{vaultAddress:r,tokenClassKey:s,cachedAt:Date.now()}),s}get(e){const t=this.getCacheEntry(Vt(e));return t?.vaultAddress??null}getCacheEntry(e){return this.cache.get(e)??null}setCacheEntry(e,t){this.cache.size>=eT.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=Vt(e),r=this.parseVaultAddressToTokenClassKey(t);this.setCacheEntry(n,{vaultAddress:t,tokenClassKey:r,cachedAt:Date.now()})}clear(){this.cache.clear(),this.accessOrder=new Set,this.cacheHits=0,this.cacheMisses=0}getStats(){const e=Array.from(this.cache.values()).map(e=>e.cachedAt),t=this.cacheHits+this.cacheMisses;return{size:this.cache.size,keys:Array.from(this.cache.keys()),maxSize:eT.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(Vt(e));return t?.tokenClassKey??null}preWarm(e){for(const{tokenName:t,vaultAddress:n}of e)this.set(t,n)}preWarmWithTokenClassKey(e){for(const{tokenName:t,vaultAddress:n,tokenClassKey:r}of e){const e=Vt(t);this.setCacheEntry(e,{vaultAddress:n,tokenClassKey:r,cachedAt:Date.now()})}}parseVaultAddressToTokenClassKey(e){try{return LE(e)}catch(e){if(e instanceof yt)throw kt("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad","Vault address");throw e}}}eT.MAX_CACHE_SIZE=1e4;class tT extends rr{constructor(e,t=!1){super(e,t)}async fetchLaunchpadFee(){return Gt(()=>this.http.get(je),{errorContext:"Failed to fetch launchpad fee"})}async fetchSaleDetails(e){return Gt(()=>this.http.get(Xe,{tokenName:e}),{errorContext:`Failed to fetch sale details for ${e}`})}async getTradeQuote(e){return Gt(()=>this.http.get(Ye,{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(Je,{amount:e}),{errorContext:"Failed to get premint quote"})}}class nT extends uE{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async emitTradeExecuted(e,t){this.validateTokenName(e,an);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,an);const r={action:"balance_updated",userAddress:e,tokenName:t,payload:n};await this.emitEvent(r)}async emitStreamStatus(e,t,n=!0){this.validateTokenName(e,an);const r={action:"stream_status",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitViewerCount(e,t,n=!1){this.validateTokenName(e,an);const r={action:"viewer_count",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitStreamCountdown(e,t,n=!0){this.validateTokenName(e,an);const r={action:"stream_countdown",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitChatMessage(e,t,n=!1){this.validateTokenName(e,an);const r={action:"chat_message",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitChatStatus(e,t,n=!1){this.validateTokenName(e,an);const r={action:"chat_status",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitTypingIndicator(e,t,n=!1){this.validateTokenName(e,an);const r={action:"typing_indicator",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitTokenBanned(e,t){this.validateTokenName(e,an);const n={action:"token_banned",tokenName:e,payload:t,broadcast:!0};await this.emitEvent(n)}async emitTokenUnbanned(e,t){this.validateTokenName(e,an);const n={action:"token_unbanned",tokenName:e,payload:t,broadcast:!0};await this.emitEvent(n)}async emitModeratorAdded(e,t,n=!1){this.validateTokenName(e,an);const r={action:"moderator_added",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitModeratorRemoved(e,t,n=!1){this.validateTokenName(e,an);const r={action:"moderator_removed",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitUserProfileUpdated(e,t){this.validateRequiredString(e,"userAddress","User Address");const n={action:"user_profile_updated",userAddress:e,payload:t};await this.emitEvent(n)}async emitSiteConfigChanged(e){const t={action:"site_config_changed",payload:e,broadcast:!0};await this.emitEvent(t)}async emitFeatureStatus(e){const t={action:"feature_status",payload:e,broadcast:!0};await this.emitEvent(t)}async emitEvent(e){this.validateRequiredString(e.action,"action","Event Action");const t=this.buildEndpoint("/v1/websocket",{});await this.http.post(t,e,this.getDualAuthHeaders())}async getConnectedClients(e){const t=this.buildEndpoint("/v1/connected-clients",{}),n={};void 0!==e?.room&&""!==e.room&&(n.room=e.room),void 0!==e?.tokenName&&(n.tokenName=e.tokenName),void 0!==e?.userAddress&&(n.userAddress=e.userAddress),void 0!==e?.userAddresses&&(n.userAddresses=e.userAddresses),void 0!==e?.authenticated&&(n.authenticated=e.authenticated),void 0!==e?.isOverseer&&(n.isOverseer=e.isOverseer),void 0!==e?.minConnectionSeconds&&(n.minConnectionSeconds=e.minConnectionSeconds),void 0!==e?.offset&&(n.offset=e.offset),void 0!==e?.limit&&(n.limit=e.limit);const r=await this.http.get(t,Object.keys(n).length>0?n:void 0,this.getDualAuthHeaders());return this.extractData(r)}async isUserOnline(e){this.validateRequiredString(e,"userAddress","User Address");const t=await this.getConnectedClients({userAddress:e,limit:1});if(0===t.clients.length)return{online:!1};const n=t.clients[0];return void 0===n?{online:!1}:{online:!0,socketId:n.socketId,rooms:n.rooms,connectedAt:n.connectedAt}}async getOnlineUsers(e){if(!Array.isArray(e)||0===e.length)throw new vt("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,an);const n={tokenName:e};void 0!==t?.authenticated&&(n.authenticated=t.authenticated),void 0!==t?.limit&&(n.limit=t.limit);const r=await this.getConnectedClients(n);return{clients:r.clients,count:r.summary.totalConnected,authenticatedCount:r.summary.authenticatedCount}}async getOnlineOverseers(){const e=await this.getConnectedClients({isOverseer:!0});return{clients:e.clients,count:e.summary.totalConnected}}async emitRecordingStatus(e,t){this.validateTokenName(e,an);const n={action:"recording_status",tokenName:e,payload:t};await this.emitEvent(n)}async emitRecordingsCountUpdated(e,t){this.validateTokenName(e,an);const n={action:"recordings_count_updated",tokenName:e,payload:t};await this.emitEvent(n)}async emitDownloadReady(e,t){this.validateTokenName(e,an);const n={action:"download_ready",tokenName:e,payload:t};await this.emitEvent(n)}}class rT{constructor(e=0){this.defaultTtlMs=e,this.cache=new Map}get(e){const t=this.cache.get(e);if(t){if(!(void 0!==t.expiresAt&&Date.now()>t.expiresAt))return t.value;this.cache.delete(e)}}set(e,t,n){const r=n??this.defaultTtlMs,s={value:t};r>0&&(s.expiresAt=Date.now()+r),this.cache.set(e,s)}has(e){return void 0!==this.get(e)}delete(e){this.cache.delete(e)}clear(){this.cache.clear()}get size(){return this.cache.size}}async function sT(e,t,n,r={}){const{logger:s,cacheNullish:i=!1,keyGenerator:o}=r,a=o?o(e):String(e),c=n.get(a);if(void 0!==c)return s&&s.debug(`Cache hit for key: ${a}`),c;s&&s.debug(`Cache miss for key: ${a}, fetching...`);const l=await t();return null!=l?(n.set(a,l),s&&s.debug(`Cached result for key: ${a}`)):i&&(n.set(a,l),s&&s.debug(`Cached nullish result for key: ${a}`)),l}class iT extends sr{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 AS({maxAttempts:this.config.reconnectAttempts??5,baseDelayMs:this.config.reconnectDelay??2e3}),this.eventBuffer=new rT(3e4),this.isSocketIOAvailable=this.checkSocketIOAvailability(),iT.instances.add(this)}checkSocketIOAvailability(){try{return"function"==typeof a.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)=>{Ji(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:",at(e)),e}this.logger.debug("🔌 Connecting to Socket.IO server:",this.config.url),this.socket=a.io(this.config.url,{transports:["websocket"],reconnection:!0,reconnectionAttempts:this.config.reconnectAttempts??5,reconnectionDelay:this.config.reconnectDelay??2e3}),this.socket.on("connect",()=>{this.logger.debug("✅ Socket.IO connected successfully:",this.socket?.id),this.logger.debug("📡 Connected to bundle backend WebSocket:",this.config.url),this.logger.debug("🔗 Ready to monitor transaction updates"),this.reconnectionManager.reset(),e()}),this.socket.on("connect_error",e=>{this.logger.error("❌ Socket.IO connection error:",e),t(e)}),this.socket.on("disconnect",e=>{this.logger.debug(`🔌 Socket.IO disconnected: ${e}`),this.handleReconnect()}),this.socket.on("error",e=>{this.logger.error("❌ Socket.IO error:",e)}),this.socket.onAny((e,...t)=>{if(""!==e&&t.length>0&&"object"==typeof t[0]&&null!==t[0]){const n=t[0],r=n.status??n.Status;"string"==typeof r&&(this.logger.debug(`📡 [Event Buffer] Buffering event for ${e}: ${r}`),this.eventBuffer.size>=this.MAX_BUFFER_SIZE&&this.logger.warn(`📡 [Event Buffer] Buffer approaching limit (${this.eventBuffer.size}/${this.MAX_BUFFER_SIZE})`),this.eventBuffer.set(e,n))}this.debug&&this.logger.debug(`📡 [WebSocket Event] "${e}":`,JSON.stringify(t,null,2))}),this.hasOnAnyListener=!0},"Socket.IO connection failed",this.logger,e=>{this.logger.error("Socket.IO connection failed:",e);const n=ot(e)?e:new Error(at(e));throw t(n),n}).catch(t)})}async monitorTransaction(e,t){this.listeners.set(e,t),this.logger.debug(`📡 Starting to monitor transaction: ${e}`),this.logger.debug(`📡 WebSocket connected: ${String(this.socket?.connected??!1)}`);const n=this.eventBuffer.get(e);null!=n&&(this.logger.debug(`📡 [Event Buffer] Found buffered event for ${e}, delivering immediately`),setImmediate(()=>{this.processTransactionEvent(e,n,t)}),this.eventBuffer.delete(e));const r=this.config.timeout??3e5,s=setTimeout(()=>{if(this.listeners.has(e)){const n=Math.round(r/1e3),s={transactionId:e,status:exports.SDKTransactionStatus.TIMEOUT,message:`Transaction monitoring timeout - no response after ${n} seconds`,timestamp:Date.now()};this.logger.debug(`📡 Transaction timeout for ${e} (${n}s)`),t(s),this.listeners.delete(e),this.timeouts.delete(e),this.socket?.off(e)}},r);if(this.timeouts.set(e,s),this.socket?.connected)this.socket.off(e),this.logger.debug(`📡 Listening for transaction updates: ${e}`),this.logger.debug(`📡 WebSocket connection ID: ${String(this.socket.id)}`),this.logger.debug(`📡 WebSocket URL: ${this.config.url}`),this.socket.on(e,n=>{this.processTransactionEvent(e,n,t)});else{const n={transactionId:e,status:exports.SDKTransactionStatus.FAILED,message:"WebSocket not connected - cannot monitor transaction",timestamp:Date.now()};t(n),this.listeners.delete(e),this.timeouts.delete(e)}await Promise.resolve()}processTransactionEvent(e,t,n){this.logger.debug(`📡 Socket.IO transaction update for ${e}:`,JSON.stringify(t,null,2));const r=t,s=r?.data,i=r?.status??r?.Status??s?.status??s?.Status;let o=r?.message??r?.Message??s?.message??s?.Message??r?.error??s?.error;Kn(o)||(o=i===Zw.FAILED||i===Zw.ERROR?"Transaction failed - check transaction details":i===Zw.COMPLETED||i===Zw.PROCESSED||i===Zw.SUCCESS?"Transaction completed successfully":null!=i?`Transaction status: ${String(i)}`:"Unknown transaction status");const a=r?.blockHash??s?.blockHash,c=r?.gasUsed??s?.gasUsed,l=r?.Data??s?.Data,u={transactionId:e,status:this.mapSocketStatus(i),message:"string"==typeof o?o:"Transaction update received",timestamp:Date.now(),...null!=a?{blockHash:a}:{},...null!=c?{gasUsed:c}:{},...null!=l?{data:l}:{}};if(this.logger.debug(`📡 Mapped status for ${e}: ${String(i)} -> ${u.status}`),this.logger.debug(`📡 Final message: "${String(o)}"`),n(u),u.status===exports.SDKTransactionStatus.COMPLETED||u.status===exports.SDKTransactionStatus.FAILED){this.listeners.delete(e);const t=this.timeouts.get(e);t&&(clearTimeout(t),this.timeouts.delete(e)),this.socket?.off(e),this.logger.debug(`📡 Cleaned up listener for ${e} (${u.status})`)}}async waitForTransaction(e){return new Promise((t,n)=>{this.monitorTransaction(e,e=>{e.status===exports.SDKTransactionStatus.COMPLETED?t(e):e.status!==exports.SDKTransactionStatus.FAILED&&e.status!==exports.SDKTransactionStatus.TIMEOUT||n(new Error(`Transaction ${String(e.status)}: ${e.message}`))})})}mapSocketStatus(e){const t=e?.toUpperCase();return tE[t]??exports.SDKTransactionStatus.PENDING}async handleReconnect(){this.reconnectionManager.shouldRetry()?(this.reconnectionManager.recordAttempt(),this.logger.debug(`🔄 Attempting Socket.IO reconnect ${this.reconnectionManager.getStatusString()}`),setTimeout(()=>{this.socket&&!this.socket.connected&&this.socket.connect()},this.reconnectionManager.getNextDelay())):this.logger.error("❌ Socket.IO max reconnection attempts reached")}disconnect(){this.socket&&(this.listeners.forEach((e,t)=>{this.socket?.off(t)}),this.listeners.clear(),this.timeouts.forEach(e=>{clearTimeout(e)}),this.timeouts.clear(),this.eventBuffer.clear(),this.logger.debug("🧹 Cleared event buffer"),this.hasOnAnyListener&&(this.socket.offAny(),this.hasOnAnyListener=!1,this.logger.debug("🧹 Removed onAny debug listener")),this.socket.disconnect(),this.socket=null,this.logger.debug("🔌 Socket.IO disconnected")),iT.instances.delete(this)}static cleanupAll(e=!1){for(const e of iT.instances)e.disconnect();iT.instances.clear()}isConnected(){return this.socket?.connected??!1}getSocket(){return this.socket}}iT.instances=new Set;class oT extends rr{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 yt("limit must be between 1 and 50","limit","INVALID_LIMIT");this.logger.debug("Fetching weekly challenge leaderboard",{limit:t});const n={limit:String(t)},r=await this.http.get(Qe.GET_LEADERBOARD,n),s=this.extractData(r);return this.logger.debug("Fetched weekly challenge leaderboard",{count:s.count}),{leaderboard:s}}async getTokenHistory(e){const{vaultAddress:t}=e;if("string"!=typeof t||""===t.trim())throw new yt("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)),r=await this.http.get(n),s=this.extractData(r);return this.logger.debug("Fetched token weekly history",{count:s.length}),{snapshots:s}}}class aT extends ir{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 cT extends aT{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 lT extends KE{constructor(e,t=!1){super(e,t,"WrappableTokenService"),this.cache=new cT(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())})`),Ji(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 Ji(async()=>{const e=await async function(e){const{cache:t,fetchFn:n,logger:r,itemTypeName:s="items"}=e;if(t.has()){const e=t.getAll();return r&&r.debug(`Returning ${e.length} cached ${s}`),{items:e,fetchedAt:t.getFetchTimestamp()??Date.now(),itemCount:e.length}}r&&r.debug(`Fetching all ${s} (no cache)`);const i=await n();try{t.setAll(i)}catch(e){r&&r.error("Cache operation failed (non-fatal):",e)}return{items:i,fetchedAt:Date.now(),itemCount:i.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=FE(e),n=this.cache.getByTokenId(t);return n||(await sT("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=FE(e);await sT("wrappable:check",()=>this.fetchAllWrappableTokens(),{get:()=>this.cache.has()?{}:void 0,set:()=>{}},{logger:this.logger});const n=this.cache.getByTokenId(t),r=void 0!==n,s={isWrappable:r,tokenId:t};return r&&(s.wrapCounterpart=n.wrapCounterpart),s}getCacheStats(){return this.cache.getStats()}clearCache(){this.cache.clear()}}class uT extends sr{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 oA(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 St("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",r=t?"unwrapToken()":"wrapToken()",s=t?"ALREADY_ON_ASSET_CHANNEL":"NOT_ON_ASSET_CHANNEL";throw new yt(`Cannot ${t?"wrap":"unwrap"} ${n.symbol} - it's ${e}. Use ${r} instead.`,"tokenId",s)}const r=await this.getCounterpartOrThrow(e.tokenId,n.symbol);return this.executeChannelBridge({sourceToken:n,destinationToken:r,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 St("tokenId","Token identifier");if(0===t.length)throw St("amount");const r=await this.getWrappableTokenOrThrow(e);if(n?"asset"===r.channel:"asset"!==r.channel){const e=n?"already on asset channel":"not on asset channel",t=n?"ALREADY_ON_ASSET_CHANNEL":"NOT_ON_ASSET_CHANNEL";throw new yt(`Cannot ${n?"wrap":"unwrap"} ${r.symbol} - it's ${e}`,"tokenId",t)}const s=this.determineChannelRouting(r,n);return{fee:"0",feeToken:"GALA",authorizationType:s.authType,feeChannel:s.sourceChannel}}async executeChannelBridge(e){const{sourceToken:t,destinationToken:n,amount:r,recipient:s,isWrap:i}=e;if(void 0===this.nativeSigner||void 0===this.walletAddress||0===this.walletAddress.length)throw new yt("Wallet required for wrap/unwrap operations. Initialize SDK with a private key.","wallet","WALLET_REQUIRED");const o=this.walletAddress,a=this.determineChannelRouting(t,i),c=`galaswap-operation-${Pv()}`,l={quantity:r,tokenInstance:{collection:t.galaChainDescriptor.collection,category:t.galaChainDescriptor.category,type:t.galaChainDescriptor.type,additionalKey:t.galaChainDescriptor.additionalKey,instance:"0"},destinationChainId:a.destinationChannelId,recipient:s??o,wrap:!0,uniqueKey:c};return this.logger.debug(`[WrapService] ${i?"Wrap":"Unwrap"} message (pre-signing)`,{amount:r,uniqueKey:c,sourceChannel:a.sourceChannel}),this.executeWrapBridgeRequest({sourceToken:t,destinationToken:n,amount:r,message:l,routing:a,isWrap:i,senderAddress:o})}async executeWrapBridgeRequest(e){const{sourceToken:t,destinationToken:n,amount:r,message:s,routing:i,isWrap:o}=e;try{const e=await this.nativeSigner.signObject("RequestTokenBridgeOut",s);this.logger.debug(`[WrapService] ${o?"Wrap":"Unwrap"} request (signed)`,{sourceToken:t.symbol,destinationToken:n.symbol,amount:r,channel:i.sourceChannel});const a=await this.galaConnectClient.requestBridgeOut(e);if(this.logger.debug("[WrapService] RequestBridgeOut response",{status:a.Status,hasData:"Data"in a}),function(e){return"object"==typeof e&&null!==e&&"Status"in e&&"number"==typeof e.Status&&1!==e.Status}(a)){const e=`Status=${a.Status}`,s="string"==typeof a.Message&&a.Message.length>0?`: ${a.Message}`:"";return{success:!1,fromToken:t.symbol,toToken:n.symbol,amount:r,fromChannel:i.sourceChannel,toChannel:o?"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}(a)){const e=a.Data;this.logger.debug("[WrapService] Step 1 complete, bridgeRequestId:",e);const s={bridgeFromChannel:i.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:r,fromChannel:i.sourceChannel,toChannel:o?"asset":n.channel??"music",error:`BridgeTokenOut failed: status=${String(c.Status)}`}:{success:!0,transactionId:c.Hash??e,fromToken:t.symbol,toToken:n.symbol,amount:r,fromChannel:i.sourceChannel,toChannel:o?"asset":n.channel??"music",completedAt:Date.now()}}return{success:!1,fromToken:t.symbol,toToken:n.symbol,amount:r,fromChannel:i.sourceChannel,toChannel:o?"asset":n.channel??"music",error:`Unexpected response format from GalaChain (type=${typeof a})`}}catch(e){const s=at(e);return this.logger.error(`[WrapService] ${o?"Wrap":"Unwrap"} operation failed:`,s),{success:!1,fromToken:t.symbol,toToken:n.symbol,amount:r,fromChannel:i.sourceChannel,toChannel:o?"asset":n.channel??"music",error:s}}}determineChannelRouting(e,t){if(t){return{sourceChannel:e.channel??"music",destinationChannelId:co.ASSET,authType:"cross_channel_authorization"}}return{sourceChannel:"asset",destinationChannelId:co.MUSIC,authType:"automatic"}}async getCounterpartOrThrow(e,t){const n=await this.wrappableTokenService.getWrapCounterpart(e);if(null==n)throw new yt(`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 yt(`Token not found or not wrappable: ${this.formatTokenId(e)}`,"tokenId","TOKEN_NOT_WRAPPABLE");return t}formatTokenId(e){return"string"==typeof e?e:io(e)}}class dT 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 hT{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 gT{constructor(e){this.bundleBaseUrl=ET(e.bundleBaseUrl),this.launchpadBaseUrl=ET(e.launchpadBaseUrl),this.signer=e.signer,this.walletAddress=e.walletAddress,this.requestor=e.httpRequestor??fetch.bind(globalThis),this.socketFactory=e.socketFactory??(e=>a.io(e,{transports:["websocket"]}))}async submit(e){let t;try{t=await this.signer.signTypedData(e.method,e.dto)}catch(e){if(e instanceof dT)throw e;const t=e instanceof Error?e.message:"Launchpad signing failed.";throw new dT(t,"LAUNCHPAD_SIGNING_FAILED",{chainMessage:t})}const n=function(e){return Object.fromEntries(Object.entries(e).filter(([e])=>"prefix"!==e))}(t),r=`${this.bundleBaseUrl}/bundle`,s=await this.requestor(r,{method:"POST",headers:{"content-type":"application/json","X-Wallet-Address":this.walletAddress},body:JSON.stringify({stringsInstructions:e.stringsInstructions,method:e.method,signedDto:n})}),i=await vT(s);if(!s.ok)throw pT(s.status,i,r);const o=function(e){if("string"==typeof e&&""!==e)return e;if(!wT(e))throw new dT("Bundler returned no bundle id.","INVALID_BUNDLE_RESPONSE");const t=e.data,n=e.bundleId;if("string"==typeof t&&""!==t)return t;if(wT(t)&&"string"==typeof t.bundleId&&""!==t.bundleId)return t.bundleId;if("string"==typeof n&&""!==n)return n;throw new dT("Bundler returned no bundle id.","INVALID_BUNDLE_RESPONSE")}(i),a=bT(e.dto,"uniqueKey");return new hT({bundleId:o,uniqueKey:a,method:e.method,wait:t=>this.waitForResult(e,o,t)})}async waitForResult(e,t,n={}){const r=n.timeoutMs??6e4,s=n.pollIntervalMs??2500,i=Date.now();let o,a,c=!1,l=new Promise(()=>{});try{o=this.socketFactory(this.bundleBaseUrl),l=new Promise((e,n)=>{a=t=>{const r=function(e){if(!wT(e))return;const t=e.status;return"PROCESSED"!==t&&"FAILED"!==t?void 0:{status:t,data:e.data}}(t);void 0===r||c||(c=!0,"FAILED"===r.status?n(fT(r.data)):e(r))},o?.on(t,a)})}catch{o=void 0}const u=this.pollConfirmation(e,t,i,r,s);try{return await Promise.race([l,u])}finally{c=!0,void 0!==o&&(void 0!==a&&o.off(t,a),o.disconnect())}}async pollConfirmation(e,t,n,r,s){const i="CreateSale"===e.method,o=i?function(e,t){const n=bT(t,"tokenName");return`${e}/v1/tokens/${encodeURIComponent(n)}`}(this.launchpadBaseUrl,e.dto):`${this.bundleBaseUrl}/bundle?id=${encodeURIComponent(t)}`;for(;Date.now()-n<=r;){const e=await this.requestor(o,{method:"GET"}),t=await vT(e);if(i){if(e.ok)return{status:"PROCESSED",data:yT(t)};if(404!==e.status&&202!==e.status)throw pT(e.status,t,o)}else{if(!e.ok)throw pT(e.status,t,o);const n=wT(t)?t.status:void 0;if("COMPLETED"===n||"PROCESSED"===n)return{status:"PROCESSED",data:t};if("FAILED"===n)throw fT(t)}const a=r-(Date.now()-n);if(a<=0)break;await AT(Math.min(Math.max(0,s),a))}throw new dT(`Timed out waiting for bundle ${e.dto.uniqueKey}`,"BUNDLE_CONFIRMATION_TIMEOUT",{details:{method:e.method}})}}function fT(e){const t=mT(e)??"Launchpad bundle failed on chain.";return new dT(t,"BUNDLE_FAILED",{chainMessage:t})}function pT(e,t,n){const r=mT(t)??`Bundle request failed with HTTP ${e}`;return new dT(r,"BUNDLE_REQUEST_FAILED",{status:e,chainMessage:r,details:{body:t,url:n}})}function mT(e){if("string"==typeof e&&""!==e)return e;if(wT(e))for(const t of["chainMessage","message","Message","error"]){const n=e[t];if("string"==typeof n&&""!==n)return n;if(wT(n)){const e=mT(n);if(void 0!==e)return e}}}function yT(e){return wT(e)?e.data??e.Data??e:e}function bT(e,t){const n=e[t];if("string"!=typeof n||""===n)throw new dT(`Missing ${t} in launchpad DTO.`,"INVALID_LAUNCHPAD_DTO");return n}async function vT(e){try{return await e.json()}catch{return e.text()}}function wT(e){return"object"==typeof e&&null!==e}function ET(e){return e.replace(/\/$/u,"")}function AT(e){return new Promise(t=>setTimeout(t,e))}class ST{constructor(e){this.transport=e.transport,this.walletAddress=e.walletAddress}createSale(e){!function(e){const t=Ys(e);!t.success&&t.errors&&Li(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??kT(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:dA(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 r={vaultAddress:t.vaultAddress,...n,extraFees:t.extraFees??{maxAcceptableReverseBondingCurveFee:"0"},uniqueKey:t.uniqueKey??kT(this.walletAddress)};return this.transport.submit({method:e,dto:r,stringsInstructions:uA(t.vaultAddress)})}}function kT(e){return`galaswap-operation-${r.v4()}-${Date.now()}-${e}`}class TT{constructor(e){this.gatewayBaseUrl=e.gatewayBaseUrl.replace(/\/$/u,""),this.signer=e.signer,this.walletAddress=BT(e.walletAddress),this.requestor=e.httpRequestor??fetch.bind(globalThis)}transfer(e){const t=IT(e),n={from:this.walletAddress,to:BT(e.to),quantity:e.quantity,tokenInstance:t,uniqueKey:e.uniqueKey??RT(this.walletAddress)};return this.direct("TransferToken",n)}burn(e){const t={tokenInstances:[{quantity:e.quantity,tokenInstanceKey:IT(e)}],uniqueKey:e.uniqueKey??RT(this.walletAddress)};return this.direct("BurnTokens",t)}lock(e){const t={lockAuthority:e.lockAuthority??this.walletAddress,tokenInstances:[{owner:this.walletAddress,quantity:e.quantity,tokenInstanceKey:IT(e)}],uniqueKey:e.uniqueKey??RT(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:IT(e)}],uniqueKey:e.uniqueKey??RT(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),r=`${this.gatewayBaseUrl}/api/asset/token-contract/${e}`,s=await this.post(r,n),i=await async function(e){try{return await e.json()}catch{return e.text()}}(s),o=xT(i);if(!s.ok||void 0!==o?.Status&&1!==o.Status)throw function(e,t,n){const r=xT(t),s=_T(r,"Message")??_T(r,"message")??_T(r,"ErrorKey")??`Gateway request failed with HTTP ${e}`,i=_T(r,"ErrorKey")??"GATEWAY_REQUEST_FAILED";return new dT(s,i,{status:e,chainMessage:s,details:{body:t,url:n}})}(s.status,i,r);const a=xT(NT(i))?.mode??o?.mode;if(void 0!==a&&"sync"!==a){throw new dT(`Unsupported gateway transaction mode: ${"string"==typeof a?a:"non-sync"}`,"INVALID_GATEWAY_RESPONSE",{status:s.status,details:{body:i,url:r}})}const c=NT(i),l=DT(s,"x-transaction-id")??CT(c)??CT(i),u=function(e){const t=DT(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!==u&&{blockNumber:u}}}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 dT)throw e;const t=e instanceof Error?e.message:"Native GalaChain signing failed.";throw new dT(t,"NATIVE_SIGNING_FAILED",{chainMessage:t})}}}function IT(e){const t=e.tokenClassKey;if(void 0===t)throw new dT("tokenClassKey is required.","INVALID_TOKEN_IDENTIFIER");const n=function(e){if("string"!=typeof e){const{collection:t,category:n,type:r,additionalKey:s}=e;if([t,n,r,s].some(e=>"string"!=typeof e||""===e))throw new dT("Invalid token class key: all four fields are required.","INVALID_TOKEN_IDENTIFIER");return{collection:t,category:n,type:r,additionalKey:s}}if(!e.includes("|")&&!e.includes("$"))throw new dT(`Invalid token class key "${e}": a bare symbol is not a class key and none is derived from it. Pass "collection|category|type|additionalKey".`,"INVALID_TOKEN_IDENTIFIER");try{return hw(e)}catch{throw new dT(`Invalid token class key: ${e}`,"INVALID_TOKEN_IDENTIFIER")}}(t);return{...n,instance:e.instance??"0"}}function NT(e){const t=xT(e);return t?.Data??t?.data??e}function CT(e){if("string"==typeof e&&""!==e)return e;const t=xT(e);return _T(t,"transactionId")??_T(t,"txnId")??_T(t,"id")}function _T(e,t){const n=e?.[t];return"string"==typeof n&&""!==n?n:void 0}function xT(e){return"object"==typeof e&&null!==e?e:void 0}function RT(e){return`galaswap-operation-${r.v4()}-${Date.now()}-${e}`}function BT(e){return"eth|0x"===e.slice(0,6).toLowerCase()?`eth|${e.slice(6)}`:e}function DT(e,t){const n=e.headers;if(void 0===n)return;if("function"==typeof n.get)return OT(n.get(t));const r=t.toLowerCase();for(const[e,t]of Object.entries(n))if(e.toLowerCase()===r)return OT(t)}function OT(e){const t=e?.trim();return void 0===t||""===t?void 0:t}function MT(e,t=3e4){return c.create({baseURL:e,timeout:t,headers:{"Content-Type":"application/json"}})}const LT=new Set(["accesstoken","refreshtoken","token","password","privatekey","secret","apikey","api_key","rawkey","authorization","x-api-key","bearer","streamadminapikey","userapikey","signature","signedpayload"]);function UT(e,t=0){if(t>5)return"[...]";if(null==e)return e;if(Array.isArray(e))return e.map(e=>UT(e,t+1));if(e instanceof Map){const n={};for(const[r,s]of e.entries()){const e=String(r);n[e]=LT.has(e.toLowerCase())?"[REDACTED]":UT(s,t+1)}return n}if("object"==typeof e){const n={};for(const[r,s]of Object.entries(e))n[r]=LT.has(r.toLowerCase())?"[REDACTED]":UT(s,t+1);return n}return e}class PT{constructor(e,t={}){this.auth=e,this.debug=t.debug??!1,this.logger=new Jt({debug:this.debug,context:"HttpClient"});const n=t.baseUrl??so("stage").launchpadBaseUrl,r=t.timeout??6e4;this.axios=MT(n,r),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 Ji(async()=>{const t={method:e.method,url:e.url,data:e.data,...void 0!==e.params&&{params:Ai(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]":UT(e.data);this.logger.debug("Request:",{method:e.method,url:e.url?.split("?")[0],baseURL:this.axios.defaults.baseURL,params:UT(t.params),data:n,isFormData:e.data instanceof FormData,contentType:t.headers?.["Content-Type"]??"not set"});const r=await this.axios.request(t),s=function(e){const t={};if(null==e||"object"!=typeof e)return t;for(const[n,r]of Object.entries(e))"string"==typeof r?t[n.toLowerCase()]=r:"number"!=typeof r&&"boolean"!=typeof r||(t[n.toLowerCase()]=String(r));return t}(r.headers);return this.logger.debug("Response:",{status:r.status,data:UT(r.data),transactionId:s["x-transaction-id"],blockNumber:s["x-block-number"]}),{data:r.data,headers:s,status:r.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 Ji(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,r={message:n?.message??at(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=r,this.logger.error("Backend error:",r)}else void 0!==t.request?this.logger.error("Network error:",t.message??"Unknown error"):this.logger.error("Request setup error:",t.message??"Unknown error");return Promise.reject(e instanceof Error?e:new Error(String(e)))})}cleanup(){void 0!==this.requestInterceptorId&&(this.axios.interceptors.request.eject(this.requestInterceptorId),this.requestInterceptorId=void 0),void 0!==this.responseInterceptorId&&(this.axios.interceptors.response.eject(this.responseInterceptorId),this.responseInterceptorId=void 0),this.logger.debug("Interceptors cleaned up")}}class FT extends Error{constructor(e,t){super(e),this.cause=t,this.name="WebSocketError"}}class $T 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 KT(e,t){if(Wn(e))throw new FT(`Invalid WebSocket response received for transaction ${t}: response is null or undefined`);if("object"!=typeof e)throw new FT(`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 FT(`Invalid WebSocket response received for transaction ${t}: missing status field`)}function GT(e,t,n,r){KT(e,t);const s=e,i=s.data??{};if(!function(e){if(Wn(e)||"object"!=typeof e)return!1;const t=e;return!(void 0!==t.inputQuantity&&"string"!=typeof t.inputQuantity||void 0!==t.outputQuantity&&"string"!=typeof t.outputQuantity||void 0!==t.totalFees&&"string"!=typeof t.totalFees||void 0!==t.vaultAddress&&"string"!=typeof t.vaultAddress)}(i))throw new FT(`Invalid trade data received for transaction ${t}`);const o={transactionId:t,type:n,method:"native"===r.type?"native":"exact",inputAmount:i.inputQuantity??r.amount,outputAmount:i.outputQuantity??r.expectedAmount??"0",totalFees:i.totalFees??"0",tokenName:r.tokenName,vaultAddress:i.vaultAddress??"",timestamp:Date.now()};return void 0!==s.blockHash&&(o.blockHash=s.blockHash),void 0!==s.gasUsed&&(o.gasUsed=s.gasUsed),void 0!==r.slippageToleranceFactor&&(o.slippageTolerance=r.slippageToleranceFactor),o}function WT(e,t,n){return{types:{EIP712Domain:HT(e),...t},primaryType:Object.keys(t)[0],domain:qT(e),message:n}}function HT(e){const t=[];return void 0!==e.name&&t.push({name:"name",type:"string"}),void 0!==e.version&&t.push({name:"version",type:"string"}),void 0!==e.chainId&&t.push({name:"chainId",type:"uint256"}),void 0!==e.verifyingContract&&t.push({name:"verifyingContract",type:"address"}),void 0!==e.salt&&t.push({name:"salt",type:"bytes32"}),t}function qT(e){const t={};return void 0!==e.name&&(t.name=e.name),void 0!==e.version&&(t.version=e.version),void 0!==e.chainId&&(t.chainId="bigint"==typeof e.chainId||"number"==typeof e.chainId?`0x${e.chainId.toString(16)}`:e.chainId),void 0!==e.verifyingContract&&(t.verifyingContract=e.verifyingContract),void 0!==e.salt&&(t.salt=e.salt),t}function zT(e){return`0x${Buffer.from(e,"utf8").toString("hex")}`}class VT{constructor(t){this.connectedAddress=null,this.provider=t,this.eventHandlers=function(t,n,r){if(null==t||"function"!=typeof t.on)return{accountsChanged:null,disconnect:null};const s=t=>{const r=t[0];n(void 0===r?null:e.getAddress(r))},i=()=>r();return t.on("accountsChanged",s),t.on("disconnect",i),{accountsChanged:s,disconnect:i}}(t,e=>{this.connectedAddress=e},()=>{this.connectedAddress=null})}removeEventListeners(){!function(e,t){if("function"!=typeof e.removeListener)return;null!==t.accountsChanged&&e.removeListener("accountsChanged",t.accountsChanged);null!==t.disconnect&&e.removeListener("disconnect",t.disconnect)}(this.provider,this.eventHandlers)}}async function jT(e,t,n){try{return await e()}catch(e){if(e instanceof eo)throw e;return t(e,n)}}const XT=4001,YT=4100,JT=4900,QT=4901;class ZT extends VT{constructor(e){if(super(e),this.providerType="external",null==e)throw new eo("EIP-1193 provider is required",ji.INVALID_CONFIG)}handleProviderError(e,t){const n=e;if(n.code===XT)throw new eo(`User rejected ${t}`,ji.USER_REJECTED,e instanceof Error?e:void 0);if(n.code===YT)throw new eo("Wallet is not authorized",ji.NOT_CONNECTED,e instanceof Error?e:void 0);if(n.code===JT||n.code===QT)throw this.connectedAddress=null,new eo("Wallet disconnected",ji.NOT_CONNECTED,e instanceof Error?e:void 0);throw new eo(n.message??`${t} failed`,t.includes("sign")?ji.SIGNING_FAILED:ji.UNKNOWN,e instanceof Error?e:void 0)}ensureConnected(){if(!this.connectedAddress)throw new eo("Wallet is not connected. Call connect() first.",ji.NOT_CONNECTED)}async connect(){try{const t=await this.provider.request({method:"eth_requestAccounts"});if(null==t||0===t.length)throw new eo("No accounts returned from wallet",ji.CONNECTION_FAILED);const n=t[0];if(void 0===n)throw new eo("No accounts returned from wallet",ji.CONNECTION_FAILED);return this.connectedAddress=e.getAddress(n),this.connectedAddress}catch(e){if(e instanceof eo)throw e;return this.handleProviderError(e,"connect")}}async disconnect(){this.connectedAddress=null,this.removeEventListeners();try{await this.provider.request({method:"wallet_revokePermissions",params:[{eth_accounts:{}}]})}catch{}}isConnected(){return null!==this.connectedAddress}async signMessage(e){return this.ensureConnected(),jT(()=>async function(e,t,n){return e.request({method:"personal_sign",params:[zT(n),t]})}(this.provider,this.connectedAddress,e),(e,t)=>this.handleProviderError(e,t),"sign message")}async signTypedData(e,t,n){return this.ensureConnected(),jT(()=>async function(e,t,n,r,s){return e.request({method:"eth_signTypedData_v4",params:[t,JSON.stringify(WT(n,r,s))]})}(this.provider,this.connectedAddress,e,t,n),(e,t)=>this.handleProviderError(e,t),"sign typed data")}async getAddress(){await Promise.resolve(),this.ensureConnected();const e=this.connectedAddress;if(null==e)throw new eo("Wallet is not connected",ji.NOT_CONNECTED);return e}async getGalaAddress(){return`eth|${(await this.getAddress()).slice(2)}`}async getPrivateKey(){return Promise.reject(new eo("Private key is not accessible with external wallet providers. Use PrivateKeyProvider if you need private key access for @gala-chain operations.",ji.PRIVATE_KEY_NOT_ACCESSIBLE))}getProvider(){return this.provider}}function eI(e){return"privateKey"===e.providerType}function tI(e){if(e&&eI(e))return e.getWallet()}function nI(e){return"object"==typeof e&&null!==e&&"request"in e&&"function"==typeof e.request}const rI={MUSIC:"$MUSIC",GMUSIC:"$GMUSIC"};class sI{constructor(e){let n,r;this._tokenRoomRefCounts=new Map,this._tokenRoomListeners=new Map,this._tokenRoomUnsubscribers=new Map,e.walletProvider?(n=e.walletProvider,r=tI(e.walletProvider)):e.wallet&&(r=e.wallet,n=to.fromWallet(e.wallet)),this.wallet=r;const s=e.env??"prod",i=so(s);this.environment=s,this.config={baseUrl:e.launchpadBaseUrl??i.launchpadBaseUrl,gatewayBaseUrl:i.gatewayBaseUrl,bundleBaseUrl:i.bundleBaseUrl,webSocketUrl:i.webSocketUrl,gdexWebSocketUrl:i.gdexWebSocketUrl,dexApiBaseUrl:i.dexApiBaseUrl,dexBackendBaseUrl:i.dexBackendBaseUrl,launchpadFrontendUrl:i.launchpadFrontendUrl,timeout:3e4,debug:!1,...e};const o=e.signer??(void 0!==r?new oA(r.privateKey):void 0),a=e.walletAddress??e.galaChainAddress??(void 0!==r?`eth|${r.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}(o)),c=o??{signObject:()=>Promise.reject(new Error("A signer is required for token writes.")),signTypedData:()=>Promise.reject(new Error("A signer is required for launchpad writes."))},l=a??"",u=new gT({bundleBaseUrl:this.config.bundleBaseUrl,launchpadBaseUrl:this.config.baseUrl,signer:c,walletAddress:l,...void 0!==e.httpRequestor&&{httpRequestor:e.httpRequestor}});if(this.launchpad=new ST({transport:u,walletAddress:l}),this.tokens=new TT({gatewayBaseUrl:this.config.gatewayBaseUrl,dexBackendBaseUrl:this.config.dexBackendBaseUrl,signer:c,walletAddress:l,...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?sI.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR:this.parseSlippageToleranceFactor(e.slippageToleranceFactor),this.maxAcceptableReverseBondingCurveFeeSlippageFactor=void 0===e.maxAcceptableReverseBondingCurveFeeSlippageFactor?sI.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR:this.parseFeeSlippageFactor(e.maxAcceptableReverseBondingCurveFeeSlippageFactor),this.calculateAmountMode=e.calculateAmountMode??sI.DEFAULT_CALCULATE_AMOUNT_MODE,this.galaChainAddressOverride=e.galaChainAddress,this.signerWalletAddress=e.walletAddress??(void 0===r?a:void 0),this.auth=new no({wallet:r,walletProvider:n,messagePrefix:"Create a GalaChain Wallet"}),this.jwtAuth=new Yi,void 0!==e.accessToken&&""!==e.accessToken){const t=e.accessTokenExpiresIn??86400;this.jwtAuth.setToken(e.accessToken,t)}this.http=new PT(this.auth,this.config),this.sessionAuth=new Zi(this.http,this.auth,this.jwtAuth,e.debug??!1),this.galaChainHttp=new PT(this.auth,{...this.config,baseUrl:this.config.gatewayBaseUrl}),this.bundleHttp=new PT(this.auth,{...this.config,baseUrl:this.config.bundleBaseUrl}),this.dexApiHttp=new PT(this.auth,{...this.config,baseUrl:this.config.dexApiBaseUrl}),this.dexBackendHttp=new PT(this.auth,{...this.config,baseUrl:this.config.dexBackendBaseUrl}),this.galaChainPublicAxios=MT(this.config.gatewayBaseUrl,this.config.timeout??3e4),this.cache=new or(e.debug??!1),this.launchpadService=new KS(this.http,this.jwtAuth),this.tokenResolverService=new eT(this.launchpadService.poolService),this.launchpadAPI=new Hi(this.http,this.tokenResolverService,this.logger,this.bundleHttp,this.galaChainHttp,this.dexApiHttp,this.calculateAmountMode,this.launchpad),this.galaChainService=new ES(this.galaChainHttp,r,this.tokenResolverService,e.debug??!1,this.galaChainPublicAxios),this.dexService=new LA(this.dexBackendHttp,this.cache,this.galaChainService,e.debug??!1),this.bundleService=new fA(this.bundleHttp,this.tokenResolverService,this.config.debug??!1,r,r?this.getAddress():void 0,this.slippageToleranceFactor,this.maxAcceptableReverseBondingCurveFeeSlippageFactor),this.websocketService=new iT({url:this.config.webSocketUrl},this.config.debug),this.priceHistoryService=new _k(this.dexBackendHttp,this.config.debug??!1,this.tokenResolverService);const d=e.signer??(void 0===r?void 0:new oA(r.privateKey)),h=e.walletAddress??(void 0===r?void 0:this.getAddress());this.dexClient=new t.GSwap({env:this.environment,...void 0===d?{}:{signer:d},...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 lk(this.galaChainHttp),this.tradingQuotesService=new tT(this.http,e.debug??!1)}createOverrideSdk(t){if(!Kn(t))throw It("Invalid privateKey: must be a non-empty string","privateKey");if(!t.match(/^0x[a-fA-F0-9]{64}$/))throw It('Invalid privateKey format: must be "0x" followed by 64 hexadecimal characters',"privateKey");const n=new e.Wallet(t),r={...this.config,wallet:n};return new sI(r)}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 St("wallet","Wallet");return this.wallet}setWallet(e){if(null==e||"object"!=typeof e||!("address"in e))throw new yt("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?tI(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:r,streamAdminApiKey:s,userApiKey:i,accessToken:o,headers:a,...c}=this.config;return{...c,...void 0!==s&&{streamAdminApiKey:"[REDACTED]"},...void 0!==i&&{userApiKey:"[REDACTED]"},...void 0!==o&&{accessToken:"[REDACTED]"},...void 0!==a&&{headers:Object.fromEntries(Object.keys(a).map(e=>[e,"[REDACTED]"]))},environment:this.environment,slippageToleranceFactor:this.slippageToleranceFactor,maxAcceptableReverseBondingCurveFeeSlippageFactor:this.maxAcceptableReverseBondingCurveFeeSlippageFactor,calculateAmountMode:this.calculateAmountMode,gasFee:zt.GAS_FEE}}getVersion(){return nE}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),r=Math.min(t,100);return n.holders.slice(0,r).map((e,t)=>({...e,rank:t+1}))}async getHolderCount(e){const t=await this.fetchTokenDistribution(e);return{count:t.totalHolders,totalBalance:t.totalSupply}}async getHolderRank(e,t){const n=await this.fetchTokenDistribution(e),r=n.holders.findIndex(e=>e.address.toLowerCase()===t.toLowerCase());if(-1===r)return null;const s=n.holders[r];return void 0===s?null:{rank:r+1,balance:s.balance,holderCount:n.totalHolders}}async getHoldersByBalance(e,t){const n=await this.fetchTokenDistribution(e),r=t?.minBalance??0,s=t?.maxBalance??1/0,i=Math.min(t?.limit??100,1e3),o=new Map;return n.holders.forEach((e,t)=>{o.set(e.address,t+1)}),n.holders.filter(e=>{const t=parseFloat(e.balance);return t>=r&&t<=s}).map(e=>({...e,rank:o.get(e.address)??0})).slice(0,i)}async getHolderHistory(e,t,n=20){return this.getTrades({tokenName:e,userAddress:t,pageSize:Math.min(n,100)})}async fetchUserHolderContext(e,t){return this.launchpadService.fetchUserHolderContext(e,t)}async fetchTokenPrice(e){const{tokenName:t,tokenId:n}=e,{hasA:r}=Vn(e,"tokenName","tokenId",{description:"token identifier"});if(r&&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(ut(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=Vt((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: ${at(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(pt(e));const n=(await this.galaChainService.fetchPoolDetails({vaultAddress:t})).Data,r=await this.launchpadAPI.fetchPoolDetailsForCalculation(e);return n.currentSupply=r.currentSupply,n.reverseBondingCurveMaxFeeFactor=r.reverseBondingCurveMaxFeeFactor,n.reverseBondingCurveMinFeeFactor=r.reverseBondingCurveMinFeeFactor,n.reverseBondingCurveNetFeeFactor=r.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 vr}),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 Qw({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 qE(this.dexApiHttp,this.config.debug??!1)),this._bridgeableTokenService}getWrappableTokenService(){return this._wrappableTokenService??(this._wrappableTokenService=new lT(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 _w({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 uT({galaConnectClient:this.getGalaConnectClient(),wrappableTokenService:this.getWrappableTokenService(),...e&&{walletAddress:this.getAddress(),wallet:e}})}return this._wrapService}getStreamingService(){return this._streamingService??(this._streamingService=new qk(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._streamingService}getStreamChatService(){return this._streamChatService??(this._streamChatService=new Rk(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._streamChatService}getBanService(){return this._banService??(this._banService=new BE(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._banService}getTokenBanService(){return this._tokenBanService??(this._tokenBanService=new Zk(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._tokenBanService}getAIModerationService(){return this._aiModerationService??(this._aiModerationService=new dE(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._aiModerationService}getWeeklyChallengeService(){return this._weeklyChallengeService??(this._weeklyChallengeService=new oT(this.http,this.config.debug??!1)),this._weeklyChallengeService}getOEmbedService(){return this._oembedService??(this._oembedService=new dk(this.http,this.config.debug??!1)),this._oembedService}getPlatformStatsService(){return this._platformStatsService??(this._platformStatsService=new Ck(this.http,this.config.debug??!1)),this._platformStatsService}getNotificationService(){return this._notificationService??(this._notificationService=new uk(this.http,this.config.debug??!1,this.jwtAuth)),this._notificationService}getClientConfigService(){return this._clientConfigService??(this._clientConfigService=new pA(this.http,this.config.debug??!1)),this._clientConfigService}getApiKeyService(){return this._apiKeyService??(this._apiKeyService=new AE(this.http,this.jwtAuth,this.config.debug??!1)),this._apiKeyService}getModeratorService(){return this._moderatorService??(this._moderatorService=new nk(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._moderatorService}getFlagService(){return this._flagService??(this._flagService=new BA(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._flagService}getOverseerService(){return this._overseerService??(this._overseerService=new Tk(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._overseerService}getWebSocketAdminService(){return this._websocketAdminService??(this._websocketAdminService=new nT(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._websocketAdminService}getContentReactionService(){return this._contentReactionService??(this._contentReactionService=new OA(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 vr}),n=t(e);if(void 0===n)throw new yt(`Invalid address format: "${e}". Expected formats: eth|0x..., 0x..., or client|...`);return n}getMessagesService(){return this._messagesService??(this._messagesService=new GS(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._messagesService}getRestrictedNamesService(){return this._restrictedNamesService??(this._restrictedNamesService=new xk(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.userApiKey)),this._restrictedNamesService}getPlatformConfigService(){return this._platformConfigService??(this._platformConfigService=new Nk(this.http,this.jwtAuth,this.config.debug??!1)),this._platformConfigService}getEventsBatcherService(){return this._eventsBatcherService??(this._eventsBatcherService=new PA(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 Vk({url:this.config.streamWebSocketUrl},this.config.debug??!1),this._streamWebSocketService.setStreamingEventService(this.getStreamingEventService())}return this._streamWebSocketService}getGdexStreamService(){return this._gdexStreamService??(this._gdexStreamService=new kS({url:this.config.gdexWebSocketUrl})),this._gdexStreamService}getStreamingEventService(){return this._streamingEventService??(this._streamingEventService=new Bk(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 r=await n.getPinnedMessage(e);return{tokenName:e,pinnedMessage:null===r.message?null:this.toLegacyPinnedMessage(r.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 getActiveModerators(e){return(await this.listModeratorInvites({tokenName:e,status:"CLAIMED"})).items.filter(e=>null!==e.claimedBy).map(e=>({address:e.claimedBy,role:e.role,joinedAt:e.claimedAt,inviteId:e.id}))}async revokeModeratorInvite(e){return this.getModeratorService().revokeInvite(e)}async updateModeratorInviteRole(e){return this.getModeratorService().updateInviteRole(e)}async updateModeratorInvite(e){return this.getModeratorService().updateInvite(e)}async getModeratorInviteByCode(e){return this.getModeratorService().getInviteByCode(e)}async createFlag(e){return this.getFlagService().createFlag(e)}async listFlags(e){return this.getFlagService().listFlags(e)}async listGlobalFlags(e={}){return this.getFlagService().listGlobalFlags(e)}async dismissFlag(e){return this.getFlagService().dismissFlag(e)}async actionFlag(e){return this.getFlagService().actionFlag(e)}async createOverseerInvite(e={}){return this.getOverseerService().createInvite(e)}async listOverseerInvites(e={}){return this.getOverseerService().listInvites(e)}async getOverseerInviteByCode(e){return this.getOverseerService().getInviteByCode(e)}async claimOverseerInvite(e){return this.getOverseerService().claimInvite(e)}async revokeOverseerInvite(e){return this.getOverseerService().revokeInvite(e)}async listOverseers(e={}){return this.getOverseerService().listOverseers(e)}async createOverseerDirect(e){return this.getOverseerService().createOverseerDirect(e)}async revokeOverseer(e){return this.getOverseerService().revokeOverseer(e)}async getMyOverseerStatus(){return this.getOverseerService().getMyStatus()}async getOverseerSummary(){return this.getOverseerService().getSummary()}async getBanStats(){return this.getOverseerService().getBanStats()}async getTokenBanStats(){return this.getOverseerService().getTokenBanStats()}async getInviteStats(){return this.getOverseerService().getInviteStats()}async getFlagStats(){return this.getOverseerService().getFlagStats()}async getUserStats(){return this.getOverseerService().getUserStats()}async listOverseerUsers(e){return this.getOverseerService().listOverseerUsers(e)}async getOverseerUserSummary(e){return this.getOverseerService().getOverseerUserSummary(e)}async flushCacheByAddress(e){return this.getOverseerService().flushCacheByAddress(e)}async flushCacheByToken(e){return this.getOverseerService().flushCacheByToken(e)}async flushAllCache(e){return this.getOverseerService().flushAllCache(e)}async flushWalletAliasCache(e){return this.getOverseerService().flushWalletAliasCache(e)}async emitWebSocketEvent(e){return this.getWebSocketAdminService().emitEvent(e)}async emitTradeExecuted(e,t){return this.getWebSocketAdminService().emitTradeExecuted(e,t)}async emitBalanceUpdated(e,t,n){return this.getWebSocketAdminService().emitBalanceUpdated(e,t,n)}async emitStreamStatus(e,t){return this.getWebSocketAdminService().emitStreamStatus(e,t)}async emitViewerCount(e,t){return this.getWebSocketAdminService().emitViewerCount(e,t)}async emitStreamCountdown(e,t){return this.getWebSocketAdminService().emitStreamCountdown(e,t)}async emitChatMessage(e,t){return this.getWebSocketAdminService().emitChatMessage(e,t)}async emitChatStatus(e,t){return this.getWebSocketAdminService().emitChatStatus(e,t)}async emitTypingIndicator(e,t){return this.getWebSocketAdminService().emitTypingIndicator(e,t)}async emitTokenBanned(e,t){return this.getWebSocketAdminService().emitTokenBanned(e,t)}async emitTokenUnbanned(e,t){return this.getWebSocketAdminService().emitTokenUnbanned(e,t)}async emitModeratorAdded(e,t){return this.getWebSocketAdminService().emitModeratorAdded(e,t)}async emitModeratorRemoved(e,t){return this.getWebSocketAdminService().emitModeratorRemoved(e,t)}async emitUserProfileUpdated(e,t){return this.getWebSocketAdminService().emitUserProfileUpdated(e,t)}async emitSiteConfigChanged(e){return this.getWebSocketAdminService().emitSiteConfigChanged(e)}async emitFeatureStatus(e){return this.getWebSocketAdminService().emitFeatureStatus(e)}async emitRecordingStatus(e,t){return this.getWebSocketAdminService().emitRecordingStatus(e,t)}async emitRecordingsCountUpdated(e,t){return this.getWebSocketAdminService().emitRecordingsCountUpdated(e,t)}async emitDownloadReady(e,t){return this.getWebSocketAdminService().emitDownloadReady(e,t)}async getConnectedClients(e){return this.getWebSocketAdminService().getConnectedClients(e)}async isUserOnline(e){return this.getWebSocketAdminService().isUserOnline(e)}async getOnlineUsers(e){return this.getWebSocketAdminService().getOnlineUsers(e)}async getTokenViewers(e,t){return this.getWebSocketAdminService().getTokenViewers(e,t)}async getOnlineOverseers(){return this.getWebSocketAdminService().getOnlineOverseers()}async banToken(e){return this.getTokenBanService().banToken(e)}async unbanToken(e){return this.getTokenBanService().unbanToken(e)}async listTokenBans(e={}){return this.getTokenBanService().listTokenBans(e)}async getTokenBan(e){return this.getTokenBanService().getTokenBan(e)}async isTokenBanned(e){return this.getTokenBanService().isTokenBanned(e)}async getAIModerationSettings(){return this.getAIModerationService().getSettings()}async updateAIModerationSettings(e){return this.getAIModerationService().updateSettings(e)}async getAIModeration(e){return this.getAIModerationService().getModeration(e)}async triggerAIModeration(e){return this.getAIModerationService().triggerModeration(e)}async getAIModerationStatus(){return this.getAIModerationService().getStatus()}async getWeeklyChallengeLeaderboard(e={}){return this.getWeeklyChallengeService().getLeaderboard(e)}async getTokenWeeklyHistory(e){return this.getWeeklyChallengeService().getTokenHistory(e)}async getHomeOEmbed(e={}){return this.getOEmbedService().getHomeOEmbedJson(e)}async getPoolOEmbed(e){return this.getOEmbedService().getPoolOEmbedJson(e)}async getProfileOEmbed(e){return this.getOEmbedService().getProfileOEmbedJson(e)}async getPlatformStats(){return this.getPlatformStatsService().getStats()}async 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 getTokenConfig(e){return this.launchpadService.poolService.getTokenConfig(e)}async getTrades(e){return this.launchpadService.getTrades(e)}async getRecentTrades(e,t=50){return this.getTrades({...void 0!==e&&{tokenName:e},pageSize:Math.min(t,500)})}async getPoolRealtimeState(e){const[t,n,r,s]=await Promise.allSettled([this.getHolderCount(e),this.getTokenConfig(e),this.getRecentTrades(e,10),this.fetchTokenPrice({tokenName:e})]);return{tokenName:e,holderCount:"fulfilled"===t.status?t.value:null,..."rejected"===t.status&&{holderCountError:String(t.reason)},chatConfig:"fulfilled"===n.status?n.value:null,..."rejected"===n.status&&{chatConfigError:String(n.reason)},recentTrades:"fulfilled"===r.status?r.value:null,..."rejected"===r.status&&{recentTradesError:String(r.reason)},price:"fulfilled"===s.status?s.value:null,..."rejected"===s.status&&{priceError:String(s.reason)}}}async fetchLaunchpadFee(){return this.tradingQuotesService.fetchLaunchpadFee()}async fetchSaleDetails(e){return this.tradingQuotesService.fetchSaleDetails(e)}async getTradeQuote(e){return this.tradingQuotesService.getTradeQuote(e)}async getPremintQuote(e){return this.tradingQuotesService.getPremintQuote(e)}async connectStreamWebSocket(e){const t=this.getStreamWebSocketService();await t.connect(),e&&t.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)}watchBanEnforcement(e,t={}){const n=(e,n,r,s)=>(void 0===t.actionType||t.actionType===e)&&((void 0===t.userAddress||t.userAddress===n)&&((void 0===t.tokenName||t.tokenName===r)&&!!(void 0===t.reason||null!==s&&s.includes(t.reason)))),r=this.onUserBanned(t=>{n("BANNED",t.userAddress,t.tokenName,t.reason)&&e({actionType:"BANNED",userAddress:t.userAddress,tokenName:t.tokenName,reason:t.reason})}),s=this.onUserUnbanned(t=>{n("UNBANNED",t.userAddress,t.tokenName,null)&&e({actionType:"UNBANNED",userAddress:t.userAddress,tokenName:t.tokenName,reason:null,timestamp:t.timestamp})}),i=this.onBanEnforcement(t=>{n("ENFORCEMENT",t.userAddress,t.tokenName,t.reason)&&e({actionType:"ENFORCEMENT",userAddress:t.userAddress,tokenName:t.tokenName,reason:t.reason,timestamp:t.timestamp})});return()=>{r(),s(),i()}}watchTokenRoomEvent(e,t,n,r){const s=r.tokenName;if(void 0===s||""===s)throw new Error(`${e} requires a tokenName filter - these are per-token stream events with no way to watch every token at once.`);const i=s.toLowerCase(),o=`${e}:${i}`,a=n;let c=this._tokenRoomListeners.get(o);const l=void 0===c;void 0===c&&(c=new Set,this._tokenRoomListeners.set(o,c)),c.add(a),this._tokenRoomRefCounts.set(i,(this._tokenRoomRefCounts.get(i)??0)+1);const u=this.getStreamWebSocketService(),d=(async()=>{u.isConnected()||await this.connectStreamWebSocket(),await u.subscribeToStream(i),l&&this._tokenRoomUnsubscribers.set(o,t.call(u,i,e=>{for(const t of c)t(e)}))})();let h=!1;return()=>{if(h)return;h=!0,c.delete(a);const e=(this._tokenRoomRefCounts.get(i)??1)-1,t=e<=0;t?this._tokenRoomRefCounts.delete(i):this._tokenRoomRefCounts.set(i,e),d.then(()=>{if(0===c.size){this._tokenRoomListeners.delete(o);const e=this._tokenRoomUnsubscribers.get(o);this._tokenRoomUnsubscribers.delete(o),e?.()}t&&!this._tokenRoomRefCounts.has(i)&&u.unsubscribeFromStream(i)})}}watchCommentCreated(e,t={}){return this.watchTokenRoomEvent("watchCommentCreated",(e,t)=>this.getStreamWebSocketService().subscribeCommentCreated(e,t),n=>{void 0!==t.authorAddress&&t.authorAddress!==n.userAddress||void 0!==t.minLength&&n.content.length<t.minLength||e(n)},t)}watchHolderCountUpdated(e,t={}){return this.watchTokenRoomEvent("watchHolderCountUpdated",(e,t)=>this.getStreamWebSocketService().subscribeHolderCountUpdated(e,t),n=>{void 0!==t.minThreshold&&Math.abs(n.change??0)<t.minThreshold||e(n)},t)}watchModeratorAdded(e,t={}){return this.watchTokenRoomEvent("watchModeratorAdded",(e,t)=>this.getStreamWebSocketService().subscribeModeratorAdded(e,t),e,t)}watchPoolMetadataUpdated(e,t={}){return this.watchTokenRoomEvent("watchPoolMetadataUpdated",(e,t)=>this.getStreamWebSocketService().subscribePoolMetadataUpdated(e,t),e,t)}watchTradeExecuted(e,t={}){return this.watchTokenRoomEvent("watchTradeExecuted",(e,t)=>this.getStreamWebSocketService().subscribeTradeExecuted(e,t),n=>{void 0!==t.tradeType&&t.tradeType!==n.tradeType||void 0!==t.userAddress&&t.userAddress!==n.userAddress||void 0!==t.minAmount&&Number(n.inputAmount)<t.minAmount||e(n)},t)}watchTokenBanned(e,t={}){return this.watchTokenRoomEvent("watchTokenBanned",(e,t)=>this.getStreamWebSocketService().subscribeTokenBanned(e,t),e,t)}watchModeratorChanged(e,t={}){const n=(e,n)=>(void 0===t.eventType||t.eventType===e)&&(void 0===t.moderatorAddress||t.moderatorAddress===n),r=this.watchModeratorAdded(t=>{n("ADDED",t.userAddress)&&e({actionType:"ADDED",tokenName:t.tokenName,moderatorAddress:t.userAddress,role:t.role})},t),s=this.watchTokenRoomEvent("watchModeratorRemoved",(e,t)=>this.getStreamWebSocketService().subscribeModeratorRemoved(e,t),t=>{n("REMOVED",t.userAddress)&&e({actionType:"REMOVED",tokenName:t.tokenName,moderatorAddress:t.userAddress})},t),i=this.watchTokenRoomEvent("watchModeratorRoleUpdated",(e,t)=>this.getStreamWebSocketService().subscribeModeratorRoleUpdated(e,t),t=>{n("ROLE_UPDATED",t.userAddress)&&e({actionType:"ROLE_UPDATED",tokenName:t.tokenName,moderatorAddress:t.userAddress,oldRole:t.oldRole,newRole:t.newRole})},t);return()=>{r(),s(),i()}}watchPoolUpdated(e,t={}){const n=e=>void 0===t.updateType||t.updateType===e,r=this.watchPoolMetadataUpdated(t=>{n("METADATA")&&e({updateType:"METADATA",tokenName:t.tokenName,details:t})},t),s=this.watchTokenRoomEvent("watchPoolSocialLinksUpdated",(e,t)=>this.getStreamWebSocketService().subscribePoolSocialLinksUpdated(e,t),t=>{n("SOCIAL_LINKS")&&e({updateType:"SOCIAL_LINKS",tokenName:t.tokenName,details:t})},t),i=this.watchTokenRoomEvent("watchPoolBadgeAssigned",(e,t)=>this.getStreamWebSocketService().subscribePoolBadgeAssigned(e,t),t=>{n("BADGE_ASSIGNED")&&e({updateType:"BADGE_ASSIGNED",tokenName:t.tokenName,details:t})},t);return()=>{r(),s(),i()}}watchTokenBanChanged(e,t={}){const n=e=>void 0===t.banStatus||t.banStatus===e,r=this.watchTokenBanned(t=>{n("BANNED")&&e({banStatus:"BANNED",tokenName:t.tokenName,reason:t.reason})},t),s=this.watchTokenRoomEvent("watchTokenUnbanned",(e,t)=>this.getStreamWebSocketService().subscribeTokenUnbanned(e,t),t=>{n("UNBANNED")&&e({banStatus:"UNBANNED",tokenName:t.tokenName})},t);return()=>{r(),s()}}onDexPoolCreation(e,t={}){const n=t.intervalMs??3e4;let r,s=!1;const i=async()=>{let n;try{n=await this.dex.pools.getPools()}catch{return}if(!s)if(void 0!==r)for(const s of n)r.has(s.poolRef)||(r.add(s.poolRef),void 0!==t.minTVL&&(s.tvlUsd??0)<t.minTVL||(void 0===t.tokens||t.tokens.includes(s.token0)||t.tokens.includes(s.token1))&&e({poolRef:s.poolRef,token0:s.token0,token1:s.token1,fee:s.fee,tvlUsd:s.tvlUsd}));else r=new Set(n.map(e=>e.poolRef))};i();const o=setInterval(()=>{i()},n);return()=>{s=!0,clearInterval(o)}}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 vr}),n=t(e.address);if(void 0!==e.tokenId&&""!==e.tokenId){const{normalizeToTokenInstanceKey:t}=await Promise.resolve().then(function(){return $E}),r=t(e.tokenId),{collection:s,category:i,type:o,additionalKey:a}=r;return this.galaChainService.fetchTokenBalance({owner:n,collection:s,category:i,additionalKey:a,type:o,instance:"0"},e.withExpired??!1)}if(void 0!==e.tokenName&&""!==e.tokenName){const t=Xt(e.tokenName),r=rI[t];if(void 0!==r)return this.galaChainService.fetchTokenBalance({owner:n,collection:r,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 r=await this.resolveTokenClassKey(e.tokenName);return{quantity:t.balance,collection:r.collection,category:r.category,tokenId:io(r)}}throw St("tokenId or tokenName","Either tokenId or tokenName")}async fetchLockedBalance(e){const t=await this.fetchTokenBalance(e);if(!t)return null;const n="lockedHolds"in t||"lockedQuantity"in t;return{tokenId:t.tokenId,lockedQuantity:n?t.lockedQuantity??"0":"0",lockedHolds:n?t.lockedHolds??[]:[]}}async fetchAvailableBalance(e){const t=await this.fetchTokenBalance(e);if(!t)return null;const n="availableQuantity"in t;return{tokenId:t.tokenId,availableQuantity:n?t.availableQuantity??String(t.quantity):String(t.quantity),totalQuantity:String(t.quantity)}}async calculateBuyAmount(e){return this.launchpadAPI.calculateBuyAmount(e)}async calculateSellAmount(e){return this.launchpadAPI.calculateSellAmount(e)}async calculateBuyAmountLocal(e){return this.launchpadAPI.calculateBuyAmountLocal(e)}async calculateSellAmountLocal(e){return this.launchpadAPI.calculateSellAmountLocal(e)}async calculateBuyAmountExternal(e){return this.launchpadAPI.calculateBuyAmountExternal(e)}async calculateSellAmountExternal(e){return this.launchpadAPI.calculateSellAmountExternal(e)}async calculateBuyAmountForGraduation(e){return this.launchpadAPI.calculateBuyAmountForGraduation(e)}async graduateToken(e){const{tokenName:t,slippageToleranceFactor:n,maxAcceptableReverseBondingCurveFeeSlippageFactor:r,privateKey:s,calculateAmountMode:i,currentSupply:o}=e;let a=t;void 0===i&&void 0===o||(a={tokenName:t,...void 0!==i&&{calculateAmountMode:i},...void 0!==o&&{currentSupply:o}});const c=await this.calculateBuyAmountForGraduation(a),l={tokenName:t,amount:c.amount,type:"exact",expectedAmount:c.amount,maxAcceptableReverseBondingCurveFee:c.reverseBondingCurveFee,slippageToleranceFactor:this.slippageToleranceFactor};return void 0!==n&&(l.slippageToleranceFactor=n),void 0!==r&&(l.maxAcceptableReverseBondingCurveFeeSlippageFactor=r),void 0!==s&&(l.privateKey=s),await this.buy(l)}async calculateInitialBuyAmount(e){const t={nativeTokenQuantity:e};return this.launchpadAPI.calculateInitialBuyAmount(t)}async buy(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...r}=e;return t.buy(r)}this.validateWallet(),await this.ensureWebSocketConnection();const t=(await this.bundleService.buyToken(e)).data,n=t?.transactionId;if(void 0===n||""===n)throw Nt("No transaction ID returned from buy operation");return this.waitForConfirmation(n,t=>GT(t,n,"buy",e))}async sell(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...r}=e;return t.sell(r)}this.validateWallet(),await this.ensureWebSocketConnection();const t=(await this.bundleService.sellToken(e)).data,n=t?.transactionId;if(void 0===n||""===n)throw Nt("No transaction ID returned from sell operation");return this.waitForConfirmation(n,t=>GT(t,n,"sell",e))}async getBundlerTransactionResult(e){return this.bundleService.getBundlerTransactionResult(e)}async launchToken(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...r}=e;return t.launchToken(r)}this.validateWallet(),await this.ensureWebSocketConnection();const t=await this.launchpadAPI.launchToken(e);return this.waitForConfirmation(t,n=>{KT(n,t);const r=n.data??{};if(!function(e){if(Wn(e)||"object"!=typeof e)return!1;const t=e;return!(void 0!==t.vaultAddress&&"string"!=typeof t.vaultAddress||void 0!==t.tokenStringKey&&"string"!=typeof t.tokenStringKey||void 0!==t.creatorAddress&&"string"!=typeof t.creatorAddress)}(r))throw new FT(`Invalid launch data received for transaction ${t}`);const s={transactionId:t,vaultAddress:r.vaultAddress??"",tokenStringKey:r.tokenStringKey??"",tokenName:e.tokenName,tokenSymbol:e.tokenSymbol,creatorAddress:r.creatorAddress??this.getAddress(),timestamp:Date.now(),...void 0!==n.blockHash&&""!==n.blockHash?{blockHash:n.blockHash}:{},...void 0!==n.gasUsed?{gasUsed:n.gasUsed}:{}};return"string"==typeof e.tokenImage&&(s.tokenImage=e.tokenImage),void 0!==e.preBuyQuantity&&(s.preBuyQuantity=e.preBuyQuantity),""!==s.vaultAddress&&this.tokenResolverService.set(e.tokenName,s.vaultAddress),s})}async uploadTokenImage(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...r}=e;return t.uploadTokenImage(r)}return this.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 vr}),n=t(e)??this.getAddress();return this.launchpadService.fetchProfile(n)}async fetchReferralUrl(){this.validateWallet();const e=this.getAddress();return await this.dexApiHttp.get(v,void 0,{"x-wallet-address":e})}async fetchReferrals(e){const t=await this.resolveReferralAddress(e?.address),n=e?.page??1,r=e?.limit??10,s={pageNumber:n,limit:r,sortBy:e?.sortBy??"joined",sortDir:e?.sortDir??"desc"},i=await this.dexApiHttp.get(w,s,{"x-wallet-address":t});if(!Array.isArray(i))throw new bt("Unexpected API response: expected array, got "+typeof i);return{referrals:i,page:n,limit:r,hasMore:i.length===r}}async fetchAllReferrals(e){const t=await OE((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(E,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 vr}),n={...e,address:t(e.address)};if(void 0!==n.privateKey&&""!==n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...r}=n;return e.updateProfile(r)}return this.validateWallet(),this.launchpadService.updateProfile(n)}async uploadProfileImage(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return vr}),n={...e,address:t(e.address)??this.getAddress()};if(void 0!==n.privateKey&&""!==n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...r}=n;return e.uploadProfileImage(r)}return this.validateWallet(),this.launchpadService.uploadProfileImage(n)}async fetchTokensHeld(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return vr}),n=t(e?.address)??this.getAddress(),r={pageSize:e?.pageSize??10,address:n,...void 0!==e?.cursor?{cursor:e.cursor}:{}};return void 0!==e?.tokenName&&""!==e.tokenName&&(r.tokenName=e.tokenName),void 0!==e?.search&&""!==e.search&&(r.search=e.search),this.launchpadService.fetchTokensHeld(r)}async fetchTokensCreated(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return vr}),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 vr}),n={...e,recipientAddress:t(e.recipientAddress)};if(void 0!==n.privateKey&&""!==n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...r}=n;return e.transferGala(r)}return this.validateWallet(),this.galaChainService.transferGala(n)}async transferToken(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return vr}),n={...e,to:t(e.to)};if(void 0!==n.privateKey&&""!==n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...r}=n;return e.transferToken(r)}return this.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 vr});return{...e,lockAuthority:t(e.lockAuthority)}}return e})),n={...e,tokens:t};if(void 0!==n.privateKey&&""!==n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...r}=n;return e.lockTokens(r)}return this.validateWallet(),this.galaChainService.lockTokens(n)}async unlockTokens(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...r}=e;return t.unlockTokens(r)}return this.validateWallet(),this.galaChainService.unlockTokens(e)}async burnTokens(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...r}=e;return t.burnTokens(r)}return this.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{On(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=In("string"==typeof e||"number"==typeof e?e:String(e),sI.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR);return t<0||t>1?(this.logger.warn(`Invalid slippage tolerance factor: ${String(e)}, using default: ${sI.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR}`),sI.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR):t}parseFeeSlippageFactor(e){const t=In("string"==typeof e||"number"==typeof e?e:String(e),sI.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: ${sI.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR}`),sI.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR):t}async ensureWebSocketConnection(){this.websocketService.isConnected()||(await this.websocketService.connect(),this.logger.debug("WebSocket connection established"))}async waitForConfirmation(e,t){this.logger.debug(`Waiting for confirmation of transaction: ${e}`);try{const n=await this.websocketService.waitForTransaction(e);if(n.status!==exports.SDKTransactionStatus.COMPLETED)throw new $T(e,n.status,n.message);let r;try{r=t(n)}catch(t){if(t instanceof FT)throw t;throw new FT(`Failed to transform WebSocket response for transaction ${e}`,ot(t)?t:new Error(at(t)))}return this.logger.debug(`Transaction confirmed: ${e}`,r),r}catch(t){if(this.logger.error(`Transaction confirmation failed: ${e}`,t),t instanceof $T||t instanceof FT)throw t;throw new FT(`WebSocket confirmation failed for transaction ${e}`,ot(t)?t:new Error(at(t)))}}async warmCacheFromPools(e){if(void 0===e||!Array.isArray(e))return;const{extractMetadataFromPoolData:t,isValidPoolForCaching:n}=await Promise.resolve().then(function(){return tN});e.forEach(e=>{if(!n(e))return;const r=t(e,this.logger);r&&this.launchpadAPI.warmCacheFromPoolData(e.tokenName,r)})}connectWebSocket(){this.websocketService.connect()}disconnectWebSocket(){this.websocketService.disconnect()}isWebSocketConnected(){return this.websocketService.isConnected()}subscribeToEvent(e,t){const n=this.websocketService.getSocket();return n?(n.on(e,t),()=>{n.off(e,t),this.logger.debug(`Unsubscribed from event: "${e}"`)}):(this.logger.warn(`⚠️ WebSocket not connected - subscribing to "${e}" without connection`),()=>{})}onLaunchpadTokenCreation(e,t){const n=1e3,r=Math.max(t?.intervalMs??3e4,n);null!=t?.intervalMs&&t.intervalMs<n&&this.logger.warn(`Poll interval ${t.intervalMs}ms is below minimum 1000ms. Using minimum interval instead.`);const s=t?.creatorAddress,i=new Map;let o=!0,a=null;let c=0;const l=async()=>{if(o){try{const t=await this.fetchPools({type:"recent",pageSize:20});c>0&&(this.logger.debug("Successfully recovered from polling errors"),c=0),t.items.forEach(t=>{i.has(t.tokenName)||((e=>{if(i.set(e,!0),i.size>1e3){const e=i.keys().next().value;void 0!==e&&i.delete(e)}})(t.tokenName),void 0!==s&&""!==s&&t.creatorAddress!==s||e(t))})}catch(e){c++;const t=at(e);c>=5?this.logger.error(`Polling for new launchpad tokens failed ${c} consecutive times. Last error: ${t}. Continuing to retry...`):c>1?this.logger.warn(`Error polling for new launchpad tokens (attempt ${c}/5): ${t}`):this.logger.debug(`Error polling for new launchpad tokens: ${t}`)}if(o){const e=Math.min(Math.max(c-1,0),2),t=r*Math.pow(2,e);a=setTimeout(()=>{l()},t)}}};return l(),()=>{o=!1,a&&clearTimeout(a),this.logger.debug("Stopped watching for launchpad token creation")}}matchesCreatorFilter(e,t){return void 0===t||""===t||e.creatorAddress===t}subscribeToTokenCreations(e,t){if(this.logger.debug("Subscribing to token creation broadcasts"+(void 0!==t?.creatorFilter&&""!==t.creatorFilter?` (filter: ${t.creatorFilter})`:"")),null===this.websocketService||void 0===this.websocketService)throw It("WebSocket service not initialized. Ensure websocketUrl is configured and the service is connected.","websocketService");let n=!1,r=null;const s=(n,...r)=>{try{if(r.length>0&&"object"==typeof r[0]&&null!==r[0]){const n=r[0].data;if(void 0!==n?.Data&&null!==n.Data&&"object"==typeof n.Data){const r=n.Data;if("CreateSale"===r.functionName){const n={tokenName:""!==r.tokenName?r.tokenName:"",symbol:""!==r.symbol?r.symbol:"",creatorAddress:""!==r.creatorAddress?r.creatorAddress:"",description:""!==r.description?r.description:"",image:""!==r.image?r.image:"",vaultAddress:""!==r.vaultAddress?r.vaultAddress:"",tokenStringKey:""!==r.tokenStringKey?r.tokenStringKey:"",preBuyQuantity:""!==r.initialBuyQuantity?r.initialBuyQuantity:"0",websiteUrl:""!==r.websiteUrl?r.websiteUrl:"",telegramUrl:""!==r.telegramUrl?r.telegramUrl:"",twitterUrl:""!==r.twitterUrl?r.twitterUrl:"",instagramUrl:""!==r.instagramUrl?r.instagramUrl:"",facebookUrl:""!==r.facebookUrl?r.facebookUrl:"",redditUrl:""!==r.redditUrl?r.redditUrl:"",tiktokUrl:""!==r.tiktokUrl?r.tiktokUrl:"",isFinalized:!1!==r.isFinalized&&null!==r.isFinalized&&void 0!==r.isFinalized&&r.isFinalized};this.matchesCreatorFilter(n,t?.creatorFilter)&&e(n)}}}}catch(e){this.logger.warn(`Error processing token creation broadcast: ${at(e)}`)}};let i=this.websocketService.getSocket();if(i)i.onAny(s),n=!0,this.logger.debug("Token creation broadcast listener registered");else{this.logger.debug("WebSocket not yet connected, initiating connection..."),this.websocketService.connect().catch(e=>{const n=new Error(`WebSocket connection failed: ${at(e)}`);this.logger.warn("Failed to establish WebSocket connection:",e),t?.onError&&t.onError(n)});let e=0;const o=()=>{if(i=this.websocketService.getSocket(),!i&&e<sI.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS)return e++,void(r=setTimeout(()=>o(),sI.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS));if(!i&&e>=sI.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS){const e=new Error(`WebSocket not available after ${sI.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS*sI.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS}ms`);return this.logger.warn("Token creation broadcast subscription timeout:",e.message),void(t?.onError&&t.onError(e))}i&&(i.onAny(s),n=!0,this.logger.debug("Token creation broadcast listener registered"))};o()}return()=>{try{if(null!==r&&(clearTimeout(r),r=null,this.logger.debug("Cleared token creation broadcast polling timeout")),!n)return void this.logger.debug("Cleanup called before listener registration - no action needed");const e=this.websocketService.getSocket();e&&(e.offAny(s),n=!1,this.logger.debug("Stopped listening to token creation broadcasts"))}catch(e){this.logger.warn("Error removing token creation listener:",e)}}}getNftCollectionClaimFee(){return this.nftCollectionService.getCollectionClaimFee()}getNftTokenClassCreateFee(){return this.nftCollectionService.getTokenClassCreateFee()}estimateNftMintFee(e){return this.nftCollectionService.estimateMintFee(e)}estimateNftOperationFees(e){return this.nftCollectionService.estimateNftOperationFees(e)}claimNftCollection(e){return this.nftCollectionService.claimCollection(e)}fetchNftCollections(e){return this.nftCollectionService.fetchUserCollections(e)}isNftCollectionAvailable(e){return this.nftCollectionService.isCollectionAvailable(e)}createNftTokenClass(e){return this.nftCollectionService.createTokenClass(e)}fetchNftTokenClasses(e){return this.nftCollectionService.fetchTokenClasses(e)}mintNft(e){return this.nftCollectionService.mintNft(e)}fetchNftBalances(e,t){return this.nftCollectionService.fetchNftBalances(e,t)}async cleanup(){try{if(this.logger.debug("Starting cleanup..."),void 0!==this._eventsBatcherService)try{await this._eventsBatcherService.shutdown(5e3),this._eventsBatcherService=void 0}catch(e){this.logger.warn("Error during events shutdown:",e)}this.http.cleanup(),null!==this.websocketService&&void 0!==this.websocketService&&this.websocketService.disconnect(),void 0!==this._streamWebSocketService&&(this._streamWebSocketService.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..."),iT.cleanupAll(e),t.debug("Global cleanup completed")}}function iI(){const e=globalThis;return e.process?.env??{}}sI.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR=.15,sI.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR=.01,sI.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY=zt.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY,sI.DEFAULT_CALCULATE_AMOUNT_MODE=it.LOCAL,sI.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS=30,sI.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS=100;let oI=0;class aI{constructor(){this.utilityInstance=!0,this.utilityInstance}static generateWallet(){try{const t=e.Wallet.createRandom();if(null===t.mnemonic?.phrase||void 0===t.mnemonic?.phrase||""===t.mnemonic.phrase)throw St("mnemonic","Mnemonic phrase");const n=aI.toGalaAddress(t.address);return{privateKey:t.privateKey,address:t.address,galaAddress:n,mnemonic:t.mnemonic.phrase,wallet:new e.Wallet(t.privateKey)}}catch(t){if("test"===iI().NODE_ENV){const t=`test-wallet-${Date.now()}-${++oI}`,n="0x"+Buffer.from(t).toString("hex").padStart(64,"1").slice(0,64),r=new e.Wallet(n),s=aI.toGalaAddress(r.address);return{privateKey:r.privateKey,address:r.address,galaAddress:s,mnemonic:"test test test test test test test test test test test junk",wallet:r}}throw t}}static fromPrivateKey(t){const n=new e.Wallet(t),r=aI.toGalaAddress(n.address);return{privateKey:n.privateKey,address:n.address,galaAddress:r,mnemonic:"",wallet:n}}static fromMnemonic(t,n=0){try{const r=e.Mnemonic.fromPhrase(t),s=e.HDNodeWallet.fromMnemonic(r,`m/44'/60'/0'/0/${n}`),i=new e.Wallet(s.privateKey),o=aI.toGalaAddress(i.address);return{privateKey:i.privateKey,address:i.address,galaAddress:o,mnemonic:t,wallet:i}}catch(r){if("test"===iI().NODE_ENV){const r=`test-mnemonic-index-${n}-${t}`,s="0x"+Buffer.from(r).toString("hex").padStart(64,"1").slice(0,64),i=new e.Wallet(s),o=aI.toGalaAddress(i.address);return{privateKey:i.privateKey,address:i.address,galaAddress:o,mnemonic:t,wallet:i}}throw r}}static toGalaAddress(t){const n=dr(t);if(!/^[a-fA-F0-9]{40}$/.test(n))throw kt("address","a valid Ethereum address (40 hex characters)");return`eth|${e.getAddress(`0x${n}`).slice(2)}`}static toEthereumAddress(e){try{return gr(e)}catch(t){const n=at(t);if(n.includes("required")||!e?.startsWith("eth|"))throw St("galaAddress","Gala address starting with eth|");if(n.includes("Invalid backend"))throw kt("galaAddress","Gala format (eth|{40-hex-chars})");throw t}}static isValidEthereumAddress(e){try{const t=dr(e);return/^[a-fA-F0-9]{40}$/.test(t)}catch{return!1}}static isValidGalaAddress(e){return""!==e&&"backend"===br(e)}static generateMultipleWallets(e=1){On(e,1,100,"count");const t=[];if("test"===iI().NODE_ENV)for(let n=0;n<e;n++){const e=`test-multi-${n}-${Date.now()}-${++oI}`,r="0x"+Buffer.from(e).toString("hex").padStart(64,"1").slice(0,64);t.push(aI.fromPrivateKey(r))}else for(let n=0;n<e;n++)t.push(aI.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 cI(e){if(void 0===e)return aI.generateWallet();const t=e.trim();if(!Kn(t))throw kt("input","a non-empty string");if(function(e){const t=dr(e);return/^[a-fA-F0-9]{64}$/.test(t)}(t))return aI.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 aI.fromMnemonic(t);throw kt("input","a private key (64 hex characters) or mnemonic (12/24 words)","Wallet input")}const lI={METAMASK:"io.metamask",METAMASK_FLASK:"io.metamask.flask",COINBASE:"com.coinbase.wallet",TRUST_WALLET:"com.trustwallet.app",PHANTOM:"app.phantom",RAINBOW:"me.rainbow",OKX:"com.okex.wallet",RABBY:"io.rabby",BRAVE:"com.brave.wallet",FRAME:"sh.frame",LEDGER:"com.ledger",ZERION:"io.zerion.wallet",GALA:"com.gala.wallet"},uI={[lI.METAMASK]:"data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjQiIGhlaWdodD0iMjQiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0iTTIxLjU0IDQuMjJsLTguMzQgNi4yMSAxLjU0LTMuNjUtLTUuNTMtMi41MXoiIGZpbGw9IiNFMjc2MUIiLz48L3N2Zz4=",[lI.GALA]:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACkAAAApCAYAAACoYAD2AAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAjWSURBVHgBzZkLVI1ZG8f/pZKjq0uK0LglIiMKU5EuBkMxUgmjL6GFSZJ7QpJx+Ujpk1Eat3KJySXjTnIpVJRPhnTSxWVaSveL1Zlnv3WshnM67wlrzX+t3T5nv3vv99d+9/O8z36OAj5DIpGoM1W2VPSp6FJp03ipmkoRlVwq9xUUFDLwGVKCnCKwAVRNqa2rc8vOLeiRkpqpcO/hY7woeI3yikrUva9DG1VV6HXqiJHDv0Uvg66oqa0VqigrX6dxUQScCDmlwLcjwfWjKuhJdq5jVMwpxMRfQP7LN7zGttPWxARbC3i4OsDCzOQuNQUS7GnwlExIgmtH1ea0zCfugdsjFeMvJLI2tFSmA/sieMV82Fqa/UFfvQhWKGuMggzAYfX19dHBYdGGm8MPoKy8El9Knm4OWO83L6+DtmaAkpLSPrQEkgDH5eQVnnTxWqVyN/3/+Brqrq+H+H1bMdCo13pa0QDIA0mAM4R5hbu/d/MW/Pn8Bb6mdHXa42hEMCyGmqwh0EDwgSRAq5wXBZfsXBcqP88tAF+1VlGBj6crvunWGf5bIvCm6C3vsZoaarh6NByDjA0XEWgImoMkwG7FpWXJ5uPddZ/l5IGPVJSV4OJgj83+P0OnvTbXVkp7d2NIFGJPXSTX9IrXPHqdOiDp5J66b7p1sSDQlKbXFD/qG7g1/ABvQAd7K9w6HYXoHQHQUBNg0679WBTwXzKwcmxatQDX4nbT6k4D3VTmXC9fF2G230Zl+niEFksgsRNdmJKS9kik0MVMZrGY5Cm6k5ohEiv8t+MiA3OHD9cFPa1EO6OOiIpLSrnrtH1EP3mvFSnqm8ucOzg0mg1Z15RNoQlkhtXkucZJKelS/1vTAQ0+zsZyKPf9wvVk+ARsR1a2UGJ/Zr0L3Z3gPdsVrVopIutZLhas3oIrSXel3oM99swrMSXamhp96An8xdoUGwFtL95Ilgqor6eDvVtWIyUhGrZWZriZ8gAWjp4YO91bKiBTbv5LLAnciX6jpuJg3Dn07dUdl2LDcO5gCHM7Esewx74r+rgWffxJ3Cbekx6795+QejMbSzOMthzC7a3id6XYfzwBd1IzwVdPaY/P9F6LQXZuSLhyC+aD+2PqBFu0UlSU2P8AzV9ZWe0j/q5Aq6hWU1NbqNnXWr227v0nA9b4eNBq5eL2vQz8/B9nLJ7bYAhXb9/H4rXb8eDRU8irbl100ZE8wQLaCu4+6yX2uUIuadQIU0u6VxL7V4bEJVyWCMjE/F5seBBUVVvDb8NO9Bw+CcfOXIb1cFOknT+IqG3+0OnQDnxl0LUzAhbPRsrZfRg5bLDUfldu3WPVGPaHQdqkZjyRNfcHCxPSPnOetxL2rgvwPDcfs5x/QOr5/dyKqwkawkmHMSNxM34vlnrN+OB+BAJVrg/r6+48QaZbOnnuGqsMxZCmj58KIa8u3biL/tYumLN0I9oS3FrfOXhw6RAST+zBycjN5AmM0Fm3A1RUlOHqaM+tOutTXV0Lv8AQFL76q9n5CxquW4gh2wnz+b0VPlZ48DKU09vFmGBD9saiE72HKV7kjMPQ6kfEJVzlgA+FBaJrZx3s+DUG/aydsS3isMy5S96VoaysQo9sRoNF5uqv3hShJWL79XD4BpwjqMXrdmDPod+51bv/IAthQX5wHDsKAtrL56/dwdKgUGQ8fibX/BVV1VBXbytgK6laVlGFlmj2kiCcuZSEsaNH4PH1o7SKg5jrQPatE5g2aQz+JK8wxXMZ50/lBWSqe88ZszKDrNGiKKQlYlHSxFm+8F3XELj062NAlq4NbS0NRB89A8tJc3CiwQBapDb0FEhVDLLYQF8Xn6N7Dz8Nip8J81FR2bInxMSsX0NdjS1lKYMU9unRDf82ddHtyMLADIKtZZDJvb8wZDFZJjOWz5FJv96s4hw4g7xm/d1QmYO6UpDBR4l30tBjmCPu01lcmvR0OkBdrW2z84y35Vxkihgyy9LMJL9jey2JndneYjofE4oNy7zQjoyiObFVfFdWLvFaa3Lsc6Y74tG1WIIUUOAh+fzE9uOIISwHgSMcJHvmVI54uEyUOCAoZB/3GnxR+BorF85C+oWDcJ5oB3ll0r83kn7/Fbs3rUB9vQgrN4WDDnoS+7LMx0Cj3snEVchBNraHzXT6oUbaI2ABhdFIJ2ym4wGLXmKYA6eYsGd3fciSloY6Qjcswd2z0RhMQfOZi0noNWIyNoX9JjXJ4DXjR1ZtFX/nIFkWgQLS05PpDSFNNTV1WB68C8Y2rkhMTsOYUcOQTJFMgK+n1MP7NMcxeJoUh/mznOj0WAwb5/mY6O6LktIyqfcZYNQTThNs2YaOF7c1PT50p/2Ubmg5RavobQlkaabTODpKLCAjaM/dlK1YSGQsd5wYQFH39oBFGG0xFNU1NVj1y/8QceAkKquqZc57+3QkzL81HksL94e47UNoTI252praa3fSo+Gj/ccSYD5+FrbuPsgBimU9whQ3KBJigJeTUtDXaiq274nhBei/yIMBHm4K+A/IRoW6TLQ7tWTedPARy6ot3RAKE9tpeNj4btZQb8tZ92SPpbBzWcj73M0C4DU+s4X08RNrkpTBYA7xhrf/tj6h+45CHhn27M7lKCsoyGhu332sQcZ9kBgXUazWVmBKq5gDWZCNoAaUTUugk54RiwG/puzo9Bm5zb+MTqRsH96U1Ke5rBrzL/E7I48MXkFWXVVdgy+txXPdsHG5F8sC2xOg1BOdrPwke734ZQvzV09fuAbJaY/wJdRFVwcRvyzHOJvvLtPXaQTYbMqYVzqaYCdQ2UFZ3h6U7QVlfdESMec/d8Yk+M51e01gLCcZzmcc75x5I+wMquanZz4xjz52FiyhzwIJ5uglSYlSKz0IzMJ8ENwoUrccNjhLSVHxAF0KI8BS8JRckE1gzamyp/J94auiITl5BSpvS0rJsqu4Xx8E9OsDi9D19TrVUyovh+KFOOp7nsptgpM7Em4R5EfArdDwOw5L7rAsATvcFVMRskJQsr24DP0NVvGaoREi2pYAAAAASUVORK5CYII="};function dI(){return"undefined"!=typeof window&&"function"==typeof window.dispatchEvent}function hI(){if(!dI())return null;return window.ethereum??null}function gI(e){return"object"==typeof e&&null!==e&&"function"==typeof e.request}async function fI(e=500){const t=[],n=new Map;return dI()?new Promise(r=>{const s=new Set,i=e=>{const r=e,{info:i,provider:o}=r.detail;if(s.has(i.uuid))return;s.add(i.uuid);const a={id:i.rdns||i.uuid,name:i.name,rdns:i.rdns||i.uuid,icon:i.icon??uI[i.rdns||""]??"",provider:o,isInjected:!1};t.push(a),n.set(a.id,a)};window.addEventListener("eip6963:announceProvider",i),window.dispatchEvent(new Event("eip6963:requestProvider")),setTimeout(()=>{if(window.removeEventListener("eip6963:announceProvider",i),0===t.length){const e=hI();if(e){const r=window;let s="Browser Wallet",i="injected";r.ethereum?.isMetaMask?(s="MetaMask",i=lI.METAMASK):r.ethereum?.isCoinbaseWallet?(s="Coinbase Wallet",i=lI.COINBASE):r.ethereum?.isTrust&&(s="Trust Wallet",i=lI.TRUST_WALLET);const o={id:i,name:s,rdns:i,icon:uI[i]??"",provider:e,isInjected:!0};t.push(o),n.set(o.id,o)}}if(!n.has(lI.TRUST_WALLET)){const e=function(){if(!dI())return null;const e=window;if(gI(e.ethereum)&&e.ethereum.isTrust)return e.ethereum;const t=e.ethereum?.providers?.find(e=>gI(e)&&!0===e.isTrust);return void 0!==t?t:gI(e.trustwallet)?e.trustwallet:null}();if(null!==e&&!t.some(t=>t.provider===e)){const r={id:lI.TRUST_WALLET,name:"Trust Wallet",rdns:lI.TRUST_WALLET,icon:uI[lI.TRUST_WALLET]??"",provider:e,isInjected:!0};t.push(r),n.set(r.id,r)}}const e=window;if(e.gala?.request&&!n.has(lI.GALA)){const r={id:lI.GALA,name:"Gala Wallet",rdns:lI.GALA,icon:uI[lI.GALA]??"",provider:e.gala,isInjected:!0};t.push(r),n.set(r.id,r)}r({wallets:t,byId:n,hasWallets:t.length>0,...void 0===t[0]?{}:{primary:t[0]}})},e)}):{wallets:t,byId:n,hasWallets:!1}}async function pI(e,t){return(await fI(t)).byId.get(e)??null}function mI(){const e=globalThis;return e.process?.env??{}}function yI(e){const t={};return void 0!==e.cursor&&(t.cursor=e.cursor),void 0!==e.pageSize&&(t.pageSize=e.pageSize),t}function bI(e){return"string"==typeof e?e:"number"==typeof e||"boolean"==typeof e||"bigint"==typeof e?String(e):JSON.stringify(e)??""}function vI(e){if(null==e||"object"!=typeof e)return 0;const t=e;if("number"==typeof t.status)return t.status;if("number"==typeof t.statusCode)return t.statusCode;if("number"==typeof t.code)return t.code;const n=t.response;return n&&"number"==typeof n.status?n.status:0}function wI(e){const t=e.trim().toLowerCase();if(0===t.length)throw new Error("Token name cannot be empty");return t}function EI(e){if(void 0!==e&&e.length>0&&!/^[a-z0-9]+$/.test(e.toLowerCase()))throw new Error(`Invalid asset extension format: "${e}". Must contain only alphanumeric characters.`)}function AI(e,t){return`${e.replace(/\/$/,"")}${t}`}const SI=new Map;const kI={NEW_HOLDER:"NEW_HOLDER",EXITED_HOLDER:"EXITED_HOLDER",BALANCE_CHANGED:"BALANCE_CHANGED"},TI=vi({type:"string",userAddress:"string",balance:"string",rank:"number",previousRank:"optional-number"}),II=vi({tokenName:"string",userAddress:"string",quantity:"optional-string",percentage:"optional-number",holderTier:"optional-object",isCreator:"boolean",rank:"optional-number"});on.MIN_LENGTH,on.MAX_LENGTH,on.PATTERN;qn({ENABLED:"ENABLED",DISABLED:"DISABLED",ADMIN_DISABLED:"ADMIN_DISABLED"});function NI(e){return"global"===e||"token"===e}function CI(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.messageId&&"string"==typeof t.content&&"string"==typeof t.userAddress&&"string"==typeof t.tokenName&&"string"==typeof t.createdAt}function _I(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.messageId&&"string"==typeof t.content&&"string"==typeof t.userAddress&&"string"==typeof t.pinnedBy&&"string"==typeof t.pinnedAt}const xI=qn({RATE_LIMITED:"RATE_LIMITED",INVALID_EMOJI:"INVALID_EMOJI",NOT_AUTHENTICATED:"NOT_AUTHENTICATED",STREAM_NOT_LIVE:"STREAM_NOT_LIVE"});function RI(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.userAddress&&"string"==typeof t.fullName&&(void 0===t.profileImage||"string"==typeof t.profileImage)}var BI,DI,OI,MI,LI,UI;exports.AnalysisStatus=void 0,(BI=exports.AnalysisStatus||(exports.AnalysisStatus={})).PENDING="PENDING",BI.PROCESSING="PROCESSING",BI.COMPLETED="COMPLETED",BI.FAILED="FAILED",exports.AnalysisType=void 0,(DI=exports.AnalysisType||(exports.AnalysisType={})).TEXT="TEXT",DI.IMAGE="IMAGE",DI.VIDEO="VIDEO",exports.AIRecommendation=void 0,(OI=exports.AIRecommendation||(exports.AIRecommendation={})).NO_ACTION="NO_ACTION",OI.REVIEW_REQUIRED="REVIEW_REQUIRED",OI.DELETE_CONTENT="DELETE_CONTENT",OI.BAN_USER="BAN_USER",OI.DELETE_AND_BAN="DELETE_AND_BAN",exports.AnalysisCategory=void 0,(MI=exports.AnalysisCategory||(exports.AnalysisCategory={})).VIOLENCE="VIOLENCE",MI.HATE_SPEECH="HATE_SPEECH",MI.SEXUAL_CONTENT="SEXUAL_CONTENT",MI.HARASSMENT="HARASSMENT",MI.SPAM="SPAM",MI.SCAM="SCAM",MI.SELF_HARM="SELF_HARM",MI.ILLEGAL_ACTIVITY="ILLEGAL_ACTIVITY",MI.MISINFORMATION="MISINFORMATION",MI.COPYRIGHT="COPYRIGHT",MI.SAFE="SAFE",exports.AnalysisTier=void 0,(LI=exports.AnalysisTier||(exports.AnalysisTier={})).QUICK="QUICK",LI.DETAILED="DETAILED",exports.AIModerationMode=void 0,(UI=exports.AIModerationMode||(exports.AIModerationMode={})).DISABLED="DISABLED",UI.ADVISORY="ADVISORY";const PI={[exports.AnalysisStatus.PENDING]:"Pending",[exports.AnalysisStatus.PROCESSING]:"Processing",[exports.AnalysisStatus.COMPLETED]:"Completed",[exports.AnalysisStatus.FAILED]:"Failed"},FI={[exports.AIRecommendation.NO_ACTION]:"No Action Needed",[exports.AIRecommendation.REVIEW_REQUIRED]:"Human Review Required",[exports.AIRecommendation.DELETE_CONTENT]:"Delete Content",[exports.AIRecommendation.BAN_USER]:"Ban User",[exports.AIRecommendation.DELETE_AND_BAN]:"Delete & Ban"},$I={[exports.AnalysisCategory.VIOLENCE]:"Violence",[exports.AnalysisCategory.HATE_SPEECH]:"Hate Speech",[exports.AnalysisCategory.SEXUAL_CONTENT]:"Sexual Content",[exports.AnalysisCategory.HARASSMENT]:"Harassment",[exports.AnalysisCategory.SPAM]:"Spam",[exports.AnalysisCategory.SCAM]:"Scam",[exports.AnalysisCategory.SELF_HARM]:"Self Harm",[exports.AnalysisCategory.ILLEGAL_ACTIVITY]:"Illegal Activity",[exports.AnalysisCategory.MISINFORMATION]:"Misinformation",[exports.AnalysisCategory.COPYRIGHT]:"Copyright",[exports.AnalysisCategory.SAFE]:"Safe"},KI={[exports.AnalysisTier.QUICK]:"Quick Scan",[exports.AnalysisTier.DETAILED]:"Detailed Scan"},GI={[exports.AnalysisType.TEXT]:"Text",[exports.AnalysisType.IMAGE]:"Image",[exports.AnalysisType.VIDEO]:"Video"},WI={[exports.AIModerationMode.DISABLED]:"Disabled",[exports.AIModerationMode.ADVISORY]:"Advisory"},HI=qn(exports.AnalysisStatus),qI=qn(exports.AnalysisType),zI=qn(exports.AIRecommendation),VI=qn(exports.AnalysisCategory),jI=qn(exports.AnalysisTier),XI=qn(exports.AIModerationMode),YI=Yn([{field:"id",type:"number"},{field:"flagId",type:"number"},{field:"status",type:"string",validator:HI},{field:"analysisType",type:"string",validator:qI},{field:"provider",type:"string"}]),JI=Yn([{field:"enabled",type:"boolean"},{field:"mode",type:"string",validator:XI},{field:"provider",type:"string"}]);function QI(e){return null!==e.analysisTier}function ZI(e){if(!Kn(e))throw St("content");if(0===e.trim().length)throw Ut("content","Content");if(e.length>fn.COMMENTS_V1.MAX_LENGTH)throw Lt("content",fn.COMMENTS_V1.MAX_LENGTH,e.length)}function eN(e){if(!Kn(e))throw St("content");if(0===e.trim().length)throw new yt("content cannot be empty","content",mt.REQUIRED);if(e.length>fn.CHAT_MESSAGES_V1.MAX_LENGTH)throw new yt(`content must be at most ${fn.CHAT_MESSAGES_V1.MAX_LENGTH} characters`,"content",mt.TOO_LONG)}var tN=Object.freeze({__proto__:null,extractMetadataFromPoolData:function(e,t){const n={};if(void 0!==e.vaultAddress&&(n.vaultAddress=e.vaultAddress),void 0!==e.reverseBondingCurveMinFeePortion){const r=In(e.reverseBondingCurveMinFeePortion,NaN);isNaN(r)?t&&t.debug(`Skipping invalid reverseBondingCurveMinFeePortion for ${e.tokenName}: "${e.reverseBondingCurveMinFeePortion}"`):n.reverseBondingCurveMinFeeFactor=r}if(void 0!==e.reverseBondingCurveMaxFeePortion){const r=In(e.reverseBondingCurveMaxFeePortion,NaN);isNaN(r)?t&&t.debug(`Skipping invalid reverseBondingCurveMaxFeePortion for ${e.tokenName}: "${e.reverseBondingCurveMaxFeePortion}"`):n.reverseBondingCurveMaxFeeFactor=r}return void 0!==n.reverseBondingCurveMaxFeeFactor&&void 0!==n.reverseBondingCurveMinFeeFactor&&(n.reverseBondingCurveNetFeeFactor=n.reverseBondingCurveMaxFeeFactor-n.reverseBondingCurveMinFeeFactor),Object.keys(n).length>0?n:null},isValidPoolForCaching:function(e){if(null===e||"object"!=typeof e)return!1;const t=e;return"tokenName"in t&&"string"==typeof t.tokenName&&t.tokenName.length>0}});Object.defineProperty(exports,"GSwap",{enumerable:!0,get:function(){return t.GSwap}}),exports.ACTIVE_USER_TYPE=SE,exports.AI_MODE_LABELS=WI,exports.AI_RECOMMENDATION_LABELS=FI,exports.ALL_PERMISSIONS=pE,exports.ANALYSIS_CATEGORY_LABELS=$I,exports.ANALYSIS_STATUS_LABELS=PI,exports.ANALYSIS_TIER_LABELS=KI,exports.ANALYSIS_TYPE_LABELS=GI,exports.API_KEY_PERMISSION={MANAGE_COMMENTS:"MANAGE_COMMENTS",MANAGE_CHAT:"MANAGE_CHAT",BAN_USERS:"BAN_USERS",UNBAN_USERS:"UNBAN_USERS",MANAGE_SIMULCAST:"MANAGE_SIMULCAST",GET_STREAM_KEY:"GET_STREAM_KEY",STOP_STREAM:"STOP_STREAM",RESET_STREAM_KEY:"RESET_STREAM_KEY",START_STREAM:"START_STREAM",DELETE_RECORDINGS:"DELETE_RECORDINGS",MANAGE_STREAM_SETTINGS:"MANAGE_STREAM_SETTINGS"},exports.API_KEY_ROLE=hE,exports.API_KEY_ROLES=gE,exports.API_KEY_ROLE_HIERARCHY=EE,exports.AddressFormatter=lr,exports.AgentConfig=class{constructor(){this.utilityInstance=!0,this.utilityInstance}static async quickSetup(e={}){const t=e.environment??this.detectEnvironment(),n=this.setupWallet(e.privateKey),r=this.buildSdkConfig(e,t,n),s=new sI(r),i={sdk:s,wallet:n,config:r};if(!1!==e.autoValidate){const e=await this.validateSetup(s,n);return{...i,validation:e}}return i}static readOnlySetup(e={}){const t=e.environment??this.detectEnvironment(),n=this.buildSdkConfig(e,t),r=new sI(n);return Promise.resolve({sdk:r,config:n})}static async validateSetup(e,t){const n=[],r=[],s={canTrade:!1,canCreateTokens:!1,hasBalance:!1,connectionHealthy:!1};try{const t=await e.fetchGalaBalance(e.getAddress());if(s.connectionHealthy=!0,void 0!==t?.quantity&&""!==t.quantity){const e=In(t.quantity,0);s.hasBalance=e>0,s.canTrade=e>=.1,s.canCreateTokens=e>=100,0===e?r.push("Wallet has zero GALA balance - cannot perform transactions"):e<.1?r.push("GALA balance too low for trading (minimum 0.1 GALA)"):e<100&&r.push("GALA balance too low for token creation (minimum 100 GALA)")}else n.push("Failed to fetch GALA balance: No balance returned")}catch(e){n.push(`Balance check error: ${at(e)}`)}try{const t=await e.fetchPools({type:"recent",pageSize:1});null!==t.items&&void 0!==t.items&&0!==t.items.length||r.push("Pool listing not accessible - some features may be limited")}catch(e){r.push(`Pool access test failed: ${at(e)}`)}return{ready:0===n.length&&s.connectionHealthy,sdk:e,wallet:t??aI.generateWallet(),issues:n,warnings:r,capabilities:s}}static getRecommendedConfig(e,t="general"){const n={environment:e,autoValidate:!0};switch(e){case"prod":Object.assign(n,{debug:!1,timeout:3e4});break;case"stage":Object.assign(n,{debug:!0,timeout:45e3})}switch(t){case"trading":n.timeout=1.5*(n.timeout??3e4);break;case"creation":n.timeout=2*(n.timeout??3e4);break;case"monitoring":n.timeout=.5*(n.timeout??3e4);break;case"general":break;default:throw new Error(`Unexpected useCase: ${String(t)}`)}return n}static async multiWalletSetup(e,t="stage"){const n={};for(const[r,s]of Object.entries(e)){const{sdk:e}=await this.quickSetup({environment:t,privateKey:s,agentId:`multi-wallet-${r}`,autoValidate:!1});n[r]=e}return n}static detectEnvironment(){return"stage"===(mI().LAUNCHPAD_ENV??mI().ENVIRONMENT)?"stage":"prod"}static setupWallet(e){if(void 0===e||""===e){const e=mI().PRIVATE_KEY;return void 0!==e&&""!==e?aI.fromPrivateKey(e):aI.generateWallet()}return"generate"===e?aI.generateWallet():aI.fromPrivateKey(e)}static buildSdkConfig(e,t,n){const r=e.galaChainAddress??mI().WALLET_ADDRESS;return{wallet:n?.wallet,baseUrl:e.baseUrl??this.getDefaultBaseUrl(t),timeout:e.timeout??this.getDefaultTimeout(t),debug:e.debug??"prod"!==t,...this.getEnvironmentDefaults(t),...e.config??{},...void 0!==r&&""!==r?{galaChainAddress:r}:{},env:t}}static getDefaultBaseUrl(e){return so(e).launchpadBaseUrl}static getDefaultTimeout(e){switch(e){case"prod":return 3e4;case"stage":return 45e3}}static getEnvironmentDefaults(e){const t=so(e);return{bundleBaseUrl:t.bundleBaseUrl,gatewayBaseUrl:t.gatewayBaseUrl}}},exports.AuthError=Xi,exports.BAN_DURATIONS={ONE_HOUR:3600,ONE_DAY:86400,ONE_WEEK:604800,ONE_MONTH:2592e3},exports.BRIDGE_CONTRACT_ABI=Eo,exports.BRIDGE_TOKEN_METADATA=vo,exports.BaseBridgeStrategy=xw,exports.BridgeRateLimiter=Jv,exports.BrowserWalletSigner=cA,exports.BundleSubmission=hT,exports.BundlerTransport=gT,exports.BurnError=hS,exports.CALCULATION_MODES=it,exports.CHAIN_IDS=ao,exports.CONTENT_REACTION_TYPES=DA,exports.CONTENT_TYPE_LABELS=SA,exports.CROSS_RATE_TYPED_DATA_TYPES=qv,exports.ChartService=class extends rr{constructor(e,t=!1){super(e,t)}async getChart(e){if(null==e)throw St("options","Chart options");const{tokenName:t,from:n,to:r,resolution:s}=e;if(null==t||""===t)throw St("tokenName","Token name");if(null==n)throw St("from","Start timestamp");if(null==r)throw St("to","End timestamp");if(null==s)throw St("resolution","Data resolution interval");Ui(t);const i=173e6;if("number"!=typeof n||n<i)throw new yt("from must be a valid timestamp (min: 173000000)","from","INVALID_TIMESTAMP");if("number"!=typeof r||r<i)throw new yt("to must be a valid timestamp (min: 173000000)","to","INVALID_TIMESTAMP");if("number"!=typeof s||s<1)throw new yt("resolution must be a number >= 1","resolution","INVALID_RESOLUTION");const{adaptQueryParams:o}=await Promise.resolve().then(function(){return Si}),a=o({tokenName:t,from:n,to:r,resolution:s}),c=await Ht(()=>this.http.get(b.CHART,a),{errorContext:"Failed to fetch chart data"}),l=$t(c);if(null==l||"object"!=typeof l)throw Tt("Invalid API response: missing or invalid data",c.status??500);const u=l,d=u.data;if(!Array.isArray(d))throw Tt("Invalid API response: expected data array",c.status??500);const h={dataPoints:d.map(e=>{if("object"!=typeof e||null===e)throw Tt("Invalid API response: invalid data point structure",c.status??500);const t=e,n=t.startTime??t.timestamp,r=t.openPrice??t.value,s=t.closePrice??t.value,i=t.lowPrice??t.value,o=t.highPrice??t.value,a=t.volume??"0";return{startTime:"number"==typeof n?n:Number(n),openPrice:String(r),closePrice:String(s),lowPrice:String(i),highPrice:String(o),volume:String(a)}})};return"boolean"==typeof u.isPreviousData&&(h.isPreviousData=u.isPreviousData),h}},exports.ConfigurationError=vt,exports.DEFAULT_ETHEREUM_BRIDGE_CONTRACT=lo,exports.DEFAULT_ETHEREUM_RPC_URL="https://ethereum.publicnode.com",exports.DEFAULT_ETHEREUM_TOKENS=yo,exports.DEFAULT_EVENTS_CONFIG=UA,exports.DEFAULT_POLL_INTERVAL_MS=15e3,exports.DEFAULT_POLL_TIMEOUT_MS=27e5,exports.DEFAULT_PRICING_CONCURRENCY=5,exports.DEFAULT_RATE_LIMIT_RPS=12,exports.DEFAULT_SOLANA_BRIDGE_PROGRAM="AaE4dTnL75XqgUJpdxBKg6vS9sTJgBPJwBQRVhD29WwS",exports.DEFAULT_SOLANA_RPC_URL="https://api.mainnet-beta.solana.com",exports.DEFAULT_SOLANA_TOKENS=bo,exports.DEFAULT_WEBSOCKET_RECONNECT_ATTEMPTS=5,exports.ENVIRONMENT_URLS=ro,exports.ERC20_ABI=wo,exports.ERROR_CODES=mt,exports.ETHEREUM_BRIDGE_CONTRACT_SEPOLIA=uo,exports.ETHEREUM_TOKENS_PROD=go,exports.ETHEREUM_TOKENS_STAGE=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.EXTENDED_STREAM_ROLE=Kk,exports.EthereumBridgeStrategy=Dw,exports.EventBufferWithAutoCleanup=class{constructor(e={},t){this.events=[],this.timeouts=new Map,this.maxSize=e.maxSize??100,this.defaultTtlMs=e.defaultTtlMs??3e4,this.logger=t}push(e){if(this.events.length>=this.maxSize){const e=0;this.events.shift();const t=this.timeouts.get(e);t&&(clearTimeout(t),this.timeouts.delete(e)),this.logger?.warn(`Buffer full (${this.maxSize}), dropped oldest event`)}this.events.push(e);const t=this.events.length-1,n=setTimeout(()=>{this.events[t]===e&&this.events.splice(t,1),this.timeouts.delete(t)},this.defaultTtlMs);this.timeouts.set(t,n)}getAll(){return[...this.events]}clear(){for(const e of this.timeouts.values())clearTimeout(e);this.events=[],this.timeouts.clear()}get size(){return this.events.length}},exports.EventsBatcherService=PA,exports.ExternalWalletProvider=ZT,exports.FLAG_ACTION_LABELS=AA,exports.FLAG_DETAILS_MAX_LENGTH=500,exports.FLAG_REASON_LABELS=wA,exports.FLAG_STATUS_LABELS=EA,exports.FileValidationError=Di,exports.GALACHAIN_CHANNELS=co,exports.GALACONNECT_PRODUCTION_URL=ho,exports.GALA_BRIDGE_TYPED_DATA_DOMAIN=Fv,exports.GALA_DECIMALS=8,exports.GALA_TOKEN_CLASS_KEY={collection:"GALA",category:"Unit",type:"none",additionalKey:"none"},exports.GalaConnectClient=_w,exports.GalaConnectHttpError=Aw,exports.GalaWalletSigner=aA,exports.GdexStreamError=SS,exports.GdexStreamService=kS,exports.GlobalAndRoomCallbackDispatcher=class{constructor(e){this.globalCallbacks=[],this.roomCallbacks=new Map,this.logger=e}registerGlobalCallback(e){this.globalCallbacks.push(e)}registerRoomCallback(e,t){const n=this.roomCallbacks.get(e)??[];n.push(t),this.roomCallbacks.set(e,n)}dispatch(e,t){for(const e of this.globalCallbacks)try{e(t)}catch(e){this.logger?.error(`Error in global callback: ${at(e)}`)}const n=this.roomCallbacks.get(e);if(n)for(const r of n)try{r(t)}catch(t){this.logger?.error(`Error in room callback for ${e}: ${at(t)}`)}}clear(){this.globalCallbacks=[],this.roomCallbacks.clear()}clearRoom(e){this.roomCallbacks.delete(e)}},exports.HOLDER_DELTA_TYPES=kI,exports.IMAGE_EXTENSIONS=Vr,exports.INVITE_STATUS=VS,exports.INVITE_STATUSES=jS,exports.JWT_CONSTANTS=qi,exports.KNOWN_WALLET_RDNS=lI,exports.LAUNCHPAD_TOKEN_DECIMALS=18,exports.LEGACY_TYPED_DATA_TYPES=Hv,exports.LaunchpadSDK=sI,exports.LaunchpadSDKError=dT,exports.LaunchpadWrites=ST,exports.ListenerCleanupManager=class{constructor(e){this.listeners=[],this.logger=e}register(e,t){this.listeners.push({id:e,cleanup:t})}async cleanup(){const e=[];for(let t=this.listeners.length-1;t>=0;t--){const n=this.listeners[t];if(void 0===n)continue;const{id:r,cleanup:s}=n;try{await s()}catch(t){const n=t instanceof Error?t:new Error(String(t));e.push(n),this.logger?.error(`Cleanup error for listener ${r}:`,n)}}return this.listeners=[],e}clear(){this.listeners=[]}get size(){return this.listeners.length}},exports.LockError=ZA,exports.MAX_BURN_BATCH_SIZE=50,exports.MAX_CONCURRENT_POOL_FETCHES=5,exports.MAX_LOCK_BATCH_SIZE=100,exports.MAX_UNLOCK_BATCH_SIZE=100,exports.MESSAGES_CONSTRAINTS=_S,exports.MESSAGE_TYPES=CS,exports.MODERATOR_ROLE=WS,exports.MODERATOR_ROLES=HS,exports.NFT_FEES=rk,exports.NetworkError=bt,exports.NftCollectionService=lk,exports.OEmbedService=dk,exports.OVERSEER_INVITE_STATUS=gk,exports.OVERSEER_STATUS=fk,exports.PAGINATION_DEFAULTS=rE,exports.PERMISSION=fE,exports.POOL_FETCH_CONFIG={MAX_CONCURRENT_FETCHES:5,PAGE_SIZE:50,BACKEND_PAGE_SIZE:20},exports.POOL_TYPES={RECENT:"recent",POPULAR:"popular"},exports.PayloadWalkerWithDeduplication=class{constructor(e,t,n=50){this.seen=new Set,this.extractor=e,this.dedupeKeyFn=t,this.maxDepth=n}walk(e){const t=[],n=new WeakSet,r=(e,s=0)=>{if(s>this.maxDepth)return;if(null==e||"object"!=typeof e)return;if(n.has(e))return;n.add(e);const i=this.extractor(e);if(null!==i){const e=this.dedupeKeyFn(i);this.seen.has(e)||(this.seen.add(e),t.push(i))}for(const t of Object.values(e))r(t,s+1)};return r(e,0),t}reset(){this.seen.clear()}getSeenCount(){return this.seen.size}},exports.PendingSubscriptionTracker=class{constructor(){this.pending=new Map}addPending(e,t){this.removePending(e);const n=setTimeout(()=>{this.pending.delete(e)},t);this.pending.set(e,{timeoutId:n,addedAt:Date.now()})}removePending(e){const t=this.pending.get(e);t&&(clearTimeout(t.timeoutId),this.pending.delete(e))}isPending(e){return this.pending.has(e)}getPendingCount(){return this.pending.size}clearExpired(){for(const[e,t]of this.pending.entries())null==t&&this.pending.delete(e)}clear(){for(const e of this.pending.values())clearTimeout(e.timeoutId);this.pending.clear()}},exports.PlatformStatsService=Ck,exports.PrivateKeyProvider=to,exports.PrivateKeySigner=oA,exports.QUERY_FIELD_NAMES={PAGE:"page",LIMIT:"limit",TOKEN_NAME:"tokenName",VAULT_ADDRESS:"vaultAddress",USER_ADDRESS:"userAddress",TRADE_TYPE:"tradeType",POOL_TYPE:"type",SEARCH:"search",SORT_ORDER:"sortOrder",START_DATE:"startDate",END_DATE:"endDate"},exports.REACTION_EMOJI_MAP={heart:"❤️",fire:"🔥",laugh:"😂",wow:"😮",thumbs_up:"👍"},exports.RECORDING_STATUS=Ok,exports.ROLE_SOURCE=$k,exports.RoomSubscriptionManager=class{constructor(){this.rooms=new Set}addRoom(e){this.rooms.add(e)}removeRoom(e){this.rooms.delete(e)}getRooms(){return Array.from(this.rooms)}isSubscribedTo(e){return this.rooms.has(e)}clear(){this.rooms.clear()}get size(){return this.rooms.size}},exports.SDK_VERSION=nE,exports.SIMULATE_EVENT_TYPE={STREAM_STARTED:"stream.started",STREAM_STOPPED:"stream.stopped",RECORDING_READY:"recording.ready",SIMULCAST_ERROR:"simulcast.error"},exports.SIMULCAST_PLATFORM=Mk,exports.SIMULCAST_STATUS={ACTIVE:"ACTIVE",IDLE:"IDLE",ERRORED:"ERRORED",DISABLED:"DISABLED"},exports.SOLANA_COMPUTE={UNIT_LIMIT:2e5,UNIT_PRICE_MICROLAMPORTS:375e3},exports.SOLANA_DISCRIMINATORS=Ao,exports.STREAM_EVENTS=zk,exports.STREAM_PERMISSION={MANAGE_COMMENTS:"MANAGE_COMMENTS",MANAGE_CHAT:"MANAGE_CHAT",BAN_USERS:"BAN_USERS",UNBAN_USERS:"UNBAN_USERS",MANAGE_SIMULCAST:"MANAGE_SIMULCAST",GET_STREAM_KEY:"GET_STREAM_KEY",STOP_STREAM:"STOP_STREAM",RESET_STREAM_KEY:"RESET_STREAM_KEY",START_STREAM:"START_STREAM",DELETE_RECORDINGS:"DELETE_RECORDINGS",MANAGE_STREAM_SETTINGS:"MANAGE_STREAM_SETTINGS"},exports.STREAM_ROLE=Fk,exports.STREAM_STATUS=Dk,exports.SelectiveEventForwarding=class{constructor(){this.filters=[]}addFilter(e){return this.filters.push(e),this}forward(e){for(const t of this.filters)if(!t(e))return!1;return!0}clearFilters(){this.filters=[]}get filterCount(){return this.filters.length}},exports.SolanaBridgeStrategy=jw,exports.StreamWebSocketService=Vk,exports.StreamingEventService=Bk,exports.TIME_CONSTANTS={ONE_SECOND_MS:1e3,ONE_MINUTE_MS:6e4,ONE_HOUR_MS:36e5,ONE_DAY_MS:864e5,ONE_WEEK_MS:6048e5,ONE_MONTH_MS:2592e6},exports.TRADES_QUERY_CONSTRAINTS=DS,exports.TRADING_TYPES=st,exports.TokenRestrictedError=class extends yt{constructor(e){super(e,"token","TOKEN_RESTRICTED"),this.name="TokenRestrictedError"}},exports.TokenWrites=TT,exports.TradingQuotesService=tT,exports.TransactionError=wt,exports.TransactionFailedError=$T,exports.TypingIndicatorDebouncer=class{constructor(e={},t){this.pendingIndicators=new Map,this.activeIndicators=new Set,this.delayMs=e.delayMs??3e3,this.onTyping=e.onTyping,this.onStopTyping=e.onStopTyping}indicate(e,t){const n=`${e}:${t}`,r=this.pendingIndicators.get(n);r&&clearTimeout(r),this.activeIndicators.has(n)||(this.activeIndicators.add(n),this.onTyping?.(e,t));const s=setTimeout(()=>{this.activeIndicators.delete(n),this.pendingIndicators.delete(n),this.onStopTyping?.(e,t)},this.delayMs);this.pendingIndicators.set(n,s)}stopTyping(e,t){const n=`${e}:${t}`,r=this.pendingIndicators.get(n);r&&(clearTimeout(r),this.pendingIndicators.delete(n)),this.activeIndicators.has(n)&&(this.activeIndicators.delete(n),this.onStopTyping?.(e,t))}clear(){for(const e of this.pendingIndicators.values())clearTimeout(e);this.pendingIndicators.clear(),this.activeIndicators.clear()}get activeCount(){return this.activeIndicators.size}},exports.ValidationError=yt,exports.WebSocketError=FT,exports.WebSocketTimeoutError=class extends FT{constructor(e,t){super(`WebSocket confirmation timeout for transaction ${e} after ${t}ms`),this.name="WebSocketTimeoutError"}},exports.WeeklyChallengeService=oT,exports.addCursorToPagination=function(e,t){return void 0===t?e:{...e,cursor:t}},exports.addressFormatSchema=Ir,exports.aggregateMultipleApiSources=async function(e,t,n){const r=n?.logger,s=n?.fetcher??(async e=>{const t=await fetch(e);if(!t.ok)throw new Error(`HTTP ${t.status}`);return t.json()});r?.debug(`Aggregating from ${e.length} endpoints`);const i=e.map(async(t,n)=>{try{const i=await s(t);return r?.debug(`Endpoint [${n+1}/${e.length}] succeeded: ${t}`),i}catch(s){return void r?.warn(`Endpoint [${n+1}/${e.length}] failed: ${t} - ${at(s)}`)}}),o=(await Promise.allSettled(i)).map(e=>{if("fulfilled"===e.status)return e.value});return r?.debug(`Aggregating ${o.filter(e=>void 0!==e).length} successful results`),t(o)},exports.amountMethodSchema=ls,exports.amountTypeSchema=cs,exports.assertValidWalletAddress=mr,exports.bidirectionalTokenMatch=function(e,t,n,r){return e===n&&t===r||e===r&&t===n},exports.browserFileSchema=Xr,exports.bufferFileSchema=Yr,exports.buildConcurrentBatchRequests=async function(e,t,n,r){const s=r?.logger,i=[];i.length=e.length;let o=0,a=0;s?.debug(`Starting concurrent batch requests: ${e.length} URLs, batch size: ${t}`);for(let r=0;r<e.length;r+=t){const c=e.slice(r,r+t),l=r;try{const t=c.map((t,r)=>{const c=l+r;return(async()=>{try{const r=await n(t);return i[c]=r,o++,s?.debug(`Fetched [${c+1}/${e.length}]: ${t}`),r}catch(n){throw a++,s?.warn(`Failed [${c+1}/${e.length}]: ${t} - ${at(n)}`),n}})()}),r=await Promise.allSettled(t);for(let e=0;e<r.length;e++){const t=r[e];"rejected"===t?.status&&s?.debug(`Promise rejected in batch at index ${l+e}`)}}catch(e){s?.error(`Batch processing error at index ${r}: ${at(e)}`)}}return s?.debug(`Batch complete: ${o} succeeded, ${a} failed`),i},exports.buildQueryParametersWithValidation=function(e){if(null==e||"object"!=typeof e)return"";const t=[];for(const[n,r]of Object.entries(e)){if(Gn(r))continue;let e;e="string"==typeof r?r:"number"==typeof r||"boolean"==typeof r?String(r):Array.isArray(r)?r.map(e=>bI(e)).join(","):bI(r);const s=encodeURIComponent(n),i=encodeURIComponent(e);t.push(`${s}=${i}`)}return t.length>0?`?${t.join("&")}`:""},exports.buildSafePaginationOptions=yI,exports.buyTokensDataSchema=Ss,exports.calculateLinearFeeInterpolation=function(e,t,n){const r="number"==typeof e?new o(e):e;if(r.isLessThan(0)||r.isGreaterThan(1))throw new Error(`Progress must be between 0 and 1, got: ${r.toString()}`);if(n<t)throw new Error(`maxFee must be >= minFee, got minFee: ${t}, maxFee: ${n}`);const s=n-t;return new o(t).plus(new o(s).multipliedBy(r))},exports.calculatePreMintDataSchema=xs,exports.calculateScaledFeeAmount=function(e,t){if(t<0)throw new Error(`feeFactor must be >= 0, got: ${t}`);return ki(e).multipliedBy(t).integerValue(o.ROUND_DOWN)},exports.calculateTotalPages=iE,exports.capitalize=Et,exports.caseInsensitiveTokenComparison=function(e,t){return e.toLowerCase()===t.toLowerCase()},exports.checkPoolOptionsSchema=as,exports.commonValidators=Jn,exports.compareAmounts=function(e,t){const n=ki(e),r=ki(t);return n.comparedTo(r)},exports.conditionalSpreadBuilder=function(e,t){const n={...e};for(const[e,r]of Object.entries(t))void 0!==r&&(n[e]=r);return n},exports.conditionalTrimAndValidateString=US,exports.createLaunchpadSDK=function(t){Wn(t)&&(t={});const{wallet:n,env:r,config:s={},...i}=t,o={...{...i,...s}};delete o.wallet,delete o.env,delete o.config;const a=!Wn(o.signer)||!Wn(o.walletProvider);let c;if(Wn(n))c=a?void 0:cI().wallet;else if("string"==typeof n){c=cI(n).wallet}else{if(!(n instanceof e.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!==r?{env:r}:{},debug:!1,timeout:3e4,...o};return new sI(l)},exports.createLimitSchema=Mr,exports.createOptionsValidator=function(e){return t=>{const n=[],r=t;for(const t of e){const{field:e,required:s,type:i,validator:o}=t,a=r[e];if(s){if(Wn(a)){n.push(`${e} is required`);continue}if("string"===i){if("string"!=typeof a){n.push(`${e} must be a string`);continue}if(0===a.trim().length){n.push(`${e} is required`);continue}}}if(!Wn(a))if(void 0===i||typeof a===i){if(void 0!==o){const e=o(a,r);null!=e&&""!==e&&n.push(e)}}else n.push(`${e} must be a ${i}`)}return n}},exports.createPaginatedResultSchema=function(e){return n.z.object({data:n.z.array(e),...bs})},exports.createPaginationQuery=function(e,t=rE.DEFAULT_LIMIT){if("number"!=typeof e||!Number.isInteger(e)||e<0)throw Bt("offset","a non-negative integer",e);return Ln(t,"limit"),{offset:e,limit:t}},exports.createProviderFromEip1193=function(e){return new ZT(e)},exports.createProviderFromWallet=function(e){return to.fromWallet(e)},exports.createSolanaWallet=function(){const e=nv.generate();return{privateKey:zw.encode(e.secretKey),publicKey:e.publicKey.toBase58(),address:e.publicKey.toBase58()}},exports.createTradeDataSchema=As,exports.createWallet=cI,exports.createWalletProvider=function(e){if(null!==e.privateKey&&void 0!==e.privateKey&&e.privateKey.length>0)return new to(e.privateKey);if(null!==e.eip1193Provider&&void 0!==e.eip1193Provider)return new ZT(e.eip1193Provider);throw new eo("Invalid wallet provider config: must provide either privateKey or eip1193Provider",ji.INVALID_CONFIG)},exports.decimalRoundingUp=function(e,t){if(t<0)throw new Error(`decimals must be >= 0, got: ${t}`);const n=ki(e),r=new o(10).pow(t);return n.multipliedBy(r).integerValue(o.ROUND_UP).dividedBy(r)},exports.deduplicateByKey=function(e,t,n=!0){const r=new Map;if(e.forEach((e,n)=>{const s=t(e);r.set(s,n)}),n){const n=new Set;return e.filter(e=>{const r=t(e);return!n.has(r)&&(n.add(r),!0)})}return e.filter((e,n)=>{const s=t(e);return r.get(s)===n})},exports.detectWallets=fI,exports.ensureConnected=async function(e){return e.isConnected()?e.getAddress():e.connect()},exports.errorMessageCaseNormalization=function(e){return e.toLowerCase()},exports.ethereumAddressSchema=Nr,exports.extractFieldWithFallbackPath=function(e,t,n=null){if(null==e||"object"!=typeof e)return n;const r=e;for(const e of t){const t=e.split(".");let n=r;for(const e of t){if(null==n||"object"!=typeof n){n=null;break}n=n[e]}if(Kn(n))return n;if(null!=n&&""!==n)return n}return n},exports.extractPaginationMetadata=function(e){const t={page:1,pageSize:20,totalCount:-1,hasMore:!1};if(null==e||"object"!=typeof e)return t;const n=e,r=Cn(bI(n.page??n.Page??n.current??1),t.page),s=Cn(bI(n.pageSize??n.limit??n.size??t.pageSize),t.pageSize),i=n.data,o=i?.meta;let a;a="number"==typeof n.totalCount?n.totalCount:"number"==typeof n.total?n.total:"number"==typeof o?.totalItems?o.totalItems:"number"==typeof i?.count?i.count:Cn(bI(n.totalCount??n.total??-1),t.totalCount);let c=t.hasMore;return"boolean"==typeof n.hasMore?c=n.hasMore:"boolean"==typeof n.has_more?c=n.has_more:"boolean"==typeof o?.hasMore&&(c=o.hasMore),{page:r,pageSize:s,totalCount:a,hasMore:c}},exports.fetchGalaBalanceOptionsSchema=Ms,exports.fetchPoolDetailsDataSchema=Rs,exports.fetchTokenBalanceOptionsSchema=Fs,exports.fileSizeSchema=Fr,exports.fileUploadSchema=jr,exports.filenameSchema=$r,exports.flexibleAddressSchema=Cr,exports.flexibleFileSchema=Jr,exports.formatGalaForDTO=Bn,exports.formatLaunchpadTokenForDTO=Dn,exports.formatTokenAmount=function(e,t=6){const n=ki(e);if(!n.isFinite())return"0";if(n.abs().lt(1e-6)&&!Ni(n))return n.toExponential(2);const r=Math.min(t,n.abs().lt(1)?t:n.abs().lt(100)?4:2);return n.toFixed(r).replace(/\.?0+$/,"")},exports.formatTokenDescriptor=function(e){return io(e)},exports.fromBackendAddressFormat=gr,exports.fromBaseUnits=ww,exports.fullNameSchema=Tr,exports.generateBuySellStringsInstructions=uA,exports.generateCreateSaleStringsInstructions=dA,exports.generateEIP712Types=tA,exports.generateUniqueKey=eA,exports.getAmountOptionsSchema=_s,exports.getEnv=function(e,t){return globalThis.process?.env[e]??t},exports.getEnvOrThrow=function(e,t){const n=globalThis.process?.env[e];if(en(n)||!Qt(n)){throw St(e,`${e} (${void 0!==t?`${t} (checked root .env and local .env)`:"checked root .env and local .env"})`)}return n},exports.getEnvironmentConfig=so,exports.getEthereumAddressFromPrivateKey=function(t){if(!t.match(/^0x[a-fA-F0-9]{64}$/))throw kt("privateKey","0x-prefixed 64 hexadecimal characters","Private key");return e.getAddress(e.computeAddress(t))},exports.getEthereumBridgeContractByEnvironment=mo,exports.getEthereumTokenConfig=function(e){const t=Xt(e);return yo.find(e=>Xt(e.symbol)===t)},exports.getEthereumTokensByEnvironment=po,exports.getGalaBridgeTypedDataTypes=zv,exports.getInjectedEip1193Provider=function(){if("undefined"==typeof window)return null;const e=window.ethereum;return nI(e)?e:null},exports.getIntervalRegistryStats=function(){const e=Array.from(SI.entries()).map(([e,t])=>({id:e,...t}));return{size:SI.size,entries:e}},exports.getLaunchTokenDataValidationErrors=gi,exports.getNftFeeAsNumber=function(e){return parseFloat(rk[e])},exports.getPublicKeyFromPrivateKey=function(t){if(!t.match(/^0x[a-fA-F0-9]{64}$/))throw kt("privateKey","0x-prefixed 64 hexadecimal characters","Private key");const n=new e.SigningKey(t);return{publicKey:n.publicKey,compressedPublicKey:n.compressedPublicKey}},exports.getRecordingAnimatedUrl=function(e,t,n,r="gif"){const s=wI(e),i=t.trim();if(0===i.length)throw new Error("Recording ID cannot be empty");return EI(r),AI(n,`/v1/tokens/${encodeURIComponent(s)}/recordings/${encodeURIComponent(i)}/assets/animated.${r.toLowerCase()}`)},exports.getRecordingAssetUrl=function(e,t,n,r,s){const i=wI(e),o=t.trim(),a=n.trim().toLowerCase();if(0===o.length)throw new Error("Recording ID cannot be empty");if(0===a.length)throw new Error("Asset type cannot be empty");EI(s);const c=void 0!==s&&s.length>0?`.${s.toLowerCase()}`:"";return AI(r,`/v1/tokens/${encodeURIComponent(i)}/recordings/${encodeURIComponent(o)}/assets/${encodeURIComponent(a)}${c}`)},exports.getRecordingPosterUrl=function(e,t,n){const r=wI(e),s=t.trim();if(0===s.length)throw new Error("Recording ID cannot be empty");return AI(n,`/v1/tokens/${encodeURIComponent(r)}/recordings/${encodeURIComponent(s)}/assets/poster.jpg`)},exports.getRecordingStoryboardUrl=function(e,t,n,r="vtt"){const s=wI(e),i=t.trim();if(0===i.length)throw new Error("Recording ID cannot be empty");return EI(r),AI(n,`/v1/tokens/${encodeURIComponent(s)}/recordings/${encodeURIComponent(i)}/assets/storyboard.${r.toLowerCase()}`)},exports.getRecordingStreamUrl=function(e,t,n){const r=wI(e),s=t.trim();if(0===s.length)throw new Error("Recording ID cannot be empty");return AI(n,`/v1/tokens/${encodeURIComponent(r)}/recordings/${encodeURIComponent(s)}/assets/stream.m3u8`)},exports.getRecordingThumbnailUrl=function(e,t,n,r="jpg"){const s=wI(e),i=t.trim();if(0===i.length)throw new Error("Recording ID cannot be empty");return EI(r),AI(n,`/v1/tokens/${encodeURIComponent(s)}/recordings/${encodeURIComponent(i)}/assets/thumbnail.${r.toLowerCase()}`)},exports.getSolanaTokenConfig=function(e){const t=Xt(e);return bo.find(e=>Xt(e.symbol)===t)},exports.getStaticTokenMetadata=function(e){const t=Xt(e);return vo[t]},exports.getTieredModerationSavings=function(e,t){if(!QI(e)||null===e.tokensUsed)return 0;const n=1500*t.maxFrames;if(0===n)return 0;const r=(n-e.tokensUsed)/n*100;return Math.max(0,Math.round(r))},exports.getTokenAnimatedUrl=function(e,t,n="gif"){const r=wI(e);return EI(n),AI(t,`/v1/tokens/${encodeURIComponent(r)}/assets/animated.${n.toLowerCase()}`)},exports.getTokenAssetUrl=function(e,t,n,r){const s=wI(e),i=t.trim().toLowerCase();if(0===i.length)throw new Error("Asset type cannot be empty");EI(r);const o=void 0!==r&&r.length>0?`.${r.toLowerCase()}`:"";return AI(n,`/v1/tokens/${encodeURIComponent(s)}/assets/${encodeURIComponent(i)}${o}`)},exports.getTokenImageUrl=function(e,t){const n=wI(e);return AI(t,`/v1/tokens/${encodeURIComponent(n)}/assets/image`)},exports.getTokenLiveStreamUrl=function(e,t){const n=wI(e);return AI(t,`/v1/tokens/${encodeURIComponent(n)}/assets/live.m3u8`)},exports.getTokenPosterUrl=function(e,t){const n=wI(e);return AI(t,`/v1/tokens/${encodeURIComponent(n)}/assets/poster.jpg`)},exports.getTokenStoryboardUrl=function(e,t,n="vtt"){const r=wI(e);return EI(n),AI(t,`/v1/tokens/${encodeURIComponent(r)}/assets/storyboard.${n.toLowerCase()}`)},exports.getTokenThumbnailUrl=function(e,t,n="jpg"){const r=wI(e);return EI(n),AI(t,`/v1/tokens/${encodeURIComponent(r)}/assets/thumbnail.${n.toLowerCase()}`)},exports.getTradeOptionsSchema=Ts,exports.getWalletByRdns=pI,exports.graduateTokenOptionsSchema=ds,exports.graphDataOptionsSchema=us,exports.groupByKey=function(e,t){const n=new Map;for(const r of e){const e=t(r);n.has(e)||n.set(e,[]),n.get(e).push(r)}return n},exports.hasAnyWallet=function(){return null!==hI()},exports.hasMorePages=function(e,t,n){if("number"!=typeof e||!Number.isInteger(e))throw Bt("offset","a non-negative integer",e);if(e<0)throw _t("offset",0,1/0,e);return e+t<n},exports.hexStringExtractionAndNormalization=function(e){if(""===e||"string"!=typeof e)return null;if(e.includes("|")){const t=e.split("|");if(t.length>=2){const e=t[1];if(void 0!==e&&PS(e))return FS(e)}return null}return PS(e)?FS(e):null},exports.imageExtensionSchema=Qr,exports.imageFilenameSchema=Zr,exports.imageMimeTypeSchema=Kr,exports.imageUploadOptionsSchema=is,exports.isAIModerationData=YI,exports.isAIModerationMode=XI,exports.isAIModerationSettings=JI,exports.isAIRecommendation=zI,exports.isActiveUserType=kE,exports.isAnalysisCategory=VI,exports.isAnalysisStatus=HI,exports.isAnalysisTier=jI,exports.isAnalysisType=qI,exports.isBanData=TE,exports.isBanEnforcementEvent=CE,exports.isBurnTokenEntry=lS,exports.isBurnTokensData=uS,exports.isChatDisabledReason=NI,exports.isChatMessageItem=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.id&&"string"==typeof t.tokenName&&"string"==typeof t.userAddress&&"string"==typeof t.content&&"string"==typeof t.createdAt&&"number"==typeof t.flagCount&&"object"==typeof t.reactions},exports.isChatStatusResponse=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"boolean"==typeof t.enabled&&(void 0===t.reason||NI(t.reason))},exports.isClaimableInvite=function(e){if(e.status!==gk.PENDING)return!1;if(null!==e.expiresAt&&void 0!==e.expiresAt){if(nn(e.expiresAt)<=new Date)return!1}return!0},exports.isContentType=kA,exports.isEip1193Provider=nI,exports.isEmptyValue=Gn,exports.isExtendedStreamRole=Gk,exports.isExternalProvider=function(e){return"external"===e.providerType},exports.isFlagAction=NA,exports.isFlagData=CA,exports.isFlagReason=TA,exports.isFlagStatus=IA,exports.isHolderDelta=TI,exports.isHolderDeltaType=function(e){return"string"==typeof e&&(e===kI.NEW_HOLDER||e===kI.EXITED_HOLDER||e===kI.BALANCE_CHANGED)},exports.isLockTokenEntry=VA,exports.isLockTokensData=XA,exports.isMessage=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.id&&"string"==typeof t.type&&(t.type===CS.CHAT_MESSAGE||t.type===CS.COMMENT)&&"string"==typeof t.tokenName&&"string"==typeof t.userAddress&&"string"==typeof t.content&&"string"==typeof t.createdAt},exports.isMessageType=function(e){return e===CS.CHAT_MESSAGE||e===CS.COMMENT},exports.isModeratedToken=ZS,exports.isModerationTiered=QI,exports.isModeratorInvite=QS,exports.isNonEmptyString=Kn,exports.isOverseerInviteStatus=pk,exports.isOverseerStatus=mk,exports.isPinnedMessage=_I,exports.isPrivateKeyProvider=eI,exports.isPublicInviteInfo=ek,exports.isReactionErrorCode=xI,exports.isRecordingStatus=Uk,exports.isSimulcastPlatform=Pk,exports.isStreamChatDeletedEvent=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.messageId&&"string"==typeof t.deletedAt},exports.isStreamChatErrorEvent=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.message},exports.isStreamChatMessage=CI,exports.isStreamChatMessageEvent=function(e){return CI(e)},exports.isStreamChatPinnedEvent=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&_I(t.pinnedMessage)},exports.isStreamChatUnpinnedEvent=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.unpinnedMessageId},exports.isStreamReactionErrorEvent=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.message},exports.isStreamReactionEvent=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.emoji&&"number"==typeof t.timestamp&&"number"==typeof t.streamTime},exports.isStreamStatus=Lk,exports.isStreamStatusEvent=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&Lk(t.status)&&(null===t.playbackId||"string"==typeof t.playbackId)&&"boolean"==typeof t.isLive},exports.isStreamingEvent=function(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.type&&["stream_status","user_banned","user_unbanned","ban_enforcement","content_flagged","flag_resolved","stream_chat_message","stream_chat_updated","stream_chat_deleted","stream_chat_pinned","stream_chat_unpinned","chat_status_changed","viewer_count","recording_status","simulcast_status","download_ready","recordings_count_updated","user_typing","stream_reaction","content_reaction_added","content_reaction_removed","stream_countdown_updated","stream_language_updated","stream_control_status_changed","connection","authenticated","token_subscribed","token_unsubscribed","room_subscribed","room_left"].includes(t.type)},exports.isTokenAccessResult=function(e){if(null==e||"object"!=typeof e)return!1;const t=e,n=t.permissions;return Array.isArray(n)&&n.every(e=>"string"==typeof e)&&(null===t.source||"owner"===t.source||"moderator_invite"===t.source||"api_key"===t.source||"overseer"===t.source)&&(void 0===t.matchedPreset||null===t.matchedPreset||"MODERATOR"===t.matchedPreset||"TECHNICAL_PRODUCER"===t.matchedPreset||"MANAGER"===t.matchedPreset)&&"boolean"==typeof t.isOwner&&"boolean"==typeof t.isOverseer},exports.isTokenBanData=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"number"==typeof t.id&&"string"==typeof t.tokenName&&"string"==typeof t.bannedBy&&"string"==typeof t.createdAt&&(null===t.reason||"string"==typeof t.reason)},exports.isTypingIndicatorEvent=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&Array.isArray(t.typingUsers)&&t.typingUsers.every(RI)},exports.isTypingUser=RI,exports.isUnlockTokenEntry=jA,exports.isUnlockTokensData=YA,exports.isUserBannedEvent=IE,exports.isUserHoldingData=II,exports.isUserUnbannedEvent=NE,exports.isValidAddress=pr,exports.isValidApiKeyRole=mE,exports.isValidBanDuration=xE,exports.isValidBanReason=_E,exports.isValidChatContent=function(e){return!!Kn(e)&&(e.length>=fn.CHAT_MESSAGE.MIN_LENGTH&&e.length<=fn.CHAT_MESSAGE.MAX_LENGTH)},exports.isValidChatTokenName=function(e){return!!Kn(e)&&on.PATTERN.test(e)},exports.isValidGalaChainChannel=function(e){return Object.values(co).includes(e)},exports.isValidInviteCode=JS,exports.isValidInviteStatus=YS,exports.isValidLaunchTokenData=function(e){return Ys(e).success},exports.isValidModeratorRole=XS,exports.isValidTokenBanReason=jk,exports.isValidTokenName=function(e,t=on){if("string"!=typeof e)return!1;const n=e.trim();return 0!==n.length&&t.PATTERN.test(n)},exports.isViewerCountEvent=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"number"==typeof t.viewerCount},exports.isWalletAvailable=async function(e,t){return null!==await pI(e,t)},exports.isoDateStringSchema=Gr,exports.launchTokenDataSchema=ss,exports.loadEnvWithFallback=function(){const e=y.join(process.cwd(),"..","..",".env");m.existsSync(e)&&p.config({path:e});const t=y.join(process.cwd(),".env");m.existsSync(t)&&p.config({path:t})},exports.mergeSafePaginationOptions=function(e,t){return yI({...e,...t})},exports.nonNegativeDecimalStringSchema=Rr,exports.normalizeAddressInput=fr,exports.normalizeDataWithMapping=function(e,t){return e.map(e=>{const n={};for(const[r,s]of Object.entries(t)){const t=s(e);void 0!==t&&(n[r]=t)}return n})},exports.normalizeErrorMessage=function(e,t){return e.toLowerCase().includes(t.toLowerCase())},exports.normalizeLimit=sE,exports.normalizeTokenKey=jt,exports.normalizeTokenName=Vt,exports.normalizeTokenSymbol=Xt,exports.optionalUrlSchema=Dr,exports.pageNumberSchema=Or,exports.paginationResultMetaSchema=vs,exports.parseHttpErrorResponse=function(e){const t={statusCode:0,errorMessage:"Unknown error",raw:e};if(null==e)return t;const n=e;let r=t.statusCode;"number"==typeof n.status?r=n.status:"number"==typeof n.statusCode?r=n.statusCode:"number"==typeof n.code&&(r=n.code);let s,i=t.errorMessage;"string"==typeof n.message?i=n.message:"string"==typeof n.error?i=n.error:e instanceof Error?i=e.message:"string"==typeof e&&(i=e);const o=n.response;if(o){const e=o.data;if("object"==typeof e&&null!==e){s=e;const t=e;"string"==typeof t.message?i=t.message:"string"==typeof t.error&&(i=t.error)}}const a={statusCode:r,errorMessage:i,raw:e};return null!=s&&(a.errorData=s),a},exports.parseLaunchpadVaultAddress=lA,exports.percentileIndexCalculation=function(e,t){if(0===e.length)return-1;if(t<0||t>100)throw new Error(`Percentile must be between 0 and 100, got: ${t}`);const n=(e.length-1)*(t/100),r=Math.floor(n);return Math.min(r,e.length-1)},exports.poolFetchTypeSchema=os,exports.poolPaginationSchema=ps,exports.positiveDecimalStringSchema=xr,exports.priceTickRangeMapping=function(e,t,n=60){const r=ki(e),s=ki(t);if(r.isLessThanOrEqualTo(0)||s.isLessThanOrEqualTo(0))throw new Error("Prices must be positive");if(r.isGreaterThanOrEqualTo(s))throw new Error(`minPrice must be < maxPrice, got: ${r.toString()} >= ${s.toString()}`);const i=Math.floor(Ii(r)),a=Math.ceil(Ii(s)),c=Math.floor(i/n)*n,l=Math.ceil(a/n)*n;return{minTick:c,maxTick:l,actualMinPrice:new o(1.0001).pow(c),actualMaxPrice:new o(1.0001).pow(l)}},exports.privateKeySchema=Hr,exports.providerToWallet=tI,exports.registerInterval=function(e,t){const n=e;return SI.set(n,{createdAt:Date.now(),label:t}),n},exports.requireNonNegative=function(...e){e.forEach(e=>{if(e.isNaN())throw Dt("value","NaN");if(!e.isFinite())throw Rt("value","finite");if(e.isLessThan(0))throw xt("value","0",e.toString())})},exports.requirePositive=_i,exports.requirePositiveWithContext=xi,exports.retryableHttpRequest=async function(e,t){const n=t?.maxRetries??3,r=t?.backoffMs??100,s=t?.retryableStatus??[429,503,504];let i,o=0;for(;o<=n;)try{return await e()}catch(e){i=e,o++;const t=vI(e),a=s.includes(t);if(o>n||!a)throw e;const c=r*Math.pow(2,o-1);await new Promise(e=>setTimeout(e,c))}throw i},exports.reverseBondingCurveConfigSchema=rs,exports.reverseBondingCurveConfigurationSchema=Bs,exports.roleHasSufficientPermission=function(e,t){return e===hE.MANAGER?t!==hE.OWNER:e===hE.OWNER||e===t},exports.roundTickBoundaries=function(e,t,n){if(e>=t)throw new Error(`tickLower must be < tickUpper, got: ${e} >= ${t}`);if(n<=0)throw new Error(`tickSpacing must be > 0, got: ${n}`);return{tickLower:Math.floor(e/n)*n,tickUpper:Math.ceil(t/n)*n}},exports.roundTickToSpacing=function(e,t){if(t<=0)throw new Error(`tickSpacing must be > 0, got: ${t}`);return Math.floor(e/t)*t},exports.safeDivideWithMinimum=function(e,t,n,r="0"){const s=ki(t);if(Ni(s))return ki(r);const i=ki(e).dividedBy(s);if(null!=n){const e=ki(n);if(e.isLessThan(0))throw new Error(`minimum must be >= 0, got: ${e.toString()}`);if(i.isLessThan(e))return e}return i},exports.searchQuerySchema=kr,exports.sellTokensDataSchema=ks,exports.standardLimitSchema=Lr,exports.standardPaginationSchema=hs,exports.stripHexPrefix=ar,exports.subscribeToWalletChanges=function(e){if(!dI())return()=>{};let t=!0,n={wallets:[],byId:new Map,hasWallets:!1};const r=r=>{if(!t)return;const s=r,{info:i,provider:o}=s.detail,a=i.rdns||i.uuid;if(n.byId.has(a))return;const c={id:a,name:i.name,rdns:a,icon:i.icon??"",provider:o,isInjected:!1},l=[...n.wallets,c],u=new Map(n.byId);u.set(c.id,c),n={wallets:l,byId:u,hasWallets:!0,...void 0===l[0]?{}:{primary:l[0]}},e(n)};return window.addEventListener("eip6963:announceProvider",r),fI().then(r=>{t&&(n=r,e(r))}),()=>{t=!1,window.removeEventListener("eip6963:announceProvider",r)}},exports.timestampSchema=Wr,exports.toBackendAddressFormat=hr,exports.toBackendAddressFromEthers=yr,exports.toBaseUnits=vw,exports.tokenCategorySchema=ts,exports.tokenCollectionSchema=ns,exports.tokenDescriptionSchema=Ar,exports.tokenHoldSchema=Ps,exports.tokenListOptionsSchema=Os,exports.tokenNameSchema=wr,exports.tokenSymbolSchema=Er,exports.tokenUrlsSchema=es,exports.tradeCalculationMethodSchema=Cs,exports.tradeCalculationTypeSchema=Ns,exports.tradeLimitSchema=Pr,exports.tradeListParamsSchema=Is,exports.tradePaginationSchema=fs,exports.tradePaginationWithFiltersSchema=ys,exports.tradeTypeBackendSchema=Es,exports.tradeTypeSchema=ws,exports.transactionIdSchema=qr,exports.transformRawApiTokenToDomainModel=function(e){if(null==e||"object"!=typeof e)throw new Error("Token must be an object");const t=e,n=(Kn(t.name)?t.name:void 0)??(Kn(t.tokenName)?t.tokenName:void 0)??"";if(!Kn(n))throw new Error("Token name is required and must be a non-empty string");const r=(Kn(t.symbol)?t.symbol:void 0)??(Kn(t.tokenSymbol)?t.tokenSymbol:void 0)??"";if(!Kn(r))throw new Error("Token symbol is required and must be a non-empty string");let s=8;"number"==typeof t.decimals&&t.decimals>=0&&(s=Math.floor(t.decimals));const i={name:n,symbol:r,decimals:s};return Kn(t.address)&&(i.address=t.address),"boolean"==typeof t.verified&&(i.verified=t.verified),i},exports.trimmedLengthValidation=function(e){return null==e||"string"!=typeof e||0===e.trim().length},exports.uniqueKeySchema=zr,exports.unregisterAllIntervals=function(){const e=SI.size;return SI.clear(),e},exports.unregisterInterval=function(e){const t=e;SI.delete(t)},exports.updateProfileDataSchema=Ls,exports.uploadProfileImageOptionsSchema=Us,exports.urlSchema=Br,exports.userLimitSchema=Ur,exports.userPaginationSchema=gs,exports.userTokenNameSchema=Sr,exports.userTokenTypeSchema=Ds,exports.userTokensPaginationSchema=ms,exports.validateAddress=Hs,exports.validateAmountString=zs,exports.validateBanTokenOptions=Xk,exports.validateBuyTokensData=oi,exports.validateCalculatePreMintData=di,exports.validateChatMessageId=function(e){if(!Kn(e))throw St("id","Message ID");if(!pn.CHAT_MESSAGE.PATTERN.test(e))throw new yt("Invalid message ID format. Expected: chat-{timestamp}-{uuid}","id",mt.INVALID_FORMAT)},exports.validateCheckPoolOptions=Zs,exports.validateConstrainedEnumVariant=function(e,t,n){if(!t.includes(e))throw new yt(`${n} must be one of [${t.map(e=>String(e)).join(", ")}], received "${e}"`,n,"INVALID_ENUM_VALUE")},exports.validateCreateApiKeyOptions=yE,exports.validateCreateChatMessageOptions=function(e){if(!Kn(e.tokenName))throw St("tokenName");if(e.tokenName.length>cn.MAX_LENGTH)throw new yt(`tokenName must be at most ${cn.MAX_LENGTH} characters`,"tokenName",mt.TOO_LONG);eN(e.content)},exports.validateCreateCommentOptions=function(e){if(!Kn(e.tokenName))throw St("tokenName","Token name");const{MIN_LENGTH:t,MAX_LENGTH:n,PATTERN:r}=an;if(e.tokenName.length<t||e.tokenName.length>n||!r.test(e.tokenName))throw kt("tokenName",`${t}-${n} alphanumeric characters`,"Token name");ZI(e.content)},exports.validateCreateMessageOptions=function(e){if(void 0===e.type||null===e.type)throw St("type");if(e.type!==CS.CHAT_MESSAGE&&e.type!==CS.COMMENT)throw new yt(`type must be one of: ${Object.values(CS).join(", ")}`,"type",mt.INVALID_VALUE);if(!Kn(e.tokenName))throw St("tokenName");if(e.tokenName.length>cn.MAX_LENGTH)throw new yt(`tokenName must be at most ${cn.MAX_LENGTH} characters`,"tokenName",mt.TOO_LONG);if(!Kn(e.content))throw St("content");if(0===e.content.trim().length)throw Ut("content","Content");const t=e.type===CS.CHAT_MESSAGE?_S.CONTENT.CHAT_MAX_LENGTH:_S.CONTENT.COMMENT_MAX_LENGTH;if(e.content.length>t)throw Lt("content",t,e.content.length)},exports.validateCreateModeratorInviteOptions=function(e){const t=[],n=e.inviteScope??qS.TOKEN;return void 0===e.inviteScope||tk(e.inviteScope)||gt(t,()=>{throw Ot("inviteScope",e.inviteScope,zS,"Invite scope")}),n===qS.TOKEN?gt(t,()=>{jn(e.tokenName??"","tokenName",on)}):n===qS.ALL_OWNER_TOKENS&&void 0!==e.tokenName&&""!==e.tokenName&&t.push("Token name should not be provided for ALL_OWNER_TOKENS scope invites"),XS(e.role)||gt(t,()=>{throw Ot("role",e.role,HS,"Role")}),void 0!==e.description&&""!==e.description&>(t,()=>{Mn(e.description,fn.DESCRIPTION.MAX_LENGTH,"description")}),void 0===e.expiresAt||""===e.expiresAt||rn(e.expiresAt)||gt(t,()=>{throw function(e,t="a valid date",n){const r=Et(e,n);return new yt(`${r} must be ${t}`,e,"INVALID_DATE")}("expiresAt","ISO 8601 format")}),t},exports.validateCreateOverseerDirectOptions=kk,exports.validateCreateOverseerInviteOptions=yk,exports.validateCreateTradeData=ii,exports.validateDecimalRangeStrict=function(e,t,n,r){const s="string"==typeof e?parseFloat(e):e;if(!isFinite(s))throw new yt(`${r} must be a valid finite number between ${t} and ${n}`,r,"INVALID_NUMBER");if(s<t||s>n)throw _t(r,t,n,s,r)},exports.validateFeePortionConstraints=Fn,exports.validateFetchGalaBalanceOptions=ti,exports.validateFetchMessagesOptions=function(e){const t=void 0!==e.type,n=void 0!==e.tokenName&&""!==e.tokenName,r=void 0!==e.userAddress&&""!==e.userAddress;if(!t&&!n&&!r)throw Mt(["type","tokenName","userAddress"]);if(void 0!==e.type&&e.type!==CS.CHAT_MESSAGE&&e.type!==CS.COMMENT)throw new yt(`type must be one of: ${Object.values(CS).join(", ")}`,"type",mt.INVALID_VALUE);NS(e.tokenName,e.userAddress),void 0!==e.pageSize&&Hn(0,void 0,dn.MAX_LIMIT,e.pageSize)},exports.validateFetchPoolDetailsData=hi,exports.validateFetchTokenBalanceOptions=si,exports.validateFullName=Vs,exports.validateGetAmountOptions=ui,exports.validateGetChatMessagesOptions=function(e){if(!(void 0!==e.tokenName&&""!==e.tokenName||void 0!==e.userAddress&&""!==e.userAddress))throw new yt("At least one of tokenName or userAddress is required","options",mt.REQUIRED);NS(e.tokenName,e.userAddress),void 0!==e.pageSize&&Hn(0,void 0,dn.MAX_LIMIT,e.pageSize)},exports.validateGetCommentsOptions=function(e){if(!(void 0!==e.tokenName&&""!==e.tokenName||void 0!==e.userAddress&&""!==e.userAddress))throw Mt(["tokenName","userAddress"]);if(void 0!==e.tokenName&&""!==e.tokenName){const{MIN_LENGTH:t,MAX_LENGTH:n,PATTERN:r}=an;if(e.tokenName.length<t||e.tokenName.length>n||!r.test(e.tokenName))throw kt("tokenName",`${t}-${n} alphanumeric characters`,"Token name")}Hn(0,void 0,dn.MAX_LIMIT,e.pageSize,e.cursor)},exports.validateGetTokenBanOptions=Qk,exports.validateGetTradeOptions=ci,exports.validateGetTradesOptions=OS,exports.validateImageUploadOptions=Qs,exports.validateInviteCode=function(e){const t=[];return Kn(e)?JS(e)||t.push("Invalid invite code format"):t.push(St("inviteCode","Invite code").message),t},exports.validateLaunchTokenData=fi,exports.validateListApiKeysOptions=wE,exports.validateListModeratorInvitesOptions=function(e){const t=[];return gt(t,()=>{jn(e.tokenName??"","tokenName",on)}),void 0===e.status||YS(e.status)||gt(t,()=>{throw Ot("status",e.status,jS,"Status")}),gt(t,()=>{Hn(0,void 0,ln,e.pageSize)}),t},exports.validateListOverseerInvitesOptions=bk,exports.validateListOverseersOptions=vk,exports.validateListTokenBansOptions=Jk,exports.validateListUsersOptions=Sk,exports.validateMessageId=function(e){if(!Kn(e))throw St("id","Message ID");const t=pn.CHAT_MESSAGE.PATTERN.test(e),n=/^msg-\d{13}-[a-f0-9]{32}$/.test(e);if(!t&&!n)throw new yt("Invalid message ID format. Expected: chat-{timestamp}-{uuid} or msg-{timestamp}-{uuid}","id",mt.INVALID_FORMAT)},exports.validateMinMaxRelationship=function(e,t,n,r){const s="string"==typeof e?parseFloat(e):e,i="string"==typeof t?parseFloat(t):t;if(!isFinite(s))throw new yt(`${n} must be a valid finite number`,n,"INVALID_MIN_VALUE");if(!isFinite(i))throw new yt(`${r} must be a valid finite number`,r,"INVALID_MAX_VALUE");if(s>i)throw new yt(`${n} (${s}) must be less than or equal to ${r} (${i})`,n,"INVALID_RANGE")},exports.validateOptionalTokenName=function(e,t="tokenName",n=on){if(null==e)return;if("string"!=typeof e)throw Bt(t,"a string",e);const r=e.trim();if(0!==r.length&&!n.PATTERN.test(r))throw new yt(`${t} must be ${n.MIN_LENGTH}-${n.MAX_LENGTH} alphanumeric characters`,t,mt.INVALID_FORMAT)},exports.validateOverseerInviteCode=wk,exports.validateOverseerInviteId=Ak,exports.validateOverseerWalletAddress=Ek,exports.validatePaginationParams=function(e,t,n){if("number"!=typeof e||!Number.isInteger(e)||e<0)throw Bt("offset","a non-negative integer",e);Ln(t,"limit")},exports.validateSearchQuery=js,exports.validateSellTokensData=ai,exports.validateSortOrderDirection=Pn,exports.validateTokenDescription=Ws,exports.validateTokenListOptions=ei,exports.validateTokenName=Xn,exports.validateTokenSymbol=Gs,exports.validateTokenUrls=Js,exports.validateTradeListParams=li,exports.validateUnbanTokenOptions=Yk,exports.validateUpdateApiKeyOptions=bE,exports.validateUpdateChatMessageOptions=function(e){eN(e.content)},exports.validateUpdateCommentOptions=function(e){ZI(e.content)},exports.validateUpdateMessageOptions=function(e){if(!Kn(e.content))throw St("content");if(0===e.content.trim().length)throw Ut("content","Content");const t=Math.max(_S.CONTENT.CHAT_MAX_LENGTH,_S.CONTENT.COMMENT_MAX_LENGTH);if(e.content.length>t)throw Lt("content",t,e.content.length)},exports.validateUpdatePlatformConfigOptions=Ik,exports.validateUpdateProfileData=ni,exports.validateUpdateTokenConfigOptions=xS,exports.validateUploadProfileImageOptions=ri,exports.validateUserTokenName=Xs,exports.validateVaultAddress=qs,exports.vaultAddressSchema=_r,exports.walletToProvider=function(e){if(e)return to.fromWallet(e)},exports.wasModerationEscalated=function(e){return!0===e.escalatedFromQuick};
|