@gala-chain/launchpad-sdk 7.0.0-beta.3 → 7.0.0-beta.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -0
- package/dist/LaunchpadSDK.d.ts +10 -8
- package/dist/LaunchpadSDK.d.ts.map +1 -1
- package/dist/api/dto/BondingCurveDTOs.d.ts +2 -2
- package/dist/api/dto/BondingCurveDTOs.d.ts.map +1 -1
- package/dist/api/dto/BurnTokensDto.d.ts +1 -1
- package/dist/api/dto/BurnTokensDto.d.ts.map +1 -1
- package/dist/api/dto/LockTokenDto.d.ts +1 -1
- package/dist/api/dto/LockTokenDto.d.ts.map +1 -1
- package/dist/api/dto/TransferTokenDto.d.ts +1 -1
- package/dist/api/dto/TransferTokenDto.d.ts.map +1 -1
- package/dist/api/dto/UnlockTokenDto.d.ts +1 -1
- package/dist/api/dto/UnlockTokenDto.d.ts.map +1 -1
- package/dist/bridge/strategies/EthereumBridgeStrategy.d.ts.map +1 -1
- package/dist/constants/version.generated.d.ts +1 -1
- package/dist/helpers/sdk.d.ts.map +1 -1
- package/dist/index.browser.esm.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.esm.js +1 -1
- package/dist/index.js +1 -1
- package/dist/launchpad/writes.d.ts.map +1 -1
- package/dist/native.cjs +1 -1
- package/dist/native.esm.js +1 -1
- package/dist/react.cjs +1 -1
- package/dist/react.esm.js +1 -1
- package/dist/schemas/user.d.ts +6 -6
- package/dist/schemas/user.d.ts.map +1 -1
- package/dist/schemas/validators.d.ts +1 -1
- package/dist/services/ContentReactionService.d.ts.map +1 -1
- package/dist/services/LaunchpadService.d.ts +1 -6
- package/dist/services/LaunchpadService.d.ts.map +1 -1
- package/dist/services/ModeratorService.d.ts.map +1 -1
- package/dist/services/NftCollectionService.d.ts.map +1 -1
- package/dist/services/UserService.d.ts +3 -10
- package/dist/services/UserService.d.ts.map +1 -1
- package/dist/signing/signers.d.ts +4 -2
- package/dist/signing/signers.d.ts.map +1 -1
- package/dist/types/backend-responses.d.ts +1 -1
- package/dist/types/backend-responses.d.ts.map +1 -1
- package/dist/types/dto.d.ts +2 -2
- package/dist/types/dto.d.ts.map +1 -1
- package/dist/types/options.dto.d.ts +10 -10
- package/dist/types/user.dto.d.ts +13 -5
- package/dist/types/user.dto.d.ts.map +1 -1
- package/dist/wallet/GalaChainConnectProvider.d.ts.map +1 -1
- package/dist/wallet.cjs +1 -1
- package/dist/wallet.esm.js +1 -1
- package/package.json +32 -27
package/dist/index.esm.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{getAddress as e,Wallet as t,isAddress as n,JsonRpcProvider as r,Contract as i,Signature as s,keccak256 as o,toUtf8Bytes as a,Mnemonic as c,HDNodeWallet as l,computeAddress as u,SigningKey as d}from"ethers";import{BrowserWalletSigner as h,GalaWalletSigner as g,PrivateKeySigner as f,GSwap as m}from"@gala-chain/gswap-sdk";export{GSwap}from"@gala-chain/gswap-sdk";import{z as p}from"zod";import*as y from"uuid";import{v4 as b}from"uuid";import*as v from"node:crypto";import{ChainCallDTO as w,calculatePersonalSignPrefix as E,SigningClient as A,SigningType as k}from"@gala-chain/connect";import{TokenClassKey as S}from"@gala-chain/api";import T from"bignumber.js";import{io as I}from"socket.io-client";import N from"axios";import*as C from"dotenv";import*as _ from"fs";import*as x from"path";const R={UPLOAD_IMAGE:"/v1/tokens/:tokenName/image",FETCH_POOLS:"/v1/tokens",GET_TOKEN:"/v1/tokens/:tokenName",GET_TOKEN_DISTRIBUTION:"/v1/holders",CHART:"/v1/chart",GET_TRADES:"/v1/tokens/:tokenName/trades",GET_PROFILE:"/v1/users/:address",UPDATE_PROFILE:"/v1/users/me",GET_CURRENT_USER:"/v1/users/me/profile",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"},B="/v1/users/referrals/url",D="/v1/users/referrals",M="/v1/users/referrals/summary",O="/market/price-series",U="/v1/tokens/:tokenName/start-stream",L="/v1/tokens/:tokenName/stop-stream",P="/v1/tokens/:tokenName/stream/disable",F="/v1/tokens/:tokenName/stream/enable",$="/v1/tokens/:tokenName/reset-key",K="/v1/tokens/:tokenName/recordings",G="/v1/tokens/:tokenName/recordings/:assetId/download",H="/v1/tokens/:tokenName/recordings/:assetId",W="/v1/tokens/:tokenName/simulcasts",q="/v1/tokens/:tokenName/simulcasts",j="/v1/tokens/:tokenName/simulcasts/:targetId",V="/v1/config",z="/v1/config",X="/v1/config",J="/v1/tokens/:tokenName/role",Y="/v1/roles",Q="/v1/permissions",Z="/v1/tokens/:tokenName/credentials",ee="/auth/login",te="/auth/logout",ne="/auth/refresh",re="/auth/session",ie="/v1/tokens/:tokenName/bans",se="/v1/tokens/:tokenName/bans",oe="/v1/tokens/:tokenName/bans/:userAddress",ae="/v1/tokens/:tokenName/bans/:userAddress",ce="/v1/tokens/:tokenName/active-users",le="/v1/user-bans",ue="/v1/user-bans",de="/v1/user-bans/:userAddress",he="/v1/user-bans/:userAddress",ge={CREATE:"/v1/api-keys",LIST:"/v1/api-keys",GET:"/v1/api-keys/:id",UPDATE:"/v1/api-keys/:id",REVOKE:"/v1/api-keys/:id"},fe="/v1/moderator-invites",me="/v1/moderator-invites/claim",pe="/v1/moderated-tokens",ye="/v1/moderator-invites",be="/v1/moderator-invites/:id",ve="/v1/moderator-invites/:id/role",we="/v1/moderator-invites/:id",Ee="/v1/moderator-invites/code/:code",Ae={CREATE:"/v1/content-flags",LIST:"/v1/content-flags",DISMISS:"/v1/content-flags/:id/dismiss",ACTION:"/v1/content-flags/:id/action"},ke="/v1/overseer-invites",Se="/v1/overseer-invites",Te="/v1/overseer-invites/code/:code",Ie="/v1/overseer-invites/claim",Ne="/v1/overseer-invites/:id",Ce="/v1/overseers",_e="/v1/overseers",xe="/v1/overseers/:address",Re="/v1/overseers/me",Be="/v1/overseer-summary",De="/v1/overseer-summary/bans",Me="/v1/overseer-summary/token-bans",Oe="/v1/overseer-summary/invites",Ue="/v1/overseer-summary/flags",Le="/v1/overseer-summary/users",Pe="/v1/users",Fe="/v1/users/:address/summary",$e="/v1/cache/flush/address/:address",Ke="/v1/cache/flush/token/:tokenName",Ge="/v1/cache/flush/all",He="/v1/cache/flush/wallet-aliases/:address",We="/v1/cache/flush/wallet-aliases",qe="/v1/token-bans",je="/v1/token-bans",Ve="/v1/token-bans/:tokenName",ze="/v1/token-bans/:tokenName",Xe="/v1/reactions",Je="/v1/reactions",Ye="/v1/trades",Qe={GET_MESSAGES:"/v1/messages",CREATE_MESSAGE:"/v1/messages",UPDATE_MESSAGE:"/v1/messages/:id",DELETE_MESSAGE:"/v1/messages/:id",GET_PINNED:"/v1/messages/pinned",PIN_MESSAGE:"/v1/messages/:id/pin",UNPIN_MESSAGE:"/v1/messages/:id/pin",GET_MESSAGE_STATS:"/v1/messages/stats"},Ze="/v1/restricted-token-names",et="/v1/restricted-token-names",tt="/live/:tokenName/chat",nt="/live/:tokenName/chat",rt="/live/:tokenName/chat",it="/live/:tokenName/chat/slow-mode",st={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"},ot="/v1/stats",at="/v1/trading/fee",ct="/v1/trading/sale-details",lt="/v1/trading/quote",ut="/v1/trading/premint-quote",dt={GET_LEADERBOARD:"/weekly-challenge",GET_TOKEN_HISTORY:"/weekly-challenge/history/:vaultAddress"},ht="/v1/notifications/register",gt="/v1/notifications/unregister",ft="/v1/notifications/preferences",mt="/v1/notifications/preferences",pt="/v1/config/client-flags",yt={NATIVE:"native",EXACT:"exact"},bt={RECENT:"recent",POPULAR:"popular"},vt={LOCAL:"local",EXTERNAL:"external"};function wt(e){return e instanceof Error}function Et(e){return wt(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 At(e){return wt(e)||"object"==typeof e&&null!==e&&"stack"in e&&"string"==typeof e.stack?e.stack:void 0}function kt(e){if(function(e){return"object"==typeof e&&null!==e&&"code"in e&&("string"==typeof e.code||"number"==typeof e.code)}(e))return e.code}function St(e){return"object"==typeof e&&null!==e&&"message"in e&&("response"in e||"request"in e||"config"in e)}function Tt(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 It(e){if(null==e||"object"!=typeof e)return"";const t=e.Message;return"string"==typeof t&&t.trim().length>0?` - ${t}`:""}function Nt(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 Ct="Token name is required and must be a string",_t=e=>`Could not find vault address for token: ${e}`,xt={REQUIRED:"REQUIRED",INVALID_TYPE:"INVALID_TYPE",INVALID_VALUE:"INVALID_VALUE",INVALID_FORMAT:"INVALID_FORMAT",TOO_SHORT:"TOO_SHORT",TOO_LONG:"TOO_LONG",TOO_LARGE:"TOO_LARGE",TOO_SMALL:"TOO_SMALL",EMPTY_ARRAY:"EMPTY_ARRAY",ARRAY_TOO_LARGE:"ARRAY_TOO_LARGE",ZERO_VALUE:"ZERO_VALUE",INVALID_TICK_SPACING:"INVALID_TICK_SPACING",INVALID_FEE_TIER:"INVALID_FEE_TIER",INVALID_RANGE:"INVALID_RANGE",INVALID_PARAMETERS:"INVALID_PARAMETERS",NOT_FOUND:"NOT_FOUND",INVALID_DATA:"INVALID_DATA"};class Rt extends Error{constructor(e,t,n){super(e),this.field=t,this.code=n,this.name="ValidationError"}}class Bt extends Rt{constructor(e){super(e,"token","TOKEN_RESTRICTED"),this.name="TokenRestrictedError"}}class Dt extends Error{constructor(e,t,n){super(e),this.statusCode=t,this.originalError=n,this.name="NetworkError"}}class Mt extends Error{constructor(e,t){super(e),this.field=t,this.name="ConfigurationError"}}class Ot extends Error{constructor(e,t,n){super(e),this.transactionId=t,this.code=n,this.name="TransactionError"}}function Ut(e,t){return void 0!==t?t:e.charAt(0).toUpperCase()+e.slice(1)}function Lt(e,t){return new Rt(`Token "${e}" not found. Please verify the token name is correct.`,"tokenName","TOKEN_NOT_FOUND")}function Pt(e,t){const n=Ut(e,t);return new Rt(`${n} is required`,e,"REQUIRED")}function Ft(e,t,n){const r=Ut(e,n);return new Rt(`${r} must be ${t}`,e,"INVALID_FORMAT")}function $t(e,t,n){return new Dt(e,t,n)}function Kt(e,t){return new Mt(e,t)}function Gt(e,t,n){return new Ot(e,t,n)}function Ht(e,t,n,r){n&&n.error(`${t}:`,e);const i=St(e)?e.response?.status:void 0;return $t(`${t}: ${Et(e)}`,i,wt(e)?e:void 0)}function Wt(e,t,n,r,i){const s=Ut(e,i);return new Rt(`${s} must be between ${t} and ${n}${void 0!==r?`, received: ${r}`:""}`,e,"OUT_OF_RANGE")}function qt(e,t,n,r){const i=Ut(e,r);return new Rt(`${i} must be at least ${t}${void 0!==n?`, received: ${n}`:""}`,e,"TOO_SMALL")}function jt(e,t,n,r){const i=Ut(e,r);return new Rt(`${i} must be at most ${t}${void 0!==n?`, received: ${n}`:""}`,e,"TOO_LARGE")}function Vt(e,t,n,r){const i=Ut(e,r),s=void 0!==n?`, received: ${"object"==typeof n?"object":String(n)}`:"";return new Rt(`${i} must be ${t}${s}`,e,"INVALID_TYPE")}function zt(e,t,n){const r=Ut(e,n);return new Rt(`${r} must be a valid number${void 0!==t?`: "${t}"`:""}`,e,"INVALID_NUMBER")}function Xt(e,t,n,r){const i=Ut(e,r);return new Rt(`Invalid ${i}: ${t}. Must be one of: ${n.join(", ")}`,e,"INVALID_ENUM")}function Jt(e,t){if(e.length<2)return Pt(void 0!==e[0]&&""!==e[0]?e[0]:"field");let n;if(2===e.length)n=e.join(" or ");else{n=`${e.slice(0,-1).join(", ")} or ${e[e.length-1]??"field"}`}return new Rt(`At least one of ${n} must be provided`,e[0],"REQUIRED")}function Yt(e,t,n,r){const i=Ut(e,r);return new Rt(`${i} must be at most ${t} characters${void 0!==n?`, received: ${n}`:""}`,e,"TOO_LONG")}function Qt(e,t){const n=Ut(e,t);return new Rt(`${n} cannot be empty`,e,"EMPTY_STRING")}function Zt(e){return null!=e&&"object"==typeof e&&"data"in e}function en(e,t,n=!1){const r=!0===e.error,i=n&&(null===e.data||void 0===e.data);if(r||i){const n=e?.statusCode??e.status??void 0;throw $t(e?.message??t,n)}}function tn(e){if(Zt(e))return e.data}function nn(e,t="No data found in response"){if(!Zt(e))throw $t(t);const n=e.data;if(null==n)throw $t(t);return n}async function rn(e,t={}){return an(e,t,e=>{if(void 0===e.data)throw new Rt(`${t.errorContext??"Operation failed"}: No data returned from API`,"data","NO_DATA");return e.data})}async function sn(e,t={}){const{errorContext:n="Operation failed",logger:r,debugLogEnabled:i=!1}=t;i&&r&&r.debug(`${n}: starting operation`);try{const t=await e();return i&&r&&r.debug(`${n}: completed successfully`),t}catch(e){throw r&&r.error(n,{error:e}),e}}async function on(e,t={}){return an(e,t,e=>e)}async function an(e,t,n){const{errorContext:r="Operation failed",logger:i,debugLogEnabled:s=!1}=t;s&&i&&i.debug(`${r}: starting operation`);try{const t=await e();if(null==t)throw new Rt(`${r}: No response from server`,"response","NO_RESPONSE");return en(t,r,!0),s&&i&&i.debug(`${r}: completed successfully`),n(t)}catch(e){throw i&&i.error(r,{error:e}),e}}const cn={BASE_PRICE:1650667151e-14,PRICE_SCALING_FACTOR:1166069e-12,TRADING_FEE_FACTOR:.001,GAS_FEE:"1",DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY:1e7};function ln(e){return e.trim().toLowerCase()}function un(e){return e.trim().toUpperCase()}function dn(e){return e.trim().toUpperCase()}var hn;!function(e){e.DEBUG="DEBUG",e.INFO="INFO",e.WARN="WARN",e.ERROR="ERROR"}(hn||(hn={}));class gn{constructor(e){this.levelPriority={[hn.DEBUG]:0,[hn.INFO]:1,[hn.WARN]:2,[hn.ERROR]:3},this.debugEnabled=e.debug,this.context=e.context??"SDK",this.minLevel=e.minLevel??(e.debug?hn.DEBUG:hn.INFO)}debug(e,t){this.log(hn.DEBUG,e,t)}info(e,t){this.log(hn.INFO,e,t)}warn(e,t){this.log(hn.WARN,e,t)}error(e,t){this.log(hn.ERROR,e,t)}log(e,t,n){if(this.levelPriority[e]<this.levelPriority[this.minLevel])return;if(e===hn.DEBUG&&!this.debugEnabled)return;const r=`[${(new Date).toISOString()}] [${this.context}] [${e}]`,i=this.getConsoleMethod(e);void 0!==n?wt(n)?i(`${r} ${t}`,n.message,At(n)??""):i(`${r} ${t}`,n):i(`${r} ${t}`)}getConsoleMethod(e){switch(e){case hn.DEBUG:return console.debug;case hn.INFO:return console.info;case hn.WARN:return console.warn;case hn.ERROR:return console.error;default:return console.log}}child(e){return new gn({debug:this.debugEnabled,context:`${this.context}:${e}`,minLevel:this.minLevel})}isDebugEnabled(){return this.debugEnabled&&this.levelPriority[hn.DEBUG]>=this.levelPriority[this.minLevel]}}function fn(e){return"string"==typeof e&&e.trim().length>0}function mn(e){return null==e||""===e}function pn(e){return null==e}const yn=new gn({debug:!1,context:"DateUtils"});function bn(e,t){if(null==e)return new Date;if(e instanceof Date)return isNaN(e.getTime())?new Date:e;try{const t=new Date(e);return isNaN(t.getTime())?(yn.warn(`Invalid date string received: "${e}". Using fallback.`),new Date):t}catch(t){return yn.warn(`Date parsing error for "${e}":`,t),new Date}}function vn(e){if(null==e)return!1;if(e instanceof Date)return!isNaN(e.getTime());if("string"!=typeof e)return!1;const t=new Date(e);return!isNaN(t.getTime())}function wn(e){return Date.now()-e}const En={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]+$/},kn={MIN_LENGTH:1,MAX_LENGTH:50},Sn=100,Tn=20,In={MAX_LIMIT:50,DEFAULT_OFFSET:0,DEFAULT_LIMIT:20},Nn={PATTERN:/^(eth\|[0-9a-fA-F]{40}|client\|[a-zA-Z0-9_-]+)$/},Cn={MAX_LENGTH:100},_n={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}},xn={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})$/}},Rn=60,Bn=31536e3,Dn={MAX_LENGTH:64,PATTERN:/^(galaswap-operation-|galaconnect-operation-)/},Mn={PATTERN:/^[a-fA-F0-9]{64}$/},On={STREAM_URL_PATTERN:/^(rtmps?|srt):\/\/.+/},Un=50,Ln=1,Pn=100,Fn={FULL_NAME:{MIN_LENGTH:1,MAX_LENGTH:100,ALPHABETS_ONLY_PATTERN:/^[a-zA-Z]+(?:\s[a-zA-Z]+)?$/}};function $n(e,t){if(mn(e))return t;try{return JSON.parse(e)}catch{return t}}function Kn(e,t=0){if(mn(e))return t;if("number"==typeof e)return isNaN(e)||!isFinite(e)?t:e;const n=parseFloat(e);return isNaN(n)||!isFinite(n)?t:n}function Gn(e,t,n){if(pn(e))return t;if("number"==typeof e)return isNaN(e)?t:e;const r=Number(e);return isNaN(r)?t:r}function Hn(e,t,n){if(pn(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 Wn(e,t){if(pn(e)||""===e)throw Pt(t);if(T.isBigNumber(e)){if(e.isNaN())throw zt(t,"NaN");return e}try{const n=new T(e);if(n.isNaN())throw zt(t,e);if(!n.isFinite())throw zt(t,e);return n}catch(n){if(n instanceof Rt)throw n;throw zt(t,e)}}function qn(e,t=0){if(pn(e))return t;if("number"==typeof e)return isNaN(e)?t:e;return Kn(String(e).replace("%","").trim(),t)}function jn(e,t=18){const n=Kn(e,0);if(0===n)return"0";return n.toFixed(t).replace(/\.?0+$/,"")}function Vn(e){return jn(e,8)}function zn(e){return jn(e,18)}function Xn(e,t,n,r){if("number"!=typeof e)throw Vt(r,"a number",e,r);if(e<t||e>n)throw Wt(r,t,n,e)}function Jn(e,t,n){if("string"!=typeof e)throw Vt(n,"a string",e,n);if(e.length>t)throw jt(n,t,e.length)}function Yn(e,t){if("number"!=typeof e)throw Vt(t,"a number",e,t);if(!Number.isInteger(e))throw Vt(t,"an integer",e,t);if(e<=0)throw qt(t,1,e,t)}function Qn(e,t,n=!1){if("string"!=typeof e)throw Vt(t,"a string",e,t);if(!n&&0===e.trim().length)throw Pt(t,`${t} (non-empty string)`)}function Zn(e,t){if("ASC"!==e&&"DESC"!==e)throw new Rt(`${t} must be either 'ASC' or 'DESC'`,t,"INVALID_ENUM_VALUE")}function er(e,t,n,r){const i="string"==typeof e?parseFloat(e):e;if(!isFinite(i))throw new Rt(`${r} must be a valid finite number between ${t} and ${n}`,r,"INVALID_NUMBER");if(i<t||i>n)throw Wt(r,t,n,i,r)}function tr(e,t,n){const r="string"==typeof e?parseFloat(e):e,i="string"==typeof t?parseFloat(t):t;if(!isFinite(r))throw new Rt(`${n} minFee must be a valid finite number`,n,"INVALID_FEE_MINIMUM");if(!isFinite(i))throw new Rt(`${n} maxFee must be a valid finite number`,n,"INVALID_FEE_MAXIMUM");if(r<.1)throw new Rt(`${n} minFee must be >= 0.1, received ${r}`,n,"INVALID_FEE_MINIMUM");if(i>.5)throw new Rt(`${n} maxFee must be <= 0.5, received ${i}`,n,"INVALID_FEE_MAXIMUM");if(r>i)throw new Rt(`${n} minFee (${r}) must be <= maxFee (${i})`,n,"INVALID_FEE_RANGE")}function nr(e,t,n,r){const i="string"==typeof e?parseFloat(e):e,s="string"==typeof t?parseFloat(t):t;if(!isFinite(i))throw new Rt(`${n} must be a valid finite number`,n,"INVALID_MIN_VALUE");if(!isFinite(s))throw new Rt(`${r} must be a valid finite number`,r,"INVALID_MAX_VALUE");if(i>s)throw new Rt(`${n} (${i}) must be less than or equal to ${r} (${s})`,n,"INVALID_RANGE")}function rr(e,t,n){if(!t.includes(e))throw new Rt(`${n} must be one of [${t.map(e=>String(e)).join(", ")}], received "${e}"`,n,"INVALID_ENUM_VALUE")}const ir={ETH_ADDRESS:/^0x[0-9a-fA-F]{40}$/,BACKEND_ADDRESS:/^eth\|(0x)?[0-9a-fA-F]{40}$/,CLIENT_ADDRESS:/^client\|[a-zA-Z0-9_-]+$/},sr=fn,or=mn,ar=pn;function cr(e,t,n=100,r,i){if(void 0!==i&&"string"!=typeof i)throw new Rt("cursor must be a string","cursor",xt.INVALID_TYPE);const s=r??t,o=void 0!==r?"pageSize":"limit";if(void 0!==s&&(Yn(s,o),s>n))throw new Rt(`${o} must be at most ${n}`,o,xt.TOO_LARGE)}function lr(e){const t=Object.values(e);return e=>"string"==typeof e&&t.includes(e)}function ur(e){return Object.values(e)}function dr(e,t,n,r={}){const{description:i="parameter",treatEmptyAsNull:s=!0}=r,o=e[t],a=e[n],c=null!=o&&(!s||""!==o),l=null!=a&&(!s||""!==a);if(!c&&!l)throw Kt(`Either ${t} or ${n} must be provided (${i})`,n);if(c&&l)throw Kt(`Cannot provide both ${t} and ${n}. Provide exactly one (${i}).`,n);return{chosen:c?t:n,hasA:c,hasB:l}}function hr(e,t="tokenName",n=En){if(!sr(e))throw Pt(t);const r=e.trim();if(0===r.length)throw Pt(t);if(r.length<n.MIN_LENGTH)throw Wt(t,n.MIN_LENGTH,n.MAX_LENGTH,r.length,`${t} length`);if(r.length>n.MAX_LENGTH)throw Wt(t,n.MIN_LENGTH,n.MAX_LENGTH,r.length,`${t} length`);if(!n.PATTERN.test(r))throw new Rt(`${t} must contain only alphanumeric characters`,t,xt.INVALID_FORMAT)}function gr(e,t="tokenName",n=En){if(null==e)return;if("string"!=typeof e)throw Vt(t,"a string",e);const r=e.trim();if(0!==r.length&&!n.PATTERN.test(r))throw new Rt(`${t} must be ${n.MIN_LENGTH}-${n.MAX_LENGTH} alphanumeric characters`,t,xt.INVALID_FORMAT)}function fr(e,t=En){if("string"!=typeof e)return!1;const n=e.trim();return 0!==n.length&&t.PATTERN.test(n)}function mr(e,t="tokenName",n=En){if(null==e)throw Pt(t,t);if("string"!=typeof e)throw Vt(t,"a string",e);const r=e.trim();if(0===r.length)throw Pt(t,t);if(!n.PATTERN.test(r))throw new Rt(`${t} must be ${n.MIN_LENGTH}-${n.MAX_LENGTH} alphanumeric characters`,t,xt.INVALID_FORMAT)}function pr(e){return t=>{if(null==t||"object"!=typeof t)return!1;const n=t;for(const{field:t,type:r,nullable:i=!1,optional:s=!1,validator:o}of e){const e=n[t];if((!s||void 0!==e)&&(!i||null!==e)){if(typeof e!==r)return!1;if(o&&!o(e))return!1}}return!0}}const yr={requiredString:e=>t=>ar(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(!or(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(!ar(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=>ar(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(!ar(n))return t.includes(n)?void 0:`${e} must be one of: ${t.join(", ")}`},requiredEnumValue:(e,t)=>n=>ar(n)?`${e} is required`:t.includes(n)?void 0:`${e} must be one of: ${t.join(", ")}`,isoDate:e=>t=>{if(!ar(t))return"string"!=typeof t?`${e} must be a string`:vn(t)?void 0:`${e} must be a valid ISO 8601 date string`},walletAddress:(e,t=!1)=>n=>{if(ar(n))return t?`${e} is required`:void 0;if("string"!=typeof n)return`${e} must be a string`;return ir.ETH_ADDRESS.test(n)||ir.BACKEND_ADDRESS.test(n)||ir.CLIENT_ADDRESS.test(n)?void 0:`${e} must be a valid wallet address`}};function br(e){return t=>{const n=[],r=t;for(const t of e){const{field:e,required:i,type:s,validator:o}=t,a=r[e];if(i){if(ar(a)){n.push(`${e} is required`);continue}if("string"===s){if("string"!=typeof a){n.push(`${e} must be a string`);continue}if(0===a.trim().length){n.push(`${e} is required`);continue}}}if(!ar(a))if(void 0===s||typeof a===s){if(void 0!==o){const e=o(a,r);null!=e&&""!==e&&n.push(e)}}else n.push(`${e} must be a ${s}`)}return n}}function vr(e){return""===e||0===e.trim().length}function wr(e,t,n){if(!ar(e)){if("string"!=typeof e)throw Vt(t,"a string",e,t);if(e.length>n)throw new Rt(`${t} must be at most ${n} characters`,t,xt.TOO_LARGE)}}function Er(e,t){ar(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 Vt(t,"a date",e,t);if(isNaN(n.getTime()))throw new Rt(`${t} must be a valid date`,t,xt.INVALID_FORMAT)}(e,t)}function Ar(e,t,n){try{Yn(e,t)}catch{throw function(e,t,n,r="OPERATION_FAILED"){return new Rt(`${e} failed: ${t}`,n,r)}(n,"must be a positive integer",t)}}function kr(e,t,n="status"){void 0!==e&&function(e,t,n){const r=Object.values(t);if(!r.includes(e))throw new Rt(`${n} must be one of: ${r.join(", ")}`,n,xt.INVALID_FORMAT)}(e,t,n)}class Sr{constructor(e,t=!1,n){this.http=e,this.logger=new gn({debug:t,context:this.constructor.name}),this.jwtAuth=n}setJwtAuth(e){this.jwtAuth=e}getJwtHeaders(){if(!this.jwtAuth){const e=globalThis;if("test"===e.process?.env?.NODE_ENV&&!this.isCalledFromUserCode())return{};throw new Mt("JWT authentication required. Call sdk.login() first.")}return this.jwtAuth.getJwtHeaders()}isCalledFromUserCode(){const e=At(new Error)??"";return!(!e.includes("expect")&&!e.includes("jest"))||!(!e.includes("tests/")&&!e.includes(".test.ts"))}validatePositiveInteger(e,t,n){Ar(e,t,n)}}class Tr{constructor(e=!1,t){this.logger=t||new gn({debug:e,context:this.constructor.name})}}class Ir extends Tr{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 Nr extends Ir{constructor(e=!1){super(e)}normalizeKey(e){return ln(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>=Nr.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??cn.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 i=0;i+=2*r.length,void 0!==n.reverseBondingCurveMinFeeFactor&&(i+=8),void 0!==n.reverseBondingCurveMaxFeeFactor&&(i+=8),void 0!==n.reverseBondingCurveNetFeeFactor&&(i+=8),i+=8,void 0!==n.vaultAddress&&""!==n.vaultAddress&&(i+=2*n.vaultAddress.length),void 0!==n.maxSupply&&""!==n.maxSupply&&(i+=2*n.maxSupply.length),void 0!==n.symbol&&""!==n.symbol&&(i+=2*n.symbol.length),i+=32,t+=i}),{cacheSize:t,oldestEntry:this.cache.size>0?e:0}}getByTokenId(e){const t=`token:${ln(e)}`;return this.cache.get(t)??null}setByTokenId(e,t){const n=`token:${ln(e)}`;this.updateCacheEntry(n,t)}hasByTokenId(e){const t=`token:${ln(e)}`;return this.cache.has(t)}}function Cr(e){return""===e?"":e.startsWith("0x")?e.slice(2):e}Nr.MAX_CACHE_SIZE=1e4;const _r={ETHEREUM:ir.ETH_ADDRESS,ETHEREUM_NO_PREFIX:/^[a-fA-F0-9]{40}$/,BACKEND:ir.BACKEND_ADDRESS,CLIENT:ir.CLIENT_ADDRESS};class xr{toBackendFormat(t){if(!sr(t))throw new Rt("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 Rt(`Invalid Ethereum address format in backend address. Expected 40 hex characters after 'eth|'. Got: "${t}"`,"address","INVALID_FORMAT");return t}if(n=Cr(t),!/^[a-fA-F0-9]{40}$/.test(n))throw new Rt(`Invalid Ethereum address format. Expected 40 hex characters (with or without 0x prefix). Got: "${t}"`,"address","INVALID_FORMAT");return`eth|${e(`0x${n}`).slice(2)}`}toEthereumFormat(e){if(!sr(e))throw new Rt("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 Rt(`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(!_r.CLIENT.test(e))throw new Rt(`Invalid client address format: "${e}"`,"address","INVALID_FORMAT");return e}if(e.startsWith("eth|")){if(!_r.BACKEND.test(e))throw new Rt(`Invalid backend address format: "${e}"`,"address","INVALID_FORMAT");return e}return this.toBackendFormat(e)}}isValid(e){return!!sr(e)&&(!!_r.ETHEREUM.test(e)||(!!_r.ETHEREUM_NO_PREFIX.test(e)||(!!_r.BACKEND.test(e)||!!_r.CLIENT.test(e))))}assertValid(e,t="address"){if(!this.isValid(e))throw new Rt(`${t} must be a valid wallet address (Ethereum or backend format)`,t,"INVALID_FORMAT")}detectFormat(e){return sr(e)?_r.ETHEREUM.test(e)||_r.ETHEREUM_NO_PREFIX.test(e)?"ethereum":_r.BACKEND.test(e)?"backend":_r.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 Cr(e).toLowerCase();if(/^[a-fA-F0-9]{40}$/.test(e))return e.toLowerCase();throw new Rt(`Cannot extract hex from address: "${e}". Expected Ethereum or backend format.`,"address","INVALID_FORMAT")}}const Rr=new xr,Br=Cr;function Dr(e){return Rr.toBackendFormat(e)}function Mr(e){return Rr.toEthereumFormat(e)}function Or(e){return Rr.normalizeInput(e)}function Ur(e){return Rr.isValid(e)}function Lr(e,t="address"){Rr.assertValid(e,t)}function Pr(e){const t="string"==typeof e?e:e.address;return Rr.toBackendFormat(t)}function Fr(e){return Rr.detectFormat(e)}var $r=Object.freeze({__proto__:null,AddressFormatter:xr,assertValidWalletAddress:Lr,detectFormat:Fr,fromBackendAddressFormat:Mr,isValidAddress:Ur,normalizeAddressInput:Or,stripHexPrefix:Br,toBackendAddressFormat:Dr,toBackendAddressFromEthers:Pr});const Kr=p.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"),Gr=p.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"),Hr=p.string({message:"Token description is required"}).min(1,"Token description is required").max(500,"Token description must be at most 500 characters"),Wr=p.string().min(1,"Token name must be at least 1 character").max(50,"Token name must be at most 50 characters"),qr=p.string().min(1,"Search query must be at least 1 character").max(100,"Search query must be at most 100 characters"),jr=p.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"),Vr=p.string().regex(ir.BACKEND_ADDRESS,"Address must be in format: eth|[40-hex-chars]"),zr=p.string().regex(ir.ETH_ADDRESS,"Invalid Ethereum address format"),Xr=p.string().refine(e=>ir.BACKEND_ADDRESS.test(e)||ir.ETH_ADDRESS.test(e)||ir.CLIENT_ADDRESS.test(e),"Address must be eth|[40-hex], 0x[40-hex], or client|[identifier] format").transform(e=>(new xr).normalizeInput(e)??e),Jr=p.string().refine(e=>ir.BACKEND_ADDRESS.test(e)||/^service\|Token\$Unit\$[A-Z0-9]+\$eth:[0-9a-fA-F]{40}\$launchpad$/.test(e),"Invalid vault address format"),Yr=p.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>Kn(e,0)>0,"Amount must be greater than zero"),Qr=p.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>Kn(e,0)>=0,"Amount must be zero or greater"),Zr=p.string().url("Must be a valid URL").regex(/^https?:\/\//,"URL must start with http:// or https://"),ei=p.string().optional().refine(e=>void 0===e||""===e||/^https?:\/\/.+\..+/.test(e),"Must be a valid URL if provided"),ti=p.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 ni(e=100){return p.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 ri=ni(100),ii=ni(20),si=ni(20),oi=p.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"),ai=p.string().max(255,"Filename must be at most 255 characters"),ci=p.enum(["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"]),li=p.string().datetime("Must be a valid ISO 8601 date string"),ui=p.number().int("Timestamp must be an integer").min(0,"Timestamp must be non-negative"),di=p.string().regex(/^0x[a-fA-F0-9]{64}$/,"Private key must be format: 0x + 64 hex characters"),hi=p.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"),gi=p.string().regex(/^galaconnect-operation-[a-z0-9-]+$/,"Unique key must be format: galaconnect-operation-{unique-id}"),fi=[".png",".jpg",".jpeg",".gif",".webp",".svg"],mi=p.object({file:p.union([p.instanceof(File),p.instanceof(Buffer)]),name:ai,size:oi,type:ci}),pi=p.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"),yi=p.instanceof(Buffer).refine(e=>e.length>=1&&e.length<=10485760,"Buffer size must be between 1 byte and 10MB"),bi=p.union([pi,yi]),vi=p.enum([".png",".jpg",".jpeg",".gif",".webp",".svg"]),wi=ai.refine(e=>{const t=e.slice(e.lastIndexOf(".")).toLowerCase();return fi.includes(t)},`Filename must end with one of: ${fi.join(", ")}`),Ei=p.object({websiteUrl:ei,telegramUrl:ei,twitterUrl:ei,instagramUrl:ei,facebookUrl:ei,redditUrl:ei,tiktokUrl:ei}).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"),Ai=p.string().min(1,"Token category must not be empty").default("Unit"),ki=p.string().min(1,"Token collection must not be empty").default("Token"),Si=p.object({minFeePortion:p.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal string").refine(e=>Kn(e,0)>=.1,"Minimum fee must be >= 0.1").refine(e=>Kn(e,0)<=.5,"Minimum fee must be <= 0.5"),maxFeePortion:p.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal string").refine(e=>Kn(e,0)>=.1,"Maximum fee must be >= 0.1").refine(e=>Kn(e,0)<=.5,"Maximum fee must be <= 0.5")}).refine(e=>Kn(e.maxFeePortion,0)>=Kn(e.minFeePortion,0),{message:"Maximum fee must be >= minimum fee",path:["maxFeePortion"]}),Ti=p.object({tokenName:Kr,tokenSymbol:Gr,tokenDescription:Hr,tokenImage:p.union([p.instanceof(File),p.instanceof(Buffer),p.string().url("Token image must be a valid URL")]).optional(),preBuyQuantity:Qr.default("0"),websiteUrl:ei,telegramUrl:ei,twitterUrl:ei,instagramUrl:ei,facebookUrl:ei,redditUrl:ei,tiktokUrl:ei,tokenCategory:Ai,tokenCollection:ki,reverseBondingCurveConfiguration:Si.optional(),saleStartTime:p.number().int().positive().optional(),privateKey:di.optional()}),Ii=p.object({file:p.union([p.instanceof(File),p.instanceof(Buffer)]),tokenName:Kr}),Ni=p.enum(["RECENT","POPULAR"]),Ci=p.object({tokenName:Kr.optional(),symbol:Gr.optional()}).refine(e=>void 0!==e.tokenName||void 0!==e.symbol,"At least one of tokenName or symbol is required"),_i=p.enum(["NATIVE","MEME"]),xi=p.enum(["IN","OUT"]),Ri=p.object({from:p.number().int("From timestamp must be an integer").min(173e6,"From timestamp must be at least 173000000"),to:p.number().int("To timestamp must be an integer").min(173e6,"To timestamp must be at least 173000000"),resolution:p.number().int("Resolution must be an integer").min(1,"Resolution must be at least 1"),tokenName:Kr}),Bi=p.object({tokenName:Kr,slippageToleranceFactor:p.number().min(0).max(1).optional(),maxAcceptableReverseBondingCurveFeeSlippageFactor:p.number().min(0).max(1).optional(),privateKey:di.optional()}),Di=p.object({offset:p.number().int().min(0).default(0),pageSize:p.number().int().min(1).max(100).default(10)}),Mi=p.object({offset:p.number().int().min(0).default(0),pageSize:p.number().int().min(1).max(20).default(10)}),Oi=p.object({offset:p.number().int().min(0).default(0),pageSize:p.number().int().min(1).max(20).default(10)}),Ui=Di.extend({type:p.enum(["RECENT","POPULAR"]).optional(),tokenName:p.string().min(1).max(50).optional(),search:p.string().min(1).max(100).optional()}),Li=Mi.extend({tokenName:p.string().min(1).max(50).optional(),search:p.string().min(1).max(100).optional()}),Pi=Oi.extend({tradeType:p.enum(["BUY","SELL"]).optional(),tokenName:p.string().min(1).max(50).optional(),userAddress:p.string().regex(/^(0x[a-fA-F0-9]{40}|eth\|[a-fA-F0-9]{40})$/).optional(),startDate:p.string().datetime().optional(),endDate:p.string().datetime().optional(),sortOrder:p.enum(["ASC","DESC"]).default("DESC")}),Fi={page:p.number().int().min(1),limit:p.number().int().min(1),total:p.number().int().min(0),totalPages:p.number().int().min(0),hasNext:p.boolean(),hasPrevious:p.boolean()},$i=p.object(Fi);function Ki(e){return p.object({data:p.array(e),...Fi})}const Gi=p.enum(["buy","sell"]),Hi=p.enum(["BUY","SELL"]),Wi=p.object({tradeType:Gi,tokenAmount:Yr,vaultAddress:Jr,userAddress:Xr,slippageTolerance:Yr.optional(),deadline:p.number().int().positive().optional()}),qi=p.object({tokenSymbol:Gr,nativeTokenQuantity:Yr,expectedToken:Yr,maxAcceptableReverseBondingCurveFee:Qr.default("0").optional()}),ji=p.object({tokenSymbol:Gr,tokenQuantity:Yr,expectedNativeToken:Yr,maxAcceptableReverseBondingCurveFee:Qr.default("0").optional()}),Vi=Oi.extend({tokenName:Wr.optional()}),zi=p.object({page:p.number().int().min(1).max(1e3).default(1).optional(),limit:p.number().int().min(1).max(20).default(10).optional()}),Xi=p.enum(["NATIVE","MEME"]),Ji=p.enum(["IN","OUT"]),Yi=p.object({type:Xi,method:Ji,vaultAddress:Jr,amount:Yr}),Qi=p.object({nativeTokenQuantity:Yr}),Zi=p.object({vaultAddress:Jr}),es=p.object({minFeePortion:Yr,maxFeePortion:Yr}),ts=p.enum(["all","DEFI","ASSET"]),ns=Mi.extend({type:ts.optional(),address:Xr.optional(),search:qr.optional(),tokenName:Wr.optional()}),rs=p.object({address:Xr.optional(),refresh:p.boolean().optional()}),is=p.object({profileImage:p.string(),fullName:jr,address:Xr,privateKey:di.optional()}),ss=p.object({file:p.union([p.instanceof(File),p.instanceof(Buffer)]),address:Xr.optional(),privateKey:di.optional()}),os=p.object({created:p.number(),createdBy:p.string(),expires:p.number(),instanceId:p.string(),lockAuthority:p.string(),name:p.string(),quantity:p.string(),vestingPeriodStart:p.number()}),as=p.object({address:Xr,tokenId:p.union([p.string(),p.object({collection:p.string(),category:p.string(),type:p.string(),additionalKey:p.string()}),p.object({collection:p.string(),category:p.string(),type:p.string(),additionalKey:p.string(),instance:p.string()})]).optional(),tokenName:Wr.optional(),withExpired:p.boolean().optional()}).refine(e=>void 0!==e.tokenId||void 0!==e.tokenName,"At least one token identifier (tokenId or tokenName) is required");function cs(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 ls=cs(Kr),us=cs(Gr),ds=cs(Hr),hs=cs(Xr),gs=cs(Jr),fs=cs(Yr),ms=cs(jr),ps=cs(qr),ys=cs(Wr),bs=cs(Ti),vs=cs(Ei),ws=cs(Ii),Es=cs(Ci),As=cs(ns),ks=cs(rs),Ss=cs(is),Ts=cs(ss),Is=cs(as),Ns=cs(Wi),Cs=cs(qi),_s=cs(ji),xs=cs(Vi),Rs=cs(zi),Bs=cs(Yi),Ds=cs(Qi),Ms=cs(Zi);function Os(e){return bs(e).success}function Us(e){const t=bs(e);return t.success?[]:t.errors??["Unknown validation error"]}function Ls(e){const t=Us(e);if(t.length>0)throw new Error(`LaunchTokenData validation failed:\n${t.map(e=>`- ${e}`).join("\n")}`)}function Ps(e,t){return"string"==typeof e[t]}function Fs(e,t){return void 0===e[t]||"string"==typeof e[t]}function $s(e,t){return void 0===e[t]||"number"==typeof e[t]}function Ks(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 Gs(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(!Ks(n[t],r))return!1}return!0}}lr({BUY:"buy",SELL:"sell"});const Hs=Gs({vaultAddress:"string"}),Ws=Gs({nativeTokenQuantity:"string"});function qs(e){if(ar(e)||"object"!=typeof e)return{};const t={};for(const[n,r]of Object.entries(e))ar(r)||(sr(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 js=Object.freeze({__proto__:null,adaptQueryParams:qs});function Vs(e,t="0"){return function(e,t="0"){if(mn(e))return new T(t);if(T.isBigNumber(e))return e.isNaN()?new T(t):e;try{const n=new T(e);return n.isNaN()||!n.isFinite()?new T(t):n}catch{return new T(t)}}(e,t)}function zs(e,t){return void 0!==t?Vs(e).toFixed(t):Vs(e).toFixed()}function Xs(e){const t=Vs(e),n=Math.log(1.0001),r=t.toNumber();return Math.log(r)/n}function Js(e){return Vs(e).isZero()}function Ys(e,t){return Vs(e).isLessThan(Vs(t))}function Qs(...e){e.forEach(e=>{if(e.isNaN())throw zt("value","NaN");if(!e.isFinite())throw jt("value","finite");if(e.isLessThanOrEqualTo(0))throw qt("value","0",e.toString())})}function Zs(...e){e.forEach(e=>{if(e.isNaN())throw zt("value","NaN");if(!e.isFinite())throw jt("value","finite");if(e.isLessThan(0))throw qt("value","0",e.toString())})}function eo(e,t,n){if(e.isNaN())throw zt(t,"NaN");if(!e.isFinite())throw jt(t,"finite");if(e.isLessThanOrEqualTo(0))throw qt(t,"0",e.toString())}function to(e,t,n="0"){const r=Vs(t);return Js(r)?Vs(n):Vs(e).dividedBy(r)}const no={calculateBuyWithExact(e,t){const n=Kn(e),r=Kn(t),{BASE_PRICE:i,PRICE_SCALING_FACTOR:s,TRADING_FEE_FACTOR:o,GAS_FEE:a}=cn,c=function(e,t){const n=Math.pow(10,t);return Math.ceil(e*n)/n}(i*(Math.exp((r+n)*s)-Math.exp(r*s))/s,8),l=zs(Vs(c).multipliedBy(o));return{amount:c.toString(),reverseBondingCurveFee:"0",transactionFee:l,gasFee:a}},calculateBuyWithNative(e,t){const n=Kn(e),r=Kn(t),{BASE_PRICE:i,PRICE_SCALING_FACTOR:s,TRADING_FEE_FACTOR:o,GAS_FEE:a}=cn,c=Math.log(n*s/i+Math.exp(r*s))/s-r,l=zs(Vs(c).multipliedBy(o));return{amount:c.toString(),reverseBondingCurveFee:"0",transactionFee:l,gasFee:a}},calculateSellWithExact(e,t,n,r,i){const s=Kn(e),o=Kn(t),a=Kn(n),{BASE_PRICE:c,PRICE_SCALING_FACTOR:l,TRADING_FEE_FACTOR:u,GAS_FEE:d}=cn,h=c*(Math.exp(o*l)-Math.exp((o-s)*l))/l,g=Vs(h),f=r+o/a*(i-r),m=zs(g.multipliedBy(f),8),p=zs(g.multipliedBy(u));return{amount:h.toString(),reverseBondingCurveFee:m,transactionFee:p,gasFee:d}},calculateSellWithNative(e,t,n,r,i){const s=Kn(e),o=Kn(t),a=Kn(n),{BASE_PRICE:c,PRICE_SCALING_FACTOR:l,TRADING_FEE_FACTOR:u,GAS_FEE:d}=cn;if(s>=c*(Math.exp(o*l)-1)/l){const e=Vs(s),t=r+o/a*(i-r),n=zs(e.multipliedBy(t),8),c=zs(e.multipliedBy(u));return{amount:o.toString(),reverseBondingCurveFee:n,transactionFee:c,gasFee:d}}const h=o-Math.log(Math.exp(o*l)-s*l/c)/l,g=Vs(s),f=r+o/a*(i-r),m=zs(g.multipliedBy(f),8),p=zs(g.multipliedBy(u));return{amount:h.toString(),reverseBondingCurveFee:m,transactionFee:p,gasFee:d}}};class ro extends Error{constructor(e,t,n){super(e),this.filename=t,this.mimeType=n,this.name="FileValidationError"}}function io(e,t,n){if(null==e)throw new ro("File is required",t,n);if("undefined"!=typeof File&&e instanceof File){const t=pi.safeParse(e);if(!t.success){const n=t.error.issues.map(e=>e.message).join("; ");throw new ro(n,e.name,e.type)}return}if(Buffer.isBuffer(e)){if(void 0===t||""===t)throw new ro("Filename is required when uploading Buffer objects",t,n);const r=yi.safeParse(e);if(!r.success){const e=r.error.issues.map(e=>e.message).join("; ");throw new ro(e,t,n)}try{Jn(t,255,"filename")}catch(e){throw new ro(e.message,t,n)}const i=["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"];if(!i.includes(n))throw new ro(`Invalid file type "${n}" is not allowed. Allowed types: ${i.join(", ")}`,t,n);const s=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(s))throw new ro(`File extension "${s}" 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"}}(s);if(a!==n&&"application/octet-stream"!==a)throw new ro(`File extension "${s}" does not match MIME type "${n}"`,t,n);return}throw new ro("File must be a File object (browser) or Buffer (Node.js)",t,n)}class so{validate(e,t={}){const{allowZero:n=!0,minimum:r,maximum:i,maxDecimals:s=so.MAX_DECIMAL_PLACES,fieldName:o="amount"}=t;if(!sr(e))throw new Rt(`${o} cannot be empty or whitespace-only. Provide a valid numeric string.`,o,"INVALID_NUMERIC_STRING");if(/[eE]/.test(e))throw new Rt(`${o} cannot use scientific notation. Use standard decimal format (e.g., "1000" instead of "1e3").`,o,"INVALID_NUMERIC_STRING");const a=Kn(e,NaN);if(isNaN(a))throw new Rt(`${o} must be a valid numeric string. Received: "${e}"`,o,"INVALID_NUMERIC_STRING");if(!isFinite(a))throw new Rt(`${o} must be a finite number. Cannot be Infinity or -Infinity.`,o,"INVALID_NUMERIC_STRING");if(a<0)throw new Rt(`${o} must be non-negative. Received: "${e}"`,o,"INVALID_NUMERIC_STRING");if(!n&&0===a)throw new Rt(`${o} must be greater than zero. Received: "${e}"`,o,"INVALID_NUMERIC_STRING");const c=Vs(e),l=c.decimalPlaces()??0;if(l>s)throw new Rt(`${o} cannot exceed ${s} decimal places. Received: ${l} decimal places`,o,"PRECISION_EXCEEDED");if(void 0!==r&&Ys(c,r))throw new Rt(`${o} must be at least ${r}. Received: "${e}"`,o,"BELOW_MINIMUM");if(void 0!==i&&(u=i,Vs(c).isGreaterThan(Vs(u))))throw new Rt(`${o} cannot exceed ${i}. Received: "${e}"`,o,"EXCEEDS_MAXIMUM");var u}parseAmount(e,t="0"){return Vs(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 zs(e,t)}clampAmount(e,t,n){const r=Vs(e),i=Vs(t),s=Vs(n);return function(e,t,n){const r=Vs(e),i=Vs(t),s=Vs(n);return r.isGreaterThanOrEqualTo(i)&&r.isLessThanOrEqualTo(s)}(r,i,s)?zs(r):Ys(r,i)?zs(i):zs(s)}}function oo(e,t){throw new Rt(e.join("; "),t,"VALIDATION_ERROR")}function ao(e){const t=ls(e);!t.success&&t.errors&&oo(t.errors,"tokenName")}function co(e){const t=Ri.safeParse(e);var n;t.success||oo((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 lo(e,t,n=!0){uo.validate(e,{fieldName:t,allowZero:n})}so.MAX_DECIMAL_PLACES=18,so.MIN_POSITIVE="0.00000000000000001";const uo=new so;function ho(e,t,n=zs){if(!Array.isArray(e))throw $t("Invalid API response: expected array of holders",t);for(const n of e){if(!go(n))throw $t("Invalid holder data: missing or invalid owner field",t);if(!fo(n))throw $t("Invalid holder data: missing or invalid quantity field",t);const e=Kn(n.quantity,NaN);if(isNaN(e)||!isFinite(e))throw $t(`Invalid holder quantity: "${n.quantity}"`,t)}const r=e,i=r.reduce((e,t)=>e.plus(t.quantity),Vs(0));return{holders:r.map(e=>({address:e.owner,balance:e.quantity,percentage:to(Vs(e.quantity),i,Vs(0)).multipliedBy(100).toNumber()})),totalSupply:n(i),totalHolders:r.length,lastUpdated:new Date}}function go(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.owner&&""!==t.owner}function fo(e){return"string"==typeof e.quantity&&""!==e.quantity}class mo{constructor(e,t,n,r,i,s,o="local",a){this.http=e,this.tokenResolver=t,this.logger=n,this.bundleHttp=r,this.galaChainHttp=i,this.dexApiHttp=s,this.defaultCalculateAmountMode=o,this.launchpadWrites=a,this.metadataCache=new Nr}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;ao(t);const r=`${t}.png`;io(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 Ft("file","a File object (browser) or Buffer (Node.js)");{const r=`${void 0!==n.tokenName&&""!==n.tokenName?n.tokenName:t}.png`,i=new Blob([n.file],{type:"image/png"});e.append("image",i,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 $t(void 0!==r.message&&""!==r.message?r.message:"Image upload failed - no URL returned",r.status);const i=tn(r);if(!i?.imageUrl)throw $t("Image upload failed - no URL returned",r.status);return i.imageUrl}catch(e){if(wt(e)&&e.message.includes("FormData"))throw Kt("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&&cr(0,void 0,100,e.pageSize),void 0!==e.tokenName&&""!==e.tokenName&&ao(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=qs(t),r=await this.http.get(R.FETCH_POOLS,n);if(!0===r.error||200!==r.status)throw $t(void 0!==r.message&&""!==r.message?r.message:"Failed to fetch pools",r.status);const i=tn(r);if(null==i)throw $t("Failed to fetch pools - no data returned",r.status);let s=[];if(i.tokens)if(Array.isArray(i.tokens))s=i.tokens.map(e=>this.normalizePoolData(e));else{const e=i.tokens;s=[this.normalizePoolData(e)]}else i.pools&&Array.isArray(i.pools)&&(s=i.pools.map(e=>this.normalizePoolData(e)));const{extractMetadataFromPoolData:o,isValidPoolForCaching:a}=await Promise.resolve().then(function(){return cx});s.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=i.count??i.total??0,l={hasNextPage:i.hasNextPage??!1};return void 0!==i.hasPrevPage&&(l.hasPrevPage=i.hasPrevPage),void 0!==i.nextCursor&&(l.nextCursor=i.nextCursor),void 0!==i.prevCursor&&(l.prevCursor=i.prevCursor),c>0&&(l.totalCount=c),{items:s,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 Ft("options","an options object");const{tokenName:t,amount:n,type:r,currentSupply:i}=e;return"external"===this.validateAmountCalculationInputs(t,n,r,e.mode,[yt.NATIVE,yt.EXACT],'"native" or "exact"')?this.calculateBuyAmountExternal({tokenName:t,amount:n,type:r}):this.calculateBuyAmountLocal(this.addIfDefined({tokenName:t,amount:n,type:r},"currentSupply",i))}async calculateBuyAmountExternal(e){const{tokenName:t,amount:n,type:r}=e;return this.validateExternalAmountInputs(t,n),"exact"===r?rn(()=>this.http.get(lt,{tokenName:t,amount:n,type:"MEME",method:"OUT"}),{errorContext:`Failed to calculate buy amount for ${t} (exact tokens)`}):rn(()=>this.http.get(lt,{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:i,maxSupply:s,reverseBondingCurveMaxFeeFactor:o,reverseBondingCurveMinFeeFactor:a}=e;if("external"===this.validateAmountCalculationInputs(t,n,r,e.mode,[yt.EXACT,yt.NATIVE],'"exact" or "native"'))return this.calculateSellAmountExternal({tokenName:t,amount:n,type:r});{const e={tokenName:t,amount:n,type:r,...void 0!==i&&{currentSupply:i},...void 0!==s&&{maxSupply:s},...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?rn(()=>this.http.get(lt,{tokenName:t,amount:n,type:"MEME",method:"IN"}),{errorContext:`Failed to calculate sell amount for ${t} (exact tokens)`}):rn(()=>this.http.get(lt,{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:i}=e;if(!sr(n))throw Pt("amount","Amount");if(r!==yt.NATIVE&&r!==yt.EXACT)throw Vt("type",'"native" or "exact"',r);void 0!==i&&lo(i,"currentSupply");const s=null==i||""===i;if(s&&(null==t||""===t))throw Pt("tokenName","Token name (required when currentSupply is not provided)");null!=t&&""!==t&&ao(t);let o=i;if(s){o=(await this.fetchPoolDetailsForCalculation(t)).currentSupply}return r===yt.EXACT?no.calculateBuyWithExact(n,o):no.calculateBuyWithNative(n,o)}async calculateSellAmountLocal(e){const{tokenName:t,amount:n,type:r,currentSupply:i,maxSupply:s,reverseBondingCurveMaxFeeFactor:o,reverseBondingCurveMinFeeFactor:a}=e;if(!sr(n))throw Pt("amount","Amount");if(r!==yt.EXACT&&r!==yt.NATIVE)throw Vt("type",'"exact" or "native"',r);void 0!==i&&lo(i,"currentSupply");const c=null==i||""===i||null==s||""===s||void 0===o||void 0===a;if(c&&(null==t||""===t))throw Pt("tokenName","Token name (required when currentSupply, maxSupply, or fee factors are not provided)");null!=t&&""!==t&&ao(t);let l=i,u=s,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===yt.EXACT?no.calculateSellWithExact(n,l,u,h,d):no.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 Ps(t,"tokenName")&&function(e){return void 0===e.calculateAmountMode||"local"===e.calculateAmountMode||"external"===e.calculateAmountMode}(t)&&Fs(t,"currentSupply")}(e))throw Vt("options","CalculateBuyAmountForGraduationOptions or string (token name)",typeof e);const{tokenName:n,calculateAmountMode:r,currentSupply:i}=t;ao(n);const s=await this.fetchSaleDetails(n),o=i??zs(Vs(s.maxSupply).minus(s.sellingTokenQuantity)),a=s.sellingTokenQuantity;if("0"===a)throw Pt("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 Kt("Bundle backend client not configured. LaunchToken requires bundleHttp client.","bundleHttp");Ls(e);const t=void 0!==e.preBuyQuantity&&""!==e.preBuyQuantity?e.preBuyQuantity:"0",n=Kn(t);if(0===n&&"0"!==t)throw zt("preBuyQuantity",t,"Pre-buy quantity");if(n<0)throw zt("preBuyQuantity",t,"Pre-buy quantity");if(e.reverseBondingCurveConfiguration){const{minFeePortion:t,maxFeePortion:n}=e.reverseBondingCurveConfiguration;tr(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 Pt("tokenName","Token name");ao(e);const t=await this.http.get(`/holders/${e}`);if(!0===t.error||200!==t.status)throw $t(void 0!==t.message&&""!==t.message?t.message:"Failed to fetch token distribution",t.status);const n=tn(t);if(null==n)throw $t("Failed to fetch token distribution - no data returned",t.status);return ho(n,t.status)}async calculateInitialBuyAmount(e){if(!Ws(e))throw Ft("data","valid pre-mint calculation data");if(!this.galaChainHttp)throw Kt("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 i=r,s=i.calculatedQuantity,o=i.extraFees;if("string"!=typeof s||"object"!=typeof o||null===o)return!1;const a=o;return"string"==typeof a.reverseBondingCurve&&"string"==typeof a.transactionFees}(n))throw $t("Malformed response data from GalaChain gateway");try{Tt(n,"Pre-mint calculation")}catch(e){throw $t(Et(e),500)}const{calculatedQuantity:r,extraFees:i}=n.Data;return{amount:r,reverseBondingCurveFee:i.reverseBondingCurve,transactionFee:i.transactionFees,gasFee:"1"}}catch(e){if(wt(e)&&e instanceof Dt)throw e;throw $t(Et(e),500)}}async fetchPoolDetailsForCalculation(e){const t=await this.fetchSaleDetails(e),n=zs(Vs(t.maxSupply).minus(t.sellingTokenQuantity)),r=t.sellingTokenQuantity,i=t.maxSupply;let s=.5,o=.1;const a=t.reverseBondingCurveConfiguration;null!=a?.maxFeePortion&&(s=qn(a.maxFeePortion,.5)),null!=a?.minFeePortion&&(o=qn(a.minFeePortion,.1)),void 0===a&&this.logger.debug(`Pool details missing reverse bonding curve configuration for token ${e}, using defaults (min: 0.1, max: 0.5)`);const c=s-o;return this.metadataCache.set(e,{maxSupply:i,reverseBondingCurveMaxFeeFactor:s,reverseBondingCurveMinFeeFactor:o,reverseBondingCurveNetFeeFactor:c}),{currentSupply:n,remainingTokens:r,maxSupply:i,reverseBondingCurveMaxFeeFactor:s,reverseBondingCurveMinFeeFactor:o,reverseBondingCurveNetFeeFactor:c}}async fetchCurrentSupply(e){ao(e);const t=await this.fetchSaleDetails(e),n=zs(Vs(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:!Js(t)||!Js(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 Rt(_t(e),"tokenName","VAULT_NOT_FOUND");if(void 0===this.galaChainHttp||null===this.galaChainHttp)throw Kt("GalaChain HTTP client not configured");const n=await this.galaChainHttp.post("/api/asset/launchpad-contract/FetchSaleDetails",{vaultAddress:t});if(1!==n.Status)throw $t(`Failed to fetch pool details: Status ${n.Status}`,n.Status);return n.Data}validateAmountCalculationInputs(e,t,n,r,i,s){const o=r??this.defaultCalculateAmountMode;if("local"!==o&&"external"!==o)throw Vt("mode",'"local" or "external"',o);if(!sr(e))throw Pt("tokenName","Token name");if(!sr(t))throw Pt("amount","Amount");if("string"!=typeof n||!i.includes(n))throw Vt("type",s,n);return o}validateExternalAmountInputs(e,t){if("string"!=typeof e||""===e)throw new Rt("Token name must be a non-empty string","tokenName","INVALID_TOKEN_NAME");if("string"!=typeof t||""===t)throw new Rt("Amount must be a non-empty string","amount","INVALID_AMOUNT")}getAddress(){return this.http.getAddress()}formatAddressForBackend(e){return Dr(e)}validateTokenName(e){return ao(e)}validatePagination(e){void 0!==e.pageSize&&cr(0,void 0,100,e.pageSize)}async fetchTokenPrice(e){if(void 0===this.dexApiHttp||null===this.dexApiHttp)throw Kt("DEX API client not configured. Token price fetching requires dexApiHttp client.","dexApiHttp");if(null==e||""===e||Array.isArray(e)&&0===e.length)throw Pt("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 $t(`Failed to fetch token prices: ${Et(e)}`,void 0,wt(e)?e:void 0)}}warmCacheFromPoolData(e,t){this.metadataCache.warmFromPoolData(e,t)}getCacheStats(){return this.metadataCache.getStats()}clearCache(e){this.metadataCache.clear(e)}}const po={REFRESH_THRESHOLD_MS:3e5,DEFAULT_EXPIRY_S:86400,LOGIN_MESSAGE_PREFIX:"Sign in to Launchpad t:",AUTH_HEADER:"Authorization",BEARER_PREFIX:"Bearer "};class yo{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 bo,vo;!function(e){e.WALLET_NOT_CONNECTED="WALLET_NOT_CONNECTED",e.SIGNATURE_FAILED="SIGNATURE_FAILED",e.INVALID_ADDRESS="INVALID_ADDRESS",e.MESSAGE_GENERATION_FAILED="MESSAGE_GENERATION_FAILED"}(bo||(bo={}));class wo extends Error{constructor(e,t,n){super(t),this.type=e,this.originalError=n,this.name="AuthError"}}class Eo{constructor(e,t=po.REFRESH_THRESHOLD_MS){this.tokenState=null,this.STORAGE_KEYS={ACCESS_TOKEN:"lpad_access_token",ACCESS_EXPIRES:"lpad_access_expires",REFRESH_TOKEN:"lpad_refresh_token",REFRESH_EXPIRES:"lpad_refresh_expires"},this.storage=e??new yo,this.refreshThresholdMs=t}setToken(e,t){if(!sr(e))throw new wo(bo.SIGNATURE_FAILED,"JWT token must be a non-empty string");if("number"!=typeof t)throw new wo(bo.SIGNATURE_FAILED,"Token expiration must be a positive finite number (seconds)");if(!Number.isFinite(t))throw new wo(bo.SIGNATURE_FAILED,"Token expiration must be a positive finite number (seconds)");if(t<=0)throw new wo(bo.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 wo(bo.SIGNATURE_FAILED,"Access token must be set before refresh token");this.tokenState.refreshToken=n.trim(),this.tokenState.refreshExpiresAt=e,await this.storage.set(this.STORAGE_KEYS.REFRESH_TOKEN,n.trim()),await this.storage.set(this.STORAGE_KEYS.REFRESH_EXPIRES,String(e))}}getToken(){return this.tokenState?.token??null}hasToken(){return null!==this.tokenState}isExpired(){return!this.tokenState||Date.now()>=this.tokenState.expiresAt}shouldRefresh(e){if(!this.tokenState)return!1;const t=e??this.refreshThresholdMs,n=this.tokenState.expiresAt-Date.now();return n>0&&n<=t}getTimeUntilExpiry(){if(!this.tokenState)return 0;const e=this.tokenState.expiresAt-Date.now();return Math.max(0,e)}getExpiresAt(){return this.tokenState?.expiresAt??null}getAuthorizationHeader(){const e=this.getToken();return null===e||""===e?null:`${po.BEARER_PREFIX}${e}`}getJwtHeaders(){const e=this.getAuthorizationHeader();if(null===e||""===e)throw new wo(bo.WALLET_NOT_CONNECTED,"No JWT token available. Call login() first.");return{[po.AUTH_HEADER]:e}}async getRefreshToken(){if(!this.tokenState?.refreshToken){const e=await this.storage.get(this.STORAGE_KEYS.REFRESH_TOKEN),t=await this.storage.get(this.STORAGE_KEYS.REFRESH_EXPIRES);if(e&&t){const n=Number(t);if(Number.isFinite(n)&&Date.now()<n)return e}return null}return null!==this.tokenState.refreshExpiresAt&&void 0!==this.tokenState.refreshExpiresAt&&(!Number.isFinite(this.tokenState.refreshExpiresAt)||Date.now()>=this.tokenState.refreshExpiresAt)?null:this.tokenState.refreshToken??null}async restoreFromStorage(){const e=await this.storage.get(this.STORAGE_KEYS.ACCESS_TOKEN),t=await this.storage.get(this.STORAGE_KEYS.ACCESS_EXPIRES);if(!e||!t)return!1;const n=Number(t);if(!Number.isFinite(n)||Date.now()>=n)return!1;const r=Date.now();this.tokenState={token:e,issuedAt:r,expiresAt:n};const i=await this.storage.get(this.STORAGE_KEYS.REFRESH_TOKEN),s=await this.storage.get(this.STORAGE_KEYS.REFRESH_EXPIRES);if(i&&s){const e=Number(s);Number.isFinite(e)&&Date.now()<e&&(this.tokenState.refreshToken=i,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 Ao(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),Ht(e,t,n))}}function ko(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),Ht(e,t,n))}}class So{constructor(e,t,n,r=!1){this.http=e,this.signatureAuth=t,this.jwtAuth=n,this.refreshPromise=null,this.loginPromise=null,this.logger=new gn({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 wo(bo.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 Ao(async()=>{const e=Date.now(),t=`${po.LOGIN_MESSAGE_PREFIX}${e}`;this.logger.debug("Generating login signature",{message:t,timestamp:e});const n=await this.signatureAuth.signMessage(t),r=this.signatureAuth.getAddress();Lr(r,"address");const i={address:r,message:t,signature:n.signature};let s;try{this.logger.debug("Sending login request with refresh token support",{address:r,message:t}),s=await this.http.post(ee,{...i,includeRefreshToken:!0})}catch(e){if(400!==e.statusCode)throw e;this.logger.debug("Login returned 400, retrying without includeRefreshToken (backend may not support it)"),s=await this.http.post(ee,i)}const o=this.extractLoginData(s);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 wo)throw e;throw new wo(bo.SIGNATURE_FAILED,`Login failed: ${Et(e)}`,wt(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 wo(bo.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 Ao(async()=>{this.logger.debug("Refreshing JWT token");const e=await this.jwtAuth.getRefreshToken();if(e){this.logger.debug("Using refresh token flow");const t=await this.http.post(ne,{refreshToken:e}),n=this.extractLoginData(t);return await this.jwtAuth.setTokens(n.accessToken,n.expiresIn,n.refreshToken,n.refreshExpiresIn),this.logger.debug("Token refreshed successfully via refresh token",{address:n.address,expiresIn:n.expiresIn,hasNewRefreshToken:!!n.refreshToken}),n}this.logger.debug("Using legacy access token refresh");const t=await this.http.post(ne,{},this.jwtAuth.getJwtHeaders()),n=this.extractLoginData(t);return this.jwtAuth.setToken(n.accessToken,n.expiresIn),this.logger.debug("Token refreshed successfully via access token",{address:n.address,expiresIn:n.expiresIn}),n},"SessionAuthService.performRefresh",this.logger,e=>{if(e instanceof wo)throw e;throw new wo(bo.SIGNATURE_FAILED,`Token refresh failed: ${Et(e)}`,wt(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(te,{allDevices:!0},this.jwtAuth.getJwtHeaders()),this.logger.debug("Logged out from all devices")}catch(e){this.logger.warn(`Failed to revoke all-device sessions (server-side revocation may be incomplete): ${Et(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 wo(bo.WALLET_NOT_CONNECTED,"Not authenticated. Call login() first.");return Ao(async()=>{const e=await this.http.get(re,void 0,this.jwtAuth.getJwtHeaders());return this.extractSessionData(e)},"SessionAuthService.getSession",this.logger,e=>{if(e instanceof wo)throw e;throw new wo(bo.SIGNATURE_FAILED,`Failed to get session: ${Et(e)}`,wt(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 wo(bo.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: ${Et(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 wo(bo.SIGNATURE_FAILED,""!==Et(e)?Et(e):"Authentication failed");const t=nn(e,"No data in authentication response"),{accessToken:n,expiresIn:r,address:i,refreshToken:s,refreshExpiresIn:o}=t;if(!sr(n))throw new wo(bo.SIGNATURE_FAILED,"Invalid access token in response");if("number"!=typeof r||r<=0)throw new wo(bo.SIGNATURE_FAILED,"Invalid expiration in response");return{accessToken:n,expiresIn:r,address:i,...void 0!==s&&{refreshToken:s},...void 0!==o&&{refreshExpiresIn:o}}}extractSessionData(e){if(e.error)throw new wo(bo.SIGNATURE_FAILED,""!==Et(e)?Et(e):"Failed to get session");return nn(e,"No data in session response")}}class To 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"}(vo||(vo={}));class Io{constructor(e){this.providerType="privateKey",this.connected=!0;try{this.wallet=new t(e)}catch(e){throw new To("Invalid private key provided",vo.INVALID_CONFIG,e instanceof Error?e:void 0)}}static fromWallet(e){return new Io(e.privateKey)}async signMessage(e){try{return await this.wallet.signMessage(e)}catch(e){throw new To("Failed to sign message",vo.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 To("Failed to sign typed data",vo.SIGNING_FAILED,e instanceof Error?e:void 0)}}getAddress(){return Promise.resolve(e(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{Qn(e.messagePrefix,"messagePrefix",!1)}catch{throw new wo(bo.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=Io.fromWallet(this.wallet),this.cachedAddress=this.wallet.address,this.cachedGalaAddress=Dr(this.wallet.address)}catch(e){if(e instanceof wo)throw e;if(e instanceof Rt&&("INVALID_ADDRESS"===e.code||"INVALID_FORMAT"===e.code||"address"===e.field))throw new wo(bo.INVALID_ADDRESS,e.message);if(null!==e&&"object"==typeof e&&"message"in e)throw new wo(bo.WALLET_NOT_CONNECTED,e.message);throw e}}setWallet(e){if(void 0!==e){if("object"!=typeof e||!("address"in e))throw new wo(bo.WALLET_NOT_CONNECTED,"Invalid wallet: must be an ethers Wallet instance or undefined");if("string"!=typeof e.address||""===e.address)throw new wo(bo.INVALID_ADDRESS,"Wallet address is not available");this.walletProvider=Io.fromWallet(e),this.cachedAddress=e.address,this.cachedGalaAddress=Dr(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 wo)throw e;throw new wo(bo.SIGNATURE_FAILED,"Failed to generate signature for authentication",wt(e)?e:new Error(Et(e)))}}getAddress(){if(this.validateWallet(),this.cachedGalaAddress)return this.cachedGalaAddress;if(this.wallet)return this.formatAddress(this.wallet.address);throw new wo(bo.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 wo(bo.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 wo(bo.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 wo(bo.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 wo(bo.WALLET_NOT_CONNECTED,"Private key not available with this wallet provider");try{return await this.walletProvider.getPrivateKey()}catch(e){throw new wo(bo.WALLET_NOT_CONNECTED,"Private key not available. External wallet providers cannot access private keys. Use PrivateKeyProvider for @gala-chain signing operations.",wt(e)?e:void 0)}}formatAddress(e){try{return Dr(e)}catch{throw new wo(bo.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 wo)throw e;throw new wo(bo.SIGNATURE_FAILED,Et(e),wt(e)?e:new Error(Et(e)))}}async generateAuthHeaders(e,t){await this.validateWalletAsync();try{const n=Date.now(),r=`${this.messagePrefix} ${t.toUpperCase()} ${e} ${n}`,i=await this.walletProvider.signMessage(r);return{"x-signature":i,"x-address":await this.walletProvider.getGalaAddress(),"x-message":r,"x-timestamp":n.toString()}}catch(e){if(e instanceof wo)throw e;throw new wo(bo.SIGNATURE_FAILED,"Failed to generate authentication headers",wt(e)?e:new Error(Et(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 wo)throw e;throw new wo(bo.SIGNATURE_FAILED,"Failed to sign typed data",wt(e)?e:new Error(Et(e)))}}async generateCustomSignature(e){if(!sr(e))throw new wo(bo.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 wo)throw e;throw new wo(bo.SIGNATURE_FAILED,"Failed to generate custom message signature",wt(e)?e:new Error(Et(e)))}}validateWallet(){if(this.ensureWalletProvider(),!this.walletProvider)throw new wo(bo.WALLET_NOT_CONNECTED,"Wallet is required for authentication")}async validateWalletAsync(){if(this.ensureWalletProvider(),!this.walletProvider)throw new wo(bo.WALLET_NOT_CONNECTED,"Wallet is required for authentication");if(!this.walletProvider.isConnected())throw new wo(bo.WALLET_NOT_CONNECTED,"Wallet is not connected. Call connect() on the wallet provider first.")}}const Co={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 _o(e){return Co[e]}function xo(e){return`${e.collection}|${e.category}|${e.type}|${e.additionalKey}`}function Ro(e){return`${e.collection}$${e.category}$${e.type}$${e.additionalKey}`}const Bo={GALA_CHAIN:1,ETHEREUM:2,SOLANA:1002},Do={ASSET:1,MUSIC:3};function Mo(e){return Object.values(Do).includes(e)}const Oo=12,Uo=15e3,Lo=27e5,Po={UNIT_LIMIT:2e5,UNIT_PRICE_MICROLAMPORTS:375e3},Fo="https://ethereum.publicnode.com",$o="https://api.mainnet-beta.solana.com",Ko="0x9f452b7cC24e6e6FA690fe77CF5dD2ba3DbF1ED9",Go="0x6a1734E09f3099a3675645D214ce547080ea67e0",Ho="AaE4dTnL75XqgUJpdxBKg6vS9sTJgBPJwBQRVhD29WwS",Wo="https://dex-api-platform-dex-prod-gala.gala.com",qo=[{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}],jo=[{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 Vo(e){return"prod"===e?qo:jo}function zo(e){return"prod"===e?Ko:Go}const Xo=qo,Jo=[{symbol:"GALA",amount:"1",mintAddress:"eEUiUs4JWYZrp72djAGF1A8PhpR6rHphGeGN7GbVLp6",isNative:!1,decimals:8},{symbol:"GSOL",amount:"0.001",mintAddress:"So11111111111111111111111111111111111111111",isNative:!0,decimals:9}],Yo={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"}},Qo=["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)"],Zo=["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"],ea={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 ta(e){const t=dn(e),n=Yo[t];if(void 0!==n)return n;if(!t.startsWith("G")){const e=Yo[`G${t}`];if(void 0!==e)return e}}function na(e){const t=dn(e);return Xo.find(e=>dn(e.symbol)===t||dn(e.symbol)===`G${t}`)}function ra(e){const t=dn(e);return Jo.find(e=>dn(e.symbol)===t||dn(e.symbol)===`G${t}`)}function ia(e){return xo(e)}function sa(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function oa(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{}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 aa,ca={},la={};function ua(){if(aa)return la;aa=1,la.byteLength=function(e){var t=s(e),n=t[0],r=t[1];return 3*(n+r)/4-r},la.toByteArray=function(e){var r,i,o=s(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(i=0;i<d;i+=4)r=t[e.charCodeAt(i)]<<18|t[e.charCodeAt(i+1)]<<12|t[e.charCodeAt(i+2)]<<6|t[e.charCodeAt(i+3)],l[u++]=r>>16&255,l[u++]=r>>8&255,l[u++]=255&r;2===c&&(r=t[e.charCodeAt(i)]<<2|t[e.charCodeAt(i+1)]>>4,l[u++]=255&r);1===c&&(r=t[e.charCodeAt(i)]<<10|t[e.charCodeAt(i+1)]<<4|t[e.charCodeAt(i+2)]>>2,l[u++]=r>>8&255,l[u++]=255&r);return l},la.fromByteArray=function(t){for(var n,r=t.length,i=r%3,s=[],o=16383,c=0,l=r-i;c<l;c+=o)s.push(a(t,c,c+o>l?l:c+o));1===i?(n=t[r-1],s.push(e[n>>2]+e[n<<4&63]+"==")):2===i&&(n=(t[r-2]<<8)+t[r-1],s.push(e[n>>10]+e[n>>4&63]+e[n<<2&63]+"="));return s.join("")};for(var e=[],t=[],n="undefined"!=typeof Uint8Array?Uint8Array:Array,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=0;i<64;++i)e[i]=r[i],t[r.charCodeAt(i)]=i;function s(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,i=[],s=t;s<n;s+=3)r=(e[s]<<16&16711680)+(e[s+1]<<8&65280)+(255&e[s+2]),i.push(o(r));return i.join("")}return t["-".charCodeAt(0)]=62,t["_".charCodeAt(0)]=63,la}var da,ha,ga={};function fa(){return da||(da=1,ga.read=function(e,t,n,r,i){var s,o,a=8*i-r-1,c=(1<<a)-1,l=c>>1,u=-7,d=n?i-1:0,h=n?-1:1,g=e[t+d];for(d+=h,s=g&(1<<-u)-1,g>>=-u,u+=a;u>0;s=256*s+e[t+d],d+=h,u-=8);for(o=s&(1<<-u)-1,s>>=-u,u+=r;u>0;o=256*o+e[t+d],d+=h,u-=8);if(0===s)s=1-l;else{if(s===c)return o?NaN:1/0*(g?-1:1);o+=Math.pow(2,r),s-=l}return(g?-1:1)*o*Math.pow(2,s-r)},ga.write=function(e,t,n,r,i,s){var o,a,c,l=8*s-i-1,u=(1<<l)-1,d=u>>1,h=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,g=r?0:s-1,f=r?1:-1,m=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,i),o+=d):(a=t*Math.pow(2,d-1)*Math.pow(2,i),o=0));i>=8;e[n+g]=255&a,g+=f,a/=256,i-=8);for(o=o<<i|a,l+=i;l>0;e[n+g]=255&o,g+=f,o/=256,l-=8);e[n+g-f]|=128*m}),ga}function ma(){return ha||(ha=1,function(e){const t=ua(),n=fa(),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 i=2147483647;function s(e){if(e>i)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=s(n);const i=r.write(e,t);i!==n&&(r=r.slice(0,i));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 i=function(e){if(o.isBuffer(e)){const t=0|h(e.length),n=s(t);return 0===n.length||e.copy(n,0,0,t),n}if(void 0!==e.length)return"number"!=typeof e.length||z(e.length)?s(0):u(e);if("Buffer"===e.type&&Array.isArray(e.data))return u(e.data)}(e);if(i)return i;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),s(e<0?0:0|h(e))}function u(e){const t=e.length<0?0:0|h(e.length),n=s(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>=i)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i.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 i=!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(i)return r?-1:W(e).length;t=(""+t).toLowerCase(),i=!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 S(this,t,n);case"ascii":return I(this,t,n);case"latin1":case"binary":return N(this,t,n);case"base64":return k(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 m(e,t,n){const r=e[t];e[t]=e[n],e[n]=r}function p(e,t,n,r,i){if(0===e.length)return-1;if("string"==typeof n?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),z(n=+n)&&(n=i?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(i)return-1;n=e.length-1}else if(n<0){if(!i)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,i);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):y(e,[t],n,r,i);throw new TypeError("val must be string, number or Buffer")}function y(e,t,n,r,i){let s,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(i){let r=-1;for(s=n;s<a;s++)if(l(e,s)===l(t,-1===r?0:s-r)){if(-1===r&&(r=s),s-r+1===c)return r*o}else-1!==r&&(s-=s-r),r=-1}else for(n+c>a&&(n=a-c),s=n;s>=0;s--){let n=!0;for(let r=0;r<c;r++)if(l(e,s+r)!==l(t,r)){n=!1;break}if(n)return s}return-1}function b(e,t,n,r){n=Number(n)||0;const i=e.length-n;r?(r=Number(r))>i&&(r=i):r=i;const s=t.length;let o;for(r>s/2&&(r=s/2),o=0;o<r;++o){const r=parseInt(t.substr(2*o,2),16);if(z(r))return o;e[n+o]=r}return o}function v(e,t,n,r){return j(W(t,e.length-n),e,n,r)}function w(e,t,n,r){return j(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 j(q(t),e,n,r)}function A(e,t,n,r){return j(function(e,t){let n,r,i;const s=[];for(let o=0;o<e.length&&!((t-=2)<0);++o)n=e.charCodeAt(o),r=n>>8,i=n%256,s.push(i),s.push(r);return s}(t,e.length-n),e,n,r)}function k(e,n,r){return 0===n&&r===e.length?t.fromByteArray(e):t.fromByteArray(e.slice(n,r))}function S(e,t,n){n=Math.min(e.length,n);const r=[];let i=t;for(;i<n;){const t=e[i];let s=null,o=t>239?4:t>223?3:t>191?2:1;if(i+o<=n){let n,r,a,c;switch(o){case 1:t<128&&(s=t);break;case 2:n=e[i+1],128==(192&n)&&(c=(31&t)<<6|63&n,c>127&&(s=c));break;case 3:n=e[i+1],r=e[i+2],128==(192&n)&&128==(192&r)&&(c=(15&t)<<12|(63&n)<<6|63&r,c>2047&&(c<55296||c>57343)&&(s=c));break;case 4:n=e[i+1],r=e[i+2],a=e[i+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&&(s=c))}}null===s?(s=65533,o=1):s>65535&&(s-=65536,r.push(s>>>10&1023|55296),s=56320|1023&s),r.push(s),i+=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=i,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?s(e):void 0!==t?"string"==typeof n?s(e).fill(t,n):s(e).fill(t):s(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 i=0,s=Math.min(n,r);i<s;++i)if(e[i]!==t[i]){n=e[i],r=t[i];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 i=0;for(n=0;n<e.length;++n){let t=e[n];if(V(t,Uint8Array))i+t.length>r.length?(o.isBuffer(t)||(t=o.from(t)),t.copy(r,i)):Uint8Array.prototype.set.call(r,t,i);else{if(!o.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(r,i)}i+=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)m(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)m(this,t,t+3),m(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)m(this,t,t+7),m(this,t+1,t+6),m(this,t+2,t+5),m(this,t+3,t+4);return this},o.prototype.toString=function(){const e=this.length;return 0===e?"":0===arguments.length?S(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,i){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===i&&(i=this.length),t<0||n>e.length||r<0||i>this.length)throw new RangeError("out of range index");if(r>=i&&t>=n)return 0;if(r>=i)return-1;if(t>=n)return 1;if(this===e)return 0;let s=(i>>>=0)-(r>>>=0),a=(n>>>=0)-(t>>>=0);const c=Math.min(s,a),l=this.slice(r,i),u=e.slice(t,n);for(let e=0;e<c;++e)if(l[e]!==u[e]){s=l[e],a=u[e];break}return s<a?-1:a<s?1:0},o.prototype.includes=function(e,t,n){return-1!==this.indexOf(e,t,n)},o.prototype.indexOf=function(e,t,n){return p(this,e,t,n,!0)},o.prototype.lastIndexOf=function(e,t,n){return p(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 i=this.length-t;if((void 0===n||n>i)&&(n=i),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");let s=!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(s)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),s=!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 i=t;i<n;++i)r+=String.fromCharCode(127&e[i]);return r}function N(e,t,n){let r="";n=Math.min(e.length,n);for(let i=t;i<n;++i)r+=String.fromCharCode(e[i]);return r}function C(e,t,n){const r=e.length;(!t||t<0)&&(t=0),(!n||n<0||n>r)&&(n=r);let i="";for(let r=t;r<n;++r)i+=X[e[r]];return i}function _(e,t,n){const r=e.slice(t,n);let i="";for(let e=0;e<r.length-1;e+=2)i+=String.fromCharCode(r[e]+256*r[e+1]);return i}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,i,s){if(!o.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||t<s)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,i){$(t,r,i,e,n,7);let s=Number(t&BigInt(4294967295));e[n++]=s,s>>=8,e[n++]=s,s>>=8,e[n++]=s,s>>=8,e[n++]=s;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,i){$(t,r,i,e,n,7);let s=Number(t&BigInt(4294967295));e[n+7]=s,s>>=8,e[n+6]=s,s>>=8,e[n+5]=s,s>>=8,e[n+4]=s;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 M(e,t,n,r,i,s){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function O(e,t,r,i,s){return t=+t,r>>>=0,s||M(e,0,r,4),n.write(e,t,r,i,23,4),r+4}function U(e,t,r,i,s){return t=+t,r>>>=0,s||M(e,0,r,8),n.write(e,t,r,i,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],i=1,s=0;for(;++s<t&&(i*=256);)r+=this[e+s]*i;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],i=1;for(;t>0&&(i*=256);)r+=this[e+--t]*i;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=J(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,i=this[++e]+256*this[++e]+65536*this[++e]+n*2**24;return BigInt(r)+(BigInt(i)<<BigInt(32))}),o.prototype.readBigUInt64BE=J(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],i=this[++e]*2**24+65536*this[++e]+256*this[++e]+n;return(BigInt(r)<<BigInt(32))+BigInt(i)}),o.prototype.readIntLE=function(e,t,n){e>>>=0,t>>>=0,n||x(e,t,this.length);let r=this[e],i=1,s=0;for(;++s<t&&(i*=256);)r+=this[e+s]*i;return i*=128,r>=i&&(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,i=1,s=this[e+--r];for(;r>0&&(i*=256);)s+=this[e+--r]*i;return i*=128,s>=i&&(s-=Math.pow(2,8*t)),s},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=J(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=J(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 i=1,s=0;for(this[t]=255&e;++s<n&&(i*=256);)this[t+s]=e/i&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 i=n-1,s=1;for(this[t+i]=255&e;--i>=0&&(s*=256);)this[t+i]=e/s&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=J(function(e,t=0){return B(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),o.prototype.writeBigUInt64BE=J(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 i=0,s=1,o=0;for(this[t]=255&e;++i<n&&(s*=256);)e<0&&0===o&&0!==this[t+i-1]&&(o=1),this[t+i]=(e/s|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 i=n-1,s=1,o=0;for(this[t+i]=255&e;--i>=0&&(s*=256);)e<0&&0===o&&0!==this[t+i+1]&&(o=1),this[t+i]=(e/s|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=J(function(e,t=0){return B(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),o.prototype.writeBigInt64BE=J(function(e,t=0){return D(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),o.prototype.writeFloatLE=function(e,t,n){return O(this,e,t,!0,n)},o.prototype.writeFloatBE=function(e,t,n){return O(this,e,t,!1,n)},o.prototype.writeDoubleLE=function(e,t,n){return U(this,e,t,!0,n)},o.prototype.writeDoubleBE=function(e,t,n){return U(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 i=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),i},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 i;if(t>>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(i=t;i<n;++i)this[i]=e;else{const s=o.isBuffer(e)?e:o.from(e,r),a=s.length;if(0===a)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(i=0;i<n-t;++i)this[i+t]=s[i%a]}return this};const L={};function P(e,t,n){L[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,i,s){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*(s+1)}${n}`:`>= -(2${n} ** ${8*(s+1)-1}${n}) and < 2 ** ${8*(s+1)-1}${n}`,new L.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,i,s)}function K(e,t){if("number"!=typeof e)throw new L.ERR_INVALID_ARG_TYPE(t,"number",e)}function G(e,t,n){if(Math.floor(e)!==e)throw K(e,n),new L.ERR_OUT_OF_RANGE("offset","an integer",e);if(t<0)throw new L.ERR_BUFFER_OUT_OF_BOUNDS;throw new L.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.`,i=n;return Number.isInteger(n)&&Math.abs(n)>2**32?i=F(String(n)):"bigint"==typeof n&&(i=String(n),(n>BigInt(2)**BigInt(32)||n<-(BigInt(2)**BigInt(32)))&&(i=F(i)),i+="n"),r+=` It must be ${t}. Received ${i}`,r},RangeError);const H=/[^+/0-9A-Za-z-_]/g;function W(e,t){let n;t=t||1/0;const r=e.length;let i=null;const s=[];for(let o=0;o<r;++o){if(n=e.charCodeAt(o),n>55295&&n<57344){if(!i){if(n>56319){(t-=3)>-1&&s.push(239,191,189);continue}if(o+1===r){(t-=3)>-1&&s.push(239,191,189);continue}i=n;continue}if(n<56320){(t-=3)>-1&&s.push(239,191,189),i=n;continue}n=65536+(i-55296<<10|n-56320)}else i&&(t-=3)>-1&&s.push(239,191,189);if(i=null,n<128){if((t-=1)<0)break;s.push(n)}else if(n<2048){if((t-=2)<0)break;s.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;s.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;s.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return s}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 j(e,t,n,r){let i;for(i=0;i<r&&!(i+n>=t.length||i>=e.length);++i)t[i+n]=e[i];return i}function V(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function z(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 i=0;i<16;++i)t[r+i]=e[n]+e[i]}return t}();function J(e){return"undefined"==typeof BigInt?Y:e}function Y(){throw new Error("BigInt not supported")}}(ca)),ca}var pa=ma();const ya="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0;function ba(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function va(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function wa(e,...t){if(!ba(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 Ea(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.createHasher");va(e.outputLen),va(e.blockLen)}function Aa(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 ka(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Sa(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Ta(e,t){return e<<32-t|e>>>t}const Ia=(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)(),Na=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Ca(e){if(wa(e),Ia)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=Na[e[n]];return t}const _a=48,xa=57,Ra=65,Ba=70,Da=97,Ma=102;function Oa(e){return e>=_a&&e<=xa?e-_a:e>=Ra&&e<=Ba?e-(Ra-10):e>=Da&&e<=Ma?e-(Da-10):void 0}function Ua(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);if(Ia)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,i=0;t<n;t++,i+=2){const n=Oa(e.charCodeAt(i)),s=Oa(e.charCodeAt(i+1));if(void 0===n||void 0===s){const t=e[i]+e[i+1];throw new Error('hex string expected, got non-hex character "'+t+'" at index '+i)}r[t]=16*n+s}return r}function La(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)),wa(e),e}function Pa(...e){let t=0;for(let n=0;n<e.length;n++){const r=e[n];wa(r),t+=r.length}const n=new Uint8Array(t);for(let t=0,r=0;t<e.length;t++){const i=e[t];n.set(i,r),r+=i.length}return n}class Fa{}function $a(e){const t=t=>e().update(La(t)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function Ka(e=32){if(ya&&"function"==typeof ya.getRandomValues)return ya.getRandomValues(new Uint8Array(e));if(ya&&"function"==typeof ya.randomBytes)return Uint8Array.from(ya.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}function Ga(e,t,n){return e&t^~e&n}function Ha(e,t,n){return e&t^e&n^t&n}class Wa extends Fa{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=Sa(this.buffer)}update(e){Aa(this),wa(e=La(e));const{view:t,buffer:n,blockLen:r}=this,i=e.length;for(let s=0;s<i;){const o=Math.min(r-this.pos,i-s);if(o===r){const t=Sa(e);for(;r<=i-s;s+=r)this.process(t,s);continue}n.set(e.subarray(s,s+o),this.pos),this.pos+=o,s+=o,this.pos===r&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Aa(this),function(e,t){wa(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:i}=this;let{pos:s}=this;t[s++]=128,ka(this.buffer.subarray(s)),this.padOffset>r-s&&(this.process(n,0),s=0);for(let e=s;e<r;e++)t[e]=0;!function(e,t,n,r){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,n,r);const i=BigInt(32),s=BigInt(4294967295),o=Number(n>>i&s),a=Number(n&s),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),i),this.process(n,0);const o=Sa(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],i)}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:i,destroyed:s,pos:o}=this;return e.destroyed=s,e.finished=i,e.length=r,e.pos=o,r%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}}const qa=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ja=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Va=BigInt(2**32-1),za=BigInt(32);function Xa(e,t=!1){return t?{h:Number(e&Va),l:Number(e>>za&Va)}:{h:0|Number(e>>za&Va),l:0|Number(e&Va)}}const Ja=(e,t,n)=>e>>>n,Ya=(e,t,n)=>e<<32-n|t>>>n,Qa=(e,t,n)=>e>>>n|t<<32-n,Za=(e,t,n)=>e<<32-n|t>>>n,ec=(e,t,n)=>e<<64-n|t>>>n-32,tc=(e,t,n)=>e>>>n-32|t<<64-n;function nc(e,t,n,r){const i=(t>>>0)+(r>>>0);return{h:e+n+(i/2**32|0)|0,l:0|i}}const rc=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),ic=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,sc=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),oc=(e,t,n,r,i)=>t+n+r+i+(e/2**32|0)|0,ac=(e,t,n,r,i)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(i>>>0),cc=(e,t,n,r,i,s)=>t+n+r+i+s+(e/2**32|0)|0,lc=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]),uc=new Uint32Array(64);class dc extends Wa{constructor(e=32){super(64,e,8,!1),this.A=0|qa[0],this.B=0|qa[1],this.C=0|qa[2],this.D=0|qa[3],this.E=0|qa[4],this.F=0|qa[5],this.G=0|qa[6],this.H=0|qa[7]}get(){const{A:e,B:t,C:n,D:r,E:i,F:s,G:o,H:a}=this;return[e,t,n,r,i,s,o,a]}set(e,t,n,r,i,s,o,a){this.A=0|e,this.B=0|t,this.C=0|n,this.D=0|r,this.E=0|i,this.F=0|s,this.G=0|o,this.H=0|a}process(e,t){for(let n=0;n<16;n++,t+=4)uc[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){const t=uc[e-15],n=uc[e-2],r=Ta(t,7)^Ta(t,18)^t>>>3,i=Ta(n,17)^Ta(n,19)^n>>>10;uc[e]=i+uc[e-7]+r+uc[e-16]|0}let{A:n,B:r,C:i,D:s,E:o,F:a,G:c,H:l}=this;for(let e=0;e<64;e++){const t=l+(Ta(o,6)^Ta(o,11)^Ta(o,25))+Ga(o,a,c)+lc[e]+uc[e]|0,u=(Ta(n,2)^Ta(n,13)^Ta(n,22))+Ha(n,r,i)|0;l=c,c=a,a=o,o=s+t|0,s=i,i=r,r=n,n=t+u|0}n=n+this.A|0,r=r+this.B|0,i=i+this.C|0,s=s+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,i,s,o,a,c,l)}roundClean(){ka(uc)}destroy(){this.set(0,0,0,0,0,0,0,0),ka(this.buffer)}}const hc=(()=>function(e,t=!1){const n=e.length;let r=new Uint32Array(n),i=new Uint32Array(n);for(let s=0;s<n;s++){const{h:n,l:o}=Xa(e[s],t);[r[s],i[s]]=[n,o]}return[r,i]}(["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))))(),gc=(()=>hc[0])(),fc=(()=>hc[1])(),mc=new Uint32Array(80),pc=new Uint32Array(80);class yc extends Wa{constructor(e=64){super(128,e,16,!1),this.Ah=0|ja[0],this.Al=0|ja[1],this.Bh=0|ja[2],this.Bl=0|ja[3],this.Ch=0|ja[4],this.Cl=0|ja[5],this.Dh=0|ja[6],this.Dl=0|ja[7],this.Eh=0|ja[8],this.El=0|ja[9],this.Fh=0|ja[10],this.Fl=0|ja[11],this.Gh=0|ja[12],this.Gl=0|ja[13],this.Hh=0|ja[14],this.Hl=0|ja[15]}get(){const{Ah:e,Al:t,Bh:n,Bl:r,Ch:i,Cl:s,Dh:o,Dl:a,Eh:c,El:l,Fh:u,Fl:d,Gh:h,Gl:g,Hh:f,Hl:m}=this;return[e,t,n,r,i,s,o,a,c,l,u,d,h,g,f,m]}set(e,t,n,r,i,s,o,a,c,l,u,d,h,g,f,m){this.Ah=0|e,this.Al=0|t,this.Bh=0|n,this.Bl=0|r,this.Ch=0|i,this.Cl=0|s,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|m}process(e,t){for(let n=0;n<16;n++,t+=4)mc[n]=e.getUint32(t),pc[n]=e.getUint32(t+=4);for(let e=16;e<80;e++){const t=0|mc[e-15],n=0|pc[e-15],r=Qa(t,n,1)^Qa(t,n,8)^Ja(t,0,7),i=Za(t,n,1)^Za(t,n,8)^Ya(t,n,7),s=0|mc[e-2],o=0|pc[e-2],a=Qa(s,o,19)^ec(s,o,61)^Ja(s,0,6),c=Za(s,o,19)^tc(s,o,61)^Ya(s,o,6),l=sc(i,c,pc[e-7],pc[e-16]),u=oc(l,r,a,mc[e-7],mc[e-16]);mc[e]=0|u,pc[e]=0|l}let{Ah:n,Al:r,Bh:i,Bl:s,Ch:o,Cl:a,Dh:c,Dl:l,Eh:u,El:d,Fh:h,Fl:g,Gh:f,Gl:m,Hh:p,Hl:y}=this;for(let e=0;e<80;e++){const t=Qa(u,d,14)^Qa(u,d,18)^ec(u,d,41),b=Za(u,d,14)^Za(u,d,18)^tc(u,d,41),v=u&h^~u&f,w=ac(y,b,d&g^~d&m,fc[e],pc[e]),E=cc(w,p,t,v,gc[e],mc[e]),A=0|w,k=Qa(n,r,28)^ec(n,r,34)^ec(n,r,39),S=Za(n,r,28)^tc(n,r,34)^tc(n,r,39),T=n&i^n&o^i&o,I=r&s^r&a^s&a;p=0|f,y=0|m,f=0|h,m=0|g,h=0|u,g=0|d,({h:u,l:d}=nc(0|c,0|l,0|E,0|A)),c=0|o,l=0|a,o=0|i,a=0|s,i=0|n,s=0|r;const N=rc(A,S,I);n=ic(N,E,k,T),r=0|N}({h:n,l:r}=nc(0|this.Ah,0|this.Al,0|n,0|r)),({h:i,l:s}=nc(0|this.Bh,0|this.Bl,0|i,0|s)),({h:o,l:a}=nc(0|this.Ch,0|this.Cl,0|o,0|a)),({h:c,l:l}=nc(0|this.Dh,0|this.Dl,0|c,0|l)),({h:u,l:d}=nc(0|this.Eh,0|this.El,0|u,0|d)),({h:h,l:g}=nc(0|this.Fh,0|this.Fl,0|h,0|g)),({h:f,l:m}=nc(0|this.Gh,0|this.Gl,0|f,0|m)),({h:p,l:y}=nc(0|this.Hh,0|this.Hl,0|p,0|y)),this.set(n,r,i,s,o,a,c,l,u,d,h,g,f,m,p,y)}roundClean(){ka(mc,pc)}destroy(){ka(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const bc=$a(()=>new dc),vc=$a(()=>new yc),wc=BigInt(0),Ec=BigInt(1);function Ac(e,t=""){if("boolean"!=typeof e){throw new Error((t&&`"${t}"`)+"expected boolean, got type="+typeof e)}return e}function kc(e,t,n=""){const r=ba(e),i=e?.length,s=void 0!==t;if(!r||s&&i!==t){throw new Error((n&&`"${n}" `)+"expected Uint8Array"+(s?` of length ${t}`:"")+", got "+(r?`length=${i}`:"type="+typeof e))}return e}function Sc(e){const t=e.toString(16);return 1&t.length?"0"+t:t}function Tc(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);return""===e?wc:BigInt("0x"+e)}function Ic(e){return Tc(Ca(e))}function Nc(e){return wa(e),Tc(Ca(Uint8Array.from(e).reverse()))}function Cc(e,t){return Ua(e.toString(16).padStart(2*t,"0"))}function _c(e,t){return Cc(e,t).reverse()}function xc(e,t,n){let r;if("string"==typeof t)try{r=Ua(t)}catch(t){throw new Error(e+" must be hex string or Uint8Array, cause: "+t)}else{if(!ba(t))throw new Error(e+" must be hex string or Uint8Array");r=Uint8Array.from(t)}const i=r.length;if("number"==typeof n&&i!==n)throw new Error(e+" of length "+n+" expected, got "+i);return r}function Rc(e){return Uint8Array.from(e)}const Bc=e=>"bigint"==typeof e&&wc<=e;function Dc(e,t,n,r){if(!function(e,t,n){return Bc(e)&&Bc(t)&&Bc(n)&&t<=e&&e<n}(t,n,r))throw new Error("expected valid "+e+": "+n+" <= n < "+r+", got "+t)}function Mc(e){let t;for(t=0;e>wc;e>>=Ec,t+=1);return t}const Oc=e=>(Ec<<BigInt(e))-Ec;function Uc(e,t,n={}){if(!e||"object"!=typeof e)throw new Error("expected valid options object");function r(t,n,r){const i=e[t];if(r&&void 0===i)return;const s=typeof i;if(s!==n||null===i)throw new Error(`param "${t}" is invalid: expected ${n}, got ${s}`)}Object.entries(t).forEach(([e,t])=>r(e,t,!1)),Object.entries(n).forEach(([e,t])=>r(e,t,!0))}function Lc(e){const t=new WeakMap;return(n,...r)=>{const i=t.get(n);if(void 0!==i)return i;const s=e(n,...r);return t.set(n,s),s}}const Pc=BigInt(0),Fc=BigInt(1),$c=BigInt(2),Kc=BigInt(3),Gc=BigInt(4),Hc=BigInt(5),Wc=BigInt(7),qc=BigInt(8),jc=BigInt(9),Vc=BigInt(16);function zc(e,t){const n=e%t;return n>=Pc?n:t+n}function Xc(e,t,n){let r=e;for(;t-- >Pc;)r*=r,r%=n;return r}function Jc(e,t){if(e===Pc)throw new Error("invert: expected non-zero number");if(t<=Pc)throw new Error("invert: expected positive modulus, got "+t);let n=zc(e,t),r=t,i=Pc,s=Fc;for(;n!==Pc;){const e=r%n,t=i-s*(r/n);r=n,n=e,i=s,s=t}if(r!==Fc)throw new Error("invert: does not exist");return zc(i,t)}function Yc(e,t,n){if(!e.eql(e.sqr(t),n))throw new Error("Cannot find square root")}function Qc(e,t){const n=(e.ORDER+Fc)/Gc,r=e.pow(t,n);return Yc(e,r,t),r}function Zc(e,t){const n=(e.ORDER-Hc)/qc,r=e.mul(t,$c),i=e.pow(r,n),s=e.mul(t,i),o=e.mul(e.mul(s,$c),i),a=e.mul(s,e.sub(o,e.ONE));return Yc(e,a,t),a}function el(e){if(e<Kc)throw new Error("sqrt is not defined for small field");let t=e-Fc,n=0;for(;t%$c===Pc;)t/=$c,n++;let r=$c;const i=ol(e);for(;1===il(i,r);)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(1===n)return Qc;let s=i.pow(r,t);const o=(t+Fc)/$c;return function(e,r){if(e.is0(r))return r;if(1!==il(e,r))throw new Error("Cannot find square root");let i=n,a=e.mul(e.ONE,s),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===i)throw new Error("Cannot find square root");const r=Fc<<BigInt(i-t-1),s=e.pow(a,r);i=t,a=e.sqr(s),c=e.mul(c,a),l=e.mul(l,s)}return l}}function tl(e){return e%Gc===Kc?Qc:e%qc===Hc?Zc:e%Vc===jc?function(e){const t=ol(e),n=el(e),r=n(t,t.neg(t.ONE)),i=n(t,r),s=n(t,t.neg(r)),o=(e+Wc)/Vc;return(e,t)=>{let n=e.pow(t,o),a=e.mul(n,r);const c=e.mul(n,i),l=e.mul(n,s),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 Yc(e,g,t),g}}(e):el(e)}const nl=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function rl(e,t,n=!1){const r=new Array(t.length).fill(n?e.ZERO:void 0),i=t.reduce((t,n,i)=>e.is0(n)?t:(r[i]=t,e.mul(t,n)),e.ONE),s=e.inv(i);return t.reduceRight((t,n,i)=>e.is0(n)?t:(r[i]=e.mul(t,r[i]),e.mul(t,n)),s),r}function il(e,t){const n=(e.ORDER-Fc)/$c,r=e.pow(t,n),i=e.eql(r,e.ONE),s=e.eql(r,e.ZERO),o=e.eql(r,e.neg(e.ONE));if(!i&&!s&&!o)throw new Error("invalid Legendre symbol result");return i?1:s?0:-1}function sl(e,t){void 0!==t&&va(t);const n=void 0!==t?t:e.toString(2).length;return{nBitLength:n,nByteLength:Math.ceil(n/8)}}function ol(e,t,n=!1,r={}){if(e<=Pc)throw new Error("invalid field: expected ORDER > 0, got "+e);let i,s,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&&(i=e.BITS),e.sqrt&&(s=e.sqrt),"boolean"==typeof e.isLE&&(n=e.isLE),"boolean"==typeof e.modFromBytes&&(a=e.modFromBytes),o=e.allowedLengths}else"number"==typeof t&&(i=t),r.sqrt&&(s=r.sqrt);const{nBitLength:c,nByteLength:l}=sl(e,i);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:Oc(c),ZERO:Pc,ONE:Fc,allowedLengths:o,create:t=>zc(t,e),isValid:t=>{if("bigint"!=typeof t)throw new Error("invalid field element: expected bigint, got "+typeof t);return Pc<=t&&t<e},is0:e=>e===Pc,isValidNot0:e=>!d.is0(e)&&d.isValid(e),isOdd:e=>(e&Fc)===Fc,neg:t=>zc(-t,e),eql:(e,t)=>e===t,sqr:t=>zc(t*t,e),add:(t,n)=>zc(t+n,e),sub:(t,n)=>zc(t-n,e),mul:(t,n)=>zc(t*n,e),pow:(e,t)=>function(e,t,n){if(n<Pc)throw new Error("invalid exponent, negatives unsupported");if(n===Pc)return e.ONE;if(n===Fc)return t;let r=e.ONE,i=t;for(;n>Pc;)n&Fc&&(r=e.mul(r,i)),i=e.sqr(i),n>>=Fc;return r}(d,e,t),div:(t,n)=>zc(t*Jc(n,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>Jc(t,e),sqrt:s||(t=>(u||(u=tl(e)),u(d,t))),toBytes:e=>n?_c(e,l):Cc(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 i=n?Nc(t):Ic(t);if(a&&(i=zc(i,e)),!r&&!d.isValid(i))throw new Error("invalid field element: outside of range 0..ORDER");return i},invertBatch:e=>rl(d,e),cmov:(e,t,n)=>n?t:e});return Object.freeze(d)}function al(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 cl(e){const t=al(e);return t+Math.ceil(t/2)}const ll=BigInt(0),ul=BigInt(1);function dl(e,t){const n=t.negate();return e?n:t}function hl(e,t){const n=rl(e.Fp,t.map(e=>e.Z));return t.map((t,r)=>e.fromAffine(t.toAffine(n[r])))}function gl(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function fl(e,t){gl(e,t);const n=2**e;return{windows:Math.ceil(t/e)+1,windowSize:2**(e-1),mask:Oc(e),maxNumber:n,shiftBy:BigInt(e)}}function ml(e,t,n){const{windowSize:r,mask:i,maxNumber:s,shiftBy:o}=n;let a=Number(e&i),c=e>>o;a>r&&(a-=s,c+=ul);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 pl=new WeakMap,yl=new WeakMap;function bl(e){return yl.get(e)||1}function vl(e){if(e!==ll)throw new Error("invalid wNAF")}class wl{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>ll;)t&ul&&(n=n.add(r)),r=r.double(),t>>=ul;return n}precomputeWindow(e,t){const{windows:n,windowSize:r}=fl(t,this.bits),i=[];let s=e,o=s;for(let e=0;e<n;e++){o=s,i.push(o);for(let e=1;e<r;e++)o=o.add(s),i.push(o);s=o.double()}return i}wNAF(e,t,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let r=this.ZERO,i=this.BASE;const s=fl(e,this.bits);for(let e=0;e<s.windows;e++){const{nextN:o,offset:a,isZero:c,isNeg:l,isNegF:u,offsetF:d}=ml(n,e,s);n=o,c?i=i.add(dl(u,t[d])):r=r.add(dl(l,t[a]))}return vl(n),{p:r,f:i}}wNAFUnsafe(e,t,n,r=this.ZERO){const i=fl(e,this.bits);for(let e=0;e<i.windows&&n!==ll;e++){const{nextN:s,offset:o,isZero:a,isNeg:c}=ml(n,e,i);if(n=s,!a){const e=t[o];r=r.add(c?e.negate():e)}}return vl(n),r}getPrecomputes(e,t,n){let r=pl.get(t);return r||(r=this.precomputeWindow(t,e),1!==e&&("function"==typeof n&&(r=n(r)),pl.set(t,r))),r}cached(e,t,n){const r=bl(e);return this.wNAF(r,this.getPrecomputes(r,e,n),t)}unsafe(e,t,n,r){const i=bl(e);return 1===i?this._unsafeLadder(e,t,r):this.wNAFUnsafe(i,this.getPrecomputes(i,e,n),t,r)}createCache(e,t){gl(t,this.bits),yl.set(e,t),pl.delete(e)}hasCache(e){return 1!==bl(e)}}function El(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 i=n.length,s=r.length;if(i!==s)throw new Error("arrays of points and scalars must have equal length");const o=e.ZERO,a=Mc(BigInt(i));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const l=Oc(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<s;t++){const i=r[t],s=Number(i>>BigInt(e)&l);u[s]=u[s].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 Al(e,t,n){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return function(e){Uc(e,nl.reduce((e,t)=>(e[t]="function",e),{ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"}))}(t),t}return ol(e,{isLE:n})}function kl(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>ll))throw new Error(`CURVE.${e} must be positive bigint`)}const i=Al(t.p,n.Fp,r),s=Al(t.n,n.Fn,r),o=["Gx","Gy","a","weierstrass"===e?"b":"d"];for(const e of o)if(!i.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:i,Fn:s}}const Sl=BigInt(0),Tl=BigInt(1),Il=BigInt(2),Nl=BigInt(8);function Cl(e,t,n={}){if("function"!=typeof t)throw new Error('"hash" function param is required');Uc(n,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});const{prehash:r}=n,{BASE:i,Fp:s,Fn:o}=e,a=n.randomBytes||Ka,c=n.adjustScalarBytes||(e=>e),l=n.domain||((e,t,n)=>{if(Ac(n,"phflag"),t.length||n)throw new Error("Contexts/pre-hash are not supported");return e});function u(e){return o.create(Nc(e))}function d(e){const{head:n,prefix:r,scalar:s}=function(e){const n=p.secretKey;e=xc("private key",e,n);const r=xc("hashed private key",t(e),2*n),i=c(r.slice(0,n));return{head:i,prefix:r.slice(n,2*n),scalar:u(i)}}(e),o=i.multiply(s),a=o.toBytes();return{head:n,prefix:r,scalar:s,point:o,pointBytes:a}}function h(e){return d(e).pointBytes}function g(e=Uint8Array.of(),...n){const i=Pa(...n);return u(t(l(i,xc("context",e),!!r)))}const f={zip215:!0};const m=s.BYTES,p={secretKey:m,publicKey:m,signature:2*m,seed:m};function y(e=a(p.seed)){return kc(e,p.seed,"seed")}const b={getExtendedPublicKey:d,randomSecretKey:y,isValidSecretKey:function(e){return ba(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=p.publicKey,i=32===r;if(!i&&57!==r)throw new Error("only defined for 25519 and 448");const o=i?s.div(Tl+n,Tl-n):s.div(n-Tl,n+Tl);return s.toBytes(o)},toMontgomerySecret(e){const n=p.secretKey;kc(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=xc("message",e),r&&(e=r(e));const{prefix:s,scalar:a,pointBytes:c}=d(t),l=g(n.context,s,e),u=i.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 kc(Pa(u,o.toBytes(f)),p.signature,"result")},verify:function(t,n,s,o=f){const{context:a,zip215:c}=o,l=p.signature;t=xc("signature",t,l),n=xc("message",n),s=xc("publicKey",s,p.publicKey),void 0!==c&&Ac(c,"zip215"),r&&(n=r(n));const u=l/2,d=t.subarray(0,u),h=Nc(t.subarray(u,l));let m,y,b;try{m=e.fromBytes(s,c),y=e.fromBytes(d,c),b=i.multiplyUnsafe(h)}catch(e){return!1}if(!c&&m.isSmallOrder())return!1;const v=g(a,y.toBytes(),m.toBytes(),n);return y.add(m.multiplyUnsafe(v)).subtract(b).clearCofactor().is0()},utils:b,Point:e,lengths:p})}function _l(e){const{CURVE:t,curveOpts:n,hash:r,eddsaOpts:i}=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:ol(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),s=function(e,t={}){const n=kl("edwards",e,t,t.FpFnLE),{Fp:r,Fn:i}=n;let s=n.CURVE;const{h:o}=s;Uc(t,{},{uvRatio:"function"});const a=Il<<BigInt(8*i.BYTES)-Tl,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:Sl}}});if(!function(e,t,n,r){const i=e.sqr(n),s=e.sqr(r),o=e.add(e.mul(t.a,i),s),a=e.add(e.ONE,e.mul(t.d,e.mul(i,s)));return e.eql(o,a)}(r,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function u(e,t,n=!1){return Dc("coordinate "+e,t,n?Tl:Sl,a),t}function d(e){if(!(e instanceof f))throw new Error("ExtendedPoint expected")}const h=Lc((e,t)=>{const{X:n,Y:i,Z:s}=e,o=e.is0();null==t&&(t=o?Nl:r.inv(s));const a=c(n*t),l=c(i*t),u=r.mul(s,t);if(o)return{x:Sl,y:Tl};if(u!==Tl)throw new Error("invZ was invalid");return{x:a,y:l}}),g=Lc(e=>{const{a:t,d:n}=s;if(e.is0())throw new Error("bad point: ZERO");const{X:r,Y:i,Z:o,T:a}=e,l=c(r*r),u=c(i*i),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*i)!==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 s}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,Tl,c(t*n))}static fromBytes(e,t=!1){const n=r.BYTES,{a:i,d:o}=s;e=Rc(kc(e,n,"point")),Ac(t,"zip215");const u=Rc(e),d=e[n-1];u[n-1]=-129&d;const h=Nc(u),g=t?a:r.ORDER;Dc("point.y",h,Sl,g);const m=c(h*h),p=c(m-Tl),y=c(o*m-i);let{isValid:b,value:v}=l(p,y);if(!b)throw new Error("bad point: invalid y coordinate");const w=(v&Tl)===Tl,E=!!(128&d);if(!t&&v===Sl&&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(xc("point",e),t)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(e=8,t=!0){return m.createCache(this,e),t||this.multiply(Il),this}assertValidity(){g(this)}equals(e){d(e);const{X:t,Y:n,Z:r}=this,{X:i,Y:s,Z:o}=e,a=c(t*o),l=c(i*r),u=c(n*o),h=c(s*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}=s,{X:t,Y:n,Z:r}=this,i=c(t*t),o=c(n*n),a=c(Il*c(r*r)),l=c(e*i),u=t+n,d=c(c(u*u)-i-o),h=l+o,g=h-a,m=l-o,p=c(d*g),y=c(h*m),b=c(d*m),v=c(g*h);return new f(p,y,v,b)}add(e){d(e);const{a:t,d:n}=s,{X:r,Y:i,Z:o,T:a}=this,{X:l,Y:u,Z:h,T:g}=e,m=c(r*l),p=c(i*u),y=c(a*n*g),b=c(o*h),v=c((r+i)*(l+u)-m-p),w=b-y,E=b+y,A=c(p-t*m),k=c(v*w),S=c(E*A),T=c(v*A),I=c(w*E);return new f(k,S,I,T)}subtract(e){return this.add(e.negate())}multiply(e){if(!i.isValidNot0(e))throw new Error("invalid scalar: expected 1 <= sc < curve.n");const{p:t,f:n}=m.cached(this,e,e=>hl(f,e));return hl(f,[t,n])[0]}multiplyUnsafe(e,t=f.ZERO){if(!i.isValid(e))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return e===Sl?f.ZERO:this.is0()||e===Tl?this:m.unsafe(this,e,e=>hl(f,e),t)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}isTorsionFree(){return m.unsafe(this,s.n).is0()}toAffine(e){return h(this,e)}clearCofactor(){return o===Tl?this:this.multiplyUnsafe(o)}toBytes(){const{x:e,y:t}=this.toAffine(),n=r.toBytes(t);return n[n.length-1]|=e&Tl?128:0,n}toHex(){return Ca(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 hl(f,e)}static msm(e,t){return El(f,i,e,t)}_setWindowSize(e){this.precompute(e)}toRawBytes(){return this.toBytes()}}f.BASE=new f(s.Gx,s.Gy,Tl,c(s.Gx*s.Gy)),f.ZERO=new f(Sl,Tl,Tl,Sl),f.Fp=r,f.Fn=i;const m=new wl(f,i.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,Cl(s,r,i))}const xl=BigInt(1),Rl=BigInt(2);BigInt(3);const Bl=BigInt(5),Dl=BigInt(8),Ml=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Ol=(()=>({p:Ml,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Dl,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")}))();function Ul(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}const Ll=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Pl(e,t){const n=Ml,r=zc(t*t*t,n),i=function(e){const t=BigInt(10),n=BigInt(20),r=BigInt(40),i=BigInt(80),s=Ml,o=e*e%s*e%s,a=Xc(o,Rl,s)*o%s,c=Xc(a,xl,s)*e%s,l=Xc(c,Bl,s)*c%s,u=Xc(l,t,s)*l%s,d=Xc(u,n,s)*u%s,h=Xc(d,r,s)*d%s,g=Xc(h,i,s)*h%s,f=Xc(g,i,s)*h%s,m=Xc(f,t,s)*l%s;return{pow_p_5_8:Xc(m,Rl,s)*e%s,b2:o}}(e*zc(r*r*t,n)).pow_p_5_8;let s=zc(e*r*i,n);const o=zc(t*s*s,n),a=s,c=zc(s*Ll,n),l=o===e,u=o===zc(-e,n),d=o===zc(-e*Ll,n);return l&&(s=a),(u||d)&&(s=c),(zc(s,n)&Fc)===Fc&&(s=zc(-s,n)),{isValid:l||u,value:s}}const Fl=(()=>ol(Ol.p,{isLE:!0}))(),$l=(()=>({...Ol,Fp:Fl,hash:vc,adjustScalarBytes:Ul,uvRatio:Pl}))(),Kl=(()=>_l($l))();var Gl,Hl={exports:{}},Wl=oa(Object.freeze({__proto__:null,default:{}})),ql=Hl.exports;function jl(){return Gl||(Gl=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 i(e,t,n){if(i.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 s;"object"==typeof e?e.exports=i:t.BN=i,i.BN=i,i.wordSize=26;try{s="undefined"!=typeof window&&void 0!==window.Buffer?window.Buffer:Wl.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,i){for(var s=0,o=0,a=Math.min(e.length,r),c=t;c<a;c++){var l=e.charCodeAt(c)-48;s*=i,o=l>=49?l-49+10:l>=17?l-17+10:l,n(l>=0&&o<i,"Invalid character"),s+=o}return s}function l(e,t){e.words=t.words,e.length=t.length,e.negative=t.negative,e.red=t.red}if(i.isBN=function(e){return e instanceof i||null!==e&&"object"==typeof e&&e.constructor.wordSize===i.wordSize&&Array.isArray(e.words)},i.max=function(e,t){return e.cmp(t)>0?e:t},i.min=function(e,t){return e.cmp(t)<0?e:t},i.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 i=0;"-"===(e=e.toString().replace(/\s+/g,""))[0]&&(i++,this.negative=1),i<e.length&&(16===t?this._parseHex(e,i,r):(this._parseBase(e,t,i),"le"===r&&this._initArray(this.toArray(),t,r)))},i.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)},i.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 i=0;i<this.length;i++)this.words[i]=0;var s,o,a=0;if("be"===r)for(i=e.length-1,s=0;i>=0;i-=3)o=e[i]|e[i-1]<<8|e[i-2]<<16,this.words[s]|=o<<a&67108863,this.words[s+1]=o>>>26-a&67108863,(a+=24)>=26&&(a-=26,s++);else if("le"===r)for(i=0,s=0;i<e.length;i+=3)o=e[i]|e[i+1]<<8|e[i+2]<<16,this.words[s]|=o<<a&67108863,this.words[s+1]=o>>>26-a&67108863,(a+=24)>=26&&(a-=26,s++);return this._strip()},i.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 i,s=0,o=0;if("be"===n)for(r=e.length-1;r>=t;r-=2)i=a(e,t,r)<<s,this.words[o]|=67108863&i,s>=18?(s-=18,o+=1,this.words[o]|=i>>>26):s+=8;else for(r=(e.length-t)%2==0?t+1:t;r<e.length;r+=2)i=a(e,t,r)<<s,this.words[o]|=67108863&i,s>=18?(s-=18,o+=1,this.words[o]|=i>>>26):s+=8;this._strip()},i.prototype._parseBase=function(e,t,n){this.words=[0],this.length=1;for(var r=0,i=1;i<=67108863;i*=t)r++;r--,i=i/t|0;for(var s=e.length-n,o=s%r,a=Math.min(s,s-o)+n,l=0,u=n;u<a;u+=r)l=c(e,u,u+r,t),this.imuln(i),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()},i.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},i.prototype._move=function(e){l(e,this)},i.prototype.clone=function(){var e=new i(null);return this.copy(e),e},i.prototype._expand=function(e){for(;this.length<e;)this.words[this.length++]=0;return this},i.prototype._strip=function(){for(;this.length>1&&0===this.words[this.length-1];)this.length--;return this._normSign()},i.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},"undefined"!=typeof Symbol&&"function"==typeof Symbol.for)try{i.prototype[Symbol.for("nodejs.util.inspect.custom")]=u}catch(e){i.prototype.inspect=u}else i.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 i=0|e.words[0],s=0|t.words[0],o=i*s,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=(i=0|e.words[f])*(s=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()}i.prototype.toString=function(e,t){var r;if(t=0|t||1,16===(e=e||10)||"hex"===e){r="";for(var i=0,s=0,o=0;o<this.length;o++){var a=this.words[o],c=(16777215&(a<<i|s)).toString(16);s=a>>>24-i&16777215,(i+=2)>=26&&(i-=26,o--),r=0!==s||o!==this.length-1?d[6-c.length]+c+r:c+r}for(0!==s&&(r=s.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 m=f.modrn(u).toString(e);r=(f=f.idivn(u)).isZero()?m+r:d[l-m.length]+m+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")},i.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},i.prototype.toJSON=function(){return this.toString(16,2)},s&&(i.prototype.toBuffer=function(e,t){return this.toArrayLike(s,e,t)}),i.prototype.toArray=function(e,t){return this.toArrayLike(Array,e,t)},i.prototype.toArrayLike=function(e,t,r){this._strip();var i=this.byteLength(),s=r||Math.max(1,i);n(i<=s,"byte array longer than desired length"),n(s>0,"Requested array length <= 0");var o=function(e,t){return e.allocUnsafe?e.allocUnsafe(t):new e(t)}(e,s);return this["_toArrayLike"+("le"===t?"LE":"BE")](o,i),o},i.prototype._toArrayLikeLE=function(e,t){for(var n=0,r=0,i=0,s=0;i<this.length;i++){var o=this.words[i]<<s|r;e[n++]=255&o,n<e.length&&(e[n++]=o>>8&255),n<e.length&&(e[n++]=o>>16&255),6===s?(n<e.length&&(e[n++]=o>>24&255),r=0,s=0):(r=o>>>24,s+=2)}if(n<e.length)for(e[n++]=r;n<e.length;)e[n++]=0},i.prototype._toArrayLikeBE=function(e,t){for(var n=e.length-1,r=0,i=0,s=0;i<this.length;i++){var o=this.words[i]<<s|r;e[n--]=255&o,n>=0&&(e[n--]=o>>8&255),n>=0&&(e[n--]=o>>16&255),6===s?(n>=0&&(e[n--]=o>>24&255),r=0,s=0):(r=o>>>24,s+=2)}if(n>=0)for(e[n--]=r;n>=0;)e[n--]=0},Math.clz32?i.prototype._countBits=function(e){return 32-Math.clz32(e)}:i.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},i.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},i.prototype.bitLength=function(){var e=this.words[this.length-1],t=this._countBits(e);return 26*(this.length-1)+t},i.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},i.prototype.byteLength=function(){return Math.ceil(this.bitLength()/8)},i.prototype.toTwos=function(e){return 0!==this.negative?this.abs().inotn(e).iaddn(1):this.clone()},i.prototype.fromTwos=function(e){return this.testn(e-1)?this.notn(e).iaddn(1).ineg():this.clone()},i.prototype.isNeg=function(){return 0!==this.negative},i.prototype.neg=function(){return this.clone().ineg()},i.prototype.ineg=function(){return this.isZero()||(this.negative^=1),this},i.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()},i.prototype.ior=function(e){return n(0===(this.negative|e.negative)),this.iuor(e)},i.prototype.or=function(e){return this.length>e.length?this.clone().ior(e):e.clone().ior(this)},i.prototype.uor=function(e){return this.length>e.length?this.clone().iuor(e):e.clone().iuor(this)},i.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()},i.prototype.iand=function(e){return n(0===(this.negative|e.negative)),this.iuand(e)},i.prototype.and=function(e){return this.length>e.length?this.clone().iand(e):e.clone().iand(this)},i.prototype.uand=function(e){return this.length>e.length?this.clone().iuand(e):e.clone().iuand(this)},i.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()},i.prototype.ixor=function(e){return n(0===(this.negative|e.negative)),this.iuxor(e)},i.prototype.xor=function(e){return this.length>e.length?this.clone().ixor(e):e.clone().ixor(this)},i.prototype.uxor=function(e){return this.length>e.length?this.clone().iuxor(e):e.clone().iuxor(this)},i.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 i=0;i<t;i++)this.words[i]=67108863&~this.words[i];for(r>0&&(this.words[i]=~this.words[i]&67108863>>26-r,i++);i<this.length;i++)this.words[i]=0;return this._strip()},i.prototype.notn=function(e){return this.clone().inotn(e)},i.prototype.setn=function(e,t){n("number"==typeof e&&e>=0);var r=e/26|0,i=e%26;return this._expand(r+1),this.words[r]=t?this.words[r]|1<<i:this.words[r]&~(1<<i),this._strip()},i.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 i=0,s=0;s<r.length;s++)t=(0|n.words[s])+(0|r.words[s])+i,this.words[s]=67108863&t,i=t>>>26;for(;0!==i&&s<n.length;s++)t=(0|n.words[s])+i,this.words[s]=67108863&t,i=t>>>26;if(this.length=n.length,0!==i)this.words[this.length]=i,this.length++;else if(n!==this)for(;s<n.length;s++)this.words[s]=n.words[s];return this},i.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)},i.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,i=this.cmp(e);if(0===i)return this.negative=0,this.length=1,this.words[0]=0,this;i>0?(n=this,r=e):(n=e,r=this);for(var s=0,o=0;o<r.length;o++)s=(t=(0|n.words[o])-(0|r.words[o])+s)>>26,this.words[o]=67108863&t;for(;0!==s&&o<n.length;o++)s=(t=(0|n.words[o])+s)>>26,this.words[o]=67108863&t;if(0===s&&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()},i.prototype.sub=function(e){return this.clone().isub(e)};var m=function(e,t,n){var r,i,s,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,m=g>>>13,p=0|o[2],y=8191&p,b=p>>>13,v=0|o[3],w=8191&v,E=v>>>13,A=0|o[4],k=8191&A,S=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,M=0|o[8],O=8191&M,U=M>>>13,L=0|o[9],P=8191&L,F=L>>>13,$=0|a[0],K=8191&$,G=$>>>13,H=0|a[1],W=8191&H,q=H>>>13,j=0|a[2],V=8191&j,z=j>>>13,X=0|a[3],J=8191&X,Y=X>>>13,Q=0|a[4],Z=8191&Q,ee=Q>>>13,te=0|a[5],ne=8191&te,re=te>>>13,ie=0|a[6],se=8191&ie,oe=ie>>>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,me=ge>>>13;n.negative=e.negative^t.negative,n.length=19;var pe=(l+(r=Math.imul(d,K))|0)+((8191&(i=(i=Math.imul(d,G))+Math.imul(h,K)|0))<<13)|0;l=((s=Math.imul(h,G))+(i>>>13)|0)+(pe>>>26)|0,pe&=67108863,r=Math.imul(f,K),i=(i=Math.imul(f,G))+Math.imul(m,K)|0,s=Math.imul(m,G);var ye=(l+(r=r+Math.imul(d,W)|0)|0)+((8191&(i=(i=i+Math.imul(d,q)|0)+Math.imul(h,W)|0))<<13)|0;l=((s=s+Math.imul(h,q)|0)+(i>>>13)|0)+(ye>>>26)|0,ye&=67108863,r=Math.imul(y,K),i=(i=Math.imul(y,G))+Math.imul(b,K)|0,s=Math.imul(b,G),r=r+Math.imul(f,W)|0,i=(i=i+Math.imul(f,q)|0)+Math.imul(m,W)|0,s=s+Math.imul(m,q)|0;var be=(l+(r=r+Math.imul(d,V)|0)|0)+((8191&(i=(i=i+Math.imul(d,z)|0)+Math.imul(h,V)|0))<<13)|0;l=((s=s+Math.imul(h,z)|0)+(i>>>13)|0)+(be>>>26)|0,be&=67108863,r=Math.imul(w,K),i=(i=Math.imul(w,G))+Math.imul(E,K)|0,s=Math.imul(E,G),r=r+Math.imul(y,W)|0,i=(i=i+Math.imul(y,q)|0)+Math.imul(b,W)|0,s=s+Math.imul(b,q)|0,r=r+Math.imul(f,V)|0,i=(i=i+Math.imul(f,z)|0)+Math.imul(m,V)|0,s=s+Math.imul(m,z)|0;var ve=(l+(r=r+Math.imul(d,J)|0)|0)+((8191&(i=(i=i+Math.imul(d,Y)|0)+Math.imul(h,J)|0))<<13)|0;l=((s=s+Math.imul(h,Y)|0)+(i>>>13)|0)+(ve>>>26)|0,ve&=67108863,r=Math.imul(k,K),i=(i=Math.imul(k,G))+Math.imul(S,K)|0,s=Math.imul(S,G),r=r+Math.imul(w,W)|0,i=(i=i+Math.imul(w,q)|0)+Math.imul(E,W)|0,s=s+Math.imul(E,q)|0,r=r+Math.imul(y,V)|0,i=(i=i+Math.imul(y,z)|0)+Math.imul(b,V)|0,s=s+Math.imul(b,z)|0,r=r+Math.imul(f,J)|0,i=(i=i+Math.imul(f,Y)|0)+Math.imul(m,J)|0,s=s+Math.imul(m,Y)|0;var we=(l+(r=r+Math.imul(d,Z)|0)|0)+((8191&(i=(i=i+Math.imul(d,ee)|0)+Math.imul(h,Z)|0))<<13)|0;l=((s=s+Math.imul(h,ee)|0)+(i>>>13)|0)+(we>>>26)|0,we&=67108863,r=Math.imul(I,K),i=(i=Math.imul(I,G))+Math.imul(N,K)|0,s=Math.imul(N,G),r=r+Math.imul(k,W)|0,i=(i=i+Math.imul(k,q)|0)+Math.imul(S,W)|0,s=s+Math.imul(S,q)|0,r=r+Math.imul(w,V)|0,i=(i=i+Math.imul(w,z)|0)+Math.imul(E,V)|0,s=s+Math.imul(E,z)|0,r=r+Math.imul(y,J)|0,i=(i=i+Math.imul(y,Y)|0)+Math.imul(b,J)|0,s=s+Math.imul(b,Y)|0,r=r+Math.imul(f,Z)|0,i=(i=i+Math.imul(f,ee)|0)+Math.imul(m,Z)|0,s=s+Math.imul(m,ee)|0;var Ee=(l+(r=r+Math.imul(d,ne)|0)|0)+((8191&(i=(i=i+Math.imul(d,re)|0)+Math.imul(h,ne)|0))<<13)|0;l=((s=s+Math.imul(h,re)|0)+(i>>>13)|0)+(Ee>>>26)|0,Ee&=67108863,r=Math.imul(_,K),i=(i=Math.imul(_,G))+Math.imul(x,K)|0,s=Math.imul(x,G),r=r+Math.imul(I,W)|0,i=(i=i+Math.imul(I,q)|0)+Math.imul(N,W)|0,s=s+Math.imul(N,q)|0,r=r+Math.imul(k,V)|0,i=(i=i+Math.imul(k,z)|0)+Math.imul(S,V)|0,s=s+Math.imul(S,z)|0,r=r+Math.imul(w,J)|0,i=(i=i+Math.imul(w,Y)|0)+Math.imul(E,J)|0,s=s+Math.imul(E,Y)|0,r=r+Math.imul(y,Z)|0,i=(i=i+Math.imul(y,ee)|0)+Math.imul(b,Z)|0,s=s+Math.imul(b,ee)|0,r=r+Math.imul(f,ne)|0,i=(i=i+Math.imul(f,re)|0)+Math.imul(m,ne)|0,s=s+Math.imul(m,re)|0;var Ae=(l+(r=r+Math.imul(d,se)|0)|0)+((8191&(i=(i=i+Math.imul(d,oe)|0)+Math.imul(h,se)|0))<<13)|0;l=((s=s+Math.imul(h,oe)|0)+(i>>>13)|0)+(Ae>>>26)|0,Ae&=67108863,r=Math.imul(B,K),i=(i=Math.imul(B,G))+Math.imul(D,K)|0,s=Math.imul(D,G),r=r+Math.imul(_,W)|0,i=(i=i+Math.imul(_,q)|0)+Math.imul(x,W)|0,s=s+Math.imul(x,q)|0,r=r+Math.imul(I,V)|0,i=(i=i+Math.imul(I,z)|0)+Math.imul(N,V)|0,s=s+Math.imul(N,z)|0,r=r+Math.imul(k,J)|0,i=(i=i+Math.imul(k,Y)|0)+Math.imul(S,J)|0,s=s+Math.imul(S,Y)|0,r=r+Math.imul(w,Z)|0,i=(i=i+Math.imul(w,ee)|0)+Math.imul(E,Z)|0,s=s+Math.imul(E,ee)|0,r=r+Math.imul(y,ne)|0,i=(i=i+Math.imul(y,re)|0)+Math.imul(b,ne)|0,s=s+Math.imul(b,re)|0,r=r+Math.imul(f,se)|0,i=(i=i+Math.imul(f,oe)|0)+Math.imul(m,se)|0,s=s+Math.imul(m,oe)|0;var ke=(l+(r=r+Math.imul(d,ce)|0)|0)+((8191&(i=(i=i+Math.imul(d,le)|0)+Math.imul(h,ce)|0))<<13)|0;l=((s=s+Math.imul(h,le)|0)+(i>>>13)|0)+(ke>>>26)|0,ke&=67108863,r=Math.imul(O,K),i=(i=Math.imul(O,G))+Math.imul(U,K)|0,s=Math.imul(U,G),r=r+Math.imul(B,W)|0,i=(i=i+Math.imul(B,q)|0)+Math.imul(D,W)|0,s=s+Math.imul(D,q)|0,r=r+Math.imul(_,V)|0,i=(i=i+Math.imul(_,z)|0)+Math.imul(x,V)|0,s=s+Math.imul(x,z)|0,r=r+Math.imul(I,J)|0,i=(i=i+Math.imul(I,Y)|0)+Math.imul(N,J)|0,s=s+Math.imul(N,Y)|0,r=r+Math.imul(k,Z)|0,i=(i=i+Math.imul(k,ee)|0)+Math.imul(S,Z)|0,s=s+Math.imul(S,ee)|0,r=r+Math.imul(w,ne)|0,i=(i=i+Math.imul(w,re)|0)+Math.imul(E,ne)|0,s=s+Math.imul(E,re)|0,r=r+Math.imul(y,se)|0,i=(i=i+Math.imul(y,oe)|0)+Math.imul(b,se)|0,s=s+Math.imul(b,oe)|0,r=r+Math.imul(f,ce)|0,i=(i=i+Math.imul(f,le)|0)+Math.imul(m,ce)|0,s=s+Math.imul(m,le)|0;var Se=(l+(r=r+Math.imul(d,de)|0)|0)+((8191&(i=(i=i+Math.imul(d,he)|0)+Math.imul(h,de)|0))<<13)|0;l=((s=s+Math.imul(h,he)|0)+(i>>>13)|0)+(Se>>>26)|0,Se&=67108863,r=Math.imul(P,K),i=(i=Math.imul(P,G))+Math.imul(F,K)|0,s=Math.imul(F,G),r=r+Math.imul(O,W)|0,i=(i=i+Math.imul(O,q)|0)+Math.imul(U,W)|0,s=s+Math.imul(U,q)|0,r=r+Math.imul(B,V)|0,i=(i=i+Math.imul(B,z)|0)+Math.imul(D,V)|0,s=s+Math.imul(D,z)|0,r=r+Math.imul(_,J)|0,i=(i=i+Math.imul(_,Y)|0)+Math.imul(x,J)|0,s=s+Math.imul(x,Y)|0,r=r+Math.imul(I,Z)|0,i=(i=i+Math.imul(I,ee)|0)+Math.imul(N,Z)|0,s=s+Math.imul(N,ee)|0,r=r+Math.imul(k,ne)|0,i=(i=i+Math.imul(k,re)|0)+Math.imul(S,ne)|0,s=s+Math.imul(S,re)|0,r=r+Math.imul(w,se)|0,i=(i=i+Math.imul(w,oe)|0)+Math.imul(E,se)|0,s=s+Math.imul(E,oe)|0,r=r+Math.imul(y,ce)|0,i=(i=i+Math.imul(y,le)|0)+Math.imul(b,ce)|0,s=s+Math.imul(b,le)|0,r=r+Math.imul(f,de)|0,i=(i=i+Math.imul(f,he)|0)+Math.imul(m,de)|0,s=s+Math.imul(m,he)|0;var Te=(l+(r=r+Math.imul(d,fe)|0)|0)+((8191&(i=(i=i+Math.imul(d,me)|0)+Math.imul(h,fe)|0))<<13)|0;l=((s=s+Math.imul(h,me)|0)+(i>>>13)|0)+(Te>>>26)|0,Te&=67108863,r=Math.imul(P,W),i=(i=Math.imul(P,q))+Math.imul(F,W)|0,s=Math.imul(F,q),r=r+Math.imul(O,V)|0,i=(i=i+Math.imul(O,z)|0)+Math.imul(U,V)|0,s=s+Math.imul(U,z)|0,r=r+Math.imul(B,J)|0,i=(i=i+Math.imul(B,Y)|0)+Math.imul(D,J)|0,s=s+Math.imul(D,Y)|0,r=r+Math.imul(_,Z)|0,i=(i=i+Math.imul(_,ee)|0)+Math.imul(x,Z)|0,s=s+Math.imul(x,ee)|0,r=r+Math.imul(I,ne)|0,i=(i=i+Math.imul(I,re)|0)+Math.imul(N,ne)|0,s=s+Math.imul(N,re)|0,r=r+Math.imul(k,se)|0,i=(i=i+Math.imul(k,oe)|0)+Math.imul(S,se)|0,s=s+Math.imul(S,oe)|0,r=r+Math.imul(w,ce)|0,i=(i=i+Math.imul(w,le)|0)+Math.imul(E,ce)|0,s=s+Math.imul(E,le)|0,r=r+Math.imul(y,de)|0,i=(i=i+Math.imul(y,he)|0)+Math.imul(b,de)|0,s=s+Math.imul(b,he)|0;var Ie=(l+(r=r+Math.imul(f,fe)|0)|0)+((8191&(i=(i=i+Math.imul(f,me)|0)+Math.imul(m,fe)|0))<<13)|0;l=((s=s+Math.imul(m,me)|0)+(i>>>13)|0)+(Ie>>>26)|0,Ie&=67108863,r=Math.imul(P,V),i=(i=Math.imul(P,z))+Math.imul(F,V)|0,s=Math.imul(F,z),r=r+Math.imul(O,J)|0,i=(i=i+Math.imul(O,Y)|0)+Math.imul(U,J)|0,s=s+Math.imul(U,Y)|0,r=r+Math.imul(B,Z)|0,i=(i=i+Math.imul(B,ee)|0)+Math.imul(D,Z)|0,s=s+Math.imul(D,ee)|0,r=r+Math.imul(_,ne)|0,i=(i=i+Math.imul(_,re)|0)+Math.imul(x,ne)|0,s=s+Math.imul(x,re)|0,r=r+Math.imul(I,se)|0,i=(i=i+Math.imul(I,oe)|0)+Math.imul(N,se)|0,s=s+Math.imul(N,oe)|0,r=r+Math.imul(k,ce)|0,i=(i=i+Math.imul(k,le)|0)+Math.imul(S,ce)|0,s=s+Math.imul(S,le)|0,r=r+Math.imul(w,de)|0,i=(i=i+Math.imul(w,he)|0)+Math.imul(E,de)|0,s=s+Math.imul(E,he)|0;var Ne=(l+(r=r+Math.imul(y,fe)|0)|0)+((8191&(i=(i=i+Math.imul(y,me)|0)+Math.imul(b,fe)|0))<<13)|0;l=((s=s+Math.imul(b,me)|0)+(i>>>13)|0)+(Ne>>>26)|0,Ne&=67108863,r=Math.imul(P,J),i=(i=Math.imul(P,Y))+Math.imul(F,J)|0,s=Math.imul(F,Y),r=r+Math.imul(O,Z)|0,i=(i=i+Math.imul(O,ee)|0)+Math.imul(U,Z)|0,s=s+Math.imul(U,ee)|0,r=r+Math.imul(B,ne)|0,i=(i=i+Math.imul(B,re)|0)+Math.imul(D,ne)|0,s=s+Math.imul(D,re)|0,r=r+Math.imul(_,se)|0,i=(i=i+Math.imul(_,oe)|0)+Math.imul(x,se)|0,s=s+Math.imul(x,oe)|0,r=r+Math.imul(I,ce)|0,i=(i=i+Math.imul(I,le)|0)+Math.imul(N,ce)|0,s=s+Math.imul(N,le)|0,r=r+Math.imul(k,de)|0,i=(i=i+Math.imul(k,he)|0)+Math.imul(S,de)|0,s=s+Math.imul(S,he)|0;var Ce=(l+(r=r+Math.imul(w,fe)|0)|0)+((8191&(i=(i=i+Math.imul(w,me)|0)+Math.imul(E,fe)|0))<<13)|0;l=((s=s+Math.imul(E,me)|0)+(i>>>13)|0)+(Ce>>>26)|0,Ce&=67108863,r=Math.imul(P,Z),i=(i=Math.imul(P,ee))+Math.imul(F,Z)|0,s=Math.imul(F,ee),r=r+Math.imul(O,ne)|0,i=(i=i+Math.imul(O,re)|0)+Math.imul(U,ne)|0,s=s+Math.imul(U,re)|0,r=r+Math.imul(B,se)|0,i=(i=i+Math.imul(B,oe)|0)+Math.imul(D,se)|0,s=s+Math.imul(D,oe)|0,r=r+Math.imul(_,ce)|0,i=(i=i+Math.imul(_,le)|0)+Math.imul(x,ce)|0,s=s+Math.imul(x,le)|0,r=r+Math.imul(I,de)|0,i=(i=i+Math.imul(I,he)|0)+Math.imul(N,de)|0,s=s+Math.imul(N,he)|0;var _e=(l+(r=r+Math.imul(k,fe)|0)|0)+((8191&(i=(i=i+Math.imul(k,me)|0)+Math.imul(S,fe)|0))<<13)|0;l=((s=s+Math.imul(S,me)|0)+(i>>>13)|0)+(_e>>>26)|0,_e&=67108863,r=Math.imul(P,ne),i=(i=Math.imul(P,re))+Math.imul(F,ne)|0,s=Math.imul(F,re),r=r+Math.imul(O,se)|0,i=(i=i+Math.imul(O,oe)|0)+Math.imul(U,se)|0,s=s+Math.imul(U,oe)|0,r=r+Math.imul(B,ce)|0,i=(i=i+Math.imul(B,le)|0)+Math.imul(D,ce)|0,s=s+Math.imul(D,le)|0,r=r+Math.imul(_,de)|0,i=(i=i+Math.imul(_,he)|0)+Math.imul(x,de)|0,s=s+Math.imul(x,he)|0;var xe=(l+(r=r+Math.imul(I,fe)|0)|0)+((8191&(i=(i=i+Math.imul(I,me)|0)+Math.imul(N,fe)|0))<<13)|0;l=((s=s+Math.imul(N,me)|0)+(i>>>13)|0)+(xe>>>26)|0,xe&=67108863,r=Math.imul(P,se),i=(i=Math.imul(P,oe))+Math.imul(F,se)|0,s=Math.imul(F,oe),r=r+Math.imul(O,ce)|0,i=(i=i+Math.imul(O,le)|0)+Math.imul(U,ce)|0,s=s+Math.imul(U,le)|0,r=r+Math.imul(B,de)|0,i=(i=i+Math.imul(B,he)|0)+Math.imul(D,de)|0,s=s+Math.imul(D,he)|0;var Re=(l+(r=r+Math.imul(_,fe)|0)|0)+((8191&(i=(i=i+Math.imul(_,me)|0)+Math.imul(x,fe)|0))<<13)|0;l=((s=s+Math.imul(x,me)|0)+(i>>>13)|0)+(Re>>>26)|0,Re&=67108863,r=Math.imul(P,ce),i=(i=Math.imul(P,le))+Math.imul(F,ce)|0,s=Math.imul(F,le),r=r+Math.imul(O,de)|0,i=(i=i+Math.imul(O,he)|0)+Math.imul(U,de)|0,s=s+Math.imul(U,he)|0;var Be=(l+(r=r+Math.imul(B,fe)|0)|0)+((8191&(i=(i=i+Math.imul(B,me)|0)+Math.imul(D,fe)|0))<<13)|0;l=((s=s+Math.imul(D,me)|0)+(i>>>13)|0)+(Be>>>26)|0,Be&=67108863,r=Math.imul(P,de),i=(i=Math.imul(P,he))+Math.imul(F,de)|0,s=Math.imul(F,he);var De=(l+(r=r+Math.imul(O,fe)|0)|0)+((8191&(i=(i=i+Math.imul(O,me)|0)+Math.imul(U,fe)|0))<<13)|0;l=((s=s+Math.imul(U,me)|0)+(i>>>13)|0)+(De>>>26)|0,De&=67108863;var Me=(l+(r=Math.imul(P,fe))|0)+((8191&(i=(i=Math.imul(P,me))+Math.imul(F,fe)|0))<<13)|0;return l=((s=Math.imul(F,me))+(i>>>13)|0)+(Me>>>26)|0,Me&=67108863,c[0]=pe,c[1]=ye,c[2]=be,c[3]=ve,c[4]=we,c[5]=Ee,c[6]=Ae,c[7]=ke,c[8]=Se,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]=Me,0!==l&&(c[19]=l,n.length++),n};function p(e,t,n){n.negative=t.negative^e.negative,n.length=e.length+t.length;for(var r=0,i=0,s=0;s<n.length-1;s++){var o=i;i=0;for(var a=67108863&r,c=Math.min(s,t.length-1),l=Math.max(0,s-e.length+1);l<=c;l++){var u=s-l,d=(0|e.words[u])*(0|t.words[l]),h=67108863&d;a=67108863&(h=h+a|0),i+=(o=(o=o+(d/67108864|0)|0)+(h>>>26)|0)>>>26,o&=67108863}n.words[s]=a,r=o,o=i}return 0!==r?n.words[s]=r:n.length--,n._strip()}function y(e,t,n){return p(e,t,n)}Math.imul||(m=f),i.prototype.mulTo=function(e,t){var n=this.length+e.length;return 10===this.length&&10===e.length?m(this,e,t):n<63?f(this,e,t):n<1024?p(this,e,t):y(this,e,t)},i.prototype.mul=function(e){var t=new i(null);return t.words=new Array(this.length+e.length),this.mulTo(e,t)},i.prototype.mulf=function(e){var t=new i(null);return t.words=new Array(this.length+e.length),y(this,e,t)},i.prototype.imul=function(e){return this.clone().mulTo(e,this)},i.prototype.imuln=function(e){var t=e<0;t&&(e=-e),n("number"==typeof e),n(e<67108864);for(var r=0,i=0;i<this.length;i++){var s=(0|this.words[i])*e,o=(67108863&s)+(67108863&r);r>>=26,r+=s/67108864|0,r+=o>>>26,this.words[i]=67108863&o}return 0!==r&&(this.words[i]=r,this.length++),0===e&&(this.length=1,this._normSign()),t?this.ineg():this},i.prototype.muln=function(e){return this.clone().imuln(e)},i.prototype.sqr=function(){return this.mul(this)},i.prototype.isqr=function(){return this.imul(this.clone())},i.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,i=n%26;t[n]=e.words[r]>>>i&1}return t}(e);if(0===t.length)return new i(1);for(var n=this,r=0;r<t.length&&0===t[r];r++,n=n.sqr());if(++r<t.length)for(var s=n.sqr();r<t.length;r++,s=s.sqr())0!==t[r]&&(n=n.mul(s));return n},i.prototype.iushln=function(e){n("number"==typeof e&&e>=0);var t,r=e%26,i=(e-r)/26,s=67108863>>>26-r<<26-r;if(0!==r){var o=0;for(t=0;t<this.length;t++){var a=this.words[t]&s,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!==i){for(t=this.length-1;t>=0;t--)this.words[t+i]=this.words[t];for(t=0;t<i;t++)this.words[t]=0;this.length+=i}return this._strip()},i.prototype.ishln=function(e){return n(0===this.negative),this.iushln(e)},i.prototype.iushrn=function(e,t,r){var i;n("number"==typeof e&&e>=0),i=t?(t-t%26)/26:0;var s=e%26,o=Math.min((e-s)/26,this.length),a=67108863^67108863>>>s<<s,c=r;if(i-=o,i=Math.max(0,i),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>=i);l--){var d=0|this.words[l];this.words[l]=u<<26-s|d>>>s,u=d&a}return c&&0!==u&&(c.words[c.length++]=u),0===this.length&&(this.words[0]=0,this.length=1),this._strip()},i.prototype.ishrn=function(e,t,r){return n(0===this.negative),this.iushrn(e,t,r)},i.prototype.shln=function(e){return this.clone().ishln(e)},i.prototype.ushln=function(e){return this.clone().iushln(e)},i.prototype.shrn=function(e){return this.clone().ishrn(e)},i.prototype.ushrn=function(e){return this.clone().iushrn(e)},i.prototype.testn=function(e){n("number"==typeof e&&e>=0);var t=e%26,r=(e-t)/26,i=1<<t;return!(this.length<=r||!(this.words[r]&i))},i.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 i=67108863^67108863>>>t<<t;this.words[this.length-1]&=i}return 0===this.length&&(this.words[0]=0,this.length=1),this._strip()},i.prototype.maskn=function(e){return this.clone().imaskn(e)},i.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)},i.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},i.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()},i.prototype.addn=function(e){return this.clone().iaddn(e)},i.prototype.subn=function(e){return this.clone().isubn(e)},i.prototype.iabs=function(){return this.negative=0,this},i.prototype.abs=function(){return this.clone().iabs()},i.prototype._ishlnsubmul=function(e,t,r){var i,s,o=e.length+r;this._expand(o);var a=0;for(i=0;i<e.length;i++){s=(0|this.words[i+r])+a;var c=(0|e.words[i])*t;a=((s-=67108863&c)>>26)-(c/67108864|0),this.words[i+r]=67108863&s}for(;i<this.length-r;i++)a=(s=(0|this.words[i+r])+a)>>26,this.words[i+r]=67108863&s;if(0===a)return this._strip();for(n(-1===a),a=0,i=0;i<this.length;i++)a=(s=-(0|this.words[i])+a)>>26,this.words[i]=67108863&s;return this.negative=1,this._strip()},i.prototype._wordDiv=function(e,t){var n=(this.length,e.length),r=this.clone(),s=e,o=0|s.words[s.length-1];0!=(n=26-this._countBits(o))&&(s=s.ushln(n),r.iushln(n),o=0|s.words[s.length-1]);var a,c=r.length-s.length;if("mod"!==t){(a=new i(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(s,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[s.length+d])+(0|r.words[s.length+d-1]);for(h=Math.min(h/o|0,67108863),r._ishlnsubmul(s,h,d);0!==r.negative;)h--,r.negative=0,r._ishlnsubmul(s,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}},i.prototype.divmod=function(e,t,r){return n(!e.isZero()),this.isZero()?{div:new i(0),mod:new i(0)}:0!==this.negative&&0===e.negative?(a=this.neg().divmod(e,t),"mod"!==t&&(s=a.div.neg()),"div"!==t&&(o=a.mod.neg(),r&&0!==o.negative&&o.iadd(e)),{div:s,mod:o}):0===this.negative&&0!==e.negative?(a=this.divmod(e.neg(),t),"mod"!==t&&(s=a.div.neg()),{div:s,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 i(0),mod:this}:1===e.length?"div"===t?{div:this.divn(e.words[0]),mod:null}:"mod"===t?{div:null,mod:new i(this.modrn(e.words[0]))}:{div:this.divn(e.words[0]),mod:new i(this.modrn(e.words[0]))}:this._wordDiv(e,t);var s,o,a},i.prototype.div=function(e){return this.divmod(e,"div",!1).div},i.prototype.mod=function(e){return this.divmod(e,"mod",!1).mod},i.prototype.umod=function(e){return this.divmod(e,"mod",!0).mod},i.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),s=1&e.words[0],o=n.cmp(r);if(o<0||1===s&&0===o)return t.div;var a=new i(1);return a.negative=this.negative^e.negative,t.div.iadd(a)},i.prototype.modrn=function(e){var t=e<0;t&&(e=-e),n(e<=67108863);for(var r=(1<<26)%e,i=0,s=this.length-1;s>=0;s--)i=(r*i+(0|this.words[s]))%e;return t?-i:i},i.prototype.modn=function(e){return this.modrn(e)},i.prototype.idivn=function(e){var t=e<0;t&&(e=-e),n(e<=67108863);for(var r=0,i=this.length-1;i>=0;i--){var s=(0|this.words[i])+67108864*r;this.words[i]=s/e|0,r=s%e}return this._strip(),t?this.ineg():this},i.prototype.divn=function(e){return this.clone().idivn(e)},i.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 s=new i(1),o=new i(0),a=new i(0),c=new i(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;)(s.isOdd()||o.isOdd())&&(s.iadd(u),o.isub(d)),s.iushrn(1),o.iushrn(1);for(var f=0,m=1;0===(r.words[0]&m)&&f<26;++f,m<<=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),s.isub(a),o.isub(c)):(r.isub(t),a.isub(s),c.isub(o))}return{a:a,b:c,gcd:r.iushln(l)}},i.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 s,o=new i(1),a=new i(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(s=0===t.cmpn(1)?o:a).cmpn(0)<0&&s.iadd(e),s},i.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 i=t.cmp(n);if(i<0){var s=t;t=n,n=s}else if(0===i||0===n.cmpn(1))break;t.isub(n)}return n.iushln(r)},i.prototype.invm=function(e){return this.egcd(e).a.umod(e)},i.prototype.isEven=function(){return!(1&this.words[0])},i.prototype.isOdd=function(){return!(1&~this.words[0])},i.prototype.andln=function(e){return this.words[0]&e},i.prototype.bincn=function(e){n("number"==typeof e);var t=e%26,r=(e-t)/26,i=1<<t;if(this.length<=r)return this._expand(r+1),this.words[r]|=i,this;for(var s=i,o=r;0!==s&&o<this.length;o++){var a=0|this.words[o];s=(a+=s)>>>26,a&=67108863,this.words[o]=a}return 0!==s&&(this.words[o]=s,this.length++),this},i.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},i.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 i=0|this.words[0];t=i===e?0:i<e?-1:1}return 0!==this.negative?0|-t:t},i.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},i.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],i=0|e.words[n];if(r!==i){r<i?t=-1:r>i&&(t=1);break}}return t},i.prototype.gtn=function(e){return 1===this.cmpn(e)},i.prototype.gt=function(e){return 1===this.cmp(e)},i.prototype.gten=function(e){return this.cmpn(e)>=0},i.prototype.gte=function(e){return this.cmp(e)>=0},i.prototype.ltn=function(e){return-1===this.cmpn(e)},i.prototype.lt=function(e){return-1===this.cmp(e)},i.prototype.lten=function(e){return this.cmpn(e)<=0},i.prototype.lte=function(e){return this.cmp(e)<=0},i.prototype.eqn=function(e){return 0===this.cmpn(e)},i.prototype.eq=function(e){return 0===this.cmp(e)},i.red=function(e){return new S(e)},i.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)},i.prototype.fromRed=function(){return n(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},i.prototype._forceRed=function(e){return this.red=e,this},i.prototype.forceRed=function(e){return n(!this.red,"Already a number in reduction context"),this._forceRed(e)},i.prototype.redAdd=function(e){return n(this.red,"redAdd works only with red numbers"),this.red.add(this,e)},i.prototype.redIAdd=function(e){return n(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,e)},i.prototype.redSub=function(e){return n(this.red,"redSub works only with red numbers"),this.red.sub(this,e)},i.prototype.redISub=function(e){return n(this.red,"redISub works only with red numbers"),this.red.isub(this,e)},i.prototype.redShl=function(e){return n(this.red,"redShl works only with red numbers"),this.red.shl(this,e)},i.prototype.redMul=function(e){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.mul(this,e)},i.prototype.redIMul=function(e){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.imul(this,e)},i.prototype.redSqr=function(){return n(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},i.prototype.redISqr=function(){return n(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},i.prototype.redSqrt=function(){return n(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},i.prototype.redInvm=function(){return n(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},i.prototype.redNeg=function(){return n(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},i.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 i(t,16),this.n=this.p.bitLength(),this.k=new i(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 k(){v.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function S(e){if("string"==typeof e){var t=i._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){S.call(this,e),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new i(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 i(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),i=0;i<r;i++)t.words[i]=e.words[i];if(t.length=r,e.length<=9)return e.words[0]=0,void(e.length=1);var s=e.words[9];for(t.words[t.length++]=s&n,i=10;i<e.length;i++){var o=0|e.words[i];e.words[i-10]=(o&n)<<4|s>>>22,s=o}s>>>=22,e.words[i-10]=s,0===s&&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(k,v),k.prototype.imulK=function(e){for(var t=0,n=0;n<e.length;n++){var r=19*(0|e.words[n])+t,i=67108863&r;r>>>=26,e.words[n]=i,t=r}return 0!==t&&(e.words[e.length++]=t),e},i._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 k}return b[e]=t,t},S.prototype._verify1=function(e){n(0===e.negative,"red works only with positives"),n(e.red,"red works only with red numbers")},S.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")},S.prototype.imod=function(e){return this.prime?this.prime.ireduce(e)._forceRed(this):(l(e,e.umod(this.m)._forceRed(this)),e)},S.prototype.neg=function(e){return e.isZero()?e.clone():this.m.sub(e)._forceRed(this)},S.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)},S.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},S.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)},S.prototype.isub=function(e,t){this._verify2(e,t);var n=e.isub(t);return n.cmpn(0)<0&&n.iadd(this.m),n},S.prototype.shl=function(e,t){return this._verify1(e),this.imod(e.ushln(t))},S.prototype.imul=function(e,t){return this._verify2(e,t),this.imod(e.imul(t))},S.prototype.mul=function(e,t){return this._verify2(e,t),this.imod(e.mul(t))},S.prototype.isqr=function(e){return this.imul(e,e.clone())},S.prototype.sqr=function(e){return this.mul(e,e)},S.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 i(1)).iushrn(2);return this.pow(e,r)}for(var s=this.m.subn(1),o=0;!s.isZero()&&0===s.andln(1);)o++,s.iushrn(1);n(!s.isZero());var a=new i(1).toRed(this),c=a.redNeg(),l=this.m.subn(1).iushrn(1),u=this.m.bitLength();for(u=new i(2*u*u).toRed(this);0!==this.pow(u,l).cmp(c);)u.redIAdd(c);for(var d=this.pow(u,s),h=this.pow(e,s.addn(1).iushrn(1)),g=this.pow(e,s),f=o;0!==g.cmp(a);){for(var m=g,p=0;0!==m.cmp(a);p++)m=m.redSqr();n(p<f);var y=this.pow(d,new i(1).iushln(f-p-1));h=h.redMul(y),d=y.redSqr(),g=g.redMul(d),f=p}return h},S.prototype.invm=function(e){var t=e._invmp(this.m);return 0!==t.negative?(t.negative=0,this.imod(t).redNeg()):this.imod(t)},S.prototype.pow=function(e,t){if(t.isZero())return new i(1).toRed(this);if(0===t.cmpn(1))return e.clone();var n=new Array(16);n[0]=new i(1).toRed(this),n[1]=e;for(var r=2;r<n.length;r++)n[r]=this.mul(n[r-1],e);var s=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;s!==n[0]&&(s=this.sqr(s)),0!==d||0!==o?(o<<=1,o|=d,(4===++a||0===r&&0===u)&&(s=this.mul(s,n[o]),a=0,o=0)):a=0}c=26}return s},S.prototype.convertTo=function(e){var t=e.umod(this.m);return t===e?t.clone():t},S.prototype.convertFrom=function(e){var t=e.clone();return t.red=null,t},i.mont=function(e){return new T(e)},r(T,S),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),i=n.isub(r).iushrn(this.shift),s=i;return i.cmp(this.m)>=0?s=i.isub(this.m):i.cmpn(0)<0&&(s=i.iadd(this.m)),s._forceRed(this)},T.prototype.mul=function(e,t){if(e.isZero()||t.isZero())return new i(0)._forceRed(this);var n=e.mul(t),r=n.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),s=n.isub(r).iushrn(this.shift),o=s;return s.cmp(this.m)>=0?o=s.isub(this.m):s.cmpn(0)<0&&(o=s.iadd(this.m)),o._forceRed(this)},T.prototype.invm=function(e){return this.imod(e._invmp(this.m).mul(this.r2))._forceRed(this)}}(Hl,ql)),Hl.exports}var Vl,zl,Xl,Jl,Yl,Ql=sa(jl()),Zl={exports:{}};function eu(){return Vl||(Vl=1,function(e,t){var n=ma(),r=n.Buffer;function i(e,t){for(var n in e)t[n]=e[n]}function s(e,t,n){return r(e,t,n)}r.from&&r.alloc&&r.allocUnsafe&&r.allocUnsafeSlow?e.exports=n:(i(n,t),t.Buffer=s),s.prototype=Object.create(r.prototype),i(r,s),s.from=function(e,t,n){if("number"==typeof e)throw new TypeError("Argument must not be a number");return r(e,t,n)},s.alloc=function(e,t,n){if("number"!=typeof e)throw new TypeError("Argument must be a number");var i=r(e);return void 0!==t?"string"==typeof n?i.fill(t,n):i.fill(t):i.fill(0),i},s.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return r(e)},s.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return n.SlowBuffer(e)}}(Zl,Zl.exports)),Zl.exports}function tu(){if(Xl)return zl;Xl=1;var e=eu().Buffer;return zl=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 i=0;i<t.length;i++){var s=t.charAt(i),o=s.charCodeAt(0);if(255!==n[o])throw new TypeError(s+" is ambiguous");n[o]=i}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,i=0,s=0;t[r]===c;)i++,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<s)&&-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");s=g,r++}for(var m=o-s;m!==o&&0===u[m];)m++;var p=e.allocUnsafe(i+(o-m));p.fill(0,0,i);for(var y=i;m!==o;)p[y++]=u[m++];return p}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,i=0,s=0,o=n.length;s!==o&&0===n[s];)s++,r++;for(var l=(o-s)*u+1>>>0,d=new Uint8Array(l);s!==o;){for(var h=n[s],g=0,f=l-1;(0!==h||g<i)&&-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");i=g,s++}for(var m=l-i;m!==l&&0===d[m];)m++;for(var p=c.repeat(r);m<l;++m)p+=t.charAt(d[m]);return p},decodeUnsafe:d,decode:function(e){var t=d(e);if(t)return t;throw new Error("Non-base"+a+" character")}}},zl}function nu(){if(Yl)return Jl;Yl=1;return Jl=tu()("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")}var ru=sa(nu());const iu=bc;var su={};function ou(e,t,n){return t<=e&&e<=n}function au(e){if(void 0===e)return{};if(e===Object(e))return e;throw TypeError("Could not convert argument to dictionary")}function cu(e){this.tokens=[].slice.call(e)}cu.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 lu=-1;function uu(e,t){if(e)throw TypeError("Decoder error");return t||65533}var du="utf-8";function hu(e,t){if(!(this instanceof hu))return new hu(e,t);if((e=void 0!==e?String(e).toLowerCase():du)!==du)throw new Error("Encoding not supported. Only utf-8 is supported");t=au(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 gu(e,t){if(!(this instanceof gu))return new gu(e,t);if((e=void 0!==e?String(e).toLowerCase():du)!==du)throw new Error("Encoding not supported. Only utf-8 is supported");t=au(t),this._streaming=!1,this._encoder=null,this._options={fatal:Boolean(t.fatal)},Object.defineProperty(this,"encoding",{value:"utf-8"})}function fu(e){var t=e.fatal,n=0,r=0,i=0,s=128,o=191;this.handler=function(e,a){if(-1===a&&0!==i)return i=0,uu(t);if(-1===a)return lu;if(0===i){if(ou(a,0,127))return a;if(ou(a,194,223))i=1,n=a-192;else if(ou(a,224,239))224===a&&(s=160),237===a&&(o=159),i=2,n=a-224;else{if(!ou(a,240,244))return uu(t);240===a&&(s=144),244===a&&(o=143),i=3,n=a-240}return n<<=6*i,null}if(!ou(a,s,o))return n=i=r=0,s=128,o=191,e.prepend(a),uu(t);if(s=128,o=191,n+=a-128<<6*(i-(r+=1)),r!==i)return null;var c=n;return n=i=r=0,c}}function mu(e){e.fatal,this.handler=function(e,t){if(-1===t)return lu;if(ou(t,0,127))return t;var n,r;ou(t,128,2047)?(n=1,r=192):ou(t,2048,65535)?(n=2,r=224):ou(t,65536,1114111)&&(n=3,r=240);for(var i=[(t>>6*n)+r];n>0;){var s=t>>6*(n-1);i.push(128|63&s),n-=1}return i}}hu.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=au(t),this._streaming||(this._decoder=new fu({fatal:this._fatal}),this._BOMseen=!1),this._streaming=Boolean(t.stream);for(var r,i=new cu(n),s=[];!i.endOfStream()&&(r=this._decoder.handler(i,i.read()))!==lu;)null!==r&&(Array.isArray(r)?s.push.apply(s,r):s.push(r));if(!this._streaming){do{if((r=this._decoder.handler(i,i.read()))===lu)break;null!==r&&(Array.isArray(r)?s.push.apply(s,r):s.push(r))}while(!i.endOfStream());this._decoder=null}return s.length&&(-1===["utf-8"].indexOf(this.encoding)||this._ignoreBOM||this._BOMseen||(65279===s[0]?(this._BOMseen=!0,s.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}(s)}},gu.prototype={encode:function(e,t){e=e?String(e):"",t=au(t),this._streaming||(this._encoder=new mu(this._options)),this._streaming=Boolean(t.stream);for(var n,r=[],i=new cu(function(e){for(var t=String(e),n=t.length,r=0,i=[];r<n;){var s=t.charCodeAt(r);if(s<55296||s>57343)i.push(s);else if(56320<=s&&s<=57343)i.push(65533);else if(55296<=s&&s<=56319)if(r===n-1)i.push(65533);else{var o=e.charCodeAt(r+1);if(56320<=o&&o<=57343){var a=1023&s,c=1023&o;i.push(65536+(a<<10)+c),r+=1}else i.push(65533)}r+=1}return i}(e));!i.endOfStream()&&(n=this._encoder.handler(i,i.read()))!==lu;)Array.isArray(n)?r.push.apply(r,n):r.push(n);if(!this._streaming){for(;(n=this._encoder.handler(i,i.read()))!==lu;)Array.isArray(n)?r.push.apply(r,n):r.push(n);this._encoder=null}return new Uint8Array(r)}};var pu,yu=oa(Object.freeze({__proto__:null,TextDecoder:hu,TextEncoder:gu}));function bu(){if(pu)return su;pu=1;var e=su&&su.__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=su&&su.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=su&&su.__decorate||function(e,t,n,r){var i,s=arguments.length,o=s<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--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,n,o):i(t,n))||o);return s>3&&o&&Object.defineProperty(t,n,o),o},r=su&&su.__importStar||function(n){if(n&&n.__esModule)return n;var r={};if(null!=n)for(var i in n)"default"!==i&&Object.hasOwnProperty.call(n,i)&&e(r,n,i);return t(r,n),r},i=su&&su.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(su,"__esModule",{value:!0}),su.deserializeUnchecked=su.deserialize=su.serialize=su.BinaryReader=su.BinaryWriter=su.BorshError=su.baseDecode=su.baseEncode=void 0;const s=i(jl()),o=i(nu()),a=r(yu),c=new("function"!=typeof TextDecoder?a.TextDecoder:TextDecoder)("utf-8",{fatal:!0});su.baseEncode=function(e){return"string"==typeof e&&(e=Buffer.from(e,"utf8")),o.default.encode(Buffer.from(e))},su.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(".")}}su.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 s.default(e).toArray("le",8)))}writeU128(e){this.maybeResize(),this.writeBuffer(Buffer.from(new s.default(e).toArray("le",16)))}writeU256(e){this.maybeResize(),this.writeBuffer(Buffer.from(new s.default(e).toArray("le",32)))}writeU512(e){this.maybeResize(),this.writeBuffer(Buffer.from(new s.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}}}su.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 s.default(e,"le")}readU128(){const e=this.readBuffer(16);return new s.default(e,"le")}readU256(){const e=this.readBuffer(32);return new s.default(e,"le")}readU512(){const e=this.readBuffer(64);return new s.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 m(e,t,n,r,i){try{if("string"==typeof r)i[`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`);i.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++)m(e,null,n[t],r[0],i)}else i.writeArray(n,n=>{m(e,t,n,r[0],i)});else if(void 0!==r.kind)switch(r.kind){case"option":null==n?i.writeU8(0):(i.writeU8(1),m(e,t,n,r.type,i));break;case"map":i.writeU32(n.size),n.forEach((n,s)=>{m(e,t,s,r.key,i),m(e,t,n,r.value,i)});break;default:throw new u(`FieldType ${r} unrecognized`)}else p(e,n,i)}catch(e){throw e instanceof u&&e.addToFieldPath(t),e}}function p(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,i])=>{m(e,r,t[r],i,n)});else{if("enum"!==r.kind)throw new u(`Unexpected schema kind: ${r.kind} for ${t.constructor.name}`);{const i=t[r.field];for(let s=0;s<r.values.length;++s){const[o,a]=r.values[s];if(o===i){n.writeU8(s),m(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 i=0;i<n[1];i++)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 i=new Map;const s=r.readU32();for(let o=0;o<s;o++){const s=y(e,t,n.key,r),o=y(e,t,n.value,r);i.set(s,o)}return i}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[i,s]of e.get(t).fields)r[i]=y(e,i,s,n);return new t(r)}if("enum"===r.kind){const i=n.readU8();if(i>=r.values.length)throw new u(`Enum index: ${i} is out of range`);const[s,o]=r.values[i],a=y(e,s,o,n);return new t({[s]: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),su.BinaryReader=g,su.serialize=function(e,t,n=d){const r=new n;return p(e,t,r),r.toArray()},su.deserialize=function(e,t,n,r=g){const i=new r(n),s=b(e,t,i);if(i.offset<n.length)throw new u(`Unexpected ${n.length-i.offset} bytes after deserialized data`);return s},su.deserializeUnchecked=function(e,t,n,r=g){return b(e,t,new r(n))},su}var vu,wu=bu(),Eu={};function Au(){if(vu)return Eu;vu=1,Object.defineProperty(Eu,"__esModule",{value:!0}),Eu.s16=Eu.s8=Eu.nu64be=Eu.u48be=Eu.u40be=Eu.u32be=Eu.u24be=Eu.u16be=Eu.nu64=Eu.u48=Eu.u40=Eu.u32=Eu.u24=Eu.u16=Eu.u8=Eu.offset=Eu.greedy=Eu.Constant=Eu.UTF8=Eu.CString=Eu.Blob=Eu.Boolean=Eu.BitField=Eu.BitStructure=Eu.VariantLayout=Eu.Union=Eu.UnionLayoutDiscriminator=Eu.UnionDiscriminator=Eu.Structure=Eu.Sequence=Eu.DoubleBE=Eu.Double=Eu.FloatBE=Eu.Float=Eu.NearInt64BE=Eu.NearInt64=Eu.NearUInt64BE=Eu.NearUInt64=Eu.IntBE=Eu.Int=Eu.UIntBE=Eu.UInt=Eu.OffsetLayout=Eu.GreedyCount=Eu.ExternalLayout=Eu.bindConstructorLayout=Eu.nameWithProperty=Eu.Layout=Eu.uint8ArrayToBuffer=Eu.checkUint8Array=void 0,Eu.constant=Eu.utf8=Eu.cstr=Eu.blob=Eu.unionLayoutDiscriminator=Eu.union=Eu.seq=Eu.bits=Eu.struct=Eu.f64be=Eu.f64=Eu.f32be=Eu.f32=Eu.ns64be=Eu.s48be=Eu.s40be=Eu.s32be=Eu.s24be=Eu.s16be=Eu.ns64=Eu.s48=Eu.s40=Eu.s32=Eu.s24=void 0;const e=ma();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)}Eu.checkUint8Array=t,Eu.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 i(e,t){return t.property?e+"["+t.property+"]":e}Eu.Layout=r,Eu.nameWithProperty=i,Eu.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 s extends r{isCount(){throw new Error("ExternalLayout is abstract")}}Eu.ExternalLayout=s;class o extends s{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}}Eu.GreedyCount=o;class a extends s{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)}}Eu.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}}Eu.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}}Eu.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}}Eu.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}}Eu.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 m extends r{constructor(e){super(8,e)}decode(e,t=0){const r=n(e),i=r.readUInt32LE(t);return f(r.readUInt32LE(t+4),i)}encode(e,t,r=0){const i=g(e),s=n(t);return s.writeUInt32LE(i.lo32,r),s.writeUInt32LE(i.hi32,r+4),8}}Eu.NearUInt64=m;class p 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 i=g(e),s=n(t);return s.writeUInt32BE(i.hi32,r),s.writeUInt32BE(i.lo32,r+4),8}}Eu.NearUInt64BE=p;class y extends r{constructor(e){super(8,e)}decode(e,t=0){const r=n(e),i=r.readUInt32LE(t);return f(r.readInt32LE(t+4),i)}encode(e,t,r=0){const i=g(e),s=n(t);return s.writeUInt32LE(i.lo32,r),s.writeInt32LE(i.hi32,r+4),8}}Eu.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 i=g(e),s=n(t);return s.writeInt32BE(i.hi32,r),s.writeUInt32BE(i.lo32,r+4),8}}Eu.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}}Eu.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}}Eu.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}}Eu.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}}Eu.DoubleBE=A;class k extends r{constructor(e,t,n){if(!(e instanceof r))throw new TypeError("elementLayout must be a Layout");if(!(t instanceof s&&t.isCount()||Number.isInteger(t)&&0<=t))throw new TypeError("count must be non-negative integer or an unsigned integer ExternalLayout");let i=-1;!(t instanceof s)&&0<e.span&&(i=t*e.span),super(i,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 s&&(r=r.decode(e,t)),0<this.elementLayout.span)n=r*this.elementLayout.span;else{let i=0;for(;i<r;)n+=this.elementLayout.getSpan(e,t+n),++i}return n}decode(e,t=0){const n=[];let r=0,i=this.count;for(i instanceof s&&(i=i.decode(e,t));r<i;)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,i=e.reduce((e,i)=>e+r.encode(i,t,n+e),0);return this.count instanceof s&&this.count.encode(e.length,t,n),i}}Eu.Sequence=k;class S 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 i=-1;try{i=e.reduce((e,t)=>e+t.getSpan(),0)}catch(e){}super(i,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 i=r.getSpan(e,t);return t+=i,n+i},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 i=0,s=0;for(const r of this.fields){let o=r.span;if(s=0<o?o:0,void 0!==r.property){const i=e[r.property];void 0!==i&&(s=r.encode(i,t,n),0>o&&(o=r.getSpan(t,n)))}i=n,n+=o}return i+s-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)}}}Eu.Structure=S;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")}}Eu.UnionDiscriminator=T;class I extends T{constructor(e,t){if(!(e instanceof s&&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)}}Eu.UnionLayoutDiscriminator=I;class N extends r{constructor(e,t,n){let i;if(e instanceof c||e instanceof l)i=new I(new a(e));else if(e instanceof s&&e.isCount())i=new I(e);else{if(!(e instanceof T))throw new TypeError("discr must be a UnionDiscriminator or an unsigned integer layout");i=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+=i.layout.span)),super(o,n),this.discriminator=i,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,i=r.decode(e,t),s=this.registry[i];if(void 0===s){const s=this.defaultLayout;let o=0;this.usesPrefixDiscriminator&&(o=r.layout.span),n=this.makeDestinationObject(),n[r.property]=i,n[s.property]=s.decode(e,t+o)}else n=s.decode(e,t);return n}encode(e,t,n=0){const r=this.getSourceVariant(e);if(void 0===r){const r=this.discriminator,i=this.defaultLayout;let s=0;return this.usesPrefixDiscriminator&&(s=r.layout.span),r.encode(e[r.property],t,n),s+i.encode(e[i.property],t,n+s)}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]}}Eu.Union=N;class C extends r{constructor(e,t,n,i){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===i&&(i=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 i)throw new TypeError("variant must have a String property")}let s=e.span;0>e.span&&(s=n?n.span:0,0<=s&&e.usesPrefixDiscriminator&&(s+=e.discriminator.layout.span)),super(s,i),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 i=r;if(this.layout&&(this.layout.encode(e[this.property],t,n+r),i+=this.layout.getSpan(t,n+r),0<=this.union.span&&i>this.union.span))throw new Error("encoded variant overruns containing union");return i}fromArray(e){if(this.layout)return this.layout.fromArray(e)}}function _(e){return 0>e&&(e+=4294967296),e}Eu.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}}Eu.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,i=e.fields.reduce((e,t)=>e+t.bits,0);if(t+i>r)throw new Error("bits too long for span remainder ("+(r-i)+" of "+r+" remain)");this.container=e,this.bits=t,this.valueMask=(1<<t)-1,32===t&&(this.valueMask=4294967295),this.start=i,this.container.msb&&(this.start=r-i-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(i("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)}}Eu.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)}}Eu.Boolean=B;class D extends r{constructor(e,t){if(!(e instanceof s&&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 s||(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 s&&(o=e.length),!(e instanceof Uint8Array&&o===e.length))throw new TypeError(i("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 s&&this.length.encode(o,t,r),o}}Eu.Blob=D;class M 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,i=0){"string"!=typeof t&&(t=String(t));const s=e.Buffer.from(t,"utf8"),o=s.length;if(i+o>r.length)throw new RangeError("encoding overruns Buffer");const a=n(r);return s.copy(a,i),a[i+o]=0,o+1}}Eu.CString=M;class O 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,i=0){"string"!=typeof t&&(t=String(t));const s=e.Buffer.from(t,"utf8"),o=s.length;if(0<=this.maxSpan&&this.maxSpan<o)throw new RangeError("text length exceeds maxSpan");if(i+o>r.length)throw new RangeError("encoding overruns Buffer");return s.copy(n(r),i),o}}Eu.UTF8=O;class U extends r{constructor(e,t){super(0,t),this.value=e}decode(e,t){return this.value}encode(e,t,n){return 0}}return Eu.Constant=U,Eu.greedy=(e,t)=>new o(e,t),Eu.offset=(e,t,n)=>new a(e,t,n),Eu.u8=e=>new c(1,e),Eu.u16=e=>new c(2,e),Eu.u24=e=>new c(3,e),Eu.u32=e=>new c(4,e),Eu.u40=e=>new c(5,e),Eu.u48=e=>new c(6,e),Eu.nu64=e=>new m(e),Eu.u16be=e=>new l(2,e),Eu.u24be=e=>new l(3,e),Eu.u32be=e=>new l(4,e),Eu.u40be=e=>new l(5,e),Eu.u48be=e=>new l(6,e),Eu.nu64be=e=>new p(e),Eu.s8=e=>new u(1,e),Eu.s16=e=>new u(2,e),Eu.s24=e=>new u(3,e),Eu.s32=e=>new u(4,e),Eu.s40=e=>new u(5,e),Eu.s48=e=>new u(6,e),Eu.ns64=e=>new y(e),Eu.s16be=e=>new d(2,e),Eu.s24be=e=>new d(3,e),Eu.s32be=e=>new d(4,e),Eu.s40be=e=>new d(5,e),Eu.s48be=e=>new d(6,e),Eu.ns64be=e=>new b(e),Eu.f32=e=>new v(e),Eu.f32be=e=>new w(e),Eu.f64=e=>new E(e),Eu.f64be=e=>new A(e),Eu.struct=(e,t,n)=>new S(e,t,n),Eu.bits=(e,t,n)=>new x(e,t,n),Eu.seq=(e,t,n)=>new k(e,t,n),Eu.union=(e,t,n)=>new N(e,t,n),Eu.unionLayoutDiscriminator=(e,t)=>new I(e,t),Eu.blob=(e,t)=>new D(e,t),Eu.cstr=e=>new M(e),Eu.utf8=(e,t)=>new O(e,t),Eu.constant=(e,t)=>new U(e,t),Eu}var ku=Au(),Su=1,Tu=2,Iu=3,Nu=4,Cu=5,_u=6,xu=7,Ru=8,Bu=9,Du=10,Mu=-32700,Ou=-32603,Uu=-32602,Lu=-32601,Pu=-32600,Fu=-32019,$u=-32018,Ku=-32017,Gu=-32016,Hu=-32015,Wu=-32014,qu=-32013,ju=-32012,Vu=-32011,zu=-32010,Xu=-32009,Ju=-32008,Yu=-32007,Qu=-32006,Zu=-32005,ed=-32004,td=-32003,nd=-32002,rd=-32001,id=28e5,sd=2800001,od=2800002,ad=2800003,cd=2800004,ld=2800005,ud=2800006,dd=2800007,hd=2800008,gd=2800009,fd=2800010,md=2800011,pd=323e4,yd=32300001,bd=3230002,vd=3230003,wd=3230004,Ed=361e4,Ad=3610001,kd=3610002,Sd=3610003,Td=3610004,Id=3610005,Nd=3610006,Cd=3610007,_d=3611e3,xd=3704e3,Rd=3704001,Bd=3704002,Dd=3704003,Md=3704004,Od=4128e3,Ud=4128001,Ld=4128002,Pd=4615e3,Fd=4615001,$d=4615002,Kd=4615003,Gd=4615004,Hd=4615005,Wd=4615006,qd=4615007,jd=4615008,Vd=4615009,zd=4615010,Xd=4615011,Jd=4615012,Yd=4615013,Qd=4615014,Zd=4615015,eh=4615016,th=4615017,nh=4615018,rh=4615019,ih=4615020,sh=4615021,oh=4615022,ah=4615023,ch=4615024,lh=4615025,uh=4615026,dh=4615027,hh=4615028,gh=4615029,fh=4615030,mh=4615031,ph=4615032,yh=4615033,bh=4615034,vh=4615035,wh=4615036,Eh=4615037,Ah=4615038,kh=4615039,Sh=4615040,Th=4615041,Ih=4615042,Nh=4615043,Ch=4615044,_h=4615045,xh=4615046,Rh=4615047,Bh=4615048,Dh=4615049,Mh=4615050,Oh=4615051,Uh=4615052,Lh=4615053,Ph=4615054,Fh=5508e3,$h=5508001,Kh=5508002,Gh=5508003,Hh=5508004,Wh=5508005,qh=5508006,jh=5508007,Vh=5508008,zh=5508009,Xh=5508010,Jh=5508011,Yh=5607e3,Qh=5607001,Zh=5607002,eg=5607003,tg=5607004,ng=5607005,rg=5607006,ig=5607007,sg=5607008,og=5607009,ag=5607010,cg=5607011,lg=5607012,ug=5607013,dg=5607014,hg=5607015,gg=5607016,fg=5607017,mg=5663e3,pg=5663001,yg=5663002,bg=5663003,vg=5663004,wg=5663005,Eg=5663006,Ag=5663007,kg=5663008,Sg=5663009,Tg=5663010,Ig=5663011,Ng=5663012,Cg=5663013,_g=5663014,xg=5663015,Rg=5663016,Bg=5663017,Dg=5663018,Mg=5663019,Og=5663020,Ug=5663021,Lg=5663022,Pg=705e4,Fg=7050001,$g=7050002,Kg=7050003,Gg=7050004,Hg=7050005,Wg=7050006,qg=7050007,jg=7050008,Vg=7050009,zg=7050010,Xg=7050011,Jg=7050012,Yg=7050013,Qg=7050014,Zg=7050015,ef=7050016,tf=7050017,nf=7050018,rf=7050019,sf=7050020,of=7050021,af=7050022,cf=7050023,lf=7050024,uf=7050025,df=7050026,hf=7050027,gf=7050028,ff=7050029,mf=7050030,pf=7050031,yf=7050032,bf=7050033,vf=7050034,wf=7050035,Ef=7050036,Af=7618e3,kf=7618001,Sf=7618002,Tf=7618003,If=7618004,Nf=7618005,Cf=7618006,_f=7618007,xf=7618008,Rf=7618009,Bf=8078e3,Df=8078001,Mf=8078002,Of=8078003,Uf=8078004,Lf=8078005,Pf=8078006,Ff=8078007,$f=8078008,Kf=8078009,Gf=8078010,Hf=8078011,Wf=8078012,qf=8078013,jf=8078014,Vf=8078015,zf=8078016,Xf=8078017,Jf=8078018,Yf=8078019,Qf=8078020,Zf=8078021,em=8078022,tm=8078023,nm=81e5,rm=8100001,im=8100002,sm=8100003,om=819e4,am=8190001,cm=8190002,lm=8190003,um=8190004,dm=99e5,hm=9900001,gm=9900002,fm=9900003,mm=9900004,pm=9900005,ym=9900006;function bm(e){if(Array.isArray(e)){return"%5B"+e.map(bm).join("%2C%20")+"%5D"}return"bigint"==typeof e?`${e}n`:encodeURIComponent(String(null!=e&&null===Object.getPrototypeOf(e)?{...e}:e))}function vm([e,t]){return`${e}=${bm(t)}`}var wm={[pd]:"Account not found at address: $address",[wd]:"Not all accounts were decoded. Encoded accounts found at addresses: $addresses.",[vd]:"Expected decoded account at address: $address",[bd]:"Failed to decode account data at address: $address",[yd]:"Accounts not found at addresses: $addresses",[gd]:"Unable to find a viable program address bump seed.",[od]:"$putativeAddress is not a base58-encoded address.",[id]:"Expected base58 encoded address to decode to a byte array of length 32. Actual length: $actualLength.",[ad]:"The `CryptoKey` must be an `Ed25519` public key.",[md]:"$putativeOffCurveAddress is not a base58-encoded off-curve address.",[hd]:"Invalid seeds; point must fall off the Ed25519 curve.",[cd]:"Expected given program derived address to have the following format: [Address, ProgramDerivedAddressBump].",[ud]:"A maximum of $maxSeeds seeds, including the bump seed, may be supplied when creating an address. Received: $actual.",[dd]:"The seed at index $index with length $actual exceeds the maximum length of $maxSeedLength bytes.",[ld]:"Expected program derived address bump to be in the range [0, 255], got: $bump.",[fd]:"Program address cannot end with PDA marker.",[sd]:"Expected base58-encoded address string of length in the range [32, 44]. Actual length: $actualLength.",[Nu]:"Expected base58-encoded blockash string of length in the range [32, 44]. Actual length: $actualLength.",[Su]:"The network has progressed past the last block for which this transaction could have been committed.",[Bf]:"Codec [$codecDescription] cannot decode empty byte arrays.",[em]:"Enum codec cannot use lexical values [$stringValues] as discriminators. Either remove all lexical values or set `useValuesAsDiscriminators` to `false`.",[Qf]:"Sentinel [$hexSentinel] must not be present in encoded bytes [$hexEncodedBytes].",[Lf]:"Encoder and decoder must have the same fixed size, got [$encoderFixedSize] and [$decoderFixedSize].",[Pf]:"Encoder and decoder must have the same max size, got [$encoderMaxSize] and [$decoderMaxSize].",[Uf]:"Encoder and decoder must either both be fixed-size or variable-size.",[$f]:"Enum discriminator out of range. Expected a number in [$formattedValidDiscriminators], got $discriminator.",[Mf]:"Expected a fixed-size codec, got a variable-size one.",[qf]:"Codec [$codecDescription] expected a positive byte length, got $bytesLength.",[Of]:"Expected a variable-size codec, got a fixed-size one.",[Yf]:"Codec [$codecDescription] expected zero-value [$hexZeroValue] to have the same size as the provided fixed-size item [$expectedSize bytes].",[Df]:"Codec [$codecDescription] expected $expected bytes, got $bytesLength.",[Jf]:"Expected byte array constant [$hexConstant] to be present in data [$hexData] at offset [$offset].",[Kf]:"Invalid discriminated union variant. Expected one of [$variants], got $value.",[Gf]:"Invalid enum variant. Expected one of [$stringValues] or a number in [$formattedNumericalValues], got $variant.",[Vf]:"Invalid literal union variant. Expected one of [$variants], got $value.",[Ff]:"Expected [$codecDescription] to have $expected items, got $actual.",[Wf]:"Invalid value $value for base $base with alphabet $alphabet.",[zf]:"Literal union discriminator out of range. Expected a number between $minRange and $maxRange, got $discriminator.",[Hf]:"Codec [$codecDescription] expected number to be in the range [$min, $max], got $value.",[jf]:"Codec [$codecDescription] expected offset to be in the range [0, $bytesLength], got $offset.",[Zf]:"Expected sentinel [$hexSentinel] to be present in decoded bytes [$hexDecodedBytes].",[Xf]:"Union variant out of range. Expected an index between $minRange and $maxRange, got $variant.",[tm]:"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?",[_d]:"No random values implementation could be found.",[Vd]:"instruction requires an uninitialized account",[ah]:"instruction tries to borrow reference for an account which is already borrowed",[ch]:"instruction left account with an outstanding borrowed reference",[sh]:"program other than the account's owner changed the size of the account data",[Hd]:"account data too small for instruction",[oh]:"instruction expected an executable account",[xh]:"An account does not have enough lamports to be rent-exempt",[Bh]:"Program arithmetic overflowed",[_h]:"Failed to serialize or deserialize account data: $encodedData",[Ph]:"Builtin programs must consume compute units",[ph]:"Cross-program invocation call depth too deep",[Ah]:"Computational budget exceeded",[uh]:"custom program error: #$code",[th]:"instruction contains duplicate accounts",[lh]:"instruction modifications of multiply-passed account differ",[fh]:"executable accounts must be rent exempt",[hh]:"instruction changed executable accounts data",[gh]:"instruction changed the balance of an executable account",[nh]:"instruction changed executable bit of an account",[Qd]:"instruction modified data of an account it does not own",[Yd]:"instruction spent from the balance of an account it does not own",[Fd]:"generic instruction error",[Mh]:"Provided owner is not allowed",[Nh]:"Account is immutable",[Ch]:"Incorrect authority provided",[qd]:"incorrect program id for instruction",[Wd]:"insufficient funds for instruction",[Gd]:"invalid account data for instruction",[Rh]:"Invalid account owner",[$d]:"invalid program argument",[dh]:"program returned invalid error code",[Kd]:"invalid instruction data",[Eh]:"Failed to reallocate account data",[wh]:"Provided seeds do not result in a valid address",[Oh]:"Accounts data allocations exceeded the maximum allowed per transaction",[Uh]:"Max accounts exceeded",[Lh]:"Max instruction trace length exceeded",[vh]:"Length of the seed is too long for address generation",[yh]:"An account required by the instruction is missing",[jd]:"missing required signature for instruction",[Jd]:"instruction illegally modified the program id of an account",[ih]:"insufficient account keys for instruction",[kh]:"Cross-program invocation with unauthorized signer or writable account",[Sh]:"Failed to create program execution environment",[Ih]:"Program failed to compile",[Th]:"Program failed to complete",[eh]:"instruction modified data of a read-only account",[Zd]:"instruction changed the balance of a read-only account",[bh]:"Cross-program invocation reentrancy not allowed for this instruction",[rh]:"instruction modified rent epoch of an account",[Xd]:"sum of account balances before and after instruction do not match",[zd]:"instruction requires an initialized account",[Pd]:"",[mh]:"Unsupported program id",[Dh]:"Unsupported sysvar",[pm]:"Invalid instruction plan kind: $kind.",[Sf]:"The provided instruction plan is empty.",[Nf]:"No failed transaction plan result was found in the provided transaction plan result.",[If]:"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.",[Tf]:"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.",[Af]:"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).",[ym]:"Invalid transaction plan kind: $kind.",[kf]:"No more instructions to pack; the message packer has completed the instruction plan.",[Cf]:"Unexpected instruction plan. Expected $expectedKind plan, got $actualKind plan.",[_f]:"Unexpected transaction plan. Expected $expectedKind plan, got $actualKind plan.",[xf]:"Unexpected transaction plan result. Expected $expectedKind plan, got $actualKind plan.",[Rf]:"Expected a successful transaction plan result. I.e. there is at least one failed or cancelled transaction in the plan.",[Od]:"The instruction does not have any accounts.",[Ud]:"The instruction does not have any data.",[Ld]:"Expected instruction to have progress address $expectedProgramAddress, got $actualProgramAddress.",[Cu]:"Expected base58 encoded blockhash to decode to a byte array of length 32. Actual length: $actualLength.",[Tu]:"The nonce `$expectedNonceValue` is no longer valid. It has advanced to `$actualNonceValue`",[gm]:"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",[mm]:"Invariant violation: This data publisher does not publish to the channel named `$channelName`. Supported channels include $supportedChannelNames.",[hm]:"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",[dm]:"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",[fm]:"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",[Ou]:"JSON-RPC error: Internal JSON-RPC error ($__serverMessage)",[Uu]:"JSON-RPC error: Invalid method parameter(s) ($__serverMessage)",[Pu]:"JSON-RPC error: The JSON sent is not a valid `Request` object ($__serverMessage)",[Lu]:"JSON-RPC error: The method does not exist / is not available ($__serverMessage)",[Mu]:"JSON-RPC error: An error occurred on the server while parsing the JSON text ($__serverMessage)",[ju]:"$__serverMessage",[rd]:"$__serverMessage",[ed]:"$__serverMessage",[Wu]:"$__serverMessage",[Ku]:"Epoch rewards period still active at slot $slot",[zu]:"$__serverMessage",[Xu]:"$__serverMessage",[Fu]:"Failed to query long-term storage; please try again",[Gu]:"Minimum context slot has not been reached",[Zu]:"Node is unhealthy; behind by $numSlotsBehind slots",[Ju]:"No snapshot",[nd]:"Transaction simulation failed",[$u]:"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",[Yu]:"$__serverMessage",[Vu]:"Transaction history is not available from this node",[Qu]:"$__serverMessage",[qu]:"Transaction signature length mismatch",[td]:"Transaction signature verification failure",[Hu]:"$__serverMessage",[xd]:"Key pair bytes must be of length 64, got $byteLength.",[Rd]:"Expected private key bytes with length 32. Actual length: $actualLength.",[Bd]:"Expected base58-encoded signature to decode to a byte array of length 64. Actual length: $actualLength.",[Md]:"The provided private key does not match the provided public key.",[Dd]:"Expected base58-encoded signature string of length in the range [64, 88]. Actual length: $actualLength.",[_u]:"Lamports value must be in the range [0, 2e64-1]",[xu]:"`$value` cannot be parsed as a `BigInt`",[Du]:"$message",[Ru]:"`$value` cannot be parsed as a `Number`",[Iu]:"No nonce account could be found at address `$nonceAccountAddress`",[eg]:"Expected base58 encoded application domain to decode to a byte array of length 32. Actual length: $actualLength.",[ug]:"Attempted to sign an offchain message with an address that is not a signer for it",[Zh]:"Expected base58-encoded application domain string of length in the range [32, 44]. Actual length: $actualLength.",[lg]:"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]`.",[Yh]:"The message body provided has a byte-length of $actualBytes. The maximum allowable byte-length is $maxBytes",[ig]:"Expected message format $expectedMessageFormat, got $actualMessageFormat",[sg]:"The message length specified in the message preamble is $specifiedLength bytes. The actual length of the message is $actualLength bytes.",[og]:"Offchain message content must be non-empty",[ng]:"Offchain message must specify the address of at least one required signer",[ag]:"Offchain message envelope must reserve space for at least one signature",[tg]:"The offchain message preamble specifies $numRequiredSignatures required signature(s), got $signaturesLength.",[hg]:"The signatories of this offchain message must be listed in lexicographical order",[gg]:"An address must be listed no more than once among the signatories of an offchain message",[cg]:"Offchain message is missing signatures for addresses: $addresses.",[fg]:"Offchain message signature verification failed. Signature mismatch for required signatories [$signatoriesWithInvalidSignatures]. Missing signatures for signatories [$signatoriesWithMissingSignatures]",[Qh]:"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].",[dg]:"Expected offchain message version $expectedVersion. Got $actualVersion.",[rg]:"This version of Kit does not support decoding offchain messages with version $unsupportedVersion. The current max supported version is 0.",[om]:"The notification name must end in 'Notifications' and the API must supply a subscription plan creator function for the notification '$notificationName'.",[cm]:"WebSocket was closed before payload could be added to the send buffer",[lm]:"WebSocket connection closed",[um]:"WebSocket failed to connect",[am]:"Failed to obtain a subscription id from the server",[sm]:"Could not find an API plan for RPC method: `$method`",[nm]:"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`.",[im]:"HTTP error ($statusCode): $message",[rm]:"HTTP header(s) forbidden: $headers. Learn more at https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name.",[Fh]:"Multiple distinct signers were identified for address `$address`. Please ensure that you are using the same signer instance for each address.",[$h]:"The provided value does not implement the `KeyPairSigner` interface",[Gh]:"The provided value does not implement the `MessageModifyingSigner` interface",[Hh]:"The provided value does not implement the `MessagePartialSigner` interface",[Kh]:"The provided value does not implement any of the `MessageSigner` interfaces",[qh]:"The provided value does not implement the `TransactionModifyingSigner` interface",[jh]:"The provided value does not implement the `TransactionPartialSigner` interface",[Vh]:"The provided value does not implement the `TransactionSendingSigner` interface",[Wh]:"The provided value does not implement any of the `TransactionSigner` interfaces",[zh]:"More than one `TransactionSendingSigner` was identified.",[Xh]:"No `TransactionSendingSigner` was identified. Please provide a valid `TransactionWithSingleSendingSigner` transaction.",[Jh]:"Wallet account signers do not support signing multiple messages/transactions in a single operation",[Cd]:"Cannot export a non-extractable key.",[Ad]:"No digest implementation could be found.",[Ed]:"Cryptographic operations are only allowed in secure browser contexts. Read more here: https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts.",[kd]:"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.",[Sd]:"No signature verification implementation could be found.",[Td]:"No key generation implementation could be found.",[Id]:"No signing implementation could be found.",[Nd]:"No key export implementation could be found.",[Bu]:"Timestamp value must be in the range [-(2n ** 63n), (2n ** 63n) - 1]. `$value` given",[ef]:"Transaction processing left an account with an outstanding borrowed reference",[Fg]:"Account in use",[$g]:"Account loaded twice",[Kg]:"Attempt to debit an account but found no record of a prior credit.",[cf]:"Transaction loads an address table account that doesn't exist",[qg]:"This transaction has already been processed",[jg]:"Blockhash not found",[Vg]:"Loader call chain is too deep",[Zg]:"Transactions are currently disabled due to cluster maintenance",[mf]:"Transaction contains a duplicate instruction ($index) that is not allowed",[Hg]:"Insufficient funds for fee",[pf]:"Transaction results in an account ($accountIndex) with insufficient funds for rent",[Wg]:"This account may not be used to pay transaction fees",[Xg]:"Transaction contains an invalid account reference",[uf]:"Transaction loads an address table account with invalid data",[df]:"Transaction address table lookup uses an invalid index",[lf]:"Transaction loads an address table account with an invalid owner",[bf]:"LoadedAccountsDataSizeLimit set for transaction must be greater than 0.",[Yg]:"This program may not be used for executing instructions",[hf]:"Transaction leaves an account with a lower balance than rent-exempt minimum",[rf]:"Transaction loads a writable account that cannot be written",[yf]:"Transaction exceeded max loaded accounts data size cap",[zg]:"Transaction requires a fee but has no signature present",[Gg]:"Attempt to load a program that does not exist",[wf]:"Execution of the program referenced by account at index $accountIndex is temporarily restricted.",[vf]:"ResanitizationNeeded",[Qg]:"Transaction failed to sanitize accounts offsets correctly",[Jg]:"Transaction did not pass signature verification",[af]:"Transaction locked too many accounts",[Ef]:"Sum of account balances before and after transaction do not match",[Pg]:"The transaction failed with the error `$errorName`",[nf]:"Transaction version is unsupported",[of]:"Transaction would exceed account data limit within the block",[ff]:"Transaction would exceed total account data limit",[sf]:"Transaction would exceed max account limit within the block",[tf]:"Transaction would exceed max Block Cost Limit",[gf]:"Transaction would exceed max Vote Cost Limit",[xg]:"Attempted to sign a transaction with an address that is not a signer for it",[Tg]:"Transaction is missing an address at index: $index.",[Rg]:"Transaction has no expected signers therefore it cannot be encoded",[Og]:"Transaction size $transactionSize exceeds limit of $transactionSizeLimit bytes",[yg]:"Transaction does not have a blockhash lifetime",[bg]:"Transaction is not a durable nonce transaction",[wg]:"Contents of these address lookup tables unknown: $lookupTableAddresses",[Eg]:"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",[kg]:"No fee payer set in CompiledTransaction",[Ag]:"Could not find program address at index $index",[Dg]:"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",[Mg]:"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",[Ig]:"Transaction is missing a fee payer.",[Ng]:"Could not determine this transaction's signature. Make sure that the transaction has been signed by its fee payer.",[_g]:"Transaction first instruction is not advance nonce account instruction.",[Cg]:"Transaction with no instructions cannot be durable nonce transaction.",[mg]:"This transaction includes an address (`$programAddress`) which is both invoked and set as the fee payer. Program addresses may not pay fees",[pg]:"This transaction includes an address (`$programAddress`) which is both invoked and marked writable. Program addresses may not be writable",[Bg]:"The transaction message expected the transaction to have $numRequiredSignatures signatures, got $signaturesLength.",[Sg]:"Transaction is missing signatures for addresses: $addresses.",[vg]:"Transaction version must be in the range [0, 127]. `$actualVersion` given",[Ug]:"This version of Kit does not support decoding transactions with version $unsupportedVersion. The current max supported version is 0.",[Lg]:"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."},Em="i",Am="t";function km(e,t={}){if("production"!==process.env.NODE_ENV)return function(e,t={}){const n=wm[e];if(0===n.length)return"";let r;function i(e){if(2===r[Am]){const i=n.slice(r[Em]+1,e);s.push(i in t?`${t[i]}`:`$${i}`)}else 1===r[Am]&&s.push(n.slice(r[Em],e))}const s=[];return n.split("").forEach((e,t)=>{if(0===t)return void(r={[Em]:0,[Am]:"\\"===n[0]?0:"$"===n[0]?2:1});let s;switch(r[Am]){case 0:s={[Em]:t,[Am]:1};break;case 1:"\\"===e?s={[Em]:t,[Am]:0}:"$"===e&&(s={[Em]:t,[Am]:2});break;case 2:"\\"===e?s={[Em]:t,[Am]:0}:"$"===e?s={[Em]:t,[Am]:2}:e.match(/\w/)||(s={[Em]:t,[Am]:1})}s&&(r!==s&&i(t),r=s)}),i(),s.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(vm).join("&");return btoa(t)}(t)}'`),`${n}\``}}var Sm=class extends Error{cause=this.cause;context;constructor(...[e,t]){let n,r;t&&Object.entries(Object.getOwnPropertyDescriptors(t)).forEach(([t,i])=>{"cause"===t?r={cause:i.value}:(void 0===n&&(n={__code:e}),Object.defineProperty(n,t,i))});super(km(e,n),r),this.context=Object.freeze(void 0===n?{__code:e}:n),this.name="SolanaError"}};function Tm(e){return"fixedSize"in e&&"number"==typeof e.fixedSize}function Im(e){return 1!==e?.endian}function Nm(e){return t={fixedSize:e.size,write(t,n,r){e.range&&function(e,t,n,r){if(r<t||r>n)throw new Sm(Hf,{codecDescription:e,max:n,min:t,value:r})}(e.name,e.range[0],e.range[1],t);const i=new ArrayBuffer(e.size);return e.set(new DataView(i),t,Im(e.config)),n.set(new Uint8Array(i),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 Cm(e){return t={fixedSize:e.size,read(t,n=0){!function(e,t,n=0){if(t.length-n<=0)throw new Sm(Bf,{codecDescription:e})}(e.name,t,n),function(e,t,n,r=0){const i=n.length-r;if(i<t)throw new Sm(Df,{bytesLength:i,codecDescription:e,expected:t})}(e.name,e.size,t,n);const r=new DataView(function(e,t,n){const r=e.byteOffset+(t??0),i=n??e.byteLength;let s;return"undefined"==typeof SharedArrayBuffer?s=e.buffer:e.buffer instanceof SharedArrayBuffer?(s=new ArrayBuffer(e.length),new Uint8Array(s).set(new Uint8Array(e))):s=e.buffer,0!==r&&r!==-e.byteLength||i!==e.byteLength?s.slice(r,r+i):s}(t,n,e.size));return[e.get(r,Im(e.config)),n+e.size]}},Object.freeze({...t,decode:(e,n=0)=>t.read(e,n)[0]});var t}var _m=(e={})=>function(e,t){if(Tm(e)!==Tm(t))throw new Sm(Uf);if(Tm(e)&&Tm(t)&&e.fixedSize!==t.fixedSize)throw new Sm(Lf,{decoderFixedSize:t.fixedSize,encoderFixedSize:e.fixedSize});if(!Tm(e)&&!Tm(t)&&e.maxSize!==t.maxSize)throw new Sm(Pf,{decoderMaxSize:t.maxSize,encoderMaxSize:e.maxSize});return{...t,...e,decode:t.decode,encode:e.encode,read:t.read,write:e.write}}(((e={})=>Nm({config:e,name:"u64",range:[0n,BigInt("0xffffffffffffffff")],set:(e,t,n)=>e.setBigUint64(0,BigInt(t),n),size:8}))(e),((e={})=>Cm({config:e,get:(e,t)=>e.getBigUint64(0,t),name:"u64",size:8}))(e));class xm extends TypeError{constructor(e,t){let n;const{message:r,explanation:i,...s}=e,{path:o}=e,a=0===o.length?r:`At path: ${o.join(".")} -- ${r}`;super(i??a),null!=i&&(this.cause=a),Object.assign(this,s),this.name=this.constructor.name,this.failures=()=>n??(n=[e,...t()])}}function Rm(e){return"object"==typeof e&&null!=e}function Bm(e){return Rm(e)&&!Array.isArray(e)}function Dm(e){return"symbol"==typeof e?e.toString():"string"==typeof e?JSON.stringify(e):`${e}`}function Mm(e,t,n,r){if(!0===e)return;!1===e?e={}:"string"==typeof e&&(e={message:e});const{path:i,branch:s}=t,{type:o}=n,{refinement:a,message:c=`Expected a value of type \`${o}\`${a?` with refinement \`${a}\``:""}, but received: \`${Dm(r)}\``}=e;return{value:r,type:o,refinement:a,key:i[i.length-1],path:i,branch:s,...e,message:c}}function*Om(e,t,n,r){var i;Rm(i=e)&&"function"==typeof i[Symbol.iterator]||(e=[e]);for(const i of e){const e=Mm(i,t,n,r);e&&(yield e)}}function*Um(e,t,n={}){const{path:r=[],branch:i=[e],coerce:s=!1,mask:o=!1}=n,a={path:r,branch:i,mask:o};s&&(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=Um(u,d,{path:void 0===l?r:[...r,l],branch:void 0===l?i:[...i,u],coerce:s,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]):s&&(u=n[1],void 0===l?e=u:e instanceof Map?e.set(l,u):e instanceof Set?e.add(u):Rm(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 Lm=class{constructor(e){const{type:t,schema:n,validator:r,refiner:i,coercer:s=e=>e,entries:o=function*(){}}=e;this.type=t,this.schema=n,this.entries=o,this.coercer=s,this.validator=r?(e,t)=>Om(r(e,t),t,this,e):()=>[],this.refiner=i?(e,t)=>Om(i(e,t),t,this,e):()=>[]}assert(e,t){return function(e,t,n){const r=$m(e,t,{message:n});if(r[0])throw r[0]}(e,this,t)}create(e,t){return Pm(e,this,t)}is(e){return Fm(e,this)}mask(e,t){return function(e,t,n){const r=$m(e,t,{coerce:!0,mask:!0,message:n});if(r[0])throw r[0];return r[1]}(e,this,t)}validate(e,t={}){return $m(e,this,t)}};function Pm(e,t,n){const r=$m(e,t,{coerce:!0,message:n});if(r[0])throw r[0];return r[1]}function Fm(e,t){return!$m(e,t)[0]}function $m(e,t,n={}){const r=Um(e,t,n),i=function(e){const{done:t,value:n}=e.next();return t?void 0:n}(r);if(i[0]){return[new xm(i[0],function*(){for(const e of r)e[0]&&(yield e[0])}),void 0]}return[void 0,i[1]]}function Km(e,t){return new Lm({type:e,schema:null,validator:t})}function Gm(e){return new Lm({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: ${Dm(e)}`})}function Hm(){return Km("boolean",e=>"boolean"==typeof e)}function Wm(e){return Km("instance",t=>t instanceof e||`Expected a \`${e.name}\` instance, but received: ${Dm(t)}`)}function qm(e){const t=Dm(e),n=typeof e;return new Lm({type:"literal",schema:"string"===n||"number"===n||"boolean"===n?e:null,validator:n=>n===e||`Expected the literal \`${t}\`, but received: ${Dm(n)}`})}function jm(e){return new Lm({...e,validator:(t,n)=>null===t||e.validator(t,n),refiner:(t,n)=>null===t||e.refiner(t,n)})}function Vm(){return Km("number",e=>"number"==typeof e&&!isNaN(e)||`Expected a number, but received: ${Dm(e)}`)}function zm(e){return new Lm({...e,validator:(t,n)=>void 0===t||e.validator(t,n),refiner:(t,n)=>void 0===t||e.refiner(t,n)})}function Xm(e,t){return new Lm({type:"record",schema:null,*entries(n){if(Rm(n))for(const r in n){const i=n[r];yield[r,r,e],yield[r,i,t]}},validator:e=>Bm(e)||`Expected an object, but received: ${Dm(e)}`,coercer:e=>Bm(e)?{...e}:e})}function Jm(){return Km("string",e=>"string"==typeof e||`Expected a string, but received: ${Dm(e)}`)}function Ym(e){const t=Km("never",()=>!1);return new Lm({type:"tuple",schema:null,*entries(n){if(Array.isArray(n)){const r=Math.max(e.length,n.length);for(let i=0;i<r;i++)yield[i,n[i],e[i]||t]}},validator:e=>Array.isArray(e)||`Expected an array, but received: ${Dm(e)}`,coercer:e=>Array.isArray(e)?e.slice():e})}function Qm(e){const t=Object.keys(e);return new Lm({type:"type",schema:e,*entries(n){if(Rm(n))for(const r of t)yield[r,n[r],e[r]]},validator:e=>Bm(e)||`Expected an object, but received: ${Dm(e)}`,coercer:e=>Bm(e)?{...e}:e})}function Zm(e){const t=e.map(e=>e.type).join(" | ");return new Lm({type:"union",schema:null,coercer(t,n){for(const r of e){const[e,i]=r.validate(t,{coerce:!0,mask:n.mask});if(!e)return i}return t},validator(n,r){const i=[];for(const t of e){const[...e]=Um(n,t,r),[s]=e;if(!s[0])return[];for(const[t]of e)t&&i.push(t)}return[`Expected the value to satisfy a union of \`${t}\`, but received: ${Dm(n)}`,...i]}})}function ep(){return Km("unknown",()=>!0)}function tp(e,t,n){return new Lm({...e,coercer:(r,i)=>Fm(r,t)?e.coercer(n(r,i),i):e.coercer(r,i)})}var np,rp,ip,sp,op=oa(y);function ap(){if(rp)return np;rp=1;const e=op.v4;return np=function(t,n,r,i){if("string"!=typeof t)throw new TypeError(t+" must be a string");const s="number"==typeof(i=i||{}).version?i.version:2;if(1!==s&&2!==s)throw new TypeError(s+" must be 1 or 2");const o={method:t};if(2===s&&(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 i.generator?i.generator:function(){return e()};o.id=t(o,i)}else 2===s&&null===r?i.notificationIdNull&&(o.id=null):o.id=r;return o}}function cp(){if(sp)return ip;sp=1;const e=op.v4,t=ap(),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 ip=n,n.prototype.request=function(e,n,r,i){const s=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)i=n,o=e;else{"function"==typeof r&&(i=r,r=void 0);const s="function"==typeof i;try{o=t(e,n,r,{generator:this.options.generator,version:this.options.version,notificationIdNull:this.options.notificationIdNull})}catch(e){if(s)return void i(e);throw e}if(!s)return o}let c;try{c=JSON.stringify(o,this.options.replacer)}catch(e){return void i(e)}return this.callServer(c,function(e,t){s._parseResponse(e,t,i)}),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)}},ip}var lp,up=sa(cp()),dp={exports:{}};function hp(){return lp||(lp=1,function(e){var t=Object.prototype.hasOwnProperty,n="~";function r(){}function i(e,t,n){this.fn=e,this.context=t,this.once=n||!1}function s(e,t,r,s,o){if("function"!=typeof r)throw new TypeError("The listener must be a function");var a=new i(r,s||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,i=[];if(0===this._eventsCount)return i;for(r in e=this._events)t.call(e,r)&&i.push(n?r.slice(1):r);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(e)):i},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 i=0,s=r.length,o=new Array(s);i<s;i++)o[i]=r[i].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,i,s,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,i),!0;case 5:return u.fn.call(u.context,t,r,i,s),!0;case 6:return u.fn.call(u.context,t,r,i,s,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,i);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 s(this,e,t,n,!1)},a.prototype.once=function(e,t,n){return s(this,e,t,n,!0)},a.prototype.removeListener=function(e,t,r,i){var s=n?n+e:e;if(!this._events[s])return this;if(!t)return o(this,s),this;var a=this._events[s];if(a.fn)a.fn!==t||i&&!a.once||r&&a.context!==r||o(this,s);else{for(var c=0,l=[],u=a.length;c<u;c++)(a[c].fn!==t||i&&!a[c].once||r&&a[c].context!==r)&&l.push(a[c]);l.length?this._events[s]=1===l.length?l[0]:l:o(this,s)}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}(dp)),dp.exports}var gp=sa(hp()),fp=class extends gp{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 mp=class{encode(e){return JSON.stringify(e)}decode(e){return JSON.parse(e)}},pp=class extends gp{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:i=1e3,max_reconnects:s=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=i,this.max_reconnects=s,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 mp,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((i,s)=>{if(!this.ready)return s(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 s(e);this.queue[o]={promise:[i,s]},n&&(this.queue[o].timeout=setTimeout(()=>{delete this.queue[o],s(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 i={jsonrpc:"2.0",method:e,params:t};this.socket.send(this.dataPack.encode(i),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=pa.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 yp extends Fa{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,Ea(e);const n=La(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,i=new Uint8Array(r);i.set(n.length>r?e.create().update(n).digest():n);for(let e=0;e<i.length;e++)i[e]^=54;this.iHash.update(i),this.oHash=e.create();for(let e=0;e<i.length;e++)i[e]^=106;this.oHash.update(i),ka(i)}update(e){return Aa(this),this.iHash.update(e),this}digestInto(e){Aa(this),wa(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:i,blockLen:s,outputLen:o}=this;return e.finished=r,e.destroyed=i,e.blockLen=s,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 bp=(e,t,n)=>new yp(e,t).update(n).digest();bp.create=(e,t)=>new yp(e,t);const vp=(e,t)=>(e+(e>=0?t:-t)/Ip)/t;function wp(e){if(!["compact","recovered","der"].includes(e))throw new Error('Signature format must be "compact", "recovered", or "der"');return e}function Ep(e,t){const n={};for(let r of Object.keys(t))n[r]=void 0===e[r]?t[r]:e[r];return Ac(n.lowS,"lowS"),Ac(n.prehash,"prehash"),void 0!==n.format&&wp(n.format),n}class Ap extends Error{constructor(e=""){super(e)}}const kp={Err:Ap,_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,i=Sc(r);if(i.length/2&128)throw new n("tlv.encode: long form length too big");const s=r>127?Sc(i.length/2|128):"";return Sc(e)+s+i+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 i=t[r++];let s=0;if(!!(128&i)){const e=127&i;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)s=s<<8|e;if(r+=e,s<128)throw new n("tlv.decode(long): not minimal encoding")}else s=i;const o=t.subarray(r,r+s);if(o.length!==s)throw new n("tlv.decode: wrong value length");return{v:o,l:t.subarray(r+s)}}},_int:{encode(e){const{Err:t}=kp;if(e<Sp)throw new t("integer: negative integers are not allowed");let n=Sc(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 Ic(e)}},toSig(e){const{Err:t,_int:n,_tlv:r}=kp,i=xc("signature",e),{v:s,l:o}=r.decode(48,i);if(o.length)throw new t("invalid signature: left bytes after parsing");const{v:a,l:c}=r.decode(2,s),{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)}},Sp=BigInt(0),Tp=BigInt(1),Ip=BigInt(2),Np=BigInt(3),Cp=BigInt(4);function _p(e,t){const{BYTES:n}=e;let r;if("bigint"==typeof t)r=t;else{let i=xc("private key",t);try{r=e.fromBytes(i)}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 xp(e,t={}){const n=kl("weierstrass",e,t),{Fp:r,Fn:i}=n;let s=n.CURVE;const{h:o,n:a}=s;Uc(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:c}=t;if(c&&(!r.is0(s.a)||"bigint"!=typeof c.beta||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const l=Bp(r,i);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:i,y:s}=t.toAffine(),o=r.toBytes(i);if(Ac(n,"isCompressed"),n){u();return Pa(Rp(!r.isOdd(s)),o)}return Pa(Uint8Array.of(4),o,r.toBytes(s))},h=t.fromBytes||function(e){kc(e,void 0,"Point");const{publicKey:t,publicKeyUncompressed:n}=l,i=e.length,s=e[0],o=e.subarray(1);if(i!==t||2!==s&&3!==s){if(i===n&&4===s){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 ${i}, 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&~s)!==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,s.a)),s.b)}function f(e,t){const n=r.sqr(t),i=g(e);return r.eql(n,i)}if(!f(s.Gx,s.Gy))throw new Error("bad curve params: generator point");const m=r.mul(r.pow(s.a,Np),Cp),p=r.mul(r.sqr(s.b),BigInt(27));if(r.is0(r.add(m,p)))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 k))throw new Error("ProjectivePoint expected")}function v(e){if(!c||!c.basises)throw new Error("no endo");return function(e,t,n){const[[r,i],[s,o]]=t,a=vp(o*e,n),c=vp(-i*e,n);let l=e-a*r-c*s,u=-a*i-c*o;const d=l<Sp,h=u<Sp;d&&(l=-l),h&&(u=-u);const g=Oc(Math.ceil(Mc(n)/2))+Tp;if(l<Sp||l>=g||u<Sp||u>=g)throw new Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:d,k1:l,k2neg:h,k2:u}}(e,c.basises,i.ORDER)}const w=Lc((e,t)=>{const{X:n,Y:i,Z:s}=e;if(r.eql(s,r.ONE))return{x:n,y:i};const o=e.is0();null==t&&(t=o?r.ONE:r.inv(s));const a=r.mul(n,t),c=r.mul(i,t),l=r.mul(s,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=Lc(e=>{if(e.is0()){if(t.allowInfinityPoint&&!r.is0(e.Y))return;throw new Error("bad point: ZERO")}const{x:n,y:i}=e.toAffine();if(!r.isValid(n)||!r.isValid(i))throw new Error("bad point: x or y not field elements");if(!f(n,i))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,i,s){return n=new k(r.mul(n.X,e),n.Y,n.Z),t=dl(i,t),n=dl(s,n),t.add(n)}class k{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 s}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 k)throw new Error("projective point not allowed");return r.is0(t)&&r.is0(n)?k.ZERO:new k(t,n,r.ONE)}static fromBytes(e){const t=k.fromAffine(h(kc(e,void 0,"point")));return t.assertValidity(),t}static fromHex(e){return k.fromBytes(xc("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(Np),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:i}=this,{X:s,Y:o,Z:a}=e,c=r.eql(r.mul(t,a),r.mul(s,i)),l=r.eql(r.mul(n,a),r.mul(o,i));return c&&l}negate(){return new k(this.X,r.neg(this.Y),this.Z)}double(){const{a:e,b:t}=s,n=r.mul(t,Np),{X:i,Y:o,Z:a}=this;let c=r.ZERO,l=r.ZERO,u=r.ZERO,d=r.mul(i,i),h=r.mul(o,o),g=r.mul(a,a),f=r.mul(i,o);return f=r.add(f,f),u=r.mul(i,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 k(c,l,u)}add(e){b(e);const{X:t,Y:n,Z:i}=this,{X:o,Y:a,Z:c}=e;let l=r.ZERO,u=r.ZERO,d=r.ZERO;const h=s.a,g=r.mul(s.b,Np);let f=r.mul(t,o),m=r.mul(n,a),p=r.mul(i,c),y=r.add(t,n),v=r.add(o,a);y=r.mul(y,v),v=r.add(f,m),y=r.sub(y,v),v=r.add(t,i);let w=r.add(o,c);return v=r.mul(v,w),w=r.add(f,p),v=r.sub(v,w),w=r.add(n,i),l=r.add(a,c),w=r.mul(w,l),l=r.add(m,p),w=r.sub(w,l),d=r.mul(h,v),l=r.mul(g,p),d=r.add(l,d),l=r.sub(m,d),d=r.add(m,d),u=r.mul(l,d),m=r.add(f,f),m=r.add(m,f),p=r.mul(h,p),v=r.mul(g,v),m=r.add(m,p),p=r.sub(f,p),p=r.mul(h,p),v=r.add(v,p),f=r.mul(m,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,m),d=r.mul(w,d),d=r.add(d,f),new k(l,u,d)}subtract(e){return this.add(e.negate())}is0(){return this.equals(k.ZERO)}multiply(e){const{endo:n}=t;if(!i.isValidNot0(e))throw new Error("invalid scalar: out of range");let r,s;const o=e=>T.cached(this,e,e=>hl(k,e));if(n){const{k1neg:t,k1:i,k2neg:a,k2:c}=v(e),{p:l,f:u}=o(i),{p:d,f:h}=o(c);s=u.add(h),r=A(n.beta,l,d,t,a)}else{const{p:t,f:n}=o(e);r=t,s=n}return hl(k,[r,s])[0]}multiplyUnsafe(e){const{endo:n}=t,r=this;if(!i.isValid(e))throw new Error("invalid scalar: out of range");if(e===Sp||r.is0())return k.ZERO;if(e===Tp)return r;if(T.hasCache(this))return this.multiply(e);if(n){const{k1neg:t,k1:i,k2neg:s,k2:o}=v(e),{p1:a,p2:c}=function(e,t,n,r){let i=t,s=e.ZERO,o=e.ZERO;for(;n>ll||r>ll;)n&ul&&(s=s.add(i)),r&ul&&(o=o.add(i)),i=i.double(),n>>=ul,r>>=ul;return{p1:s,p2:o}}(k,r,i,o);return A(n.beta,a,c,t,s)}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===Tp||(e?e(k,this):T.unsafe(this,a).is0())}clearCofactor(){const{clearCofactor:e}=t;return o===Tp?this:e?e(k,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(e=!0){return Ac(e,"isCompressed"),this.assertValidity(),d(k,this,e)}toHex(e=!0){return Ca(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 hl(k,e)}static msm(e,t){return El(k,i,e,t)}static fromPrivateKey(e){return k.BASE.multiply(_p(i,e))}}k.BASE=new k(s.Gx,s.Gy,r.ONE),k.ZERO=new k(r.ZERO,r.ONE,r.ZERO),k.Fp=r,k.Fn=i;const S=i.BITS,T=new wl(k,t.endo?Math.ceil(S/2):S);return k.BASE.precompute(8),k}function Rp(e){return Uint8Array.of(e?2:3)}function Bp(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function Dp(e,t={}){const{Fn:n}=e,r=t.randomBytes||Ka,i=Object.assign(Bp(e.Fp,n),{seed:cl(n.ORDER)});function s(e){try{return!!_p(n,e)}catch(e){return!1}}function o(e=r(i.seed)){return function(e,t,n=!1){const r=e.length,i=al(t),s=cl(t);if(r<16||r<s||r>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+r);const o=zc(n?Nc(e):Ic(e),t-Fc)+Fc;return n?_c(o,i):Cc(o,i)}(kc(e,i.seed,"seed"),n.ORDER)}function a(t,r=!0){return e.BASE.multiply(_p(n,t)).toBytes(r)}function c(t){if("bigint"==typeof t)return!1;if(t instanceof e)return!0;const{secretKey:r,publicKey:s,publicKeyUncompressed:o}=i;if(n.allowedLengths||r===s)return;const a=xc("key",t).length;return a===s||a===o}const l={isValidSecretKey:s,isValidPublicKey:function(t,n){const{publicKey:r,publicKeyUncompressed:s}=i;try{const i=t.length;return(!0!==n||i===r)&&((!1!==n||i===s)&&!!e.fromBytes(t))}catch(e){return!1}},randomSecretKey:o,isValidPrivateKey:s,randomPrivateKey:o,normPrivateKeyToScalar:e=>_p(n,e),precompute:(t=8,n=e.BASE)=>n.precompute(t,!1)};return Object.freeze({getPublicKey:a,getSharedSecret:function(t,r,i=!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 s=_p(n,t);return e.fromHex(r).multiply(s).toBytes(i)},keygen:function(e){const t=o(e);return{secretKey:t,publicKey:a(t)}},Point:e,utils:l,lengths:i})}function Mp(e,t,n={}){Ea(t),Uc(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const r=n.randomBytes||Ka,i=n.hmac||((e,...n)=>bp(t,e,Pa(...n))),{Fp:s,Fn:o}=e,{ORDER:a,BITS:c}=o,{keygen:l,getPublicKey:u,getSharedSecret:d,utils:h,lengths:g}=Dp(e,n),f={prehash:!1,lowS:"boolean"==typeof n.lowS&&n.lowS,format:void 0,extraEntropy:!1},m="compact";function p(e){return e>a>>Tp}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=m){let n;if(function(e,t){wp(t);const n=g.signature;kc(e,"compact"===t?n:"recovered"===t?n+1:void 0,`${t} signature`)}(e,t),"der"===t){const{r:t,s:n}=kp.toSig(kc(e));return new b(t,n)}"recovered"===t&&(n=e[0],t="compact",e=e.subarray(1));const r=o.BYTES,i=e.subarray(0,r),s=e.subarray(r,2*r);return new b(o.fromBytes(i),o.fromBytes(s),n)}static fromHex(e,t){return this.fromBytes(Ua(e),t)}addRecoveryBit(e){return new b(this.r,this.s,e)}recoverPublicKey(t){const n=s.ORDER,{r:r,s:i,recovery:c}=this;if(null==c||![0,1,2,3].includes(c))throw new Error("recovery id invalid");if(a*Ip<n&&c>1)throw new Error("recovery id is ambiguous for h>1 curve");const l=2===c||3===c?r+a:r;if(!s.isValid(l))throw new Error("recovery id 2 or 3 invalid");const u=s.toBytes(l),d=e.fromBytes(Pa(Rp(!(1&c)),u)),h=o.inv(l),g=w(xc("msgHash",t)),f=o.create(-g*h),m=o.create(i*h),p=e.BASE.multiplyUnsafe(f).add(d.multiplyUnsafe(m));if(p.is0())throw new Error("point at infinify");return p.assertValidity(),p}hasHighS(){return p(this.s)}toBytes(e=m){if(wp(e),"der"===e)return Ua(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 Pa(Uint8Array.of(this.recovery),t,n)}return Pa(t,n)}toHex(e){return Ca(this.toBytes(e))}assertValidity(){}static fromCompact(e){return b.fromBytes(xc("sig",e),"compact")}static fromDER(e){return b.fromBytes(xc("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 Ca(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return Ca(this.toBytes("compact"))}}const v=n.bits2int||function(e){if(e.length>8192)throw new Error("input is too large");const t=Ic(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=Oc(c);function A(e){return Dc("num < 2^"+c,e,Sp,E),o.toBytes(e)}function k(e,n){return kc(e,void 0,"message"),n?kc(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,s,a={}){n=xc("message",n);const{seed:c,k2sig:l}=function(t,n,i){if(["recovered","canonical"].some(e=>e in i))throw new Error("sign() legacy options not supported");const{lowS:s,prehash:a,extraEntropy:c}=Ep(i,f);t=k(t,a);const l=w(t),u=_p(o,n),d=[A(u),A(l)];if(null!=c&&!1!==c){const e=!0===c?r(g.secretKey):c;d.push(xc("extraEntropy",e))}const h=Pa(...d),m=l;return{seed:h,k2sig:function(t){const n=v(t);if(!o.isValidNot0(n))return;const r=o.inv(n),i=e.BASE.multiply(n).toAffine(),a=o.create(i.x);if(a===Sp)return;const c=o.create(r*o.create(m+a*u));if(c===Sp)return;let l=(i.x===a?0:2)|Number(i.y&Tp),d=c;return s&&p(c)&&(d=o.neg(c),l^=1),new b(a,d,l)}}}(n,s,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),i=e=>Uint8Array.of(e);let s=r(e),o=r(e),a=0;const c=()=>{s.fill(1),o.fill(0),a=0},l=(...e)=>n(o,s,...e),u=(e=r(0))=>{o=l(i(0),e),s=l(),0!==e.length&&(o=l(i(1),e),s=l())},d=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let e=0;const n=[];for(;e<t;){s=l();const t=s.slice();n.push(t),e+=s.length}return Pa(...n)};return(e,t)=>{let n;for(c(),u(e);!(n=t(d()));)u();return c(),n}}(t.outputLen,o.BYTES,i)(c,l)},verify:function(t,n,r,i={}){const{lowS:s,prehash:a,format:c}=Ep(i,f);if(r=xc("publicKey",r),n=k(xc("message",n),a),"strict"in i)throw new Error("options.strict was renamed to lowS");const l=void 0===c?function(e){let t;const n="string"==typeof e||ba(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(xc("sig",e),"der")}catch(e){if(!(e instanceof kp.Err))throw e}if(!t)try{t=b.fromBytes(xc("sig",e),"compact")}catch(e){return!1}}return t||!1}(t):b.fromBytes(xc("sig",t),c);if(!1===l)return!1;try{const t=e.fromBytes(r);if(s&&l.hasHighS())return!1;const{r:i,s:a}=l,c=w(n),u=o.inv(a),d=o.create(c*u),h=o.create(i*u),g=e.BASE.multiplyUnsafe(d).add(t.multiplyUnsafe(h));if(g.is0())return!1;return o.create(g.x)===i}catch(e){return!1}},recoverPublicKey:function(e,t,n={}){const{prehash:r}=Ep(n,f);return t=k(t,r),b.fromBytes(e,"recovered").recoverPublicKey(t).toBytes()},Signature:b,hash:t})}function Op(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:ol(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 Up(e){const{CURVE:t,curveOpts:n,hash:r,ecdsaOpts:i}=Op(e);return function(e,t){const n=t.Point;return Object.assign({},t,{ProjectivePoint:n,CURVE:Object.assign({},e,sl(n.Fn.ORDER,n.Fn.BITS))})}(e,Mp(xp(t,n),r,i))}const Lp={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Pp={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},Fp=BigInt(2);const $p=ol(Lp.p,{sqrt:function(e){const t=Lp.p,n=BigInt(3),r=BigInt(6),i=BigInt(11),s=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),l=e*e*e%t,u=l*l*e%t,d=Xc(u,n,t)*u%t,h=Xc(d,n,t)*u%t,g=Xc(h,Fp,t)*l%t,f=Xc(g,i,t)*g%t,m=Xc(f,s,t)*f%t,p=Xc(m,a,t)*m%t,y=Xc(p,c,t)*p%t,b=Xc(y,a,t)*m%t,v=Xc(b,n,t)*u%t,w=Xc(v,o,t)*f%t,E=Xc(w,r,t)*l%t,A=Xc(E,Fp,t);if(!$p.eql($p.sqr(A),e))throw new Error("Cannot find square root");return A}}),Kp=function(e,t){const n=t=>Up({...e,hash:t});return{...n(t),create:n}}({...Lp,Fp:$p,lowS:!0,endo:Pp},bc);Kl.utils.randomPrivateKey;const Gp=()=>{const e=Kl.utils.randomPrivateKey(),t=Hp(e),n=new Uint8Array(64);return n.set(e),n.set(t,32),{publicKey:t,secretKey:n}},Hp=Kl.getPublicKey;function Wp(e){try{return Kl.ExtendedPoint.fromHex(e),!0}catch{return!1}}const qp=Kl.verify,jp=e=>pa.Buffer.isBuffer(e)?e:e instanceof Uint8Array?pa.Buffer.from(e.buffer,e.byteOffset,e.byteLength):pa.Buffer.from(e);class Vp{constructor(e){Object.assign(this,e)}encode(){return pa.Buffer.from(wu.serialize(zp,this))}static decode(e){return wu.deserialize(zp,this,e)}static decodeUnchecked(e){return wu.deserializeUnchecked(zp,this,e)}}const zp=new Map;var Xp;const Jp=32;let Yp=1;class Qp extends Vp{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=ru.decode(e);if(t.length!=Jp)throw new Error("Invalid public key input");this._bn=new Ql(t)}else this._bn=new Ql(e);if(this._bn.byteLength()>Jp)throw new Error("Invalid public key input")}}static unique(){const e=new Qp(Yp);return Yp+=1,new Qp(e.toBuffer())}equals(e){return this._bn.eq(e._bn)}toBase58(){return ru.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(pa.Buffer);if(e.length===Jp)return e;const t=pa.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=pa.Buffer.concat([e.toBuffer(),pa.Buffer.from(t),n.toBuffer()]),i=iu(r);return new Qp(i)}static createProgramAddressSync(e,t){let n=pa.Buffer.alloc(0);e.forEach(function(e){if(e.length>32)throw new TypeError("Max seed length exceeded");n=pa.Buffer.concat([n,jp(e)])}),n=pa.Buffer.concat([n,t.toBuffer(),pa.Buffer.from("ProgramDerivedAddress")]);const r=iu(n);if(Wp(r))throw new Error("Invalid seeds, address must fall off the curve");return new Qp(r)}static async createProgramAddress(e,t){return this.createProgramAddressSync(e,t)}static findProgramAddressSync(e,t){let n,r=255;for(;0!=r;){try{const i=e.concat(pa.Buffer.from([r]));n=this.createProgramAddressSync(i,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 Wp(new Qp(e).toBytes())}}Xp=Qp,Qp.default=new Xp("11111111111111111111111111111111"),zp.set(Qp,{kind:"struct",fields:[["_bn","u256"]]}),new Qp("BPFLoader1111111111111111111111111111111111");const Zp=1232;class ey extends Error{constructor(e){super(`Signature ${e} has expired: block height exceeded.`),this.signature=void 0,this.signature=e}}Object.defineProperty(ey.prototype,"name",{value:"TransactionExpiredBlockheightExceededError"});class ty 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(ty.prototype,"name",{value:"TransactionExpiredTimeoutError"});class ny extends Error{constructor(e){super(`Signature ${e} has expired: the nonce is no longer valid.`),this.signature=void 0,this.signature=e}}Object.defineProperty(ny.prototype,"name",{value:"TransactionExpiredNonceInvalidError"});class ry{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 iy=(e="publicKey")=>ku.blob(32,e),sy=(e="string")=>{const t=ku.struct([ku.u32("length"),ku.u32("lengthPadding"),ku.blob(ku.offset(ku.u32(),-8),"chars")],e),n=t.decode.bind(t),r=t.encode.bind(t),i=t;return i.decode=(e,t)=>n(e,t).chars.toString(),i.encode=(e,t,n)=>{const i={chars:pa.Buffer.from(e,"utf8")};return r(i,t,n)},i.alloc=e=>ku.u32().span+ku.u32().span+pa.Buffer.from(e,"utf8").length,i};function oy(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 oy({layout:e},t[e.property]);return 0};let r=0;return e.layout.fields.forEach(e=>{r+=n(e)}),r}function ay(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 cy(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 ly(e,t){if(!e)throw new Error(t||"Assertion failed")}class uy{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},i=r(t);i.isSigner=!0,i.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 uy(t,n)}getMessageComponents(){const e=[...this.keyMetaMap.entries()];ly(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),i=e.filter(([,e])=>!e.isSigner&&!e.isWritable),s={numRequiredSignatures:t.length+n.length,numReadonlySignedAccounts:n.length,numReadonlyUnsignedAccounts:i.length};{ly(t.length>0,"Expected at least one writable signer key");const[e]=t[0];ly(e===this.payer.toBase58(),"Expected first writable signer key to be the fee payer")}return[s,[...t.map(([e])=>new Qp(e)),...n.map(([e])=>new Qp(e)),...r.map(([e])=>new Qp(e)),...i.map(([e])=>new Qp(e))]]}extractTableLookup(e){const[t,n]=this.drainKeysFoundInLookupTable(e.state.addresses,e=>!e.isSigner&&!e.isInvoked&&e.isWritable),[r,i]=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:i}]}drainKeysFoundInLookupTable(e,t){const n=new Array,r=new Array;for(const[i,s]of this.keyMetaMap.entries())if(t(s)){const t=new Qp(i),s=e.findIndex(e=>e.equals(t));s>=0&&(ly(s<256,"Max lookup table index exceeded"),n.push(s),r.push(t),this.keyMetaMap.delete(i))}return[n,r]}}const dy="Reached end of buffer unexpectedly";function hy(e){if(0===e.length)throw new Error(dy);return e.shift()}function gy(e,...t){const[n]=t;if(2===t.length?n+(t[1]??0)>e.length:n>=e.length)throw new Error(dy);return e.splice(...t)}class fy{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 Qp(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:ru.decode(e.data)}))}get addressTableLookups(){return[]}getAccountKeys(){return new ry(this.staticAccountKeys)}static compile(e){const t=uy.compile(e.instructions,e.payerKey),[n,r]=t.getMessageComponents(),i=new ry(r).compileInstructions(e.instructions).map(e=>({programIdIndex:e.programIdIndex,accounts:e.accountKeyIndexes,data:ru.encode(e.data)}));return new fy({header:n,accountKeys:r,recentBlockhash:e.recentBlockhash,instructions:i})}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=[];cy(t,e);const n=this.instructions.map(e=>{const{accounts:t,programIdIndex:n}=e,r=Array.from(ru.decode(e.data));let i=[];cy(i,t.length);let s=[];return cy(s,r.length),{programIdIndex:n,keyIndicesCount:pa.Buffer.from(i),keyIndices:t,dataLength:pa.Buffer.from(s),data:r}});let r=[];cy(r,n.length);let i=pa.Buffer.alloc(Zp);pa.Buffer.from(r).copy(i);let s=r.length;n.forEach(e=>{const t=ku.struct([ku.u8("programIdIndex"),ku.blob(e.keyIndicesCount.length,"keyIndicesCount"),ku.seq(ku.u8("keyIndex"),e.keyIndices.length,"keyIndices"),ku.blob(e.dataLength.length,"dataLength"),ku.seq(ku.u8("userdatum"),e.data.length,"data")]).encode(e,i,s);s+=t}),i=i.slice(0,s);const o=ku.struct([ku.blob(1,"numRequiredSignatures"),ku.blob(1,"numReadonlySignedAccounts"),ku.blob(1,"numReadonlyUnsignedAccounts"),ku.blob(t.length,"keyCount"),ku.seq(iy("key"),e,"keys"),iy("recentBlockhash")]),a={numRequiredSignatures:pa.Buffer.from([this.header.numRequiredSignatures]),numReadonlySignedAccounts:pa.Buffer.from([this.header.numReadonlySignedAccounts]),numReadonlyUnsignedAccounts:pa.Buffer.from([this.header.numReadonlyUnsignedAccounts]),keyCount:pa.Buffer.from(t),keys:this.accountKeys.map(e=>jp(e.toBytes())),recentBlockhash:ru.decode(this.recentBlockhash)};let c=pa.Buffer.alloc(2048);const l=o.encode(a,c);return i.copy(c,l),c.slice(0,l+i.length)}static from(e){let t=[...e];const n=hy(t);if(n!==(127&n))throw new Error("Versioned messages must be deserialized with VersionedMessage.deserialize()");const r=hy(t),i=hy(t),s=ay(t);let o=[];for(let e=0;e<s;e++){const e=gy(t,0,Jp);o.push(new Qp(pa.Buffer.from(e)))}const a=gy(t,0,Jp),c=ay(t);let l=[];for(let e=0;e<c;e++){const e=hy(t),n=gy(t,0,ay(t)),r=gy(t,0,ay(t)),i=ru.encode(pa.Buffer.from(r));l.push({programIdIndex:e,accounts:n,data:i})}const u={header:{numRequiredSignatures:n,numReadonlySignedAccounts:r,numReadonlyUnsignedAccounts:i},recentBlockhash:ru.encode(pa.Buffer.from(a)),accountKeys:o,instructions:l};return new fy(u)}}class my{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 ry(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=uy.compile(e.instructions,e.payerKey),n=new Array,r={writable:new Array,readonly:new Array},i=e.addressLookupTableAccounts||[];for(const e of i){const i=t.extractTableLookup(e);if(void 0!==i){const[e,{writable:t,readonly:s}]=i;n.push(e),r.writable.push(...t),r.readonly.push(...s)}}const[s,o]=t.getMessageComponents(),a=new ry(o,r).compileInstructions(e.instructions);return new my({header:s,staticAccountKeys:o,recentBlockhash:e.recentBlockhash,compiledInstructions:a,addressTableLookups:n})}serialize(){const e=Array();cy(e,this.staticAccountKeys.length);const t=this.serializeInstructions(),n=Array();cy(n,this.compiledInstructions.length);const r=this.serializeAddressTableLookups(),i=Array();cy(i,this.addressTableLookups.length);const s=ku.struct([ku.u8("prefix"),ku.struct([ku.u8("numRequiredSignatures"),ku.u8("numReadonlySignedAccounts"),ku.u8("numReadonlyUnsignedAccounts")],"header"),ku.blob(e.length,"staticAccountKeysLength"),ku.seq(iy(),this.staticAccountKeys.length,"staticAccountKeys"),iy("recentBlockhash"),ku.blob(n.length,"instructionsLength"),ku.blob(t.length,"serializedInstructions"),ku.blob(i.length,"addressTableLookupsLength"),ku.blob(r.length,"serializedAddressTableLookups")]),o=new Uint8Array(Zp),a=s.encode({prefix:128,header:this.header,staticAccountKeysLength:new Uint8Array(e),staticAccountKeys:this.staticAccountKeys.map(e=>e.toBytes()),recentBlockhash:ru.decode(this.recentBlockhash),instructionsLength:new Uint8Array(n),serializedInstructions:t,addressTableLookupsLength:new Uint8Array(i),serializedAddressTableLookups:r},o);return o.slice(0,a)}serializeInstructions(){let e=0;const t=new Uint8Array(Zp);for(const n of this.compiledInstructions){const r=Array();cy(r,n.accountKeyIndexes.length);const i=Array();cy(i,n.data.length);e+=ku.struct([ku.u8("programIdIndex"),ku.blob(r.length,"encodedAccountKeyIndexesLength"),ku.seq(ku.u8(),n.accountKeyIndexes.length,"accountKeyIndexes"),ku.blob(i.length,"encodedDataLength"),ku.blob(n.data.length,"data")]).encode({programIdIndex:n.programIdIndex,encodedAccountKeyIndexesLength:new Uint8Array(r),accountKeyIndexes:n.accountKeyIndexes,encodedDataLength:new Uint8Array(i),data:n.data},t,e)}return t.slice(0,e)}serializeAddressTableLookups(){let e=0;const t=new Uint8Array(Zp);for(const n of this.addressTableLookups){const r=Array();cy(r,n.writableIndexes.length);const i=Array();cy(i,n.readonlyIndexes.length);e+=ku.struct([iy("accountKey"),ku.blob(r.length,"encodedWritableIndexesLength"),ku.seq(ku.u8(),n.writableIndexes.length,"writableIndexes"),ku.blob(i.length,"encodedReadonlyIndexesLength"),ku.seq(ku.u8(),n.readonlyIndexes.length,"readonlyIndexes")]).encode({accountKey:n.accountKey.toBytes(),encodedWritableIndexesLength:new Uint8Array(r),writableIndexes:n.writableIndexes,encodedReadonlyIndexesLength:new Uint8Array(i),readonlyIndexes:n.readonlyIndexes},t,e)}return t.slice(0,e)}static deserialize(e){let t=[...e];const n=hy(t),r=127&n;ly(n!==r,"Expected versioned message but received legacy message");ly(0===r,`Expected versioned message with version 0 but found version ${r}`);const i={numRequiredSignatures:hy(t),numReadonlySignedAccounts:hy(t),numReadonlyUnsignedAccounts:hy(t)},s=[],o=ay(t);for(let e=0;e<o;e++)s.push(new Qp(gy(t,0,Jp)));const a=ru.encode(gy(t,0,Jp)),c=ay(t),l=[];for(let e=0;e<c;e++){const e=hy(t),n=gy(t,0,ay(t)),r=ay(t),i=new Uint8Array(gy(t,0,r));l.push({programIdIndex:e,accountKeyIndexes:n,data:i})}const u=ay(t),d=[];for(let e=0;e<u;e++){const e=new Qp(gy(t,0,Jp)),n=gy(t,0,ay(t)),r=gy(t,0,ay(t));d.push({accountKey:e,writableIndexes:n,readonlyIndexes:r})}return new my({header:i,staticAccountKeys:s,recentBlockhash:a,compiledInstructions:l,addressTableLookups:d})}}function py(e){const t=gy(e,0,4);return t[0]+256*t[1]+65536*t[2]+t[3]*2**24}class yy{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 ry(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=hy(t),r=127&n;ly(n!==r,"Expected versioned message but received legacy message");ly(1===r,`Expected versioned message with version 1 but found version ${r}`);const i={numRequiredSignatures:hy(t),numReadonlySignedAccounts:hy(t),numReadonlyUnsignedAccounts:hy(t)},s=py(t);ly(!(-32&s),"Unexpected bits set in the transaction config mask");const o=3&s;ly(0===o||3===o,"Expected both or neither of the priority fee bits to be set in the transaction config mask");const a=ru.encode(gy(t,0,Jp)),c=hy(t),l=hy(t),u=[];for(let e=0;e<l;e++)u.push(new Qp(gy(t,0,Jp)));const d={computeUnitLimit:null,heapSize:null,loadedAccountsDataSizeLimit:null,priorityFee:null};0!==o&&(d.priorityFee=function(e){const t=gy(e,0,8);let n=BigInt(0);for(let e=t.length-1;e>=0;e--)n=n<<BigInt(8)|BigInt(t[e]);return ly(n<=BigInt(Number.MAX_SAFE_INTEGER),"Expected u64 value to be within the safe integer range"),Number(n)}(t)),4&s&&(d.computeUnitLimit=py(t)),8&s&&(d.loadedAccountsDataSizeLimit=py(t)),16&s&&(d.heapSize=py(t));const h=[];for(let e=0;e<c;e++){const e=hy(t),n=hy(t),r=hy(t)+256*hy(t);h.push({accountKeyIndexesLength:n,dataLength:r,programIdIndex:e})}const g=[];for(const e of h)g.push({programIdIndex:e.programIdIndex,accountKeyIndexes:gy(t,0,e.accountKeyIndexesLength),data:new Uint8Array(gy(t,0,e.dataLength))});return ly(0===t.length,"Expected no bytes to remain after deserializing a version 1 message"),new yy({header:i,staticAccountKeys:u,recentBlockhash:a,compiledInstructions:g,transactionConfig:d})}}let by=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 vy=pa.Buffer.alloc(64).fill(0);class wy{constructor(e){this.keys=void 0,this.programId=void 0,this.data=pa.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 Ey{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 wy(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=[],i=[];t.forEach(e=>{e.keys.forEach(e=>{i.push({...e})});const t=e.programId.toString();r.includes(t)||r.push(t)}),r.forEach(e=>{i.push({pubkey:new Qp(e),isSigner:!1,isWritable:!1})});const s=[];i.forEach(e=>{const t=e.pubkey.toString(),n=s.findIndex(e=>e.pubkey.toString()===t);n>-1?(s[n].isWritable=s[n].isWritable||e.isWritable,s[n].isSigner=s[n].isSigner||e.isSigner):s.push(e)}),s.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=s.findIndex(e=>e.pubkey.equals(n));if(o>-1){const[e]=s.splice(o,1);e.isSigner=!0,e.isWritable=!0,s.unshift(e)}else s.unshift({pubkey:n,isSigner:!0,isWritable:!0});for(const e of this.signatures){const t=s.findIndex(t=>t.pubkey.equals(e.publicKey));if(!(t>-1))throw new Error(`unknown signer: ${e.publicKey.toString()}`);s[t].isSigner||(s[t].isSigner=!0)}let a=0,c=0,l=0;const u=[],d=[];s.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:ru.encode(t)}});return g.forEach(e=>{ly(e.programIdIndex>=0),e.accounts.forEach(e=>ly(e>=0))}),new fy({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)=>Kl.sign(e,t.slice(0,32)))(n,e.secretKey);this._addSignature(e.publicKey,jp(t))})}addSignature(e,t){this._compile(),this._addSignature(e,t)}_addSignature(e,t){ly(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=pa.Buffer.from(t)}verifySignatures(e=!0){return!this._getMessageSignednessErrors(this.serializeMessage(),e)}_getMessageSignednessErrors(e,t){const n={};for(const{signature:r,publicKey:i}of this.signatures)null===r?t&&(n.missing||=[]).push(i):qp(r,e,i.toBytes())||(n.invalid||=[]).push(i);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=[];cy(n,t.length);const r=n.length+64*t.length+e.length,i=pa.Buffer.alloc(r);return ly(t.length<256),pa.Buffer.from(n).copy(i,0),t.forEach(({signature:e},t)=>{null!==e&&(ly(64===e.length,"signature has invalid length"),pa.Buffer.from(e).copy(i,n.length+64*t))}),e.copy(i,n.length+64*t.length),ly(i.length<=Zp,`Transaction too large: ${i.length} > 1232`),i}get keys(){return ly(1===this.instructions.length),this.instructions[0].keys.map(e=>e.pubkey)}get programId(){return ly(1===this.instructions.length),this.instructions[0].programId}get data(){return ly(1===this.instructions.length),this.instructions[0].data}static from(e){let t=[...e];const n=ay(t);let r=[];for(let e=0;e<n;e++){const e=gy(t,0,64);r.push(ru.encode(pa.Buffer.from(e)))}return Ey.populate(fy.from(t),r)}static populate(e,t=[]){const n=new Ey;return n.recentBlockhash=e.recentBlockhash,e.header.numRequiredSignatures>0&&(n.feePayer=e.accountKeys[0]),t.forEach((t,r)=>{const i={signature:t==ru.encode(vy)?null:ru.decode(t),publicKey:e.accountKeys[r]};n.signatures.push(i)}),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 wy({keys:r,programId:e.accountKeys[t.programIdIndex],data:ru.decode(t.data)}))}),n._message=e,n._json=n.toJSON(),n}}new Qp("SysvarC1ock11111111111111111111111111111111"),new Qp("SysvarEpochSchedu1e111111111111111111111111"),new Qp("Sysvar1nstructions1111111111111111111111111");const Ay=new Qp("SysvarRecentB1ockHashes11111111111111111111"),ky=new Qp("SysvarRent111111111111111111111111111111111");new Qp("SysvarRewards111111111111111111111111111111"),new Qp("SysvarS1otHashes111111111111111111111111111"),new Qp("SysvarS1otHistory11111111111111111111111111"),new Qp("SysvarStakeHistory1111111111111111111111111");class Sy extends Error{constructor({action:e,signature:t,transactionMessage:n,logs:r}){const i=r?`Logs: \n${JSON.stringify(r.slice(-10),null,2)}. `:"",s="\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}. `+i+s;break;case"simulate":o=`Simulation failed. \nMessage: ${n}. \n`+i+s;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 Ty 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 Iy(e){return new Promise(t=>setTimeout(t,e))}function Ny(e,t){const n=e.layout.span>=0?e.layout.span:oy(e,t),r=pa.Buffer.alloc(n),i=Object.assign({instruction:e.index},t);return e.layout.encode(i,r),r}const Cy=ku.nu64("lamportsPerSignature"),_y=ku.struct([ku.u32("version"),ku.u32("state"),iy("authorizedPubkey"),iy("nonce"),ku.struct([Cy],"feeCalculator")]),xy=_y.span;class Ry{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=_y.decode(jp(e),0);return new Ry({authorizedPubkey:new Qp(t.authorizedPubkey),nonce:new Qp(t.nonce).toString(),feeCalculator:t.feeCalculator})}}function By(e){const t=ku.blob(8,e),n=t.decode.bind(t),r=t.encode.bind(t),i=t,s=_m();return i.decode=(e,t)=>{const r=n(e,t);return s.decode(r)},i.encode=(e,t,n)=>{const i=s.encode(e);return r(i,t,n)},i}const Dy=Object.freeze({Create:{index:0,layout:ku.struct([ku.u32("instruction"),ku.ns64("lamports"),ku.ns64("space"),iy("programId")])},Assign:{index:1,layout:ku.struct([ku.u32("instruction"),iy("programId")])},Transfer:{index:2,layout:ku.struct([ku.u32("instruction"),By("lamports")])},CreateWithSeed:{index:3,layout:ku.struct([ku.u32("instruction"),iy("base"),sy("seed"),ku.ns64("lamports"),ku.ns64("space"),iy("programId")])},AdvanceNonceAccount:{index:4,layout:ku.struct([ku.u32("instruction")])},WithdrawNonceAccount:{index:5,layout:ku.struct([ku.u32("instruction"),ku.ns64("lamports")])},InitializeNonceAccount:{index:6,layout:ku.struct([ku.u32("instruction"),iy("authorized")])},AuthorizeNonceAccount:{index:7,layout:ku.struct([ku.u32("instruction"),iy("authorized")])},Allocate:{index:8,layout:ku.struct([ku.u32("instruction"),ku.ns64("space")])},AllocateWithSeed:{index:9,layout:ku.struct([ku.u32("instruction"),iy("base"),sy("seed"),ku.ns64("space"),iy("programId")])},AssignWithSeed:{index:10,layout:ku.struct([ku.u32("instruction"),iy("base"),sy("seed"),iy("programId")])},TransferWithSeed:{index:11,layout:ku.struct([ku.u32("instruction"),By("lamports"),sy("seed"),iy("programId")])},UpgradeNonceAccount:{index:12,layout:ku.struct([ku.u32("instruction")])}});class My{constructor(){}static createAccount(e){const t=Ny(Dy.Create,{lamports:e.lamports,space:e.space,programId:jp(e.programId.toBuffer())});return new wy({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=Ny(Dy.TransferWithSeed,{lamports:BigInt(e.lamports),seed:e.seed,programId:jp(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=Ny(Dy.Transfer,{lamports:BigInt(e.lamports)}),n=[{pubkey:e.fromPubkey,isSigner:!0,isWritable:!0},{pubkey:e.toPubkey,isSigner:!1,isWritable:!0}]}return new wy({keys:n,programId:this.programId,data:t})}static assign(e){let t,n;if("basePubkey"in e){t=Ny(Dy.AssignWithSeed,{base:jp(e.basePubkey.toBuffer()),seed:e.seed,programId:jp(e.programId.toBuffer())}),n=[{pubkey:e.accountPubkey,isSigner:!1,isWritable:!0},{pubkey:e.basePubkey,isSigner:!0,isWritable:!1}]}else{t=Ny(Dy.Assign,{programId:jp(e.programId.toBuffer())}),n=[{pubkey:e.accountPubkey,isSigner:!0,isWritable:!0}]}return new wy({keys:n,programId:this.programId,data:t})}static createAccountWithSeed(e){const t=Ny(Dy.CreateWithSeed,{base:jp(e.basePubkey.toBuffer()),seed:e.seed,lamports:e.lamports,space:e.space,programId:jp(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 wy({keys:n,programId:this.programId,data:t})}static createNonceAccount(e){const t=new Ey;"basePubkey"in e&&"seed"in e?t.add(My.createAccountWithSeed({fromPubkey:e.fromPubkey,newAccountPubkey:e.noncePubkey,basePubkey:e.basePubkey,seed:e.seed,lamports:e.lamports,space:xy,programId:this.programId})):t.add(My.createAccount({fromPubkey:e.fromPubkey,newAccountPubkey:e.noncePubkey,lamports:e.lamports,space:xy,programId:this.programId}));const n={noncePubkey:e.noncePubkey,authorizedPubkey:e.authorizedPubkey};return t.add(this.nonceInitialize(n)),t}static nonceInitialize(e){const t=Ny(Dy.InitializeNonceAccount,{authorized:jp(e.authorizedPubkey.toBuffer())}),n={keys:[{pubkey:e.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:Ay,isSigner:!1,isWritable:!1},{pubkey:ky,isSigner:!1,isWritable:!1}],programId:this.programId,data:t};return new wy(n)}static nonceAdvance(e){const t=Ny(Dy.AdvanceNonceAccount),n={keys:[{pubkey:e.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:Ay,isSigner:!1,isWritable:!1},{pubkey:e.authorizedPubkey,isSigner:!0,isWritable:!1}],programId:this.programId,data:t};return new wy(n)}static nonceWithdraw(e){const t=Ny(Dy.WithdrawNonceAccount,{lamports:e.lamports});return new wy({keys:[{pubkey:e.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:e.toPubkey,isSigner:!1,isWritable:!0},{pubkey:Ay,isSigner:!1,isWritable:!1},{pubkey:ky,isSigner:!1,isWritable:!1},{pubkey:e.authorizedPubkey,isSigner:!0,isWritable:!1}],programId:this.programId,data:t})}static nonceAuthorize(e){const t=Ny(Dy.AuthorizeNonceAccount,{authorized:jp(e.newAuthorizedPubkey.toBuffer())});return new wy({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=Ny(Dy.AllocateWithSeed,{base:jp(e.basePubkey.toBuffer()),seed:e.seed,space:e.space,programId:jp(e.programId.toBuffer())}),n=[{pubkey:e.accountPubkey,isSigner:!1,isWritable:!0},{pubkey:e.basePubkey,isSigner:!0,isWritable:!1}]}else{t=Ny(Dy.Allocate,{space:e.space}),n=[{pubkey:e.accountPubkey,isSigner:!0,isWritable:!0}]}return new wy({keys:n,programId:this.programId,data:t})}}function Oy(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Uy,Ly;function Py(){if(Ly)return Uy;Ly=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,i){var s,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(),i);if("[object Array]"===(d=e.call(r))){for(a="[",o=r.length-1,s=0;s<o;s++)a+=n(r[s],!0)+",";return o>-1&&(a+=n(r[s],!0)),a+"]"}if("[object Object]"===d){for(o=(c=t(r).sort()).length,a="",s=0;s<o;)void 0!==(u=n(r[l=c[s]],!1))&&(a&&(a+=","),a+=JSON.stringify(l)+":"+u),s++;return"{"+a+"}"}return JSON.stringify(r);case"function":case"undefined":return i?null:void 0;case"string":return JSON.stringify(r);default:return isFinite(r)?r:null}}return Uy=function(e){var t=n(e,!1);if(void 0!==t)return""+t}}My.programId=new Qp("11111111111111111111111111111111"),new Qp("BPFLoader2111111111111111111111111111111111");var Fy=Oy(Py());function $y(e){let t=0;for(;e>1;)e/=2,t++;return t}class Ky{constructor(e,t,n,r,i){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=i}getEpoch(e){return this.getEpochAndSlotIndex(e)[0]}getEpochAndSlotIndex(e){if(e<this.firstNormalSlot){const n=$y(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)))-$y(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+$y(32)):this.slotsPerEpoch}}var Gy=globalThis.fetch;class Hy extends pp{constructor(e,t,n){super(e=>{const n=function(e,t){return new fp(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 Wy{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}(qy,e),n=e.length-56;ly(n>=0,"lookup table is invalid"),ly(n%32==0,"lookup table is invalid");const r=n/32,{addresses:i}=ku.struct([ku.seq(iy(),r,"addresses")]).decode(e.slice(56));return{deactivationSlot:t.deactivationSlot,lastExtendedSlot:t.lastExtendedSlot,lastExtendedSlotStartIndex:t.lastExtendedStartIndex,authority:0!==t.authority.length?new Qp(t.authority[0]):void 0,addresses:i.map(e=>new Qp(e))}}}const qy={index:1,layout:ku.struct([ku.u32("typeIndex"),By("deactivationSlot"),ku.nu64("lastExtendedSlot"),ku.u8("lastExtendedStartIndex"),ku.u8(),ku.seq(iy(),ku.offset(ku.u8(),-1),"authority")])},jy=/^[^:]+:\/\/([^:[]+|\[[^\]]+\])(:\d+)?(.*)/i;const Vy=tp(Wm(Qp),Jm(),e=>new Qp(e)),zy=Ym([Jm(),qm("base64")]),Xy=tp(Wm(pa.Buffer),zy,e=>pa.Buffer.from(e[0],"base64"));function Jy(e){let t,n;if("string"==typeof e)t=e;else if(e){const{commitment:r,...i}=e;t=r,n=i}return{commitment:t,config:n}}function Yy(e){return e.map(e=>"memcmp"in e?{...e,memcmp:{...e.memcmp,encoding:e.memcmp.encoding??"base58"}}:e)}function Qy(e){return Zm([Qm({jsonrpc:qm("2.0"),id:Jm(),result:e}),Qm({jsonrpc:qm("2.0"),id:Jm(),error:Qm({code:ep(),message:Jm(),data:zm(Km("any",()=>!0))})})])}const Zy=Qy(ep());function eb(e){return tp(Qy(e),Zy,t=>"error"in t?t:{...t,result:Pm(t.result,e)})}function tb(e){return eb(Qm({context:Qm({slot:Vm()}),value:e}))}function nb(e){return Qm({context:Qm({slot:Vm()}),value:e})}function rb(e,t){if(0===e)return new my({header:t.header,staticAccountKeys:t.accountKeys.map(e=>new Qp(e)),recentBlockhash:t.recentBlockhash,compiledInstructions:t.instructions.map(e=>({programIdIndex:e.programIdIndex,accountKeyIndexes:e.accounts,data:ru.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 yy({header:t.header,staticAccountKeys:t.accountKeys.map(e=>new Qp(e)),recentBlockhash:t.recentBlockhash,compiledInstructions:t.instructions.map(e=>({programIdIndex:e.programIdIndex,accountKeyIndexes:e.accounts,data:ru.decode(e.data)})),transactionConfig:e})}return new fy(t)}const ib=Qm({foundation:Vm(),foundationTerm:Vm(),initial:Vm(),taper:Vm(),terminal:Vm()}),sb=eb(Gm(jm(Qm({epoch:Vm(),effectiveSlot:Vm(),amount:Vm(),postBalance:Vm(),commission:zm(jm(Vm()))})))),ob=Gm(Qm({slot:Vm(),prioritizationFee:Vm()})),ab=Qm({total:Vm(),validator:Vm(),foundation:Vm(),epoch:Vm()}),cb=Qm({epoch:Vm(),slotIndex:Vm(),slotsInEpoch:Vm(),absoluteSlot:Vm(),blockHeight:zm(Vm()),transactionCount:zm(Vm())}),lb=Qm({slotsPerEpoch:Vm(),leaderScheduleSlotOffset:Vm(),warmup:Hm(),firstNormalEpoch:Vm(),firstNormalSlot:Vm()}),ub=Xm(Jm(),Gm(Vm())),db=jm(Zm([Qm({}),Jm()])),hb=Qm({err:db}),gb=qm("receivedSignature"),fb=Qm({"solana-core":Jm(),"feature-set":zm(Vm())}),mb=Qm({program:Jm(),programId:Vy,parsed:ep()}),pb=Qm({programId:Vy,accounts:Gm(Vy),data:Jm()}),yb=tb(Qm({err:jm(Zm([Qm({}),Jm()])),logs:jm(Gm(Jm())),accounts:zm(jm(Gm(jm(Qm({executable:Hm(),owner:Jm(),lamports:Vm(),data:Gm(Jm()),rentEpoch:zm(Vm())}))))),unitsConsumed:zm(Vm()),returnData:zm(jm(Qm({programId:Jm(),data:Ym([Jm(),qm("base64")])}))),innerInstructions:zm(jm(Gm(Qm({index:Vm(),instructions:Gm(Zm([mb,pb]))}))))})),bb=tb(Qm({byIdentity:Xm(Jm(),Gm(Vm())),range:Qm({firstSlot:Vm(),lastSlot:Vm()})}));const vb=eb(ib),wb=eb(ab),Eb=eb(ob),Ab=eb(cb),kb=eb(lb),Sb=eb(ub),Tb=eb(Vm()),Ib=tb(Qm({total:Vm(),circulating:Vm(),nonCirculating:Vm(),nonCirculatingAccounts:Gm(Vy)})),Nb=Qm({amount:Jm(),uiAmount:jm(Vm()),decimals:Vm(),uiAmountString:zm(Jm())}),Cb=tb(Gm(Qm({address:Vy,amount:Jm(),uiAmount:jm(Vm()),decimals:Vm(),uiAmountString:zm(Jm())}))),_b=tb(Gm(Qm({pubkey:Vy,account:Qm({executable:Hm(),owner:Vy,lamports:Vm(),data:Xy,rentEpoch:Vm()})}))),xb=Qm({program:Jm(),parsed:ep(),space:Vm()}),Rb=tb(Gm(Qm({pubkey:Vy,account:Qm({executable:Hm(),owner:Vy,lamports:Vm(),data:xb,rentEpoch:Vm()})}))),Bb=tb(Gm(Qm({lamports:Vm(),address:Vy}))),Db=Qm({executable:Hm(),owner:Vy,lamports:Vm(),data:Xy,rentEpoch:Vm()}),Mb=Qm({pubkey:Vy,account:Db}),Ob=tp(Zm([Wm(pa.Buffer),xb]),Zm([zy,xb]),e=>Array.isArray(e)?Pm(e,Xy):e),Ub=Qm({executable:Hm(),owner:Vy,lamports:Vm(),data:Ob,rentEpoch:Vm()}),Lb=Qm({pubkey:Vy,account:Ub}),Pb=Qm({state:Zm([qm("active"),qm("inactive"),qm("activating"),qm("deactivating")]),active:Vm(),inactive:Vm()}),Fb=eb(Gm(Qm({signature:Jm(),slot:Vm(),err:db,memo:jm(Jm()),blockTime:zm(jm(Vm()))}))),$b=eb(Gm(Qm({signature:Jm(),slot:Vm(),err:db,memo:jm(Jm()),blockTime:zm(jm(Vm()))}))),Kb=Qm({subscription:Vm(),result:nb(Db)}),Gb=Qm({pubkey:Vy,account:Db}),Hb=Qm({subscription:Vm(),result:nb(Gb)}),Wb=Qm({parent:Vm(),slot:Vm(),root:Vm()}),qb=Qm({subscription:Vm(),result:Wb}),jb=Zm([Qm({type:Zm([qm("firstShredReceived"),qm("completed"),qm("optimisticConfirmation"),qm("root")]),slot:Vm(),timestamp:Vm()}),Qm({type:qm("createdBank"),parent:Vm(),slot:Vm(),timestamp:Vm()}),Qm({type:qm("frozen"),slot:Vm(),timestamp:Vm(),stats:Qm({numTransactionEntries:Vm(),numSuccessfulTransactions:Vm(),numFailedTransactions:Vm(),maxTransactionsPerEntry:Vm()})}),Qm({type:qm("dead"),slot:Vm(),timestamp:Vm(),err:Jm()})]),Vb=Qm({subscription:Vm(),result:jb}),zb=Qm({subscription:Vm(),result:nb(Zm([hb,gb]))}),Xb=Qm({subscription:Vm(),result:Vm()}),Jb=Qm({pubkey:Jm(),gossip:jm(Jm()),tpu:jm(Jm()),rpc:jm(Jm()),version:jm(Jm())}),Yb=Qm({votePubkey:Jm(),nodePubkey:Jm(),activatedStake:Vm(),epochVoteAccount:Hm(),epochCredits:Gm(Ym([Vm(),Vm(),Vm()])),commission:Vm(),lastVote:Vm(),rootSlot:jm(Vm())}),Qb=eb(Qm({current:Gm(Yb),delinquent:Gm(Yb)})),Zb=Zm([qm("processed"),qm("confirmed"),qm("finalized")]),ev=Qm({slot:Vm(),confirmations:jm(Vm()),err:db,confirmationStatus:zm(Zb)}),tv=tb(Gm(jm(ev))),nv=eb(Vm()),rv=Qm({accountKey:Vy,writableIndexes:Gm(Vm()),readonlyIndexes:Gm(Vm())}),iv=Qm({computeUnitLimit:jm(Vm()),heapSize:jm(Vm()),loadedAccountsDataSizeLimit:jm(Vm()),priorityFee:jm(Vm())}),sv=Qm({signatures:Gm(Jm()),message:Qm({accountKeys:Gm(Jm()),header:Qm({numRequiredSignatures:Vm(),numReadonlySignedAccounts:Vm(),numReadonlyUnsignedAccounts:Vm()}),instructions:Gm(Qm({accounts:Gm(Vm()),data:Jm(),programIdIndex:Vm()})),recentBlockhash:Jm(),addressTableLookups:zm(Gm(rv)),transactionConfig:zm(jm(iv))})}),ov=Qm({pubkey:Vy,signer:Hm(),writable:Hm(),source:zm(Zm([qm("transaction"),qm("lookupTable")]))}),av=Qm({accountKeys:Gm(ov),signatures:Gm(Jm())}),cv=Qm({parsed:ep(),program:Jm(),programId:Vy}),lv=Qm({accounts:Gm(Vy),data:Jm(),programId:Vy}),uv=tp(Zm([lv,cv]),Zm([Qm({parsed:ep(),program:Jm(),programId:Jm()}),Qm({accounts:Gm(Jm()),data:Jm(),programId:Jm()})]),e=>Pm(e,"accounts"in e?lv:cv)),dv=Qm({signatures:Gm(Jm()),message:Qm({accountKeys:Gm(ov),instructions:Gm(uv),recentBlockhash:Jm(),addressTableLookups:zm(jm(Gm(rv))),transactionConfig:zm(jm(iv))})}),hv=Qm({accountIndex:Vm(),mint:Jm(),owner:zm(Jm()),programId:zm(Jm()),uiTokenAmount:Nb}),gv=Qm({writable:Gm(Vy),readonly:Gm(Vy)}),fv=Qm({err:db,fee:Vm(),innerInstructions:zm(jm(Gm(Qm({index:Vm(),instructions:Gm(Qm({accounts:Gm(Vm()),data:Jm(),programIdIndex:Vm()}))})))),preBalances:Gm(Vm()),postBalances:Gm(Vm()),logMessages:zm(jm(Gm(Jm()))),preTokenBalances:zm(jm(Gm(hv))),postTokenBalances:zm(jm(Gm(hv))),loadedAddresses:zm(gv),computeUnitsConsumed:zm(Vm()),costUnits:zm(Vm())}),mv=Qm({err:db,fee:Vm(),innerInstructions:zm(jm(Gm(Qm({index:Vm(),instructions:Gm(uv)})))),preBalances:Gm(Vm()),postBalances:Gm(Vm()),logMessages:zm(jm(Gm(Jm()))),preTokenBalances:zm(jm(Gm(hv))),postTokenBalances:zm(jm(Gm(hv))),loadedAddresses:zm(gv),computeUnitsConsumed:zm(Vm()),costUnits:zm(Vm())}),pv=Zm([qm(0),qm(1),qm("legacy")]),yv=Qm({pubkey:Jm(),lamports:Vm(),postBalance:jm(Vm()),rewardType:jm(Jm()),commission:zm(jm(Vm()))}),bv=eb(jm(Qm({blockhash:Jm(),previousBlockhash:Jm(),parentSlot:Vm(),transactions:Gm(Qm({transaction:sv,meta:jm(fv),version:zm(pv)})),rewards:zm(Gm(yv)),blockTime:jm(Vm()),blockHeight:jm(Vm())}))),vv=eb(jm(Qm({blockhash:Jm(),previousBlockhash:Jm(),parentSlot:Vm(),rewards:zm(Gm(yv)),blockTime:jm(Vm()),blockHeight:jm(Vm())}))),wv=eb(jm(Qm({blockhash:Jm(),previousBlockhash:Jm(),parentSlot:Vm(),transactions:Gm(Qm({transaction:av,meta:jm(fv),version:zm(pv)})),rewards:zm(Gm(yv)),blockTime:jm(Vm()),blockHeight:jm(Vm())}))),Ev=eb(jm(Qm({blockhash:Jm(),previousBlockhash:Jm(),parentSlot:Vm(),transactions:Gm(Qm({transaction:dv,meta:jm(mv),version:zm(pv)})),rewards:zm(Gm(yv)),blockTime:jm(Vm()),blockHeight:jm(Vm())}))),Av=eb(jm(Qm({blockhash:Jm(),previousBlockhash:Jm(),parentSlot:Vm(),transactions:Gm(Qm({transaction:av,meta:jm(mv),version:zm(pv)})),rewards:zm(Gm(yv)),blockTime:jm(Vm()),blockHeight:jm(Vm())}))),kv=eb(jm(Qm({blockhash:Jm(),previousBlockhash:Jm(),parentSlot:Vm(),rewards:zm(Gm(yv)),blockTime:jm(Vm()),blockHeight:jm(Vm())}))),Sv=eb(jm(Qm({blockhash:Jm(),previousBlockhash:Jm(),parentSlot:Vm(),transactions:Gm(Qm({transaction:sv,meta:jm(fv)})),rewards:zm(Gm(yv)),blockTime:jm(Vm())}))),Tv=eb(jm(Qm({blockhash:Jm(),previousBlockhash:Jm(),parentSlot:Vm(),signatures:Gm(Jm()),blockTime:jm(Vm())}))),Iv=eb(jm(Qm({slot:Vm(),meta:jm(fv),blockTime:zm(jm(Vm())),transaction:sv,version:zm(pv)}))),Nv=eb(jm(Qm({slot:Vm(),transaction:dv,meta:jm(mv),blockTime:zm(jm(Vm())),version:zm(pv)}))),Cv=tb(Qm({blockhash:Jm(),lastValidBlockHeight:Vm()})),_v=tb(Hm()),xv=eb(Gm(Qm({slot:Vm(),numTransactions:Vm(),numSlots:Vm(),samplePeriodSecs:Vm()}))),Rv=tb(jm(Qm({feeCalculator:Qm({lamportsPerSignature:Vm()})}))),Bv=eb(Jm()),Dv=eb(Jm()),Mv=Qm({err:db,logs:Gm(Jm()),signature:Jm()}),Ov=Qm({result:nb(Mv),subscription:Vm()}),Uv={"solana-client":"js/1.99.0"};class Lv{constructor(e,t){let n,r,i,s,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}=Jy(t),i=this._buildArgs([],n,void 0,r),s=Fy(i);return e[s]=e[s]??(async()=>{try{const e=Pm(await this._rpcRequest("getBlockHeight",i),eb(Vm()));if("error"in e)throw new Ty(e.error,"failed to get block height information");return e.result}finally{delete e[s]}})(),await e[s]}})(),t&&"string"==typeof t?this._commitment=t:t&&(this._commitment=t.commitment,this._confirmTransactionInitialTimeout=t.confirmTransactionInitialTimeout,n=t.wsEndpoint,r=t.httpHeaders,i=t.fetch,s=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(jy);if(null==t)throw TypeError(`Failed to validate endpoint URL \`${e}\``);const[n,r,i,s]=t,o=e.startsWith("https:")?"wss:":"ws:",a=null==i?null:parseInt(i.slice(1),10);return`${o}//${r}${null==a?"":`:${a+1}`}${s}`}(e),this._rpcClient=function(e,t,n,r,i){const s=n||Gy;let o;return r&&(o=async(e,t)=>{const n=await new Promise((n,i)=>{try{r(e,t,(e,t)=>n([e,t]))}catch(e){i(e)}});return await s(...n)}),new up(async(n,r)=>{const a={method:"POST",body:n,agent:void 0,headers:Object.assign({"Content-Type":"application/json"},t||{},Uv)};try{let t,n=5,c=500;for(;t=o?await o(e,a):await s(e,a),429===t.status&&!0!==i&&(n-=1,0!==n);)await Iy(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,i,s,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 i=t.map(t=>e.request(t.methodName,t.args));e.request(i,(e,t)=>{e?r(e):n(t)})})}(this._rpcClient),this._rpcWebSocket=new Hy(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}=Jy(t),i=this._buildArgs([e.toBase58()],n,void 0,r),s=Pm(await this._rpcRequest("getBalance",i),tb(Vm()));if("error"in s)throw new Ty(s.error,`failed to get balance for ${e.toBase58()}`);return s.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=Pm(await this._rpcRequest("getBlockTime",[e]),eb(jm(Vm())));if("error"in t)throw new Ty(t.error,`failed to get block time for slot ${e}`);return t.result}async getMinimumLedgerSlot(){const e=Pm(await this._rpcRequest("minimumLedgerSlot",[]),eb(Vm()));if("error"in e)throw new Ty(e.error,"failed to get minimum ledger slot");return e.result}async getFirstAvailableBlock(){const e=Pm(await this._rpcRequest("getFirstAvailableBlock",[]),Tb);if("error"in e)throw new Ty(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=Pm(await this._rpcRequest("getSupply",[t]),Ib);if("error"in n)throw new Ty(n.error,"failed to get supply");return n.result}async getTokenSupply(e,t){const n=this._buildArgs([e.toBase58()],t),r=Pm(await this._rpcRequest("getTokenSupply",n),tb(Nb));if("error"in r)throw new Ty(r.error,"failed to get token supply");return r.result}async getTokenAccountBalance(e,t){const n=this._buildArgs([e.toBase58()],t),r=Pm(await this._rpcRequest("getTokenAccountBalance",n),tb(Nb));if("error"in r)throw new Ty(r.error,"failed to get token account balance");return r.result}async getTokenAccountsByOwner(e,t,n){const{commitment:r,config:i}=Jy(n);let s=[e.toBase58()];"mint"in t?s.push({mint:t.mint.toBase58()}):s.push({programId:t.programId.toBase58()});const o=this._buildArgs(s,r,"base64",i),a=Pm(await this._rpcRequest("getTokenAccountsByOwner",o),_b);if("error"in a)throw new Ty(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 i=this._buildArgs(r,n,"jsonParsed"),s=Pm(await this._rpcRequest("getTokenAccountsByOwner",i),Rb);if("error"in s)throw new Ty(s.error,`failed to get token accounts owned by account ${e.toBase58()}`);return s.result}async getLargestAccounts(e){const t={...e,commitment:e&&e.commitment||this.commitment},n=t.filter||t.commitment?[t]:[],r=Pm(await this._rpcRequest("getLargestAccounts",n),Bb);if("error"in r)throw new Ty(r.error,"failed to get largest accounts");return r.result}async getTokenLargestAccounts(e,t){const n=this._buildArgs([e.toBase58()],t),r=Pm(await this._rpcRequest("getTokenLargestAccounts",n),Cb);if("error"in r)throw new Ty(r.error,"failed to get token largest accounts");return r.result}async getAccountInfoAndContext(e,t){const{commitment:n,config:r}=Jy(t),i=this._buildArgs([e.toBase58()],n,"base64",r),s=Pm(await this._rpcRequest("getAccountInfo",i),tb(jm(Db)));if("error"in s)throw new Ty(s.error,`failed to get info about account ${e.toBase58()}`);return s.result}async getParsedAccountInfo(e,t){const{commitment:n,config:r}=Jy(t),i=this._buildArgs([e.toBase58()],n,"jsonParsed",r),s=Pm(await this._rpcRequest("getAccountInfo",i),tb(jm(Ub)));if("error"in s)throw new Ty(s.error,`failed to get info about account ${e.toBase58()}`);return s.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}=Jy(t),i=e.map(e=>e.toBase58()),s=this._buildArgs([i],n,"jsonParsed",r),o=Pm(await this._rpcRequest("getMultipleAccounts",s),tb(Gm(jm(Ub))));if("error"in o)throw new Ty(o.error,`failed to get info for accounts ${i}`);return o.result}async getMultipleAccountsInfoAndContext(e,t){const{commitment:n,config:r}=Jy(t),i=e.map(e=>e.toBase58()),s=this._buildArgs([i],n,"base64",r),o=Pm(await this._rpcRequest("getMultipleAccounts",s),tb(Gm(jm(Db))));if("error"in o)throw new Ty(o.error,`failed to get info for accounts ${i}`);return o.result}async getMultipleAccountsInfo(e,t){return(await this.getMultipleAccountsInfoAndContext(e,t)).value}async getStakeActivation(e,t,n){const{commitment:r,config:i}=Jy(t),s=this._buildArgs([e.toBase58()],r,void 0,{...i,epoch:null!=n?n:i?.epoch}),o=Pm(await this._rpcRequest("getStakeActivation",s),eb(Pb));if("error"in o)throw new Ty(o.error,`failed to get Stake Activation ${e.toBase58()}`);return o.result}async getProgramAccounts(e,t){const{commitment:n,config:r}=Jy(t),{encoding:i,...s}=r||{},o=this._buildArgs([e.toBase58()],n,i||"base64",{...s,...s.filters?{filters:Yy(s.filters)}:null}),a=await this._rpcRequest("getProgramAccounts",o),c=Gm(Mb),l=!0===s.withContext?Pm(a,tb(c)):Pm(a,eb(c));if("error"in l)throw new Ty(l.error,`failed to get accounts owned by program ${e.toBase58()}`);return l.result}async getParsedProgramAccounts(e,t){const{commitment:n,config:r}=Jy(t),i=this._buildArgs([e.toBase58()],n,"jsonParsed",r),s=Pm(await this._rpcRequest("getProgramAccounts",i),eb(Gm(Lb)));if("error"in s)throw new Ty(s.error,`failed to get accounts owned by program ${e.toBase58()}`);return s.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=ru.decode(n)}catch(e){throw new Error("signature must be base58 encoded: "+n)}return ly(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,i=!1;return{abortConfirmation:()=>{r&&(r(),r=void 0),null!=n&&(this.removeSignatureListener(n),n=void 0)},confirmationPromise:new Promise((s,o)=>{try{n=this.onSignature(t,(e,t)=>{n=void 0;const r={context:t,value:e};s({__type:by.PROCESSED,response:r})},e);const a=new Promise(e=>{null==n?e():r=this._onSubscriptionStateChange(n,t=>{"subscribed"===t&&e()})});(async()=>{if(await a,i)return;const n=await this.getSignatureStatus(t);if(i)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}i=!0,s({__type:by.PROCESSED,response:{context:r,value:c}})}})()}catch(e){o(e)}})}}async confirmTransactionUsingBlockHeightExceedanceStrategy({commitment:e,strategy:{abortSignal:t,lastValidBlockHeight:n,signature:r}}){let i=!1;const s=new Promise(t=>{const r=async()=>{try{return await this.getBlockHeight(e)}catch(e){return-1}};(async()=>{let e=await r();if(!i){for(;e<=n;){if(await Iy(1e3),i)return;if(e=await r(),i)return}t({__type:by.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,s]);if(e.__type!==by.PROCESSED)throw new ey(r);l=e.response}finally{i=!0,o()}return l}async confirmTransactionUsingDurableNonceStrategy({commitment:e,strategy:{abortSignal:t,minContextSlot:n,nonceAccountPubkey:r,nonceValue:i,signature:s}}){let o=!1;const a=new Promise(t=>{let s=i,a=null;const c=async()=>{try{const{context:t,value:i}=await this.getNonceAndContext(r,{commitment:e,minContextSlot:n});return a=t.slot,i?.nonce}catch(e){return s}};(async()=>{if(s=await c(),!o)for(;;){if(i!==s)return void t({__type:by.NONCE_INVALID,slotInWhichNonceDidAdvance:a});if(await Iy(2e3),o)return;if(s=await c(),o)return}})()}),{abortConfirmation:c,confirmationPromise:l}=this.getTransactionConfirmationPromise({commitment:e,signature:s}),u=this.getCancellationPromise(t);let d;try{const t=await Promise.race([u,l,a]);if(t.__type===by.PROCESSED)d=t.response;else{let r;for(;;){const e=await this.getSignatureStatus(s);if(null==e)break;if(!(e.context.slot<(t.slotInWhichNonceDidAdvance??n))){r=e;break}await Iy(400)}if(!r?.value)throw new ny(s);{const t=e||"finalized",{confirmationStatus:n}=r.value;switch(t){case"processed":case"recent":if("processed"!==n&&"confirmed"!==n&&"finalized"!==n)throw new ny(s);break;case"confirmed":case"single":case"singleGossip":if("confirmed"!==n&&"finalized"!==n)throw new ny(s);break;case"finalized":case"max":case"root":if("finalized"!==n)throw new ny(s)}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:by.TIMED_OUT,timeoutMs:r}),r)}),{abortConfirmation:i,confirmationPromise:s}=this.getTransactionConfirmationPromise({commitment:e,signature:t});let o;try{const e=await Promise.race([s,r]);if(e.__type!==by.PROCESSED)throw new ty(t,e.timeoutMs/1e3);o=e.response}finally{clearTimeout(n),i()}return o}async getClusterNodes(){const e=Pm(await this._rpcRequest("getClusterNodes",[]),eb(Gm(Jb)));if("error"in e)throw new Ty(e.error,"failed to get cluster nodes");return e.result}async getVoteAccounts(e){const t=this._buildArgs([],e),n=Pm(await this._rpcRequest("getVoteAccounts",t),Qb);if("error"in n)throw new Ty(n.error,"failed to get vote accounts");return n.result}async getSlot(e){const{commitment:t,config:n}=Jy(e),r=this._buildArgs([],t,void 0,n),i=Pm(await this._rpcRequest("getSlot",r),eb(Vm()));if("error"in i)throw new Ty(i.error,"failed to get slot");return i.result}async getSlotLeader(e){const{commitment:t,config:n}=Jy(e),r=this._buildArgs([],t,void 0,n),i=Pm(await this._rpcRequest("getSlotLeader",r),eb(Jm()));if("error"in i)throw new Ty(i.error,"failed to get slot leader");return i.result}async getSlotLeaders(e,t){const n=[e,t],r=Pm(await this._rpcRequest("getSlotLeaders",n),eb(Gm(Vy)));if("error"in r)throw new Ty(r.error,"failed to get slot leaders");return r.result}async getSignatureStatus(e,t){const{context:n,value:r}=await this.getSignatureStatuses([e],t);ly(1===r.length);return{context:n,value:r[0]}}async getSignatureStatuses(e,t){const n=[e];t&&n.push(t);const r=Pm(await this._rpcRequest("getSignatureStatuses",n),tv);if("error"in r)throw new Ty(r.error,"failed to get signature status");return r.result}async getTransactionCount(e){const{commitment:t,config:n}=Jy(e),r=this._buildArgs([],t,void 0,n),i=Pm(await this._rpcRequest("getTransactionCount",r),eb(Vm()));if("error"in i)throw new Ty(i.error,"failed to get transaction count");return i.result}async getTotalSupply(e){return(await this.getSupply({commitment:e,excludeNonCirculatingAccountsList:!0})).value.total}async getInflationGovernor(e){const t=this._buildArgs([],e),n=Pm(await this._rpcRequest("getInflationGovernor",t),vb);if("error"in n)throw new Ty(n.error,"failed to get inflation");return n.result}async getInflationReward(e,t,n){const{commitment:r,config:i}=Jy(n),s=this._buildArgs([e.map(e=>e.toBase58())],r,void 0,{...i,epoch:null!=t?t:i?.epoch}),o=Pm(await this._rpcRequest("getInflationReward",s),sb);if("error"in o)throw new Ty(o.error,"failed to get inflation reward");return o.result}async getInflationRate(){const e=Pm(await this._rpcRequest("getInflationRate",[]),wb);if("error"in e)throw new Ty(e.error,"failed to get inflation rate");return e.result}async getEpochInfo(e){const{commitment:t,config:n}=Jy(e),r=this._buildArgs([],t,void 0,n),i=Pm(await this._rpcRequest("getEpochInfo",r),Ab);if("error"in i)throw new Ty(i.error,"failed to get epoch info");return i.result}async getEpochSchedule(){const e=Pm(await this._rpcRequest("getEpochSchedule",[]),kb);if("error"in e)throw new Ty(e.error,"failed to get epoch schedule");const t=e.result;return new Ky(t.slotsPerEpoch,t.leaderScheduleSlotOffset,t.warmup,t.firstNormalEpoch,t.firstNormalSlot)}async getLeaderSchedule(){const e=Pm(await this._rpcRequest("getLeaderSchedule",[]),Sb);if("error"in e)throw new Ty(e.error,"failed to get leader schedule");return e.result}async getMinimumBalanceForRentExemption(e,t){const n=this._buildArgs([e],t),r=Pm(await this._rpcRequest("getMinimumBalanceForRentExemption",n),nv);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=Pm(await this._rpcRequest("getRecentPerformanceSamples",e?[e]:[]),xv);if("error"in t)throw new Ty(t.error,"failed to get recent performance samples");return t.result}async getFeeCalculatorForBlockhash(e,t){const n=this._buildArgs([e],t),r=Pm(await this._rpcRequest("getFeeCalculatorForBlockhash",n),Rv);if("error"in r)throw new Ty(r.error,"failed to get fee calculator");const{context:i,value:s}=r.result;return{context:i,value:null!==s?s.feeCalculator:null}}async getFeeForMessage(e,t){const n=jp(e.serialize()).toString("base64"),r=this._buildArgs([n],t),i=Pm(await this._rpcRequest("getFeeForMessage",r),tb(jm(Vm())));if("error"in i)throw new Ty(i.error,"failed to get fee for message");if(null===i.result)throw new Error("invalid blockhash");return i.result}async getRecentPrioritizationFees(e){const t=e?.lockedWritableAccounts?.map(e=>e.toBase58()),n=t?.length?[t]:[],r=Pm(await this._rpcRequest("getRecentPrioritizationFees",n),Eb);if("error"in r)throw new Ty(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}=Jy(e),r=this._buildArgs([],t,void 0,n),i=Pm(await this._rpcRequest("getLatestBlockhash",r),Cv);if("error"in i)throw new Ty(i.error,"failed to get latest blockhash");return i.result}async isBlockhashValid(e,t){const{commitment:n,config:r}=Jy(t),i=this._buildArgs([e],n,void 0,r),s=Pm(await this._rpcRequest("isBlockhashValid",i),_v);if("error"in s)throw new Ty(s.error,"failed to determine if the blockhash `"+e+"`is valid");return s.result}async getVersion(){const e=Pm(await this._rpcRequest("getVersion",[]),eb(fb));if("error"in e)throw new Ty(e.error,"failed to get version");return e.result}async getGenesisHash(){const e=Pm(await this._rpcRequest("getGenesisHash",[]),eb(Jm()));if("error"in e)throw new Ty(e.error,"failed to get genesis hash");return e.result}async getBlock(e,t){const{commitment:n,config:r}=Jy(t),i=this._buildArgsAtLeastConfirmed([e],n,void 0,r),s=await this._rpcRequest("getBlock",i);try{switch(r?.transactionDetails){case"accounts":{const e=Pm(s,wv);if("error"in e)throw e.error;return e.result}case"none":{const e=Pm(s,vv);if("error"in e)throw e.error;return e.result}default:{const e=Pm(s,bv);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:rb(n,e.message)},version:n}))}:null}}}catch(e){throw new Ty(e,"failed to get confirmed block")}}async getParsedBlock(e,t){const{commitment:n,config:r}=Jy(t),i=this._buildArgsAtLeastConfirmed([e],n,"jsonParsed",r),s=await this._rpcRequest("getBlock",i);try{switch(r?.transactionDetails){case"accounts":{const e=Pm(s,Av);if("error"in e)throw e.error;return e.result}case"none":{const e=Pm(s,kv);if("error"in e)throw e.error;return e.result}default:{const e=Pm(s,Ev);if("error"in e)throw e.error;return e.result}}}catch(e){throw new Ty(e,"failed to get block")}}async getBlockProduction(e){let t,n;if("string"==typeof e)n=e;else if(e){const{commitment:r,...i}=e;n=r,t=i}const r=this._buildArgs([],n,"base64",t),i=Pm(await this._rpcRequest("getBlockProduction",r),bb);if("error"in i)throw new Ty(i.error,"failed to get block production information");return i.result}async getTransaction(e,t){const{commitment:n,config:r}=Jy(t),i=this._buildArgsAtLeastConfirmed([e],n,void 0,r),s=Pm(await this._rpcRequest("getTransaction",i),Iv);if("error"in s)throw new Ty(s.error,"failed to get transaction");const o=s.result;return o?{...o,transaction:{...o.transaction,message:rb(o.version,o.transaction.message)}}:o}async getParsedTransaction(e,t){const{commitment:n,config:r}=Jy(t),i=this._buildArgsAtLeastConfirmed([e],n,"jsonParsed",r),s=Pm(await this._rpcRequest("getTransaction",i),Nv);if("error"in s)throw new Ty(s.error,"failed to get transaction");return s.result}async getParsedTransactions(e,t){const{commitment:n,config:r}=Jy(t),i=e.map(e=>({methodName:"getTransaction",args:this._buildArgsAtLeastConfirmed([e],n,"jsonParsed",r)}));return(await this._rpcBatchRequest(i)).map(e=>{const t=Pm(e,Nv);if("error"in t)throw new Ty(t.error,"failed to get transactions");return t.result})}async getTransactions(e,t){const{commitment:n,config:r}=Jy(t),i=e.map(e=>({methodName:"getTransaction",args:this._buildArgsAtLeastConfirmed([e],n,void 0,r)}));return(await this._rpcBatchRequest(i)).map(e=>{const t=Pm(e,Iv);if("error"in t)throw new Ty(t.error,"failed to get transactions");const n=t.result;return n?{...n,transaction:{...n.transaction,message:rb(n.version,n.transaction.message)}}:n})}async getConfirmedBlock(e,t){const n=this._buildArgsAtLeastConfirmed([e],t),r=Pm(await this._rpcRequest("getBlock",n),Sv);if("error"in r)throw new Ty(r.error,"failed to get confirmed block");const i=r.result;if(!i)throw new Error("Confirmed block "+e+" not found");const s={...i,transactions:i.transactions.map(({transaction:e,meta:t})=>{const n=new fy(e.message);return{meta:t,transaction:{...e,message:n}}})};return{...s,transactions:s.transactions.map(({transaction:e,meta:t})=>({meta:t,transaction:Ey.populate(e.message,e.signatures)}))}}async getBlocks(e,t,n){const r=this._buildArgsAtLeastConfirmed(void 0!==t?[e,t]:[e],n),i=Pm(await this._rpcRequest("getBlocks",r),eb(Gm(Vm())));if("error"in i)throw new Ty(i.error,"failed to get blocks");return i.result}async getBlockSignatures(e,t){const n=this._buildArgsAtLeastConfirmed([e],t,void 0,{transactionDetails:"signatures",rewards:!1}),r=Pm(await this._rpcRequest("getBlock",n),Tv);if("error"in r)throw new Ty(r.error,"failed to get block");const i=r.result;if(!i)throw new Error("Block "+e+" not found");return i}async getConfirmedBlockSignatures(e,t){const n=this._buildArgsAtLeastConfirmed([e],t,void 0,{transactionDetails:"signatures",rewards:!1}),r=Pm(await this._rpcRequest("getBlock",n),Tv);if("error"in r)throw new Ty(r.error,"failed to get confirmed block");const i=r.result;if(!i)throw new Error("Confirmed block "+e+" not found");return i}async getConfirmedTransaction(e,t){const n=this._buildArgsAtLeastConfirmed([e],t),r=Pm(await this._rpcRequest("getTransaction",n),Iv);if("error"in r)throw new Ty(r.error,"failed to get transaction");const i=r.result;if(!i)return i;const s=new fy(i.transaction.message),o=i.transaction.signatures;return{...i,transaction:Ey.populate(s,o)}}async getParsedConfirmedTransaction(e,t){const n=this._buildArgsAtLeastConfirmed([e],t,"jsonParsed"),r=Pm(await this._rpcRequest("getTransaction",n),Nv);if("error"in r)throw new Ty(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=Pm(e,Nv);if("error"in t)throw new Ty(t.error,"failed to get confirmed transactions");return t.result})}async getConfirmedSignaturesForAddress(e,t,n){let r={},i=await this.getFirstAvailableBlock();for(;!("until"in r)&&!(--t<=0||t<i);)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 s=await this.getSlot("finalized");for(;!("before"in r||++n>s);)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),i=Pm(await this._rpcRequest("getConfirmedSignaturesForAddress2",r),Fb);if("error"in i)throw new Ty(i.error,"failed to get confirmed signatures for address");return i.result}async getSignaturesForAddress(e,t,n){const r=this._buildArgsAtLeastConfirmed([e.toBase58()],n,void 0,t),i=Pm(await this._rpcRequest("getSignaturesForAddress",r),$b);if("error"in i)throw new Ty(i.error,"failed to get signatures for address");return i.result}async getAddressLookupTable(e,t){const{context:n,value:r}=await this.getAccountInfoAndContext(e,t);let i=null;return null!==r&&(i=new Wy({key:e,state:Wy.deserialize(r.data)})),{context:n,value:i}}async getNonceAndContext(e,t){const{context:n,value:r}=await this.getAccountInfoAndContext(e,t);let i=null;return null!==r&&(i=Ry.fromAccountData(r.data)),{context:n,value:i}}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=Pm(await this._rpcRequest("requestAirdrop",[e.toBase58(),t]),Bv);if("error"in n)throw new Ty(n.error,`airdrop to ${e.toBase58()} failed`);return n.result}async _blockhashWithExpiryBlockHeight(e){if(!e){for(;this._pollingBlockhash;)await Iy(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 Iy(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}=Jy(e),r=this._buildArgs([],t,"base64",n),i=Pm(await this._rpcRequest("getStakeMinimumDelegation",r),tb(Vm()));if("error"in i)throw new Ty(i.error,"failed to get stake minimum delegation");return i.result}async simulateTransaction(e,t,n){if("message"in e){const r=e.serialize(),i=pa.Buffer.from(r).toString("base64");if(Array.isArray(t)||void 0!==n)throw new Error("Invalid arguments");const s=t||{};s.encoding="base64","commitment"in s||(s.commitment=this.commitment),t&&"object"==typeof t&&"innerInstructions"in t&&(s.innerInstructions=t.innerInstructions);const o=[i,s],a=Pm(await this._rpcRequest("simulateTransaction",o),yb);if("error"in a)throw new Error("failed to simulate transaction: "+a.error.message);return a.result}let r;if(e instanceof Ey){let t=e;r=new Ey,r.feePayer=t.feePayer,r.instructions=e.instructions,r.nonceInfo=t.nonceInfo,r.signatures=t.signatures}else r=Ey.populate(e),r._message=r._json=void 0;if(void 0!==t&&!Array.isArray(t))throw new Error("Invalid arguments");const i=t;if(r.nonceInfo&&i)r.sign(...i);else{let e=this._disableBlockhashCaching;for(;;){const t=await this._blockhashWithExpiryBlockHeight(e);if(r.lastValidBlockHeight=t.lastValidBlockHeight,r.recentBlockhash=t.blockhash,!i)break;if(r.sign(...i),!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 s=r._compile(),o=s.serialize(),a=r._serialize(o).toString("base64"),c={encoding:"base64",commitment:this.commitment};if(n){const e=(Array.isArray(n)?n:s.nonProgramIds()).map(e=>e.toBase58());c.accounts={encoding:"base64",addresses:e}}i&&(c.sigVerify=!0),t&&"object"==typeof t&&"innerInstructions"in t&&(c.innerInstructions=t.innerInstructions);const l=[a,c],u=Pm(await this._rpcRequest("simulateTransaction",l),yb);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 Sy({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 i=e.signature.toString("base64");if(!this._blockhashInfo.transactionSignatures.includes(i)){this._blockhashInfo.transactionSignatures.push(i);break}t=!0}}const i=e.serialize();return await this.sendRawTransaction(i,n)}async sendRawTransaction(e,t){const n=jp(e).toString("base64");return await this.sendEncodedTransaction(n,t)}async sendEncodedTransaction(e,t){const n={encoding:"base64"},r=t&&t.skipPreflight,i=!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),i&&(n.preflightCommitment=i);const s=[e,n],o=Pm(await this._rpcRequest("sendTransaction",s),Dv);if("error"in o){let e;throw"data"in o.error&&(e=o.error.data.logs),new Sy({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:i}=n;try{this._setSubscription(e,{...n,state:"subscribing"});const t=await this._rpcWebSocket.call(i,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:i}=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(i,[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}=Pm(e,Kb);this._handleServerNotification(n,[t.value,t.context])}_makeSubscription(e,t){const n=this._nextClientSubscriptionId++,r=Fy([e.method,t]),i=this._subscriptionsByHash[r];return void 0===i?this._subscriptionsByHash[r]={...e,args:t,callbacks:new Set([e.callback]),state:"pending"}:i.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];ly(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:i}=Jy(n),s=this._buildArgs([e.toBase58()],r||this._commitment||"finalized","base64",i);return this._makeSubscription({callback:t,method:"accountSubscribe",unsubscribeMethod:"accountUnsubscribe"},s)}async removeAccountChangeListener(e){await this._unsubscribeClientSubscription(e,"account change")}_wsOnProgramAccountNotification(e){const{result:t,subscription:n}=Pm(e,Hb);this._handleServerNotification(n,[{accountId:t.value.pubkey,accountInfo:t.value.account},t.context])}onProgramAccountChange(e,t,n,r){const{commitment:i,config:s}=Jy(n),o=this._buildArgs([e.toBase58()],i||this._commitment||"finalized","base64",s||(r?{filters:Yy(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}=Pm(e,Ov);this._handleServerNotification(n,[t.value,t.context])}_wsOnSlotNotification(e){const{result:t,subscription:n}=Pm(e,qb);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}=Pm(e,Vb);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 i=t||this._commitment;if(i||n||r){let t={};n&&(t.encoding=n),i&&(t.commitment=i),r&&(t=Object.assign(t,r)),e.push(t)}return e}_buildArgsAtLeastConfirmed(e,t,n,r){const i=t||this._commitment;if(i&&!["confirmed","finalized"].includes(i))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}=Pm(e,zb);"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"),i=this._makeSubscription({callback:(e,n)=>{if("status"===e.type){t(e.result,n);try{this.removeSignatureListener(i)}catch(e){}}},method:"signatureSubscribe",unsubscribeMethod:"signatureUnsubscribe"},r);return i}onSignatureWithOptions(e,t,n){const{commitment:r,...i}={...n,commitment:n&&n.commitment||this._commitment||"finalized"},s=this._buildArgs([e],r,void 0,i),o=this._makeSubscription({callback:(e,n)=>{t(e,n);try{this.removeSignatureListener(o)}catch(e){}},method:"signatureSubscribe",unsubscribeMethod:"signatureUnsubscribe"},s);return o}async removeSignatureListener(e){await this._unsubscribeClientSubscription(e,"signature result")}_wsOnRootNotification(e){const{result:t,subscription:n}=Pm(e,Xb);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 Pv{constructor(e){this._keypair=void 0,this._keypair=e??Gp()}static generate(){return new Pv(Gp())}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=Hp(t);for(let e=0;e<32;e++)if(n[e]!==r[e])throw new Error("provided secretKey is invalid")}return new Pv({publicKey:n,secretKey:e})}static fromSeed(e){const t=Hp(e),n=new Uint8Array(64);return n.set(e),n.set(t,32),new Pv({publicKey:t,secretKey:n})}get publicKey(){return new Qp(this._keypair.publicKey)}get secretKey(){return new Uint8Array(this._keypair.secretKey)}}Object.freeze({CreateLookupTable:{index:0,layout:ku.struct([ku.u32("instruction"),By("recentSlot"),ku.u8("bumpSeed")])},FreezeLookupTable:{index:1,layout:ku.struct([ku.u32("instruction")])},ExtendLookupTable:{index:2,layout:ku.struct([ku.u32("instruction"),By(),ku.seq(iy(),ku.offset(ku.u32(),-8),"addresses")])},DeactivateLookupTable:{index:3,layout:ku.struct([ku.u32("instruction")])},CloseLookupTable:{index:4,layout:ku.struct([ku.u32("instruction")])}}),new Qp("AddressLookupTab1e1111111111111111111111111");const Fv=Object.freeze({RequestUnits:{index:0,layout:ku.struct([ku.u8("instruction"),ku.u32("units"),ku.u32("additionalFee")])},RequestHeapFrame:{index:1,layout:ku.struct([ku.u8("instruction"),ku.u32("bytes")])},SetComputeUnitLimit:{index:2,layout:ku.struct([ku.u8("instruction"),ku.u32("units")])},SetComputeUnitPrice:{index:3,layout:ku.struct([ku.u8("instruction"),By("microLamports")])}});class $v{constructor(){}static requestUnits(e){const t=Ny(Fv.RequestUnits,e);return new wy({keys:[],programId:this.programId,data:t})}static requestHeapFrame(e){const t=Ny(Fv.RequestHeapFrame,e);return new wy({keys:[],programId:this.programId,data:t})}static setComputeUnitLimit(e){const t=Ny(Fv.SetComputeUnitLimit,e);return new wy({keys:[],programId:this.programId,data:t})}static setComputeUnitPrice(e){const t=Ny(Fv.SetComputeUnitPrice,{microLamports:BigInt(e.microLamports)});return new wy({keys:[],programId:this.programId,data:t})}}var Kv;$v.programId=new Qp("ComputeBudget111111111111111111111111111111"),ku.struct([ku.u8("numSignatures"),ku.u8("padding"),ku.u16("signatureOffset"),ku.u16("signatureInstructionIndex"),ku.u16("publicKeyOffset"),ku.u16("publicKeyInstructionIndex"),ku.u16("messageDataOffset"),ku.u16("messageDataSize"),ku.u16("messageInstructionIndex")]),new Qp("Ed25519SigVerify111111111111111111111111111"),Kp.utils.isValidPrivateKey,ku.struct([ku.u8("numSignatures"),ku.u16("signatureOffset"),ku.u8("signatureInstructionIndex"),ku.u16("ethAddressOffset"),ku.u8("ethAddressInstructionIndex"),ku.u16("messageDataOffset"),ku.u16("messageDataSize"),ku.u8("messageInstructionIndex"),ku.blob(20,"ethAddress"),ku.blob(64,"signature"),ku.u8("recoveryId")]),new Qp("KeccakSecp256k11111111111111111111111111111"),new Qp("StakeConfig11111111111111111111111111111111");class Gv{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}}Kv=Gv,Gv.default=new Kv(0,0,Qp.default),Object.freeze({Initialize:{index:0,layout:ku.struct([ku.u32("instruction"),((e="authorized")=>ku.struct([iy("staker"),iy("withdrawer")],e))(),((e="lockup")=>ku.struct([ku.ns64("unixTimestamp"),ku.ns64("epoch"),iy("custodian")],e))()])},Authorize:{index:1,layout:ku.struct([ku.u32("instruction"),iy("newAuthorized"),ku.u32("stakeAuthorizationType")])},Delegate:{index:2,layout:ku.struct([ku.u32("instruction")])},Split:{index:3,layout:ku.struct([ku.u32("instruction"),ku.ns64("lamports")])},Withdraw:{index:4,layout:ku.struct([ku.u32("instruction"),ku.ns64("lamports")])},Deactivate:{index:5,layout:ku.struct([ku.u32("instruction")])},Merge:{index:7,layout:ku.struct([ku.u32("instruction")])},AuthorizeWithSeed:{index:8,layout:ku.struct([ku.u32("instruction"),iy("newAuthorized"),ku.u32("stakeAuthorizationType"),sy("authoritySeed"),iy("authorityOwner")])}}),new Qp("Stake11111111111111111111111111111111111111"),Object.freeze({InitializeAccount:{index:0,layout:ku.struct([ku.u32("instruction"),((e="voteInit")=>ku.struct([iy("nodePubkey"),iy("authorizedVoter"),iy("authorizedWithdrawer"),ku.u8("commission")],e))()])},Authorize:{index:1,layout:ku.struct([ku.u32("instruction"),iy("newAuthorized"),ku.u32("voteAuthorizationType")])},Withdraw:{index:3,layout:ku.struct([ku.u32("instruction"),ku.ns64("lamports")])},UpdateValidatorIdentity:{index:4,layout:ku.struct([ku.u32("instruction")])},AuthorizeWithSeed:{index:10,layout:ku.struct([ku.u32("instruction"),((e="voteAuthorizeWithSeedArgs")=>ku.struct([ku.u32("voteAuthorizationType"),iy("currentAuthorityDerivedKeyOwnerPubkey"),sy("currentAuthorityDerivedKeySeed"),iy("newAuthorized")],e))()])}}),new Qp("Vote111111111111111111111111111111111111111"),new Qp("Va1idator1nfo111111111111111111111111111111"),Qm({name:Jm(),website:zm(Jm()),details:zm(Jm()),iconUrl:zm(Jm()),keybaseUsername:zm(Jm())}),new Qp("Vote111111111111111111111111111111111111111"),ku.struct([iy("nodePubkey"),iy("authorizedWithdrawer"),ku.u8("commission"),ku.nu64(),ku.seq(ku.struct([ku.nu64("slot"),ku.u32("confirmationCount")]),ku.offset(ku.u32(),-8),"votes"),ku.u8("rootSlotValid"),ku.nu64("rootSlot"),ku.nu64(),ku.seq(ku.struct([ku.nu64("epoch"),iy("authorizedVoter")]),ku.offset(ku.u32(),-8),"authorizedVoters"),ku.struct([ku.seq(ku.struct([iy("authorizedPubkey"),ku.nu64("epochOfLastAuthorizedSwitch"),ku.nu64("targetEpoch")]),32,"buf"),ku.nu64("idx"),ku.u8("isEmpty")],"priorVoters"),ku.nu64(),ku.seq(ku.struct([ku.nu64("epoch"),ku.nu64("credits"),ku.nu64("prevCredits")]),ku.offset(ku.u32(),-8),"epochCredits"),ku.struct([ku.nu64("slot"),ku.nu64("timestamp")],"lastTimestamp")]);function Hv(e){return/^0x[a-fA-F0-9]{64}$/.test(e)}function Wv(e){const t=new Map;for(const n of e)t.set(un(n.symbol),n);return t}function qv(e,t,n){const r=function(e,t){return e.get(un(t))}(e,t);if(!r){throw Kt(`Token ${t} not supported for ${n}. Supported: ${Array.from(e.keys()).join(", ")}`,"tokenSymbol")}return r}function jv(e){if(null==e||!Hv(e))throw Ft("privateKey","a 0x-prefixed 64-character hex string (e.g., 0x1234...abcd)","Ethereum private key")}function Vv(e,t,n){return{symbol:e,quantity:t,decimals:n,contractAddress:null,isNative:!0}}function zv(e,t){return{symbol:e.symbol,quantity:t,decimals:e.decimals??18,contractAddress:e.contractAddress,isNative:!1}}function Xv(e,t){return{symbol:e.symbol,quantity:t,decimals:e.decimals??9,contractAddress:e.mintAddress,isNative:e.isNative??!1}}function Jv(e,t,n){const r=e.find(e=>e.symbol===t);if(!r){const r=e.map(e=>e.symbol).join(", ");throw Pt("tokenSymbol",`Unsupported ${n} token: ${t}. Supported: ${r}`)}return r}const Yv={Ethereum:"Ethereum bridging not configured. Provide ethereumPrivateKey in config.",Solana:"Solana bridging not configured. Provide solanaPrivateKey in config."};function Qv(e,t,n){if(void 0===e)throw Kt(n??Yv[t],`${t.toLowerCase()}Strategy`);return e}function Zv(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 ew="Token symbol resolution failed. This is an internal error - BridgeService should resolve tokenId to symbol before calling strategy.",tw="Bridge request ID missing from RequestTokenBridgeOut response",nw="BridgeTokenOut response missing transaction hash";function rw(e){if(void 0===e||""===e)throw Kt(ew,"tokenSymbol");return e}function iw(e,t){if(!n(e)){throw Ft(t??"address","a valid 0x-prefixed Ethereum address",e)}}function sw(e,t){try{return new Qp(e)}catch{throw Ft(t??"address","a valid Solana address (base58)",e)}}function ow(e){try{return new Qp(e)}catch{throw Ft("address","a valid Solana address (base58)",e)}}function aw(e){const t={};for(const[n,r]of Object.entries(e))void 0!==r&&(r&&"object"==typeof r&&!Array.isArray(r)?t[n]=aw(r):t[n]=r);return t}function cw(e,t){const n=Kn(e,-1);if(n<=0)throw new Error(`Invalid bridge amount for ${t}: "${e}". Amount must be a positive number.`);return n}var lw,uw,dw,hw,gw,fw;function mw(){return uw?lw:(uw=1,lw={space:"",cycles:!1,replacer:(e,t)=>t,stringify:JSON.stringify})}function pw(){return hw?dw:(hw=1,dw={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 yw(){if(fw)return gw;fw=1;const e=mw(),t=pw().isFunction,n=pw().isBoolean,r=pw().isObject,i=pw().isArray,s=pw().isRegex,o=pw().assign,a=pw().keys;return gw=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&&(m=l.compare,function(e){return function(t,n){const r={key:t,value:e[t]},i={key:n,value:e[n]};return m(r,i)}});var m;d||g(c);const p=[];return function e(t,n,o,c){const l=u?"\n"+new Array(c+1).join(u):"",m=u?": ":":";if(o=function(e){return null==e?e:s(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(i(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!==p.indexOf(o))return g("[Circular]");p.push(o)}const t=a(o).sort(f&&f(o)),n=[];for(let r=0;r<t.length;r++){const i=t[r],s=e(o,i,o[i],c+1);if(!s)continue;const a=g(i)+m+s;n.push(l+u+a)}return p.splice(p.indexOf(o),1),"{"+n.join(",")+l+"}"}}}({"":c},"",c,0)},gw}var bw=sa(yw());let vw=null;if("undefined"==typeof window&&"undefined"!=typeof require)try{vw=v}catch{}function ww(){if(void 0!==vw?.randomUUID)try{return vw.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 Ew={name:"GalaConnect",chainId:1},Aw=[{name:"destinationChainId",type:"uint256"},{name:"destinationChainTxFee",type:"destinationChainTxFee"},{name:"quantity",type:"string"},{name:"recipient",type:"string"},{name:"tokenInstance",type:"tokenInstance"},{name:"uniqueKey",type:"string"}],kw=[{name:"collection",type:"string"},{name:"category",type:"string"},{name:"type",type:"string"},{name:"additionalKey",type:"string"}],Sw=[{name:"collection",type:"string"},{name:"category",type:"string"},{name:"type",type:"string"},{name:"additionalKey",type:"string"},{name:"instance",type:"string"}],Tw=[{name:"name",type:"string"},{name:"symbol",type:"string"}],Iw={GalaTransaction:Aw,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:kw,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:Sw,externalQuoteToken:Tw,tokenInstance:Sw},Nw={GalaTransaction:Aw,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:kw,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:Tw,externalQuoteToken:Tw,externalCrossRateToken:Tw,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:Sw,tokenInstance:Sw};function Cw(e){return e?Nw:Iw}async function _w(e,t){const{wallet:n}=t,r=e.uniqueKey??`galaconnect-operation-${ww()}`,i="string"==typeof e.destinationChainId?Hn(e.destinationChainId,1):e.destinationChainId,s=function(e){const t={...e,galaDecimals:"string"==typeof e.galaDecimals?Hn(e.galaDecimals,0):e.galaDecimals,timestamp:"string"==typeof e.timestamp?Hn(e.timestamp,0):e.timestamp};if(e.galaExchangeRate&&(t.galaExchangeRate={...e.galaExchangeRate,timestamp:"string"==typeof e.galaExchangeRate.timestamp?Hn(e.galaExchangeRate.timestamp,0):e.galaExchangeRate.timestamp}),e.galaExchangeCrossRate){const n=e.galaExchangeCrossRate;t.galaExchangeCrossRate={...n,timestamp:"string"==typeof n.timestamp?Hn(n.timestamp,0):n.timestamp},n.baseTokenCrossRate&&(t.galaExchangeCrossRate.baseTokenCrossRate={...n.baseTokenCrossRate,timestamp:"string"==typeof n.baseTokenCrossRate.timestamp?Hn(n.baseTokenCrossRate.timestamp,0):n.baseTokenCrossRate.timestamp}),n.quoteTokenCrossRate&&(t.galaExchangeCrossRate.quoteTokenCrossRate={...n.quoteTokenCrossRate,timestamp:"string"==typeof n.quoteTokenCrossRate.timestamp?Hn(n.quoteTokenCrossRate.timestamp,0):n.quoteTokenCrossRate.timestamp})}return t}(e.destinationChainTxFee),o=Boolean(s.galaExchangeCrossRate),a={destinationChainId:i,destinationChainTxFee:aw(o?{...s,galaExchangeRate:void 0}:{...s,galaExchangeCrossRate:void 0}),quantity:e.quantity,recipient:e.recipient,tokenInstance:e.tokenInstance,uniqueKey:r},c=Cw(o),l=await n.signTypedData(Ew,c,a),u=`Ethereum Signed Message:\n${bw({domain:Ew,message:a,primaryType:"GalaTransaction",types:c}).length}`;return{...a,signature:l,prefix:u,types:c,domain:Ew}}async function xw(e,t){const{amount:n,recipientAddress:r,tokenSymbol:i}=e,{galaConnectClient:s,tokenMetadataResolver:o,ethereumWallet:a,destinationChainId:c,destinationChain:l,validateRecipientAddress:u}=t,d=rw(i);cw(n,d),u(r,"recipient");const h=await o.getTokenMetadata(d),g=await s.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}),m=await _w(f,{wallet:a}),p=function(e){if(void 0===e||""===e)throw Kt(tw,"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 s.requestBridgeOut(m)));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 Kt(nw,"transactionHash");return t}(await s.bridgeTokenOut({bridgeFromChannel:"asset",bridgeRequestId:p})),tokenSymbol:d,amount:n,feePaid:g.estimatedTotalTxFeeInGala,baseUrl:s.getBaseUrl()})}var Rw;!function(e){e[e.PENDING=0]="PENDING",e[e.SUBMITTED=1]="SUBMITTED",e[e.CONFIRMED=2]="CONFIRMED",e[e.PROCESSING=3]="PROCESSING",e[e.FINALIZING=4]="FINALIZING",e[e.COMPLETED=5]="COMPLETED",e[e.FAILED=6]="FAILED",e[e.DELIVERY_FAILED=7]="DELIVERY_FAILED"}(Rw||(Rw={}));const Bw=Rw.COMPLETED,Dw=Rw.FAILED,Mw=Rw.DELIVERY_FAILED;class Ow{constructor(e){if(this.lastTimestamp=0,this.pendingPromise=Promise.resolve(),this.chainLength=0,this.maxChainLength=1e3,e<=0)throw qt("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,i=Math.max(0,this.minIntervalMs-r);i>0&&await new Promise(e=>setTimeout(e,i)),this.lastTimestamp=Date.now();try{const n=await e();t(n)}catch(e){n(wt(e)?e:new Error(Et(e)))}}),this.chainLength++,this.chainLength>=this.maxChainLength){this.chainLength=0;const e=this.pendingPromise;this.pendingPromise=e.then(()=>Promise.resolve())}return r}}const Uw={maxRetries:3,initialDelayMs:1e3,maxDelayMs:3e4,backoffMultiplier:2,jitterFactor:.1},Lw=new Set([408,429,500,502,503,504]),Pw=[/ECONNRESET/i,/ECONNREFUSED/i,/ETIMEDOUT/i,/ENOTFOUND/i,/EAI_AGAIN/i,/socket hang up/i,/network/i,/timeout/i,/aborted/i];function Fw(e){if(null!=e&&"object"==typeof e){const t=e;if("number"==typeof t.status)return Lw.has(t.status);if("number"==typeof t.statusCode)return Lw.has(t.statusCode);const n=kt(e);if("string"==typeof n&&("ECONNRESET"===n||"ECONNREFUSED"===n||"ETIMEDOUT"===n||"ENOTFOUND"===n||"EAI_AGAIN"===n))return!0}const t=Et(e);return Pw.some(e=>e.test(t))}function $w(e,t){const n=t.initialDelayMs*Math.pow(t.backoffMultiplier,e-1),r=Math.min(n,t.maxDelayMs),i=r*t.jitterFactor*Math.random();return Math.floor(r+i)}function Kw(e){return new Promise(t=>setTimeout(t,e))}function Gw(e,t){return Qv(e.get("Ethereum"),"Ethereum",t)}function Hw(e,t){return Qv(e.get("Solana"),"Solana",t)}function Ww(e,t){return e??t.getWalletAddress()}async function qw(e,t,n,r,i){const s=await t.getTokenMetadata(r);return function(e){const t="string"==typeof e.timestamp?Hn(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:s.descriptor}))}async function jw(e,t){return function(e){const t=Hn(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===Bw,isFailed:t===Dw||t===Mw}}(await e.getBridgeStatus(t))}function Vw(e,t,n){try{const n=function(e,t){if(!sr(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,i,s,...o]=n;if(""===r||""===i||""===s)throw new Error("Collection, category, and type must be non-empty");const a=o.join(t);if(void 0===r||void 0===i||void 0===s||""===a)throw new Error("AdditionalKey must be non-empty");return{collection:r,category:i,type:s,additionalKey:a}}catch(r){throw function(e,t,n,r){const i=e?.split?.(t)??[],s=void 0!==n?` (${n})`:"";return new Rt(`Invalid ${"|"===t?"pipe":"dollar"}-delimited token: "${e}" (${i.length} parts)${s}. Expected format: "collection${t}category${t}type${t}additionalKey" (4 parts minimum). Received: [${i.map(e=>`"${e}"`).join(", ")}]. Error: ${Et(r)}`,"token",`INVALID_${"|"===t?"PIPE":"DOLLAR"}_DELIMITED_TOKEN`)}(e,t,n,r)}}function zw(e){return Vw(e,"|","pipe-delimited token")}function Xw(e){return sr(e)&&e.includes("|")}function Jw(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,i=t.type,s=t.additionalKey;return"string"==typeof n&&"string"==typeof r&&"string"==typeof i&&"string"==typeof s&&n.length>0&&r.length>0&&i.length>0&&s.length>0}function Qw(e){let t;if("string"==typeof e)t=zw(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:xo(t)}}function Zw(e,t){let n;try{n=Wn(e,"amount")}catch(t){throw zt("amount",`${e} (${Et(t)})`)}if(!n.isFinite())throw zt("amount",e);const r=n.multipliedBy(Vs(10).pow(t));if(!r.isInteger())throw zt("amount",`${e} (cannot be represented with ${t} decimals)`);return BigInt(r.toFixed(0))}function eE(e,t){return Vs(e.toString()).dividedBy(Vs(10).pow(t)).toFixed(t).replace(/\.?0+$/,"")}function tE(e,t=6){const n=Vs(e);if(!n.isFinite())return"0";if(n.abs().lt(1e-6)&&!Js(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+$/,"")}function nE(e,t){const n=Vs(e),r=Vs(t);return n.comparedTo(r)}class rE{constructor(e){this.cache=new Map,this.galaConnectClient=e.galaConnectClient}async getTokenMetadata(e){const t=dn(e),n=this.cache.get(t);if(n)return n;const r=Yo[t];if(void 0!==r)return this.cache.set(t,r),r;const i=await this.fetchFromApi(e);return this.cache.set(t,i),i}hasMetadata(e){const t=dn(e);return this.cache.has(t)||t in Yo}clearCache(){this.cache.clear()}async fetchFromApi(e){let t=e,n=await this.galaConnectClient.getBridgeConfigurations(t),r=n.find(e=>dn(e.symbol)===dn(t)&&e.verified);if(r||e.startsWith("G")||(t=`G${e}`,n=await this.galaConnectClient.getBridgeConfigurations(t),r=n.find(e=>dn(e.symbol)===dn(t)&&e.verified)),!r)throw new Error(`Unable to locate token metadata for ${e}`);return i={collection:r.collection,category:r.category,type:r.type,additionalKey:r.additionalKey},s=r.decimals,o=r.channel,{descriptor:{collection:i.collection,category:i.category,type:i.type,additionalKey:i.additionalKey},decimals:s,...void 0!==o?{channel:o}:{}};var i,s,o}}class iE 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 sE=Wo,oE="https://galachain-gateway-chain-platform-galachain-mainnet.gala.com",aE=12,cE=!0,lE=3,uE=1e3;class dE{constructor(e){this.baseUrl=e.baseUrl??sE,this.galachainBaseUrl=e.galachainBaseUrl??oE,this.walletAddress=e.walletAddress,this.rateLimiter=new Ow(e.requestsPerSecond??aE),this.defaultHeaders={"Content-Type":"application/json","X-Wallet-Address":this.walletAddress};const t=e.enableRetry??cE;this.retryOptions=t?{maxRetries:e.maxRetries??lE,initialDelayMs:e.retryInitialDelayMs??uE,...e.onRetry&&{onRetry:e.onRetry},shouldRetry:e=>Fw(e instanceof iE?{status:e.status}:e)}:null}getBaseUrl(){return this.baseUrl}async getBridgeConfigurations(e){return Ao(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?$n(e,{rawBody:e}):{message:"Failed to fetch bridge configurations"},new iE(n.status,"/v1/connect/bridge-configurations",t)}return(await n.json()).data.tokens},"GalaConnectClient.getBridgeConfigurations",void 0,e=>{if(e instanceof iE)throw e;throw Ht(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 Ao(async()=>{const r=n.baseUrl??this.baseUrl,i=new URL(e,r),s=n.skipWalletHeader?{"Content-Type":"application/json","X-Wallet-Address":""}:this.defaultHeaders,o=await this.request(i.toString(),{method:"POST",headers:s,body:JSON.stringify(t,(e,t)=>"bigint"==typeof t?t.toString():t)});if(!o.ok){const t=await o.text(),n=500,r=$n(t,{rawBody:t.slice(0,n)});throw new iE(o.status,e,r)}const a=await o.text();if(""!==a){const t=function(e){if(mn(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: ${Et(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 iE)throw e;throw Ht(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(),i=await this.safeParseJson(n);throw new iE(t,e,i)}}return r});return this.retryOptions?async function(e,t={}){const n={...Uw,...t},r=t.shouldRetry??(e=>Fw(e));let i;for(let s=1;s<=n.maxRetries+1;s++)try{return await e()}catch(e){if(i=e,s>n.maxRetries)break;if(!r(e,s))break;const o=$w(s,n);t.onRetry&&t.onRetry(e,s,o),await new Promise(e=>setTimeout(e,o))}throw i}(n,this.retryOptions):n()}async safeParseJson(e){const t=await e.text();try{return JSON.parse(t)}catch{return{rawBody:t}}}}class hE{async waitForCompletion(e,t={}){const{pollInterval:n=15e3,timeout:r=27e5,onStatusUpdate:i}=t,s=Date.now();for(;;){const t=await this.getStatus(e);if(i&&i(t),t.status===Rw.COMPLETED||t.status===Rw.FAILED||t.status===Rw.DELIVERY_FAILED)return t;if(wn(s)>r)throw Gt(`Bridge transaction timed out after ${r}ms. Last status: ${t.status}`,e,"TIMEOUT");await new Promise(e=>setTimeout(e,n))}}}class gE extends hE{constructor(e,t){super(),this.galaConnectClient=e,this.tokenConfigs=t}async getStatus(e){return jw(this.galaConnectClient,e)}getSupportedTokens(){return e=this.tokenConfigs,Array.from(e.keys());var e}isTokenSupported(e){return function(e,t){return e.has(un(t))}(this.tokenConfigs,e)}}async function fE(e,t,...n){const r=e[t];return"function"==typeof r?await r(...n):await e.getFunction(t)(...n)}class mE extends gE{constructor(e){const n=e.tokenConfigs??Xo;super(e.galaConnectClient,Wv(n)),this.network="Ethereum",this.galaChainWalletAddress=e.galaChainWalletAddress,jv(e.ethereumPrivateKey);const i=e.ethereumRpcUrl??"https://ethereum.publicnode.com";this.ethereumProvider=new r(i),this.ethereumWallet=new t(e.ethereumPrivateKey,this.ethereumProvider),this.ethereumWalletAddress=e.ethereumWalletAddress??this.ethereumWallet.address,this.ethereumBridgeContract=e.ethereumBridgeContract??"0x3F98b5A26EF3f04E1DA3B0B41dD350E8C8F3A7c2",this.tokenMetadataResolver=new rE({galaConnectClient:this.galaConnectClient})}async estimateFee(e,t){return qw(this.galaConnectClient,this.tokenMetadataResolver,"Ethereum",e)}async bridgeOut(e){return xw(e,{galaConnectClient:this.galaConnectClient,tokenMetadataResolver:this.tokenMetadataResolver,ethereumWallet:this.ethereumWallet,destinationChainId:Bo.ETHEREUM,destinationChain:"Ethereum",validateRecipientAddress:iw})}async bridgeIn(n){const{amount:r,sourcePrivateKey:s,recipientAddress:o,tokenSymbol:a}=n,c=rw(a);if(cw(r,c),void 0!==s&&""!==s&&!Hv(s))throw Ft("sourcePrivateKey","0x-prefixed 64-character hex string",s.slice(0,10)+"...");const l=void 0!==s&&""!==s?new t(s,this.ethereumProvider):this.ethereumWallet,u=qv(this.tokenConfigs,c,"Ethereum bridge"),d=await this.tokenMetadataResolver.getTokenMetadata(c),h=new i(u.contractAddress,Qo,l),g=await fE(h,"decimals"),f=Hn("string"==typeof g||"number"==typeof g||"bigint"==typeof g?g:void 0,18),m=Zw(r,f),p=await fE(h,"balanceOf",l.address);if("bigint"!=typeof p)throw new Error("Ethereum balance response was not a bigint");const y=p;if(y<m){throw Kt(`Insufficient ${c} balance on Ethereum. Needed ${eE(m,f)}, have ${eE(y,f)}`,"amount")}const b=function(t){const n=new xr;if("client"===n.detectFormat(t))return t;const r=n.normalizeInput(t);if(null==r)throw Ft("address","a valid GalaChain address (eth|0x{40-hex}, 0x{40-hex}, or {40-hex})","GalaChain address");const i=n.extractHex(r);return`eth|${e("0x"+i).slice(2)}`}(o??this.galaChainWalletAddress);return Zv({fromChain:"Ethereum",transactionHash:(await this.executeBridgeDeposit({wallet:l,tokenContract:h,tokenConfig:u,amountBaseUnits:m,decimals:f,recipient:b,metadata:d})).txHash,tokenSymbol:c,amount:r,baseUrl:this.galaConnectClient.getBaseUrl()})}isValidAddress(e){return ir.ETH_ADDRESS.test(e)}getWalletAddress(){return this.ethereumWalletAddress}async getEthereumTokenBalance(e,t){const n=qv(this.tokenConfigs,e,"Ethereum"),r=t??this.ethereumWalletAddress;iw(r);const s=new i(n.contractAddress,Qo,this.ethereumProvider),o=await fE(s,"balanceOf",r);if("bigint"!=typeof o)throw new Error("Ethereum balance response was not a bigint");return eE(o,n.decimals??18)}async getEthereumNativeBalance(e){const t=e??this.ethereumWalletAddress;iw(t);return eE(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 Ft("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>=mE.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: ${Et(e)}`}}}async executeBridgeDeposit(e){const t=new i(this.ethereumBridgeContract,Zo,e.wallet),n=(new TextEncoder).encode(e.recipient);let r;r=e.tokenConfig.bridgeUsesPermit?await this.bridgeWithPermit(e.wallet,e.tokenContract,e.tokenConfig,t,e.amountBaseUnits,n):await this.bridgeWithApproval(e.wallet,e.tokenContract,t,e.tokenConfig,e.amountBaseUnits,n);if(!await r.wait())throw Kt("Bridge transaction receipt not available","ethereumRpcUrl");await Kw(3e4);const s={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:eE(e.amountBaseUnits,e.decimals),tokenInstance:s,fromChain:"Ethereum",toChain:"GC",hash:r.hash}),{txHash:r.hash}}async bridgeWithPermit(e,t,n,r,i,o){const a=await this.ethereumProvider.getNetwork(),c=await fE(t,"name");if("string"!=typeof c)throw new Error("Ethereum token name response was not a string");const l=c,u=await fE(t,"nonces",e.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 e.signTypedData({name:l,version:"1",chainId:Hn(a.chainId,1),verifyingContract:n.contractAddress},{Permit:[{name:"owner",type:"address"},{name:"spender",type:"address"},{name:"value",type:"uint256"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}]},{owner:e.address,spender:this.ethereumBridgeContract,value:i,nonce:d,deadline:h}),f=s.from(g);return await fE(r,"bridgeOutWithPermit",n.contractAddress,i,Bo.GALA_CHAIN,o,h,f.v,f.r,f.s)}async bridgeWithApproval(e,t,n,r,i,s){const o=await fE(t,"allowance",e.address,this.ethereumBridgeContract);if("bigint"!=typeof o)throw new Error("Ethereum allowance response was not a bigint");if(BigInt(o)<i){const e=await fE(t,"approve",this.ethereumBridgeContract,i);await e.wait()}return await fE(n,"bridgeOut",r.contractAddress,i,0,Bo.GALA_CHAIN,s)}}mE.ETHEREUM_FINALITY_THRESHOLD=12;const pE=new Qp("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA");new Qp("TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb");const yE=new Qp("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL");new Qp("So11111111111111111111111111111111111111112"),new Qp("9pan9bMn5HatX4EJdBwg9VgCa7Uz5HL8N1m5D3NdXejP");const bE=e=>({decode:e.decode.bind(e),encode:e.encode.bind(e)});var vE,wE={};function EE(){if(vE)return wE;return vE=1,Object.defineProperty(wE,"__esModule",{value:!0}),wE.toBigIntLE=function(e){{const t=Buffer.from(e);t.reverse();const n=t.toString("hex");return 0===n.length?BigInt(0):BigInt(`0x${n}`)}},wE.toBigIntBE=function(e){{const t=e.toString("hex");return 0===t.length?BigInt(0):BigInt(`0x${t}`)}},wE.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}},wE.toBufferBE=function(e,t){{const n=e.toString(16);return Buffer.from(n.padStart(2*t,"0").slice(0,2*t),"hex")}},wE}var AE=EE();const kE=(SE=8,e=>{const t=ku.blob(SE,e),{encode:n,decode:r}=bE(t),i=t;return i.decode=(e,t)=>{const n=r(e,t);return AE.toBigIntLE(Buffer.from(n))},i.encode=(e,t,r)=>{const i=AE.toBufferLE(e,SE);return n(i,t,r)},i});var SE;const TE=e=>{const t=ku.blob(32,e),{encode:n,decode:r}=bE(t),i=t;return i.decode=(e,t)=>{const n=r(e,t);return new Qp(n)},i.encode=(e,t,r)=>{const i=e.toBuffer();return n(i,t,r)},i};var IE;!function(e){e[e.Uninitialized=0]="Uninitialized",e[e.Initialized=1]="Initialized",e[e.Frozen=2]="Frozen"}(IE||(IE={}));const NE=ku.struct([TE("mint"),TE("owner"),kE("amount"),ku.u32("delegateOption"),TE("delegate"),ku.u8("state"),ku.u32("isNativeOption"),kE("isNative"),kE("delegatedAmount"),ku.u32("closeAuthorityOption"),TE("closeAuthority")]);NE.span;var CE=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),i=r.charCodeAt(0);if(255!==t[i])throw new TypeError(r+" is ambiguous");t[i]=n}const n=e.length,r=e.charAt(0),i=Math.log(n)/Math.log(256),s=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 s=0,o=0,a=0;for(;e[s]===r;)o++,s++;const c=(e.length-s)*i+1>>>0,l=new Uint8Array(c);for(;s<e.length;){const r=e.charCodeAt(s);if(r>255)return;let i=t[r];if(255===i)return;let o=0;for(let e=c-1;(0!==i||o<a)&&-1!==e;e--,o++)i+=n*l[e]>>>0,l[e]=i%256>>>0,i=i/256>>>0;if(0!==i)throw new Error("Non-zero carry");a=o,s++}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 i=0,o=0,a=0;const c=t.length;for(;a!==c&&0===t[a];)a++,i++;const l=(c-a)*s+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(i);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 _E(e,t,n,r,i){const[s]=Qp.findProgramAddressSync([t.toBuffer(),r.toBuffer(),e.toBuffer()],i);return s}class xE extends gE{constructor(e){const n=e.tokenConfigs??Jo;super(e.galaConnectClient,Wv(n)),this.network="Solana",this.solanaBridgeAccountCache=new Map,this.galaChainWalletAddress=e.galaChainWalletAddress,jv(e.ethereumPrivateKey);const i=new r("https://ethereum.publicnode.com");this.ethereumWallet=new t(e.ethereumPrivateKey,i);const s=e.solanaRpcUrl??"https://api.mainnet-beta.solana.com";let o;this.solanaConnection=new Lv(s,"confirmed");try{o=CE.decode(e.solanaPrivateKeyBase58)}catch{throw Ft("solanaPrivateKeyBase58","base58-encoded string",e.solanaPrivateKeyBase58.slice(0,20)+"...")}if(64!==o.length)throw Ft("solanaPrivateKeyBase58","64 bytes when decoded",`${o.length} bytes`);this.solanaKeypair=Pv.fromSecretKey(o);const a=e.solanaBridgeProgram??"AaE4dTnL75XqgUJpdxBKg6vS9sTJgBPJwBQRVhD29WwS";this.solanaBridgeProgramId=new Qp(a),[this.solanaBridgeTokenAuthority]=Qp.findProgramAddressSync([Buffer.from("bridge_token_authority")],this.solanaBridgeProgramId),[this.solanaBridgeConfigPda]=Qp.findProgramAddressSync([Buffer.from("configv1")],this.solanaBridgeProgramId),[this.solanaNativeBridgePda]=Qp.findProgramAddressSync([Buffer.from("native_sol_bridge")],this.solanaBridgeProgramId),this.tokenMetadataResolver=new rE({galaConnectClient:this.galaConnectClient})}async estimateFee(e,t){return qw(this.galaConnectClient,this.tokenMetadataResolver,"Solana",e)}async bridgeOut(e){return xw(e,{galaConnectClient:this.galaConnectClient,tokenMetadataResolver:this.tokenMetadataResolver,ethereumWallet:this.ethereumWallet,destinationChainId:Bo.SOLANA,destinationChain:"Solana",validateRecipientAddress:sw})}async bridgeIn(e){const{amount:t,sourcePrivateKey:n,recipientAddress:r,tokenSymbol:i}=e,s=rw(i);cw(t,s);let o=this.solanaKeypair;if(void 0!==n&&""!==n){let e;try{e=CE.decode(n)}catch{throw Ft("sourcePrivateKey","base58-encoded string",n.slice(0,20)+"...")}if(64!==e.length)throw Ft("sourcePrivateKey","64 bytes when decoded",`${e.length} bytes`);o=Pv.fromSecretKey(e)}const a=qv(this.tokenConfigs,s,"Solana bridge"),c=await this.tokenMetadataResolver.getTokenMetadata(s),l=Zw(t,c.decimals),u=r??this.galaChainWalletAddress;return Zv({fromChain:"Solana",transactionHash:await this.executeSolanaBridgeOut({keypair:o,tokenConfig:a,metadata:c,amountBaseUnits:l,recipient:u,amount:t}),tokenSymbol:s,amount:t,baseUrl:this.galaConnectClient.getBaseUrl()})}isValidAddress(e){try{return new Qp(e),!0}catch{return!1}}getWalletAddress(){return this.solanaKeypair.publicKey.toBase58()}async getSolanaTokenBalance(e,t){const n=qv(this.tokenConfigs,e,"Solana");if(n.isNative)return this.getSolanaNativeBalance(t);const r=t??this.solanaKeypair.publicKey.toBase58(),i=ow(r),s=_E(new Qp(n.mintAddress),i,0,pE,yE);try{const e=await async function(e,t,n,r){const i=await e.getAccountInfo(t);if(!i)throw new Error(`could not find account ${t.toBase58()}`);if(!i.owner.equals(r))throw new Error(`account owner mismatch: expected ${r.toBase58()}, got ${i.owner.toBase58()}`);return{amount:NE.decode(i.data).amount,decimals:0}}(this.solanaConnection,s,0,pE),t=n.decimals??8;return eE(e.amount,t)}catch(t){if(wt(t)&&t.message.includes("could not find")){return eE(0n,n.decimals??8)}throw Kt(`Failed to fetch ${e} balance for ${r}: ${Et(t)}`,`${e}Account`)}}async getSolanaNativeBalance(e){const t=ow(e??this.solanaKeypair.publicKey.toBase58()),n=await this.solanaConnection.getBalance(t,"confirmed");return eE(BigInt(n),9)}async requestDevnetAirdrop(e=1,t){Xn(e,1e-5,2,"amount");const n=void 0!==t&&""!==t?ow(t):this.solanaKeypair.publicKey,r=this.solanaConnection.rpcEndpoint;if(!r.includes("devnet"))throw Kt(`Solana devnet faucet only available on devnet. Current RPC: ${r}. Ensure SDK is configured with environment='stage' for devnet access.`,"solanaRpcUrl");const i=Math.floor(1e9*e);return await this.solanaConnection.requestAirdrop(n,i)}async getSolanaTransactionStatus(e){if(!sr(e))throw Ft("signature","a non-empty string");if(!/^[1-9A-HJ-NP-Za-km-z]{80,90}$/.test(e))throw Ft("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 Qp(e.tokenConfig.mintAddress),n=Boolean(e.tokenConfig.isNative),r=n?void 0:await this.getSolanaBridgeAccounts(t),i=n?void 0:_E(t,e.keypair.publicKey,0,pE,yE),s=Buffer.from(e.recipient,"utf8"),o=Buffer.alloc(8);o.writeBigUInt64LE(e.amountBaseUnits);const a=Buffer.alloc(4);a.writeUInt32LE(s.length);const c=n?this.buildNativeBridgeInstruction(e.keypair.publicKey,o,a,s):this.buildTokenBridgeInstruction(e.keypair.publicKey,i,t,r,o,a,s),l=new Ey;l.add($v.setComputeUnitPrice({microLamports:375e3}),$v.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 i=1;i<=n;i++){try{const s=await this.solanaConnection.getLatestBlockhash("confirmed");e.recentBlockhash=s.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:s.blockhash,lastValidBlockHeight:s.lastValidBlockHeight},"confirmed"),o}catch(e){const t=wt(e)?e.message.toLowerCase():"";if(!(t.includes("block height exceeded")||t.includes("blockhash not found")||t.includes("expired")))throw e;const s=await this.solanaConnection.getSignatureStatuses([o]);if("confirmed"===s.value[0]?.confirmationStatus||"finalized"===s.value[0]?.confirmationStatus)return o;r=new Error(`Transaction ${o} not confirmed - block height exceeded (attempt ${i}/${n})`)}}catch(e){r=wt(e)?e:new Error(Et(e));const t=r.message.toLowerCase();if(!(t.includes("block height exceeded")||t.includes("blockhash not found")||t.includes("timeout")||t.includes("expired"))||i===n)throw r}const s=Math.min(1e3*Math.pow(2,i-1),5e3);await Kw(s)}throw r??new Error("Transaction confirmation failed after max retries")}buildNativeBridgeInstruction(e,t,n,r){const i=Buffer.concat([ea.BRIDGE_OUT_NATIVE,t,n,r]);return new wy({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:My.programId,isSigner:!1,isWritable:!1}],data:i})}buildTokenBridgeInstruction(e,t,n,r,i,s,o){const a=Buffer.concat([ea.BRIDGE_OUT,i,s,o]);return new wy({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:My.programId,isSigner:!1,isWritable:!1},{pubkey:pE,isSigner:!1,isWritable:!1}],data:a})}async getSolanaBridgeAccounts(e){const t=e.toBase58(),n=this.solanaBridgeAccountCache.get(t);if(n)return n;const[r]=Qp.findProgramAddressSync([Buffer.from("mint_lookup_v1"),e.toBuffer()],this.solanaBridgeProgramId),i=await this.solanaConnection.getAccountInfo(r,"confirmed");if(!i)throw Kt(`Mint lookup account not found for ${r.toBase58()}`,"solanaBridgeProgram");if(!i.owner.equals(this.solanaBridgeProgramId))throw Kt("Mint lookup account owner mismatch for Solana bridge program","solanaBridgeProgram");if(i.data.length<40)throw Kt("Mint lookup account data is unexpectedly short","solanaBridgeProgram");const s={mintLookup:r,tokenBridge:new Qp(i.data.slice(8,40)),bridgeTokenAccount:_E(e,this.solanaBridgeTokenAuthority,0,pE,yE)};return this.solanaBridgeAccountCache.set(t,s),s}}const RE={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"}},BE={solanaBridgeProgram:"AaE4dTnL75XqgUJpdxBKg6vS9sTJgBPJwBQRVhD29WwS",rateLimit:12,pollInterval:15e3,pollTimeout:27e5};class DE{static normalizeGalaChainAddress(e){const t=new xr;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 Kt(`Invalid GalaChain address format: ${e}`,"galaChainWalletAddress");const i=t.extractHex(r);return`eth|${DE.checksumAddress(i)}`}static checksumAddress(e){const t=e.toLowerCase(),n=Cr(o(a(t)));let r="";for(let e=0;e<t.length;e++){const i=t[e],s=n[e];void 0!==i&&void 0!==s&&parseInt(s,16)>=8?r+=i.toUpperCase():r+=i??""}return r}constructor(e){const t=DE.normalizeGalaChainAddress(e.galaChainWalletAddress),n=e.environment??"prod",r=Co["stage"===n?"stage":"prod"],i=RE[n],s={galaConnectBaseUrl:e.galaConnectBaseUrl??r.dexApiBaseUrl,galaChainApiBaseUrl:e.galaChainApiBaseUrl??r.gatewayBaseUrl,ethereumRpcUrl:e.ethereumRpcUrl??i.ethereum,solanaRpcUrl:e.solanaRpcUrl??i.solana,ethereumBridgeContract:e.ethereumBridgeContract??zo(n),solanaBridgeProgram:e.solanaBridgeProgram??BE.solanaBridgeProgram,rateLimit:e.rateLimit??BE.rateLimit,pollInterval:e.pollInterval??BE.pollInterval,pollTimeout:e.pollTimeout??BE.pollTimeout,galaChainWalletAddress:t,ethereumPrivateKey:e.ethereumPrivateKey,environment:n};this.config=e.solanaPrivateKey?{...s,solanaPrivateKey:e.solanaPrivateKey}:s,this.galaConnectClient=new dE({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=Vo(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 mE(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:Jo};this.strategies.set("Solana",new xE(e))}}async resolveTokenSymbol(e,t){return Ao(async()=>{if(!this.bridgeableTokenService)throw Kt("BridgeableTokenService is required for tokenId resolution. Pass bridgeableTokenService in BridgeServiceConfig or use the SDK's bridge methods.","bridgeableTokenService");const n=Qw(e).stringified,r="Ethereum"===t?"ETHEREUM":"SOLANA",i=await this.bridgeableTokenService.getTokenByTokenId(n,r);if(!i){throw Kt([`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 i.symbol},"BridgeService.resolveTokenSymbol")}async estimateBridgeFee(e){return Ao(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 Ao(async()=>{const t=await this.resolveTokenSymbol(e.tokenId,e.destinationChain),n=this.getStrategy(e.destinationChain);if(!n.isValidAddress(e.recipientAddress))throw Kt(`Invalid recipient address for ${e.destinationChain}: ${e.recipientAddress}`,"recipientAddress");if(!n.isTokenSupported(t))throw Kt(`Token ${t} is not supported for ${e.destinationChain} bridging`,"tokenSymbol");return n.bridgeOut({...e,tokenSymbol:t})},"BridgeService.bridgeOut")}async bridgeIn(e){return Ao(async()=>{const t=await this.resolveTokenSymbol(e.tokenId,e.sourceChain),n=this.getStrategy(e.sourceChain);if(!n.isTokenSupported(t))throw Kt(`Token ${t} is not supported for ${e.sourceChain} bridging`,"tokenSymbol");return n.bridgeIn({...e,tokenSymbol:t})},"BridgeService.bridgeIn")}async getBridgeStatus(e,t){return Ao(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=wt(e)?e:new Error(Et(e))}const i=this.strategies.get("Solana");if(i)try{return await i.getStatus(e)}catch(e){r=wt(e)?e:new Error(Et(e))}const s=r?` (last error: ${r.message})`:"";throw Gt(`Unable to get status for transaction ${e}${s}`,e)},"BridgeService.getBridgeStatus")}async waitForBridgeCompletion(e,t){return Ao(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 i=this.strategies.get("Solana");if(i)return i.waitForCompletion(e,n);throw Gt(`Unable to wait for transaction ${e}: no suitable strategy found`,e)},"BridgeService.waitForBridgeCompletion")}getSupportedBridgeTokens(e){const t=[],n=Vo(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 Jo){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 Ao(async()=>Gw(this.strategies).getEthereumTokenBalance(e,t),"BridgeService.getEthereumTokenBalance")}async getEthereumNativeBalance(e){return Ao(async()=>Gw(this.strategies).getEthereumNativeBalance(e),"BridgeService.getEthereumNativeBalance")}async getSolanaTokenBalance(e,t){return Ao(async()=>Hw(this.strategies).getSolanaTokenBalance(e,t),"BridgeService.getSolanaTokenBalance")}async getSolanaNativeBalance(e){return Ao(async()=>Hw(this.strategies).getSolanaNativeBalance(e),"BridgeService.getSolanaNativeBalance")}async fetchEthereumWalletTokenBalance(e,t){return Ao(async()=>{const n=Gw(this.strategies),r=Jv(Vo(this.config.environment),e,"Ethereum"),i=Ww(t,n);return zv(r,await n.getEthereumTokenBalance(e,i))},"BridgeService.fetchEthereumWalletTokenBalance")}async fetchEthereumWalletNativeBalance(e){return Ao(async()=>{const t=Gw(this.strategies),n=Ww(e,t);return Vv("ETH",await t.getEthereumNativeBalance(n),18)},"BridgeService.fetchEthereumWalletNativeBalance")}async fetchSolanaWalletTokenBalance(e,t){return Ao(async()=>{const n=Hw(this.strategies),r=Jv(Jo,e,"Solana"),i=Ww(t,n);return Xv(r,await n.getSolanaTokenBalance(e,i))},"BridgeService.fetchSolanaWalletTokenBalance")}async fetchSolanaWalletNativeBalance(e){return Ao(async()=>{const t=Hw(this.strategies),n=Ww(e,t);return Vv("SOL",await t.getSolanaNativeBalance(n),9)},"BridgeService.fetchSolanaWalletNativeBalance")}async requestSolanaDevnetAirdrop(e,t){return Ao(async()=>Hw(this.strategies).requestDevnetAirdrop(e,t),"BridgeService.requestSolanaDevnetAirdrop")}async getSolanaTransactionStatus(e){return Ao(async()=>Hw(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 Ao(async()=>Gw(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 Ao(async()=>{const t=Gw(this.strategies),n=Ww(e,t),r=Vo(this.config.environment),[i,...s]=await Promise.all([t.getEthereumNativeBalance(n),...r.map(async e=>zv(e,await t.getEthereumTokenBalance(e.symbol,n)))]);return{address:n,native:Vv("ETH",i,18),tokens:s,timestamp:Date.now()}},"BridgeService.fetchEthereumWalletAllBalances")}async fetchSolanaWalletAllBalances(e){return Ao(async()=>{const t=Hw(this.strategies),n=Ww(e,t),[r,...i]=await Promise.all([t.getSolanaNativeBalance(n),...Jo.map(async e=>Xv(e,await t.getSolanaTokenBalance(e.symbol,n)))]);return{address:n,native:Vv("SOL",r,9),tokens:i,timestamp:Date.now()}},"BridgeService.fetchSolanaWalletAllBalances")}getStrategy(e){const t=this.strategies.get(e);if(!t)throw Kt(`Bridging to ${e} is not configured. `+("Solana"===e?"Please provide solanaPrivateKey in config.":"Please check your configuration."),`${e.toLowerCase()}PrivateKey`);return t}}var ME,OE;!function(e){e.PROCESSED="PROCESSED",e.COMPLETED="COMPLETED",e.SUCCESS="SUCCESS",e.FAILED="FAILED",e.ERROR="ERROR",e.PROCESSING="PROCESSING",e.PENDING="PENDING"}(ME||(ME={})),function(e){e.PENDING="pending",e.PROCESSING="processing",e.COMPLETED="completed",e.FAILED="failed",e.TIMEOUT="timeout"}(OE||(OE={}));const UE={[ME.PROCESSED]:OE.COMPLETED,[ME.COMPLETED]:OE.COMPLETED,[ME.SUCCESS]:OE.COMPLETED,[ME.FAILED]:OE.FAILED,[ME.ERROR]:OE.FAILED,[ME.PROCESSING]:OE.PROCESSING,[ME.PENDING]:OE.PENDING},LE="7.0.0-beta.3",PE={DEFAULT_PAGE_SIZE:50,MAX_PAGE_SIZE:1e3,SAFETY_MAX_PAGES:1e4,DEFAULT_OFFSET:0,DEFAULT_LIMIT:10,BACKEND_MAX_PAGE_SIZE:20},FE={MAX_CONCURRENT_FETCHES:5,PAGE_SIZE:50,BACKEND_PAGE_SIZE:20};function $E(e,t=PE.DEFAULT_LIMIT){if("number"!=typeof e||!Number.isInteger(e)||e<0)throw Vt("offset","a non-negative integer",e);return Yn(t,"limit"),{offset:e,limit:t}}function KE(e,t,n){if("number"!=typeof e||!Number.isInteger(e)||e<0)throw Vt("offset","a non-negative integer",e);Yn(t,"limit")}function GE(e,t=1,n=PE.BACKEND_MAX_PAGE_SIZE){return Math.max(t,Math.min(n,Math.ceil(e??t)))}function HE(e,t){if("number"!=typeof e||!Number.isInteger(e))throw Vt("total","a non-negative integer",e);if(e<0)throw Wt("total",0,1/0,e);if("number"!=typeof t||!Number.isInteger(t))throw Vt("limit","a non-negative integer",t);if(t<0)throw Wt("limit",0,1/0,t);return 0===t?1:0===e?0:Math.ceil(e/t)}function WE(e,t,n){if("number"!=typeof e||!Number.isInteger(e))throw Vt("offset","a non-negative integer",e);if(e<0)throw Wt("offset",0,1/0,e);return e+t<n}function qE(e){return"string"==typeof e?e:"number"==typeof e||"boolean"==typeof e||"bigint"==typeof e?String(e):JSON.stringify(e)??""}function jE(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 VE(e,t,n){for(const r of n){const n=t[r];null!=n&&""!==n&&(e[r]=qE(n))}return e}const zE="x-api-key";class XE extends Sr{constructor(e,t,n,r=!1,i){super(e,r),this.adminApiKey=t??void 0,this.jwtAuth=n,this.userApiKey=i??void 0}setJwtAuth(e){this.jwtAuth=e}validateTokenName(e,t){!function(e,t){if(!sr(e))throw Pt("tokenName","Token name");const n=ln(e);if(!t.PATTERN.test(n))throw Ft("tokenName",`${t.MIN_LENGTH}-${t.MAX_LENGTH} alphanumeric characters`,"Token name")}(e,t)}validateRequiredString(e,t,n){!function(e,t,n){if(!sr(e))throw Pt(t,n)}(e,t,n)}validateOptionalString(e,t,n,r){!function(e,t,n,r){if(null!=e){if("string"!=typeof e)throw Vt(t,"string",typeof e,n);if(e.length>r)throw jt(t,r,e.length,n)}}(e,t,n,r)}validateOptionalNumber(e,t,n,r,i,s,o){!function(e,t,n,r,i){if(null!=e){if("number"!=typeof e)throw Vt(t,"number",typeof e,n);if(e<r||e>i)throw Wt(t,r,i,e,n)}}(e,t,n,r,i)}validateOptionalDate(e,t,n){!function(e,t,n){if(null!=e&&!vn(e))throw Ft(t,"a valid ISO 8601 date string",n)}(e,t,n)}validatePositiveInteger(e,t,n){Ar(e,t,n)}validateStatusFilter(e,t,n="status"){kr(e,t,n)}buildPaginationParams(e,t){return jE(e,t)}addOptionalFilterParams(e,t,n){return VE(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 Mt("Admin API key required for this operation. Set streamAdminApiKey in SDK config.");return{[zE]:this.adminApiKey}}getJwtHeaders(){if(!this.jwtAuth)throw new Mt("JWT authentication required. Call sdk.login() first.");return this.jwtAuth.getJwtHeaders()}hasJwtAuth(){return this.jwtAuth?.isValid()??!1}hasAdminApiKey(){return void 0!==this.adminApiKey&&""!==this.adminApiKey}getDualAuthHeaders(){return void 0!==this.adminApiKey&&""!==this.adminApiKey?this.getAdminHeaders():this.getJwtHeaders()}getMultiAuthHeaders(){return void 0!==this.userApiKey&&""!==this.userApiKey?{[zE]:this.userApiKey}:this.getJwtHeaders()}extractData(e){return en(e,"Backend request failed",!0),nn(e,"No data in backend response")}extractDataOrNull(e){return en(e,"Backend request failed",!1),e.data??null}async toggleFeature(e,t,n){this.validateTokenName(e,n);const r=this.buildEndpoint(t,{tokenName:e}),i=await this.http.post(r,{},this.getAdminHeaders()),s=this.extractData(i);return{enabled:s.enabled,tokenName:s.tokenName??ln(e)}}}class JE extends XE{constructor(e,t,n,r=!1,i){super(e,t,n,r,i)}async getSettings(){return{settings:(await this.http.get(st.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(st.UPDATE_SETTINGS,t,this.getDualAuthHeaders())).settings}}async getModeration(e){this.validatePositiveInteger(e.flagId,"flagId","Flag ID");const t=st.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=st.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(st.GET_STATUS,{},this.getDualAuthHeaders())).status}}}const YE={MODERATOR:"MODERATOR",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MANAGER:"MANAGER",OWNER:"OWNER"},QE=ur(YE),ZE={MANAGE_COMMENTS:"MANAGE_COMMENTS",MANAGE_CHAT:"MANAGE_CHAT",BAN_USERS:"BAN_USERS",UNBAN_USERS:"UNBAN_USERS",MANAGE_SIMULCAST:"MANAGE_SIMULCAST",GET_STREAM_KEY:"GET_STREAM_KEY",STOP_STREAM:"STOP_STREAM",RESET_STREAM_KEY:"RESET_STREAM_KEY",START_STREAM:"START_STREAM",DELETE_RECORDINGS:"DELETE_RECORDINGS",MANAGE_STREAM_SETTINGS:"MANAGE_STREAM_SETTINGS"},eA={MANAGE_COMMUNITY:"MANAGE_COMMUNITY",MANAGE_STREAM:"MANAGE_STREAM",MANAGE_SETTINGS:"MANAGE_SETTINGS",MANAGE_RECORDINGS:"MANAGE_RECORDINGS",VIEW_ANALYTICS:"VIEW_ANALYTICS"},tA=Object.values(eA);function nA(e){return QE.includes(e)}function rA(e){const t=[];return void 0===e.role||null===e.role?t.push("Role is required"):nA(e.role)||t.push(`Invalid role. Must be one of: ${QE.join(", ")}`),sA(e,t),t}function iA(e){const t=[];return["role","description","delegateAllTokens","tokenNames","expiresAt","tokenPermissions"].some(t=>void 0!==e[t])||t.push("At least one field must be provided for update"),void 0===e.role||nA(e.role)||t.push(`Invalid role. Must be one of: ${QE.join(", ")}`),sA(e,t,!0),t}function sA(e,t,n=!1){const r=t.length;if(Nt(t,()=>{wr(e.description,"description",255)}),t.length>r&&(t[r]="Description must be 255 characters or less"),void 0!==e.tokenNames){const n=t.length;Nt(t,()=>{if(!Array.isArray(e.tokenNames))throw Vt("tokenNames","an array",e.tokenNames);if(!e.tokenNames.every(e=>"string"==typeof e))throw Vt("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;Nt(t,()=>{Er(e.expiresAt,"expiresAt")}),t.length>n&&(t[n]="expiresAt must be a valid ISO 8601 date string")}}function oA(e){if(void 0!==e.pageSize&&("number"!=typeof e.pageSize||e.pageSize<1||e.pageSize>Sn))throw Vt("pageSize",`number between 1 and ${Sn}`,typeof e.pageSize);if(void 0!==e.cursor&&("string"!=typeof e.cursor||""===e.cursor.trim()))throw Vt("cursor","non-empty string",typeof e.cursor)}const aA={[YE.MODERATOR]:1,[YE.TECHNICAL_PRODUCER]:1,[YE.MANAGER]:2,[YE.OWNER]:3};function cA(e,t){return e===YE.MANAGER?t!==YE.OWNER:e===YE.OWNER||e===t}class lA extends Sr{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),en(n,"API key operation failed",!0),e.data}validateApiKeyId(e){this.validatePositiveInteger(e,"id","API key ID")}async create(e){const t=rA(e);if(t.length>0)throw new Rt(t.join("; "),"options","VALIDATION_FAILED");this.logger.debug("Creating API key",{role:e.role,delegateAllTokens:e.delegateAllTokens});const n={role:e.role};void 0!==e.description&&(n.description=e.description),void 0!==e.delegateAllTokens&&(n.delegateAllTokens=e.delegateAllTokens),void 0!==e.tokenNames&&e.tokenNames.length>0&&(n.tokenNames=e.tokenNames),void 0!==e.expiresAt&&(n.expiresAt=e.expiresAt),void 0!==e.tokenPermissions&&(n.tokenPermissions=e.tokenPermissions);const r=await this.http.post(ge.CREATE,n,this.getJwtHeaders()),i=this.extractData(r);return this.logger.debug("API key created",{id:i.id,keyPrefix:i.keyPrefix}),i}async findAll(e={}){oA(e),this.logger.debug("Listing API keys",e);const t=jE(e,Sn),n=await this.http.get(ge.LIST,t,this.getJwtHeaders()),r=this.extractData(n);return this.logger.debug("Listed API keys",{count:r.apiKeys.length,total:r.pageInfo.totalCount}),r}async findOne(e){this.validateApiKeyId(e),this.logger.debug("Getting API key",{id:e});const t=ge.GET.replace(":id",String(e)),n=await this.http.get(t,{},this.getJwtHeaders()),r=this.extractData(n);return this.logger.debug("Got API key",{id:r.id,keyPrefix:r.keyPrefix}),r}async update(e,t){this.validateApiKeyId(e);const n=iA(t);if(n.length>0)throw new Rt(n.join("; "),"options","VALIDATION_FAILED");this.logger.debug("Updating API key",{id:e,options:t});const r={};void 0!==t.role&&(r.role=t.role),void 0!==t.description&&(r.description=t.description),void 0!==t.delegateAllTokens&&(r.delegateAllTokens=t.delegateAllTokens),void 0!==t.tokenNames&&(r.tokenNames=t.tokenNames),void 0!==t.expiresAt&&(r.expiresAt=t.expiresAt),void 0!==t.tokenPermissions&&(r.tokenPermissions=t.tokenPermissions);const i=ge.UPDATE.replace(":id",String(e)),s=await this.http.patch(i,r,this.getJwtHeaders()),o=this.extractData(s);return this.logger.debug("Updated API key",{id:o.id,keyPrefix:o.keyPrefix}),o}async revoke(e){this.validateApiKeyId(e),this.logger.debug("Revoking API key",{id:e});const t=ge.REVOKE.replace(":id",String(e));await this.http.delete(t,{},this.getJwtHeaders()),this.logger.debug("API key revoked",{id:e})}getRoles(){return[...QE]}}const uA={ONE_HOUR:3600,ONE_DAY:86400,ONE_WEEK:604800,ONE_MONTH:2592e3},dA={VIEWERS:"viewers",CHAT_PARTICIPANTS:"chat_participants"},hA=lr(dA),gA=pr([{field:"id",type:"number"},{field:"userAddress",type:"string"},{field:"bannedBy",type:"string"},{field:"createdAt",type:"string"},{field:"isPermanent",type:"boolean"},{field:"tokenName",type:"string",nullable:!0},{field:"reason",type:"string",nullable:!0},{field:"expiresAt",type:"string",nullable:!0}]),fA=pr([{field:"userAddress",type:"string"},{field:"isPermanent",type:"boolean"}]),mA=pr([{field:"userAddress",type:"string"}]),pA=pr([{field:"tokenName",type:"string"},{field:"action",type:"string",validator:e=>"CHAT_MESSAGE"===e||"COMMENT"===e||"REACTION"===e}]);function yA(e){return null==e||""===e||"string"==typeof e&&(!vr(e)&&e.length<=_n.BAN_REASON.MAX_LENGTH)}function bA(e){return!!ar(e)||"number"==typeof e&&(e>=Rn&&e<=Bn)}function vA(e){if(!sr(e.userAddress))throw Pt("userAddress");if(!yA(e.reason))throw new Rt(`reason must be at most ${_n.BAN_REASON.MAX_LENGTH} characters`,"reason","TOO_LONG");if(!bA(e.durationSeconds))throw new Rt(`durationSeconds must be between ${Rn} and ${Bn} seconds`,"durationSeconds","OUT_OF_RANGE")}class wA extends XE{constructor(e,t,n,r=!1,i){super(e,t,n,r,i)}async createBan(e){!function(e){hr(e.tokenName,"tokenName",En),vA(e)}(e);const t=this.buildEndpoint(ie,{tokenName:e.tokenName}),n=EA(e),r=await this.http.post(t,n,this.getMultiAuthHeaders());return{ban:this.extractData(r),tokenName:ln(e.tokenName)}}async removeBan(e){!function(e){if(hr(e.tokenName,"tokenName",En),!sr(e.userAddress))throw Pt("userAddress")}(e);const t=this.buildEndpoint(ae,{tokenName:e.tokenName,userAddress:e.userAddress}),n=await this.http.delete(t,{},this.getMultiAuthHeaders()),r=this.extractDataOrNull(n);return{removed:r?.removed??!0,tokenName:ln(e.tokenName),userAddress:r?.userAddress??e.userAddress.toLowerCase()}}async listBans(e){!function(e){hr(e.tokenName,"tokenName",En),cr(0,void 0,Sn,e.pageSize)}(e);const t=this.buildEndpoint(se,{tokenName:e.tokenName}),n=this.buildPaginationParams(e,Sn);this.addOptionalFilterParams(n,e,["search","name","userAddress"]);const r=await this.http.get(t,n,this.getMultiAuthHeaders()),i=this.extractData(r);return{items:i.bans,pageInfo:i.pageInfo}}async getBanStatus(e){!function(e){if(hr(e.tokenName,"tokenName",En),!sr(e.userAddress))throw Pt("userAddress")}(e);const t=this.buildEndpoint(oe,{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:ln(e.tokenName),userAddress:e.userAddress.toLowerCase()}}async getActiveUsers(e){!function(e){if(hr(e.tokenName,"tokenName",En),void 0!==e.type&&!hA(e.type))throw new Rt(`type must be one of: ${Object.values(dA).join(", ")}`,"type",xt.INVALID_VALUE)}(e);const t=this.buildEndpoint(ce,{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){vA(e)}(e);const t=EA(e),n=await this.http.post(le,t,this.getDualAuthHeaders());return{ban:this.extractData(n)}}async removeGlobalBan(e){!function(e){if(!sr(e.userAddress))throw Pt("userAddress")}(e);const t=this.buildEndpoint(he,{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){cr(0,void 0,Sn,e.pageSize)}(t);const n=this.buildPaginationParams(t,Sn);this.addOptionalFilterParams(n,t,["search","name","userAddress"]);const r=await this.http.get(ue,n,this.getDualAuthHeaders()),i=this.extractData(r);return{items:i.bans,pageInfo:i.pageInfo}}async getGlobalBan(e){!function(e){if(!sr(e.userAddress))throw Pt("userAddress")}(e);const t=this.buildEndpoint(de,{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 EA(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 AA(e,t={}){const{maxPages:n=1e4,logger:r,pageSize:i=20,concurrency:s=1,startPage:o=1}=t,a=[];let c=o;const l=o+n-1;let u=!0,d=0;if(s<=1)for(;u&&c<=l;){r&&r.debug(`Auto-pagination: fetching page ${c} with limit ${i}`);const t=await e(c,i);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=${s}`);u&&c<=l;){const t=[];for(let e=0;e<s&&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,i).catch(e=>{const n=e,s=n.statusCode??n.response?.status??n.originalError?.response?.status??n.status??n.launchpadError?.statusCode;if(400===s||404===s)return r&&r.debug(`Auto-pagination: page ${t} returned ${s} (end of pagination)`,{statusCode:s}),{items:[],total:0,totalPages:0,page:t,limit:i,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 kA(e){if("string"==typeof e){if(!Xw(e))throw new Rt(`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=zw(t.slice(0,4).join("|")),n=t[4]??"0";return{...e,instance:n.length>0?n:"0"}}return{...zw(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 Rt("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 Rt("Invalid tokenId object format. All fields (collection, category, type, additionalKey) are required","tokenId","INVALID_TOKEN_ID_FORMAT");return{...e,instance:"0"}}throw new Rt(`Invalid tokenId type: ${typeof e}. Expected string, TokenClassKey, or TokenInstanceKey`,"tokenId","INVALID_TOKEN_ID_TYPE")}function SA(e){return function(e){try{if(!sr(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,i,s,...o]=n;if(""===r||""===i||""===s)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===i||void 0===s||""===c||void 0===c)throw new Error("AdditionalKey must be non-empty");return{collection:r,category:i,type:s,additionalKey:c}}catch(t){throw new Rt(`Invalid vault address: "${e}". Expected format: "service|Token$Unit$SYMBOL$additionalKey$launchpad". Error: ${Et(t)}`,"vaultAddress","INVALID_VAULT_ADDRESS_FORMAT")}}(e)}function TA(e){return{...SA(e),instance:"0"}}function IA(e){return SA(e).type}function NA(e){return xo(kA(e))}var CA=Object.freeze({__proto__:null,extractTokenSymbolFromVault:IA,isTokenClassKeyStrict:Yw,normalizeToTokenInstanceKey:kA,normalizeTokenIdToString:NA,parseVaultAddressToTokenClassKey:SA,parseVaultAddressToTokenInstance:TA});class _A{constructor(e,t=!1,n){this.dexApiHttp=e,this.logger=new gn({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()),i=this.buildApiParams(n),s=await this.dexApiHttp.request({method:"GET",url:this.getApiEndpoint(),params:{...i,pageSize:r,offset:e}});if(ar(s)||!Array.isArray(s.tokens))throw new Rt("Invalid API response: expected { tokens: array }","response","INVALID_RESPONSE");return{items:this.transformApiResponse(s.tokens),rawCount:s.tokens.length}}async autoPaginateFetch(e){return async function(e,t){const{maxLimit:n,logger:r,maxPages:i=1e4}=t,s=[];let o=0,a=!0,c=0;for(;a&&c<i;){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}s.push(...t.items),a=t.rawCount===n,o+=n,c++,r&&r.debug(`Auto-pagination (offset): fetched ${s.length} items so far (hasMore=${String(a)})`)}return c>=i&&r&&r.warn(`Auto-pagination (offset): exceeded maxPages limit of ${i}, stopping`),r&&r.debug(`Auto-pagination (offset): completed with total items: ${s.length}`),s}(async(t,n)=>this.executePaginatedRequest(t,n,e),{maxLimit:this.getMaxLimit(),logger:this.logger})}handleError(e,t){throw Ht(e,t,this.logger)}}class xA extends Tr{constructor(e=!1){super(e),this.primaryIndex=new Map,this.secondaryIndex=new Map,this.fetchTimestamps=new Map}normalizeKey(e){return un(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 i=this.normalizeKey(this.extractSecondaryKey(e));r.set(i,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 i=this.normalizeKey(this.extractSecondaryKey(e));r.set(i,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={},i={};for(const t of e)r[t]=0;for(const[e,s]of this.primaryIndex){t.push(e),n+=s.size,r[e]=s.size;const o=this.fetchTimestamps.get(e);void 0!==o&&(i[e]=o)}return{networks:t,totalItems:n,itemsByNetwork:r,fetchTimestamps:i}}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 RA=["ETHEREUM","SOLANA"];class BA extends xA{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(RA);return{...e,totalTokens:e.totalItems,tokensByNetwork:e.itemsByNetwork}}}class DA extends _A{constructor(e,t=!1){super(e,t,"BridgeableTokenService"),this.cache=new BA(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),i={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&&(i.ethereumContractAddress=t.contractAddress),void 0!==t?.symbol&&(i.ethereumSymbol=t.symbol),void 0!==t?.allowanceStorageSlot&&(i.ethereumAllowanceSlot=t.allowanceStorageSlot),void 0!==n?.contractAddress&&(i.solanaContractAddress=n.contractAddress),void 0!==n?.symbol&&(i.solanaSymbol=n.symbol),void 0!==e.image&&(i.image=e.image),void 0!==e.description&&(i.description=e.description),i})}async fetchBridgeableTokensByNetwork(e){const{network:t,offset:n=0,limit:r=this.getDefaultLimit()}=e,i=Math.min(r,this.getMaxLimit());return this.logger.debug(`Fetching bridgeable tokens for ${t} (offset=${n}, limit=${i})`),Ao(async()=>{const e=(await this.executePaginatedRequest(n,i,{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 Ao(async()=>{const t=await async function(e){const{network:t,cache:n,fetchFn:r,logger:i,itemTypeName:s="items"}=e;if(n.has(t)){const e=n.getAll(t);return i&&i.debug(`Returning ${e.length} cached ${s} for ${t}`),{items:e,fetchedAt:n.getFetchTimestamp(t)??Date.now(),itemCount:e.length}}i&&i.debug(`Fetching all ${s} 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=NA(t);this.cache.has(n)||await this.fetchAllBridgeableTokensByNetwork(n);const i=this.cache.getByTokenId(n,r),s=void 0!==i,o=s?"ETHEREUM"===n?i.ethereumContractAddress:i.solanaContractAddress:void 0,a={isBridgeable:s,tokenSymbol:i?.symbol??zw(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 MA(e){return{maxAcceptableReverseBondingCurveFee:Vn(e.maxAcceptableReverseBondingCurveFee)}}const OA={BuyNativeDto:class extends w{constructor(e,t,n="0",r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=Vn(t),this.expectedToken=zn(n),this.extraFees=MA(r)}},BuyExactDto:class extends w{constructor(e,t,n,r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=zn(t),this.expectedNativeToken=Vn(n),this.extraFees=MA(r)}},SellExactDto:class extends w{constructor(e,t,n="0",r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=zn(t),this.expectedNativeToken=Vn(n),this.extraFees=MA(r)}},SellNativeDto:class extends w{constructor(e,t,n,r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=Vn(t),this.expectedToken=zn(n),this.extraFees=MA(r)}}};function UA(e,t,n){let r;Xn(t,0,1,"slippageToleranceFactor");try{r=Wn(e,"expectedAmount")}catch{throw new Error(`Invalid expected amount: ${e}. Must be a valid number`)}if(0===t)return e;const i=r.multipliedBy(t);let s;switch(n){case"buy-native":case"sell-exact":s=r.minus(i);break;case"buy-exact":case"sell-native":s=r.plus(i);break;default:throw new Error(`Unknown operation type: ${n}`)}return Vs(s).isLessThan(0)&&(s=Vs(0)),zs(s)}function LA(e){return`${e}-${Date.now()}_${b().replace(/-/gu,"").substring(0,26)}`}function PA(){return LA("galaconnect-operation")}function FA(e,t){const n={[e]:[]},r=new Set;function i(e){const t=n[e];if(void 0===t)throw new Error("Missing EIP-712 type "+e);return t}function s(e,t,o,a=!1){if(void 0===t)return;if(Array.isArray(t)){const n=s(e,t[0],o,!0);return a||(r.add(e),i(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,i]of Object.entries(t)){if(r.has(n))throw new Error("Name collisions not yet supported");s(n,i,e)}return a||(r.add(e),i(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),i(o).push({name:e,type:c})),c}for(const[n,r]of Object.entries(t))s(n,r,e);return n}const $A={name:"GalaChain"},KA={name:"ethereum",chainId:1};function GA(e){if("string"!=typeof e)throw new Error("Wallet returned an invalid signature");return e}function HA(e,t,n,r){return{...e,signature:t,types:n,domain:r}}class WA extends f{constructor(e){super(e),this.typedDataClient=new A(e)}async signTypedData(e,t){const n=await this.typedDataClient.sign(e,t,k.SIGN_TYPED_DATA),r=FA(e,t);return{...HA(t,n.signature,r,$A)}}}class qA extends g{async signTypedData(e,t){const n=FA(e,t),r=E(t),i={domain:KA,types:n,message:{...t,prefix:r},Primary_type:e};return HA(t,GA(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(i),this.walletAddress]})),n,KA)}}class jA extends h{constructor(e,t){super(e,t),this.typedDataProvider=e}async signTypedData(e,t){const n=this.typedDataProvider,r=await n.getNetwork(),i={name:r.name,chainId:Number(r.chainId)},s=FA(e,t),o=E(t),a=await n.getSigner();return HA(t,GA(await a.signTypedData(i,s,{...t,prefix:o})),s,i)}}function VA(e){if(!sr(e))throw new Error("Invalid token format: token must be a non-empty string");return e.replace(/\|/g,"$")}function zA(e){return Vw(e,"$","dollar-delimited token")}class XA extends Tr{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(),i=`$service$${n.toStringKey()}$launchpad`,s=`$tokenBalance$${n.toStringKey()}$${e}`,o=`$tokenBalance$${n.toStringKey()}$${e}`,a=`$tokenBalance$${r.toStringKey()}$${e}`,c=[i,s,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=Et(e);throw new Rt(`Failed to generate stringsInstructions: ${t}`,"vaultAddress","INVALID_VAULT_ADDRESS")}}createTokenInstance(e){const t=new S;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 S;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(!sr(e))throw Pt("vaultAddress","Vault address");try{const t=IA(e);return this.logger.debug("🔍 Extracted token symbol:",{vaultAddress:e,tokenSymbol:t}),t}catch(e){if(e instanceof Rt)throw Ft("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad");throw e}}validateVaultAddress(e){if(!sr(e))throw Pt("vaultAddress","Vault address");if(!e.startsWith("service|Token$Unit$"))throw Ft("vaultAddress",'starting with "service|Token$Unit$"');if(!e.endsWith("$launchpad"))throw Ft("vaultAddress",'ending with "$launchpad"');const t=function(e){if(!sr(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 Ft("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 Ft("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 zA(e)}catch(e){if(e instanceof Rt)throw Ft("stringKey","format: collection$category$type$additionalKey (4 parts)");throw e}}}function JA(e){return"object"==typeof e&&null!==e?e:void 0}class YA extends Sr{constructor(e,t,n=!1,r,i,s=.05,o=.01){if(super(e,n),this.tokenResolver=t,this._walletProvider=r,this.userAddress=i,this.defaultSlippageToleranceFactor=s,this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor=o,this.bundleEndpoint="/bundle",null!==this._walletProvider&&void 0!==this._walletProvider&&null!=i){const e=JA(this._walletProvider),t=e?.privateKey;"string"==typeof t?this.signer=new WA(t):function(e){const t=JA(e);return"function"==typeof t?.request}(this._walletProvider)&&void 0!==this.userAddress&&(this.signer=new jA(this._walletProvider,this.userAddress)),this.tokenKeyService=new XA(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 sn(()=>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:Zt(n),error:n.error}),this.handleBundleResponse(n))}catch(e){if(e instanceof Rt)return{success:!1,error:Et(e)};throw e}}validateBundleData(e){if(null==e)throw Pt("bundleData","Bundle data");if(null===e.signedDto||void 0===e.signedDto)throw Pt("signedDto","Signed DTO");if(!sr(e.method))throw Pt("method","Method name");if(!Array.isArray(e.stringsInstructions))throw Ft("stringsInstructions","an array of resource tracking strings");if(0===e.stringsInstructions.length)throw new Rt("stringsInstructions cannot be empty","stringsInstructions","EMPTY_ARRAY");const t=["BuyWithNative","BuyExactToken","SellExactToken","SellWithNative"];if(!t.includes(e.method))throw Ft("method",`one of: ${t.join(", ")}`);e.stringsInstructions.forEach((e,t)=>{if(!sr(e))throw new Rt(`stringsInstructions[${t}] must be a non-empty string`,`stringsInstructions[${t}]`,"INVALID_INSTRUCTION");if(!Jw(e))throw new Rt(`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=tn(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(St(e)&&null!==e.response&&void 0!==e.response){const t=tn(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 Et(e)??"Unknown bundle transaction error"}async getBundlerTransactionResult(e){try{if(!sr(e))throw Pt("transactionId","Transaction ID");let t;this.logger.debug("🔍 Checking bundler transaction result:",e);try{t=await sn(()=>this.http.get(`${this.bundleEndpoint}?id=${e}`),{errorContext:"Failed to get bundler transaction result",logger:this.logger})}catch(e){return{success:!1,error:this.formatErrorMessage(e)}}return null==t?{success:!1,error:"No response from bundler transaction query"}:(this.logger.debug("📊 Bundler transaction result:",t),{success:!0,data:t})}catch(e){if(e instanceof Rt)return{success:!1,error:Et(e)};throw e}}async cancelTransaction(e){try{if(!sr(e))throw Pt("transactionId","Transaction ID");let t;this.logger.debug("🚫 Cancelling transaction:",e);try{t=await sn(()=>this.http.delete(`${this.bundleEndpoint}/${e}`),{errorContext:"Failed to cancel transaction",logger:this.logger})}catch(e){return{success:!1,error:this.formatErrorMessage(e)}}return null==t?{success:!1,error:"No response from transaction cancellation"}:(this.logger.debug("🗑️ Transaction cancellation response:",t),{success:!0,data:t})}catch(e){if(e instanceof Rt)return{success:!1,error:Et(e)};throw e}}async getHealthStatus(){this.logger.debug("🏥 Checking bundle service health");try{const e=await sn(()=>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:i}=e,{effectiveSlippageFactor:s,effectiveMaxFee:o,vaultAddress:a}=await this.prepareTradingOperation(t,e.maxAcceptableReverseBondingCurveFee,e.maxAcceptableReverseBondingCurveFeeSlippageFactor,e.slippageToleranceFactor);if("native"===r){if(null==i||""===i)throw new Rt("expectedAmount is required for native buy operations. Use getBuyTokenAmount() first to calculate expected tokens.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=UA(i,s,"buy-native");this.logger.debug("BuyNative slippage applied:",{originalExpectedTokens:i,slippageFactor:s,adjustedMinTokens:e});const t=new OA.BuyNativeDto(a,n,e,{maxAcceptableReverseBondingCurveFee:o});return await this.executeBundleTransaction(t,"BuyWithNative",a)}{if(null==i||""===i)throw new Rt("expectedAmount is required for exact buy operations. Use getBuyTokenAmount() first to calculate expected GALA cost.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=UA(i,s,"buy-exact");this.logger.debug("BuyExact slippage applied:",{originalExpectedGalaCost:i,slippageFactor:s,adjustedMaxGalaCost:e});const t=new OA.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:i}=e,{effectiveSlippageFactor:s,effectiveMaxFee:o,vaultAddress:a}=await this.prepareTradingOperation(t,e.maxAcceptableReverseBondingCurveFee,e.maxAcceptableReverseBondingCurveFeeSlippageFactor,e.slippageToleranceFactor);if("exact"===r){if(null==i||""===i)throw new Rt("expectedAmount is required for exact sell operations. Use getSellTokenAmount() first to calculate expected GALA.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=UA(i,s,"sell-exact");this.logger.debug("SellExact slippage applied:",{originalExpectedGala:i,slippageFactor:s,adjustedMinGala:e});const t=new OA.SellExactDto(a,n,e,{maxAcceptableReverseBondingCurveFee:o});return await this.executeBundleTransaction(t,"SellExactToken",a)}{if(null==i||""===i)throw new Rt("expectedAmount is required for native sell operations. Use getSellTokenAmount() first to calculate tokens to sell.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=UA(i,s,"sell-native");this.logger.debug("SellNative slippage applied:",{originalExpectedTokensToSell:i,slippageFactor:s,adjustedMaxTokensToSell:e});const t=new OA.SellNativeDto(a,n,e,{maxAcceptableReverseBondingCurveFee:o});return await this.executeBundleTransaction(t,"SellWithNative",a)}}async prepareTradingOperation(e,t,n,r){const{effectiveSlippageFactor:i,effectiveMaxFee:s}=this.calculateEffectiveSlippage(t,n,r),o=await this.resolveTokenNameToVault(e);if(null==o)throw Lt(e);return{effectiveSlippageFactor:i,effectiveMaxFee:s,vaultAddress:o}}calculateEffectiveSlippage(e,t,n){const r=n??this.defaultSlippageToleranceFactor,i=t??this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor;let s=e??"0";return null!=e&&(s=UA(e,i,"buy-exact"),this.logger.debug("Reverse bonding curve fee slippage applied:",{baseFee:e,slippageFactor:i,adjustedMaxFee:s})),{effectiveSlippageFactor:r,effectiveFeeSlippageFactor:i,effectiveMaxFee:s}}ensureTradingServicesAvailable(){if(!this.signer||!this.tokenKeyService)throw Kt("Trading services not available. BundleService requires walletProvider and userAddress for trading operations.","walletProvider");if(null===this.userAddress||void 0===this.userAddress)throw Pt("userAddress","User address")}async executeBundleTransaction(e,t,n){this.ensureTradingServicesAvailable();try{e.uniqueKey=LA("galaswap-operation");const r=await this.signer.signObject(t,e),i=this.tokenKeyService.generateStringsInstructions(n),s={stringsInstructions:i,method:t,signedDto:r};this.logger.debug("📦 Bundle transaction data:",{method:t,stringsInstructions:i,dtoKeys:Object.keys(r)});const o=await this.submitTransaction(s);if(o.success){const e=tn(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 Ot("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 QA extends Sr{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(pt),t=this.extractData(e);return this.logger.debug("Fetched client feature flags",{flagCount:Object.keys(t.flags).length}),{flags:t.flags}}}var ZA,ek,tk,nk;!function(e){e.CHAT_MESSAGE="CHAT_MESSAGE",e.COMMENT="COMMENT",e.STREAM="STREAM",e.RECORDING="RECORDING"}(ZA||(ZA={})),function(e){e.INAPPROPRIATE_CONTENT="INAPPROPRIATE_CONTENT",e.SPAM="SPAM",e.HARASSMENT="HARASSMENT",e.SCAM="SCAM",e.OTHER="OTHER"}(ek||(ek={})),function(e){e.PENDING="PENDING",e.DISMISSED="DISMISSED",e.ACTIONED="ACTIONED"}(tk||(tk={})),function(e){e.DELETE_CONTENT="DELETE_CONTENT",e.BAN_USER="BAN_USER",e.DELETE_AND_BAN="DELETE_AND_BAN"}(nk||(nk={}));const rk={[ek.INAPPROPRIATE_CONTENT]:"Inappropriate Content",[ek.SPAM]:"Spam",[ek.HARASSMENT]:"Harassment",[ek.SCAM]:"Scam",[ek.OTHER]:"Other"},ik={[tk.PENDING]:"Pending",[tk.DISMISSED]:"Dismissed",[tk.ACTIONED]:"Actioned"},sk={[nk.DELETE_CONTENT]:"Delete Content",[nk.BAN_USER]:"Ban User",[nk.DELETE_AND_BAN]:"Delete & Ban"},ok={[ZA.CHAT_MESSAGE]:"Chat Message",[ZA.COMMENT]:"Comment",[ZA.STREAM]:"Stream",[ZA.RECORDING]:"Recording"},ak=500,ck=lr(ZA),lk=lr(ek),uk=lr(tk),dk=lr(nk),hk=pr([{field:"id",type:"number"},{field:"tokenName",type:"string"},{field:"contentType",type:"string",validator:ck},{field:"contentId",type:"string"},{field:"reporterAddress",type:"string"},{field:"reportedUserAddress",type:"string"},{field:"status",type:"string",validator:uk}]),gk={TOKEN_NAME:An,CONTENT_ID:_n.CONTENT_ID,DETAILS:_n.FLAG_DETAILS,PAGINATION:{MAX_LIMIT:Sn}};function fk(e,t="tokenName"){hr(e,t,gk.TOKEN_NAME)}function mk(e){if(void 0!==e.contentType&&!ck(e.contentType))throw Ft("contentType",`one of: ${Object.values(ZA).join(", ")}`,"Content type");if(void 0!==e.status&&!uk(e.status))throw Ft("status",`one of: ${Object.values(tk).join(", ")}`);if(void 0!==e.reason&&!lk(e.reason))throw Ft("reason",`one of: ${Object.values(ek).join(", ")}`);if(void 0!==e.reporterAddress&&!sr(e.reporterAddress))throw Vt("reporterAddress","a non-empty string",typeof e.reporterAddress);if(void 0!==e.reporterAddress&&Lr(e.reporterAddress,"reporterAddress"),void 0!==e.reportedUserAddress&&!sr(e.reportedUserAddress))throw Vt("reportedUserAddress","a non-empty string",typeof e.reportedUserAddress);void 0!==e.reportedUserAddress&&Lr(e.reportedUserAddress,"reportedUserAddress"),cr(0,void 0,gk.PAGINATION.MAX_LIMIT,e.pageSize)}class pk extends XE{constructor(e,t,n,r=!1,i){super(e,t,n,r,i)}async createFlag(e){!function(e){if(fk(e.tokenName),void 0===e.contentType)throw Pt("contentType","Content type");if(!ck(e.contentType))throw Ft("contentType",`one of: ${Object.values(ZA).join(", ")}`,"Content type");if(!sr(e.contentId))throw Pt("contentId","Content ID");if(e.contentId.length>gk.CONTENT_ID.MAX_LENGTH)throw jt("contentId",gk.CONTENT_ID.MAX_LENGTH,e.contentId.length,"Content ID");if(!sr(e.reportedUserAddress))throw Pt("reportedUserAddress","Reported user address");if(Lr(e.reportedUserAddress,"reportedUserAddress"),!(e.contentType!==ZA.STREAM&&e.contentType!==ZA.RECORDING||void 0!==e.reason&&null!==e.reason))throw Pt("reason","Reason");if(void 0!==e.reason&&!lk(e.reason))throw Ft("reason",`one of: ${Object.values(ek).join(", ")}`,"Reason");if(void 0!==e.details&&!sr(e.details))throw Vt("details","a non-empty string",typeof e.details);if(void 0!==e.details&&e.details.length>gk.DETAILS.MAX_LENGTH)throw jt("details",gk.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(Ae.CREATE,t,this.getMultiAuthHeaders());return{flag:this.extractData(n).flag}}async listFlags(e){return function(e){fk(e.tokenName),mk(e)}(e),this.fetchFlagList(e)}async listGlobalFlags(e={}){return function(e){void 0!==e.tokenName&&fk(e.tokenName),mk(e)}(e),this.fetchFlagList(e)}async dismissFlag(e){!function(e){if(void 0===e.flagId||null===e.flagId)throw Pt("flagId","Flag ID");try{Yn(e.flagId,"flagId")}catch{throw Ft("flagId","a positive integer","Flag ID")}}(e);const t=Ae.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 Pt("flagId","Flag ID");try{Yn(e.flagId,"flagId")}catch{throw Ft("flagId","a positive integer","Flag ID")}if(void 0===e.action)throw Pt("action","Action");if(!dk(e.action))throw Ft("action",`one of: ${Object.values(nk).join(", ")}`,"Action")}(e);const t=Ae.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=jE(e,Sn);VE(t,e,["tokenName","contentType","status","reason","reporterAddress","reportedUserAddress"]);const n=await this.http.get(Ae.LIST,t,this.getMultiAuthHeaders()),r=this.extractData(n);return{items:r.flags,pageInfo:r.pageInfo}}}const yk=["heart","fire","laugh","wow","thumbs_up"],bk={heart:"❤️",fire:"🔥",laugh:"😂",wow:"😮",thumbs_up:"👍"};class vk extends XE{constructor(e,t,n,r=!1,i){super(e,t,n,r,i)}validateReactionTokenName(e){this.validateTokenName(e,An)}validateMessageId(e){if(!sr(e))throw Pt("messageId","Message ID");if(Jn(e,xn.CONTENT_REACTION.MAX_LENGTH,"messageId"),!xn.CONTENT_REACTION.PATTERN.test(e))throw Ft("messageId","msg-{timestamp}-{uuid} or chat-{timestamp}-{uuid} format","Message ID")}validateReactionType(e){if(!sr(e))throw Pt("reactionType","Reaction type");if(!yk.includes(e))throw Ft("reactionType",`one of: ${yk.join(", ")}`,"Reaction type")}async addContentReaction(e){void 0!==e.tokenName&&this.validateReactionTokenName(e.tokenName),this.validateMessageId(e.messageId),this.validateReactionType(e.reactionType);const t=Xe,n={messageId:e.messageId,reactionType:e.reactionType};void 0!==e.tokenName&&(n.tokenName=ln(e.tokenName));const r=await this.http.post(t,n,this.getMultiAuthHeaders()),i=this.extractData(r),{created:s,...o}=i;return{data:o,created:s}}async removeContentReaction(e){void 0!==e.tokenName&&this.validateReactionTokenName(e.tokenName),this.validateMessageId(e.messageId),this.validateReactionType(e.reactionType);const t=`${Je}?${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 wk extends Tr{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}=dr(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 Rt("tokenName parameter requires LaunchpadSDK routing - call LaunchpadSDK.fetchTokenPrice({tokenName}) instead","tokenName","INVALID_PARAMS")}async _fetchDexTokenSpotPrice(e){if(null==e)throw Pt("tokenId","Token ID");try{const t=kA(e),n=xo(t),r=VA(n);if(this.logger.debug(`Fetching DEX spot price for token: ${r}`),!this.dexBackendHttp)throw $t("DEX Backend API client not configured");const i=await this.dexBackendHttp.request({method:"GET",url:"/market/price",params:{assetIds:r}}),s=null!==i&&"object"==typeof i?i:{},o=[t.type,t.collection].filter(e=>"string"==typeof e&&""!==e&&"none"!==e).map(e=>e.toUpperCase()).map(e=>s[e]).find(e=>void 0!==e)??(1===Object.keys(s).length?Object.values(s)[0]:void 0),a=o?.price;if("number"!=typeof a||!Number.isFinite(a))throw new Rt(`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: ${wt(e)?e.message:String(e)}`),l=dn("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 Rt)throw e;throw $t(`Failed to fetch DEX spot price: ${Et(e)}`)}}async fetchLaunchpadTokenSpotPrice(e,t,n){if(!sr(e))throw new Rt(Ct,"tokenName",xt.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=xo(t.sellingToken);return this._fetchDexTokenSpotPrice(n)}}catch(t){this.logger.debug(`Could not determine graduation status for ${e}, falling back to bonding curve: ${Et(t)}`)}this.logger.debug(`Using bonding curve calculation for token: ${e}`);const r=await t({tokenName:e,amount:"1",type:"native"}),i=await this._fetchDexTokenSpotPrice({collection:"GALA",category:"Unit",type:"none",additionalKey:"none"});if(null==i)throw $t("GALA price not available");const s=Kn(r.amount,0)/1e18;if(s<=0)throw new Rt(`Invalid token amount calculation: ${s}`,"amount","INVALID_CALCULATION");const o=i.price/s;return{symbol:dn(e),price:o}}catch(t){if(wt(t))throw $t(`Failed to calculate launchpad token spot price for ${e}: ${Et(t)}`);throw $t(`Failed to calculate launchpad token spot price for ${e}: ${Et(t)}`)}}async fetchTokenDetails(e){this.logger.debug("Fetching token details from GalaChain for tokenId:",e);try{if(!this.galaChainService)throw $t("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 Rt||wt(t))&&("NetworkError"===t.name||Et(t).includes("Token not found")))throw t;throw $t(`Failed to fetch token details from GalaChain for ${String(e)}: ${Et(t)}`,500)}}async fetchAllDexSeasons(){try{if(!this.dexBackendHttp)throw $t("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=tn(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:bn(t?.start??null),end:bn(t?.end??null),rulesId:t?.rules_id??0}});return this.logger.debug(`Fetched ${n.length} DEX seasons`),n}catch(e){if(wt(e)&&Et(e).includes("not configured"))throw e;if(St(e)&&404===e.response?.status)return this.logger.warn("Seasons endpoint not available"),[];throw $t(`Failed to fetch DEX seasons: ${Et(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{Yn(e,"seasonId")}catch{throw Pt("seasonId","Season ID must be a positive number")}try{if(!this.dexBackendHttp)throw $t("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=tn(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(wt(t)&&Et(t).includes("must be a positive number"))throw t;throw $t(`Failed to fetch DEX leaderboard for season ${e}: ${Et(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 $t("DEX Backend API client not configured");const e=tn(await this.dexBackendHttp.request({method:"GET",url:"/v2/trade/volume"}));if(!e)throw $t("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 $t(`Failed to fetch DEX volume summary: ${Et(e)}`)}}}const Ek={BATCH_SIZE:20,FLUSH_INTERVAL_MS:3e3,MAX_QUEUE_SIZE:1e3,FLUSH_ON_PAGE_HIDE:!0,FLUSH_ON_PAGE_UNLOAD:!0,DEBUG:!1},Ak={LOGIN:"login",LOGOUT:"logout",TOKEN_BUY:"token_buy",TOKEN_SELL:"token_sell",TOKEN_SWAP:"token_swap",TOKEN_CREATED:"token_created",TOKEN_GRADUATED:"token_graduated",PAGE_VIEW:"page_view",PAGE_LEAVE:"page_leave",STREAM_START:"stream_start",STREAM_END:"stream_end",STREAM_VIEWERS_CHANGED:"stream_viewers_changed",CHAT_MESSAGE_SENT:"chat_message_sent",CHAT_MESSAGE_RECEIVED:"chat_message_received",LIQUIDITY_ADDED:"liquidity_added",LIQUIDITY_REMOVED:"liquidity_removed",BRIDGE_DEPOSIT:"bridge_deposit",BRIDGE_WITHDRAW:"bridge_withdraw",PROFILE_UPDATED:"profile_updated",BALANCE_CHANGED:"balance_changed",ERROR_OCCURRED:"error_occurred"};class kk{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 gn({debug:t.debug??!1,context:"EventsBatcherService"}),this.config={batchSize:t.batchSize??Ek.BATCH_SIZE,flushIntervalMs:t.flushIntervalMs??Ek.FLUSH_INTERVAL_MS,maxQueueSize:t.maxQueueSize??Ek.MAX_QUEUE_SIZE,flushOnPageHide:t.flushOnPageHide??Ek.FLUSH_ON_PAGE_HIDE,flushOnPageUnload:t.flushOnPageUnload??Ek.FLUSH_ON_PAGE_UNLOAD,debug:t.debug??Ek.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 Sk(e){return 0===(e?.length??0)?"0":e.reduce((e,t)=>T(e).plus(t.quantity).toString(),"0")}function Tk(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 Ik extends Sr{constructor(e,t=!1){super(e,t)}getChannelForCollection(e){return"MUSIC"===(Jw(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{Tt(r,"Fetch balances")}catch{return null}if(0===(r.Data?.length??0))return null;const i=r.Data.find(t=>t.collection===e.collection&&t.category===e.category&&t.additionalKey===e.additionalKey&&t.type===e.type);if(!i||"0"===i.quantity)return null;const s=xo(i),o={quantity:i.quantity,collection:i.collection,category:i.category,tokenId:s};if((i.inUseHolds?.length??0)>0){const e=Tk(i.inUseHolds??[],t);e.length>0&&(o.inUseHolds=e,o.inUseQuantity=Sk(e))}if((i.lockedHolds?.length??0)>0){const e=Tk(i.lockedHolds??[],t);e.length>0&&(o.lockedHolds=e,o.lockedQuantity=Sk(e))}return void 0===o.lockedQuantity&&void 0===o.inUseQuantity||(o.availableQuantity=function(e,t="0",n="0"){return T(e).minus(t).minus(n).toString()}(o.quantity,o.lockedQuantity,o.inUseQuantity)),o}catch(e){throw $t(`Failed to fetch token balance from GalaChain: ${Et(e)}`,void 0,wt(e)?e:void 0)}}}function Nk(e){return"string"==typeof e?{...zA(e),instance:"0"}:{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey,instance:"0"}}function Ck(e){return Ro(e)}function _k(e){const t=e[0];return void 0===t?void 0:Ck(t.tokenInstanceKey)}class xk extends w{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,i){const s=Nk(r);return new xk({lockAuthority:t??e,tokenInstances:[{owner:e,quantity:n,tokenInstanceKey:s}],...void 0!==i?.expires&&{expires:i.expires},...void 0!==i?.name&&{name:i.name},uniqueKey:i?.uniqueKey??PA()})}static forGALA(e,t,n,r){return new xk({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??PA()})}getTokenClassKey(){return _k(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 Rk extends w{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 i=Nk(n);return new Rk({tokenInstances:[{owner:e,quantity:t,tokenInstanceKey:i}],...void 0!==r?.name&&{name:r.name},uniqueKey:r?.uniqueKey??PA()})}static forGALA(e,t,n){return new Rk({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??PA()})}getTokenClassKey(){return _k(this.tokenInstances)}toSigningPayload(){return{tokenInstances:this.tokenInstances,...void 0!==this.name&&{name:this.name},uniqueKey:this.uniqueKey}}}function Bk(e){if(null==e||"object"!=typeof e)return!1;const t=e;return sr(t.amount)&&(void 0!==t.tokenId||sr(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 Dk(e){if(null==e||"object"!=typeof e)return!1;const t=e;return sr(t.amount)&&(void 0!==t.tokenId||sr(t.tokenName))&&(void 0===t.name||"string"==typeof t.name)}function Mk(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every(Bk)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}function Ok(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every(Dk)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}const Uk=100,Lk=100;var Pk,Fk;!function(e){e.TOKEN_NOT_FOUND="TOKEN_NOT_FOUND",e.INVALID_AMOUNT="INVALID_AMOUNT",e.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",e.SIGNATURE_FAILED="SIGNATURE_FAILED",e.NETWORK_ERROR="NETWORK_ERROR",e.WALLET_REQUIRED="WALLET_REQUIRED",e.VALIDATION_ERROR="VALIDATION_ERROR",e.LOCK_NOT_FOUND="LOCK_NOT_FOUND",e.LOCK_EXPIRED="LOCK_EXPIRED",e.INSUFFICIENT_LOCKED_BALANCE="INSUFFICIENT_LOCKED_BALANCE",e.NOT_LOCK_AUTHORITY="NOT_LOCK_AUTHORITY",e.LOCK_NAME_MISMATCH="LOCK_NAME_MISMATCH"}(Pk||(Pk={}));class $k 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"}(Fk||(Fk={}));class Kk extends Error{constructor(e,t,n){super(e),this.type=t,this.details=n,this.name="TransferError"}}function Gk(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 Hk(e,t,n,r="[DEBUG] Token resolution (launchpad)"){const i=await t.resolveTokenToVault(e);if(null!==i){const t=TA(i);return n.debug(r,{tokenName:e,vaultAddress:i,tokenInstance:{collection:t.collection,category:t.category,type:t.type,instance:t.instance}}),t}const s={collection:un(e),category:"Unit",type:"none",additionalKey:"none",instance:"0"};return n.debug("[DEBUG] Token resolution (standard format)",{tokenName:e,tokenInstance:{collection:s.collection,category:s.category,type:s.type}}),s}const Wk=100,qk=100;class jk extends Sr{constructor(e,t,n,r=!1){super(e,r),this.wallet=t,this.tokenResolver=n,this.nativeSigner=t?new WA(t.privateKey):void 0}async lockTokens(e){if(this.validateLockTokensData(e),!this.wallet||!this.nativeSigner)throw new $k("Wallet required for token lock operations",Pk.WALLET_REQUIRED);return Ao(async()=>{const{ownerAddress:t,tokenInstances:n}=this.createTokenOperationContext(),r=[];let i=t;const s=e.tokens.find(e=>void 0!==e.lockAuthority);void 0!==s?.lockAuthority&&(i=Dr(s.lockAuthority));const o=e.tokens.find(e=>void 0!==e.expires),a=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,lockAuthority:void 0!==s.lockAuthority?Dr(s.lockAuthority):i})}const c=new xk({lockAuthority:i,tokenInstances:n,...void 0!==o?.expires&&{expires:o.expires},...void 0!==a?.name&&{name:a.name},uniqueKey:e.uniqueKey??PA()}),l=await this.nativeSigner.signObject("LockToken",c.toSigningPayload()),u=new xk({...c.toSigningPayload(),signedPayload:l}),d=await this.http.post("/api/asset/token-contract/LockToken",u);try{Tt(d,"Token lock failed")}catch(e){const t=It(d);throw new $k(`${Et(e)}${t}`,Pk.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 $k("Wallet required for token unlock operations",Pk.WALLET_REQUIRED);return Ao(async()=>{const{ownerAddress:t,tokenInstances:n}=this.createTokenOperationContext(),r=[],i=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})}const s=new Rk({tokenInstances:n,...void 0!==i?.name&&{name:i.name},uniqueKey:e.uniqueKey??PA()}),o=await this.nativeSigner.signObject("UnlockToken",s.toSigningPayload()),a=new Rk({...s.toSigningPayload(),signedPayload:o}),c=await this.http.post("/api/asset/token-contract/UnlockToken",a);try{Tt(c,"Token unlock failed")}catch(e){const t=It(c);throw new $k(`${Et(e)}${t}`,Pk.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 $k("Must provide either tokenId or tokenName for token identification",Pk.TOKEN_NOT_FOUND);if(void 0!==e.tokenName)try{mr(e.tokenName,"tokenName")}catch{throw new $k("Invalid token name format",Pk.TOKEN_NOT_FOUND,{tokenName:e.tokenName})}try{Qs(Vs(e.amount))}catch{throw new $k(Ft(t,"a positive number",n).message,Pk.INVALID_AMOUNT,{amount:e.amount})}}validateLockTokensData(e){if(!Mk(e))throw new $k("Invalid lock data: missing required fields",Pk.VALIDATION_ERROR);if(e.tokens.length>Wk)throw new $k(`Batch size exceeds maximum limit of ${Wk} tokens per lock operation`,Pk.VALIDATION_ERROR);for(const t of e.tokens){if(this.validateSharedTokenEntry(t,"lockAmount","Lock amount"),void 0!==t.lockAuthority&&!Ur(t.lockAuthority))throw new $k("Invalid lock authority address format",Pk.VALIDATION_ERROR,{lockAuthority:t.lockAuthority});if(void 0!==t.expires)try{Yn(t.expires,"expires")}catch{throw new $k(Ft("expires","a positive integer (epoch milliseconds)","Expires").message,Pk.VALIDATION_ERROR)}}}validateUnlockTokensData(e){if(!Ok(e))throw new $k("Invalid unlock data: missing required fields",Pk.VALIDATION_ERROR);if(e.tokens.length>qk)throw new $k(`Batch size exceeds maximum limit of ${qk} tokens per unlock operation`,Pk.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 $k)return e;let r=t,i=Pk.NETWORK_ERROR;if(St(e)){const n=e.response?.data;if("object"==typeof n&&null!==n){const e=n.Message;"string"==typeof e&&e.length>0&&(r=`${t}: ${e}`);const s="string"==typeof e?e.toLowerCase():"";s.includes("insufficient")||s.includes("balance")?i=Pk.INSUFFICIENT_BALANCE:s.includes("lock")&&s.includes("not found")?i=Pk.LOCK_NOT_FOUND:s.includes("not found")||s.includes("token")?i=Pk.TOKEN_NOT_FOUND:s.includes("authority")?i=Pk.NOT_LOCK_AUTHORITY:s.includes("expired")&&(i=Pk.LOCK_EXPIRED)}}else wt(e)&&(r=`${t}: ${Et(e)}`);return new $k(r,i,Gk(n))}async resolveTokenInstance(e){return Ao(async()=>Hk(e,this.tokenResolver,this.logger),`Failed to resolve token '${e}'`,this.logger,t=>{if(t instanceof Kk)throw new $k(Et(t),Pk.TOKEN_NOT_FOUND);throw new $k(`Failed to resolve token '${e}': ${Et(t)}`,Pk.TOKEN_NOT_FOUND,{tokenName:e})})}async resolveTokenEntry(e){if(void 0!==e.tokenId){const t=kA(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 $k("Must provide either tokenId or tokenName for token identification",Pk.TOKEN_NOT_FOUND)}createTokenOperationContext(){return{ownerAddress:Dr(this.wallet.address),tokenInstances:[]}}}class Vk extends Sr{constructor(e,t=!1,n){super(e,t),this.publicAxios=n}async fetchTokenClassFromChain(e){try{const t="string"==typeof e?kA(e):e,n={tokenClasses:[{collection:t.collection,category:t.category,type:t.type,additionalKey:t.additionalKey}]};if(!this.publicAxios)throw Pt("publicAxios","Public Axios instance");const r=(await this.publicAxios.post("/api/asset/token-contract/FetchTokenClasses",n)).data;if(Tt(r,"Failed to fetch token class from GalaChain"),null===r.Data||void 0===r.Data||0===r.Data.length)throw $t(`Token not found on GalaChain: ${xo(t)}`,404);const i=r.Data[0];if(void 0===i)throw $t(`Token not found on GalaChain: ${xo(t)}`,404);return i}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 Pt("tokenClasses","Token classes array");const t={tokenClasses:e};if(!this.publicAxios)throw Pt("publicAxios","Public Axios instance");const n=(await this.publicAxios.post("/api/asset/token-contract/FetchTokenClassesWithSupply",t)).data;if(Tt(n,"Failed to fetch token classes with supply from GalaChain"),!n.Data||0===n.Data.length)throw $t("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 Rt)throw e;if(St(e)&&404===e.response?.status)throw $t(t,404,wt(e)?e:void 0);if(wt(e)&&"Error"===e.name&&Et(e).includes("status indicates failure"))throw $t(Et(e),400,wt(e)?e:void 0);const r=Et(e);if(r.includes("Token not found")){if(e instanceof Error)throw e;throw new Error(r)}throw $t(`${n}: ${r}`,void 0,wt(e)?e:void 0)}}class zk extends w{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=Nk(e.tokenClassKey);return{quantity:e.quantity,tokenInstanceKey:t}});return new zk({tokenInstances:n,uniqueKey:t?.uniqueKey??PA()})}static fromTokenClassKey(e,t,n){return zk.fromTokens([{tokenClassKey:t,quantity:e}],n)}static forGALA(e,t){return new zk({tokenInstances:[{quantity:e,tokenInstanceKey:{collection:"GALA",category:"Unit",type:"none",additionalKey:"none",instance:"0"}}],uniqueKey:t?.uniqueKey??PA()})}getTokenClassKey(){if(0===this.tokenInstances.length)return;const e=this.tokenInstances[0];return void 0!==e?Ck(e.tokenInstanceKey):void 0}toSigningPayload(){return{tokenInstances:this.tokenInstances,uniqueKey:this.uniqueKey}}}class Xk extends w{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,i){let s;if("string"==typeof r){s={...zA(r),instance:"0"}}else s={collection:r.collection,category:r.category,type:r.type,additionalKey:r.additionalKey,instance:"0"};return new Xk({from:e,to:t,quantity:n,tokenInstance:s,uniqueKey:i??PA()})}static forGALA(e,t,n,r){return new Xk({from:e,to:t,quantity:n,tokenInstance:{collection:"GALA",category:"Unit",type:"none",additionalKey:"none",instance:"0"},uniqueKey:r??PA()})}getTokenClassKey(){return Ro(this.tokenInstance)}toSigningPayload(){return{from:this.from,to:this.to,quantity:this.quantity,tokenInstance:this.tokenInstance,uniqueKey:this.uniqueKey}}}function Jk(e){if(null==e||"object"!=typeof e)return!1;const t=e;return sr(t.amount)&&(void 0!==t.tokenId||sr(t.tokenName))}function Yk(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every(Jk)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}const Qk=50;var Zk;!function(e){e.TOKEN_NOT_FOUND="TOKEN_NOT_FOUND",e.INVALID_AMOUNT="INVALID_AMOUNT",e.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",e.SIGNATURE_FAILED="SIGNATURE_FAILED",e.NETWORK_ERROR="NETWORK_ERROR",e.WALLET_REQUIRED="WALLET_REQUIRED",e.VALIDATION_ERROR="VALIDATION_ERROR"}(Zk||(Zk={}));class eS extends Error{constructor(e,t,n){super(e),this.type=t,this.details=n,this.name="BurnError"}}const tS={validateAmount(e){const t=Vs(e);try{eo(t,"amount")}catch(t){throw new Kk(t.message,Fk.INVALID_AMOUNT,{amount:e})}},validateUniqueKey(e){if(!ar(e)&&sr(e)){if(e.length>Dn.MAX_LENGTH)throw new Rt(`Unique key too long. Maximum length: ${Dn.MAX_LENGTH}`);if(!Dn.PATTERN.test(e))throw new Kk('Invalid unique key format. Must start with "galaswap-operation-" or "galaconnect-operation-"',Fk.INVALID_AMOUNT,{uniqueKey:e})}}},nS="gala-transfer-successful",rS="token-transfer-successful",iS="token-locked-successfully",sS="token-unlocked-successfully",oS="transfer-successful-no-id",aS=50;class cS extends Sr{constructor(e,t,n,r=!1){super(e,r),this.wallet=t,this.tokenResolver=n,this.nativeSigner=t?new WA(t.privateKey):void 0}async transferGala(e){if(this.validateTransferGalaData(e),!this.wallet||!this.nativeSigner)throw new Kk("Wallet required for GALA transfer operations",Fk.WALLET_REQUIRED);try{const t=Dr(e.recipientAddress),n=Dr(this.wallet.address),r=Xk.forGALA(n,t,e.amount,e.uniqueKey),i=await this.nativeSigner.signObject("TransferToken",r.toSigningPayload()),s=new Xk({...r.toSigningPayload(),signedPayload:i}),{data:o,headers:a}=await this.http.postWithMeta("/api/asset/token-contract/TransferToken",s);if(null==o)throw new Kk("No response from GalaChain transfer service",Fk.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 Kk("Wallet required for token transfer operations",Fk.WALLET_REQUIRED);try{const t=Dr(e.to),n=Dr(this.wallet.address);let r;if(null!==e.tokenId&&void 0!==e.tokenId)r=kA(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 Kk("Must provide either tokenId or tokenName for token identification",Fk.TOKEN_NOT_FOUND);r=await this.resolveTokenInstance(e.tokenName)}const i=new Xk({from:n,to:t,quantity:e.amount,tokenInstance:r,uniqueKey:e.uniqueKey??PA()}),s=await this.nativeSigner.signObject("TransferToken",i.toSigningPayload()),o=new Xk({...i.toSigningPayload(),signedPayload:s}),{data:a,headers:c}=await this.http.postWithMeta("/api/asset/token-contract/TransferToken",o);if(null==a)throw new Kk("No response from GalaChain transfer service",Fk.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 Kk)throw t;throw new Kk(`Failed to resolve token class key for '${e}': ${Et(t)}`,Fk.TOKEN_NOT_FOUND,{tokenName:e})}}async burnTokens(e){if(this.validateBurnTokensData(e),!this.wallet||!this.nativeSigner)throw new eS("Wallet required for token burn operations",Zk.WALLET_REQUIRED);try{const t=[];for(const n of e.tokens){let e;if(null!==n.tokenId&&void 0!==n.tokenId)e=kA(n.tokenId),this.logger.debug("[DEBUG] Using provided tokenId:",n.tokenId);else{if(null===n.tokenName||void 0===n.tokenName)throw new eS("Must provide either tokenId or tokenName for token identification",Zk.TOKEN_NOT_FOUND);e=await this.resolveTokenInstance(n.tokenName)}t.push({quantity:n.amount,tokenInstanceKey:e})}const n=new zk({tokenInstances:t,uniqueKey:e.uniqueKey??PA()}),r=await this.nativeSigner.signObject("BurnTokens",n.toSigningPayload()),i=new zk({...n.toSigningPayload(),signedPayload:r}),s=await this.http.post("/api/asset/token-contract/BurnTokens",i);if(null==s)throw new eS("No response from GalaChain burn service",Zk.NETWORK_ERROR);try{Tt(s,"Token burn operation")}catch(e){throw new Dt(Et(e),500)}return this.extractBurnResult(s)}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 sr(t.recipientAddress)&&sr(t.amount)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)}(e))throw new Rt("Invalid GALA transfer data: missing required fields");if(!Ur(e.recipientAddress))throw new Kk("Invalid recipient address format",Fk.INVALID_RECIPIENT,{recipientAddress:e.recipientAddress});tS.validateAmount(e.amount),tS.validateUniqueKey(e.uniqueKey)}validateTransferTokenData(e){if(!function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return sr(t.to)&&sr(t.amount)&&(void 0!==t.tokenId||sr(t.tokenName))&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)}(e))throw new Rt("Invalid token transfer data: missing required fields");if(!Ur(e.to))throw new Kk("Invalid recipient address format",Fk.INVALID_RECIPIENT,{recipientAddress:e.to});if(!(null!==e.tokenId&&void 0!==e.tokenId||null!==e.tokenName&&void 0!==e.tokenName))throw new Kk("Must provide either tokenId or tokenName for token identification",Fk.TOKEN_NOT_FOUND);if(null!==e.tokenName&&void 0!==e.tokenName)try{mr(e.tokenName,"tokenName")}catch{throw new Kk("Invalid token name format",Fk.TOKEN_NOT_FOUND,{tokenName:e.tokenName})}tS.validateAmount(e.amount),tS.validateUniqueKey(e.uniqueKey)}validateBurnTokensData(e){if(!Yk(e))throw new eS("Invalid burn data: missing required fields",Zk.VALIDATION_ERROR);if(e.tokens.length>aS)throw new eS(`Batch size exceeds maximum limit of ${aS} tokens per burn operation`,Zk.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 eS("Must provide either tokenId or tokenName for token identification",Zk.TOKEN_NOT_FOUND);const e=Vs(t.amount);try{Qs(e)}catch{throw new eS("Burn amount must be a positive number",Zk.INVALID_AMOUNT,{amount:t.amount})}}}async resolveTokenInstance(e){try{return await Hk(e,this.tokenResolver,this.logger,`[DEBUG] Token resolution for '${e}' (launchpad):`)}catch(t){if(t instanceof Kk)throw t;throw new Kk(`Failed to resolve token '${e}': ${Et(t)}`,Fk.TOKEN_NOT_FOUND,{tokenName:e})}}extractTransferResult(e,t,n){const r=this.readHeaderValue(t,"x-transaction-id"),i=this.readBlockNumberHeader(t),s=null!=e&&"object"==typeof e&&"Status"in e;s&&Tt(e,"Extract transaction ID");const o=s&&"Data"in e;if(void 0!==r&&r.length>0)return{transactionId:r,...void 0!==i?{blockNumber:i}:{}};if(null!=e&&"object"==typeof e){if("transactionId"in e&&"string"==typeof e.transactionId&&e.transactionId.length>0)return{transactionId:e.transactionId,...void 0!==i?{blockNumber:i}:{}};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!==i?{blockNumber:i}:{}}}}let e=oS;if(t.Data.length>0)switch(n){case"gala":e=nS;break;case"token":e=rS;break;case"lock":e=iS;break;case"unlock":e=sS}return{transactionId:e,...void 0!==i?{blockNumber:i}:{}}}}}throw new Kk("Operation succeeded but transaction ID could not be extracted (missing x-transaction-id header and body fields)",Fk.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 Kk)return e;if(e instanceof Rt)return new Kk(Et(e),Fk.INVALID_AMOUNT);if(St(e)&&e.response){const t=e.response.status,r=e.response.data;if(400===t){const e=r?.message;return new Kk(("string"==typeof e?e:void 0)??"Invalid transfer request",Fk.INVALID_AMOUNT)}if(403===t)return new Kk("Insufficient balance for transfer",Fk.INSUFFICIENT_BALANCE);if(404===t){const e={};return"tokenName"in n&&(e.tokenName=n.tokenName),new Kk("Token not found",Fk.TOKEN_NOT_FOUND,e)}}if("object"==typeof e&&null!==e&&"code"in e&&("ECONNABORTED"===kt(e)||"ETIMEDOUT"===kt(e)))return new Kk("Transfer request timed out",Fk.NETWORK_ERROR);const r=""!==Et(e)?Et(e):t;return new Kk(r,Fk.NETWORK_ERROR)}handleBurnError(e,t,n){if(e instanceof eS)return e;let r=t,i=Zk.NETWORK_ERROR;if(St(e)){const n=e.response?.data;if("object"==typeof n){const e=n.Message;if("string"==typeof e&&e.length>0){r=`${t}: ${e}`;const n=e.toLowerCase();n.includes("insufficient")||n.includes("balance")?i=Zk.INSUFFICIENT_BALANCE:(n.includes("not found")||n.includes("token"))&&(i=Zk.TOKEN_NOT_FOUND)}}}else wt(e)&&(r=`${t}: ${Et(e)}`);return new eS(r,i,Gk(n))}}class lS extends Sr{constructor(e,t,n,r=!1,i){super(e,r),this.balanceService=new Ik(e,r),this.tokenService=new Vk(e,r,i),this.lockService=new jk(e,t,n,r),this.transferService=new cS(e,t,n,r)}async fetchPoolDetails(e){this.validateFetchPoolDetailsData(e);const t=await this.http.post("/api/asset/launchpad-contract/FetchSaleDetails",e);ko(()=>Tt(t,"Failed to fetch pool details"),"Failed to fetch pool details",this.logger,e=>{throw $t(Et(e),500)});const n=t.Data.reverseBondingCurveConfiguration,r=n?.minFeePortion??"0",i=n?.maxFeePortion??"0",s=!Js(r)||!Js(i),o=t.Data;return o.reverseBondingCurveMinFeePortion=r,o.reverseBondingCurveMaxFeePortion=i,o.hasReverseBondingCurveFee=s,o.isGraduated="Finished"===t.Data.saleStatus,delete o.reverseBondingCurveConfiguration,t}async fetchLaunchTokenFee(){const e=await this.http.post("/api/asset/launchpad-contract/FetchLaunchpadFeeAmount",{});return ko(()=>Tt(e,"Failed to fetch launch token fee"),"Failed to fetch launch token fee",this.logger,e=>{throw $t(Et(e),500)}),e.Data.feeAmount}validateFetchPoolDetailsData(e){if(!Hs(e))throw Pt("data","Fetch pool details data");if("string"!=typeof e.vaultAddress||""===e.vaultAddress)throw Pt("vaultAddress","Vault address");if(!e.vaultAddress.startsWith("service|Token$Unit$"))throw new Rt("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 uS{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 dS extends Error{constructor(e,t,n){super(t),this.name="GdexStreamError",this.code=e,void 0!==n&&(this.data=n)}}class hS extends Tr{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??_o("prod").gdexWebSocketUrl,this.requestTimeoutMs=e.requestTimeoutMs??15e3,this.reconnectionManager=new uS({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,i)=>{const s=setTimeout(()=>{this.pending.delete(n),i(new Error(`GDEX request "${e}" timed out after ${this.requestTimeoutMs}ms`))},this.requestTimeoutMs);this.pending.set(n,{resolve:e=>t(e),reject:i,timeout:s});try{this.socket?.send(JSON.stringify(r))}catch(e){clearTimeout(s),this.pending.delete(n),i(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 dS(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 i=this.subscriptionsByServerId.get(n);if(i?.active)try{i.callback(r)}catch(e){this.logger.error("GDEX subscription callback failed",e)}}async subscribe(e,t,n){const r={channel:e,...n},i=await this.request("gdex_subscribe",r);let s;const o={subscriptionId:i.subscriptionId,unsubscribe:async()=>this.unsubscribe(s)};return s={serverId:i.subscriptionId,params:r,callback:t,handle:o,active:!0},this.activeSubscriptions.add(s),this.subscriptionsByServerId.set(s.serverId,s),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 dS)||-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 gS(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 Ft("file","a File object (browser) or Buffer (Node.js)");{const i=new Blob([e],{type:"image/png"});r.append(t,i,n)}}return r}class fS extends Sr{constructor(e,t,n=!1){super(e,n,t)}async uploadImageByTokenName(e){const{tokenName:t,options:n}=e;ao(t);const r=`${t}.png`;io(n.file,r,"image/png");try{const e=`${n.tokenName??t}.png`,r=gS(n.file,"image",e),i=await rn(()=>this.http.request({method:"POST",url:`${R.UPLOAD_IMAGE}?tokenName=${encodeURIComponent(n.tokenName??t)}`,data:r,headers:this.getJwtHeaders()}),{errorContext:"Image upload failed"});return"string"==typeof i?i:""}catch(e){if(e instanceof Mt)throw e;if(wt(e)&&Et(e).includes("FormData"))throw Kt("File upload failed: FormData not supported in this environment. Ensure you have proper polyfills for Node.js environments.","FormData");throw e}}}function mS(e,t){if(void 0!==e){if(!sr(e))throw Vt("tokenName","string");if(e.length>kn.MAX_LENGTH)throw new Rt(`tokenName must be at most ${kn.MAX_LENGTH} characters`,"tokenName",xt.TOO_LONG)}if(void 0!==t){if(!sr(t))throw Vt("userAddress","string");if(t.length>Cn.MAX_LENGTH)throw new Rt(`userAddress must be at most ${Cn.MAX_LENGTH} characters`,"userAddress",xt.TOO_LONG)}}const pS={CHAT_MESSAGE:"CHAT_MESSAGE",COMMENT:"COMMENT"},yS={PAGINATION:{MAX_LIMIT:In.MAX_LIMIT},CONTENT:{CHAT_MAX_LENGTH:_n.CHAT_MESSAGES_V1.MAX_LENGTH,COMMENT_MAX_LENGTH:_n.COMMENTS_V1.MAX_LENGTH}};function bS(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 Jt(["type","tokenName","userAddress"]);if(void 0!==e.type&&e.type!==pS.CHAT_MESSAGE&&e.type!==pS.COMMENT)throw new Rt(`type must be one of: ${Object.values(pS).join(", ")}`,"type",xt.INVALID_VALUE);mS(e.tokenName,e.userAddress),void 0!==e.pageSize&&cr(0,void 0,In.MAX_LIMIT,e.pageSize)}function vS(e){if(void 0===e.type||null===e.type)throw Pt("type");if(e.type!==pS.CHAT_MESSAGE&&e.type!==pS.COMMENT)throw new Rt(`type must be one of: ${Object.values(pS).join(", ")}`,"type",xt.INVALID_VALUE);if(!sr(e.tokenName))throw Pt("tokenName");if(e.tokenName.length>kn.MAX_LENGTH)throw new Rt(`tokenName must be at most ${kn.MAX_LENGTH} characters`,"tokenName",xt.TOO_LONG);if(!sr(e.content))throw Pt("content");if(0===e.content.trim().length)throw Qt("content","Content");const t=e.type===pS.CHAT_MESSAGE?yS.CONTENT.CHAT_MAX_LENGTH:yS.CONTENT.COMMENT_MAX_LENGTH;if(e.content.length>t)throw Yt("content",t,e.content.length)}function wS(e){if(!sr(e.content))throw Pt("content");if(0===e.content.trim().length)throw Qt("content","Content");const t=Math.max(yS.CONTENT.CHAT_MAX_LENGTH,yS.CONTENT.COMMENT_MAX_LENGTH);if(e.content.length>t)throw Yt("content",t,e.content.length)}function ES(e){if(!sr(e))throw Pt("id","Message ID");const t=xn.CHAT_MESSAGE.PATTERN.test(e),n=/^msg-\d{13}-[a-f0-9]{32}$/.test(e);if(!t&&!n)throw new Rt("Invalid message ID format. Expected: chat-{timestamp}-{uuid} or msg-{timestamp}-{uuid}","id",xt.INVALID_FORMAT)}function AS(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 Rt("At least one config option must be provided (messagesEnabled, commentsEnabled, streamingEnabled, nextLiveStreamAt, streamLanguage, or social URLs)","options",xt.REQUIRED);if(void 0!==e.messagesEnabled&&"boolean"!=typeof e.messagesEnabled)throw Vt("messagesEnabled","boolean");if(void 0!==e.commentsEnabled&&"boolean"!=typeof e.commentsEnabled)throw Vt("commentsEnabled","boolean");if(void 0!==e.streamingEnabled&&"boolean"!=typeof e.streamingEnabled)throw Vt("streamingEnabled","boolean");if(void 0!==e.streamLanguage&&"string"!=typeof e.streamLanguage)throw Vt("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 Vt(n,"string or null")}if(void 0!==e.nextLiveStreamAt&&null!==e.nextLiveStreamAt){if("string"!=typeof e.nextLiveStreamAt)throw Vt("nextLiveStreamAt","string or null");const t=new Date(e.nextLiveStreamAt);if(isNaN(t.getTime()))throw new Rt("nextLiveStreamAt must be a valid ISO date string","nextLiveStreamAt",xt.INVALID_FORMAT)}}function kS(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.id&&"string"==typeof t.type&&(t.type===pS.CHAT_MESSAGE||t.type===pS.COMMENT)&&"string"==typeof t.tokenName&&"string"==typeof t.userAddress&&"string"==typeof t.content&&"string"==typeof t.createdAt}function SS(e){return e===pS.CHAT_MESSAGE||e===pS.COMMENT}function TS(e,t){if(null==e)return[];if(Array.isArray(e))return e;const n=e[t];return Array.isArray(n)?n:[]}class IS extends Sr{constructor(e,t,n=!1){super(e,n,t)}buildPoolFilters(e){return{...!ar(e.search)&&{search:e.search},...!ar(e.tokenName)&&{tokenName:e.tokenName},...!ar(e.type)&&{type:e.type},...!ar(e.hasUpcomingShows)&&{hasUpcomingShows:e.hasUpcomingShows},...!ar(e.language)&&{language:e.language},...!ar(e.recentlyStreamed)&&{recentlyStreamed:e.recentlyStreamed},...!ar(e.hasRecordings)&&{hasRecordings:e.hasRecordings},...!ar(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),ar(e.type)||(r.type=e.type),ar(e.tokenName)||(r.tokenName=e.tokenName),ar(e.search)||(r.search=e.search),ar(e.hasUpcomingShows)||(r.hasUpcomingShows=e.hasUpcomingShows.toString()),ar(e.language)||(r.language=e.language),ar(e.recentlyStreamed)||(r.recentlyStreamed=e.recentlyStreamed.toString()),ar(e.hasRecordings)||(r.hasRecordings=e.hasRecordings.toString()),ar(e.streamStatus)||(r.streamStatus=e.streamStatus);const i=qs(r),s=tn(await on(()=>this.http.get(R.FETCH_POOLS,i),{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}(s),a={hasNextPage:s.hasNextPage??s.pageInfo?.hasNextPage??!1},c=s.count??s.total;void 0!==c&&(a.totalCount=c);const l=s.nextCursor??s.pageInfo?.endCursor;null!=l&&(a.nextCursor=l);const u=s.prevCursor??s.pageInfo?.startCursor;null!=u&&(a.prevCursor=u);const d=s.hasPrevPage??s.pageInfo?.hasPreviousPage;return void 0!==d&&(a.hasPrevPage=d),{items:o,pageInfo:a}}async fetchPools(e){const t=e?.cursor,n=e?.pageSize??PE.DEFAULT_LIMIT;sr(e?.tokenName)&&ao(e.tokenName);const r=void 0!==e?.type?{recent:"RECENT",popular:"POPULAR",recordings:"RECORDINGS",seconds_streamed:"SECONDS_STREAMED"}[e.type]:void 0,i=void 0!==e?.streamStatus?{idle:"IDLE",active:"ACTIVE",disabled:"DISABLED"}[e.streamStatus]:void 0,s={...this.buildPoolFilters({search:e?.search,tokenName:e?.tokenName,type:r,hasUpcomingShows:e?.hasUpcomingShows,language:e?.language,recentlyStreamed:e?.recentlyStreamed,hasRecordings:e?.hasRecordings,streamStatus:i}),pageSize:n,...void 0!==t&&{cursor:t}},o=await this.fetchSinglePage(s);return{items:o.items,pageInfo:o.pageInfo}}async fetchAllPools(e){const t=[];let n;const r=PE.BACKEND_MAX_PAGE_SIZE;for(;;){const i={...e,pageSize:r,...void 0!==n&&{cursor:n}},s=await this.fetchPools(i);if(t.push(...s.items),0===s.items.length)break;if(!s.pageInfo.hasNextPage)break;n=s.pageInfo.nextCursor}return{items:t,pageInfo:{hasNextPage:!1,totalCount:t.length}}}async checkPool(e){!function(e){const t=Es(e);!t.success&&t.errors&&oo(t.errors,"options")}(e),sr(e.tokenName)&&ao(e.tokenName);try{const t=await this.http.post(R.VALIDATE_TOKEN,{tokenName:e.tokenName,symbol:e.symbol});if(null==t)throw new Error("Invalid response from check pool endpoint");const n=t.data??t;if(null==n)throw new Error("Invalid response from check pool endpoint");if(!0===sr(e.symbol)){return!n.symbolAvailable}if(!0===sr(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 i="number"==typeof n.statusCode?n.statusCode:null;if(404===i)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===i&&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 Ps(t,"tokenName")&&$s(t,"from")&&$s(t,"to")&&$s(t,"resolution")}(e))throw new Rt("Invalid options provided. Expected { tokenName: string, from?: number, to?: number, resolution?: number }","options","INVALID_OPTIONS");const{tokenName:t,from:n,to:r,resolution:i}=e;if(ao(t),null==n||null==r||null==i)throw new Rt("Graph options (from, to, resolution) are required","options","MISSING_GRAPH_OPTIONS");const s={tokenName:t,from:n,to:r,resolution:i};co(s);const o=qs(s);return{dataPoints:await rn(()=>this.http.get(R.CHART,o),{errorContext:"Failed to fetch graph data"})}}async fetchTokenDistribution(e){if(""===e||null==e)throw Pt("tokenName","Token name");let t;ao(e);try{t=await on(()=>this.http.get(`${R.GET_TOKEN_DISTRIBUTION}?tokenName=${e}`),{errorContext:"Failed to fetch token distribution"})}catch(t){if(St(t)&&500===t.response?.status)throw $t(`Token distribution data temporarily unavailable for ${e}. This is a backend issue - please try again later.`,500);throw t}return ho(tn(t),t.status,e=>e.toFixed())}async fetchUserHolderContext(e,t){if(""===e||null==e)throw Pt("tokenName","Token name");if(""===t||null==t)throw Pt("userAddress","User address");return ao(e),rn(()=>this.http.get(`${R.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");ao(e);try{const t=R.GET_TOKEN.replace(":tokenName",e.toLowerCase().trim()),n=tn(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&&ao(e.tokenName);try{const t=await this.http.post(R.VALIDATE_TOKEN,{tokenName:e.tokenName?.toLowerCase().trim(),symbol:e.symbol?.toUpperCase().trim()});if(null==t)throw new Error("Invalid response from validation endpoint");const n=t.data??t;if(null==n)throw new Error("Invalid response from validation endpoint");return n}catch(e){throw this.logger.warn(`Token validation failed: ${String(e)}`),e}}async fetchTokenStats(e){if(!sr(e))throw Pt("tokenName","Token name");ao(e);const t=R.TOKEN_STATS.replace(":tokenName",e.toLowerCase().trim());try{const e=tn(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 Pt("tokenName","Token name");ao(e),AS(t);const n=R.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 NS={PAGINATION:In,TOKEN_NAME:kn,USER_ADDRESS:Cn};function CS(e){if(void 0!==e.tokenName){if(!sr(e.tokenName))throw Vt("tokenName","a non-empty string",typeof e.tokenName);if(e.tokenName.length>NS.TOKEN_NAME.MAX_LENGTH)throw jt("tokenName",NS.TOKEN_NAME.MAX_LENGTH,e.tokenName.length)}if(void 0!==e.userAddress){if(!sr(e.userAddress))throw Vt("userAddress","a non-empty string",typeof e.userAddress);if(e.userAddress.length>NS.USER_ADDRESS.MAX_LENGTH)throw jt("userAddress",NS.USER_ADDRESS.MAX_LENGTH,e.userAddress.length)}if(void 0!==e.search){if("string"!=typeof e.search)throw Vt("search","a string",typeof e.search);if(e.search.length>256)throw jt("search",256,e.search.length)}if(cr(0,void 0,NS.PAGINATION.MAX_LIMIT,e.pageSize),void 0!==e.txnType&&"BUY"!==e.txnType&&"SELL"!==e.txnType)throw Ft("txnType",'"BUY" or "SELL"');if(void 0!==e.startDate){if(!sr(e.startDate))throw Vt("startDate","a non-empty string",typeof e.startDate);if(isNaN(Date.parse(e.startDate)))throw Ft("startDate","a valid ISO 8601 date")}if(void 0!==e.endDate){if(!sr(e.endDate))throw Vt("endDate","a non-empty string",typeof e.endDate);if(isNaN(Date.parse(e.endDate)))throw Ft("endDate","a valid ISO 8601 date")}if(void 0!==e.minAmount)try{Xn(e.minAmount,0,Number.MAX_SAFE_INTEGER,"minAmount")}catch{throw Ft("minAmount","a non-negative number")}if(void 0!==e.maxAmount)try{Xn(e.maxAmount,0,Number.MAX_SAFE_INTEGER,"maxAmount")}catch{throw Ft("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),i="number"==typeof t?t:Number(t);if(isNaN(r)||isNaN(i))throw Vt(n,"numeric values",void 0,n);if(r>i)throw new Rt(`Minimum value (${r}) must be less than or equal to maximum value (${i}) for ${n}`,n,xt.INVALID_RANGE)}(e.minAmount,e.maxAmount,"amountRange")}class _S extends Sr{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 Ps(t,"tokenName")&&(void 0===t.tradeType||"buy"===t.tradeType||"sell"===t.tradeType)&&Fs(t,"userAddress")&&$s(t,"offset")&&$s(t,"pageSize")&&$s(t,"page")&&$s(t,"limit")}(e))throw new Rt("Invalid options provided. Expected { tokenName: string, tradeType?: string, userAddress?: string, cursor?: string, pageSize?: number, startDate?: Date, endDate?: Date, sortOrder?: string }","options","INVALID_OPTIONS");const{tokenName:t,cursor:n,pageSize:r=PE.DEFAULT_LIMIT}=e;if(!sr(t))throw Pt("tokenName","Token name");const i={pageSize:String(Math.min(r,Tn))};void 0!==n&&(i.cursor=n);const s={...i};s.tokenName=t;const o=await this.http.get(R.GET_TRADES,s);if(null==o)throw new Rt("No response from trade service","response","NO_RESPONSE");const a=tn(o),c=TS(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=ln(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?GE(e.pageSize,1,NS.PAGINATION.MAX_LIMIT):NS.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 rn(()=>this.http.get(Ye,t),{errorContext:"Failed to fetch trades"})}}function xS(e){return!!sr(e)&&Nn.PATTERN.test(e)}function RS(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 BS(e,t){return e.toLowerCase()===t.toLowerCase()}function DS(e){return e.toLowerCase()}function MS(e,t){return e.toLowerCase().includes(t.toLowerCase())}function OS(e,t,n,r){return e===n&&t===r||e===r&&t===n}function US(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}function LS(e){return null==e||"string"!=typeof e||0===e.trim().length}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}lr({ALL:"all",DEFI:"DEFI",ASSET:"ASSET",COLLECTION:"COLLECTION",CREATED:"created"});class $S extends Sr{constructor(e,t,n=!1){super(e,n,t)}async fetchProfile(e){const t=e??this.http.getAddress();if(""===t||null==t||!xS(t))throw Ft("address","eth|[40-hex-chars] or client|[identifier]","Address");const n=null==e,r=n?R.GET_CURRENT_USER:R.GET_PROFILE.replace(":address",t),i=await this.http.get(r,void 0,n?this.getJwtHeaders():void 0);if(null==i)throw new Rt("No response from user service","response","NO_RESPONSE");return i}async updateProfile(e){this.validateUpdateProfileData(e);let t=e.profileImage;if(!sr(t))try{const n=await this.fetchProfile(e.address);t=n.data?.profileImage??""}catch{t=""}const n={profileImage:t,fullName:e.fullName};await rn(()=>this.http.put(R.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 Rt("Wallet address not available - wallet not configured","address","NO_WALLET");try{const n=`profile-image-${t}.png`,r=gS(e.file,"image",n),i=await rn(()=>this.http.request({method:"POST",url:`${R.UPLOAD_IMAGE}?tokenName=${encodeURIComponent(t)}`,data:r,headers:this.getJwtHeaders()}),{errorContext:"Image upload failed"});return"string"==typeof i?i:""}catch(e){if(e instanceof Rt||e instanceof Mt)throw e;throw new Rt(`Profile image upload failed: ${Et(e)}`,"file","UPLOAD_FAILED")}}async fetchTokenList(e){return this.buildFetchRequest(R.GET_TOKEN_LIST,e,{includeType:!0,errorMessage:"Failed to fetch token list"})}async fetchTokensHeld(e){return this.buildFetchRequest(R.GET_TOKENS_HELD,e,{includeType:!1,errorMessage:"Failed to fetch tokens held"})}async fetchTokensCreated(e){const{cursor:t,pageSize:n,search:r,tokenName:i,status:s}=e??{},o=e?.type??(void 0!==s?"created":"DEFI"),a=this.http.getAddress();if(null==a||""===a)throw new Rt("Wallet address not available - wallet not configured","address","NO_WALLET");const c={type:o,address:a,pageSize:n??PE.DEFAULT_LIMIT};return void 0!==t&&(c.cursor=t),void 0!==r&&(c.search=r),void 0!==i&&(c.tokenName=i),void 0!==s&&(c.status=s),this.fetchTokenList(c)}async getManagedTokens(e={}){const t=jE({pageSize:e.pageSize??PE.DEFAULT_LIMIT,...void 0!==e.cursor&&{cursor:e.cursor}},Tn);return rn(()=>this.http.get(R.GET_MANAGED_TOKENS,t,this.getJwtHeaders()),{errorContext:"Failed to fetch managed tokens"})}async buildFetchRequest(e,t,n){this.validateGetTokenListOptions(t);const r=jE({pageSize:t.pageSize??PE.DEFAULT_LIMIT,...void 0!==t.cursor&&{cursor:t.cursor}},Tn);VE(r,t,["address","search","tokenName","status"]),n.includeType&&!e.includes("?type=")&&(r.type="all"===(t.type??"DEFI")?"DEFI":t.type??"DEFI");let i=e;if(e.includes(":address")){const n=t.address??this.http.getAddress();if(0===n.length)throw Pt("address","User address");i=e.replace(":address",n),delete r.address}const s=tn(await on(()=>this.http.get(i,r),{errorContext:n.errorMessage})),o=TS(s,"token"),a={hasNextPage:s.hasNextPage??!1},c=s.count??s.total;void 0!==c&&(a.totalCount=c),void 0!==s.nextCursor&&(a.nextCursor=s.nextCursor),void 0!==s.prevCursor&&(a.prevCursor=s.prevCursor),void 0!==s.hasPrevPage&&(a.hasPrevPage=s.hasPrevPage);const l={tokens:o,pageInfo:a};return void 0!==c&&(l.total=c),l}validateGetTokenListOptions(e){const t=e.pageSize??PE.DEFAULT_LIMIT;if(t<1||t>Tn)throw new Rt(`pageSize must be between 1 and ${Tn}`,"pageSize","OUT_OF_RANGE");if(void 0!==e.address&&!xS(e.address))throw Ft("address","eth|[40-hex-chars] or client|[identifier]","Address");const n=RS(e.search);if(null!==n&&!(sr(r=n)&&r.length>=Ln&&r.length<=Pn))throw Wt("search",Ln,Pn,n.length,"Search query");var r;const i=RS(e.tokenName);if(null!==i&&!(sr(s=i)&&s.length>=kn.MIN_LENGTH&&s.length<=kn.MAX_LENGTH))throw Wt("tokenName",kn.MIN_LENGTH,kn.MAX_LENGTH,i.length,"Token name");var s}validateUpdateProfileData(e){if(!xS(e.address))throw Ft("address","eth|[40-hex-chars] or client|[identifier]","Address");if(t=e.fullName,!(sr(t)&&t.length>=Fn.FULL_NAME.MIN_LENGTH&&t.length<=Fn.FULL_NAME.MAX_LENGTH&&Fn.FULL_NAME.ALPHABETS_ONLY_PATTERN.test(t)))throw Wt("fullName",Fn.FULL_NAME.MIN_LENGTH,Fn.FULL_NAME.MAX_LENGTH,e.fullName.length,"Full name");var t}validateUploadProfileImageOptions(e){if(void 0!==e.address&&!xS(e.address))throw Ft("address","eth|[40-hex-chars] or client|[identifier]","Address")}}class KS{constructor(e,t,n=!1){this.http=e,this.poolService=new IS(e,t,n),this.tradeService=new _S(e,n),this.userService=new $S(e,t,n),this.imageService=new fS(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 ao(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 GS extends XE{constructor(e,t,n,r=!1,i){super(e,t,n,r,i)}validateContent(e,t){if(!sr(e))throw Pt("content","Message content");if(0===e.trim().length)throw Pt("content","Message content");Jn(e,t===pS.CHAT_MESSAGE?_n.CHAT_MESSAGES_V1.MAX_LENGTH:_n.COMMENTS_V1.MAX_LENGTH,"content")}validateMessageId(e){if(!sr(e))throw Pt("id","Message ID");if(e.length<10||e.length>64)throw Ft("id","valid message ID format","Message ID")}validateMessageType(e){if(e!==pS.CHAT_MESSAGE&&e!==pS.COMMENT)throw new Rt(`type must be one of: ${Object.values(pS).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??PE.DEFAULT_LIMIT;const i=jE(r,In.MAX_LIMIT),s={};void 0!==i.pageSize&&(s.pageSize=i.pageSize),void 0!==i.cursor&&(s.cursor=i.cursor),t&&(s.type=e.type.toUpperCase()),n&&(s.tokenName=ln(e.tokenName)),void 0!==e.userAddress&&""!==e.userAddress&&(s.userAddress=e.userAddress),void 0!==e.search&&""!==e.search&&(s.search=e.search);const o=await this.http.get(Qe.GET_MESSAGES,s),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:ln(e.tokenName),content:e.content.trim()},n=await this.http.post(Qe.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(Qe.UPDATE_MESSAGE,e),r={content:t.content.trim()},i=await this.http.put(n,r,this.getJwtHeaders());return{message:this.extractData(i)}}async deleteMessage(e){this.validateMessageId(e);const t=this.buildEndpointWithId(Qe.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(Qe.GET_PINNED,{tokenName:ln(e)});return{message:this.extractData(t)}}async pinMessage(e){this.validateMessageId(e);const t=Qe.PIN_MESSAGE.replace(":id",e);return await this.http.post(t,{},this.getDualAuthHeaders()),{success:!0}}async unpinMessage(e){this.validateMessageId(e);const t=Qe.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(Qe.GET_MESSAGE_STATS,void 0,this.getDualAuthHeaders());return this.extractData(e)}}const HS={MODERATOR:"MODERATOR",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MANAGER:"MANAGER"},WS=ur(HS),qS={TOKEN:"TOKEN",ALL_OWNER_TOKENS:"ALL_OWNER_TOKENS"},jS=ur(qS),VS={PENDING:"PENDING",CLAIMED:"CLAIMED",REVOKED:"REVOKED",EXPIRED:"EXPIRED"},zS=ur(VS);function XS(e){return WS.includes(e)}function JS(e){return zS.includes(e)}function YS(e){return Mn.PATTERN.test(e)}const QS=pr([{field:"id",type:"number"},{field:"inviteScope",type:"string"},{field:"tokenName",type:"string",nullable:!0},{field:"role",type:"string"},{field:"inviteCode",type:"string"},{field:"inviteUrl",type:"string"},{field:"status",type:"string"},{field:"createdAt",type:"string"}]),ZS=pr([{field:"tokenName",type:"string"},{field:"tokenSymbol",type:"string"},{field:"role",type:"string"},{field:"inviteScope",type:"string"},{field:"creatorAddress",type:"string"},{field:"claimedAt",type:"string"}]),eT=pr([{field:"inviteScope",type:"string"},{field:"tokenName",type:"string",nullable:!0},{field:"tokenSymbol",type:"string",nullable:!0},{field:"role",type:"string"},{field:"status",type:"string"},{field:"invitedBy",type:"string"}]);function tT(e){return jS.includes(e)}function nT(e){const t=[],n=e.inviteScope??qS.TOKEN;return void 0===e.inviteScope||tT(e.inviteScope)||Nt(t,()=>{throw Xt("inviteScope",e.inviteScope,jS,"Invite scope")}),n===qS.TOKEN?Nt(t,()=>{hr(e.tokenName??"","tokenName",En)}):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)||Nt(t,()=>{throw Xt("role",e.role,WS,"Role")}),void 0!==e.description&&""!==e.description&&Nt(t,()=>{Jn(e.description,_n.DESCRIPTION.MAX_LENGTH,"description")}),void 0===e.expiresAt||""===e.expiresAt||vn(e.expiresAt)||Nt(t,()=>{throw function(e,t="a valid date",n){const r=Ut(e,n);return new Rt(`${r} must be ${t}`,e,"INVALID_DATE")}("expiresAt","ISO 8601 format")}),t}function rT(e){const t=[];return sr(e)?YS(e)||t.push("Invalid invite code format"):t.push(Pt("inviteCode","Invite code").message),t}function iT(e){const t=[];return Nt(t,()=>{hr(e.tokenName??"","tokenName",En)}),void 0===e.status||JS(e.status)||Nt(t,()=>{throw Xt("status",e.status,zS,"Status")}),Nt(t,()=>{cr(0,void 0,Sn,e.pageSize)}),t}class sT extends XE{constructor(e,t,n,r=!1,i){super(e,t,n,r,i)}validateRole(e){if(!sr(e))throw Pt("role","Role");if(!XS(e))throw Ft("role",`one of: ${WS.join(", ")}`,"Role")}validateInviteCodeFormat(e){if(!sr(e))throw Pt("inviteCode","Invite code");if(!YS(e))throw Ft("inviteCode","valid invite code format","Invite code")}validateInviteScope(e){if(void 0!==e&&!tT(e))throw new Rt(`Invalid invite scope. Must be one of: ${jS.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 Rt("Token name is required for TOKEN scope invites","tokenName","REQUIRED");this.validateTokenName(e.tokenName,En)}else if(t===qS.ALL_OWNER_TOKENS&&e.tokenName)throw new Rt("Token name should not be provided for ALL_OWNER_TOKENS scope invites","tokenName","INVALID_VALUE");this.validateRole(e.role),this.validateOptionalString(e.description,"description","Description",_n.DESCRIPTION.MAX_LENGTH),this.validateOptionalDate(e.expiresAt,"expiresAt","Expiration date");const n=fe,r={inviteScope:t,role:e.role};t===qS.TOKEN&&null!==e.tokenName&&void 0!==e.tokenName&&""!==e.tokenName&&(r.tokenName=ln(e.tokenName)),void 0!==e.description&&(r.description=e.description),void 0!==e.expiresAt&&(r.expiresAt=e.expiresAt);const i=await this.http.post(n,r,this.getMultiAuthHeaders());return{invite:this.extractData(i)}}async listInvites(e){void 0!==e.tokenName&&""!==e.tokenName&&this.validateTokenName(e.tokenName,En),this.validateStatusFilter(e.status,VS);const t=ye,n={...this.buildPaginationParams(e,In.MAX_LIMIT)};void 0!==e.tokenName&&""!==e.tokenName&&(n.tokenName=ln(e.tokenName)),void 0!==e.status&&(n.status=e.status);const r=await this.http.get(t,n,this.getMultiAuthHeaders()),i=this.extractData(r);return{items:i.invites,pageInfo:i.pageInfo}}async revokeInvite(e){this.validatePositiveInteger(e,"inviteId","Invite ID");const t=this.buildEndpoint(be,{id:String(e)});en(await this.http.delete(t,void 0,this.getMultiAuthHeaders()),"Failed to revoke invite")}async updateInviteRole(e){this.validatePositiveInteger(e.inviteId,"inviteId","Invite ID"),this.validateRole(e.role);const t=this.buildEndpoint(ve,{id:String(e.inviteId)}),n={role:e.role},r=await this.http.patch(t,n,this.getMultiAuthHeaders());return{invite:this.extractData(r)}}async updateInvite(e){if(this.validatePositiveInteger(e.inviteId,"inviteId","Invite ID"),void 0===e.role&&(void 0===e.description||""===e.description))throw new Rt("At least one of role or description must be provided","options","REQUIRED");void 0!==e.role&&this.validateRole(e.role),void 0!==e.description&&this.validateOptionalString(e.description,"description","Description",_n.DESCRIPTION.MAX_LENGTH);const t=this.buildEndpoint(we,{id:String(e.inviteId)}),n={};void 0!==e.role&&(n.role=e.role),void 0!==e.description&&(n.description=e.description);const r=await this.http.patch(t,n,this.getMultiAuthHeaders());return{invite:this.extractData(r)}}async claimInvite(e){this.validateInviteCodeFormat(e.inviteCode);const t=me,n={inviteCode:e.inviteCode},r=await this.http.post(t,n,this.getMultiAuthHeaders()),i=this.extractData(r);return"tokenName"in i&&void 0!==i.tokenName?{token:i}:{blanketAccess:i}}async getModeratedTokens(e){const t=pe,n=this.buildPaginationParams(e??{},In.MAX_LIMIT),r=await this.http.get(t,n,this.getMultiAuthHeaders()),i=this.extractData(r);return{items:i.tokens,pageInfo:i.pageInfo}}async getInviteByCode(e){this.validateInviteCodeFormat(e);const t=this.buildEndpoint(Ee,{code:e}),n=await this.http.get(t,{});return this.extractData(n)}}const oT={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 aT(e){return parseFloat(oT[e])}function cT(e){return`${e}-${Date.now()}-${Math.random().toString(36).substring(2,11)}`}function lT(){return Date.now()+6e4}function uT(e){return""!==e&&"string"==typeof e&&/^[a-zA-Z0-9]{3,50}$/.test(e)}function dT(e){try{return Math.floor(parseFloat(String(e))??0).toString()}catch{return"0"}}function hT(e){return""!==e&&"string"==typeof e&&/^eth\|[0-9a-fA-F]{40}$/.test(e)}class gT extends Sr{constructor(e){super(e)}getCollectionClaimFee(){return oT.COLLECTION_CLAIM_FEE}getTokenClassCreateFee(){return oT.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(!hT(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=oT.COLLECTION_CLAIM_FEE;n.collectionClaim=e,t=String(BigInt(t)+BigInt(e))}if((e.createTokenClasses??0)>0){const r=oT.TOKEN_CLASS_CREATE_FEE,i=String(BigInt(r)*BigInt(e.createTokenClasses));n.tokenClassCreate=r,n.tokenClassCount=e.createTokenClasses,t=String(BigInt(t)+BigInt(i))}return{totalFee:t,breakdown:n}}async claimCollection(e){try{if(this.logger.debug("Claiming NFT collection",e.collectionName),!uT(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:lT(),uniqueKey:cT("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),!hT(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),!uT(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(!uT(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?dT(e.maxSupply):void 0,maxCapacity:void 0!==e.maxCapacity?dT(e.maxCapacity):void 0,additionalKey:e.additionalKey,expiresAt:lT(),uniqueKey:cT("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),!uT(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(!hT(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:lT(),uniqueKey:cT("mint")};this.logger.debug("Built mint DTO",r);const i=`mint-${Date.now()}`,s=Array.from({length:t},(e,t)=>t+1);return{transactionId:i,mintedQuantity:e.quantity,owner:e.ownerAddress,tokenInstances:s,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}),!hT(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 fT extends Sr{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(ht,{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:gt,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(ft,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(mt,e,t),r=this.extractData(n);return this.logger.debug("Updated notification preferences",{tradesEnabled:r.tradesEnabled,streamsEnabled:r.streamsEnabled}),{preferences:r}}}class mT extends Sr{constructor(e,t=!1){super(e,t)}async getHomeOEmbedJson(e={}){this.logger.debug("Fetching home oEmbed (JSON)");const t=await this.http.get(R.OEMBED,{format:"json"});return this.logger.debug("Fetched home oEmbed (JSON)",{title:t.title}),{oembed:t}}async getHomeOEmbedHtml(e={}){this.logger.debug("Fetching home oEmbed (HTML)");const t=await this.http.get(R.OEMBED,{},{responseType:"text"});return this.logger.debug("Fetched home oEmbed (HTML)"),{html:t}}async getPoolOEmbedJson(e){const{tokenName:t}=e;if(null==t||"string"!=typeof t||""===t.trim())throw new Rt("tokenName is required","tokenName","REQUIRED_FIELD");this.logger.debug("Fetching pool oEmbed (JSON)",{tokenName:t});const n=R.OEMBED_BUY_SELL.replace(":tokenName",t.toLowerCase().trim()),r=await this.http.get(n,{format:"json"});return this.logger.debug("Fetched pool oEmbed (JSON)",{tokenName:t,title:r.title}),{oembed:r}}async getPoolOEmbedHtml(e){const{tokenName:t}=e;if(null==t||"string"!=typeof t||""===t.trim())throw new Rt("tokenName is required","tokenName","REQUIRED_FIELD");this.logger.debug("Fetching pool oEmbed (HTML)",{tokenName:t});const n=R.OEMBED_BUY_SELL.replace(":tokenName",t.toLowerCase().trim()),r=await this.http.get(n,{},{responseType:"text"});return this.logger.debug("Fetched pool oEmbed (HTML)",{tokenName:t}),{html:r}}async getProfileOEmbedJson(e){const{address:t}=e;if(null==t||"string"!=typeof t||""===t.trim())throw new Rt("address is required","address","REQUIRED_FIELD");this.logger.debug("Fetching profile oEmbed (JSON)",{address:t});const n=R.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 Rt("address is required","address","REQUIRED_FIELD");this.logger.debug("Fetching profile oEmbed (HTML)",{address:t});const n=R.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 pT(e){if(!sr(e))throw Pt("address","Address")}const yT={PENDING:"PENDING",CLAIMED:"CLAIMED",REVOKED:"REVOKED",EXPIRED:"EXPIRED"},bT={ACTIVE:"ACTIVE",REVOKED:"REVOKED"},vT=lr(yT),wT=lr(bT);function ET(e){if(e.status!==yT.PENDING)return!1;if(null!==e.expiresAt&&void 0!==e.expiresAt){if(bn(e.expiresAt)<=new Date)return!1}return!0}function AT(e){try{wr(e.description,"description",255)}catch(e){if(e instanceof Rt){throw e.message.includes("255")?new Error("description must be at most 255 characters"):new Error("description must be a string")}throw e}if(void 0!==e.expiresAt){if(!sr(e.expiresAt))throw new Error("expiresAt must be a non-empty string");try{Er(e.expiresAt,"expiresAt")}catch(e){if(e instanceof Rt)throw new Error("expiresAt must be a valid ISO 8601 date string");throw e}if(vn(e.expiresAt)){if(bn(e.expiresAt)<=new Date)throw new Error("expiresAt must be in the future")}}}function kT(e){if(void 0!==e.status&&!vT(e.status))throw Xt("status",e.status,Object.values(yT),"status");cr(0,void 0,50,e.pageSize,e.cursor)}function ST(e){if(void 0!==e.status&&!wT(e.status))throw Xt("status",e.status,Object.values(bT),"status");cr(0,void 0,50,e.pageSize,e.cursor)}function TT(e){if(!sr(e))throw new Error("Invite code must be a non-empty string");Jn(e,100,"code")}function IT(e){if(!sr(e))throw new Error("Address must be a non-empty string");try{Lr(e,"address")}catch{throw new Error("Invalid wallet address format. Must be eth|..., 0x..., or client|... format")}}function NT(e){try{Yn(e,"id")}catch(e){if(e instanceof Rt)throw new Error("Invite ID must be a positive integer");throw e}}function CT(e){if(null==e||"object"!=typeof e)throw new Rt("Options are required");if(void 0!==e.search){if("string"!=typeof e.search)throw new Rt("Search must be a string");if(0===e.search.length)throw new Rt("Search query cannot be empty string")}if(void 0!==e.sortBy){if("string"!=typeof e.sortBy)throw new Rt("Sort field must be a string");if(0===e.sortBy.length)throw new Rt("Sort field cannot be empty string")}if(void 0!==e.sortOrder&&"asc"!==e.sortOrder&&"desc"!==e.sortOrder)throw new Rt('Sort order must be "asc" or "desc"')}function _T(e){if(null==e||"object"!=typeof e)throw new Rt("Options are required");if(!sr(e.userAddress))throw new Rt("userAddress is required and must be a non-empty string");try{Lr(e.userAddress,"userAddress")}catch{throw new Rt("Invalid wallet address format. Must be eth|..., 0x..., or client|... format")}if(void 0!==e.description){if("string"!=typeof e.description)throw new Rt("description must be a string");if(e.description.length>255)throw new Rt("description must be at most 255 characters")}}class xT extends XE{constructor(e,t,n,r=!1,i){super(e,t,n,r,i)}validateInviteCodeFormat(e){if(!sr(e))throw Pt("inviteCode","Invite code");TT(e)}validateWalletAddressFormat(e){if(!sr(e))throw Pt("address","Address");IT(e)}async createInvite(e={}){AT(e),this.validateOptionalString(e.description,"description","Description",_n.DESCRIPTION.MAX_LENGTH),this.validateOptionalDate(e.expiresAt,"expiresAt","Expiration date");const t=ke,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={}){kT(e),this.validateStatusFilter(e.status,yT);const t=Se,n={...this.buildPaginationParams(e,In.MAX_LIMIT)};void 0!==e.status&&(n.status=e.status);const r=await this.http.get(t,n,this.getDualAuthHeaders()),i=this.extractData(r);return{items:i.invites,pageInfo:i.pageInfo}}async getInviteByCode(e){this.validateInviteCodeFormat(e);const t=this.buildEndpoint(Te,{code:e}),n=await this.http.get(t,{});return this.extractData(n)}async revokeInvite(e){NT(e);const t=this.buildEndpoint(Ne,{id:String(e)});en(await this.http.delete(t,this.getDualAuthHeaders()),"Failed to revoke invite")}async claimInvite(e){this.validateInviteCodeFormat(e);const t=Ie,n={inviteCode:e},r=await this.http.post(t,n,this.getJwtHeaders());return{invite:this.extractData(r)}}async listOverseers(e={}){ST(e),this.validateStatusFilter(e.status,bT);const t=Ce,n={...this.buildPaginationParams(e,In.MAX_LIMIT)};void 0!==e.status&&(n.status=e.status);const r=await this.http.get(t,n,this.getDualAuthHeaders()),i=this.extractData(r);return{items:i.overseers,pageInfo:i.pageInfo}}async createOverseerDirect(e){_T(e),this.validateWalletAddressFormat(e.userAddress),this.validateOptionalString(e.description,"description","Description",_n.DESCRIPTION.MAX_LENGTH);const t=_e,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(xe,{address:e});en(await this.http.delete(t,this.getDualAuthHeaders()),"Failed to revoke overseer")}async getMyStatus(){const e=Re,t=await this.http.get(e,{},this.getJwtHeaders());return this.extractData(t)}async getSummary(){const e=Be,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getBanStats(){const e=De,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getTokenBanStats(){const e=Me,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getInviteStats(){const e=Oe,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getFlagStats(){const e=Ue,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getUserStats(){const e=Le,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async listOverseerUsers(e){const t=e??{};Object.keys(t).length>0&&CT(t);const n=Pe,r=this.buildPaginationParams(t,In.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 i=await this.http.get(n,r,this.getDualAuthHeaders()),s=this.extractData(i);return{items:s.users,pageInfo:s.pageInfo}}async getOverseerUserSummary(e){if(!sr(e))throw Pt("address","User address");IT(e);const t=this.buildEndpoint(Fe,{address:e}),n=await this.http.get(t,{},this.getDualAuthHeaders());return this.extractData(n)}async flushCacheByAddress(e){pT(e);const t=this.buildEndpoint($e,{address:e}),n=await this.http.delete(t,void 0,this.getDualAuthHeaders());return this.extractData(n)}async flushCacheByToken(e){!function(e){if(!sr(e))throw Pt("tokenName","Token name")}(e);const t=this.buildEndpoint(Ke,{tokenName:e}),n=await this.http.delete(t,void 0,this.getDualAuthHeaders());return this.extractData(n)}async flushAllCache(e){!function(e){if(!0!==e)throw new Rt("Safety confirmation required: must pass confirm=true to flush all cache","confirm","CONFIRMATION_REQUIRED")}(e);const t=Ge,n=await this.http.delete(t,{confirm:"true"},this.getDualAuthHeaders());return this.extractData(n)}async flushWalletAliasCache(e){if(void 0!==e){pT(e);const t=this.buildEndpoint(He,{address:e}),n=await this.http.delete(t,void 0,this.getDualAuthHeaders());return this.extractData(n)}const t=We,n=await this.http.delete(t,{confirm:"true"},this.getDualAuthHeaders());return this.extractData(n)}}function RT(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 BT extends Sr{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),en(t,"Platform config operation failed",!0),e.data}async getPlatformConfig(){const e=await this.http.get(V);return this.extractData(e)}async updatePlatformConfig(e){const t=RT(e);if(t.length>0)throw new Rt(t.join("; "),"options","VALIDATION_FAILED");const n=await this.http.put(z,e,this.getJwtHeaders());return this.extractData(n)}async getAvailableRoles(){const e=await this.http.get(Y);return this.extractData(e)}}class DT extends Sr{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(ot),t=this.extractData(e);return this.logger.debug("Fetched platform stats",{totalTokens:t.totalTokens,timestamp:t.timestamp}),{stats:t}}}class MT extends Sr{constructor(e,t=!1,n){super(e,t),this.tokenResolverService=n}async fetchTokenClassKeyByTokenName(e){if(""===e)throw Pt("tokenName","Token name");if(!this.tokenResolverService)throw Kt("TokenResolverService is required for token name resolution. Ensure it is passed to PriceHistoryService constructor.","tokenResolverService");try{hr(e)}catch(e){throw Kt(Et(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 Kt(`Token '${e}' not found or could not be resolved to vault address`,"tokenName");this.logger.debug(`Resolved '${e}' to vault address: ${t}`);const n=xo(SA(t));return this.logger.debug(`Extracted token class key: ${n}`),n}catch(t){if(wt(t)&&Et(t).includes("ConfigurationError"))throw t;throw $t(`Failed to resolve token name '${e}': ${Et(t)}`,500)}}async fetchPriceHistory(e){if(null==e)throw Pt("options","Fetch options");return this.logger.debug("Fetching price history from DEX Backend API with options:",e),this.validateOptions(e),await Ao(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 Kt("Token ID is required but was not provided or resolved","tokenId");const{normalizeToTokenInstanceKey:n}=await Promise.resolve().then(function(){return CA}),r=VA(xo(n(t))),{from:i,to:s,sortOrder:o="DESC"}=e,a=e.timeframe??this.inferTimeframe(i,s),c={token:r,timeframe:a};this.logger.debug(`Querying price series for token ${r}, timeframe ${a}`);const l=await this.http.get(O,c);if(null==l)throw $t("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 $t("Invalid API response: missing price series",500);const r="string"==typeof t.tokenId?t.tokenId:t.tokenName??xo(t.tokenId),i=t.from?.getTime(),s=t.to?.getTime(),o=e.prices.filter(e=>"number"==typeof e.time&&"number"==typeof e.price).filter(e=>(void 0===i||1e3*e.time>=i)&&(void 0===s||1e3*e.time<=s)).sort((e,t)=>"ASC"===n?e.time-t.time:t.time-e.time),a=Gn(t.offset,0),c=Gn(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 Pt("options","Fetch options");return this.logger.debug("Fetching all price history with options:",e),Ao(async()=>{const t=await AA((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?HE(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(dr(e,"tokenName","tokenId",{description:"token identifier"}),t&&!vn(t))throw Kt("from must be a valid Date","from");if(void 0!==n&&!vn(n))throw Kt("to must be a valid Date","to");null!=r&&Zn(r,"sortOrder"),cr(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 OT extends XE{constructor(e,t,n,r){super(e,t,n,!1,r)}async getRestrictedNames(){try{return{success:!0,data:(await this.http.get(Ze)).data}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}async updateRestrictedNames(e){try{if(!sr(e.content))throw new Rt("Content is required");return{success:!0,data:(await this.http.put(et,e)).data}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}}class UT extends XE{constructor(e,t,n,r=!1,i){super(e,t,n,r,i)}async getChatStatus(e){if(null==e||""===e)throw Pt("tokenName","Token name");return this.validateTokenName(e,En),Ao(async()=>{const t=this.buildEndpoint(tt,{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 Pt("tokenName","Token name");return this.validateTokenName(e,En),Ao(async()=>{const t=this.buildEndpoint(rt,{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 Pt("tokenName","Token name");return this.validateTokenName(e,En),Ao(async()=>{const t=this.buildEndpoint(nt,{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??ln(e)};return void 0!==t.status&&null!==t.status&&(n.status=t.status),n}async setSlowMode(e,t){if(null==e||""===e)throw Pt("tokenName","Token name");if(this.validateTokenName(e,En),"number"!=typeof t||t<0||t>600)throw new Error("slowModeSeconds must be a number between 0 and 600");return Ao(async()=>{const n=this.buildEndpoint(it,{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 LT extends Tr{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 PT={IDLE:"IDLE",ACTIVE:"ACTIVE",DISABLED:"DISABLED"},FT={READY:"READY",PROCESSING:"PROCESSING",ERRORED:"ERRORED",DELETED:"DELETED"},$T={ACTIVE:"ACTIVE",IDLE:"IDLE",ERRORED:"ERRORED",DISABLED:"DISABLED"},KT={YOUTUBE:"YOUTUBE",TWITCH:"TWITCH",FACEBOOK:"FACEBOOK",CUSTOM:"CUSTOM"},GT=lr(PT),HT=lr(FT),WT=lr(KT);function qT(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&>(t.status)&&(null===t.playbackId||"string"==typeof t.playbackId)&&"boolean"==typeof t.isLive}function jT(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"number"==typeof t.viewerCount}const VT={OWNER:"OWNER",MANAGER:"MANAGER",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MODERATOR:"MODERATOR"},zT={OWNER:"OWNER",MODERATOR:"MODERATOR"};lr(VT),lr(zT);const XT={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"},JT={...VT,OVERSEER:"OVERSEER"},YT=lr(JT);function QT(e){if(null==e||"object"!=typeof e)return!1;const t=e,n=t.permissions;return Array.isArray(n)&&n.every(e=>"string"==typeof e)&&(null===t.source||"owner"===t.source||"moderator_invite"===t.source||"api_key"===t.source||"overseer"===t.source)&&(void 0===t.matchedPreset||null===t.matchedPreset||"MODERATOR"===t.matchedPreset||"TECHNICAL_PRODUCER"===t.matchedPreset||"MANAGER"===t.matchedPreset)&&"boolean"==typeof t.isOwner&&"boolean"==typeof t.isOverseer}function ZT(e,t="tokenName"){hr(e,t,En)}function eI(e){if(ZT(e.tokenName),!sr(e.language))throw Pt("language");if(t=e.language,!sr(t)||!/^[a-z]{2}(-[A-Z]{2})?$/.test(t))throw new Rt('language must be a valid ISO 639-1 code (e.g., "en", "es", "zh-CN")',"language",xt.INVALID_FORMAT);var t}const tI={STREAM_STARTED:"stream.started",STREAM_STOPPED:"stream.stopped",RECORDING_READY:"recording.ready",SIMULCAST_ERROR:"simulcast.error"};class nI extends XE{constructor(e,t,n,r=!1,i){super(e,t,n,r,i)}async startStream(e){this.validateTokenName(e,En);const t=this.buildEndpoint(U,{tokenName:e}),n=await this.http.post(t,{},this.getJwtHeaders());return this.extractData(n)}async stopStream(e){this.validateTokenName(e,En);const t=this.buildEndpoint(L,{tokenName:e});await this.http.post(t,{},this.getJwtHeaders())}async disableStream(e){return this.toggleFeature(e,P,En)}async enableStream(e){return this.toggleFeature(e,F,En)}async resetStreamKey(e){this.validateTokenName(e,En);const t=this.buildEndpoint($,{tokenName:e}),n=await this.http.post(t,{},this.getJwtHeaders());return this.extractData(n)}async getStreamCredentials(e){this.validateTokenName(e,En);const t=this.buildEndpoint(Z,{tokenName:e}),n=await this.http.get(t,{},this.getJwtHeaders());return this.extractData(n)}async getRecordings(e){!function(e){ZT(e.tokenName),cr(0,void 0,Un,e.pageSize)}(e);const t=this.buildEndpoint(K,{tokenName:e.tokenName}),n=this.buildPaginationParams(e,Un),r=e.offset;"number"==typeof r&&(n.offset=String(r));const i=await this.http.get(t,n),s=this.extractData(i),o=e,a=s.pageSize??s.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:s.recordings,tokenName:ln(e.tokenName),page:s.page??l,limit:a,total:s.total,hasNext:s.recordings.length===a}}async getRecordingDownload(e,t){this.validateTokenName(e,En),this.validateRequiredString(t,"assetId","Asset ID");const n=this.buildEndpoint(G,{tokenName:e,assetId:t}),r=await this.http.get(n,{},this.getJwtHeaders());return this.extractData(r)}async deleteRecording(e,t){this.validateTokenName(e,En),this.validateRequiredString(t,"assetId","Asset ID");const n=this.buildEndpoint(H,{tokenName:e,assetId:t});await this.http.delete(n,void 0,this.getJwtHeaders())}async getSimulcastTargets(e){this.validateTokenName(e,En);const t=this.buildEndpoint(W,{tokenName:e}),n=await this.http.get(t);return this.extractData(n)}async addSimulcastTarget(e){!function(e){if(ZT(e.tokenName),!sr(e.platform))throw Pt("platform");if(!WT(e.platform))throw new Rt("platform must be one of: 'YOUTUBE', 'TWITCH', 'FACEBOOK', 'CUSTOM'","platform",xt.INVALID_VALUE);if(!sr(e.rtmpUrl))throw Pt("rtmpUrl");if(!On.STREAM_URL_PATTERN.test(e.rtmpUrl))throw new Rt("rtmpUrl must be a valid RTMP, RTMPS, or SRT URL","rtmpUrl",xt.INVALID_FORMAT);if(!sr(e.streamKey))throw Pt("streamKey");if(void 0!==e.name&&"string"!=typeof e.name)throw new Rt("name must be a string","name",xt.INVALID_TYPE)}(e);const t=this.buildEndpoint(q,{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,En),this.validateRequiredString(t,"targetId","Target ID");const n=this.buildEndpoint(j,{tokenName:e,targetId:t});await this.http.delete(n,void 0,this.getJwtHeaders())}async getGlobalStreamingStatus(){const e=await this.http.get(V);return this.extractData(e)}async disableGlobalStreaming(){const e=await this.http.put(z,{},this.getAdminHeaders());return this.extractData(e)}async enableGlobalStreaming(){const e=await this.http.put(X,{},this.getAdminHeaders());return this.extractData(e)}async setNextLiveStream(e){let t;!function(e){if(ZT(e.tokenName),null!==e.nextLiveStreamAt){if(!(e.nextLiveStreamAt instanceof Date||sr(e.nextLiveStreamAt)))throw new Rt("nextLiveStreamAt must be a Date, ISO 8601 string, or null","nextLiveStreamAt",xt.INVALID_TYPE);if("string"==typeof e.nextLiveStreamAt){const t=Date.parse(e.nextLiveStreamAt);if(isNaN(t))throw new Rt("nextLiveStreamAt must be a valid ISO 8601 date string","nextLiveStreamAt",xt.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,En);const t=`/v1/tokens/${e.toLowerCase().trim()}`;await this.http.patch(t,{nextLiveStreamAt:null},this.getJwtHeaders())}async setStreamLanguage(e){eI(e);const t=`/v1/tokens/${e.tokenName.toLowerCase().trim()}`;await this.http.patch(t,{streamLanguage:e.language},this.getJwtHeaders())}async getStreamRole(e){!function(e){ZT(e.tokenName)}(e);const t=this.buildEndpoint(J,{tokenName:e.tokenName}),n=this.jwtAuth?this.getJwtHeaders():{},r=await this.http.get(t,{},n);return this.extractData(r)}async getAvailableRoles(){const e=await this.http.get(Y);return this.extractData(e)}async getTokenAccess(e){!function(e){ZT(e.tokenName)}(e);const t=await this.http.get(Q,{tokenName:ln(e.tokenName)},this.getJwtHeaders());return this.extractData(t)}async setNextLiveStreamCountdown(e,t){return this.setNextLiveStream({tokenName:e,nextLiveStreamAt:t})}}const rI={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 iI extends Tr{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 Mt("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 uS({maxAttempts:this.config.reconnectAttempts,baseDelayMs:this.config.reconnectDelay}),this.isSocketIOAvailable=this.checkSocketIOAvailability()}checkSocketIOAvailability(){try{return"function"==typeof I||(this.logger.warn('⚠️ Socket.IO client not available. Install "socket.io-client" package.'),!1)}catch(e){return this.logger.warn("⚠️ Socket.IO availability check failed:",Et(e)),!1}}getRoomName(e){return`token:${ln(e)}`}bufferEvent(e,t,n){const r=`${e}:${t}`;let i=this.eventBuffer.get(r);i||(i=[],this.eventBuffer.set(r,i)),i.length>=this.MAX_BUFFER_SIZE&&(i.shift(),this.logger.warn(`⚠️ [Stream Buffer] Event buffer overflow for ${r} - dropping oldest event. Consider processing events faster or increasing buffer size.`)),i.push(n);const s=this.eventBufferTimeouts.get(r);s&&clearTimeout(s);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=ln(e),r=[{key:`${rI.STREAM_STATUS}:${n}`,callback:t.onStreamStatus},{key:`${rI.VIEWER_COUNT}:${n}`,callback:t.onViewerCount},{key:`${rI.CHAT_MESSAGE}:${n}`,callback:t.onChatMessage},{key:`${rI.CHAT_STATUS}:${n}`,callback:t.onChatStatus},{key:`${rI.CHAT_PINNED}:${n}`,callback:t.onChatPinned},{key:`${rI.CHAT_UNPINNED}:${n}`,callback:t.onChatUnpinned},{key:`${rI.STREAM_COUNTDOWN_UPDATED}:${n}`,callback:t.onCountdownUpdated},{key:`${rI.STREAM_LANGUAGE_UPDATED}:${n}`,callback:t.onLanguageUpdated},{key:`${rI.TOKEN_BANNED}:${n}`,callback:t.onTokenBanned},{key:`${rI.TOKEN_UNBANNED}:${n}`,callback:t.onTokenUnbanned},{key:`${rI.MODERATOR_INVITE_CREATED}:${n}`,callback:t.onModeratorInviteCreated},{key:`${rI.MODERATOR_ADDED}:${n}`,callback:t.onModeratorAdded},{key:`${rI.MODERATOR_REMOVED}:${n}`,callback:t.onModeratorRemoved},{key:`${rI.MODERATOR_ROLE_UPDATED}:${n}`,callback:t.onModeratorRoleUpdated},{key:`${rI.TRADE_EXECUTED}:${n}`,callback:t.onTradeExecuted},{key:`${rI.BALANCE_UPDATED}:${n}`,callback:t.onBalanceUpdated},{key:`${rI.POOL_METADATA_UPDATED}:${n}`,callback:t.onPoolMetadataUpdated},{key:`${rI.POOL_SOCIAL_LINKS_UPDATED}:${n}`,callback:t.onPoolSocialLinksUpdated},{key:`${rI.POOL_BADGE_ASSIGNED}:${n}`,callback:t.onPoolBadgeAssigned},{key:`${rI.HOLDER_COUNT_UPDATED}:${n}`,callback:t.onHolderCountUpdated},{key:`${rI.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(rI.STREAM_STATUS,e=>{this.logger.debug(`📡 [Stream Status] ${e.tokenName}: ${e.status}`),this.bufferEvent(rI.STREAM_STATUS,e.tokenName,e);const t=this.roomCallbacks.get(ln(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(rI.STREAM_SUBSCRIBED,e=>{this.logger.debug(`📡 [Subscribed] ${e.tokenName}`);const t=ln(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(rI.STREAM_UNSUBSCRIBED,e=>{const t=e.room.replace("token:","");this.logger.debug(`📡 [Unsubscribed] ${t}`);const n=this.roomCallbacks.get(ln(t));n?.onStreamUnsubscribed&&n.onStreamUnsubscribed(e)}),this.socket.on(rI.VIEWER_COUNT,e=>{this.logger.debug(`📡 [Viewer Count] ${e.tokenName}: ${e.viewerCount}`),this.bufferEvent(rI.VIEWER_COUNT,e.tokenName,e);const t=this.roomCallbacks.get(ln(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(rI.STREAM_GLOBAL_STATUS,e=>{this.logger.debug(`📡 [Global Stream Status] enabled: ${String(e.enabled)}`),this.globalCallbacks.onStreamGlobalStatus&&this.globalCallbacks.onStreamGlobalStatus(e)}),this.socket.on(rI.CHAT_MESSAGE,e=>{this.logger.debug(`📡 [Chat Message] ${e.tokenName}: ${e.content.slice(0,50)}...`),this.bufferEvent(rI.CHAT_MESSAGE,e.tokenName,e);const t=this.roomCallbacks.get(ln(e.tokenName));t?.onChatMessage&&t.onChatMessage(e),this.globalCallbacks.onChatMessage&&this.globalCallbacks.onChatMessage(e)}),this.socket.on(rI.CHAT_SENT,e=>{this.logger.debug(`📡 [Chat Sent] ${e.tokenName}: ${e.messageId}`);const t=this.roomCallbacks.get(ln(e.tokenName));t?.onChatSent&&t.onChatSent(e)}),this.socket.on(rI.CHAT_ERROR,e=>{this.logger.error(`📡 [Chat Error] ${e.tokenName}: ${e.message}`);const t=this.roomCallbacks.get(ln(e.tokenName));t?.onChatError&&t.onChatError(e),this.globalCallbacks.onChatError&&this.globalCallbacks.onChatError(e)}),this.socket.on(rI.CHAT_STATUS,e=>{this.logger.debug(`📡 [Chat Status] ${e.tokenName}: ${String(e.enabled)}`),this.bufferEvent(rI.CHAT_STATUS,e.tokenName,e);const t=this.roomCallbacks.get(ln(e.tokenName));t?.onChatStatus&&t.onChatStatus(e),this.globalCallbacks.onChatStatus&&this.globalCallbacks.onChatStatus(e)}),this.socket.on(rI.CHAT_GLOBAL_STATUS,e=>{this.logger.debug(`📡 [Global Chat Status] enabled: ${String(e.enabled)}`),this.globalCallbacks.onChatGlobalStatus&&this.globalCallbacks.onChatGlobalStatus(e)}),this.socket.on(rI.CHAT_AUTHENTICATED,e=>{this.logger.debug(`📡 [Authenticated] ${e.address}`),this.isAuthenticated=!0,this.globalCallbacks.onChatAuthenticated&&this.globalCallbacks.onChatAuthenticated(e)}),this.socket.on(rI.CHAT_AUTH_ERROR,e=>{this.logger.error(`📡 [Auth Error] ${e.message}`),this.isAuthenticated=!1,this.globalCallbacks.onChatAuthError&&this.globalCallbacks.onChatAuthError(e)}),this.socket.on(rI.REACTION,e=>{this.logger.debug(`📡 [Reaction] ${e.tokenName}: ${e.emoji}`);const t=this.roomCallbacks.get(ln(e.tokenName));t?.onReaction&&t.onReaction(e),this.globalCallbacks.onReaction&&this.globalCallbacks.onReaction(e)}),this.socket.on(rI.REACTION_ERROR,e=>{this.logger.error(`📡 [Reaction Error] ${e.tokenName}: ${e.message}`);const t=this.roomCallbacks.get(ln(e.tokenName));t?.onReactionError&&t.onReactionError(e),this.globalCallbacks.onReactionError&&this.globalCallbacks.onReactionError(e)}),this.socket.on(rI.USER_TYPING,e=>{const t=e.typingUsers.length;this.logger.debug(`📡 [Typing] ${e.tokenName}: ${t} user(s) typing`);const n=this.roomCallbacks.get(ln(e.tokenName));n?.onTypingIndicator&&n.onTypingIndicator(e),this.globalCallbacks.onTypingIndicator&&this.globalCallbacks.onTypingIndicator(e)}),this.socket.on(rI.CHAT_PINNED,e=>{this.logger.debug(`📡 [Chat Pinned] ${e.tokenName}: ${e.pinnedMessage.messageId}`),this.bufferEvent(rI.CHAT_PINNED,e.tokenName,e);const t=this.roomCallbacks.get(ln(e.tokenName));t?.onChatPinned&&t.onChatPinned(e),this.globalCallbacks.onChatPinned&&this.globalCallbacks.onChatPinned(e)}),this.socket.on(rI.CHAT_UNPINNED,e=>{this.logger.debug(`📡 [Chat Unpinned] ${e.tokenName}: ${e.unpinnedMessageId}`),this.bufferEvent(rI.CHAT_UNPINNED,e.tokenName,e);const t=this.roomCallbacks.get(ln(e.tokenName));t?.onChatUnpinned&&t.onChatUnpinned(e),this.globalCallbacks.onChatUnpinned&&this.globalCallbacks.onChatUnpinned(e)}),this.socket.on(rI.STREAM_COUNTDOWN_UPDATED,e=>{const t=e.nextLiveStreamAt??"cleared";this.logger.debug(`📡 [Countdown Updated] ${e.tokenName}: ${t}`),this.bufferEvent(rI.STREAM_COUNTDOWN_UPDATED,e.tokenName,e);const n=this.roomCallbacks.get(ln(e.tokenName));n?.onCountdownUpdated&&n.onCountdownUpdated(e),this.globalCallbacks.onCountdownUpdated&&this.globalCallbacks.onCountdownUpdated(e)}),this.socket.on(rI.STREAM_LANGUAGE_UPDATED,e=>{this.logger.debug(`📡 [Language Updated] ${e.tokenName}: ${e.language}`),this.bufferEvent(rI.STREAM_LANGUAGE_UPDATED,e.tokenName,e);const t=this.roomCallbacks.get(ln(e.tokenName));t?.onLanguageUpdated&&t.onLanguageUpdated(e),this.globalCallbacks.onLanguageUpdated&&this.globalCallbacks.onLanguageUpdated(e)}),this.socket.on(rI.TOKEN_BANNED,e=>{this.logger.debug(`📡 [Token Banned] ${e.tokenName}`),this.bufferEvent(rI.TOKEN_BANNED,e.tokenName,e);const t=this.roomCallbacks.get(ln(e.tokenName));t?.onTokenBanned&&t.onTokenBanned(e),this.globalCallbacks.onTokenBanned&&this.globalCallbacks.onTokenBanned(e)}),this.socket.on(rI.TOKEN_UNBANNED,e=>{this.logger.debug(`📡 [Token Unbanned] ${e.tokenName}`),this.bufferEvent(rI.TOKEN_UNBANNED,e.tokenName,e);const t=this.roomCallbacks.get(ln(e.tokenName));t?.onTokenUnbanned&&t.onTokenUnbanned(e),this.globalCallbacks.onTokenUnbanned&&this.globalCallbacks.onTokenUnbanned(e)}),this.socket.on(rI.MODERATOR_INVITE_CREATED,e=>{this.logger.debug(`📡 [Moderator Invite Created] ${e.tokenName}: by ${e.invitedBy}`),this.bufferEvent(rI.MODERATOR_INVITE_CREATED,e.tokenName,e);const t=this.roomCallbacks.get(ln(e.tokenName));t?.onModeratorInviteCreated&&t.onModeratorInviteCreated(e)}),this.socket.on(rI.MODERATOR_ADDED,e=>{this.logger.debug(`📡 [Moderator Added] ${e.tokenName}: ${e.userAddress}`),this.bufferEvent(rI.MODERATOR_ADDED,e.tokenName,e);const t=this.roomCallbacks.get(ln(e.tokenName));t?.onModeratorAdded&&t.onModeratorAdded(e)}),this.socket.on(rI.MODERATOR_REMOVED,e=>{this.logger.debug(`📡 [Moderator Removed] ${e.tokenName}: ${e.userAddress}`),this.bufferEvent(rI.MODERATOR_REMOVED,e.tokenName,e);const t=this.roomCallbacks.get(ln(e.tokenName));t?.onModeratorRemoved&&t.onModeratorRemoved(e)}),this.socket.on(rI.MODERATOR_ROLE_UPDATED,e=>{this.logger.debug(`📡 [Moderator Role Updated] ${e.tokenName}: ${e.userAddress}`),this.bufferEvent(rI.MODERATOR_ROLE_UPDATED,e.tokenName,e);const t=this.roomCallbacks.get(ln(e.tokenName));t?.onModeratorRoleUpdated&&t.onModeratorRoleUpdated(e)}),this.socket.on(rI.OVERSEER_ADDED,e=>{this.logger.debug(`📡 [Overseer Added] ${e.userAddress}`),this.globalCallbacks.onOverseerAdded&&this.globalCallbacks.onOverseerAdded(e)}),this.socket.on(rI.OVERSEER_REMOVED,e=>{this.logger.debug(`📡 [Overseer Removed] ${e.userAddress}`),this.globalCallbacks.onOverseerRemoved&&this.globalCallbacks.onOverseerRemoved(e)}),this.socket.on(rI.TRADE_EXECUTED,e=>{this.logger.debug(`📡 [Trade Executed] ${e.tokenName}: ${e.tradeType}`),this.bufferEvent(rI.TRADE_EXECUTED,e.tokenName,e);const t=this.roomCallbacks.get(ln(e.tokenName));t?.onTradeExecuted&&t.onTradeExecuted(e),this.isGlobalFeedSubscribed&&!t&&this.globalFeedCallbacks.onTradeExecuted&&this.globalFeedCallbacks.onTradeExecuted(e)}),this.socket.on(rI.BALANCE_UPDATED,e=>{this.logger.debug(`📡 [Balance Updated] ${e.tokenName}: ${e.tradeType}`),this.bufferEvent(rI.BALANCE_UPDATED,e.tokenName,e);const t=this.roomCallbacks.get(ln(e.tokenName));t?.onBalanceUpdated&&t.onBalanceUpdated(e)}),this.socket.on(rI.POOL_METADATA_UPDATED,e=>{this.logger.debug(`📡 [Pool Metadata Updated] ${e.tokenName}`),this.bufferEvent(rI.POOL_METADATA_UPDATED,e.tokenName,e);const t=this.roomCallbacks.get(ln(e.tokenName));t?.onPoolMetadataUpdated&&t.onPoolMetadataUpdated(e)}),this.socket.on(rI.POOL_SOCIAL_LINKS_UPDATED,e=>{this.logger.debug(`📡 [Pool Social Links Updated] ${e.tokenName}`),this.bufferEvent(rI.POOL_SOCIAL_LINKS_UPDATED,e.tokenName,e);const t=this.roomCallbacks.get(ln(e.tokenName));t?.onPoolSocialLinksUpdated&&t.onPoolSocialLinksUpdated(e)}),this.socket.on(rI.POOL_BADGE_ASSIGNED,e=>{this.logger.debug(`📡 [Pool Badge Assigned] ${e.tokenName}: ${e.badge}`),this.bufferEvent(rI.POOL_BADGE_ASSIGNED,e.tokenName,e);const t=this.roomCallbacks.get(ln(e.tokenName));t?.onPoolBadgeAssigned&&t.onPoolBadgeAssigned(e),this.isGlobalFeedSubscribed&&!t&&this.globalFeedCallbacks.onPoolBadgeAssigned&&this.globalFeedCallbacks.onPoolBadgeAssigned(e)}),this.socket.on(rI.HOLDER_COUNT_UPDATED,e=>{this.logger.debug(`📡 [Holder Count Updated] ${e.tokenName}: ${e.holderCount}`),this.bufferEvent(rI.HOLDER_COUNT_UPDATED,e.tokenName,e);const t=this.roomCallbacks.get(ln(e.tokenName));t?.onHolderCountUpdated&&t.onHolderCountUpdated(e),this.isGlobalFeedSubscribed&&!t&&this.globalFeedCallbacks.onHolderCountUpdated&&this.globalFeedCallbacks.onHolderCountUpdated(e)}),this.socket.on(rI.COMMENT_CREATED,e=>{this.logger.debug(`📡 [Comment Created] ${e.tokenName}: ID ${e.id}`),this.bufferEvent(rI.COMMENT_CREATED,e.tokenName,e);const t=this.roomCallbacks.get(ln(e.tokenName));t?.onCommentCreated&&t.onCommentCreated(e)}),this.socket.on(rI.USER_PROFILE_UPDATED,e=>{this.logger.debug(`📡 [User Profile Updated] ${e.userAddress}`),this.globalCallbacks.onUserProfileUpdated&&this.globalCallbacks.onUserProfileUpdated(e)}),this.socket.on(rI.API_KEY_CREATED,e=>{this.logger.debug(`📡 [API Key Created] ${e.keyId}`),this.globalCallbacks.onApiKeyCreated&&this.globalCallbacks.onApiKeyCreated(e)}),this.socket.on(rI.API_KEY_UPDATED,e=>{this.logger.debug(`📡 [API Key Updated] ${e.keyId}`),this.globalCallbacks.onApiKeyUpdated&&this.globalCallbacks.onApiKeyUpdated(e)}),this.socket.on(rI.API_KEY_REVOKED,e=>{this.logger.debug(`📡 [API Key Revoked] ${e.keyId}`),this.globalCallbacks.onApiKeyRevoked&&this.globalCallbacks.onApiKeyRevoked(e)}),this.socket.on(rI.TOKEN_CONFIG_UPDATED,e=>{this.logger.debug(`📡 [Token Config Updated] ${e.tokenName}`),this.bufferEvent(rI.TOKEN_CONFIG_UPDATED,e.tokenName,e);const t=this.roomCallbacks.get(ln(e.tokenName));t?.onTokenConfigUpdated&&t.onTokenConfigUpdated(e),this.isGlobalFeedSubscribed&&!t&&this.globalFeedCallbacks.onTokenConfigUpdated&&this.globalFeedCallbacks.onTokenConfigUpdated(e)}),this.socket.on(rI.STATS_UPDATED,e=>{this.logger.debug(`📡 [Stats Updated] ${e.tokenName} price=${e.galaPrice}`),this.bufferEvent(rI.STATS_UPDATED,e.tokenName,e);const t=this.roomCallbacks.get(ln(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(rI.ENGAGEMENT_STATS_UPDATED,e=>{this.logger.debug(`📡 [Engagement Stats Updated] ${e.tokenName} chatters=${e.chat.uniqueChatters}`),this.bufferEvent(rI.ENGAGEMENT_STATS_UPDATED,e.tokenName,e);const t=this.roomCallbacks.get(ln(e.tokenName));t?.onEngagementStatsUpdated&&t.onEngagementStatsUpdated(e),this.globalCallbacks.onEngagementStatsUpdated&&this.globalCallbacks.onEngagementStatsUpdated(e)}),this.socket.on(rI.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(rI.GLOBAL_FEED_UNSUBSCRIBED,e=>{this.logger.debug("📡 [Global Feed Unsubscribed]"),this.isGlobalFeedSubscribed=!1,this.globalFeedCallbacks.onGlobalFeedUnsubscribed&&this.globalFeedCallbacks.onGlobalFeedUnsubscribed(e)}),this.socket.on(rI.SITE_CONFIG_CHANGED,e=>{this.logger.debug(`📡 [Site Config Changed] ${e.key}`),this.globalFeedCallbacks.onSiteConfigChanged&&this.globalFeedCallbacks.onSiteConfigChanged(e)}),this.socket.on(rI.STREAM_GLOBAL_STATUS,e=>{this.logger.debug(`📡 [Stream Global Status] enabled=${String(e.enabled)}`),this.globalFeedCallbacks.onStreamGlobalStatus&&this.globalFeedCallbacks.onStreamGlobalStatus(e)}),this.socket.on(rI.CHAT_GLOBAL_STATUS,e=>{this.logger.debug(`📡 [Chat Global Status] enabled=${String(e.enabled)}`),this.globalFeedCallbacks.onStreamChatGlobalStatus&&this.globalFeedCallbacks.onStreamChatGlobalStatus(e)}),this.socket.on(rI.COMMENTS_GLOBAL_STATUS,e=>{this.logger.debug(`📡 [Comments Global Status] enabled=${String(e.enabled)}`),this.globalFeedCallbacks.onCommentsGlobalStatus&&this.globalFeedCallbacks.onCommentsGlobalStatus(e)}),this.socket.on(rI.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(rI.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(rI.SUBSCRIBE_GLOBAL_FEED)}catch(e){this.logger.error("Failed to re-subscribe to global feed:",e)}}async connect(){return new Promise((e,t)=>{Ao(async()=>{if(!this.isSocketIOAvailable)throw new Mt('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=I(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 Rt("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(""===e)throw Pt("token","Authentication token");this.logger.debug("📡 Authenticating with stream server"),this.socket.emit(rI.AUTHENTICATE,{token:e}),this.config.authToken=e}async subscribeToStream(e,t={}){if(""===e)throw Pt("tokenName","Token name");if(!this.socket?.connected)throw new Rt("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");const n=ln(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,i)=>{const s=setTimeout(()=>{this.pendingSubscriptions.delete(n),i(new Error(`Subscription to ${e} timed out after ${this.config.subscriptionTimeout}ms`))},this.config.subscriptionTimeout);this.pendingSubscriptions.set(n,{resolve:r,reject:i,timeoutId:s}),this.roomCallbacks.set(n,t),this.subscribedRooms.set(n,{tokenName:n,subscribedAt:Date.now()}),this.logger.debug(`📡 Subscribing to stream: ${n}`),this.socket.emit(rI.SUBSCRIBE,{tokenName:n})})}unsubscribeFromStream(e){const t=ln(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(rI.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 Pt("tokenName","Token name");if(""===t)throw Pt("content","Message content");if(!this.socket?.connected)throw new Rt("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(!this.isAuthenticated)throw new Rt("Not authenticated. Call authenticate() first.","auth","NOT_AUTHENTICATED");const n=ln(e);this.logger.debug(`📡 Sending chat message to ${n}: ${t.slice(0,30)}...`),this.socket.emit(rI.SEND_CHAT,{tokenName:n,content:t})}sendReaction(e,t,n=0){if(""===e)throw Pt("tokenName","Token name");if(""===t)throw Pt("emoji");if(!this.socket?.connected)throw new Rt("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(!this.isAuthenticated)throw new Rt("Not authenticated. Call authenticate() first.","auth","NOT_AUTHENTICATED");const r=ln(e);this.logger.debug(`📡 Sending reaction to ${r}: ${t}`),this.socket.emit(rI.SEND_REACTION,{tokenName:r,emoji:t,streamTime:n})}sendTypingStart(e){this.sendTypingEvent(e,rI.TYPING_START,"typing_start")}sendTypingStop(e){this.sendTypingEvent(e,rI.TYPING_STOP,"typing_stop")}sendTypingEvent(e,t,n){if(""===e)throw Pt("tokenName","Token name");if(!this.socket?.connected)throw new Rt("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(!this.isAuthenticated)throw new Rt("Not authenticated. Call authenticate() first.","auth","NOT_AUTHENTICATED");const r=ln(e);this.logger.debug(`📡 Sending ${n} to ${r}`),this.socket.emit(t,{tokenName:r})}subscribeTokenBanned(e,t){const n=ln(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=ln(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=ln(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=ln(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=ln(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=ln(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=ln(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=ln(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=ln(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=ln(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=ln(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=ln(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 Rt("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(rI.SUBSCRIBE_GLOBAL_FEED)})}unsubscribeFromGlobalFeed(){this.isGlobalFeedSubscribed?(this.logger.debug("📡 Unsubscribing from global feed"),this.socket?.connected&&this.socket.emit(rI.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 sI(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"number"==typeof t.id&&"string"==typeof t.tokenName&&"string"==typeof t.bannedBy&&"string"==typeof t.createdAt&&(null===t.reason||"string"==typeof t.reason)}function oI(e){return null==e||""===e||"string"==typeof e&&(!vr(e)&&e.length<=_n.BAN_REASON.MAX_LENGTH)}function aI(e){if(hr(e.tokenName,"tokenName",En),!oI(e.reason))throw new Rt(`reason must be at most ${_n.BAN_REASON.MAX_LENGTH} characters`,"reason","TOO_LONG")}function cI(e){hr(e.tokenName,"tokenName",En)}function lI(e){cr(0,void 0,Sn,e.pageSize)}function uI(e){hr(e.tokenName,"tokenName",En)}class dI extends XE{constructor(e,t,n,r=!1,i){super(e,t,n,r,i)}async banToken(e){aI(e);const t=qe,n={tokenName:ln(e.tokenName)};if(void 0!==e.reason)try{Qn(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:ln(e.tokenName)}}async unbanToken(e){cI(e);const t=this.buildEndpoint(ze,{tokenName:e.tokenName});return en(await this.http.delete(t,void 0,this.getDualAuthHeaders()),"Failed to unban token",!1),{tokenName:ln(e.tokenName)}}async listTokenBans(e={}){lI(e);const t=je,n=this.buildPaginationParams(e,Sn);this.addOptionalFilterParams(n,e,["search"]);const r=await this.http.get(t,n,this.getDualAuthHeaders()),i=this.extractData(r);return{items:i.bans,pageInfo:i.pageInfo}}async getTokenBan(e){uI(e);const t=this.buildEndpoint(Ve,{tokenName:e.tokenName}),n=await this.http.get(t,{},this.getDualAuthHeaders()),r=this.extractDataOrNull(n);return{banned:null!==r,...null!==r&&{ban:r},tokenName:ln(e.tokenName)}}async isTokenBanned(e){return this.getTokenBan(e)}}class hI extends Tr{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(!sr(e))throw Pt("tokenName","Token name");const t=ln(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(!sr(e))throw Pt("tokenName","Token name");const t=ln(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 Lt(e);const i=this.parseVaultAddressToTokenClassKey(r);return this.setCacheEntry(t,{vaultAddress:r,tokenClassKey:i,cachedAt:Date.now()}),i}get(e){const t=this.getCacheEntry(ln(e));return t?.vaultAddress??null}getCacheEntry(e){return this.cache.get(e)??null}setCacheEntry(e,t){this.cache.size>=hI.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=ln(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:hI.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(ln(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=ln(t);this.setCacheEntry(e,{vaultAddress:n,tokenClassKey:r,cachedAt:Date.now()})}}parseVaultAddressToTokenClassKey(e){try{return SA(e)}catch(e){if(e instanceof Rt)throw Ft("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad","Vault address");throw e}}}hI.MAX_CACHE_SIZE=1e4;class gI extends Sr{constructor(e,t=!1){super(e,t)}async fetchLaunchpadFee(){return rn(()=>this.http.get(at),{errorContext:"Failed to fetch launchpad fee"})}async fetchSaleDetails(e){return rn(()=>this.http.get(ct,{tokenName:e}),{errorContext:`Failed to fetch sale details for ${e}`})}async getTradeQuote(e){return rn(()=>this.http.get(lt,{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 rn(()=>this.http.get(ut,{amount:e}),{errorContext:"Failed to get premint quote"})}}class fI extends XE{constructor(e,t,n,r=!1,i){super(e,t,n,r,i)}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 Mt("userAddresses must be a non-empty array");const t=await this.getConnectedClients({userAddresses:e.join(","),limit:e.length}),n=t.clients.filter(e=>"string"==typeof e.address&&""!==e.address).map(e=>e.address);return{online:n,offline:e.filter(e=>!n.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 mI{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,i={value:t};r>0&&(i.expiresAt=Date.now()+r),this.cache.set(e,i)}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 pI(e,t,n,r={}){const{logger:i,cacheNullish:s=!1,keyGenerator:o}=r,a=o?o(e):String(e),c=n.get(a);if(void 0!==c)return i&&i.debug(`Cache hit for key: ${a}`),c;i&&i.debug(`Cache miss for key: ${a}, fetching...`);const l=await t();return null!=l?(n.set(a,l),i&&i.debug(`Cached result for key: ${a}`)):s&&(n.set(a,l),i&&i.debug(`Cached nullish result for key: ${a}`)),l}class yI extends Tr{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 uS({maxAttempts:this.config.reconnectAttempts??5,baseDelayMs:this.config.reconnectDelay??2e3}),this.eventBuffer=new mI(3e4),this.isSocketIOAvailable=this.checkSocketIOAvailability(),yI.instances.add(this)}checkSocketIOAvailability(){try{return"function"==typeof I||(this.logger.warn('⚠️ Socket.IO client not available. Install "socket.io-client" package.'),!1)}catch(e){return this.logger.warn("⚠️ Socket.IO availability check failed:",e),!1}}async connect(){return new Promise((e,t)=>{Ao(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:",Et(e)),e}this.logger.debug("🔌 Connecting to Socket.IO server:",this.config.url),this.socket=I(this.config.url,{transports:["websocket"],reconnection:!0,reconnectionAttempts:this.config.reconnectAttempts??5,reconnectionDelay:this.config.reconnectDelay??2e3}),this.socket.on("connect",()=>{this.logger.debug("✅ Socket.IO connected successfully:",this.socket?.id),this.logger.debug("📡 Connected to bundle backend WebSocket:",this.config.url),this.logger.debug("🔗 Ready to monitor transaction updates"),this.reconnectionManager.reset(),e()}),this.socket.on("connect_error",e=>{this.logger.error("❌ Socket.IO connection error:",e),t(e)}),this.socket.on("disconnect",e=>{this.logger.debug(`🔌 Socket.IO disconnected: ${e}`),this.handleReconnect()}),this.socket.on("error",e=>{this.logger.error("❌ Socket.IO error:",e)}),this.socket.onAny((e,...t)=>{if(""!==e&&t.length>0&&"object"==typeof t[0]&&null!==t[0]){const n=t[0],r=n.status??n.Status;"string"==typeof r&&(this.logger.debug(`📡 [Event Buffer] Buffering event for ${e}: ${r}`),this.eventBuffer.size>=this.MAX_BUFFER_SIZE&&this.logger.warn(`📡 [Event Buffer] Buffer approaching limit (${this.eventBuffer.size}/${this.MAX_BUFFER_SIZE})`),this.eventBuffer.set(e,n))}this.debug&&this.logger.debug(`📡 [WebSocket Event] "${e}":`,JSON.stringify(t,null,2))}),this.hasOnAnyListener=!0},"Socket.IO connection failed",this.logger,e=>{this.logger.error("Socket.IO connection failed:",e);const n=wt(e)?e:new Error(Et(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,i=setTimeout(()=>{if(this.listeners.has(e)){const n=Math.round(r/1e3),i={transactionId:e,status:OE.TIMEOUT,message:`Transaction monitoring timeout - no response after ${n} seconds`,timestamp:Date.now()};this.logger.debug(`📡 Transaction timeout for ${e} (${n}s)`),t(i),this.listeners.delete(e),this.timeouts.delete(e),this.socket?.off(e)}},r);if(this.timeouts.set(e,i),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:OE.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,i=r?.data,s=r?.status??r?.Status??i?.status??i?.Status;let o=r?.message??r?.Message??i?.message??i?.Message??r?.error??i?.error;sr(o)||(o=s===ME.FAILED||s===ME.ERROR?"Transaction failed - check transaction details":s===ME.COMPLETED||s===ME.PROCESSED||s===ME.SUCCESS?"Transaction completed successfully":null!=s?`Transaction status: ${String(s)}`:"Unknown transaction status");const a=r?.blockHash??i?.blockHash,c=r?.gasUsed??i?.gasUsed,l=r?.Data??i?.Data,u={transactionId:e,status:this.mapSocketStatus(s),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(s)} -> ${u.status}`),this.logger.debug(`📡 Final message: "${String(o)}"`),n(u),u.status===OE.COMPLETED||u.status===OE.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===OE.COMPLETED?t(e):e.status!==OE.FAILED&&e.status!==OE.TIMEOUT||n(new Error(`Transaction ${String(e.status)}: ${e.message}`))})})}mapSocketStatus(e){const t=e?.toUpperCase();return UE[t]??OE.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")),yI.instances.delete(this)}static cleanupAll(e=!1){for(const e of yI.instances)e.disconnect();yI.instances.clear()}isConnected(){return this.socket?.connected??!1}getSocket(){return this.socket}}yI.instances=new Set;class bI extends Sr{constructor(e,t=!1){super(e,t)}extractData(e){if(e.error||void 0===e.data){const t=e.message??"Weekly challenge operation failed";throw new Error(t)}return e.data}async getLeaderboard(e={}){const{limit:t=10}=e;if(t<1||t>50)throw new Rt("limit must be between 1 and 50","limit","INVALID_LIMIT");this.logger.debug("Fetching weekly challenge leaderboard",{limit:t});const n={limit:String(t)},r=await this.http.get(dt.GET_LEADERBOARD,n),i=this.extractData(r);return this.logger.debug("Fetched weekly challenge leaderboard",{count:i.count}),{leaderboard:i}}async getTokenHistory(e){const{vaultAddress:t}=e;if("string"!=typeof t||""===t.trim())throw new Rt("vaultAddress is required","vaultAddress","REQUIRED_FIELD");this.logger.debug("Fetching token weekly history",{vaultAddress:t});const n=dt.GET_TOKEN_HISTORY.replace(":vaultAddress",encodeURIComponent(t)),r=await this.http.get(n),i=this.extractData(r);return this.logger.debug("Fetched token weekly history",{count:i.length}),{snapshots:i}}}class vI extends Ir{constructor(e=!1){super(e),this.lastFetchedAt=null}normalizeKey(e){return un(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 wI extends vI{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 EI extends _A{constructor(e,t=!1){super(e,t,"WrappableTokenService"),this.cache=new wI(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())})`),Ao(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 Ao(async()=>{const e=await async function(e){const{cache:t,fetchFn:n,logger:r,itemTypeName:i="items"}=e;if(t.has()){const e=t.getAll();return r&&r.debug(`Returning ${e.length} cached ${i}`),{items:e,fetchedAt:t.getFetchTimestamp()??Date.now(),itemCount:e.length}}r&&r.debug(`Fetching all ${i} (no cache)`);const s=await n();try{t.setAll(s)}catch(e){r&&r.error("Cache operation failed (non-fatal):",e)}return{items:s,fetchedAt:Date.now(),itemCount:s.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=NA(e),n=this.cache.getByTokenId(t);return n||(await pI("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=NA(e);await pI("wrappable:check",()=>this.fetchAllWrappableTokens(),{get:()=>this.cache.has()?{}:void 0,set:()=>{}},{logger:this.logger});const n=this.cache.getByTokenId(t),r=void 0!==n,i={isWrappable:r,tokenId:t};return r&&(i.wrapCounterpart=n.wrapCounterpart),i}getCacheStats(){return this.cache.getStats()}clearCache(){this.cache.clear()}}class AI extends Tr{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 WA(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 Pt("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()",i=t?"ALREADY_ON_ASSET_CHANNEL":"NOT_ON_ASSET_CHANNEL";throw new Rt(`Cannot ${t?"wrap":"unwrap"} ${n.symbol} - it's ${e}. Use ${r} instead.`,"tokenId",i)}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 Pt("tokenId","Token identifier");if(0===t.length)throw Pt("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 Rt(`Cannot ${n?"wrap":"unwrap"} ${r.symbol} - it's ${e}`,"tokenId",t)}const i=this.determineChannelRouting(r,n);return{fee:"0",feeToken:"GALA",authorizationType:i.authType,feeChannel:i.sourceChannel}}async executeChannelBridge(e){const{sourceToken:t,destinationToken:n,amount:r,recipient:i,isWrap:s}=e;if(void 0===this.nativeSigner||void 0===this.walletAddress||0===this.walletAddress.length)throw new Rt("Wallet required for wrap/unwrap operations. Initialize SDK with a private key.","wallet","WALLET_REQUIRED");const o=this.walletAddress,a=this.determineChannelRouting(t,s),c=`galaswap-operation-${ww()}`,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:i??o,wrap:!0,uniqueKey:c};return this.logger.debug(`[WrapService] ${s?"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:s,senderAddress:o})}async executeWrapBridgeRequest(e){const{sourceToken:t,destinationToken:n,amount:r,message:i,routing:s,isWrap:o}=e;try{const e=await this.nativeSigner.signObject("RequestTokenBridgeOut",i);this.logger.debug(`[WrapService] ${o?"Wrap":"Unwrap"} request (signed)`,{sourceToken:t.symbol,destinationToken:n.symbol,amount:r,channel:s.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}`,i="string"==typeof a.Message&&a.Message.length>0?`: ${a.Message}`:"";return{success:!1,fromToken:t.symbol,toToken:n.symbol,amount:r,fromChannel:s.sourceChannel,toChannel:o?"asset":n.channel??"music",error:`GalaChain request failed (${e}${i})`}}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 i={bridgeFromChannel:s.sourceChannel,bridgeRequestId:e};this.logger.debug("[WrapService] Step 2 - BridgeTokenOut",{bridgeFromChannel:i.bridgeFromChannel});const c=await this.galaConnectClient.bridgeTokenOut(i);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:s.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:s.sourceChannel,toChannel:o?"asset":n.channel??"music",completedAt:Date.now()}}return{success:!1,fromToken:t.symbol,toToken:n.symbol,amount:r,fromChannel:s.sourceChannel,toChannel:o?"asset":n.channel??"music",error:`Unexpected response format from GalaChain (type=${typeof a})`}}catch(e){const i=Et(e);return this.logger.error(`[WrapService] ${o?"Wrap":"Unwrap"} operation failed:`,i),{success:!1,fromToken:t.symbol,toToken:n.symbol,amount:r,fromChannel:s.sourceChannel,toChannel:o?"asset":n.channel??"music",error:i}}}determineChannelRouting(e,t){if(t){return{sourceChannel:e.channel??"music",destinationChannelId:Do.ASSET,authType:"cross_channel_authorization"}}return{sourceChannel:"asset",destinationChannelId:Do.MUSIC,authType:"automatic"}}async getCounterpartOrThrow(e,t){const n=await this.wrappableTokenService.getWrapCounterpart(e);if(null==n)throw new Rt(`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 Rt(`Token not found or not wrappable: ${this.formatTokenId(e)}`,"tokenId","TOKEN_NOT_WRAPPABLE");return t}formatTokenId(e){return"string"==typeof e?e:xo(e)}}class kI 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 SI{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 TI{constructor(e){this.bundleBaseUrl=DI(e.bundleBaseUrl),this.launchpadBaseUrl=DI(e.launchpadBaseUrl),this.signer=e.signer,this.walletAddress=e.walletAddress,this.requestor=e.httpRequestor??fetch.bind(globalThis),this.socketFactory=e.socketFactory??(e=>I(e,{transports:["websocket"]}))}async submit(e){let t;try{t=await this.signer.signTypedData(e.method,e.dto)}catch(e){if(e instanceof kI)throw e;const t=e instanceof Error?e.message:"Launchpad signing failed.";throw new kI(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`,i=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})}),s=await RI(i);if(!i.ok)throw NI(i.status,s,r);const o=function(e){if("string"==typeof e&&""!==e)return e;if(!BI(e))throw new kI("Bundler returned no bundle id.","INVALID_BUNDLE_RESPONSE");const t=e.data,n=e.bundleId;if("string"==typeof t&&""!==t)return t;if(BI(t)&&"string"==typeof t.bundleId&&""!==t.bundleId)return t.bundleId;if("string"==typeof n&&""!==n)return n;throw new kI("Bundler returned no bundle id.","INVALID_BUNDLE_RESPONSE")}(s),a=xI(e.dto,"uniqueKey");return new SI({bundleId:o,uniqueKey:a,method:e.method,wait:t=>this.waitForResult(e,o,t)})}async waitForResult(e,t,n={}){const r=n.timeoutMs??6e4,i=n.pollIntervalMs??2500,s=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(!BI(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(II(r.data)):e(r))},o?.on(t,a)})}catch{o=void 0}const u=this.pollConfirmation(e,t,s,r,i);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,i){const s="CreateSale"===e.method,o=s?function(e,t){const n=xI(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 RI(e);if(s){if(e.ok)return{status:"PROCESSED",data:_I(t)};if(404!==e.status&&202!==e.status)throw NI(e.status,t,o)}else{if(!e.ok)throw NI(e.status,t,o);const n=BI(t)?t.status:void 0;if("COMPLETED"===n||"PROCESSED"===n)return{status:"PROCESSED",data:t};if("FAILED"===n)throw II(t)}const a=r-(Date.now()-n);if(a<=0)break;await MI(Math.min(Math.max(0,i),a))}throw new kI(`Timed out waiting for bundle ${e.dto.uniqueKey}`,"BUNDLE_CONFIRMATION_TIMEOUT",{details:{method:e.method}})}}function II(e){const t=CI(e)??"Launchpad bundle failed on chain.";return new kI(t,"BUNDLE_FAILED",{chainMessage:t})}function NI(e,t,n){const r=CI(t)??`Bundle request failed with HTTP ${e}`;return new kI(r,"BUNDLE_REQUEST_FAILED",{status:e,chainMessage:r,details:{body:t,url:n}})}function CI(e){if("string"==typeof e&&""!==e)return e;if(BI(e))for(const t of["chainMessage","message","Message","error"]){const n=e[t];if("string"==typeof n&&""!==n)return n;if(BI(n)){const e=CI(n);if(void 0!==e)return e}}}function _I(e){return BI(e)?e.data??e.Data??e:e}function xI(e,t){const n=e[t];if("string"!=typeof n||""===n)throw new kI(`Missing ${t} in launchpad DTO.`,"INVALID_LAUNCHPAD_DTO");return n}async function RI(e){try{return await e.json()}catch{return e.text()}}function BI(e){return"object"==typeof e&&null!==e}function DI(e){return e.replace(/\/$/u,"")}function MI(e){return new Promise(t=>setTimeout(t,e))}function OI(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,i,s,o,a,...c]=n.split("$");if(void 0===r||void 0===i||void 0===s||void 0===o||"launchpad"!==a||c.length>0||""===r||""===i||""===s||""===o)throw new Error(`Invalid vaultAddress format (expected service|<collection>$<category>$<type>$<additionalKey>$launchpad): ${e}`);return{collection:r,category:i,type:s,additionalKey:o}}function UI(e){const{collection:t,category:n,type:r}=OI(e),i=`${t}$${n}$${r}$none`,s="GALA$Unit$none$none";return[`$service$${i}$launchpad`,`$tokenBalance$${i}$${e}`,`$tokenBalance$${i}$${e}`,`$tokenBalance$${s}$${e}`,`$tokenBalance$${s}$${e}`]}function LI(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 PI{constructor(e){this.transport=e.transport,this.walletAddress=e.walletAddress}createSale(e){const t=function(e,t){const n={tokenName:e.tokenName,tokenSymbol:e.tokenSymbol,tokenDescription:e.tokenDescription,tokenImage:e.tokenImage,preBuyQuantity:e.preBuyQuantity??"0",websiteUrl:e.websiteUrl??"",telegramUrl:e.telegramUrl??"",twitterUrl:e.twitterUrl??"",instagramUrl:e.instagramUrl??"",facebookUrl:e.facebookUrl??"",redditUrl:e.redditUrl??"",tiktokUrl:e.tiktokUrl??"",tokenCategory:e.tokenCategory??"Unit",tokenCollection:e.tokenCollection??"Token",uniqueKey:e.uniqueKey??FI(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:LI(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??FI(this.walletAddress)};return this.transport.submit({method:e,dto:r,stringsInstructions:UI(t.vaultAddress)})}}function FI(e){return`galaswap-operation-${b()}-${Date.now()}-${e}`}class $I{constructor(e){this.gatewayBaseUrl=e.gatewayBaseUrl.replace(/\/$/u,""),this.signer=e.signer,this.walletAddress=VI(e.walletAddress),this.requestor=e.httpRequestor??fetch.bind(globalThis)}transfer(e){const t=KI(e),n={from:this.walletAddress,to:VI(e.to),quantity:e.quantity,tokenInstance:t,uniqueKey:e.uniqueKey??jI(this.walletAddress)};return this.direct("TransferToken",n)}burn(e){const t={tokenInstances:[{quantity:e.quantity,tokenInstanceKey:KI(e)}],uniqueKey:e.uniqueKey??jI(this.walletAddress)};return this.direct("BurnTokens",t)}lock(e){const t={lockAuthority:e.lockAuthority??this.walletAddress,tokenInstances:[{owner:this.walletAddress,quantity:e.quantity,tokenInstanceKey:KI(e)}],uniqueKey:e.uniqueKey??jI(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:KI(e)}],uniqueKey:e.uniqueKey??jI(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}`,i=await this.post(r,n),s=await async function(e){try{return await e.json()}catch{return e.text()}}(i),o=qI(s);if(!i.ok||void 0!==o?.Status&&1!==o.Status)throw function(e,t,n){const r=qI(t),i=WI(r,"Message")??WI(r,"message")??WI(r,"ErrorKey")??`Gateway request failed with HTTP ${e}`,s=WI(r,"ErrorKey")??"GATEWAY_REQUEST_FAILED";return new kI(i,s,{status:e,chainMessage:i,details:{body:t,url:n}})}(i.status,s,r);const a=qI(GI(s))?.mode??o?.mode;if(void 0!==a&&"sync"!==a){throw new kI(`Unsupported gateway transaction mode: ${"string"==typeof a?a:"non-sync"}`,"INVALID_GATEWAY_RESPONSE",{status:i.status,details:{body:s,url:r}})}const c=GI(s),l=zI(i,"x-transaction-id")??HI(c)??HI(s),u=function(e){const t=zI(e,"x-block-number");if(void 0===t)return;const n=Number.parseInt(t,10);return Number.isFinite(n)?n:void 0}(i);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 kI)throw e;const t=e instanceof Error?e.message:"Native GalaChain signing failed.";throw new kI(t,"NATIVE_SIGNING_FAILED",{chainMessage:t})}}}function KI(e){const t=e.tokenClassKey??e.symbol;if(void 0===t)throw new kI("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,i,s]=e.split(t);if(void 0===n||void 0===r||void 0===i||void 0===s||[n,r,i,s].some(e=>""===e))throw new kI(`Invalid token class key: ${e}`,"INVALID_TOKEN_IDENTIFIER");return{collection:n,category:r,type:i,additionalKey:s}}(t);return{...n,instance:e.instance??"0"}}function GI(e){const t=qI(e);return t?.Data??t?.data??e}function HI(e){if("string"==typeof e&&""!==e)return e;const t=qI(e);return WI(t,"transactionId")??WI(t,"txnId")??WI(t,"id")}function WI(e,t){const n=e?.[t];return"string"==typeof n&&""!==n?n:void 0}function qI(e){return"object"==typeof e&&null!==e?e:void 0}function jI(e){return`galaswap-operation-${b()}-${Date.now()}-${e}`}function VI(e){return"eth|0x"===e.slice(0,6).toLowerCase()?`eth|${e.slice(6)}`:e}function zI(e,t){const n=e.headers;if(void 0===n)return;if("function"==typeof n.get)return XI(n.get(t));const r=t.toLowerCase();for(const[e,t]of Object.entries(n))if(e.toLowerCase()===r)return XI(t)}function XI(e){const t=e?.trim();return void 0===t||""===t?void 0:t}function JI(e,t=3e4){return N.create({baseURL:e,timeout:t,headers:{"Content-Type":"application/json"}})}const YI=new Set(["accesstoken","refreshtoken","token","password","privatekey","secret","apikey","api_key","rawkey","authorization","x-api-key","bearer","streamadminapikey","userapikey","signature","signedpayload"]);function QI(e,t=0){if(t>5)return"[...]";if(null==e)return e;if(Array.isArray(e))return e.map(e=>QI(e,t+1));if(e instanceof Map){const n={};for(const[r,i]of e.entries()){const e=String(r);n[e]=YI.has(e.toLowerCase())?"[REDACTED]":QI(i,t+1)}return n}if("object"==typeof e){const n={};for(const[r,i]of Object.entries(e))n[r]=YI.has(r.toLowerCase())?"[REDACTED]":QI(i,t+1);return n}return e}class ZI{constructor(e,t={}){this.auth=e,this.debug=t.debug??!1,this.logger=new gn({debug:this.debug,context:"HttpClient"});const n=t.baseUrl??_o("stage").launchpadBaseUrl,r=t.timeout??6e4;this.axios=JI(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 Ao(async()=>{const t={method:e.method,url:e.url,data:e.data,...void 0!==e.params&&{params:qs(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]":QI(e.data);this.logger.debug("Request:",{method:e.method,url:e.url?.split("?")[0],baseURL:this.axios.defaults.baseURL,params:QI(t.params),data:n,isFormData:e.data instanceof FormData,contentType:t.headers?.["Content-Type"]??"not set"});const r=await this.axios.request(t),i=function(e){const t={};if(null==e||"object"!=typeof e)return t;for(const[n,r]of Object.entries(e))"string"==typeof r?t[n.toLowerCase()]=r:"number"!=typeof r&&"boolean"!=typeof r||(t[n.toLowerCase()]=String(r));return t}(r.headers);return this.logger.debug("Response:",{status:r.status,data:QI(r.data),transactionId:i["x-transaction-id"],blockNumber:i["x-block-number"]}),{data:r.data,headers:i,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 Ao(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??Et(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 eN extends Error{constructor(e,t){super(e),this.cause=t,this.name="WebSocketError"}}class tN extends eN{constructor(e,t){super(`WebSocket confirmation timeout for transaction ${e} after ${t}ms`),this.name="WebSocketTimeoutError"}}class nN 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 rN(e,t){if(ar(e))throw new eN(`Invalid WebSocket response received for transaction ${t}: response is null or undefined`);if("object"!=typeof e)throw new eN(`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 eN(`Invalid WebSocket response received for transaction ${t}: missing status field`)}function iN(e,t,n,r){rN(e,t);const i=e,s=i.data??{};if(!function(e){if(ar(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)}(s))throw new eN(`Invalid trade data received for transaction ${t}`);const o={transactionId:t,type:n,method:"native"===r.type?"native":"exact",inputAmount:s.inputQuantity??r.amount,outputAmount:s.outputQuantity??r.expectedAmount??"0",totalFees:s.totalFees??"0",tokenName:r.tokenName,vaultAddress:s.vaultAddress??"",timestamp:Date.now()};return void 0!==i.blockHash&&(o.blockHash=i.blockHash),void 0!==i.gasUsed&&(o.gasUsed=i.gasUsed),void 0!==r.slippageToleranceFactor&&(o.slippageTolerance=r.slippageToleranceFactor),o}function sN(e,t,n){return{types:{EIP712Domain:oN(e),...t},primaryType:Object.keys(t)[0],domain:aN(e),message:n}}function oN(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 aN(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 cN(e){return`0x${Buffer.from(e,"utf8").toString("hex")}`}class lN{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 i=t=>{const r=t[0];n(void 0===r?null:e(r))},s=()=>r();return t.on("accountsChanged",i),t.on("disconnect",s),{accountsChanged:i,disconnect:s}}(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 uN(e,t,n){try{return await e()}catch(e){if(e instanceof To)throw e;return t(e,n)}}const dN=4001,hN=4100,gN=4900,fN=4901;class mN extends lN{constructor(e){if(super(e),this.providerType="external",null==e)throw new To("EIP-1193 provider is required",vo.INVALID_CONFIG)}handleProviderError(e,t){const n=e;if(n.code===dN)throw new To(`User rejected ${t}`,vo.USER_REJECTED,e instanceof Error?e:void 0);if(n.code===hN)throw new To("Wallet is not authorized",vo.NOT_CONNECTED,e instanceof Error?e:void 0);if(n.code===gN||n.code===fN)throw this.connectedAddress=null,new To("Wallet disconnected",vo.NOT_CONNECTED,e instanceof Error?e:void 0);throw new To(n.message??`${t} failed`,t.includes("sign")?vo.SIGNING_FAILED:vo.UNKNOWN,e instanceof Error?e:void 0)}ensureConnected(){if(!this.connectedAddress)throw new To("Wallet is not connected. Call connect() first.",vo.NOT_CONNECTED)}async connect(){try{const t=await this.provider.request({method:"eth_requestAccounts"});if(null==t||0===t.length)throw new To("No accounts returned from wallet",vo.CONNECTION_FAILED);const n=t[0];if(void 0===n)throw new To("No accounts returned from wallet",vo.CONNECTION_FAILED);return this.connectedAddress=e(n),this.connectedAddress}catch(e){if(e instanceof To)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(),uN(()=>async function(e,t,n){return e.request({method:"personal_sign",params:[cN(n),t]})}(this.provider,this.connectedAddress,e),(e,t)=>this.handleProviderError(e,t),"sign message")}async signTypedData(e,t,n){return this.ensureConnected(),uN(()=>async function(e,t,n,r,i){return e.request({method:"eth_signTypedData_v4",params:[t,JSON.stringify(sN(n,r,i))]})}(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 To("Wallet is not connected",vo.NOT_CONNECTED);return e}async getGalaAddress(){return`eth|${(await this.getAddress()).slice(2)}`}async getPrivateKey(){return Promise.reject(new To("Private key is not accessible with external wallet providers. Use PrivateKeyProvider if you need private key access for @gala-chain operations.",vo.PRIVATE_KEY_NOT_ACCESSIBLE))}getProvider(){return this.provider}}function pN(e){if(null!==e.privateKey&&void 0!==e.privateKey&&e.privateKey.length>0)return new Io(e.privateKey);if(null!==e.eip1193Provider&&void 0!==e.eip1193Provider)return new mN(e.eip1193Provider);throw new To("Invalid wallet provider config: must provide either privateKey or eip1193Provider",vo.INVALID_CONFIG)}function yN(e){return Io.fromWallet(e)}function bN(e){return new mN(e)}function vN(e){return"privateKey"===e.providerType}function wN(e){return"external"===e.providerType}function EN(e){if(e)return Io.fromWallet(e)}function AN(e){if(e&&vN(e))return e.getWallet()}async function kN(e){return e.isConnected()?e.getAddress():e.connect()}function SN(e){return"object"==typeof e&&null!==e&&"request"in e&&"function"==typeof e.request}function TN(){if("undefined"==typeof window)return null;const e=window.ethereum;return SN(e)?e:null}class IN{constructor(e){let t,n;e.walletProvider?(t=e.walletProvider,n=AN(e.walletProvider)):e.wallet&&(n=e.wallet,t=Io.fromWallet(e.wallet)),this.wallet=n;const r=e.env??"prod",i=_o(r);this.environment=r,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 s=e.signer??(void 0!==n?new WA(n.privateKey):void 0),o=s??{signObject:()=>Promise.reject(new Error("A signer is required for token writes.")),signTypedData:()=>Promise.reject(new Error("A signer is required for launchpad writes."))},a=e.walletAddress??e.galaChainAddress??(void 0!==n?`eth|${n.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}(s))??"",c=new TI({bundleBaseUrl:this.config.bundleBaseUrl,launchpadBaseUrl:this.config.baseUrl,signer:o,walletAddress:a,...void 0!==e.httpRequestor&&{httpRequestor:e.httpRequestor}});if(this.launchpad=new PI({transport:c,walletAddress:a}),this.tokens=new $I({gatewayBaseUrl:this.config.gatewayBaseUrl,dexBackendBaseUrl:this.config.dexBackendBaseUrl,signer:o,walletAddress:a,...void 0!==e.httpRequestor&&{httpRequestor:e.httpRequestor}}),this.logger=new gn({debug:this.config.debug??!1,context:"LaunchpadSDK"}),this.validateConfiguration(),this.slippageToleranceFactor=void 0===e.slippageToleranceFactor?IN.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR:this.parseSlippageToleranceFactor(e.slippageToleranceFactor),this.maxAcceptableReverseBondingCurveFeeSlippageFactor=void 0===e.maxAcceptableReverseBondingCurveFeeSlippageFactor?IN.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR:this.parseFeeSlippageFactor(e.maxAcceptableReverseBondingCurveFeeSlippageFactor),this.calculateAmountMode=e.calculateAmountMode??IN.DEFAULT_CALCULATE_AMOUNT_MODE,this.galaChainAddressOverride=e.galaChainAddress,this.auth=new No({wallet:n,walletProvider:t,messagePrefix:"Create a GalaChain Wallet"}),this.jwtAuth=new Eo,void 0!==e.accessToken&&""!==e.accessToken){const t=e.accessTokenExpiresIn??86400;this.jwtAuth.setToken(e.accessToken,t)}this.http=new ZI(this.auth,this.config),this.sessionAuth=new So(this.http,this.auth,this.jwtAuth,e.debug??!1),this.galaChainHttp=new ZI(this.auth,{...this.config,baseUrl:this.config.gatewayBaseUrl}),this.bundleHttp=new ZI(this.auth,{...this.config,baseUrl:this.config.bundleBaseUrl}),this.dexApiHttp=new ZI(this.auth,{...this.config,baseUrl:this.config.dexApiBaseUrl}),this.dexBackendHttp=new ZI(this.auth,{...this.config,baseUrl:this.config.dexBackendBaseUrl}),this.galaChainPublicAxios=JI(this.config.gatewayBaseUrl,this.config.timeout??3e4),this.cache=new Nr(e.debug??!1),this.launchpadService=new KS(this.http,this.jwtAuth),this.tokenResolverService=new hI(this.launchpadService.poolService),this.launchpadAPI=new mo(this.http,this.tokenResolverService,this.logger,this.bundleHttp,this.galaChainHttp,this.dexApiHttp,this.calculateAmountMode,this.launchpad),this.galaChainService=new lS(this.galaChainHttp,n,this.tokenResolverService,e.debug??!1,this.galaChainPublicAxios),this.dexService=new wk(this.dexBackendHttp,this.cache,this.galaChainService,e.debug??!1),this.bundleService=new YA(this.bundleHttp,this.tokenResolverService,this.config.debug??!1,n,n?this.getAddress():void 0,this.slippageToleranceFactor,this.maxAcceptableReverseBondingCurveFeeSlippageFactor),this.websocketService=new yI({url:this.config.webSocketUrl},this.config.debug),this.priceHistoryService=new MT(this.dexBackendHttp,this.config.debug??!1,this.tokenResolverService);const l=e.signer??(void 0===n?void 0:new WA(n.privateKey)),u=e.walletAddress??(void 0===n?void 0:this.getAddress());this.dexClient=new m({env:this.environment,...void 0===l?{}:{signer:l},...void 0===u?{}:{walletAddress:u},...void 0===this.config.dexBackendBaseUrl?{}:{dexBackendBaseUrl:this.config.dexBackendBaseUrl},...void 0===this.config.gatewayBaseUrl?{}:{gatewayBaseUrl:this.config.gatewayBaseUrl},...void 0===e.httpRequestor?{}:{httpRequestor:e.httpRequestor}}),this.nftCollectionService=new gT(this.galaChainHttp),this.tradingQuotesService=new gI(this.http,e.debug??!1)}createOverrideSdk(e){if(!sr(e))throw Kt("Invalid privateKey: must be a non-empty string","privateKey");if(!e.match(/^0x[a-fA-F0-9]{64}$/))throw Kt('Invalid privateKey format: must be "0x" followed by 64 hexadecimal characters',"privateKey");const n=new t(e),r={...this.config,wallet:n};return new IN(r)}get dex(){return this.dexClient}getAddress(){return void 0!==this.galaChainAddressOverride&&""!==this.galaChainAddressOverride?this.galaChainAddressOverride:(this.validateWallet(),this.auth.getAddress())}getEthereumAddress(){return this.validateWallet(),this.wallet.address}validateWallet(){if(!this.wallet)throw Pt("wallet","Wallet");return this.wallet}setWallet(e){if(null==e||"object"!=typeof e||!("address"in e))throw new Rt("Invalid wallet: must be an ethers Wallet instance, received "+typeof e,"wallet","INVALID_WALLET");this.wallet=e,this.auth.setWallet(e)}setWalletProvider(e){this.auth.setWalletProvider(e),this.wallet=e?AN(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:i,userApiKey:s,accessToken:o,headers:a,...c}=this.config;return{...c,...void 0!==i&&{streamAdminApiKey:"[REDACTED]"},...void 0!==s&&{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:cn.GAS_FEE}}getVersion(){return LE}getUrlByTokenName(e){const t=this.config.launchpadFrontendUrl;if(void 0===t||""===t)throw Kt("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 i=n.holders[r];return void 0===i?null:{rank:r+1,balance:i.balance,holderCount:n.totalHolders}}async getHoldersByBalance(e,t){const n=await this.fetchTokenDistribution(e),r=t?.minBalance??0,i=t?.maxBalance??1/0,s=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<=i}).map(e=>({...e,rank:o.get(e.address)??0})).slice(0,s)}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}=dr(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 i=n;try{return await this.dexService.fetchTokenPrice({tokenId:i})}catch(e){const t=function(e){if(St(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=ln((await this.fetchTokenDetails(i)).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: ${Et(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(_t(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 $r}),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 DE({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 DA(this.dexApiHttp,this.config.debug??!1)),this._bridgeableTokenService}getWrappableTokenService(){return this._wrappableTokenService??(this._wrappableTokenService=new EI(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 dE({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 AI({galaConnectClient:this.getGalaConnectClient(),wrappableTokenService:this.getWrappableTokenService(),...e&&{walletAddress:this.getAddress(),wallet:e}})}return this._wrapService}getStreamingService(){return this._streamingService??(this._streamingService=new nI(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._streamingService}getStreamChatService(){return this._streamChatService??(this._streamChatService=new UT(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._streamChatService}getBanService(){return this._banService??(this._banService=new wA(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._banService}getTokenBanService(){return this._tokenBanService??(this._tokenBanService=new dI(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._tokenBanService}getAIModerationService(){return this._aiModerationService??(this._aiModerationService=new JE(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._aiModerationService}getWeeklyChallengeService(){return this._weeklyChallengeService??(this._weeklyChallengeService=new bI(this.http,this.config.debug??!1)),this._weeklyChallengeService}getOEmbedService(){return this._oembedService??(this._oembedService=new mT(this.http,this.config.debug??!1)),this._oembedService}getPlatformStatsService(){return this._platformStatsService??(this._platformStatsService=new DT(this.http,this.config.debug??!1)),this._platformStatsService}getNotificationService(){return this._notificationService??(this._notificationService=new fT(this.http,this.config.debug??!1,this.jwtAuth)),this._notificationService}getClientConfigService(){return this._clientConfigService??(this._clientConfigService=new QA(this.http,this.config.debug??!1)),this._clientConfigService}getApiKeyService(){return this._apiKeyService??(this._apiKeyService=new lA(this.http,this.jwtAuth,this.config.debug??!1)),this._apiKeyService}getModeratorService(){return this._moderatorService??(this._moderatorService=new sT(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._moderatorService}getFlagService(){return this._flagService??(this._flagService=new pk(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._flagService}getOverseerService(){return this._overseerService??(this._overseerService=new xT(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._overseerService}getWebSocketAdminService(){return this._websocketAdminService??(this._websocketAdminService=new fI(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._websocketAdminService}getContentReactionService(){return this._contentReactionService??(this._contentReactionService=new vk(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 $r}),n=t(e);if(void 0===n)throw new Rt(`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 OT(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.userApiKey)),this._restrictedNamesService}getPlatformConfigService(){return this._platformConfigService??(this._platformConfigService=new BT(this.http,this.jwtAuth,this.config.debug??!1)),this._platformConfigService}getEventsBatcherService(){return this._eventsBatcherService??(this._eventsBatcherService=new kk(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 iI({url:this.config.streamWebSocketUrl},this.config.debug??!1)}return this._streamWebSocketService}getGdexStreamService(){return this._gdexStreamService??(this._gdexStreamService=new hS({url:this.config.gdexWebSocketUrl})),this._gdexStreamService}getStreamingEventService(){return this._streamingEventService??(this._streamingEventService=new LT(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 $r}),n=t(e.address);if(void 0!==e.tokenId&&""!==e.tokenId){const{normalizeToTokenInstanceKey:t}=await Promise.resolve().then(function(){return CA}),r=t(e.tokenId),{collection:i,category:s,type:o,additionalKey:a}=r;return this.galaChainService.fetchTokenBalance({owner:n,collection:i,category:s,additionalKey:a,type:o,instance:"0"},e.withExpired??!1)}if(void 0!==e.tokenName&&""!==e.tokenName){const t=dn(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",i={collection:r,category:"Unit",type:t.symbol,additionalKey:"none"};return{quantity:t.balance,collection:r,category:"Unit",tokenId:xo(i)}}throw Pt("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:i,calculateAmountMode:s,currentSupply:o}=e;let a=t;void 0===s&&void 0===o||(a={tokenName:t,...void 0!==s&&{calculateAmountMode:s},...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!==i&&(l.privateKey=i),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 Gt("No transaction ID returned from buy operation");return this.waitForConfirmation(n,t=>iN(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 Gt("No transaction ID returned from sell operation");return this.waitForConfirmation(n,t=>iN(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=>{rN(n,t);const r=n.data??{};if(!function(e){if(ar(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 eN(`Invalid launch data received for transaction ${t}`);const i={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&&(i.tokenImage=e.tokenImage),void 0!==e.preBuyQuantity&&(i.preBuyQuantity=e.preBuyQuantity),""!==i.vaultAddress&&this.tokenResolverService.set(e.tokenName,i.vaultAddress),i})}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 $r}),n=t(e)??this.getAddress();return this.launchpadService.fetchProfile(n)}async fetchReferralUrl(){this.validateWallet();const e=this.getAddress();return await this.dexApiHttp.get(B,void 0,{"x-wallet-address":e})}async fetchReferrals(e){const t=await this.resolveReferralAddress(e?.address),n=e?.page??1,r=e?.limit??10,i={pageNumber:n,limit:r,sortBy:e?.sortBy??"joined",sortDir:e?.sortDir??"desc"},s=await this.dexApiHttp.get(D,i,{"x-wallet-address":t});if(!Array.isArray(s))throw new Dt("Unexpected API response: expected array, got "+typeof s);return{referrals:s,page:n,limit:r,hasMore:s.length===r}}async fetchAllReferrals(e){const t=await AA((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(M,void 0,{"x-wallet-address":t});if(void 0===n||"number"!=typeof n.referralCount||void 0===n.rewardTotals)throw new Dt(`Unexpected API response: expected { referralCount, rewardTotals }, got ${JSON.stringify(n)}`);return n}async updateProfile(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return $r}),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 $r}),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 $r}),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 $r}),n=t(e?.address)??this.getAddress(),r={type:void 0!==e?.status?"created":"DEFI",address:n,pageSize:e?.pageSize??10};return void 0!==e?.cursor&&(r.cursor=e.cursor),void 0!==e?.tokenName&&""!==e.tokenName&&(r.tokenName=e.tokenName),void 0!==e?.search&&""!==e.search&&(r.search=e.search),void 0!==e?.status&&(r.status=e.status),this.launchpadService.fetchTokenList(r)}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 $r}),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 $r}),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 $r});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{Xn(this.config.timeout,1,3e5,"timeout")}catch{this.logger.warn(`Invalid timeout value: ${this.config.timeout??"undefined"}. Using default 30000ms.`),this.config.timeout=3e4}if(void 0===this.config.baseUrl||""===this.config.baseUrl)throw Kt("baseUrl is required in configuration","baseUrl");if(void 0===this.config.webSocketUrl||""===this.config.webSocketUrl)throw Kt("webSocketUrl is required in configuration","webSocketUrl");try{new URL(this.config.baseUrl)}catch{throw Kt(`Invalid baseUrl format: ${this.config.baseUrl}`,"baseUrl")}try{new URL(this.config.webSocketUrl)}catch{throw Kt(`Invalid webSocketUrl format: ${this.config.webSocketUrl}`,"webSocketUrl")}if(void 0!==this.config.gatewayBaseUrl&&""!==this.config.gatewayBaseUrl)try{new URL(this.config.gatewayBaseUrl)}catch{throw Kt(`Invalid gatewayBaseUrl format: ${this.config.gatewayBaseUrl}`,"gatewayBaseUrl")}if(void 0!==this.config.bundleBaseUrl&&""!==this.config.bundleBaseUrl)try{new URL(this.config.bundleBaseUrl)}catch{throw Kt(`Invalid bundleBaseUrl format: ${this.config.bundleBaseUrl}`,"bundleBaseUrl")}if(void 0!==this.config.launchpadFrontendUrl&&""!==this.config.launchpadFrontendUrl)try{new URL(this.config.launchpadFrontendUrl)}catch{throw Kt(`Invalid launchpadFrontendUrl format: ${this.config.launchpadFrontendUrl}`,"launchpadFrontendUrl")}}parseSlippageToleranceFactor(e){const t=Kn("string"==typeof e||"number"==typeof e?e:String(e),IN.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR);return t<0||t>1?(this.logger.warn(`Invalid slippage tolerance factor: ${String(e)}, using default: ${IN.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR}`),IN.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR):t}parseFeeSlippageFactor(e){const t=Kn("string"==typeof e||"number"==typeof e?e:String(e),IN.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: ${IN.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR}`),IN.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!==OE.COMPLETED)throw new nN(e,n.status,n.message);let r;try{r=t(n)}catch(t){if(t instanceof eN)throw t;throw new eN(`Failed to transform WebSocket response for transaction ${e}`,wt(t)?t:new Error(Et(t)))}return this.logger.debug(`Transaction confirmed: ${e}`,r),r}catch(t){if(this.logger.error(`Transaction confirmation failed: ${e}`,t),t instanceof nN||t instanceof eN)throw t;throw new eN(`WebSocket confirmation failed for transaction ${e}`,wt(t)?t:new Error(Et(t)))}}async warmCacheFromPools(e){if(void 0===e||!Array.isArray(e))return;const{extractMetadataFromPoolData:t,isValidPoolForCaching:n}=await Promise.resolve().then(function(){return cx});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 i=t?.creatorAddress,s=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=>{s.has(t.tokenName)||((e=>{if(s.set(e,!0),s.size>1e3){const e=s.keys().next().value;void 0!==e&&s.delete(e)}})(t.tokenName),void 0!==i&&""!==i&&t.creatorAddress!==i||e(t))})}catch(e){c++;const t=Et(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 Kt("WebSocket service not initialized. Ensure websocketUrl is configured and the service is connected.","websocketService");let n=!1,r=null;const i=(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: ${Et(e)}`)}};let s=this.websocketService.getSocket();if(s)s.onAny(i),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: ${Et(e)}`);this.logger.warn("Failed to establish WebSocket connection:",e),t?.onError&&t.onError(n)});let e=0;const o=()=>{if(s=this.websocketService.getSocket(),!s&&e<IN.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS)return e++,void(r=setTimeout(()=>o(),IN.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS));if(!s&&e>=IN.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS){const e=new Error(`WebSocket not available after ${IN.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS*IN.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS}ms`);return this.logger.warn("Token creation broadcast subscription timeout:",e.message),void(t?.onError&&t.onError(e))}s&&(s.onAny(i),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(i),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 gn({debug:e,context:"LaunchpadSDK"});t.debug("Starting global cleanup..."),yI.cleanupAll(e),t.debug("Global cleanup completed")}}function NN(){const e=globalThis;return e.process?.env??{}}IN.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR=.15,IN.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR=.01,IN.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY=cn.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY,IN.DEFAULT_CALCULATE_AMOUNT_MODE=vt.LOCAL,IN.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS=30,IN.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS=100;let CN=0;class _N{constructor(){this.utilityInstance=!0,this.utilityInstance}static generateWallet(){try{const e=t.createRandom();if(null===e.mnemonic?.phrase||void 0===e.mnemonic?.phrase||""===e.mnemonic.phrase)throw Pt("mnemonic","Mnemonic phrase");const n=_N.toGalaAddress(e.address);return{privateKey:e.privateKey,address:e.address,galaAddress:n,mnemonic:e.mnemonic.phrase,wallet:new t(e.privateKey)}}catch(e){if("test"===NN().NODE_ENV){const e=`test-wallet-${Date.now()}-${++CN}`,n="0x"+Buffer.from(e).toString("hex").padStart(64,"1").slice(0,64),r=new t(n),i=_N.toGalaAddress(r.address);return{privateKey:r.privateKey,address:r.address,galaAddress:i,mnemonic:"test test test test test test test test test test test junk",wallet:r}}throw e}}static fromPrivateKey(e){const n=new t(e),r=_N.toGalaAddress(n.address);return{privateKey:n.privateKey,address:n.address,galaAddress:r,mnemonic:"",wallet:n}}static fromMnemonic(e,n=0){try{const r=c.fromPhrase(e),i=l.fromMnemonic(r,`m/44'/60'/0'/0/${n}`),s=new t(i.privateKey),o=_N.toGalaAddress(s.address);return{privateKey:s.privateKey,address:s.address,galaAddress:o,mnemonic:e,wallet:s}}catch(r){if("test"===NN().NODE_ENV){const r=`test-mnemonic-index-${n}-${e}`,i="0x"+Buffer.from(r).toString("hex").padStart(64,"1").slice(0,64),s=new t(i),o=_N.toGalaAddress(s.address);return{privateKey:s.privateKey,address:s.address,galaAddress:o,mnemonic:e,wallet:s}}throw r}}static toGalaAddress(t){const n=Br(t);if(!/^[a-fA-F0-9]{40}$/.test(n))throw Ft("address","a valid Ethereum address (40 hex characters)");return`eth|${e(`0x${n}`).slice(2)}`}static toEthereumAddress(e){try{return Mr(e)}catch(t){const n=Et(t);if(n.includes("required")||!e?.startsWith("eth|"))throw Pt("galaAddress","Gala address starting with eth|");if(n.includes("Invalid backend"))throw Ft("galaAddress","Gala format (eth|{40-hex-chars})");throw t}}static isValidEthereumAddress(e){try{const t=Br(e);return/^[a-fA-F0-9]{40}$/.test(t)}catch{return!1}}static isValidGalaAddress(e){return""!==e&&"backend"===Fr(e)}static generateMultipleWallets(e=1){Xn(e,1,100,"count");const t=[];if("test"===NN().NODE_ENV)for(let n=0;n<e;n++){const e=`test-multi-${n}-${Date.now()}-${++CN}`,r="0x"+Buffer.from(e).toString("hex").padStart(64,"1").slice(0,64);t.push(_N.fromPrivateKey(r))}else for(let n=0;n<e;n++)t.push(_N.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 xN(e){if(void 0===e)return _N.generateWallet();const t=e.trim();if(!sr(t))throw Ft("input","a non-empty string");if(function(e){const t=Br(e);return/^[a-fA-F0-9]{64}$/.test(t)}(t))return _N.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 _N.fromMnemonic(t);throw Ft("input","a private key (64 hex characters) or mnemonic (12/24 words)","Wallet input")}function RN(e){if(!e.match(/^0x[a-fA-F0-9]{64}$/))throw Ft("privateKey","0x-prefixed 64 hexadecimal characters","Private key");const t=new d(e);return{publicKey:t.publicKey,compressedPublicKey:t.compressedPublicKey}}function BN(t){if(!t.match(/^0x[a-fA-F0-9]{64}$/))throw Ft("privateKey","0x-prefixed 64 hexadecimal characters","Private key");return e(u(t))}function DN(){const e=Pv.generate();return{privateKey:CE.encode(e.secretKey),publicKey:e.publicKey.toBase58(),address:e.publicKey.toBase58()}}function MN(e){ar(e)&&(e={});const{wallet:n,env:r,config:i={},...s}=e,o={...{...s,...i}};let a;if(delete o.wallet,delete o.env,delete o.config,ar(n)){a=xN().wallet}else if("string"==typeof n){a=xN(n).wallet}else{if(!(n instanceof t))throw Kt("Invalid wallet input. Expected string (private key or mnemonic) or Wallet instance.","wallet");a=n}const c={wallet:a,...void 0!==r?{env:r}:{},debug:!1,timeout:3e4,...o};return new IN(c)}let ON=null;async function UN(){if(!1===ON)return null;try{const e=await import("@gala-chain/connect");return ON=!0,e}catch{return ON=!1,null}}class LN{constructor(e){if(this.providerType="external",this.connectedAddress=null,!e)throw new To("@gala-chain/connect client is required",vo.INVALID_CONFIG);if("function"!=typeof e.signMessage)throw new To("Invalid @gala-chain/connect client: signMessage method is required",vo.INVALID_CONFIG);this.client=e}static async createBrowserClient(e){const t=await UN();if(null==t)throw new To("Failed to create BrowserConnectClient: @gala-chain/connect is not installed. Install it with: npm install @gala-chain/connect",vo.PROVIDER_NOT_AVAILABLE);const{BrowserConnectClient:n}=t,r=n,i=e?new r(e):new r;return new LN(i)}static async createTrustWalletClient(){const e=await UN();if(null==e)throw new To("Failed to create TrustWalletConnectClient: @gala-chain/connect is not installed. Install it with: npm install @gala-chain/connect",vo.PROVIDER_NOT_AVAILABLE);const{TrustWalletConnectClient:t}=e,n=new t;return new LN(n)}static async isAvailable(){return null!==await UN()}ensureConnected(){if(null===this.connectedAddress||void 0===this.connectedAddress)throw new To("Wallet is not connected. Call connect() first.",vo.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(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(t),this.connectedAddress}throw new To("Failed to connect: no account returned",vo.CONNECTION_FAILED)}catch(e){if(e instanceof To)throw e;const t=e instanceof Error?e.message:String(e);if(t.length>0&&(t.includes("rejected")||t.includes("denied")))throw new To("User rejected connection",vo.USER_REJECTED,e instanceof Error?e:void 0);throw new To("Failed to connect to wallet",vo.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 To("User rejected signing",vo.USER_REJECTED,e instanceof Error?e:void 0);throw new To("Failed to sign message",vo.SIGNING_FAILED,e instanceof Error?e:void 0)}}signTypedData(e,t,n){return Promise.reject(new To("signTypedData is not supported by GalaChainConnectProvider. Use ExternalWalletProvider with the underlying EIP-1193 provider instead.",vo.SIGNING_FAILED))}async getAddress(){return await Promise.resolve(),this.ensureConnected()}async getGalaAddress(){return`eth|${(await this.getAddress()).slice(2)}`}getPrivateKey(){return Promise.reject(new To("Private key is not accessible with @gala-chain/connect. Use PrivateKeyProvider if you need private key access.",vo.PRIVATE_KEY_NOT_ACCESSIBLE))}getClient(){return this.client}}const PN={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"},FN={[PN.METAMASK]:"data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjQiIGhlaWdodD0iMjQiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0iTTIxLjU0IDQuMjJsLTguMzQgNi4yMSAxLjU0LTMuNjUtLTUuNTMtMi41MXoiIGZpbGw9IiNFMjc2MUIiLz48L3N2Zz4=",[PN.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 $N(){return"undefined"!=typeof window&&"function"==typeof window.dispatchEvent}function KN(){if(!$N())return null;return window.ethereum??null}async function GN(e=500){const t=[],n=new Map;return $N()?new Promise(r=>{const i=new Set,s=e=>{const r=e,{info:s,provider:o}=r.detail;if(i.has(s.uuid))return;i.add(s.uuid);const a={id:s.rdns||s.uuid,name:s.name,rdns:s.rdns||s.uuid,icon:s.icon??FN[s.rdns||""]??"",provider:o,isInjected:!1};t.push(a),n.set(a.id,a)};window.addEventListener("eip6963:announceProvider",s),window.dispatchEvent(new Event("eip6963:requestProvider")),setTimeout(()=>{if(window.removeEventListener("eip6963:announceProvider",s),0===t.length){const e=KN();if(e){const r=window;let i="Browser Wallet",s="injected";r.ethereum?.isMetaMask?(i="MetaMask",s=PN.METAMASK):r.ethereum?.isCoinbaseWallet?(i="Coinbase Wallet",s=PN.COINBASE):r.ethereum?.isTrust&&(i="Trust Wallet",s=PN.TRUST_WALLET);const o={id:s,name:i,rdns:s,icon:FN[s]??"",provider:e,isInjected:!0};t.push(o),n.set(o.id,o)}}const e=window;if(e.gala?.request&&!n.has(PN.GALA)){const r={id:PN.GALA,name:"Gala Wallet",rdns:PN.GALA,icon:FN[PN.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}}function HN(e){if(!$N())return()=>{};let t=!0,n={wallets:[],byId:new Map,hasWallets:!1};const r=r=>{if(!t)return;const i=r,{info:s,provider:o}=i.detail,a=s.rdns||s.uuid;if(n.byId.has(a))return;const c={id:a,name:s.name,rdns:a,icon:s.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),GN().then(r=>{t&&(n=r,e(r))}),()=>{t=!1,window.removeEventListener("eip6963:announceProvider",r)}}async function WN(e,t){return(await GN(t)).byId.get(e)??null}async function qN(e,t){return null!==await WN(e,t)}function jN(){return null!==KN()}function VN(){const e=globalThis;return e.process?.env??{}}class zN{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),i=new IN(r),s={sdk:i,wallet:n,config:r};if(!1!==e.autoValidate){const e=await this.validateSetup(i,n);return{...s,validation:e}}return s}static readOnlySetup(e={}){const t=e.environment??this.detectEnvironment(),n=this.buildSdkConfig(e,t),r=new IN(n);return Promise.resolve({sdk:r,config:n})}static async validateSetup(e,t){const n=[],r=[],i={canTrade:!1,canCreateTokens:!1,hasBalance:!1,connectionHealthy:!1};try{const t=await e.fetchGalaBalance(e.getAddress());if(i.connectionHealthy=!0,void 0!==t?.quantity&&""!==t.quantity){const e=Kn(t.quantity,0);i.hasBalance=e>0,i.canTrade=e>=.1,i.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: ${Et(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: ${Et(e)}`)}return{ready:0===n.length&&i.connectionHealthy,sdk:e,wallet:t??_N.generateWallet(),issues:n,warnings:r,capabilities:i}}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,i]of Object.entries(e)){const{sdk:e}=await this.quickSetup({environment:t,privateKey:i,agentId:`multi-wallet-${r}`,autoValidate:!1});n[r]=e}return n}static detectEnvironment(){return"stage"===(VN().LAUNCHPAD_ENV??VN().ENVIRONMENT)?"stage":"prod"}static setupWallet(e){if(void 0===e||""===e){const e=VN().PRIVATE_KEY;return void 0!==e&&""!==e?_N.fromPrivateKey(e):_N.generateWallet()}return"generate"===e?_N.generateWallet():_N.fromPrivateKey(e)}static buildSdkConfig(e,t,n){const r=e.galaChainAddress??VN().WALLET_ADDRESS;return{wallet:n?.wallet,baseUrl:e.baseUrl??this.getDefaultBaseUrl(t),timeout:e.timeout??this.getDefaultTimeout(t),debug:e.debug??"prod"!==t,...this.getEnvironmentDefaults(t),...e.config??{},...void 0!==r&&""!==r?{galaChainAddress:r}:{},env:t}}static getDefaultBaseUrl(e){return _o(e).launchpadBaseUrl}static getDefaultTimeout(e){switch(e){case"prod":return 3e4;case"stage":return 45e3}}static getEnvironmentDefaults(e){const t=_o(e);return{bundleBaseUrl:t.bundleBaseUrl,gatewayBaseUrl:t.gatewayBaseUrl}}}function XN(e,t,n){const r="number"==typeof e?new T(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 i=n-t;return new T(t).plus(new T(i).multipliedBy(r))}function JN(e,t,n){if(e>=t)throw new Error(`tickLower must be < tickUpper, got: ${e} >= ${t}`);if(n<=0)throw new Error(`tickSpacing must be > 0, got: ${n}`);return{tickLower:Math.floor(e/n)*n,tickUpper:Math.ceil(t/n)*n}}function YN(e,t,n=60){const r=Vs(e),i=Vs(t);if(r.isLessThanOrEqualTo(0)||i.isLessThanOrEqualTo(0))throw new Error("Prices must be positive");if(r.isGreaterThanOrEqualTo(i))throw new Error(`minPrice must be < maxPrice, got: ${r.toString()} >= ${i.toString()}`);const s=Math.floor(Xs(r)),o=Math.ceil(Xs(i)),a=Math.floor(s/n)*n,c=Math.ceil(o/n)*n;return{minTick:a,maxTick:c,actualMinPrice:new T(1.0001).pow(a),actualMaxPrice:new T(1.0001).pow(c)}}function QN(e,t){if(0===e.length)return-1;if(t<0||t>100)throw new Error(`Percentile must be between 0 and 100, got: ${t}`);const n=(e.length-1)*(t/100),r=Math.floor(n);return Math.min(r,e.length-1)}function ZN(e,t){if(t<0)throw new Error(`decimals must be >= 0, got: ${t}`);const n=Vs(e),r=new T(10).pow(t);return n.multipliedBy(r).integerValue(T.ROUND_UP).dividedBy(r)}function eC(e,t,n,r="0"){const i=Vs(t);if(Js(i))return Vs(r);const s=Vs(e).dividedBy(i);if(null!=n){const e=Vs(n);if(e.isLessThan(0))throw new Error(`minimum must be >= 0, got: ${e.toString()}`);if(s.isLessThan(e))return e}return s}function tC(e,t){if(t<=0)throw new Error(`tickSpacing must be > 0, got: ${t}`);return Math.floor(e/t)*t}function nC(e,t){if(t<0)throw new Error(`feeFactor must be >= 0, got: ${t}`);return Vs(e).multipliedBy(t).integerValue(T.ROUND_DOWN)}function rC(e,t){const n=new Map;for(const r of e){const e=t(r);n.has(e)||n.set(e,[]),n.get(e).push(r)}return n}function iC(e){if(null==e||"object"!=typeof e)throw new Error("Token must be an object");const t=e,n=(sr(t.name)?t.name:void 0)??(sr(t.tokenName)?t.tokenName:void 0)??"";if(!sr(n))throw new Error("Token name is required and must be a non-empty string");const r=(sr(t.symbol)?t.symbol:void 0)??(sr(t.tokenSymbol)?t.tokenSymbol:void 0)??(sr(t.collection)?t.collection:void 0)??"";if(!sr(r))throw new Error("Token symbol is required and must be a non-empty string");let i=8;"number"==typeof t.decimals&&t.decimals>=0&&(i=Math.floor(t.decimals));const s={name:n,symbol:r,decimals:i};return sr(t.address)&&(s.address=t.address),"boolean"==typeof t.verified&&(s.verified=t.verified),s}function sC(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(sr(n))return n;if(null!=n&&""!==n)return n}return n}function oC(e,t){return e.map(e=>{const n={};for(const[r,i]of Object.entries(t)){const t=i(e);void 0!==t&&(n[r]=t)}return n})}function aC(e,t,n=!0){const r=new Map;if(e.forEach((e,n)=>{const i=t(e);r.set(i,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 i=t(e);return r.get(i)===n})}function cC(e,t){const n={...e};for(const[e,r]of Object.entries(t))void 0!==r&&(n[e]=r);return n}class lC{constructor(){this.rooms=new Set}addRoom(e){this.rooms.add(e)}removeRoom(e){this.rooms.delete(e)}getRooms(){return Array.from(this.rooms)}isSubscribedTo(e){return this.rooms.has(e)}clear(){this.rooms.clear()}get size(){return this.rooms.size}}class uC{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,i=0)=>{if(i>this.maxDepth)return;if(null==e||"object"!=typeof e)return;if(n.has(e))return;n.add(e);const s=this.extractor(e);if(null!==s){const e=this.dedupeKeyFn(s);this.seen.has(e)||(this.seen.add(e),t.push(s))}for(const t of Object.values(e))r(t,i+1)};return r(e,0),t}reset(){this.seen.clear()}getSeenCount(){return this.seen.size}}class dC{constructor(){this.pending=new Map}addPending(e,t){this.removePending(e);const n=setTimeout(()=>{this.pending.delete(e)},t);this.pending.set(e,{timeoutId:n,addedAt:Date.now()})}removePending(e){const t=this.pending.get(e);t&&(clearTimeout(t.timeoutId),this.pending.delete(e))}isPending(e){return this.pending.has(e)}getPendingCount(){return this.pending.size}clearExpired(){for(const[e,t]of this.pending.entries())null==t&&this.pending.delete(e)}clear(){for(const e of this.pending.values())clearTimeout(e.timeoutId);this.pending.clear()}}class hC{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: ${Et(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}: ${Et(t)}`)}}clear(){this.globalCallbacks=[],this.roomCallbacks.clear()}clearRoom(e){this.roomCallbacks.delete(e)}}class gC{constructor(){this.filters=[]}addFilter(e){return this.filters.push(e),this}forward(e){for(const t of this.filters)if(!t(e))return!1;return!0}clearFilters(){this.filters=[]}get filterCount(){return this.filters.length}}class fC{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:i}=n;try{await i()}catch(t){const n=t instanceof Error?t:new Error(String(t));e.push(n),this.logger?.error(`Cleanup error for listener ${r}:`,n)}}return this.listeners=[],e}clear(){this.listeners=[]}get size(){return this.listeners.length}}class mC{constructor(e={},t){this.events=[],this.timeouts=new Map,this.maxSize=e.maxSize??100,this.defaultTtlMs=e.defaultTtlMs??3e4,this.logger=t}push(e){if(this.events.length>=this.maxSize){const e=0;this.events.shift();const t=this.timeouts.get(e);t&&(clearTimeout(t),this.timeouts.delete(e)),this.logger?.warn(`Buffer full (${this.maxSize}), dropped oldest event`)}this.events.push(e);const t=this.events.length-1,n=setTimeout(()=>{this.events[t]===e&&this.events.splice(t,1),this.timeouts.delete(t)},this.defaultTtlMs);this.timeouts.set(t,n)}getAll(){return[...this.events]}clear(){for(const e of this.timeouts.values())clearTimeout(e);this.events=[],this.timeouts.clear()}get size(){return this.events.length}}class pC{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 i=setTimeout(()=>{this.activeIndicators.delete(n),this.pendingIndicators.delete(n),this.onStopTyping?.(e,t)},this.delayMs);this.pendingIndicators.set(n,i)}stopTyping(e,t){const n=`${e}:${t}`,r=this.pendingIndicators.get(n);r&&(clearTimeout(r),this.pendingIndicators.delete(n)),this.activeIndicators.has(n)&&(this.activeIndicators.delete(n),this.onStopTyping?.(e,t))}clear(){for(const e of this.pendingIndicators.values())clearTimeout(e);this.pendingIndicators.clear(),this.activeIndicators.clear()}get activeCount(){return this.activeIndicators.size}}const yC=5,bC=8,vC=18,wC={collection:"GALA",category:"Unit",type:"none",additionalKey:"none"},EC={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"},AC=5,kC=5;function SC(e){const t={};return void 0!==e.cursor&&(t.cursor=e.cursor),void 0!==e.pageSize&&(t.pageSize=e.pageSize),t}function TC(e,t){return SC({...e,...t})}function IC(e,t){return void 0===t?e:{...e,cursor:t}}function NC(e){return"string"==typeof e?e:"number"==typeof e||"boolean"==typeof e||"bigint"==typeof e?String(e):JSON.stringify(e)??""}async function CC(e,t,n,r){const i=r?.logger,s=[];s.length=e.length;let o=0,a=0;i?.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 s[c]=r,o++,i?.debug(`Fetched [${c+1}/${e.length}]: ${t}`),r}catch(n){throw a++,i?.warn(`Failed [${c+1}/${e.length}]: ${t} - ${Et(n)}`),n}})()}),r=await Promise.allSettled(t);for(let e=0;e<r.length;e++){const t=r[e];"rejected"===t?.status&&i?.debug(`Promise rejected in batch at index ${l+e}`)}}catch(e){i?.error(`Batch processing error at index ${r}: ${Et(e)}`)}}return i?.debug(`Batch complete: ${o} succeeded, ${a} failed`),s}function _C(e){const t={page:1,pageSize:20,totalCount:-1,hasMore:!1};if(null==e||"object"!=typeof e)return t;const n=e,r=Hn(NC(n.page??n.Page??n.current??1),t.page),i=Hn(NC(n.pageSize??n.limit??n.size??t.pageSize),t.pageSize),s=n.data,o=s?.meta;let a;a="number"==typeof n.totalCount?n.totalCount:"number"==typeof n.total?n.total:"number"==typeof o?.totalItems?o.totalItems:"number"==typeof s?.count?s.count:Hn(NC(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:i,totalCount:a,hasMore:c}}function xC(e){if(null==e||"object"!=typeof e)return"";const t=[];for(const[n,r]of Object.entries(e)){if(or(r))continue;let e;e="string"==typeof r?r:"number"==typeof r||"boolean"==typeof r?String(r):Array.isArray(r)?r.map(e=>NC(e)).join(","):NC(r);const i=encodeURIComponent(n),s=encodeURIComponent(e);t.push(`${i}=${s}`)}return t.length>0?`?${t.join("&")}`:""}async function RC(e,t){const n=t?.maxRetries??3,r=t?.backoffMs??100,i=t?.retryableStatus??[429,503,504];let s,o=0;for(;o<=n;)try{return await e()}catch(e){s=e,o++;const t=MC(e),a=i.includes(t);if(o>n||!a)throw e;const c=r*Math.pow(2,o-1);await new Promise(e=>setTimeout(e,c))}throw s}function BC(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 i,s=t.errorMessage;"string"==typeof n.message?s=n.message:"string"==typeof n.error?s=n.error:e instanceof Error?s=e.message:"string"==typeof e&&(s=e);const o=n.response;if(o){const e=o.data;if("object"==typeof e&&null!==e){i=e;const t=e;"string"==typeof t.message?s=t.message:"string"==typeof t.error&&(s=t.error)}}const a={statusCode:r,errorMessage:s,raw:e};return null!=i&&(a.errorData=i),a}async function DC(e,t,n){const r=n?.logger,i=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 s=e.map(async(t,n)=>{try{const s=await i(t);return r?.debug(`Endpoint [${n+1}/${e.length}] succeeded: ${t}`),s}catch(i){return void r?.warn(`Endpoint [${n+1}/${e.length}] failed: ${t} - ${Et(i)}`)}}),o=(await Promise.allSettled(s)).map(e=>{if("fulfilled"===e.status)return e.value});return r?.debug(`Aggregating ${o.filter(e=>void 0!==e).length} successful results`),t(o)}function MC(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 OC(e){const t=e.trim().toLowerCase();if(0===t.length)throw new Error("Token name cannot be empty");return t}function UC(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 LC(e,t){return`${e.replace(/\/$/,"")}${t}`}function PC(e,t){const n=OC(e);return LC(t,`/v1/tokens/${encodeURIComponent(n)}/assets/image`)}function FC(e,t,n="jpg"){const r=OC(e);UC(n);return LC(t,`/v1/tokens/${encodeURIComponent(r)}/assets/thumbnail.${n.toLowerCase()}`)}function $C(e,t,n="gif"){const r=OC(e);UC(n);return LC(t,`/v1/tokens/${encodeURIComponent(r)}/assets/animated.${n.toLowerCase()}`)}function KC(e,t){const n=OC(e);return LC(t,`/v1/tokens/${encodeURIComponent(n)}/assets/poster.jpg`)}function GC(e,t,n="vtt"){const r=OC(e);UC(n);return LC(t,`/v1/tokens/${encodeURIComponent(r)}/assets/storyboard.${n.toLowerCase()}`)}function HC(e,t){const n=OC(e);return LC(t,`/v1/tokens/${encodeURIComponent(n)}/assets/live.m3u8`)}function WC(e,t,n,r){const i=OC(e),s=t.trim().toLowerCase();if(0===s.length)throw new Error("Asset type cannot be empty");UC(r);const o=void 0!==r&&r.length>0?`.${r.toLowerCase()}`:"";return LC(n,`/v1/tokens/${encodeURIComponent(i)}/assets/${encodeURIComponent(s)}${o}`)}function qC(e,t,n,r="jpg"){const i=OC(e),s=t.trim();if(0===s.length)throw new Error("Recording ID cannot be empty");UC(r);return LC(n,`/v1/tokens/${encodeURIComponent(i)}/recordings/${encodeURIComponent(s)}/assets/thumbnail.${r.toLowerCase()}`)}function jC(e,t,n,r="gif"){const i=OC(e),s=t.trim();if(0===s.length)throw new Error("Recording ID cannot be empty");UC(r);return LC(n,`/v1/tokens/${encodeURIComponent(i)}/recordings/${encodeURIComponent(s)}/assets/animated.${r.toLowerCase()}`)}function VC(e,t,n){const r=OC(e),i=t.trim();if(0===i.length)throw new Error("Recording ID cannot be empty");return LC(n,`/v1/tokens/${encodeURIComponent(r)}/recordings/${encodeURIComponent(i)}/assets/poster.jpg`)}function zC(e,t,n,r="vtt"){const i=OC(e),s=t.trim();if(0===s.length)throw new Error("Recording ID cannot be empty");UC(r);return LC(n,`/v1/tokens/${encodeURIComponent(i)}/recordings/${encodeURIComponent(s)}/assets/storyboard.${r.toLowerCase()}`)}function XC(e,t,n){const r=OC(e),i=t.trim();if(0===i.length)throw new Error("Recording ID cannot be empty");return LC(n,`/v1/tokens/${encodeURIComponent(r)}/recordings/${encodeURIComponent(i)}/assets/stream.m3u8`)}function JC(e,t,n,r,i){const s=OC(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");UC(i);const c=void 0!==i&&i.length>0?`.${i.toLowerCase()}`:"";return LC(r,`/v1/tokens/${encodeURIComponent(s)}/recordings/${encodeURIComponent(o)}/assets/${encodeURIComponent(a)}${c}`)}const YC=new Map;function QC(e,t){const n=e;return YC.set(n,{createdAt:Date.now(),label:t}),n}function ZC(e){const t=e;YC.delete(t)}function e_(){const e=YC.size;return YC.clear(),e}function t_(){const e=Array.from(YC.entries()).map(([e,t])=>({id:e,...t}));return{size:YC.size,entries:e}}class n_ extends Sr{constructor(e,t=!1){super(e,t)}async getChart(e){if(null==e)throw Pt("options","Chart options");const{tokenName:t,from:n,to:r,resolution:i}=e;if(null==t||""===t)throw Pt("tokenName","Token name");if(null==n)throw Pt("from","Start timestamp");if(null==r)throw Pt("to","End timestamp");if(null==i)throw Pt("resolution","Data resolution interval");ao(t);const s=173e6;if("number"!=typeof n||n<s)throw new Rt("from must be a valid timestamp (min: 173000000)","from","INVALID_TIMESTAMP");if("number"!=typeof r||r<s)throw new Rt("to must be a valid timestamp (min: 173000000)","to","INVALID_TIMESTAMP");if("number"!=typeof i||i<1)throw new Rt("resolution must be a number >= 1","resolution","INVALID_RESOLUTION");const{adaptQueryParams:o}=await Promise.resolve().then(function(){return js}),a=o({tokenName:t,from:n,to:r,resolution:i}),c=await on(()=>this.http.get(R.CHART,a),{errorContext:"Failed to fetch chart data"}),l=tn(c);if(null==l||"object"!=typeof l)throw $t("Invalid API response: missing or invalid data",c.status??500);const u=l,d=u.data;if(!Array.isArray(d))throw $t("Invalid API response: expected data array",c.status??500);const h={dataPoints:d.map(e=>{if("object"!=typeof e||null===e)throw $t("Invalid API response: invalid data point structure",c.status??500);const t=e,n=t.startTime??t.timestamp,r=t.openPrice??t.value,i=t.closePrice??t.value,s=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(i),lowPrice:String(s),highPrice:String(o),volume:String(a)}})};return"boolean"==typeof u.isPreviousData&&(h.isPreviousData=u.isPreviousData),h}}const r_={NEW_HOLDER:"NEW_HOLDER",EXITED_HOLDER:"EXITED_HOLDER",BALANCE_CHANGED:"BALANCE_CHANGED"},i_=Gs({type:"string",userAddress:"string",balance:"string",rank:"number",previousRank:"optional-number"}),s_=Gs({tokenName:"string",userAddress:"string",quantity:"optional-string",percentage:"optional-number",holderTier:"optional-object",isCreator:"boolean",rank:"optional-number"});function o_(e){return"string"==typeof e&&(e===r_.NEW_HOLDER||e===r_.EXITED_HOLDER||e===r_.BALANCE_CHANGED)}class a_ extends Tr{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 ln(e);const t=e;return ln(`${t.type??t.symbol??"unknown"}|${t.additionalKey??"none"}`)}extractMetadata(e){let t,n,r="Token",i="Unit",s="none";if("string"==typeof e)if(Xw(e)){const o=zw(e);"Token"===o.collection&&""!==o.type?(r=o.collection,i=""!==o.category?o.category:"Unit",t=o.type,s=""!==o.additionalKey?o.additionalKey:"none",n=t):(t=o.collection,n=t,i=""!==o.category?o.category:"Unit",s=""!==o.additionalKey?o.additionalKey:"none")}else t=e,n=e;else{const o=e;t=o.type??"unknown",r=o.collection??"Token",i=o.category??"Unit",s=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:i,type:t.toUpperCase(),additionalKey:s,verified:!1}}getDecimalsForToken(e){return{GALA:8,GUSDC:6,USDC:6,USDT:6,WETH:18,DAI:18}[e.toUpperCase()]??18}isCacheExpired(e){return wn(e)>this.cacheExpiry}setCacheExpiry(e){this.cacheExpiry=e,this.logger.debug(`Set token metadata cache expiry to ${e}ms`)}}function c_(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)}En.MIN_LENGTH,En.MAX_LENGTH,En.PATTERN;lr({ENABLED:"ENABLED",DISABLED:"DISABLED",ADMIN_DISABLED:"ADMIN_DISABLED"});function l_(e){return"global"===e||"token"===e}function u_(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 d_(e){return u_(e)}function h_(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.message}function g_(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.messageId&&"string"==typeof t.deletedAt}function f_(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.messageId&&"string"==typeof t.content&&"string"==typeof t.userAddress&&"string"==typeof t.pinnedBy&&"string"==typeof t.pinnedAt}function m_(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&f_(t.pinnedMessage)}function p_(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.unpinnedMessageId}function y_(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"boolean"==typeof t.enabled&&(void 0===t.reason||l_(t.reason))}function b_(e){return!!sr(e)&&(e.length>=_n.CHAT_MESSAGE.MIN_LENGTH&&e.length<=_n.CHAT_MESSAGE.MAX_LENGTH)}function v_(e){return!!sr(e)&&En.PATTERN.test(e)}function w_(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.emoji&&"number"==typeof t.timestamp&&"number"==typeof t.streamTime}function E_(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.message}const A_=lr({RATE_LIMITED:"RATE_LIMITED",INVALID_EMOJI:"INVALID_EMOJI",NOT_AUTHENTICATED:"NOT_AUTHENTICATED",STREAM_NOT_LIVE:"STREAM_NOT_LIVE"});function k_(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.userAddress&&"string"==typeof t.fullName&&(void 0===t.profileImage||"string"==typeof t.profileImage)}function S_(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&Array.isArray(t.typingUsers)&&t.typingUsers.every(k_)}const T_={ONE_SECOND_MS:1e3,ONE_MINUTE_MS:6e4,ONE_HOUR_MS:36e5,ONE_DAY_MS:864e5,ONE_WEEK_MS:6048e5,ONE_MONTH_MS:2592e6};var I_,N_,C_,__,x_,R_;!function(e){e.PENDING="PENDING",e.PROCESSING="PROCESSING",e.COMPLETED="COMPLETED",e.FAILED="FAILED"}(I_||(I_={})),function(e){e.TEXT="TEXT",e.IMAGE="IMAGE",e.VIDEO="VIDEO"}(N_||(N_={})),function(e){e.NO_ACTION="NO_ACTION",e.REVIEW_REQUIRED="REVIEW_REQUIRED",e.DELETE_CONTENT="DELETE_CONTENT",e.BAN_USER="BAN_USER",e.DELETE_AND_BAN="DELETE_AND_BAN"}(C_||(C_={})),function(e){e.VIOLENCE="VIOLENCE",e.HATE_SPEECH="HATE_SPEECH",e.SEXUAL_CONTENT="SEXUAL_CONTENT",e.HARASSMENT="HARASSMENT",e.SPAM="SPAM",e.SCAM="SCAM",e.SELF_HARM="SELF_HARM",e.ILLEGAL_ACTIVITY="ILLEGAL_ACTIVITY",e.MISINFORMATION="MISINFORMATION",e.COPYRIGHT="COPYRIGHT",e.SAFE="SAFE"}(__||(__={})),function(e){e.QUICK="QUICK",e.DETAILED="DETAILED"}(x_||(x_={})),function(e){e.DISABLED="DISABLED",e.ADVISORY="ADVISORY"}(R_||(R_={}));const B_={[I_.PENDING]:"Pending",[I_.PROCESSING]:"Processing",[I_.COMPLETED]:"Completed",[I_.FAILED]:"Failed"},D_={[C_.NO_ACTION]:"No Action Needed",[C_.REVIEW_REQUIRED]:"Human Review Required",[C_.DELETE_CONTENT]:"Delete Content",[C_.BAN_USER]:"Ban User",[C_.DELETE_AND_BAN]:"Delete & Ban"},M_={[__.VIOLENCE]:"Violence",[__.HATE_SPEECH]:"Hate Speech",[__.SEXUAL_CONTENT]:"Sexual Content",[__.HARASSMENT]:"Harassment",[__.SPAM]:"Spam",[__.SCAM]:"Scam",[__.SELF_HARM]:"Self Harm",[__.ILLEGAL_ACTIVITY]:"Illegal Activity",[__.MISINFORMATION]:"Misinformation",[__.COPYRIGHT]:"Copyright",[__.SAFE]:"Safe"},O_={[x_.QUICK]:"Quick Scan",[x_.DETAILED]:"Detailed Scan"},U_={[N_.TEXT]:"Text",[N_.IMAGE]:"Image",[N_.VIDEO]:"Video"},L_={[R_.DISABLED]:"Disabled",[R_.ADVISORY]:"Advisory"},P_=lr(I_),F_=lr(N_),$_=lr(C_),K_=lr(__),G_=lr(x_),H_=lr(R_),W_=pr([{field:"id",type:"number"},{field:"flagId",type:"number"},{field:"status",type:"string",validator:P_},{field:"analysisType",type:"string",validator:F_},{field:"provider",type:"string"}]),q_=pr([{field:"enabled",type:"boolean"},{field:"mode",type:"string",validator:H_},{field:"provider",type:"string"}]);function j_(e){return null!==e.analysisTier}function V_(e){return!0===e.escalatedFromQuick}function z_(e,t){if(!j_(e)||null===e.tokensUsed)return 0;const n=1500*t.maxFrames;if(0===n)return 0;const r=(n-e.tokensUsed)/n*100;return Math.max(0,Math.round(r))}function X_(e){if(!(void 0!==e.tokenName&&""!==e.tokenName||void 0!==e.userAddress&&""!==e.userAddress))throw Jt(["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 Ft("tokenName",`${t}-${n} alphanumeric characters`,"Token name")}cr(0,void 0,In.MAX_LIMIT,e.pageSize,e.cursor)}function J_(e){if(!sr(e.tokenName))throw Pt("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 Ft("tokenName",`${t}-${n} alphanumeric characters`,"Token name");Q_(e.content)}function Y_(e){Q_(e.content)}function Q_(e){if(!sr(e))throw Pt("content");if(0===e.trim().length)throw Qt("content","Content");if(e.length>_n.COMMENTS_V1.MAX_LENGTH)throw Yt("content",_n.COMMENTS_V1.MAX_LENGTH,e.length)}function Z_(e){if(!(void 0!==e.tokenName&&""!==e.tokenName||void 0!==e.userAddress&&""!==e.userAddress))throw new Rt("At least one of tokenName or userAddress is required","options",xt.REQUIRED);mS(e.tokenName,e.userAddress),void 0!==e.pageSize&&cr(0,void 0,In.MAX_LIMIT,e.pageSize)}function ex(e){if(!sr(e.tokenName))throw Pt("tokenName");if(e.tokenName.length>kn.MAX_LENGTH)throw new Rt(`tokenName must be at most ${kn.MAX_LENGTH} characters`,"tokenName",xt.TOO_LONG);nx(e.content)}function tx(e){nx(e.content)}function nx(e){if(!sr(e))throw Pt("content");if(0===e.trim().length)throw new Rt("content cannot be empty","content",xt.REQUIRED);if(e.length>_n.CHAT_MESSAGES_V1.MAX_LENGTH)throw new Rt(`content must be at most ${_n.CHAT_MESSAGES_V1.MAX_LENGTH} characters`,"content",xt.TOO_LONG)}function rx(e){if(!sr(e))throw Pt("id","Message ID");if(!xn.CHAT_MESSAGE.PATTERN.test(e))throw new Rt("Invalid message ID format. Expected: chat-{timestamp}-{uuid}","id",xt.INVALID_FORMAT)}function ix(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}function sx(){const e=x.join(process.cwd(),"..","..",".env");_.existsSync(e)&&C.config({path:e});const t=x.join(process.cwd(),".env");_.existsSync(t)&&C.config({path:t})}function ox(e,t){const n=globalThis.process?.env[e];if(pn(n)||!fn(n)){throw Pt(e,`${e} (${void 0!==t?`${t} (checked root .env and local .env)`:"checked root .env and local .env"})`)}return n}function ax(e,t){return globalThis.process?.env[e]??t}var cx=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=Kn(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=Kn(e.reverseBondingCurveMaxFeePortion,NaN);isNaN(r)?t&&t.debug(`Skipping invalid reverseBondingCurveMaxFeePortion for ${e.tokenName}: "${e.reverseBondingCurveMaxFeePortion}"`):n.reverseBondingCurveMaxFeeFactor=r}return void 0!==n.reverseBondingCurveMaxFeeFactor&&void 0!==n.reverseBondingCurveMinFeeFactor&&(n.reverseBondingCurveNetFeeFactor=n.reverseBondingCurveMaxFeeFactor-n.reverseBondingCurveMinFeeFactor),Object.keys(n).length>0?n:null},isValidPoolForCaching:function(e){if(null===e||"object"!=typeof e)return!1;const t=e;return"tokenName"in t&&"string"==typeof t.tokenName&&t.tokenName.length>0}});export{dA as ACTIVE_USER_TYPE,R_ as AIModerationMode,C_ as AIRecommendation,L_ as AI_MODE_LABELS,D_ as AI_RECOMMENDATION_LABELS,tA as ALL_PERMISSIONS,M_ as ANALYSIS_CATEGORY_LABELS,B_ as ANALYSIS_STATUS_LABELS,O_ as ANALYSIS_TIER_LABELS,U_ as ANALYSIS_TYPE_LABELS,ZE as API_KEY_PERMISSION,YE as API_KEY_ROLE,QE as API_KEY_ROLES,aA as API_KEY_ROLE_HIERARCHY,xr as AddressFormatter,zN as AgentConfig,__ as AnalysisCategory,I_ as AnalysisStatus,x_ as AnalysisTier,N_ as AnalysisType,wo as AuthError,bo as AuthErrorType,uA as BAN_DURATIONS,Zo as BRIDGE_CONTRACT_ABI,Yo as BRIDGE_TOKEN_METADATA,hE as BaseBridgeStrategy,Ow as BridgeRateLimiter,Rw as BridgeStatusCode,jA as BrowserWalletSigner,SI as BundleSubmission,TI as BundlerTransport,eS as BurnError,Zk as BurnErrorType,vt as CALCULATION_MODES,Bo as CHAIN_IDS,yk as CONTENT_REACTION_TYPES,ok as CONTENT_TYPE_LABELS,Nw as CROSS_RATE_TYPED_DATA_TYPES,n_ as ChartService,Mt as ConfigurationError,ZA as ContentType,Ko as DEFAULT_ETHEREUM_BRIDGE_CONTRACT,Fo as DEFAULT_ETHEREUM_RPC_URL,Xo as DEFAULT_ETHEREUM_TOKENS,Ek as DEFAULT_EVENTS_CONFIG,Uo as DEFAULT_POLL_INTERVAL_MS,Lo as DEFAULT_POLL_TIMEOUT_MS,AC as DEFAULT_PRICING_CONCURRENCY,Oo as DEFAULT_RATE_LIMIT_RPS,Ho as DEFAULT_SOLANA_BRIDGE_PROGRAM,$o as DEFAULT_SOLANA_RPC_URL,Jo as DEFAULT_SOLANA_TOKENS,kC as DEFAULT_WEBSOCKET_RECONNECT_ATTEMPTS,Co as ENVIRONMENT_URLS,Qo as ERC20_ABI,xt as ERROR_CODES,Go as ETHEREUM_BRIDGE_CONTRACT_SEPOLIA,qo as ETHEREUM_TOKENS_PROD,jo as ETHEREUM_TOKENS_STAGE,Ak as EVENT_TYPES,JT as EXTENDED_STREAM_ROLE,mE as EthereumBridgeStrategy,mC as EventBufferWithAutoCleanup,kk as EventsBatcherService,mN as ExternalWalletProvider,sk as FLAG_ACTION_LABELS,ak as FLAG_DETAILS_MAX_LENGTH,rk as FLAG_REASON_LABELS,ik as FLAG_STATUS_LABELS,ro as FileValidationError,nk as FlagAction,ek as FlagReason,tk as FlagStatus,Do as GALACHAIN_CHANNELS,Wo as GALACONNECT_PRODUCTION_URL,Ew as GALA_BRIDGE_TYPED_DATA_DOMAIN,bC as GALA_DECIMALS,wC as GALA_TOKEN_CLASS_KEY,LN as GalaChainConnectProvider,dE as GalaConnectClient,iE as GalaConnectHttpError,qA as GalaWalletSigner,dS as GdexStreamError,hS as GdexStreamService,hC as GlobalAndRoomCallbackDispatcher,r_ as HOLDER_DELTA_TYPES,fi as IMAGE_EXTENSIONS,VS as INVITE_STATUS,zS as INVITE_STATUSES,po as JWT_CONSTANTS,PN as KNOWN_WALLET_RDNS,vC as LAUNCHPAD_TOKEN_DECIMALS,Iw as LEGACY_TYPED_DATA_TYPES,IN as LaunchpadSDK,kI as LaunchpadSDKError,PI as LaunchpadWrites,fC as ListenerCleanupManager,$k as LockError,Pk as LockErrorType,Qk as MAX_BURN_BATCH_SIZE,yC as MAX_CONCURRENT_POOL_FETCHES,Uk as MAX_LOCK_BATCH_SIZE,Lk as MAX_UNLOCK_BATCH_SIZE,yS as MESSAGES_CONSTRAINTS,pS as MESSAGE_TYPES,HS as MODERATOR_ROLE,WS as MODERATOR_ROLES,oT as NFT_FEES,Dt as NetworkError,gT as NftCollectionService,mT as OEmbedService,yT as OVERSEER_INVITE_STATUS,bT as OVERSEER_STATUS,PE as PAGINATION_DEFAULTS,eA as PERMISSION,FE as POOL_FETCH_CONFIG,bt as POOL_TYPES,uC as PayloadWalkerWithDeduplication,dC as PendingSubscriptionTracker,DT as PlatformStatsService,Io as PrivateKeyProvider,WA as PrivateKeySigner,EC as QUERY_FIELD_NAMES,bk as REACTION_EMOJI_MAP,FT as RECORDING_STATUS,zT as ROLE_SOURCE,lC as RoomSubscriptionManager,OE as SDKTransactionStatus,LE as SDK_VERSION,tI as SIMULATE_EVENT_TYPE,KT as SIMULCAST_PLATFORM,$T as SIMULCAST_STATUS,Po as SOLANA_COMPUTE,ea as SOLANA_DISCRIMINATORS,rI as STREAM_EVENTS,XT as STREAM_PERMISSION,VT as STREAM_ROLE,PT as STREAM_STATUS,gC as SelectiveEventForwarding,xE as SolanaBridgeStrategy,iI as StreamWebSocketService,LT as StreamingEventService,T_ as TIME_CONSTANTS,NS as TRADES_QUERY_CONSTRAINTS,yt as TRADING_TYPES,a_ as TokenMetadataService,Bt as TokenRestrictedError,$I as TokenWrites,gI as TradingQuotesService,Ot as TransactionError,nN as TransactionFailedError,pC as TypingIndicatorDebouncer,Rt as ValidationError,eN as WebSocketError,tN as WebSocketTimeoutError,bI as WeeklyChallengeService,IC as addCursorToPagination,Vr as addressFormatSchema,DC as aggregateMultipleApiSources,xi as amountMethodSchema,_i as amountTypeSchema,Lr as assertValidWalletAddress,OS as bidirectionalTokenMatch,pi as browserFileSchema,yi as bufferFileSchema,CC as buildConcurrentBatchRequests,xC as buildQueryParametersWithValidation,SC as buildSafePaginationOptions,qi as buyTokensDataSchema,XN as calculateLinearFeeInterpolation,Qi as calculatePreMintDataSchema,nC as calculateScaledFeeAmount,HE as calculateTotalPages,Ut as capitalize,BS as caseInsensitiveTokenComparison,Ci as checkPoolOptionsSchema,yr as commonValidators,nE as compareAmounts,cC as conditionalSpreadBuilder,RS as conditionalTrimAndValidateString,MN as createLaunchpadSDK,ni as createLimitSchema,br as createOptionsValidator,Ki as createPaginatedResultSchema,$E as createPaginationQuery,bN as createProviderFromEip1193,yN as createProviderFromWallet,DN as createSolanaWallet,Wi as createTradeDataSchema,xN as createWallet,pN as createWalletProvider,ZN as decimalRoundingUp,aC as deduplicateByKey,GN as detectWallets,kN as ensureConnected,DS as errorMessageCaseNormalization,zr as ethereumAddressSchema,sC as extractFieldWithFallbackPath,_C as extractPaginationMetadata,rs as fetchGalaBalanceOptionsSchema,Zi as fetchPoolDetailsDataSchema,as as fetchTokenBalanceOptionsSchema,oi as fileSizeSchema,mi as fileUploadSchema,ai as filenameSchema,Xr as flexibleAddressSchema,bi as flexibleFileSchema,Vn as formatGalaForDTO,zn as formatLaunchpadTokenForDTO,tE as formatTokenAmount,ia as formatTokenDescriptor,Mr as fromBackendAddressFormat,eE as fromBaseUnits,jr as fullNameSchema,UI as generateBuySellStringsInstructions,LI as generateCreateSaleStringsInstructions,FA as generateEIP712Types,PA as generateUniqueKey,Yi as getAmountOptionsSchema,ax as getEnv,ox as getEnvOrThrow,_o as getEnvironmentConfig,BN as getEthereumAddressFromPrivateKey,zo as getEthereumBridgeContractByEnvironment,na as getEthereumTokenConfig,Vo as getEthereumTokensByEnvironment,Cw as getGalaBridgeTypedDataTypes,TN as getInjectedEip1193Provider,t_ as getIntervalRegistryStats,Us as getLaunchTokenDataValidationErrors,aT as getNftFeeAsNumber,RN as getPublicKeyFromPrivateKey,jC as getRecordingAnimatedUrl,JC as getRecordingAssetUrl,VC as getRecordingPosterUrl,zC as getRecordingStoryboardUrl,XC as getRecordingStreamUrl,qC as getRecordingThumbnailUrl,ra as getSolanaTokenConfig,ta as getStaticTokenMetadata,z_ as getTieredModerationSavings,$C as getTokenAnimatedUrl,WC as getTokenAssetUrl,PC as getTokenImageUrl,HC as getTokenLiveStreamUrl,KC as getTokenPosterUrl,GC as getTokenStoryboardUrl,FC as getTokenThumbnailUrl,Vi as getTradeOptionsSchema,WN as getWalletByRdns,Bi as graduateTokenOptionsSchema,Ri as graphDataOptionsSchema,rC as groupByKey,jN as hasAnyWallet,WE as hasMorePages,US as hexStringExtractionAndNormalization,vi as imageExtensionSchema,wi as imageFilenameSchema,ci as imageMimeTypeSchema,Ii as imageUploadOptionsSchema,W_ as isAIModerationData,H_ as isAIModerationMode,q_ as isAIModerationSettings,$_ as isAIRecommendation,hA as isActiveUserType,K_ as isAnalysisCategory,P_ as isAnalysisStatus,G_ as isAnalysisTier,F_ as isAnalysisType,gA as isBanData,pA as isBanEnforcementEvent,Jk as isBurnTokenEntry,Yk as isBurnTokensData,l_ as isChatDisabledReason,ix as isChatMessageItem,y_ as isChatStatusResponse,ET as isClaimableInvite,ck as isContentType,SN as isEip1193Provider,or as isEmptyValue,YT as isExtendedStreamRole,wN as isExternalProvider,dk as isFlagAction,hk as isFlagData,lk as isFlagReason,uk as isFlagStatus,i_ as isHolderDelta,o_ as isHolderDeltaType,Bk as isLockTokenEntry,Mk as isLockTokensData,kS as isMessage,SS as isMessageType,ZS as isModeratedToken,j_ as isModerationTiered,QS as isModeratorInvite,sr as isNonEmptyString,vT as isOverseerInviteStatus,wT as isOverseerStatus,f_ as isPinnedMessage,vN as isPrivateKeyProvider,eT as isPublicInviteInfo,A_ as isReactionErrorCode,HT as isRecordingStatus,WT as isSimulcastPlatform,g_ as isStreamChatDeletedEvent,h_ as isStreamChatErrorEvent,u_ as isStreamChatMessage,d_ as isStreamChatMessageEvent,m_ as isStreamChatPinnedEvent,p_ as isStreamChatUnpinnedEvent,E_ as isStreamReactionErrorEvent,w_ as isStreamReactionEvent,GT as isStreamStatus,qT as isStreamStatusEvent,c_ as isStreamingEvent,QT as isTokenAccessResult,sI as isTokenBanData,S_ as isTypingIndicatorEvent,k_ as isTypingUser,Dk as isUnlockTokenEntry,Ok as isUnlockTokensData,fA as isUserBannedEvent,s_ as isUserHoldingData,mA as isUserUnbannedEvent,Ur as isValidAddress,nA as isValidApiKeyRole,bA as isValidBanDuration,yA as isValidBanReason,b_ as isValidChatContent,v_ as isValidChatTokenName,Mo as isValidGalaChainChannel,YS as isValidInviteCode,JS as isValidInviteStatus,Os as isValidLaunchTokenData,XS as isValidModeratorRole,oI as isValidTokenBanReason,fr as isValidTokenName,jT as isViewerCountEvent,qN as isWalletAvailable,li as isoDateStringSchema,Ti as launchTokenDataSchema,sx as loadEnvWithFallback,TC as mergeSafePaginationOptions,Qr as nonNegativeDecimalStringSchema,Or as normalizeAddressInput,oC as normalizeDataWithMapping,MS as normalizeErrorMessage,GE as normalizeLimit,un as normalizeTokenKey,ln as normalizeTokenName,dn as normalizeTokenSymbol,ei as optionalUrlSchema,ti as pageNumberSchema,$i as paginationResultMetaSchema,BC as parseHttpErrorResponse,OI as parseLaunchpadVaultAddress,QN as percentileIndexCalculation,Ni as poolFetchTypeSchema,Ui as poolPaginationSchema,Yr as positiveDecimalStringSchema,YN as priceTickRangeMapping,di as privateKeySchema,AN as providerToWallet,QC as registerInterval,Zs as requireNonNegative,Qs as requirePositive,eo as requirePositiveWithContext,RC as retryableHttpRequest,Si as reverseBondingCurveConfigSchema,es as reverseBondingCurveConfigurationSchema,cA as roleHasSufficientPermission,JN as roundTickBoundaries,tC as roundTickToSpacing,eC as safeDivideWithMinimum,qr as searchQuerySchema,ji as sellTokensDataSchema,ri as standardLimitSchema,Di as standardPaginationSchema,Cr as stripHexPrefix,HN as subscribeToWalletChanges,ui as timestampSchema,Dr as toBackendAddressFormat,Pr as toBackendAddressFromEthers,Zw as toBaseUnits,Ai as tokenCategorySchema,ki as tokenCollectionSchema,Hr as tokenDescriptionSchema,os as tokenHoldSchema,ns as tokenListOptionsSchema,Kr as tokenNameSchema,Gr as tokenSymbolSchema,Ei as tokenUrlsSchema,Ji as tradeCalculationMethodSchema,Xi as tradeCalculationTypeSchema,si as tradeLimitSchema,zi as tradeListParamsSchema,Oi as tradePaginationSchema,Pi as tradePaginationWithFiltersSchema,Hi as tradeTypeBackendSchema,Gi as tradeTypeSchema,hi as transactionIdSchema,iC as transformRawApiTokenToDomainModel,LS as trimmedLengthValidation,gi as uniqueKeySchema,e_ as unregisterAllIntervals,ZC as unregisterInterval,is as updateProfileDataSchema,ss as uploadProfileImageOptionsSchema,Zr as urlSchema,ii as userLimitSchema,Mi as userPaginationSchema,Wr as userTokenNameSchema,ts as userTokenTypeSchema,Li as userTokensPaginationSchema,hs as validateAddress,fs as validateAmountString,aI as validateBanTokenOptions,Cs as validateBuyTokensData,Ds as validateCalculatePreMintData,rx as validateChatMessageId,Es as validateCheckPoolOptions,rr as validateConstrainedEnumVariant,rA as validateCreateApiKeyOptions,ex as validateCreateChatMessageOptions,J_ as validateCreateCommentOptions,vS as validateCreateMessageOptions,nT as validateCreateModeratorInviteOptions,_T as validateCreateOverseerDirectOptions,AT as validateCreateOverseerInviteOptions,Ns as validateCreateTradeData,er as validateDecimalRangeStrict,tr as validateFeePortionConstraints,ks as validateFetchGalaBalanceOptions,bS as validateFetchMessagesOptions,Ms as validateFetchPoolDetailsData,Is as validateFetchTokenBalanceOptions,ms as validateFullName,Bs as validateGetAmountOptions,Z_ as validateGetChatMessagesOptions,X_ as validateGetCommentsOptions,uI as validateGetTokenBanOptions,xs as validateGetTradeOptions,CS as validateGetTradesOptions,ws as validateImageUploadOptions,rT as validateInviteCode,Ls as validateLaunchTokenData,oA as validateListApiKeysOptions,iT as validateListModeratorInvitesOptions,kT as validateListOverseerInvitesOptions,ST as validateListOverseersOptions,lI as validateListTokenBansOptions,CT as validateListUsersOptions,ES as validateMessageId,nr as validateMinMaxRelationship,gr as validateOptionalTokenName,TT as validateOverseerInviteCode,NT as validateOverseerInviteId,IT as validateOverseerWalletAddress,KE as validatePaginationParams,ps as validateSearchQuery,_s as validateSellTokensData,Zn as validateSortOrderDirection,ds as validateTokenDescription,As as validateTokenListOptions,mr as validateTokenName,us as validateTokenSymbol,vs as validateTokenUrls,Rs as validateTradeListParams,cI as validateUnbanTokenOptions,iA as validateUpdateApiKeyOptions,tx as validateUpdateChatMessageOptions,Y_ as validateUpdateCommentOptions,wS as validateUpdateMessageOptions,RT as validateUpdatePlatformConfigOptions,Ss as validateUpdateProfileData,AS as validateUpdateTokenConfigOptions,Ts as validateUploadProfileImageOptions,ys as validateUserTokenName,gs as validateVaultAddress,Jr as vaultAddressSchema,EN as walletToProvider,V_ as wasModerationEscalated};
|
|
1
|
+
import{getAddress as e,Wallet as t,isAddress as n,JsonRpcProvider as r,Contract as i,Signature as s,keccak256 as o,toUtf8Bytes as a,Mnemonic as c,HDNodeWallet as l,computeAddress as u,SigningKey as d}from"ethers";import{BrowserWalletSigner as h,GalaWalletSigner as g,PrivateKeySigner as f,GSwap as m}from"@gala-chain/gswap-sdk";export{GSwap}from"@gala-chain/gswap-sdk";import{z as p}from"zod";import*as y from"uuid";import{v4 as b}from"uuid";import*as v from"node:crypto";import{ChainCallDTO as w,TokenClassKey as E}from"@gala-chain/api";import A from"bignumber.js";import{io as k}from"socket.io-client";import S from"axios";import*as T from"dotenv";import*as I from"fs";import*as N from"path";const C={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"},_="/v1/users/referrals/url",x="/v1/users/referrals",R="/v1/users/referrals/summary",B="/market/price-series",D="/v1/tokens/:tokenName/start-stream",M="/v1/tokens/:tokenName/stop-stream",O="/v1/tokens/:tokenName/stream/disable",U="/v1/tokens/:tokenName/stream/enable",L="/v1/tokens/:tokenName/reset-key",P="/v1/tokens/:tokenName/recordings",F="/v1/tokens/:tokenName/recordings/:assetId/download",$="/v1/tokens/:tokenName/recordings/:assetId",K="/v1/tokens/:tokenName/simulcasts",G="/v1/tokens/:tokenName/simulcasts",H="/v1/tokens/:tokenName/simulcasts/:targetId",W="/v1/config",q="/v1/config",j="/v1/config",V="/v1/tokens/:tokenName/role",z="/v1/roles",X="/v1/permissions",J="/v1/tokens/:tokenName/credentials",Y="/auth/login",Q="/auth/logout",Z="/auth/refresh",ee="/auth/session",te="/v1/tokens/:tokenName/bans",ne="/v1/tokens/:tokenName/bans",re="/v1/tokens/:tokenName/bans/:userAddress",ie="/v1/tokens/:tokenName/bans/:userAddress",se="/v1/tokens/:tokenName/active-users",oe="/v1/user-bans",ae="/v1/user-bans",ce="/v1/user-bans/:userAddress",le="/v1/user-bans/:userAddress",ue={CREATE:"/v1/api-keys",LIST:"/v1/api-keys",GET:"/v1/api-keys/:id",UPDATE:"/v1/api-keys/:id",REVOKE:"/v1/api-keys/:id"},de="/v1/moderator-invites",he="/v1/moderator-invites/claim",ge="/v1/moderated-tokens",fe="/v1/moderator-invites",me="/v1/moderator-invites/:id",pe="/v1/moderator-invites/:id/role",ye="/v1/moderator-invites/:id",be="/v1/moderator-invites/code/:code",ve={CREATE:"/v1/content-flags",LIST:"/v1/content-flags",DISMISS:"/v1/content-flags/:id/dismiss",ACTION:"/v1/content-flags/:id/action"},we="/v1/overseer-invites",Ee="/v1/overseer-invites",Ae="/v1/overseer-invites/code/:code",ke="/v1/overseer-invites/claim",Se="/v1/overseer-invites/:id",Te="/v1/overseers",Ie="/v1/overseers",Ne="/v1/overseers/:address",Ce="/v1/overseers/me",_e="/v1/overseer-summary",xe="/v1/overseer-summary/bans",Re="/v1/overseer-summary/token-bans",Be="/v1/overseer-summary/invites",De="/v1/overseer-summary/flags",Me="/v1/overseer-summary/users",Oe="/v1/users",Ue="/v1/users/:address/summary",Le="/v1/cache/flush/address/:address",Pe="/v1/cache/flush/token/:tokenName",Fe="/v1/cache/flush/all",$e="/v1/cache/flush/wallet-aliases/:address",Ke="/v1/cache/flush/wallet-aliases",Ge="/v1/token-bans",He="/v1/token-bans",We="/v1/token-bans/:tokenName",qe="/v1/token-bans/:tokenName",je="/v1/reactions",Ve="/v1/reactions",ze="/v1/trades",Xe={GET_MESSAGES:"/v1/messages",CREATE_MESSAGE:"/v1/messages",UPDATE_MESSAGE:"/v1/messages/:id",DELETE_MESSAGE:"/v1/messages/:id",GET_PINNED:"/v1/messages/pinned",PIN_MESSAGE:"/v1/messages/:id/pin",UNPIN_MESSAGE:"/v1/messages/:id/pin",GET_MESSAGE_STATS:"/v1/messages/stats"},Je="/v1/restricted-token-names",Ye="/v1/restricted-token-names",Qe="/live/:tokenName/chat",Ze="/live/:tokenName/chat",et="/live/:tokenName/chat",tt="/live/:tokenName/chat/slow-mode",nt={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"},rt="/v1/stats",it="/v1/trading/fee",st="/v1/trading/sale-details",ot="/v1/trading/quote",at="/v1/trading/premint-quote",ct={GET_LEADERBOARD:"/weekly-challenge",GET_TOKEN_HISTORY:"/weekly-challenge/history/:vaultAddress"},lt="/v1/notifications/register",ut="/v1/notifications/unregister",dt="/v1/notifications/preferences",ht="/v1/notifications/preferences",gt="/v1/config/client-flags",ft={NATIVE:"native",EXACT:"exact"},mt={RECENT:"recent",POPULAR:"popular"},pt={LOCAL:"local",EXTERNAL:"external"};function yt(e){return e instanceof Error}function bt(e){return yt(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 vt(e){return yt(e)||"object"==typeof e&&null!==e&&"stack"in e&&"string"==typeof e.stack?e.stack:void 0}function wt(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 Et(e){return"object"==typeof e&&null!==e&&"message"in e&&("response"in e||"request"in e||"config"in e)}function At(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 kt(e){if(null==e||"object"!=typeof e)return"";const t=e.Message;return"string"==typeof t&&t.trim().length>0?` - ${t}`:""}function St(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 Tt="Token name is required and must be a string",It=e=>`Could not find vault address for token: ${e}`,Nt={REQUIRED:"REQUIRED",INVALID_TYPE:"INVALID_TYPE",INVALID_VALUE:"INVALID_VALUE",INVALID_FORMAT:"INVALID_FORMAT",TOO_SHORT:"TOO_SHORT",TOO_LONG:"TOO_LONG",TOO_LARGE:"TOO_LARGE",TOO_SMALL:"TOO_SMALL",EMPTY_ARRAY:"EMPTY_ARRAY",ARRAY_TOO_LARGE:"ARRAY_TOO_LARGE",ZERO_VALUE:"ZERO_VALUE",INVALID_TICK_SPACING:"INVALID_TICK_SPACING",INVALID_FEE_TIER:"INVALID_FEE_TIER",INVALID_RANGE:"INVALID_RANGE",INVALID_PARAMETERS:"INVALID_PARAMETERS",NOT_FOUND:"NOT_FOUND",INVALID_DATA:"INVALID_DATA"};class Ct extends Error{constructor(e,t,n){super(e),this.field=t,this.code=n,this.name="ValidationError"}}class _t extends Ct{constructor(e){super(e,"token","TOKEN_RESTRICTED"),this.name="TokenRestrictedError"}}class xt extends Error{constructor(e,t,n){super(e),this.statusCode=t,this.originalError=n,this.name="NetworkError"}}class Rt extends Error{constructor(e,t){super(e),this.field=t,this.name="ConfigurationError"}}class Bt extends Error{constructor(e,t,n){super(e),this.transactionId=t,this.code=n,this.name="TransactionError"}}function Dt(e,t){return void 0!==t?t:e.charAt(0).toUpperCase()+e.slice(1)}function Mt(e,t){return new Ct(`Token "${e}" not found. Please verify the token name is correct.`,"tokenName","TOKEN_NOT_FOUND")}function Ot(e,t){const n=Dt(e,t);return new Ct(`${n} is required`,e,"REQUIRED")}function Ut(e,t,n){const r=Dt(e,n);return new Ct(`${r} must be ${t}`,e,"INVALID_FORMAT")}function Lt(e,t,n){return new xt(e,t,n)}function Pt(e,t){return new Rt(e,t)}function Ft(e,t,n){return new Bt(e,t,n)}function $t(e,t,n,r){n&&n.error(`${t}:`,e);const i=Et(e)?e.response?.status:void 0;return Lt(`${t}: ${bt(e)}`,i,yt(e)?e:void 0)}function Kt(e,t,n,r,i){const s=Dt(e,i);return new Ct(`${s} must be between ${t} and ${n}${void 0!==r?`, received: ${r}`:""}`,e,"OUT_OF_RANGE")}function Gt(e,t,n,r){const i=Dt(e,r);return new Ct(`${i} must be at least ${t}${void 0!==n?`, received: ${n}`:""}`,e,"TOO_SMALL")}function Ht(e,t,n,r){const i=Dt(e,r);return new Ct(`${i} must be at most ${t}${void 0!==n?`, received: ${n}`:""}`,e,"TOO_LARGE")}function Wt(e,t,n,r){const i=Dt(e,r),s=void 0!==n?`, received: ${"object"==typeof n?"object":String(n)}`:"";return new Ct(`${i} must be ${t}${s}`,e,"INVALID_TYPE")}function qt(e,t,n){const r=Dt(e,n);return new Ct(`${r} must be a valid number${void 0!==t?`: "${t}"`:""}`,e,"INVALID_NUMBER")}function jt(e,t,n,r){const i=Dt(e,r);return new Ct(`Invalid ${i}: ${t}. Must be one of: ${n.join(", ")}`,e,"INVALID_ENUM")}function Vt(e,t){if(e.length<2)return Ot(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 Ct(`At least one of ${n} must be provided`,e[0],"REQUIRED")}function zt(e,t,n,r){const i=Dt(e,r);return new Ct(`${i} must be at most ${t} characters${void 0!==n?`, received: ${n}`:""}`,e,"TOO_LONG")}function Xt(e,t){const n=Dt(e,t);return new Ct(`${n} cannot be empty`,e,"EMPTY_STRING")}function Jt(e){return null!=e&&"object"==typeof e&&"data"in e}function Yt(e,t,n=!1){const r=!0===e.error,i=n&&(null===e.data||void 0===e.data);if(r||i){const n=e?.statusCode??e.status??void 0;throw Lt(e?.message??t,n)}}function Qt(e){if(Jt(e))return e.data}function Zt(e,t="No data found in response"){if(!Jt(e))throw Lt(t);const n=e.data;if(null==n)throw Lt(t);return n}async function en(e,t={}){return rn(e,t,e=>{if(void 0===e.data)throw new Ct(`${t.errorContext??"Operation failed"}: No data returned from API`,"data","NO_DATA");return e.data})}async function tn(e,t={}){const{errorContext:n="Operation failed",logger:r,debugLogEnabled:i=!1}=t;i&&r&&r.debug(`${n}: starting operation`);try{const t=await e();return i&&r&&r.debug(`${n}: completed successfully`),t}catch(e){throw r&&r.error(n,{error:e}),e}}async function nn(e,t={}){return rn(e,t,e=>e)}async function rn(e,t,n){const{errorContext:r="Operation failed",logger:i,debugLogEnabled:s=!1}=t;s&&i&&i.debug(`${r}: starting operation`);try{const t=await e();if(null==t)throw new Ct(`${r}: No response from server`,"response","NO_RESPONSE");return Yt(t,r,!0),s&&i&&i.debug(`${r}: completed successfully`),n(t)}catch(e){throw i&&i.error(r,{error:e}),e}}const sn={BASE_PRICE:1650667151e-14,PRICE_SCALING_FACTOR:1166069e-12,TRADING_FEE_FACTOR:.001,GAS_FEE:"1",DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY:1e7};function on(e){return e.trim().toLowerCase()}function an(e){return e.trim().toUpperCase()}function cn(e){return e.trim().toUpperCase()}var ln;!function(e){e.DEBUG="DEBUG",e.INFO="INFO",e.WARN="WARN",e.ERROR="ERROR"}(ln||(ln={}));class un{constructor(e){this.levelPriority={[ln.DEBUG]:0,[ln.INFO]:1,[ln.WARN]:2,[ln.ERROR]:3},this.debugEnabled=e.debug,this.context=e.context??"SDK",this.minLevel=e.minLevel??(e.debug?ln.DEBUG:ln.INFO)}debug(e,t){this.log(ln.DEBUG,e,t)}info(e,t){this.log(ln.INFO,e,t)}warn(e,t){this.log(ln.WARN,e,t)}error(e,t){this.log(ln.ERROR,e,t)}log(e,t,n){if(this.levelPriority[e]<this.levelPriority[this.minLevel])return;if(e===ln.DEBUG&&!this.debugEnabled)return;const r=`[${(new Date).toISOString()}] [${this.context}] [${e}]`,i=this.getConsoleMethod(e);void 0!==n?yt(n)?i(`${r} ${t}`,n.message,vt(n)??""):i(`${r} ${t}`,n):i(`${r} ${t}`)}getConsoleMethod(e){switch(e){case ln.DEBUG:return console.debug;case ln.INFO:return console.info;case ln.WARN:return console.warn;case ln.ERROR:return console.error;default:return console.log}}child(e){return new un({debug:this.debugEnabled,context:`${this.context}:${e}`,minLevel:this.minLevel})}isDebugEnabled(){return this.debugEnabled&&this.levelPriority[ln.DEBUG]>=this.levelPriority[this.minLevel]}}function dn(e){return"string"==typeof e&&e.trim().length>0}function hn(e){return null==e||""===e}function gn(e){return null==e}const fn=new un({debug:!1,context:"DateUtils"});function mn(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())?(fn.warn(`Invalid date string received: "${e}". Using fallback.`),new Date):t}catch(t){return fn.warn(`Date parsing error for "${e}":`,t),new Date}}function pn(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 yn(e){return Date.now()-e}const bn={MIN_LENGTH:3,MAX_LENGTH:20,PATTERN:/^[a-zA-Z0-9]{3,20}$/},vn={MIN_LENGTH:2,MAX_LENGTH:20,PATTERN:/^[a-zA-Z0-9]+$/},wn={MIN_LENGTH:1,MAX_LENGTH:50},En=100,An=20,kn={MAX_LIMIT:50,DEFAULT_OFFSET:0,DEFAULT_LIMIT:20},Sn={PATTERN:/^(eth\|[0-9a-fA-F]{40}|client\|[a-zA-Z0-9_-]+)$/},Tn={MAX_LENGTH:100},In={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}},Nn={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})$/}},Cn=60,_n=31536e3,xn={MAX_LENGTH:64,PATTERN:/^(galaswap-operation-|galaconnect-operation-)/},Rn={PATTERN:/^[a-fA-F0-9]{64}$/},Bn={STREAM_URL_PATTERN:/^(rtmps?|srt):\/\/.+/},Dn=50,Mn=1,On=100,Un={FULL_NAME:{MIN_LENGTH:1,MAX_LENGTH:100,ALPHABETS_ONLY_PATTERN:/^[a-zA-Z]+(?:\s[a-zA-Z]+)?$/}};function Ln(e,t){if(hn(e))return t;try{return JSON.parse(e)}catch{return t}}function Pn(e,t=0){if(hn(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 Fn(e,t,n){if(gn(e))return t;if("number"==typeof e)return isNaN(e)?t:e;const r=Number(e);return isNaN(r)?t:r}function $n(e,t,n){if(gn(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 Kn(e,t){if(gn(e)||""===e)throw Ot(t);if(A.isBigNumber(e)){if(e.isNaN())throw qt(t,"NaN");return e}try{const n=new A(e);if(n.isNaN())throw qt(t,e);if(!n.isFinite())throw qt(t,e);return n}catch(n){if(n instanceof Ct)throw n;throw qt(t,e)}}function Gn(e,t=0){if(gn(e))return t;if("number"==typeof e)return isNaN(e)?t:e;return Pn(String(e).replace("%","").trim(),t)}function Hn(e,t=18){const n=Pn(e,0);if(0===n)return"0";return n.toFixed(t).replace(/\.?0+$/,"")}function Wn(e){return Hn(e,8)}function qn(e){return Hn(e,18)}function jn(e,t,n,r){if("number"!=typeof e)throw Wt(r,"a number",e,r);if(e<t||e>n)throw Kt(r,t,n,e)}function Vn(e,t,n){if("string"!=typeof e)throw Wt(n,"a string",e,n);if(e.length>t)throw Ht(n,t,e.length)}function zn(e,t){if("number"!=typeof e)throw Wt(t,"a number",e,t);if(!Number.isInteger(e))throw Wt(t,"an integer",e,t);if(e<=0)throw Gt(t,1,e,t)}function Xn(e,t,n=!1){if("string"!=typeof e)throw Wt(t,"a string",e,t);if(!n&&0===e.trim().length)throw Ot(t,`${t} (non-empty string)`)}function Jn(e,t){if("ASC"!==e&&"DESC"!==e)throw new Ct(`${t} must be either 'ASC' or 'DESC'`,t,"INVALID_ENUM_VALUE")}function Yn(e,t,n,r){const i="string"==typeof e?parseFloat(e):e;if(!isFinite(i))throw new Ct(`${r} must be a valid finite number between ${t} and ${n}`,r,"INVALID_NUMBER");if(i<t||i>n)throw Kt(r,t,n,i,r)}function Qn(e,t,n){const r="string"==typeof e?parseFloat(e):e,i="string"==typeof t?parseFloat(t):t;if(!isFinite(r))throw new Ct(`${n} minFee must be a valid finite number`,n,"INVALID_FEE_MINIMUM");if(!isFinite(i))throw new Ct(`${n} maxFee must be a valid finite number`,n,"INVALID_FEE_MAXIMUM");if(r<.1)throw new Ct(`${n} minFee must be >= 0.1, received ${r}`,n,"INVALID_FEE_MINIMUM");if(i>.5)throw new Ct(`${n} maxFee must be <= 0.5, received ${i}`,n,"INVALID_FEE_MAXIMUM");if(r>i)throw new Ct(`${n} minFee (${r}) must be <= maxFee (${i})`,n,"INVALID_FEE_RANGE")}function Zn(e,t,n,r){const i="string"==typeof e?parseFloat(e):e,s="string"==typeof t?parseFloat(t):t;if(!isFinite(i))throw new Ct(`${n} must be a valid finite number`,n,"INVALID_MIN_VALUE");if(!isFinite(s))throw new Ct(`${r} must be a valid finite number`,r,"INVALID_MAX_VALUE");if(i>s)throw new Ct(`${n} (${i}) must be less than or equal to ${r} (${s})`,n,"INVALID_RANGE")}function er(e,t,n){if(!t.includes(e))throw new Ct(`${n} must be one of [${t.map(e=>String(e)).join(", ")}], received "${e}"`,n,"INVALID_ENUM_VALUE")}const tr={ETH_ADDRESS:/^0x[0-9a-fA-F]{40}$/,BACKEND_ADDRESS:/^eth\|(0x)?[0-9a-fA-F]{40}$/,CLIENT_ADDRESS:/^client\|[a-zA-Z0-9_-]+$/},nr=dn,rr=hn,ir=gn;function sr(e,t,n=100,r,i){if(void 0!==i&&"string"!=typeof i)throw new Ct("cursor must be a string","cursor",Nt.INVALID_TYPE);const s=r??t,o=void 0!==r?"pageSize":"limit";if(void 0!==s&&(zn(s,o),s>n))throw new Ct(`${o} must be at most ${n}`,o,Nt.TOO_LARGE)}function or(e){const t=Object.values(e);return e=>"string"==typeof e&&t.includes(e)}function ar(e){return Object.values(e)}function cr(e,t,n,r={}){const{description:i="parameter",treatEmptyAsNull:s=!0}=r,o=e[t],a=e[n],c=null!=o&&(!s||""!==o),l=null!=a&&(!s||""!==a);if(!c&&!l)throw Pt(`Either ${t} or ${n} must be provided (${i})`,n);if(c&&l)throw Pt(`Cannot provide both ${t} and ${n}. Provide exactly one (${i}).`,n);return{chosen:c?t:n,hasA:c,hasB:l}}function lr(e,t="tokenName",n=bn){if(!nr(e))throw Ot(t);const r=e.trim();if(0===r.length)throw Ot(t);if(r.length<n.MIN_LENGTH)throw Kt(t,n.MIN_LENGTH,n.MAX_LENGTH,r.length,`${t} length`);if(r.length>n.MAX_LENGTH)throw Kt(t,n.MIN_LENGTH,n.MAX_LENGTH,r.length,`${t} length`);if(!n.PATTERN.test(r))throw new Ct(`${t} must contain only alphanumeric characters`,t,Nt.INVALID_FORMAT)}function ur(e,t="tokenName",n=bn){if(null==e)return;if("string"!=typeof e)throw Wt(t,"a string",e);const r=e.trim();if(0!==r.length&&!n.PATTERN.test(r))throw new Ct(`${t} must be ${n.MIN_LENGTH}-${n.MAX_LENGTH} alphanumeric characters`,t,Nt.INVALID_FORMAT)}function dr(e,t=bn){if("string"!=typeof e)return!1;const n=e.trim();return 0!==n.length&&t.PATTERN.test(n)}function hr(e,t="tokenName",n=bn){if(null==e)throw Ot(t,t);if("string"!=typeof e)throw Wt(t,"a string",e);const r=e.trim();if(0===r.length)throw Ot(t,t);if(!n.PATTERN.test(r))throw new Ct(`${t} must be ${n.MIN_LENGTH}-${n.MAX_LENGTH} alphanumeric characters`,t,Nt.INVALID_FORMAT)}function gr(e){return t=>{if(null==t||"object"!=typeof t)return!1;const n=t;for(const{field:t,type:r,nullable:i=!1,optional:s=!1,validator:o}of e){const e=n[t];if((!s||void 0!==e)&&(!i||null!==e)){if(typeof e!==r)return!1;if(o&&!o(e))return!1}}return!0}}const fr={requiredString:e=>t=>ir(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(!rr(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(!ir(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=>ir(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(!ir(n))return t.includes(n)?void 0:`${e} must be one of: ${t.join(", ")}`},requiredEnumValue:(e,t)=>n=>ir(n)?`${e} is required`:t.includes(n)?void 0:`${e} must be one of: ${t.join(", ")}`,isoDate:e=>t=>{if(!ir(t))return"string"!=typeof t?`${e} must be a string`:pn(t)?void 0:`${e} must be a valid ISO 8601 date string`},walletAddress:(e,t=!1)=>n=>{if(ir(n))return t?`${e} is required`:void 0;if("string"!=typeof n)return`${e} must be a string`;return tr.ETH_ADDRESS.test(n)||tr.BACKEND_ADDRESS.test(n)||tr.CLIENT_ADDRESS.test(n)?void 0:`${e} must be a valid wallet address`}};function mr(e){return t=>{const n=[],r=t;for(const t of e){const{field:e,required:i,type:s,validator:o}=t,a=r[e];if(i){if(ir(a)){n.push(`${e} is required`);continue}if("string"===s){if("string"!=typeof a){n.push(`${e} must be a string`);continue}if(0===a.trim().length){n.push(`${e} is required`);continue}}}if(!ir(a))if(void 0===s||typeof a===s){if(void 0!==o){const e=o(a,r);null!=e&&""!==e&&n.push(e)}}else n.push(`${e} must be a ${s}`)}return n}}function pr(e){return""===e||0===e.trim().length}function yr(e,t,n){if(!ir(e)){if("string"!=typeof e)throw Wt(t,"a string",e,t);if(e.length>n)throw new Ct(`${t} must be at most ${n} characters`,t,Nt.TOO_LARGE)}}function br(e,t){ir(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 Wt(t,"a date",e,t);if(isNaN(n.getTime()))throw new Ct(`${t} must be a valid date`,t,Nt.INVALID_FORMAT)}(e,t)}function vr(e,t,n){try{zn(e,t)}catch{throw function(e,t,n,r="OPERATION_FAILED"){return new Ct(`${e} failed: ${t}`,n,r)}(n,"must be a positive integer",t)}}function wr(e,t,n="status"){void 0!==e&&function(e,t,n){const r=Object.values(t);if(!r.includes(e))throw new Ct(`${n} must be one of: ${r.join(", ")}`,n,Nt.INVALID_FORMAT)}(e,t,n)}class Er{constructor(e,t=!1,n){this.http=e,this.logger=new un({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 Rt("JWT authentication required. Call sdk.login() first.")}return this.jwtAuth.getJwtHeaders()}isCalledFromUserCode(){const e=vt(new Error)??"";return!(!e.includes("expect")&&!e.includes("jest"))||!(!e.includes("tests/")&&!e.includes(".test.ts"))}validatePositiveInteger(e,t,n){vr(e,t,n)}}class Ar{constructor(e=!1,t){this.logger=t||new un({debug:e,context:this.constructor.name})}}class kr extends Ar{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 Sr extends kr{constructor(e=!1){super(e)}normalizeKey(e){return on(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>=Sr.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??sn.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 i=0;i+=2*r.length,void 0!==n.reverseBondingCurveMinFeeFactor&&(i+=8),void 0!==n.reverseBondingCurveMaxFeeFactor&&(i+=8),void 0!==n.reverseBondingCurveNetFeeFactor&&(i+=8),i+=8,void 0!==n.vaultAddress&&""!==n.vaultAddress&&(i+=2*n.vaultAddress.length),void 0!==n.maxSupply&&""!==n.maxSupply&&(i+=2*n.maxSupply.length),void 0!==n.symbol&&""!==n.symbol&&(i+=2*n.symbol.length),i+=32,t+=i}),{cacheSize:t,oldestEntry:this.cache.size>0?e:0}}getByTokenId(e){const t=`token:${on(e)}`;return this.cache.get(t)??null}setByTokenId(e,t){const n=`token:${on(e)}`;this.updateCacheEntry(n,t)}hasByTokenId(e){const t=`token:${on(e)}`;return this.cache.has(t)}}function Tr(e){return""===e?"":e.startsWith("0x")?e.slice(2):e}Sr.MAX_CACHE_SIZE=1e4;const Ir={ETHEREUM:tr.ETH_ADDRESS,ETHEREUM_NO_PREFIX:/^[a-fA-F0-9]{40}$/,BACKEND:tr.BACKEND_ADDRESS,CLIENT:tr.CLIENT_ADDRESS};class Nr{toBackendFormat(t){if(!nr(t))throw new Ct("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 Ct(`Invalid Ethereum address format in backend address. Expected 40 hex characters after 'eth|'. Got: "${t}"`,"address","INVALID_FORMAT");return t}if(n=Tr(t),!/^[a-fA-F0-9]{40}$/.test(n))throw new Ct(`Invalid Ethereum address format. Expected 40 hex characters (with or without 0x prefix). Got: "${t}"`,"address","INVALID_FORMAT");return`eth|${e(`0x${n}`).slice(2)}`}toEthereumFormat(e){if(!nr(e))throw new Ct("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 Ct(`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(!Ir.CLIENT.test(e))throw new Ct(`Invalid client address format: "${e}"`,"address","INVALID_FORMAT");return e}if(e.startsWith("eth|")){if(!Ir.BACKEND.test(e))throw new Ct(`Invalid backend address format: "${e}"`,"address","INVALID_FORMAT");return e}return this.toBackendFormat(e)}}isValid(e){return!!nr(e)&&(!!Ir.ETHEREUM.test(e)||(!!Ir.ETHEREUM_NO_PREFIX.test(e)||(!!Ir.BACKEND.test(e)||!!Ir.CLIENT.test(e))))}assertValid(e,t="address"){if(!this.isValid(e))throw new Ct(`${t} must be a valid wallet address (Ethereum or backend format)`,t,"INVALID_FORMAT")}detectFormat(e){return nr(e)?Ir.ETHEREUM.test(e)||Ir.ETHEREUM_NO_PREFIX.test(e)?"ethereum":Ir.BACKEND.test(e)?"backend":Ir.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 Tr(e).toLowerCase();if(/^[a-fA-F0-9]{40}$/.test(e))return e.toLowerCase();throw new Ct(`Cannot extract hex from address: "${e}". Expected Ethereum or backend format.`,"address","INVALID_FORMAT")}}const Cr=new Nr,_r=Tr;function xr(e){return Cr.toBackendFormat(e)}function Rr(e){return Cr.toEthereumFormat(e)}function Br(e){return Cr.normalizeInput(e)}function Dr(e){return Cr.isValid(e)}function Mr(e,t="address"){Cr.assertValid(e,t)}function Or(e){const t="string"==typeof e?e:e.address;return Cr.toBackendFormat(t)}function Ur(e){return Cr.detectFormat(e)}var Lr=Object.freeze({__proto__:null,AddressFormatter:Nr,assertValidWalletAddress:Mr,detectFormat:Ur,fromBackendAddressFormat:Rr,isValidAddress:Dr,normalizeAddressInput:Br,stripHexPrefix:_r,toBackendAddressFormat:xr,toBackendAddressFromEthers:Or});const Pr=p.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"),Fr=p.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"),$r=p.string({message:"Token description is required"}).min(1,"Token description is required").max(500,"Token description must be at most 500 characters"),Kr=p.string().min(1,"Token name must be at least 1 character").max(50,"Token name must be at most 50 characters"),Gr=p.string().min(1,"Search query must be at least 1 character").max(100,"Search query must be at most 100 characters"),Hr=p.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"),Wr=p.string().regex(tr.BACKEND_ADDRESS,"Address must be in format: eth|[40-hex-chars]"),qr=p.string().regex(tr.ETH_ADDRESS,"Invalid Ethereum address format"),jr=p.string().refine(e=>tr.BACKEND_ADDRESS.test(e)||tr.ETH_ADDRESS.test(e)||tr.CLIENT_ADDRESS.test(e),"Address must be eth|[40-hex], 0x[40-hex], or client|[identifier] format").transform(e=>(new Nr).normalizeInput(e)??e),Vr=p.string().refine(e=>tr.BACKEND_ADDRESS.test(e)||/^service\|Token\$Unit\$[A-Z0-9]+\$eth:[0-9a-fA-F]{40}\$launchpad$/.test(e),"Invalid vault address format"),zr=p.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>Pn(e,0)>0,"Amount must be greater than zero"),Xr=p.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>Pn(e,0)>=0,"Amount must be zero or greater"),Jr=p.string().url("Must be a valid URL").regex(/^https?:\/\//,"URL must start with http:// or https://"),Yr=p.string().optional().refine(e=>void 0===e||""===e||/^https?:\/\/.+\..+/.test(e),"Must be a valid URL if provided"),Qr=p.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 Zr(e=100){return p.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 ei=Zr(100),ti=Zr(20),ni=Zr(20),ri=p.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"),ii=p.string().max(255,"Filename must be at most 255 characters"),si=p.enum(["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"]),oi=p.string().datetime("Must be a valid ISO 8601 date string"),ai=p.number().int("Timestamp must be an integer").min(0,"Timestamp must be non-negative"),ci=p.string().regex(/^0x[a-fA-F0-9]{64}$/,"Private key must be format: 0x + 64 hex characters"),li=p.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"),ui=p.string().regex(/^galaconnect-operation-[a-z0-9-]+$/,"Unique key must be format: galaconnect-operation-{unique-id}"),di=[".png",".jpg",".jpeg",".gif",".webp",".svg"],hi=p.object({file:p.union([p.instanceof(File),p.instanceof(Buffer)]),name:ii,size:ri,type:si}),gi=p.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"),fi=p.instanceof(Buffer).refine(e=>e.length>=1&&e.length<=10485760,"Buffer size must be between 1 byte and 10MB"),mi=p.union([gi,fi]),pi=p.enum([".png",".jpg",".jpeg",".gif",".webp",".svg"]),yi=ii.refine(e=>{const t=e.slice(e.lastIndexOf(".")).toLowerCase();return di.includes(t)},`Filename must end with one of: ${di.join(", ")}`),bi=p.object({websiteUrl:Yr,telegramUrl:Yr,twitterUrl:Yr,instagramUrl:Yr,facebookUrl:Yr,redditUrl:Yr,tiktokUrl:Yr}).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"),vi=p.string().min(1,"Token category must not be empty").default("Unit"),wi=p.string().min(1,"Token collection must not be empty").default("Token"),Ei=p.object({minFeePortion:p.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal string").refine(e=>Pn(e,0)>=.1,"Minimum fee must be >= 0.1").refine(e=>Pn(e,0)<=.5,"Minimum fee must be <= 0.5"),maxFeePortion:p.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal string").refine(e=>Pn(e,0)>=.1,"Maximum fee must be >= 0.1").refine(e=>Pn(e,0)<=.5,"Maximum fee must be <= 0.5")}).refine(e=>Pn(e.maxFeePortion,0)>=Pn(e.minFeePortion,0),{message:"Maximum fee must be >= minimum fee",path:["maxFeePortion"]}),Ai=p.object({tokenName:Pr,tokenSymbol:Fr,tokenDescription:$r,tokenImage:p.union([p.instanceof(File),p.instanceof(Buffer),p.string().url("Token image must be a valid URL")]).optional(),preBuyQuantity:Xr.default("0"),websiteUrl:Yr,telegramUrl:Yr,twitterUrl:Yr,instagramUrl:Yr,facebookUrl:Yr,redditUrl:Yr,tiktokUrl:Yr,tokenCategory:vi,tokenCollection:wi,reverseBondingCurveConfiguration:Ei.optional(),saleStartTime:p.number().int().positive().optional(),privateKey:ci.optional()}),ki=p.object({file:p.union([p.instanceof(File),p.instanceof(Buffer)]),tokenName:Pr}),Si=p.enum(["RECENT","POPULAR"]),Ti=p.object({tokenName:Pr.optional(),symbol:Fr.optional()}).refine(e=>void 0!==e.tokenName||void 0!==e.symbol,"At least one of tokenName or symbol is required"),Ii=p.enum(["NATIVE","MEME"]),Ni=p.enum(["IN","OUT"]),Ci=p.object({from:p.number().int("From timestamp must be an integer").min(173e6,"From timestamp must be at least 173000000"),to:p.number().int("To timestamp must be an integer").min(173e6,"To timestamp must be at least 173000000"),resolution:p.number().int("Resolution must be an integer").min(1,"Resolution must be at least 1"),tokenName:Pr}),_i=p.object({tokenName:Pr,slippageToleranceFactor:p.number().min(0).max(1).optional(),maxAcceptableReverseBondingCurveFeeSlippageFactor:p.number().min(0).max(1).optional(),privateKey:ci.optional()}),xi=p.object({offset:p.number().int().min(0).default(0),pageSize:p.number().int().min(1).max(100).default(10)}),Ri=p.object({offset:p.number().int().min(0).default(0),pageSize:p.number().int().min(1).max(20).default(10)}),Bi=p.object({offset:p.number().int().min(0).default(0),pageSize:p.number().int().min(1).max(20).default(10)}),Di=xi.extend({type:p.enum(["RECENT","POPULAR"]).optional(),tokenName:p.string().min(1).max(50).optional(),search:p.string().min(1).max(100).optional()}),Mi=Ri.extend({tokenName:p.string().min(1).max(50).optional(),search:p.string().min(1).max(100).optional()}),Oi=Bi.extend({tradeType:p.enum(["BUY","SELL"]).optional(),tokenName:p.string().min(1).max(50).optional(),userAddress:p.string().regex(/^(0x[a-fA-F0-9]{40}|eth\|[a-fA-F0-9]{40})$/).optional(),startDate:p.string().datetime().optional(),endDate:p.string().datetime().optional(),sortOrder:p.enum(["ASC","DESC"]).default("DESC")}),Ui={page:p.number().int().min(1),limit:p.number().int().min(1),total:p.number().int().min(0),totalPages:p.number().int().min(0),hasNext:p.boolean(),hasPrevious:p.boolean()},Li=p.object(Ui);function Pi(e){return p.object({data:p.array(e),...Ui})}const Fi=p.enum(["buy","sell"]),$i=p.enum(["BUY","SELL"]),Ki=p.object({tradeType:Fi,tokenAmount:zr,vaultAddress:Vr,userAddress:jr,slippageTolerance:zr.optional(),deadline:p.number().int().positive().optional()}),Gi=p.object({tokenSymbol:Fr,nativeTokenQuantity:zr,expectedToken:zr,maxAcceptableReverseBondingCurveFee:Xr.default("0").optional()}),Hi=p.object({tokenSymbol:Fr,tokenQuantity:zr,expectedNativeToken:zr,maxAcceptableReverseBondingCurveFee:Xr.default("0").optional()}),Wi=Bi.extend({tokenName:Kr.optional()}),qi=p.object({page:p.number().int().min(1).max(1e3).default(1).optional(),limit:p.number().int().min(1).max(20).default(10).optional()}),ji=p.enum(["NATIVE","MEME"]),Vi=p.enum(["IN","OUT"]),zi=p.object({type:ji,method:Vi,vaultAddress:Vr,amount:zr}),Xi=p.object({nativeTokenQuantity:zr}),Ji=p.object({vaultAddress:Vr}),Yi=p.object({minFeePortion:zr,maxFeePortion:zr}),Qi=p.enum(["both","held","created"]),Zi=Ri.extend({type:Qi.optional(),address:jr.optional(),search:Gr.optional(),tokenName:Kr.optional()}),es=p.object({address:jr.optional(),refresh:p.boolean().optional()}),ts=p.object({profileImage:p.string(),fullName:Hr,address:jr,privateKey:ci.optional()}),ns=p.object({file:p.union([p.instanceof(File),p.instanceof(Buffer)]),address:jr.optional(),privateKey:ci.optional()}),rs=p.object({created:p.number(),createdBy:p.string(),expires:p.number(),instanceId:p.string(),lockAuthority:p.string(),name:p.string(),quantity:p.string(),vestingPeriodStart:p.number()}),is=p.object({address:jr,tokenId:p.union([p.string(),p.object({collection:p.string(),category:p.string(),type:p.string(),additionalKey:p.string()}),p.object({collection:p.string(),category:p.string(),type:p.string(),additionalKey:p.string(),instance:p.string()})]).optional(),tokenName:Kr.optional(),withExpired:p.boolean().optional()}).refine(e=>void 0!==e.tokenId||void 0!==e.tokenName,"At least one token identifier (tokenId or tokenName) is required");function ss(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 os=ss(Pr),as=ss(Fr),cs=ss($r),ls=ss(jr),us=ss(Vr),ds=ss(zr),hs=ss(Hr),gs=ss(Gr),fs=ss(Kr),ms=ss(Ai),ps=ss(bi),ys=ss(ki),bs=ss(Ti),vs=ss(Zi),ws=ss(es),Es=ss(ts),As=ss(ns),ks=ss(is),Ss=ss(Ki),Ts=ss(Gi),Is=ss(Hi),Ns=ss(Wi),Cs=ss(qi),_s=ss(zi),xs=ss(Xi),Rs=ss(Ji);function Bs(e){return ms(e).success}function Ds(e){const t=ms(e);return t.success?[]:t.errors??["Unknown validation error"]}function Ms(e){const t=Ds(e);if(t.length>0)throw new Error(`LaunchTokenData validation failed:\n${t.map(e=>`- ${e}`).join("\n")}`)}function Os(e,t){return"string"==typeof e[t]}function Us(e,t){return void 0===e[t]||"string"==typeof e[t]}function Ls(e,t){return void 0===e[t]||"number"==typeof e[t]}function Ps(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 Fs(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(!Ps(n[t],r))return!1}return!0}}or({BUY:"buy",SELL:"sell"});const $s=Fs({vaultAddress:"string"}),Ks=Fs({nativeTokenQuantity:"string"});function Gs(e){if(ir(e)||"object"!=typeof e)return{};const t={};for(const[n,r]of Object.entries(e))ir(r)||(nr(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 Hs=Object.freeze({__proto__:null,adaptQueryParams:Gs});function Ws(e,t="0"){return function(e,t="0"){if(hn(e))return new A(t);if(A.isBigNumber(e))return e.isNaN()?new A(t):e;try{const n=new A(e);return n.isNaN()||!n.isFinite()?new A(t):n}catch{return new A(t)}}(e,t)}function qs(e,t){return void 0!==t?Ws(e).toFixed(t):Ws(e).toFixed()}function js(e){const t=Ws(e),n=Math.log(1.0001),r=t.toNumber();return Math.log(r)/n}function Vs(e){return Ws(e).isZero()}function zs(e,t){return Ws(e).isLessThan(Ws(t))}function Xs(...e){e.forEach(e=>{if(e.isNaN())throw qt("value","NaN");if(!e.isFinite())throw Ht("value","finite");if(e.isLessThanOrEqualTo(0))throw Gt("value","0",e.toString())})}function Js(...e){e.forEach(e=>{if(e.isNaN())throw qt("value","NaN");if(!e.isFinite())throw Ht("value","finite");if(e.isLessThan(0))throw Gt("value","0",e.toString())})}function Ys(e,t,n){if(e.isNaN())throw qt(t,"NaN");if(!e.isFinite())throw Ht(t,"finite");if(e.isLessThanOrEqualTo(0))throw Gt(t,"0",e.toString())}function Qs(e,t,n="0"){const r=Ws(t);return Vs(r)?Ws(n):Ws(e).dividedBy(r)}const Zs={calculateBuyWithExact(e,t){const n=Pn(e),r=Pn(t),{BASE_PRICE:i,PRICE_SCALING_FACTOR:s,TRADING_FEE_FACTOR:o,GAS_FEE:a}=sn,c=function(e,t){const n=Math.pow(10,t);return Math.ceil(e*n)/n}(i*(Math.exp((r+n)*s)-Math.exp(r*s))/s,8),l=qs(Ws(c).multipliedBy(o));return{amount:c.toString(),reverseBondingCurveFee:"0",transactionFee:l,gasFee:a}},calculateBuyWithNative(e,t){const n=Pn(e),r=Pn(t),{BASE_PRICE:i,PRICE_SCALING_FACTOR:s,TRADING_FEE_FACTOR:o,GAS_FEE:a}=sn,c=Math.log(n*s/i+Math.exp(r*s))/s-r,l=qs(Ws(c).multipliedBy(o));return{amount:c.toString(),reverseBondingCurveFee:"0",transactionFee:l,gasFee:a}},calculateSellWithExact(e,t,n,r,i){const s=Pn(e),o=Pn(t),a=Pn(n),{BASE_PRICE:c,PRICE_SCALING_FACTOR:l,TRADING_FEE_FACTOR:u,GAS_FEE:d}=sn,h=c*(Math.exp(o*l)-Math.exp((o-s)*l))/l,g=Ws(h),f=r+o/a*(i-r),m=qs(g.multipliedBy(f),8),p=qs(g.multipliedBy(u));return{amount:h.toString(),reverseBondingCurveFee:m,transactionFee:p,gasFee:d}},calculateSellWithNative(e,t,n,r,i){const s=Pn(e),o=Pn(t),a=Pn(n),{BASE_PRICE:c,PRICE_SCALING_FACTOR:l,TRADING_FEE_FACTOR:u,GAS_FEE:d}=sn;if(s>=c*(Math.exp(o*l)-1)/l){const e=Ws(s),t=r+o/a*(i-r),n=qs(e.multipliedBy(t),8),c=qs(e.multipliedBy(u));return{amount:o.toString(),reverseBondingCurveFee:n,transactionFee:c,gasFee:d}}const h=o-Math.log(Math.exp(o*l)-s*l/c)/l,g=Ws(s),f=r+o/a*(i-r),m=qs(g.multipliedBy(f),8),p=qs(g.multipliedBy(u));return{amount:h.toString(),reverseBondingCurveFee:m,transactionFee:p,gasFee:d}}};class eo extends Error{constructor(e,t,n){super(e),this.filename=t,this.mimeType=n,this.name="FileValidationError"}}function to(e,t,n){if(null==e)throw new eo("File is required",t,n);if("undefined"!=typeof File&&e instanceof File){const t=gi.safeParse(e);if(!t.success){const n=t.error.issues.map(e=>e.message).join("; ");throw new eo(n,e.name,e.type)}return}if(Buffer.isBuffer(e)){if(void 0===t||""===t)throw new eo("Filename is required when uploading Buffer objects",t,n);const r=fi.safeParse(e);if(!r.success){const e=r.error.issues.map(e=>e.message).join("; ");throw new eo(e,t,n)}try{Vn(t,255,"filename")}catch(e){throw new eo(e.message,t,n)}const i=["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"];if(!i.includes(n))throw new eo(`Invalid file type "${n}" is not allowed. Allowed types: ${i.join(", ")}`,t,n);const s=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(s))throw new eo(`File extension "${s}" 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"}}(s);if(a!==n&&"application/octet-stream"!==a)throw new eo(`File extension "${s}" does not match MIME type "${n}"`,t,n);return}throw new eo("File must be a File object (browser) or Buffer (Node.js)",t,n)}class no{validate(e,t={}){const{allowZero:n=!0,minimum:r,maximum:i,maxDecimals:s=no.MAX_DECIMAL_PLACES,fieldName:o="amount"}=t;if(!nr(e))throw new Ct(`${o} cannot be empty or whitespace-only. Provide a valid numeric string.`,o,"INVALID_NUMERIC_STRING");if(/[eE]/.test(e))throw new Ct(`${o} cannot use scientific notation. Use standard decimal format (e.g., "1000" instead of "1e3").`,o,"INVALID_NUMERIC_STRING");const a=Pn(e,NaN);if(isNaN(a))throw new Ct(`${o} must be a valid numeric string. Received: "${e}"`,o,"INVALID_NUMERIC_STRING");if(!isFinite(a))throw new Ct(`${o} must be a finite number. Cannot be Infinity or -Infinity.`,o,"INVALID_NUMERIC_STRING");if(a<0)throw new Ct(`${o} must be non-negative. Received: "${e}"`,o,"INVALID_NUMERIC_STRING");if(!n&&0===a)throw new Ct(`${o} must be greater than zero. Received: "${e}"`,o,"INVALID_NUMERIC_STRING");const c=Ws(e),l=c.decimalPlaces()??0;if(l>s)throw new Ct(`${o} cannot exceed ${s} decimal places. Received: ${l} decimal places`,o,"PRECISION_EXCEEDED");if(void 0!==r&&zs(c,r))throw new Ct(`${o} must be at least ${r}. Received: "${e}"`,o,"BELOW_MINIMUM");if(void 0!==i&&(u=i,Ws(c).isGreaterThan(Ws(u))))throw new Ct(`${o} cannot exceed ${i}. Received: "${e}"`,o,"EXCEEDS_MAXIMUM");var u}parseAmount(e,t="0"){return Ws(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 qs(e,t)}clampAmount(e,t,n){const r=Ws(e),i=Ws(t),s=Ws(n);return function(e,t,n){const r=Ws(e),i=Ws(t),s=Ws(n);return r.isGreaterThanOrEqualTo(i)&&r.isLessThanOrEqualTo(s)}(r,i,s)?qs(r):zs(r,i)?qs(i):qs(s)}}function ro(e,t){throw new Ct(e.join("; "),t,"VALIDATION_ERROR")}function io(e){const t=os(e);!t.success&&t.errors&&ro(t.errors,"tokenName")}function so(e){const t=Ci.safeParse(e);var n;t.success||ro((n=t.error.issues,Array.isArray(n)?n.map(e=>null!=e&&"object"==typeof e&&"message"in e&&"string"==typeof e.message?e.message:String(e)).filter(e=>""!==e):[]),"options")}function oo(e,t,n=!0){ao.validate(e,{fieldName:t,allowZero:n})}no.MAX_DECIMAL_PLACES=18,no.MIN_POSITIVE="0.00000000000000001";const ao=new no;function co(e,t,n=qs){if(!Array.isArray(e))throw Lt("Invalid API response: expected array of holders",t);for(const n of e){if(!lo(n))throw Lt("Invalid holder data: missing or invalid owner field",t);if(!uo(n))throw Lt("Invalid holder data: missing or invalid quantity field",t);const e=Pn(n.quantity,NaN);if(isNaN(e)||!isFinite(e))throw Lt(`Invalid holder quantity: "${n.quantity}"`,t)}const r=e,i=r.reduce((e,t)=>e.plus(t.quantity),Ws(0));return{holders:r.map(e=>({address:e.owner,balance:e.quantity,percentage:Qs(Ws(e.quantity),i,Ws(0)).multipliedBy(100).toNumber()})),totalSupply:n(i),totalHolders:r.length,lastUpdated:new Date}}function lo(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.owner&&""!==t.owner}function uo(e){return"string"==typeof e.quantity&&""!==e.quantity}class ho{constructor(e,t,n,r,i,s,o="local",a){this.http=e,this.tokenResolver=t,this.logger=n,this.bundleHttp=r,this.galaChainHttp=i,this.dexApiHttp=s,this.defaultCalculateAmountMode=o,this.launchpadWrites=a,this.metadataCache=new Sr}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;io(t);const r=`${t}.png`;to(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 Ut("file","a File object (browser) or Buffer (Node.js)");{const r=`${void 0!==n.tokenName&&""!==n.tokenName?n.tokenName:t}.png`,i=new Blob([n.file],{type:"image/png"});e.append("image",i,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 Lt(void 0!==r.message&&""!==r.message?r.message:"Image upload failed - no URL returned",r.status);const i=Qt(r);if(!i?.imageUrl)throw Lt("Image upload failed - no URL returned",r.status);return i.imageUrl}catch(e){if(yt(e)&&e.message.includes("FormData"))throw Pt("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&&sr(0,void 0,100,e.pageSize),void 0!==e.tokenName&&""!==e.tokenName&&io(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=Gs(t),r=await this.http.get(C.FETCH_POOLS,n);if(!0===r.error||200!==r.status)throw Lt(void 0!==r.message&&""!==r.message?r.message:"Failed to fetch pools",r.status);const i=Qt(r);if(null==i)throw Lt("Failed to fetch pools - no data returned",r.status);let s=[];if(i.tokens)if(Array.isArray(i.tokens))s=i.tokens.map(e=>this.normalizePoolData(e));else{const e=i.tokens;s=[this.normalizePoolData(e)]}else i.pools&&Array.isArray(i.pools)&&(s=i.pools.map(e=>this.normalizePoolData(e)));const{extractMetadataFromPoolData:o,isValidPoolForCaching:a}=await Promise.resolve().then(function(){return rx});s.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=i.count??i.total??0,l={hasNextPage:i.hasNextPage??!1};return void 0!==i.hasPrevPage&&(l.hasPrevPage=i.hasPrevPage),void 0!==i.nextCursor&&(l.nextCursor=i.nextCursor),void 0!==i.prevCursor&&(l.prevCursor=i.prevCursor),c>0&&(l.totalCount=c),{items:s,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 Ut("options","an options object");const{tokenName:t,amount:n,type:r,currentSupply:i}=e;return"external"===this.validateAmountCalculationInputs(t,n,r,e.mode,[ft.NATIVE,ft.EXACT],'"native" or "exact"')?this.calculateBuyAmountExternal({tokenName:t,amount:n,type:r}):this.calculateBuyAmountLocal(this.addIfDefined({tokenName:t,amount:n,type:r},"currentSupply",i))}async calculateBuyAmountExternal(e){const{tokenName:t,amount:n,type:r}=e;return this.validateExternalAmountInputs(t,n),"exact"===r?en(()=>this.http.get(ot,{tokenName:t,amount:n,type:"MEME",method:"OUT"}),{errorContext:`Failed to calculate buy amount for ${t} (exact tokens)`}):en(()=>this.http.get(ot,{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:i,maxSupply:s,reverseBondingCurveMaxFeeFactor:o,reverseBondingCurveMinFeeFactor:a}=e;if("external"===this.validateAmountCalculationInputs(t,n,r,e.mode,[ft.EXACT,ft.NATIVE],'"exact" or "native"'))return this.calculateSellAmountExternal({tokenName:t,amount:n,type:r});{const e={tokenName:t,amount:n,type:r,...void 0!==i&&{currentSupply:i},...void 0!==s&&{maxSupply:s},...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?en(()=>this.http.get(ot,{tokenName:t,amount:n,type:"MEME",method:"IN"}),{errorContext:`Failed to calculate sell amount for ${t} (exact tokens)`}):en(()=>this.http.get(ot,{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:i}=e;if(!nr(n))throw Ot("amount","Amount");if(r!==ft.NATIVE&&r!==ft.EXACT)throw Wt("type",'"native" or "exact"',r);void 0!==i&&oo(i,"currentSupply");const s=null==i||""===i;if(s&&(null==t||""===t))throw Ot("tokenName","Token name (required when currentSupply is not provided)");null!=t&&""!==t&&io(t);let o=i;if(s){o=(await this.fetchPoolDetailsForCalculation(t)).currentSupply}return r===ft.EXACT?Zs.calculateBuyWithExact(n,o):Zs.calculateBuyWithNative(n,o)}async calculateSellAmountLocal(e){const{tokenName:t,amount:n,type:r,currentSupply:i,maxSupply:s,reverseBondingCurveMaxFeeFactor:o,reverseBondingCurveMinFeeFactor:a}=e;if(!nr(n))throw Ot("amount","Amount");if(r!==ft.EXACT&&r!==ft.NATIVE)throw Wt("type",'"exact" or "native"',r);void 0!==i&&oo(i,"currentSupply");const c=null==i||""===i||null==s||""===s||void 0===o||void 0===a;if(c&&(null==t||""===t))throw Ot("tokenName","Token name (required when currentSupply, maxSupply, or fee factors are not provided)");null!=t&&""!==t&&io(t);let l=i,u=s,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===ft.EXACT?Zs.calculateSellWithExact(n,l,u,h,d):Zs.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 Os(t,"tokenName")&&function(e){return void 0===e.calculateAmountMode||"local"===e.calculateAmountMode||"external"===e.calculateAmountMode}(t)&&Us(t,"currentSupply")}(e))throw Wt("options","CalculateBuyAmountForGraduationOptions or string (token name)",typeof e);const{tokenName:n,calculateAmountMode:r,currentSupply:i}=t;io(n);const s=await this.fetchSaleDetails(n),o=i??qs(Ws(s.maxSupply).minus(s.sellingTokenQuantity)),a=s.sellingTokenQuantity;if("0"===a)throw Ot("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 Pt("Bundle backend client not configured. LaunchToken requires bundleHttp client.","bundleHttp");Ms(e);const t=void 0!==e.preBuyQuantity&&""!==e.preBuyQuantity?e.preBuyQuantity:"0",n=Pn(t);if(0===n&&"0"!==t)throw qt("preBuyQuantity",t,"Pre-buy quantity");if(n<0)throw qt("preBuyQuantity",t,"Pre-buy quantity");if(e.reverseBondingCurveConfiguration){const{minFeePortion:t,maxFeePortion:n}=e.reverseBondingCurveConfiguration;Qn(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 Ot("tokenName","Token name");io(e);const t=await this.http.get(`/holders/${e}`);if(!0===t.error||200!==t.status)throw Lt(void 0!==t.message&&""!==t.message?t.message:"Failed to fetch token distribution",t.status);const n=Qt(t);if(null==n)throw Lt("Failed to fetch token distribution - no data returned",t.status);return co(n,t.status)}async calculateInitialBuyAmount(e){if(!Ks(e))throw Ut("data","valid pre-mint calculation data");if(!this.galaChainHttp)throw Pt("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 i=r,s=i.calculatedQuantity,o=i.extraFees;if("string"!=typeof s||"object"!=typeof o||null===o)return!1;const a=o;return"string"==typeof a.reverseBondingCurve&&"string"==typeof a.transactionFees}(n))throw Lt("Malformed response data from GalaChain gateway");try{At(n,"Pre-mint calculation")}catch(e){throw Lt(bt(e),500)}const{calculatedQuantity:r,extraFees:i}=n.Data;return{amount:r,reverseBondingCurveFee:i.reverseBondingCurve,transactionFee:i.transactionFees,gasFee:"1"}}catch(e){if(yt(e)&&e instanceof xt)throw e;throw Lt(bt(e),500)}}async fetchPoolDetailsForCalculation(e){const t=await this.fetchSaleDetails(e),n=qs(Ws(t.maxSupply).minus(t.sellingTokenQuantity)),r=t.sellingTokenQuantity,i=t.maxSupply;let s=.5,o=.1;const a=t.reverseBondingCurveConfiguration;null!=a?.maxFeePortion&&(s=Gn(a.maxFeePortion,.5)),null!=a?.minFeePortion&&(o=Gn(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=s-o;return this.metadataCache.set(e,{maxSupply:i,reverseBondingCurveMaxFeeFactor:s,reverseBondingCurveMinFeeFactor:o,reverseBondingCurveNetFeeFactor:c}),{currentSupply:n,remainingTokens:r,maxSupply:i,reverseBondingCurveMaxFeeFactor:s,reverseBondingCurveMinFeeFactor:o,reverseBondingCurveNetFeeFactor:c}}async fetchCurrentSupply(e){io(e);const t=await this.fetchSaleDetails(e),n=qs(Ws(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:!Vs(t)||!Vs(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 Ct(It(e),"tokenName","VAULT_NOT_FOUND");if(void 0===this.galaChainHttp||null===this.galaChainHttp)throw Pt("GalaChain HTTP client not configured");const n=await this.galaChainHttp.post("/api/asset/launchpad-contract/FetchSaleDetails",{vaultAddress:t});if(1!==n.Status)throw Lt(`Failed to fetch pool details: Status ${n.Status}`,n.Status);return n.Data}validateAmountCalculationInputs(e,t,n,r,i,s){const o=r??this.defaultCalculateAmountMode;if("local"!==o&&"external"!==o)throw Wt("mode",'"local" or "external"',o);if(!nr(e))throw Ot("tokenName","Token name");if(!nr(t))throw Ot("amount","Amount");if("string"!=typeof n||!i.includes(n))throw Wt("type",s,n);return o}validateExternalAmountInputs(e,t){if("string"!=typeof e||""===e)throw new Ct("Token name must be a non-empty string","tokenName","INVALID_TOKEN_NAME");if("string"!=typeof t||""===t)throw new Ct("Amount must be a non-empty string","amount","INVALID_AMOUNT")}getAddress(){return this.http.getAddress()}formatAddressForBackend(e){return xr(e)}validateTokenName(e){return io(e)}validatePagination(e){void 0!==e.pageSize&&sr(0,void 0,100,e.pageSize)}async fetchTokenPrice(e){if(void 0===this.dexApiHttp||null===this.dexApiHttp)throw Pt("DEX API client not configured. Token price fetching requires dexApiHttp client.","dexApiHttp");if(null==e||""===e||Array.isArray(e)&&0===e.length)throw Ot("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 Lt(`Failed to fetch token prices: ${bt(e)}`,void 0,yt(e)?e:void 0)}}warmCacheFromPoolData(e,t){this.metadataCache.warmFromPoolData(e,t)}getCacheStats(){return this.metadataCache.getStats()}clearCache(e){this.metadataCache.clear(e)}}const go={REFRESH_THRESHOLD_MS:3e5,DEFAULT_EXPIRY_S:86400,LOGIN_MESSAGE_PREFIX:"Sign in to Launchpad t:",AUTH_HEADER:"Authorization",BEARER_PREFIX:"Bearer "};class fo{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 mo,po;!function(e){e.WALLET_NOT_CONNECTED="WALLET_NOT_CONNECTED",e.SIGNATURE_FAILED="SIGNATURE_FAILED",e.INVALID_ADDRESS="INVALID_ADDRESS",e.MESSAGE_GENERATION_FAILED="MESSAGE_GENERATION_FAILED"}(mo||(mo={}));class yo extends Error{constructor(e,t,n){super(t),this.type=e,this.originalError=n,this.name="AuthError"}}class bo{constructor(e,t=go.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 fo,this.refreshThresholdMs=t}setToken(e,t){if(!nr(e))throw new yo(mo.SIGNATURE_FAILED,"JWT token must be a non-empty string");if("number"!=typeof t)throw new yo(mo.SIGNATURE_FAILED,"Token expiration must be a positive finite number (seconds)");if(!Number.isFinite(t))throw new yo(mo.SIGNATURE_FAILED,"Token expiration must be a positive finite number (seconds)");if(t<=0)throw new yo(mo.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 yo(mo.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:`${go.BEARER_PREFIX}${e}`}getJwtHeaders(){const e=this.getAuthorizationHeader();if(null===e||""===e)throw new yo(mo.WALLET_NOT_CONNECTED,"No JWT token available. Call login() first.");return{[go.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 i=await this.storage.get(this.STORAGE_KEYS.REFRESH_TOKEN),s=await this.storage.get(this.STORAGE_KEYS.REFRESH_EXPIRES);if(i&&s){const e=Number(s);Number.isFinite(e)&&Date.now()<e&&(this.tokenState.refreshToken=i,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 vo(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),$t(e,t,n))}}function wo(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),$t(e,t,n))}}class Eo{constructor(e,t,n,r=!1){this.http=e,this.signatureAuth=t,this.jwtAuth=n,this.refreshPromise=null,this.loginPromise=null,this.logger=new un({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 yo(mo.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 vo(async()=>{const e=Date.now(),t=`${go.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 i={address:r,message:t,signature:n.signature};let s;try{this.logger.debug("Sending login request with refresh token support",{address:r,message:t}),s=await this.http.post(Y,{...i,includeRefreshToken:!0})}catch(e){if(400!==e.statusCode)throw e;this.logger.debug("Login returned 400, retrying without includeRefreshToken (backend may not support it)"),s=await this.http.post(Y,i)}const o=this.extractLoginData(s);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 yo)throw e;throw new yo(mo.SIGNATURE_FAILED,`Login failed: ${bt(e)}`,yt(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 yo(mo.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 vo(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(Z,{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(Z,{},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 yo)throw e;throw new yo(mo.SIGNATURE_FAILED,`Token refresh failed: ${bt(e)}`,yt(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(Q,{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): ${bt(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 yo(mo.WALLET_NOT_CONNECTED,"Not authenticated. Call login() first.");return vo(async()=>{const e=await this.http.get(ee,void 0,this.jwtAuth.getJwtHeaders());return this.extractSessionData(e)},"SessionAuthService.getSession",this.logger,e=>{if(e instanceof yo)throw e;throw new yo(mo.SIGNATURE_FAILED,`Failed to get session: ${bt(e)}`,yt(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 yo(mo.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: ${bt(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 yo(mo.SIGNATURE_FAILED,""!==bt(e)?bt(e):"Authentication failed");const t=Zt(e,"No data in authentication response"),{accessToken:n,expiresIn:r,address:i,refreshToken:s,refreshExpiresIn:o}=t;if(!nr(n))throw new yo(mo.SIGNATURE_FAILED,"Invalid access token in response");if("number"!=typeof r||r<=0)throw new yo(mo.SIGNATURE_FAILED,"Invalid expiration in response");return{accessToken:n,expiresIn:r,address:i,...void 0!==s&&{refreshToken:s},...void 0!==o&&{refreshExpiresIn:o}}}extractSessionData(e){if(e.error)throw new yo(mo.SIGNATURE_FAILED,""!==bt(e)?bt(e):"Failed to get session");return Zt(e,"No data in session response")}}class Ao 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"}(po||(po={}));class ko{constructor(e){this.providerType="privateKey",this.connected=!0;try{this.wallet=new t(e)}catch(e){throw new Ao("Invalid private key provided",po.INVALID_CONFIG,e instanceof Error?e:void 0)}}static fromWallet(e){return new ko(e.privateKey)}async signMessage(e){try{return await this.wallet.signMessage(e)}catch(e){throw new Ao("Failed to sign message",po.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 Ao("Failed to sign typed data",po.SIGNING_FAILED,e instanceof Error?e:void 0)}}getAddress(){return Promise.resolve(e(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 So{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{Xn(e.messagePrefix,"messagePrefix",!1)}catch{throw new yo(mo.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=ko.fromWallet(this.wallet),this.cachedAddress=this.wallet.address,this.cachedGalaAddress=xr(this.wallet.address)}catch(e){if(e instanceof yo)throw e;if(e instanceof Ct&&("INVALID_ADDRESS"===e.code||"INVALID_FORMAT"===e.code||"address"===e.field))throw new yo(mo.INVALID_ADDRESS,e.message);if(null!==e&&"object"==typeof e&&"message"in e)throw new yo(mo.WALLET_NOT_CONNECTED,e.message);throw e}}setWallet(e){if(void 0!==e){if("object"!=typeof e||!("address"in e))throw new yo(mo.WALLET_NOT_CONNECTED,"Invalid wallet: must be an ethers Wallet instance or undefined");if("string"!=typeof e.address||""===e.address)throw new yo(mo.INVALID_ADDRESS,"Wallet address is not available");this.walletProvider=ko.fromWallet(e),this.cachedAddress=e.address,this.cachedGalaAddress=xr(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 yo)throw e;throw new yo(mo.SIGNATURE_FAILED,"Failed to generate signature for authentication",yt(e)?e:new Error(bt(e)))}}getAddress(){if(this.validateWallet(),this.cachedGalaAddress)return this.cachedGalaAddress;if(this.wallet)return this.formatAddress(this.wallet.address);throw new yo(mo.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 yo(mo.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 yo(mo.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 yo(mo.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 yo(mo.WALLET_NOT_CONNECTED,"Private key not available with this wallet provider");try{return await this.walletProvider.getPrivateKey()}catch(e){throw new yo(mo.WALLET_NOT_CONNECTED,"Private key not available. External wallet providers cannot access private keys. Use PrivateKeyProvider for @gala-chain signing operations.",yt(e)?e:void 0)}}formatAddress(e){try{return xr(e)}catch{throw new yo(mo.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 yo)throw e;throw new yo(mo.SIGNATURE_FAILED,bt(e),yt(e)?e:new Error(bt(e)))}}async generateAuthHeaders(e,t){await this.validateWalletAsync();try{const n=Date.now(),r=`${this.messagePrefix} ${t.toUpperCase()} ${e} ${n}`,i=await this.walletProvider.signMessage(r);return{"x-signature":i,"x-address":await this.walletProvider.getGalaAddress(),"x-message":r,"x-timestamp":n.toString()}}catch(e){if(e instanceof yo)throw e;throw new yo(mo.SIGNATURE_FAILED,"Failed to generate authentication headers",yt(e)?e:new Error(bt(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 yo)throw e;throw new yo(mo.SIGNATURE_FAILED,"Failed to sign typed data",yt(e)?e:new Error(bt(e)))}}async generateCustomSignature(e){if(!nr(e))throw new yo(mo.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 yo)throw e;throw new yo(mo.SIGNATURE_FAILED,"Failed to generate custom message signature",yt(e)?e:new Error(bt(e)))}}validateWallet(){if(this.ensureWalletProvider(),!this.walletProvider)throw new yo(mo.WALLET_NOT_CONNECTED,"Wallet is required for authentication")}async validateWalletAsync(){if(this.ensureWalletProvider(),!this.walletProvider)throw new yo(mo.WALLET_NOT_CONNECTED,"Wallet is required for authentication");if(!this.walletProvider.isConnected())throw new yo(mo.WALLET_NOT_CONNECTED,"Wallet is not connected. Call connect() on the wallet provider first.")}}const To={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 Io(e){return To[e]}function No(e){return`${e.collection}|${e.category}|${e.type}|${e.additionalKey}`}function Co(e){return`${e.collection}$${e.category}$${e.type}$${e.additionalKey}`}const _o={GALA_CHAIN:1,ETHEREUM:2,SOLANA:1002},xo={ASSET:1,MUSIC:3};function Ro(e){return Object.values(xo).includes(e)}const Bo=12,Do=15e3,Mo=27e5,Oo={UNIT_LIMIT:2e5,UNIT_PRICE_MICROLAMPORTS:375e3},Uo="https://ethereum.publicnode.com",Lo="https://api.mainnet-beta.solana.com",Po="0x9f452b7cC24e6e6FA690fe77CF5dD2ba3DbF1ED9",Fo="0x6a1734E09f3099a3675645D214ce547080ea67e0",$o="AaE4dTnL75XqgUJpdxBKg6vS9sTJgBPJwBQRVhD29WwS",Ko="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}],Ho=[{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 Wo(e){return"prod"===e?Go:Ho}function qo(e){return"prod"===e?Po:Fo}const jo=Go,Vo=[{symbol:"GALA",amount:"1",mintAddress:"eEUiUs4JWYZrp72djAGF1A8PhpR6rHphGeGN7GbVLp6",isNative:!1,decimals:8},{symbol:"GSOL",amount:"0.001",mintAddress:"So11111111111111111111111111111111111111111",isNative:!0,decimals:9}],zo={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"}},Xo=["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)"],Jo=["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"],Yo={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 Qo(e){const t=cn(e),n=zo[t];if(void 0!==n)return n;if(!t.startsWith("G")){const e=zo[`G${t}`];if(void 0!==e)return e}}function Zo(e){const t=cn(e);return jo.find(e=>cn(e.symbol)===t||cn(e.symbol)===`G${t}`)}function ea(e){const t=cn(e);return Vo.find(e=>cn(e.symbol)===t||cn(e.symbol)===`G${t}`)}function ta(e){return No(e)}function na(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function ra(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 ia,sa={},oa={};function aa(){if(ia)return oa;ia=1,oa.byteLength=function(e){var t=s(e),n=t[0],r=t[1];return 3*(n+r)/4-r},oa.toByteArray=function(e){var r,i,o=s(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(i=0;i<d;i+=4)r=t[e.charCodeAt(i)]<<18|t[e.charCodeAt(i+1)]<<12|t[e.charCodeAt(i+2)]<<6|t[e.charCodeAt(i+3)],l[u++]=r>>16&255,l[u++]=r>>8&255,l[u++]=255&r;2===c&&(r=t[e.charCodeAt(i)]<<2|t[e.charCodeAt(i+1)]>>4,l[u++]=255&r);1===c&&(r=t[e.charCodeAt(i)]<<10|t[e.charCodeAt(i+1)]<<4|t[e.charCodeAt(i+2)]>>2,l[u++]=r>>8&255,l[u++]=255&r);return l},oa.fromByteArray=function(t){for(var n,r=t.length,i=r%3,s=[],o=16383,c=0,l=r-i;c<l;c+=o)s.push(a(t,c,c+o>l?l:c+o));1===i?(n=t[r-1],s.push(e[n>>2]+e[n<<4&63]+"==")):2===i&&(n=(t[r-2]<<8)+t[r-1],s.push(e[n>>10]+e[n>>4&63]+e[n<<2&63]+"="));return s.join("")};for(var e=[],t=[],n="undefined"!=typeof Uint8Array?Uint8Array:Array,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=0;i<64;++i)e[i]=r[i],t[r.charCodeAt(i)]=i;function s(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,i=[],s=t;s<n;s+=3)r=(e[s]<<16&16711680)+(e[s+1]<<8&65280)+(255&e[s+2]),i.push(o(r));return i.join("")}return t["-".charCodeAt(0)]=62,t["_".charCodeAt(0)]=63,oa}var ca,la,ua={};function da(){return ca||(ca=1,ua.read=function(e,t,n,r,i){var s,o,a=8*i-r-1,c=(1<<a)-1,l=c>>1,u=-7,d=n?i-1:0,h=n?-1:1,g=e[t+d];for(d+=h,s=g&(1<<-u)-1,g>>=-u,u+=a;u>0;s=256*s+e[t+d],d+=h,u-=8);for(o=s&(1<<-u)-1,s>>=-u,u+=r;u>0;o=256*o+e[t+d],d+=h,u-=8);if(0===s)s=1-l;else{if(s===c)return o?NaN:1/0*(g?-1:1);o+=Math.pow(2,r),s-=l}return(g?-1:1)*o*Math.pow(2,s-r)},ua.write=function(e,t,n,r,i,s){var o,a,c,l=8*s-i-1,u=(1<<l)-1,d=u>>1,h=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,g=r?0:s-1,f=r?1:-1,m=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,i),o+=d):(a=t*Math.pow(2,d-1)*Math.pow(2,i),o=0));i>=8;e[n+g]=255&a,g+=f,a/=256,i-=8);for(o=o<<i|a,l+=i;l>0;e[n+g]=255&o,g+=f,o/=256,l-=8);e[n+g-f]|=128*m}),ua}function ha(){return la||(la=1,function(e){const t=aa(),n=da(),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 i=2147483647;function s(e){if(e>i)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=s(n);const i=r.write(e,t);i!==n&&(r=r.slice(0,i));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 i=function(e){if(o.isBuffer(e)){const t=0|h(e.length),n=s(t);return 0===n.length||e.copy(n,0,0,t),n}if(void 0!==e.length)return"number"!=typeof e.length||z(e.length)?s(0):u(e);if("Buffer"===e.type&&Array.isArray(e.data))return u(e.data)}(e);if(i)return i;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),s(e<0?0:0|h(e))}function u(e){const t=e.length<0?0:0|h(e.length),n=s(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>=i)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i.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 i=!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(i)return r?-1:W(e).length;t=(""+t).toLowerCase(),i=!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 S(this,t,n);case"ascii":return I(this,t,n);case"latin1":case"binary":return N(this,t,n);case"base64":return k(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 m(e,t,n){const r=e[t];e[t]=e[n],e[n]=r}function p(e,t,n,r,i){if(0===e.length)return-1;if("string"==typeof n?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),z(n=+n)&&(n=i?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(i)return-1;n=e.length-1}else if(n<0){if(!i)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,i);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):y(e,[t],n,r,i);throw new TypeError("val must be string, number or Buffer")}function y(e,t,n,r,i){let s,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(i){let r=-1;for(s=n;s<a;s++)if(l(e,s)===l(t,-1===r?0:s-r)){if(-1===r&&(r=s),s-r+1===c)return r*o}else-1!==r&&(s-=s-r),r=-1}else for(n+c>a&&(n=a-c),s=n;s>=0;s--){let n=!0;for(let r=0;r<c;r++)if(l(e,s+r)!==l(t,r)){n=!1;break}if(n)return s}return-1}function b(e,t,n,r){n=Number(n)||0;const i=e.length-n;r?(r=Number(r))>i&&(r=i):r=i;const s=t.length;let o;for(r>s/2&&(r=s/2),o=0;o<r;++o){const r=parseInt(t.substr(2*o,2),16);if(z(r))return o;e[n+o]=r}return o}function v(e,t,n,r){return j(W(t,e.length-n),e,n,r)}function w(e,t,n,r){return j(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 j(q(t),e,n,r)}function A(e,t,n,r){return j(function(e,t){let n,r,i;const s=[];for(let o=0;o<e.length&&!((t-=2)<0);++o)n=e.charCodeAt(o),r=n>>8,i=n%256,s.push(i),s.push(r);return s}(t,e.length-n),e,n,r)}function k(e,n,r){return 0===n&&r===e.length?t.fromByteArray(e):t.fromByteArray(e.slice(n,r))}function S(e,t,n){n=Math.min(e.length,n);const r=[];let i=t;for(;i<n;){const t=e[i];let s=null,o=t>239?4:t>223?3:t>191?2:1;if(i+o<=n){let n,r,a,c;switch(o){case 1:t<128&&(s=t);break;case 2:n=e[i+1],128==(192&n)&&(c=(31&t)<<6|63&n,c>127&&(s=c));break;case 3:n=e[i+1],r=e[i+2],128==(192&n)&&128==(192&r)&&(c=(15&t)<<12|(63&n)<<6|63&r,c>2047&&(c<55296||c>57343)&&(s=c));break;case 4:n=e[i+1],r=e[i+2],a=e[i+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&&(s=c))}}null===s?(s=65533,o=1):s>65535&&(s-=65536,r.push(s>>>10&1023|55296),s=56320|1023&s),r.push(s),i+=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=i,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?s(e):void 0!==t?"string"==typeof n?s(e).fill(t,n):s(e).fill(t):s(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 i=0,s=Math.min(n,r);i<s;++i)if(e[i]!==t[i]){n=e[i],r=t[i];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 i=0;for(n=0;n<e.length;++n){let t=e[n];if(V(t,Uint8Array))i+t.length>r.length?(o.isBuffer(t)||(t=o.from(t)),t.copy(r,i)):Uint8Array.prototype.set.call(r,t,i);else{if(!o.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(r,i)}i+=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)m(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)m(this,t,t+3),m(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)m(this,t,t+7),m(this,t+1,t+6),m(this,t+2,t+5),m(this,t+3,t+4);return this},o.prototype.toString=function(){const e=this.length;return 0===e?"":0===arguments.length?S(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,i){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===i&&(i=this.length),t<0||n>e.length||r<0||i>this.length)throw new RangeError("out of range index");if(r>=i&&t>=n)return 0;if(r>=i)return-1;if(t>=n)return 1;if(this===e)return 0;let s=(i>>>=0)-(r>>>=0),a=(n>>>=0)-(t>>>=0);const c=Math.min(s,a),l=this.slice(r,i),u=e.slice(t,n);for(let e=0;e<c;++e)if(l[e]!==u[e]){s=l[e],a=u[e];break}return s<a?-1:a<s?1:0},o.prototype.includes=function(e,t,n){return-1!==this.indexOf(e,t,n)},o.prototype.indexOf=function(e,t,n){return p(this,e,t,n,!0)},o.prototype.lastIndexOf=function(e,t,n){return p(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 i=this.length-t;if((void 0===n||n>i)&&(n=i),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");let s=!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(s)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),s=!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 i=t;i<n;++i)r+=String.fromCharCode(127&e[i]);return r}function N(e,t,n){let r="";n=Math.min(e.length,n);for(let i=t;i<n;++i)r+=String.fromCharCode(e[i]);return r}function C(e,t,n){const r=e.length;(!t||t<0)&&(t=0),(!n||n<0||n>r)&&(n=r);let i="";for(let r=t;r<n;++r)i+=X[e[r]];return i}function _(e,t,n){const r=e.slice(t,n);let i="";for(let e=0;e<r.length-1;e+=2)i+=String.fromCharCode(r[e]+256*r[e+1]);return i}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,i,s){if(!o.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||t<s)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,i){$(t,r,i,e,n,7);let s=Number(t&BigInt(4294967295));e[n++]=s,s>>=8,e[n++]=s,s>>=8,e[n++]=s,s>>=8,e[n++]=s;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,i){$(t,r,i,e,n,7);let s=Number(t&BigInt(4294967295));e[n+7]=s,s>>=8,e[n+6]=s,s>>=8,e[n+5]=s,s>>=8,e[n+4]=s;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 M(e,t,n,r,i,s){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function O(e,t,r,i,s){return t=+t,r>>>=0,s||M(e,0,r,4),n.write(e,t,r,i,23,4),r+4}function U(e,t,r,i,s){return t=+t,r>>>=0,s||M(e,0,r,8),n.write(e,t,r,i,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],i=1,s=0;for(;++s<t&&(i*=256);)r+=this[e+s]*i;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],i=1;for(;t>0&&(i*=256);)r+=this[e+--t]*i;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=J(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,i=this[++e]+256*this[++e]+65536*this[++e]+n*2**24;return BigInt(r)+(BigInt(i)<<BigInt(32))}),o.prototype.readBigUInt64BE=J(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],i=this[++e]*2**24+65536*this[++e]+256*this[++e]+n;return(BigInt(r)<<BigInt(32))+BigInt(i)}),o.prototype.readIntLE=function(e,t,n){e>>>=0,t>>>=0,n||x(e,t,this.length);let r=this[e],i=1,s=0;for(;++s<t&&(i*=256);)r+=this[e+s]*i;return i*=128,r>=i&&(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,i=1,s=this[e+--r];for(;r>0&&(i*=256);)s+=this[e+--r]*i;return i*=128,s>=i&&(s-=Math.pow(2,8*t)),s},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=J(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=J(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 i=1,s=0;for(this[t]=255&e;++s<n&&(i*=256);)this[t+s]=e/i&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 i=n-1,s=1;for(this[t+i]=255&e;--i>=0&&(s*=256);)this[t+i]=e/s&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=J(function(e,t=0){return B(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),o.prototype.writeBigUInt64BE=J(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 i=0,s=1,o=0;for(this[t]=255&e;++i<n&&(s*=256);)e<0&&0===o&&0!==this[t+i-1]&&(o=1),this[t+i]=(e/s|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 i=n-1,s=1,o=0;for(this[t+i]=255&e;--i>=0&&(s*=256);)e<0&&0===o&&0!==this[t+i+1]&&(o=1),this[t+i]=(e/s|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=J(function(e,t=0){return B(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),o.prototype.writeBigInt64BE=J(function(e,t=0){return D(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),o.prototype.writeFloatLE=function(e,t,n){return O(this,e,t,!0,n)},o.prototype.writeFloatBE=function(e,t,n){return O(this,e,t,!1,n)},o.prototype.writeDoubleLE=function(e,t,n){return U(this,e,t,!0,n)},o.prototype.writeDoubleBE=function(e,t,n){return U(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 i=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),i},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 i;if(t>>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(i=t;i<n;++i)this[i]=e;else{const s=o.isBuffer(e)?e:o.from(e,r),a=s.length;if(0===a)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(i=0;i<n-t;++i)this[i+t]=s[i%a]}return this};const L={};function P(e,t,n){L[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,i,s){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*(s+1)}${n}`:`>= -(2${n} ** ${8*(s+1)-1}${n}) and < 2 ** ${8*(s+1)-1}${n}`,new L.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,i,s)}function K(e,t){if("number"!=typeof e)throw new L.ERR_INVALID_ARG_TYPE(t,"number",e)}function G(e,t,n){if(Math.floor(e)!==e)throw K(e,n),new L.ERR_OUT_OF_RANGE("offset","an integer",e);if(t<0)throw new L.ERR_BUFFER_OUT_OF_BOUNDS;throw new L.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.`,i=n;return Number.isInteger(n)&&Math.abs(n)>2**32?i=F(String(n)):"bigint"==typeof n&&(i=String(n),(n>BigInt(2)**BigInt(32)||n<-(BigInt(2)**BigInt(32)))&&(i=F(i)),i+="n"),r+=` It must be ${t}. Received ${i}`,r},RangeError);const H=/[^+/0-9A-Za-z-_]/g;function W(e,t){let n;t=t||1/0;const r=e.length;let i=null;const s=[];for(let o=0;o<r;++o){if(n=e.charCodeAt(o),n>55295&&n<57344){if(!i){if(n>56319){(t-=3)>-1&&s.push(239,191,189);continue}if(o+1===r){(t-=3)>-1&&s.push(239,191,189);continue}i=n;continue}if(n<56320){(t-=3)>-1&&s.push(239,191,189),i=n;continue}n=65536+(i-55296<<10|n-56320)}else i&&(t-=3)>-1&&s.push(239,191,189);if(i=null,n<128){if((t-=1)<0)break;s.push(n)}else if(n<2048){if((t-=2)<0)break;s.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;s.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;s.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return s}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 j(e,t,n,r){let i;for(i=0;i<r&&!(i+n>=t.length||i>=e.length);++i)t[i+n]=e[i];return i}function V(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function z(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 i=0;i<16;++i)t[r+i]=e[n]+e[i]}return t}();function J(e){return"undefined"==typeof BigInt?Y:e}function Y(){throw new Error("BigInt not supported")}}(sa)),sa}var ga=ha();const fa="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0;function ma(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function pa(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function ya(e,...t){if(!ma(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 ba(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.createHasher");pa(e.outputLen),pa(e.blockLen)}function va(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 wa(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Ea(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Aa(e,t){return e<<32-t|e>>>t}const ka=(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)(),Sa=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Ta(e){if(ya(e),ka)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=Sa[e[n]];return t}const Ia=48,Na=57,Ca=65,_a=70,xa=97,Ra=102;function Ba(e){return e>=Ia&&e<=Na?e-Ia:e>=Ca&&e<=_a?e-(Ca-10):e>=xa&&e<=Ra?e-(xa-10):void 0}function Da(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);if(ka)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,i=0;t<n;t++,i+=2){const n=Ba(e.charCodeAt(i)),s=Ba(e.charCodeAt(i+1));if(void 0===n||void 0===s){const t=e[i]+e[i+1];throw new Error('hex string expected, got non-hex character "'+t+'" at index '+i)}r[t]=16*n+s}return r}function Ma(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)),ya(e),e}function Oa(...e){let t=0;for(let n=0;n<e.length;n++){const r=e[n];ya(r),t+=r.length}const n=new Uint8Array(t);for(let t=0,r=0;t<e.length;t++){const i=e[t];n.set(i,r),r+=i.length}return n}class Ua{}function La(e){const t=t=>e().update(Ma(t)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function Pa(e=32){if(fa&&"function"==typeof fa.getRandomValues)return fa.getRandomValues(new Uint8Array(e));if(fa&&"function"==typeof fa.randomBytes)return Uint8Array.from(fa.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}function Fa(e,t,n){return e&t^~e&n}function $a(e,t,n){return e&t^e&n^t&n}class Ka extends Ua{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=Ea(this.buffer)}update(e){va(this),ya(e=Ma(e));const{view:t,buffer:n,blockLen:r}=this,i=e.length;for(let s=0;s<i;){const o=Math.min(r-this.pos,i-s);if(o===r){const t=Ea(e);for(;r<=i-s;s+=r)this.process(t,s);continue}n.set(e.subarray(s,s+o),this.pos),this.pos+=o,s+=o,this.pos===r&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){va(this),function(e,t){ya(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:i}=this;let{pos:s}=this;t[s++]=128,wa(this.buffer.subarray(s)),this.padOffset>r-s&&(this.process(n,0),s=0);for(let e=s;e<r;e++)t[e]=0;!function(e,t,n,r){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,n,r);const i=BigInt(32),s=BigInt(4294967295),o=Number(n>>i&s),a=Number(n&s),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),i),this.process(n,0);const o=Ea(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],i)}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:i,destroyed:s,pos:o}=this;return e.destroyed=s,e.finished=i,e.length=r,e.pos=o,r%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}}const Ga=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ha=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Wa=BigInt(2**32-1),qa=BigInt(32);function ja(e,t=!1){return t?{h:Number(e&Wa),l:Number(e>>qa&Wa)}:{h:0|Number(e>>qa&Wa),l:0|Number(e&Wa)}}const Va=(e,t,n)=>e>>>n,za=(e,t,n)=>e<<32-n|t>>>n,Xa=(e,t,n)=>e>>>n|t<<32-n,Ja=(e,t,n)=>e<<32-n|t>>>n,Ya=(e,t,n)=>e<<64-n|t>>>n-32,Qa=(e,t,n)=>e>>>n-32|t<<64-n;function Za(e,t,n,r){const i=(t>>>0)+(r>>>0);return{h:e+n+(i/2**32|0)|0,l:0|i}}const ec=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),tc=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,nc=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),rc=(e,t,n,r,i)=>t+n+r+i+(e/2**32|0)|0,ic=(e,t,n,r,i)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(i>>>0),sc=(e,t,n,r,i,s)=>t+n+r+i+s+(e/2**32|0)|0,oc=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]),ac=new Uint32Array(64);class cc extends Ka{constructor(e=32){super(64,e,8,!1),this.A=0|Ga[0],this.B=0|Ga[1],this.C=0|Ga[2],this.D=0|Ga[3],this.E=0|Ga[4],this.F=0|Ga[5],this.G=0|Ga[6],this.H=0|Ga[7]}get(){const{A:e,B:t,C:n,D:r,E:i,F:s,G:o,H:a}=this;return[e,t,n,r,i,s,o,a]}set(e,t,n,r,i,s,o,a){this.A=0|e,this.B=0|t,this.C=0|n,this.D=0|r,this.E=0|i,this.F=0|s,this.G=0|o,this.H=0|a}process(e,t){for(let n=0;n<16;n++,t+=4)ac[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){const t=ac[e-15],n=ac[e-2],r=Aa(t,7)^Aa(t,18)^t>>>3,i=Aa(n,17)^Aa(n,19)^n>>>10;ac[e]=i+ac[e-7]+r+ac[e-16]|0}let{A:n,B:r,C:i,D:s,E:o,F:a,G:c,H:l}=this;for(let e=0;e<64;e++){const t=l+(Aa(o,6)^Aa(o,11)^Aa(o,25))+Fa(o,a,c)+oc[e]+ac[e]|0,u=(Aa(n,2)^Aa(n,13)^Aa(n,22))+$a(n,r,i)|0;l=c,c=a,a=o,o=s+t|0,s=i,i=r,r=n,n=t+u|0}n=n+this.A|0,r=r+this.B|0,i=i+this.C|0,s=s+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,i,s,o,a,c,l)}roundClean(){wa(ac)}destroy(){this.set(0,0,0,0,0,0,0,0),wa(this.buffer)}}const lc=(()=>function(e,t=!1){const n=e.length;let r=new Uint32Array(n),i=new Uint32Array(n);for(let s=0;s<n;s++){const{h:n,l:o}=ja(e[s],t);[r[s],i[s]]=[n,o]}return[r,i]}(["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))))(),uc=(()=>lc[0])(),dc=(()=>lc[1])(),hc=new Uint32Array(80),gc=new Uint32Array(80);class fc extends Ka{constructor(e=64){super(128,e,16,!1),this.Ah=0|Ha[0],this.Al=0|Ha[1],this.Bh=0|Ha[2],this.Bl=0|Ha[3],this.Ch=0|Ha[4],this.Cl=0|Ha[5],this.Dh=0|Ha[6],this.Dl=0|Ha[7],this.Eh=0|Ha[8],this.El=0|Ha[9],this.Fh=0|Ha[10],this.Fl=0|Ha[11],this.Gh=0|Ha[12],this.Gl=0|Ha[13],this.Hh=0|Ha[14],this.Hl=0|Ha[15]}get(){const{Ah:e,Al:t,Bh:n,Bl:r,Ch:i,Cl:s,Dh:o,Dl:a,Eh:c,El:l,Fh:u,Fl:d,Gh:h,Gl:g,Hh:f,Hl:m}=this;return[e,t,n,r,i,s,o,a,c,l,u,d,h,g,f,m]}set(e,t,n,r,i,s,o,a,c,l,u,d,h,g,f,m){this.Ah=0|e,this.Al=0|t,this.Bh=0|n,this.Bl=0|r,this.Ch=0|i,this.Cl=0|s,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|m}process(e,t){for(let n=0;n<16;n++,t+=4)hc[n]=e.getUint32(t),gc[n]=e.getUint32(t+=4);for(let e=16;e<80;e++){const t=0|hc[e-15],n=0|gc[e-15],r=Xa(t,n,1)^Xa(t,n,8)^Va(t,0,7),i=Ja(t,n,1)^Ja(t,n,8)^za(t,n,7),s=0|hc[e-2],o=0|gc[e-2],a=Xa(s,o,19)^Ya(s,o,61)^Va(s,0,6),c=Ja(s,o,19)^Qa(s,o,61)^za(s,o,6),l=nc(i,c,gc[e-7],gc[e-16]),u=rc(l,r,a,hc[e-7],hc[e-16]);hc[e]=0|u,gc[e]=0|l}let{Ah:n,Al:r,Bh:i,Bl:s,Ch:o,Cl:a,Dh:c,Dl:l,Eh:u,El:d,Fh:h,Fl:g,Gh:f,Gl:m,Hh:p,Hl:y}=this;for(let e=0;e<80;e++){const t=Xa(u,d,14)^Xa(u,d,18)^Ya(u,d,41),b=Ja(u,d,14)^Ja(u,d,18)^Qa(u,d,41),v=u&h^~u&f,w=ic(y,b,d&g^~d&m,dc[e],gc[e]),E=sc(w,p,t,v,uc[e],hc[e]),A=0|w,k=Xa(n,r,28)^Ya(n,r,34)^Ya(n,r,39),S=Ja(n,r,28)^Qa(n,r,34)^Qa(n,r,39),T=n&i^n&o^i&o,I=r&s^r&a^s&a;p=0|f,y=0|m,f=0|h,m=0|g,h=0|u,g=0|d,({h:u,l:d}=Za(0|c,0|l,0|E,0|A)),c=0|o,l=0|a,o=0|i,a=0|s,i=0|n,s=0|r;const N=ec(A,S,I);n=tc(N,E,k,T),r=0|N}({h:n,l:r}=Za(0|this.Ah,0|this.Al,0|n,0|r)),({h:i,l:s}=Za(0|this.Bh,0|this.Bl,0|i,0|s)),({h:o,l:a}=Za(0|this.Ch,0|this.Cl,0|o,0|a)),({h:c,l:l}=Za(0|this.Dh,0|this.Dl,0|c,0|l)),({h:u,l:d}=Za(0|this.Eh,0|this.El,0|u,0|d)),({h:h,l:g}=Za(0|this.Fh,0|this.Fl,0|h,0|g)),({h:f,l:m}=Za(0|this.Gh,0|this.Gl,0|f,0|m)),({h:p,l:y}=Za(0|this.Hh,0|this.Hl,0|p,0|y)),this.set(n,r,i,s,o,a,c,l,u,d,h,g,f,m,p,y)}roundClean(){wa(hc,gc)}destroy(){wa(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const mc=La(()=>new cc),pc=La(()=>new fc),yc=BigInt(0),bc=BigInt(1);function vc(e,t=""){if("boolean"!=typeof e){throw new Error((t&&`"${t}"`)+"expected boolean, got type="+typeof e)}return e}function wc(e,t,n=""){const r=ma(e),i=e?.length,s=void 0!==t;if(!r||s&&i!==t){throw new Error((n&&`"${n}" `)+"expected Uint8Array"+(s?` of length ${t}`:"")+", got "+(r?`length=${i}`:"type="+typeof e))}return e}function Ec(e){const t=e.toString(16);return 1&t.length?"0"+t:t}function Ac(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);return""===e?yc:BigInt("0x"+e)}function kc(e){return Ac(Ta(e))}function Sc(e){return ya(e),Ac(Ta(Uint8Array.from(e).reverse()))}function Tc(e,t){return Da(e.toString(16).padStart(2*t,"0"))}function Ic(e,t){return Tc(e,t).reverse()}function Nc(e,t,n){let r;if("string"==typeof t)try{r=Da(t)}catch(t){throw new Error(e+" must be hex string or Uint8Array, cause: "+t)}else{if(!ma(t))throw new Error(e+" must be hex string or Uint8Array");r=Uint8Array.from(t)}const i=r.length;if("number"==typeof n&&i!==n)throw new Error(e+" of length "+n+" expected, got "+i);return r}function Cc(e){return Uint8Array.from(e)}const _c=e=>"bigint"==typeof e&&yc<=e;function xc(e,t,n,r){if(!function(e,t,n){return _c(e)&&_c(t)&&_c(n)&&t<=e&&e<n}(t,n,r))throw new Error("expected valid "+e+": "+n+" <= n < "+r+", got "+t)}function Rc(e){let t;for(t=0;e>yc;e>>=bc,t+=1);return t}const Bc=e=>(bc<<BigInt(e))-bc;function Dc(e,t,n={}){if(!e||"object"!=typeof e)throw new Error("expected valid options object");function r(t,n,r){const i=e[t];if(r&&void 0===i)return;const s=typeof i;if(s!==n||null===i)throw new Error(`param "${t}" is invalid: expected ${n}, got ${s}`)}Object.entries(t).forEach(([e,t])=>r(e,t,!1)),Object.entries(n).forEach(([e,t])=>r(e,t,!0))}function Mc(e){const t=new WeakMap;return(n,...r)=>{const i=t.get(n);if(void 0!==i)return i;const s=e(n,...r);return t.set(n,s),s}}const Oc=BigInt(0),Uc=BigInt(1),Lc=BigInt(2),Pc=BigInt(3),Fc=BigInt(4),$c=BigInt(5),Kc=BigInt(7),Gc=BigInt(8),Hc=BigInt(9),Wc=BigInt(16);function qc(e,t){const n=e%t;return n>=Oc?n:t+n}function jc(e,t,n){let r=e;for(;t-- >Oc;)r*=r,r%=n;return r}function Vc(e,t){if(e===Oc)throw new Error("invert: expected non-zero number");if(t<=Oc)throw new Error("invert: expected positive modulus, got "+t);let n=qc(e,t),r=t,i=Oc,s=Uc;for(;n!==Oc;){const e=r%n,t=i-s*(r/n);r=n,n=e,i=s,s=t}if(r!==Uc)throw new Error("invert: does not exist");return qc(i,t)}function zc(e,t,n){if(!e.eql(e.sqr(t),n))throw new Error("Cannot find square root")}function Xc(e,t){const n=(e.ORDER+Uc)/Fc,r=e.pow(t,n);return zc(e,r,t),r}function Jc(e,t){const n=(e.ORDER-$c)/Gc,r=e.mul(t,Lc),i=e.pow(r,n),s=e.mul(t,i),o=e.mul(e.mul(s,Lc),i),a=e.mul(s,e.sub(o,e.ONE));return zc(e,a,t),a}function Yc(e){if(e<Pc)throw new Error("sqrt is not defined for small field");let t=e-Uc,n=0;for(;t%Lc===Oc;)t/=Lc,n++;let r=Lc;const i=rl(e);for(;1===tl(i,r);)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(1===n)return Xc;let s=i.pow(r,t);const o=(t+Uc)/Lc;return function(e,r){if(e.is0(r))return r;if(1!==tl(e,r))throw new Error("Cannot find square root");let i=n,a=e.mul(e.ONE,s),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===i)throw new Error("Cannot find square root");const r=Uc<<BigInt(i-t-1),s=e.pow(a,r);i=t,a=e.sqr(s),c=e.mul(c,a),l=e.mul(l,s)}return l}}function Qc(e){return e%Fc===Pc?Xc:e%Gc===$c?Jc:e%Wc===Hc?function(e){const t=rl(e),n=Yc(e),r=n(t,t.neg(t.ONE)),i=n(t,r),s=n(t,t.neg(r)),o=(e+Kc)/Wc;return(e,t)=>{let n=e.pow(t,o),a=e.mul(n,r);const c=e.mul(n,i),l=e.mul(n,s),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 zc(e,g,t),g}}(e):Yc(e)}const Zc=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function el(e,t,n=!1){const r=new Array(t.length).fill(n?e.ZERO:void 0),i=t.reduce((t,n,i)=>e.is0(n)?t:(r[i]=t,e.mul(t,n)),e.ONE),s=e.inv(i);return t.reduceRight((t,n,i)=>e.is0(n)?t:(r[i]=e.mul(t,r[i]),e.mul(t,n)),s),r}function tl(e,t){const n=(e.ORDER-Uc)/Lc,r=e.pow(t,n),i=e.eql(r,e.ONE),s=e.eql(r,e.ZERO),o=e.eql(r,e.neg(e.ONE));if(!i&&!s&&!o)throw new Error("invalid Legendre symbol result");return i?1:s?0:-1}function nl(e,t){void 0!==t&&pa(t);const n=void 0!==t?t:e.toString(2).length;return{nBitLength:n,nByteLength:Math.ceil(n/8)}}function rl(e,t,n=!1,r={}){if(e<=Oc)throw new Error("invalid field: expected ORDER > 0, got "+e);let i,s,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&&(i=e.BITS),e.sqrt&&(s=e.sqrt),"boolean"==typeof e.isLE&&(n=e.isLE),"boolean"==typeof e.modFromBytes&&(a=e.modFromBytes),o=e.allowedLengths}else"number"==typeof t&&(i=t),r.sqrt&&(s=r.sqrt);const{nBitLength:c,nByteLength:l}=nl(e,i);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:Bc(c),ZERO:Oc,ONE:Uc,allowedLengths:o,create:t=>qc(t,e),isValid:t=>{if("bigint"!=typeof t)throw new Error("invalid field element: expected bigint, got "+typeof t);return Oc<=t&&t<e},is0:e=>e===Oc,isValidNot0:e=>!d.is0(e)&&d.isValid(e),isOdd:e=>(e&Uc)===Uc,neg:t=>qc(-t,e),eql:(e,t)=>e===t,sqr:t=>qc(t*t,e),add:(t,n)=>qc(t+n,e),sub:(t,n)=>qc(t-n,e),mul:(t,n)=>qc(t*n,e),pow:(e,t)=>function(e,t,n){if(n<Oc)throw new Error("invalid exponent, negatives unsupported");if(n===Oc)return e.ONE;if(n===Uc)return t;let r=e.ONE,i=t;for(;n>Oc;)n&Uc&&(r=e.mul(r,i)),i=e.sqr(i),n>>=Uc;return r}(d,e,t),div:(t,n)=>qc(t*Vc(n,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>Vc(t,e),sqrt:s||(t=>(u||(u=Qc(e)),u(d,t))),toBytes:e=>n?Ic(e,l):Tc(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 i=n?Sc(t):kc(t);if(a&&(i=qc(i,e)),!r&&!d.isValid(i))throw new Error("invalid field element: outside of range 0..ORDER");return i},invertBatch:e=>el(d,e),cmov:(e,t,n)=>n?t:e});return Object.freeze(d)}function il(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 sl(e){const t=il(e);return t+Math.ceil(t/2)}const ol=BigInt(0),al=BigInt(1);function cl(e,t){const n=t.negate();return e?n:t}function ll(e,t){const n=el(e.Fp,t.map(e=>e.Z));return t.map((t,r)=>e.fromAffine(t.toAffine(n[r])))}function ul(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function dl(e,t){ul(e,t);const n=2**e;return{windows:Math.ceil(t/e)+1,windowSize:2**(e-1),mask:Bc(e),maxNumber:n,shiftBy:BigInt(e)}}function hl(e,t,n){const{windowSize:r,mask:i,maxNumber:s,shiftBy:o}=n;let a=Number(e&i),c=e>>o;a>r&&(a-=s,c+=al);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 gl=new WeakMap,fl=new WeakMap;function ml(e){return fl.get(e)||1}function pl(e){if(e!==ol)throw new Error("invalid wNAF")}class yl{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>ol;)t&al&&(n=n.add(r)),r=r.double(),t>>=al;return n}precomputeWindow(e,t){const{windows:n,windowSize:r}=dl(t,this.bits),i=[];let s=e,o=s;for(let e=0;e<n;e++){o=s,i.push(o);for(let e=1;e<r;e++)o=o.add(s),i.push(o);s=o.double()}return i}wNAF(e,t,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let r=this.ZERO,i=this.BASE;const s=dl(e,this.bits);for(let e=0;e<s.windows;e++){const{nextN:o,offset:a,isZero:c,isNeg:l,isNegF:u,offsetF:d}=hl(n,e,s);n=o,c?i=i.add(cl(u,t[d])):r=r.add(cl(l,t[a]))}return pl(n),{p:r,f:i}}wNAFUnsafe(e,t,n,r=this.ZERO){const i=dl(e,this.bits);for(let e=0;e<i.windows&&n!==ol;e++){const{nextN:s,offset:o,isZero:a,isNeg:c}=hl(n,e,i);if(n=s,!a){const e=t[o];r=r.add(c?e.negate():e)}}return pl(n),r}getPrecomputes(e,t,n){let r=gl.get(t);return r||(r=this.precomputeWindow(t,e),1!==e&&("function"==typeof n&&(r=n(r)),gl.set(t,r))),r}cached(e,t,n){const r=ml(e);return this.wNAF(r,this.getPrecomputes(r,e,n),t)}unsafe(e,t,n,r){const i=ml(e);return 1===i?this._unsafeLadder(e,t,r):this.wNAFUnsafe(i,this.getPrecomputes(i,e,n),t,r)}createCache(e,t){ul(t,this.bits),fl.set(e,t),gl.delete(e)}hasCache(e){return 1!==ml(e)}}function bl(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 i=n.length,s=r.length;if(i!==s)throw new Error("arrays of points and scalars must have equal length");const o=e.ZERO,a=Rc(BigInt(i));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const l=Bc(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<s;t++){const i=r[t],s=Number(i>>BigInt(e)&l);u[s]=u[s].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 vl(e,t,n){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return function(e){Dc(e,Zc.reduce((e,t)=>(e[t]="function",e),{ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"}))}(t),t}return rl(e,{isLE:n})}function wl(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>ol))throw new Error(`CURVE.${e} must be positive bigint`)}const i=vl(t.p,n.Fp,r),s=vl(t.n,n.Fn,r),o=["Gx","Gy","a","weierstrass"===e?"b":"d"];for(const e of o)if(!i.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:i,Fn:s}}const El=BigInt(0),Al=BigInt(1),kl=BigInt(2),Sl=BigInt(8);function Tl(e,t,n={}){if("function"!=typeof t)throw new Error('"hash" function param is required');Dc(n,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});const{prehash:r}=n,{BASE:i,Fp:s,Fn:o}=e,a=n.randomBytes||Pa,c=n.adjustScalarBytes||(e=>e),l=n.domain||((e,t,n)=>{if(vc(n,"phflag"),t.length||n)throw new Error("Contexts/pre-hash are not supported");return e});function u(e){return o.create(Sc(e))}function d(e){const{head:n,prefix:r,scalar:s}=function(e){const n=p.secretKey;e=Nc("private key",e,n);const r=Nc("hashed private key",t(e),2*n),i=c(r.slice(0,n));return{head:i,prefix:r.slice(n,2*n),scalar:u(i)}}(e),o=i.multiply(s),a=o.toBytes();return{head:n,prefix:r,scalar:s,point:o,pointBytes:a}}function h(e){return d(e).pointBytes}function g(e=Uint8Array.of(),...n){const i=Oa(...n);return u(t(l(i,Nc("context",e),!!r)))}const f={zip215:!0};const m=s.BYTES,p={secretKey:m,publicKey:m,signature:2*m,seed:m};function y(e=a(p.seed)){return wc(e,p.seed,"seed")}const b={getExtendedPublicKey:d,randomSecretKey:y,isValidSecretKey:function(e){return ma(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=p.publicKey,i=32===r;if(!i&&57!==r)throw new Error("only defined for 25519 and 448");const o=i?s.div(Al+n,Al-n):s.div(n-Al,n+Al);return s.toBytes(o)},toMontgomerySecret(e){const n=p.secretKey;wc(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=Nc("message",e),r&&(e=r(e));const{prefix:s,scalar:a,pointBytes:c}=d(t),l=g(n.context,s,e),u=i.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 wc(Oa(u,o.toBytes(f)),p.signature,"result")},verify:function(t,n,s,o=f){const{context:a,zip215:c}=o,l=p.signature;t=Nc("signature",t,l),n=Nc("message",n),s=Nc("publicKey",s,p.publicKey),void 0!==c&&vc(c,"zip215"),r&&(n=r(n));const u=l/2,d=t.subarray(0,u),h=Sc(t.subarray(u,l));let m,y,b;try{m=e.fromBytes(s,c),y=e.fromBytes(d,c),b=i.multiplyUnsafe(h)}catch(e){return!1}if(!c&&m.isSmallOrder())return!1;const v=g(a,y.toBytes(),m.toBytes(),n);return y.add(m.multiplyUnsafe(v)).subtract(b).clearCofactor().is0()},utils:b,Point:e,lengths:p})}function Il(e){const{CURVE:t,curveOpts:n,hash:r,eddsaOpts:i}=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:rl(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),s=function(e,t={}){const n=wl("edwards",e,t,t.FpFnLE),{Fp:r,Fn:i}=n;let s=n.CURVE;const{h:o}=s;Dc(t,{},{uvRatio:"function"});const a=kl<<BigInt(8*i.BYTES)-Al,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:El}}});if(!function(e,t,n,r){const i=e.sqr(n),s=e.sqr(r),o=e.add(e.mul(t.a,i),s),a=e.add(e.ONE,e.mul(t.d,e.mul(i,s)));return e.eql(o,a)}(r,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function u(e,t,n=!1){return xc("coordinate "+e,t,n?Al:El,a),t}function d(e){if(!(e instanceof f))throw new Error("ExtendedPoint expected")}const h=Mc((e,t)=>{const{X:n,Y:i,Z:s}=e,o=e.is0();null==t&&(t=o?Sl:r.inv(s));const a=c(n*t),l=c(i*t),u=r.mul(s,t);if(o)return{x:El,y:Al};if(u!==Al)throw new Error("invZ was invalid");return{x:a,y:l}}),g=Mc(e=>{const{a:t,d:n}=s;if(e.is0())throw new Error("bad point: ZERO");const{X:r,Y:i,Z:o,T:a}=e,l=c(r*r),u=c(i*i),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*i)!==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 s}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,Al,c(t*n))}static fromBytes(e,t=!1){const n=r.BYTES,{a:i,d:o}=s;e=Cc(wc(e,n,"point")),vc(t,"zip215");const u=Cc(e),d=e[n-1];u[n-1]=-129&d;const h=Sc(u),g=t?a:r.ORDER;xc("point.y",h,El,g);const m=c(h*h),p=c(m-Al),y=c(o*m-i);let{isValid:b,value:v}=l(p,y);if(!b)throw new Error("bad point: invalid y coordinate");const w=(v&Al)===Al,E=!!(128&d);if(!t&&v===El&&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(Nc("point",e),t)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(e=8,t=!0){return m.createCache(this,e),t||this.multiply(kl),this}assertValidity(){g(this)}equals(e){d(e);const{X:t,Y:n,Z:r}=this,{X:i,Y:s,Z:o}=e,a=c(t*o),l=c(i*r),u=c(n*o),h=c(s*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}=s,{X:t,Y:n,Z:r}=this,i=c(t*t),o=c(n*n),a=c(kl*c(r*r)),l=c(e*i),u=t+n,d=c(c(u*u)-i-o),h=l+o,g=h-a,m=l-o,p=c(d*g),y=c(h*m),b=c(d*m),v=c(g*h);return new f(p,y,v,b)}add(e){d(e);const{a:t,d:n}=s,{X:r,Y:i,Z:o,T:a}=this,{X:l,Y:u,Z:h,T:g}=e,m=c(r*l),p=c(i*u),y=c(a*n*g),b=c(o*h),v=c((r+i)*(l+u)-m-p),w=b-y,E=b+y,A=c(p-t*m),k=c(v*w),S=c(E*A),T=c(v*A),I=c(w*E);return new f(k,S,I,T)}subtract(e){return this.add(e.negate())}multiply(e){if(!i.isValidNot0(e))throw new Error("invalid scalar: expected 1 <= sc < curve.n");const{p:t,f:n}=m.cached(this,e,e=>ll(f,e));return ll(f,[t,n])[0]}multiplyUnsafe(e,t=f.ZERO){if(!i.isValid(e))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return e===El?f.ZERO:this.is0()||e===Al?this:m.unsafe(this,e,e=>ll(f,e),t)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}isTorsionFree(){return m.unsafe(this,s.n).is0()}toAffine(e){return h(this,e)}clearCofactor(){return o===Al?this:this.multiplyUnsafe(o)}toBytes(){const{x:e,y:t}=this.toAffine(),n=r.toBytes(t);return n[n.length-1]|=e&Al?128:0,n}toHex(){return Ta(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 ll(f,e)}static msm(e,t){return bl(f,i,e,t)}_setWindowSize(e){this.precompute(e)}toRawBytes(){return this.toBytes()}}f.BASE=new f(s.Gx,s.Gy,Al,c(s.Gx*s.Gy)),f.ZERO=new f(El,Al,Al,El),f.Fp=r,f.Fn=i;const m=new yl(f,i.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,Tl(s,r,i))}const Nl=BigInt(1),Cl=BigInt(2);BigInt(3);const _l=BigInt(5),xl=BigInt(8),Rl=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Bl=(()=>({p:Rl,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:xl,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")}))();function Dl(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}const Ml=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Ol(e,t){const n=Rl,r=qc(t*t*t,n),i=function(e){const t=BigInt(10),n=BigInt(20),r=BigInt(40),i=BigInt(80),s=Rl,o=e*e%s*e%s,a=jc(o,Cl,s)*o%s,c=jc(a,Nl,s)*e%s,l=jc(c,_l,s)*c%s,u=jc(l,t,s)*l%s,d=jc(u,n,s)*u%s,h=jc(d,r,s)*d%s,g=jc(h,i,s)*h%s,f=jc(g,i,s)*h%s,m=jc(f,t,s)*l%s;return{pow_p_5_8:jc(m,Cl,s)*e%s,b2:o}}(e*qc(r*r*t,n)).pow_p_5_8;let s=qc(e*r*i,n);const o=qc(t*s*s,n),a=s,c=qc(s*Ml,n),l=o===e,u=o===qc(-e,n),d=o===qc(-e*Ml,n);return l&&(s=a),(u||d)&&(s=c),(qc(s,n)&Uc)===Uc&&(s=qc(-s,n)),{isValid:l||u,value:s}}const Ul=(()=>rl(Bl.p,{isLE:!0}))(),Ll=(()=>({...Bl,Fp:Ul,hash:pc,adjustScalarBytes:Dl,uvRatio:Ol}))(),Pl=(()=>Il(Ll))();var Fl,$l={exports:{}},Kl=ra(Object.freeze({__proto__:null,default:{}})),Gl=$l.exports;function Hl(){return Fl||(Fl=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 i(e,t,n){if(i.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 s;"object"==typeof e?e.exports=i:t.BN=i,i.BN=i,i.wordSize=26;try{s="undefined"!=typeof window&&void 0!==window.Buffer?window.Buffer:Kl.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,i){for(var s=0,o=0,a=Math.min(e.length,r),c=t;c<a;c++){var l=e.charCodeAt(c)-48;s*=i,o=l>=49?l-49+10:l>=17?l-17+10:l,n(l>=0&&o<i,"Invalid character"),s+=o}return s}function l(e,t){e.words=t.words,e.length=t.length,e.negative=t.negative,e.red=t.red}if(i.isBN=function(e){return e instanceof i||null!==e&&"object"==typeof e&&e.constructor.wordSize===i.wordSize&&Array.isArray(e.words)},i.max=function(e,t){return e.cmp(t)>0?e:t},i.min=function(e,t){return e.cmp(t)<0?e:t},i.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 i=0;"-"===(e=e.toString().replace(/\s+/g,""))[0]&&(i++,this.negative=1),i<e.length&&(16===t?this._parseHex(e,i,r):(this._parseBase(e,t,i),"le"===r&&this._initArray(this.toArray(),t,r)))},i.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)},i.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 i=0;i<this.length;i++)this.words[i]=0;var s,o,a=0;if("be"===r)for(i=e.length-1,s=0;i>=0;i-=3)o=e[i]|e[i-1]<<8|e[i-2]<<16,this.words[s]|=o<<a&67108863,this.words[s+1]=o>>>26-a&67108863,(a+=24)>=26&&(a-=26,s++);else if("le"===r)for(i=0,s=0;i<e.length;i+=3)o=e[i]|e[i+1]<<8|e[i+2]<<16,this.words[s]|=o<<a&67108863,this.words[s+1]=o>>>26-a&67108863,(a+=24)>=26&&(a-=26,s++);return this._strip()},i.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 i,s=0,o=0;if("be"===n)for(r=e.length-1;r>=t;r-=2)i=a(e,t,r)<<s,this.words[o]|=67108863&i,s>=18?(s-=18,o+=1,this.words[o]|=i>>>26):s+=8;else for(r=(e.length-t)%2==0?t+1:t;r<e.length;r+=2)i=a(e,t,r)<<s,this.words[o]|=67108863&i,s>=18?(s-=18,o+=1,this.words[o]|=i>>>26):s+=8;this._strip()},i.prototype._parseBase=function(e,t,n){this.words=[0],this.length=1;for(var r=0,i=1;i<=67108863;i*=t)r++;r--,i=i/t|0;for(var s=e.length-n,o=s%r,a=Math.min(s,s-o)+n,l=0,u=n;u<a;u+=r)l=c(e,u,u+r,t),this.imuln(i),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()},i.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},i.prototype._move=function(e){l(e,this)},i.prototype.clone=function(){var e=new i(null);return this.copy(e),e},i.prototype._expand=function(e){for(;this.length<e;)this.words[this.length++]=0;return this},i.prototype._strip=function(){for(;this.length>1&&0===this.words[this.length-1];)this.length--;return this._normSign()},i.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},"undefined"!=typeof Symbol&&"function"==typeof Symbol.for)try{i.prototype[Symbol.for("nodejs.util.inspect.custom")]=u}catch(e){i.prototype.inspect=u}else i.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 i=0|e.words[0],s=0|t.words[0],o=i*s,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=(i=0|e.words[f])*(s=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()}i.prototype.toString=function(e,t){var r;if(t=0|t||1,16===(e=e||10)||"hex"===e){r="";for(var i=0,s=0,o=0;o<this.length;o++){var a=this.words[o],c=(16777215&(a<<i|s)).toString(16);s=a>>>24-i&16777215,(i+=2)>=26&&(i-=26,o--),r=0!==s||o!==this.length-1?d[6-c.length]+c+r:c+r}for(0!==s&&(r=s.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 m=f.modrn(u).toString(e);r=(f=f.idivn(u)).isZero()?m+r:d[l-m.length]+m+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")},i.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},i.prototype.toJSON=function(){return this.toString(16,2)},s&&(i.prototype.toBuffer=function(e,t){return this.toArrayLike(s,e,t)}),i.prototype.toArray=function(e,t){return this.toArrayLike(Array,e,t)},i.prototype.toArrayLike=function(e,t,r){this._strip();var i=this.byteLength(),s=r||Math.max(1,i);n(i<=s,"byte array longer than desired length"),n(s>0,"Requested array length <= 0");var o=function(e,t){return e.allocUnsafe?e.allocUnsafe(t):new e(t)}(e,s);return this["_toArrayLike"+("le"===t?"LE":"BE")](o,i),o},i.prototype._toArrayLikeLE=function(e,t){for(var n=0,r=0,i=0,s=0;i<this.length;i++){var o=this.words[i]<<s|r;e[n++]=255&o,n<e.length&&(e[n++]=o>>8&255),n<e.length&&(e[n++]=o>>16&255),6===s?(n<e.length&&(e[n++]=o>>24&255),r=0,s=0):(r=o>>>24,s+=2)}if(n<e.length)for(e[n++]=r;n<e.length;)e[n++]=0},i.prototype._toArrayLikeBE=function(e,t){for(var n=e.length-1,r=0,i=0,s=0;i<this.length;i++){var o=this.words[i]<<s|r;e[n--]=255&o,n>=0&&(e[n--]=o>>8&255),n>=0&&(e[n--]=o>>16&255),6===s?(n>=0&&(e[n--]=o>>24&255),r=0,s=0):(r=o>>>24,s+=2)}if(n>=0)for(e[n--]=r;n>=0;)e[n--]=0},Math.clz32?i.prototype._countBits=function(e){return 32-Math.clz32(e)}:i.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},i.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},i.prototype.bitLength=function(){var e=this.words[this.length-1],t=this._countBits(e);return 26*(this.length-1)+t},i.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},i.prototype.byteLength=function(){return Math.ceil(this.bitLength()/8)},i.prototype.toTwos=function(e){return 0!==this.negative?this.abs().inotn(e).iaddn(1):this.clone()},i.prototype.fromTwos=function(e){return this.testn(e-1)?this.notn(e).iaddn(1).ineg():this.clone()},i.prototype.isNeg=function(){return 0!==this.negative},i.prototype.neg=function(){return this.clone().ineg()},i.prototype.ineg=function(){return this.isZero()||(this.negative^=1),this},i.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()},i.prototype.ior=function(e){return n(0===(this.negative|e.negative)),this.iuor(e)},i.prototype.or=function(e){return this.length>e.length?this.clone().ior(e):e.clone().ior(this)},i.prototype.uor=function(e){return this.length>e.length?this.clone().iuor(e):e.clone().iuor(this)},i.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()},i.prototype.iand=function(e){return n(0===(this.negative|e.negative)),this.iuand(e)},i.prototype.and=function(e){return this.length>e.length?this.clone().iand(e):e.clone().iand(this)},i.prototype.uand=function(e){return this.length>e.length?this.clone().iuand(e):e.clone().iuand(this)},i.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()},i.prototype.ixor=function(e){return n(0===(this.negative|e.negative)),this.iuxor(e)},i.prototype.xor=function(e){return this.length>e.length?this.clone().ixor(e):e.clone().ixor(this)},i.prototype.uxor=function(e){return this.length>e.length?this.clone().iuxor(e):e.clone().iuxor(this)},i.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 i=0;i<t;i++)this.words[i]=67108863&~this.words[i];for(r>0&&(this.words[i]=~this.words[i]&67108863>>26-r,i++);i<this.length;i++)this.words[i]=0;return this._strip()},i.prototype.notn=function(e){return this.clone().inotn(e)},i.prototype.setn=function(e,t){n("number"==typeof e&&e>=0);var r=e/26|0,i=e%26;return this._expand(r+1),this.words[r]=t?this.words[r]|1<<i:this.words[r]&~(1<<i),this._strip()},i.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 i=0,s=0;s<r.length;s++)t=(0|n.words[s])+(0|r.words[s])+i,this.words[s]=67108863&t,i=t>>>26;for(;0!==i&&s<n.length;s++)t=(0|n.words[s])+i,this.words[s]=67108863&t,i=t>>>26;if(this.length=n.length,0!==i)this.words[this.length]=i,this.length++;else if(n!==this)for(;s<n.length;s++)this.words[s]=n.words[s];return this},i.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)},i.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,i=this.cmp(e);if(0===i)return this.negative=0,this.length=1,this.words[0]=0,this;i>0?(n=this,r=e):(n=e,r=this);for(var s=0,o=0;o<r.length;o++)s=(t=(0|n.words[o])-(0|r.words[o])+s)>>26,this.words[o]=67108863&t;for(;0!==s&&o<n.length;o++)s=(t=(0|n.words[o])+s)>>26,this.words[o]=67108863&t;if(0===s&&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()},i.prototype.sub=function(e){return this.clone().isub(e)};var m=function(e,t,n){var r,i,s,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,m=g>>>13,p=0|o[2],y=8191&p,b=p>>>13,v=0|o[3],w=8191&v,E=v>>>13,A=0|o[4],k=8191&A,S=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,M=0|o[8],O=8191&M,U=M>>>13,L=0|o[9],P=8191&L,F=L>>>13,$=0|a[0],K=8191&$,G=$>>>13,H=0|a[1],W=8191&H,q=H>>>13,j=0|a[2],V=8191&j,z=j>>>13,X=0|a[3],J=8191&X,Y=X>>>13,Q=0|a[4],Z=8191&Q,ee=Q>>>13,te=0|a[5],ne=8191&te,re=te>>>13,ie=0|a[6],se=8191&ie,oe=ie>>>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,me=ge>>>13;n.negative=e.negative^t.negative,n.length=19;var pe=(l+(r=Math.imul(d,K))|0)+((8191&(i=(i=Math.imul(d,G))+Math.imul(h,K)|0))<<13)|0;l=((s=Math.imul(h,G))+(i>>>13)|0)+(pe>>>26)|0,pe&=67108863,r=Math.imul(f,K),i=(i=Math.imul(f,G))+Math.imul(m,K)|0,s=Math.imul(m,G);var ye=(l+(r=r+Math.imul(d,W)|0)|0)+((8191&(i=(i=i+Math.imul(d,q)|0)+Math.imul(h,W)|0))<<13)|0;l=((s=s+Math.imul(h,q)|0)+(i>>>13)|0)+(ye>>>26)|0,ye&=67108863,r=Math.imul(y,K),i=(i=Math.imul(y,G))+Math.imul(b,K)|0,s=Math.imul(b,G),r=r+Math.imul(f,W)|0,i=(i=i+Math.imul(f,q)|0)+Math.imul(m,W)|0,s=s+Math.imul(m,q)|0;var be=(l+(r=r+Math.imul(d,V)|0)|0)+((8191&(i=(i=i+Math.imul(d,z)|0)+Math.imul(h,V)|0))<<13)|0;l=((s=s+Math.imul(h,z)|0)+(i>>>13)|0)+(be>>>26)|0,be&=67108863,r=Math.imul(w,K),i=(i=Math.imul(w,G))+Math.imul(E,K)|0,s=Math.imul(E,G),r=r+Math.imul(y,W)|0,i=(i=i+Math.imul(y,q)|0)+Math.imul(b,W)|0,s=s+Math.imul(b,q)|0,r=r+Math.imul(f,V)|0,i=(i=i+Math.imul(f,z)|0)+Math.imul(m,V)|0,s=s+Math.imul(m,z)|0;var ve=(l+(r=r+Math.imul(d,J)|0)|0)+((8191&(i=(i=i+Math.imul(d,Y)|0)+Math.imul(h,J)|0))<<13)|0;l=((s=s+Math.imul(h,Y)|0)+(i>>>13)|0)+(ve>>>26)|0,ve&=67108863,r=Math.imul(k,K),i=(i=Math.imul(k,G))+Math.imul(S,K)|0,s=Math.imul(S,G),r=r+Math.imul(w,W)|0,i=(i=i+Math.imul(w,q)|0)+Math.imul(E,W)|0,s=s+Math.imul(E,q)|0,r=r+Math.imul(y,V)|0,i=(i=i+Math.imul(y,z)|0)+Math.imul(b,V)|0,s=s+Math.imul(b,z)|0,r=r+Math.imul(f,J)|0,i=(i=i+Math.imul(f,Y)|0)+Math.imul(m,J)|0,s=s+Math.imul(m,Y)|0;var we=(l+(r=r+Math.imul(d,Z)|0)|0)+((8191&(i=(i=i+Math.imul(d,ee)|0)+Math.imul(h,Z)|0))<<13)|0;l=((s=s+Math.imul(h,ee)|0)+(i>>>13)|0)+(we>>>26)|0,we&=67108863,r=Math.imul(I,K),i=(i=Math.imul(I,G))+Math.imul(N,K)|0,s=Math.imul(N,G),r=r+Math.imul(k,W)|0,i=(i=i+Math.imul(k,q)|0)+Math.imul(S,W)|0,s=s+Math.imul(S,q)|0,r=r+Math.imul(w,V)|0,i=(i=i+Math.imul(w,z)|0)+Math.imul(E,V)|0,s=s+Math.imul(E,z)|0,r=r+Math.imul(y,J)|0,i=(i=i+Math.imul(y,Y)|0)+Math.imul(b,J)|0,s=s+Math.imul(b,Y)|0,r=r+Math.imul(f,Z)|0,i=(i=i+Math.imul(f,ee)|0)+Math.imul(m,Z)|0,s=s+Math.imul(m,ee)|0;var Ee=(l+(r=r+Math.imul(d,ne)|0)|0)+((8191&(i=(i=i+Math.imul(d,re)|0)+Math.imul(h,ne)|0))<<13)|0;l=((s=s+Math.imul(h,re)|0)+(i>>>13)|0)+(Ee>>>26)|0,Ee&=67108863,r=Math.imul(_,K),i=(i=Math.imul(_,G))+Math.imul(x,K)|0,s=Math.imul(x,G),r=r+Math.imul(I,W)|0,i=(i=i+Math.imul(I,q)|0)+Math.imul(N,W)|0,s=s+Math.imul(N,q)|0,r=r+Math.imul(k,V)|0,i=(i=i+Math.imul(k,z)|0)+Math.imul(S,V)|0,s=s+Math.imul(S,z)|0,r=r+Math.imul(w,J)|0,i=(i=i+Math.imul(w,Y)|0)+Math.imul(E,J)|0,s=s+Math.imul(E,Y)|0,r=r+Math.imul(y,Z)|0,i=(i=i+Math.imul(y,ee)|0)+Math.imul(b,Z)|0,s=s+Math.imul(b,ee)|0,r=r+Math.imul(f,ne)|0,i=(i=i+Math.imul(f,re)|0)+Math.imul(m,ne)|0,s=s+Math.imul(m,re)|0;var Ae=(l+(r=r+Math.imul(d,se)|0)|0)+((8191&(i=(i=i+Math.imul(d,oe)|0)+Math.imul(h,se)|0))<<13)|0;l=((s=s+Math.imul(h,oe)|0)+(i>>>13)|0)+(Ae>>>26)|0,Ae&=67108863,r=Math.imul(B,K),i=(i=Math.imul(B,G))+Math.imul(D,K)|0,s=Math.imul(D,G),r=r+Math.imul(_,W)|0,i=(i=i+Math.imul(_,q)|0)+Math.imul(x,W)|0,s=s+Math.imul(x,q)|0,r=r+Math.imul(I,V)|0,i=(i=i+Math.imul(I,z)|0)+Math.imul(N,V)|0,s=s+Math.imul(N,z)|0,r=r+Math.imul(k,J)|0,i=(i=i+Math.imul(k,Y)|0)+Math.imul(S,J)|0,s=s+Math.imul(S,Y)|0,r=r+Math.imul(w,Z)|0,i=(i=i+Math.imul(w,ee)|0)+Math.imul(E,Z)|0,s=s+Math.imul(E,ee)|0,r=r+Math.imul(y,ne)|0,i=(i=i+Math.imul(y,re)|0)+Math.imul(b,ne)|0,s=s+Math.imul(b,re)|0,r=r+Math.imul(f,se)|0,i=(i=i+Math.imul(f,oe)|0)+Math.imul(m,se)|0,s=s+Math.imul(m,oe)|0;var ke=(l+(r=r+Math.imul(d,ce)|0)|0)+((8191&(i=(i=i+Math.imul(d,le)|0)+Math.imul(h,ce)|0))<<13)|0;l=((s=s+Math.imul(h,le)|0)+(i>>>13)|0)+(ke>>>26)|0,ke&=67108863,r=Math.imul(O,K),i=(i=Math.imul(O,G))+Math.imul(U,K)|0,s=Math.imul(U,G),r=r+Math.imul(B,W)|0,i=(i=i+Math.imul(B,q)|0)+Math.imul(D,W)|0,s=s+Math.imul(D,q)|0,r=r+Math.imul(_,V)|0,i=(i=i+Math.imul(_,z)|0)+Math.imul(x,V)|0,s=s+Math.imul(x,z)|0,r=r+Math.imul(I,J)|0,i=(i=i+Math.imul(I,Y)|0)+Math.imul(N,J)|0,s=s+Math.imul(N,Y)|0,r=r+Math.imul(k,Z)|0,i=(i=i+Math.imul(k,ee)|0)+Math.imul(S,Z)|0,s=s+Math.imul(S,ee)|0,r=r+Math.imul(w,ne)|0,i=(i=i+Math.imul(w,re)|0)+Math.imul(E,ne)|0,s=s+Math.imul(E,re)|0,r=r+Math.imul(y,se)|0,i=(i=i+Math.imul(y,oe)|0)+Math.imul(b,se)|0,s=s+Math.imul(b,oe)|0,r=r+Math.imul(f,ce)|0,i=(i=i+Math.imul(f,le)|0)+Math.imul(m,ce)|0,s=s+Math.imul(m,le)|0;var Se=(l+(r=r+Math.imul(d,de)|0)|0)+((8191&(i=(i=i+Math.imul(d,he)|0)+Math.imul(h,de)|0))<<13)|0;l=((s=s+Math.imul(h,he)|0)+(i>>>13)|0)+(Se>>>26)|0,Se&=67108863,r=Math.imul(P,K),i=(i=Math.imul(P,G))+Math.imul(F,K)|0,s=Math.imul(F,G),r=r+Math.imul(O,W)|0,i=(i=i+Math.imul(O,q)|0)+Math.imul(U,W)|0,s=s+Math.imul(U,q)|0,r=r+Math.imul(B,V)|0,i=(i=i+Math.imul(B,z)|0)+Math.imul(D,V)|0,s=s+Math.imul(D,z)|0,r=r+Math.imul(_,J)|0,i=(i=i+Math.imul(_,Y)|0)+Math.imul(x,J)|0,s=s+Math.imul(x,Y)|0,r=r+Math.imul(I,Z)|0,i=(i=i+Math.imul(I,ee)|0)+Math.imul(N,Z)|0,s=s+Math.imul(N,ee)|0,r=r+Math.imul(k,ne)|0,i=(i=i+Math.imul(k,re)|0)+Math.imul(S,ne)|0,s=s+Math.imul(S,re)|0,r=r+Math.imul(w,se)|0,i=(i=i+Math.imul(w,oe)|0)+Math.imul(E,se)|0,s=s+Math.imul(E,oe)|0,r=r+Math.imul(y,ce)|0,i=(i=i+Math.imul(y,le)|0)+Math.imul(b,ce)|0,s=s+Math.imul(b,le)|0,r=r+Math.imul(f,de)|0,i=(i=i+Math.imul(f,he)|0)+Math.imul(m,de)|0,s=s+Math.imul(m,he)|0;var Te=(l+(r=r+Math.imul(d,fe)|0)|0)+((8191&(i=(i=i+Math.imul(d,me)|0)+Math.imul(h,fe)|0))<<13)|0;l=((s=s+Math.imul(h,me)|0)+(i>>>13)|0)+(Te>>>26)|0,Te&=67108863,r=Math.imul(P,W),i=(i=Math.imul(P,q))+Math.imul(F,W)|0,s=Math.imul(F,q),r=r+Math.imul(O,V)|0,i=(i=i+Math.imul(O,z)|0)+Math.imul(U,V)|0,s=s+Math.imul(U,z)|0,r=r+Math.imul(B,J)|0,i=(i=i+Math.imul(B,Y)|0)+Math.imul(D,J)|0,s=s+Math.imul(D,Y)|0,r=r+Math.imul(_,Z)|0,i=(i=i+Math.imul(_,ee)|0)+Math.imul(x,Z)|0,s=s+Math.imul(x,ee)|0,r=r+Math.imul(I,ne)|0,i=(i=i+Math.imul(I,re)|0)+Math.imul(N,ne)|0,s=s+Math.imul(N,re)|0,r=r+Math.imul(k,se)|0,i=(i=i+Math.imul(k,oe)|0)+Math.imul(S,se)|0,s=s+Math.imul(S,oe)|0,r=r+Math.imul(w,ce)|0,i=(i=i+Math.imul(w,le)|0)+Math.imul(E,ce)|0,s=s+Math.imul(E,le)|0,r=r+Math.imul(y,de)|0,i=(i=i+Math.imul(y,he)|0)+Math.imul(b,de)|0,s=s+Math.imul(b,he)|0;var Ie=(l+(r=r+Math.imul(f,fe)|0)|0)+((8191&(i=(i=i+Math.imul(f,me)|0)+Math.imul(m,fe)|0))<<13)|0;l=((s=s+Math.imul(m,me)|0)+(i>>>13)|0)+(Ie>>>26)|0,Ie&=67108863,r=Math.imul(P,V),i=(i=Math.imul(P,z))+Math.imul(F,V)|0,s=Math.imul(F,z),r=r+Math.imul(O,J)|0,i=(i=i+Math.imul(O,Y)|0)+Math.imul(U,J)|0,s=s+Math.imul(U,Y)|0,r=r+Math.imul(B,Z)|0,i=(i=i+Math.imul(B,ee)|0)+Math.imul(D,Z)|0,s=s+Math.imul(D,ee)|0,r=r+Math.imul(_,ne)|0,i=(i=i+Math.imul(_,re)|0)+Math.imul(x,ne)|0,s=s+Math.imul(x,re)|0,r=r+Math.imul(I,se)|0,i=(i=i+Math.imul(I,oe)|0)+Math.imul(N,se)|0,s=s+Math.imul(N,oe)|0,r=r+Math.imul(k,ce)|0,i=(i=i+Math.imul(k,le)|0)+Math.imul(S,ce)|0,s=s+Math.imul(S,le)|0,r=r+Math.imul(w,de)|0,i=(i=i+Math.imul(w,he)|0)+Math.imul(E,de)|0,s=s+Math.imul(E,he)|0;var Ne=(l+(r=r+Math.imul(y,fe)|0)|0)+((8191&(i=(i=i+Math.imul(y,me)|0)+Math.imul(b,fe)|0))<<13)|0;l=((s=s+Math.imul(b,me)|0)+(i>>>13)|0)+(Ne>>>26)|0,Ne&=67108863,r=Math.imul(P,J),i=(i=Math.imul(P,Y))+Math.imul(F,J)|0,s=Math.imul(F,Y),r=r+Math.imul(O,Z)|0,i=(i=i+Math.imul(O,ee)|0)+Math.imul(U,Z)|0,s=s+Math.imul(U,ee)|0,r=r+Math.imul(B,ne)|0,i=(i=i+Math.imul(B,re)|0)+Math.imul(D,ne)|0,s=s+Math.imul(D,re)|0,r=r+Math.imul(_,se)|0,i=(i=i+Math.imul(_,oe)|0)+Math.imul(x,se)|0,s=s+Math.imul(x,oe)|0,r=r+Math.imul(I,ce)|0,i=(i=i+Math.imul(I,le)|0)+Math.imul(N,ce)|0,s=s+Math.imul(N,le)|0,r=r+Math.imul(k,de)|0,i=(i=i+Math.imul(k,he)|0)+Math.imul(S,de)|0,s=s+Math.imul(S,he)|0;var Ce=(l+(r=r+Math.imul(w,fe)|0)|0)+((8191&(i=(i=i+Math.imul(w,me)|0)+Math.imul(E,fe)|0))<<13)|0;l=((s=s+Math.imul(E,me)|0)+(i>>>13)|0)+(Ce>>>26)|0,Ce&=67108863,r=Math.imul(P,Z),i=(i=Math.imul(P,ee))+Math.imul(F,Z)|0,s=Math.imul(F,ee),r=r+Math.imul(O,ne)|0,i=(i=i+Math.imul(O,re)|0)+Math.imul(U,ne)|0,s=s+Math.imul(U,re)|0,r=r+Math.imul(B,se)|0,i=(i=i+Math.imul(B,oe)|0)+Math.imul(D,se)|0,s=s+Math.imul(D,oe)|0,r=r+Math.imul(_,ce)|0,i=(i=i+Math.imul(_,le)|0)+Math.imul(x,ce)|0,s=s+Math.imul(x,le)|0,r=r+Math.imul(I,de)|0,i=(i=i+Math.imul(I,he)|0)+Math.imul(N,de)|0,s=s+Math.imul(N,he)|0;var _e=(l+(r=r+Math.imul(k,fe)|0)|0)+((8191&(i=(i=i+Math.imul(k,me)|0)+Math.imul(S,fe)|0))<<13)|0;l=((s=s+Math.imul(S,me)|0)+(i>>>13)|0)+(_e>>>26)|0,_e&=67108863,r=Math.imul(P,ne),i=(i=Math.imul(P,re))+Math.imul(F,ne)|0,s=Math.imul(F,re),r=r+Math.imul(O,se)|0,i=(i=i+Math.imul(O,oe)|0)+Math.imul(U,se)|0,s=s+Math.imul(U,oe)|0,r=r+Math.imul(B,ce)|0,i=(i=i+Math.imul(B,le)|0)+Math.imul(D,ce)|0,s=s+Math.imul(D,le)|0,r=r+Math.imul(_,de)|0,i=(i=i+Math.imul(_,he)|0)+Math.imul(x,de)|0,s=s+Math.imul(x,he)|0;var xe=(l+(r=r+Math.imul(I,fe)|0)|0)+((8191&(i=(i=i+Math.imul(I,me)|0)+Math.imul(N,fe)|0))<<13)|0;l=((s=s+Math.imul(N,me)|0)+(i>>>13)|0)+(xe>>>26)|0,xe&=67108863,r=Math.imul(P,se),i=(i=Math.imul(P,oe))+Math.imul(F,se)|0,s=Math.imul(F,oe),r=r+Math.imul(O,ce)|0,i=(i=i+Math.imul(O,le)|0)+Math.imul(U,ce)|0,s=s+Math.imul(U,le)|0,r=r+Math.imul(B,de)|0,i=(i=i+Math.imul(B,he)|0)+Math.imul(D,de)|0,s=s+Math.imul(D,he)|0;var Re=(l+(r=r+Math.imul(_,fe)|0)|0)+((8191&(i=(i=i+Math.imul(_,me)|0)+Math.imul(x,fe)|0))<<13)|0;l=((s=s+Math.imul(x,me)|0)+(i>>>13)|0)+(Re>>>26)|0,Re&=67108863,r=Math.imul(P,ce),i=(i=Math.imul(P,le))+Math.imul(F,ce)|0,s=Math.imul(F,le),r=r+Math.imul(O,de)|0,i=(i=i+Math.imul(O,he)|0)+Math.imul(U,de)|0,s=s+Math.imul(U,he)|0;var Be=(l+(r=r+Math.imul(B,fe)|0)|0)+((8191&(i=(i=i+Math.imul(B,me)|0)+Math.imul(D,fe)|0))<<13)|0;l=((s=s+Math.imul(D,me)|0)+(i>>>13)|0)+(Be>>>26)|0,Be&=67108863,r=Math.imul(P,de),i=(i=Math.imul(P,he))+Math.imul(F,de)|0,s=Math.imul(F,he);var De=(l+(r=r+Math.imul(O,fe)|0)|0)+((8191&(i=(i=i+Math.imul(O,me)|0)+Math.imul(U,fe)|0))<<13)|0;l=((s=s+Math.imul(U,me)|0)+(i>>>13)|0)+(De>>>26)|0,De&=67108863;var Me=(l+(r=Math.imul(P,fe))|0)+((8191&(i=(i=Math.imul(P,me))+Math.imul(F,fe)|0))<<13)|0;return l=((s=Math.imul(F,me))+(i>>>13)|0)+(Me>>>26)|0,Me&=67108863,c[0]=pe,c[1]=ye,c[2]=be,c[3]=ve,c[4]=we,c[5]=Ee,c[6]=Ae,c[7]=ke,c[8]=Se,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]=Me,0!==l&&(c[19]=l,n.length++),n};function p(e,t,n){n.negative=t.negative^e.negative,n.length=e.length+t.length;for(var r=0,i=0,s=0;s<n.length-1;s++){var o=i;i=0;for(var a=67108863&r,c=Math.min(s,t.length-1),l=Math.max(0,s-e.length+1);l<=c;l++){var u=s-l,d=(0|e.words[u])*(0|t.words[l]),h=67108863&d;a=67108863&(h=h+a|0),i+=(o=(o=o+(d/67108864|0)|0)+(h>>>26)|0)>>>26,o&=67108863}n.words[s]=a,r=o,o=i}return 0!==r?n.words[s]=r:n.length--,n._strip()}function y(e,t,n){return p(e,t,n)}Math.imul||(m=f),i.prototype.mulTo=function(e,t){var n=this.length+e.length;return 10===this.length&&10===e.length?m(this,e,t):n<63?f(this,e,t):n<1024?p(this,e,t):y(this,e,t)},i.prototype.mul=function(e){var t=new i(null);return t.words=new Array(this.length+e.length),this.mulTo(e,t)},i.prototype.mulf=function(e){var t=new i(null);return t.words=new Array(this.length+e.length),y(this,e,t)},i.prototype.imul=function(e){return this.clone().mulTo(e,this)},i.prototype.imuln=function(e){var t=e<0;t&&(e=-e),n("number"==typeof e),n(e<67108864);for(var r=0,i=0;i<this.length;i++){var s=(0|this.words[i])*e,o=(67108863&s)+(67108863&r);r>>=26,r+=s/67108864|0,r+=o>>>26,this.words[i]=67108863&o}return 0!==r&&(this.words[i]=r,this.length++),0===e&&(this.length=1,this._normSign()),t?this.ineg():this},i.prototype.muln=function(e){return this.clone().imuln(e)},i.prototype.sqr=function(){return this.mul(this)},i.prototype.isqr=function(){return this.imul(this.clone())},i.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,i=n%26;t[n]=e.words[r]>>>i&1}return t}(e);if(0===t.length)return new i(1);for(var n=this,r=0;r<t.length&&0===t[r];r++,n=n.sqr());if(++r<t.length)for(var s=n.sqr();r<t.length;r++,s=s.sqr())0!==t[r]&&(n=n.mul(s));return n},i.prototype.iushln=function(e){n("number"==typeof e&&e>=0);var t,r=e%26,i=(e-r)/26,s=67108863>>>26-r<<26-r;if(0!==r){var o=0;for(t=0;t<this.length;t++){var a=this.words[t]&s,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!==i){for(t=this.length-1;t>=0;t--)this.words[t+i]=this.words[t];for(t=0;t<i;t++)this.words[t]=0;this.length+=i}return this._strip()},i.prototype.ishln=function(e){return n(0===this.negative),this.iushln(e)},i.prototype.iushrn=function(e,t,r){var i;n("number"==typeof e&&e>=0),i=t?(t-t%26)/26:0;var s=e%26,o=Math.min((e-s)/26,this.length),a=67108863^67108863>>>s<<s,c=r;if(i-=o,i=Math.max(0,i),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>=i);l--){var d=0|this.words[l];this.words[l]=u<<26-s|d>>>s,u=d&a}return c&&0!==u&&(c.words[c.length++]=u),0===this.length&&(this.words[0]=0,this.length=1),this._strip()},i.prototype.ishrn=function(e,t,r){return n(0===this.negative),this.iushrn(e,t,r)},i.prototype.shln=function(e){return this.clone().ishln(e)},i.prototype.ushln=function(e){return this.clone().iushln(e)},i.prototype.shrn=function(e){return this.clone().ishrn(e)},i.prototype.ushrn=function(e){return this.clone().iushrn(e)},i.prototype.testn=function(e){n("number"==typeof e&&e>=0);var t=e%26,r=(e-t)/26,i=1<<t;return!(this.length<=r||!(this.words[r]&i))},i.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 i=67108863^67108863>>>t<<t;this.words[this.length-1]&=i}return 0===this.length&&(this.words[0]=0,this.length=1),this._strip()},i.prototype.maskn=function(e){return this.clone().imaskn(e)},i.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)},i.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},i.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()},i.prototype.addn=function(e){return this.clone().iaddn(e)},i.prototype.subn=function(e){return this.clone().isubn(e)},i.prototype.iabs=function(){return this.negative=0,this},i.prototype.abs=function(){return this.clone().iabs()},i.prototype._ishlnsubmul=function(e,t,r){var i,s,o=e.length+r;this._expand(o);var a=0;for(i=0;i<e.length;i++){s=(0|this.words[i+r])+a;var c=(0|e.words[i])*t;a=((s-=67108863&c)>>26)-(c/67108864|0),this.words[i+r]=67108863&s}for(;i<this.length-r;i++)a=(s=(0|this.words[i+r])+a)>>26,this.words[i+r]=67108863&s;if(0===a)return this._strip();for(n(-1===a),a=0,i=0;i<this.length;i++)a=(s=-(0|this.words[i])+a)>>26,this.words[i]=67108863&s;return this.negative=1,this._strip()},i.prototype._wordDiv=function(e,t){var n=(this.length,e.length),r=this.clone(),s=e,o=0|s.words[s.length-1];0!=(n=26-this._countBits(o))&&(s=s.ushln(n),r.iushln(n),o=0|s.words[s.length-1]);var a,c=r.length-s.length;if("mod"!==t){(a=new i(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(s,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[s.length+d])+(0|r.words[s.length+d-1]);for(h=Math.min(h/o|0,67108863),r._ishlnsubmul(s,h,d);0!==r.negative;)h--,r.negative=0,r._ishlnsubmul(s,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}},i.prototype.divmod=function(e,t,r){return n(!e.isZero()),this.isZero()?{div:new i(0),mod:new i(0)}:0!==this.negative&&0===e.negative?(a=this.neg().divmod(e,t),"mod"!==t&&(s=a.div.neg()),"div"!==t&&(o=a.mod.neg(),r&&0!==o.negative&&o.iadd(e)),{div:s,mod:o}):0===this.negative&&0!==e.negative?(a=this.divmod(e.neg(),t),"mod"!==t&&(s=a.div.neg()),{div:s,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 i(0),mod:this}:1===e.length?"div"===t?{div:this.divn(e.words[0]),mod:null}:"mod"===t?{div:null,mod:new i(this.modrn(e.words[0]))}:{div:this.divn(e.words[0]),mod:new i(this.modrn(e.words[0]))}:this._wordDiv(e,t);var s,o,a},i.prototype.div=function(e){return this.divmod(e,"div",!1).div},i.prototype.mod=function(e){return this.divmod(e,"mod",!1).mod},i.prototype.umod=function(e){return this.divmod(e,"mod",!0).mod},i.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),s=1&e.words[0],o=n.cmp(r);if(o<0||1===s&&0===o)return t.div;var a=new i(1);return a.negative=this.negative^e.negative,t.div.iadd(a)},i.prototype.modrn=function(e){var t=e<0;t&&(e=-e),n(e<=67108863);for(var r=(1<<26)%e,i=0,s=this.length-1;s>=0;s--)i=(r*i+(0|this.words[s]))%e;return t?-i:i},i.prototype.modn=function(e){return this.modrn(e)},i.prototype.idivn=function(e){var t=e<0;t&&(e=-e),n(e<=67108863);for(var r=0,i=this.length-1;i>=0;i--){var s=(0|this.words[i])+67108864*r;this.words[i]=s/e|0,r=s%e}return this._strip(),t?this.ineg():this},i.prototype.divn=function(e){return this.clone().idivn(e)},i.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 s=new i(1),o=new i(0),a=new i(0),c=new i(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;)(s.isOdd()||o.isOdd())&&(s.iadd(u),o.isub(d)),s.iushrn(1),o.iushrn(1);for(var f=0,m=1;0===(r.words[0]&m)&&f<26;++f,m<<=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),s.isub(a),o.isub(c)):(r.isub(t),a.isub(s),c.isub(o))}return{a:a,b:c,gcd:r.iushln(l)}},i.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 s,o=new i(1),a=new i(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(s=0===t.cmpn(1)?o:a).cmpn(0)<0&&s.iadd(e),s},i.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 i=t.cmp(n);if(i<0){var s=t;t=n,n=s}else if(0===i||0===n.cmpn(1))break;t.isub(n)}return n.iushln(r)},i.prototype.invm=function(e){return this.egcd(e).a.umod(e)},i.prototype.isEven=function(){return!(1&this.words[0])},i.prototype.isOdd=function(){return!(1&~this.words[0])},i.prototype.andln=function(e){return this.words[0]&e},i.prototype.bincn=function(e){n("number"==typeof e);var t=e%26,r=(e-t)/26,i=1<<t;if(this.length<=r)return this._expand(r+1),this.words[r]|=i,this;for(var s=i,o=r;0!==s&&o<this.length;o++){var a=0|this.words[o];s=(a+=s)>>>26,a&=67108863,this.words[o]=a}return 0!==s&&(this.words[o]=s,this.length++),this},i.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},i.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 i=0|this.words[0];t=i===e?0:i<e?-1:1}return 0!==this.negative?0|-t:t},i.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},i.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],i=0|e.words[n];if(r!==i){r<i?t=-1:r>i&&(t=1);break}}return t},i.prototype.gtn=function(e){return 1===this.cmpn(e)},i.prototype.gt=function(e){return 1===this.cmp(e)},i.prototype.gten=function(e){return this.cmpn(e)>=0},i.prototype.gte=function(e){return this.cmp(e)>=0},i.prototype.ltn=function(e){return-1===this.cmpn(e)},i.prototype.lt=function(e){return-1===this.cmp(e)},i.prototype.lten=function(e){return this.cmpn(e)<=0},i.prototype.lte=function(e){return this.cmp(e)<=0},i.prototype.eqn=function(e){return 0===this.cmpn(e)},i.prototype.eq=function(e){return 0===this.cmp(e)},i.red=function(e){return new S(e)},i.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)},i.prototype.fromRed=function(){return n(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},i.prototype._forceRed=function(e){return this.red=e,this},i.prototype.forceRed=function(e){return n(!this.red,"Already a number in reduction context"),this._forceRed(e)},i.prototype.redAdd=function(e){return n(this.red,"redAdd works only with red numbers"),this.red.add(this,e)},i.prototype.redIAdd=function(e){return n(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,e)},i.prototype.redSub=function(e){return n(this.red,"redSub works only with red numbers"),this.red.sub(this,e)},i.prototype.redISub=function(e){return n(this.red,"redISub works only with red numbers"),this.red.isub(this,e)},i.prototype.redShl=function(e){return n(this.red,"redShl works only with red numbers"),this.red.shl(this,e)},i.prototype.redMul=function(e){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.mul(this,e)},i.prototype.redIMul=function(e){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.imul(this,e)},i.prototype.redSqr=function(){return n(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},i.prototype.redISqr=function(){return n(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},i.prototype.redSqrt=function(){return n(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},i.prototype.redInvm=function(){return n(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},i.prototype.redNeg=function(){return n(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},i.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 i(t,16),this.n=this.p.bitLength(),this.k=new i(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 k(){v.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function S(e){if("string"==typeof e){var t=i._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){S.call(this,e),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new i(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 i(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),i=0;i<r;i++)t.words[i]=e.words[i];if(t.length=r,e.length<=9)return e.words[0]=0,void(e.length=1);var s=e.words[9];for(t.words[t.length++]=s&n,i=10;i<e.length;i++){var o=0|e.words[i];e.words[i-10]=(o&n)<<4|s>>>22,s=o}s>>>=22,e.words[i-10]=s,0===s&&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(k,v),k.prototype.imulK=function(e){for(var t=0,n=0;n<e.length;n++){var r=19*(0|e.words[n])+t,i=67108863&r;r>>>=26,e.words[n]=i,t=r}return 0!==t&&(e.words[e.length++]=t),e},i._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 k}return b[e]=t,t},S.prototype._verify1=function(e){n(0===e.negative,"red works only with positives"),n(e.red,"red works only with red numbers")},S.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")},S.prototype.imod=function(e){return this.prime?this.prime.ireduce(e)._forceRed(this):(l(e,e.umod(this.m)._forceRed(this)),e)},S.prototype.neg=function(e){return e.isZero()?e.clone():this.m.sub(e)._forceRed(this)},S.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)},S.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},S.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)},S.prototype.isub=function(e,t){this._verify2(e,t);var n=e.isub(t);return n.cmpn(0)<0&&n.iadd(this.m),n},S.prototype.shl=function(e,t){return this._verify1(e),this.imod(e.ushln(t))},S.prototype.imul=function(e,t){return this._verify2(e,t),this.imod(e.imul(t))},S.prototype.mul=function(e,t){return this._verify2(e,t),this.imod(e.mul(t))},S.prototype.isqr=function(e){return this.imul(e,e.clone())},S.prototype.sqr=function(e){return this.mul(e,e)},S.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 i(1)).iushrn(2);return this.pow(e,r)}for(var s=this.m.subn(1),o=0;!s.isZero()&&0===s.andln(1);)o++,s.iushrn(1);n(!s.isZero());var a=new i(1).toRed(this),c=a.redNeg(),l=this.m.subn(1).iushrn(1),u=this.m.bitLength();for(u=new i(2*u*u).toRed(this);0!==this.pow(u,l).cmp(c);)u.redIAdd(c);for(var d=this.pow(u,s),h=this.pow(e,s.addn(1).iushrn(1)),g=this.pow(e,s),f=o;0!==g.cmp(a);){for(var m=g,p=0;0!==m.cmp(a);p++)m=m.redSqr();n(p<f);var y=this.pow(d,new i(1).iushln(f-p-1));h=h.redMul(y),d=y.redSqr(),g=g.redMul(d),f=p}return h},S.prototype.invm=function(e){var t=e._invmp(this.m);return 0!==t.negative?(t.negative=0,this.imod(t).redNeg()):this.imod(t)},S.prototype.pow=function(e,t){if(t.isZero())return new i(1).toRed(this);if(0===t.cmpn(1))return e.clone();var n=new Array(16);n[0]=new i(1).toRed(this),n[1]=e;for(var r=2;r<n.length;r++)n[r]=this.mul(n[r-1],e);var s=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;s!==n[0]&&(s=this.sqr(s)),0!==d||0!==o?(o<<=1,o|=d,(4===++a||0===r&&0===u)&&(s=this.mul(s,n[o]),a=0,o=0)):a=0}c=26}return s},S.prototype.convertTo=function(e){var t=e.umod(this.m);return t===e?t.clone():t},S.prototype.convertFrom=function(e){var t=e.clone();return t.red=null,t},i.mont=function(e){return new T(e)},r(T,S),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),i=n.isub(r).iushrn(this.shift),s=i;return i.cmp(this.m)>=0?s=i.isub(this.m):i.cmpn(0)<0&&(s=i.iadd(this.m)),s._forceRed(this)},T.prototype.mul=function(e,t){if(e.isZero()||t.isZero())return new i(0)._forceRed(this);var n=e.mul(t),r=n.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),s=n.isub(r).iushrn(this.shift),o=s;return s.cmp(this.m)>=0?o=s.isub(this.m):s.cmpn(0)<0&&(o=s.iadd(this.m)),o._forceRed(this)},T.prototype.invm=function(e){return this.imod(e._invmp(this.m).mul(this.r2))._forceRed(this)}}($l,Gl)),$l.exports}var Wl,ql,jl,Vl,zl,Xl=na(Hl()),Jl={exports:{}};function Yl(){return Wl||(Wl=1,function(e,t){var n=ha(),r=n.Buffer;function i(e,t){for(var n in e)t[n]=e[n]}function s(e,t,n){return r(e,t,n)}r.from&&r.alloc&&r.allocUnsafe&&r.allocUnsafeSlow?e.exports=n:(i(n,t),t.Buffer=s),s.prototype=Object.create(r.prototype),i(r,s),s.from=function(e,t,n){if("number"==typeof e)throw new TypeError("Argument must not be a number");return r(e,t,n)},s.alloc=function(e,t,n){if("number"!=typeof e)throw new TypeError("Argument must be a number");var i=r(e);return void 0!==t?"string"==typeof n?i.fill(t,n):i.fill(t):i.fill(0),i},s.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return r(e)},s.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return n.SlowBuffer(e)}}(Jl,Jl.exports)),Jl.exports}function Ql(){if(jl)return ql;jl=1;var e=Yl().Buffer;return ql=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 i=0;i<t.length;i++){var s=t.charAt(i),o=s.charCodeAt(0);if(255!==n[o])throw new TypeError(s+" is ambiguous");n[o]=i}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,i=0,s=0;t[r]===c;)i++,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<s)&&-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");s=g,r++}for(var m=o-s;m!==o&&0===u[m];)m++;var p=e.allocUnsafe(i+(o-m));p.fill(0,0,i);for(var y=i;m!==o;)p[y++]=u[m++];return p}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,i=0,s=0,o=n.length;s!==o&&0===n[s];)s++,r++;for(var l=(o-s)*u+1>>>0,d=new Uint8Array(l);s!==o;){for(var h=n[s],g=0,f=l-1;(0!==h||g<i)&&-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");i=g,s++}for(var m=l-i;m!==l&&0===d[m];)m++;for(var p=c.repeat(r);m<l;++m)p+=t.charAt(d[m]);return p},decodeUnsafe:d,decode:function(e){var t=d(e);if(t)return t;throw new Error("Non-base"+a+" character")}}},ql}function Zl(){if(zl)return Vl;zl=1;return Vl=Ql()("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")}var eu=na(Zl());const tu=mc;var nu={};function ru(e,t,n){return t<=e&&e<=n}function iu(e){if(void 0===e)return{};if(e===Object(e))return e;throw TypeError("Could not convert argument to dictionary")}function su(e){this.tokens=[].slice.call(e)}su.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 ou=-1;function au(e,t){if(e)throw TypeError("Decoder error");return t||65533}var cu="utf-8";function lu(e,t){if(!(this instanceof lu))return new lu(e,t);if((e=void 0!==e?String(e).toLowerCase():cu)!==cu)throw new Error("Encoding not supported. Only utf-8 is supported");t=iu(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 uu(e,t){if(!(this instanceof uu))return new uu(e,t);if((e=void 0!==e?String(e).toLowerCase():cu)!==cu)throw new Error("Encoding not supported. Only utf-8 is supported");t=iu(t),this._streaming=!1,this._encoder=null,this._options={fatal:Boolean(t.fatal)},Object.defineProperty(this,"encoding",{value:"utf-8"})}function du(e){var t=e.fatal,n=0,r=0,i=0,s=128,o=191;this.handler=function(e,a){if(-1===a&&0!==i)return i=0,au(t);if(-1===a)return ou;if(0===i){if(ru(a,0,127))return a;if(ru(a,194,223))i=1,n=a-192;else if(ru(a,224,239))224===a&&(s=160),237===a&&(o=159),i=2,n=a-224;else{if(!ru(a,240,244))return au(t);240===a&&(s=144),244===a&&(o=143),i=3,n=a-240}return n<<=6*i,null}if(!ru(a,s,o))return n=i=r=0,s=128,o=191,e.prepend(a),au(t);if(s=128,o=191,n+=a-128<<6*(i-(r+=1)),r!==i)return null;var c=n;return n=i=r=0,c}}function hu(e){e.fatal,this.handler=function(e,t){if(-1===t)return ou;if(ru(t,0,127))return t;var n,r;ru(t,128,2047)?(n=1,r=192):ru(t,2048,65535)?(n=2,r=224):ru(t,65536,1114111)&&(n=3,r=240);for(var i=[(t>>6*n)+r];n>0;){var s=t>>6*(n-1);i.push(128|63&s),n-=1}return i}}lu.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=iu(t),this._streaming||(this._decoder=new du({fatal:this._fatal}),this._BOMseen=!1),this._streaming=Boolean(t.stream);for(var r,i=new su(n),s=[];!i.endOfStream()&&(r=this._decoder.handler(i,i.read()))!==ou;)null!==r&&(Array.isArray(r)?s.push.apply(s,r):s.push(r));if(!this._streaming){do{if((r=this._decoder.handler(i,i.read()))===ou)break;null!==r&&(Array.isArray(r)?s.push.apply(s,r):s.push(r))}while(!i.endOfStream());this._decoder=null}return s.length&&(-1===["utf-8"].indexOf(this.encoding)||this._ignoreBOM||this._BOMseen||(65279===s[0]?(this._BOMseen=!0,s.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}(s)}},uu.prototype={encode:function(e,t){e=e?String(e):"",t=iu(t),this._streaming||(this._encoder=new hu(this._options)),this._streaming=Boolean(t.stream);for(var n,r=[],i=new su(function(e){for(var t=String(e),n=t.length,r=0,i=[];r<n;){var s=t.charCodeAt(r);if(s<55296||s>57343)i.push(s);else if(56320<=s&&s<=57343)i.push(65533);else if(55296<=s&&s<=56319)if(r===n-1)i.push(65533);else{var o=e.charCodeAt(r+1);if(56320<=o&&o<=57343){var a=1023&s,c=1023&o;i.push(65536+(a<<10)+c),r+=1}else i.push(65533)}r+=1}return i}(e));!i.endOfStream()&&(n=this._encoder.handler(i,i.read()))!==ou;)Array.isArray(n)?r.push.apply(r,n):r.push(n);if(!this._streaming){for(;(n=this._encoder.handler(i,i.read()))!==ou;)Array.isArray(n)?r.push.apply(r,n):r.push(n);this._encoder=null}return new Uint8Array(r)}};var gu,fu=ra(Object.freeze({__proto__:null,TextDecoder:lu,TextEncoder:uu}));function mu(){if(gu)return nu;gu=1;var e=nu&&nu.__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=nu&&nu.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=nu&&nu.__decorate||function(e,t,n,r){var i,s=arguments.length,o=s<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--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,n,o):i(t,n))||o);return s>3&&o&&Object.defineProperty(t,n,o),o},r=nu&&nu.__importStar||function(n){if(n&&n.__esModule)return n;var r={};if(null!=n)for(var i in n)"default"!==i&&Object.hasOwnProperty.call(n,i)&&e(r,n,i);return t(r,n),r},i=nu&&nu.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(nu,"__esModule",{value:!0}),nu.deserializeUnchecked=nu.deserialize=nu.serialize=nu.BinaryReader=nu.BinaryWriter=nu.BorshError=nu.baseDecode=nu.baseEncode=void 0;const s=i(Hl()),o=i(Zl()),a=r(fu),c=new("function"!=typeof TextDecoder?a.TextDecoder:TextDecoder)("utf-8",{fatal:!0});nu.baseEncode=function(e){return"string"==typeof e&&(e=Buffer.from(e,"utf8")),o.default.encode(Buffer.from(e))},nu.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(".")}}nu.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 s.default(e).toArray("le",8)))}writeU128(e){this.maybeResize(),this.writeBuffer(Buffer.from(new s.default(e).toArray("le",16)))}writeU256(e){this.maybeResize(),this.writeBuffer(Buffer.from(new s.default(e).toArray("le",32)))}writeU512(e){this.maybeResize(),this.writeBuffer(Buffer.from(new s.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}}}nu.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 s.default(e,"le")}readU128(){const e=this.readBuffer(16);return new s.default(e,"le")}readU256(){const e=this.readBuffer(32);return new s.default(e,"le")}readU512(){const e=this.readBuffer(64);return new s.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 m(e,t,n,r,i){try{if("string"==typeof r)i[`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`);i.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++)m(e,null,n[t],r[0],i)}else i.writeArray(n,n=>{m(e,t,n,r[0],i)});else if(void 0!==r.kind)switch(r.kind){case"option":null==n?i.writeU8(0):(i.writeU8(1),m(e,t,n,r.type,i));break;case"map":i.writeU32(n.size),n.forEach((n,s)=>{m(e,t,s,r.key,i),m(e,t,n,r.value,i)});break;default:throw new u(`FieldType ${r} unrecognized`)}else p(e,n,i)}catch(e){throw e instanceof u&&e.addToFieldPath(t),e}}function p(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,i])=>{m(e,r,t[r],i,n)});else{if("enum"!==r.kind)throw new u(`Unexpected schema kind: ${r.kind} for ${t.constructor.name}`);{const i=t[r.field];for(let s=0;s<r.values.length;++s){const[o,a]=r.values[s];if(o===i){n.writeU8(s),m(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 i=0;i<n[1];i++)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 i=new Map;const s=r.readU32();for(let o=0;o<s;o++){const s=y(e,t,n.key,r),o=y(e,t,n.value,r);i.set(s,o)}return i}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[i,s]of e.get(t).fields)r[i]=y(e,i,s,n);return new t(r)}if("enum"===r.kind){const i=n.readU8();if(i>=r.values.length)throw new u(`Enum index: ${i} is out of range`);const[s,o]=r.values[i],a=y(e,s,o,n);return new t({[s]: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),nu.BinaryReader=g,nu.serialize=function(e,t,n=d){const r=new n;return p(e,t,r),r.toArray()},nu.deserialize=function(e,t,n,r=g){const i=new r(n),s=b(e,t,i);if(i.offset<n.length)throw new u(`Unexpected ${n.length-i.offset} bytes after deserialized data`);return s},nu.deserializeUnchecked=function(e,t,n,r=g){return b(e,t,new r(n))},nu}var pu,yu=mu(),bu={};function vu(){if(pu)return bu;pu=1,Object.defineProperty(bu,"__esModule",{value:!0}),bu.s16=bu.s8=bu.nu64be=bu.u48be=bu.u40be=bu.u32be=bu.u24be=bu.u16be=bu.nu64=bu.u48=bu.u40=bu.u32=bu.u24=bu.u16=bu.u8=bu.offset=bu.greedy=bu.Constant=bu.UTF8=bu.CString=bu.Blob=bu.Boolean=bu.BitField=bu.BitStructure=bu.VariantLayout=bu.Union=bu.UnionLayoutDiscriminator=bu.UnionDiscriminator=bu.Structure=bu.Sequence=bu.DoubleBE=bu.Double=bu.FloatBE=bu.Float=bu.NearInt64BE=bu.NearInt64=bu.NearUInt64BE=bu.NearUInt64=bu.IntBE=bu.Int=bu.UIntBE=bu.UInt=bu.OffsetLayout=bu.GreedyCount=bu.ExternalLayout=bu.bindConstructorLayout=bu.nameWithProperty=bu.Layout=bu.uint8ArrayToBuffer=bu.checkUint8Array=void 0,bu.constant=bu.utf8=bu.cstr=bu.blob=bu.unionLayoutDiscriminator=bu.union=bu.seq=bu.bits=bu.struct=bu.f64be=bu.f64=bu.f32be=bu.f32=bu.ns64be=bu.s48be=bu.s40be=bu.s32be=bu.s24be=bu.s16be=bu.ns64=bu.s48=bu.s40=bu.s32=bu.s24=void 0;const e=ha();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)}bu.checkUint8Array=t,bu.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 i(e,t){return t.property?e+"["+t.property+"]":e}bu.Layout=r,bu.nameWithProperty=i,bu.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 s extends r{isCount(){throw new Error("ExternalLayout is abstract")}}bu.ExternalLayout=s;class o extends s{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}}bu.GreedyCount=o;class a extends s{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)}}bu.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}}bu.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}}bu.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}}bu.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}}bu.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 m extends r{constructor(e){super(8,e)}decode(e,t=0){const r=n(e),i=r.readUInt32LE(t);return f(r.readUInt32LE(t+4),i)}encode(e,t,r=0){const i=g(e),s=n(t);return s.writeUInt32LE(i.lo32,r),s.writeUInt32LE(i.hi32,r+4),8}}bu.NearUInt64=m;class p 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 i=g(e),s=n(t);return s.writeUInt32BE(i.hi32,r),s.writeUInt32BE(i.lo32,r+4),8}}bu.NearUInt64BE=p;class y extends r{constructor(e){super(8,e)}decode(e,t=0){const r=n(e),i=r.readUInt32LE(t);return f(r.readInt32LE(t+4),i)}encode(e,t,r=0){const i=g(e),s=n(t);return s.writeUInt32LE(i.lo32,r),s.writeInt32LE(i.hi32,r+4),8}}bu.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 i=g(e),s=n(t);return s.writeInt32BE(i.hi32,r),s.writeUInt32BE(i.lo32,r+4),8}}bu.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}}bu.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}}bu.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}}bu.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}}bu.DoubleBE=A;class k extends r{constructor(e,t,n){if(!(e instanceof r))throw new TypeError("elementLayout must be a Layout");if(!(t instanceof s&&t.isCount()||Number.isInteger(t)&&0<=t))throw new TypeError("count must be non-negative integer or an unsigned integer ExternalLayout");let i=-1;!(t instanceof s)&&0<e.span&&(i=t*e.span),super(i,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 s&&(r=r.decode(e,t)),0<this.elementLayout.span)n=r*this.elementLayout.span;else{let i=0;for(;i<r;)n+=this.elementLayout.getSpan(e,t+n),++i}return n}decode(e,t=0){const n=[];let r=0,i=this.count;for(i instanceof s&&(i=i.decode(e,t));r<i;)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,i=e.reduce((e,i)=>e+r.encode(i,t,n+e),0);return this.count instanceof s&&this.count.encode(e.length,t,n),i}}bu.Sequence=k;class S 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 i=-1;try{i=e.reduce((e,t)=>e+t.getSpan(),0)}catch(e){}super(i,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 i=r.getSpan(e,t);return t+=i,n+i},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 i=0,s=0;for(const r of this.fields){let o=r.span;if(s=0<o?o:0,void 0!==r.property){const i=e[r.property];void 0!==i&&(s=r.encode(i,t,n),0>o&&(o=r.getSpan(t,n)))}i=n,n+=o}return i+s-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)}}}bu.Structure=S;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")}}bu.UnionDiscriminator=T;class I extends T{constructor(e,t){if(!(e instanceof s&&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)}}bu.UnionLayoutDiscriminator=I;class N extends r{constructor(e,t,n){let i;if(e instanceof c||e instanceof l)i=new I(new a(e));else if(e instanceof s&&e.isCount())i=new I(e);else{if(!(e instanceof T))throw new TypeError("discr must be a UnionDiscriminator or an unsigned integer layout");i=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+=i.layout.span)),super(o,n),this.discriminator=i,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,i=r.decode(e,t),s=this.registry[i];if(void 0===s){const s=this.defaultLayout;let o=0;this.usesPrefixDiscriminator&&(o=r.layout.span),n=this.makeDestinationObject(),n[r.property]=i,n[s.property]=s.decode(e,t+o)}else n=s.decode(e,t);return n}encode(e,t,n=0){const r=this.getSourceVariant(e);if(void 0===r){const r=this.discriminator,i=this.defaultLayout;let s=0;return this.usesPrefixDiscriminator&&(s=r.layout.span),r.encode(e[r.property],t,n),s+i.encode(e[i.property],t,n+s)}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]}}bu.Union=N;class C extends r{constructor(e,t,n,i){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===i&&(i=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 i)throw new TypeError("variant must have a String property")}let s=e.span;0>e.span&&(s=n?n.span:0,0<=s&&e.usesPrefixDiscriminator&&(s+=e.discriminator.layout.span)),super(s,i),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 i=r;if(this.layout&&(this.layout.encode(e[this.property],t,n+r),i+=this.layout.getSpan(t,n+r),0<=this.union.span&&i>this.union.span))throw new Error("encoded variant overruns containing union");return i}fromArray(e){if(this.layout)return this.layout.fromArray(e)}}function _(e){return 0>e&&(e+=4294967296),e}bu.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}}bu.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,i=e.fields.reduce((e,t)=>e+t.bits,0);if(t+i>r)throw new Error("bits too long for span remainder ("+(r-i)+" of "+r+" remain)");this.container=e,this.bits=t,this.valueMask=(1<<t)-1,32===t&&(this.valueMask=4294967295),this.start=i,this.container.msb&&(this.start=r-i-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(i("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)}}bu.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)}}bu.Boolean=B;class D extends r{constructor(e,t){if(!(e instanceof s&&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 s||(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 s&&(o=e.length),!(e instanceof Uint8Array&&o===e.length))throw new TypeError(i("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 s&&this.length.encode(o,t,r),o}}bu.Blob=D;class M 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,i=0){"string"!=typeof t&&(t=String(t));const s=e.Buffer.from(t,"utf8"),o=s.length;if(i+o>r.length)throw new RangeError("encoding overruns Buffer");const a=n(r);return s.copy(a,i),a[i+o]=0,o+1}}bu.CString=M;class O 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,i=0){"string"!=typeof t&&(t=String(t));const s=e.Buffer.from(t,"utf8"),o=s.length;if(0<=this.maxSpan&&this.maxSpan<o)throw new RangeError("text length exceeds maxSpan");if(i+o>r.length)throw new RangeError("encoding overruns Buffer");return s.copy(n(r),i),o}}bu.UTF8=O;class U extends r{constructor(e,t){super(0,t),this.value=e}decode(e,t){return this.value}encode(e,t,n){return 0}}return bu.Constant=U,bu.greedy=(e,t)=>new o(e,t),bu.offset=(e,t,n)=>new a(e,t,n),bu.u8=e=>new c(1,e),bu.u16=e=>new c(2,e),bu.u24=e=>new c(3,e),bu.u32=e=>new c(4,e),bu.u40=e=>new c(5,e),bu.u48=e=>new c(6,e),bu.nu64=e=>new m(e),bu.u16be=e=>new l(2,e),bu.u24be=e=>new l(3,e),bu.u32be=e=>new l(4,e),bu.u40be=e=>new l(5,e),bu.u48be=e=>new l(6,e),bu.nu64be=e=>new p(e),bu.s8=e=>new u(1,e),bu.s16=e=>new u(2,e),bu.s24=e=>new u(3,e),bu.s32=e=>new u(4,e),bu.s40=e=>new u(5,e),bu.s48=e=>new u(6,e),bu.ns64=e=>new y(e),bu.s16be=e=>new d(2,e),bu.s24be=e=>new d(3,e),bu.s32be=e=>new d(4,e),bu.s40be=e=>new d(5,e),bu.s48be=e=>new d(6,e),bu.ns64be=e=>new b(e),bu.f32=e=>new v(e),bu.f32be=e=>new w(e),bu.f64=e=>new E(e),bu.f64be=e=>new A(e),bu.struct=(e,t,n)=>new S(e,t,n),bu.bits=(e,t,n)=>new x(e,t,n),bu.seq=(e,t,n)=>new k(e,t,n),bu.union=(e,t,n)=>new N(e,t,n),bu.unionLayoutDiscriminator=(e,t)=>new I(e,t),bu.blob=(e,t)=>new D(e,t),bu.cstr=e=>new M(e),bu.utf8=(e,t)=>new O(e,t),bu.constant=(e,t)=>new U(e,t),bu}var wu=vu(),Eu=1,Au=2,ku=3,Su=4,Tu=5,Iu=6,Nu=7,Cu=8,_u=9,xu=10,Ru=-32700,Bu=-32603,Du=-32602,Mu=-32601,Ou=-32600,Uu=-32019,Lu=-32018,Pu=-32017,Fu=-32016,$u=-32015,Ku=-32014,Gu=-32013,Hu=-32012,Wu=-32011,qu=-32010,ju=-32009,Vu=-32008,zu=-32007,Xu=-32006,Ju=-32005,Yu=-32004,Qu=-32003,Zu=-32002,ed=-32001,td=28e5,nd=2800001,rd=2800002,id=2800003,sd=2800004,od=2800005,ad=2800006,cd=2800007,ld=2800008,ud=2800009,dd=2800010,hd=2800011,gd=323e4,fd=32300001,md=3230002,pd=3230003,yd=3230004,bd=361e4,vd=3610001,wd=3610002,Ed=3610003,Ad=3610004,kd=3610005,Sd=3610006,Td=3610007,Id=3611e3,Nd=3704e3,Cd=3704001,_d=3704002,xd=3704003,Rd=3704004,Bd=4128e3,Dd=4128001,Md=4128002,Od=4615e3,Ud=4615001,Ld=4615002,Pd=4615003,Fd=4615004,$d=4615005,Kd=4615006,Gd=4615007,Hd=4615008,Wd=4615009,qd=4615010,jd=4615011,Vd=4615012,zd=4615013,Xd=4615014,Jd=4615015,Yd=4615016,Qd=4615017,Zd=4615018,eh=4615019,th=4615020,nh=4615021,rh=4615022,ih=4615023,sh=4615024,oh=4615025,ah=4615026,ch=4615027,lh=4615028,uh=4615029,dh=4615030,hh=4615031,gh=4615032,fh=4615033,mh=4615034,ph=4615035,yh=4615036,bh=4615037,vh=4615038,wh=4615039,Eh=4615040,Ah=4615041,kh=4615042,Sh=4615043,Th=4615044,Ih=4615045,Nh=4615046,Ch=4615047,_h=4615048,xh=4615049,Rh=4615050,Bh=4615051,Dh=4615052,Mh=4615053,Oh=4615054,Uh=5508e3,Lh=5508001,Ph=5508002,Fh=5508003,$h=5508004,Kh=5508005,Gh=5508006,Hh=5508007,Wh=5508008,qh=5508009,jh=5508010,Vh=5508011,zh=5607e3,Xh=5607001,Jh=5607002,Yh=5607003,Qh=5607004,Zh=5607005,eg=5607006,tg=5607007,ng=5607008,rg=5607009,ig=5607010,sg=5607011,og=5607012,ag=5607013,cg=5607014,lg=5607015,ug=5607016,dg=5607017,hg=5663e3,gg=5663001,fg=5663002,mg=5663003,pg=5663004,yg=5663005,bg=5663006,vg=5663007,wg=5663008,Eg=5663009,Ag=5663010,kg=5663011,Sg=5663012,Tg=5663013,Ig=5663014,Ng=5663015,Cg=5663016,_g=5663017,xg=5663018,Rg=5663019,Bg=5663020,Dg=5663021,Mg=5663022,Og=705e4,Ug=7050001,Lg=7050002,Pg=7050003,Fg=7050004,$g=7050005,Kg=7050006,Gg=7050007,Hg=7050008,Wg=7050009,qg=7050010,jg=7050011,Vg=7050012,zg=7050013,Xg=7050014,Jg=7050015,Yg=7050016,Qg=7050017,Zg=7050018,ef=7050019,tf=7050020,nf=7050021,rf=7050022,sf=7050023,of=7050024,af=7050025,cf=7050026,lf=7050027,uf=7050028,df=7050029,hf=7050030,gf=7050031,ff=7050032,mf=7050033,pf=7050034,yf=7050035,bf=7050036,vf=7618e3,wf=7618001,Ef=7618002,Af=7618003,kf=7618004,Sf=7618005,Tf=7618006,If=7618007,Nf=7618008,Cf=7618009,_f=8078e3,xf=8078001,Rf=8078002,Bf=8078003,Df=8078004,Mf=8078005,Of=8078006,Uf=8078007,Lf=8078008,Pf=8078009,Ff=8078010,$f=8078011,Kf=8078012,Gf=8078013,Hf=8078014,Wf=8078015,qf=8078016,jf=8078017,Vf=8078018,zf=8078019,Xf=8078020,Jf=8078021,Yf=8078022,Qf=8078023,Zf=81e5,em=8100001,tm=8100002,nm=8100003,rm=819e4,im=8190001,sm=8190002,om=8190003,am=8190004,cm=99e5,lm=9900001,um=9900002,dm=9900003,hm=9900004,gm=9900005,fm=9900006;function mm(e){if(Array.isArray(e)){return"%5B"+e.map(mm).join("%2C%20")+"%5D"}return"bigint"==typeof e?`${e}n`:encodeURIComponent(String(null!=e&&null===Object.getPrototypeOf(e)?{...e}:e))}function pm([e,t]){return`${e}=${mm(t)}`}var ym={[gd]:"Account not found at address: $address",[yd]:"Not all accounts were decoded. Encoded accounts found at addresses: $addresses.",[pd]:"Expected decoded account at address: $address",[md]:"Failed to decode account data at address: $address",[fd]:"Accounts not found at addresses: $addresses",[ud]:"Unable to find a viable program address bump seed.",[rd]:"$putativeAddress is not a base58-encoded address.",[td]:"Expected base58 encoded address to decode to a byte array of length 32. Actual length: $actualLength.",[id]:"The `CryptoKey` must be an `Ed25519` public key.",[hd]:"$putativeOffCurveAddress is not a base58-encoded off-curve address.",[ld]:"Invalid seeds; point must fall off the Ed25519 curve.",[sd]:"Expected given program derived address to have the following format: [Address, ProgramDerivedAddressBump].",[ad]:"A maximum of $maxSeeds seeds, including the bump seed, may be supplied when creating an address. Received: $actual.",[cd]:"The seed at index $index with length $actual exceeds the maximum length of $maxSeedLength bytes.",[od]:"Expected program derived address bump to be in the range [0, 255], got: $bump.",[dd]:"Program address cannot end with PDA marker.",[nd]:"Expected base58-encoded address string of length in the range [32, 44]. Actual length: $actualLength.",[Su]:"Expected base58-encoded blockash string of length in the range [32, 44]. Actual length: $actualLength.",[Eu]:"The network has progressed past the last block for which this transaction could have been committed.",[_f]:"Codec [$codecDescription] cannot decode empty byte arrays.",[Yf]:"Enum codec cannot use lexical values [$stringValues] as discriminators. Either remove all lexical values or set `useValuesAsDiscriminators` to `false`.",[Xf]:"Sentinel [$hexSentinel] must not be present in encoded bytes [$hexEncodedBytes].",[Mf]:"Encoder and decoder must have the same fixed size, got [$encoderFixedSize] and [$decoderFixedSize].",[Of]:"Encoder and decoder must have the same max size, got [$encoderMaxSize] and [$decoderMaxSize].",[Df]:"Encoder and decoder must either both be fixed-size or variable-size.",[Lf]:"Enum discriminator out of range. Expected a number in [$formattedValidDiscriminators], got $discriminator.",[Rf]:"Expected a fixed-size codec, got a variable-size one.",[Gf]:"Codec [$codecDescription] expected a positive byte length, got $bytesLength.",[Bf]:"Expected a variable-size codec, got a fixed-size one.",[zf]:"Codec [$codecDescription] expected zero-value [$hexZeroValue] to have the same size as the provided fixed-size item [$expectedSize bytes].",[xf]:"Codec [$codecDescription] expected $expected bytes, got $bytesLength.",[Vf]:"Expected byte array constant [$hexConstant] to be present in data [$hexData] at offset [$offset].",[Pf]:"Invalid discriminated union variant. Expected one of [$variants], got $value.",[Ff]:"Invalid enum variant. Expected one of [$stringValues] or a number in [$formattedNumericalValues], got $variant.",[Wf]:"Invalid literal union variant. Expected one of [$variants], got $value.",[Uf]:"Expected [$codecDescription] to have $expected items, got $actual.",[Kf]:"Invalid value $value for base $base with alphabet $alphabet.",[qf]:"Literal union discriminator out of range. Expected a number between $minRange and $maxRange, got $discriminator.",[$f]:"Codec [$codecDescription] expected number to be in the range [$min, $max], got $value.",[Hf]:"Codec [$codecDescription] expected offset to be in the range [0, $bytesLength], got $offset.",[Jf]:"Expected sentinel [$hexSentinel] to be present in decoded bytes [$hexDecodedBytes].",[jf]:"Union variant out of range. Expected an index between $minRange and $maxRange, got $variant.",[Qf]:"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?",[Id]:"No random values implementation could be found.",[Wd]:"instruction requires an uninitialized account",[ih]:"instruction tries to borrow reference for an account which is already borrowed",[sh]:"instruction left account with an outstanding borrowed reference",[nh]:"program other than the account's owner changed the size of the account data",[$d]:"account data too small for instruction",[rh]:"instruction expected an executable account",[Nh]:"An account does not have enough lamports to be rent-exempt",[_h]:"Program arithmetic overflowed",[Ih]:"Failed to serialize or deserialize account data: $encodedData",[Oh]:"Builtin programs must consume compute units",[gh]:"Cross-program invocation call depth too deep",[vh]:"Computational budget exceeded",[ah]:"custom program error: #$code",[Qd]:"instruction contains duplicate accounts",[oh]:"instruction modifications of multiply-passed account differ",[dh]:"executable accounts must be rent exempt",[lh]:"instruction changed executable accounts data",[uh]:"instruction changed the balance of an executable account",[Zd]:"instruction changed executable bit of an account",[Xd]:"instruction modified data of an account it does not own",[zd]:"instruction spent from the balance of an account it does not own",[Ud]:"generic instruction error",[Rh]:"Provided owner is not allowed",[Sh]:"Account is immutable",[Th]:"Incorrect authority provided",[Gd]:"incorrect program id for instruction",[Kd]:"insufficient funds for instruction",[Fd]:"invalid account data for instruction",[Ch]:"Invalid account owner",[Ld]:"invalid program argument",[ch]:"program returned invalid error code",[Pd]:"invalid instruction data",[bh]:"Failed to reallocate account data",[yh]:"Provided seeds do not result in a valid address",[Bh]:"Accounts data allocations exceeded the maximum allowed per transaction",[Dh]:"Max accounts exceeded",[Mh]:"Max instruction trace length exceeded",[ph]:"Length of the seed is too long for address generation",[fh]:"An account required by the instruction is missing",[Hd]:"missing required signature for instruction",[Vd]:"instruction illegally modified the program id of an account",[th]:"insufficient account keys for instruction",[wh]:"Cross-program invocation with unauthorized signer or writable account",[Eh]:"Failed to create program execution environment",[kh]:"Program failed to compile",[Ah]:"Program failed to complete",[Yd]:"instruction modified data of a read-only account",[Jd]:"instruction changed the balance of a read-only account",[mh]:"Cross-program invocation reentrancy not allowed for this instruction",[eh]:"instruction modified rent epoch of an account",[jd]:"sum of account balances before and after instruction do not match",[qd]:"instruction requires an initialized account",[Od]:"",[hh]:"Unsupported program id",[xh]:"Unsupported sysvar",[gm]:"Invalid instruction plan kind: $kind.",[Ef]:"The provided instruction plan is empty.",[Sf]:"No failed transaction plan result was found in the provided transaction plan result.",[kf]:"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.",[Af]:"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.",[vf]:"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).",[fm]:"Invalid transaction plan kind: $kind.",[wf]:"No more instructions to pack; the message packer has completed the instruction plan.",[Tf]:"Unexpected instruction plan. Expected $expectedKind plan, got $actualKind plan.",[If]:"Unexpected transaction plan. Expected $expectedKind plan, got $actualKind plan.",[Nf]:"Unexpected transaction plan result. Expected $expectedKind plan, got $actualKind plan.",[Cf]:"Expected a successful transaction plan result. I.e. there is at least one failed or cancelled transaction in the plan.",[Bd]:"The instruction does not have any accounts.",[Dd]:"The instruction does not have any data.",[Md]:"Expected instruction to have progress address $expectedProgramAddress, got $actualProgramAddress.",[Tu]:"Expected base58 encoded blockhash to decode to a byte array of length 32. Actual length: $actualLength.",[Au]:"The nonce `$expectedNonceValue` is no longer valid. It has advanced to `$actualNonceValue`",[um]:"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",[hm]:"Invariant violation: This data publisher does not publish to the channel named `$channelName`. Supported channels include $supportedChannelNames.",[lm]:"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",[cm]:"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",[dm]:"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",[Bu]:"JSON-RPC error: Internal JSON-RPC error ($__serverMessage)",[Du]:"JSON-RPC error: Invalid method parameter(s) ($__serverMessage)",[Ou]:"JSON-RPC error: The JSON sent is not a valid `Request` object ($__serverMessage)",[Mu]:"JSON-RPC error: The method does not exist / is not available ($__serverMessage)",[Ru]:"JSON-RPC error: An error occurred on the server while parsing the JSON text ($__serverMessage)",[Hu]:"$__serverMessage",[ed]:"$__serverMessage",[Yu]:"$__serverMessage",[Ku]:"$__serverMessage",[Pu]:"Epoch rewards period still active at slot $slot",[qu]:"$__serverMessage",[ju]:"$__serverMessage",[Uu]:"Failed to query long-term storage; please try again",[Fu]:"Minimum context slot has not been reached",[Ju]:"Node is unhealthy; behind by $numSlotsBehind slots",[Vu]:"No snapshot",[Zu]:"Transaction simulation failed",[Lu]:"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",[zu]:"$__serverMessage",[Wu]:"Transaction history is not available from this node",[Xu]:"$__serverMessage",[Gu]:"Transaction signature length mismatch",[Qu]:"Transaction signature verification failure",[$u]:"$__serverMessage",[Nd]:"Key pair bytes must be of length 64, got $byteLength.",[Cd]:"Expected private key bytes with length 32. Actual length: $actualLength.",[_d]:"Expected base58-encoded signature to decode to a byte array of length 64. Actual length: $actualLength.",[Rd]:"The provided private key does not match the provided public key.",[xd]:"Expected base58-encoded signature string of length in the range [64, 88]. Actual length: $actualLength.",[Iu]:"Lamports value must be in the range [0, 2e64-1]",[Nu]:"`$value` cannot be parsed as a `BigInt`",[xu]:"$message",[Cu]:"`$value` cannot be parsed as a `Number`",[ku]:"No nonce account could be found at address `$nonceAccountAddress`",[Yh]:"Expected base58 encoded application domain to decode to a byte array of length 32. Actual length: $actualLength.",[ag]:"Attempted to sign an offchain message with an address that is not a signer for it",[Jh]:"Expected base58-encoded application domain string of length in the range [32, 44]. Actual length: $actualLength.",[og]:"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]`.",[zh]:"The message body provided has a byte-length of $actualBytes. The maximum allowable byte-length is $maxBytes",[tg]:"Expected message format $expectedMessageFormat, got $actualMessageFormat",[ng]:"The message length specified in the message preamble is $specifiedLength bytes. The actual length of the message is $actualLength bytes.",[rg]:"Offchain message content must be non-empty",[Zh]:"Offchain message must specify the address of at least one required signer",[ig]:"Offchain message envelope must reserve space for at least one signature",[Qh]:"The offchain message preamble specifies $numRequiredSignatures required signature(s), got $signaturesLength.",[lg]:"The signatories of this offchain message must be listed in lexicographical order",[ug]:"An address must be listed no more than once among the signatories of an offchain message",[sg]:"Offchain message is missing signatures for addresses: $addresses.",[dg]:"Offchain message signature verification failed. Signature mismatch for required signatories [$signatoriesWithInvalidSignatures]. Missing signatures for signatories [$signatoriesWithMissingSignatures]",[Xh]:"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].",[cg]:"Expected offchain message version $expectedVersion. Got $actualVersion.",[eg]:"This version of Kit does not support decoding offchain messages with version $unsupportedVersion. The current max supported version is 0.",[rm]:"The notification name must end in 'Notifications' and the API must supply a subscription plan creator function for the notification '$notificationName'.",[sm]:"WebSocket was closed before payload could be added to the send buffer",[om]:"WebSocket connection closed",[am]:"WebSocket failed to connect",[im]:"Failed to obtain a subscription id from the server",[nm]:"Could not find an API plan for RPC method: `$method`",[Zf]:"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`.",[tm]:"HTTP error ($statusCode): $message",[em]:"HTTP header(s) forbidden: $headers. Learn more at https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name.",[Uh]:"Multiple distinct signers were identified for address `$address`. Please ensure that you are using the same signer instance for each address.",[Lh]:"The provided value does not implement the `KeyPairSigner` interface",[Fh]:"The provided value does not implement the `MessageModifyingSigner` interface",[$h]:"The provided value does not implement the `MessagePartialSigner` interface",[Ph]:"The provided value does not implement any of the `MessageSigner` interfaces",[Gh]:"The provided value does not implement the `TransactionModifyingSigner` interface",[Hh]:"The provided value does not implement the `TransactionPartialSigner` interface",[Wh]:"The provided value does not implement the `TransactionSendingSigner` interface",[Kh]:"The provided value does not implement any of the `TransactionSigner` interfaces",[qh]:"More than one `TransactionSendingSigner` was identified.",[jh]:"No `TransactionSendingSigner` was identified. Please provide a valid `TransactionWithSingleSendingSigner` transaction.",[Vh]:"Wallet account signers do not support signing multiple messages/transactions in a single operation",[Td]:"Cannot export a non-extractable key.",[vd]:"No digest implementation could be found.",[bd]:"Cryptographic operations are only allowed in secure browser contexts. Read more here: https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts.",[wd]:"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.",[Ed]:"No signature verification implementation could be found.",[Ad]:"No key generation implementation could be found.",[kd]:"No signing implementation could be found.",[Sd]:"No key export implementation could be found.",[_u]:"Timestamp value must be in the range [-(2n ** 63n), (2n ** 63n) - 1]. `$value` given",[Yg]:"Transaction processing left an account with an outstanding borrowed reference",[Ug]:"Account in use",[Lg]:"Account loaded twice",[Pg]:"Attempt to debit an account but found no record of a prior credit.",[sf]:"Transaction loads an address table account that doesn't exist",[Gg]:"This transaction has already been processed",[Hg]:"Blockhash not found",[Wg]:"Loader call chain is too deep",[Jg]:"Transactions are currently disabled due to cluster maintenance",[hf]:"Transaction contains a duplicate instruction ($index) that is not allowed",[$g]:"Insufficient funds for fee",[gf]:"Transaction results in an account ($accountIndex) with insufficient funds for rent",[Kg]:"This account may not be used to pay transaction fees",[jg]:"Transaction contains an invalid account reference",[af]:"Transaction loads an address table account with invalid data",[cf]:"Transaction address table lookup uses an invalid index",[of]:"Transaction loads an address table account with an invalid owner",[mf]:"LoadedAccountsDataSizeLimit set for transaction must be greater than 0.",[zg]:"This program may not be used for executing instructions",[lf]:"Transaction leaves an account with a lower balance than rent-exempt minimum",[ef]:"Transaction loads a writable account that cannot be written",[ff]:"Transaction exceeded max loaded accounts data size cap",[qg]:"Transaction requires a fee but has no signature present",[Fg]:"Attempt to load a program that does not exist",[yf]:"Execution of the program referenced by account at index $accountIndex is temporarily restricted.",[pf]:"ResanitizationNeeded",[Xg]:"Transaction failed to sanitize accounts offsets correctly",[Vg]:"Transaction did not pass signature verification",[rf]:"Transaction locked too many accounts",[bf]:"Sum of account balances before and after transaction do not match",[Og]:"The transaction failed with the error `$errorName`",[Zg]:"Transaction version is unsupported",[nf]:"Transaction would exceed account data limit within the block",[df]:"Transaction would exceed total account data limit",[tf]:"Transaction would exceed max account limit within the block",[Qg]:"Transaction would exceed max Block Cost Limit",[uf]:"Transaction would exceed max Vote Cost Limit",[Ng]:"Attempted to sign a transaction with an address that is not a signer for it",[Ag]:"Transaction is missing an address at index: $index.",[Cg]:"Transaction has no expected signers therefore it cannot be encoded",[Bg]:"Transaction size $transactionSize exceeds limit of $transactionSizeLimit bytes",[fg]:"Transaction does not have a blockhash lifetime",[mg]:"Transaction is not a durable nonce transaction",[yg]:"Contents of these address lookup tables unknown: $lookupTableAddresses",[bg]:"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",[wg]:"No fee payer set in CompiledTransaction",[vg]:"Could not find program address at index $index",[xg]:"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",[Rg]:"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",[kg]:"Transaction is missing a fee payer.",[Sg]:"Could not determine this transaction's signature. Make sure that the transaction has been signed by its fee payer.",[Ig]:"Transaction first instruction is not advance nonce account instruction.",[Tg]:"Transaction with no instructions cannot be durable nonce transaction.",[hg]:"This transaction includes an address (`$programAddress`) which is both invoked and set as the fee payer. Program addresses may not pay fees",[gg]:"This transaction includes an address (`$programAddress`) which is both invoked and marked writable. Program addresses may not be writable",[_g]:"The transaction message expected the transaction to have $numRequiredSignatures signatures, got $signaturesLength.",[Eg]:"Transaction is missing signatures for addresses: $addresses.",[pg]:"Transaction version must be in the range [0, 127]. `$actualVersion` given",[Dg]:"This version of Kit does not support decoding transactions with version $unsupportedVersion. The current max supported version is 0.",[Mg]:"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."},bm="i",vm="t";function wm(e,t={}){if("production"!==process.env.NODE_ENV)return function(e,t={}){const n=ym[e];if(0===n.length)return"";let r;function i(e){if(2===r[vm]){const i=n.slice(r[bm]+1,e);s.push(i in t?`${t[i]}`:`$${i}`)}else 1===r[vm]&&s.push(n.slice(r[bm],e))}const s=[];return n.split("").forEach((e,t)=>{if(0===t)return void(r={[bm]:0,[vm]:"\\"===n[0]?0:"$"===n[0]?2:1});let s;switch(r[vm]){case 0:s={[bm]:t,[vm]:1};break;case 1:"\\"===e?s={[bm]:t,[vm]:0}:"$"===e&&(s={[bm]:t,[vm]:2});break;case 2:"\\"===e?s={[bm]:t,[vm]:0}:"$"===e?s={[bm]:t,[vm]:2}:e.match(/\w/)||(s={[bm]:t,[vm]:1})}s&&(r!==s&&i(t),r=s)}),i(),s.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(pm).join("&");return btoa(t)}(t)}'`),`${n}\``}}var Em=class extends Error{cause=this.cause;context;constructor(...[e,t]){let n,r;t&&Object.entries(Object.getOwnPropertyDescriptors(t)).forEach(([t,i])=>{"cause"===t?r={cause:i.value}:(void 0===n&&(n={__code:e}),Object.defineProperty(n,t,i))});super(wm(e,n),r),this.context=Object.freeze(void 0===n?{__code:e}:n),this.name="SolanaError"}};function Am(e){return"fixedSize"in e&&"number"==typeof e.fixedSize}function km(e){return 1!==e?.endian}function Sm(e){return t={fixedSize:e.size,write(t,n,r){e.range&&function(e,t,n,r){if(r<t||r>n)throw new Em($f,{codecDescription:e,max:n,min:t,value:r})}(e.name,e.range[0],e.range[1],t);const i=new ArrayBuffer(e.size);return e.set(new DataView(i),t,km(e.config)),n.set(new Uint8Array(i),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 Tm(e){return t={fixedSize:e.size,read(t,n=0){!function(e,t,n=0){if(t.length-n<=0)throw new Em(_f,{codecDescription:e})}(e.name,t,n),function(e,t,n,r=0){const i=n.length-r;if(i<t)throw new Em(xf,{bytesLength:i,codecDescription:e,expected:t})}(e.name,e.size,t,n);const r=new DataView(function(e,t,n){const r=e.byteOffset+(t??0),i=n??e.byteLength;let s;return"undefined"==typeof SharedArrayBuffer?s=e.buffer:e.buffer instanceof SharedArrayBuffer?(s=new ArrayBuffer(e.length),new Uint8Array(s).set(new Uint8Array(e))):s=e.buffer,0!==r&&r!==-e.byteLength||i!==e.byteLength?s.slice(r,r+i):s}(t,n,e.size));return[e.get(r,km(e.config)),n+e.size]}},Object.freeze({...t,decode:(e,n=0)=>t.read(e,n)[0]});var t}var Im=(e={})=>function(e,t){if(Am(e)!==Am(t))throw new Em(Df);if(Am(e)&&Am(t)&&e.fixedSize!==t.fixedSize)throw new Em(Mf,{decoderFixedSize:t.fixedSize,encoderFixedSize:e.fixedSize});if(!Am(e)&&!Am(t)&&e.maxSize!==t.maxSize)throw new Em(Of,{decoderMaxSize:t.maxSize,encoderMaxSize:e.maxSize});return{...t,...e,decode:t.decode,encode:e.encode,read:t.read,write:e.write}}(((e={})=>Sm({config:e,name:"u64",range:[0n,BigInt("0xffffffffffffffff")],set:(e,t,n)=>e.setBigUint64(0,BigInt(t),n),size:8}))(e),((e={})=>Tm({config:e,get:(e,t)=>e.getBigUint64(0,t),name:"u64",size:8}))(e));class Nm extends TypeError{constructor(e,t){let n;const{message:r,explanation:i,...s}=e,{path:o}=e,a=0===o.length?r:`At path: ${o.join(".")} -- ${r}`;super(i??a),null!=i&&(this.cause=a),Object.assign(this,s),this.name=this.constructor.name,this.failures=()=>n??(n=[e,...t()])}}function Cm(e){return"object"==typeof e&&null!=e}function _m(e){return Cm(e)&&!Array.isArray(e)}function xm(e){return"symbol"==typeof e?e.toString():"string"==typeof e?JSON.stringify(e):`${e}`}function Rm(e,t,n,r){if(!0===e)return;!1===e?e={}:"string"==typeof e&&(e={message:e});const{path:i,branch:s}=t,{type:o}=n,{refinement:a,message:c=`Expected a value of type \`${o}\`${a?` with refinement \`${a}\``:""}, but received: \`${xm(r)}\``}=e;return{value:r,type:o,refinement:a,key:i[i.length-1],path:i,branch:s,...e,message:c}}function*Bm(e,t,n,r){var i;Cm(i=e)&&"function"==typeof i[Symbol.iterator]||(e=[e]);for(const i of e){const e=Rm(i,t,n,r);e&&(yield e)}}function*Dm(e,t,n={}){const{path:r=[],branch:i=[e],coerce:s=!1,mask:o=!1}=n,a={path:r,branch:i,mask:o};s&&(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=Dm(u,d,{path:void 0===l?r:[...r,l],branch:void 0===l?i:[...i,u],coerce:s,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]):s&&(u=n[1],void 0===l?e=u:e instanceof Map?e.set(l,u):e instanceof Set?e.add(u):Cm(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 Mm=class{constructor(e){const{type:t,schema:n,validator:r,refiner:i,coercer:s=e=>e,entries:o=function*(){}}=e;this.type=t,this.schema=n,this.entries=o,this.coercer=s,this.validator=r?(e,t)=>Bm(r(e,t),t,this,e):()=>[],this.refiner=i?(e,t)=>Bm(i(e,t),t,this,e):()=>[]}assert(e,t){return function(e,t,n){const r=Lm(e,t,{message:n});if(r[0])throw r[0]}(e,this,t)}create(e,t){return Om(e,this,t)}is(e){return Um(e,this)}mask(e,t){return function(e,t,n){const r=Lm(e,t,{coerce:!0,mask:!0,message:n});if(r[0])throw r[0];return r[1]}(e,this,t)}validate(e,t={}){return Lm(e,this,t)}};function Om(e,t,n){const r=Lm(e,t,{coerce:!0,message:n});if(r[0])throw r[0];return r[1]}function Um(e,t){return!Lm(e,t)[0]}function Lm(e,t,n={}){const r=Dm(e,t,n),i=function(e){const{done:t,value:n}=e.next();return t?void 0:n}(r);if(i[0]){return[new Nm(i[0],function*(){for(const e of r)e[0]&&(yield e[0])}),void 0]}return[void 0,i[1]]}function Pm(e,t){return new Mm({type:e,schema:null,validator:t})}function Fm(e){return new Mm({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: ${xm(e)}`})}function $m(){return Pm("boolean",e=>"boolean"==typeof e)}function Km(e){return Pm("instance",t=>t instanceof e||`Expected a \`${e.name}\` instance, but received: ${xm(t)}`)}function Gm(e){const t=xm(e),n=typeof e;return new Mm({type:"literal",schema:"string"===n||"number"===n||"boolean"===n?e:null,validator:n=>n===e||`Expected the literal \`${t}\`, but received: ${xm(n)}`})}function Hm(e){return new Mm({...e,validator:(t,n)=>null===t||e.validator(t,n),refiner:(t,n)=>null===t||e.refiner(t,n)})}function Wm(){return Pm("number",e=>"number"==typeof e&&!isNaN(e)||`Expected a number, but received: ${xm(e)}`)}function qm(e){return new Mm({...e,validator:(t,n)=>void 0===t||e.validator(t,n),refiner:(t,n)=>void 0===t||e.refiner(t,n)})}function jm(e,t){return new Mm({type:"record",schema:null,*entries(n){if(Cm(n))for(const r in n){const i=n[r];yield[r,r,e],yield[r,i,t]}},validator:e=>_m(e)||`Expected an object, but received: ${xm(e)}`,coercer:e=>_m(e)?{...e}:e})}function Vm(){return Pm("string",e=>"string"==typeof e||`Expected a string, but received: ${xm(e)}`)}function zm(e){const t=Pm("never",()=>!1);return new Mm({type:"tuple",schema:null,*entries(n){if(Array.isArray(n)){const r=Math.max(e.length,n.length);for(let i=0;i<r;i++)yield[i,n[i],e[i]||t]}},validator:e=>Array.isArray(e)||`Expected an array, but received: ${xm(e)}`,coercer:e=>Array.isArray(e)?e.slice():e})}function Xm(e){const t=Object.keys(e);return new Mm({type:"type",schema:e,*entries(n){if(Cm(n))for(const r of t)yield[r,n[r],e[r]]},validator:e=>_m(e)||`Expected an object, but received: ${xm(e)}`,coercer:e=>_m(e)?{...e}:e})}function Jm(e){const t=e.map(e=>e.type).join(" | ");return new Mm({type:"union",schema:null,coercer(t,n){for(const r of e){const[e,i]=r.validate(t,{coerce:!0,mask:n.mask});if(!e)return i}return t},validator(n,r){const i=[];for(const t of e){const[...e]=Dm(n,t,r),[s]=e;if(!s[0])return[];for(const[t]of e)t&&i.push(t)}return[`Expected the value to satisfy a union of \`${t}\`, but received: ${xm(n)}`,...i]}})}function Ym(){return Pm("unknown",()=>!0)}function Qm(e,t,n){return new Mm({...e,coercer:(r,i)=>Um(r,t)?e.coercer(n(r,i),i):e.coercer(r,i)})}var Zm,ep,tp,np,rp=ra(y);function ip(){if(ep)return Zm;ep=1;const e=rp.v4;return Zm=function(t,n,r,i){if("string"!=typeof t)throw new TypeError(t+" must be a string");const s="number"==typeof(i=i||{}).version?i.version:2;if(1!==s&&2!==s)throw new TypeError(s+" must be 1 or 2");const o={method:t};if(2===s&&(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 i.generator?i.generator:function(){return e()};o.id=t(o,i)}else 2===s&&null===r?i.notificationIdNull&&(o.id=null):o.id=r;return o}}function sp(){if(np)return tp;np=1;const e=rp.v4,t=ip(),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 tp=n,n.prototype.request=function(e,n,r,i){const s=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)i=n,o=e;else{"function"==typeof r&&(i=r,r=void 0);const s="function"==typeof i;try{o=t(e,n,r,{generator:this.options.generator,version:this.options.version,notificationIdNull:this.options.notificationIdNull})}catch(e){if(s)return void i(e);throw e}if(!s)return o}let c;try{c=JSON.stringify(o,this.options.replacer)}catch(e){return void i(e)}return this.callServer(c,function(e,t){s._parseResponse(e,t,i)}),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)}},tp}var op,ap=na(sp()),cp={exports:{}};function lp(){return op||(op=1,function(e){var t=Object.prototype.hasOwnProperty,n="~";function r(){}function i(e,t,n){this.fn=e,this.context=t,this.once=n||!1}function s(e,t,r,s,o){if("function"!=typeof r)throw new TypeError("The listener must be a function");var a=new i(r,s||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,i=[];if(0===this._eventsCount)return i;for(r in e=this._events)t.call(e,r)&&i.push(n?r.slice(1):r);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(e)):i},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 i=0,s=r.length,o=new Array(s);i<s;i++)o[i]=r[i].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,i,s,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,i),!0;case 5:return u.fn.call(u.context,t,r,i,s),!0;case 6:return u.fn.call(u.context,t,r,i,s,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,i);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 s(this,e,t,n,!1)},a.prototype.once=function(e,t,n){return s(this,e,t,n,!0)},a.prototype.removeListener=function(e,t,r,i){var s=n?n+e:e;if(!this._events[s])return this;if(!t)return o(this,s),this;var a=this._events[s];if(a.fn)a.fn!==t||i&&!a.once||r&&a.context!==r||o(this,s);else{for(var c=0,l=[],u=a.length;c<u;c++)(a[c].fn!==t||i&&!a[c].once||r&&a[c].context!==r)&&l.push(a[c]);l.length?this._events[s]=1===l.length?l[0]:l:o(this,s)}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}(cp)),cp.exports}var up=na(lp()),dp=class extends up{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 hp=class{encode(e){return JSON.stringify(e)}decode(e){return JSON.parse(e)}},gp=class extends up{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:i=1e3,max_reconnects:s=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=i,this.max_reconnects=s,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 hp,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((i,s)=>{if(!this.ready)return s(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 s(e);this.queue[o]={promise:[i,s]},n&&(this.queue[o].timeout=setTimeout(()=>{delete this.queue[o],s(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 i={jsonrpc:"2.0",method:e,params:t};this.socket.send(this.dataPack.encode(i),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=ga.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 fp extends Ua{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,ba(e);const n=Ma(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,i=new Uint8Array(r);i.set(n.length>r?e.create().update(n).digest():n);for(let e=0;e<i.length;e++)i[e]^=54;this.iHash.update(i),this.oHash=e.create();for(let e=0;e<i.length;e++)i[e]^=106;this.oHash.update(i),wa(i)}update(e){return va(this),this.iHash.update(e),this}digestInto(e){va(this),ya(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:i,blockLen:s,outputLen:o}=this;return e.finished=r,e.destroyed=i,e.blockLen=s,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 mp=(e,t,n)=>new fp(e,t).update(n).digest();mp.create=(e,t)=>new fp(e,t);const pp=(e,t)=>(e+(e>=0?t:-t)/kp)/t;function yp(e){if(!["compact","recovered","der"].includes(e))throw new Error('Signature format must be "compact", "recovered", or "der"');return e}function bp(e,t){const n={};for(let r of Object.keys(t))n[r]=void 0===e[r]?t[r]:e[r];return vc(n.lowS,"lowS"),vc(n.prehash,"prehash"),void 0!==n.format&&yp(n.format),n}class vp extends Error{constructor(e=""){super(e)}}const wp={Err:vp,_tlv:{encode:(e,t)=>{const{Err:n}=wp;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,i=Ec(r);if(i.length/2&128)throw new n("tlv.encode: long form length too big");const s=r>127?Ec(i.length/2|128):"";return Ec(e)+s+i+t},decode(e,t){const{Err:n}=wp;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 i=t[r++];let s=0;if(!!(128&i)){const e=127&i;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)s=s<<8|e;if(r+=e,s<128)throw new n("tlv.decode(long): not minimal encoding")}else s=i;const o=t.subarray(r,r+s);if(o.length!==s)throw new n("tlv.decode: wrong value length");return{v:o,l:t.subarray(r+s)}}},_int:{encode(e){const{Err:t}=wp;if(e<Ep)throw new t("integer: negative integers are not allowed");let n=Ec(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}=wp;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 kc(e)}},toSig(e){const{Err:t,_int:n,_tlv:r}=wp,i=Nc("signature",e),{v:s,l:o}=r.decode(48,i);if(o.length)throw new t("invalid signature: left bytes after parsing");const{v:a,l:c}=r.decode(2,s),{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}=wp,r=t.encode(2,n.encode(e.r))+t.encode(2,n.encode(e.s));return t.encode(48,r)}},Ep=BigInt(0),Ap=BigInt(1),kp=BigInt(2),Sp=BigInt(3),Tp=BigInt(4);function Ip(e,t){const{BYTES:n}=e;let r;if("bigint"==typeof t)r=t;else{let i=Nc("private key",t);try{r=e.fromBytes(i)}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 Np(e,t={}){const n=wl("weierstrass",e,t),{Fp:r,Fn:i}=n;let s=n.CURVE;const{h:o,n:a}=s;Dc(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:c}=t;if(c&&(!r.is0(s.a)||"bigint"!=typeof c.beta||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const l=_p(r,i);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:i,y:s}=t.toAffine(),o=r.toBytes(i);if(vc(n,"isCompressed"),n){u();return Oa(Cp(!r.isOdd(s)),o)}return Oa(Uint8Array.of(4),o,r.toBytes(s))},h=t.fromBytes||function(e){wc(e,void 0,"Point");const{publicKey:t,publicKeyUncompressed:n}=l,i=e.length,s=e[0],o=e.subarray(1);if(i!==t||2!==s&&3!==s){if(i===n&&4===s){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 ${i}, 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&~s)!==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,s.a)),s.b)}function f(e,t){const n=r.sqr(t),i=g(e);return r.eql(n,i)}if(!f(s.Gx,s.Gy))throw new Error("bad curve params: generator point");const m=r.mul(r.pow(s.a,Sp),Tp),p=r.mul(r.sqr(s.b),BigInt(27));if(r.is0(r.add(m,p)))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 k))throw new Error("ProjectivePoint expected")}function v(e){if(!c||!c.basises)throw new Error("no endo");return function(e,t,n){const[[r,i],[s,o]]=t,a=pp(o*e,n),c=pp(-i*e,n);let l=e-a*r-c*s,u=-a*i-c*o;const d=l<Ep,h=u<Ep;d&&(l=-l),h&&(u=-u);const g=Bc(Math.ceil(Rc(n)/2))+Ap;if(l<Ep||l>=g||u<Ep||u>=g)throw new Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:d,k1:l,k2neg:h,k2:u}}(e,c.basises,i.ORDER)}const w=Mc((e,t)=>{const{X:n,Y:i,Z:s}=e;if(r.eql(s,r.ONE))return{x:n,y:i};const o=e.is0();null==t&&(t=o?r.ONE:r.inv(s));const a=r.mul(n,t),c=r.mul(i,t),l=r.mul(s,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=Mc(e=>{if(e.is0()){if(t.allowInfinityPoint&&!r.is0(e.Y))return;throw new Error("bad point: ZERO")}const{x:n,y:i}=e.toAffine();if(!r.isValid(n)||!r.isValid(i))throw new Error("bad point: x or y not field elements");if(!f(n,i))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,i,s){return n=new k(r.mul(n.X,e),n.Y,n.Z),t=cl(i,t),n=cl(s,n),t.add(n)}class k{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 s}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 k)throw new Error("projective point not allowed");return r.is0(t)&&r.is0(n)?k.ZERO:new k(t,n,r.ONE)}static fromBytes(e){const t=k.fromAffine(h(wc(e,void 0,"point")));return t.assertValidity(),t}static fromHex(e){return k.fromBytes(Nc("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(Sp),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:i}=this,{X:s,Y:o,Z:a}=e,c=r.eql(r.mul(t,a),r.mul(s,i)),l=r.eql(r.mul(n,a),r.mul(o,i));return c&&l}negate(){return new k(this.X,r.neg(this.Y),this.Z)}double(){const{a:e,b:t}=s,n=r.mul(t,Sp),{X:i,Y:o,Z:a}=this;let c=r.ZERO,l=r.ZERO,u=r.ZERO,d=r.mul(i,i),h=r.mul(o,o),g=r.mul(a,a),f=r.mul(i,o);return f=r.add(f,f),u=r.mul(i,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 k(c,l,u)}add(e){b(e);const{X:t,Y:n,Z:i}=this,{X:o,Y:a,Z:c}=e;let l=r.ZERO,u=r.ZERO,d=r.ZERO;const h=s.a,g=r.mul(s.b,Sp);let f=r.mul(t,o),m=r.mul(n,a),p=r.mul(i,c),y=r.add(t,n),v=r.add(o,a);y=r.mul(y,v),v=r.add(f,m),y=r.sub(y,v),v=r.add(t,i);let w=r.add(o,c);return v=r.mul(v,w),w=r.add(f,p),v=r.sub(v,w),w=r.add(n,i),l=r.add(a,c),w=r.mul(w,l),l=r.add(m,p),w=r.sub(w,l),d=r.mul(h,v),l=r.mul(g,p),d=r.add(l,d),l=r.sub(m,d),d=r.add(m,d),u=r.mul(l,d),m=r.add(f,f),m=r.add(m,f),p=r.mul(h,p),v=r.mul(g,v),m=r.add(m,p),p=r.sub(f,p),p=r.mul(h,p),v=r.add(v,p),f=r.mul(m,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,m),d=r.mul(w,d),d=r.add(d,f),new k(l,u,d)}subtract(e){return this.add(e.negate())}is0(){return this.equals(k.ZERO)}multiply(e){const{endo:n}=t;if(!i.isValidNot0(e))throw new Error("invalid scalar: out of range");let r,s;const o=e=>T.cached(this,e,e=>ll(k,e));if(n){const{k1neg:t,k1:i,k2neg:a,k2:c}=v(e),{p:l,f:u}=o(i),{p:d,f:h}=o(c);s=u.add(h),r=A(n.beta,l,d,t,a)}else{const{p:t,f:n}=o(e);r=t,s=n}return ll(k,[r,s])[0]}multiplyUnsafe(e){const{endo:n}=t,r=this;if(!i.isValid(e))throw new Error("invalid scalar: out of range");if(e===Ep||r.is0())return k.ZERO;if(e===Ap)return r;if(T.hasCache(this))return this.multiply(e);if(n){const{k1neg:t,k1:i,k2neg:s,k2:o}=v(e),{p1:a,p2:c}=function(e,t,n,r){let i=t,s=e.ZERO,o=e.ZERO;for(;n>ol||r>ol;)n&al&&(s=s.add(i)),r&al&&(o=o.add(i)),i=i.double(),n>>=al,r>>=al;return{p1:s,p2:o}}(k,r,i,o);return A(n.beta,a,c,t,s)}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===Ap||(e?e(k,this):T.unsafe(this,a).is0())}clearCofactor(){const{clearCofactor:e}=t;return o===Ap?this:e?e(k,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(e=!0){return vc(e,"isCompressed"),this.assertValidity(),d(k,this,e)}toHex(e=!0){return Ta(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 ll(k,e)}static msm(e,t){return bl(k,i,e,t)}static fromPrivateKey(e){return k.BASE.multiply(Ip(i,e))}}k.BASE=new k(s.Gx,s.Gy,r.ONE),k.ZERO=new k(r.ZERO,r.ONE,r.ZERO),k.Fp=r,k.Fn=i;const S=i.BITS,T=new yl(k,t.endo?Math.ceil(S/2):S);return k.BASE.precompute(8),k}function Cp(e){return Uint8Array.of(e?2:3)}function _p(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function xp(e,t={}){const{Fn:n}=e,r=t.randomBytes||Pa,i=Object.assign(_p(e.Fp,n),{seed:sl(n.ORDER)});function s(e){try{return!!Ip(n,e)}catch(e){return!1}}function o(e=r(i.seed)){return function(e,t,n=!1){const r=e.length,i=il(t),s=sl(t);if(r<16||r<s||r>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+r);const o=qc(n?Sc(e):kc(e),t-Uc)+Uc;return n?Ic(o,i):Tc(o,i)}(wc(e,i.seed,"seed"),n.ORDER)}function a(t,r=!0){return e.BASE.multiply(Ip(n,t)).toBytes(r)}function c(t){if("bigint"==typeof t)return!1;if(t instanceof e)return!0;const{secretKey:r,publicKey:s,publicKeyUncompressed:o}=i;if(n.allowedLengths||r===s)return;const a=Nc("key",t).length;return a===s||a===o}const l={isValidSecretKey:s,isValidPublicKey:function(t,n){const{publicKey:r,publicKeyUncompressed:s}=i;try{const i=t.length;return(!0!==n||i===r)&&((!1!==n||i===s)&&!!e.fromBytes(t))}catch(e){return!1}},randomSecretKey:o,isValidPrivateKey:s,randomPrivateKey:o,normPrivateKeyToScalar:e=>Ip(n,e),precompute:(t=8,n=e.BASE)=>n.precompute(t,!1)};return Object.freeze({getPublicKey:a,getSharedSecret:function(t,r,i=!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 s=Ip(n,t);return e.fromHex(r).multiply(s).toBytes(i)},keygen:function(e){const t=o(e);return{secretKey:t,publicKey:a(t)}},Point:e,utils:l,lengths:i})}function Rp(e,t,n={}){ba(t),Dc(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const r=n.randomBytes||Pa,i=n.hmac||((e,...n)=>mp(t,e,Oa(...n))),{Fp:s,Fn:o}=e,{ORDER:a,BITS:c}=o,{keygen:l,getPublicKey:u,getSharedSecret:d,utils:h,lengths:g}=xp(e,n),f={prehash:!1,lowS:"boolean"==typeof n.lowS&&n.lowS,format:void 0,extraEntropy:!1},m="compact";function p(e){return e>a>>Ap}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=m){let n;if(function(e,t){yp(t);const n=g.signature;wc(e,"compact"===t?n:"recovered"===t?n+1:void 0,`${t} signature`)}(e,t),"der"===t){const{r:t,s:n}=wp.toSig(wc(e));return new b(t,n)}"recovered"===t&&(n=e[0],t="compact",e=e.subarray(1));const r=o.BYTES,i=e.subarray(0,r),s=e.subarray(r,2*r);return new b(o.fromBytes(i),o.fromBytes(s),n)}static fromHex(e,t){return this.fromBytes(Da(e),t)}addRecoveryBit(e){return new b(this.r,this.s,e)}recoverPublicKey(t){const n=s.ORDER,{r:r,s:i,recovery:c}=this;if(null==c||![0,1,2,3].includes(c))throw new Error("recovery id invalid");if(a*kp<n&&c>1)throw new Error("recovery id is ambiguous for h>1 curve");const l=2===c||3===c?r+a:r;if(!s.isValid(l))throw new Error("recovery id 2 or 3 invalid");const u=s.toBytes(l),d=e.fromBytes(Oa(Cp(!(1&c)),u)),h=o.inv(l),g=w(Nc("msgHash",t)),f=o.create(-g*h),m=o.create(i*h),p=e.BASE.multiplyUnsafe(f).add(d.multiplyUnsafe(m));if(p.is0())throw new Error("point at infinify");return p.assertValidity(),p}hasHighS(){return p(this.s)}toBytes(e=m){if(yp(e),"der"===e)return Da(wp.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 Oa(Uint8Array.of(this.recovery),t,n)}return Oa(t,n)}toHex(e){return Ta(this.toBytes(e))}assertValidity(){}static fromCompact(e){return b.fromBytes(Nc("sig",e),"compact")}static fromDER(e){return b.fromBytes(Nc("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 Ta(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return Ta(this.toBytes("compact"))}}const v=n.bits2int||function(e){if(e.length>8192)throw new Error("input is too large");const t=kc(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=Bc(c);function A(e){return xc("num < 2^"+c,e,Ep,E),o.toBytes(e)}function k(e,n){return wc(e,void 0,"message"),n?wc(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,s,a={}){n=Nc("message",n);const{seed:c,k2sig:l}=function(t,n,i){if(["recovered","canonical"].some(e=>e in i))throw new Error("sign() legacy options not supported");const{lowS:s,prehash:a,extraEntropy:c}=bp(i,f);t=k(t,a);const l=w(t),u=Ip(o,n),d=[A(u),A(l)];if(null!=c&&!1!==c){const e=!0===c?r(g.secretKey):c;d.push(Nc("extraEntropy",e))}const h=Oa(...d),m=l;return{seed:h,k2sig:function(t){const n=v(t);if(!o.isValidNot0(n))return;const r=o.inv(n),i=e.BASE.multiply(n).toAffine(),a=o.create(i.x);if(a===Ep)return;const c=o.create(r*o.create(m+a*u));if(c===Ep)return;let l=(i.x===a?0:2)|Number(i.y&Ap),d=c;return s&&p(c)&&(d=o.neg(c),l^=1),new b(a,d,l)}}}(n,s,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),i=e=>Uint8Array.of(e);let s=r(e),o=r(e),a=0;const c=()=>{s.fill(1),o.fill(0),a=0},l=(...e)=>n(o,s,...e),u=(e=r(0))=>{o=l(i(0),e),s=l(),0!==e.length&&(o=l(i(1),e),s=l())},d=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let e=0;const n=[];for(;e<t;){s=l();const t=s.slice();n.push(t),e+=s.length}return Oa(...n)};return(e,t)=>{let n;for(c(),u(e);!(n=t(d()));)u();return c(),n}}(t.outputLen,o.BYTES,i)(c,l)},verify:function(t,n,r,i={}){const{lowS:s,prehash:a,format:c}=bp(i,f);if(r=Nc("publicKey",r),n=k(Nc("message",n),a),"strict"in i)throw new Error("options.strict was renamed to lowS");const l=void 0===c?function(e){let t;const n="string"==typeof e||ma(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(Nc("sig",e),"der")}catch(e){if(!(e instanceof wp.Err))throw e}if(!t)try{t=b.fromBytes(Nc("sig",e),"compact")}catch(e){return!1}}return t||!1}(t):b.fromBytes(Nc("sig",t),c);if(!1===l)return!1;try{const t=e.fromBytes(r);if(s&&l.hasHighS())return!1;const{r:i,s:a}=l,c=w(n),u=o.inv(a),d=o.create(c*u),h=o.create(i*u),g=e.BASE.multiplyUnsafe(d).add(t.multiplyUnsafe(h));if(g.is0())return!1;return o.create(g.x)===i}catch(e){return!1}},recoverPublicKey:function(e,t,n={}){const{prehash:r}=bp(n,f);return t=k(t,r),b.fromBytes(e,"recovered").recoverPublicKey(t).toBytes()},Signature:b,hash:t})}function Bp(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:rl(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 Dp(e){const{CURVE:t,curveOpts:n,hash:r,ecdsaOpts:i}=Bp(e);return function(e,t){const n=t.Point;return Object.assign({},t,{ProjectivePoint:n,CURVE:Object.assign({},e,nl(n.Fn.ORDER,n.Fn.BITS))})}(e,Rp(Np(t,n),r,i))}const Mp={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Op={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},Up=BigInt(2);const Lp=rl(Mp.p,{sqrt:function(e){const t=Mp.p,n=BigInt(3),r=BigInt(6),i=BigInt(11),s=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),l=e*e*e%t,u=l*l*e%t,d=jc(u,n,t)*u%t,h=jc(d,n,t)*u%t,g=jc(h,Up,t)*l%t,f=jc(g,i,t)*g%t,m=jc(f,s,t)*f%t,p=jc(m,a,t)*m%t,y=jc(p,c,t)*p%t,b=jc(y,a,t)*m%t,v=jc(b,n,t)*u%t,w=jc(v,o,t)*f%t,E=jc(w,r,t)*l%t,A=jc(E,Up,t);if(!Lp.eql(Lp.sqr(A),e))throw new Error("Cannot find square root");return A}}),Pp=function(e,t){const n=t=>Dp({...e,hash:t});return{...n(t),create:n}}({...Mp,Fp:Lp,lowS:!0,endo:Op},mc);Pl.utils.randomPrivateKey;const Fp=()=>{const e=Pl.utils.randomPrivateKey(),t=$p(e),n=new Uint8Array(64);return n.set(e),n.set(t,32),{publicKey:t,secretKey:n}},$p=Pl.getPublicKey;function Kp(e){try{return Pl.ExtendedPoint.fromHex(e),!0}catch{return!1}}const Gp=Pl.verify,Hp=e=>ga.Buffer.isBuffer(e)?e:e instanceof Uint8Array?ga.Buffer.from(e.buffer,e.byteOffset,e.byteLength):ga.Buffer.from(e);class Wp{constructor(e){Object.assign(this,e)}encode(){return ga.Buffer.from(yu.serialize(qp,this))}static decode(e){return yu.deserialize(qp,this,e)}static decodeUnchecked(e){return yu.deserializeUnchecked(qp,this,e)}}const qp=new Map;var jp;const Vp=32;let zp=1;class Xp extends Wp{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=eu.decode(e);if(t.length!=Vp)throw new Error("Invalid public key input");this._bn=new Xl(t)}else this._bn=new Xl(e);if(this._bn.byteLength()>Vp)throw new Error("Invalid public key input")}}static unique(){const e=new Xp(zp);return zp+=1,new Xp(e.toBuffer())}equals(e){return this._bn.eq(e._bn)}toBase58(){return eu.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(ga.Buffer);if(e.length===Vp)return e;const t=ga.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=ga.Buffer.concat([e.toBuffer(),ga.Buffer.from(t),n.toBuffer()]),i=tu(r);return new Xp(i)}static createProgramAddressSync(e,t){let n=ga.Buffer.alloc(0);e.forEach(function(e){if(e.length>32)throw new TypeError("Max seed length exceeded");n=ga.Buffer.concat([n,Hp(e)])}),n=ga.Buffer.concat([n,t.toBuffer(),ga.Buffer.from("ProgramDerivedAddress")]);const r=tu(n);if(Kp(r))throw new Error("Invalid seeds, address must fall off the curve");return new Xp(r)}static async createProgramAddress(e,t){return this.createProgramAddressSync(e,t)}static findProgramAddressSync(e,t){let n,r=255;for(;0!=r;){try{const i=e.concat(ga.Buffer.from([r]));n=this.createProgramAddressSync(i,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 Kp(new Xp(e).toBytes())}}jp=Xp,Xp.default=new jp("11111111111111111111111111111111"),qp.set(Xp,{kind:"struct",fields:[["_bn","u256"]]}),new Xp("BPFLoader1111111111111111111111111111111111");const Jp=1232;class Yp extends Error{constructor(e){super(`Signature ${e} has expired: block height exceeded.`),this.signature=void 0,this.signature=e}}Object.defineProperty(Yp.prototype,"name",{value:"TransactionExpiredBlockheightExceededError"});class Qp 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(Qp.prototype,"name",{value:"TransactionExpiredTimeoutError"});class Zp extends Error{constructor(e){super(`Signature ${e} has expired: the nonce is no longer valid.`),this.signature=void 0,this.signature=e}}Object.defineProperty(Zp.prototype,"name",{value:"TransactionExpiredNonceInvalidError"});class ey{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 ty=(e="publicKey")=>wu.blob(32,e),ny=(e="string")=>{const t=wu.struct([wu.u32("length"),wu.u32("lengthPadding"),wu.blob(wu.offset(wu.u32(),-8),"chars")],e),n=t.decode.bind(t),r=t.encode.bind(t),i=t;return i.decode=(e,t)=>n(e,t).chars.toString(),i.encode=(e,t,n)=>{const i={chars:ga.Buffer.from(e,"utf8")};return r(i,t,n)},i.alloc=e=>wu.u32().span+wu.u32().span+ga.Buffer.from(e,"utf8").length,i};function ry(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 ry({layout:e},t[e.property]);return 0};let r=0;return e.layout.fields.forEach(e=>{r+=n(e)}),r}function iy(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 sy(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 oy(e,t){if(!e)throw new Error(t||"Assertion failed")}class ay{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},i=r(t);i.isSigner=!0,i.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 ay(t,n)}getMessageComponents(){const e=[...this.keyMetaMap.entries()];oy(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),i=e.filter(([,e])=>!e.isSigner&&!e.isWritable),s={numRequiredSignatures:t.length+n.length,numReadonlySignedAccounts:n.length,numReadonlyUnsignedAccounts:i.length};{oy(t.length>0,"Expected at least one writable signer key");const[e]=t[0];oy(e===this.payer.toBase58(),"Expected first writable signer key to be the fee payer")}return[s,[...t.map(([e])=>new Xp(e)),...n.map(([e])=>new Xp(e)),...r.map(([e])=>new Xp(e)),...i.map(([e])=>new Xp(e))]]}extractTableLookup(e){const[t,n]=this.drainKeysFoundInLookupTable(e.state.addresses,e=>!e.isSigner&&!e.isInvoked&&e.isWritable),[r,i]=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:i}]}drainKeysFoundInLookupTable(e,t){const n=new Array,r=new Array;for(const[i,s]of this.keyMetaMap.entries())if(t(s)){const t=new Xp(i),s=e.findIndex(e=>e.equals(t));s>=0&&(oy(s<256,"Max lookup table index exceeded"),n.push(s),r.push(t),this.keyMetaMap.delete(i))}return[n,r]}}const cy="Reached end of buffer unexpectedly";function ly(e){if(0===e.length)throw new Error(cy);return e.shift()}function uy(e,...t){const[n]=t;if(2===t.length?n+(t[1]??0)>e.length:n>=e.length)throw new Error(cy);return e.splice(...t)}class dy{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 Xp(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:eu.decode(e.data)}))}get addressTableLookups(){return[]}getAccountKeys(){return new ey(this.staticAccountKeys)}static compile(e){const t=ay.compile(e.instructions,e.payerKey),[n,r]=t.getMessageComponents(),i=new ey(r).compileInstructions(e.instructions).map(e=>({programIdIndex:e.programIdIndex,accounts:e.accountKeyIndexes,data:eu.encode(e.data)}));return new dy({header:n,accountKeys:r,recentBlockhash:e.recentBlockhash,instructions:i})}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=[];sy(t,e);const n=this.instructions.map(e=>{const{accounts:t,programIdIndex:n}=e,r=Array.from(eu.decode(e.data));let i=[];sy(i,t.length);let s=[];return sy(s,r.length),{programIdIndex:n,keyIndicesCount:ga.Buffer.from(i),keyIndices:t,dataLength:ga.Buffer.from(s),data:r}});let r=[];sy(r,n.length);let i=ga.Buffer.alloc(Jp);ga.Buffer.from(r).copy(i);let s=r.length;n.forEach(e=>{const t=wu.struct([wu.u8("programIdIndex"),wu.blob(e.keyIndicesCount.length,"keyIndicesCount"),wu.seq(wu.u8("keyIndex"),e.keyIndices.length,"keyIndices"),wu.blob(e.dataLength.length,"dataLength"),wu.seq(wu.u8("userdatum"),e.data.length,"data")]).encode(e,i,s);s+=t}),i=i.slice(0,s);const o=wu.struct([wu.blob(1,"numRequiredSignatures"),wu.blob(1,"numReadonlySignedAccounts"),wu.blob(1,"numReadonlyUnsignedAccounts"),wu.blob(t.length,"keyCount"),wu.seq(ty("key"),e,"keys"),ty("recentBlockhash")]),a={numRequiredSignatures:ga.Buffer.from([this.header.numRequiredSignatures]),numReadonlySignedAccounts:ga.Buffer.from([this.header.numReadonlySignedAccounts]),numReadonlyUnsignedAccounts:ga.Buffer.from([this.header.numReadonlyUnsignedAccounts]),keyCount:ga.Buffer.from(t),keys:this.accountKeys.map(e=>Hp(e.toBytes())),recentBlockhash:eu.decode(this.recentBlockhash)};let c=ga.Buffer.alloc(2048);const l=o.encode(a,c);return i.copy(c,l),c.slice(0,l+i.length)}static from(e){let t=[...e];const n=ly(t);if(n!==(127&n))throw new Error("Versioned messages must be deserialized with VersionedMessage.deserialize()");const r=ly(t),i=ly(t),s=iy(t);let o=[];for(let e=0;e<s;e++){const e=uy(t,0,Vp);o.push(new Xp(ga.Buffer.from(e)))}const a=uy(t,0,Vp),c=iy(t);let l=[];for(let e=0;e<c;e++){const e=ly(t),n=uy(t,0,iy(t)),r=uy(t,0,iy(t)),i=eu.encode(ga.Buffer.from(r));l.push({programIdIndex:e,accounts:n,data:i})}const u={header:{numRequiredSignatures:n,numReadonlySignedAccounts:r,numReadonlyUnsignedAccounts:i},recentBlockhash:eu.encode(ga.Buffer.from(a)),accountKeys:o,instructions:l};return new dy(u)}}class hy{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 ey(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=ay.compile(e.instructions,e.payerKey),n=new Array,r={writable:new Array,readonly:new Array},i=e.addressLookupTableAccounts||[];for(const e of i){const i=t.extractTableLookup(e);if(void 0!==i){const[e,{writable:t,readonly:s}]=i;n.push(e),r.writable.push(...t),r.readonly.push(...s)}}const[s,o]=t.getMessageComponents(),a=new ey(o,r).compileInstructions(e.instructions);return new hy({header:s,staticAccountKeys:o,recentBlockhash:e.recentBlockhash,compiledInstructions:a,addressTableLookups:n})}serialize(){const e=Array();sy(e,this.staticAccountKeys.length);const t=this.serializeInstructions(),n=Array();sy(n,this.compiledInstructions.length);const r=this.serializeAddressTableLookups(),i=Array();sy(i,this.addressTableLookups.length);const s=wu.struct([wu.u8("prefix"),wu.struct([wu.u8("numRequiredSignatures"),wu.u8("numReadonlySignedAccounts"),wu.u8("numReadonlyUnsignedAccounts")],"header"),wu.blob(e.length,"staticAccountKeysLength"),wu.seq(ty(),this.staticAccountKeys.length,"staticAccountKeys"),ty("recentBlockhash"),wu.blob(n.length,"instructionsLength"),wu.blob(t.length,"serializedInstructions"),wu.blob(i.length,"addressTableLookupsLength"),wu.blob(r.length,"serializedAddressTableLookups")]),o=new Uint8Array(Jp),a=s.encode({prefix:128,header:this.header,staticAccountKeysLength:new Uint8Array(e),staticAccountKeys:this.staticAccountKeys.map(e=>e.toBytes()),recentBlockhash:eu.decode(this.recentBlockhash),instructionsLength:new Uint8Array(n),serializedInstructions:t,addressTableLookupsLength:new Uint8Array(i),serializedAddressTableLookups:r},o);return o.slice(0,a)}serializeInstructions(){let e=0;const t=new Uint8Array(Jp);for(const n of this.compiledInstructions){const r=Array();sy(r,n.accountKeyIndexes.length);const i=Array();sy(i,n.data.length);e+=wu.struct([wu.u8("programIdIndex"),wu.blob(r.length,"encodedAccountKeyIndexesLength"),wu.seq(wu.u8(),n.accountKeyIndexes.length,"accountKeyIndexes"),wu.blob(i.length,"encodedDataLength"),wu.blob(n.data.length,"data")]).encode({programIdIndex:n.programIdIndex,encodedAccountKeyIndexesLength:new Uint8Array(r),accountKeyIndexes:n.accountKeyIndexes,encodedDataLength:new Uint8Array(i),data:n.data},t,e)}return t.slice(0,e)}serializeAddressTableLookups(){let e=0;const t=new Uint8Array(Jp);for(const n of this.addressTableLookups){const r=Array();sy(r,n.writableIndexes.length);const i=Array();sy(i,n.readonlyIndexes.length);e+=wu.struct([ty("accountKey"),wu.blob(r.length,"encodedWritableIndexesLength"),wu.seq(wu.u8(),n.writableIndexes.length,"writableIndexes"),wu.blob(i.length,"encodedReadonlyIndexesLength"),wu.seq(wu.u8(),n.readonlyIndexes.length,"readonlyIndexes")]).encode({accountKey:n.accountKey.toBytes(),encodedWritableIndexesLength:new Uint8Array(r),writableIndexes:n.writableIndexes,encodedReadonlyIndexesLength:new Uint8Array(i),readonlyIndexes:n.readonlyIndexes},t,e)}return t.slice(0,e)}static deserialize(e){let t=[...e];const n=ly(t),r=127&n;oy(n!==r,"Expected versioned message but received legacy message");oy(0===r,`Expected versioned message with version 0 but found version ${r}`);const i={numRequiredSignatures:ly(t),numReadonlySignedAccounts:ly(t),numReadonlyUnsignedAccounts:ly(t)},s=[],o=iy(t);for(let e=0;e<o;e++)s.push(new Xp(uy(t,0,Vp)));const a=eu.encode(uy(t,0,Vp)),c=iy(t),l=[];for(let e=0;e<c;e++){const e=ly(t),n=uy(t,0,iy(t)),r=iy(t),i=new Uint8Array(uy(t,0,r));l.push({programIdIndex:e,accountKeyIndexes:n,data:i})}const u=iy(t),d=[];for(let e=0;e<u;e++){const e=new Xp(uy(t,0,Vp)),n=uy(t,0,iy(t)),r=uy(t,0,iy(t));d.push({accountKey:e,writableIndexes:n,readonlyIndexes:r})}return new hy({header:i,staticAccountKeys:s,recentBlockhash:a,compiledInstructions:l,addressTableLookups:d})}}function gy(e){const t=uy(e,0,4);return t[0]+256*t[1]+65536*t[2]+t[3]*2**24}class fy{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 ey(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=ly(t),r=127&n;oy(n!==r,"Expected versioned message but received legacy message");oy(1===r,`Expected versioned message with version 1 but found version ${r}`);const i={numRequiredSignatures:ly(t),numReadonlySignedAccounts:ly(t),numReadonlyUnsignedAccounts:ly(t)},s=gy(t);oy(!(-32&s),"Unexpected bits set in the transaction config mask");const o=3&s;oy(0===o||3===o,"Expected both or neither of the priority fee bits to be set in the transaction config mask");const a=eu.encode(uy(t,0,Vp)),c=ly(t),l=ly(t),u=[];for(let e=0;e<l;e++)u.push(new Xp(uy(t,0,Vp)));const d={computeUnitLimit:null,heapSize:null,loadedAccountsDataSizeLimit:null,priorityFee:null};0!==o&&(d.priorityFee=function(e){const t=uy(e,0,8);let n=BigInt(0);for(let e=t.length-1;e>=0;e--)n=n<<BigInt(8)|BigInt(t[e]);return oy(n<=BigInt(Number.MAX_SAFE_INTEGER),"Expected u64 value to be within the safe integer range"),Number(n)}(t)),4&s&&(d.computeUnitLimit=gy(t)),8&s&&(d.loadedAccountsDataSizeLimit=gy(t)),16&s&&(d.heapSize=gy(t));const h=[];for(let e=0;e<c;e++){const e=ly(t),n=ly(t),r=ly(t)+256*ly(t);h.push({accountKeyIndexesLength:n,dataLength:r,programIdIndex:e})}const g=[];for(const e of h)g.push({programIdIndex:e.programIdIndex,accountKeyIndexes:uy(t,0,e.accountKeyIndexesLength),data:new Uint8Array(uy(t,0,e.dataLength))});return oy(0===t.length,"Expected no bytes to remain after deserializing a version 1 message"),new fy({header:i,staticAccountKeys:u,recentBlockhash:a,compiledInstructions:g,transactionConfig:d})}}let my=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 py=ga.Buffer.alloc(64).fill(0);class yy{constructor(e){this.keys=void 0,this.programId=void 0,this.data=ga.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 by{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 yy(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=[],i=[];t.forEach(e=>{e.keys.forEach(e=>{i.push({...e})});const t=e.programId.toString();r.includes(t)||r.push(t)}),r.forEach(e=>{i.push({pubkey:new Xp(e),isSigner:!1,isWritable:!1})});const s=[];i.forEach(e=>{const t=e.pubkey.toString(),n=s.findIndex(e=>e.pubkey.toString()===t);n>-1?(s[n].isWritable=s[n].isWritable||e.isWritable,s[n].isSigner=s[n].isSigner||e.isSigner):s.push(e)}),s.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=s.findIndex(e=>e.pubkey.equals(n));if(o>-1){const[e]=s.splice(o,1);e.isSigner=!0,e.isWritable=!0,s.unshift(e)}else s.unshift({pubkey:n,isSigner:!0,isWritable:!0});for(const e of this.signatures){const t=s.findIndex(t=>t.pubkey.equals(e.publicKey));if(!(t>-1))throw new Error(`unknown signer: ${e.publicKey.toString()}`);s[t].isSigner||(s[t].isSigner=!0)}let a=0,c=0,l=0;const u=[],d=[];s.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:eu.encode(t)}});return g.forEach(e=>{oy(e.programIdIndex>=0),e.accounts.forEach(e=>oy(e>=0))}),new dy({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)=>Pl.sign(e,t.slice(0,32)))(n,e.secretKey);this._addSignature(e.publicKey,Hp(t))})}addSignature(e,t){this._compile(),this._addSignature(e,t)}_addSignature(e,t){oy(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=ga.Buffer.from(t)}verifySignatures(e=!0){return!this._getMessageSignednessErrors(this.serializeMessage(),e)}_getMessageSignednessErrors(e,t){const n={};for(const{signature:r,publicKey:i}of this.signatures)null===r?t&&(n.missing||=[]).push(i):Gp(r,e,i.toBytes())||(n.invalid||=[]).push(i);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=[];sy(n,t.length);const r=n.length+64*t.length+e.length,i=ga.Buffer.alloc(r);return oy(t.length<256),ga.Buffer.from(n).copy(i,0),t.forEach(({signature:e},t)=>{null!==e&&(oy(64===e.length,"signature has invalid length"),ga.Buffer.from(e).copy(i,n.length+64*t))}),e.copy(i,n.length+64*t.length),oy(i.length<=Jp,`Transaction too large: ${i.length} > 1232`),i}get keys(){return oy(1===this.instructions.length),this.instructions[0].keys.map(e=>e.pubkey)}get programId(){return oy(1===this.instructions.length),this.instructions[0].programId}get data(){return oy(1===this.instructions.length),this.instructions[0].data}static from(e){let t=[...e];const n=iy(t);let r=[];for(let e=0;e<n;e++){const e=uy(t,0,64);r.push(eu.encode(ga.Buffer.from(e)))}return by.populate(dy.from(t),r)}static populate(e,t=[]){const n=new by;return n.recentBlockhash=e.recentBlockhash,e.header.numRequiredSignatures>0&&(n.feePayer=e.accountKeys[0]),t.forEach((t,r)=>{const i={signature:t==eu.encode(py)?null:eu.decode(t),publicKey:e.accountKeys[r]};n.signatures.push(i)}),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 yy({keys:r,programId:e.accountKeys[t.programIdIndex],data:eu.decode(t.data)}))}),n._message=e,n._json=n.toJSON(),n}}new Xp("SysvarC1ock11111111111111111111111111111111"),new Xp("SysvarEpochSchedu1e111111111111111111111111"),new Xp("Sysvar1nstructions1111111111111111111111111");const vy=new Xp("SysvarRecentB1ockHashes11111111111111111111"),wy=new Xp("SysvarRent111111111111111111111111111111111");new Xp("SysvarRewards111111111111111111111111111111"),new Xp("SysvarS1otHashes111111111111111111111111111"),new Xp("SysvarS1otHistory11111111111111111111111111"),new Xp("SysvarStakeHistory1111111111111111111111111");class Ey extends Error{constructor({action:e,signature:t,transactionMessage:n,logs:r}){const i=r?`Logs: \n${JSON.stringify(r.slice(-10),null,2)}. `:"",s="\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}. `+i+s;break;case"simulate":o=`Simulation failed. \nMessage: ${n}. \n`+i+s;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 Ay 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 ky(e){return new Promise(t=>setTimeout(t,e))}function Sy(e,t){const n=e.layout.span>=0?e.layout.span:ry(e,t),r=ga.Buffer.alloc(n),i=Object.assign({instruction:e.index},t);return e.layout.encode(i,r),r}const Ty=wu.nu64("lamportsPerSignature"),Iy=wu.struct([wu.u32("version"),wu.u32("state"),ty("authorizedPubkey"),ty("nonce"),wu.struct([Ty],"feeCalculator")]),Ny=Iy.span;class Cy{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=Iy.decode(Hp(e),0);return new Cy({authorizedPubkey:new Xp(t.authorizedPubkey),nonce:new Xp(t.nonce).toString(),feeCalculator:t.feeCalculator})}}function _y(e){const t=wu.blob(8,e),n=t.decode.bind(t),r=t.encode.bind(t),i=t,s=Im();return i.decode=(e,t)=>{const r=n(e,t);return s.decode(r)},i.encode=(e,t,n)=>{const i=s.encode(e);return r(i,t,n)},i}const xy=Object.freeze({Create:{index:0,layout:wu.struct([wu.u32("instruction"),wu.ns64("lamports"),wu.ns64("space"),ty("programId")])},Assign:{index:1,layout:wu.struct([wu.u32("instruction"),ty("programId")])},Transfer:{index:2,layout:wu.struct([wu.u32("instruction"),_y("lamports")])},CreateWithSeed:{index:3,layout:wu.struct([wu.u32("instruction"),ty("base"),ny("seed"),wu.ns64("lamports"),wu.ns64("space"),ty("programId")])},AdvanceNonceAccount:{index:4,layout:wu.struct([wu.u32("instruction")])},WithdrawNonceAccount:{index:5,layout:wu.struct([wu.u32("instruction"),wu.ns64("lamports")])},InitializeNonceAccount:{index:6,layout:wu.struct([wu.u32("instruction"),ty("authorized")])},AuthorizeNonceAccount:{index:7,layout:wu.struct([wu.u32("instruction"),ty("authorized")])},Allocate:{index:8,layout:wu.struct([wu.u32("instruction"),wu.ns64("space")])},AllocateWithSeed:{index:9,layout:wu.struct([wu.u32("instruction"),ty("base"),ny("seed"),wu.ns64("space"),ty("programId")])},AssignWithSeed:{index:10,layout:wu.struct([wu.u32("instruction"),ty("base"),ny("seed"),ty("programId")])},TransferWithSeed:{index:11,layout:wu.struct([wu.u32("instruction"),_y("lamports"),ny("seed"),ty("programId")])},UpgradeNonceAccount:{index:12,layout:wu.struct([wu.u32("instruction")])}});class Ry{constructor(){}static createAccount(e){const t=Sy(xy.Create,{lamports:e.lamports,space:e.space,programId:Hp(e.programId.toBuffer())});return new yy({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=Sy(xy.TransferWithSeed,{lamports:BigInt(e.lamports),seed:e.seed,programId:Hp(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=Sy(xy.Transfer,{lamports:BigInt(e.lamports)}),n=[{pubkey:e.fromPubkey,isSigner:!0,isWritable:!0},{pubkey:e.toPubkey,isSigner:!1,isWritable:!0}]}return new yy({keys:n,programId:this.programId,data:t})}static assign(e){let t,n;if("basePubkey"in e){t=Sy(xy.AssignWithSeed,{base:Hp(e.basePubkey.toBuffer()),seed:e.seed,programId:Hp(e.programId.toBuffer())}),n=[{pubkey:e.accountPubkey,isSigner:!1,isWritable:!0},{pubkey:e.basePubkey,isSigner:!0,isWritable:!1}]}else{t=Sy(xy.Assign,{programId:Hp(e.programId.toBuffer())}),n=[{pubkey:e.accountPubkey,isSigner:!0,isWritable:!0}]}return new yy({keys:n,programId:this.programId,data:t})}static createAccountWithSeed(e){const t=Sy(xy.CreateWithSeed,{base:Hp(e.basePubkey.toBuffer()),seed:e.seed,lamports:e.lamports,space:e.space,programId:Hp(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 yy({keys:n,programId:this.programId,data:t})}static createNonceAccount(e){const t=new by;"basePubkey"in e&&"seed"in e?t.add(Ry.createAccountWithSeed({fromPubkey:e.fromPubkey,newAccountPubkey:e.noncePubkey,basePubkey:e.basePubkey,seed:e.seed,lamports:e.lamports,space:Ny,programId:this.programId})):t.add(Ry.createAccount({fromPubkey:e.fromPubkey,newAccountPubkey:e.noncePubkey,lamports:e.lamports,space:Ny,programId:this.programId}));const n={noncePubkey:e.noncePubkey,authorizedPubkey:e.authorizedPubkey};return t.add(this.nonceInitialize(n)),t}static nonceInitialize(e){const t=Sy(xy.InitializeNonceAccount,{authorized:Hp(e.authorizedPubkey.toBuffer())}),n={keys:[{pubkey:e.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:vy,isSigner:!1,isWritable:!1},{pubkey:wy,isSigner:!1,isWritable:!1}],programId:this.programId,data:t};return new yy(n)}static nonceAdvance(e){const t=Sy(xy.AdvanceNonceAccount),n={keys:[{pubkey:e.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:vy,isSigner:!1,isWritable:!1},{pubkey:e.authorizedPubkey,isSigner:!0,isWritable:!1}],programId:this.programId,data:t};return new yy(n)}static nonceWithdraw(e){const t=Sy(xy.WithdrawNonceAccount,{lamports:e.lamports});return new yy({keys:[{pubkey:e.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:e.toPubkey,isSigner:!1,isWritable:!0},{pubkey:vy,isSigner:!1,isWritable:!1},{pubkey:wy,isSigner:!1,isWritable:!1},{pubkey:e.authorizedPubkey,isSigner:!0,isWritable:!1}],programId:this.programId,data:t})}static nonceAuthorize(e){const t=Sy(xy.AuthorizeNonceAccount,{authorized:Hp(e.newAuthorizedPubkey.toBuffer())});return new yy({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=Sy(xy.AllocateWithSeed,{base:Hp(e.basePubkey.toBuffer()),seed:e.seed,space:e.space,programId:Hp(e.programId.toBuffer())}),n=[{pubkey:e.accountPubkey,isSigner:!1,isWritable:!0},{pubkey:e.basePubkey,isSigner:!0,isWritable:!1}]}else{t=Sy(xy.Allocate,{space:e.space}),n=[{pubkey:e.accountPubkey,isSigner:!0,isWritable:!0}]}return new yy({keys:n,programId:this.programId,data:t})}}function By(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Dy,My;function Oy(){if(My)return Dy;My=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,i){var s,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(),i);if("[object Array]"===(d=e.call(r))){for(a="[",o=r.length-1,s=0;s<o;s++)a+=n(r[s],!0)+",";return o>-1&&(a+=n(r[s],!0)),a+"]"}if("[object Object]"===d){for(o=(c=t(r).sort()).length,a="",s=0;s<o;)void 0!==(u=n(r[l=c[s]],!1))&&(a&&(a+=","),a+=JSON.stringify(l)+":"+u),s++;return"{"+a+"}"}return JSON.stringify(r);case"function":case"undefined":return i?null:void 0;case"string":return JSON.stringify(r);default:return isFinite(r)?r:null}}return Dy=function(e){var t=n(e,!1);if(void 0!==t)return""+t}}Ry.programId=new Xp("11111111111111111111111111111111"),new Xp("BPFLoader2111111111111111111111111111111111");var Uy=By(Oy());function Ly(e){let t=0;for(;e>1;)e/=2,t++;return t}class Py{constructor(e,t,n,r,i){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=i}getEpoch(e){return this.getEpochAndSlotIndex(e)[0]}getEpochAndSlotIndex(e){if(e<this.firstNormalSlot){const n=Ly(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)))-Ly(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+Ly(32)):this.slotsPerEpoch}}var Fy=globalThis.fetch;class $y extends gp{constructor(e,t,n){super(e=>{const n=function(e,t){return new dp(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 Ky{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}(Gy,e),n=e.length-56;oy(n>=0,"lookup table is invalid"),oy(n%32==0,"lookup table is invalid");const r=n/32,{addresses:i}=wu.struct([wu.seq(ty(),r,"addresses")]).decode(e.slice(56));return{deactivationSlot:t.deactivationSlot,lastExtendedSlot:t.lastExtendedSlot,lastExtendedSlotStartIndex:t.lastExtendedStartIndex,authority:0!==t.authority.length?new Xp(t.authority[0]):void 0,addresses:i.map(e=>new Xp(e))}}}const Gy={index:1,layout:wu.struct([wu.u32("typeIndex"),_y("deactivationSlot"),wu.nu64("lastExtendedSlot"),wu.u8("lastExtendedStartIndex"),wu.u8(),wu.seq(ty(),wu.offset(wu.u8(),-1),"authority")])},Hy=/^[^:]+:\/\/([^:[]+|\[[^\]]+\])(:\d+)?(.*)/i;const Wy=Qm(Km(Xp),Vm(),e=>new Xp(e)),qy=zm([Vm(),Gm("base64")]),jy=Qm(Km(ga.Buffer),qy,e=>ga.Buffer.from(e[0],"base64"));function Vy(e){let t,n;if("string"==typeof e)t=e;else if(e){const{commitment:r,...i}=e;t=r,n=i}return{commitment:t,config:n}}function zy(e){return e.map(e=>"memcmp"in e?{...e,memcmp:{...e.memcmp,encoding:e.memcmp.encoding??"base58"}}:e)}function Xy(e){return Jm([Xm({jsonrpc:Gm("2.0"),id:Vm(),result:e}),Xm({jsonrpc:Gm("2.0"),id:Vm(),error:Xm({code:Ym(),message:Vm(),data:qm(Pm("any",()=>!0))})})])}const Jy=Xy(Ym());function Yy(e){return Qm(Xy(e),Jy,t=>"error"in t?t:{...t,result:Om(t.result,e)})}function Qy(e){return Yy(Xm({context:Xm({slot:Wm()}),value:e}))}function Zy(e){return Xm({context:Xm({slot:Wm()}),value:e})}function eb(e,t){if(0===e)return new hy({header:t.header,staticAccountKeys:t.accountKeys.map(e=>new Xp(e)),recentBlockhash:t.recentBlockhash,compiledInstructions:t.instructions.map(e=>({programIdIndex:e.programIdIndex,accountKeyIndexes:e.accounts,data:eu.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 fy({header:t.header,staticAccountKeys:t.accountKeys.map(e=>new Xp(e)),recentBlockhash:t.recentBlockhash,compiledInstructions:t.instructions.map(e=>({programIdIndex:e.programIdIndex,accountKeyIndexes:e.accounts,data:eu.decode(e.data)})),transactionConfig:e})}return new dy(t)}const tb=Xm({foundation:Wm(),foundationTerm:Wm(),initial:Wm(),taper:Wm(),terminal:Wm()}),nb=Yy(Fm(Hm(Xm({epoch:Wm(),effectiveSlot:Wm(),amount:Wm(),postBalance:Wm(),commission:qm(Hm(Wm()))})))),rb=Fm(Xm({slot:Wm(),prioritizationFee:Wm()})),ib=Xm({total:Wm(),validator:Wm(),foundation:Wm(),epoch:Wm()}),sb=Xm({epoch:Wm(),slotIndex:Wm(),slotsInEpoch:Wm(),absoluteSlot:Wm(),blockHeight:qm(Wm()),transactionCount:qm(Wm())}),ob=Xm({slotsPerEpoch:Wm(),leaderScheduleSlotOffset:Wm(),warmup:$m(),firstNormalEpoch:Wm(),firstNormalSlot:Wm()}),ab=jm(Vm(),Fm(Wm())),cb=Hm(Jm([Xm({}),Vm()])),lb=Xm({err:cb}),ub=Gm("receivedSignature"),db=Xm({"solana-core":Vm(),"feature-set":qm(Wm())}),hb=Xm({program:Vm(),programId:Wy,parsed:Ym()}),gb=Xm({programId:Wy,accounts:Fm(Wy),data:Vm()}),fb=Qy(Xm({err:Hm(Jm([Xm({}),Vm()])),logs:Hm(Fm(Vm())),accounts:qm(Hm(Fm(Hm(Xm({executable:$m(),owner:Vm(),lamports:Wm(),data:Fm(Vm()),rentEpoch:qm(Wm())}))))),unitsConsumed:qm(Wm()),returnData:qm(Hm(Xm({programId:Vm(),data:zm([Vm(),Gm("base64")])}))),innerInstructions:qm(Hm(Fm(Xm({index:Wm(),instructions:Fm(Jm([hb,gb]))}))))})),mb=Qy(Xm({byIdentity:jm(Vm(),Fm(Wm())),range:Xm({firstSlot:Wm(),lastSlot:Wm()})}));const pb=Yy(tb),yb=Yy(ib),bb=Yy(rb),vb=Yy(sb),wb=Yy(ob),Eb=Yy(ab),Ab=Yy(Wm()),kb=Qy(Xm({total:Wm(),circulating:Wm(),nonCirculating:Wm(),nonCirculatingAccounts:Fm(Wy)})),Sb=Xm({amount:Vm(),uiAmount:Hm(Wm()),decimals:Wm(),uiAmountString:qm(Vm())}),Tb=Qy(Fm(Xm({address:Wy,amount:Vm(),uiAmount:Hm(Wm()),decimals:Wm(),uiAmountString:qm(Vm())}))),Ib=Qy(Fm(Xm({pubkey:Wy,account:Xm({executable:$m(),owner:Wy,lamports:Wm(),data:jy,rentEpoch:Wm()})}))),Nb=Xm({program:Vm(),parsed:Ym(),space:Wm()}),Cb=Qy(Fm(Xm({pubkey:Wy,account:Xm({executable:$m(),owner:Wy,lamports:Wm(),data:Nb,rentEpoch:Wm()})}))),_b=Qy(Fm(Xm({lamports:Wm(),address:Wy}))),xb=Xm({executable:$m(),owner:Wy,lamports:Wm(),data:jy,rentEpoch:Wm()}),Rb=Xm({pubkey:Wy,account:xb}),Bb=Qm(Jm([Km(ga.Buffer),Nb]),Jm([qy,Nb]),e=>Array.isArray(e)?Om(e,jy):e),Db=Xm({executable:$m(),owner:Wy,lamports:Wm(),data:Bb,rentEpoch:Wm()}),Mb=Xm({pubkey:Wy,account:Db}),Ob=Xm({state:Jm([Gm("active"),Gm("inactive"),Gm("activating"),Gm("deactivating")]),active:Wm(),inactive:Wm()}),Ub=Yy(Fm(Xm({signature:Vm(),slot:Wm(),err:cb,memo:Hm(Vm()),blockTime:qm(Hm(Wm()))}))),Lb=Yy(Fm(Xm({signature:Vm(),slot:Wm(),err:cb,memo:Hm(Vm()),blockTime:qm(Hm(Wm()))}))),Pb=Xm({subscription:Wm(),result:Zy(xb)}),Fb=Xm({pubkey:Wy,account:xb}),$b=Xm({subscription:Wm(),result:Zy(Fb)}),Kb=Xm({parent:Wm(),slot:Wm(),root:Wm()}),Gb=Xm({subscription:Wm(),result:Kb}),Hb=Jm([Xm({type:Jm([Gm("firstShredReceived"),Gm("completed"),Gm("optimisticConfirmation"),Gm("root")]),slot:Wm(),timestamp:Wm()}),Xm({type:Gm("createdBank"),parent:Wm(),slot:Wm(),timestamp:Wm()}),Xm({type:Gm("frozen"),slot:Wm(),timestamp:Wm(),stats:Xm({numTransactionEntries:Wm(),numSuccessfulTransactions:Wm(),numFailedTransactions:Wm(),maxTransactionsPerEntry:Wm()})}),Xm({type:Gm("dead"),slot:Wm(),timestamp:Wm(),err:Vm()})]),Wb=Xm({subscription:Wm(),result:Hb}),qb=Xm({subscription:Wm(),result:Zy(Jm([lb,ub]))}),jb=Xm({subscription:Wm(),result:Wm()}),Vb=Xm({pubkey:Vm(),gossip:Hm(Vm()),tpu:Hm(Vm()),rpc:Hm(Vm()),version:Hm(Vm())}),zb=Xm({votePubkey:Vm(),nodePubkey:Vm(),activatedStake:Wm(),epochVoteAccount:$m(),epochCredits:Fm(zm([Wm(),Wm(),Wm()])),commission:Wm(),lastVote:Wm(),rootSlot:Hm(Wm())}),Xb=Yy(Xm({current:Fm(zb),delinquent:Fm(zb)})),Jb=Jm([Gm("processed"),Gm("confirmed"),Gm("finalized")]),Yb=Xm({slot:Wm(),confirmations:Hm(Wm()),err:cb,confirmationStatus:qm(Jb)}),Qb=Qy(Fm(Hm(Yb))),Zb=Yy(Wm()),ev=Xm({accountKey:Wy,writableIndexes:Fm(Wm()),readonlyIndexes:Fm(Wm())}),tv=Xm({computeUnitLimit:Hm(Wm()),heapSize:Hm(Wm()),loadedAccountsDataSizeLimit:Hm(Wm()),priorityFee:Hm(Wm())}),nv=Xm({signatures:Fm(Vm()),message:Xm({accountKeys:Fm(Vm()),header:Xm({numRequiredSignatures:Wm(),numReadonlySignedAccounts:Wm(),numReadonlyUnsignedAccounts:Wm()}),instructions:Fm(Xm({accounts:Fm(Wm()),data:Vm(),programIdIndex:Wm()})),recentBlockhash:Vm(),addressTableLookups:qm(Fm(ev)),transactionConfig:qm(Hm(tv))})}),rv=Xm({pubkey:Wy,signer:$m(),writable:$m(),source:qm(Jm([Gm("transaction"),Gm("lookupTable")]))}),iv=Xm({accountKeys:Fm(rv),signatures:Fm(Vm())}),sv=Xm({parsed:Ym(),program:Vm(),programId:Wy}),ov=Xm({accounts:Fm(Wy),data:Vm(),programId:Wy}),av=Qm(Jm([ov,sv]),Jm([Xm({parsed:Ym(),program:Vm(),programId:Vm()}),Xm({accounts:Fm(Vm()),data:Vm(),programId:Vm()})]),e=>Om(e,"accounts"in e?ov:sv)),cv=Xm({signatures:Fm(Vm()),message:Xm({accountKeys:Fm(rv),instructions:Fm(av),recentBlockhash:Vm(),addressTableLookups:qm(Hm(Fm(ev))),transactionConfig:qm(Hm(tv))})}),lv=Xm({accountIndex:Wm(),mint:Vm(),owner:qm(Vm()),programId:qm(Vm()),uiTokenAmount:Sb}),uv=Xm({writable:Fm(Wy),readonly:Fm(Wy)}),dv=Xm({err:cb,fee:Wm(),innerInstructions:qm(Hm(Fm(Xm({index:Wm(),instructions:Fm(Xm({accounts:Fm(Wm()),data:Vm(),programIdIndex:Wm()}))})))),preBalances:Fm(Wm()),postBalances:Fm(Wm()),logMessages:qm(Hm(Fm(Vm()))),preTokenBalances:qm(Hm(Fm(lv))),postTokenBalances:qm(Hm(Fm(lv))),loadedAddresses:qm(uv),computeUnitsConsumed:qm(Wm()),costUnits:qm(Wm())}),hv=Xm({err:cb,fee:Wm(),innerInstructions:qm(Hm(Fm(Xm({index:Wm(),instructions:Fm(av)})))),preBalances:Fm(Wm()),postBalances:Fm(Wm()),logMessages:qm(Hm(Fm(Vm()))),preTokenBalances:qm(Hm(Fm(lv))),postTokenBalances:qm(Hm(Fm(lv))),loadedAddresses:qm(uv),computeUnitsConsumed:qm(Wm()),costUnits:qm(Wm())}),gv=Jm([Gm(0),Gm(1),Gm("legacy")]),fv=Xm({pubkey:Vm(),lamports:Wm(),postBalance:Hm(Wm()),rewardType:Hm(Vm()),commission:qm(Hm(Wm()))}),mv=Yy(Hm(Xm({blockhash:Vm(),previousBlockhash:Vm(),parentSlot:Wm(),transactions:Fm(Xm({transaction:nv,meta:Hm(dv),version:qm(gv)})),rewards:qm(Fm(fv)),blockTime:Hm(Wm()),blockHeight:Hm(Wm())}))),pv=Yy(Hm(Xm({blockhash:Vm(),previousBlockhash:Vm(),parentSlot:Wm(),rewards:qm(Fm(fv)),blockTime:Hm(Wm()),blockHeight:Hm(Wm())}))),yv=Yy(Hm(Xm({blockhash:Vm(),previousBlockhash:Vm(),parentSlot:Wm(),transactions:Fm(Xm({transaction:iv,meta:Hm(dv),version:qm(gv)})),rewards:qm(Fm(fv)),blockTime:Hm(Wm()),blockHeight:Hm(Wm())}))),bv=Yy(Hm(Xm({blockhash:Vm(),previousBlockhash:Vm(),parentSlot:Wm(),transactions:Fm(Xm({transaction:cv,meta:Hm(hv),version:qm(gv)})),rewards:qm(Fm(fv)),blockTime:Hm(Wm()),blockHeight:Hm(Wm())}))),vv=Yy(Hm(Xm({blockhash:Vm(),previousBlockhash:Vm(),parentSlot:Wm(),transactions:Fm(Xm({transaction:iv,meta:Hm(hv),version:qm(gv)})),rewards:qm(Fm(fv)),blockTime:Hm(Wm()),blockHeight:Hm(Wm())}))),wv=Yy(Hm(Xm({blockhash:Vm(),previousBlockhash:Vm(),parentSlot:Wm(),rewards:qm(Fm(fv)),blockTime:Hm(Wm()),blockHeight:Hm(Wm())}))),Ev=Yy(Hm(Xm({blockhash:Vm(),previousBlockhash:Vm(),parentSlot:Wm(),transactions:Fm(Xm({transaction:nv,meta:Hm(dv)})),rewards:qm(Fm(fv)),blockTime:Hm(Wm())}))),Av=Yy(Hm(Xm({blockhash:Vm(),previousBlockhash:Vm(),parentSlot:Wm(),signatures:Fm(Vm()),blockTime:Hm(Wm())}))),kv=Yy(Hm(Xm({slot:Wm(),meta:Hm(dv),blockTime:qm(Hm(Wm())),transaction:nv,version:qm(gv)}))),Sv=Yy(Hm(Xm({slot:Wm(),transaction:cv,meta:Hm(hv),blockTime:qm(Hm(Wm())),version:qm(gv)}))),Tv=Qy(Xm({blockhash:Vm(),lastValidBlockHeight:Wm()})),Iv=Qy($m()),Nv=Yy(Fm(Xm({slot:Wm(),numTransactions:Wm(),numSlots:Wm(),samplePeriodSecs:Wm()}))),Cv=Qy(Hm(Xm({feeCalculator:Xm({lamportsPerSignature:Wm()})}))),_v=Yy(Vm()),xv=Yy(Vm()),Rv=Xm({err:cb,logs:Fm(Vm()),signature:Vm()}),Bv=Xm({result:Zy(Rv),subscription:Wm()}),Dv={"solana-client":"js/1.99.0"};class Mv{constructor(e,t){let n,r,i,s,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}=Vy(t),i=this._buildArgs([],n,void 0,r),s=Uy(i);return e[s]=e[s]??(async()=>{try{const e=Om(await this._rpcRequest("getBlockHeight",i),Yy(Wm()));if("error"in e)throw new Ay(e.error,"failed to get block height information");return e.result}finally{delete e[s]}})(),await e[s]}})(),t&&"string"==typeof t?this._commitment=t:t&&(this._commitment=t.commitment,this._confirmTransactionInitialTimeout=t.confirmTransactionInitialTimeout,n=t.wsEndpoint,r=t.httpHeaders,i=t.fetch,s=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(Hy);if(null==t)throw TypeError(`Failed to validate endpoint URL \`${e}\``);const[n,r,i,s]=t,o=e.startsWith("https:")?"wss:":"ws:",a=null==i?null:parseInt(i.slice(1),10);return`${o}//${r}${null==a?"":`:${a+1}`}${s}`}(e),this._rpcClient=function(e,t,n,r,i){const s=n||Fy;let o;return r&&(o=async(e,t)=>{const n=await new Promise((n,i)=>{try{r(e,t,(e,t)=>n([e,t]))}catch(e){i(e)}});return await s(...n)}),new ap(async(n,r)=>{const a={method:"POST",body:n,agent:void 0,headers:Object.assign({"Content-Type":"application/json"},t||{},Dv)};try{let t,n=5,c=500;for(;t=o?await o(e,a):await s(e,a),429===t.status&&!0!==i&&(n-=1,0!==n);)await ky(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,i,s,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 i=t.map(t=>e.request(t.methodName,t.args));e.request(i,(e,t)=>{e?r(e):n(t)})})}(this._rpcClient),this._rpcWebSocket=new $y(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}=Vy(t),i=this._buildArgs([e.toBase58()],n,void 0,r),s=Om(await this._rpcRequest("getBalance",i),Qy(Wm()));if("error"in s)throw new Ay(s.error,`failed to get balance for ${e.toBase58()}`);return s.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=Om(await this._rpcRequest("getBlockTime",[e]),Yy(Hm(Wm())));if("error"in t)throw new Ay(t.error,`failed to get block time for slot ${e}`);return t.result}async getMinimumLedgerSlot(){const e=Om(await this._rpcRequest("minimumLedgerSlot",[]),Yy(Wm()));if("error"in e)throw new Ay(e.error,"failed to get minimum ledger slot");return e.result}async getFirstAvailableBlock(){const e=Om(await this._rpcRequest("getFirstAvailableBlock",[]),Ab);if("error"in e)throw new Ay(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=Om(await this._rpcRequest("getSupply",[t]),kb);if("error"in n)throw new Ay(n.error,"failed to get supply");return n.result}async getTokenSupply(e,t){const n=this._buildArgs([e.toBase58()],t),r=Om(await this._rpcRequest("getTokenSupply",n),Qy(Sb));if("error"in r)throw new Ay(r.error,"failed to get token supply");return r.result}async getTokenAccountBalance(e,t){const n=this._buildArgs([e.toBase58()],t),r=Om(await this._rpcRequest("getTokenAccountBalance",n),Qy(Sb));if("error"in r)throw new Ay(r.error,"failed to get token account balance");return r.result}async getTokenAccountsByOwner(e,t,n){const{commitment:r,config:i}=Vy(n);let s=[e.toBase58()];"mint"in t?s.push({mint:t.mint.toBase58()}):s.push({programId:t.programId.toBase58()});const o=this._buildArgs(s,r,"base64",i),a=Om(await this._rpcRequest("getTokenAccountsByOwner",o),Ib);if("error"in a)throw new Ay(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 i=this._buildArgs(r,n,"jsonParsed"),s=Om(await this._rpcRequest("getTokenAccountsByOwner",i),Cb);if("error"in s)throw new Ay(s.error,`failed to get token accounts owned by account ${e.toBase58()}`);return s.result}async getLargestAccounts(e){const t={...e,commitment:e&&e.commitment||this.commitment},n=t.filter||t.commitment?[t]:[],r=Om(await this._rpcRequest("getLargestAccounts",n),_b);if("error"in r)throw new Ay(r.error,"failed to get largest accounts");return r.result}async getTokenLargestAccounts(e,t){const n=this._buildArgs([e.toBase58()],t),r=Om(await this._rpcRequest("getTokenLargestAccounts",n),Tb);if("error"in r)throw new Ay(r.error,"failed to get token largest accounts");return r.result}async getAccountInfoAndContext(e,t){const{commitment:n,config:r}=Vy(t),i=this._buildArgs([e.toBase58()],n,"base64",r),s=Om(await this._rpcRequest("getAccountInfo",i),Qy(Hm(xb)));if("error"in s)throw new Ay(s.error,`failed to get info about account ${e.toBase58()}`);return s.result}async getParsedAccountInfo(e,t){const{commitment:n,config:r}=Vy(t),i=this._buildArgs([e.toBase58()],n,"jsonParsed",r),s=Om(await this._rpcRequest("getAccountInfo",i),Qy(Hm(Db)));if("error"in s)throw new Ay(s.error,`failed to get info about account ${e.toBase58()}`);return s.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}=Vy(t),i=e.map(e=>e.toBase58()),s=this._buildArgs([i],n,"jsonParsed",r),o=Om(await this._rpcRequest("getMultipleAccounts",s),Qy(Fm(Hm(Db))));if("error"in o)throw new Ay(o.error,`failed to get info for accounts ${i}`);return o.result}async getMultipleAccountsInfoAndContext(e,t){const{commitment:n,config:r}=Vy(t),i=e.map(e=>e.toBase58()),s=this._buildArgs([i],n,"base64",r),o=Om(await this._rpcRequest("getMultipleAccounts",s),Qy(Fm(Hm(xb))));if("error"in o)throw new Ay(o.error,`failed to get info for accounts ${i}`);return o.result}async getMultipleAccountsInfo(e,t){return(await this.getMultipleAccountsInfoAndContext(e,t)).value}async getStakeActivation(e,t,n){const{commitment:r,config:i}=Vy(t),s=this._buildArgs([e.toBase58()],r,void 0,{...i,epoch:null!=n?n:i?.epoch}),o=Om(await this._rpcRequest("getStakeActivation",s),Yy(Ob));if("error"in o)throw new Ay(o.error,`failed to get Stake Activation ${e.toBase58()}`);return o.result}async getProgramAccounts(e,t){const{commitment:n,config:r}=Vy(t),{encoding:i,...s}=r||{},o=this._buildArgs([e.toBase58()],n,i||"base64",{...s,...s.filters?{filters:zy(s.filters)}:null}),a=await this._rpcRequest("getProgramAccounts",o),c=Fm(Rb),l=!0===s.withContext?Om(a,Qy(c)):Om(a,Yy(c));if("error"in l)throw new Ay(l.error,`failed to get accounts owned by program ${e.toBase58()}`);return l.result}async getParsedProgramAccounts(e,t){const{commitment:n,config:r}=Vy(t),i=this._buildArgs([e.toBase58()],n,"jsonParsed",r),s=Om(await this._rpcRequest("getProgramAccounts",i),Yy(Fm(Mb)));if("error"in s)throw new Ay(s.error,`failed to get accounts owned by program ${e.toBase58()}`);return s.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=eu.decode(n)}catch(e){throw new Error("signature must be base58 encoded: "+n)}return oy(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,i=!1;return{abortConfirmation:()=>{r&&(r(),r=void 0),null!=n&&(this.removeSignatureListener(n),n=void 0)},confirmationPromise:new Promise((s,o)=>{try{n=this.onSignature(t,(e,t)=>{n=void 0;const r={context:t,value:e};s({__type:my.PROCESSED,response:r})},e);const a=new Promise(e=>{null==n?e():r=this._onSubscriptionStateChange(n,t=>{"subscribed"===t&&e()})});(async()=>{if(await a,i)return;const n=await this.getSignatureStatus(t);if(i)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}i=!0,s({__type:my.PROCESSED,response:{context:r,value:c}})}})()}catch(e){o(e)}})}}async confirmTransactionUsingBlockHeightExceedanceStrategy({commitment:e,strategy:{abortSignal:t,lastValidBlockHeight:n,signature:r}}){let i=!1;const s=new Promise(t=>{const r=async()=>{try{return await this.getBlockHeight(e)}catch(e){return-1}};(async()=>{let e=await r();if(!i){for(;e<=n;){if(await ky(1e3),i)return;if(e=await r(),i)return}t({__type:my.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,s]);if(e.__type!==my.PROCESSED)throw new Yp(r);l=e.response}finally{i=!0,o()}return l}async confirmTransactionUsingDurableNonceStrategy({commitment:e,strategy:{abortSignal:t,minContextSlot:n,nonceAccountPubkey:r,nonceValue:i,signature:s}}){let o=!1;const a=new Promise(t=>{let s=i,a=null;const c=async()=>{try{const{context:t,value:i}=await this.getNonceAndContext(r,{commitment:e,minContextSlot:n});return a=t.slot,i?.nonce}catch(e){return s}};(async()=>{if(s=await c(),!o)for(;;){if(i!==s)return void t({__type:my.NONCE_INVALID,slotInWhichNonceDidAdvance:a});if(await ky(2e3),o)return;if(s=await c(),o)return}})()}),{abortConfirmation:c,confirmationPromise:l}=this.getTransactionConfirmationPromise({commitment:e,signature:s}),u=this.getCancellationPromise(t);let d;try{const t=await Promise.race([u,l,a]);if(t.__type===my.PROCESSED)d=t.response;else{let r;for(;;){const e=await this.getSignatureStatus(s);if(null==e)break;if(!(e.context.slot<(t.slotInWhichNonceDidAdvance??n))){r=e;break}await ky(400)}if(!r?.value)throw new Zp(s);{const t=e||"finalized",{confirmationStatus:n}=r.value;switch(t){case"processed":case"recent":if("processed"!==n&&"confirmed"!==n&&"finalized"!==n)throw new Zp(s);break;case"confirmed":case"single":case"singleGossip":if("confirmed"!==n&&"finalized"!==n)throw new Zp(s);break;case"finalized":case"max":case"root":if("finalized"!==n)throw new Zp(s)}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:my.TIMED_OUT,timeoutMs:r}),r)}),{abortConfirmation:i,confirmationPromise:s}=this.getTransactionConfirmationPromise({commitment:e,signature:t});let o;try{const e=await Promise.race([s,r]);if(e.__type!==my.PROCESSED)throw new Qp(t,e.timeoutMs/1e3);o=e.response}finally{clearTimeout(n),i()}return o}async getClusterNodes(){const e=Om(await this._rpcRequest("getClusterNodes",[]),Yy(Fm(Vb)));if("error"in e)throw new Ay(e.error,"failed to get cluster nodes");return e.result}async getVoteAccounts(e){const t=this._buildArgs([],e),n=Om(await this._rpcRequest("getVoteAccounts",t),Xb);if("error"in n)throw new Ay(n.error,"failed to get vote accounts");return n.result}async getSlot(e){const{commitment:t,config:n}=Vy(e),r=this._buildArgs([],t,void 0,n),i=Om(await this._rpcRequest("getSlot",r),Yy(Wm()));if("error"in i)throw new Ay(i.error,"failed to get slot");return i.result}async getSlotLeader(e){const{commitment:t,config:n}=Vy(e),r=this._buildArgs([],t,void 0,n),i=Om(await this._rpcRequest("getSlotLeader",r),Yy(Vm()));if("error"in i)throw new Ay(i.error,"failed to get slot leader");return i.result}async getSlotLeaders(e,t){const n=[e,t],r=Om(await this._rpcRequest("getSlotLeaders",n),Yy(Fm(Wy)));if("error"in r)throw new Ay(r.error,"failed to get slot leaders");return r.result}async getSignatureStatus(e,t){const{context:n,value:r}=await this.getSignatureStatuses([e],t);oy(1===r.length);return{context:n,value:r[0]}}async getSignatureStatuses(e,t){const n=[e];t&&n.push(t);const r=Om(await this._rpcRequest("getSignatureStatuses",n),Qb);if("error"in r)throw new Ay(r.error,"failed to get signature status");return r.result}async getTransactionCount(e){const{commitment:t,config:n}=Vy(e),r=this._buildArgs([],t,void 0,n),i=Om(await this._rpcRequest("getTransactionCount",r),Yy(Wm()));if("error"in i)throw new Ay(i.error,"failed to get transaction count");return i.result}async getTotalSupply(e){return(await this.getSupply({commitment:e,excludeNonCirculatingAccountsList:!0})).value.total}async getInflationGovernor(e){const t=this._buildArgs([],e),n=Om(await this._rpcRequest("getInflationGovernor",t),pb);if("error"in n)throw new Ay(n.error,"failed to get inflation");return n.result}async getInflationReward(e,t,n){const{commitment:r,config:i}=Vy(n),s=this._buildArgs([e.map(e=>e.toBase58())],r,void 0,{...i,epoch:null!=t?t:i?.epoch}),o=Om(await this._rpcRequest("getInflationReward",s),nb);if("error"in o)throw new Ay(o.error,"failed to get inflation reward");return o.result}async getInflationRate(){const e=Om(await this._rpcRequest("getInflationRate",[]),yb);if("error"in e)throw new Ay(e.error,"failed to get inflation rate");return e.result}async getEpochInfo(e){const{commitment:t,config:n}=Vy(e),r=this._buildArgs([],t,void 0,n),i=Om(await this._rpcRequest("getEpochInfo",r),vb);if("error"in i)throw new Ay(i.error,"failed to get epoch info");return i.result}async getEpochSchedule(){const e=Om(await this._rpcRequest("getEpochSchedule",[]),wb);if("error"in e)throw new Ay(e.error,"failed to get epoch schedule");const t=e.result;return new Py(t.slotsPerEpoch,t.leaderScheduleSlotOffset,t.warmup,t.firstNormalEpoch,t.firstNormalSlot)}async getLeaderSchedule(){const e=Om(await this._rpcRequest("getLeaderSchedule",[]),Eb);if("error"in e)throw new Ay(e.error,"failed to get leader schedule");return e.result}async getMinimumBalanceForRentExemption(e,t){const n=this._buildArgs([e],t),r=Om(await this._rpcRequest("getMinimumBalanceForRentExemption",n),Zb);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=Om(await this._rpcRequest("getRecentPerformanceSamples",e?[e]:[]),Nv);if("error"in t)throw new Ay(t.error,"failed to get recent performance samples");return t.result}async getFeeCalculatorForBlockhash(e,t){const n=this._buildArgs([e],t),r=Om(await this._rpcRequest("getFeeCalculatorForBlockhash",n),Cv);if("error"in r)throw new Ay(r.error,"failed to get fee calculator");const{context:i,value:s}=r.result;return{context:i,value:null!==s?s.feeCalculator:null}}async getFeeForMessage(e,t){const n=Hp(e.serialize()).toString("base64"),r=this._buildArgs([n],t),i=Om(await this._rpcRequest("getFeeForMessage",r),Qy(Hm(Wm())));if("error"in i)throw new Ay(i.error,"failed to get fee for message");if(null===i.result)throw new Error("invalid blockhash");return i.result}async getRecentPrioritizationFees(e){const t=e?.lockedWritableAccounts?.map(e=>e.toBase58()),n=t?.length?[t]:[],r=Om(await this._rpcRequest("getRecentPrioritizationFees",n),bb);if("error"in r)throw new Ay(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}=Vy(e),r=this._buildArgs([],t,void 0,n),i=Om(await this._rpcRequest("getLatestBlockhash",r),Tv);if("error"in i)throw new Ay(i.error,"failed to get latest blockhash");return i.result}async isBlockhashValid(e,t){const{commitment:n,config:r}=Vy(t),i=this._buildArgs([e],n,void 0,r),s=Om(await this._rpcRequest("isBlockhashValid",i),Iv);if("error"in s)throw new Ay(s.error,"failed to determine if the blockhash `"+e+"`is valid");return s.result}async getVersion(){const e=Om(await this._rpcRequest("getVersion",[]),Yy(db));if("error"in e)throw new Ay(e.error,"failed to get version");return e.result}async getGenesisHash(){const e=Om(await this._rpcRequest("getGenesisHash",[]),Yy(Vm()));if("error"in e)throw new Ay(e.error,"failed to get genesis hash");return e.result}async getBlock(e,t){const{commitment:n,config:r}=Vy(t),i=this._buildArgsAtLeastConfirmed([e],n,void 0,r),s=await this._rpcRequest("getBlock",i);try{switch(r?.transactionDetails){case"accounts":{const e=Om(s,yv);if("error"in e)throw e.error;return e.result}case"none":{const e=Om(s,pv);if("error"in e)throw e.error;return e.result}default:{const e=Om(s,mv);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:eb(n,e.message)},version:n}))}:null}}}catch(e){throw new Ay(e,"failed to get confirmed block")}}async getParsedBlock(e,t){const{commitment:n,config:r}=Vy(t),i=this._buildArgsAtLeastConfirmed([e],n,"jsonParsed",r),s=await this._rpcRequest("getBlock",i);try{switch(r?.transactionDetails){case"accounts":{const e=Om(s,vv);if("error"in e)throw e.error;return e.result}case"none":{const e=Om(s,wv);if("error"in e)throw e.error;return e.result}default:{const e=Om(s,bv);if("error"in e)throw e.error;return e.result}}}catch(e){throw new Ay(e,"failed to get block")}}async getBlockProduction(e){let t,n;if("string"==typeof e)n=e;else if(e){const{commitment:r,...i}=e;n=r,t=i}const r=this._buildArgs([],n,"base64",t),i=Om(await this._rpcRequest("getBlockProduction",r),mb);if("error"in i)throw new Ay(i.error,"failed to get block production information");return i.result}async getTransaction(e,t){const{commitment:n,config:r}=Vy(t),i=this._buildArgsAtLeastConfirmed([e],n,void 0,r),s=Om(await this._rpcRequest("getTransaction",i),kv);if("error"in s)throw new Ay(s.error,"failed to get transaction");const o=s.result;return o?{...o,transaction:{...o.transaction,message:eb(o.version,o.transaction.message)}}:o}async getParsedTransaction(e,t){const{commitment:n,config:r}=Vy(t),i=this._buildArgsAtLeastConfirmed([e],n,"jsonParsed",r),s=Om(await this._rpcRequest("getTransaction",i),Sv);if("error"in s)throw new Ay(s.error,"failed to get transaction");return s.result}async getParsedTransactions(e,t){const{commitment:n,config:r}=Vy(t),i=e.map(e=>({methodName:"getTransaction",args:this._buildArgsAtLeastConfirmed([e],n,"jsonParsed",r)}));return(await this._rpcBatchRequest(i)).map(e=>{const t=Om(e,Sv);if("error"in t)throw new Ay(t.error,"failed to get transactions");return t.result})}async getTransactions(e,t){const{commitment:n,config:r}=Vy(t),i=e.map(e=>({methodName:"getTransaction",args:this._buildArgsAtLeastConfirmed([e],n,void 0,r)}));return(await this._rpcBatchRequest(i)).map(e=>{const t=Om(e,kv);if("error"in t)throw new Ay(t.error,"failed to get transactions");const n=t.result;return n?{...n,transaction:{...n.transaction,message:eb(n.version,n.transaction.message)}}:n})}async getConfirmedBlock(e,t){const n=this._buildArgsAtLeastConfirmed([e],t),r=Om(await this._rpcRequest("getBlock",n),Ev);if("error"in r)throw new Ay(r.error,"failed to get confirmed block");const i=r.result;if(!i)throw new Error("Confirmed block "+e+" not found");const s={...i,transactions:i.transactions.map(({transaction:e,meta:t})=>{const n=new dy(e.message);return{meta:t,transaction:{...e,message:n}}})};return{...s,transactions:s.transactions.map(({transaction:e,meta:t})=>({meta:t,transaction:by.populate(e.message,e.signatures)}))}}async getBlocks(e,t,n){const r=this._buildArgsAtLeastConfirmed(void 0!==t?[e,t]:[e],n),i=Om(await this._rpcRequest("getBlocks",r),Yy(Fm(Wm())));if("error"in i)throw new Ay(i.error,"failed to get blocks");return i.result}async getBlockSignatures(e,t){const n=this._buildArgsAtLeastConfirmed([e],t,void 0,{transactionDetails:"signatures",rewards:!1}),r=Om(await this._rpcRequest("getBlock",n),Av);if("error"in r)throw new Ay(r.error,"failed to get block");const i=r.result;if(!i)throw new Error("Block "+e+" not found");return i}async getConfirmedBlockSignatures(e,t){const n=this._buildArgsAtLeastConfirmed([e],t,void 0,{transactionDetails:"signatures",rewards:!1}),r=Om(await this._rpcRequest("getBlock",n),Av);if("error"in r)throw new Ay(r.error,"failed to get confirmed block");const i=r.result;if(!i)throw new Error("Confirmed block "+e+" not found");return i}async getConfirmedTransaction(e,t){const n=this._buildArgsAtLeastConfirmed([e],t),r=Om(await this._rpcRequest("getTransaction",n),kv);if("error"in r)throw new Ay(r.error,"failed to get transaction");const i=r.result;if(!i)return i;const s=new dy(i.transaction.message),o=i.transaction.signatures;return{...i,transaction:by.populate(s,o)}}async getParsedConfirmedTransaction(e,t){const n=this._buildArgsAtLeastConfirmed([e],t,"jsonParsed"),r=Om(await this._rpcRequest("getTransaction",n),Sv);if("error"in r)throw new Ay(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=Om(e,Sv);if("error"in t)throw new Ay(t.error,"failed to get confirmed transactions");return t.result})}async getConfirmedSignaturesForAddress(e,t,n){let r={},i=await this.getFirstAvailableBlock();for(;!("until"in r)&&!(--t<=0||t<i);)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 s=await this.getSlot("finalized");for(;!("before"in r||++n>s);)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),i=Om(await this._rpcRequest("getConfirmedSignaturesForAddress2",r),Ub);if("error"in i)throw new Ay(i.error,"failed to get confirmed signatures for address");return i.result}async getSignaturesForAddress(e,t,n){const r=this._buildArgsAtLeastConfirmed([e.toBase58()],n,void 0,t),i=Om(await this._rpcRequest("getSignaturesForAddress",r),Lb);if("error"in i)throw new Ay(i.error,"failed to get signatures for address");return i.result}async getAddressLookupTable(e,t){const{context:n,value:r}=await this.getAccountInfoAndContext(e,t);let i=null;return null!==r&&(i=new Ky({key:e,state:Ky.deserialize(r.data)})),{context:n,value:i}}async getNonceAndContext(e,t){const{context:n,value:r}=await this.getAccountInfoAndContext(e,t);let i=null;return null!==r&&(i=Cy.fromAccountData(r.data)),{context:n,value:i}}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=Om(await this._rpcRequest("requestAirdrop",[e.toBase58(),t]),_v);if("error"in n)throw new Ay(n.error,`airdrop to ${e.toBase58()} failed`);return n.result}async _blockhashWithExpiryBlockHeight(e){if(!e){for(;this._pollingBlockhash;)await ky(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 ky(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}=Vy(e),r=this._buildArgs([],t,"base64",n),i=Om(await this._rpcRequest("getStakeMinimumDelegation",r),Qy(Wm()));if("error"in i)throw new Ay(i.error,"failed to get stake minimum delegation");return i.result}async simulateTransaction(e,t,n){if("message"in e){const r=e.serialize(),i=ga.Buffer.from(r).toString("base64");if(Array.isArray(t)||void 0!==n)throw new Error("Invalid arguments");const s=t||{};s.encoding="base64","commitment"in s||(s.commitment=this.commitment),t&&"object"==typeof t&&"innerInstructions"in t&&(s.innerInstructions=t.innerInstructions);const o=[i,s],a=Om(await this._rpcRequest("simulateTransaction",o),fb);if("error"in a)throw new Error("failed to simulate transaction: "+a.error.message);return a.result}let r;if(e instanceof by){let t=e;r=new by,r.feePayer=t.feePayer,r.instructions=e.instructions,r.nonceInfo=t.nonceInfo,r.signatures=t.signatures}else r=by.populate(e),r._message=r._json=void 0;if(void 0!==t&&!Array.isArray(t))throw new Error("Invalid arguments");const i=t;if(r.nonceInfo&&i)r.sign(...i);else{let e=this._disableBlockhashCaching;for(;;){const t=await this._blockhashWithExpiryBlockHeight(e);if(r.lastValidBlockHeight=t.lastValidBlockHeight,r.recentBlockhash=t.blockhash,!i)break;if(r.sign(...i),!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 s=r._compile(),o=s.serialize(),a=r._serialize(o).toString("base64"),c={encoding:"base64",commitment:this.commitment};if(n){const e=(Array.isArray(n)?n:s.nonProgramIds()).map(e=>e.toBase58());c.accounts={encoding:"base64",addresses:e}}i&&(c.sigVerify=!0),t&&"object"==typeof t&&"innerInstructions"in t&&(c.innerInstructions=t.innerInstructions);const l=[a,c],u=Om(await this._rpcRequest("simulateTransaction",l),fb);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 Ey({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 i=e.signature.toString("base64");if(!this._blockhashInfo.transactionSignatures.includes(i)){this._blockhashInfo.transactionSignatures.push(i);break}t=!0}}const i=e.serialize();return await this.sendRawTransaction(i,n)}async sendRawTransaction(e,t){const n=Hp(e).toString("base64");return await this.sendEncodedTransaction(n,t)}async sendEncodedTransaction(e,t){const n={encoding:"base64"},r=t&&t.skipPreflight,i=!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),i&&(n.preflightCommitment=i);const s=[e,n],o=Om(await this._rpcRequest("sendTransaction",s),xv);if("error"in o){let e;throw"data"in o.error&&(e=o.error.data.logs),new Ey({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:i}=n;try{this._setSubscription(e,{...n,state:"subscribing"});const t=await this._rpcWebSocket.call(i,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:i}=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(i,[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}=Om(e,Pb);this._handleServerNotification(n,[t.value,t.context])}_makeSubscription(e,t){const n=this._nextClientSubscriptionId++,r=Uy([e.method,t]),i=this._subscriptionsByHash[r];return void 0===i?this._subscriptionsByHash[r]={...e,args:t,callbacks:new Set([e.callback]),state:"pending"}:i.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];oy(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:i}=Vy(n),s=this._buildArgs([e.toBase58()],r||this._commitment||"finalized","base64",i);return this._makeSubscription({callback:t,method:"accountSubscribe",unsubscribeMethod:"accountUnsubscribe"},s)}async removeAccountChangeListener(e){await this._unsubscribeClientSubscription(e,"account change")}_wsOnProgramAccountNotification(e){const{result:t,subscription:n}=Om(e,$b);this._handleServerNotification(n,[{accountId:t.value.pubkey,accountInfo:t.value.account},t.context])}onProgramAccountChange(e,t,n,r){const{commitment:i,config:s}=Vy(n),o=this._buildArgs([e.toBase58()],i||this._commitment||"finalized","base64",s||(r?{filters:zy(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}=Om(e,Bv);this._handleServerNotification(n,[t.value,t.context])}_wsOnSlotNotification(e){const{result:t,subscription:n}=Om(e,Gb);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}=Om(e,Wb);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 i=t||this._commitment;if(i||n||r){let t={};n&&(t.encoding=n),i&&(t.commitment=i),r&&(t=Object.assign(t,r)),e.push(t)}return e}_buildArgsAtLeastConfirmed(e,t,n,r){const i=t||this._commitment;if(i&&!["confirmed","finalized"].includes(i))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}=Om(e,qb);"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"),i=this._makeSubscription({callback:(e,n)=>{if("status"===e.type){t(e.result,n);try{this.removeSignatureListener(i)}catch(e){}}},method:"signatureSubscribe",unsubscribeMethod:"signatureUnsubscribe"},r);return i}onSignatureWithOptions(e,t,n){const{commitment:r,...i}={...n,commitment:n&&n.commitment||this._commitment||"finalized"},s=this._buildArgs([e],r,void 0,i),o=this._makeSubscription({callback:(e,n)=>{t(e,n);try{this.removeSignatureListener(o)}catch(e){}},method:"signatureSubscribe",unsubscribeMethod:"signatureUnsubscribe"},s);return o}async removeSignatureListener(e){await this._unsubscribeClientSubscription(e,"signature result")}_wsOnRootNotification(e){const{result:t,subscription:n}=Om(e,jb);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 Ov{constructor(e){this._keypair=void 0,this._keypair=e??Fp()}static generate(){return new Ov(Fp())}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=$p(t);for(let e=0;e<32;e++)if(n[e]!==r[e])throw new Error("provided secretKey is invalid")}return new Ov({publicKey:n,secretKey:e})}static fromSeed(e){const t=$p(e),n=new Uint8Array(64);return n.set(e),n.set(t,32),new Ov({publicKey:t,secretKey:n})}get publicKey(){return new Xp(this._keypair.publicKey)}get secretKey(){return new Uint8Array(this._keypair.secretKey)}}Object.freeze({CreateLookupTable:{index:0,layout:wu.struct([wu.u32("instruction"),_y("recentSlot"),wu.u8("bumpSeed")])},FreezeLookupTable:{index:1,layout:wu.struct([wu.u32("instruction")])},ExtendLookupTable:{index:2,layout:wu.struct([wu.u32("instruction"),_y(),wu.seq(ty(),wu.offset(wu.u32(),-8),"addresses")])},DeactivateLookupTable:{index:3,layout:wu.struct([wu.u32("instruction")])},CloseLookupTable:{index:4,layout:wu.struct([wu.u32("instruction")])}}),new Xp("AddressLookupTab1e1111111111111111111111111");const Uv=Object.freeze({RequestUnits:{index:0,layout:wu.struct([wu.u8("instruction"),wu.u32("units"),wu.u32("additionalFee")])},RequestHeapFrame:{index:1,layout:wu.struct([wu.u8("instruction"),wu.u32("bytes")])},SetComputeUnitLimit:{index:2,layout:wu.struct([wu.u8("instruction"),wu.u32("units")])},SetComputeUnitPrice:{index:3,layout:wu.struct([wu.u8("instruction"),_y("microLamports")])}});class Lv{constructor(){}static requestUnits(e){const t=Sy(Uv.RequestUnits,e);return new yy({keys:[],programId:this.programId,data:t})}static requestHeapFrame(e){const t=Sy(Uv.RequestHeapFrame,e);return new yy({keys:[],programId:this.programId,data:t})}static setComputeUnitLimit(e){const t=Sy(Uv.SetComputeUnitLimit,e);return new yy({keys:[],programId:this.programId,data:t})}static setComputeUnitPrice(e){const t=Sy(Uv.SetComputeUnitPrice,{microLamports:BigInt(e.microLamports)});return new yy({keys:[],programId:this.programId,data:t})}}var Pv;Lv.programId=new Xp("ComputeBudget111111111111111111111111111111"),wu.struct([wu.u8("numSignatures"),wu.u8("padding"),wu.u16("signatureOffset"),wu.u16("signatureInstructionIndex"),wu.u16("publicKeyOffset"),wu.u16("publicKeyInstructionIndex"),wu.u16("messageDataOffset"),wu.u16("messageDataSize"),wu.u16("messageInstructionIndex")]),new Xp("Ed25519SigVerify111111111111111111111111111"),Pp.utils.isValidPrivateKey,wu.struct([wu.u8("numSignatures"),wu.u16("signatureOffset"),wu.u8("signatureInstructionIndex"),wu.u16("ethAddressOffset"),wu.u8("ethAddressInstructionIndex"),wu.u16("messageDataOffset"),wu.u16("messageDataSize"),wu.u8("messageInstructionIndex"),wu.blob(20,"ethAddress"),wu.blob(64,"signature"),wu.u8("recoveryId")]),new Xp("KeccakSecp256k11111111111111111111111111111"),new Xp("StakeConfig11111111111111111111111111111111");class Fv{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}}Pv=Fv,Fv.default=new Pv(0,0,Xp.default),Object.freeze({Initialize:{index:0,layout:wu.struct([wu.u32("instruction"),((e="authorized")=>wu.struct([ty("staker"),ty("withdrawer")],e))(),((e="lockup")=>wu.struct([wu.ns64("unixTimestamp"),wu.ns64("epoch"),ty("custodian")],e))()])},Authorize:{index:1,layout:wu.struct([wu.u32("instruction"),ty("newAuthorized"),wu.u32("stakeAuthorizationType")])},Delegate:{index:2,layout:wu.struct([wu.u32("instruction")])},Split:{index:3,layout:wu.struct([wu.u32("instruction"),wu.ns64("lamports")])},Withdraw:{index:4,layout:wu.struct([wu.u32("instruction"),wu.ns64("lamports")])},Deactivate:{index:5,layout:wu.struct([wu.u32("instruction")])},Merge:{index:7,layout:wu.struct([wu.u32("instruction")])},AuthorizeWithSeed:{index:8,layout:wu.struct([wu.u32("instruction"),ty("newAuthorized"),wu.u32("stakeAuthorizationType"),ny("authoritySeed"),ty("authorityOwner")])}}),new Xp("Stake11111111111111111111111111111111111111"),Object.freeze({InitializeAccount:{index:0,layout:wu.struct([wu.u32("instruction"),((e="voteInit")=>wu.struct([ty("nodePubkey"),ty("authorizedVoter"),ty("authorizedWithdrawer"),wu.u8("commission")],e))()])},Authorize:{index:1,layout:wu.struct([wu.u32("instruction"),ty("newAuthorized"),wu.u32("voteAuthorizationType")])},Withdraw:{index:3,layout:wu.struct([wu.u32("instruction"),wu.ns64("lamports")])},UpdateValidatorIdentity:{index:4,layout:wu.struct([wu.u32("instruction")])},AuthorizeWithSeed:{index:10,layout:wu.struct([wu.u32("instruction"),((e="voteAuthorizeWithSeedArgs")=>wu.struct([wu.u32("voteAuthorizationType"),ty("currentAuthorityDerivedKeyOwnerPubkey"),ny("currentAuthorityDerivedKeySeed"),ty("newAuthorized")],e))()])}}),new Xp("Vote111111111111111111111111111111111111111"),new Xp("Va1idator1nfo111111111111111111111111111111"),Xm({name:Vm(),website:qm(Vm()),details:qm(Vm()),iconUrl:qm(Vm()),keybaseUsername:qm(Vm())}),new Xp("Vote111111111111111111111111111111111111111"),wu.struct([ty("nodePubkey"),ty("authorizedWithdrawer"),wu.u8("commission"),wu.nu64(),wu.seq(wu.struct([wu.nu64("slot"),wu.u32("confirmationCount")]),wu.offset(wu.u32(),-8),"votes"),wu.u8("rootSlotValid"),wu.nu64("rootSlot"),wu.nu64(),wu.seq(wu.struct([wu.nu64("epoch"),ty("authorizedVoter")]),wu.offset(wu.u32(),-8),"authorizedVoters"),wu.struct([wu.seq(wu.struct([ty("authorizedPubkey"),wu.nu64("epochOfLastAuthorizedSwitch"),wu.nu64("targetEpoch")]),32,"buf"),wu.nu64("idx"),wu.u8("isEmpty")],"priorVoters"),wu.nu64(),wu.seq(wu.struct([wu.nu64("epoch"),wu.nu64("credits"),wu.nu64("prevCredits")]),wu.offset(wu.u32(),-8),"epochCredits"),wu.struct([wu.nu64("slot"),wu.nu64("timestamp")],"lastTimestamp")]);function $v(e){return/^0x[a-fA-F0-9]{64}$/.test(e)}function Kv(e){const t=new Map;for(const n of e)t.set(an(n.symbol),n);return t}function Gv(e,t,n){const r=function(e,t){return e.get(an(t))}(e,t);if(!r){throw Pt(`Token ${t} not supported for ${n}. Supported: ${Array.from(e.keys()).join(", ")}`,"tokenSymbol")}return r}function Hv(e){if(null==e||!$v(e))throw Ut("privateKey","a 0x-prefixed 64-character hex string (e.g., 0x1234...abcd)","Ethereum private key")}function Wv(e,t,n){return{symbol:e,quantity:t,decimals:n,contractAddress:null,isNative:!0}}function qv(e,t){return{symbol:e.symbol,quantity:t,decimals:e.decimals??18,contractAddress:e.contractAddress,isNative:!1}}function jv(e,t){return{symbol:e.symbol,quantity:t,decimals:e.decimals??9,contractAddress:e.mintAddress,isNative:e.isNative??!1}}function Vv(e,t,n){const r=e.find(e=>e.symbol===t);if(!r){const r=e.map(e=>e.symbol).join(", ");throw Ot("tokenSymbol",`Unsupported ${n} token: ${t}. Supported: ${r}`)}return r}const zv={Ethereum:"Ethereum bridging not configured. Provide ethereumPrivateKey in config.",Solana:"Solana bridging not configured. Provide solanaPrivateKey in config."};function Xv(e,t,n){if(void 0===e)throw Pt(n??zv[t],`${t.toLowerCase()}Strategy`);return e}function Jv(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 Yv="Token symbol resolution failed. This is an internal error - BridgeService should resolve tokenId to symbol before calling strategy.",Qv="Bridge request ID missing from RequestTokenBridgeOut response",Zv="BridgeTokenOut response missing transaction hash";function ew(e){if(void 0===e||""===e)throw Pt(Yv,"tokenSymbol");return e}function tw(e,t){if(!n(e)){throw Ut(t??"address","a valid 0x-prefixed Ethereum address",e)}}function nw(e,t){try{return new Xp(e)}catch{throw Ut(t??"address","a valid Solana address (base58)",e)}}function rw(e){try{return new Xp(e)}catch{throw Ut("address","a valid Solana address (base58)",e)}}function iw(e){const t={};for(const[n,r]of Object.entries(e))void 0!==r&&(r&&"object"==typeof r&&!Array.isArray(r)?t[n]=iw(r):t[n]=r);return t}function sw(e,t){const n=Pn(e,-1);if(n<=0)throw new Error(`Invalid bridge amount for ${t}: "${e}". Amount must be a positive number.`);return n}var ow,aw,cw,lw,uw,dw;function hw(){return aw?ow:(aw=1,ow={space:"",cycles:!1,replacer:(e,t)=>t,stringify:JSON.stringify})}function gw(){return lw?cw:(lw=1,cw={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 fw(){if(dw)return uw;dw=1;const e=hw(),t=gw().isFunction,n=gw().isBoolean,r=gw().isObject,i=gw().isArray,s=gw().isRegex,o=gw().assign,a=gw().keys;return uw=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&&(m=l.compare,function(e){return function(t,n){const r={key:t,value:e[t]},i={key:n,value:e[n]};return m(r,i)}});var m;d||g(c);const p=[];return function e(t,n,o,c){const l=u?"\n"+new Array(c+1).join(u):"",m=u?": ":":";if(o=function(e){return null==e?e:s(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(i(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!==p.indexOf(o))return g("[Circular]");p.push(o)}const t=a(o).sort(f&&f(o)),n=[];for(let r=0;r<t.length;r++){const i=t[r],s=e(o,i,o[i],c+1);if(!s)continue;const a=g(i)+m+s;n.push(l+u+a)}return p.splice(p.indexOf(o),1),"{"+n.join(",")+l+"}"}}}({"":c},"",c,0)},uw}var mw=na(fw());let pw=null;if("undefined"==typeof window&&"undefined"!=typeof require)try{pw=v}catch{}function yw(){if(void 0!==pw?.randomUUID)try{return pw.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 bw={name:"GalaConnect",chainId:1},vw=[{name:"destinationChainId",type:"uint256"},{name:"destinationChainTxFee",type:"destinationChainTxFee"},{name:"quantity",type:"string"},{name:"recipient",type:"string"},{name:"tokenInstance",type:"tokenInstance"},{name:"uniqueKey",type:"string"}],ww=[{name:"collection",type:"string"},{name:"category",type:"string"},{name:"type",type:"string"},{name:"additionalKey",type:"string"}],Ew=[{name:"collection",type:"string"},{name:"category",type:"string"},{name:"type",type:"string"},{name:"additionalKey",type:"string"},{name:"instance",type:"string"}],Aw=[{name:"name",type:"string"},{name:"symbol",type:"string"}],kw={GalaTransaction:vw,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:ww,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:Ew,externalQuoteToken:Aw,tokenInstance:Ew},Sw={GalaTransaction:vw,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:ww,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:Aw,externalQuoteToken:Aw,externalCrossRateToken:Aw,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:Ew,tokenInstance:Ew};function Tw(e){return e?Sw:kw}async function Iw(e,t){const{wallet:n}=t,r=e.uniqueKey??`galaconnect-operation-${yw()}`,i="string"==typeof e.destinationChainId?$n(e.destinationChainId,1):e.destinationChainId,s=function(e){const t={...e,galaDecimals:"string"==typeof e.galaDecimals?$n(e.galaDecimals,0):e.galaDecimals,timestamp:"string"==typeof e.timestamp?$n(e.timestamp,0):e.timestamp};if(e.galaExchangeRate&&(t.galaExchangeRate={...e.galaExchangeRate,timestamp:"string"==typeof e.galaExchangeRate.timestamp?$n(e.galaExchangeRate.timestamp,0):e.galaExchangeRate.timestamp}),e.galaExchangeCrossRate){const n=e.galaExchangeCrossRate;t.galaExchangeCrossRate={...n,timestamp:"string"==typeof n.timestamp?$n(n.timestamp,0):n.timestamp},n.baseTokenCrossRate&&(t.galaExchangeCrossRate.baseTokenCrossRate={...n.baseTokenCrossRate,timestamp:"string"==typeof n.baseTokenCrossRate.timestamp?$n(n.baseTokenCrossRate.timestamp,0):n.baseTokenCrossRate.timestamp}),n.quoteTokenCrossRate&&(t.galaExchangeCrossRate.quoteTokenCrossRate={...n.quoteTokenCrossRate,timestamp:"string"==typeof n.quoteTokenCrossRate.timestamp?$n(n.quoteTokenCrossRate.timestamp,0):n.quoteTokenCrossRate.timestamp})}return t}(e.destinationChainTxFee),o=Boolean(s.galaExchangeCrossRate),a={destinationChainId:i,destinationChainTxFee:iw(o?{...s,galaExchangeRate:void 0}:{...s,galaExchangeCrossRate:void 0}),quantity:e.quantity,recipient:e.recipient,tokenInstance:e.tokenInstance,uniqueKey:r},c=Tw(o),l=await n.signTypedData(bw,c,a),u=`Ethereum Signed Message:\n${mw({domain:bw,message:a,primaryType:"GalaTransaction",types:c}).length}`;return{...a,signature:l,prefix:u,types:c,domain:bw}}async function Nw(e,t){const{amount:n,recipientAddress:r,tokenSymbol:i}=e,{galaConnectClient:s,tokenMetadataResolver:o,ethereumWallet:a,destinationChainId:c,destinationChain:l,validateRecipientAddress:u}=t,d=ew(i);sw(n,d),u(r,"recipient");const h=await o.getTokenMetadata(d),g=await s.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}),m=await Iw(f,{wallet:a}),p=function(e){if(void 0===e||""===e)throw Pt(Qv,"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 s.requestBridgeOut(m)));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 Pt(Zv,"transactionHash");return t}(await s.bridgeTokenOut({bridgeFromChannel:"asset",bridgeRequestId:p})),tokenSymbol:d,amount:n,feePaid:g.estimatedTotalTxFeeInGala,baseUrl:s.getBaseUrl()})}var Cw;!function(e){e[e.PENDING=0]="PENDING",e[e.SUBMITTED=1]="SUBMITTED",e[e.CONFIRMED=2]="CONFIRMED",e[e.PROCESSING=3]="PROCESSING",e[e.FINALIZING=4]="FINALIZING",e[e.COMPLETED=5]="COMPLETED",e[e.FAILED=6]="FAILED",e[e.DELIVERY_FAILED=7]="DELIVERY_FAILED"}(Cw||(Cw={}));const _w={COMPLETED:Cw.COMPLETED,FAILED:Cw.FAILED,DELIVERY_FAILED:Cw.DELIVERY_FAILED};class xw{constructor(e){if(this.lastTimestamp=0,this.pendingPromise=Promise.resolve(),this.chainLength=0,this.maxChainLength=1e3,e<=0)throw Gt("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,i=Math.max(0,this.minIntervalMs-r);i>0&&await new Promise(e=>setTimeout(e,i)),this.lastTimestamp=Date.now();try{const n=await e();t(n)}catch(e){n(yt(e)?e:new Error(bt(e)))}}),this.chainLength++,this.chainLength>=this.maxChainLength){this.chainLength=0;const e=this.pendingPromise;this.pendingPromise=e.then(()=>Promise.resolve())}return r}}const Rw={maxRetries:3,initialDelayMs:1e3,maxDelayMs:3e4,backoffMultiplier:2,jitterFactor:.1},Bw=new Set([408,429,500,502,503,504]),Dw=[/ECONNRESET/i,/ECONNREFUSED/i,/ETIMEDOUT/i,/ENOTFOUND/i,/EAI_AGAIN/i,/socket hang up/i,/network/i,/timeout/i,/aborted/i];function Mw(e){if(null!=e&&"object"==typeof e){const t=e;if("number"==typeof t.status)return Bw.has(t.status);if("number"==typeof t.statusCode)return Bw.has(t.statusCode);const n=wt(e);if("string"==typeof n&&("ECONNRESET"===n||"ECONNREFUSED"===n||"ETIMEDOUT"===n||"ENOTFOUND"===n||"EAI_AGAIN"===n))return!0}const t=bt(e);return Dw.some(e=>e.test(t))}function Ow(e,t){const n=t.initialDelayMs*Math.pow(t.backoffMultiplier,e-1),r=Math.min(n,t.maxDelayMs),i=r*t.jitterFactor*Math.random();return Math.floor(r+i)}function Uw(e){return new Promise(t=>setTimeout(t,e))}function Lw(e,t){return Xv(e.get("Ethereum"),"Ethereum",t)}function Pw(e,t){return Xv(e.get("Solana"),"Solana",t)}function Fw(e,t){return e??t.getWalletAddress()}async function $w(e,t,n,r,i){const s=await t.getTokenMetadata(r);return function(e){const t="string"==typeof e.timestamp?$n(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:s.descriptor}))}async function Kw(e,t){return function(e){const t=$n(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(_w.COMPLETED),isFailed:t===Number(_w.FAILED)||t===Number(_w.DELIVERY_FAILED)}}(await e.getBridgeStatus(t))}function Gw(e,t,n){try{const n=function(e,t){if(!nr(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,i,s,...o]=n;if(""===r||""===i||""===s)throw new Error("Collection, category, and type must be non-empty");const a=o.join(t);if(void 0===r||void 0===i||void 0===s||""===a)throw new Error("AdditionalKey must be non-empty");return{collection:r,category:i,type:s,additionalKey:a}}catch(r){throw function(e,t,n,r){const i=e?.split?.(t)??[],s=void 0!==n?` (${n})`:"";return new Ct(`Invalid ${"|"===t?"pipe":"dollar"}-delimited token: "${e}" (${i.length} parts)${s}. Expected format: "collection${t}category${t}type${t}additionalKey" (4 parts minimum). Received: [${i.map(e=>`"${e}"`).join(", ")}]. Error: ${bt(r)}`,"token",`INVALID_${"|"===t?"PIPE":"DOLLAR"}_DELIMITED_TOKEN`)}(e,t,n,r)}}function Hw(e){return Gw(e,"|","pipe-delimited token")}function Ww(e){return nr(e)&&e.includes("|")}function qw(e){return"string"==typeof e&&e.includes("$")}function jw(e){if("object"!=typeof e||null===e)return!1;const t=e,n=t.collection,r=t.category,i=t.type,s=t.additionalKey;return"string"==typeof n&&"string"==typeof r&&"string"==typeof i&&"string"==typeof s&&n.length>0&&r.length>0&&i.length>0&&s.length>0}function Vw(e){let t;if("string"==typeof e)t=Hw(e);else{if(!jw(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:No(t)}}function zw(e,t){let n;try{n=Kn(e,"amount")}catch(t){throw qt("amount",`${e} (${bt(t)})`)}if(!n.isFinite())throw qt("amount",e);const r=n.multipliedBy(Ws(10).pow(t));if(!r.isInteger())throw qt("amount",`${e} (cannot be represented with ${t} decimals)`);return BigInt(r.toFixed(0))}function Xw(e,t){return Ws(e.toString()).dividedBy(Ws(10).pow(t)).toFixed(t).replace(/\.?0+$/,"")}function Jw(e,t=6){const n=Ws(e);if(!n.isFinite())return"0";if(n.abs().lt(1e-6)&&!Vs(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+$/,"")}function Yw(e,t){const n=Ws(e),r=Ws(t);return n.comparedTo(r)}class Qw{constructor(e){this.cache=new Map,this.galaConnectClient=e.galaConnectClient}async getTokenMetadata(e){const t=cn(e),n=this.cache.get(t);if(n)return n;const r=zo[t];if(void 0!==r)return this.cache.set(t,r),r;const i=await this.fetchFromApi(e);return this.cache.set(t,i),i}hasMetadata(e){const t=cn(e);return this.cache.has(t)||t in zo}clearCache(){this.cache.clear()}async fetchFromApi(e){let t=e,n=await this.galaConnectClient.getBridgeConfigurations(t),r=n.find(e=>cn(e.symbol)===cn(t)&&e.verified);if(r||e.startsWith("G")||(t=`G${e}`,n=await this.galaConnectClient.getBridgeConfigurations(t),r=n.find(e=>cn(e.symbol)===cn(t)&&e.verified)),!r)throw new Error(`Unable to locate token metadata for ${e}`);return i={collection:r.collection,category:r.category,type:r.type,additionalKey:r.additionalKey},s=r.decimals,o=r.channel,{descriptor:{collection:i.collection,category:i.category,type:i.type,additionalKey:i.additionalKey},decimals:s,...void 0!==o?{channel:o}:{}};var i,s,o}}class Zw 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 eE=Ko,tE="https://galachain-gateway-chain-platform-galachain-mainnet.gala.com",nE=12,rE=!0,iE=3,sE=1e3;class oE{constructor(e){this.baseUrl=e.baseUrl??eE,this.galachainBaseUrl=e.galachainBaseUrl??tE,this.walletAddress=e.walletAddress,this.rateLimiter=new xw(e.requestsPerSecond??nE),this.defaultHeaders={"Content-Type":"application/json","X-Wallet-Address":this.walletAddress};const t=e.enableRetry??rE;this.retryOptions=t?{maxRetries:e.maxRetries??iE,initialDelayMs:e.retryInitialDelayMs??sE,...e.onRetry&&{onRetry:e.onRetry},shouldRetry:e=>Mw(e instanceof Zw?{status:e.status}:e)}:null}getBaseUrl(){return this.baseUrl}async getBridgeConfigurations(e){return vo(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?Ln(e,{rawBody:e}):{message:"Failed to fetch bridge configurations"},new Zw(n.status,"/v1/connect/bridge-configurations",t)}return(await n.json()).data.tokens},"GalaConnectClient.getBridgeConfigurations",void 0,e=>{if(e instanceof Zw)throw e;throw $t(e,"GalaConnectClient.getBridgeConfigurations")})}async fetchBridgeFee(e){return this.postJson("/v1/bridge/fee",e,{skipWalletHeader:!0})}async requestBridgeOut(e){return this.postJson("/v1/RequestTokenBridgeOut",e)}async bridgeTokenOut(e){return this.postJson("/v1/BridgeTokenOut",e)}async getBridgeStatus(e){return this.postJson("/v1/bridge/status",{hash:e})}async registerBridgeTransaction(e){return this.postJson("/v1/bridge/transaction",e)}async fetchBalances(e="asset"){return this.postJson("/v1/FetchBalances",{owner:this.walletAddress,channel:e},{baseUrl:this.galachainBaseUrl})}async postJson(e,t,n={}){return vo(async()=>{const r=n.baseUrl??this.baseUrl,i=new URL(e,r),s=n.skipWalletHeader?{"Content-Type":"application/json","X-Wallet-Address":""}:this.defaultHeaders,o=await this.request(i.toString(),{method:"POST",headers:s,body:JSON.stringify(t,(e,t)=>"bigint"==typeof t?t.toString():t)});if(!o.ok){const t=await o.text(),n=500,r=Ln(t,{rawBody:t.slice(0,n)});throw new Zw(o.status,e,r)}const a=await o.text();if(""!==a){const t=function(e){if(hn(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: ${bt(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 Zw)throw e;throw $t(e,t)})}async request(e,t){const n=async()=>this.rateLimiter.schedule(async()=>{const n={...this.defaultHeaders,...t.headers};""===n["X-Wallet-Address"]?delete n["X-Wallet-Address"]:n["X-Wallet-Address"]??(n["X-Wallet-Address"]=this.walletAddress);const 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(),i=await this.safeParseJson(n);throw new Zw(t,e,i)}}return r});return this.retryOptions?async function(e,t={}){const n={...Rw,...t},r=t.shouldRetry??(e=>Mw(e));let i;for(let s=1;s<=n.maxRetries+1;s++)try{return await e()}catch(e){if(i=e,s>n.maxRetries)break;if(!r(e,s))break;const o=Ow(s,n);t.onRetry&&t.onRetry(e,s,o),await new Promise(e=>setTimeout(e,o))}throw i}(n,this.retryOptions):n()}async safeParseJson(e){const t=await e.text();try{return JSON.parse(t)}catch{return{rawBody:t}}}}class aE{async waitForCompletion(e,t={}){const{pollInterval:n=15e3,timeout:r=27e5,onStatusUpdate:i}=t,s=Date.now();for(;;){const t=await this.getStatus(e);if(i&&i(t),t.status===Cw.COMPLETED||t.status===Cw.FAILED||t.status===Cw.DELIVERY_FAILED)return t;if(yn(s)>r)throw Ft(`Bridge transaction timed out after ${r}ms. Last status: ${t.status}`,e,"TIMEOUT");await new Promise(e=>setTimeout(e,n))}}}class cE extends aE{constructor(e,t){super(),this.galaConnectClient=e,this.tokenConfigs=t}async getStatus(e){return Kw(this.galaConnectClient,e)}getSupportedTokens(){return e=this.tokenConfigs,Array.from(e.keys());var e}isTokenSupported(e){return function(e,t){return e.has(an(t))}(this.tokenConfigs,e)}}async function lE(e,t,...n){const r=e[t];return"function"==typeof r?await r(...n):await e.getFunction(t)(...n)}class uE extends cE{constructor(e){const n=e.tokenConfigs??jo;super(e.galaConnectClient,Kv(n)),this.network="Ethereum",this.galaChainWalletAddress=e.galaChainWalletAddress,Hv(e.ethereumPrivateKey);const i=e.ethereumRpcUrl??"https://ethereum.publicnode.com";this.ethereumProvider=new r(i),this.ethereumWallet=new t(e.ethereumPrivateKey,this.ethereumProvider),this.ethereumWalletAddress=e.ethereumWalletAddress??this.ethereumWallet.address,this.ethereumBridgeContract=e.ethereumBridgeContract??"0x3F98b5A26EF3f04E1DA3B0B41dD350E8C8F3A7c2",this.tokenMetadataResolver=new Qw({galaConnectClient:this.galaConnectClient})}async estimateFee(e,t){return $w(this.galaConnectClient,this.tokenMetadataResolver,"Ethereum",e)}async bridgeOut(e){return Nw(e,{galaConnectClient:this.galaConnectClient,tokenMetadataResolver:this.tokenMetadataResolver,ethereumWallet:this.ethereumWallet,destinationChainId:_o.ETHEREUM,destinationChain:"Ethereum",validateRecipientAddress:tw})}async bridgeIn(n){const{amount:r,sourcePrivateKey:s,recipientAddress:o,tokenSymbol:a}=n,c=ew(a);if(sw(r,c),void 0!==s&&""!==s&&!$v(s))throw Ut("sourcePrivateKey","0x-prefixed 64-character hex string",s.slice(0,10)+"...");const l=void 0!==s&&""!==s?new t(s,this.ethereumProvider):this.ethereumWallet,u=Gv(this.tokenConfigs,c,"Ethereum bridge"),d=await this.tokenMetadataResolver.getTokenMetadata(c),h=new i(u.contractAddress,Xo,l),g=await lE(h,"decimals"),f=$n("string"==typeof g||"number"==typeof g||"bigint"==typeof g?g:void 0,18),m=zw(r,f),p=await lE(h,"balanceOf",l.address);if("bigint"!=typeof p)throw new Error("Ethereum balance response was not a bigint");const y=p;if(y<m){throw Pt(`Insufficient ${c} balance on Ethereum. Needed ${Xw(m,f)}, have ${Xw(y,f)}`,"amount")}const b=function(t){const n=new Nr;if("client"===n.detectFormat(t))return t;const r=n.normalizeInput(t);if(null==r)throw Ut("address","a valid GalaChain address (eth|0x{40-hex}, 0x{40-hex}, or {40-hex})","GalaChain address");const i=n.extractHex(r);return`eth|${e("0x"+i).slice(2)}`}(o??this.galaChainWalletAddress);return Jv({fromChain:"Ethereum",transactionHash:(await this.executeBridgeDeposit({wallet:l,tokenContract:h,tokenConfig:u,amountBaseUnits:m,decimals:f,recipient:b,metadata:d})).txHash,tokenSymbol:c,amount:r,baseUrl:this.galaConnectClient.getBaseUrl()})}isValidAddress(e){return tr.ETH_ADDRESS.test(e)}getWalletAddress(){return this.ethereumWalletAddress}async getEthereumTokenBalance(e,t){const n=Gv(this.tokenConfigs,e,"Ethereum"),r=t??this.ethereumWalletAddress;tw(r);const s=new i(n.contractAddress,Xo,this.ethereumProvider),o=await lE(s,"balanceOf",r);if("bigint"!=typeof o)throw new Error("Ethereum balance response was not a bigint");return Xw(o,n.decimals??18)}async getEthereumNativeBalance(e){const t=e??this.ethereumWalletAddress;tw(t);return Xw(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 Ut("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>=uE.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: ${bt(e)}`}}}async executeBridgeDeposit(e){const t=new i(this.ethereumBridgeContract,Jo,e.wallet),n=(new TextEncoder).encode(e.recipient);let r;r=e.tokenConfig.bridgeUsesPermit?await this.bridgeWithPermit(e.wallet,e.tokenContract,e.tokenConfig,t,e.amountBaseUnits,n):await this.bridgeWithApproval(e.wallet,e.tokenContract,t,e.tokenConfig,e.amountBaseUnits,n);if(!await r.wait())throw Pt("Bridge transaction receipt not available","ethereumRpcUrl");await Uw(3e4);const s={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:Xw(e.amountBaseUnits,e.decimals),tokenInstance:s,fromChain:"Ethereum",toChain:"GC",hash:r.hash}),{txHash:r.hash}}async bridgeWithPermit(e,t,n,r,i,o){const a=await this.ethereumProvider.getNetwork(),c=await lE(t,"name");if("string"!=typeof c)throw new Error("Ethereum token name response was not a string");const l=c,u=await lE(t,"nonces",e.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 e.signTypedData({name:l,version:"1",chainId:$n(a.chainId,1),verifyingContract:n.contractAddress},{Permit:[{name:"owner",type:"address"},{name:"spender",type:"address"},{name:"value",type:"uint256"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}]},{owner:e.address,spender:this.ethereumBridgeContract,value:i,nonce:d,deadline:h}),f=s.from(g);return await lE(r,"bridgeOutWithPermit",n.contractAddress,i,_o.GALA_CHAIN,o,h,f.v,f.r,f.s)}async bridgeWithApproval(e,t,n,r,i,s){const o=await lE(t,"allowance",e.address,this.ethereumBridgeContract);if("bigint"!=typeof o)throw new Error("Ethereum allowance response was not a bigint");if(BigInt(o)<i){const e=await lE(t,"approve",this.ethereumBridgeContract,i);await e.wait()}return await lE(n,"bridgeOut",r.contractAddress,i,0,_o.GALA_CHAIN,s)}}uE.ETHEREUM_FINALITY_THRESHOLD=12;const dE=new Xp("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA");new Xp("TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb");const hE=new Xp("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL");new Xp("So11111111111111111111111111111111111111112"),new Xp("9pan9bMn5HatX4EJdBwg9VgCa7Uz5HL8N1m5D3NdXejP");const gE=e=>({decode:e.decode.bind(e),encode:e.encode.bind(e)});var fE,mE={};function pE(){if(fE)return mE;return fE=1,Object.defineProperty(mE,"__esModule",{value:!0}),mE.toBigIntLE=function(e){{const t=Buffer.from(e);t.reverse();const n=t.toString("hex");return 0===n.length?BigInt(0):BigInt(`0x${n}`)}},mE.toBigIntBE=function(e){{const t=e.toString("hex");return 0===t.length?BigInt(0):BigInt(`0x${t}`)}},mE.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}},mE.toBufferBE=function(e,t){{const n=e.toString(16);return Buffer.from(n.padStart(2*t,"0").slice(0,2*t),"hex")}},mE}var yE=pE();const bE=function(e,t){return n=>{const r=wu.blob(t,n),{encode:i,decode:s}=gE(r),o=r;return o.decode=(t,n)=>{const r=s(t,n);return e?yE.toBigIntLE(ga.Buffer.from(r)):yE.toBigIntBE(ga.Buffer.from(r))},o.encode=(n,r,s)=>{let o;return function(e){if("bigint"!=typeof e)throw new Error("Expected a `BigInt`")}(n),o=0===t?ga.Buffer.alloc(0):e?yE.toBufferLE(n,t):yE.toBufferBE(n,t),i(o,r,s)},o}}.bind(null,!0),vE=bE(8),wE=e=>{const t=wu.blob(32,e),{encode:n,decode:r}=gE(t),i=t;return i.decode=(e,t)=>{const n=r(e,t);return new Xp(n)},i.encode=(e,t,r)=>{const i=e.toBuffer();return n(i,t,r)},i};var EE;!function(e){e[e.Uninitialized=0]="Uninitialized",e[e.Initialized=1]="Initialized",e[e.Frozen=2]="Frozen"}(EE||(EE={}));const AE=wu.struct([wE("mint"),wE("owner"),vE("amount"),wu.u32("delegateOption"),wE("delegate"),wu.u8("state"),wu.u32("isNativeOption"),vE("isNative"),vE("delegatedAmount"),wu.u32("closeAuthorityOption"),wE("closeAuthority")]);AE.span;var kE=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),i=r.charCodeAt(0);if(255!==t[i])throw new TypeError(r+" is ambiguous");t[i]=n}const n=e.length,r=e.charAt(0),i=Math.log(n)/Math.log(256),s=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 s=0,o=0,a=0;for(;e[s]===r;)o++,s++;const c=(e.length-s)*i+1>>>0,l=new Uint8Array(c);for(;s<e.length;){const r=e.charCodeAt(s);if(r>255)return;let i=t[r];if(255===i)return;let o=0;for(let e=c-1;(0!==i||o<a)&&-1!==e;e--,o++)i+=n*l[e]>>>0,l[e]=i%256>>>0,i=i/256>>>0;if(0!==i)throw new Error("Non-zero carry");a=o,s++}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 i=0,o=0,a=0;const c=t.length;for(;a!==c&&0===t[a];)a++,i++;const l=(c-a)*s+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(i);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 SE(e,t,n,r,i){const[s]=Xp.findProgramAddressSync([t.toBuffer(),r.toBuffer(),e.toBuffer()],i);return s}class TE extends cE{constructor(e){const n=e.tokenConfigs??Vo;super(e.galaConnectClient,Kv(n)),this.network="Solana",this.solanaBridgeAccountCache=new Map,this.galaChainWalletAddress=e.galaChainWalletAddress,Hv(e.ethereumPrivateKey);const i=new r("https://ethereum.publicnode.com");this.ethereumWallet=new t(e.ethereumPrivateKey,i);const s=e.solanaRpcUrl??"https://api.mainnet-beta.solana.com";let o;this.solanaConnection=new Mv(s,"confirmed");try{o=kE.decode(e.solanaPrivateKeyBase58)}catch{throw Ut("solanaPrivateKeyBase58","base58-encoded string",e.solanaPrivateKeyBase58.slice(0,20)+"...")}if(64!==o.length)throw Ut("solanaPrivateKeyBase58","64 bytes when decoded",`${o.length} bytes`);this.solanaKeypair=Ov.fromSecretKey(o);const a=e.solanaBridgeProgram??"AaE4dTnL75XqgUJpdxBKg6vS9sTJgBPJwBQRVhD29WwS";this.solanaBridgeProgramId=new Xp(a),[this.solanaBridgeTokenAuthority]=Xp.findProgramAddressSync([Buffer.from("bridge_token_authority")],this.solanaBridgeProgramId),[this.solanaBridgeConfigPda]=Xp.findProgramAddressSync([Buffer.from("configv1")],this.solanaBridgeProgramId),[this.solanaNativeBridgePda]=Xp.findProgramAddressSync([Buffer.from("native_sol_bridge")],this.solanaBridgeProgramId),this.tokenMetadataResolver=new Qw({galaConnectClient:this.galaConnectClient})}async estimateFee(e,t){return $w(this.galaConnectClient,this.tokenMetadataResolver,"Solana",e)}async bridgeOut(e){return Nw(e,{galaConnectClient:this.galaConnectClient,tokenMetadataResolver:this.tokenMetadataResolver,ethereumWallet:this.ethereumWallet,destinationChainId:_o.SOLANA,destinationChain:"Solana",validateRecipientAddress:nw})}async bridgeIn(e){const{amount:t,sourcePrivateKey:n,recipientAddress:r,tokenSymbol:i}=e,s=ew(i);sw(t,s);let o=this.solanaKeypair;if(void 0!==n&&""!==n){let e;try{e=kE.decode(n)}catch{throw Ut("sourcePrivateKey","base58-encoded string",n.slice(0,20)+"...")}if(64!==e.length)throw Ut("sourcePrivateKey","64 bytes when decoded",`${e.length} bytes`);o=Ov.fromSecretKey(e)}const a=Gv(this.tokenConfigs,s,"Solana bridge"),c=await this.tokenMetadataResolver.getTokenMetadata(s),l=zw(t,c.decimals),u=r??this.galaChainWalletAddress;return Jv({fromChain:"Solana",transactionHash:await this.executeSolanaBridgeOut({keypair:o,tokenConfig:a,metadata:c,amountBaseUnits:l,recipient:u,amount:t}),tokenSymbol:s,amount:t,baseUrl:this.galaConnectClient.getBaseUrl()})}isValidAddress(e){try{return new Xp(e),!0}catch{return!1}}getWalletAddress(){return this.solanaKeypair.publicKey.toBase58()}async getSolanaTokenBalance(e,t){const n=Gv(this.tokenConfigs,e,"Solana");if(n.isNative)return this.getSolanaNativeBalance(t);const r=t??this.solanaKeypair.publicKey.toBase58(),i=rw(r),s=SE(new Xp(n.mintAddress),i,0,dE,hE);try{const e=await async function(e,t,n,r){const i=await e.getAccountInfo(t);if(!i)throw new Error(`could not find account ${t.toBase58()}`);if(!i.owner.equals(r))throw new Error(`account owner mismatch: expected ${r.toBase58()}, got ${i.owner.toBase58()}`);return{amount:AE.decode(i.data).amount,decimals:0}}(this.solanaConnection,s,0,dE),t=n.decimals??8;return Xw(e.amount,t)}catch(t){if(yt(t)&&t.message.includes("could not find")){return Xw(0n,n.decimals??8)}throw Pt(`Failed to fetch ${e} balance for ${r}: ${bt(t)}`,`${e}Account`)}}async getSolanaNativeBalance(e){const t=rw(e??this.solanaKeypair.publicKey.toBase58()),n=await this.solanaConnection.getBalance(t,"confirmed");return Xw(BigInt(n),9)}async requestDevnetAirdrop(e=1,t){jn(e,1e-5,2,"amount");const n=void 0!==t&&""!==t?rw(t):this.solanaKeypair.publicKey,r=this.solanaConnection.rpcEndpoint;if(!r.includes("devnet"))throw Pt(`Solana devnet faucet only available on devnet. Current RPC: ${r}. Ensure SDK is configured with environment='stage' for devnet access.`,"solanaRpcUrl");const i=Math.floor(1e9*e);return await this.solanaConnection.requestAirdrop(n,i)}async getSolanaTransactionStatus(e){if(!nr(e))throw Ut("signature","a non-empty string");if(!/^[1-9A-HJ-NP-Za-km-z]{80,90}$/.test(e))throw Ut("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 Xp(e.tokenConfig.mintAddress),n=Boolean(e.tokenConfig.isNative),r=n?void 0:await this.getSolanaBridgeAccounts(t),i=n?void 0:SE(t,e.keypair.publicKey,0,dE,hE),s=Buffer.from(e.recipient,"utf8"),o=Buffer.alloc(8);o.writeBigUInt64LE(e.amountBaseUnits);const a=Buffer.alloc(4);a.writeUInt32LE(s.length);const c=n?this.buildNativeBridgeInstruction(e.keypair.publicKey,o,a,s):this.buildTokenBridgeInstruction(e.keypair.publicKey,i,t,r,o,a,s),l=new by;l.add(Lv.setComputeUnitPrice({microLamports:375e3}),Lv.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 i=1;i<=n;i++){try{const s=await this.solanaConnection.getLatestBlockhash("confirmed");e.recentBlockhash=s.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:s.blockhash,lastValidBlockHeight:s.lastValidBlockHeight},"confirmed"),o}catch(e){const t=yt(e)?e.message.toLowerCase():"";if(!(t.includes("block height exceeded")||t.includes("blockhash not found")||t.includes("expired")))throw e;const s=await this.solanaConnection.getSignatureStatuses([o]);if("confirmed"===s.value[0]?.confirmationStatus||"finalized"===s.value[0]?.confirmationStatus)return o;r=new Error(`Transaction ${o} not confirmed - block height exceeded (attempt ${i}/${n})`)}}catch(e){r=yt(e)?e:new Error(bt(e));const t=r.message.toLowerCase();if(!(t.includes("block height exceeded")||t.includes("blockhash not found")||t.includes("timeout")||t.includes("expired"))||i===n)throw r}const s=Math.min(1e3*Math.pow(2,i-1),5e3);await Uw(s)}throw r??new Error("Transaction confirmation failed after max retries")}buildNativeBridgeInstruction(e,t,n,r){const i=Buffer.concat([Yo.BRIDGE_OUT_NATIVE,t,n,r]);return new yy({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:Ry.programId,isSigner:!1,isWritable:!1}],data:i})}buildTokenBridgeInstruction(e,t,n,r,i,s,o){const a=Buffer.concat([Yo.BRIDGE_OUT,i,s,o]);return new yy({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:Ry.programId,isSigner:!1,isWritable:!1},{pubkey:dE,isSigner:!1,isWritable:!1}],data:a})}async getSolanaBridgeAccounts(e){const t=e.toBase58(),n=this.solanaBridgeAccountCache.get(t);if(n)return n;const[r]=Xp.findProgramAddressSync([Buffer.from("mint_lookup_v1"),e.toBuffer()],this.solanaBridgeProgramId),i=await this.solanaConnection.getAccountInfo(r,"confirmed");if(!i)throw Pt(`Mint lookup account not found for ${r.toBase58()}`,"solanaBridgeProgram");if(!i.owner.equals(this.solanaBridgeProgramId))throw Pt("Mint lookup account owner mismatch for Solana bridge program","solanaBridgeProgram");if(i.data.length<40)throw Pt("Mint lookup account data is unexpectedly short","solanaBridgeProgram");const s={mintLookup:r,tokenBridge:new Xp(i.data.slice(8,40)),bridgeTokenAccount:SE(e,this.solanaBridgeTokenAuthority,0,dE,hE)};return this.solanaBridgeAccountCache.set(t,s),s}}const IE={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"}},NE={solanaBridgeProgram:"AaE4dTnL75XqgUJpdxBKg6vS9sTJgBPJwBQRVhD29WwS",rateLimit:12,pollInterval:15e3,pollTimeout:27e5};class CE{static normalizeGalaChainAddress(e){const t=new Nr;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 Pt(`Invalid GalaChain address format: ${e}`,"galaChainWalletAddress");const i=t.extractHex(r);return`eth|${CE.checksumAddress(i)}`}static checksumAddress(e){const t=e.toLowerCase(),n=Tr(o(a(t)));let r="";for(let e=0;e<t.length;e++){const i=t[e],s=n[e];void 0!==i&&void 0!==s&&parseInt(s,16)>=8?r+=i.toUpperCase():r+=i??""}return r}constructor(e){const t=CE.normalizeGalaChainAddress(e.galaChainWalletAddress),n=e.environment??"prod",r=To["stage"===n?"stage":"prod"],i=IE[n],s={galaConnectBaseUrl:e.galaConnectBaseUrl??r.dexApiBaseUrl,galaChainApiBaseUrl:e.galaChainApiBaseUrl??r.gatewayBaseUrl,ethereumRpcUrl:e.ethereumRpcUrl??i.ethereum,solanaRpcUrl:e.solanaRpcUrl??i.solana,ethereumBridgeContract:e.ethereumBridgeContract??qo(n),solanaBridgeProgram:e.solanaBridgeProgram??NE.solanaBridgeProgram,rateLimit:e.rateLimit??NE.rateLimit,pollInterval:e.pollInterval??NE.pollInterval,pollTimeout:e.pollTimeout??NE.pollTimeout,galaChainWalletAddress:t,ethereumPrivateKey:e.ethereumPrivateKey,environment:n};this.config=e.solanaPrivateKey?{...s,solanaPrivateKey:e.solanaPrivateKey}:s,this.galaConnectClient=new oE({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=Wo(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 uE(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:Vo};this.strategies.set("Solana",new TE(e))}}async resolveTokenSymbol(e,t){return vo(async()=>{if(!this.bridgeableTokenService)throw Pt("BridgeableTokenService is required for tokenId resolution. Pass bridgeableTokenService in BridgeServiceConfig or use the SDK's bridge methods.","bridgeableTokenService");const n=Vw(e).stringified,r="Ethereum"===t?"ETHEREUM":"SOLANA",i=await this.bridgeableTokenService.getTokenByTokenId(n,r);if(!i){throw Pt([`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 i.symbol},"BridgeService.resolveTokenSymbol")}async estimateBridgeFee(e){return vo(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 vo(async()=>{const t=await this.resolveTokenSymbol(e.tokenId,e.destinationChain),n=this.getStrategy(e.destinationChain);if(!n.isValidAddress(e.recipientAddress))throw Pt(`Invalid recipient address for ${e.destinationChain}: ${e.recipientAddress}`,"recipientAddress");if(!n.isTokenSupported(t))throw Pt(`Token ${t} is not supported for ${e.destinationChain} bridging`,"tokenSymbol");return n.bridgeOut({...e,tokenSymbol:t})},"BridgeService.bridgeOut")}async bridgeIn(e){return vo(async()=>{const t=await this.resolveTokenSymbol(e.tokenId,e.sourceChain),n=this.getStrategy(e.sourceChain);if(!n.isTokenSupported(t))throw Pt(`Token ${t} is not supported for ${e.sourceChain} bridging`,"tokenSymbol");return n.bridgeIn({...e,tokenSymbol:t})},"BridgeService.bridgeIn")}async getBridgeStatus(e,t){return vo(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=yt(e)?e:new Error(bt(e))}const i=this.strategies.get("Solana");if(i)try{return await i.getStatus(e)}catch(e){r=yt(e)?e:new Error(bt(e))}const s=r?` (last error: ${r.message})`:"";throw Ft(`Unable to get status for transaction ${e}${s}`,e)},"BridgeService.getBridgeStatus")}async waitForBridgeCompletion(e,t){return vo(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 i=this.strategies.get("Solana");if(i)return i.waitForCompletion(e,n);throw Ft(`Unable to wait for transaction ${e}: no suitable strategy found`,e)},"BridgeService.waitForBridgeCompletion")}getSupportedBridgeTokens(e){const t=[],n=Wo(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 Vo){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 vo(async()=>Lw(this.strategies).getEthereumTokenBalance(e,t),"BridgeService.getEthereumTokenBalance")}async getEthereumNativeBalance(e){return vo(async()=>Lw(this.strategies).getEthereumNativeBalance(e),"BridgeService.getEthereumNativeBalance")}async getSolanaTokenBalance(e,t){return vo(async()=>Pw(this.strategies).getSolanaTokenBalance(e,t),"BridgeService.getSolanaTokenBalance")}async getSolanaNativeBalance(e){return vo(async()=>Pw(this.strategies).getSolanaNativeBalance(e),"BridgeService.getSolanaNativeBalance")}async fetchEthereumWalletTokenBalance(e,t){return vo(async()=>{const n=Lw(this.strategies),r=Vv(Wo(this.config.environment),e,"Ethereum"),i=Fw(t,n);return qv(r,await n.getEthereumTokenBalance(e,i))},"BridgeService.fetchEthereumWalletTokenBalance")}async fetchEthereumWalletNativeBalance(e){return vo(async()=>{const t=Lw(this.strategies),n=Fw(e,t);return Wv("ETH",await t.getEthereumNativeBalance(n),18)},"BridgeService.fetchEthereumWalletNativeBalance")}async fetchSolanaWalletTokenBalance(e,t){return vo(async()=>{const n=Pw(this.strategies),r=Vv(Vo,e,"Solana"),i=Fw(t,n);return jv(r,await n.getSolanaTokenBalance(e,i))},"BridgeService.fetchSolanaWalletTokenBalance")}async fetchSolanaWalletNativeBalance(e){return vo(async()=>{const t=Pw(this.strategies),n=Fw(e,t);return Wv("SOL",await t.getSolanaNativeBalance(n),9)},"BridgeService.fetchSolanaWalletNativeBalance")}async requestSolanaDevnetAirdrop(e,t){return vo(async()=>Pw(this.strategies).requestDevnetAirdrop(e,t),"BridgeService.requestSolanaDevnetAirdrop")}async getSolanaTransactionStatus(e){return vo(async()=>Pw(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 vo(async()=>Lw(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 vo(async()=>{const t=Lw(this.strategies),n=Fw(e,t),r=Wo(this.config.environment),[i,...s]=await Promise.all([t.getEthereumNativeBalance(n),...r.map(async e=>qv(e,await t.getEthereumTokenBalance(e.symbol,n)))]);return{address:n,native:Wv("ETH",i,18),tokens:s,timestamp:Date.now()}},"BridgeService.fetchEthereumWalletAllBalances")}async fetchSolanaWalletAllBalances(e){return vo(async()=>{const t=Pw(this.strategies),n=Fw(e,t),[r,...i]=await Promise.all([t.getSolanaNativeBalance(n),...Vo.map(async e=>jv(e,await t.getSolanaTokenBalance(e.symbol,n)))]);return{address:n,native:Wv("SOL",r,9),tokens:i,timestamp:Date.now()}},"BridgeService.fetchSolanaWalletAllBalances")}getStrategy(e){const t=this.strategies.get(e);if(!t)throw Pt(`Bridging to ${e} is not configured. `+("Solana"===e?"Please provide solanaPrivateKey in config.":"Please check your configuration."),`${e.toLowerCase()}PrivateKey`);return t}}var _E,xE;!function(e){e.PROCESSED="PROCESSED",e.COMPLETED="COMPLETED",e.SUCCESS="SUCCESS",e.FAILED="FAILED",e.ERROR="ERROR",e.PROCESSING="PROCESSING",e.PENDING="PENDING"}(_E||(_E={})),function(e){e.PENDING="pending",e.PROCESSING="processing",e.COMPLETED="completed",e.FAILED="failed",e.TIMEOUT="timeout"}(xE||(xE={}));const RE={[_E.PROCESSED]:xE.COMPLETED,[_E.COMPLETED]:xE.COMPLETED,[_E.SUCCESS]:xE.COMPLETED,[_E.FAILED]:xE.FAILED,[_E.ERROR]:xE.FAILED,[_E.PROCESSING]:xE.PROCESSING,[_E.PENDING]:xE.PENDING},BE="7.0.0-beta.5",DE={DEFAULT_PAGE_SIZE:50,MAX_PAGE_SIZE:1e3,SAFETY_MAX_PAGES:1e4,DEFAULT_OFFSET:0,DEFAULT_LIMIT:10,BACKEND_MAX_PAGE_SIZE:20},ME={MAX_CONCURRENT_FETCHES:5,PAGE_SIZE:50,BACKEND_PAGE_SIZE:20};function OE(e,t=DE.DEFAULT_LIMIT){if("number"!=typeof e||!Number.isInteger(e)||e<0)throw Wt("offset","a non-negative integer",e);return zn(t,"limit"),{offset:e,limit:t}}function UE(e,t,n){if("number"!=typeof e||!Number.isInteger(e)||e<0)throw Wt("offset","a non-negative integer",e);zn(t,"limit")}function LE(e,t=1,n=DE.BACKEND_MAX_PAGE_SIZE){return Math.max(t,Math.min(n,Math.ceil(e??t)))}function PE(e,t){if("number"!=typeof e||!Number.isInteger(e))throw Wt("total","a non-negative integer",e);if(e<0)throw Kt("total",0,1/0,e);if("number"!=typeof t||!Number.isInteger(t))throw Wt("limit","a non-negative integer",t);if(t<0)throw Kt("limit",0,1/0,t);return 0===t?1:0===e?0:Math.ceil(e/t)}function FE(e,t,n){if("number"!=typeof e||!Number.isInteger(e))throw Wt("offset","a non-negative integer",e);if(e<0)throw Kt("offset",0,1/0,e);return e+t<n}function $E(e){return"string"==typeof e?e:"number"==typeof e||"boolean"==typeof e||"bigint"==typeof e?String(e):JSON.stringify(e)??""}function KE(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 GE(e,t,n){for(const r of n){const n=t[r];null!=n&&""!==n&&(e[r]=$E(n))}return e}const HE="x-api-key";class WE extends Er{constructor(e,t,n,r=!1,i){super(e,r),this.adminApiKey=t??void 0,this.jwtAuth=n,this.userApiKey=i??void 0}setJwtAuth(e){this.jwtAuth=e}validateTokenName(e,t){!function(e,t){if(!nr(e))throw Ot("tokenName","Token name");const n=on(e);if(!t.PATTERN.test(n))throw Ut("tokenName",`${t.MIN_LENGTH}-${t.MAX_LENGTH} alphanumeric characters`,"Token name")}(e,t)}validateRequiredString(e,t,n){!function(e,t,n){if(!nr(e))throw Ot(t,n)}(e,t,n)}validateOptionalString(e,t,n,r){!function(e,t,n,r){if(null!=e){if("string"!=typeof e)throw Wt(t,"string",typeof e,n);if(e.length>r)throw Ht(t,r,e.length,n)}}(e,t,n,r)}validateOptionalNumber(e,t,n,r,i,s,o){!function(e,t,n,r,i){if(null!=e){if("number"!=typeof e)throw Wt(t,"number",typeof e,n);if(e<r||e>i)throw Kt(t,r,i,e,n)}}(e,t,n,r,i)}validateOptionalDate(e,t,n){!function(e,t,n){if(null!=e&&!pn(e))throw Ut(t,"a valid ISO 8601 date string",n)}(e,t,n)}validatePositiveInteger(e,t,n){vr(e,t,n)}validateStatusFilter(e,t,n="status"){wr(e,t,n)}buildPaginationParams(e,t){return KE(e,t)}addOptionalFilterParams(e,t,n){return GE(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 Rt("Admin API key required for this operation. Set streamAdminApiKey in SDK config.");return{[HE]:this.adminApiKey}}getJwtHeaders(){if(!this.jwtAuth)throw new Rt("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?{[HE]:this.userApiKey}:this.getJwtHeaders()}extractData(e){return Yt(e,"Backend request failed",!0),Zt(e,"No data in backend response")}extractDataOrNull(e){return Yt(e,"Backend request failed",!1),e.data??null}async toggleFeature(e,t,n){this.validateTokenName(e,n);const r=this.buildEndpoint(t,{tokenName:e}),i=await this.http.post(r,{},this.getAdminHeaders()),s=this.extractData(i);return{enabled:s.enabled,tokenName:s.tokenName??on(e)}}}class qE extends WE{constructor(e,t,n,r=!1,i){super(e,t,n,r,i)}async getSettings(){return{settings:(await this.http.get(nt.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(nt.UPDATE_SETTINGS,t,this.getDualAuthHeaders())).settings}}async getModeration(e){this.validatePositiveInteger(e.flagId,"flagId","Flag ID");const t=nt.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=nt.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(nt.GET_STATUS,{},this.getDualAuthHeaders())).status}}}const jE={MODERATOR:"MODERATOR",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MANAGER:"MANAGER",OWNER:"OWNER"},VE=ar(jE),zE={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"},XE={MANAGE_COMMUNITY:"MANAGE_COMMUNITY",MANAGE_STREAM:"MANAGE_STREAM",MANAGE_SETTINGS:"MANAGE_SETTINGS",MANAGE_RECORDINGS:"MANAGE_RECORDINGS",VIEW_ANALYTICS:"VIEW_ANALYTICS"},JE=Object.values(XE);function YE(e){return VE.includes(e)}function QE(e){const t=[];return void 0===e.role||null===e.role?t.push("Role is required"):YE(e.role)||t.push(`Invalid role. Must be one of: ${VE.join(", ")}`),eA(e,t),t}function ZE(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||YE(e.role)||t.push(`Invalid role. Must be one of: ${VE.join(", ")}`),eA(e,t,!0),t}function eA(e,t,n=!1){const r=t.length;if(St(t,()=>{yr(e.description,"description",255)}),t.length>r&&(t[r]="Description must be 255 characters or less"),void 0!==e.tokenNames){const n=t.length;St(t,()=>{if(!Array.isArray(e.tokenNames))throw Wt("tokenNames","an array",e.tokenNames);if(!e.tokenNames.every(e=>"string"==typeof e))throw Wt("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;St(t,()=>{br(e.expiresAt,"expiresAt")}),t.length>n&&(t[n]="expiresAt must be a valid ISO 8601 date string")}}function tA(e){if(void 0!==e.pageSize&&("number"!=typeof e.pageSize||e.pageSize<1||e.pageSize>En))throw Wt("pageSize",`number between 1 and ${En}`,typeof e.pageSize);if(void 0!==e.cursor&&("string"!=typeof e.cursor||""===e.cursor.trim()))throw Wt("cursor","non-empty string",typeof e.cursor)}const nA={[jE.MODERATOR]:1,[jE.TECHNICAL_PRODUCER]:1,[jE.MANAGER]:2,[jE.OWNER]:3};function rA(e,t){return e===jE.MANAGER?t!==jE.OWNER:e===jE.OWNER||e===t}class iA extends Er{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),Yt(n,"API key operation failed",!0),e.data}validateApiKeyId(e){this.validatePositiveInteger(e,"id","API key ID")}async create(e){const t=QE(e);if(t.length>0)throw new Ct(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(ue.CREATE,n,this.getJwtHeaders()),i=this.extractData(r);return this.logger.debug("API key created",{id:i.id,keyPrefix:i.keyPrefix}),i}async findAll(e={}){tA(e),this.logger.debug("Listing API keys",e);const t=KE(e,En),n=await this.http.get(ue.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=ue.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=ZE(t);if(n.length>0)throw new Ct(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 i=ue.UPDATE.replace(":id",String(e)),s=await this.http.patch(i,r,this.getJwtHeaders()),o=this.extractData(s);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=ue.REVOKE.replace(":id",String(e));await this.http.delete(t,{},this.getJwtHeaders()),this.logger.debug("API key revoked",{id:e})}getRoles(){return[...VE]}}const sA={ONE_HOUR:3600,ONE_DAY:86400,ONE_WEEK:604800,ONE_MONTH:2592e3},oA={VIEWERS:"viewers",CHAT_PARTICIPANTS:"chat_participants"},aA=or(oA),cA=gr([{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}]),lA=gr([{field:"userAddress",type:"string"},{field:"isPermanent",type:"boolean"}]),uA=gr([{field:"userAddress",type:"string"}]),dA=gr([{field:"tokenName",type:"string"},{field:"action",type:"string",validator:e=>"CHAT_MESSAGE"===e||"COMMENT"===e||"REACTION"===e}]);function hA(e){return null==e||""===e||"string"==typeof e&&(!pr(e)&&e.length<=In.BAN_REASON.MAX_LENGTH)}function gA(e){return!!ir(e)||"number"==typeof e&&(e>=Cn&&e<=_n)}function fA(e){if(!nr(e.userAddress))throw Ot("userAddress");if(!hA(e.reason))throw new Ct(`reason must be at most ${In.BAN_REASON.MAX_LENGTH} characters`,"reason","TOO_LONG");if(!gA(e.durationSeconds))throw new Ct(`durationSeconds must be between ${Cn} and ${_n} seconds`,"durationSeconds","OUT_OF_RANGE")}class mA extends WE{constructor(e,t,n,r=!1,i){super(e,t,n,r,i)}async createBan(e){!function(e){lr(e.tokenName,"tokenName",bn),fA(e)}(e);const t=this.buildEndpoint(te,{tokenName:e.tokenName}),n=pA(e),r=await this.http.post(t,n,this.getMultiAuthHeaders());return{ban:this.extractData(r),tokenName:on(e.tokenName)}}async removeBan(e){!function(e){if(lr(e.tokenName,"tokenName",bn),!nr(e.userAddress))throw Ot("userAddress")}(e);const t=this.buildEndpoint(ie,{tokenName:e.tokenName,userAddress:e.userAddress}),n=await this.http.delete(t,{},this.getMultiAuthHeaders()),r=this.extractDataOrNull(n);return{removed:r?.removed??!0,tokenName:on(e.tokenName),userAddress:r?.userAddress??e.userAddress.toLowerCase()}}async listBans(e){!function(e){lr(e.tokenName,"tokenName",bn),sr(0,void 0,En,e.pageSize)}(e);const t=this.buildEndpoint(ne,{tokenName:e.tokenName}),n=this.buildPaginationParams(e,En);this.addOptionalFilterParams(n,e,["search","name","userAddress"]);const r=await this.http.get(t,n,this.getMultiAuthHeaders()),i=this.extractData(r);return{items:i.bans,pageInfo:i.pageInfo}}async getBanStatus(e){!function(e){if(lr(e.tokenName,"tokenName",bn),!nr(e.userAddress))throw Ot("userAddress")}(e);const t=this.buildEndpoint(re,{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:on(e.tokenName),userAddress:e.userAddress.toLowerCase()}}async getActiveUsers(e){!function(e){if(lr(e.tokenName,"tokenName",bn),void 0!==e.type&&!aA(e.type))throw new Ct(`type must be one of: ${Object.values(oA).join(", ")}`,"type",Nt.INVALID_VALUE)}(e);const t=this.buildEndpoint(se,{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){fA(e)}(e);const t=pA(e),n=await this.http.post(oe,t,this.getDualAuthHeaders());return{ban:this.extractData(n)}}async removeGlobalBan(e){!function(e){if(!nr(e.userAddress))throw Ot("userAddress")}(e);const t=this.buildEndpoint(le,{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){sr(0,void 0,En,e.pageSize)}(t);const n=this.buildPaginationParams(t,En);this.addOptionalFilterParams(n,t,["search","name","userAddress"]);const r=await this.http.get(ae,n,this.getDualAuthHeaders()),i=this.extractData(r);return{items:i.bans,pageInfo:i.pageInfo}}async getGlobalBan(e){!function(e){if(!nr(e.userAddress))throw Ot("userAddress")}(e);const t=this.buildEndpoint(ce,{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 pA(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 yA(e,t={}){const{maxPages:n=1e4,logger:r,pageSize:i=20,concurrency:s=1,startPage:o=1}=t,a=[];let c=o;const l=o+n-1;let u=!0,d=0;if(s<=1)for(;u&&c<=l;){r&&r.debug(`Auto-pagination: fetching page ${c} with limit ${i}`);const t=await e(c,i);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=${s}`);u&&c<=l;){const t=[];for(let e=0;e<s&&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,i).catch(e=>{const n=e,s=n.statusCode??n.response?.status??n.originalError?.response?.status??n.status??n.launchpadError?.statusCode;if(400===s||404===s)return r&&r.debug(`Auto-pagination: page ${t} returned ${s} (end of pagination)`,{statusCode:s}),{items:[],total:0,totalPages:0,page:t,limit:i,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 bA(e){if("string"==typeof e){if(!Ww(e))throw new Ct(`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=Hw(t.slice(0,4).join("|")),n=t[4]??"0";return{...e,instance:n.length>0?n:"0"}}return{...Hw(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(!jw(e))throw new Ct("Invalid tokenId object format. All fields (collection, category, type, additionalKey) must be non-empty strings","tokenId","INVALID_TOKEN_ID_FORMAT");return e}if(!jw(e))throw new Ct("Invalid tokenId object format. All fields (collection, category, type, additionalKey) are required","tokenId","INVALID_TOKEN_ID_FORMAT");return{...e,instance:"0"}}throw new Ct(`Invalid tokenId type: ${typeof e}. Expected string, TokenClassKey, or TokenInstanceKey`,"tokenId","INVALID_TOKEN_ID_TYPE")}function vA(e){return function(e){try{if(!nr(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,i,s,...o]=n;if(""===r||""===i||""===s)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===i||void 0===s||""===c||void 0===c)throw new Error("AdditionalKey must be non-empty");return{collection:r,category:i,type:s,additionalKey:c}}catch(t){throw new Ct(`Invalid vault address: "${e}". Expected format: "service|Token$Unit$SYMBOL$additionalKey$launchpad". Error: ${bt(t)}`,"vaultAddress","INVALID_VAULT_ADDRESS_FORMAT")}}(e)}function wA(e){return{...vA(e),instance:"0"}}function EA(e){return vA(e).type}function AA(e){return No(bA(e))}var kA=Object.freeze({__proto__:null,extractTokenSymbolFromVault:EA,isTokenClassKeyStrict:jw,normalizeToTokenInstanceKey:bA,normalizeTokenIdToString:AA,parseVaultAddressToTokenClassKey:vA,parseVaultAddressToTokenInstance:wA});class SA{constructor(e,t=!1,n){this.dexApiHttp=e,this.logger=new un({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()),i=this.buildApiParams(n),s=await this.dexApiHttp.request({method:"GET",url:this.getApiEndpoint(),params:{...i,pageSize:r,offset:e}});if(ir(s)||!Array.isArray(s.tokens))throw new Ct("Invalid API response: expected { tokens: array }","response","INVALID_RESPONSE");return{items:this.transformApiResponse(s.tokens),rawCount:s.tokens.length}}async autoPaginateFetch(e){return async function(e,t){const{maxLimit:n,logger:r,maxPages:i=1e4}=t,s=[];let o=0,a=!0,c=0;for(;a&&c<i;){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}s.push(...t.items),a=t.rawCount===n,o+=n,c++,r&&r.debug(`Auto-pagination (offset): fetched ${s.length} items so far (hasMore=${String(a)})`)}return c>=i&&r&&r.warn(`Auto-pagination (offset): exceeded maxPages limit of ${i}, stopping`),r&&r.debug(`Auto-pagination (offset): completed with total items: ${s.length}`),s}(async(t,n)=>this.executePaginatedRequest(t,n,e),{maxLimit:this.getMaxLimit(),logger:this.logger})}handleError(e,t){throw $t(e,t,this.logger)}}class TA extends Ar{constructor(e=!1){super(e),this.primaryIndex=new Map,this.secondaryIndex=new Map,this.fetchTimestamps=new Map}normalizeKey(e){return an(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 i=this.normalizeKey(this.extractSecondaryKey(e));r.set(i,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 i=this.normalizeKey(this.extractSecondaryKey(e));r.set(i,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={},i={};for(const t of e)r[t]=0;for(const[e,s]of this.primaryIndex){t.push(e),n+=s.size,r[e]=s.size;const o=this.fetchTimestamps.get(e);void 0!==o&&(i[e]=o)}return{networks:t,totalItems:n,itemsByNetwork:r,fetchTimestamps:i}}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 IA=["ETHEREUM","SOLANA"];class NA extends TA{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(IA);return{...e,totalTokens:e.totalItems,tokensByNetwork:e.itemsByNetwork}}}class CA extends SA{constructor(e,t=!1){super(e,t,"BridgeableTokenService"),this.cache=new NA(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),i={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&&(i.ethereumContractAddress=t.contractAddress),void 0!==t?.symbol&&(i.ethereumSymbol=t.symbol),void 0!==t?.allowanceStorageSlot&&(i.ethereumAllowanceSlot=t.allowanceStorageSlot),void 0!==n?.contractAddress&&(i.solanaContractAddress=n.contractAddress),void 0!==n?.symbol&&(i.solanaSymbol=n.symbol),void 0!==e.image&&(i.image=e.image),void 0!==e.description&&(i.description=e.description),i})}async fetchBridgeableTokensByNetwork(e){const{network:t,offset:n=0,limit:r=this.getDefaultLimit()}=e,i=Math.min(r,this.getMaxLimit());return this.logger.debug(`Fetching bridgeable tokens for ${t} (offset=${n}, limit=${i})`),vo(async()=>{const e=(await this.executePaginatedRequest(n,i,{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 vo(async()=>{const t=await async function(e){const{network:t,cache:n,fetchFn:r,logger:i,itemTypeName:s="items"}=e;if(n.has(t)){const e=n.getAll(t);return i&&i.debug(`Returning ${e.length} cached ${s} for ${t}`),{items:e,fetchedAt:n.getFetchTimestamp(t)??Date.now(),itemCount:e.length}}i&&i.debug(`Fetching all ${s} 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=AA(t);this.cache.has(n)||await this.fetchAllBridgeableTokensByNetwork(n);const i=this.cache.getByTokenId(n,r),s=void 0!==i,o=s?"ETHEREUM"===n?i.ethereumContractAddress:i.solanaContractAddress:void 0,a={isBridgeable:s,tokenSymbol:i?.symbol??Hw(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 _A(e){return{maxAcceptableReverseBondingCurveFee:Wn(e.maxAcceptableReverseBondingCurveFee)}}const xA={BuyNativeDto:class extends w{constructor(e,t,n="0",r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=Wn(t),this.expectedToken=qn(n),this.extraFees=_A(r)}},BuyExactDto:class extends w{constructor(e,t,n,r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=qn(t),this.expectedNativeToken=Wn(n),this.extraFees=_A(r)}},SellExactDto:class extends w{constructor(e,t,n="0",r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=qn(t),this.expectedNativeToken=Wn(n),this.extraFees=_A(r)}},SellNativeDto:class extends w{constructor(e,t,n,r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=Wn(t),this.expectedToken=qn(n),this.extraFees=_A(r)}}};function RA(e,t,n){let r;jn(t,0,1,"slippageToleranceFactor");try{r=Kn(e,"expectedAmount")}catch{throw new Error(`Invalid expected amount: ${e}. Must be a valid number`)}if(0===t)return e;const i=r.multipliedBy(t);let s;switch(n){case"buy-native":case"sell-exact":s=r.minus(i);break;case"buy-exact":case"sell-native":s=r.plus(i);break;default:throw new Error(`Unknown operation type: ${n}`)}return Ws(s).isLessThan(0)&&(s=Ws(0)),qs(s)}function BA(e){return`${e}-${Date.now()}_${b().replace(/-/gu,"").substring(0,26)}`}function DA(){return BA("galaconnect-operation")}function MA(e,t){const n={[e]:[]},r=new Set;function i(e){const t=n[e];if(void 0===t)throw new Error("Missing EIP-712 type "+e);return t}function s(e,t,o,a=!1){if(void 0===t)return;if(Array.isArray(t)){const n=s(e,t[0],o,!0);return a||(r.add(e),i(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,i]of Object.entries(t)){if(r.has(n))throw new Error("Name collisions not yet supported");s(n,i,e)}return a||(r.add(e),i(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),i(o).push({name:e,type:c})),c}for(const[n,r]of Object.entries(t))s(n,r,e);return n}const OA={name:"GalaChain"},UA={name:"ethereum",chainId:1};function LA(e){if("string"!=typeof e)throw new Error("Wallet returned an invalid signature");return e}function PA(e,t,n,r){return{...e,signature:t,types:n,domain:r}}class FA extends f{constructor(e){super(e),this.typedDataWallet=new t(e),this.walletAddress=`eth|${this.typedDataWallet.address.slice(2)}`}async signTypedData(e,t){const n=MA(e,t);return PA(t,await this.typedDataWallet.signTypedData(OA,n,t),n,OA)}}class $A extends g{async signTypedData(e,t){const n=MA(e,t),r={domain:UA,types:n,message:t,Primary_type:e};return PA(t,LA(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,UA)}}class KA extends h{constructor(e,t){super(e,t),this.typedDataProvider=e}async signTypedData(e,t){const n=this.typedDataProvider,r=await n.getNetwork(),i={name:r.name,chainId:Number(r.chainId)},s=MA(e,t),o=await n.getSigner();return PA(t,LA(await o.signTypedData(i,s,t)),s,i)}}function GA(e){if(!nr(e))throw new Error("Invalid token format: token must be a non-empty string");return e.replace(/\|/g,"$")}function HA(e){return Gw(e,"$","dollar-delimited token")}class WA extends Ar{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(),i=`$service$${n.toStringKey()}$launchpad`,s=`$tokenBalance$${n.toStringKey()}$${e}`,o=`$tokenBalance$${n.toStringKey()}$${e}`,a=`$tokenBalance$${r.toStringKey()}$${e}`,c=[i,s,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=bt(e);throw new Ct(`Failed to generate stringsInstructions: ${t}`,"vaultAddress","INVALID_VAULT_ADDRESS")}}createTokenInstance(e){const t=new E;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 E;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(!nr(e))throw Ot("vaultAddress","Vault address");try{const t=EA(e);return this.logger.debug("🔍 Extracted token symbol:",{vaultAddress:e,tokenSymbol:t}),t}catch(e){if(e instanceof Ct)throw Ut("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad");throw e}}validateVaultAddress(e){if(!nr(e))throw Ot("vaultAddress","Vault address");if(!e.startsWith("service|Token$Unit$"))throw Ut("vaultAddress",'starting with "service|Token$Unit$"');if(!e.endsWith("$launchpad"))throw Ut("vaultAddress",'ending with "$launchpad"');const t=function(e){if(!nr(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 Ut("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 Ut("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 HA(e)}catch(e){if(e instanceof Ct)throw Ut("stringKey","format: collection$category$type$additionalKey (4 parts)");throw e}}}function qA(e){return"object"==typeof e&&null!==e?e:void 0}class jA extends Er{constructor(e,t,n=!1,r,i,s=.05,o=.01){if(super(e,n),this.tokenResolver=t,this._walletProvider=r,this.userAddress=i,this.defaultSlippageToleranceFactor=s,this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor=o,this.bundleEndpoint="/bundle",null!==this._walletProvider&&void 0!==this._walletProvider&&null!=i){const e=qA(this._walletProvider),t=e?.privateKey;"string"==typeof t?this.signer=new FA(t):function(e){const t=qA(e);return"function"==typeof t?.request}(this._walletProvider)&&void 0!==this.userAddress&&(this.signer=new KA(this._walletProvider,this.userAddress)),this.tokenKeyService=new WA(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 tn(()=>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:Jt(n),error:n.error}),this.handleBundleResponse(n))}catch(e){if(e instanceof Ct)return{success:!1,error:bt(e)};throw e}}validateBundleData(e){if(null==e)throw Ot("bundleData","Bundle data");if(null===e.signedDto||void 0===e.signedDto)throw Ot("signedDto","Signed DTO");if(!nr(e.method))throw Ot("method","Method name");if(!Array.isArray(e.stringsInstructions))throw Ut("stringsInstructions","an array of resource tracking strings");if(0===e.stringsInstructions.length)throw new Ct("stringsInstructions cannot be empty","stringsInstructions","EMPTY_ARRAY");const t=["BuyWithNative","BuyExactToken","SellExactToken","SellWithNative"];if(!t.includes(e.method))throw Ut("method",`one of: ${t.join(", ")}`);e.stringsInstructions.forEach((e,t)=>{if(!nr(e))throw new Ct(`stringsInstructions[${t}] must be a non-empty string`,`stringsInstructions[${t}]`,"INVALID_INSTRUCTION");if(!qw(e))throw new Ct(`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=Qt(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(Et(e)&&null!==e.response&&void 0!==e.response){const t=Qt(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 bt(e)??"Unknown bundle transaction error"}async getBundlerTransactionResult(e){try{if(!nr(e))throw Ot("transactionId","Transaction ID");let t;this.logger.debug("🔍 Checking bundler transaction result:",e);try{t=await tn(()=>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 Ct)return{success:!1,error:bt(e)};throw e}}async cancelTransaction(e){try{if(!nr(e))throw Ot("transactionId","Transaction ID");let t;this.logger.debug("🚫 Cancelling transaction:",e);try{t=await tn(()=>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 Ct)return{success:!1,error:bt(e)};throw e}}async getHealthStatus(){this.logger.debug("🏥 Checking bundle service health");try{const e=await tn(()=>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:i}=e,{effectiveSlippageFactor:s,effectiveMaxFee:o,vaultAddress:a}=await this.prepareTradingOperation(t,e.maxAcceptableReverseBondingCurveFee,e.maxAcceptableReverseBondingCurveFeeSlippageFactor,e.slippageToleranceFactor);if("native"===r){if(null==i||""===i)throw new Ct("expectedAmount is required for native buy operations. Use getBuyTokenAmount() first to calculate expected tokens.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=RA(i,s,"buy-native");this.logger.debug("BuyNative slippage applied:",{originalExpectedTokens:i,slippageFactor:s,adjustedMinTokens:e});const t=new xA.BuyNativeDto(a,n,e,{maxAcceptableReverseBondingCurveFee:o});return await this.executeBundleTransaction(t,"BuyWithNative",a)}{if(null==i||""===i)throw new Ct("expectedAmount is required for exact buy operations. Use getBuyTokenAmount() first to calculate expected GALA cost.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=RA(i,s,"buy-exact");this.logger.debug("BuyExact slippage applied:",{originalExpectedGalaCost:i,slippageFactor:s,adjustedMaxGalaCost:e});const t=new xA.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:i}=e,{effectiveSlippageFactor:s,effectiveMaxFee:o,vaultAddress:a}=await this.prepareTradingOperation(t,e.maxAcceptableReverseBondingCurveFee,e.maxAcceptableReverseBondingCurveFeeSlippageFactor,e.slippageToleranceFactor);if("exact"===r){if(null==i||""===i)throw new Ct("expectedAmount is required for exact sell operations. Use getSellTokenAmount() first to calculate expected GALA.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=RA(i,s,"sell-exact");this.logger.debug("SellExact slippage applied:",{originalExpectedGala:i,slippageFactor:s,adjustedMinGala:e});const t=new xA.SellExactDto(a,n,e,{maxAcceptableReverseBondingCurveFee:o});return await this.executeBundleTransaction(t,"SellExactToken",a)}{if(null==i||""===i)throw new Ct("expectedAmount is required for native sell operations. Use getSellTokenAmount() first to calculate tokens to sell.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=RA(i,s,"sell-native");this.logger.debug("SellNative slippage applied:",{originalExpectedTokensToSell:i,slippageFactor:s,adjustedMaxTokensToSell:e});const t=new xA.SellNativeDto(a,n,e,{maxAcceptableReverseBondingCurveFee:o});return await this.executeBundleTransaction(t,"SellWithNative",a)}}async prepareTradingOperation(e,t,n,r){const{effectiveSlippageFactor:i,effectiveMaxFee:s}=this.calculateEffectiveSlippage(t,n,r),o=await this.resolveTokenNameToVault(e);if(null==o)throw Mt(e);return{effectiveSlippageFactor:i,effectiveMaxFee:s,vaultAddress:o}}calculateEffectiveSlippage(e,t,n){const r=n??this.defaultSlippageToleranceFactor,i=t??this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor;let s=e??"0";return null!=e&&(s=RA(e,i,"buy-exact"),this.logger.debug("Reverse bonding curve fee slippage applied:",{baseFee:e,slippageFactor:i,adjustedMaxFee:s})),{effectiveSlippageFactor:r,effectiveFeeSlippageFactor:i,effectiveMaxFee:s}}ensureTradingServicesAvailable(){if(!this.signer||!this.tokenKeyService)throw Pt("Trading services not available. BundleService requires walletProvider and userAddress for trading operations.","walletProvider");if(null===this.userAddress||void 0===this.userAddress)throw Ot("userAddress","User address")}async executeBundleTransaction(e,t,n){this.ensureTradingServicesAvailable();try{e.uniqueKey=BA("galaswap-operation");const r=await this.signer.signObject(t,e),i=this.tokenKeyService.generateStringsInstructions(n),s={stringsInstructions:i,method:t,signedDto:r};this.logger.debug("📦 Bundle transaction data:",{method:t,stringsInstructions:i,dtoKeys:Object.keys(r)});const o=await this.submitTransaction(s);if(o.success){const e=Qt(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 Bt("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 VA extends Er{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(gt),t=this.extractData(e);return this.logger.debug("Fetched client feature flags",{flagCount:Object.keys(t.flags).length}),{flags:t.flags}}}var zA,XA,JA,YA;!function(e){e.CHAT_MESSAGE="CHAT_MESSAGE",e.COMMENT="COMMENT",e.STREAM="STREAM",e.RECORDING="RECORDING"}(zA||(zA={})),function(e){e.INAPPROPRIATE_CONTENT="INAPPROPRIATE_CONTENT",e.SPAM="SPAM",e.HARASSMENT="HARASSMENT",e.SCAM="SCAM",e.OTHER="OTHER"}(XA||(XA={})),function(e){e.PENDING="PENDING",e.DISMISSED="DISMISSED",e.ACTIONED="ACTIONED"}(JA||(JA={})),function(e){e.DELETE_CONTENT="DELETE_CONTENT",e.BAN_USER="BAN_USER",e.DELETE_AND_BAN="DELETE_AND_BAN"}(YA||(YA={}));const QA={[XA.INAPPROPRIATE_CONTENT]:"Inappropriate Content",[XA.SPAM]:"Spam",[XA.HARASSMENT]:"Harassment",[XA.SCAM]:"Scam",[XA.OTHER]:"Other"},ZA={[JA.PENDING]:"Pending",[JA.DISMISSED]:"Dismissed",[JA.ACTIONED]:"Actioned"},ek={[YA.DELETE_CONTENT]:"Delete Content",[YA.BAN_USER]:"Ban User",[YA.DELETE_AND_BAN]:"Delete & Ban"},tk={[zA.CHAT_MESSAGE]:"Chat Message",[zA.COMMENT]:"Comment",[zA.STREAM]:"Stream",[zA.RECORDING]:"Recording"},nk=500,rk=or(zA),ik=or(XA),sk=or(JA),ok=or(YA),ak=gr([{field:"id",type:"number"},{field:"tokenName",type:"string"},{field:"contentType",type:"string",validator:rk},{field:"contentId",type:"string"},{field:"reporterAddress",type:"string"},{field:"reportedUserAddress",type:"string"},{field:"status",type:"string",validator:sk}]),ck={TOKEN_NAME:vn,CONTENT_ID:In.CONTENT_ID,DETAILS:In.FLAG_DETAILS,PAGINATION:{MAX_LIMIT:En}};function lk(e,t="tokenName"){lr(e,t,ck.TOKEN_NAME)}function uk(e){if(void 0!==e.contentType&&!rk(e.contentType))throw Ut("contentType",`one of: ${Object.values(zA).join(", ")}`,"Content type");if(void 0!==e.status&&!sk(e.status))throw Ut("status",`one of: ${Object.values(JA).join(", ")}`);if(void 0!==e.reason&&!ik(e.reason))throw Ut("reason",`one of: ${Object.values(XA).join(", ")}`);if(void 0!==e.reporterAddress&&!nr(e.reporterAddress))throw Wt("reporterAddress","a non-empty string",typeof e.reporterAddress);if(void 0!==e.reporterAddress&&Mr(e.reporterAddress,"reporterAddress"),void 0!==e.reportedUserAddress&&!nr(e.reportedUserAddress))throw Wt("reportedUserAddress","a non-empty string",typeof e.reportedUserAddress);void 0!==e.reportedUserAddress&&Mr(e.reportedUserAddress,"reportedUserAddress"),sr(0,void 0,ck.PAGINATION.MAX_LIMIT,e.pageSize)}class dk extends WE{constructor(e,t,n,r=!1,i){super(e,t,n,r,i)}async createFlag(e){!function(e){if(lk(e.tokenName),void 0===e.contentType)throw Ot("contentType","Content type");if(!rk(e.contentType))throw Ut("contentType",`one of: ${Object.values(zA).join(", ")}`,"Content type");if(!nr(e.contentId))throw Ot("contentId","Content ID");if(e.contentId.length>ck.CONTENT_ID.MAX_LENGTH)throw Ht("contentId",ck.CONTENT_ID.MAX_LENGTH,e.contentId.length,"Content ID");if(!nr(e.reportedUserAddress))throw Ot("reportedUserAddress","Reported user address");if(Mr(e.reportedUserAddress,"reportedUserAddress"),!(e.contentType!==zA.STREAM&&e.contentType!==zA.RECORDING||void 0!==e.reason&&null!==e.reason))throw Ot("reason","Reason");if(void 0!==e.reason&&!ik(e.reason))throw Ut("reason",`one of: ${Object.values(XA).join(", ")}`,"Reason");if(void 0!==e.details&&!nr(e.details))throw Wt("details","a non-empty string",typeof e.details);if(void 0!==e.details&&e.details.length>ck.DETAILS.MAX_LENGTH)throw Ht("details",ck.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(ve.CREATE,t,this.getMultiAuthHeaders());return{flag:this.extractData(n).flag}}async listFlags(e){return function(e){lk(e.tokenName),uk(e)}(e),this.fetchFlagList(e)}async listGlobalFlags(e={}){return function(e){void 0!==e.tokenName&&lk(e.tokenName),uk(e)}(e),this.fetchFlagList(e)}async dismissFlag(e){!function(e){if(void 0===e.flagId||null===e.flagId)throw Ot("flagId","Flag ID");try{zn(e.flagId,"flagId")}catch{throw Ut("flagId","a positive integer","Flag ID")}}(e);const t=ve.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 Ot("flagId","Flag ID");try{zn(e.flagId,"flagId")}catch{throw Ut("flagId","a positive integer","Flag ID")}if(void 0===e.action)throw Ot("action","Action");if(!ok(e.action))throw Ut("action",`one of: ${Object.values(YA).join(", ")}`,"Action")}(e);const t=ve.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=KE(e,En);GE(t,e,["tokenName","contentType","status","reason","reporterAddress","reportedUserAddress"]);const n=await this.http.get(ve.LIST,t,this.getMultiAuthHeaders()),r=this.extractData(n);return{items:r.flags,pageInfo:r.pageInfo}}}const hk=["heart","fire","laugh","wow","thumbs_up"],gk={heart:"❤️",fire:"🔥",laugh:"😂",wow:"😮",thumbs_up:"👍"};class fk extends WE{constructor(e,t,n,r=!1,i){super(e,t,n,r,i)}validateReactionTokenName(e){this.validateTokenName(e,vn)}validateMessageId(e){if(!nr(e))throw Ot("messageId","Message ID");if(Vn(e,Nn.CONTENT_REACTION.MAX_LENGTH,"messageId"),!Nn.CONTENT_REACTION.PATTERN.test(e))throw Ut("messageId","msg-{timestamp}-{uuid} or chat-{timestamp}-{uuid} format","Message ID")}validateReactionType(e){if(!nr(e))throw Ot("reactionType","Reaction type");if(!hk.includes(e))throw Ut("reactionType",`one of: ${hk.join(", ")}`,"Reaction type")}async addContentReaction(e){void 0!==e.tokenName&&this.validateReactionTokenName(e.tokenName),this.validateMessageId(e.messageId),this.validateReactionType(e.reactionType);const t=je,n={messageId:e.messageId,reactionType:e.reactionType};void 0!==e.tokenName&&(n.tokenName=on(e.tokenName));const r=await this.http.post(t,n,this.getMultiAuthHeaders()),i=this.extractData(r),{created:s,...o}=i;return{data:o,created:s}}async removeContentReaction(e){void 0!==e.tokenName&&this.validateReactionTokenName(e.tokenName),this.validateMessageId(e.messageId),this.validateReactionType(e.reactionType);const t=`${Ve}?${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 mk extends Ar{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}=cr(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 Ct("tokenName parameter requires LaunchpadSDK routing - call LaunchpadSDK.fetchTokenPrice({tokenName}) instead","tokenName","INVALID_PARAMS")}async _fetchDexTokenSpotPrice(e){if(null==e)throw Ot("tokenId","Token ID");try{const t=bA(e),n=No(t),r=GA(n);if(this.logger.debug(`Fetching DEX spot price for token: ${r}`),!this.dexBackendHttp)throw Lt("DEX Backend API client not configured");const i=await this.dexBackendHttp.request({method:"GET",url:"/market/price",params:{assetIds:r}}),s=null!==i&&"object"==typeof i?i:{},o=[t.type,t.collection].filter(e=>"string"==typeof e&&""!==e&&"none"!==e).map(e=>e.toUpperCase()).map(e=>s[e]).find(e=>void 0!==e)??(1===Object.keys(s).length?Object.values(s)[0]:void 0),a=o?.price;if("number"!=typeof a||!Number.isFinite(a))throw new Ct(`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: ${yt(e)?e.message:String(e)}`),l=cn("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 Ct)throw e;throw Lt(`Failed to fetch DEX spot price: ${bt(e)}`)}}async fetchLaunchpadTokenSpotPrice(e,t,n){if(!nr(e))throw new Ct(Tt,"tokenName",Nt.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=No(t.sellingToken);return this._fetchDexTokenSpotPrice(n)}}catch(t){this.logger.debug(`Could not determine graduation status for ${e}, falling back to bonding curve: ${bt(t)}`)}this.logger.debug(`Using bonding curve calculation for token: ${e}`);const r=await t({tokenName:e,amount:"1",type:"native"}),i=await this._fetchDexTokenSpotPrice({collection:"GALA",category:"Unit",type:"none",additionalKey:"none"});if(null==i)throw Lt("GALA price not available");const s=Pn(r.amount,0)/1e18;if(s<=0)throw new Ct(`Invalid token amount calculation: ${s}`,"amount","INVALID_CALCULATION");const o=i.price/s;return{symbol:cn(e),price:o}}catch(t){if(yt(t))throw Lt(`Failed to calculate launchpad token spot price for ${e}: ${bt(t)}`);throw Lt(`Failed to calculate launchpad token spot price for ${e}: ${bt(t)}`)}}async fetchTokenDetails(e){this.logger.debug("Fetching token details from GalaChain for tokenId:",e);try{if(!this.galaChainService)throw Lt("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 Ct||yt(t))&&("NetworkError"===t.name||bt(t).includes("Token not found")))throw t;throw Lt(`Failed to fetch token details from GalaChain for ${String(e)}: ${bt(t)}`,500)}}async fetchAllDexSeasons(){try{if(!this.dexBackendHttp)throw Lt("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=Qt(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:mn(t?.start??null),end:mn(t?.end??null),rulesId:t?.rules_id??0}});return this.logger.debug(`Fetched ${n.length} DEX seasons`),n}catch(e){if(yt(e)&&bt(e).includes("not configured"))throw e;if(Et(e)&&404===e.response?.status)return this.logger.warn("Seasons endpoint not available"),[];throw Lt(`Failed to fetch DEX seasons: ${bt(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{zn(e,"seasonId")}catch{throw Ot("seasonId","Season ID must be a positive number")}try{if(!this.dexBackendHttp)throw Lt("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=Qt(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(yt(t)&&bt(t).includes("must be a positive number"))throw t;throw Lt(`Failed to fetch DEX leaderboard for season ${e}: ${bt(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 Lt("DEX Backend API client not configured");const e=Qt(await this.dexBackendHttp.request({method:"GET",url:"/v2/trade/volume"}));if(!e)throw Lt("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 Lt(`Failed to fetch DEX volume summary: ${bt(e)}`)}}}const pk={BATCH_SIZE:20,FLUSH_INTERVAL_MS:3e3,MAX_QUEUE_SIZE:1e3,FLUSH_ON_PAGE_HIDE:!0,FLUSH_ON_PAGE_UNLOAD:!0,DEBUG:!1},yk={LOGIN:"login",LOGOUT:"logout",TOKEN_BUY:"token_buy",TOKEN_SELL:"token_sell",TOKEN_SWAP:"token_swap",TOKEN_CREATED:"token_created",TOKEN_GRADUATED:"token_graduated",PAGE_VIEW:"page_view",PAGE_LEAVE:"page_leave",STREAM_START:"stream_start",STREAM_END:"stream_end",STREAM_VIEWERS_CHANGED:"stream_viewers_changed",CHAT_MESSAGE_SENT:"chat_message_sent",CHAT_MESSAGE_RECEIVED:"chat_message_received",LIQUIDITY_ADDED:"liquidity_added",LIQUIDITY_REMOVED:"liquidity_removed",BRIDGE_DEPOSIT:"bridge_deposit",BRIDGE_WITHDRAW:"bridge_withdraw",PROFILE_UPDATED:"profile_updated",BALANCE_CHANGED:"balance_changed",ERROR_OCCURRED:"error_occurred"};class bk{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 un({debug:t.debug??!1,context:"EventsBatcherService"}),this.config={batchSize:t.batchSize??pk.BATCH_SIZE,flushIntervalMs:t.flushIntervalMs??pk.FLUSH_INTERVAL_MS,maxQueueSize:t.maxQueueSize??pk.MAX_QUEUE_SIZE,flushOnPageHide:t.flushOnPageHide??pk.FLUSH_ON_PAGE_HIDE,flushOnPageUnload:t.flushOnPageUnload??pk.FLUSH_ON_PAGE_UNLOAD,debug:t.debug??pk.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 vk(e){return 0===(e?.length??0)?"0":e.reduce((e,t)=>A(e).plus(t.quantity).toString(),"0")}function wk(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 Ek extends Er{constructor(e,t=!1){super(e,t)}getChannelForCollection(e){return"MUSIC"===(qw(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{At(r,"Fetch balances")}catch{return null}if(0===(r.Data?.length??0))return null;const i=r.Data.find(t=>t.collection===e.collection&&t.category===e.category&&t.additionalKey===e.additionalKey&&t.type===e.type);if(!i||"0"===i.quantity)return null;const s=No(i),o={quantity:i.quantity,collection:i.collection,category:i.category,tokenId:s};if((i.inUseHolds?.length??0)>0){const e=wk(i.inUseHolds??[],t);e.length>0&&(o.inUseHolds=e,o.inUseQuantity=vk(e))}if((i.lockedHolds?.length??0)>0){const e=wk(i.lockedHolds??[],t);e.length>0&&(o.lockedHolds=e,o.lockedQuantity=vk(e))}return void 0===o.lockedQuantity&&void 0===o.inUseQuantity||(o.availableQuantity=function(e,t="0",n="0"){return A(e).minus(t).minus(n).toString()}(o.quantity,o.lockedQuantity,o.inUseQuantity)),o}catch(e){throw Lt(`Failed to fetch token balance from GalaChain: ${bt(e)}`,void 0,yt(e)?e:void 0)}}}function Ak(e){return"string"==typeof e?{...HA(e),instance:"0"}:{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey,instance:"0"}}function kk(e){return Co(e)}function Sk(e){const t=e[0];return void 0===t?void 0:kk(t.tokenInstanceKey)}class Tk extends w{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,i){const s=Ak(r);return new Tk({lockAuthority:t??e,tokenInstances:[{owner:e,quantity:n,tokenInstanceKey:s}],...void 0!==i?.expires&&{expires:i.expires},...void 0!==i?.name&&{name:i.name},uniqueKey:i?.uniqueKey??DA()})}static forGALA(e,t,n,r){return new Tk({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??DA()})}getTokenClassKey(){return Sk(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 Ik extends w{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 i=Ak(n);return new Ik({tokenInstances:[{owner:e,quantity:t,tokenInstanceKey:i}],...void 0!==r?.name&&{name:r.name},uniqueKey:r?.uniqueKey??DA()})}static forGALA(e,t,n){return new Ik({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??DA()})}getTokenClassKey(){return Sk(this.tokenInstances)}toSigningPayload(){return{tokenInstances:this.tokenInstances,...void 0!==this.name&&{name:this.name},uniqueKey:this.uniqueKey}}}function Nk(e){if(null==e||"object"!=typeof e)return!1;const t=e;return nr(t.amount)&&(void 0!==t.tokenId||nr(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 Ck(e){if(null==e||"object"!=typeof e)return!1;const t=e;return nr(t.amount)&&(void 0!==t.tokenId||nr(t.tokenName))&&(void 0===t.name||"string"==typeof t.name)}function _k(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every(Nk)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}function xk(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every(Ck)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}const Rk=100,Bk=100;var Dk,Mk;!function(e){e.TOKEN_NOT_FOUND="TOKEN_NOT_FOUND",e.INVALID_AMOUNT="INVALID_AMOUNT",e.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",e.SIGNATURE_FAILED="SIGNATURE_FAILED",e.NETWORK_ERROR="NETWORK_ERROR",e.WALLET_REQUIRED="WALLET_REQUIRED",e.VALIDATION_ERROR="VALIDATION_ERROR",e.LOCK_NOT_FOUND="LOCK_NOT_FOUND",e.LOCK_EXPIRED="LOCK_EXPIRED",e.INSUFFICIENT_LOCKED_BALANCE="INSUFFICIENT_LOCKED_BALANCE",e.NOT_LOCK_AUTHORITY="NOT_LOCK_AUTHORITY",e.LOCK_NAME_MISMATCH="LOCK_NAME_MISMATCH"}(Dk||(Dk={}));class Ok 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"}(Mk||(Mk={}));class Uk extends Error{constructor(e,t,n){super(e),this.type=t,this.details=n,this.name="TransferError"}}function Lk(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 Pk(e,t,n,r="[DEBUG] Token resolution (launchpad)"){const i=await t.resolveTokenToVault(e);if(null!==i){const t=wA(i);return n.debug(r,{tokenName:e,vaultAddress:i,tokenInstance:{collection:t.collection,category:t.category,type:t.type,instance:t.instance}}),t}const s={collection:an(e),category:"Unit",type:"none",additionalKey:"none",instance:"0"};return n.debug("[DEBUG] Token resolution (standard format)",{tokenName:e,tokenInstance:{collection:s.collection,category:s.category,type:s.type}}),s}const Fk=100,$k=100;class Kk extends Er{constructor(e,t,n,r=!1){super(e,r),this.wallet=t,this.tokenResolver=n,this.nativeSigner=t?new FA(t.privateKey):void 0}async lockTokens(e){if(this.validateLockTokensData(e),!this.wallet||!this.nativeSigner)throw new Ok("Wallet required for token lock operations",Dk.WALLET_REQUIRED);return vo(async()=>{const{ownerAddress:t,tokenInstances:n}=this.createTokenOperationContext(),r=[];let i=t;const s=e.tokens.find(e=>void 0!==e.lockAuthority);void 0!==s?.lockAuthority&&(i=xr(s.lockAuthority));const o=e.tokens.find(e=>void 0!==e.expires),a=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,lockAuthority:void 0!==s.lockAuthority?xr(s.lockAuthority):i})}const c=new Tk({lockAuthority:i,tokenInstances:n,...void 0!==o?.expires&&{expires:o.expires},...void 0!==a?.name&&{name:a.name},uniqueKey:e.uniqueKey??DA()}),l=await this.nativeSigner.signObject("LockToken",c.toSigningPayload()),u=new Tk({...c.toSigningPayload(),signedPayload:l}),d=await this.http.post("/api/asset/token-contract/LockToken",u);try{At(d,"Token lock failed")}catch(e){const t=kt(d);throw new Ok(`${bt(e)}${t}`,Dk.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 Ok("Wallet required for token unlock operations",Dk.WALLET_REQUIRED);return vo(async()=>{const{ownerAddress:t,tokenInstances:n}=this.createTokenOperationContext(),r=[],i=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})}const s=new Ik({tokenInstances:n,...void 0!==i?.name&&{name:i.name},uniqueKey:e.uniqueKey??DA()}),o=await this.nativeSigner.signObject("UnlockToken",s.toSigningPayload()),a=new Ik({...s.toSigningPayload(),signedPayload:o}),c=await this.http.post("/api/asset/token-contract/UnlockToken",a);try{At(c,"Token unlock failed")}catch(e){const t=kt(c);throw new Ok(`${bt(e)}${t}`,Dk.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 Ok("Must provide either tokenId or tokenName for token identification",Dk.TOKEN_NOT_FOUND);if(void 0!==e.tokenName)try{hr(e.tokenName,"tokenName")}catch{throw new Ok("Invalid token name format",Dk.TOKEN_NOT_FOUND,{tokenName:e.tokenName})}try{Xs(Ws(e.amount))}catch{throw new Ok(Ut(t,"a positive number",n).message,Dk.INVALID_AMOUNT,{amount:e.amount})}}validateLockTokensData(e){if(!_k(e))throw new Ok("Invalid lock data: missing required fields",Dk.VALIDATION_ERROR);if(e.tokens.length>Fk)throw new Ok(`Batch size exceeds maximum limit of ${Fk} tokens per lock operation`,Dk.VALIDATION_ERROR);for(const t of e.tokens){if(this.validateSharedTokenEntry(t,"lockAmount","Lock amount"),void 0!==t.lockAuthority&&!Dr(t.lockAuthority))throw new Ok("Invalid lock authority address format",Dk.VALIDATION_ERROR,{lockAuthority:t.lockAuthority});if(void 0!==t.expires)try{zn(t.expires,"expires")}catch{throw new Ok(Ut("expires","a positive integer (epoch milliseconds)","Expires").message,Dk.VALIDATION_ERROR)}}}validateUnlockTokensData(e){if(!xk(e))throw new Ok("Invalid unlock data: missing required fields",Dk.VALIDATION_ERROR);if(e.tokens.length>$k)throw new Ok(`Batch size exceeds maximum limit of ${$k} tokens per unlock operation`,Dk.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 Ok)return e;let r=t,i=Dk.NETWORK_ERROR;if(Et(e)){const n=e.response?.data;if("object"==typeof n&&null!==n){const e=n.Message;"string"==typeof e&&e.length>0&&(r=`${t}: ${e}`);const s="string"==typeof e?e.toLowerCase():"";s.includes("insufficient")||s.includes("balance")?i=Dk.INSUFFICIENT_BALANCE:s.includes("lock")&&s.includes("not found")?i=Dk.LOCK_NOT_FOUND:s.includes("not found")||s.includes("token")?i=Dk.TOKEN_NOT_FOUND:s.includes("authority")?i=Dk.NOT_LOCK_AUTHORITY:s.includes("expired")&&(i=Dk.LOCK_EXPIRED)}}else yt(e)&&(r=`${t}: ${bt(e)}`);return new Ok(r,i,Lk(n))}async resolveTokenInstance(e){return vo(async()=>Pk(e,this.tokenResolver,this.logger),`Failed to resolve token '${e}'`,this.logger,t=>{if(t instanceof Uk)throw new Ok(bt(t),Dk.TOKEN_NOT_FOUND);throw new Ok(`Failed to resolve token '${e}': ${bt(t)}`,Dk.TOKEN_NOT_FOUND,{tokenName:e})})}async resolveTokenEntry(e){if(void 0!==e.tokenId){const t=bA(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 Ok("Must provide either tokenId or tokenName for token identification",Dk.TOKEN_NOT_FOUND)}createTokenOperationContext(){return{ownerAddress:xr(this.wallet.address),tokenInstances:[]}}}class Gk extends Er{constructor(e,t=!1,n){super(e,t),this.publicAxios=n}async fetchTokenClassFromChain(e){try{const t="string"==typeof e?bA(e):e,n={tokenClasses:[{collection:t.collection,category:t.category,type:t.type,additionalKey:t.additionalKey}]};if(!this.publicAxios)throw Ot("publicAxios","Public Axios instance");const r=(await this.publicAxios.post("/api/asset/token-contract/FetchTokenClasses",n)).data;if(At(r,"Failed to fetch token class from GalaChain"),null===r.Data||void 0===r.Data||0===r.Data.length)throw Lt(`Token not found on GalaChain: ${No(t)}`,404);const i=r.Data[0];if(void 0===i)throw Lt(`Token not found on GalaChain: ${No(t)}`,404);return i}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 Ot("tokenClasses","Token classes array");const t={tokenClasses:e};if(!this.publicAxios)throw Ot("publicAxios","Public Axios instance");const n=(await this.publicAxios.post("/api/asset/token-contract/FetchTokenClassesWithSupply",t)).data;if(At(n,"Failed to fetch token classes with supply from GalaChain"),!n.Data||0===n.Data.length)throw Lt("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 Ct)throw e;if(Et(e)&&404===e.response?.status)throw Lt(t,404,yt(e)?e:void 0);if(yt(e)&&"Error"===e.name&&bt(e).includes("status indicates failure"))throw Lt(bt(e),400,yt(e)?e:void 0);const r=bt(e);if(r.includes("Token not found")){if(e instanceof Error)throw e;throw new Error(r)}throw Lt(`${n}: ${r}`,void 0,yt(e)?e:void 0)}}class Hk extends w{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=Ak(e.tokenClassKey);return{quantity:e.quantity,tokenInstanceKey:t}});return new Hk({tokenInstances:n,uniqueKey:t?.uniqueKey??DA()})}static fromTokenClassKey(e,t,n){return Hk.fromTokens([{tokenClassKey:t,quantity:e}],n)}static forGALA(e,t){return new Hk({tokenInstances:[{quantity:e,tokenInstanceKey:{collection:"GALA",category:"Unit",type:"none",additionalKey:"none",instance:"0"}}],uniqueKey:t?.uniqueKey??DA()})}getTokenClassKey(){if(0===this.tokenInstances.length)return;const e=this.tokenInstances[0];return void 0!==e?kk(e.tokenInstanceKey):void 0}toSigningPayload(){return{tokenInstances:this.tokenInstances,uniqueKey:this.uniqueKey}}}class Wk extends w{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,i){let s;if("string"==typeof r){s={...HA(r),instance:"0"}}else s={collection:r.collection,category:r.category,type:r.type,additionalKey:r.additionalKey,instance:"0"};return new Wk({from:e,to:t,quantity:n,tokenInstance:s,uniqueKey:i??DA()})}static forGALA(e,t,n,r){return new Wk({from:e,to:t,quantity:n,tokenInstance:{collection:"GALA",category:"Unit",type:"none",additionalKey:"none",instance:"0"},uniqueKey:r??DA()})}getTokenClassKey(){return Co(this.tokenInstance)}toSigningPayload(){return{from:this.from,to:this.to,quantity:this.quantity,tokenInstance:this.tokenInstance,uniqueKey:this.uniqueKey}}}function qk(e){if(null==e||"object"!=typeof e)return!1;const t=e;return nr(t.amount)&&(void 0!==t.tokenId||nr(t.tokenName))}function jk(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every(qk)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}const Vk=50;var zk;!function(e){e.TOKEN_NOT_FOUND="TOKEN_NOT_FOUND",e.INVALID_AMOUNT="INVALID_AMOUNT",e.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",e.SIGNATURE_FAILED="SIGNATURE_FAILED",e.NETWORK_ERROR="NETWORK_ERROR",e.WALLET_REQUIRED="WALLET_REQUIRED",e.VALIDATION_ERROR="VALIDATION_ERROR"}(zk||(zk={}));class Xk extends Error{constructor(e,t,n){super(e),this.type=t,this.details=n,this.name="BurnError"}}const Jk={validateAmount(e){const t=Ws(e);try{Ys(t,"amount")}catch(t){throw new Uk(t.message,Mk.INVALID_AMOUNT,{amount:e})}},validateUniqueKey(e){if(!ir(e)&&nr(e)){if(e.length>xn.MAX_LENGTH)throw new Ct(`Unique key too long. Maximum length: ${xn.MAX_LENGTH}`);if(!xn.PATTERN.test(e))throw new Uk('Invalid unique key format. Must start with "galaswap-operation-" or "galaconnect-operation-"',Mk.INVALID_AMOUNT,{uniqueKey:e})}}},Yk="gala-transfer-successful",Qk="token-transfer-successful",Zk="token-locked-successfully",eS="token-unlocked-successfully",tS="transfer-successful-no-id",nS=50;class rS extends Er{constructor(e,t,n,r=!1){super(e,r),this.wallet=t,this.tokenResolver=n,this.nativeSigner=t?new FA(t.privateKey):void 0}async transferGala(e){if(this.validateTransferGalaData(e),!this.wallet||!this.nativeSigner)throw new Uk("Wallet required for GALA transfer operations",Mk.WALLET_REQUIRED);try{const t=xr(e.recipientAddress),n=xr(this.wallet.address),r=Wk.forGALA(n,t,e.amount,e.uniqueKey),i=await this.nativeSigner.signObject("TransferToken",r.toSigningPayload()),s=new Wk({...r.toSigningPayload(),signedPayload:i}),{data:o,headers:a}=await this.http.postWithMeta("/api/asset/token-contract/TransferToken",s);if(null==o)throw new Uk("No response from GalaChain transfer service",Mk.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 Uk("Wallet required for token transfer operations",Mk.WALLET_REQUIRED);try{const t=xr(e.to),n=xr(this.wallet.address);let r;if(null!==e.tokenId&&void 0!==e.tokenId)r=bA(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 Uk("Must provide either tokenId or tokenName for token identification",Mk.TOKEN_NOT_FOUND);r=await this.resolveTokenInstance(e.tokenName)}const i=new Wk({from:n,to:t,quantity:e.amount,tokenInstance:r,uniqueKey:e.uniqueKey??DA()}),s=await this.nativeSigner.signObject("TransferToken",i.toSigningPayload()),o=new Wk({...i.toSigningPayload(),signedPayload:s}),{data:a,headers:c}=await this.http.postWithMeta("/api/asset/token-contract/TransferToken",o);if(null==a)throw new Uk("No response from GalaChain transfer service",Mk.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 Uk)throw t;throw new Uk(`Failed to resolve token class key for '${e}': ${bt(t)}`,Mk.TOKEN_NOT_FOUND,{tokenName:e})}}async burnTokens(e){if(this.validateBurnTokensData(e),!this.wallet||!this.nativeSigner)throw new Xk("Wallet required for token burn operations",zk.WALLET_REQUIRED);try{const t=[];for(const n of e.tokens){let e;if(null!==n.tokenId&&void 0!==n.tokenId)e=bA(n.tokenId),this.logger.debug("[DEBUG] Using provided tokenId:",n.tokenId);else{if(null===n.tokenName||void 0===n.tokenName)throw new Xk("Must provide either tokenId or tokenName for token identification",zk.TOKEN_NOT_FOUND);e=await this.resolveTokenInstance(n.tokenName)}t.push({quantity:n.amount,tokenInstanceKey:e})}const n=new Hk({tokenInstances:t,uniqueKey:e.uniqueKey??DA()}),r=await this.nativeSigner.signObject("BurnTokens",n.toSigningPayload()),i=new Hk({...n.toSigningPayload(),signedPayload:r}),s=await this.http.post("/api/asset/token-contract/BurnTokens",i);if(null==s)throw new Xk("No response from GalaChain burn service",zk.NETWORK_ERROR);try{At(s,"Token burn operation")}catch(e){throw new xt(bt(e),500)}return this.extractBurnResult(s)}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 nr(t.recipientAddress)&&nr(t.amount)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)}(e))throw new Ct("Invalid GALA transfer data: missing required fields");if(!Dr(e.recipientAddress))throw new Uk("Invalid recipient address format",Mk.INVALID_RECIPIENT,{recipientAddress:e.recipientAddress});Jk.validateAmount(e.amount),Jk.validateUniqueKey(e.uniqueKey)}validateTransferTokenData(e){if(!function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return nr(t.to)&&nr(t.amount)&&(void 0!==t.tokenId||nr(t.tokenName))&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)}(e))throw new Ct("Invalid token transfer data: missing required fields");if(!Dr(e.to))throw new Uk("Invalid recipient address format",Mk.INVALID_RECIPIENT,{recipientAddress:e.to});if(!(null!==e.tokenId&&void 0!==e.tokenId||null!==e.tokenName&&void 0!==e.tokenName))throw new Uk("Must provide either tokenId or tokenName for token identification",Mk.TOKEN_NOT_FOUND);if(null!==e.tokenName&&void 0!==e.tokenName)try{hr(e.tokenName,"tokenName")}catch{throw new Uk("Invalid token name format",Mk.TOKEN_NOT_FOUND,{tokenName:e.tokenName})}Jk.validateAmount(e.amount),Jk.validateUniqueKey(e.uniqueKey)}validateBurnTokensData(e){if(!jk(e))throw new Xk("Invalid burn data: missing required fields",zk.VALIDATION_ERROR);if(e.tokens.length>nS)throw new Xk(`Batch size exceeds maximum limit of ${nS} tokens per burn operation`,zk.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 Xk("Must provide either tokenId or tokenName for token identification",zk.TOKEN_NOT_FOUND);const e=Ws(t.amount);try{Xs(e)}catch{throw new Xk("Burn amount must be a positive number",zk.INVALID_AMOUNT,{amount:t.amount})}}}async resolveTokenInstance(e){try{return await Pk(e,this.tokenResolver,this.logger,`[DEBUG] Token resolution for '${e}' (launchpad):`)}catch(t){if(t instanceof Uk)throw t;throw new Uk(`Failed to resolve token '${e}': ${bt(t)}`,Mk.TOKEN_NOT_FOUND,{tokenName:e})}}extractTransferResult(e,t,n){const r=this.readHeaderValue(t,"x-transaction-id"),i=this.readBlockNumberHeader(t),s=null!=e&&"object"==typeof e&&"Status"in e;s&&At(e,"Extract transaction ID");const o=s&&"Data"in e;if(void 0!==r&&r.length>0)return{transactionId:r,...void 0!==i?{blockNumber:i}:{}};if(null!=e&&"object"==typeof e){if("transactionId"in e&&"string"==typeof e.transactionId&&e.transactionId.length>0)return{transactionId:e.transactionId,...void 0!==i?{blockNumber:i}:{}};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!==i?{blockNumber:i}:{}}}}let e=tS;if(t.Data.length>0)switch(n){case"gala":e=Yk;break;case"token":e=Qk;break;case"lock":e=Zk;break;case"unlock":e=eS}return{transactionId:e,...void 0!==i?{blockNumber:i}:{}}}}}throw new Uk("Operation succeeded but transaction ID could not be extracted (missing x-transaction-id header and body fields)",Mk.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 Uk)return e;if(e instanceof Ct)return new Uk(bt(e),Mk.INVALID_AMOUNT);if(Et(e)&&e.response){const t=e.response.status,r=e.response.data;if(400===t){const e=r?.message;return new Uk(("string"==typeof e?e:void 0)??"Invalid transfer request",Mk.INVALID_AMOUNT)}if(403===t)return new Uk("Insufficient balance for transfer",Mk.INSUFFICIENT_BALANCE);if(404===t){const e={};return"tokenName"in n&&(e.tokenName=n.tokenName),new Uk("Token not found",Mk.TOKEN_NOT_FOUND,e)}}if("object"==typeof e&&null!==e&&"code"in e&&("ECONNABORTED"===wt(e)||"ETIMEDOUT"===wt(e)))return new Uk("Transfer request timed out",Mk.NETWORK_ERROR);const r=""!==bt(e)?bt(e):t;return new Uk(r,Mk.NETWORK_ERROR)}handleBurnError(e,t,n){if(e instanceof Xk)return e;let r=t,i=zk.NETWORK_ERROR;if(Et(e)){const n=e.response?.data;if("object"==typeof n){const e=n.Message;if("string"==typeof e&&e.length>0){r=`${t}: ${e}`;const n=e.toLowerCase();n.includes("insufficient")||n.includes("balance")?i=zk.INSUFFICIENT_BALANCE:(n.includes("not found")||n.includes("token"))&&(i=zk.TOKEN_NOT_FOUND)}}}else yt(e)&&(r=`${t}: ${bt(e)}`);return new Xk(r,i,Lk(n))}}class iS extends Er{constructor(e,t,n,r=!1,i){super(e,r),this.balanceService=new Ek(e,r),this.tokenService=new Gk(e,r,i),this.lockService=new Kk(e,t,n,r),this.transferService=new rS(e,t,n,r)}async fetchPoolDetails(e){this.validateFetchPoolDetailsData(e);const t=await this.http.post("/api/asset/launchpad-contract/FetchSaleDetails",e);wo(()=>At(t,"Failed to fetch pool details"),"Failed to fetch pool details",this.logger,e=>{throw Lt(bt(e),500)});const n=t.Data.reverseBondingCurveConfiguration,r=n?.minFeePortion??"0",i=n?.maxFeePortion??"0",s=!Vs(r)||!Vs(i),o=t.Data;return o.reverseBondingCurveMinFeePortion=r,o.reverseBondingCurveMaxFeePortion=i,o.hasReverseBondingCurveFee=s,o.isGraduated="Finished"===t.Data.saleStatus,delete o.reverseBondingCurveConfiguration,t}async fetchLaunchTokenFee(){const e=await this.http.post("/api/asset/launchpad-contract/FetchLaunchpadFeeAmount",{});return wo(()=>At(e,"Failed to fetch launch token fee"),"Failed to fetch launch token fee",this.logger,e=>{throw Lt(bt(e),500)}),e.Data.feeAmount}validateFetchPoolDetailsData(e){if(!$s(e))throw Ot("data","Fetch pool details data");if("string"!=typeof e.vaultAddress||""===e.vaultAddress)throw Ot("vaultAddress","Vault address");if(!e.vaultAddress.startsWith("service|Token$Unit$"))throw new Ct("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 sS{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 oS extends Error{constructor(e,t,n){super(t),this.name="GdexStreamError",this.code=e,void 0!==n&&(this.data=n)}}class aS extends Ar{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??Io("prod").gdexWebSocketUrl,this.requestTimeoutMs=e.requestTimeoutMs??15e3,this.reconnectionManager=new sS({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,i)=>{const s=setTimeout(()=>{this.pending.delete(n),i(new Error(`GDEX request "${e}" timed out after ${this.requestTimeoutMs}ms`))},this.requestTimeoutMs);this.pending.set(n,{resolve:e=>t(e),reject:i,timeout:s});try{this.socket?.send(JSON.stringify(r))}catch(e){clearTimeout(s),this.pending.delete(n),i(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 oS(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 i=this.subscriptionsByServerId.get(n);if(i?.active)try{i.callback(r)}catch(e){this.logger.error("GDEX subscription callback failed",e)}}async subscribe(e,t,n){const r={channel:e,...n},i=await this.request("gdex_subscribe",r);let s;const o={subscriptionId:i.subscriptionId,unsubscribe:async()=>this.unsubscribe(s)};return s={serverId:i.subscriptionId,params:r,callback:t,handle:o,active:!0},this.activeSubscriptions.add(s),this.subscriptionsByServerId.set(s.serverId,s),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 oS)||-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 cS(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 Ut("file","a File object (browser) or Buffer (Node.js)");{const i=new Blob([e],{type:"image/png"});r.append(t,i,n)}}return r}class lS extends Er{constructor(e,t,n=!1){super(e,n,t)}async uploadImageByTokenName(e){const{tokenName:t,options:n}=e;io(t);const r=`${t}.png`;to(n.file,r,"image/png");try{const e=`${n.tokenName??t}.png`,r=cS(n.file,"image",e),i=await en(()=>this.http.request({method:"POST",url:`${C.UPLOAD_IMAGE}?tokenName=${encodeURIComponent(n.tokenName??t)}`,data:r,headers:this.getJwtHeaders()}),{errorContext:"Image upload failed"});return"string"==typeof i?i:""}catch(e){if(e instanceof Rt)throw e;if(yt(e)&&bt(e).includes("FormData"))throw Pt("File upload failed: FormData not supported in this environment. Ensure you have proper polyfills for Node.js environments.","FormData");throw e}}}function uS(e,t){if(void 0!==e){if(!nr(e))throw Wt("tokenName","string");if(e.length>wn.MAX_LENGTH)throw new Ct(`tokenName must be at most ${wn.MAX_LENGTH} characters`,"tokenName",Nt.TOO_LONG)}if(void 0!==t){if(!nr(t))throw Wt("userAddress","string");if(t.length>Tn.MAX_LENGTH)throw new Ct(`userAddress must be at most ${Tn.MAX_LENGTH} characters`,"userAddress",Nt.TOO_LONG)}}const dS={CHAT_MESSAGE:"CHAT_MESSAGE",COMMENT:"COMMENT"},hS={PAGINATION:{MAX_LIMIT:kn.MAX_LIMIT},CONTENT:{CHAT_MAX_LENGTH:In.CHAT_MESSAGES_V1.MAX_LENGTH,COMMENT_MAX_LENGTH:In.COMMENTS_V1.MAX_LENGTH}};function gS(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 Vt(["type","tokenName","userAddress"]);if(void 0!==e.type&&e.type!==dS.CHAT_MESSAGE&&e.type!==dS.COMMENT)throw new Ct(`type must be one of: ${Object.values(dS).join(", ")}`,"type",Nt.INVALID_VALUE);uS(e.tokenName,e.userAddress),void 0!==e.pageSize&&sr(0,void 0,kn.MAX_LIMIT,e.pageSize)}function fS(e){if(void 0===e.type||null===e.type)throw Ot("type");if(e.type!==dS.CHAT_MESSAGE&&e.type!==dS.COMMENT)throw new Ct(`type must be one of: ${Object.values(dS).join(", ")}`,"type",Nt.INVALID_VALUE);if(!nr(e.tokenName))throw Ot("tokenName");if(e.tokenName.length>wn.MAX_LENGTH)throw new Ct(`tokenName must be at most ${wn.MAX_LENGTH} characters`,"tokenName",Nt.TOO_LONG);if(!nr(e.content))throw Ot("content");if(0===e.content.trim().length)throw Xt("content","Content");const t=e.type===dS.CHAT_MESSAGE?hS.CONTENT.CHAT_MAX_LENGTH:hS.CONTENT.COMMENT_MAX_LENGTH;if(e.content.length>t)throw zt("content",t,e.content.length)}function mS(e){if(!nr(e.content))throw Ot("content");if(0===e.content.trim().length)throw Xt("content","Content");const t=Math.max(hS.CONTENT.CHAT_MAX_LENGTH,hS.CONTENT.COMMENT_MAX_LENGTH);if(e.content.length>t)throw zt("content",t,e.content.length)}function pS(e){if(!nr(e))throw Ot("id","Message ID");const t=Nn.CHAT_MESSAGE.PATTERN.test(e),n=/^msg-\d{13}-[a-f0-9]{32}$/.test(e);if(!t&&!n)throw new Ct("Invalid message ID format. Expected: chat-{timestamp}-{uuid} or msg-{timestamp}-{uuid}","id",Nt.INVALID_FORMAT)}function yS(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 Ct("At least one config option must be provided (messagesEnabled, commentsEnabled, streamingEnabled, nextLiveStreamAt, streamLanguage, or social URLs)","options",Nt.REQUIRED);if(void 0!==e.messagesEnabled&&"boolean"!=typeof e.messagesEnabled)throw Wt("messagesEnabled","boolean");if(void 0!==e.commentsEnabled&&"boolean"!=typeof e.commentsEnabled)throw Wt("commentsEnabled","boolean");if(void 0!==e.streamingEnabled&&"boolean"!=typeof e.streamingEnabled)throw Wt("streamingEnabled","boolean");if(void 0!==e.streamLanguage&&"string"!=typeof e.streamLanguage)throw Wt("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 Wt(n,"string or null")}if(void 0!==e.nextLiveStreamAt&&null!==e.nextLiveStreamAt){if("string"!=typeof e.nextLiveStreamAt)throw Wt("nextLiveStreamAt","string or null");const t=new Date(e.nextLiveStreamAt);if(isNaN(t.getTime()))throw new Ct("nextLiveStreamAt must be a valid ISO date string","nextLiveStreamAt",Nt.INVALID_FORMAT)}}function bS(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.id&&"string"==typeof t.type&&(t.type===dS.CHAT_MESSAGE||t.type===dS.COMMENT)&&"string"==typeof t.tokenName&&"string"==typeof t.userAddress&&"string"==typeof t.content&&"string"==typeof t.createdAt}function vS(e){return e===dS.CHAT_MESSAGE||e===dS.COMMENT}function wS(e,t){if(null==e)return[];if(Array.isArray(e))return e;const n=e[t];return Array.isArray(n)?n:[]}class ES extends Er{constructor(e,t,n=!1){super(e,n,t)}buildPoolFilters(e){return{...!ir(e.search)&&{search:e.search},...!ir(e.tokenName)&&{tokenName:e.tokenName},...!ir(e.type)&&{type:e.type},...!ir(e.hasUpcomingShows)&&{hasUpcomingShows:e.hasUpcomingShows},...!ir(e.language)&&{language:e.language},...!ir(e.recentlyStreamed)&&{recentlyStreamed:e.recentlyStreamed},...!ir(e.hasRecordings)&&{hasRecordings:e.hasRecordings},...!ir(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),ir(e.type)||(r.type=e.type),ir(e.tokenName)||(r.tokenName=e.tokenName),ir(e.search)||(r.search=e.search),ir(e.hasUpcomingShows)||(r.hasUpcomingShows=e.hasUpcomingShows.toString()),ir(e.language)||(r.language=e.language),ir(e.recentlyStreamed)||(r.recentlyStreamed=e.recentlyStreamed.toString()),ir(e.hasRecordings)||(r.hasRecordings=e.hasRecordings.toString()),ir(e.streamStatus)||(r.streamStatus=e.streamStatus);const i=Gs(r),s=Qt(await nn(()=>this.http.get(C.FETCH_POOLS,i),{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}(s),a={hasNextPage:s.hasNextPage??s.pageInfo?.hasNextPage??!1},c=s.count??s.total;void 0!==c&&(a.totalCount=c);const l=s.nextCursor??s.pageInfo?.endCursor;null!=l&&(a.nextCursor=l);const u=s.prevCursor??s.pageInfo?.startCursor;null!=u&&(a.prevCursor=u);const d=s.hasPrevPage??s.pageInfo?.hasPreviousPage;return void 0!==d&&(a.hasPrevPage=d),{items:o,pageInfo:a}}async fetchPools(e){const t=e?.cursor,n=e?.pageSize??DE.DEFAULT_LIMIT;nr(e?.tokenName)&&io(e.tokenName);const r=void 0!==e?.type?{recent:"RECENT",popular:"POPULAR",recordings:"RECORDINGS",seconds_streamed:"SECONDS_STREAMED"}[e.type]:void 0,i=void 0!==e?.streamStatus?{idle:"IDLE",active:"ACTIVE",disabled:"DISABLED"}[e.streamStatus]:void 0,s={...this.buildPoolFilters({search:e?.search,tokenName:e?.tokenName,type:r,hasUpcomingShows:e?.hasUpcomingShows,language:e?.language,recentlyStreamed:e?.recentlyStreamed,hasRecordings:e?.hasRecordings,streamStatus:i}),pageSize:n,...void 0!==t&&{cursor:t}},o=await this.fetchSinglePage(s);return{items:o.items,pageInfo:o.pageInfo}}async fetchAllPools(e){const t=[];let n;const r=DE.BACKEND_MAX_PAGE_SIZE;for(;;){const i={...e,pageSize:r,...void 0!==n&&{cursor:n}},s=await this.fetchPools(i);if(t.push(...s.items),0===s.items.length)break;if(!s.pageInfo.hasNextPage)break;n=s.pageInfo.nextCursor}return{items:t,pageInfo:{hasNextPage:!1,totalCount:t.length}}}async checkPool(e){!function(e){const t=bs(e);!t.success&&t.errors&&ro(t.errors,"options")}(e),nr(e.tokenName)&&io(e.tokenName);try{const t=await this.http.post(C.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===nr(e.symbol)){return!n.symbolAvailable}if(!0===nr(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 i="number"==typeof n.statusCode?n.statusCode:null;if(404===i)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===i&&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 Os(t,"tokenName")&&Ls(t,"from")&&Ls(t,"to")&&Ls(t,"resolution")}(e))throw new Ct("Invalid options provided. Expected { tokenName: string, from?: number, to?: number, resolution?: number }","options","INVALID_OPTIONS");const{tokenName:t,from:n,to:r,resolution:i}=e;if(io(t),null==n||null==r||null==i)throw new Ct("Graph options (from, to, resolution) are required","options","MISSING_GRAPH_OPTIONS");const s={tokenName:t,from:n,to:r,resolution:i};so(s);const o=Gs(s);return{dataPoints:await en(()=>this.http.get(C.CHART,o),{errorContext:"Failed to fetch graph data"})}}async fetchTokenDistribution(e){if(""===e||null==e)throw Ot("tokenName","Token name");let t;io(e);try{t=await nn(()=>this.http.get(`${C.GET_TOKEN_DISTRIBUTION}?tokenName=${e}`),{errorContext:"Failed to fetch token distribution"})}catch(t){if(Et(t)&&500===t.response?.status)throw Lt(`Token distribution data temporarily unavailable for ${e}. This is a backend issue - please try again later.`,500);throw t}return co(Qt(t),t.status,e=>e.toFixed())}async fetchUserHolderContext(e,t){if(""===e||null==e)throw Ot("tokenName","Token name");if(""===t||null==t)throw Ot("userAddress","User address");return io(e),en(()=>this.http.get(`${C.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");io(e);try{const t=C.GET_TOKEN.replace(":tokenName",e.toLowerCase().trim()),n=Qt(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&&io(e.tokenName);try{const t=await this.http.post(C.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(!nr(e))throw Ot("tokenName","Token name");io(e);const t=C.TOKEN_STATS.replace(":tokenName",e.toLowerCase().trim());try{const e=Qt(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 Ot("tokenName","Token name");io(e),yS(t);const n=C.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 AS={PAGINATION:kn,TOKEN_NAME:wn,USER_ADDRESS:Tn};function kS(e){if(void 0!==e.tokenName){if(!nr(e.tokenName))throw Wt("tokenName","a non-empty string",typeof e.tokenName);if(e.tokenName.length>AS.TOKEN_NAME.MAX_LENGTH)throw Ht("tokenName",AS.TOKEN_NAME.MAX_LENGTH,e.tokenName.length)}if(void 0!==e.userAddress){if(!nr(e.userAddress))throw Wt("userAddress","a non-empty string",typeof e.userAddress);if(e.userAddress.length>AS.USER_ADDRESS.MAX_LENGTH)throw Ht("userAddress",AS.USER_ADDRESS.MAX_LENGTH,e.userAddress.length)}if(void 0!==e.search){if("string"!=typeof e.search)throw Wt("search","a string",typeof e.search);if(e.search.length>256)throw Ht("search",256,e.search.length)}if(sr(0,void 0,AS.PAGINATION.MAX_LIMIT,e.pageSize),void 0!==e.txnType&&"BUY"!==e.txnType&&"SELL"!==e.txnType)throw Ut("txnType",'"BUY" or "SELL"');if(void 0!==e.startDate){if(!nr(e.startDate))throw Wt("startDate","a non-empty string",typeof e.startDate);if(isNaN(Date.parse(e.startDate)))throw Ut("startDate","a valid ISO 8601 date")}if(void 0!==e.endDate){if(!nr(e.endDate))throw Wt("endDate","a non-empty string",typeof e.endDate);if(isNaN(Date.parse(e.endDate)))throw Ut("endDate","a valid ISO 8601 date")}if(void 0!==e.minAmount)try{jn(e.minAmount,0,Number.MAX_SAFE_INTEGER,"minAmount")}catch{throw Ut("minAmount","a non-negative number")}if(void 0!==e.maxAmount)try{jn(e.maxAmount,0,Number.MAX_SAFE_INTEGER,"maxAmount")}catch{throw Ut("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),i="number"==typeof t?t:Number(t);if(isNaN(r)||isNaN(i))throw Wt(n,"numeric values",void 0,n);if(r>i)throw new Ct(`Minimum value (${r}) must be less than or equal to maximum value (${i}) for ${n}`,n,Nt.INVALID_RANGE)}(e.minAmount,e.maxAmount,"amountRange")}class SS extends Er{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 Os(t,"tokenName")&&(void 0===t.tradeType||"buy"===t.tradeType||"sell"===t.tradeType)&&Us(t,"userAddress")&&Ls(t,"offset")&&Ls(t,"pageSize")&&Ls(t,"page")&&Ls(t,"limit")}(e))throw new Ct("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=DE.DEFAULT_LIMIT}=e;if(!nr(t))throw Ot("tokenName","Token name");const i={pageSize:String(Math.min(r,An))};void 0!==n&&(i.cursor=n);const s={...i};s.tokenName=t;const o=await this.http.get(C.GET_TRADES,s);if(null==o)throw new Ct("No response from trade service","response","NO_RESPONSE");const a=Qt(o),c=wS(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=on(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?LE(e.pageSize,1,AS.PAGINATION.MAX_LIMIT):AS.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){kS(e);const t=this.buildTradesQueryParams(e);return en(()=>this.http.get(ze,t),{errorContext:"Failed to fetch trades"})}}function TS(e){return!!nr(e)&&Sn.PATTERN.test(e)}function IS(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 NS(e,t){return e.toLowerCase()===t.toLowerCase()}function CS(e){return e.toLowerCase()}function _S(e,t){return e.toLowerCase().includes(t.toLowerCase())}function xS(e,t,n,r){return e===n&&t===r||e===r&&t===n}function RS(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&&DS(e))return MS(e)}return null}return DS(e)?MS(e):null}function BS(e){return null==e||"string"!=typeof e||0===e.trim().length}function DS(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 MS(e){return e.startsWith("0x")?e.slice(2):e}or({BOTH:"both",HELD:"held",CREATED:"created"});class OS extends Er{constructor(e,t,n=!1){super(e,n,t)}async fetchProfile(e){const t=e??this.http.getAddress();if(""===t||null==t||!TS(t))throw Ut("address","eth|[40-hex-chars] or client|[identifier]","Address");const n=null==e,r=n?C.GET_CURRENT_USER:C.GET_PROFILE.replace(":address",t),i=await this.http.get(r,void 0,n?this.getJwtHeaders():void 0);if(null==i)throw new Ct("No response from user service","response","NO_RESPONSE");return i}async updateProfile(e){this.validateUpdateProfileData(e);let t=e.profileImage;if(!nr(t))try{const n=await this.fetchProfile(e.address);t=n.data?.profileImage??""}catch{t=""}const n={profileImage:t,fullName:e.fullName};await en(()=>this.http.put(C.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 Ct("Wallet address not available - wallet not configured","address","NO_WALLET");try{const n=`profile-image-${t}.png`,r=cS(e.file,"image",n),i=await en(()=>this.http.request({method:"POST",url:`${C.UPLOAD_IMAGE}?tokenName=${encodeURIComponent(t)}`,data:r,headers:this.getJwtHeaders()}),{errorContext:"Image upload failed"});return"string"==typeof i?i:""}catch(e){if(e instanceof Ct||e instanceof Rt)throw e;throw new Ct(`Profile image upload failed: ${bt(e)}`,"file","UPLOAD_FAILED")}}async fetchTokenList(e){if(void 0!==e.status&&"created"!==e.type)throw new Ct("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 i=await this.buildFetchRequest(C.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?{...i,tokens:i.tokens.filter(e=>e.tokenName===t||e.name===t)}:i}async fetchTokensHeld(e){if(void 0!==e.type&&"held"!==e.type)throw new Ct("fetchTokensHeld only supports type=held","type","INVALID_TYPE");if(void 0!==e.status)throw new Ct("status filters only apply when type=created","status","INVALID_FILTER");return this.buildFetchRequest(C.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:i,status:s}=e??{};if(void 0!==e?.type&&"created"!==e.type)throw new Ct("fetchTokensCreated only supports type=created","type","INVALID_TYPE");const o=e?.address??this.http.getAddress();if(null==o||""===o)throw new Ct("Wallet address not available - wallet not configured","address","NO_WALLET");const a={type:"created",address:o,pageSize:n??DE.DEFAULT_LIMIT};return void 0!==t&&(a.cursor=t),void 0!==r&&(a.search=r),void 0!==i&&void 0===r&&(a.search=i),void 0!==i&&(a.tokenName=i),void 0!==s&&(a.status=s),this.fetchTokenList(a)}async getManagedTokens(e={}){const t=KE({pageSize:e.pageSize??DE.DEFAULT_LIMIT,...void 0!==e.cursor&&{cursor:e.cursor}},An);return en(()=>this.http.get(C.GET_MANAGED_TOKENS,t,this.getJwtHeaders()),{errorContext:"Failed to fetch managed tokens"})}async buildFetchRequest(e,t,n){this.validateGetTokenListOptions(t);const r=KE({pageSize:t.pageSize??DE.DEFAULT_LIMIT,...void 0!==t.cursor&&{cursor:t.cursor}},An);GE(r,t,["address","search","tokenName","status"]),n.includeType&&!e.includes("?type=")&&(r.type=n.requestType);let i=e;const s=t.address??this.http.getAddress();if(e.includes(":address")){if(0===s.length)throw Ot("address","User address");i=e.replace(":address",s),delete r.address}const o=Qt(await nn(()=>this.http.get(i,r),{errorContext:n.errorMessage})),a=wS(o,n.responseKey).map(e=>{const t="string"==typeof e.tokenName?e.tokenName:"",r="string"==typeof e.name?e.name:t,i="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:s,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:i,updatedAt:"string"==typeof e.updatedAt?e.updatedAt:i}}),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??DE.DEFAULT_LIMIT;if(t<1||t>An)throw new Ct(`pageSize must be between 1 and ${An}`,"pageSize","OUT_OF_RANGE");if(void 0!==e.address&&!TS(e.address))throw Ut("address","eth|[40-hex-chars] or client|[identifier]","Address");const n=IS(e.search);if(null!==n&&!(nr(r=n)&&r.length>=Mn&&r.length<=On))throw Kt("search",Mn,On,n.length,"Search query");var r;const i=IS(e.tokenName);if(null!==i&&!(nr(s=i)&&s.length>=wn.MIN_LENGTH&&s.length<=wn.MAX_LENGTH))throw Kt("tokenName",wn.MIN_LENGTH,wn.MAX_LENGTH,i.length,"Token name");var s}validateUpdateProfileData(e){if(!TS(e.address))throw Ut("address","eth|[40-hex-chars] or client|[identifier]","Address");if(t=e.fullName,!(nr(t)&&t.length>=Un.FULL_NAME.MIN_LENGTH&&t.length<=Un.FULL_NAME.MAX_LENGTH&&Un.FULL_NAME.ALPHABETS_ONLY_PATTERN.test(t)))throw Kt("fullName",Un.FULL_NAME.MIN_LENGTH,Un.FULL_NAME.MAX_LENGTH,e.fullName.length,"Full name");var t}validateUploadProfileImageOptions(e){if(void 0!==e.address&&!TS(e.address))throw Ut("address","eth|[40-hex-chars] or client|[identifier]","Address")}}class US{constructor(e,t,n=!1){this.http=e,this.poolService=new ES(e,t,n),this.tradeService=new SS(e,n),this.userService=new OS(e,t,n),this.imageService=new lS(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 io(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 LS extends WE{constructor(e,t,n,r=!1,i){super(e,t,n,r,i)}validateContent(e,t){if(!nr(e))throw Ot("content","Message content");if(0===e.trim().length)throw Ot("content","Message content");Vn(e,t===dS.CHAT_MESSAGE?In.CHAT_MESSAGES_V1.MAX_LENGTH:In.COMMENTS_V1.MAX_LENGTH,"content")}validateMessageId(e){if(!nr(e))throw Ot("id","Message ID");if(e.length<10||e.length>64)throw Ut("id","valid message ID format","Message ID")}validateMessageType(e){if(e!==dS.CHAT_MESSAGE&&e!==dS.COMMENT)throw new Ct(`type must be one of: ${Object.values(dS).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,vn);const r={};void 0!==e.cursor&&(r.cursor=e.cursor),r.pageSize=e.pageSize??DE.DEFAULT_LIMIT;const i=KE(r,kn.MAX_LIMIT),s={};void 0!==i.pageSize&&(s.pageSize=i.pageSize),void 0!==i.cursor&&(s.cursor=i.cursor),t&&(s.type=e.type.toUpperCase()),n&&(s.tokenName=on(e.tokenName)),void 0!==e.userAddress&&""!==e.userAddress&&(s.userAddress=e.userAddress),void 0!==e.search&&""!==e.search&&(s.search=e.search);const o=await this.http.get(Xe.GET_MESSAGES,s),a=this.extractData(o);return{messages:a.messages,pageInfo:a.pageInfo}}async createMessage(e){this.validateMessageType(e.type),this.validateTokenName(e.tokenName,vn),this.validateContent(e.content,e.type);const t={type:e.type,tokenName:on(e.tokenName),content:e.content.trim()},n=await this.http.post(Xe.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(Xe.UPDATE_MESSAGE,e),r={content:t.content.trim()},i=await this.http.put(n,r,this.getJwtHeaders());return{message:this.extractData(i)}}async deleteMessage(e){this.validateMessageId(e);const t=this.buildEndpointWithId(Xe.DELETE_MESSAGE,e);return await this.http.delete(t,void 0,this.getDualAuthHeaders()),{success:!0}}async getPinnedMessage(e){this.validateTokenName(e,vn);const t=await this.http.get(Xe.GET_PINNED,{tokenName:on(e)});return{message:this.extractData(t)}}async pinMessage(e){this.validateMessageId(e);const t=Xe.PIN_MESSAGE.replace(":id",e);return await this.http.post(t,{},this.getDualAuthHeaders()),{success:!0}}async unpinMessage(e){this.validateMessageId(e);const t=Xe.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(Xe.GET_MESSAGE_STATS,void 0,this.getDualAuthHeaders());return this.extractData(e)}}const PS={MODERATOR:"MODERATOR",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MANAGER:"MANAGER"},FS=ar(PS),$S={TOKEN:"TOKEN",ALL_OWNER_TOKENS:"ALL_OWNER_TOKENS"},KS=ar($S),GS={PENDING:"PENDING",CLAIMED:"CLAIMED",REVOKED:"REVOKED",EXPIRED:"EXPIRED"},HS=ar(GS);function WS(e){return FS.includes(e)}function qS(e){return HS.includes(e)}function jS(e){return Rn.PATTERN.test(e)}const VS=gr([{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=gr([{field:"tokenName",type:"string"},{field:"tokenSymbol",type:"string"},{field:"role",type:"string"},{field:"inviteScope",type:"string"},{field:"creatorAddress",type:"string"},{field:"claimedAt",type:"string"}]),XS=gr([{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 KS.includes(e)}function YS(e){const t=[],n=e.inviteScope??$S.TOKEN;return void 0===e.inviteScope||JS(e.inviteScope)||St(t,()=>{throw jt("inviteScope",e.inviteScope,KS,"Invite scope")}),n===$S.TOKEN?St(t,()=>{lr(e.tokenName??"","tokenName",bn)}):n===$S.ALL_OWNER_TOKENS&&void 0!==e.tokenName&&""!==e.tokenName&&t.push("Token name should not be provided for ALL_OWNER_TOKENS scope invites"),WS(e.role)||St(t,()=>{throw jt("role",e.role,FS,"Role")}),void 0!==e.description&&""!==e.description&&St(t,()=>{Vn(e.description,In.DESCRIPTION.MAX_LENGTH,"description")}),void 0===e.expiresAt||""===e.expiresAt||pn(e.expiresAt)||St(t,()=>{throw function(e,t="a valid date",n){const r=Dt(e,n);return new Ct(`${r} must be ${t}`,e,"INVALID_DATE")}("expiresAt","ISO 8601 format")}),t}function QS(e){const t=[];return nr(e)?jS(e)||t.push("Invalid invite code format"):t.push(Ot("inviteCode","Invite code").message),t}function ZS(e){const t=[];return St(t,()=>{lr(e.tokenName??"","tokenName",bn)}),void 0===e.status||qS(e.status)||St(t,()=>{throw jt("status",e.status,HS,"Status")}),St(t,()=>{sr(0,void 0,En,e.pageSize)}),t}class eT extends WE{constructor(e,t,n,r=!1,i){super(e,t,n,r,i)}validateRole(e){if(!nr(e))throw Ot("role","Role");if(!WS(e))throw Ut("role",`one of: ${FS.join(", ")}`,"Role")}validateInviteCodeFormat(e){if(!nr(e))throw Ot("inviteCode","Invite code");if(!jS(e))throw Ut("inviteCode","valid invite code format","Invite code")}validateInviteScope(e){if(void 0!==e&&!JS(e))throw new Ct(`Invalid invite scope. Must be one of: ${KS.join(", ")}`,"inviteScope","INVALID_VALUE")}async createInvite(e){this.validateInviteScope(e.inviteScope);const t=e.inviteScope??$S.TOKEN;if(t===$S.TOKEN){if(void 0===e.tokenName||""===e.tokenName)throw new Ct("Token name is required for TOKEN scope invites","tokenName","REQUIRED");this.validateTokenName(e.tokenName,bn)}else if(t===$S.ALL_OWNER_TOKENS&&e.tokenName)throw new Ct("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",In.DESCRIPTION.MAX_LENGTH),this.validateOptionalDate(e.expiresAt,"expiresAt","Expiration date");const n=de,r={inviteScope:t,role:e.role};t===$S.TOKEN&&null!==e.tokenName&&void 0!==e.tokenName&&""!==e.tokenName&&(r.tokenName=on(e.tokenName)),void 0!==e.description&&(r.description=e.description),void 0!==e.expiresAt&&(r.expiresAt=e.expiresAt);const i=await this.http.post(n,r,this.getMultiAuthHeaders());return{invite:this.extractData(i)}}async listInvites(e){void 0!==e.tokenName&&""!==e.tokenName&&this.validateTokenName(e.tokenName,bn),this.validateStatusFilter(e.status,GS);const t=fe,n={...this.buildPaginationParams(e,kn.MAX_LIMIT)};void 0!==e.tokenName&&""!==e.tokenName&&(n.tokenName=on(e.tokenName)),void 0!==e.status&&(n.status=e.status);const r=await this.http.get(t,n,this.getMultiAuthHeaders()),i=this.extractData(r);return{items:i.invites,pageInfo:i.pageInfo}}async revokeInvite(e){this.validatePositiveInteger(e,"inviteId","Invite ID");const t=this.buildEndpoint(me,{id:String(e)});Yt(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(pe,{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 Ct("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",In.DESCRIPTION.MAX_LENGTH);const t=this.buildEndpoint(ye,{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=he,n={inviteCode:e.inviteCode},r=await this.http.post(t,n,this.getMultiAuthHeaders()),i=this.extractData(r);return"tokenName"in i&&void 0!==i.tokenName?{token:i}:{blanketAccess:i}}async getModeratedTokens(e){const t=ge,n=this.buildPaginationParams(e??{},kn.MAX_LIMIT),r=await this.http.get(t,n,this.getMultiAuthHeaders()),i=this.extractData(r);return{items:i.tokens,pageInfo:i.pageInfo}}async getInviteByCode(e){this.validateInviteCodeFormat(e);const t=this.buildEndpoint(be,{code:e}),n=await this.http.get(t,{});return this.extractData(n)}}const tT={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 nT(e){return parseFloat(tT[e])}function rT(e){return`${e}-${Date.now()}-${Math.random().toString(36).substring(2,11)}`}function iT(){return Date.now()+6e4}function sT(e){return""!==e&&"string"==typeof e&&/^[a-zA-Z0-9]{3,50}$/.test(e)}function oT(e){try{return Math.floor(parseFloat(String(e))??0).toString()}catch{return"0"}}function aT(e){return""!==e&&"string"==typeof e&&/^eth\|[0-9a-fA-F]{40}$/.test(e)}class cT extends Er{constructor(e){super(e)}getCollectionClaimFee(){return tT.COLLECTION_CLAIM_FEE}getTokenClassCreateFee(){return tT.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(!aT(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=tT.COLLECTION_CLAIM_FEE;n.collectionClaim=e,t=String(BigInt(t)+BigInt(e))}if((e.createTokenClasses??0)>0){const r=tT.TOKEN_CLASS_CREATE_FEE,i=String(BigInt(r)*BigInt(e.createTokenClasses));n.tokenClassCreate=r,n.tokenClassCount=e.createTokenClasses,t=String(BigInt(t)+BigInt(i))}return{totalFee:t,breakdown:n}}async claimCollection(e){try{if(this.logger.debug("Claiming NFT collection",e.collectionName),!sT(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:iT(),uniqueKey:rT("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),!aT(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),!sT(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(!sT(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?oT(e.maxSupply):void 0,maxCapacity:void 0!==e.maxCapacity?oT(e.maxCapacity):void 0,additionalKey:e.additionalKey,expiresAt:iT(),uniqueKey:rT("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),!sT(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(!aT(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:iT(),uniqueKey:rT("mint")};this.logger.debug("Built mint DTO",r);const i=`mint-${Date.now()}`,s=Array.from({length:t},(e,t)=>t+1);return{transactionId:i,mintedQuantity:e.quantity,owner:e.ownerAddress,tokenInstances:s,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}),!aT(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 lT extends Er{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(lt,{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:ut,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(dt,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(ht,e,t),r=this.extractData(n);return this.logger.debug("Updated notification preferences",{tradesEnabled:r.tradesEnabled,streamsEnabled:r.streamsEnabled}),{preferences:r}}}class uT extends Er{constructor(e,t=!1){super(e,t)}async getHomeOEmbedJson(e={}){this.logger.debug("Fetching home oEmbed (JSON)");const t=await this.http.get(C.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(C.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 Ct("tokenName is required","tokenName","REQUIRED_FIELD");this.logger.debug("Fetching pool oEmbed (JSON)",{tokenName:t});const n=C.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 Ct("tokenName is required","tokenName","REQUIRED_FIELD");this.logger.debug("Fetching pool oEmbed (HTML)",{tokenName:t});const n=C.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 Ct("address is required","address","REQUIRED_FIELD");this.logger.debug("Fetching profile oEmbed (JSON)",{address:t});const n=C.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 Ct("address is required","address","REQUIRED_FIELD");this.logger.debug("Fetching profile oEmbed (HTML)",{address:t});const n=C.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 dT(e){if(!nr(e))throw Ot("address","Address")}const hT={PENDING:"PENDING",CLAIMED:"CLAIMED",REVOKED:"REVOKED",EXPIRED:"EXPIRED"},gT={ACTIVE:"ACTIVE",REVOKED:"REVOKED"},fT=or(hT),mT=or(gT);function pT(e){if(e.status!==hT.PENDING)return!1;if(null!==e.expiresAt&&void 0!==e.expiresAt){if(mn(e.expiresAt)<=new Date)return!1}return!0}function yT(e){try{yr(e.description,"description",255)}catch(e){if(e instanceof Ct){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(!nr(e.expiresAt))throw new Error("expiresAt must be a non-empty string");try{br(e.expiresAt,"expiresAt")}catch(e){if(e instanceof Ct)throw new Error("expiresAt must be a valid ISO 8601 date string");throw e}if(pn(e.expiresAt)){if(mn(e.expiresAt)<=new Date)throw new Error("expiresAt must be in the future")}}}function bT(e){if(void 0!==e.status&&!fT(e.status))throw jt("status",e.status,Object.values(hT),"status");sr(0,void 0,50,e.pageSize,e.cursor)}function vT(e){if(void 0!==e.status&&!mT(e.status))throw jt("status",e.status,Object.values(gT),"status");sr(0,void 0,50,e.pageSize,e.cursor)}function wT(e){if(!nr(e))throw new Error("Invite code must be a non-empty string");Vn(e,100,"code")}function ET(e){if(!nr(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 AT(e){try{zn(e,"id")}catch(e){if(e instanceof Ct)throw new Error("Invite ID must be a positive integer");throw e}}function kT(e){if(null==e||"object"!=typeof e)throw new Ct("Options are required");if(void 0!==e.search){if("string"!=typeof e.search)throw new Ct("Search must be a string");if(0===e.search.length)throw new Ct("Search query cannot be empty string")}if(void 0!==e.sortBy){if("string"!=typeof e.sortBy)throw new Ct("Sort field must be a string");if(0===e.sortBy.length)throw new Ct("Sort field cannot be empty string")}if(void 0!==e.sortOrder&&"asc"!==e.sortOrder&&"desc"!==e.sortOrder)throw new Ct('Sort order must be "asc" or "desc"')}function ST(e){if(null==e||"object"!=typeof e)throw new Ct("Options are required");if(!nr(e.userAddress))throw new Ct("userAddress is required and must be a non-empty string");try{Mr(e.userAddress,"userAddress")}catch{throw new Ct("Invalid wallet address format. Must be eth|..., 0x..., or client|... format")}if(void 0!==e.description){if("string"!=typeof e.description)throw new Ct("description must be a string");if(e.description.length>255)throw new Ct("description must be at most 255 characters")}}class TT extends WE{constructor(e,t,n,r=!1,i){super(e,t,n,r,i)}validateInviteCodeFormat(e){if(!nr(e))throw Ot("inviteCode","Invite code");wT(e)}validateWalletAddressFormat(e){if(!nr(e))throw Ot("address","Address");ET(e)}async createInvite(e={}){yT(e),this.validateOptionalString(e.description,"description","Description",In.DESCRIPTION.MAX_LENGTH),this.validateOptionalDate(e.expiresAt,"expiresAt","Expiration date");const t=we,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={}){bT(e),this.validateStatusFilter(e.status,hT);const t=Ee,n={...this.buildPaginationParams(e,kn.MAX_LIMIT)};void 0!==e.status&&(n.status=e.status);const r=await this.http.get(t,n,this.getDualAuthHeaders()),i=this.extractData(r);return{items:i.invites,pageInfo:i.pageInfo}}async getInviteByCode(e){this.validateInviteCodeFormat(e);const t=this.buildEndpoint(Ae,{code:e}),n=await this.http.get(t,{});return this.extractData(n)}async revokeInvite(e){AT(e);const t=this.buildEndpoint(Se,{id:String(e)});Yt(await this.http.delete(t,this.getDualAuthHeaders()),"Failed to revoke invite")}async claimInvite(e){this.validateInviteCodeFormat(e);const t=ke,n={inviteCode:e},r=await this.http.post(t,n,this.getJwtHeaders());return{invite:this.extractData(r)}}async listOverseers(e={}){vT(e),this.validateStatusFilter(e.status,gT);const t=Te,n={...this.buildPaginationParams(e,kn.MAX_LIMIT)};void 0!==e.status&&(n.status=e.status);const r=await this.http.get(t,n,this.getDualAuthHeaders()),i=this.extractData(r);return{items:i.overseers,pageInfo:i.pageInfo}}async createOverseerDirect(e){ST(e),this.validateWalletAddressFormat(e.userAddress),this.validateOptionalString(e.description,"description","Description",In.DESCRIPTION.MAX_LENGTH);const t=Ie,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(Ne,{address:e});Yt(await this.http.delete(t,this.getDualAuthHeaders()),"Failed to revoke overseer")}async getMyStatus(){const e=Ce,t=await this.http.get(e,{},this.getJwtHeaders());return this.extractData(t)}async getSummary(){const e=_e,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getBanStats(){const e=xe,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getTokenBanStats(){const e=Re,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getInviteStats(){const e=Be,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getFlagStats(){const e=De,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getUserStats(){const e=Me,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async listOverseerUsers(e){const t=e??{};Object.keys(t).length>0&&kT(t);const n=Oe,r=this.buildPaginationParams(t,kn.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 i=await this.http.get(n,r,this.getDualAuthHeaders()),s=this.extractData(i);return{items:s.users,pageInfo:s.pageInfo}}async getOverseerUserSummary(e){if(!nr(e))throw Ot("address","User address");ET(e);const t=this.buildEndpoint(Ue,{address:e}),n=await this.http.get(t,{},this.getDualAuthHeaders());return this.extractData(n)}async flushCacheByAddress(e){dT(e);const t=this.buildEndpoint(Le,{address:e}),n=await this.http.delete(t,void 0,this.getDualAuthHeaders());return this.extractData(n)}async flushCacheByToken(e){!function(e){if(!nr(e))throw Ot("tokenName","Token name")}(e);const t=this.buildEndpoint(Pe,{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 Ct("Safety confirmation required: must pass confirm=true to flush all cache","confirm","CONFIRMATION_REQUIRED")}(e);const t=Fe,n=await this.http.delete(t,{confirm:"true"},this.getDualAuthHeaders());return this.extractData(n)}async flushWalletAliasCache(e){if(void 0!==e){dT(e);const t=this.buildEndpoint($e,{address:e}),n=await this.http.delete(t,void 0,this.getDualAuthHeaders());return this.extractData(n)}const t=Ke,n=await this.http.delete(t,{confirm:"true"},this.getDualAuthHeaders());return this.extractData(n)}}function IT(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 NT extends Er{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),Yt(t,"Platform config operation failed",!0),e.data}async getPlatformConfig(){const e=await this.http.get(W);return this.extractData(e)}async updatePlatformConfig(e){const t=IT(e);if(t.length>0)throw new Ct(t.join("; "),"options","VALIDATION_FAILED");const n=await this.http.put(q,e,this.getJwtHeaders());return this.extractData(n)}async getAvailableRoles(){const e=await this.http.get(z);return this.extractData(e)}}class CT extends Er{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(rt),t=this.extractData(e);return this.logger.debug("Fetched platform stats",{totalTokens:t.totalTokens,timestamp:t.timestamp}),{stats:t}}}class _T extends Er{constructor(e,t=!1,n){super(e,t),this.tokenResolverService=n}async fetchTokenClassKeyByTokenName(e){if(""===e)throw Ot("tokenName","Token name");if(!this.tokenResolverService)throw Pt("TokenResolverService is required for token name resolution. Ensure it is passed to PriceHistoryService constructor.","tokenResolverService");try{lr(e)}catch(e){throw Pt(bt(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 Pt(`Token '${e}' not found or could not be resolved to vault address`,"tokenName");this.logger.debug(`Resolved '${e}' to vault address: ${t}`);const n=No(vA(t));return this.logger.debug(`Extracted token class key: ${n}`),n}catch(t){if(yt(t)&&bt(t).includes("ConfigurationError"))throw t;throw Lt(`Failed to resolve token name '${e}': ${bt(t)}`,500)}}async fetchPriceHistory(e){if(null==e)throw Ot("options","Fetch options");return this.logger.debug("Fetching price history from DEX Backend API with options:",e),this.validateOptions(e),await vo(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 Pt("Token ID is required but was not provided or resolved","tokenId");const{normalizeToTokenInstanceKey:n}=await Promise.resolve().then(function(){return kA}),r=GA(No(n(t))),{from:i,to:s,sortOrder:o="DESC"}=e,a=e.timeframe??this.inferTimeframe(i,s),c={token:r,timeframe:a};this.logger.debug(`Querying price series for token ${r}, timeframe ${a}`);const l=await this.http.get(B,c);if(null==l)throw Lt("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 Lt("Invalid API response: missing price series",500);const r="string"==typeof t.tokenId?t.tokenId:t.tokenName??No(t.tokenId),i=t.from?.getTime(),s=t.to?.getTime(),o=e.prices.filter(e=>"number"==typeof e.time&&"number"==typeof e.price).filter(e=>(void 0===i||1e3*e.time>=i)&&(void 0===s||1e3*e.time<=s)).sort((e,t)=>"ASC"===n?e.time-t.time:t.time-e.time),a=Fn(t.offset,0),c=Fn(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 Ot("options","Fetch options");return this.logger.debug("Fetching all price history with options:",e),vo(async()=>{const t=await yA((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?PE(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(cr(e,"tokenName","tokenId",{description:"token identifier"}),t&&!pn(t))throw Pt("from must be a valid Date","from");if(void 0!==n&&!pn(n))throw Pt("to must be a valid Date","to");null!=r&&Jn(r,"sortOrder"),sr(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 xT extends WE{constructor(e,t,n,r){super(e,t,n,!1,r)}async getRestrictedNames(){try{return{success:!0,data:(await this.http.get(Je)).data}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}async updateRestrictedNames(e){try{if(!nr(e.content))throw new Ct("Content is required");return{success:!0,data:(await this.http.put(Ye,e)).data}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}}class RT extends WE{constructor(e,t,n,r=!1,i){super(e,t,n,r,i)}async getChatStatus(e){if(null==e||""===e)throw Ot("tokenName","Token name");return this.validateTokenName(e,bn),vo(async()=>{const t=this.buildEndpoint(Qe,{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 Ot("tokenName","Token name");return this.validateTokenName(e,bn),vo(async()=>{const t=this.buildEndpoint(et,{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 Ot("tokenName","Token name");return this.validateTokenName(e,bn),vo(async()=>{const t=this.buildEndpoint(Ze,{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??on(e)};return void 0!==t.status&&null!==t.status&&(n.status=t.status),n}async setSlowMode(e,t){if(null==e||""===e)throw Ot("tokenName","Token name");if(this.validateTokenName(e,bn),"number"!=typeof t||t<0||t>600)throw new Error("slowModeSeconds must be a number between 0 and 600");return vo(async()=>{const n=this.buildEndpoint(tt,{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 BT extends Ar{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 DT={IDLE:"IDLE",ACTIVE:"ACTIVE",DISABLED:"DISABLED"},MT={READY:"READY",PROCESSING:"PROCESSING",ERRORED:"ERRORED",DELETED:"DELETED"},OT={ACTIVE:"ACTIVE",IDLE:"IDLE",ERRORED:"ERRORED",DISABLED:"DISABLED"},UT={YOUTUBE:"YOUTUBE",TWITCH:"TWITCH",FACEBOOK:"FACEBOOK",CUSTOM:"CUSTOM"},LT=or(DT),PT=or(MT),FT=or(UT);function $T(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&<(t.status)&&(null===t.playbackId||"string"==typeof t.playbackId)&&"boolean"==typeof t.isLive}function KT(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"number"==typeof t.viewerCount}const GT={OWNER:"OWNER",MANAGER:"MANAGER",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MODERATOR:"MODERATOR"},HT={OWNER:"OWNER",MODERATOR:"MODERATOR"};or(GT),or(HT);const WT={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"},qT={...GT,OVERSEER:"OVERSEER"},jT=or(qT);function VT(e){if(null==e||"object"!=typeof e)return!1;const t=e,n=t.permissions;return Array.isArray(n)&&n.every(e=>"string"==typeof e)&&(null===t.source||"owner"===t.source||"moderator_invite"===t.source||"api_key"===t.source||"overseer"===t.source)&&(void 0===t.matchedPreset||null===t.matchedPreset||"MODERATOR"===t.matchedPreset||"TECHNICAL_PRODUCER"===t.matchedPreset||"MANAGER"===t.matchedPreset)&&"boolean"==typeof t.isOwner&&"boolean"==typeof t.isOverseer}function zT(e,t="tokenName"){lr(e,t,bn)}function XT(e){if(zT(e.tokenName),!nr(e.language))throw Ot("language");if(t=e.language,!nr(t)||!/^[a-z]{2}(-[A-Z]{2})?$/.test(t))throw new Ct('language must be a valid ISO 639-1 code (e.g., "en", "es", "zh-CN")',"language",Nt.INVALID_FORMAT);var t}const JT={STREAM_STARTED:"stream.started",STREAM_STOPPED:"stream.stopped",RECORDING_READY:"recording.ready",SIMULCAST_ERROR:"simulcast.error"};class YT extends WE{constructor(e,t,n,r=!1,i){super(e,t,n,r,i)}async startStream(e){this.validateTokenName(e,bn);const t=this.buildEndpoint(D,{tokenName:e}),n=await this.http.post(t,{},this.getJwtHeaders());return this.extractData(n)}async stopStream(e){this.validateTokenName(e,bn);const t=this.buildEndpoint(M,{tokenName:e});await this.http.post(t,{},this.getJwtHeaders())}async disableStream(e){return this.toggleFeature(e,O,bn)}async enableStream(e){return this.toggleFeature(e,U,bn)}async resetStreamKey(e){this.validateTokenName(e,bn);const t=this.buildEndpoint(L,{tokenName:e}),n=await this.http.post(t,{},this.getJwtHeaders());return this.extractData(n)}async getStreamCredentials(e){this.validateTokenName(e,bn);const t=this.buildEndpoint(J,{tokenName:e}),n=await this.http.get(t,{},this.getJwtHeaders());return this.extractData(n)}async getRecordings(e){!function(e){zT(e.tokenName),sr(0,void 0,Dn,e.pageSize)}(e);const t=this.buildEndpoint(P,{tokenName:e.tokenName}),n=this.buildPaginationParams(e,Dn),r=e.offset;"number"==typeof r&&(n.offset=String(r));const i=await this.http.get(t,n),s=this.extractData(i),o=e,a=s.pageSize??s.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:s.recordings,tokenName:on(e.tokenName),page:s.page??l,limit:a,total:s.total,hasNext:s.recordings.length===a}}async getRecordingDownload(e,t){this.validateTokenName(e,bn),this.validateRequiredString(t,"assetId","Asset ID");const n=this.buildEndpoint(F,{tokenName:e,assetId:t}),r=await this.http.get(n,{},this.getJwtHeaders());return this.extractData(r)}async deleteRecording(e,t){this.validateTokenName(e,bn),this.validateRequiredString(t,"assetId","Asset ID");const n=this.buildEndpoint($,{tokenName:e,assetId:t});await this.http.delete(n,void 0,this.getJwtHeaders())}async getSimulcastTargets(e){this.validateTokenName(e,bn);const t=this.buildEndpoint(K,{tokenName:e}),n=await this.http.get(t);return this.extractData(n)}async addSimulcastTarget(e){!function(e){if(zT(e.tokenName),!nr(e.platform))throw Ot("platform");if(!FT(e.platform))throw new Ct("platform must be one of: 'YOUTUBE', 'TWITCH', 'FACEBOOK', 'CUSTOM'","platform",Nt.INVALID_VALUE);if(!nr(e.rtmpUrl))throw Ot("rtmpUrl");if(!Bn.STREAM_URL_PATTERN.test(e.rtmpUrl))throw new Ct("rtmpUrl must be a valid RTMP, RTMPS, or SRT URL","rtmpUrl",Nt.INVALID_FORMAT);if(!nr(e.streamKey))throw Ot("streamKey");if(void 0!==e.name&&"string"!=typeof e.name)throw new Ct("name must be a string","name",Nt.INVALID_TYPE)}(e);const t=this.buildEndpoint(G,{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,bn),this.validateRequiredString(t,"targetId","Target ID");const n=this.buildEndpoint(H,{tokenName:e,targetId:t});await this.http.delete(n,void 0,this.getJwtHeaders())}async getGlobalStreamingStatus(){const e=await this.http.get(W);return this.extractData(e)}async disableGlobalStreaming(){const e=await this.http.put(q,{},this.getAdminHeaders());return this.extractData(e)}async enableGlobalStreaming(){const e=await this.http.put(j,{},this.getAdminHeaders());return this.extractData(e)}async setNextLiveStream(e){let t;!function(e){if(zT(e.tokenName),null!==e.nextLiveStreamAt){if(!(e.nextLiveStreamAt instanceof Date||nr(e.nextLiveStreamAt)))throw new Ct("nextLiveStreamAt must be a Date, ISO 8601 string, or null","nextLiveStreamAt",Nt.INVALID_TYPE);if("string"==typeof e.nextLiveStreamAt){const t=Date.parse(e.nextLiveStreamAt);if(isNaN(t))throw new Ct("nextLiveStreamAt must be a valid ISO 8601 date string","nextLiveStreamAt",Nt.INVALID_FORMAT)}}}(e),t=null===e.nextLiveStreamAt?null:e.nextLiveStreamAt instanceof Date?e.nextLiveStreamAt.toISOString():e.nextLiveStreamAt;const n=`/v1/tokens/${e.tokenName.toLowerCase().trim()}`;await this.http.patch(n,{nextLiveStreamAt:t},this.getJwtHeaders())}async clearNextLiveStream(e){this.validateTokenName(e,bn);const t=`/v1/tokens/${e.toLowerCase().trim()}`;await this.http.patch(t,{nextLiveStreamAt:null},this.getJwtHeaders())}async setStreamLanguage(e){XT(e);const t=`/v1/tokens/${e.tokenName.toLowerCase().trim()}`;await this.http.patch(t,{streamLanguage:e.language},this.getJwtHeaders())}async getStreamRole(e){!function(e){zT(e.tokenName)}(e);const t=this.buildEndpoint(V,{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(z);return this.extractData(e)}async getTokenAccess(e){!function(e){zT(e.tokenName)}(e);const t=await this.http.get(X,{tokenName:on(e.tokenName)},this.getJwtHeaders());return this.extractData(t)}async setNextLiveStreamCountdown(e,t){return this.setNextLiveStream({tokenName:e,nextLiveStreamAt:t})}}const QT={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 ZT extends Ar{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 Rt("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 sS({maxAttempts:this.config.reconnectAttempts,baseDelayMs:this.config.reconnectDelay}),this.isSocketIOAvailable=this.checkSocketIOAvailability()}checkSocketIOAvailability(){try{return"function"==typeof k||(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:",bt(e)),!1}}getRoomName(e){return`token:${on(e)}`}bufferEvent(e,t,n){const r=`${e}:${t}`;let i=this.eventBuffer.get(r);i||(i=[],this.eventBuffer.set(r,i)),i.length>=this.MAX_BUFFER_SIZE&&(i.shift(),this.logger.warn(`⚠️ [Stream Buffer] Event buffer overflow for ${r} - dropping oldest event. Consider processing events faster or increasing buffer size.`)),i.push(n);const s=this.eventBufferTimeouts.get(r);s&&clearTimeout(s);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=on(e),r=[{key:`${QT.STREAM_STATUS}:${n}`,callback:t.onStreamStatus},{key:`${QT.VIEWER_COUNT}:${n}`,callback:t.onViewerCount},{key:`${QT.CHAT_MESSAGE}:${n}`,callback:t.onChatMessage},{key:`${QT.CHAT_STATUS}:${n}`,callback:t.onChatStatus},{key:`${QT.CHAT_PINNED}:${n}`,callback:t.onChatPinned},{key:`${QT.CHAT_UNPINNED}:${n}`,callback:t.onChatUnpinned},{key:`${QT.STREAM_COUNTDOWN_UPDATED}:${n}`,callback:t.onCountdownUpdated},{key:`${QT.STREAM_LANGUAGE_UPDATED}:${n}`,callback:t.onLanguageUpdated},{key:`${QT.TOKEN_BANNED}:${n}`,callback:t.onTokenBanned},{key:`${QT.TOKEN_UNBANNED}:${n}`,callback:t.onTokenUnbanned},{key:`${QT.MODERATOR_INVITE_CREATED}:${n}`,callback:t.onModeratorInviteCreated},{key:`${QT.MODERATOR_ADDED}:${n}`,callback:t.onModeratorAdded},{key:`${QT.MODERATOR_REMOVED}:${n}`,callback:t.onModeratorRemoved},{key:`${QT.MODERATOR_ROLE_UPDATED}:${n}`,callback:t.onModeratorRoleUpdated},{key:`${QT.TRADE_EXECUTED}:${n}`,callback:t.onTradeExecuted},{key:`${QT.BALANCE_UPDATED}:${n}`,callback:t.onBalanceUpdated},{key:`${QT.POOL_METADATA_UPDATED}:${n}`,callback:t.onPoolMetadataUpdated},{key:`${QT.POOL_SOCIAL_LINKS_UPDATED}:${n}`,callback:t.onPoolSocialLinksUpdated},{key:`${QT.POOL_BADGE_ASSIGNED}:${n}`,callback:t.onPoolBadgeAssigned},{key:`${QT.HOLDER_COUNT_UPDATED}:${n}`,callback:t.onHolderCountUpdated},{key:`${QT.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(QT.STREAM_STATUS,e=>{this.logger.debug(`📡 [Stream Status] ${e.tokenName}: ${e.status}`),this.bufferEvent(QT.STREAM_STATUS,e.tokenName,e);const t=this.roomCallbacks.get(on(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(QT.STREAM_SUBSCRIBED,e=>{this.logger.debug(`📡 [Subscribed] ${e.tokenName}`);const t=on(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(QT.STREAM_UNSUBSCRIBED,e=>{const t=e.room.replace("token:","");this.logger.debug(`📡 [Unsubscribed] ${t}`);const n=this.roomCallbacks.get(on(t));n?.onStreamUnsubscribed&&n.onStreamUnsubscribed(e)}),this.socket.on(QT.VIEWER_COUNT,e=>{this.logger.debug(`📡 [Viewer Count] ${e.tokenName}: ${e.viewerCount}`),this.bufferEvent(QT.VIEWER_COUNT,e.tokenName,e);const t=this.roomCallbacks.get(on(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(QT.STREAM_GLOBAL_STATUS,e=>{this.logger.debug(`📡 [Global Stream Status] enabled: ${String(e.enabled)}`),this.globalCallbacks.onStreamGlobalStatus&&this.globalCallbacks.onStreamGlobalStatus(e)}),this.socket.on(QT.CHAT_MESSAGE,e=>{this.logger.debug(`📡 [Chat Message] ${e.tokenName}: ${e.content.slice(0,50)}...`),this.bufferEvent(QT.CHAT_MESSAGE,e.tokenName,e);const t=this.roomCallbacks.get(on(e.tokenName));t?.onChatMessage&&t.onChatMessage(e),this.globalCallbacks.onChatMessage&&this.globalCallbacks.onChatMessage(e)}),this.socket.on(QT.CHAT_SENT,e=>{this.logger.debug(`📡 [Chat Sent] ${e.tokenName}: ${e.messageId}`);const t=this.roomCallbacks.get(on(e.tokenName));t?.onChatSent&&t.onChatSent(e)}),this.socket.on(QT.CHAT_ERROR,e=>{this.logger.error(`📡 [Chat Error] ${e.tokenName}: ${e.message}`);const t=this.roomCallbacks.get(on(e.tokenName));t?.onChatError&&t.onChatError(e),this.globalCallbacks.onChatError&&this.globalCallbacks.onChatError(e)}),this.socket.on(QT.CHAT_STATUS,e=>{this.logger.debug(`📡 [Chat Status] ${e.tokenName}: ${String(e.enabled)}`),this.bufferEvent(QT.CHAT_STATUS,e.tokenName,e);const t=this.roomCallbacks.get(on(e.tokenName));t?.onChatStatus&&t.onChatStatus(e),this.globalCallbacks.onChatStatus&&this.globalCallbacks.onChatStatus(e)}),this.socket.on(QT.CHAT_GLOBAL_STATUS,e=>{this.logger.debug(`📡 [Global Chat Status] enabled: ${String(e.enabled)}`),this.globalCallbacks.onChatGlobalStatus&&this.globalCallbacks.onChatGlobalStatus(e)}),this.socket.on(QT.CHAT_AUTHENTICATED,e=>{this.logger.debug(`📡 [Authenticated] ${e.address}`),this.isAuthenticated=!0,this.globalCallbacks.onChatAuthenticated&&this.globalCallbacks.onChatAuthenticated(e)}),this.socket.on(QT.CHAT_AUTH_ERROR,e=>{this.logger.error(`📡 [Auth Error] ${e.message}`),this.isAuthenticated=!1,this.globalCallbacks.onChatAuthError&&this.globalCallbacks.onChatAuthError(e)}),this.socket.on(QT.REACTION,e=>{this.logger.debug(`📡 [Reaction] ${e.tokenName}: ${e.emoji}`);const t=this.roomCallbacks.get(on(e.tokenName));t?.onReaction&&t.onReaction(e),this.globalCallbacks.onReaction&&this.globalCallbacks.onReaction(e)}),this.socket.on(QT.REACTION_ERROR,e=>{this.logger.error(`📡 [Reaction Error] ${e.tokenName}: ${e.message}`);const t=this.roomCallbacks.get(on(e.tokenName));t?.onReactionError&&t.onReactionError(e),this.globalCallbacks.onReactionError&&this.globalCallbacks.onReactionError(e)}),this.socket.on(QT.USER_TYPING,e=>{const t=e.typingUsers.length;this.logger.debug(`📡 [Typing] ${e.tokenName}: ${t} user(s) typing`);const n=this.roomCallbacks.get(on(e.tokenName));n?.onTypingIndicator&&n.onTypingIndicator(e),this.globalCallbacks.onTypingIndicator&&this.globalCallbacks.onTypingIndicator(e)}),this.socket.on(QT.CHAT_PINNED,e=>{this.logger.debug(`📡 [Chat Pinned] ${e.tokenName}: ${e.pinnedMessage.messageId}`),this.bufferEvent(QT.CHAT_PINNED,e.tokenName,e);const t=this.roomCallbacks.get(on(e.tokenName));t?.onChatPinned&&t.onChatPinned(e),this.globalCallbacks.onChatPinned&&this.globalCallbacks.onChatPinned(e)}),this.socket.on(QT.CHAT_UNPINNED,e=>{this.logger.debug(`📡 [Chat Unpinned] ${e.tokenName}: ${e.unpinnedMessageId}`),this.bufferEvent(QT.CHAT_UNPINNED,e.tokenName,e);const t=this.roomCallbacks.get(on(e.tokenName));t?.onChatUnpinned&&t.onChatUnpinned(e),this.globalCallbacks.onChatUnpinned&&this.globalCallbacks.onChatUnpinned(e)}),this.socket.on(QT.STREAM_COUNTDOWN_UPDATED,e=>{const t=e.nextLiveStreamAt??"cleared";this.logger.debug(`📡 [Countdown Updated] ${e.tokenName}: ${t}`),this.bufferEvent(QT.STREAM_COUNTDOWN_UPDATED,e.tokenName,e);const n=this.roomCallbacks.get(on(e.tokenName));n?.onCountdownUpdated&&n.onCountdownUpdated(e),this.globalCallbacks.onCountdownUpdated&&this.globalCallbacks.onCountdownUpdated(e)}),this.socket.on(QT.STREAM_LANGUAGE_UPDATED,e=>{this.logger.debug(`📡 [Language Updated] ${e.tokenName}: ${e.language}`),this.bufferEvent(QT.STREAM_LANGUAGE_UPDATED,e.tokenName,e);const t=this.roomCallbacks.get(on(e.tokenName));t?.onLanguageUpdated&&t.onLanguageUpdated(e),this.globalCallbacks.onLanguageUpdated&&this.globalCallbacks.onLanguageUpdated(e)}),this.socket.on(QT.TOKEN_BANNED,e=>{this.logger.debug(`📡 [Token Banned] ${e.tokenName}`),this.bufferEvent(QT.TOKEN_BANNED,e.tokenName,e);const t=this.roomCallbacks.get(on(e.tokenName));t?.onTokenBanned&&t.onTokenBanned(e),this.globalCallbacks.onTokenBanned&&this.globalCallbacks.onTokenBanned(e)}),this.socket.on(QT.TOKEN_UNBANNED,e=>{this.logger.debug(`📡 [Token Unbanned] ${e.tokenName}`),this.bufferEvent(QT.TOKEN_UNBANNED,e.tokenName,e);const t=this.roomCallbacks.get(on(e.tokenName));t?.onTokenUnbanned&&t.onTokenUnbanned(e),this.globalCallbacks.onTokenUnbanned&&this.globalCallbacks.onTokenUnbanned(e)}),this.socket.on(QT.MODERATOR_INVITE_CREATED,e=>{this.logger.debug(`📡 [Moderator Invite Created] ${e.tokenName}: by ${e.invitedBy}`),this.bufferEvent(QT.MODERATOR_INVITE_CREATED,e.tokenName,e);const t=this.roomCallbacks.get(on(e.tokenName));t?.onModeratorInviteCreated&&t.onModeratorInviteCreated(e)}),this.socket.on(QT.MODERATOR_ADDED,e=>{this.logger.debug(`📡 [Moderator Added] ${e.tokenName}: ${e.userAddress}`),this.bufferEvent(QT.MODERATOR_ADDED,e.tokenName,e);const t=this.roomCallbacks.get(on(e.tokenName));t?.onModeratorAdded&&t.onModeratorAdded(e)}),this.socket.on(QT.MODERATOR_REMOVED,e=>{this.logger.debug(`📡 [Moderator Removed] ${e.tokenName}: ${e.userAddress}`),this.bufferEvent(QT.MODERATOR_REMOVED,e.tokenName,e);const t=this.roomCallbacks.get(on(e.tokenName));t?.onModeratorRemoved&&t.onModeratorRemoved(e)}),this.socket.on(QT.MODERATOR_ROLE_UPDATED,e=>{this.logger.debug(`📡 [Moderator Role Updated] ${e.tokenName}: ${e.userAddress}`),this.bufferEvent(QT.MODERATOR_ROLE_UPDATED,e.tokenName,e);const t=this.roomCallbacks.get(on(e.tokenName));t?.onModeratorRoleUpdated&&t.onModeratorRoleUpdated(e)}),this.socket.on(QT.OVERSEER_ADDED,e=>{this.logger.debug(`📡 [Overseer Added] ${e.userAddress}`),this.globalCallbacks.onOverseerAdded&&this.globalCallbacks.onOverseerAdded(e)}),this.socket.on(QT.OVERSEER_REMOVED,e=>{this.logger.debug(`📡 [Overseer Removed] ${e.userAddress}`),this.globalCallbacks.onOverseerRemoved&&this.globalCallbacks.onOverseerRemoved(e)}),this.socket.on(QT.TRADE_EXECUTED,e=>{this.logger.debug(`📡 [Trade Executed] ${e.tokenName}: ${e.tradeType}`),this.bufferEvent(QT.TRADE_EXECUTED,e.tokenName,e);const t=this.roomCallbacks.get(on(e.tokenName));t?.onTradeExecuted&&t.onTradeExecuted(e),this.isGlobalFeedSubscribed&&!t&&this.globalFeedCallbacks.onTradeExecuted&&this.globalFeedCallbacks.onTradeExecuted(e)}),this.socket.on(QT.BALANCE_UPDATED,e=>{this.logger.debug(`📡 [Balance Updated] ${e.tokenName}: ${e.tradeType}`),this.bufferEvent(QT.BALANCE_UPDATED,e.tokenName,e);const t=this.roomCallbacks.get(on(e.tokenName));t?.onBalanceUpdated&&t.onBalanceUpdated(e)}),this.socket.on(QT.POOL_METADATA_UPDATED,e=>{this.logger.debug(`📡 [Pool Metadata Updated] ${e.tokenName}`),this.bufferEvent(QT.POOL_METADATA_UPDATED,e.tokenName,e);const t=this.roomCallbacks.get(on(e.tokenName));t?.onPoolMetadataUpdated&&t.onPoolMetadataUpdated(e)}),this.socket.on(QT.POOL_SOCIAL_LINKS_UPDATED,e=>{this.logger.debug(`📡 [Pool Social Links Updated] ${e.tokenName}`),this.bufferEvent(QT.POOL_SOCIAL_LINKS_UPDATED,e.tokenName,e);const t=this.roomCallbacks.get(on(e.tokenName));t?.onPoolSocialLinksUpdated&&t.onPoolSocialLinksUpdated(e)}),this.socket.on(QT.POOL_BADGE_ASSIGNED,e=>{this.logger.debug(`📡 [Pool Badge Assigned] ${e.tokenName}: ${e.badge}`),this.bufferEvent(QT.POOL_BADGE_ASSIGNED,e.tokenName,e);const t=this.roomCallbacks.get(on(e.tokenName));t?.onPoolBadgeAssigned&&t.onPoolBadgeAssigned(e),this.isGlobalFeedSubscribed&&!t&&this.globalFeedCallbacks.onPoolBadgeAssigned&&this.globalFeedCallbacks.onPoolBadgeAssigned(e)}),this.socket.on(QT.HOLDER_COUNT_UPDATED,e=>{this.logger.debug(`📡 [Holder Count Updated] ${e.tokenName}: ${e.holderCount}`),this.bufferEvent(QT.HOLDER_COUNT_UPDATED,e.tokenName,e);const t=this.roomCallbacks.get(on(e.tokenName));t?.onHolderCountUpdated&&t.onHolderCountUpdated(e),this.isGlobalFeedSubscribed&&!t&&this.globalFeedCallbacks.onHolderCountUpdated&&this.globalFeedCallbacks.onHolderCountUpdated(e)}),this.socket.on(QT.COMMENT_CREATED,e=>{this.logger.debug(`📡 [Comment Created] ${e.tokenName}: ID ${e.id}`),this.bufferEvent(QT.COMMENT_CREATED,e.tokenName,e);const t=this.roomCallbacks.get(on(e.tokenName));t?.onCommentCreated&&t.onCommentCreated(e)}),this.socket.on(QT.USER_PROFILE_UPDATED,e=>{this.logger.debug(`📡 [User Profile Updated] ${e.userAddress}`),this.globalCallbacks.onUserProfileUpdated&&this.globalCallbacks.onUserProfileUpdated(e)}),this.socket.on(QT.API_KEY_CREATED,e=>{this.logger.debug(`📡 [API Key Created] ${e.keyId}`),this.globalCallbacks.onApiKeyCreated&&this.globalCallbacks.onApiKeyCreated(e)}),this.socket.on(QT.API_KEY_UPDATED,e=>{this.logger.debug(`📡 [API Key Updated] ${e.keyId}`),this.globalCallbacks.onApiKeyUpdated&&this.globalCallbacks.onApiKeyUpdated(e)}),this.socket.on(QT.API_KEY_REVOKED,e=>{this.logger.debug(`📡 [API Key Revoked] ${e.keyId}`),this.globalCallbacks.onApiKeyRevoked&&this.globalCallbacks.onApiKeyRevoked(e)}),this.socket.on(QT.TOKEN_CONFIG_UPDATED,e=>{this.logger.debug(`📡 [Token Config Updated] ${e.tokenName}`),this.bufferEvent(QT.TOKEN_CONFIG_UPDATED,e.tokenName,e);const t=this.roomCallbacks.get(on(e.tokenName));t?.onTokenConfigUpdated&&t.onTokenConfigUpdated(e),this.isGlobalFeedSubscribed&&!t&&this.globalFeedCallbacks.onTokenConfigUpdated&&this.globalFeedCallbacks.onTokenConfigUpdated(e)}),this.socket.on(QT.STATS_UPDATED,e=>{this.logger.debug(`📡 [Stats Updated] ${e.tokenName} price=${e.galaPrice}`),this.bufferEvent(QT.STATS_UPDATED,e.tokenName,e);const t=this.roomCallbacks.get(on(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(QT.ENGAGEMENT_STATS_UPDATED,e=>{this.logger.debug(`📡 [Engagement Stats Updated] ${e.tokenName} chatters=${e.chat.uniqueChatters}`),this.bufferEvent(QT.ENGAGEMENT_STATS_UPDATED,e.tokenName,e);const t=this.roomCallbacks.get(on(e.tokenName));t?.onEngagementStatsUpdated&&t.onEngagementStatsUpdated(e),this.globalCallbacks.onEngagementStatsUpdated&&this.globalCallbacks.onEngagementStatsUpdated(e)}),this.socket.on(QT.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(QT.GLOBAL_FEED_UNSUBSCRIBED,e=>{this.logger.debug("📡 [Global Feed Unsubscribed]"),this.isGlobalFeedSubscribed=!1,this.globalFeedCallbacks.onGlobalFeedUnsubscribed&&this.globalFeedCallbacks.onGlobalFeedUnsubscribed(e)}),this.socket.on(QT.SITE_CONFIG_CHANGED,e=>{this.logger.debug(`📡 [Site Config Changed] ${e.key}`),this.globalFeedCallbacks.onSiteConfigChanged&&this.globalFeedCallbacks.onSiteConfigChanged(e)}),this.socket.on(QT.STREAM_GLOBAL_STATUS,e=>{this.logger.debug(`📡 [Stream Global Status] enabled=${String(e.enabled)}`),this.globalFeedCallbacks.onStreamGlobalStatus&&this.globalFeedCallbacks.onStreamGlobalStatus(e)}),this.socket.on(QT.CHAT_GLOBAL_STATUS,e=>{this.logger.debug(`📡 [Chat Global Status] enabled=${String(e.enabled)}`),this.globalFeedCallbacks.onStreamChatGlobalStatus&&this.globalFeedCallbacks.onStreamChatGlobalStatus(e)}),this.socket.on(QT.COMMENTS_GLOBAL_STATUS,e=>{this.logger.debug(`📡 [Comments Global Status] enabled=${String(e.enabled)}`),this.globalFeedCallbacks.onCommentsGlobalStatus&&this.globalFeedCallbacks.onCommentsGlobalStatus(e)}),this.socket.on(QT.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(QT.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(QT.SUBSCRIBE_GLOBAL_FEED)}catch(e){this.logger.error("Failed to re-subscribe to global feed:",e)}}async connect(){return new Promise((e,t)=>{vo(async()=>{if(!this.isSocketIOAvailable)throw new Rt('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=k(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 Ct("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(""===e)throw Ot("token","Authentication token");this.logger.debug("📡 Authenticating with stream server"),this.socket.emit(QT.AUTHENTICATE,{token:e}),this.config.authToken=e}async subscribeToStream(e,t={}){if(""===e)throw Ot("tokenName","Token name");if(!this.socket?.connected)throw new Ct("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");const n=on(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,i)=>{const s=setTimeout(()=>{this.pendingSubscriptions.delete(n),i(new Error(`Subscription to ${e} timed out after ${this.config.subscriptionTimeout}ms`))},this.config.subscriptionTimeout);this.pendingSubscriptions.set(n,{resolve:r,reject:i,timeoutId:s}),this.roomCallbacks.set(n,t),this.subscribedRooms.set(n,{tokenName:n,subscribedAt:Date.now()}),this.logger.debug(`📡 Subscribing to stream: ${n}`),this.socket.emit(QT.SUBSCRIBE,{tokenName:n})})}unsubscribeFromStream(e){const t=on(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(QT.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 Ot("tokenName","Token name");if(""===t)throw Ot("content","Message content");if(!this.socket?.connected)throw new Ct("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(!this.isAuthenticated)throw new Ct("Not authenticated. Call authenticate() first.","auth","NOT_AUTHENTICATED");const n=on(e);this.logger.debug(`📡 Sending chat message to ${n}: ${t.slice(0,30)}...`),this.socket.emit(QT.SEND_CHAT,{tokenName:n,content:t})}sendReaction(e,t,n=0){if(""===e)throw Ot("tokenName","Token name");if(""===t)throw Ot("emoji");if(!this.socket?.connected)throw new Ct("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(!this.isAuthenticated)throw new Ct("Not authenticated. Call authenticate() first.","auth","NOT_AUTHENTICATED");const r=on(e);this.logger.debug(`📡 Sending reaction to ${r}: ${t}`),this.socket.emit(QT.SEND_REACTION,{tokenName:r,emoji:t,streamTime:n})}sendTypingStart(e){this.sendTypingEvent(e,QT.TYPING_START,"typing_start")}sendTypingStop(e){this.sendTypingEvent(e,QT.TYPING_STOP,"typing_stop")}sendTypingEvent(e,t,n){if(""===e)throw Ot("tokenName","Token name");if(!this.socket?.connected)throw new Ct("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(!this.isAuthenticated)throw new Ct("Not authenticated. Call authenticate() first.","auth","NOT_AUTHENTICATED");const r=on(e);this.logger.debug(`📡 Sending ${n} to ${r}`),this.socket.emit(t,{tokenName:r})}subscribeTokenBanned(e,t){const n=on(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=on(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=on(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=on(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=on(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=on(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=on(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=on(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=on(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=on(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=on(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=on(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 Ct("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(QT.SUBSCRIBE_GLOBAL_FEED)})}unsubscribeFromGlobalFeed(){this.isGlobalFeedSubscribed?(this.logger.debug("📡 Unsubscribing from global feed"),this.socket?.connected&&this.socket.emit(QT.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 eI(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"number"==typeof t.id&&"string"==typeof t.tokenName&&"string"==typeof t.bannedBy&&"string"==typeof t.createdAt&&(null===t.reason||"string"==typeof t.reason)}function tI(e){return null==e||""===e||"string"==typeof e&&(!pr(e)&&e.length<=In.BAN_REASON.MAX_LENGTH)}function nI(e){if(lr(e.tokenName,"tokenName",bn),!tI(e.reason))throw new Ct(`reason must be at most ${In.BAN_REASON.MAX_LENGTH} characters`,"reason","TOO_LONG")}function rI(e){lr(e.tokenName,"tokenName",bn)}function iI(e){sr(0,void 0,En,e.pageSize)}function sI(e){lr(e.tokenName,"tokenName",bn)}class oI extends WE{constructor(e,t,n,r=!1,i){super(e,t,n,r,i)}async banToken(e){nI(e);const t=Ge,n={tokenName:on(e.tokenName)};if(void 0!==e.reason)try{Xn(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:on(e.tokenName)}}async unbanToken(e){rI(e);const t=this.buildEndpoint(qe,{tokenName:e.tokenName});return Yt(await this.http.delete(t,void 0,this.getDualAuthHeaders()),"Failed to unban token",!1),{tokenName:on(e.tokenName)}}async listTokenBans(e={}){iI(e);const t=He,n=this.buildPaginationParams(e,En);this.addOptionalFilterParams(n,e,["search"]);const r=await this.http.get(t,n,this.getDualAuthHeaders()),i=this.extractData(r);return{items:i.bans,pageInfo:i.pageInfo}}async getTokenBan(e){sI(e);const t=this.buildEndpoint(We,{tokenName:e.tokenName}),n=await this.http.get(t,{},this.getDualAuthHeaders()),r=this.extractDataOrNull(n);return{banned:null!==r,...null!==r&&{ban:r},tokenName:on(e.tokenName)}}async isTokenBanned(e){return this.getTokenBan(e)}}class aI extends Ar{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(!nr(e))throw Ot("tokenName","Token name");const t=on(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(!nr(e))throw Ot("tokenName","Token name");const t=on(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 Mt(e);const i=this.parseVaultAddressToTokenClassKey(r);return this.setCacheEntry(t,{vaultAddress:r,tokenClassKey:i,cachedAt:Date.now()}),i}get(e){const t=this.getCacheEntry(on(e));return t?.vaultAddress??null}getCacheEntry(e){return this.cache.get(e)??null}setCacheEntry(e,t){this.cache.size>=aI.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=on(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:aI.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(on(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=on(t);this.setCacheEntry(e,{vaultAddress:n,tokenClassKey:r,cachedAt:Date.now()})}}parseVaultAddressToTokenClassKey(e){try{return vA(e)}catch(e){if(e instanceof Ct)throw Ut("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad","Vault address");throw e}}}aI.MAX_CACHE_SIZE=1e4;class cI extends Er{constructor(e,t=!1){super(e,t)}async fetchLaunchpadFee(){return en(()=>this.http.get(it),{errorContext:"Failed to fetch launchpad fee"})}async fetchSaleDetails(e){return en(()=>this.http.get(st,{tokenName:e}),{errorContext:`Failed to fetch sale details for ${e}`})}async getTradeQuote(e){return en(()=>this.http.get(ot,{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 en(()=>this.http.get(at,{amount:e}),{errorContext:"Failed to get premint quote"})}}class lI extends WE{constructor(e,t,n,r=!1,i){super(e,t,n,r,i)}async emitTradeExecuted(e,t){this.validateTokenName(e,vn);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,vn);const r={action:"balance_updated",userAddress:e,tokenName:t,payload:n};await this.emitEvent(r)}async emitStreamStatus(e,t,n=!0){this.validateTokenName(e,vn);const r={action:"stream_status",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitViewerCount(e,t,n=!1){this.validateTokenName(e,vn);const r={action:"viewer_count",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitStreamCountdown(e,t,n=!0){this.validateTokenName(e,vn);const r={action:"stream_countdown",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitChatMessage(e,t,n=!1){this.validateTokenName(e,vn);const r={action:"chat_message",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitChatStatus(e,t,n=!1){this.validateTokenName(e,vn);const r={action:"chat_status",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitTypingIndicator(e,t,n=!1){this.validateTokenName(e,vn);const r={action:"typing_indicator",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitTokenBanned(e,t){this.validateTokenName(e,vn);const n={action:"token_banned",tokenName:e,payload:t,broadcast:!0};await this.emitEvent(n)}async emitTokenUnbanned(e,t){this.validateTokenName(e,vn);const n={action:"token_unbanned",tokenName:e,payload:t,broadcast:!0};await this.emitEvent(n)}async emitModeratorAdded(e,t,n=!1){this.validateTokenName(e,vn);const r={action:"moderator_added",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitModeratorRemoved(e,t,n=!1){this.validateTokenName(e,vn);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 Rt("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,vn);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,vn);const n={action:"recording_status",tokenName:e,payload:t};await this.emitEvent(n)}async emitRecordingsCountUpdated(e,t){this.validateTokenName(e,vn);const n={action:"recordings_count_updated",tokenName:e,payload:t};await this.emitEvent(n)}async emitDownloadReady(e,t){this.validateTokenName(e,vn);const n={action:"download_ready",tokenName:e,payload:t};await this.emitEvent(n)}}class uI{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,i={value:t};r>0&&(i.expiresAt=Date.now()+r),this.cache.set(e,i)}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 dI(e,t,n,r={}){const{logger:i,cacheNullish:s=!1,keyGenerator:o}=r,a=o?o(e):String(e),c=n.get(a);if(void 0!==c)return i&&i.debug(`Cache hit for key: ${a}`),c;i&&i.debug(`Cache miss for key: ${a}, fetching...`);const l=await t();return null!=l?(n.set(a,l),i&&i.debug(`Cached result for key: ${a}`)):s&&(n.set(a,l),i&&i.debug(`Cached nullish result for key: ${a}`)),l}class hI extends Ar{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 sS({maxAttempts:this.config.reconnectAttempts??5,baseDelayMs:this.config.reconnectDelay??2e3}),this.eventBuffer=new uI(3e4),this.isSocketIOAvailable=this.checkSocketIOAvailability(),hI.instances.add(this)}checkSocketIOAvailability(){try{return"function"==typeof k||(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)=>{vo(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:",bt(e)),e}this.logger.debug("🔌 Connecting to Socket.IO server:",this.config.url),this.socket=k(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=yt(e)?e:new Error(bt(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,i=setTimeout(()=>{if(this.listeners.has(e)){const n=Math.round(r/1e3),i={transactionId:e,status:xE.TIMEOUT,message:`Transaction monitoring timeout - no response after ${n} seconds`,timestamp:Date.now()};this.logger.debug(`📡 Transaction timeout for ${e} (${n}s)`),t(i),this.listeners.delete(e),this.timeouts.delete(e),this.socket?.off(e)}},r);if(this.timeouts.set(e,i),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:xE.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,i=r?.data,s=r?.status??r?.Status??i?.status??i?.Status;let o=r?.message??r?.Message??i?.message??i?.Message??r?.error??i?.error;nr(o)||(o=s===_E.FAILED||s===_E.ERROR?"Transaction failed - check transaction details":s===_E.COMPLETED||s===_E.PROCESSED||s===_E.SUCCESS?"Transaction completed successfully":null!=s?`Transaction status: ${String(s)}`:"Unknown transaction status");const a=r?.blockHash??i?.blockHash,c=r?.gasUsed??i?.gasUsed,l=r?.Data??i?.Data,u={transactionId:e,status:this.mapSocketStatus(s),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(s)} -> ${u.status}`),this.logger.debug(`📡 Final message: "${String(o)}"`),n(u),u.status===xE.COMPLETED||u.status===xE.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===xE.COMPLETED?t(e):e.status!==xE.FAILED&&e.status!==xE.TIMEOUT||n(new Error(`Transaction ${String(e.status)}: ${e.message}`))})})}mapSocketStatus(e){const t=e?.toUpperCase();return RE[t]??xE.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")),hI.instances.delete(this)}static cleanupAll(e=!1){for(const e of hI.instances)e.disconnect();hI.instances.clear()}isConnected(){return this.socket?.connected??!1}getSocket(){return this.socket}}hI.instances=new Set;class gI extends Er{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 Ct("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(ct.GET_LEADERBOARD,n),i=this.extractData(r);return this.logger.debug("Fetched weekly challenge leaderboard",{count:i.count}),{leaderboard:i}}async getTokenHistory(e){const{vaultAddress:t}=e;if("string"!=typeof t||""===t.trim())throw new Ct("vaultAddress is required","vaultAddress","REQUIRED_FIELD");this.logger.debug("Fetching token weekly history",{vaultAddress:t});const n=ct.GET_TOKEN_HISTORY.replace(":vaultAddress",encodeURIComponent(t)),r=await this.http.get(n),i=this.extractData(r);return this.logger.debug("Fetched token weekly history",{count:i.length}),{snapshots:i}}}class fI extends kr{constructor(e=!1){super(e),this.lastFetchedAt=null}normalizeKey(e){return an(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 mI extends fI{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 pI extends SA{constructor(e,t=!1){super(e,t,"WrappableTokenService"),this.cache=new mI(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())})`),vo(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 vo(async()=>{const e=await async function(e){const{cache:t,fetchFn:n,logger:r,itemTypeName:i="items"}=e;if(t.has()){const e=t.getAll();return r&&r.debug(`Returning ${e.length} cached ${i}`),{items:e,fetchedAt:t.getFetchTimestamp()??Date.now(),itemCount:e.length}}r&&r.debug(`Fetching all ${i} (no cache)`);const s=await n();try{t.setAll(s)}catch(e){r&&r.error("Cache operation failed (non-fatal):",e)}return{items:s,fetchedAt:Date.now(),itemCount:s.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=AA(e),n=this.cache.getByTokenId(t);return n||(await dI("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=AA(e);await dI("wrappable:check",()=>this.fetchAllWrappableTokens(),{get:()=>this.cache.has()?{}:void 0,set:()=>{}},{logger:this.logger});const n=this.cache.getByTokenId(t),r=void 0!==n,i={isWrappable:r,tokenId:t};return r&&(i.wrapCounterpart=n.wrapCounterpart),i}getCacheStats(){return this.cache.getStats()}clearCache(){this.cache.clear()}}class yI extends Ar{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 FA(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 Ot("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()",i=t?"ALREADY_ON_ASSET_CHANNEL":"NOT_ON_ASSET_CHANNEL";throw new Ct(`Cannot ${t?"wrap":"unwrap"} ${n.symbol} - it's ${e}. Use ${r} instead.`,"tokenId",i)}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 Ot("tokenId","Token identifier");if(0===t.length)throw Ot("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 Ct(`Cannot ${n?"wrap":"unwrap"} ${r.symbol} - it's ${e}`,"tokenId",t)}const i=this.determineChannelRouting(r,n);return{fee:"0",feeToken:"GALA",authorizationType:i.authType,feeChannel:i.sourceChannel}}async executeChannelBridge(e){const{sourceToken:t,destinationToken:n,amount:r,recipient:i,isWrap:s}=e;if(void 0===this.nativeSigner||void 0===this.walletAddress||0===this.walletAddress.length)throw new Ct("Wallet required for wrap/unwrap operations. Initialize SDK with a private key.","wallet","WALLET_REQUIRED");const o=this.walletAddress,a=this.determineChannelRouting(t,s),c=`galaswap-operation-${yw()}`,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:i??o,wrap:!0,uniqueKey:c};return this.logger.debug(`[WrapService] ${s?"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:s,senderAddress:o})}async executeWrapBridgeRequest(e){const{sourceToken:t,destinationToken:n,amount:r,message:i,routing:s,isWrap:o}=e;try{const e=await this.nativeSigner.signObject("RequestTokenBridgeOut",i);this.logger.debug(`[WrapService] ${o?"Wrap":"Unwrap"} request (signed)`,{sourceToken:t.symbol,destinationToken:n.symbol,amount:r,channel:s.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}`,i="string"==typeof a.Message&&a.Message.length>0?`: ${a.Message}`:"";return{success:!1,fromToken:t.symbol,toToken:n.symbol,amount:r,fromChannel:s.sourceChannel,toChannel:o?"asset":n.channel??"music",error:`GalaChain request failed (${e}${i})`}}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 i={bridgeFromChannel:s.sourceChannel,bridgeRequestId:e};this.logger.debug("[WrapService] Step 2 - BridgeTokenOut",{bridgeFromChannel:i.bridgeFromChannel});const c=await this.galaConnectClient.bridgeTokenOut(i);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:s.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:s.sourceChannel,toChannel:o?"asset":n.channel??"music",completedAt:Date.now()}}return{success:!1,fromToken:t.symbol,toToken:n.symbol,amount:r,fromChannel:s.sourceChannel,toChannel:o?"asset":n.channel??"music",error:`Unexpected response format from GalaChain (type=${typeof a})`}}catch(e){const i=bt(e);return this.logger.error(`[WrapService] ${o?"Wrap":"Unwrap"} operation failed:`,i),{success:!1,fromToken:t.symbol,toToken:n.symbol,amount:r,fromChannel:s.sourceChannel,toChannel:o?"asset":n.channel??"music",error:i}}}determineChannelRouting(e,t){if(t){return{sourceChannel:e.channel??"music",destinationChannelId:xo.ASSET,authType:"cross_channel_authorization"}}return{sourceChannel:"asset",destinationChannelId:xo.MUSIC,authType:"automatic"}}async getCounterpartOrThrow(e,t){const n=await this.wrappableTokenService.getWrapCounterpart(e);if(null==n)throw new Ct(`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 Ct(`Token not found or not wrappable: ${this.formatTokenId(e)}`,"tokenId","TOKEN_NOT_WRAPPABLE");return t}formatTokenId(e){return"string"==typeof e?e:No(e)}}class bI 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 vI{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 wI{constructor(e){this.bundleBaseUrl=CI(e.bundleBaseUrl),this.launchpadBaseUrl=CI(e.launchpadBaseUrl),this.signer=e.signer,this.walletAddress=e.walletAddress,this.requestor=e.httpRequestor??fetch.bind(globalThis),this.socketFactory=e.socketFactory??(e=>k(e,{transports:["websocket"]}))}async submit(e){let t;try{t=await this.signer.signTypedData(e.method,e.dto)}catch(e){if(e instanceof bI)throw e;const t=e instanceof Error?e.message:"Launchpad signing failed.";throw new bI(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`,i=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})}),s=await II(i);if(!i.ok)throw AI(i.status,s,r);const o=function(e){if("string"==typeof e&&""!==e)return e;if(!NI(e))throw new bI("Bundler returned no bundle id.","INVALID_BUNDLE_RESPONSE");const t=e.data,n=e.bundleId;if("string"==typeof t&&""!==t)return t;if(NI(t)&&"string"==typeof t.bundleId&&""!==t.bundleId)return t.bundleId;if("string"==typeof n&&""!==n)return n;throw new bI("Bundler returned no bundle id.","INVALID_BUNDLE_RESPONSE")}(s),a=TI(e.dto,"uniqueKey");return new vI({bundleId:o,uniqueKey:a,method:e.method,wait:t=>this.waitForResult(e,o,t)})}async waitForResult(e,t,n={}){const r=n.timeoutMs??6e4,i=n.pollIntervalMs??2500,s=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(!NI(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(EI(r.data)):e(r))},o?.on(t,a)})}catch{o=void 0}const u=this.pollConfirmation(e,t,s,r,i);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,i){const s="CreateSale"===e.method,o=s?function(e,t){const n=TI(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 II(e);if(s){if(e.ok)return{status:"PROCESSED",data:SI(t)};if(404!==e.status&&202!==e.status)throw AI(e.status,t,o)}else{if(!e.ok)throw AI(e.status,t,o);const n=NI(t)?t.status:void 0;if("COMPLETED"===n||"PROCESSED"===n)return{status:"PROCESSED",data:t};if("FAILED"===n)throw EI(t)}const a=r-(Date.now()-n);if(a<=0)break;await _I(Math.min(Math.max(0,i),a))}throw new bI(`Timed out waiting for bundle ${e.dto.uniqueKey}`,"BUNDLE_CONFIRMATION_TIMEOUT",{details:{method:e.method}})}}function EI(e){const t=kI(e)??"Launchpad bundle failed on chain.";return new bI(t,"BUNDLE_FAILED",{chainMessage:t})}function AI(e,t,n){const r=kI(t)??`Bundle request failed with HTTP ${e}`;return new bI(r,"BUNDLE_REQUEST_FAILED",{status:e,chainMessage:r,details:{body:t,url:n}})}function kI(e){if("string"==typeof e&&""!==e)return e;if(NI(e))for(const t of["chainMessage","message","Message","error"]){const n=e[t];if("string"==typeof n&&""!==n)return n;if(NI(n)){const e=kI(n);if(void 0!==e)return e}}}function SI(e){return NI(e)?e.data??e.Data??e:e}function TI(e,t){const n=e[t];if("string"!=typeof n||""===n)throw new bI(`Missing ${t} in launchpad DTO.`,"INVALID_LAUNCHPAD_DTO");return n}async function II(e){try{return await e.json()}catch{return e.text()}}function NI(e){return"object"==typeof e&&null!==e}function CI(e){return e.replace(/\/$/u,"")}function _I(e){return new Promise(t=>setTimeout(t,e))}function xI(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,i,s,o,a,...c]=n.split("$");if(void 0===r||void 0===i||void 0===s||void 0===o||"launchpad"!==a||c.length>0||""===r||""===i||""===s||""===o)throw new Error(`Invalid vaultAddress format (expected service|<collection>$<category>$<type>$<additionalKey>$launchpad): ${e}`);return{collection:r,category:i,type:s,additionalKey:o}}function RI(e){const{collection:t,category:n,type:r}=xI(e),i=`${t}$${n}$${r}$none`,s="GALA$Unit$none$none";return[`$service$${i}$launchpad`,`$tokenBalance$${i}$${e}`,`$tokenBalance$${i}$${e}`,`$tokenBalance$${s}$${e}`,`$tokenBalance$${s}$${e}`]}function BI(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 DI{constructor(e){this.transport=e.transport,this.walletAddress=e.walletAddress}createSale(e){!function(e){const t=ms(e);!t.success&&t.errors&&ro(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??MI(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:BI(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??MI(this.walletAddress)};return this.transport.submit({method:e,dto:r,stringsInstructions:RI(t.vaultAddress)})}}function MI(e){return`galaswap-operation-${b()}-${Date.now()}-${e}`}class OI{constructor(e){this.gatewayBaseUrl=e.gatewayBaseUrl.replace(/\/$/u,""),this.signer=e.signer,this.walletAddress=GI(e.walletAddress),this.requestor=e.httpRequestor??fetch.bind(globalThis)}transfer(e){const t=UI(e),n={from:this.walletAddress,to:GI(e.to),quantity:e.quantity,tokenInstance:t,uniqueKey:e.uniqueKey??KI(this.walletAddress)};return this.direct("TransferToken",n)}burn(e){const t={tokenInstances:[{quantity:e.quantity,tokenInstanceKey:UI(e)}],uniqueKey:e.uniqueKey??KI(this.walletAddress)};return this.direct("BurnTokens",t)}lock(e){const t={lockAuthority:e.lockAuthority??this.walletAddress,tokenInstances:[{owner:this.walletAddress,quantity:e.quantity,tokenInstanceKey:UI(e)}],uniqueKey:e.uniqueKey??KI(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:UI(e)}],uniqueKey:e.uniqueKey??KI(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}`,i=await this.post(r,n),s=await async function(e){try{return await e.json()}catch{return e.text()}}(i),o=$I(s);if(!i.ok||void 0!==o?.Status&&1!==o.Status)throw function(e,t,n){const r=$I(t),i=FI(r,"Message")??FI(r,"message")??FI(r,"ErrorKey")??`Gateway request failed with HTTP ${e}`,s=FI(r,"ErrorKey")??"GATEWAY_REQUEST_FAILED";return new bI(i,s,{status:e,chainMessage:i,details:{body:t,url:n}})}(i.status,s,r);const a=$I(LI(s))?.mode??o?.mode;if(void 0!==a&&"sync"!==a){throw new bI(`Unsupported gateway transaction mode: ${"string"==typeof a?a:"non-sync"}`,"INVALID_GATEWAY_RESPONSE",{status:i.status,details:{body:s,url:r}})}const c=LI(s),l=HI(i,"x-transaction-id")??PI(c)??PI(s),u=function(e){const t=HI(e,"x-block-number");if(void 0===t)return;const n=Number.parseInt(t,10);return Number.isFinite(n)?n:void 0}(i);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 bI)throw e;const t=e instanceof Error?e.message:"Native GalaChain signing failed.";throw new bI(t,"NATIVE_SIGNING_FAILED",{chainMessage:t})}}}function UI(e){const t=e.tokenClassKey??e.symbol;if(void 0===t)throw new bI("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,i,s]=e.split(t);if(void 0===n||void 0===r||void 0===i||void 0===s||[n,r,i,s].some(e=>""===e))throw new bI(`Invalid token class key: ${e}`,"INVALID_TOKEN_IDENTIFIER");return{collection:n,category:r,type:i,additionalKey:s}}(t);return{...n,instance:e.instance??"0"}}function LI(e){const t=$I(e);return t?.Data??t?.data??e}function PI(e){if("string"==typeof e&&""!==e)return e;const t=$I(e);return FI(t,"transactionId")??FI(t,"txnId")??FI(t,"id")}function FI(e,t){const n=e?.[t];return"string"==typeof n&&""!==n?n:void 0}function $I(e){return"object"==typeof e&&null!==e?e:void 0}function KI(e){return`galaswap-operation-${b()}-${Date.now()}-${e}`}function GI(e){return"eth|0x"===e.slice(0,6).toLowerCase()?`eth|${e.slice(6)}`:e}function HI(e,t){const n=e.headers;if(void 0===n)return;if("function"==typeof n.get)return WI(n.get(t));const r=t.toLowerCase();for(const[e,t]of Object.entries(n))if(e.toLowerCase()===r)return WI(t)}function WI(e){const t=e?.trim();return void 0===t||""===t?void 0:t}function qI(e,t=3e4){return S.create({baseURL:e,timeout:t,headers:{"Content-Type":"application/json"}})}const jI=new Set(["accesstoken","refreshtoken","token","password","privatekey","secret","apikey","api_key","rawkey","authorization","x-api-key","bearer","streamadminapikey","userapikey","signature","signedpayload"]);function VI(e,t=0){if(t>5)return"[...]";if(null==e)return e;if(Array.isArray(e))return e.map(e=>VI(e,t+1));if(e instanceof Map){const n={};for(const[r,i]of e.entries()){const e=String(r);n[e]=jI.has(e.toLowerCase())?"[REDACTED]":VI(i,t+1)}return n}if("object"==typeof e){const n={};for(const[r,i]of Object.entries(e))n[r]=jI.has(r.toLowerCase())?"[REDACTED]":VI(i,t+1);return n}return e}class zI{constructor(e,t={}){this.auth=e,this.debug=t.debug??!1,this.logger=new un({debug:this.debug,context:"HttpClient"});const n=t.baseUrl??Io("stage").launchpadBaseUrl,r=t.timeout??6e4;this.axios=qI(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 vo(async()=>{const t={method:e.method,url:e.url,data:e.data,...void 0!==e.params&&{params:Gs(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]":VI(e.data);this.logger.debug("Request:",{method:e.method,url:e.url?.split("?")[0],baseURL:this.axios.defaults.baseURL,params:VI(t.params),data:n,isFormData:e.data instanceof FormData,contentType:t.headers?.["Content-Type"]??"not set"});const r=await this.axios.request(t),i=function(e){const t={};if(null==e||"object"!=typeof e)return t;for(const[n,r]of Object.entries(e))"string"==typeof r?t[n.toLowerCase()]=r:"number"!=typeof r&&"boolean"!=typeof r||(t[n.toLowerCase()]=String(r));return t}(r.headers);return this.logger.debug("Response:",{status:r.status,data:VI(r.data),transactionId:i["x-transaction-id"],blockNumber:i["x-block-number"]}),{data:r.data,headers:i,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 vo(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??bt(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 XI extends Error{constructor(e,t){super(e),this.cause=t,this.name="WebSocketError"}}class JI extends XI{constructor(e,t){super(`WebSocket confirmation timeout for transaction ${e} after ${t}ms`),this.name="WebSocketTimeoutError"}}class YI 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 QI(e,t){if(ir(e))throw new XI(`Invalid WebSocket response received for transaction ${t}: response is null or undefined`);if("object"!=typeof e)throw new XI(`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 XI(`Invalid WebSocket response received for transaction ${t}: missing status field`)}function ZI(e,t,n,r){QI(e,t);const i=e,s=i.data??{};if(!function(e){if(ir(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)}(s))throw new XI(`Invalid trade data received for transaction ${t}`);const o={transactionId:t,type:n,method:"native"===r.type?"native":"exact",inputAmount:s.inputQuantity??r.amount,outputAmount:s.outputQuantity??r.expectedAmount??"0",totalFees:s.totalFees??"0",tokenName:r.tokenName,vaultAddress:s.vaultAddress??"",timestamp:Date.now()};return void 0!==i.blockHash&&(o.blockHash=i.blockHash),void 0!==i.gasUsed&&(o.gasUsed=i.gasUsed),void 0!==r.slippageToleranceFactor&&(o.slippageTolerance=r.slippageToleranceFactor),o}function eN(e,t,n){return{types:{EIP712Domain:tN(e),...t},primaryType:Object.keys(t)[0],domain:nN(e),message:n}}function tN(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 nN(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 rN(e){return`0x${Buffer.from(e,"utf8").toString("hex")}`}class iN{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 i=t=>{const r=t[0];n(void 0===r?null:e(r))},s=()=>r();return t.on("accountsChanged",i),t.on("disconnect",s),{accountsChanged:i,disconnect:s}}(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 sN(e,t,n){try{return await e()}catch(e){if(e instanceof Ao)throw e;return t(e,n)}}const oN=4001,aN=4100,cN=4900,lN=4901;class uN extends iN{constructor(e){if(super(e),this.providerType="external",null==e)throw new Ao("EIP-1193 provider is required",po.INVALID_CONFIG)}handleProviderError(e,t){const n=e;if(n.code===oN)throw new Ao(`User rejected ${t}`,po.USER_REJECTED,e instanceof Error?e:void 0);if(n.code===aN)throw new Ao("Wallet is not authorized",po.NOT_CONNECTED,e instanceof Error?e:void 0);if(n.code===cN||n.code===lN)throw this.connectedAddress=null,new Ao("Wallet disconnected",po.NOT_CONNECTED,e instanceof Error?e:void 0);throw new Ao(n.message??`${t} failed`,t.includes("sign")?po.SIGNING_FAILED:po.UNKNOWN,e instanceof Error?e:void 0)}ensureConnected(){if(!this.connectedAddress)throw new Ao("Wallet is not connected. Call connect() first.",po.NOT_CONNECTED)}async connect(){try{const t=await this.provider.request({method:"eth_requestAccounts"});if(null==t||0===t.length)throw new Ao("No accounts returned from wallet",po.CONNECTION_FAILED);const n=t[0];if(void 0===n)throw new Ao("No accounts returned from wallet",po.CONNECTION_FAILED);return this.connectedAddress=e(n),this.connectedAddress}catch(e){if(e instanceof Ao)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(),sN(()=>async function(e,t,n){return e.request({method:"personal_sign",params:[rN(n),t]})}(this.provider,this.connectedAddress,e),(e,t)=>this.handleProviderError(e,t),"sign message")}async signTypedData(e,t,n){return this.ensureConnected(),sN(()=>async function(e,t,n,r,i){return e.request({method:"eth_signTypedData_v4",params:[t,JSON.stringify(eN(n,r,i))]})}(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 Ao("Wallet is not connected",po.NOT_CONNECTED);return e}async getGalaAddress(){return`eth|${(await this.getAddress()).slice(2)}`}async getPrivateKey(){return Promise.reject(new Ao("Private key is not accessible with external wallet providers. Use PrivateKeyProvider if you need private key access for @gala-chain operations.",po.PRIVATE_KEY_NOT_ACCESSIBLE))}getProvider(){return this.provider}}function dN(e){if(null!==e.privateKey&&void 0!==e.privateKey&&e.privateKey.length>0)return new ko(e.privateKey);if(null!==e.eip1193Provider&&void 0!==e.eip1193Provider)return new uN(e.eip1193Provider);throw new Ao("Invalid wallet provider config: must provide either privateKey or eip1193Provider",po.INVALID_CONFIG)}function hN(e){return ko.fromWallet(e)}function gN(e){return new uN(e)}function fN(e){return"privateKey"===e.providerType}function mN(e){return"external"===e.providerType}function pN(e){if(e)return ko.fromWallet(e)}function yN(e){if(e&&fN(e))return e.getWallet()}async function bN(e){return e.isConnected()?e.getAddress():e.connect()}function vN(e){return"object"==typeof e&&null!==e&&"request"in e&&"function"==typeof e.request}function wN(){if("undefined"==typeof window)return null;const e=window.ethereum;return vN(e)?e:null}class EN{constructor(e){let t,n;e.walletProvider?(t=e.walletProvider,n=yN(e.walletProvider)):e.wallet&&(n=e.wallet,t=ko.fromWallet(e.wallet)),this.wallet=n;const r=e.env??"prod",i=Io(r);this.environment=r,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 s=e.signer??(void 0!==n?new FA(n.privateKey):void 0),o=e.walletAddress??e.galaChainAddress??(void 0!==n?`eth|${n.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}(s)),a=s??{signObject:()=>Promise.reject(new Error("A signer is required for token writes.")),signTypedData:()=>Promise.reject(new Error("A signer is required for launchpad writes."))},c=o??"",l=new wI({bundleBaseUrl:this.config.bundleBaseUrl,launchpadBaseUrl:this.config.baseUrl,signer:a,walletAddress:c,...void 0!==e.httpRequestor&&{httpRequestor:e.httpRequestor}});if(this.launchpad=new DI({transport:l,walletAddress:c}),this.tokens=new OI({gatewayBaseUrl:this.config.gatewayBaseUrl,dexBackendBaseUrl:this.config.dexBackendBaseUrl,signer:a,walletAddress:c,...void 0!==e.httpRequestor&&{httpRequestor:e.httpRequestor}}),this.logger=new un({debug:this.config.debug??!1,context:"LaunchpadSDK"}),this.validateConfiguration(),this.slippageToleranceFactor=void 0===e.slippageToleranceFactor?EN.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR:this.parseSlippageToleranceFactor(e.slippageToleranceFactor),this.maxAcceptableReverseBondingCurveFeeSlippageFactor=void 0===e.maxAcceptableReverseBondingCurveFeeSlippageFactor?EN.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR:this.parseFeeSlippageFactor(e.maxAcceptableReverseBondingCurveFeeSlippageFactor),this.calculateAmountMode=e.calculateAmountMode??EN.DEFAULT_CALCULATE_AMOUNT_MODE,this.galaChainAddressOverride=e.galaChainAddress,this.signerWalletAddress=e.walletAddress??(void 0===n?o:void 0),this.auth=new So({wallet:n,walletProvider:t,messagePrefix:"Create a GalaChain Wallet"}),this.jwtAuth=new bo,void 0!==e.accessToken&&""!==e.accessToken){const t=e.accessTokenExpiresIn??86400;this.jwtAuth.setToken(e.accessToken,t)}this.http=new zI(this.auth,this.config),this.sessionAuth=new Eo(this.http,this.auth,this.jwtAuth,e.debug??!1),this.galaChainHttp=new zI(this.auth,{...this.config,baseUrl:this.config.gatewayBaseUrl}),this.bundleHttp=new zI(this.auth,{...this.config,baseUrl:this.config.bundleBaseUrl}),this.dexApiHttp=new zI(this.auth,{...this.config,baseUrl:this.config.dexApiBaseUrl}),this.dexBackendHttp=new zI(this.auth,{...this.config,baseUrl:this.config.dexBackendBaseUrl}),this.galaChainPublicAxios=qI(this.config.gatewayBaseUrl,this.config.timeout??3e4),this.cache=new Sr(e.debug??!1),this.launchpadService=new US(this.http,this.jwtAuth),this.tokenResolverService=new aI(this.launchpadService.poolService),this.launchpadAPI=new ho(this.http,this.tokenResolverService,this.logger,this.bundleHttp,this.galaChainHttp,this.dexApiHttp,this.calculateAmountMode,this.launchpad),this.galaChainService=new iS(this.galaChainHttp,n,this.tokenResolverService,e.debug??!1,this.galaChainPublicAxios),this.dexService=new mk(this.dexBackendHttp,this.cache,this.galaChainService,e.debug??!1),this.bundleService=new jA(this.bundleHttp,this.tokenResolverService,this.config.debug??!1,n,n?this.getAddress():void 0,this.slippageToleranceFactor,this.maxAcceptableReverseBondingCurveFeeSlippageFactor),this.websocketService=new hI({url:this.config.webSocketUrl},this.config.debug),this.priceHistoryService=new _T(this.dexBackendHttp,this.config.debug??!1,this.tokenResolverService);const u=e.signer??(void 0===n?void 0:new FA(n.privateKey)),d=e.walletAddress??(void 0===n?void 0:this.getAddress());this.dexClient=new m({env:this.environment,...void 0===u?{}:{signer:u},...void 0===d?{}:{walletAddress:d},...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 cT(this.galaChainHttp),this.tradingQuotesService=new cI(this.http,e.debug??!1)}createOverrideSdk(e){if(!nr(e))throw Pt("Invalid privateKey: must be a non-empty string","privateKey");if(!e.match(/^0x[a-fA-F0-9]{64}$/))throw Pt('Invalid privateKey format: must be "0x" followed by 64 hexadecimal characters',"privateKey");const n=new t(e),r={...this.config,wallet:n};return new EN(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 Ot("wallet","Wallet");return this.wallet}setWallet(e){if(null==e||"object"!=typeof e||!("address"in e))throw new Ct("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?yN(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:i,userApiKey:s,accessToken:o,headers:a,...c}=this.config;return{...c,...void 0!==i&&{streamAdminApiKey:"[REDACTED]"},...void 0!==s&&{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:sn.GAS_FEE}}getVersion(){return BE}getUrlByTokenName(e){const t=this.config.launchpadFrontendUrl;if(void 0===t||""===t)throw Pt("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 i=n.holders[r];return void 0===i?null:{rank:r+1,balance:i.balance,holderCount:n.totalHolders}}async getHoldersByBalance(e,t){const n=await this.fetchTokenDistribution(e),r=t?.minBalance??0,i=t?.maxBalance??1/0,s=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<=i}).map(e=>({...e,rank:o.get(e.address)??0})).slice(0,s)}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}=cr(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 i=n;try{return await this.dexService.fetchTokenPrice({tokenId:i})}catch(e){const t=function(e){if(Et(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=on((await this.fetchTokenDetails(i)).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: ${bt(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(It(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 Lr}),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 CE({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 CA(this.dexApiHttp,this.config.debug??!1)),this._bridgeableTokenService}getWrappableTokenService(){return this._wrappableTokenService??(this._wrappableTokenService=new pI(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 oE({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 yI({galaConnectClient:this.getGalaConnectClient(),wrappableTokenService:this.getWrappableTokenService(),...e&&{walletAddress:this.getAddress(),wallet:e}})}return this._wrapService}getStreamingService(){return this._streamingService??(this._streamingService=new YT(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._streamingService}getStreamChatService(){return this._streamChatService??(this._streamChatService=new RT(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._streamChatService}getBanService(){return this._banService??(this._banService=new mA(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._banService}getTokenBanService(){return this._tokenBanService??(this._tokenBanService=new oI(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._tokenBanService}getAIModerationService(){return this._aiModerationService??(this._aiModerationService=new qE(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._aiModerationService}getWeeklyChallengeService(){return this._weeklyChallengeService??(this._weeklyChallengeService=new gI(this.http,this.config.debug??!1)),this._weeklyChallengeService}getOEmbedService(){return this._oembedService??(this._oembedService=new uT(this.http,this.config.debug??!1)),this._oembedService}getPlatformStatsService(){return this._platformStatsService??(this._platformStatsService=new CT(this.http,this.config.debug??!1)),this._platformStatsService}getNotificationService(){return this._notificationService??(this._notificationService=new lT(this.http,this.config.debug??!1,this.jwtAuth)),this._notificationService}getClientConfigService(){return this._clientConfigService??(this._clientConfigService=new VA(this.http,this.config.debug??!1)),this._clientConfigService}getApiKeyService(){return this._apiKeyService??(this._apiKeyService=new iA(this.http,this.jwtAuth,this.config.debug??!1)),this._apiKeyService}getModeratorService(){return this._moderatorService??(this._moderatorService=new eT(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._moderatorService}getFlagService(){return this._flagService??(this._flagService=new dk(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._flagService}getOverseerService(){return this._overseerService??(this._overseerService=new TT(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._overseerService}getWebSocketAdminService(){return this._websocketAdminService??(this._websocketAdminService=new lI(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._websocketAdminService}getContentReactionService(){return this._contentReactionService??(this._contentReactionService=new fk(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 Lr}),n=t(e);if(void 0===n)throw new Ct(`Invalid address format: "${e}". Expected formats: eth|0x..., 0x..., or client|...`);return n}getMessagesService(){return this._messagesService??(this._messagesService=new LS(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._messagesService}getRestrictedNamesService(){return this._restrictedNamesService??(this._restrictedNamesService=new xT(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.userApiKey)),this._restrictedNamesService}getPlatformConfigService(){return this._platformConfigService??(this._platformConfigService=new NT(this.http,this.jwtAuth,this.config.debug??!1)),this._platformConfigService}getEventsBatcherService(){return this._eventsBatcherService??(this._eventsBatcherService=new bk(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 ZT({url:this.config.streamWebSocketUrl},this.config.debug??!1)}return this._streamWebSocketService}getGdexStreamService(){return this._gdexStreamService??(this._gdexStreamService=new aS({url:this.config.gdexWebSocketUrl})),this._gdexStreamService}getStreamingEventService(){return this._streamingEventService??(this._streamingEventService=new BT(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 Lr}),n=t(e.address);if(void 0!==e.tokenId&&""!==e.tokenId){const{normalizeToTokenInstanceKey:t}=await Promise.resolve().then(function(){return kA}),r=t(e.tokenId),{collection:i,category:s,type:o,additionalKey:a}=r;return this.galaChainService.fetchTokenBalance({owner:n,collection:i,category:s,additionalKey:a,type:o,instance:"0"},e.withExpired??!1)}if(void 0!==e.tokenName&&""!==e.tokenName){const t=cn(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",i={collection:r,category:"Unit",type:t.symbol,additionalKey:"none"};return{quantity:t.balance,collection:r,category:"Unit",tokenId:No(i)}}throw Ot("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:i,calculateAmountMode:s,currentSupply:o}=e;let a=t;void 0===s&&void 0===o||(a={tokenName:t,...void 0!==s&&{calculateAmountMode:s},...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!==i&&(l.privateKey=i),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 Ft("No transaction ID returned from buy operation");return this.waitForConfirmation(n,t=>ZI(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 Ft("No transaction ID returned from sell operation");return this.waitForConfirmation(n,t=>ZI(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=>{QI(n,t);const r=n.data??{};if(!function(e){if(ir(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 XI(`Invalid launch data received for transaction ${t}`);const i={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&&(i.tokenImage=e.tokenImage),void 0!==e.preBuyQuantity&&(i.preBuyQuantity=e.preBuyQuantity),""!==i.vaultAddress&&this.tokenResolverService.set(e.tokenName,i.vaultAddress),i})}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 Lr}),n=t(e)??this.getAddress();return this.launchpadService.fetchProfile(n)}async fetchReferralUrl(){this.validateWallet();const e=this.getAddress();return await this.dexApiHttp.get(_,void 0,{"x-wallet-address":e})}async fetchReferrals(e){const t=await this.resolveReferralAddress(e?.address),n=e?.page??1,r=e?.limit??10,i={pageNumber:n,limit:r,sortBy:e?.sortBy??"joined",sortDir:e?.sortDir??"desc"},s=await this.dexApiHttp.get(x,i,{"x-wallet-address":t});if(!Array.isArray(s))throw new xt("Unexpected API response: expected array, got "+typeof s);return{referrals:s,page:n,limit:r,hasMore:s.length===r}}async fetchAllReferrals(e){const t=await yA((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(R,void 0,{"x-wallet-address":t});if(void 0===n||"number"!=typeof n.referralCount||void 0===n.rewardTotals)throw new xt(`Unexpected API response: expected { referralCount, rewardTotals }, got ${JSON.stringify(n)}`);return n}async updateProfile(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Lr}),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 Lr}),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 Lr}),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 Lr}),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 Lr}),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 Lr}),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 Lr});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{jn(this.config.timeout,1,3e5,"timeout")}catch{this.logger.warn(`Invalid timeout value: ${this.config.timeout??"undefined"}. Using default 30000ms.`),this.config.timeout=3e4}if(void 0===this.config.baseUrl||""===this.config.baseUrl)throw Pt("baseUrl is required in configuration","baseUrl");if(void 0===this.config.webSocketUrl||""===this.config.webSocketUrl)throw Pt("webSocketUrl is required in configuration","webSocketUrl");try{new URL(this.config.baseUrl)}catch{throw Pt(`Invalid baseUrl format: ${this.config.baseUrl}`,"baseUrl")}try{new URL(this.config.webSocketUrl)}catch{throw Pt(`Invalid webSocketUrl format: ${this.config.webSocketUrl}`,"webSocketUrl")}if(void 0!==this.config.gatewayBaseUrl&&""!==this.config.gatewayBaseUrl)try{new URL(this.config.gatewayBaseUrl)}catch{throw Pt(`Invalid gatewayBaseUrl format: ${this.config.gatewayBaseUrl}`,"gatewayBaseUrl")}if(void 0!==this.config.bundleBaseUrl&&""!==this.config.bundleBaseUrl)try{new URL(this.config.bundleBaseUrl)}catch{throw Pt(`Invalid bundleBaseUrl format: ${this.config.bundleBaseUrl}`,"bundleBaseUrl")}if(void 0!==this.config.launchpadFrontendUrl&&""!==this.config.launchpadFrontendUrl)try{new URL(this.config.launchpadFrontendUrl)}catch{throw Pt(`Invalid launchpadFrontendUrl format: ${this.config.launchpadFrontendUrl}`,"launchpadFrontendUrl")}}parseSlippageToleranceFactor(e){const t=Pn("string"==typeof e||"number"==typeof e?e:String(e),EN.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR);return t<0||t>1?(this.logger.warn(`Invalid slippage tolerance factor: ${String(e)}, using default: ${EN.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR}`),EN.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR):t}parseFeeSlippageFactor(e){const t=Pn("string"==typeof e||"number"==typeof e?e:String(e),EN.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: ${EN.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR}`),EN.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!==xE.COMPLETED)throw new YI(e,n.status,n.message);let r;try{r=t(n)}catch(t){if(t instanceof XI)throw t;throw new XI(`Failed to transform WebSocket response for transaction ${e}`,yt(t)?t:new Error(bt(t)))}return this.logger.debug(`Transaction confirmed: ${e}`,r),r}catch(t){if(this.logger.error(`Transaction confirmation failed: ${e}`,t),t instanceof YI||t instanceof XI)throw t;throw new XI(`WebSocket confirmation failed for transaction ${e}`,yt(t)?t:new Error(bt(t)))}}async warmCacheFromPools(e){if(void 0===e||!Array.isArray(e))return;const{extractMetadataFromPoolData:t,isValidPoolForCaching:n}=await Promise.resolve().then(function(){return rx});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 i=t?.creatorAddress,s=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=>{s.has(t.tokenName)||((e=>{if(s.set(e,!0),s.size>1e3){const e=s.keys().next().value;void 0!==e&&s.delete(e)}})(t.tokenName),void 0!==i&&""!==i&&t.creatorAddress!==i||e(t))})}catch(e){c++;const t=bt(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 Pt("WebSocket service not initialized. Ensure websocketUrl is configured and the service is connected.","websocketService");let n=!1,r=null;const i=(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: ${bt(e)}`)}};let s=this.websocketService.getSocket();if(s)s.onAny(i),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: ${bt(e)}`);this.logger.warn("Failed to establish WebSocket connection:",e),t?.onError&&t.onError(n)});let e=0;const o=()=>{if(s=this.websocketService.getSocket(),!s&&e<EN.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS)return e++,void(r=setTimeout(()=>o(),EN.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS));if(!s&&e>=EN.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS){const e=new Error(`WebSocket not available after ${EN.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS*EN.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS}ms`);return this.logger.warn("Token creation broadcast subscription timeout:",e.message),void(t?.onError&&t.onError(e))}s&&(s.onAny(i),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(i),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 un({debug:e,context:"LaunchpadSDK"});t.debug("Starting global cleanup..."),hI.cleanupAll(e),t.debug("Global cleanup completed")}}function AN(){const e=globalThis;return e.process?.env??{}}EN.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR=.15,EN.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR=.01,EN.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY=sn.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY,EN.DEFAULT_CALCULATE_AMOUNT_MODE=pt.LOCAL,EN.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS=30,EN.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS=100;let kN=0;class SN{constructor(){this.utilityInstance=!0,this.utilityInstance}static generateWallet(){try{const e=t.createRandom();if(null===e.mnemonic?.phrase||void 0===e.mnemonic?.phrase||""===e.mnemonic.phrase)throw Ot("mnemonic","Mnemonic phrase");const n=SN.toGalaAddress(e.address);return{privateKey:e.privateKey,address:e.address,galaAddress:n,mnemonic:e.mnemonic.phrase,wallet:new t(e.privateKey)}}catch(e){if("test"===AN().NODE_ENV){const e=`test-wallet-${Date.now()}-${++kN}`,n="0x"+Buffer.from(e).toString("hex").padStart(64,"1").slice(0,64),r=new t(n),i=SN.toGalaAddress(r.address);return{privateKey:r.privateKey,address:r.address,galaAddress:i,mnemonic:"test test test test test test test test test test test junk",wallet:r}}throw e}}static fromPrivateKey(e){const n=new t(e),r=SN.toGalaAddress(n.address);return{privateKey:n.privateKey,address:n.address,galaAddress:r,mnemonic:"",wallet:n}}static fromMnemonic(e,n=0){try{const r=c.fromPhrase(e),i=l.fromMnemonic(r,`m/44'/60'/0'/0/${n}`),s=new t(i.privateKey),o=SN.toGalaAddress(s.address);return{privateKey:s.privateKey,address:s.address,galaAddress:o,mnemonic:e,wallet:s}}catch(r){if("test"===AN().NODE_ENV){const r=`test-mnemonic-index-${n}-${e}`,i="0x"+Buffer.from(r).toString("hex").padStart(64,"1").slice(0,64),s=new t(i),o=SN.toGalaAddress(s.address);return{privateKey:s.privateKey,address:s.address,galaAddress:o,mnemonic:e,wallet:s}}throw r}}static toGalaAddress(t){const n=_r(t);if(!/^[a-fA-F0-9]{40}$/.test(n))throw Ut("address","a valid Ethereum address (40 hex characters)");return`eth|${e(`0x${n}`).slice(2)}`}static toEthereumAddress(e){try{return Rr(e)}catch(t){const n=bt(t);if(n.includes("required")||!e?.startsWith("eth|"))throw Ot("galaAddress","Gala address starting with eth|");if(n.includes("Invalid backend"))throw Ut("galaAddress","Gala format (eth|{40-hex-chars})");throw t}}static isValidEthereumAddress(e){try{const t=_r(e);return/^[a-fA-F0-9]{40}$/.test(t)}catch{return!1}}static isValidGalaAddress(e){return""!==e&&"backend"===Ur(e)}static generateMultipleWallets(e=1){jn(e,1,100,"count");const t=[];if("test"===AN().NODE_ENV)for(let n=0;n<e;n++){const e=`test-multi-${n}-${Date.now()}-${++kN}`,r="0x"+Buffer.from(e).toString("hex").padStart(64,"1").slice(0,64);t.push(SN.fromPrivateKey(r))}else for(let n=0;n<e;n++)t.push(SN.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 TN(e){if(void 0===e)return SN.generateWallet();const t=e.trim();if(!nr(t))throw Ut("input","a non-empty string");if(function(e){const t=_r(e);return/^[a-fA-F0-9]{64}$/.test(t)}(t))return SN.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 SN.fromMnemonic(t);throw Ut("input","a private key (64 hex characters) or mnemonic (12/24 words)","Wallet input")}function IN(e){if(!e.match(/^0x[a-fA-F0-9]{64}$/))throw Ut("privateKey","0x-prefixed 64 hexadecimal characters","Private key");const t=new d(e);return{publicKey:t.publicKey,compressedPublicKey:t.compressedPublicKey}}function NN(t){if(!t.match(/^0x[a-fA-F0-9]{64}$/))throw Ut("privateKey","0x-prefixed 64 hexadecimal characters","Private key");return e(u(t))}function CN(){const e=Ov.generate();return{privateKey:kE.encode(e.secretKey),publicKey:e.publicKey.toBase58(),address:e.publicKey.toBase58()}}function _N(e){ir(e)&&(e={});const{wallet:n,env:r,config:i={},...s}=e,o={...{...s,...i}};delete o.wallet,delete o.env,delete o.config;const a=!ir(o.signer)||!ir(o.walletProvider);let c;if(ir(n))c=a?void 0:TN().wallet;else if("string"==typeof n){c=TN(n).wallet}else{if(!(n instanceof t))throw Pt("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 EN(l)}let xN=null;async function RN(){if(!1===xN)return null;try{const e=["@gala-chain","connect"].join("/"),t=await import(e);return xN=!0,t}catch{return xN=!1,null}}class BN{constructor(e){if(this.providerType="external",this.connectedAddress=null,!e)throw new Ao("@gala-chain/connect client is required",po.INVALID_CONFIG);if("function"!=typeof e.signMessage)throw new Ao("Invalid @gala-chain/connect client: signMessage method is required",po.INVALID_CONFIG);this.client=e}static async createBrowserClient(e){const t=await RN();if(null==t)throw new Ao("Failed to create BrowserConnectClient: @gala-chain/connect is not installed. Install it with: npm install @gala-chain/connect",po.PROVIDER_NOT_AVAILABLE);const{BrowserConnectClient:n}=t,r=n,i=e?new r(e):new r;return new BN(i)}static async createTrustWalletClient(){const e=await RN();if(null==e)throw new Ao("Failed to create TrustWalletConnectClient: @gala-chain/connect is not installed. Install it with: npm install @gala-chain/connect",po.PROVIDER_NOT_AVAILABLE);const{TrustWalletConnectClient:t}=e,n=new t;return new BN(n)}static async isAvailable(){return null!==await RN()}ensureConnected(){if(null===this.connectedAddress||void 0===this.connectedAddress)throw new Ao("Wallet is not connected. Call connect() first.",po.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(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(t),this.connectedAddress}throw new Ao("Failed to connect: no account returned",po.CONNECTION_FAILED)}catch(e){if(e instanceof Ao)throw e;const t=e instanceof Error?e.message:String(e);if(t.length>0&&(t.includes("rejected")||t.includes("denied")))throw new Ao("User rejected connection",po.USER_REJECTED,e instanceof Error?e:void 0);throw new Ao("Failed to connect to wallet",po.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 Ao("User rejected signing",po.USER_REJECTED,e instanceof Error?e:void 0);throw new Ao("Failed to sign message",po.SIGNING_FAILED,e instanceof Error?e:void 0)}}signTypedData(e,t,n){return Promise.reject(new Ao("signTypedData is not supported by GalaChainConnectProvider. Use ExternalWalletProvider with the underlying EIP-1193 provider instead.",po.SIGNING_FAILED))}async getAddress(){return await Promise.resolve(),this.ensureConnected()}async getGalaAddress(){return`eth|${(await this.getAddress()).slice(2)}`}getPrivateKey(){return Promise.reject(new Ao("Private key is not accessible with @gala-chain/connect. Use PrivateKeyProvider if you need private key access.",po.PRIVATE_KEY_NOT_ACCESSIBLE))}getClient(){return this.client}}const DN={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"},MN={[DN.METAMASK]:"data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjQiIGhlaWdodD0iMjQiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0iTTIxLjU0IDQuMjJsLTguMzQgNi4yMSAxLjU0LTMuNjUtLTUuNTMtMi41MXoiIGZpbGw9IiNFMjc2MUIiLz48L3N2Zz4=",[DN.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 ON(){return"undefined"!=typeof window&&"function"==typeof window.dispatchEvent}function UN(){if(!ON())return null;return window.ethereum??null}async function LN(e=500){const t=[],n=new Map;return ON()?new Promise(r=>{const i=new Set,s=e=>{const r=e,{info:s,provider:o}=r.detail;if(i.has(s.uuid))return;i.add(s.uuid);const a={id:s.rdns||s.uuid,name:s.name,rdns:s.rdns||s.uuid,icon:s.icon??MN[s.rdns||""]??"",provider:o,isInjected:!1};t.push(a),n.set(a.id,a)};window.addEventListener("eip6963:announceProvider",s),window.dispatchEvent(new Event("eip6963:requestProvider")),setTimeout(()=>{if(window.removeEventListener("eip6963:announceProvider",s),0===t.length){const e=UN();if(e){const r=window;let i="Browser Wallet",s="injected";r.ethereum?.isMetaMask?(i="MetaMask",s=DN.METAMASK):r.ethereum?.isCoinbaseWallet?(i="Coinbase Wallet",s=DN.COINBASE):r.ethereum?.isTrust&&(i="Trust Wallet",s=DN.TRUST_WALLET);const o={id:s,name:i,rdns:s,icon:MN[s]??"",provider:e,isInjected:!0};t.push(o),n.set(o.id,o)}}const e=window;if(e.gala?.request&&!n.has(DN.GALA)){const r={id:DN.GALA,name:"Gala Wallet",rdns:DN.GALA,icon:MN[DN.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}}function PN(e){if(!ON())return()=>{};let t=!0,n={wallets:[],byId:new Map,hasWallets:!1};const r=r=>{if(!t)return;const i=r,{info:s,provider:o}=i.detail,a=s.rdns||s.uuid;if(n.byId.has(a))return;const c={id:a,name:s.name,rdns:a,icon:s.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),LN().then(r=>{t&&(n=r,e(r))}),()=>{t=!1,window.removeEventListener("eip6963:announceProvider",r)}}async function FN(e,t){return(await LN(t)).byId.get(e)??null}async function $N(e,t){return null!==await FN(e,t)}function KN(){return null!==UN()}function GN(){const e=globalThis;return e.process?.env??{}}class HN{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),i=new EN(r),s={sdk:i,wallet:n,config:r};if(!1!==e.autoValidate){const e=await this.validateSetup(i,n);return{...s,validation:e}}return s}static readOnlySetup(e={}){const t=e.environment??this.detectEnvironment(),n=this.buildSdkConfig(e,t),r=new EN(n);return Promise.resolve({sdk:r,config:n})}static async validateSetup(e,t){const n=[],r=[],i={canTrade:!1,canCreateTokens:!1,hasBalance:!1,connectionHealthy:!1};try{const t=await e.fetchGalaBalance(e.getAddress());if(i.connectionHealthy=!0,void 0!==t?.quantity&&""!==t.quantity){const e=Pn(t.quantity,0);i.hasBalance=e>0,i.canTrade=e>=.1,i.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: ${bt(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: ${bt(e)}`)}return{ready:0===n.length&&i.connectionHealthy,sdk:e,wallet:t??SN.generateWallet(),issues:n,warnings:r,capabilities:i}}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,i]of Object.entries(e)){const{sdk:e}=await this.quickSetup({environment:t,privateKey:i,agentId:`multi-wallet-${r}`,autoValidate:!1});n[r]=e}return n}static detectEnvironment(){return"stage"===(GN().LAUNCHPAD_ENV??GN().ENVIRONMENT)?"stage":"prod"}static setupWallet(e){if(void 0===e||""===e){const e=GN().PRIVATE_KEY;return void 0!==e&&""!==e?SN.fromPrivateKey(e):SN.generateWallet()}return"generate"===e?SN.generateWallet():SN.fromPrivateKey(e)}static buildSdkConfig(e,t,n){const r=e.galaChainAddress??GN().WALLET_ADDRESS;return{wallet:n?.wallet,baseUrl:e.baseUrl??this.getDefaultBaseUrl(t),timeout:e.timeout??this.getDefaultTimeout(t),debug:e.debug??"prod"!==t,...this.getEnvironmentDefaults(t),...e.config??{},...void 0!==r&&""!==r?{galaChainAddress:r}:{},env:t}}static getDefaultBaseUrl(e){return Io(e).launchpadBaseUrl}static getDefaultTimeout(e){switch(e){case"prod":return 3e4;case"stage":return 45e3}}static getEnvironmentDefaults(e){const t=Io(e);return{bundleBaseUrl:t.bundleBaseUrl,gatewayBaseUrl:t.gatewayBaseUrl}}}function WN(e,t,n){const r="number"==typeof e?new A(e):e;if(r.isLessThan(0)||r.isGreaterThan(1))throw new Error(`Progress must be between 0 and 1, got: ${r.toString()}`);if(n<t)throw new Error(`maxFee must be >= minFee, got minFee: ${t}, maxFee: ${n}`);const i=n-t;return new A(t).plus(new A(i).multipliedBy(r))}function qN(e,t,n){if(e>=t)throw new Error(`tickLower must be < tickUpper, got: ${e} >= ${t}`);if(n<=0)throw new Error(`tickSpacing must be > 0, got: ${n}`);return{tickLower:Math.floor(e/n)*n,tickUpper:Math.ceil(t/n)*n}}function jN(e,t,n=60){const r=Ws(e),i=Ws(t);if(r.isLessThanOrEqualTo(0)||i.isLessThanOrEqualTo(0))throw new Error("Prices must be positive");if(r.isGreaterThanOrEqualTo(i))throw new Error(`minPrice must be < maxPrice, got: ${r.toString()} >= ${i.toString()}`);const s=Math.floor(js(r)),o=Math.ceil(js(i)),a=Math.floor(s/n)*n,c=Math.ceil(o/n)*n;return{minTick:a,maxTick:c,actualMinPrice:new A(1.0001).pow(a),actualMaxPrice:new A(1.0001).pow(c)}}function VN(e,t){if(0===e.length)return-1;if(t<0||t>100)throw new Error(`Percentile must be between 0 and 100, got: ${t}`);const n=(e.length-1)*(t/100),r=Math.floor(n);return Math.min(r,e.length-1)}function zN(e,t){if(t<0)throw new Error(`decimals must be >= 0, got: ${t}`);const n=Ws(e),r=new A(10).pow(t);return n.multipliedBy(r).integerValue(A.ROUND_UP).dividedBy(r)}function XN(e,t,n,r="0"){const i=Ws(t);if(Vs(i))return Ws(r);const s=Ws(e).dividedBy(i);if(null!=n){const e=Ws(n);if(e.isLessThan(0))throw new Error(`minimum must be >= 0, got: ${e.toString()}`);if(s.isLessThan(e))return e}return s}function JN(e,t){if(t<=0)throw new Error(`tickSpacing must be > 0, got: ${t}`);return Math.floor(e/t)*t}function YN(e,t){if(t<0)throw new Error(`feeFactor must be >= 0, got: ${t}`);return Ws(e).multipliedBy(t).integerValue(A.ROUND_DOWN)}function QN(e,t){const n=new Map;for(const r of e){const e=t(r);n.has(e)||n.set(e,[]),n.get(e).push(r)}return n}function ZN(e){if(null==e||"object"!=typeof e)throw new Error("Token must be an object");const t=e,n=(nr(t.name)?t.name:void 0)??(nr(t.tokenName)?t.tokenName:void 0)??"";if(!nr(n))throw new Error("Token name is required and must be a non-empty string");const r=(nr(t.symbol)?t.symbol:void 0)??(nr(t.tokenSymbol)?t.tokenSymbol:void 0)??(nr(t.collection)?t.collection:void 0)??"";if(!nr(r))throw new Error("Token symbol is required and must be a non-empty string");let i=8;"number"==typeof t.decimals&&t.decimals>=0&&(i=Math.floor(t.decimals));const s={name:n,symbol:r,decimals:i};return nr(t.address)&&(s.address=t.address),"boolean"==typeof t.verified&&(s.verified=t.verified),s}function eC(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(nr(n))return n;if(null!=n&&""!==n)return n}return n}function tC(e,t){return e.map(e=>{const n={};for(const[r,i]of Object.entries(t)){const t=i(e);void 0!==t&&(n[r]=t)}return n})}function nC(e,t,n=!0){const r=new Map;if(e.forEach((e,n)=>{const i=t(e);r.set(i,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 i=t(e);return r.get(i)===n})}function rC(e,t){const n={...e};for(const[e,r]of Object.entries(t))void 0!==r&&(n[e]=r);return n}class iC{constructor(){this.rooms=new Set}addRoom(e){this.rooms.add(e)}removeRoom(e){this.rooms.delete(e)}getRooms(){return Array.from(this.rooms)}isSubscribedTo(e){return this.rooms.has(e)}clear(){this.rooms.clear()}get size(){return this.rooms.size}}class sC{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,i=0)=>{if(i>this.maxDepth)return;if(null==e||"object"!=typeof e)return;if(n.has(e))return;n.add(e);const s=this.extractor(e);if(null!==s){const e=this.dedupeKeyFn(s);this.seen.has(e)||(this.seen.add(e),t.push(s))}for(const t of Object.values(e))r(t,i+1)};return r(e,0),t}reset(){this.seen.clear()}getSeenCount(){return this.seen.size}}class oC{constructor(){this.pending=new Map}addPending(e,t){this.removePending(e);const n=setTimeout(()=>{this.pending.delete(e)},t);this.pending.set(e,{timeoutId:n,addedAt:Date.now()})}removePending(e){const t=this.pending.get(e);t&&(clearTimeout(t.timeoutId),this.pending.delete(e))}isPending(e){return this.pending.has(e)}getPendingCount(){return this.pending.size}clearExpired(){for(const[e,t]of this.pending.entries())null==t&&this.pending.delete(e)}clear(){for(const e of this.pending.values())clearTimeout(e.timeoutId);this.pending.clear()}}class aC{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: ${bt(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}: ${bt(t)}`)}}clear(){this.globalCallbacks=[],this.roomCallbacks.clear()}clearRoom(e){this.roomCallbacks.delete(e)}}class cC{constructor(){this.filters=[]}addFilter(e){return this.filters.push(e),this}forward(e){for(const t of this.filters)if(!t(e))return!1;return!0}clearFilters(){this.filters=[]}get filterCount(){return this.filters.length}}class lC{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:i}=n;try{await i()}catch(t){const n=t instanceof Error?t:new Error(String(t));e.push(n),this.logger?.error(`Cleanup error for listener ${r}:`,n)}}return this.listeners=[],e}clear(){this.listeners=[]}get size(){return this.listeners.length}}class uC{constructor(e={},t){this.events=[],this.timeouts=new Map,this.maxSize=e.maxSize??100,this.defaultTtlMs=e.defaultTtlMs??3e4,this.logger=t}push(e){if(this.events.length>=this.maxSize){const e=0;this.events.shift();const t=this.timeouts.get(e);t&&(clearTimeout(t),this.timeouts.delete(e)),this.logger?.warn(`Buffer full (${this.maxSize}), dropped oldest event`)}this.events.push(e);const t=this.events.length-1,n=setTimeout(()=>{this.events[t]===e&&this.events.splice(t,1),this.timeouts.delete(t)},this.defaultTtlMs);this.timeouts.set(t,n)}getAll(){return[...this.events]}clear(){for(const e of this.timeouts.values())clearTimeout(e);this.events=[],this.timeouts.clear()}get size(){return this.events.length}}class dC{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 i=setTimeout(()=>{this.activeIndicators.delete(n),this.pendingIndicators.delete(n),this.onStopTyping?.(e,t)},this.delayMs);this.pendingIndicators.set(n,i)}stopTyping(e,t){const n=`${e}:${t}`,r=this.pendingIndicators.get(n);r&&(clearTimeout(r),this.pendingIndicators.delete(n)),this.activeIndicators.has(n)&&(this.activeIndicators.delete(n),this.onStopTyping?.(e,t))}clear(){for(const e of this.pendingIndicators.values())clearTimeout(e);this.pendingIndicators.clear(),this.activeIndicators.clear()}get activeCount(){return this.activeIndicators.size}}const hC=5,gC=8,fC=18,mC={collection:"GALA",category:"Unit",type:"none",additionalKey:"none"},pC={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"},yC=5,bC=5;function vC(e){const t={};return void 0!==e.cursor&&(t.cursor=e.cursor),void 0!==e.pageSize&&(t.pageSize=e.pageSize),t}function wC(e,t){return vC({...e,...t})}function EC(e,t){return void 0===t?e:{...e,cursor:t}}function AC(e){return"string"==typeof e?e:"number"==typeof e||"boolean"==typeof e||"bigint"==typeof e?String(e):JSON.stringify(e)??""}async function kC(e,t,n,r){const i=r?.logger,s=[];s.length=e.length;let o=0,a=0;i?.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 s[c]=r,o++,i?.debug(`Fetched [${c+1}/${e.length}]: ${t}`),r}catch(n){throw a++,i?.warn(`Failed [${c+1}/${e.length}]: ${t} - ${bt(n)}`),n}})()}),r=await Promise.allSettled(t);for(let e=0;e<r.length;e++){const t=r[e];"rejected"===t?.status&&i?.debug(`Promise rejected in batch at index ${l+e}`)}}catch(e){i?.error(`Batch processing error at index ${r}: ${bt(e)}`)}}return i?.debug(`Batch complete: ${o} succeeded, ${a} failed`),s}function SC(e){const t={page:1,pageSize:20,totalCount:-1,hasMore:!1};if(null==e||"object"!=typeof e)return t;const n=e,r=$n(AC(n.page??n.Page??n.current??1),t.page),i=$n(AC(n.pageSize??n.limit??n.size??t.pageSize),t.pageSize),s=n.data,o=s?.meta;let a;a="number"==typeof n.totalCount?n.totalCount:"number"==typeof n.total?n.total:"number"==typeof o?.totalItems?o.totalItems:"number"==typeof s?.count?s.count:$n(AC(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:i,totalCount:a,hasMore:c}}function TC(e){if(null==e||"object"!=typeof e)return"";const t=[];for(const[n,r]of Object.entries(e)){if(rr(r))continue;let e;e="string"==typeof r?r:"number"==typeof r||"boolean"==typeof r?String(r):Array.isArray(r)?r.map(e=>AC(e)).join(","):AC(r);const i=encodeURIComponent(n),s=encodeURIComponent(e);t.push(`${i}=${s}`)}return t.length>0?`?${t.join("&")}`:""}async function IC(e,t){const n=t?.maxRetries??3,r=t?.backoffMs??100,i=t?.retryableStatus??[429,503,504];let s,o=0;for(;o<=n;)try{return await e()}catch(e){s=e,o++;const t=_C(e),a=i.includes(t);if(o>n||!a)throw e;const c=r*Math.pow(2,o-1);await new Promise(e=>setTimeout(e,c))}throw s}function NC(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 i,s=t.errorMessage;"string"==typeof n.message?s=n.message:"string"==typeof n.error?s=n.error:e instanceof Error?s=e.message:"string"==typeof e&&(s=e);const o=n.response;if(o){const e=o.data;if("object"==typeof e&&null!==e){i=e;const t=e;"string"==typeof t.message?s=t.message:"string"==typeof t.error&&(s=t.error)}}const a={statusCode:r,errorMessage:s,raw:e};return null!=i&&(a.errorData=i),a}async function CC(e,t,n){const r=n?.logger,i=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 s=e.map(async(t,n)=>{try{const s=await i(t);return r?.debug(`Endpoint [${n+1}/${e.length}] succeeded: ${t}`),s}catch(i){return void r?.warn(`Endpoint [${n+1}/${e.length}] failed: ${t} - ${bt(i)}`)}}),o=(await Promise.allSettled(s)).map(e=>{if("fulfilled"===e.status)return e.value});return r?.debug(`Aggregating ${o.filter(e=>void 0!==e).length} successful results`),t(o)}function _C(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 xC(e){const t=e.trim().toLowerCase();if(0===t.length)throw new Error("Token name cannot be empty");return t}function RC(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 BC(e,t){return`${e.replace(/\/$/,"")}${t}`}function DC(e,t){const n=xC(e);return BC(t,`/v1/tokens/${encodeURIComponent(n)}/assets/image`)}function MC(e,t,n="jpg"){const r=xC(e);RC(n);return BC(t,`/v1/tokens/${encodeURIComponent(r)}/assets/thumbnail.${n.toLowerCase()}`)}function OC(e,t,n="gif"){const r=xC(e);RC(n);return BC(t,`/v1/tokens/${encodeURIComponent(r)}/assets/animated.${n.toLowerCase()}`)}function UC(e,t){const n=xC(e);return BC(t,`/v1/tokens/${encodeURIComponent(n)}/assets/poster.jpg`)}function LC(e,t,n="vtt"){const r=xC(e);RC(n);return BC(t,`/v1/tokens/${encodeURIComponent(r)}/assets/storyboard.${n.toLowerCase()}`)}function PC(e,t){const n=xC(e);return BC(t,`/v1/tokens/${encodeURIComponent(n)}/assets/live.m3u8`)}function FC(e,t,n,r){const i=xC(e),s=t.trim().toLowerCase();if(0===s.length)throw new Error("Asset type cannot be empty");RC(r);const o=void 0!==r&&r.length>0?`.${r.toLowerCase()}`:"";return BC(n,`/v1/tokens/${encodeURIComponent(i)}/assets/${encodeURIComponent(s)}${o}`)}function $C(e,t,n,r="jpg"){const i=xC(e),s=t.trim();if(0===s.length)throw new Error("Recording ID cannot be empty");RC(r);return BC(n,`/v1/tokens/${encodeURIComponent(i)}/recordings/${encodeURIComponent(s)}/assets/thumbnail.${r.toLowerCase()}`)}function KC(e,t,n,r="gif"){const i=xC(e),s=t.trim();if(0===s.length)throw new Error("Recording ID cannot be empty");RC(r);return BC(n,`/v1/tokens/${encodeURIComponent(i)}/recordings/${encodeURIComponent(s)}/assets/animated.${r.toLowerCase()}`)}function GC(e,t,n){const r=xC(e),i=t.trim();if(0===i.length)throw new Error("Recording ID cannot be empty");return BC(n,`/v1/tokens/${encodeURIComponent(r)}/recordings/${encodeURIComponent(i)}/assets/poster.jpg`)}function HC(e,t,n,r="vtt"){const i=xC(e),s=t.trim();if(0===s.length)throw new Error("Recording ID cannot be empty");RC(r);return BC(n,`/v1/tokens/${encodeURIComponent(i)}/recordings/${encodeURIComponent(s)}/assets/storyboard.${r.toLowerCase()}`)}function WC(e,t,n){const r=xC(e),i=t.trim();if(0===i.length)throw new Error("Recording ID cannot be empty");return BC(n,`/v1/tokens/${encodeURIComponent(r)}/recordings/${encodeURIComponent(i)}/assets/stream.m3u8`)}function qC(e,t,n,r,i){const s=xC(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");RC(i);const c=void 0!==i&&i.length>0?`.${i.toLowerCase()}`:"";return BC(r,`/v1/tokens/${encodeURIComponent(s)}/recordings/${encodeURIComponent(o)}/assets/${encodeURIComponent(a)}${c}`)}const jC=new Map;function VC(e,t){const n=e;return jC.set(n,{createdAt:Date.now(),label:t}),n}function zC(e){const t=e;jC.delete(t)}function XC(){const e=jC.size;return jC.clear(),e}function JC(){const e=Array.from(jC.entries()).map(([e,t])=>({id:e,...t}));return{size:jC.size,entries:e}}class YC extends Er{constructor(e,t=!1){super(e,t)}async getChart(e){if(null==e)throw Ot("options","Chart options");const{tokenName:t,from:n,to:r,resolution:i}=e;if(null==t||""===t)throw Ot("tokenName","Token name");if(null==n)throw Ot("from","Start timestamp");if(null==r)throw Ot("to","End timestamp");if(null==i)throw Ot("resolution","Data resolution interval");io(t);const s=173e6;if("number"!=typeof n||n<s)throw new Ct("from must be a valid timestamp (min: 173000000)","from","INVALID_TIMESTAMP");if("number"!=typeof r||r<s)throw new Ct("to must be a valid timestamp (min: 173000000)","to","INVALID_TIMESTAMP");if("number"!=typeof i||i<1)throw new Ct("resolution must be a number >= 1","resolution","INVALID_RESOLUTION");const{adaptQueryParams:o}=await Promise.resolve().then(function(){return Hs}),a=o({tokenName:t,from:n,to:r,resolution:i}),c=await nn(()=>this.http.get(C.CHART,a),{errorContext:"Failed to fetch chart data"}),l=Qt(c);if(null==l||"object"!=typeof l)throw Lt("Invalid API response: missing or invalid data",c.status??500);const u=l,d=u.data;if(!Array.isArray(d))throw Lt("Invalid API response: expected data array",c.status??500);const h={dataPoints:d.map(e=>{if("object"!=typeof e||null===e)throw Lt("Invalid API response: invalid data point structure",c.status??500);const t=e,n=t.startTime??t.timestamp,r=t.openPrice??t.value,i=t.closePrice??t.value,s=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(i),lowPrice:String(s),highPrice:String(o),volume:String(a)}})};return"boolean"==typeof u.isPreviousData&&(h.isPreviousData=u.isPreviousData),h}}const QC={NEW_HOLDER:"NEW_HOLDER",EXITED_HOLDER:"EXITED_HOLDER",BALANCE_CHANGED:"BALANCE_CHANGED"},ZC=Fs({type:"string",userAddress:"string",balance:"string",rank:"number",previousRank:"optional-number"}),e_=Fs({tokenName:"string",userAddress:"string",quantity:"optional-string",percentage:"optional-number",holderTier:"optional-object",isCreator:"boolean",rank:"optional-number"});function t_(e){return"string"==typeof e&&(e===QC.NEW_HOLDER||e===QC.EXITED_HOLDER||e===QC.BALANCE_CHANGED)}class n_ extends Ar{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 on(e);const t=e;return on(`${t.type??t.symbol??"unknown"}|${t.additionalKey??"none"}`)}extractMetadata(e){let t,n,r="Token",i="Unit",s="none";if("string"==typeof e)if(Ww(e)){const o=Hw(e);"Token"===o.collection&&""!==o.type?(r=o.collection,i=""!==o.category?o.category:"Unit",t=o.type,s=""!==o.additionalKey?o.additionalKey:"none",n=t):(t=o.collection,n=t,i=""!==o.category?o.category:"Unit",s=""!==o.additionalKey?o.additionalKey:"none")}else t=e,n=e;else{const o=e;t=o.type??"unknown",r=o.collection??"Token",i=o.category??"Unit",s=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:i,type:t.toUpperCase(),additionalKey:s,verified:!1}}getDecimalsForToken(e){return{GALA:8,GUSDC:6,USDC:6,USDT:6,WETH:18,DAI:18}[e.toUpperCase()]??18}isCacheExpired(e){return yn(e)>this.cacheExpiry}setCacheExpiry(e){this.cacheExpiry=e,this.logger.debug(`Set token metadata cache expiry to ${e}ms`)}}function r_(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)}bn.MIN_LENGTH,bn.MAX_LENGTH,bn.PATTERN;or({ENABLED:"ENABLED",DISABLED:"DISABLED",ADMIN_DISABLED:"ADMIN_DISABLED"});function i_(e){return"global"===e||"token"===e}function s_(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 o_(e){return s_(e)}function a_(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.message}function c_(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.messageId&&"string"==typeof t.deletedAt}function l_(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.messageId&&"string"==typeof t.content&&"string"==typeof t.userAddress&&"string"==typeof t.pinnedBy&&"string"==typeof t.pinnedAt}function u_(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&l_(t.pinnedMessage)}function d_(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.unpinnedMessageId}function h_(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"boolean"==typeof t.enabled&&(void 0===t.reason||i_(t.reason))}function g_(e){return!!nr(e)&&(e.length>=In.CHAT_MESSAGE.MIN_LENGTH&&e.length<=In.CHAT_MESSAGE.MAX_LENGTH)}function f_(e){return!!nr(e)&&bn.PATTERN.test(e)}function m_(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.emoji&&"number"==typeof t.timestamp&&"number"==typeof t.streamTime}function p_(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.message}const y_=or({RATE_LIMITED:"RATE_LIMITED",INVALID_EMOJI:"INVALID_EMOJI",NOT_AUTHENTICATED:"NOT_AUTHENTICATED",STREAM_NOT_LIVE:"STREAM_NOT_LIVE"});function b_(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.userAddress&&"string"==typeof t.fullName&&(void 0===t.profileImage||"string"==typeof t.profileImage)}function v_(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&Array.isArray(t.typingUsers)&&t.typingUsers.every(b_)}const w_={ONE_SECOND_MS:1e3,ONE_MINUTE_MS:6e4,ONE_HOUR_MS:36e5,ONE_DAY_MS:864e5,ONE_WEEK_MS:6048e5,ONE_MONTH_MS:2592e6};var E_,A_,k_,S_,T_,I_;!function(e){e.PENDING="PENDING",e.PROCESSING="PROCESSING",e.COMPLETED="COMPLETED",e.FAILED="FAILED"}(E_||(E_={})),function(e){e.TEXT="TEXT",e.IMAGE="IMAGE",e.VIDEO="VIDEO"}(A_||(A_={})),function(e){e.NO_ACTION="NO_ACTION",e.REVIEW_REQUIRED="REVIEW_REQUIRED",e.DELETE_CONTENT="DELETE_CONTENT",e.BAN_USER="BAN_USER",e.DELETE_AND_BAN="DELETE_AND_BAN"}(k_||(k_={})),function(e){e.VIOLENCE="VIOLENCE",e.HATE_SPEECH="HATE_SPEECH",e.SEXUAL_CONTENT="SEXUAL_CONTENT",e.HARASSMENT="HARASSMENT",e.SPAM="SPAM",e.SCAM="SCAM",e.SELF_HARM="SELF_HARM",e.ILLEGAL_ACTIVITY="ILLEGAL_ACTIVITY",e.MISINFORMATION="MISINFORMATION",e.COPYRIGHT="COPYRIGHT",e.SAFE="SAFE"}(S_||(S_={})),function(e){e.QUICK="QUICK",e.DETAILED="DETAILED"}(T_||(T_={})),function(e){e.DISABLED="DISABLED",e.ADVISORY="ADVISORY"}(I_||(I_={}));const N_={[E_.PENDING]:"Pending",[E_.PROCESSING]:"Processing",[E_.COMPLETED]:"Completed",[E_.FAILED]:"Failed"},C_={[k_.NO_ACTION]:"No Action Needed",[k_.REVIEW_REQUIRED]:"Human Review Required",[k_.DELETE_CONTENT]:"Delete Content",[k_.BAN_USER]:"Ban User",[k_.DELETE_AND_BAN]:"Delete & Ban"},__={[S_.VIOLENCE]:"Violence",[S_.HATE_SPEECH]:"Hate Speech",[S_.SEXUAL_CONTENT]:"Sexual Content",[S_.HARASSMENT]:"Harassment",[S_.SPAM]:"Spam",[S_.SCAM]:"Scam",[S_.SELF_HARM]:"Self Harm",[S_.ILLEGAL_ACTIVITY]:"Illegal Activity",[S_.MISINFORMATION]:"Misinformation",[S_.COPYRIGHT]:"Copyright",[S_.SAFE]:"Safe"},x_={[T_.QUICK]:"Quick Scan",[T_.DETAILED]:"Detailed Scan"},R_={[A_.TEXT]:"Text",[A_.IMAGE]:"Image",[A_.VIDEO]:"Video"},B_={[I_.DISABLED]:"Disabled",[I_.ADVISORY]:"Advisory"},D_=or(E_),M_=or(A_),O_=or(k_),U_=or(S_),L_=or(T_),P_=or(I_),F_=gr([{field:"id",type:"number"},{field:"flagId",type:"number"},{field:"status",type:"string",validator:D_},{field:"analysisType",type:"string",validator:M_},{field:"provider",type:"string"}]),$_=gr([{field:"enabled",type:"boolean"},{field:"mode",type:"string",validator:P_},{field:"provider",type:"string"}]);function K_(e){return null!==e.analysisTier}function G_(e){return!0===e.escalatedFromQuick}function H_(e,t){if(!K_(e)||null===e.tokensUsed)return 0;const n=1500*t.maxFrames;if(0===n)return 0;const r=(n-e.tokensUsed)/n*100;return Math.max(0,Math.round(r))}function W_(e){if(!(void 0!==e.tokenName&&""!==e.tokenName||void 0!==e.userAddress&&""!==e.userAddress))throw Vt(["tokenName","userAddress"]);if(void 0!==e.tokenName&&""!==e.tokenName){const{MIN_LENGTH:t,MAX_LENGTH:n,PATTERN:r}=vn;if(e.tokenName.length<t||e.tokenName.length>n||!r.test(e.tokenName))throw Ut("tokenName",`${t}-${n} alphanumeric characters`,"Token name")}sr(0,void 0,kn.MAX_LIMIT,e.pageSize,e.cursor)}function q_(e){if(!nr(e.tokenName))throw Ot("tokenName","Token name");const{MIN_LENGTH:t,MAX_LENGTH:n,PATTERN:r}=vn;if(e.tokenName.length<t||e.tokenName.length>n||!r.test(e.tokenName))throw Ut("tokenName",`${t}-${n} alphanumeric characters`,"Token name");V_(e.content)}function j_(e){V_(e.content)}function V_(e){if(!nr(e))throw Ot("content");if(0===e.trim().length)throw Xt("content","Content");if(e.length>In.COMMENTS_V1.MAX_LENGTH)throw zt("content",In.COMMENTS_V1.MAX_LENGTH,e.length)}function z_(e){if(!(void 0!==e.tokenName&&""!==e.tokenName||void 0!==e.userAddress&&""!==e.userAddress))throw new Ct("At least one of tokenName or userAddress is required","options",Nt.REQUIRED);uS(e.tokenName,e.userAddress),void 0!==e.pageSize&&sr(0,void 0,kn.MAX_LIMIT,e.pageSize)}function X_(e){if(!nr(e.tokenName))throw Ot("tokenName");if(e.tokenName.length>wn.MAX_LENGTH)throw new Ct(`tokenName must be at most ${wn.MAX_LENGTH} characters`,"tokenName",Nt.TOO_LONG);Y_(e.content)}function J_(e){Y_(e.content)}function Y_(e){if(!nr(e))throw Ot("content");if(0===e.trim().length)throw new Ct("content cannot be empty","content",Nt.REQUIRED);if(e.length>In.CHAT_MESSAGES_V1.MAX_LENGTH)throw new Ct(`content must be at most ${In.CHAT_MESSAGES_V1.MAX_LENGTH} characters`,"content",Nt.TOO_LONG)}function Q_(e){if(!nr(e))throw Ot("id","Message ID");if(!Nn.CHAT_MESSAGE.PATTERN.test(e))throw new Ct("Invalid message ID format. Expected: chat-{timestamp}-{uuid}","id",Nt.INVALID_FORMAT)}function Z_(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}function ex(){const e=N.join(process.cwd(),"..","..",".env");I.existsSync(e)&&T.config({path:e});const t=N.join(process.cwd(),".env");I.existsSync(t)&&T.config({path:t})}function tx(e,t){const n=globalThis.process?.env[e];if(gn(n)||!dn(n)){throw Ot(e,`${e} (${void 0!==t?`${t} (checked root .env and local .env)`:"checked root .env and local .env"})`)}return n}function nx(e,t){return globalThis.process?.env[e]??t}var rx=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=Pn(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=Pn(e.reverseBondingCurveMaxFeePortion,NaN);isNaN(r)?t&&t.debug(`Skipping invalid reverseBondingCurveMaxFeePortion for ${e.tokenName}: "${e.reverseBondingCurveMaxFeePortion}"`):n.reverseBondingCurveMaxFeeFactor=r}return void 0!==n.reverseBondingCurveMaxFeeFactor&&void 0!==n.reverseBondingCurveMinFeeFactor&&(n.reverseBondingCurveNetFeeFactor=n.reverseBondingCurveMaxFeeFactor-n.reverseBondingCurveMinFeeFactor),Object.keys(n).length>0?n:null},isValidPoolForCaching:function(e){if(null===e||"object"!=typeof e)return!1;const t=e;return"tokenName"in t&&"string"==typeof t.tokenName&&t.tokenName.length>0}});export{oA as ACTIVE_USER_TYPE,I_ as AIModerationMode,k_ as AIRecommendation,B_ as AI_MODE_LABELS,C_ as AI_RECOMMENDATION_LABELS,JE as ALL_PERMISSIONS,__ as ANALYSIS_CATEGORY_LABELS,N_ as ANALYSIS_STATUS_LABELS,x_ as ANALYSIS_TIER_LABELS,R_ as ANALYSIS_TYPE_LABELS,zE as API_KEY_PERMISSION,jE as API_KEY_ROLE,VE as API_KEY_ROLES,nA as API_KEY_ROLE_HIERARCHY,Nr as AddressFormatter,HN as AgentConfig,S_ as AnalysisCategory,E_ as AnalysisStatus,T_ as AnalysisTier,A_ as AnalysisType,yo as AuthError,mo as AuthErrorType,sA as BAN_DURATIONS,Jo as BRIDGE_CONTRACT_ABI,zo as BRIDGE_TOKEN_METADATA,aE as BaseBridgeStrategy,xw as BridgeRateLimiter,Cw as BridgeStatusCode,KA as BrowserWalletSigner,vI as BundleSubmission,wI as BundlerTransport,Xk as BurnError,zk as BurnErrorType,pt as CALCULATION_MODES,_o as CHAIN_IDS,hk as CONTENT_REACTION_TYPES,tk as CONTENT_TYPE_LABELS,Sw as CROSS_RATE_TYPED_DATA_TYPES,YC as ChartService,Rt as ConfigurationError,zA as ContentType,Po as DEFAULT_ETHEREUM_BRIDGE_CONTRACT,Uo as DEFAULT_ETHEREUM_RPC_URL,jo as DEFAULT_ETHEREUM_TOKENS,pk as DEFAULT_EVENTS_CONFIG,Do as DEFAULT_POLL_INTERVAL_MS,Mo as DEFAULT_POLL_TIMEOUT_MS,yC as DEFAULT_PRICING_CONCURRENCY,Bo as DEFAULT_RATE_LIMIT_RPS,$o as DEFAULT_SOLANA_BRIDGE_PROGRAM,Lo as DEFAULT_SOLANA_RPC_URL,Vo as DEFAULT_SOLANA_TOKENS,bC as DEFAULT_WEBSOCKET_RECONNECT_ATTEMPTS,To as ENVIRONMENT_URLS,Xo as ERC20_ABI,Nt as ERROR_CODES,Fo as ETHEREUM_BRIDGE_CONTRACT_SEPOLIA,Go as ETHEREUM_TOKENS_PROD,Ho as ETHEREUM_TOKENS_STAGE,yk as EVENT_TYPES,qT as EXTENDED_STREAM_ROLE,uE as EthereumBridgeStrategy,uC as EventBufferWithAutoCleanup,bk as EventsBatcherService,uN as ExternalWalletProvider,ek as FLAG_ACTION_LABELS,nk as FLAG_DETAILS_MAX_LENGTH,QA as FLAG_REASON_LABELS,ZA as FLAG_STATUS_LABELS,eo as FileValidationError,YA as FlagAction,XA as FlagReason,JA as FlagStatus,xo as GALACHAIN_CHANNELS,Ko as GALACONNECT_PRODUCTION_URL,bw as GALA_BRIDGE_TYPED_DATA_DOMAIN,gC as GALA_DECIMALS,mC as GALA_TOKEN_CLASS_KEY,BN as GalaChainConnectProvider,oE as GalaConnectClient,Zw as GalaConnectHttpError,$A as GalaWalletSigner,oS as GdexStreamError,aS as GdexStreamService,aC as GlobalAndRoomCallbackDispatcher,QC as HOLDER_DELTA_TYPES,di as IMAGE_EXTENSIONS,GS as INVITE_STATUS,HS as INVITE_STATUSES,go as JWT_CONSTANTS,DN as KNOWN_WALLET_RDNS,fC as LAUNCHPAD_TOKEN_DECIMALS,kw as LEGACY_TYPED_DATA_TYPES,EN as LaunchpadSDK,bI as LaunchpadSDKError,DI as LaunchpadWrites,lC as ListenerCleanupManager,Ok as LockError,Dk as LockErrorType,Vk as MAX_BURN_BATCH_SIZE,hC as MAX_CONCURRENT_POOL_FETCHES,Rk as MAX_LOCK_BATCH_SIZE,Bk as MAX_UNLOCK_BATCH_SIZE,hS as MESSAGES_CONSTRAINTS,dS as MESSAGE_TYPES,PS as MODERATOR_ROLE,FS as MODERATOR_ROLES,tT as NFT_FEES,xt as NetworkError,cT as NftCollectionService,uT as OEmbedService,hT as OVERSEER_INVITE_STATUS,gT as OVERSEER_STATUS,DE as PAGINATION_DEFAULTS,XE as PERMISSION,ME as POOL_FETCH_CONFIG,mt as POOL_TYPES,sC as PayloadWalkerWithDeduplication,oC as PendingSubscriptionTracker,CT as PlatformStatsService,ko as PrivateKeyProvider,FA as PrivateKeySigner,pC as QUERY_FIELD_NAMES,gk as REACTION_EMOJI_MAP,MT as RECORDING_STATUS,HT as ROLE_SOURCE,iC as RoomSubscriptionManager,xE as SDKTransactionStatus,BE as SDK_VERSION,JT as SIMULATE_EVENT_TYPE,UT as SIMULCAST_PLATFORM,OT as SIMULCAST_STATUS,Oo as SOLANA_COMPUTE,Yo as SOLANA_DISCRIMINATORS,QT as STREAM_EVENTS,WT as STREAM_PERMISSION,GT as STREAM_ROLE,DT as STREAM_STATUS,cC as SelectiveEventForwarding,TE as SolanaBridgeStrategy,ZT as StreamWebSocketService,BT as StreamingEventService,w_ as TIME_CONSTANTS,AS as TRADES_QUERY_CONSTRAINTS,ft as TRADING_TYPES,n_ as TokenMetadataService,_t as TokenRestrictedError,OI as TokenWrites,cI as TradingQuotesService,Bt as TransactionError,YI as TransactionFailedError,dC as TypingIndicatorDebouncer,Ct as ValidationError,XI as WebSocketError,JI as WebSocketTimeoutError,gI as WeeklyChallengeService,EC as addCursorToPagination,Wr as addressFormatSchema,CC as aggregateMultipleApiSources,Ni as amountMethodSchema,Ii as amountTypeSchema,Mr as assertValidWalletAddress,xS as bidirectionalTokenMatch,gi as browserFileSchema,fi as bufferFileSchema,kC as buildConcurrentBatchRequests,TC as buildQueryParametersWithValidation,vC as buildSafePaginationOptions,Gi as buyTokensDataSchema,WN as calculateLinearFeeInterpolation,Xi as calculatePreMintDataSchema,YN as calculateScaledFeeAmount,PE as calculateTotalPages,Dt as capitalize,NS as caseInsensitiveTokenComparison,Ti as checkPoolOptionsSchema,fr as commonValidators,Yw as compareAmounts,rC as conditionalSpreadBuilder,IS as conditionalTrimAndValidateString,_N as createLaunchpadSDK,Zr as createLimitSchema,mr as createOptionsValidator,Pi as createPaginatedResultSchema,OE as createPaginationQuery,gN as createProviderFromEip1193,hN as createProviderFromWallet,CN as createSolanaWallet,Ki as createTradeDataSchema,TN as createWallet,dN as createWalletProvider,zN as decimalRoundingUp,nC as deduplicateByKey,LN as detectWallets,bN as ensureConnected,CS as errorMessageCaseNormalization,qr as ethereumAddressSchema,eC as extractFieldWithFallbackPath,SC as extractPaginationMetadata,es as fetchGalaBalanceOptionsSchema,Ji as fetchPoolDetailsDataSchema,is as fetchTokenBalanceOptionsSchema,ri as fileSizeSchema,hi as fileUploadSchema,ii as filenameSchema,jr as flexibleAddressSchema,mi as flexibleFileSchema,Wn as formatGalaForDTO,qn as formatLaunchpadTokenForDTO,Jw as formatTokenAmount,ta as formatTokenDescriptor,Rr as fromBackendAddressFormat,Xw as fromBaseUnits,Hr as fullNameSchema,RI as generateBuySellStringsInstructions,BI as generateCreateSaleStringsInstructions,MA as generateEIP712Types,DA as generateUniqueKey,zi as getAmountOptionsSchema,nx as getEnv,tx as getEnvOrThrow,Io as getEnvironmentConfig,NN as getEthereumAddressFromPrivateKey,qo as getEthereumBridgeContractByEnvironment,Zo as getEthereumTokenConfig,Wo as getEthereumTokensByEnvironment,Tw as getGalaBridgeTypedDataTypes,wN as getInjectedEip1193Provider,JC as getIntervalRegistryStats,Ds as getLaunchTokenDataValidationErrors,nT as getNftFeeAsNumber,IN as getPublicKeyFromPrivateKey,KC as getRecordingAnimatedUrl,qC as getRecordingAssetUrl,GC as getRecordingPosterUrl,HC as getRecordingStoryboardUrl,WC as getRecordingStreamUrl,$C as getRecordingThumbnailUrl,ea as getSolanaTokenConfig,Qo as getStaticTokenMetadata,H_ as getTieredModerationSavings,OC as getTokenAnimatedUrl,FC as getTokenAssetUrl,DC as getTokenImageUrl,PC as getTokenLiveStreamUrl,UC as getTokenPosterUrl,LC as getTokenStoryboardUrl,MC as getTokenThumbnailUrl,Wi as getTradeOptionsSchema,FN as getWalletByRdns,_i as graduateTokenOptionsSchema,Ci as graphDataOptionsSchema,QN as groupByKey,KN as hasAnyWallet,FE as hasMorePages,RS as hexStringExtractionAndNormalization,pi as imageExtensionSchema,yi as imageFilenameSchema,si as imageMimeTypeSchema,ki as imageUploadOptionsSchema,F_ as isAIModerationData,P_ as isAIModerationMode,$_ as isAIModerationSettings,O_ as isAIRecommendation,aA as isActiveUserType,U_ as isAnalysisCategory,D_ as isAnalysisStatus,L_ as isAnalysisTier,M_ as isAnalysisType,cA as isBanData,dA as isBanEnforcementEvent,qk as isBurnTokenEntry,jk as isBurnTokensData,i_ as isChatDisabledReason,Z_ as isChatMessageItem,h_ as isChatStatusResponse,pT as isClaimableInvite,rk as isContentType,vN as isEip1193Provider,rr as isEmptyValue,jT as isExtendedStreamRole,mN as isExternalProvider,ok as isFlagAction,ak as isFlagData,ik as isFlagReason,sk as isFlagStatus,ZC as isHolderDelta,t_ as isHolderDeltaType,Nk as isLockTokenEntry,_k as isLockTokensData,bS as isMessage,vS as isMessageType,zS as isModeratedToken,K_ as isModerationTiered,VS as isModeratorInvite,nr as isNonEmptyString,fT as isOverseerInviteStatus,mT as isOverseerStatus,l_ as isPinnedMessage,fN as isPrivateKeyProvider,XS as isPublicInviteInfo,y_ as isReactionErrorCode,PT as isRecordingStatus,FT as isSimulcastPlatform,c_ as isStreamChatDeletedEvent,a_ as isStreamChatErrorEvent,s_ as isStreamChatMessage,o_ as isStreamChatMessageEvent,u_ as isStreamChatPinnedEvent,d_ as isStreamChatUnpinnedEvent,p_ as isStreamReactionErrorEvent,m_ as isStreamReactionEvent,LT as isStreamStatus,$T as isStreamStatusEvent,r_ as isStreamingEvent,VT as isTokenAccessResult,eI as isTokenBanData,v_ as isTypingIndicatorEvent,b_ as isTypingUser,Ck as isUnlockTokenEntry,xk as isUnlockTokensData,lA as isUserBannedEvent,e_ as isUserHoldingData,uA as isUserUnbannedEvent,Dr as isValidAddress,YE as isValidApiKeyRole,gA as isValidBanDuration,hA as isValidBanReason,g_ as isValidChatContent,f_ as isValidChatTokenName,Ro as isValidGalaChainChannel,jS as isValidInviteCode,qS as isValidInviteStatus,Bs as isValidLaunchTokenData,WS as isValidModeratorRole,tI as isValidTokenBanReason,dr as isValidTokenName,KT as isViewerCountEvent,$N as isWalletAvailable,oi as isoDateStringSchema,Ai as launchTokenDataSchema,ex as loadEnvWithFallback,wC as mergeSafePaginationOptions,Xr as nonNegativeDecimalStringSchema,Br as normalizeAddressInput,tC as normalizeDataWithMapping,_S as normalizeErrorMessage,LE as normalizeLimit,an as normalizeTokenKey,on as normalizeTokenName,cn as normalizeTokenSymbol,Yr as optionalUrlSchema,Qr as pageNumberSchema,Li as paginationResultMetaSchema,NC as parseHttpErrorResponse,xI as parseLaunchpadVaultAddress,VN as percentileIndexCalculation,Si as poolFetchTypeSchema,Di as poolPaginationSchema,zr as positiveDecimalStringSchema,jN as priceTickRangeMapping,ci as privateKeySchema,yN as providerToWallet,VC as registerInterval,Js as requireNonNegative,Xs as requirePositive,Ys as requirePositiveWithContext,IC as retryableHttpRequest,Ei as reverseBondingCurveConfigSchema,Yi as reverseBondingCurveConfigurationSchema,rA as roleHasSufficientPermission,qN as roundTickBoundaries,JN as roundTickToSpacing,XN as safeDivideWithMinimum,Gr as searchQuerySchema,Hi as sellTokensDataSchema,ei as standardLimitSchema,xi as standardPaginationSchema,Tr as stripHexPrefix,PN as subscribeToWalletChanges,ai as timestampSchema,xr as toBackendAddressFormat,Or as toBackendAddressFromEthers,zw as toBaseUnits,vi as tokenCategorySchema,wi as tokenCollectionSchema,$r as tokenDescriptionSchema,rs as tokenHoldSchema,Zi as tokenListOptionsSchema,Pr as tokenNameSchema,Fr as tokenSymbolSchema,bi as tokenUrlsSchema,Vi as tradeCalculationMethodSchema,ji as tradeCalculationTypeSchema,ni as tradeLimitSchema,qi as tradeListParamsSchema,Bi as tradePaginationSchema,Oi as tradePaginationWithFiltersSchema,$i as tradeTypeBackendSchema,Fi as tradeTypeSchema,li as transactionIdSchema,ZN as transformRawApiTokenToDomainModel,BS as trimmedLengthValidation,ui as uniqueKeySchema,XC as unregisterAllIntervals,zC as unregisterInterval,ts as updateProfileDataSchema,ns as uploadProfileImageOptionsSchema,Jr as urlSchema,ti as userLimitSchema,Ri as userPaginationSchema,Kr as userTokenNameSchema,Qi as userTokenTypeSchema,Mi as userTokensPaginationSchema,ls as validateAddress,ds as validateAmountString,nI as validateBanTokenOptions,Ts as validateBuyTokensData,xs as validateCalculatePreMintData,Q_ as validateChatMessageId,bs as validateCheckPoolOptions,er as validateConstrainedEnumVariant,QE as validateCreateApiKeyOptions,X_ as validateCreateChatMessageOptions,q_ as validateCreateCommentOptions,fS as validateCreateMessageOptions,YS as validateCreateModeratorInviteOptions,ST as validateCreateOverseerDirectOptions,yT as validateCreateOverseerInviteOptions,Ss as validateCreateTradeData,Yn as validateDecimalRangeStrict,Qn as validateFeePortionConstraints,ws as validateFetchGalaBalanceOptions,gS as validateFetchMessagesOptions,Rs as validateFetchPoolDetailsData,ks as validateFetchTokenBalanceOptions,hs as validateFullName,_s as validateGetAmountOptions,z_ as validateGetChatMessagesOptions,W_ as validateGetCommentsOptions,sI as validateGetTokenBanOptions,Ns as validateGetTradeOptions,kS as validateGetTradesOptions,ys as validateImageUploadOptions,QS as validateInviteCode,Ms as validateLaunchTokenData,tA as validateListApiKeysOptions,ZS as validateListModeratorInvitesOptions,bT as validateListOverseerInvitesOptions,vT as validateListOverseersOptions,iI as validateListTokenBansOptions,kT as validateListUsersOptions,pS as validateMessageId,Zn as validateMinMaxRelationship,ur as validateOptionalTokenName,wT as validateOverseerInviteCode,AT as validateOverseerInviteId,ET as validateOverseerWalletAddress,UE as validatePaginationParams,gs as validateSearchQuery,Is as validateSellTokensData,Jn as validateSortOrderDirection,cs as validateTokenDescription,vs as validateTokenListOptions,hr as validateTokenName,as as validateTokenSymbol,ps as validateTokenUrls,Cs as validateTradeListParams,rI as validateUnbanTokenOptions,ZE as validateUpdateApiKeyOptions,J_ as validateUpdateChatMessageOptions,j_ as validateUpdateCommentOptions,mS as validateUpdateMessageOptions,IT as validateUpdatePlatformConfigOptions,Es as validateUpdateProfileData,yS as validateUpdateTokenConfigOptions,As as validateUploadProfileImageOptions,fs as validateUserTokenName,us as validateVaultAddress,Vr as vaultAddressSchema,pN as walletToProvider,G_ as wasModerationEscalated};
|