@gala-chain/launchpad-sdk 5.0.4-beta.1 → 5.0.4-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/README.md +5 -0
  2. package/dist/ai-docs.json +647 -290
  3. package/dist/index.cjs.js +1 -1
  4. package/dist/index.d.ts +4 -0
  5. package/dist/index.d.ts.map +1 -1
  6. package/dist/index.esm.js +1 -1
  7. package/dist/index.js +1 -1
  8. package/dist/src/LaunchpadSDK.d.ts +79 -0
  9. package/dist/src/LaunchpadSDK.d.ts.map +1 -1
  10. package/dist/src/constants/nft-fees.d.ts +30 -0
  11. package/dist/src/constants/nft-fees.d.ts.map +1 -0
  12. package/dist/src/constants/version.generated.d.ts +1 -1
  13. package/dist/src/index.d.ts +4 -0
  14. package/dist/src/index.d.ts.map +1 -1
  15. package/dist/src/schemas/files.d.ts +22 -22
  16. package/dist/src/schemas/files.d.ts.map +1 -1
  17. package/dist/src/schemas/launchpad.d.ts +45 -170
  18. package/dist/src/schemas/launchpad.d.ts.map +1 -1
  19. package/dist/src/schemas/pagination.d.ts +21 -103
  20. package/dist/src/schemas/pagination.d.ts.map +1 -1
  21. package/dist/src/schemas/primitives.d.ts +13 -6
  22. package/dist/src/schemas/primitives.d.ts.map +1 -1
  23. package/dist/src/schemas/trade.d.ts +53 -105
  24. package/dist/src/schemas/trade.d.ts.map +1 -1
  25. package/dist/src/schemas/user.d.ts +26 -170
  26. package/dist/src/schemas/user.d.ts.map +1 -1
  27. package/dist/src/schemas/validators.d.ts +21 -21
  28. package/dist/src/services/NftCollectionService.d.ts +123 -0
  29. package/dist/src/services/NftCollectionService.d.ts.map +1 -0
  30. package/dist/src/types/nft.dto.d.ts +155 -0
  31. package/dist/src/types/nft.dto.d.ts.map +1 -0
  32. package/dist/src/utils/nft-helpers.d.ts +62 -0
  33. package/dist/src/utils/nft-helpers.d.ts.map +1 -0
  34. package/package.json +12 -8
package/dist/index.cjs.js CHANGED
@@ -1 +1 @@
1
- "use strict";var e=require("ethers"),t=require("axios"),n=require("@gala-chain/connect"),r=require("zod"),i=require("bignumber.js"),o=require("uuid"),s=require("@gala-chain/api"),a=require("socket.io-client"),c=require("@gala-chain/dex"),u=require("node:crypto"),l=require("path"),h=require("fs"),d=require("dotenv"),f=require("crypto");function g(e){var t=Object.create(null);return e&&Object.keys(e).forEach(function(n){if("default"!==n){var r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:function(){return e[n]}})}}),t.default=e,Object.freeze(t)}var p,m=g(u),y=g(l),w=g(h),b=g(d);if("undefined"==typeof File){const{File:e}=require("web-file-polyfill");global.File=e}function k(e,n=3e4){return t.create({baseURL:e,timeout:n,headers:{"Content-Type":"application/json"}})}exports.AuthErrorType=void 0,(p=exports.AuthErrorType||(exports.AuthErrorType={})).WALLET_NOT_CONNECTED="WALLET_NOT_CONNECTED",p.SIGNATURE_FAILED="SIGNATURE_FAILED",p.INVALID_ADDRESS="INVALID_ADDRESS",p.MESSAGE_GENERATION_FAILED="MESSAGE_GENERATION_FAILED";class v extends Error{constructor(e,t,n){super(t),this.type=e,this.originalError=n,this.name="AuthError"}}function S(e){return e instanceof Error}function A(e){return S(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 T(e){return S(e)||"object"==typeof e&&null!==e&&"stack"in e&&"string"==typeof e.stack?e.stack:void 0}function E(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 I(e){return"object"==typeof e&&null!==e&&"message"in e&&("response"in e||"request"in e||"config"in e)}function x(e,t){if(!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 C(e){if(!e||"object"!=typeof e)return"";const t=e.Message;return"string"==typeof t&&t.trim()?` - ${t}`:""}function N(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 B={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 _ extends Error{constructor(e,t,n){super(e),this.field=t,this.code=n,this.name="ValidationError"}}class P extends Error{constructor(e,t,n){super(e),this.statusCode=t,this.originalError=n,this.name="NetworkError"}}class R extends Error{constructor(e,t){super(e),this.field=t,this.name="ConfigurationError"}}class D extends Error{constructor(e,t,n){super(e),this.transactionId=t,this.code=n,this.name="TransactionError"}}class L extends Error{constructor(e,t,n){super(e),this.originalError=t,this.code=n,this.name="GSwapQuoteError"}}class O extends Error{constructor(e,t,n,r){super(e),this.originalError=t,this.transactionHash=n,this.code=r,this.name="GSwapSwapError"}}class U extends Error{constructor(e,t,n,r,i){super(e),this.originalError=t,this.tokenA=n,this.tokenB=r,this.code=i,this.name="GSwapPoolError"}}class M extends Error{constructor(e,t,n,r){super(e),this.originalError=t,this.walletAddress=n,this.code=r,this.name="GSwapAssetError"}}class F extends Error{constructor(e,t,n){super(e),this.originalError=t,this.code=n,this.name="GSwapPositionError"}}class $ extends _{constructor(e,t){super(e,"dexQuote","DEX_QUOTE_ERROR"),this.context=t,this.name="DexQuoteError"}}class q extends _{constructor(e){super(e,"dexPool","DEX_POOL_NOT_FOUND"),this.name="DexPoolNotFoundError"}}function K(e,t){return t||e.charAt(0).toUpperCase()+e.slice(1)}function G(e,t){return new _(`Token "${e}" not found. Please verify the token name is correct.`,"tokenName","TOKEN_NOT_FOUND")}function z(e,t){const n=K(e,t);return new _(`${n} is required`,e,"REQUIRED")}function W(e,t,n){const r=K(e,n);return new _(`${r} must be ${t}`,e,"INVALID_FORMAT")}function H(e,t,n){return new P(e,t,n)}function j(e,t){return new R(e,t)}function V(e,t,n){return new D(e,t,n)}function X(e,t,n,r){return n&&n.error(`${t}:`,e),H(`${t}: ${A(e)}`,r,S(e)?e:void 0)}function Q(e,t,n,r,i){const o=K(e,i);return new _(`${o} must be between ${t} and ${n}${void 0!==r?`, received: ${r}`:""}`,e,"OUT_OF_RANGE")}function J(e,t,n,r){const i=K(e,r);return new _(`${i} must be at least ${t}${void 0!==n?`, received: ${n}`:""}`,e,"TOO_SMALL")}function Y(e,t,n,r){const i=K(e,r);return new _(`${i} must be at most ${t}${void 0!==n?`, received: ${n}`:""}`,e,"TOO_LARGE")}function Z(e,t,n,r){const i=K(e,r),o=void 0!==n?`, received: ${"object"==typeof n?"object":String(n)}`:"";return new _(`${i} must be ${t}${o}`,e,"INVALID_TYPE")}function ee(e,t,n){const r=K(e,n);return new _(`${r} must be a valid number${void 0!==t?`: "${t}"`:""}`,e,"INVALID_NUMBER")}function te(e){return new _(`Liquidity position not found: ${e}`,"positionId","POSITION_NOT_FOUND")}function ne(e,t,n,r){const i=K(e,r);return new _(`Invalid ${i}: ${t}. Must be one of: ${n.join(", ")}`,e,"INVALID_ENUM")}function re(e,t,n,r){const i=K(e,r);return new _(`${i} must be at most ${t} characters${void 0!==n?`, received: ${n}`:""}`,e,"TOO_LONG")}function ie(e,t){const n=K(e,t);return new _(`${n} cannot be empty`,e,"EMPTY_STRING")}function oe(e,t,n,r){if("number"!=typeof e)throw Z(r,"a number",e,r);if(e<t||e>n)throw Q(r,t,n,e)}function se(e,t,n){if("string"!=typeof e)throw Z(n,"a string",e,n);if(e.length>t)throw Y(n,t,e.length)}function ae(e,t){if("number"!=typeof e)throw Z(t,"a number",e,t);if(!Number.isInteger(e))throw Z(t,"an integer",e,t);if(e<=0)throw J(t,1,e,t)}function ce(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 Z(n,"numeric values",void 0,n);if(r>i)throw new _(`Minimum value (${r}) must be less than or equal to maximum value (${i}) for ${n}`,n,B.INVALID_RANGE)}function ue(e,t,n=!1){if("string"!=typeof e)throw Z(t,"a string",e,t);if(!n&&0===e.trim().length)throw z(t,`${t} (non-empty string)`)}function le(e,t){if("ASC"!==e&&"DESC"!==e)throw new _(`${t} must be either 'ASC' or 'DESC'`,t,"INVALID_ENUM_VALUE")}function he(e,t,n){const r="string"==typeof e?parseFloat(e):e,i="string"==typeof t?parseFloat(t):t;if(!isFinite(r))throw new _(`${n} minFee must be a valid finite number`,n,"INVALID_FEE_MINIMUM");if(!isFinite(i))throw new _(`${n} maxFee must be a valid finite number`,n,"INVALID_FEE_MAXIMUM");if(r<.1)throw new _(`${n} minFee must be >= 0.1, received ${r}`,n,"INVALID_FEE_MINIMUM");if(i>.5)throw new _(`${n} maxFee must be <= 0.5, received ${i}`,n,"INVALID_FEE_MAXIMUM");if(r>i)throw new _(`${n} minFee (${r}) must be <= maxFee (${i})`,n,"INVALID_FEE_RANGE")}const de={MIN_LENGTH:3,MAX_LENGTH:20,PATTERN:/^[a-zA-Z0-9]{3,20}$/},fe={MIN_LENGTH:2,MAX_LENGTH:20,PATTERN:/^[a-zA-Z0-9]+$/},ge={MIN_LENGTH:1,MAX_LENGTH:50},pe=100,me=20,ye={MAX_LIMIT:50,DEFAULT_PAGE:1,DEFAULT_LIMIT:20},we=100,be={PATTERN:/^eth\|[0-9a-fA-F]{40}$/},ke={MAX_LENGTH:100},ve={COMMENT:{MAX_LENGTH:1e3},COMMENTS_V1:{MAX_LENGTH:2e3},CHAT_MESSAGE:{MIN_LENGTH:1,MAX_LENGTH:500,PATTERN:/^[\s\S]{1,500}$/},CHAT_MESSAGES_V1:{MAX_LENGTH:500},BAN_REASON:{MAX_LENGTH:500},DESCRIPTION:{MAX_LENGTH:255},TOKEN_DESCRIPTION:{MIN_LENGTH:1,MAX_LENGTH:500},FLAG_DETAILS:{MAX_LENGTH:1e3},CONTENT_ID:{MAX_LENGTH:100}},Se={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})$/}},Ae=60,Te=31536e3,Ee={MAX_LENGTH:64,PATTERN:/^(galaswap-operation-|galaconnect-operation-)/},Ie={PATTERN:/^[a-fA-F0-9]{64}$/},xe={STREAM_URL_PATTERN:/^(rtmps?|srt):\/\/.+/},Ce=50,Ne=1,Be=100,_e={FULL_NAME:{MIN_LENGTH:1,MAX_LENGTH:100,ALPHABETS_ONLY_PATTERN:/^[a-zA-Z]+(?:\s[a-zA-Z]+)?$/}};function Pe(e,t){if(Je(e))return t;try{return JSON.parse(e)}catch{return t}}function Re(e,t=0){if(Je(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 De(e,t,n){if(Ye(e))return t;if("number"==typeof e)return isNaN(e)?t:e;const r=Number(e);return isNaN(r)?t:r}function Le(e,t=0){if(Je(e))return t;if("bigint"==typeof e)try{return Number(e)}catch{return t}if("number"==typeof e)return isNaN(e)||!isFinite(e)?t:Math.floor(e);const n=parseInt(String(e),10);return isNaN(n)?t:n}function Oe(e,t,n){if(Ye(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 Ue(e,t="0"){if(Je(e))return new i(t);if(i.isBigNumber(e))return e.isNaN()?new i(t):e;try{const n=new i(e);return n.isNaN()||!n.isFinite()?new i(t):n}catch{return new i(t)}}function Me(e,t){if(Ye(e)||""===e)throw z(t);if(i.isBigNumber(e)){if(e.isNaN())throw ee(t,"NaN");return e}try{const n=new i(e);if(n.isNaN())throw ee(t,e);if(!n.isFinite())throw ee(t,e);return n}catch(n){if(n instanceof _)throw n;throw ee(t,e)}}function Fe(e,t=0){if(Ye(e))return t;if("number"==typeof e)return isNaN(e)?t:e;return Re(String(e).replace("%","").trim(),t)}function $e(e,t=18){const n=Re(e,0);if(0===n)return"0";return n.toFixed(t).replace(/\.?0+$/,"")}function qe(e){return $e(e,8)}function Ke(e){return $e(e,18)}var Ge;!function(e){e.DEBUG="DEBUG",e.INFO="INFO",e.WARN="WARN",e.ERROR="ERROR"}(Ge||(Ge={}));class ze{constructor(e){this.levelPriority={[Ge.DEBUG]:0,[Ge.INFO]:1,[Ge.WARN]:2,[Ge.ERROR]:3},this.debugEnabled=e.debug,this.context=e.context||"SDK",this.minLevel=e.minLevel||(e.debug?Ge.DEBUG:Ge.INFO)}debug(e,t){this.log(Ge.DEBUG,e,t)}info(e,t){this.log(Ge.INFO,e,t)}warn(e,t){this.log(Ge.WARN,e,t)}error(e,t){this.log(Ge.ERROR,e,t)}log(e,t,n){if(this.levelPriority[e]<this.levelPriority[this.minLevel])return;if(e===Ge.DEBUG&&!this.debugEnabled)return;const r=`[${(new Date).toISOString()}] [${this.context}] [${e}]`,i=this.getConsoleMethod(e);void 0!==n?S(n)?i(`${r} ${t}`,n.message,T(n)??""):i(`${r} ${t}`,n):i(`${r} ${t}`)}getConsoleMethod(e){switch(e){case Ge.DEBUG:return console.debug;case Ge.INFO:return console.info;case Ge.WARN:return console.warn;case Ge.ERROR:return console.error;default:return console.log}}child(e){return new ze({debug:this.debugEnabled,context:`${this.context}:${e}`,minLevel:this.minLevel})}isDebugEnabled(){return this.debugEnabled&&this.levelPriority[Ge.DEBUG]>=this.levelPriority[this.minLevel]}}const We=new ze({debug:!1,context:"DateUtils"});function He(e,t){if(!e)return new Date;if(e instanceof Date)return isNaN(e.getTime())?new Date:e;try{const n=new Date(e);return isNaN(n.getTime())?(We.warn(`Invalid date string received: "${e}". Using fallback.`),t||new Date):n}catch(t){return We.warn(`Date parsing error for "${e}":`,t),new Date}}function je(e){if(!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 Ve(e){return Date.now()-e}const Xe={ETH_ADDRESS:/^0x[0-9a-fA-F]{40}$/,BACKEND_ADDRESS:/^eth\|(0x)?[0-9a-fA-F]{40}$/,CLIENT_ADDRESS:/^client\|[a-zA-Z0-9_-]+$/};function Qe(e){return"string"==typeof e&&e.trim().length>0}function Je(e){return null==e||""===e}function Ye(e){return null==e}function Ze(e,t,n=100){if(void 0!==e&&ae(e,"page"),void 0!==t&&(ae(t,"limit"),t>n))throw new _(`limit must be at most ${n}`,"limit",B.TOO_LARGE)}function et(e){const t=Object.values(e);return e=>"string"==typeof e&&t.includes(e)}function tt(e){return Object.values(e)}function nt(e,t,n,r={}){const{description:i="parameter",treatEmptyAsNull:o=!0}=r,s=e[t],a=e[n],c=null!=s&&(!o||""!==s),u=null!=a&&(!o||""!==a);if(!c&&!u)throw j(`Either ${t} or ${n} must be provided (${i})`,n);if(c&&u)throw j(`Cannot provide both ${t} and ${n}. Provide exactly one (${i}).`,n);return{chosen:c?t:n,hasA:c,hasB:u}}function rt(e,t="tokenName",n=de){if(!Qe(e))throw z(t);const r=e.trim();if(0===r.length)throw z(t);if(r.length<n.MIN_LENGTH)throw Q(t,n.MIN_LENGTH,n.MAX_LENGTH,r.length,`${t} length`);if(r.length>n.MAX_LENGTH)throw Q(t,n.MIN_LENGTH,n.MAX_LENGTH,r.length,`${t} length`);if(!n.PATTERN.test(r))throw new _(`${t} must contain only alphanumeric characters`,t,B.INVALID_FORMAT)}function it(e,t="tokenName",n=de){if(null==e)throw z(t,t);if("string"!=typeof e)throw Z(t,"a string",e);const r=e.trim();if(0===r.length)throw z(t,t);if(!n.PATTERN.test(r))throw new _(`${t} must be ${n.MIN_LENGTH}-${n.MAX_LENGTH} alphanumeric characters`,t,B.INVALID_FORMAT)}function ot(e){return t=>{if(!t||"object"!=typeof t)return!1;const n=t;for(const{field:t,type:r,nullable:i=!1,optional:o=!1,validator:s}of e){const e=n[t];if((!o||void 0!==e)&&(!i||null!==e)){if(typeof e!==r)return!1;if(s&&!s(e))return!1}}return!0}}const st={requiredString:e=>t=>Ye(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(!Je(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(!Ye(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=>Ye(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(!Ye(n))return t.includes(n)?void 0:`${e} must be one of: ${t.join(", ")}`},requiredEnumValue:(e,t)=>n=>Ye(n)?`${e} is required`:t.includes(n)?void 0:`${e} must be one of: ${t.join(", ")}`,isoDate:e=>t=>{if(!Ye(t))return"string"!=typeof t?`${e} must be a string`:je(t)?void 0:`${e} must be a valid ISO 8601 date string`},walletAddress:(e,t=!1)=>n=>{if(Ye(n))return t?`${e} is required`:void 0;if("string"!=typeof n)return`${e} must be a string`;return Xe.ETH_ADDRESS.test(n)||Xe.BACKEND_ADDRESS.test(n)||Xe.CLIENT_ADDRESS.test(n)?void 0:`${e} must be a valid wallet address`}};function at(e){return!e||0===e.trim().length}function ct(e){return e?e.startsWith("0x")?e.slice(2):e:""}const ut={ETHEREUM:Xe.ETH_ADDRESS,ETHEREUM_NO_PREFIX:/^[a-fA-F0-9]{40}$/,BACKEND:Xe.BACKEND_ADDRESS,CLIENT:Xe.CLIENT_ADDRESS};class lt{toBackendFormat(e){if(!Qe(e))throw new _("Address is required and must be a string","address","REQUIRED");const t=ct(e);if(!/^[a-fA-F0-9]{40}$/.test(t))throw new _(`Invalid Ethereum address format. Expected 40 hex characters (with or without 0x prefix). Got: "${e}"`,"address","INVALID_FORMAT");return`eth|${t.toLowerCase()}`}toEthereumFormat(e){if(!Qe(e))throw new _("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 _(`Invalid backend address format. Expected "eth|{40-hex-characters}" or "eth|0x{40-hex-characters}". Got: "${e}"`,"address","INVALID_FORMAT");const n=t[1]?6:4;return`0x${e.substring(n)}`}normalizeInput(e){if(e){if(e.startsWith("eth|")){if(!ut.BACKEND.test(e))throw new _(`Invalid backend address format: "${e}"`,"address","INVALID_FORMAT");return e}return this.toBackendFormat(e)}}isValid(e){return!!Qe(e)&&(!!ut.ETHEREUM.test(e)||(!!ut.ETHEREUM_NO_PREFIX.test(e)||(!!ut.BACKEND.test(e)||!!ut.CLIENT.test(e))))}assertValid(e,t="address"){if(!this.isValid(e))throw new _(`${t} must be a valid wallet address (Ethereum or backend format)`,t,"INVALID_FORMAT")}detectFormat(e){return Qe(e)?ut.ETHEREUM.test(e)||ut.ETHEREUM_NO_PREFIX.test(e)?"ethereum":ut.BACKEND.test(e)?"backend":ut.CLIENT.test(e)?"client":null:null}normalize(e){if(e)return e.toLowerCase()}extractHex(e){if(e.startsWith("eth|"))return e.substring(4).toLowerCase();if(e.startsWith("0x"))return ct(e).toLowerCase();if(/^[a-fA-F0-9]{40}$/.test(e))return e.toLowerCase();throw new _(`Cannot extract hex from address: "${e}". Expected Ethereum or backend format.`,"address","INVALID_FORMAT")}}const ht=new lt,dt=ct;function ft(e){return ht.toBackendFormat(e)}function gt(e){return ht.toEthereumFormat(e)}function pt(e){return ht.normalizeInput(e)}function mt(e){return ht.isValid(e)}function yt(e,t="address"){ht.assertValid(e,t)}function wt(e){const t="string"==typeof e?e:e.address;return ht.toBackendFormat(t)}function bt(e){return ht.detectFormat(e)}var kt=Object.freeze({__proto__:null,AddressFormatter:lt,assertValidWalletAddress:yt,detectFormat:bt,fromBackendAddressFormat:gt,isValidAddress:mt,normalizeAddressInput:pt,stripHexPrefix:dt,toBackendAddressFormat:ft,toBackendAddressFromEthers:wt});class vt{constructor(e){if(this.wallet=e.wallet,this.messagePrefix=e.messagePrefix||"Create a GalaChain Wallet",void 0!==e.messagePrefix)try{ue(e.messagePrefix,"messagePrefix",!1)}catch{throw new v(exports.AuthErrorType.SIGNATURE_FAILED,"Message prefix cannot be empty")}}hasWallet(){return void 0!==this.wallet}setWallet(e){if(void 0!==e){if("object"!=typeof e||!("address"in e))throw new v(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Invalid wallet: must be an ethers Wallet instance or undefined");if(!e.address||"string"!=typeof e.address)throw new v(exports.AuthErrorType.INVALID_ADDRESS,"Wallet address is not available")}this.wallet=e}async generateSignature(){this.validateWallet();try{const e=Date.now(),t=`${this.messagePrefix} ${e}`,n=await this.wallet.signMessage(t);return{message:t,signature:n,address:this.formatAddress(this.wallet.address),timestamp:e}}catch(e){if(e instanceof v)throw e;throw new v(exports.AuthErrorType.SIGNATURE_FAILED,"Failed to generate signature for authentication",S(e)?e:new Error(A(e)))}}getAddress(){return this.validateWallet(),this.formatAddress(this.wallet.address)}getEthereumAddress(){return this.validateWallet(),this.wallet.address}getPrivateKey(){if(this.validateWallet(),!this.wallet.privateKey)throw new v(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Wallet private key not available for @gala-chain signing");return this.wallet.privateKey}formatAddress(e){try{return ft(e)}catch{throw new v(exports.AuthErrorType.INVALID_ADDRESS,`Invalid Ethereum address format: ${e}`)}}async signMessage(e){this.validateWallet();try{return{message:e,signature:await this.wallet.signMessage(e),address:this.wallet.address,timestamp:Date.now()}}catch(e){if(e instanceof v)throw e;throw new v(exports.AuthErrorType.SIGNATURE_FAILED,A(e),S(e)?e:new Error(A(e)))}}async generateAuthHeaders(e,t){this.validateWallet();try{const n=Date.now(),r=`${this.messagePrefix} ${t.toUpperCase()} ${e} ${n}`,i=await this.wallet.signMessage(r);return{"x-signature":i,"x-address":this.formatAddress(this.wallet.address),"x-message":r,"x-timestamp":n.toString()}}catch(e){if(e instanceof v)throw e;throw new v(exports.AuthErrorType.SIGNATURE_FAILED,"Failed to generate authentication headers",S(e)?e:new Error(A(e)))}}async signTypedData(e,t,n){this.validateWallet();try{return await this.wallet.signTypedData(e,t,n)}catch(e){if(e instanceof v)throw e;throw new v(exports.AuthErrorType.SIGNATURE_FAILED,"Failed to sign typed data",S(e)?e:new Error(A(e)))}}async generateCustomSignature(e){if(!Qe(e))throw new v(exports.AuthErrorType.SIGNATURE_FAILED,"Custom message must be a non-empty string");this.validateWallet();try{const t=await this.wallet.signMessage(e);return{message:e,signature:t,address:this.formatAddress(this.wallet.address),timestamp:Date.now()}}catch(e){if(e instanceof v)throw e;throw new v(exports.AuthErrorType.SIGNATURE_FAILED,"Failed to generate custom message signature",S(e)?e:new Error(A(e)))}}validateWallet(){if(!this.wallet)throw new v(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Wallet is required for authentication");if(!this.wallet.address)throw new v(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Wallet address is not available");if(!this.wallet.privateKey&&!this.wallet.signMessage)throw new v(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Wallet must have a private key for signing messages")}}const St={REFRESH_THRESHOLD_MS:3e5,DEFAULT_EXPIRY_S:86400,LOGIN_MESSAGE_PREFIX:"Sign in to Launchpad t:",AUTH_HEADER:"Authorization",BEARER_PREFIX:"Bearer "};class At{constructor(e=St.REFRESH_THRESHOLD_MS){this.tokenState=null,this.refreshThresholdMs=e}setToken(e,t){if(!Qe(e))throw new v(exports.AuthErrorType.SIGNATURE_FAILED,"JWT token must be a non-empty string");if("number"!=typeof t)throw new v(exports.AuthErrorType.SIGNATURE_FAILED,"Token expiration must be a positive finite number (seconds)");if(!isFinite(t))throw new v(exports.AuthErrorType.SIGNATURE_FAILED,"Token expiration must be a positive finite number (seconds)");if(t<=0)throw new v(exports.AuthErrorType.SIGNATURE_FAILED,"Token expiration must be a positive finite number (seconds)");const n=Date.now();this.tokenState={token:e.trim(),issuedAt:n,expiresAt:n+1e3*t}}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 e?`${St.BEARER_PREFIX}${e}`:null}getJwtHeaders(){const e=this.getAuthorizationHeader();if(!e)throw new v(exports.AuthErrorType.WALLET_NOT_CONNECTED,"No JWT token available. Call login() first.");return{[St.AUTH_HEADER]:e}}clear(){this.tokenState=null}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}}}const Tt="/launchpad/upload-image",Et="/launchpad/fetch-pool",It="/launchpad/check-pool",xt="/launchpad/get-graph-data",Ct="/holders",Nt="/launchpad/get-badge/",Bt="/launchpad/socials",_t="/trade/",Pt="/user/profile",Rt="/user/profile",Dt="/user/token-list",Lt="/user/token-hold",Ot="/v1/user/managed-tokens",Ut="/v1/users/referrals/url",Mt="/v1/users/referrals",Ft="/v1/users/referrals/summary",$t="/v1/registered",qt="/live/:tokenName/start",Kt="/live/:tokenName/stop",Gt="/live/:tokenName",zt="/live/:tokenName/disable",Wt="/live/:tokenName/enable",Ht="/live/:tokenName/reset-key",jt="/live/:tokenName/recordings",Vt="/live/:tokenName/recordings/:assetId/download",Xt="/live/:tokenName/recordings/:assetId",Qt="/live/:tokenName/simulcast",Jt="/live/:tokenName/simulcast",Yt="/live/:tokenName/simulcast/:targetId",Zt="/live/global/streaming/status",en="/live/global/streaming/disable",tn="/live/global/streaming/enable",nn="/live/:tokenName/stream/countdown",rn="/live/:tokenName/stream/countdown",on="/live/:tokenName/stream/language",sn="/live/:tokenName/role",an="/live/roles",cn="/live/:tokenName/access",un="/live/:tokenName/chat",ln="/live/:tokenName/chat",hn="/live/:tokenName/chat/:messageId",dn="/live/:tokenName/chat/status",fn="/live/:tokenName/chat/disable",gn="/live/:tokenName/chat/enable",pn="/live/:tokenName/chat/pinned",mn="/live/:tokenName/chat/pin",yn="/live/:tokenName/chat/pin",wn="/live/chat/global/status",bn="/live/chat/global/disable",kn="/live/chat/global/enable",vn="/live/:tokenName/engagement/stats",Sn="/auth/login",An="/auth/refresh",Tn="/auth/session",En="/live/:tokenName/bans",In="/live/:tokenName/bans",xn="/live/:tokenName/bans/:userAddress",Cn="/live/:tokenName/bans/:userAddress",Nn="/live/:tokenName/active-users",Bn={CREATE:"/v1/api-keys",LIST:"/v1/api-keys",GET:"/v1/api-keys/:id",UPDATE:"/v1/api-keys/:id",REVOKE:"/v1/api-keys/:id"},_n="/v1/moderators/invites",Pn="/v1/moderators/invites/claim",Rn="/v1/moderators/tokens",Dn="/v1/moderators/invites",Ln="/v1/moderators/invites/:id",On="/v1/moderators/invites/:id/role",Un="/v1/moderators/invites/code/:code",Mn={CREATE:"/v1/flags",LIST_GLOBAL:"/v1/flags/global",LIST:"/v1/flags/:tokenName",DISMISS:"/v1/flags/:id/dismiss",ACTION:"/v1/flags/:id/action"},Fn="/v1/overseer/invites",$n="/v1/overseer/invites",qn="/v1/overseer/invites/code/:code",Kn="/v1/overseer/invites/claim",Gn="/v1/overseer/invites/:id",zn="/v1/overseer",Wn="/v1/overseer/:address",Hn="/v1/overseer/me",jn="/v1/overseer/summary",Vn="/v1/overseer/users",Xn="/v1/overseer/users/:address",Qn="/v1/overseer/token-bans",Jn="/v1/overseer/token-bans",Yn="/v1/overseer/token-bans/:tokenName",Zn="/v1/overseer/token-bans/:tokenName",er="/token/comment",tr="/token/comment",nr="/token/comment/:commentId",rr="/reactions",ir="/reactions/:messageId/:reactionType",or="/v1/trades",sr="/v1/chat-messages",ar="/v1/chat-messages",cr="/v1/chat-messages/:id",ur="/v1/chat-messages/:id",lr="/v1/comments",hr="/v1/comments",dr="/v1/comments/:id",fr="/v1/comments/:id";function gr(e){return null!=e&&"object"==typeof e&&"data"in e}function pr(e,t,n=!1){const r=!0===e.error,i=n&&!e.data;if(r||i)throw H(e?.message||t)}function mr(e){if(gr(e))return e.data}function yr(e,t="No data found in response"){if(!gr(e))throw H(t);const n=e.data;if(null==n)throw H(t);return n}async function wr(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),X(e,t,n))}}function br(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),X(e,t,n))}}class kr{constructor(e,t,n,r=!1){this.http=e,this.signatureAuth=t,this.jwtAuth=n,this.refreshPromise=null,this.loginPromise=null,this.logger=new ze({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 v(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Wallet is required for login. Configure privateKey in SDK.");this.loginPromise=this.performLogin();try{return await this.loginPromise}finally{this.loginPromise=null}}async performLogin(){return wr(async()=>{const e=Date.now(),t=`${St.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();yt(r,"address");const i={address:r,message:t,signature:n.signature};this.logger.debug("Sending login request",{address:r,message:t});const o=await this.http.post(Sn,i),s=this.extractLoginData(o);return this.jwtAuth.setToken(s.accessToken,s.expiresIn),this.logger.debug("Login successful",{address:s.address,expiresIn:s.expiresIn}),s},"SessionAuthService.performLogin",this.logger,(e,t,n)=>{if(e instanceof v)throw e;throw new v(exports.AuthErrorType.SIGNATURE_FAILED,`Login failed: ${A(e)}`,S(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 v(exports.AuthErrorType.WALLET_NOT_CONNECTED,"No token to refresh. Call login() first.");this.refreshPromise=this.performRefresh();try{return await this.refreshPromise}finally{this.refreshPromise=null}}async performRefresh(){return wr(async()=>{this.logger.debug("Refreshing JWT token");const e=await this.http.post(An,{},this.jwtAuth.getJwtHeaders()),t=this.extractLoginData(e);return this.jwtAuth.setToken(t.accessToken,t.expiresIn),this.logger.debug("Token refreshed successfully",{address:t.address,expiresIn:t.expiresIn}),t},"SessionAuthService.performRefresh",this.logger,(e,t,n)=>{if(e instanceof v)throw e;throw new v(exports.AuthErrorType.SIGNATURE_FAILED,`Token refresh failed: ${A(e)}`,S(e)?e:void 0)})}logout(){this.logger.debug("Logging out"),this.jwtAuth.clear()}async getSession(){if(!this.jwtAuth.hasToken())throw new v(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Not authenticated. Call login() first.");return wr(async()=>{const e=await this.http.get(Tn,void 0,this.jwtAuth.getJwtHeaders());return this.extractSessionData(e)},"SessionAuthService.getSession",this.logger,(e,t,n)=>{if(e instanceof v)throw e;throw new v(exports.AuthErrorType.SIGNATURE_FAILED,`Failed to get session: ${A(e)}`,S(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 v(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Not authenticated. Call login() first.");if(this.jwtAuth.isExpired()){this.logger.debug("Token expired - 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 v(exports.AuthErrorType.SIGNATURE_FAILED,A(e)||"Authentication failed");const t=yr(e,"No data in authentication response"),{accessToken:n,expiresIn:r,address:i}=t;if(!Qe(n))throw new v(exports.AuthErrorType.SIGNATURE_FAILED,"Invalid access token in response");if(!r||"number"!=typeof r)throw new v(exports.AuthErrorType.SIGNATURE_FAILED,"Invalid expiration in response");return{accessToken:n,expiresIn:r,address:i}}extractSessionData(e){if(e.error)throw new v(exports.AuthErrorType.SIGNATURE_FAILED,A(e)||"Failed to get session");return yr(e,"No data in session response")}}function vr(e){if(Ye(e)||"object"!=typeof e)return{};const t={};for(const[n,r]of Object.entries(e))Ye(r)||(Qe(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}class Sr{constructor(e,t={}){this.auth=e,this.debug=t.debug??!1,this.logger=new ze({debug:this.debug,context:"HttpClient"});const n=t.baseUrl||"https://lpad-backend-dev1.defi.gala.com",r=t.timeout||3e4;this.axios=k(n,r),t.headers&&(this.axios.defaults.headers.common={...this.axios.defaults.headers.common,...t.headers}),this.setupInterceptors()}async request(e){return wr(async()=>{const t={method:e.method,url:e.url,data:e.data,...e.params&&{params:vr(e.params)},...e.headers&&{headers:e.headers},...e.timeout&&{timeout:e.timeout}};e.headers&&this.logger.debug("Custom headers provided:",e.headers),e.data instanceof FormData&&(t.headers&&t.headers["Content-Type"]&&delete t.headers["Content-Type"],this.logger.debug("FormData detected - removing Content-Type header for multipart upload"));const n=e.data instanceof FormData?"[FormData object - multipart/form-data]":e.data;this.logger.debug("Request:",{method:e.method,url:e.url,fullUrl:`${this.axios.defaults.baseURL}${e.url}`,baseURL:this.axios.defaults.baseURL,params:t.params,data:n,isFormData:e.data instanceof FormData,contentType:t.headers?.["Content-Type"]||"not set"});const r=await this.axios.request(t);return this.logger.debug("Response:",{status:r.status,data:r.data}),r.data},`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 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 wr(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)}async signWithGalaChain(e,t,r=n.SigningType.SIGN_TYPED_DATA){const i=this.auth.getPrivateKey(),o=new n.SigningClient(i);return await o.sign(e,t,r)}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 headers being sent:",e.headers),e},e=>Promise.reject(e)),this.responseInterceptorId=this.axios.interceptors.response.use(e=>e,e=>{if(e.response){const t={message:e.response.data?.message||A(e),error:e.response.data?.error,statusCode:e.response.status,details:e.response.data?.details,timestamp:e.response.data?.timestamp,path:e.response.data?.path};e.launchpadError=t,this.logger.error("Backend error:",t)}else e.request?this.logger.error("Network error:",e.message):this.logger.error("Request setup error:",e.message);return Promise.reject(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")}}const Ar="Token name is required and must be a string",Tr=e=>`Could not find vault address for token: ${e}`,Er=r.z.string().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"),Ir=r.z.string().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"),xr=r.z.string().min(1,"Token description is required").max(500,"Token description must be at most 500 characters"),Cr=r.z.string().min(1,"Token name must be at least 1 character").max(50,"Token name must be at most 50 characters"),Nr=r.z.string().min(1,"Search query must be at least 1 character").max(100,"Search query must be at most 100 characters"),Br=r.z.string().min(1,"Full name is required").max(100,"Full name must be at most 100 characters").regex(/^[a-zA-Z\s]+$/,"Full name can only contain letters and spaces"),_r=r.z.string().regex(Xe.BACKEND_ADDRESS,"Address must be in format: eth|[40-hex-chars]"),Pr=r.z.string().regex(Xe.ETH_ADDRESS,"Invalid Ethereum address format"),Rr=r.z.string().refine(e=>Xe.BACKEND_ADDRESS.test(e)||Xe.ETH_ADDRESS.test(e),"Address must be either eth|[40-hex-chars] or 0x[40-hex-chars] format").transform(e=>(new lt).normalizeInput(e)||e),Dr=r.z.string().refine(e=>Xe.BACKEND_ADDRESS.test(e)||/^service\|Token\$Unit\$[A-Z0-9]+\$eth:[0-9a-fA-F]{40}\$launchpad$/.test(e),"Invalid vault address format"),Lr=r.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>Re(e,0)>0,"Amount must be greater than zero"),Or=r.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>Re(e,0)>=0,"Amount must be zero or greater"),Ur=r.z.string().url("Must be a valid URL").regex(/^https?:\/\//,"URL must start with http:// or https://"),Mr=r.z.string().optional().refine(e=>!e||/^https?:\/\/.+\..+/.test(e),"Must be a valid URL if provided"),Fr=r.z.number().int("Page must be an integer").min(1,"Page must be at least 1").max(1e3,"Page must be at most 1000").default(1);function $r(e=100){return r.z.number().int("Limit must be an integer").min(1,"Limit must be at least 1").max(e,`Limit must be at most ${e}`).default(10)}const qr=$r(100),Kr=$r(20),Gr=$r(20),zr=r.z.number().int("File size must be an integer").min(1,"File must be at least 1 byte").max(10485760,"File must be at most 10MB"),Wr=r.z.string().max(255,"Filename must be at most 255 characters"),Hr=r.z.enum(["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"]),jr=r.z.string().datetime("Must be a valid ISO 8601 date string"),Vr=r.z.number().int("Timestamp must be an integer").min(0,"Timestamp must be non-negative"),Xr=r.z.string().regex(/^0x[a-fA-F0-9]{64}$/,"Private key must be format: 0x + 64 hex characters"),Qr=r.z.string().regex(/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/,"Transaction ID must be in UUID format"),Jr=r.z.string().regex(/^galaconnect-operation-[a-z0-9-]+$/,"Unique key must be format: galaconnect-operation-{unique-id}"),Yr=r.z.object({websiteUrl:Mr,telegramUrl:Mr,twitterUrl:Mr,instagramUrl:Mr,facebookUrl:Mr,redditUrl:Mr,tiktokUrl:Mr}).refine(e=>e.websiteUrl||e.telegramUrl||e.twitterUrl||e.instagramUrl||e.facebookUrl||e.redditUrl||e.tiktokUrl,"At least one social URL (website, telegram, twitter, instagram, facebook, reddit, or tiktok) is required"),Zr=r.z.string().min(1,"Token category must not be empty").default("Unit"),ei=r.z.string().min(1,"Token collection must not be empty").default("Token"),ti=r.z.object({minFeePortion:r.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal string").refine(e=>Re(e,0)>=.1,"Minimum fee must be >= 0.1").refine(e=>Re(e,0)<=.5,"Minimum fee must be <= 0.5"),maxFeePortion:r.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal string").refine(e=>Re(e,0)>=.1,"Maximum fee must be >= 0.1").refine(e=>Re(e,0)<=.5,"Maximum fee must be <= 0.5")}).refine(e=>Re(e.maxFeePortion,0)>=Re(e.minFeePortion,0),{message:"Maximum fee must be >= minimum fee",path:["maxFeePortion"]}),ni=r.z.object({tokenName:Er,tokenSymbol:Ir,tokenDescription:xr,tokenImage:r.z.union([r.z.instanceof(File),r.z.instanceof(Buffer),r.z.string().url("Token image must be a valid URL")]).optional(),preBuyQuantity:Or.default("0"),websiteUrl:Mr,telegramUrl:Mr,twitterUrl:Mr,instagramUrl:Mr,facebookUrl:Mr,redditUrl:Mr,tiktokUrl:Mr,tokenCategory:Zr,tokenCollection:ei,reverseBondingCurveConfiguration:ti.optional(),privateKey:Xr.optional()}),ri=r.z.object({file:r.z.union([r.z.instanceof(File),r.z.instanceof(Buffer)]),tokenName:Er}),ii=r.z.enum(["RECENT","POPULAR"]),oi=r.z.object({tokenName:Er.optional(),symbol:Ir.optional()}).refine(e=>e.tokenName||e.symbol,"At least one of tokenName or symbol is required"),si=r.z.enum(["NATIVE","MEME"]),ai=r.z.enum(["IN","OUT"]),ci=r.z.object({from:r.z.number().int("From timestamp must be an integer").min(173e6,"From timestamp must be at least 173000000"),to:r.z.number().int("To timestamp must be an integer").min(173e6,"To timestamp must be at least 173000000"),resolution:r.z.number().int("Resolution must be an integer").min(1,"Resolution must be at least 1"),tokenName:Er}),ui=r.z.object({tokenName:Er,slippageToleranceFactor:r.z.number().min(0).max(1).optional(),maxAcceptableReverseBondingCurveFeeSlippageFactor:r.z.number().min(0).max(1).optional(),privateKey:Xr.optional()}),li=[".png",".jpg",".jpeg",".gif",".webp",".svg"],hi=r.z.object({file:r.z.union([r.z.instanceof(File),r.z.instanceof(Buffer)]),name:Wr,size:zr,type:Hr}),di=r.z.instanceof(File).refine(e=>e.size>=1&&e.size<=10485760,"File size must be between 1 byte and 10MB").refine(e=>["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"].includes(e.type),"File must be a valid image type (PNG, JPG, JPEG, GIF, WebP, or SVG)").refine(e=>e.name.length<=255,"Filename must be at most 255 characters"),fi=r.z.instanceof(Buffer).refine(e=>e.length>=1&&e.length<=10485760,"Buffer size must be between 1 byte and 10MB"),gi=r.z.union([di,fi]),pi=r.z.enum([".png",".jpg",".jpeg",".gif",".webp",".svg"]),mi=Wr.refine(e=>{const t=e.slice(e.lastIndexOf(".")).toLowerCase();return li.includes(t)},`Filename must end with one of: ${li.join(", ")}`),yi=r.z.object({page:Fr,limit:qr}),wi=r.z.object({page:Fr,limit:Kr}),bi=r.z.object({page:Fr,limit:Gr}),ki=yi.extend({type:r.z.enum(["RECENT","POPULAR"]).optional(),tokenName:r.z.string().min(1).max(50).optional(),search:r.z.string().min(1).max(100).optional()}),vi=wi.extend({tokenName:r.z.string().min(1).max(50).optional(),search:r.z.string().min(1).max(100).optional()}),Si=bi.extend({tradeType:r.z.enum(["BUY","SELL"]).optional(),tokenName:r.z.string().min(1).max(50).optional(),userAddress:r.z.string().regex(/^(0x[a-fA-F0-9]{40}|eth\|[a-fA-F0-9]{40})$/).optional(),startDate:r.z.string().datetime().optional(),endDate:r.z.string().datetime().optional(),sortOrder:r.z.enum(["ASC","DESC"]).default("DESC")}),Ai=r.z.object({page:r.z.number().int().min(1),limit:r.z.number().int().min(1),total:r.z.number().int().min(0),totalPages:r.z.number().int().min(0),hasNext:r.z.boolean(),hasPrevious:r.z.boolean()});const Ti=r.z.enum(["all","DEFI","ASSET"]),Ei=wi.extend({type:Ti.optional(),address:Rr.optional(),search:Nr.optional(),tokenName:Cr.optional()}),Ii=r.z.object({address:Rr.optional(),refresh:r.z.boolean().optional()}),xi=r.z.object({profileImage:r.z.string(),fullName:Br,address:Rr,privateKey:Xr.optional()}),Ci=r.z.object({file:r.z.union([r.z.instanceof(File),r.z.instanceof(Buffer)]),address:Rr.optional(),privateKey:Xr.optional()}),Ni=r.z.object({created:r.z.number(),createdBy:r.z.string(),expires:r.z.number(),instanceId:r.z.string(),lockAuthority:r.z.string(),name:r.z.string(),quantity:r.z.string(),vestingPeriodStart:r.z.number()}),Bi=r.z.object({address:Rr,tokenId:r.z.union([r.z.string(),r.z.object({collection:r.z.string(),category:r.z.string(),type:r.z.string(),additionalKey:r.z.string()}),r.z.object({collection:r.z.string(),category:r.z.string(),type:r.z.string(),additionalKey:r.z.string(),instance:r.z.string()})]).optional(),tokenName:Cr.optional(),withExpired:r.z.boolean().optional()}).refine(e=>void 0!==e.tokenId||void 0!==e.tokenName,"At least one token identifier (tokenId or tokenName) is required"),_i=r.z.enum(["buy","sell"]),Pi=r.z.enum(["BUY","SELL"]),Ri=r.z.object({tradeType:_i,tokenAmount:Lr,vaultAddress:Dr,userAddress:Rr,slippageTolerance:Lr.optional(),deadline:r.z.number().int().positive().optional()}),Di=r.z.object({tokenSymbol:Ir,nativeTokenQuantity:Lr,expectedToken:Lr,maxAcceptableReverseBondingCurveFee:Or.default("0").optional()}),Li=r.z.object({tokenSymbol:Ir,tokenQuantity:Lr,expectedNativeToken:Lr,maxAcceptableReverseBondingCurveFee:Or.default("0").optional()}),Oi=bi.extend({tokenName:Cr.optional()}),Ui=r.z.object({page:r.z.number().int().min(1).max(1e3).default(1).optional(),limit:r.z.number().int().min(1).max(20).default(10).optional()}),Mi=r.z.enum(["NATIVE","MEME"]),Fi=r.z.enum(["IN","OUT"]),$i=r.z.object({type:Mi,method:Fi,vaultAddress:Dr,amount:Lr}),qi=r.z.object({nativeTokenQuantity:Lr}),Ki=r.z.object({vaultAddress:Dr}),Gi=r.z.object({minFeePortion:Lr,maxFeePortion:Lr});function zi(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.errors.map(e=>e.message)}}}const Wi=zi(Er),Hi=zi(Ir),ji=zi(xr),Vi=zi(Rr),Xi=zi(Dr),Qi=zi(Lr),Ji=zi(Br),Yi=zi(Nr),Zi=zi(Cr),eo=zi(ni),to=zi(Yr),no=zi(ri),ro=zi(oi),io=zi(Ei),oo=zi(Ii),so=zi(xi),ao=zi(Ci),co=zi(Bi),uo=zi(Ri),lo=zi(Di),ho=zi(Li),fo=zi(Oi),go=zi(Ui),po=zi($i),mo=zi(qi),yo=zi(Ki);function wo(e,t="0"){return Ue(e,t)}function bo(e,t){return void 0!==t?wo(e).toFixed(t):wo(e).toFixed()}function ko(e,t=.01){const n=wo(e),r=new i(1).minus(t);return n.multipliedBy(r)}function vo(e=.01){return new i(1).minus(e)}function So(e=.01){return new i(1).plus(e)}function Ao(e){const t=wo(e),n=Math.log(1.0001),r=t.toNumber();return Math.log(r)/n}function To(e,t=!1){const n=wo(e),r=new i(1).dividedBy(n);return t?r.toFixed():r}function Eo(){return new i(2).pow(96)}function Io(e,t){return i.min(wo(e),wo(t))}function xo(e,t){return i.max(wo(e),wo(t))}function Co(e){return wo(e).isZero()}function No(e){return wo(e).isGreaterThan(0)}function Bo(e){return wo(e).isLessThan(0)}function _o(e,t){return wo(e).isLessThan(wo(t))}function Po(e,t){return wo(e).multipliedBy(t).dividedBy(100)}function Ro(...e){e.forEach(e=>{if(e.isNaN())throw ee("value","NaN");if(!e.isFinite())throw Y("value","finite");if(e.isLessThanOrEqualTo(0))throw J("value","0",e.toString())})}function Do(...e){e.forEach(e=>{if(e.isNaN())throw ee("value","NaN");if(!e.isFinite())throw Y("value","finite");if(e.isLessThan(0))throw J("value","0",e.toString())})}function Lo(e,t,n){if(e.isNaN())throw ee(t,"NaN");if(!e.isFinite())throw Y(t,"finite");if(e.isLessThanOrEqualTo(0))throw J(t,"0",e.toString())}function Oo(e,t,n="0"){const r=wo(t);return Co(r)?wo(n):wo(e).dividedBy(r)}function Uo(e,t){return Math.floor(e/t)*t}class Mo{validate(e,t={}){const{allowZero:n=!0,minimum:r,maximum:i,maxDecimals:o=Mo.MAX_DECIMAL_PLACES,fieldName:s="amount"}=t;if(!Qe(e))throw new _(`${s} cannot be empty or whitespace-only. Provide a valid numeric string.`,s,"INVALID_NUMERIC_STRING");if(/[eE]/.test(e))throw new _(`${s} cannot use scientific notation. Use standard decimal format (e.g., "1000" instead of "1e3").`,s,"INVALID_NUMERIC_STRING");const a=Re(e,NaN);if(isNaN(a))throw new _(`${s} must be a valid numeric string. Received: "${e}"`,s,"INVALID_NUMERIC_STRING");if(!isFinite(a))throw new _(`${s} must be a finite number. Cannot be Infinity or -Infinity.`,s,"INVALID_NUMERIC_STRING");if(a<0)throw new _(`${s} must be non-negative. Received: "${e}"`,s,"INVALID_NUMERIC_STRING");if(!n&&0===a)throw new _(`${s} must be greater than zero. Received: "${e}"`,s,"INVALID_NUMERIC_STRING");const c=wo(e),u=c.decimalPlaces()??0;if(u>o)throw new _(`${s} cannot exceed ${o} decimal places. Received: ${u} decimal places`,s,"PRECISION_EXCEEDED");if(void 0!==r&&_o(c,r))throw new _(`${s} must be at least ${r}. Received: "${e}"`,s,"BELOW_MINIMUM");if(void 0!==i&&(l=i,wo(c).isGreaterThan(wo(l))))throw new _(`${s} cannot exceed ${i}. Received: "${e}"`,s,"EXCEEDS_MAXIMUM");var l}parseAmount(e,t="0"){return wo(e,t)}isValid(e,t={}){try{return e?(this.validate(e,t),!0):!1!==t.allowZero}catch{return!1}}formatAmount(e,t){return bo(e,t)}clampAmount(e,t,n){const r=wo(e),i=wo(t),o=wo(n);return function(e,t,n){const r=wo(e),i=wo(t),o=wo(n);return r.isGreaterThanOrEqualTo(i)&&r.isLessThanOrEqualTo(o)}(r,i,o)?bo(r):_o(r,i)?bo(i):bo(o)}}function Fo(e,t){throw new _(e.join("; "),t,"VALIDATION_ERROR")}function $o(e){const t=Wi(e);!t.success&&t.errors&&Fo(t.errors,"tokenName")}function qo(e){const t=ro(e);!t.success&&t.errors&&Fo(t.errors,"options")}function Ko(e){const t=ci.safeParse(e);var n;t.success||Fo((n=t.error.errors,Array.isArray(n)?n.map(e=>e&&"object"==typeof e&&"message"in e&&"string"==typeof e.message?e.message:String(e)).filter(Boolean):[]),"options")}function Go(e,t,n=!0){zo.validate(e,{fieldName:t,allowZero:n})}Mo.MAX_DECIMAL_PLACES=18,Mo.MIN_POSITIVE="0.00000000000000001";const zo=new Mo;const Wo={DEFAULT_PAGE:1,DEFAULT_LIMIT:10,BACKEND_MAX_PAGE_SIZE:20,SAFETY_MAX_PAGES:100};function Ho(e,t){return ae(e,"page"),ae(t,"limit"),(e-1)*t}function jo(e,t=1){return Math.max(t,Math.ceil(e||t))}function Vo(e,t=1,n=Wo.BACKEND_MAX_PAGE_SIZE){return Math.max(t,Math.min(n,Math.ceil(e||t)))}function Xo(e,t){if("number"!=typeof e||!Number.isInteger(e))throw Z("total","a non-negative integer",e);if(e<0)throw Q("total",0,1/0,e);if("number"!=typeof t||!Number.isInteger(t))throw Z("limit","a non-negative integer",t);if(t<0)throw Q("limit",0,1/0,t);return 0===t?1:0===e?0:Math.ceil(e/t)}function Qo(e,t,n){if("number"!=typeof e||!Number.isInteger(e))throw Z("offset","a non-negative integer",e);if(e<0)throw Q("offset",0,1/0,e);return e+t<n}function Jo(e,t){if(!e)return[];if(Array.isArray(e))return e;const n=e[t];return Array.isArray(n)?n:[]}function Yo(e,t){const n=e,r=Oe(String(n.page),t.page),i=Oe(String(n.limit),t.limit),o=n.data,s=o?.meta,a=Oe(String(o?.count),0),c=Oe(String(s?.totalItems),a),u=Oe(String(n.total),c);return{page:r,limit:i,total:u,totalPages:Xo(u,i)}}async function Zo(e,t={}){const{maxPages:n=1e4,logger:r,pageSize:i=20,concurrency:o=1,startPage:s=1}=t,a=[];let c=s;const u=s+n-1;let l=!0,h=0;if(o<=1)for(;l&&c<=u;){r&&r.debug(`Auto-pagination: fetching page ${c} with limit ${i}`);const t=await e(c,i);if(!t||!Array.isArray(t.items)){r&&r.warn("Auto-pagination: received invalid result structure, stopping");break}if(a.push(...t.items),h=t.total,r&&r.debug(`Auto-pagination: page ${c} returned ${t.items.length} items, hasNext: ${t.hasNext}`),0===t.items.length){r&&r.debug(`Auto-pagination: no items returned on page ${c}, exiting loop`);break}l=t.hasNext,c++}else for(r&&r.debug(`Auto-pagination: using concurrent mode with concurrency=${o}`);l&&c<=u;){const t=[];for(let e=0;e<o&&c+e<=u;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=>{if(400===e?.launchpadError?.statusCode||400===e?.status)return r&&r.debug(`Auto-pagination: page ${t} returned 400 (end of pagination)`,{statusCode:e?.launchpadError?.statusCode??e?.status}),{items:[],total:0,totalPages:0,page:t,limit:i,hasNext:!1,hasPrevious:!1};throw e})),s=await Promise.all(n);for(const e of s){if(!e||!Array.isArray(e.items)){r&&r.warn("Auto-pagination: received invalid result structure in batch, stopping"),l=!1;break}if(0===e.items.length){r&&r.debug("Auto-pagination: empty page in batch, reached end of results"),l=!1;break}if(a.push(...e.items),h=e.total,!e.hasNext){l=!1;break}}c+=t.length,r&&r.debug(`Auto-pagination: batch complete, total items so far: ${a.length}`)}return c>u&&r&&r.warn(`Auto-pagination: exceeded maxPages limit of ${n} (maxPage=${u}), stopping iteration`),r&&r.debug(`Auto-pagination: completed with total items: ${a.length}, total count: ${h}`),{items:a,total:h}}async function es(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();if(null==t)throw new _(`${n}: No response from server`,"response","NO_RESPONSE");if(pr(t,n,!0),i&&r&&r.debug(`${n}: completed successfully`),void 0===t.data)throw new _(`${n}: No data returned from API`,"data","NO_DATA");return t.data}catch(e){throw r&&r.error(n,{error:e}),e}}async function ts(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 ns(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();if(null==t)throw new _(`${n}: No response from server`,"response","NO_RESPONSE");return pr(t,n,!0),i&&r&&r.debug(`${n}: completed successfully`),t}catch(e){throw r&&r.error(n,{error:e}),e}}function rs(e){return e.trim().toLowerCase()}function is(e){return e.trim().toUpperCase()}function os(e){return e.trim().toUpperCase()}function ss(e,t,n){if(!Ye(e)){if("string"!=typeof e)throw Z(t,"a string",e,t);if(e.length>n)throw new _(`${t} must be at most ${n} characters`,t,B.TOO_LARGE)}}function as(e,t){ae(e,t)}function cs(e,t){if(Ye(e))return;let n;if(e instanceof Date)n=e;else if("string"==typeof e)n=new Date(e);else{if("number"!=typeof e)throw Z(t,"a date",e,t);n=new Date(e)}if(isNaN(n.getTime()))throw new _(`${t} must be a valid date`,t,B.INVALID_FORMAT)}function us(e,t,n){try{ae(e,t)}catch{throw function(e,t,n,r="OPERATION_FAILED"){return new _(`${e} failed: ${t}`,n,r)}(n,"must be a positive integer",t)}}function ls(e,t,n="status"){void 0!==e&&function(e,t,n){const r=Object.values(t);if(!r.includes(e))throw new _(`${n} must be one of: ${r.join(", ")}`,n,B.INVALID_FORMAT)}(e,t,n)}class hs{constructor(e,t=!1,n){this.http=e,this.logger=new ze({debug:t,context:this.constructor.name}),this.jwtAuth=n}setJwtAuth(e){this.jwtAuth=e}getJwtHeaders(){if(!this.jwtAuth){if("test"===process.env.NODE_ENV&&!this.isCalledFromUserCode())return{};throw new R("JWT authentication required. Call sdk.login() first.")}return this.jwtAuth.getJwtHeaders()}isCalledFromUserCode(){const e=T(new Error)||"";return!(!e.includes("expect")&&!e.includes("jest"))||!(!e.includes("tests/")&&!e.includes(".test.ts"))}validatePositiveInteger(e,t,n){us(e,t,n)}}class ds{constructor(e=!1,t){this.logger=t||new ze({debug:e,context:this.constructor.name})}}function fs(e,t){return"string"==typeof e[t]}function gs(e,t){return void 0===e[t]||"string"==typeof e[t]}function ps(e,t){return void 0===e[t]||"number"==typeof e[t]}function ms(e){if(!e||"object"!=typeof e)return!1;const t=e;return fs(t,"tokenName")&&ps(t,"from")&&ps(t,"to")&&ps(t,"resolution")}class ys extends hs{constructor(e,t=!1){super(e,t)}buildPoolFilters(e){return{...!Ye(e.search)&&{search:e.search},...!Ye(e.tokenName)&&{tokenName:e.tokenName},...!Ye(e.type)&&{type:e.type},...!Ye(e.hasUpcomingShows)&&{hasUpcomingShows:e.hasUpcomingShows},...!Ye(e.language)&&{language:e.language},...!Ye(e.recentlyStreamed)&&{recentlyStreamed:e.recentlyStreamed},...!Ye(e.hasRecordings)&&{hasRecordings:e.hasRecordings},...!Ye(e.streamStatus)&&{streamStatus:e.streamStatus}}}async fetchSinglePage(e){const t={page:e.page.toString(),limit:e.limit.toString()};Ye(e.type)||(t.type=e.type),Ye(e.tokenName)||(t.tokenName=e.tokenName),Ye(e.search)||(t.search=e.search),Ye(e.hasUpcomingShows)||(t.hasUpcomingShows=e.hasUpcomingShows.toString()),Ye(e.language)||(t.language=e.language),Ye(e.recentlyStreamed)||(t.recentlyStreamed=e.recentlyStreamed.toString()),Ye(e.hasRecordings)||(t.hasRecordings=e.hasRecordings.toString()),Ye(e.streamStatus)||(t.streamStatus=e.streamStatus);const n=vr(t),r=mr(await ns(()=>this.http.get(Et,n),{errorContext:"Failed to fetch pools"})),i=function(e){if(!e)return[];let t=[];if(e.tokens)if(Array.isArray(e.tokens))t=e.tokens.map(e=>({...e,createdAt:e.created_at||e.createdAt||""}));else{const n=e.tokens;t=[{...n,createdAt:n.created_at||n.createdAt||""}]}else e.pools&&Array.isArray(e.pools)&&(t=e.pools.map(e=>({...e,createdAt:e.created_at||e.createdAt||""})));return t}(r),o=r.count??r.total??0,s=Xo(o,e.limit);return{items:i,meta:{page:e.page,limit:e.limit,total:o,totalPages:s}}}async fetchPageForAutoPaginate(e,t,n){const r=await this.fetchSinglePage({...e,page:t,limit:n}),i=Ho(t,n),o=r.items.length===n&&Qo(i,n,r.meta.total);return{items:r.items,page:t,limit:n,total:r.meta.total,totalPages:r.meta.totalPages,hasNext:o,hasPrevious:t>1}}async fetchPools(e={}){const t=e.page||Wo.DEFAULT_PAGE,n=e.limit??Wo.DEFAULT_LIMIT;0!==n&&Ze(t,n),Qe(e.tokenName)&&$o(e.tokenName);const r=e.type?{recent:"RECENT",popular:"POPULAR",recordings:"RECORDINGS",seconds_streamed:"SECONDS_STREAMED"}[e.type]:void 0,i=e.streamStatus?{idle:"IDLE",active:"ACTIVE",disabled:"DISABLED"}[e.streamStatus]:void 0,o=this.buildPoolFilters({search:e.search,tokenName:e.tokenName,type:r,hasUpcomingShows:e.hasUpcomingShows,language:e.language,recentlyStreamed:e.recentlyStreamed,hasRecordings:e.hasRecordings,streamStatus:i});if(n>0&&n<=20){const e=await this.fetchSinglePage({...o,page:t,limit:n});return{items:e.items,meta:{page:t,limit:n,total:e.meta.total,totalPages:e.meta.totalPages}}}if(0===n){const e=Wo.BACKEND_MAX_PAGE_SIZE,t=await Zo((e,t)=>this.fetchPageForAutoPaginate(o,e,t),{pageSize:e,concurrency:5,logger:this.logger});return{items:t.items,meta:{page:1,limit:t.items.length,total:t.total||t.items.length,totalPages:1}}}const s=Wo.BACKEND_MAX_PAGE_SIZE,a=Xo(n,s),c=await Zo((e,t)=>this.fetchPageForAutoPaginate(o,e,t),{startPage:t,maxPages:a,pageSize:s,concurrency:5,logger:this.logger}),u=c.items.slice(0,n),l=Xo(c.total,s);return{items:u,meta:{page:t,limit:n,total:c.total,totalPages:l}}}async fetchAllPools(e){return this.fetchPools({...e,limit:0})}async checkPool(e){qo(e),Qe(e.tokenName)&&$o(e.tokenName);const t=vr(e),n=await es(()=>this.http.get(It,t),{errorContext:"Failed to check pool"});return Qe(e.symbol)?n?.isSymbolExist??!1:Qe(e.tokenName)?n?.isNameExist??!1:n?.exists??!1}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(!ms(e))throw new _("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($o(t),!n||!r||!i)throw new _("Graph options (from, to, resolution) are required","options","MISSING_GRAPH_OPTIONS");const o={tokenName:t,from:n,to:r,resolution:i};Ko(o);const s=vr(o);return{dataPoints:await es(()=>this.http.get(xt,s),{errorContext:"Failed to fetch graph data"})}}async fetchTokenDistribution(e){if(!e)throw z("tokenName","Token name");let t;$o(e);try{t=await ns(()=>this.http.get(`${Ct}/${e}`),{errorContext:"Failed to fetch token distribution"})}catch(t){if(I(t)&&500===t.response?.status)throw H(`Token distribution data temporarily unavailable for ${e}. This is a backend issue - please try again later.`,500);throw t}const n=mr(t);if(!Array.isArray(n))throw H("Invalid API response: expected array of holders",t.status);for(const e of n){if(!e.owner||"string"!=typeof e.owner)throw H("Invalid holder data: missing or invalid owner field",t.status);if(!e.quantity||"string"!=typeof e.quantity)throw H("Invalid holder data: missing or invalid quantity field",t.status);const n=Re(e.quantity,NaN);if(isNaN(n)||!isFinite(n))throw H(`Invalid holder quantity: "${e.quantity}"`,t.status)}const r=n.reduce((e,t)=>e.plus(t.quantity),wo(0));return{holders:n.map(e=>{const t=Oo(wo(e.quantity),r,wo(0)).multipliedBy(100).toNumber();return{address:e.owner,balance:e.quantity,percentage:t}}),totalSupply:r.toFixed(),totalHolders:n.length,lastUpdated:new Date}}async fetchUserHolderContext(e,t){if(!e)throw z("tokenName","Token name");if(!t)throw z("userAddress","User address");return $o(e),es(()=>this.http.get(`${Ct}/${e}`,{userAddress:t}),{errorContext:"Failed to fetch user holder context"})}async fetchTokenBadges(e){if(!e)throw z("tokenName","Token name");$o(e);const t=await es(()=>this.http.get(Nt,{tokenName:e}),{errorContext:"Failed to fetch token badges"});return{volumeBadges:t.volumeBadge||[],engagementBadges:t.engagementBadge||[]}}async hasTokenBadge(e){const{tokenName:t,badgeType:n,badgeName:r}=e;try{const e=await this.fetchTokenBadges(t);if(!e)return!1;const i=("volume"===n?e.volumeBadges:e.engagementBadges).find(e=>e.badgeName===r);return i?.isActive||!1}catch{return!1}}async resolveTokenNameToVault(e){try{const t=await this.fetchPools({tokenName:e});if(t.items&&Array.isArray(t.items)&&t.items.length>0)return t.items[0].vaultAddress||null;if(t.items&&"object"==typeof t.items){const e=t.items.tokens;return e?.vaultAddress||null}return null}catch{return null}}}function ws(e,t,n){return function(e,t={}){const{stringifyFields:n=[],optionalFields:r=[],fieldMappings:i={}}=t,o={};for(const[t,s]of Object.entries(e)){const e=t;if(r.includes(e)){if(void 0===s)continue;if("string"==typeof s&&!Qe(s))continue}const a=i[e],c=a?String(a):t;n.includes(e)?o[c]=String(s):o[c]=s}return vr(o)}({tokenName:e,page:t,limit:n},{stringifyFields:["page","limit"]})}const bs={PAGINATION:ye,TOKEN_NAME:ge,USER_ADDRESS:ke};function ks(e){if(!e.tokenName&&!e.userAddress)throw new _("At least one of tokenName or userAddress is required","options","MISSING_FILTER");if(void 0!==e.tokenName){if(!Qe(e.tokenName))throw Z("tokenName","a non-empty string",typeof e.tokenName);if(e.tokenName.length>bs.TOKEN_NAME.MAX_LENGTH)throw Y("tokenName",bs.TOKEN_NAME.MAX_LENGTH,e.tokenName.length)}if(void 0!==e.userAddress){if(!Qe(e.userAddress))throw Z("userAddress","a non-empty string",typeof e.userAddress);if(e.userAddress.length>bs.USER_ADDRESS.MAX_LENGTH)throw Y("userAddress",bs.USER_ADDRESS.MAX_LENGTH,e.userAddress.length)}if(Ze(e.page,e.limit,bs.PAGINATION.MAX_LIMIT),void 0!==e.txnType&&"BUY"!==e.txnType&&"SELL"!==e.txnType)throw W("txnType",'"BUY" or "SELL"');if(void 0!==e.startDate){if(!Qe(e.startDate))throw Z("startDate","a non-empty string",typeof e.startDate);if(isNaN(Date.parse(e.startDate)))throw W("startDate","a valid ISO 8601 date")}if(void 0!==e.endDate){if(!Qe(e.endDate))throw Z("endDate","a non-empty string",typeof e.endDate);if(isNaN(Date.parse(e.endDate)))throw W("endDate","a valid ISO 8601 date")}if(void 0!==e.minAmount)try{oe(e.minAmount,0,Number.MAX_SAFE_INTEGER,"minAmount")}catch{throw W("minAmount","a non-negative number")}if(void 0!==e.maxAmount)try{oe(e.maxAmount,0,Number.MAX_SAFE_INTEGER,"maxAmount")}catch{throw W("maxAmount","a non-negative number")}void 0!==e.minAmount&&void 0!==e.maxAmount&&ce(e.minAmount,e.maxAmount,"amountRange")}class vs extends hs{constructor(e,t=!1){super(e,t)}async fetchTrades(e){if(!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return fs(t,"tokenName")&&(void 0===t.tradeType||"buy"===t.tradeType||"sell"===t.tradeType)&&gs(t,"userAddress")&&ps(t,"page")&&ps(t,"limit")}(e))throw new _("Invalid options provided. Expected { tokenName: string, tradeType?: string, userAddress?: string, page?: number, limit?: number, startDate?: Date, endDate?: Date, sortOrder?: string }","options","INVALID_OPTIONS");const{tokenName:t,tradeType:n,userAddress:r,page:i=Wo.DEFAULT_PAGE,limit:o=Wo.DEFAULT_LIMIT,startDate:s,endDate:a,sortOrder:c}=e;if(!Qe(t))throw z("tokenName","Token name");Ze(i,o,me);const u=ws(t,i,o),l=await this.http.get(_t,u);if(!l)throw new _("No response from trade service","response","NO_RESPONSE");return{items:Jo(mr(l),"trades"),meta:Yo(l,{page:i,limit:o})}}buildTradesQueryParams(e){const t={};if(e.tokenName&&(t.tokenName=rs(e.tokenName)),e.userAddress&&(t.userAddress=e.userAddress),void 0!==e.page&&(t.page=String(e.page)),void 0!==e.limit){const n=Vo(e.limit,1,bs.PAGINATION.MAX_LIMIT);t.limit=String(n)}return e.txnType&&(t.txnType=e.txnType),e.startDate&&(t.startDate=e.startDate),e.endDate&&(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 es(()=>this.http.get(or,t),{errorContext:"Failed to fetch trades"})}}function Ss(e,t){const n={};return e.page&&(n.page=String(e.page)),e.limit&&(n.limit=String(Math.min(e.limit,t))),n}function As(e,t=e.length){return{page:1,limit:e.length,total:t,totalPages:e.length>0?Xo(t,e.length):1}}function Ts(e,t,n){for(const r of n){const n=t[r];null!=n&&""!==n&&(e[r]=String(n))}return e}function Es(e,t,n=1){if(!e)return null;if("string"!=typeof e)return null;const r=e.trim();return r.length<n?null:r}function Is(e,t){return e.toLowerCase()===t.toLowerCase()}function xs(e,t){return e.toLowerCase().includes(t.toLowerCase())}function Cs(e,t,n,r){return e===n&&t===r||e===r&&t===n}function Ns(e){if(!e||"string"!=typeof e)return!1;const t=e.startsWith("0x")?e.slice(2):e;return/^[0-9a-fA-F]{40}$/.test(t)}function Bs(e){return e.startsWith("0x")?e.slice(2):e}function _s(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 W("file","a File object (browser) or Buffer (Node.js)");{const i=new Blob([e],{type:"image/png"});r.append(t,i,n)}}return r}function Ps(e){return!!Qe(e)&&be.PATTERN.test(e)}et({ALL:"all",DEFI:"DEFI",ASSET:"ASSET"});class Rs extends hs{constructor(e,t,n=!1){super(e,n,t)}async fetchProfile(e){const t=e??this.http.getAddress();if(!t||!Ps(t))throw W("address","eth|[40-hex-chars]","Address");const n={userAddress:t},r=await this.http.get(Pt,n);if(!r)throw new _("No response from user service","response","NO_RESPONSE");return r}async updateProfile(e){this.validateUpdateProfileData(e);let t=e.profileImage;if(!Qe(t))try{const n=await this.fetchProfile(e.address);t=n.data?.profileImage||""}catch{t=""}const n={profileImage:t,fullName:e.fullName,userAddress:e.address};await es(()=>this.http.put(Rt,n,this.getJwtHeaders()),{errorContext:"Profile update failed"})}async uploadProfileImage(e){this.validateUploadProfileImageOptions(e);const t=e.address??this.http.getAddress();if(!t)throw new _("Wallet address not available - wallet not configured","address","NO_WALLET");try{const n=`profile-image-${t}.png`,r=_s(e.file,"image",n),i=await es(()=>this.http.request({method:"POST",url:`${Tt}?tokenName=${encodeURIComponent(t)}`,data:r,headers:this.getJwtHeaders()}),{errorContext:"Image upload failed"});return"string"==typeof i?i:""}catch(e){if(e instanceof _||e instanceof R)throw e;throw new _(`Profile image upload failed: ${A(e)}`,"file","UPLOAD_FAILED")}}async fetchTokenList(e){return this.buildFetchRequest(Dt,e,{includeType:!0,errorMessage:"Failed to fetch token list"})}async fetchTokensHeld(e){return this.buildFetchRequest(Lt,e,{includeType:!1,errorMessage:"Failed to fetch tokens held"})}async fetchTokensCreated(e={}){const{page:t=Wo.DEFAULT_PAGE,limit:n=Wo.DEFAULT_LIMIT,search:r,tokenName:i}=e,o=this.http.getAddress();if(!o)throw new _("Wallet address not available - wallet not configured","address","NO_WALLET");const s={type:"DEFI",address:o,page:t,limit:n};return void 0!==r&&(s.search=r),void 0!==i&&(s.tokenName=i),this.fetchTokenList(s)}async getManagedTokens(e={}){const t=jo(e.page),n=Vo(e.limit);Ze(t,n,me);const r={};void 0!==t&&(r.page=t),void 0!==n&&(r.limit=n);const i=Ss(r,me);return es(()=>this.http.get(Ot,{...i,...this.getJwtHeaders()}),{errorContext:"Failed to fetch managed tokens"})}async buildFetchRequest(e,t,n){this.validateGetTokenListOptions(t);const r={};void 0!==t.page&&(r.page=t.page),void 0!==t.limit&&(r.limit=t.limit);const i=Ss(r,me);Ts(i,t,["address","search","tokenName"]),n.includeType&&(i.type="all"!==t.type&&t.type?t.type:"DEFI");const o=await ns(()=>this.http.get(e,i),{errorContext:n.errorMessage}),s=Jo(mr(o),"token"),a=Yo(o,{page:t.page||Wo.DEFAULT_PAGE,limit:t.limit||Wo.DEFAULT_LIMIT}),c=(u=a.page,l=a.totalPages,{hasNext:u<l,hasPrevious:u>1});var u,l;return{tokens:s,...a,...c}}validateGetTokenListOptions(e){if(Ze(e.page,e.limit,me),void 0!==e.address&&!Ps(e.address))throw W("address","eth|[40-hex-chars]","Address");const t=Es(e.search);if(null!==t&&!(Qe(n=t)&&n.length>=Ne&&n.length<=Be))throw Q("search",Ne,Be,t.length,"Search query");var n;const r=Es(e.tokenName);if(null!==r&&!(Qe(i=r)&&i.length>=ge.MIN_LENGTH&&i.length<=ge.MAX_LENGTH))throw Q("tokenName",ge.MIN_LENGTH,ge.MAX_LENGTH,r.length,"Token name");var i}validateUpdateProfileData(e){if(!Ps(e.address))throw W("address","eth|[40-hex-chars]","Address");if(!(Qe(t=e.fullName)&&t.length>=_e.FULL_NAME.MIN_LENGTH&&t.length<=_e.FULL_NAME.MAX_LENGTH&&_e.FULL_NAME.ALPHABETS_ONLY_PATTERN.test(t)))throw Q("fullName",_e.FULL_NAME.MIN_LENGTH,_e.FULL_NAME.MAX_LENGTH,e.fullName.length,"Full name");var t}validateUploadProfileImageOptions(e){if(e.address&&!Ps(e.address))throw W("address","eth|[40-hex-chars]","Address")}}class Ds extends Error{constructor(e,t,n){super(e),this.filename=t,this.mimeType=n,this.name="FileValidationError"}}function Ls(e,t,n){if(!e)throw new Ds("File is required",t,n);if("undefined"!=typeof File&&e instanceof File){const t=di.safeParse(e);if(!t.success){const n=t.error.errors.map(e=>e.message).join("; ");throw new Ds(n,e.name,e.type)}return}if(Buffer.isBuffer(e)){if(!t)throw new Ds("Filename is required when uploading Buffer objects",t,n);const r=fi.safeParse(e);if(!r.success){const e=r.error.errors.map(e=>e.message).join("; ");throw new Ds(e,t,n)}try{se(t,255,"filename")}catch(e){throw new Ds(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 Ds(`Invalid file type "${n}" is not allowed. Allowed types: ${i.join(", ")}`,t,n);const o=function(e){if(!e)return"";const t=e.lastIndexOf(".");if(-1===t)return"";return e.substring(t).toLowerCase()}(t),s=[".png",".jpg",".jpeg",".gif",".webp",".svg"];if(!s.includes(o))throw new Ds(`File extension "${o}" is not allowed. Allowed extensions: ${s.join(", ")}`,t,n);const a=function(e){switch(e.toLowerCase()){case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";case".gif":return"image/gif";case".webp":return"image/webp";case".svg":return"image/svg+xml";default:return"application/octet-stream"}}(o);if(a!==n&&"application/octet-stream"!==a)throw new Ds(`File extension "${o}" does not match MIME type "${n}"`,t,n);return}throw new Ds("File must be a File object (browser) or Buffer (Node.js)",t,n)}class Os extends hs{constructor(e,t,n=!1){super(e,n,t)}async uploadImageByTokenName(e){const{tokenName:t,options:n}=e;$o(t);const r=`${t}.png`;Ls(n.file,r,"image/png");try{const e=`${n.tokenName??t}.png`,r=_s(n.file,"image",e),i=await es(()=>this.http.request({method:"POST",url:`${Tt}?tokenName=${encodeURIComponent(n.tokenName??t)}`,data:r,headers:this.getJwtHeaders()}),{errorContext:"Image upload failed"});return"string"==typeof i?i:""}catch(e){if(e instanceof R)throw e;if(S(e)&&A(e).includes("FormData"))throw j("File upload failed: FormData not supported in this environment. Ensure you have proper polyfills for Node.js environments.","FormData");throw e}}async updateTokenSocials(e){if(!Qe(e.tokenName))throw z("tokenName","Token name");if($o(e.tokenName),!this.jwtAuth)throw j("JWT authentication required for updating token social links. Initialize SDK with a wallet or provide JWT token.","JWT_AUTH_REQUIRED");const t=Bt,n=mr(await this.http.put(t,e,this.getJwtHeaders()));if(!n)throw new Error("Failed to update token social links: no data returned");return n}}class Us{constructor(e,t,n=!1){this.http=e,this.poolService=new ys(e,n),this.tradeService=new vs(e,n),this.userService=new Rs(e,t,n),this.imageService=new Os(e,t,n)}setJwtAuth(e){this.userService.setJwtAuth(e),this.imageService.setJwtAuth(e)}async uploadImageByTokenName(e){return this.imageService.uploadImageByTokenName(e)}async updateTokenSocials(e){return this.imageService.updateTokenSocials(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 fetchTokenBadges(e){return this.poolService.fetchTokenBadges(e)}async hasTokenBadge(e){return this.poolService.hasTokenBadge(e)}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 $o(e)}}function Ms(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(!t||"object"!=typeof t||Array.isArray(t))return!1;const n=t;for(const[t,r]of Object.entries(e)){if(!Ms(n[t],r))return!1}return!0}}et({BUY:"buy",SELL:"sell"});const $s=Fs({vaultAddress:"string"}),qs=Fs({nativeTokenQuantity:"string"});function Ks(e){return`${e.collection}|${e.category}|${e.type}|${e.additionalKey}`}function Gs(e){return`${e.collection}$${e.category}$${e.type}$${e.additionalKey}`}function zs(e){return`$${e.collection}$${e.category}$${e.type}$${e.additionalKey}`}function Ws(e,t,n){const r=n?` (${n})`:"";try{if(!Qe(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}`);const[r,i,o,...s]=n;if(!r||!i||!o)throw new Error("Collection, category, and type must be non-empty");const a=s.join(t);if(!a)throw new Error("AdditionalKey must be non-empty");return{collection:r,category:i,type:o,additionalKey:a}}catch(n){const i=e?.split?.(t)??[];throw new _(`Invalid ${"|"===t?"pipe":"dollar"}-delimited token: "${e}" (${i.length} parts)${r}. Expected format: "collection${t}category${t}type${t}additionalKey" (4 parts minimum). Received: [${i.map(e=>`"${e}"`).join(", ")}]. Error: ${A(n)}`,"token",`INVALID_${"|"===t?"PIPE":"DOLLAR"}_DELIMITED_TOKEN`)}}function Hs(e){if("object"==typeof e&&null!==e)return function(e){if(!e||"object"!=typeof e)throw new _("Token object must be a non-null object, got "+typeof e,"token","INVALID_TOKEN_OBJECT");const{collection:t,category:n,type:r,additionalKey:i}=e;if(!Qe(t))throw new _("Token.collection must be a non-empty string, got "+typeof t,"token.collection","MISSING_OR_INVALID_COLLECTION");if(!Qe(n))throw new _("Token.category must be a non-empty string, got "+typeof n,"token.category","MISSING_OR_INVALID_CATEGORY");if(!Qe(r))throw new _("Token.type must be a non-empty string, got "+typeof r,"token.type","MISSING_OR_INVALID_TYPE");if(!Qe(i))throw new _("Token.additionalKey must be a non-empty string, got "+typeof i,"token.additionalKey","MISSING_OR_INVALID_ADDITIONAL_KEY");return{collection:t,category:n,type:r,additionalKey:i}}(e);if(!e)throw new _(`Token cannot be null, undefined, or empty. Received: ${JSON.stringify(e)}`,"token","EMPTY_TOKEN");if("string"!=typeof e)throw new _("Token must be a string or TokenClassKey object, got "+typeof e,"token","INVALID_TOKEN_TYPE");if(Vs(e))return js(e);if(Xs(e))return function(e){return function(e,t,n){const r=` (${n})`;try{if(!Qe(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}`);const r=n[n.length-1],i=n[n.length-2],o=n[n.length-3],s=n.slice(0,n.length-3).join(t);if(!(s&&o&&i&&r))throw new Error("All components (collection, category, type, additionalKey) must be non-empty");return{collection:s,category:o,type:i,additionalKey:r}}catch(n){const i=e?.split?.(t)??[];throw new _(`Invalid dollar-delimited token: "${e}" (${i.length} parts)${r}. Expected format: "collection${t}category${t}type${t}additionalKey" (4 parts minimum). Received: [${i.map(e=>`"${e}"`).join(", ")}]. Error: ${A(n)}`,"token","INVALID_DOLLAR_DELIMITED_TOKEN")}}(e,"$","dollar-delimited token")}(e);throw new _(`Plain token string "${e}" (length: ${e.length}) is not allowed - tokens must be delimited with | or $. Expected format: "GALA|Unit|none|none" or "GALA$Unit$none$none". Input: "${e}"`,"token","PLAIN_STRING_NOT_ALLOWED")}function js(e){return Ws(e,"|","pipe-delimited token")}function Vs(e){return Qe(e)&&e.includes("|")}function Xs(e){return"string"==typeof e&&e.includes("$")}function Qs(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.collection&&"string"==typeof t.category&&"string"==typeof t.type&&"string"==typeof t.additionalKey&&t.collection.length>0&&t.category.length>0&&t.type.length>0&&t.additionalKey.length>0}function Js(e){return e&&0!==e.length?e.reduce((e,t)=>i(e).plus(t.quantity).toString(),"0"):"0"}function Ys(e,t){if(!e||0===e.length)return[];if(t)return e;const n=Date.now();return e.filter(e=>0===e.expires||e.expires>n)}class Zs extends hs{constructor(e,t=!1){super(e,t)}getChannelForCollection(e){return"MUSIC"===(Xs(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(!r)return null;try{x(r,"Fetch balances")}catch{return null}if(!r.Data||0===r.Data.length)return null;const o=r.Data.find(t=>t.collection===e.collection&&t.category===e.category&&t.additionalKey===e.additionalKey&&t.type===e.type);if(!o||"0"===o.quantity)return null;const s=Ks(o),a={quantity:o.quantity,collection:o.collection,category:o.category,tokenId:s};if(o.inUseHolds?.length){const e=Ys(o.inUseHolds??[],t);e.length>0&&(a.inUseHolds=e,a.inUseQuantity=Js(e))}if(o.lockedHolds?.length){const e=Ys(o.lockedHolds??[],t);e.length>0&&(a.lockedHolds=e,a.lockedQuantity=Js(e))}return(a.lockedQuantity||a.inUseQuantity)&&(a.availableQuantity=function(e,t="0",n="0"){return i(e).minus(t).minus(n).toString()}(a.quantity,a.lockedQuantity,a.inUseQuantity)),a}catch(e){throw H(`Failed to fetch token balance from GalaChain: ${A(e)}`,void 0,S(e)?e:void 0)}}}function ea(e){if("string"==typeof e){if(!Vs(e))throw new _(`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){return{...js(t.slice(0,4).join("|")),instance:t[4]||"0"}}return{...js(e),instance:"0"}}if("object"==typeof e&&null!==e){if("instance"in e&&void 0!==e.instance){if(!Qs(e))throw new _("Invalid tokenId object format. All fields (collection, category, type, additionalKey) must be non-empty strings","tokenId","INVALID_TOKEN_ID_FORMAT");return e}if(!Qs(e))throw new _("Invalid tokenId object format. All fields (collection, category, type, additionalKey) are required","tokenId","INVALID_TOKEN_ID_FORMAT");return{...e,instance:"0"}}throw new _(`Invalid tokenId type: ${typeof e}. Expected string, TokenClassKey, or TokenInstanceKey`,"tokenId","INVALID_TOKEN_ID_TYPE")}function ta(e){return function(e){try{if(!Qe(e))throw new Error("Vault address must be a non-empty string");const[t,n]=e.split("|");if(!n)throw new Error("Missing token part after service prefix");const r=n.split("$");if(r.length<4)throw new Error(`Invalid vault address format: expected at least 4 parts separated by $, got ${r.length}`);const[i,o,s,...a]=r;if(!i||!o||!s)throw new Error("Collection, category, and type must be non-empty");const c=a.slice(0,-1),u=c.length>0?c.join("$"):a[0];if(!u)throw new Error("AdditionalKey must be non-empty");return{collection:i,category:o,type:s,additionalKey:u}}catch(t){throw new _(`Invalid vault address: "${e}". Expected format: "service|Token$Unit$SYMBOL$additionalKey$launchpad". Error: ${A(t)}`,"vaultAddress","INVALID_VAULT_ADDRESS_FORMAT")}}(e)}function na(e){return{...ta(e),instance:"0"}}function ra(e){return ta(e).type}function ia(e){return Ks(ea(e))}var oa=Object.freeze({__proto__:null,extractTokenSymbolFromVault:ra,isTokenClassKeyStrict:Qs,normalizeToTokenInstanceKey:ea,normalizeTokenIdToString:ia,parseVaultAddressToTokenClassKey:ta,parseVaultAddressToTokenInstance:na});class sa extends hs{constructor(e,t=!1,n){super(e,t),this.publicAxios=n}async fetchTokenClassFromChain(e){try{const t="string"==typeof e?ea(e):e,n={tokenClasses:[{collection:t.collection,category:t.category,type:t.type,additionalKey:t.additionalKey}]};if(!this.publicAxios)throw z("publicAxios","Public Axios instance");const r=(await this.publicAxios.post("/api/asset/token-contract/FetchTokenClasses",n)).data;if(x(r,"Failed to fetch token class from GalaChain"),!r.Data||0===r.Data.length)throw H(`Token not found on GalaChain: ${Ks(t)}`,404);return r.Data[0]}catch(e){if(e instanceof _)throw e;if(I(e)&&404===e.response?.status)throw H("Token not found on GalaChain",404,S(e)?e:void 0);if(S(e)&&"Error"===e.name&&A(e).includes("status indicates failure"))throw H(A(e),400,S(e)?e:void 0);const t=A(e);if(t.includes("Token not found"))throw e;throw H(`Failed to fetch token class from GalaChain: ${t}`,void 0,S(e)?e:void 0)}}async fetchTokenClassesWithSupply(e){try{if(!e||0===e.length)throw z("tokenClasses","Token classes array");const t={tokenClasses:e};if(!this.publicAxios)throw z("publicAxios","Public Axios instance");const n=(await this.publicAxios.post("/api/asset/token-contract/FetchTokenClassesWithSupply",t)).data;if(x(n,"Failed to fetch token classes with supply from GalaChain"),!n.Data||0===n.Data.length)throw H("No token supply data found for requested token classes",404);return n.Data}catch(e){if(e instanceof _)throw e;if(I(e)&&404===e.response?.status)throw H("Token supply data not found on GalaChain",404,S(e)?e:void 0);if(S(e)&&"Error"===e.name&&A(e).includes("status indicates failure"))throw H(A(e),400,S(e)?e:void 0);const t=A(e);if(t.includes("Token not found"))throw e;throw H(`Failed to fetch token classes with supply from GalaChain: ${t}`,void 0,S(e)?e:void 0)}}}class aa{toLaunchpadFormat(e){if(!e)throw new _('Token is required. Use full tokenId format: "GALA|Unit|none|none"',"token","MISSING_TOKEN");if("string"==typeof e){if(Vs(e))return e;throw new _(`Invalid token format "${e}". Use full tokenId format: "${e}|Unit|none|none". For launchpad bonding curve tokens, use tokenName parameter instead (e.g., "anime").`,"token","INVALID_TOKEN_FORMAT")}return Ks({collection:e.collection||e.symbol||"unknown",category:e.category||"Unit",type:e.type||"none",additionalKey:e.additionalKey||"none"})}toTokenClass(e){if("object"==typeof e&&null!==e)return{collection:e.collection||"Token",category:e.category||"Unit",type:e.type||e.symbol||"unknown",additionalKey:e.additionalKey||"none"};if("string"!=typeof e)throw new Error("Invalid token format: expected string or object, got "+typeof e);const t=Ws(e,"|","token format conversion");return{collection:t.collection,category:t.category,type:t.type,additionalKey:t.additionalKey}}normalizeInternalApiResponse(e){return e?Vs(e)?e:`${e}|Unit|none|none`:""}normalize(e){return"string"==typeof e&&Vs(e)?e:this.toLaunchpadFormat(e)}}function ca(e){if(!Qe(e))throw new Error("Invalid token format: token must be a non-empty string");return e.replace(/\|/g,"$")}function ua(e){return Ws(e,"$","dollar-delimited token")}function la(){return`galaconnect-operation-${Date.now()}_${Math.random().toString(36).substring(2,8)}`}class ha extends n.ChainCallDTO{constructor(e){super(),this.lockAuthority=e.lockAuthority,this.tokenInstances=e.tokenInstances,this.uniqueKey=e.uniqueKey,void 0!==e.expires&&(this.expires=e.expires),void 0!==e.name&&(this.name=e.name),e.signedPayload&&(this.signature=e.signedPayload.signature,this.domain=e.signedPayload.domain,this.types=e.signedPayload.types,e.signedPayload.prefix&&(this.prefix=e.signedPayload.prefix))}static fromTokenClassKey(e,t,n,r,i){let o;if("string"==typeof r){o={...ua(r),instance:"0"}}else o={collection:r.collection,category:r.category,type:r.type,additionalKey:r.additionalKey,instance:"0"};return new ha({lockAuthority:t||e,tokenInstances:[{owner:e,quantity:n,tokenInstanceKey:o}],...void 0!==i?.expires&&{expires:i.expires},...void 0!==i?.name&&{name:i.name},uniqueKey:i?.uniqueKey||la()})}static forGALA(e,t,n,r){return new ha({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||la()})}getTokenClassKey(){if(0===this.tokenInstances.length)return;return Gs(this.tokenInstances[0].tokenInstanceKey)}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 da extends n.ChainCallDTO{constructor(e){super(),this.tokenInstances=e.tokenInstances,this.uniqueKey=e.uniqueKey,void 0!==e.name&&(this.name=e.name),e.signedPayload&&(this.signature=e.signedPayload.signature,this.domain=e.signedPayload.domain,this.types=e.signedPayload.types,e.signedPayload.prefix&&(this.prefix=e.signedPayload.prefix))}static fromTokenClassKey(e,t,n,r){let i;if("string"==typeof n){i={...ua(n),instance:"0"}}else i={collection:n.collection,category:n.category,type:n.type,additionalKey:n.additionalKey,instance:"0"};return new da({tokenInstances:[{owner:e,quantity:t,tokenInstanceKey:i}],...void 0!==r?.name&&{name:r.name},uniqueKey:r?.uniqueKey||la()})}static forGALA(e,t,n){return new da({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||la()})}getTokenClassKey(){if(0===this.tokenInstances.length)return;return Gs(this.tokenInstances[0].tokenInstanceKey)}toSigningPayload(){return{tokenInstances:this.tokenInstances,...void 0!==this.name&&{name:this.name},uniqueKey:this.uniqueKey}}}class fa{constructor(e){this.wallet=e}static generateUniqueKey(){return`${Date.now()}_${Math.random().toString(36).substring(2,8)}`}async signTransferToken(e){const t={name:"GalaChain",chainId:1},n={TransferToken:[{name:"from",type:"string"},{name:"to",type:"string"},{name:"quantity",type:"string"},{name:"tokenInstance",type:"TokenInstance"},{name:"uniqueKey",type:"string"}],TokenInstance:[{name:"collection",type:"string"},{name:"category",type:"string"},{name:"type",type:"string"},{name:"additionalKey",type:"string"},{name:"instance",type:"string"}]};return{signature:await this.wallet.signTypedData(t,n,e),domain:t,types:n,signerPublicKey:this.wallet.signingKey.publicKey}}async signLockToken(e){const t={name:"GalaChain",chainId:1},n={LockToken:[{name:"lockAuthority",type:"string"},{name:"tokenInstances",type:"TokenInstanceQuantity[]"},{name:"uniqueKey",type:"string"},...void 0!==e.expires?[{name:"expires",type:"uint256"}]:[],...void 0!==e.name?[{name:"name",type:"string"}]:[]],TokenInstanceQuantity:[{name:"owner",type:"string"},{name:"quantity",type:"string"},{name:"tokenInstanceKey",type:"TokenInstanceKey"}],TokenInstanceKey:[{name:"collection",type:"string"},{name:"category",type:"string"},{name:"type",type:"string"},{name:"additionalKey",type:"string"},{name:"instance",type:"string"}]},r={lockAuthority:e.lockAuthority,tokenInstances:e.tokenInstances,uniqueKey:e.uniqueKey};void 0!==e.expires&&(r.expires=e.expires),void 0!==e.name&&(r.name=e.name);return{signature:await this.wallet.signTypedData(t,n,r),domain:t,types:n,signerPublicKey:this.wallet.signingKey.publicKey}}async signBurnTokens(e){const t={name:"GalaChain",chainId:1},n={BurnTokens:[{name:"tokenInstances",type:"TokenInstanceQuantity[]"},{name:"uniqueKey",type:"string"}],TokenInstanceQuantity:[{name:"quantity",type:"string"},{name:"tokenInstanceKey",type:"TokenInstanceKey"}],TokenInstanceKey:[{name:"collection",type:"string"},{name:"category",type:"string"},{name:"type",type:"string"},{name:"additionalKey",type:"string"},{name:"instance",type:"string"}]},r={tokenInstances:e.tokenInstances,uniqueKey:e.uniqueKey};return{signature:await this.wallet.signTypedData(t,n,r),domain:t,types:n,signerPublicKey:this.wallet.signingKey.publicKey}}async signUnlockToken(e){const t={name:"GalaChain",chainId:1},n={UnlockToken:[{name:"tokenInstances",type:"TokenInstanceQuantity[]"},{name:"uniqueKey",type:"string"},...void 0!==e.name?[{name:"name",type:"string"}]:[]],TokenInstanceQuantity:[{name:"owner",type:"string"},{name:"quantity",type:"string"},{name:"tokenInstanceKey",type:"TokenInstanceKey"}],TokenInstanceKey:[{name:"collection",type:"string"},{name:"category",type:"string"},{name:"type",type:"string"},{name:"additionalKey",type:"string"},{name:"instance",type:"string"}]},r={tokenInstances:e.tokenInstances,uniqueKey:e.uniqueKey};void 0!==e.name&&(r.name=e.name);return{signature:await this.wallet.signTypedData(t,n,r),domain:t,types:n,signerPublicKey:this.wallet.signingKey.publicKey}}static toGalaChainAddress(e){return(new lt).toBackendFormat(e)}static fromGalaChainAddress(e){try{return(new lt).toEthereumFormat(e)}catch{try{return gt(e)}catch{return e}}}static createGALATokenInstance(){return{collection:"GALA",category:"Unit",type:"none",additionalKey:"none",instance:"0"}}static createTokenInstanceFromClassKey(e){return{...ua(e),instance:"0"}}}function ga(e){if(!e||"object"!=typeof e)return!1;const t=e;return Qe(t.amount)&&(void 0!==t.tokenId||Qe(t.tokenName))&&(void 0===t.lockAuthority||"string"==typeof t.lockAuthority)&&(void 0===t.expires||"number"==typeof t.expires)&&(void 0===t.name||"string"==typeof t.name)}function pa(e){if(!e||"object"!=typeof e)return!1;const t=e;return Qe(t.amount)&&(void 0!==t.tokenId||Qe(t.tokenName))&&(void 0===t.name||"string"==typeof t.name)}function ma(e){if(!e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every(ga)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}function ya(e){if(!e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every(pa)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}var wa,ba;exports.LockErrorType=void 0,(wa=exports.LockErrorType||(exports.LockErrorType={})).TOKEN_NOT_FOUND="TOKEN_NOT_FOUND",wa.INVALID_AMOUNT="INVALID_AMOUNT",wa.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",wa.SIGNATURE_FAILED="SIGNATURE_FAILED",wa.NETWORK_ERROR="NETWORK_ERROR",wa.WALLET_REQUIRED="WALLET_REQUIRED",wa.VALIDATION_ERROR="VALIDATION_ERROR",wa.LOCK_NOT_FOUND="LOCK_NOT_FOUND",wa.LOCK_EXPIRED="LOCK_EXPIRED",wa.INSUFFICIENT_LOCKED_BALANCE="INSUFFICIENT_LOCKED_BALANCE",wa.NOT_LOCK_AUTHORITY="NOT_LOCK_AUTHORITY",wa.LOCK_NAME_MISMATCH="LOCK_NAME_MISMATCH";class ka extends Error{constructor(e,t,n){super(e),this.type=t,this.details=n,this.name="LockError"}}!function(e){e.INVALID_RECIPIENT="INVALID_RECIPIENT",e.INVALID_AMOUNT="INVALID_AMOUNT",e.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",e.TOKEN_NOT_FOUND="TOKEN_NOT_FOUND",e.SIGNATURE_FAILED="SIGNATURE_FAILED",e.NETWORK_ERROR="NETWORK_ERROR",e.DUPLICATE_TRANSFER="DUPLICATE_TRANSFER",e.TRANSFER_LIMIT_EXCEEDED="TRANSFER_LIMIT_EXCEEDED",e.WALLET_REQUIRED="WALLET_REQUIRED"}(ba||(ba={}));class va extends Error{constructor(e,t,n){super(e),this.type=t,this.details=n,this.name="TransferError"}}const Sa=100,Aa=100;class Ta extends hs{constructor(e,t,n,r=!1){super(e,r),this.wallet=t,this.tokenResolver=n,this.signatureHelper=t?new fa(t):void 0}async lockTokens(e){if(this.validateLockTokensData(e),!this.wallet||!this.signatureHelper)throw new ka("Wallet required for token lock operations",exports.LockErrorType.WALLET_REQUIRED);return wr(async()=>{const t=ft(this.wallet.address),n=[],r=[];let i=t;const o=e.tokens.find(e=>e.lockAuthority);o?.lockAuthority&&(i=ft(o.lockAuthority));const s=e.tokens.find(e=>void 0!==e.expires),a=e.tokens.find(e=>void 0!==e.name);for(const o of e.tokens){let e;if(o.tokenId)e=ea(o.tokenId),this.logger.debug("[DEBUG] Using provided tokenId:",o.tokenId);else{if(!o.tokenName)throw new ka("Must provide either tokenId or tokenName for token identification",exports.LockErrorType.TOKEN_NOT_FOUND);e=await this.resolveTokenInstance(o.tokenName)}n.push({owner:t,quantity:o.amount,tokenInstanceKey:e}),r.push({tokenClassKey:{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey},quantity:o.amount,lockAuthority:o.lockAuthority?ft(o.lockAuthority):i})}const c=new ha({lockAuthority:i,tokenInstances:n,...void 0!==s?.expires&&{expires:s.expires},...void 0!==a?.name&&{name:a.name},uniqueKey:e.uniqueKey||la()}),u=await this.signatureHelper.signLockToken(c.toSigningPayload()),l=new ha({...c.toSigningPayload(),signedPayload:u});this.logger.debug("[DEBUG] Full Lock Request Payload:",JSON.stringify(l,null,2));const h=await this.http.post("/api/asset/token-contract/LockTokens",l);try{x(h,"Token lock failed")}catch(e){const t=C(h);throw new ka(`${A(e)}${t}`,exports.LockErrorType.NETWORK_ERROR)}return this.logger.debug("[DEBUG] Token lock response:",JSON.stringify(h,null,2)),this.extractLockResult(h,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.signatureHelper)throw new ka("Wallet required for token unlock operations",exports.LockErrorType.WALLET_REQUIRED);return wr(async()=>{const t=ft(this.wallet.address),n=[],r=[],i=e.tokens.find(e=>void 0!==e.name);for(const i of e.tokens){let e;if(i.tokenId)e=ea(i.tokenId),this.logger.debug("[DEBUG] Using provided tokenId:",i.tokenId);else{if(!i.tokenName)throw new ka("Must provide either tokenId or tokenName for token identification",exports.LockErrorType.TOKEN_NOT_FOUND);e=await this.resolveTokenInstance(i.tokenName)}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 o=new da({tokenInstances:n,...void 0!==i?.name&&{name:i.name},uniqueKey:e.uniqueKey||la()}),s=await this.signatureHelper.signUnlockToken(o.toSigningPayload()),a=new da({...o.toSigningPayload(),signedPayload:s});this.logger.debug("[DEBUG] Full Unlock Request Payload:",JSON.stringify(a,null,2));const c=await this.http.post("/api/asset/token-contract/UnlockTokens",a);try{x(c,"Token unlock failed")}catch(e){const t=C(c);throw new ka(`${A(e)}${t}`,exports.LockErrorType.NETWORK_ERROR)}return this.logger.debug("[DEBUG] Token unlock response:",JSON.stringify(c,null,2)),this.extractUnlockResult(c,r)},"Token unlock failed",this.logger,t=>{throw this.handleLockError(t,"Token unlock failed",e)})}validateLockTokensData(e){if(!ma(e))throw new ka("Invalid lock data: missing required fields",exports.LockErrorType.VALIDATION_ERROR);if(e.tokens.length>Sa)throw new ka(`Batch size exceeds maximum limit of ${Sa} tokens per lock operation`,exports.LockErrorType.VALIDATION_ERROR);for(const t of e.tokens){if(!t.tokenId&&!t.tokenName)throw new ka("Must provide either tokenId or tokenName for token identification",exports.LockErrorType.TOKEN_NOT_FOUND);if(t.tokenName)try{it(t.tokenName,"tokenName")}catch{throw new ka("Invalid token name format",exports.LockErrorType.TOKEN_NOT_FOUND,{tokenName:t.tokenName})}const e=wo(t.amount);try{Ro(e)}catch{throw new ka(W("lockAmount","a positive number","Lock amount").message,exports.LockErrorType.INVALID_AMOUNT,{amount:t.amount})}if(t.lockAuthority&&!mt(t.lockAuthority))throw new ka("Invalid lock authority address format",exports.LockErrorType.VALIDATION_ERROR,{lockAuthority:t.lockAuthority});if(void 0!==t.expires)try{ae(t.expires,"expires")}catch{throw new ka(W("expires","a positive integer (epoch milliseconds)","Expires").message,exports.LockErrorType.VALIDATION_ERROR)}}}validateUnlockTokensData(e){if(!ya(e))throw new ka("Invalid unlock data: missing required fields",exports.LockErrorType.VALIDATION_ERROR);if(e.tokens.length>Aa)throw new ka(`Batch size exceeds maximum limit of ${Aa} tokens per unlock operation`,exports.LockErrorType.VALIDATION_ERROR);for(const t of e.tokens){if(!t.tokenId&&!t.tokenName)throw new ka("Must provide either tokenId or tokenName for token identification",exports.LockErrorType.TOKEN_NOT_FOUND);if(t.tokenName)try{it(t.tokenName,"tokenName")}catch{throw new ka("Invalid token name format",exports.LockErrorType.TOKEN_NOT_FOUND,{tokenName:t.tokenName})}const e=wo(t.amount);try{Ro(e)}catch{throw new ka(W("unlockAmount","a positive number","Unlock amount").message,exports.LockErrorType.INVALID_AMOUNT,{amount:t.amount})}}}extractLockResult(e,t){let n;if(e.Data&&e.Data.length>0){const t=e.Data[0];n=t.transactionId||t.txnId||t.TxnId||t.id||void 0}return{...void 0!==n&&{transactionId:n},locked:t}}extractUnlockResult(e,t){let n;if(e.Data&&e.Data.length>0){const t=e.Data[0];n=t.transactionId||t.txnId||t.TxnId||t.id||void 0}return{...void 0!==n&&{transactionId:n},unlocked:t}}handleLockError(e,t,n){if(e instanceof ka)return e;let r=t,i=exports.LockErrorType.NETWORK_ERROR;if(I(e)){const n=e.response?.data;if("object"==typeof n&&null!==n){const e=n;e.Message&&"string"==typeof e.Message&&(r=`${t}: ${e.Message}`);const o=String(e.Message||"").toLowerCase();o.includes("insufficient")||o.includes("balance")?i=exports.LockErrorType.INSUFFICIENT_BALANCE:o.includes("lock")&&o.includes("not found")?i=exports.LockErrorType.LOCK_NOT_FOUND:o.includes("not found")||o.includes("token")?i=exports.LockErrorType.TOKEN_NOT_FOUND:o.includes("authority")?i=exports.LockErrorType.NOT_LOCK_AUTHORITY:o.includes("expired")&&(i=exports.LockErrorType.LOCK_EXPIRED)}}else S(e)&&(r=`${t}: ${A(e)}`);const o={};return void 0!==n?.tokens?.[0]?.tokenName&&(o.tokenName=n.tokens[0].tokenName),void 0!==n?.tokens?.[0]?.amount&&(o.amount=n.tokens[0].amount),new ka(r,i,Object.keys(o).length>0?o:void 0)}async resolveTokenInstance(e){return wr(async()=>{const t=await this.tokenResolver.resolveTokenToVault(e);if(t){const n=na(t);return this.logger.debug(`[DEBUG] Token resolution for '${e}' (launchpad):\n Vault Address: ${t}\n Token Instance: ${JSON.stringify(n,null,2)}`),n}const n={collection:is(e),category:"Unit",type:"none",additionalKey:"none",instance:"0"};return this.logger.debug(`[DEBUG] Token resolution for '${e}' (standard format):\n Token Instance: ${JSON.stringify(n,null,2)}`),n},`Failed to resolve token '${e}'`,this.logger,t=>{if(t instanceof va)throw new ka(A(t),exports.LockErrorType.TOKEN_NOT_FOUND);throw new ka(`Failed to resolve token '${e}': ${A(t)}`,exports.LockErrorType.TOKEN_NOT_FOUND,{tokenName:e})})}}class Ea{static validateAmount(e){const t=wo(e);try{Lo(t,"amount")}catch(t){throw new va(t.message,ba.INVALID_AMOUNT,{amount:e})}}static validateUniqueKey(e){if(!Ye(e)&&Qe(e)){if(e.length>Ee.MAX_LENGTH)throw new _(`Unique key too long. Maximum length: ${Ee.MAX_LENGTH}`);if(!Ee.PATTERN.test(e))throw new va('Invalid unique key format. Must start with "galaswap-operation-" or "galaconnect-operation-"',ba.INVALID_AMOUNT,{uniqueKey:e})}}}class Ia extends n.ChainCallDTO{constructor(e){super(),this.from=e.from,this.to=e.to,this.quantity=e.quantity,this.tokenInstance=e.tokenInstance,this.uniqueKey=e.uniqueKey,e.signedPayload&&(this.signature=e.signedPayload.signature,this.domain=e.signedPayload.domain,this.types=e.signedPayload.types,e.signedPayload.prefix&&(this.prefix=e.signedPayload.prefix))}static fromTokenClassKey(e,t,n,r,i){let o;if("string"==typeof r){o={...ua(r),instance:"0"}}else o={collection:r.collection,category:r.category,type:r.type,additionalKey:r.additionalKey,instance:"0"};return new Ia({from:e,to:t,quantity:n,tokenInstance:o,uniqueKey:i||la()})}static forGALA(e,t,n,r){return new Ia({from:e,to:t,quantity:n,tokenInstance:{collection:"GALA",category:"Unit",type:"none",additionalKey:"none",instance:"0"},uniqueKey:r||la()})}getTokenClassKey(){return Gs(this.tokenInstance)}toSigningPayload(){return{from:this.from,to:this.to,quantity:this.quantity,tokenInstance:this.tokenInstance,uniqueKey:this.uniqueKey}}}class xa extends n.ChainCallDTO{constructor(e){super(),this.tokenInstances=e.tokenInstances,this.uniqueKey=e.uniqueKey,e.signedPayload&&(this.signature=e.signedPayload.signature,this.domain=e.signedPayload.domain,this.types=e.signedPayload.types,e.signedPayload.prefix&&(this.prefix=e.signedPayload.prefix))}static fromTokens(e,t){const n=e.map(e=>{let t;if("string"==typeof e.tokenClassKey){t={...ua(e.tokenClassKey),instance:"0"}}else t={collection:e.tokenClassKey.collection,category:e.tokenClassKey.category,type:e.tokenClassKey.type,additionalKey:e.tokenClassKey.additionalKey,instance:"0"};return{quantity:e.quantity,tokenInstanceKey:t}});return new xa({tokenInstances:n,uniqueKey:t?.uniqueKey||la()})}static fromTokenClassKey(e,t,n){return xa.fromTokens([{tokenClassKey:t,quantity:e}],n)}static forGALA(e,t){return new xa({tokenInstances:[{quantity:e,tokenInstanceKey:{collection:"GALA",category:"Unit",type:"none",additionalKey:"none",instance:"0"}}],uniqueKey:t?.uniqueKey||la()})}getTokenClassKey(){if(0===this.tokenInstances.length)return;return Gs(this.tokenInstances[0].tokenInstanceKey)}toSigningPayload(){return{tokenInstances:this.tokenInstances,uniqueKey:this.uniqueKey}}}function Ca(e){if(!e||"object"!=typeof e)return!1;const t=e;return Qe(t.amount)&&(void 0!==t.tokenId||Qe(t.tokenName))}function Na(e){if(!e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every(Ca)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}var Ba;exports.BurnErrorType=void 0,(Ba=exports.BurnErrorType||(exports.BurnErrorType={})).TOKEN_NOT_FOUND="TOKEN_NOT_FOUND",Ba.INVALID_AMOUNT="INVALID_AMOUNT",Ba.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",Ba.SIGNATURE_FAILED="SIGNATURE_FAILED",Ba.NETWORK_ERROR="NETWORK_ERROR",Ba.WALLET_REQUIRED="WALLET_REQUIRED",Ba.VALIDATION_ERROR="VALIDATION_ERROR";class _a extends Error{constructor(e,t,n){super(e),this.type=t,this.details=n,this.name="BurnError"}}const Pa="gala-transfer-successful",Ra="token-transfer-successful",Da="token-locked-successfully",La="token-unlocked-successfully",Oa="transfer-successful-no-id",Ua=50;class Ma extends hs{constructor(e,t,n,r=!1){super(e,r),this.wallet=t,this.tokenResolver=n,this.signatureHelper=t?new fa(t):void 0}async transferGala(e){if(this.validateTransferGalaData(e),!this.wallet||!this.signatureHelper)throw new va("Wallet required for GALA transfer operations",ba.WALLET_REQUIRED);try{const t=ft(e.recipientAddress),n=ft(this.wallet.address),r=Ia.forGALA(n,t,e.amount,e.uniqueKey),i=await this.signatureHelper.signTransferToken(r.toSigningPayload()),o=new Ia({...r.toSigningPayload(),signedPayload:i});this.logger.debug("[DEBUG] Full GALA Transfer Request Payload:",JSON.stringify(o,null,2));const s=await this.http.post("/api/asset/token-contract/TransferToken",o);if(!s)throw new va("No response from GalaChain transfer service",ba.NETWORK_ERROR);return this.logger.debug("[DEBUG] Transfer response:",JSON.stringify(s,null,2)),this.extractTransactionIdFromResponse(s,"gala")}catch(t){throw this.handleTransferError(t,"GALA transfer failed",e)}}async transferToken(e){if(this.validateTransferTokenData(e),!this.wallet||!this.signatureHelper)throw new va("Wallet required for token transfer operations",ba.WALLET_REQUIRED);try{const t=ft(e.to),n=ft(this.wallet.address);let r;if(e.tokenId)r=ea(e.tokenId),this.logger.debug("[DEBUG] Using provided tokenId:",e.tokenId),this.logger.debug("[DEBUG] Normalized Token Instance:",JSON.stringify(r,null,2));else{if(!e.tokenName)throw new va("Must provide either tokenId or tokenName for token identification",ba.TOKEN_NOT_FOUND);r=await this.resolveTokenInstance(e.tokenName)}const i=new Ia({from:n,to:t,quantity:e.amount,tokenInstance:r,uniqueKey:e.uniqueKey||la()}),o=await this.signatureHelper.signTransferToken(i.toSigningPayload()),s=new Ia({...i.toSigningPayload(),signedPayload:o});this.logger.debug("[DEBUG] Full Transfer Request Payload:",JSON.stringify(s,null,2));const a=await this.http.post("/api/asset/token-contract/TransferToken",s);if(!a)throw new va("No response from GalaChain transfer service",ba.NETWORK_ERROR);return this.logger.debug("[DEBUG] Token transfer response:",JSON.stringify(a,null,2)),this.extractTransactionIdFromResponse(a,"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}':`,JSON.stringify(t,null,2)),t}catch(t){if(t instanceof va)throw t;throw new va(`Failed to resolve token class key for '${e}': ${A(t)}`,ba.TOKEN_NOT_FOUND,{tokenName:e})}}async burnTokens(e){if(this.validateBurnTokensData(e),!this.wallet||!this.signatureHelper)throw new _a("Wallet required for token burn operations",exports.BurnErrorType.WALLET_REQUIRED);try{const t=[];for(const n of e.tokens){let e;if(n.tokenId)e=ea(n.tokenId),this.logger.debug("[DEBUG] Using provided tokenId:",n.tokenId);else{if(!n.tokenName)throw new _a("Must provide either tokenId or tokenName for token identification",exports.BurnErrorType.TOKEN_NOT_FOUND);e=await this.resolveTokenInstance(n.tokenName)}t.push({quantity:n.amount,tokenInstanceKey:e})}const n=new xa({tokenInstances:t,uniqueKey:e.uniqueKey||la()}),r=await this.signatureHelper.signBurnTokens(n.toSigningPayload()),i=new xa({...n.toSigningPayload(),signedPayload:r});this.logger.debug("[DEBUG] Full Burn Request Payload:",JSON.stringify(i,null,2));const o=await this.http.post("/api/asset/token-contract/BurnTokens",i);if(!o)throw new _a("No response from GalaChain burn service",exports.BurnErrorType.NETWORK_ERROR);try{x(o,"Token burn operation")}catch(e){throw new P(A(e),500)}return this.logger.debug("[DEBUG] Token burn response:",JSON.stringify(o,null,2)),this.extractBurnResult(o)}catch(t){throw this.handleBurnError(t,"Token burn failed",e)}}validateTransferGalaData(e){if(!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return Qe(t.recipientAddress)&&Qe(t.amount)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)}(e))throw new _("Invalid GALA transfer data: missing required fields");if(!mt(e.recipientAddress))throw new va("Invalid recipient address format",ba.INVALID_RECIPIENT,{recipientAddress:e.recipientAddress});Ea.validateAmount(e.amount),Ea.validateUniqueKey(e.uniqueKey)}validateTransferTokenData(e){if(!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return Qe(t.to)&&Qe(t.amount)&&(void 0!==t.tokenId||Qe(t.tokenName))&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)}(e))throw new _("Invalid token transfer data: missing required fields");if(!mt(e.to))throw new va("Invalid recipient address format",ba.INVALID_RECIPIENT,{recipientAddress:e.to});if(!e.tokenId&&!e.tokenName)throw new va("Must provide either tokenId or tokenName for token identification",ba.TOKEN_NOT_FOUND);if(e.tokenName)try{it(e.tokenName,"tokenName")}catch{throw new va("Invalid token name format",ba.TOKEN_NOT_FOUND,{tokenName:e.tokenName})}Ea.validateAmount(e.amount),Ea.validateUniqueKey(e.uniqueKey)}validateBurnTokensData(e){if(!Na(e))throw new _a("Invalid burn data: missing required fields",exports.BurnErrorType.VALIDATION_ERROR);if(e.tokens.length>Ua)throw new _a(`Batch size exceeds maximum limit of ${Ua} tokens per burn operation`,exports.BurnErrorType.VALIDATION_ERROR);for(const t of e.tokens){if(!t.tokenId&&!t.tokenName)throw new _a("Must provide either tokenId or tokenName for token identification",exports.BurnErrorType.TOKEN_NOT_FOUND);const e=wo(t.amount);try{Ro(e)}catch{throw new _a("Burn amount must be a positive number",exports.BurnErrorType.INVALID_AMOUNT,{amount:t.amount})}}}async resolveTokenInstance(e){try{const t=await this.tokenResolver.resolveTokenToVault(e);if(t){const n=na(t);return this.logger.debug(`[DEBUG] Token resolution for '${e}' (launchpad):\n Vault Address: ${t}\n Token Instance: ${JSON.stringify(n,null,2)}`),n}const n={collection:is(e),category:"Unit",type:"none",additionalKey:"none",instance:"0"};return this.logger.debug(`[DEBUG] Token resolution for '${e}' (standard format):\n Token Instance: ${JSON.stringify(n,null,2)}`),n}catch(t){if(t instanceof va)throw t;throw new va(`Failed to resolve token '${e}': ${A(t)}`,ba.TOKEN_NOT_FOUND,{tokenName:e})}}extractTransactionIdFromResponse(e,t){if(e&&"object"==typeof e){if("Status"in e&&"Data"in e)try{x(e,"Extract transaction ID");const n=e;if(Array.isArray(n.Data)&&n.Data.length>0)switch(t){case"gala":return Pa;case"token":return Ra;case"lock":return Da;case"unlock":return La}return Oa}catch{}if("transactionId"in e&&"string"==typeof e.transactionId&&e.transactionId)return e.transactionId}throw new va("Operation succeeded but transaction ID could not be extracted",ba.NETWORK_ERROR)}extractBurnResult(e){const t=[];if(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(e.Data&&e.Data.length>0){const t=e.Data[0];n=t.transactionId||t.txnId||t.TxnId||t.id||void 0}return{...void 0!==n&&{transactionId:n},burned:t}}handleTransferError(e,t,n){if(e instanceof va)return e;if(e instanceof _)return new va(A(e),ba.INVALID_AMOUNT);if(I(e)&&e.response){const t=e.response.status,r=e.response.data;if(400===t)return new va(("string"==typeof r?.message?r.message:void 0)||"Invalid transfer request",ba.INVALID_AMOUNT);if(403===t)return new va("Insufficient balance for transfer",ba.INSUFFICIENT_BALANCE);if(404===t){const e={};return"tokenName"in n&&(e.tokenName=n.tokenName),new va("Token not found",ba.TOKEN_NOT_FOUND,e)}}if("object"==typeof e&&null!==e&&"code"in e&&("ECONNABORTED"===E(e)||"ETIMEDOUT"===E(e)))return new va("Transfer request timed out",ba.NETWORK_ERROR);const r=A(e);return new va(r||t,ba.NETWORK_ERROR)}handleBurnError(e,t,n){if(e instanceof _a)return e;let r=t,i=exports.BurnErrorType.NETWORK_ERROR;if(I(e)){const n=e.response?.data;if("object"==typeof n&&null!==n&&n.Message&&"string"==typeof n.Message){r=`${t}: ${n.Message}`;const e=n.Message.toLowerCase();e.includes("insufficient")||e.includes("balance")?i=exports.BurnErrorType.INSUFFICIENT_BALANCE:(e.includes("not found")||e.includes("token"))&&(i=exports.BurnErrorType.TOKEN_NOT_FOUND)}}else S(e)&&(r=`${t}: ${A(e)}`);const o={};return void 0!==n?.tokens?.[0]?.tokenName&&(o.tokenName=n.tokens[0].tokenName),void 0!==n?.tokens?.[0]?.amount&&(o.amount=n.tokens[0].amount),new _a(r,i,Object.keys(o).length>0?o:void 0)}}class Fa extends hs{constructor(e,t,n,r=!1,i){super(e,r),this.wallet=t,this.tokenResolver=n,this.publicAxios=i,this.balanceService=new Zs(e,r),this.tokenService=new sa(e,r,i),this.lockService=new Ta(e,t,n,r),this.transferService=new Ma(e,t,n,r)}async fetchPoolDetails(e){this.validateFetchPoolDetailsData(e);const t=await this.http.post("/api/asset/launchpad-contract/FetchSaleDetails",e);if(!t)throw H("No response from GalaChain service",500);br(()=>x(t,"Failed to fetch pool details"),"Failed to fetch pool details",this.logger,e=>{throw H(A(e),500)});const n=t.Data.reverseBondingCurveConfiguration,r=n?.minFeePortion??"0",i=n?.maxFeePortion??"0",o=!Co(r)||!Co(i),s=t.Data;return s.reverseBondingCurveMinFeePortion=r,s.reverseBondingCurveMaxFeePortion=i,s.hasReverseBondingCurveFee=o,s.isGraduated="Finished"===t.Data.saleStatus,delete s.reverseBondingCurveConfiguration,t}async fetchLaunchTokenFee(){const e=await this.http.post("/api/asset/launchpad-contract/FetchLaunchpadFeeAmount",{});if(!e)throw H("No response from GalaChain service",500);return br(()=>x(e,"Failed to fetch launch token fee"),"Failed to fetch launch token fee",this.logger,e=>{throw H(A(e),500)}),e.Data.feeAmount}validateFetchPoolDetailsData(e){if(!$s(e))throw z("data","Fetch pool details data");if(!e.vaultAddress||"string"!=typeof e.vaultAddress)throw z("vaultAddress","Vault address");if(!e.vaultAddress.startsWith("service|Token$Unit$"))throw new _("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 $a extends ds{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}=nt(e,"tokenName","tokenId",{description:"token identifier"});if(n&&t)return this.logger.debug(`Fetching spot price by tokenId: ${t}`),this._fetchDexTokenSpotPrice(t);throw new _("tokenName parameter requires LaunchpadSDK routing - call LaunchpadSDK.fetchTokenPrice({tokenName}) instead","tokenName","INVALID_PARAMS")}async _fetchDexTokenSpotPrice(e){if(!e)throw z("tokenId","Token ID");try{const t=ea(e),n=Ks(t),r=ca(n);if(this.logger.debug(`Fetching DEX spot price for token: ${r}`),!this.dexBackendHttp)throw H("DEX Backend API client not configured");const i=mr(await this.dexBackendHttp.request({method:"GET",url:"/v1/trade/price",params:{token:r}}));if(!i||"string"!=typeof i)throw new _("Invalid price response: data must be a string, got "+typeof i,"data","INVALID_RESPONSE");const o=function(e,t){if(Ye(e)||""===e)throw z(t);const n="number"==typeof e?e:parseFloat(String(e));if(isNaN(n))throw ee(t,e);if(!isFinite(n))throw ee(t,e);return n}(i,"price"),s=n;let a;try{if(this.cache){const e=this.cache.getByTokenId(s);if(e?.symbol)return a=e.symbol,this.logger.debug(`DEX spot price for ${a} (cached): $${o}`),{symbol:a,price:o}}this.logger.debug(`Symbol cache miss for ${s}, fetching from API`);a=(await this.fetchTokenDetails(e)).symbol,this.cache&&(this.cache.setByTokenId(s,{symbol:a}),this.logger.debug(`Cached symbol for ${s}: ${a}`)),this.logger.debug(`DEX spot price for ${a}: $${o}`)}catch(e){this.logger.debug(`Could not fetch token details for symbol, falling back to token format parsing: ${S(e)?e.message:String(e)}`),a=os("Token"===t.collection?t.type:t.collection),this.logger.debug(`DEX spot price for ${a} (fallback): $${o}`)}return{symbol:a,price:o}}catch(e){if(e instanceof _)throw e;throw H(`Failed to fetch DEX spot price: ${A(e)}`)}}async fetchLaunchpadTokenSpotPrice(e,t,n){if(!Qe(e))throw new _(Ar,"tokenName",B.REQUIRED);try{if(n)try{this.logger.debug(`Checking graduation status for token: ${e}`);const t=await n(e);if(t&&t.isGraduated){this.logger.debug(`Token ${e} is graduated, using DEX spot price`);const n=Ks(t.sellingToken);return this._fetchDexTokenSpotPrice(n)}}catch(t){this.logger.debug(`Could not determine graduation status for ${e}, falling back to bonding curve: ${A(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(!i)throw H("GALA price not available");const o=Re(r.amount,0)/1e18;if(o<=0)throw new _(`Invalid token amount calculation: ${o}`,"amount","INVALID_CALCULATION");const s=i.price/o;return{symbol:os(e),price:s}}catch(t){if(S(t))throw H(`Failed to calculate launchpad token spot price for ${e}: ${A(t)}`);throw H(`Failed to calculate launchpad token spot price for ${e}: ${A(t)}`)}}async fetchTokenDetails(e){this.logger.debug("Fetching token details from GalaChain for tokenId:",e);try{if(!this.galaChainService)throw H("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 _||S(t))&&("NetworkError"===t.name||A(t).includes("Token not found")))throw t;throw H(`Failed to fetch token details from GalaChain for ${e}: ${A(t)}`,500)}}async fetchAllDexSeasons(){try{if(!this.dexBackendHttp)throw H("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(!e||"object"!=typeof e)return this.logger.warn("Seasons endpoint returned invalid data:",e),[];{const n=mr(e);if(Array.isArray(n))t=n;else if(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=>({id:e?.id??0,name:e?.name??"",start:He(e?.start),end:He(e?.end),rulesId:e?.rules_id??0}));return this.logger.debug(`Fetched ${n.length} DEX seasons`),n}catch(e){if(S(e)&&A(e).includes("not configured"))throw e;if(I(e)&&404===e.response?.status)return this.logger.warn("Seasons endpoint not available"),[];throw H(`Failed to fetch DEX seasons: ${A(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{ae(e,"seasonId")}catch{throw z("seasonId","Season ID must be a positive number")}try{if(!this.dexBackendHttp)throw H("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(!t||"object"!=typeof t)return this.logger.warn("Leaderboard endpoint returned invalid data:",t),{entries:[],seasonId:e,totalEntries:0};{const r=mr(t);if(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=>({wallet:e?.wallet??"",rank:e?.rank??0,totalXp:e?.total_xp??0,distributionPercent:e?.distribution_percent??0,liquidityXp:e?.liquidity_xp??0,tradingXp:e?.trading_xp??0,masteryTitles:(e?.mastery_titles??[]).map(e=>({name:e?.name??"",type:e?.type??"trade",order:e?.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(S(t)&&A(t).includes("must be a positive number"))throw t;throw H(`Failed to fetch DEX leaderboard for season ${e}: ${A(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 H("DEX Backend API client not configured");const e=mr(await this.dexBackendHttp.request({method:"GET",url:"/explore/volume"}));if(!e)throw H("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 H(`Failed to fetch DEX volume summary: ${A(e)}`)}}}function qa(e){return{maxAcceptableReverseBondingCurveFee:qe(e.maxAcceptableReverseBondingCurveFee)}}class Ka extends n.ChainCallDTO{constructor(e,t,n="0",r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=qe(t),this.expectedToken=Ke(n),this.extraFees=qa(r)}}class Ga extends n.ChainCallDTO{constructor(e,t,n,r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=Ke(t),this.expectedNativeToken=qe(n),this.extraFees=qa(r)}}class za extends n.ChainCallDTO{constructor(e,t,n="0",r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=Ke(t),this.expectedNativeToken=qe(n),this.extraFees=qa(r)}}class Wa extends n.ChainCallDTO{constructor(e,t,n,r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=qe(t),this.expectedToken=Ke(n),this.extraFees=qa(r)}}const Ha={BuyNativeDto:Ka,BuyExactDto:Ga,SellExactDto:za,SellNativeDto:Wa};class ja extends ds{constructor(e,t=!1){super(t),this.walletProvider=e}async signDTO(e,t,r){try{this.logger.debug("🔐 Signing DTO:",{methodName:t,dtoKeys:Object.keys(e)});const r=this.generateEIP712Types(t,e),i=n.calculatePersonalSignPrefix(e),o={...e,prefix:i},{signature:s,domain:a}=await this.signWithEthersWallet(r,o),c={...e,signature:s,types:r,domain:a};return this.logger.debug("✅ DTO signed successfully:",{payloadKeys:Object.keys(c),signatureLength:s.length}),c}catch(e){this.logger.error("❌ Signature generation failed:",e);throw V(`Failed to sign DTO: ${A(e)}`)}}async signWithEthersWallet(e,t){try{let n,r;if(this.walletProvider.signTypedData&&!this.walletProvider.getNetwork)n={name:"ethereum",chainId:1},r=await this.walletProvider.signTypedData(n,e,t);else{if(!this.walletProvider.getNetwork||!this.walletProvider.signTypedData)throw j("Wallet provider does not support typed data signing","walletProvider");{const i=await this.walletProvider.getNetwork();n={name:i.name,chainId:Oe(i.chainId,1)},r=await this.walletProvider.signTypedData(n,e,t)}}return{signature:r,domain:n}}catch(e){throw V(`Ethers.js signing failed: ${A(e)}`)}}generateEIP712Types(e,t){const n={};n[e]=[];const r=Object.fromEntries(Object.entries(t).filter(([e,t])=>void 0!==t)),i=(e,t,r,o=!1)=>{if(void 0!==t){if(Array.isArray(t)){if(0===t.length)return;const s=i(e,t[0],r,!0);return o||n[r].push({name:e,type:(s??e)+"[]"}),s?s+"[]":void 0}if("object"==typeof t&&null!==t){if(n[e])throw new _(`Type name collision not supported: ${e}`,"fieldValue","TYPE_COLLISION");return n[e]=[],Object.entries(t).forEach(([t,n])=>{i(t,n,e)}),o||n[r].push({name:e,type:e}),e}{let i;switch(typeof t){case"string":i="string";break;case"number":i="uint256";break;case"boolean":i="bool";break;default:throw new _(`Unsupported type for field "${e}": ${typeof t} (value: ${JSON.stringify(t)})`,"fieldValue","UNSUPPORTED_TYPE")}return o||n[r].push({name:e,type:i}),i}}};return Object.entries(r).forEach(([t,n])=>{i(t,n,e)}),this.logger.debug("📝 Generated EIP-712 types:",n),n}}class Va extends ds{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`,o=`$tokenBalance$${n.toStringKey()}$${e}`,s=`$tokenBalance$${n.toStringKey()}$${e}`,a=`$tokenBalance$${r.toStringKey()}$${e}`,c=[i,o,s,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=A(e);throw new _(`Failed to generate stringsInstructions: ${t}`,"vaultAddress","INVALID_VAULT_ADDRESS")}}createTokenInstance(e){const t=new s.TokenClassKey;return t.collection=e.toLowerCase(),t.category="Unit",t.type="none",t.additionalKey="none",this.logger.debug("🪙 Created token instance:",{symbol:e,lowercaseCollection:e.toLowerCase(),stringKey:t.toStringKey()}),t}createGalaInstance(){const e=new s.TokenClassKey;return e.collection="GALA",e.category="Unit",e.type="none",e.additionalKey="none",this.logger.debug("🟡 Created GALA instance:",{stringKey:e.toStringKey()}),e}extractTokenSymbolFromVault(e){if(!Qe(e))throw z("vaultAddress","Vault address");try{const t=ra(e);return this.logger.debug("🔍 Extracted token symbol:",{vaultAddress:e,tokenSymbol:t}),t}catch(e){if(e instanceof _)throw W("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad");throw e}}validateVaultAddress(e){if(!Qe(e))throw z("vaultAddress","Vault address");if(!e.startsWith("service|Token$Unit$"))throw W("vaultAddress",'starting with "service|Token$Unit$"');if(!e.endsWith("$launchpad"))throw W("vaultAddress",'ending with "$launchpad"');const t=function(e){if(!Qe(e))return null;const t=e.match(/^service\|Token\$Unit\$([^$]+)\$eth:([a-fA-F0-9]{40})\$launchpad$/);return t?{tokenSymbol:t[1],creatorAddress:t[2].toLowerCase()}:null}(e);if(!t)throw W("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 W("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 ua(e)}catch(e){if(e instanceof _)throw W("stringKey","format: collection$category$type$additionalKey (4 parts)");throw e}}}function Xa(e,t,n){let r;oe(t,0,1,"slippageToleranceFactor");try{r=Me(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 o;switch(n){case"buy-native":case"sell-exact":o=r.minus(i);break;case"buy-exact":case"sell-native":o=r.plus(i);break;default:throw new Error(`Unknown operation type: ${n}`)}return Bo(o)&&(o=wo(0)),bo(o)}class Qa extends hs{constructor(e,t,n=!1,r,i,o=.05,s=.01){super(e,n),this.tokenResolver=t,this.walletProvider=r,this.userAddress=i,this.defaultSlippageToleranceFactor=o,this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor=s,this.bundleEndpoint="/bundle",r&&i&&(this.signatureService=new ja(r,n),this.tokenKeyService=new Va(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 ts(()=>this.http.post(this.bundleEndpoint,t),{errorContext:"Bundle transaction submission failed",logger:this.logger})}catch(e){return{success:!1,error:this.formatErrorMessage(e)}}return n?(this.logger.debug("📥 Bundle API response:",{success:n.success,hasData:gr(n),error:n.error}),this.handleBundleResponse(n)):{success:!1,error:"No response from bundle API"}}catch(e){if(e instanceof _)return{success:!1,error:A(e)};throw e}}validateBundleData(e){if(!e)throw z("bundleData","Bundle data");if(!e.signedDto)throw z("signedDto","Signed DTO");if(!Qe(e.method))throw z("method","Method name");if(!Array.isArray(e.stringsInstructions))throw W("stringsInstructions","an array of resource tracking strings");if(0===e.stringsInstructions.length)throw new _("stringsInstructions cannot be empty","stringsInstructions","EMPTY_ARRAY");const t=["BuyWithNative","BuyExactToken","SellExactToken","SellWithNative"];if(!t.includes(e.method))throw W("method",`one of: ${t.join(", ")}`);e.stringsInstructions.forEach((e,t)=>{if(!Qe(e))throw new _(`stringsInstructions[${t}] must be a non-empty string`,`stringsInstructions[${t}]`,"INVALID_INSTRUCTION");if(!Xs(e))throw new _(`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=mr(e);if(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(I(e)&&e.response){const t=mr(e.response);if(t&&"object"==typeof t){const e=t;if(e.error)return String(e.error);if(e.message)return String(e.message)}}return A(e)||"Unknown bundle transaction error"}async getBundlerTransactionResult(e){try{if(!Qe(e))throw z("transactionId","Transaction ID");let t;this.logger.debug("🔍 Checking bundler transaction result:",e);try{t=await ts(()=>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 t?(this.logger.debug("📊 Bundler transaction result:",t),{success:!0,data:t}):{success:!1,error:"No response from bundler transaction query"}}catch(e){if(e instanceof _)return{success:!1,error:A(e)};throw e}}async cancelTransaction(e){try{if(!Qe(e))throw z("transactionId","Transaction ID");let t;this.logger.debug("🚫 Cancelling transaction:",e);try{t=await ts(()=>this.http.delete(`${this.bundleEndpoint}/${e}`),{errorContext:"Failed to cancel transaction",logger:this.logger})}catch(e){return{success:!1,error:this.formatErrorMessage(e)}}return t?(this.logger.debug("🗑️ Transaction cancellation response:",t),{success:!0,data:t}):{success:!1,error:"No response from transaction cancellation"}}catch(e){if(e instanceof _)return{success:!1,error:A(e)};throw e}}async getHealthStatus(){this.logger.debug("🏥 Checking bundle service health");try{const e=await ts(()=>this.http.get(`${this.bundleEndpoint}/health`),{errorContext:"Bundle service health check failed",logger:this.logger});return e?(this.logger.debug("💚 Bundle service health:",e),{success:!0,data:e}):{success:!1,error:"No response from bundle service health check"}}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:o,effectiveMaxFee:s,vaultAddress:a}=await this.prepareTradingOperation(t,e.maxAcceptableReverseBondingCurveFee,e.maxAcceptableReverseBondingCurveFeeSlippageFactor,e.slippageToleranceFactor);if("native"===r){if(!i)throw new _("expectedAmount is required for native buy operations. Use getBuyTokenAmount() first to calculate expected tokens.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Xa(i,o,"buy-native");this.logger.debug("BuyNative slippage applied:",{originalExpectedTokens:i,slippageFactor:o,adjustedMinTokens:e});const t=new Ha.BuyNativeDto(a,n,e,{maxAcceptableReverseBondingCurveFee:s});return await this.executeBundleTransaction(t,"BuyWithNative",a)}{if(!i)throw new _("expectedAmount is required for exact buy operations. Use getBuyTokenAmount() first to calculate expected GALA cost.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Xa(i,o,"buy-exact");this.logger.debug("BuyExact slippage applied:",{originalExpectedGalaCost:i,slippageFactor:o,adjustedMaxGalaCost:e});const t=new Ha.BuyExactDto(a,n,e,{maxAcceptableReverseBondingCurveFee:s});return await this.executeBundleTransaction(t,"BuyExactToken",a)}}async sellToken(e){this.ensureTradingServicesAvailable();const{tokenName:t,amount:n,type:r,expectedAmount:i}=e,{effectiveSlippageFactor:o,effectiveMaxFee:s,vaultAddress:a}=await this.prepareTradingOperation(t,e.maxAcceptableReverseBondingCurveFee,e.maxAcceptableReverseBondingCurveFeeSlippageFactor,e.slippageToleranceFactor);if("exact"===r){if(!i)throw new _("expectedAmount is required for exact sell operations. Use getSellTokenAmount() first to calculate expected GALA.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Xa(i,o,"sell-exact");this.logger.debug("SellExact slippage applied:",{originalExpectedGala:i,slippageFactor:o,adjustedMinGala:e});const t=new Ha.SellExactDto(a,n,e,{maxAcceptableReverseBondingCurveFee:s});return await this.executeBundleTransaction(t,"SellExactToken",a)}{if(!i)throw new _("expectedAmount is required for native sell operations. Use getSellTokenAmount() first to calculate tokens to sell.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Xa(i,o,"sell-native");this.logger.debug("SellNative slippage applied:",{originalExpectedTokensToSell:i,slippageFactor:o,adjustedMaxTokensToSell:e});const t=new Ha.SellNativeDto(a,n,e,{maxAcceptableReverseBondingCurveFee:s});return await this.executeBundleTransaction(t,"SellWithNative",a)}}async prepareTradingOperation(e,t,n,r){const{effectiveSlippageFactor:i,effectiveMaxFee:o}=this.calculateEffectiveSlippage(t,n,r),s=await this.resolveTokenNameToVault(e);if(!s)throw G(e);return{effectiveSlippageFactor:i,effectiveMaxFee:o,vaultAddress:s}}calculateEffectiveSlippage(e,t,n){const r=n??this.defaultSlippageToleranceFactor,i=t??this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor;let o=e||"0";return e&&(o=Xa(e,i,"buy-exact"),this.logger.debug("Reverse bonding curve fee slippage applied:",{baseFee:e,slippageFactor:i,adjustedMaxFee:o})),{effectiveSlippageFactor:r,effectiveFeeSlippageFactor:i,effectiveMaxFee:o}}ensureTradingServicesAvailable(){if(!this.signatureService||!this.tokenKeyService)throw j("Trading services not available. BundleService requires walletProvider and userAddress for trading operations.","walletProvider");if(!this.userAddress)throw z("userAddress","User address")}async executeBundleTransaction(e,t,n){this.ensureTradingServicesAvailable();try{e.uniqueKey=`galaswap - operation - ${o.v4()}-${Date.now()}-${this.userAddress}`;const r=await this.signatureService.signDTO(e,t,this.userAddress),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 a=await this.submitTransaction(s);if(a.success){const e=mr(a);if(e)return this.logger.debug("✅ Bundle transaction submitted:",e),{success:!0,data:{transactionId:e,message:"Transaction submitted successfully. Monitor WebSocket for completion."}}}throw new D(String(a.error||"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 Ja{constructor(e=0){this.defaultTtlMs=e,this.cache=new Map}get(e){const t=this.cache.get(e);if(t){if(!(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 Ya(e,t,n,r={}){const{logger:i,cacheNullish:o=!1,keyGenerator:s}=r,a=s?s(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 u=await t();return null!=u?(n.set(a,u),i&&i.debug(`Cached result for key: ${a}`)):o&&(n.set(a,u),i&&i.debug(`Cached nullish result for key: ${a}`)),u}var Za,ec;!function(e){e.PROCESSED="PROCESSED",e.COMPLETED="COMPLETED",e.SUCCESS="SUCCESS",e.FAILED="FAILED",e.ERROR="ERROR",e.PROCESSING="PROCESSING",e.PENDING="PENDING"}(Za||(Za={})),exports.SDKTransactionStatus=void 0,(ec=exports.SDKTransactionStatus||(exports.SDKTransactionStatus={})).PENDING="pending",ec.PROCESSING="processing",ec.COMPLETED="completed",ec.FAILED="failed",ec.TIMEOUT="timeout";const tc={[Za.PROCESSED]:exports.SDKTransactionStatus.COMPLETED,[Za.COMPLETED]:exports.SDKTransactionStatus.COMPLETED,[Za.SUCCESS]:exports.SDKTransactionStatus.COMPLETED,[Za.FAILED]:exports.SDKTransactionStatus.FAILED,[Za.ERROR]:exports.SDKTransactionStatus.FAILED,[Za.PROCESSING]:exports.SDKTransactionStatus.PROCESSING,[Za.PENDING]:exports.SDKTransactionStatus.PENDING};class nc{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 rc extends ds{constructor(e,t=!1){super(t),this.socket=null,this.listeners=new Map,this.timeouts=new Map,this.hasOnAnyListener=!1,this.MAX_BUFFER_SIZE=1e3,this.config={reconnectAttempts:5,reconnectDelay:2e3,timeout:3e5,...e},this.debug=t,this.reconnectionManager=new nc({maxAttempts:this.config.reconnectAttempts??5,baseDelayMs:this.config.reconnectDelay??2e3}),this.eventBuffer=new Ja(3e4),this.isSocketIOAvailable=this.checkSocketIOAvailability()}checkSocketIOAvailability(){try{return"function"==typeof a.io||(this.logger.warn('⚠️ Socket.IO client not available. Install "socket.io-client" package.'),!1)}catch(e){return this.logger.warn("⚠️ Socket.IO availability check failed:",e),!1}}async connect(){return new Promise((e,t)=>{wr(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:",A(e)),e}this.logger.debug("🔌 Connecting to Socket.IO server:",this.config.url),this.socket=a.io(this.config.url,{transports:["websocket"],reconnection:!0,reconnectionAttempts:this.config.reconnectAttempts||5,reconnectionDelay:this.config.reconnectDelay||2e3}),this.socket.on("connect",()=>{this.logger.debug("✅ Socket.IO connected successfully:",this.socket?.id),this.logger.debug("📡 Connected to bundle backend WebSocket:",this.config.url),this.logger.debug("🔗 Ready to monitor transaction updates"),this.reconnectionManager.reset(),e()}),this.socket.on("connect_error",e=>{this.logger.error("❌ Socket.IO connection error:",e),t(e)}),this.socket.on("disconnect",e=>{this.logger.debug(`🔌 Socket.IO disconnected: ${e}`),this.handleReconnect()}),this.socket.on("error",e=>{this.logger.error("❌ Socket.IO error:",e)}),this.socket.onAny((e,...t)=>{if(e&&t.length>0&&"object"==typeof t[0]&&null!==t[0]){const n=t[0],r=n.status||n.Status;r&&"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=>{throw this.logger.error("Socket.IO connection failed:",e),t(e),e}).catch(t)})}async monitorTransaction(e,t){this.listeners.set(e,t),this.logger.debug(`📡 Starting to monitor transaction: ${e}`),this.logger.debug(`📡 WebSocket connected: ${!!this.socket&&this.socket.connected}`);const n=this.eventBuffer.get(e);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:exports.SDKTransactionStatus.TIMEOUT,message:`Transaction monitoring timeout - no response after ${n} seconds`,timestamp:Date.now()};this.logger.debug(`📡 Transaction timeout for ${e} (${n}s)`),t(i),this.listeners.delete(e),this.timeouts.delete(e),this.socket?.off(e)}},r);if(this.timeouts.set(e,i),this.socket&&this.socket.connected)this.socket.off(e),this.logger.debug(`📡 Listening for transaction updates: ${e}`),this.logger.debug(`📡 WebSocket connection ID: ${this.socket.id}`),this.logger.debug(`📡 WebSocket URL: ${this.config.url}`),this.socket.on(e,n=>{this.processTransactionEvent(e,n,t)});else{const n={transactionId:e,status:exports.SDKTransactionStatus.FAILED,message:"WebSocket not connected - cannot monitor transaction",timestamp:Date.now()};t(n),this.listeners.delete(e),this.timeouts.delete(e)}}processTransactionEvent(e,t,n){this.logger.debug(`📡 Socket.IO transaction update for ${e}:`,JSON.stringify(t,null,2));const r=t,i=r?.data,o=r?.status||r?.Status||i?.status||i?.Status;let s=r?.message||r?.Message||i?.message||i?.Message||r?.error||i?.error;Qe(s)||(s=o===Za.FAILED||o===Za.ERROR?"Transaction failed - check transaction details":o===Za.COMPLETED||o===Za.PROCESSED||o===Za.SUCCESS?"Transaction completed successfully":o?`Transaction status: ${o}`:"Unknown transaction status");const a=r?.blockHash||i?.blockHash,c=r?.gasUsed||i?.gasUsed,u=r?.Data||i?.Data,l={transactionId:e,status:this.mapSocketStatus(o),message:"string"==typeof s?s:"Transaction update received",timestamp:Date.now(),...a&&{blockHash:a},...c&&{gasUsed:c},...u&&{data:u}};if(this.logger.debug(`📡 Mapped status for ${e}: ${o} -> ${l.status}`),this.logger.debug(`📡 Final message: "${s}"`),n(l),l.status===exports.SDKTransactionStatus.COMPLETED||l.status===exports.SDKTransactionStatus.FAILED){this.listeners.delete(e);const t=this.timeouts.get(e);t&&(clearTimeout(t),this.timeouts.delete(e)),this.socket?.off(e),this.logger.debug(`📡 Cleaned up listener for ${e} (${l.status})`)}}async waitForTransaction(e){return new Promise((t,n)=>{this.monitorTransaction(e,e=>{e.status===exports.SDKTransactionStatus.COMPLETED?t(e):e.status!==exports.SDKTransactionStatus.FAILED&&e.status!==exports.SDKTransactionStatus.TIMEOUT||n(new Error(`Transaction ${e.status}: ${e.message}`))})})}mapSocketStatus(e){const t=e?.toUpperCase();return tc[t]||exports.SDKTransactionStatus.PENDING}async handleReconnect(){this.reconnectionManager.shouldRetry()?(this.reconnectionManager.recordAttempt(),this.logger.debug(`🔄 Attempting Socket.IO reconnect ${this.reconnectionManager.getStatusString()}`),setTimeout(()=>{this.socket&&!this.socket.connected&&this.socket.connect()},this.reconnectionManager.getNextDelay())):this.logger.error("❌ Socket.IO max reconnection attempts reached")}disconnect(){this.socket&&(this.listeners.forEach((e,t)=>{this.socket?.off(t)}),this.listeners.clear(),this.timeouts.forEach(e=>{clearTimeout(e)}),this.timeouts.clear(),this.eventBuffer.clear(),this.logger.debug("🧹 Cleared event buffer"),this.hasOnAnyListener&&(this.socket.offAny(),this.hasOnAnyListener=!1,this.logger.debug("🧹 Removed onAny debug listener")),this.socket.disconnect(),this.socket=null,this.logger.debug("🔌 Socket.IO disconnected"))}isConnected(){return this.socket?.connected||!1}getSocket(){return this.socket}}class ic extends ds{constructor(e,t=!1){super(t),this.poolService=e,this.cache=new Map}async resolveTokenToVault(e){if(!Qe(e))throw z("tokenName","Token name");const t=rs(e),n=this.get(t);if(n)return n;try{const n=await this.poolService.resolveTokenNameToVault(e);return n&&this.set(t,n),n}catch{return null}}async resolveTokenClassKey(e){const t=await this.resolveTokenToVault(e);if(!t)throw G(e);return this.parseVaultAddressToTokenClassKey(t)}get(e){return this.cache.get(rs(e))||null}set(e,t){this.cache.set(rs(e),t)}clear(){this.cache.clear()}getStats(){return{size:this.cache.size,keys:Array.from(this.cache.keys())}}preWarm(e){for(const{tokenName:t,vaultAddress:n}of e)this.set(t,n)}parseVaultAddressToTokenClassKey(e){try{return ta(e)}catch(e){if(e instanceof _)throw W("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad","Vault address");throw e}}}class oc extends hs{constructor(e,t=!1,n){super(e,t),this.tokenResolverService=n}async fetchTokenClassKeyByTokenName(e){if(!e)throw z("tokenName","Token name");if(!this.tokenResolverService)throw j("TokenResolverService is required for token name resolution. Ensure it is passed to PriceHistoryService constructor.","tokenResolverService");try{rt(e)}catch(e){throw j(A(e),"tokenName")}this.logger.debug(`Resolving token name '${e}' to token class key`);try{const t=await this.tokenResolverService.resolveTokenToVault(e);if(!t)throw j(`Token '${e}' not found or could not be resolved to vault address`,"tokenName");this.logger.debug(`Resolved '${e}' to vault address: ${t}`);const n=Ks(ta(t));return this.logger.debug(`Extracted token class key: ${n}`),n}catch(t){if(S(t)&&A(t).includes("ConfigurationError"))throw t;throw H(`Failed to resolve token name '${e}': ${A(t)}`,500)}}async fetchPriceHistory(e){if(!e)throw z("options","Fetch options");return this.logger.debug("Fetching price history from DEX Backend API with options:",e),this.validateOptions(e),wr(async()=>{let t=e.tokenId;if(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(!t)throw j("Token ID is required but was not provided or resolved","tokenId");const{normalizeToTokenInstanceKey:n}=await Promise.resolve().then(function(){return oa}),r=ca(Ks(n(t))),{from:i,to:o,sortOrder:s="DESC"}=e,a=De(e.page,1),c=De(e.limit,10),u={token:r,page:String(a),limit:String(c)};i&&(u.from=i.toISOString()),o&&(u.to=o.toISOString());const l=function(e){if(e)return e.toLowerCase()}(s);l&&(u.order=l),this.logger.debug(`Querying price snapshots for token ${r}, page ${a}, limit ${c}`);const h=await this.http.get("/price-oracle/fetch-price",u);if(!h)throw H("No response from price history service",500);const d=this.transformApiResponseToPriceHistory(h);return this.logger.debug(`Found ${d.snapshots.length} price snapshots, total ${d.total}`),d},"Failed to fetch price history",this.logger)}transformApiResponseToPriceHistory(e){if(!gr(e))throw H("Invalid API response: missing data wrapper",500);const t=mr(e);if(!t||"object"!=typeof t)throw H("Invalid API response: data is not an object",500);const n=t,r=n.data;if(!Array.isArray(r))throw H("Invalid API response: missing or invalid data.data array",500);const i=n.meta;if(!i||"object"!=typeof i)throw H("Invalid API response: missing data.meta pagination info",500);const o=i,s=r.map(e=>{if("object"!=typeof e||null===e)throw H("Invalid API response: invalid snapshot item",500);const t=e;return{price:t.price,timestamp:He(t.createdAt),tokenId:Ks({collection:t.collection,category:t.category,type:t.type,additionalKey:t.additionalKey})}}),a=Le(o.currentPage,1),c=Le(o.totalPages,1);return{snapshots:s,page:a,limit:Le(o.pageSize,50),total:Le(o.totalItems,0),totalPages:c,hasNext:a<c,hasPrevious:a>1}}async fetchAllPriceHistory(e){if(!e)throw z("options","Fetch options");return this.logger.debug("Fetching all price history with options:",e),wr(async()=>{const t=await Zo((t,n)=>this.fetchPriceHistory({...e,page: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});return function(e,t=e.length,n="items"){const r=e.length||0;return{page:1,limit:r,total:t,totalPages:r>0?Xo(t,r):1,hasNext:!1,hasPrevious:!1,[n]:e}}(t.items,t.total,"snapshots")},"Failed to fetch all price history",this.logger)}validateOptions(e){const t=De(e.page,1),n=De(e.limit,10),{from:r,to:i,sortOrder:o}=e;if(nt(e,"tokenName","tokenId",{description:"token identifier"}),r&&!je(r))throw j("from must be a valid Date","from");if(i&&!je(i))throw j("to must be a valid Date","to");o&&le(o,"sortOrder"),Ze(t,n,50)}}class sc extends Error{constructor(e,t,n){super(`API Error [${e}]: ${t}`),this.status=e,this.message=t,this.details=n,this.name="ApiError"}}function ac(e){return"object"==typeof e&&null!==e&&"collection"in e&&"category"in e&&"type"in e&&"additionalKey"in e&&"string"==typeof e.collection&&"string"==typeof e.category&&"string"==typeof e.type&&"string"==typeof e.additionalKey}function cc(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.positionId&&ac(t.token0ClassKey)&&ac(t.token1ClassKey)&&"number"==typeof t.fee&&"number"==typeof t.tickLower&&"number"==typeof t.tickUpper&&"string"==typeof t.liquidity&&"string"==typeof t.feeGrowthInside0Last&&"string"==typeof t.feeGrowthInside1Last&&"string"==typeof t.tokensOwed0&&"string"==typeof t.tokensOwed1}class uc{constructor(e){this.client=k(e.baseUrl,e.timeout??3e4)}async getPoolData(e){return wr(async()=>{if("string"==typeof e.token0||"string"==typeof e.token1)throw new _(`GalaChain API getPoolData requires TokenClassKey objects, not strings. Received: token0="${"string"==typeof e.token0?e.token0:"[object]"}", token1="${"string"==typeof e.token1?e.token1:"[object]"}". Convert pipe-delimited tokens using parseToken() before calling getPoolData(). Example: parseToken("GALA|Unit|none|none") → { collection: "GALA", category: "Unit", type: "none", additionalKey: "none" }`,"token","INVALID_TOKEN_FORMAT");const t=await this.client.post("/api/asset/dexv3-contract/GetPoolData",e);this.validateResponse(t.data);const n=t.data.Data;if(!function(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.token0&&"string"==typeof t.token1&&ac(t.token0ClassKey)&&ac(t.token1ClassKey)&&"number"==typeof t.fee&&"number"==typeof t.tickSpacing&&"string"==typeof t.liquidity&&"string"==typeof t.sqrtPrice&&"number"==typeof t.tick&&"string"==typeof t.feeGrowthGlobal0&&"string"==typeof t.feeGrowthGlobal1}(n))throw new sc(t.status,"Invalid pool data response format",n);return n},"GalaChainGatewayClient.getPoolData",void 0,e=>{throw this.handleError(e,"getPoolData")})}async getSlot0(e){return wr(async()=>{if("string"==typeof e.token0||"string"==typeof e.token1)throw new _(`GalaChain API getSlot0 requires TokenClassKey objects, not strings. Received: token0="${"string"==typeof e.token0?e.token0:"[object]"}", token1="${"string"==typeof e.token1?e.token1:"[object]"}". Convert pipe-delimited tokens using parseToken() before calling getSlot0(). Example: parseToken("GALA|Unit|none|none") → { collection: "GALA", category: "Unit", type: "none", additionalKey: "none" }`,"token","INVALID_TOKEN_FORMAT");const t=await this.client.post("/api/asset/dexv3-contract/GetSlot0",e);this.validateResponse(t.data);const n=t.data.Data;if(!function(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.sqrtPrice&&"number"==typeof t.tick&&"string"==typeof t.liquidity}(n))throw new sc(t.status,"Invalid slot0 data response format",n);return n},"GalaChainGatewayClient.getSlot0",void 0,e=>{throw this.handleError(e,"getSlot0")})}async getPositions(e){return wr(async()=>{const t=await this.client.post("/api/asset/dexv3-contract/GetPositions",e);this.validateResponse(t.data);const n=t.data.Data;let r;r=n&&"object"==typeof n&&"positions"in n&&Array.isArray(n.positions)?n.positions:n&&"object"==typeof n&&"positionId"in n?[n]:Array.isArray(n)?n:[];for(const e of r)if(!cc(e))throw new sc(t.status,"Invalid position in response",e);return{positions:r,count:r.length}},"GalaChainGatewayClient.getPositions",void 0,e=>{throw this.handleError(e,"getPositions")})}async getPositionById(e,t,n,r,i,o,s){return wr(async()=>{let a,c;if(void 0!==t&&void 0!==n&&void 0!==r&&void 0!==i&&void 0!==o){a={owner:e,token0:"string"==typeof t?{collection:t,category:"Unit",type:"none",additionalKey:"none"}:t,token1:"string"==typeof n?{collection:n,category:"Unit",type:"none",additionalKey:"none"}:n,fee:r,tickLower:i,tickUpper:o},s&&(a.positionId=s),c=`${e}/${t}/${n}/${r}`}else a={positionId:e},c=e;const u=await this.client.post("/api/asset/dexv3-contract/GetPositions",a);this.validateResponse(u.data);const l=u.data.Data;let h;if(l&&"object"==typeof l&&"positionId"in l&&!("positions"in l))h=l;else{if(!(l&&Array.isArray(l.positions)&&l.positions.length>0))throw new sc(404,`Position not found: ${c}`);h=l.positions[0]}const d={Data:h,Status:u.status};return void 0!==u.data.Message&&(d.Message=u.data.Message),d},"GalaChainGatewayClient.getPositionById",void 0,t=>{throw this.handleError(t,`getPositionById(${e})`)})}async getRemoveLiquidityEstimation(e){return wr(async()=>{const t=await this.client.post("/api/asset/dexv3-contract/GetRemoveLiquidityEstimation",e);this.validateResponse(t.data);const n=t.data.Data;if("string"!=typeof n.amount0||"string"!=typeof n.amount1)throw new sc(t.status,"Invalid removal estimation response format",n);return n},"GalaChainGatewayClient.getRemoveLiquidityEstimation",void 0,e=>{throw this.handleError(e,"getRemoveLiquidityEstimation")})}validateResponse(e){if(!e||"object"!=typeof e)throw new sc(500,"Invalid response format: not an object");if(!("Data"in e)||!("Status"in e))throw new sc(500,"Invalid response format: missing Data or Status field");if(e.Status>=400)throw new sc(e.Status,e.Message??"Gateway error",e.Data)}handleError(e,t){if(e instanceof sc)return e;if(I(e)){const n=e.response?.status??500,r=e.response?.data,i=r?.Message??A(e);return new sc(n,`${t}: ${i}`,r?.Data??void 0)}return new sc(500,`${t}: ${A(e)}`)}}class lc{constructor(e){this.http=e}async getUserAssets(e,t=20,n=0){return wr(async()=>{if(!Qe(e))throw z("walletAddress","Wallet address");const r=jo(Math.floor(n/t)+1),i={};i.address=e,i.page=r,i.limit=t;const o=await this.http.get("/user/assets",i);if(!o||"object"!=typeof o)throw new sc(500,"Invalid response format: not an object");const s=mr(o);if(!s||"object"!=typeof s)throw new sc(500,"Invalid response format: missing data wrapper");const a=s.token;if(!Array.isArray(a))throw new sc(500,"Invalid response format: token array must be an array");const c=[];for(const e of a){if("object"!=typeof e||null===e)throw new sc(500,"Invalid asset in response: asset must be an object");const t=e;if(!Qe(t.symbol)||!Qe(t.name))throw new sc(500,"Invalid asset in response: missing symbol or name",t);const n="number"==typeof t.decimals?t.decimals:"string"==typeof t.decimals?parseInt(t.decimals,10):void 0;if("number"!=typeof n||isNaN(n))throw new sc(500,"Invalid asset in response: decimals must be a number",t);const r={tokenId:t.compositeKey||`${t.symbol}$Unit$none$none`,symbol:t.symbol,name:t.name,decimals:n,balance:t.quantity||"0"};t.image&&(r.imageUrl=t.image),t.verify&&(r.verified=t.verify),c.push(r)}const u={tokens:c,count:"number"==typeof s.count?s.count:c.length};return void 0!==s.totalValue&&(u.totalValue=String(s.totalValue)),u},`getUserAssets(${e})`,void 0,t=>{throw this.handleError(t,`getUserAssets(${e})`)})}async fetchTokenList(e={}){return wr(async()=>{const{address:t,search:n,page:r=1,limit:i=20}=e,o={page:r,limit:Vo(i,1,20)};t&&(o.address=t),n&&(o.search=n);const s=await this.http.get("/user/token-list",o);if(!s||"object"!=typeof s)throw new sc(500,"Invalid response format: not an object");const a=mr(s);if(!a||"object"!=typeof a)throw new sc(500,"Invalid response format: missing data wrapper");const c=a.token;if(!Array.isArray(c))throw new sc(500,"Invalid response format: token array must be an array");const u=[];for(const e of c){if("object"!=typeof e||null===e)throw new sc(500,"Invalid token in response: must be an object");const t=e;if(!Qe(t.symbol))throw new sc(500,'Invalid token in response: missing required field "symbol"',{token:t});if(!Qe(t.name))throw new sc(500,'Invalid token in response: missing required field "name"',{token:t});const n=t.decimals;if("string"!=typeof n&&"number"!=typeof n)throw new sc(500,'Invalid token in response: missing required field "decimals"',{token:t});if(!Qe(t.compositeKey))throw new sc(500,'Invalid token in response: missing required field "compositeKey"',{token:t});u.push({image:"string"==typeof t.image?t.image:"",name:t.name,symbol:t.symbol,decimals:String(n),description:"string"==typeof t.description?t.description:"",verify:"boolean"==typeof t.verify&&t.verify,compositeKey:t.compositeKey,additionalKey:"string"==typeof t.additionalKey?t.additionalKey:"",category:"string"==typeof t.category?t.category:"",type:"string"==typeof t.type?t.type:"",collection:"string"==typeof t.collection?t.collection:"",subscribePrice:"boolean"==typeof t.subscribePrice&&t.subscribePrice,quantity:"string"==typeof t.quantity?t.quantity:"0"})}return{token:u,count:"number"==typeof a.count?a.count:u.length}},"fetchTokenList",void 0,e=>{throw this.handleError(e,"fetchTokenList")})}handleError(e,t){if(e instanceof sc)return e;if(I(e)){const n=e.response?.status??500,r=e.response?.data,i=r?.message??r?.Message??A(e),o=r?.Data??r?.data??void 0;if(r){e.config}return new sc(n,`${t}: ${i}`,o)}return new sc(500,`${t}: ${A(e)}`)}}class hc{static createClient(e,t=6e4){return k(e,t)}}function dc(e){try{if(!Qe(e))throw new Error("Token must be a non-empty string");return js(e)}catch(t){throw new _(`Invalid pipe-delimited token: "${e}". Expected format: "collection|category|type|additionalKey". Error: ${A(t)}`,"pipeDelimitedToken","INVALID_PIPE_DELIMITED_TOKEN_FORMAT")}}const fc=10;class gc extends ds{constructor(e,t,n){if(super(!1),this.pricingConcurrency=5,this.tokenConverter=new aa,this.webSocketService=t,this.dexQuoteService=n,this.getWalletAddress=e.getWalletAddress,this.galaChainBaseUrl=e.galaChainBaseUrl,this.bundlerBaseUrl=e.bundlerBaseUrl,this.gatewayBaseUrl=e.gatewayBaseUrl,this.privateKey=e.privateKey,!(e.gatewayBaseUrl&&e.bundlerBaseUrl&&e.dexBackendBaseUrl&&e.dexBackendHttp))throw new R("GSwapService requires explicit gatewayBaseUrl, bundlerBaseUrl, dexBackendBaseUrl, and dexBackendHttp configuration. These must be provided by LaunchpadSDK to ensure environment alignment.","gswapConfig");try{this.gatewayClient=new uc({baseUrl:e.gatewayBaseUrl,timeout:3e4}),this.dexBackendClient=new lc(e.dexBackendHttp),this.logger.debug("HTTP clients initialized successfully",{gatewayUrl:e.gatewayBaseUrl,dexBackendUrl:e.dexBackendBaseUrl})}catch(e){throw this.logger.error("Failed to initialize HTTP clients",e),new R("Failed to initialize GSwapService HTTP clients","httpClients")}}setPricingConcurrency(e){if(e<1)throw J("pricingConcurrency",1,e,"Pricing concurrency");e>100&&this.logger.warn("Pricing concurrency > 100 may cause performance issues",{concurrency:e}),this.pricingConcurrency=e,this.logger.debug("Updated pricing concurrency",{concurrency:this.pricingConcurrency})}async getSwapQuoteExactInput(e){try{if(wo(e.amount).isLessThanOrEqualTo(0))throw new L("Amount must be greater than zero",{amount:e.amount,fromToken:e.fromToken,toToken:e.toToken});if(!this.dexQuoteService)throw new L("DexQuoteService not configured - cannot provide quotes",{fromToken:e.fromToken,toToken:e.toToken});this.logger.debug("Getting swap quote for exact input",{fromToken:e.fromToken,toToken:e.toToken,amount:e.amount});const t=this.tokenConverter.toLaunchpadFormat(e.fromToken),n=this.tokenConverter.toLaunchpadFormat(e.toToken),[r,i]=t<n?[t,n]:[n,t],o=[3e3,500,1e4];let s;for(const a of o)try{const o=await this.dexQuoteService.fetchCompositePoolData({token0:r,token1:i,fee:a,gatewayBaseUrl:this.gatewayBaseUrl}),s=await this.dexQuoteService.calculateDexPoolQuoteExactAmount({compositePoolData:o,fromToken:t,toToken:n,amount:e.amount}),c=wo(s.currentSqrtPrice),u=wo(s.newSqrtPrice),l=c.gt(u)?c.minus(u).dividedBy(c):wo(0),h=wo(s.amount0),d=wo(s.amount1),f=Bo(h),g=Bo(d);this.logger.debug("=== AMOUNT SELECTION RAW DATA ===",{"quoteResult.amount0":s.amount0,"quoteResult.amount1":s.amount1,"amount0BN.isNegative()":f,"amount1BN.isNegative()":g});const p=f?h:d;this.logger.debug("=== AMOUNT SELECTION RESULT ===",{selectedFromAmount0:f,selectedAmount:p.toFixed(),selectedAmountAbs:p.absoluteValue().toFixed()});const m=p.absoluteValue().toFixed();return{fromToken:e.fromToken,toToken:e.toToken,inputAmount:e.amount,estimatedOutput:m,feeTier:a,priceImpact:l.toFixed(),executionPrice:this.calculateExecutionPrice(e.amount,m),currentSqrtPrice:s.currentSqrtPrice,newSqrtPrice:s.newSqrtPrice}}catch(e){s=e,this.logger.debug("DexQuoteService failed for fee tier, trying next",{feeTier:a,error:S(e)?e.message:"Unknown error"})}throw s||new L("No available fee tiers for quote",{feeTiers:o,fromToken:e.fromToken,toToken:e.toToken})}catch(e){this.handleGSwapError("Failed to get swap quote for exact input",L,e)}}async getSwapQuoteExactOutput(e){try{if(wo(e.amount).isLessThanOrEqualTo(0))throw new L("Amount must be greater than zero",{amount:e.amount,fromToken:e.fromToken,toToken:e.toToken});if(!this.dexQuoteService)throw new L("DexQuoteService not configured - cannot provide quotes",{fromToken:e.fromToken,toToken:e.toToken});this.logger.debug("Getting swap quote for exact output",{fromToken:e.fromToken,toToken:e.toToken,amount:e.amount});const t=this.tokenConverter.toLaunchpadFormat(e.fromToken),n=this.tokenConverter.toLaunchpadFormat(e.toToken),[r,i]=t<n?[t,n]:[n,t],o=[3e3,500,1e4];let s;for(const a of o)try{const o=await this.dexQuoteService.fetchCompositePoolData({token0:r,token1:i,fee:a,gatewayBaseUrl:this.gatewayBaseUrl}),s=await this.dexQuoteService.calculateDexPoolQuoteExactAmount({compositePoolData:o,fromToken:t,toToken:n,amount:e.amount}),c=wo(s.currentSqrtPrice),u=wo(s.newSqrtPrice),l=c.gt(u)?c.minus(u).dividedBy(c):wo(0),h=o.pool.token0,d="string"==typeof h?Hs(h).collection:"object"==typeof h&&null!==h&&"tokenName"in h?h.tokenName:String(h),f=Hs(n).collection===d?s.amount1:s.amount0;return{fromToken:e.fromToken,toToken:e.toToken,inputAmount:f,estimatedOutput:e.amount,feeTier:a,priceImpact:l.toFixed(),executionPrice:this.calculateExecutionPrice(f,e.amount),currentSqrtPrice:s.currentSqrtPrice,newSqrtPrice:s.newSqrtPrice}}catch(e){s=e,this.logger.debug("DexQuoteService failed for fee tier, trying next",{feeTier:a,error:S(e)?e.message:"Unknown error"})}throw s||new L("No available fee tiers for quote",{feeTiers:o,fromToken:e.fromToken,toToken:e.toToken})}catch(e){this.handleGSwapError("Failed to get swap quote for exact output",L,e)}}async executeSwap(e){try{if(!this.privateKey)throw new R("GSwapService not initialized with signing capability (privateKey required)","privateKey");this.logger.debug("Executing swap",{fromToken:e.fromToken,toToken:e.toToken,inputAmount:e.inputAmount});const{gswapToken0:t,gswapToken1:n}=this.convertTokenPair(e.fromToken,e.toToken),r=ko(e.estimatedOutput,e.slippageTolerance||.01),i=this.getWalletAddress();if(!i)throw new _("Wallet address required for swap execution","walletAddress",B.REQUIRED);let o;try{const t=await this.getSwapQuoteExactInput({fromToken:e.fromToken,toToken:e.toToken,amount:e.inputAmount});o=t.currentSqrtPrice,this.logger.debug("Quote refetch successful - extracted sqrtPrices",{currentSqrtPrice:o,newSqrtPrice:t.newSqrtPrice,feeTier:t.feeTier})}catch(t){this.logger.debug("Could not re-fetch quote for sqrtPrice, using default",{fromToken:e.fromToken,toToken:e.toToken,error:A(t)})}const s={fromToken:t,toToken:n,inputAmount:e.inputAmount,minOutput:r.toFixed(),feeTier:e.feeTier,walletAddress:i,slippageTolerance:e.slippageTolerance||.01,...!Ye(o)&&{currentSqrtPrice:o}},a=await this.sendSwapToBundler(s);this.logger.debug("Swap submitted, monitoring transaction",{transactionId:a,fromToken:e.fromToken,toToken:e.toToken}),await this.ensureWebSocketConnected();const c=await this.webSocketService.waitForTransaction(a);return{transactionId:c.transactionId,status:c.status,fromToken:e.fromToken,toToken:e.toToken,inputAmount:e.inputAmount,outputAmount:e.estimatedOutput,feeTier:e.feeTier,slippageTolerance:e.slippageTolerance||.01,timestamp:new Date(c.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(a)}}}catch(e){const t=e;this.handleGSwapError("Failed to execute swap",O,e,{transactionHash:t?.txHash})}}async getUserAssets(e,t=1,n=20){return wr(async()=>{if(!mt(e))throw new M(W("walletAddress","a valid address (0x..., eth|..., or client|...)").message,new Error("INVALID_ADDRESS_FORMAT"),e,"INVALID_ADDRESS");this.logger.debug("Fetching user assets",{walletAddress:e,page:t,limit:n});return(await this.dexBackendClient.fetchTokenList({address:e,page:t,limit:n})).token.filter(e=>"0"!==e.quantity).map(e=>this.transformRawTokenToUserAsset(e)).filter(e=>null!==e)},"Failed to fetch user assets",this.logger,this.createGSwapErrorHandler(M,{walletAddress:e,page:t,limit:n}))}async getAllUserAssets(e){return wr(async()=>{if(!mt(e))throw new M(W("walletAddress","a valid address (0x..., eth|..., or client|...)").message,new Error("INVALID_ADDRESS_FORMAT"),e,"INVALID_ADDRESS");this.logger.debug("Fetching all user assets (auto-paginated with optimization)",{walletAddress:e});let t=!1;const n=await Zo(async(n,r)=>{const i=await this.dexBackendClient.fetchTokenList({address:e,page:n,limit:r}),o=[];for(const e of i.token){if("0"===e.quantity){t=!0;break}const n=this.transformRawTokenToUserAsset(e);n&&o.push(n)}return{items:o,page:n,limit:r,total:o.length,totalPages:1,hasNext:!t&&i.token.length===r,hasPrevious:n>1}},{maxPages:20,pageSize:20,logger:this.logger});return this.logger.debug("Fetched all user assets",{walletAddress:e,totalAssets:n.items.length}),n.items},"Failed to fetch all user assets",this.logger,this.createGSwapErrorHandler(M,{walletAddress:e}))}async fetchAvailableDexTokens(e={}){return wr(async()=>{const{search:t,page:n=1,limit:r=20}=e;this.logger.debug("Fetching available DEX tokens",{search:t,page:n,limit:r});const i=await this.dexBackendClient.fetchTokenList({...!Ye(t)&&{search:t},page:n,limit:r}),o=i.token.map(e=>this.transformRawTokenToDexToken(e)),s=Qo(Ho(n,r),r,i.count);return{tokens:o,count:i.count,page:n,limit:r,hasMore:s}},"Failed to fetch available DEX tokens",this.logger,this.createGSwapErrorHandler(M,{...e}))}async fetchAllAvailableDexTokens(e={}){return wr(async()=>{const{search:t}=e;this.logger.debug("Fetching all available DEX tokens (auto-paginated)",{search:t});const n=await Zo(async(e,n)=>{const r=await this.dexBackendClient.fetchTokenList({...!Ye(t)&&{search:t},page:e,limit:n});return{items:r.token.map(e=>this.transformRawTokenToDexToken(e)),page:e,limit:n,total:r.token.length,totalPages:1,hasNext:r.token.length===n,hasPrevious:e>1}},{maxPages:20,pageSize:20,logger:this.logger});return this.logger.debug("Fetched all available DEX tokens",{search:t,totalTokens:n.items.length}),n.items},"Failed to fetch all available DEX tokens",this.logger,this.createGSwapErrorHandler(M,e))}async getPoolInfo(e,t){try{if(!e)throw z("tokenA","Token A");if(!t)throw z("tokenB","Token B");this.logger.debug("Fetching pool info",{tokenA:e,tokenB:t});const{gswapToken0:n,gswapToken1:r}=this.convertTokenPair(e,t),i=[500,3e3,1e4];let o=wo(0),s=0;for(const a of i)try{const e="string"==typeof n?Hs(n):n,t="string"==typeof r?Hs(r):r,i=await this.gatewayClient.getPoolData({token0:e,token1:t,fee:a});i&&(o=o.plus(wo(i.liquidity)),s++)}catch{this.logger.debug("Pool not found for fee tier",{tokenA:e,tokenB:t,feeTier:a})}return{tokenA:e,tokenB:t,liquidity:o.toFixed(),feeTiers:i,swapCount:s}}catch(n){return this.logger.warn("Failed to fetch pool info",n),this.logger.debug("Pool error details",{error:new U(`Failed to fetch pool info: ${A(n)}`,n,e,t,this.extractGSwapErrorCode(n))}),{tokenA:e,tokenB:t,liquidity:"0",feeTiers:[500,3e3,1e4],swapCount:0}}}chunkArray(e,t){const n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}async fetchPositionPrices(e){const t=this.pricingConcurrency;if(0===e.length)return new Map;const n=new Map;for(const t of e){const e=`${t.token0}|${t.token1}|${t.feeTier}`;n.has(e)||n.set(e,{token0:t.token0,token1:t.token1,feeTier:t.feeTier})}const r=Array.from(n.values()),i=this.chunkArray(r,t);this.logger.debug("Fetching pricing for positions",{totalPositions:e.length,uniquePoolsToPrice:n.size,chunks:i.length,concurrency:t});const o=new Map;for(let e=0;e<i.length;e++){const t=i[e];(await Promise.allSettled(t.map(async e=>{const t=await this.getSwapQuoteExactInput({fromToken:e.token0,toToken:e.token1,amount:"1"});return{key:`${e.token0}|${e.token1}|${e.feeTier}`,data:{token0:e.token0,token1:e.token1,feeTier:e.feeTier,currentPrice:t.executionPrice,executionPrice:t.executionPrice,priceImpact:t.priceImpact,estimatedOutput:t.estimatedOutput,pricedAt:new Date}}}))).forEach(e=>{"fulfilled"===e.status?o.set(e.value.key,e.value.data):this.logger.warn("Failed to fetch price for pool",{error:e.reason})})}return o}normalizePositionResponse(e,t){const n=e=>{if(!e)return"";if("string"==typeof e)return e;if("object"==typeof e){if(e.type&&"none"!==e.type)return e.type;if(e.collection)return e.collection;if(e.symbol)return e.symbol;if(e.tokenSymbol)return e.tokenSymbol;if(e.name)return e.name}return""},r=e.token0Symbol||n(e.token0)||n(e.tokenA)||e.tokenSymbol0||"",i=e.token1Symbol||n(e.token1)||n(e.tokenB)||e.tokenSymbol1||"",o=r?this.tokenConverter.normalizeInternalApiResponse(r):"",s=i?this.tokenConverter.normalizeInternalApiResponse(i):"";return{positionId:e.positionId||e.id||"",ownerAddress:t||e.ownerAddress||e.owner||"",token0:o,token1:s,feeTier:e.feeTier||e.fee||e.feeAmount||0,tickLower:e.tickLower||e.lowerTick||0,tickUpper:e.tickUpper||e.upperTick||0,liquidity:String(e.liquidity||e.liquidityAmount||"0"),amount0:String(e.amount0||e.amountA||"0"),amount1:String(e.amount1||e.amountB||"0"),feeAmount0:String(e.feeAmount0||e.feesA||"0"),feeAmount1:String(e.feeAmount1||e.feesB||"0"),...e.createdAt&&{createdAt:new Date(e.createdAt)},...e.updatedAt&&{updatedAt:new Date(e.updatedAt)}}}parseTokenFlexible(e){try{return Hs(e)}catch(t){if(S(t)&&A(t).includes("Plain token string"))return this.logger.debug("Using default TokenClassKey for simple token symbol",{token:e}),{collection:"Token",category:"Unit",type:e,additionalKey:"none"};throw t}}transformRawTokenToDexToken(e){return{image:e.image,name:e.name,symbol:e.symbol,decimals:Oe(e.decimals,18),description:e.description,verified:e.verify,compositeKey:e.compositeKey,additionalKey:e.additionalKey,category:e.category,type:e.type,collection:e.collection,subscribePrice:e.subscribePrice}}transformRawTokenToUserAsset(e){const t=e.symbol||"UNKNOWN";try{const n=e.compositeKey?Hs(e.compositeKey.replace(/\$/g,"|")):Hs(`${t}|Unit|none|none`);return{...this.transformRawTokenToDexToken(e),tokenId:n,balance:bo(e.quantity||"0")}}catch(e){return this.logger.debug(`Skipping asset with processing error: ${t}`,{error:A(e)}),null}}async getUserLiquidityPositions(e,n=10,r,i){try{if(!e)throw z("ownerAddress","Owner address");this.logger.debug("Fetching user liquidity positions",{ownerAddress:e,limit:n,bookmark:r});const o=`${this.galaChainBaseUrl}/api/asset/dexv3-contract/GetUserPositions`,s={user:e,limit:n,bookmark:r||""};this.logger.debug("Sending position query request",{endpoint:o,payload:s});const a=await t.post(o,s,{headers:{"Content-Type":"application/json",Accept:"application/json"}}),c=mr(a);if(200!==a.status||1!==c?.Status)return this.logger.warn("Unexpected API response status",{httpStatus:a.status,apiStatus:c?.Status}),{items:[]};const u=c?.Data||{},l=u.positions||[],h=u.nextBookMark,d=l.filter(e=>null!=e&&"object"==typeof e&&("positionId"in e||"id"in e)).map(t=>this.normalizePositionResponse(t,e));let f;this.logger.debug("Retrieved liquidity positions",{count:d.length,hasNextBookmark:!!h,nextBookmark:h}),i?.withPrices&&d.length>0&&(f=await this.fetchPositionPrices(d));const g={items:d};return Ye(h)||(g.nextBookmark=h),Ye(f)||(g.prices=f),g}catch(t){I(t)&&this.logger.error("Position query failed with HTTP error",{status:t.response?.status,statusText:t.response?.statusText,data:t.response?.data,endpoint:this.galaChainBaseUrl,ownerAddress:e}),this.handleGSwapError("Failed to fetch user liquidity positions",F,t)}}async getAllSwapUserLiquidityPositions(e,t){try{if(!e)throw z("ownerAddress","Owner address");this.logger.debug("Fetching all user liquidity positions (auto-paginated)",{ownerAddress:e});const n=async t=>{const n=await this.getUserLiquidityPositions(e,fc,t,void 0);return{items:n.items,nextBookmark:n.nextBookmark}},r=await async function(e,t={}){const{maxPages:n=1e4,logger:r,pageSize:i=20}=t,o=[];let s,a=0;for(;a<n;){r&&r.debug(`Auto-pagination (bookmark): fetching page ${a+1} with pageSize ${i}`,{bookmark:s});const t=await e(s,i);let n,c,u;if(Array.isArray(t))n=t,c=void 0,u=!1;else{if(!t||"object"!=typeof t||!("items"in t)){r&&r.warn("Auto-pagination (bookmark): received invalid result structure, stopping");break}n=t.items,c=t.nextBookmark,u=!0}if(!Array.isArray(n)){r&&r.warn("Auto-pagination (bookmark): received invalid items array, stopping");break}if(0===n.length){r&&r.debug(`Auto-pagination (bookmark): no items returned on page ${a+1}, exiting loop`);break}o.push(...n),a++,r&&r.debug(`Auto-pagination (bookmark): page ${a} returned ${n.length} items`,{hasNextBookmark:!!c,format:u?"BookmarkPaginationResult":"legacy-array"});const l=n.length<i;if(u&&(""===c||void 0===c)){r&&r.debug("Auto-pagination (bookmark): no nextBookmark returned, reached end of results",{nextBookmark:""===c?"(empty string)":"(undefined)"});break}if(l){r&&r.debug("Auto-pagination (bookmark): received fewer items than limit, reached last page",{received:n.length,pageSize:i,format:u?"BookmarkPaginationResult":"legacy-array"});break}s=c}return a>=n&&r&&r.warn(`Auto-pagination (bookmark): exceeded maxPages limit of ${n}, stopping iteration`),r&&r.debug(`Auto-pagination (bookmark): completed with total items: ${o.length}`,{pageCount:a}),{items:o,total:o.length}}(n,{maxPages:1e4,logger:this.logger,pageSize:fc}),i=r.items;if(this.logger.debug("Fetched all user liquidity positions",{ownerAddress:e,totalPositions:i.length}),t?.withPrices&&i.length>0){return{items:i,prices:await this.fetchPositionPrices(i)}}return i}catch(t){this.handleGSwapError("Failed to fetch all user liquidity positions",F,t,{ownerAddress:e})}}async getLiquidityPosition(e,t){try{if(!e)throw z("ownerAddress","Owner address");if(!t.token0)throw z("token0","Token 0");if(!t.token1)throw z("token1","Token 1");this.logger.debug("Fetching liquidity position",{ownerAddress:e,position:t}),this.validateTickSpacing(t.tickLower,t.tickUpper,t.fee);const{gswapToken0:n,gswapToken1:r}=this.convertTokenPair(t.token0,t.token1),i=dc(n),o=dc(r),s=(await this.gatewayClient.getPositions({owner:e,token0:i,token1:o,fee:t.fee,tickLower:t.tickLower,tickUpper:t.tickUpper})).positions.find(e=>e.tickLower===t.tickLower&&e.tickUpper===t.tickUpper);if(!s||"object"!=typeof s||!("positionId"in s)&&!("id"in s))throw new F("Invalid position data returned from API",null,"INVALID_DATA");const a=this.normalizePositionResponse(s,e);return this.logger.debug("Retrieved liquidity position",{positionId:a.positionId}),a}catch(e){this.handleGSwapError("Failed to fetch liquidity position",F,e)}}async getLiquidityPositionById(e,t,n,r,i,o,s){try{if(!e)throw z("ownerAddress","Owner address");if(!t)throw z("positionId","Position ID");let a;this.logger.debug("Fetching liquidity position by ID",{ownerAddress:e,positionId:t,hasToken0:!!n,hasToken1:!!r,hasFee:!!i,hasTickLower:!Ye(o),hasTickUpper:!Ye(s)});let c=null;const u=5,l=2e3;for(let h=1;h<=u;h++)try{if(n&&r&&!Ye(i)&&!Ye(o)&&!Ye(s))try{this.logger.debug("Attempting compound key lookup",{ownerAddress:e,token0:n,token1:r,feeTier:i,tickLower:o,tickUpper:s});if(a=(await this.gatewayClient.getPositionById(e,n,r,i,o,s,t)).Data,a&&"object"==typeof a&&("positionId"in a||"id"in a)){this.logger.debug("Successfully fetched position via compound key",{attempt:h,positionId:t});break}throw new F("Invalid position data from compound key lookup",null,"INVALID_DATA")}catch(e){this.logger.debug("Compound key lookup failed, trying fallback",{attempt:h,error:S(e)?e.message:e})}try{if(a=(await this.gatewayClient.getPositionById(t)).Data,a&&"object"==typeof a&&("positionId"in a||"id"in a)){this.logger.debug("Successfully fetched position on attempt",{attempt:h,positionId:t});break}throw new F("Invalid position data from direct lookup",null,"INVALID_DATA")}catch(n){this.logger.debug("Direct position lookup failed, trying fallback via GetUserPositions",{attempt:h,positionId:t,error:S(n)?n.message:n});const r=await this.getAllSwapUserLiquidityPositions(e),i=Array.isArray(r)?r:r.items;if(i.length>0){const e=i.find(e=>Is(e.positionId||"",t));if(e){a=e,this.logger.debug("Found position via fallback (GetUserPositions)",{attempt:h,positionId:t,totalPositions:i.length});break}}if(c=te(t),h<u){this.logger.warn("Fallback query did not find position, retrying",{attempt:h,positionId:t,ownerAddress:e,foundCount:i.length}),await new Promise(e=>setTimeout(e,l));continue}}}catch(e){if(h<u){this.logger.warn("Error fetching position, retrying",{attempt:h,positionId:t,error:A(e)}),await new Promise(e=>setTimeout(e,l));continue}c=S(e)?e:new Error(String(e))}if(!a||"object"!=typeof a||!("positionId"in a)&&!("id"in a))throw this.logger.error("Invalid position data returned from API after retries",{positionId:t,resultType:typeof a,resultKeys:a?Object.keys(a):"null",resultValue:JSON.stringify(a),lastError:c?.message}),c||te(t);const h=this.normalizePositionResponse(a,e);return this.logger.debug("Retrieved liquidity position by ID",{positionId:h.positionId}),h}catch(e){this.handleGSwapError("Failed to fetch liquidity position by ID",F,e)}}async fetchSwapPositionDirect(e){try{this.logger.debug("Fetching swap position via direct compound key",{token0:e.token0,token1:e.token1,fee:e.fee,owner:e.owner});const t="string"==typeof e.token0?this.parseTokenFlexible(e.token0):e.token0,n="string"==typeof e.token1?this.parseTokenFlexible(e.token1):e.token1;this.logger.debug("Fetching position via compound key",{token0:e.token0,token1:e.token1,fee:e.fee,owner:e.owner});const r=await this.gatewayClient.getPositions({token0:t,token1:n,fee:e.fee,tickLower:e.tickLower,tickUpper:e.tickUpper,owner:e.owner});if(!r.positions||0===r.positions.length)throw new F("Position not found: No position exists for this compound key",null,"NOT_FOUND");const i=r.positions[0],o=this.normalizePositionResponse(i,e.owner);return this.logger.debug("Retrieved swap position via compound key",{positionId:o.positionId,token0:o.token0,token1:o.token1}),o}catch(e){this.handleGSwapError("Failed to fetch swap position via compound key",F,e)}}async estimateRemoveLiquidity(e){try{if(!e.token0)throw z("token0","Token 0");if(!e.token1)throw z("token1","Token 1");if(!e.liquidity)throw z("liquidity","Liquidity amount");if(!e.owner)throw z("owner","Owner address");this.logger.debug("Estimating liquidity removal",{token0:e.token0,token1:e.token1,owner:e.owner}),this.validateTickSpacing(e.tickLower,e.tickUpper,e.fee);const{gswapToken0:t,gswapToken1:n}=this.convertTokenPair(e.token0,e.token1),r=dc(t),i=dc(n),o=await this.gatewayClient.getRemoveLiquidityEstimation({token0:r,token1:i,fee:e.fee,amount:e.liquidity,tickLower:e.tickLower,tickUpper:e.tickUpper,owner:e.owner});return this.logger.debug("Estimated removal",{result:o}),o}catch(e){this.handleGSwapError("Failed to estimate liquidity removal",F,e)}}async addLiquidityByPrice(e){try{if(!this.privateKey)throw new R("GSwapService not initialized with signing capability (privateKey required)","privateKey");this.logger.debug("Adding liquidity by price",{token0:e.token0,token1:e.token1,priceRange:`${e.minPrice}-${e.maxPrice}`});const{gswapToken0:t,gswapToken1:n}=this.convertTokenPair(e.token0,e.token1);await this.ensureWebSocketConnected(),this.logger.debug("Converting price range to ticks",{token0:e.token0,token1:e.token1,minPrice:e.minPrice,maxPrice:e.maxPrice,fee:e.fee});const r=Hs(t),i=Hs(n),o=(await this.gatewayClient.getPoolData({token0:r,token1:i,fee:e.fee})).tickSpacing;this.logger.debug("Retrieved tick spacing from pool",{tickSpacing:o,fee:e.fee});const s=wo(e.minPrice),a=wo(e.maxPrice),c=Math.floor(Ao(s)),u=Math.ceil(Ao(a)),l=Uo(c,o),h=Uo(u,o);this.logger.debug("Converted price range to ticks",{minPrice:e.minPrice,maxPrice:e.maxPrice,tickLower:l,tickUpper:h,tickSpacing:o});const d=this.getWalletAddress();if(!d)throw new R("GSwapService: No wallet address available - cannot create position","walletAddress");const f="string"==typeof e.token0?Hs(e.token0):e.token0,g="string"==typeof e.token1?Hs(e.token1):e.token1;this.logger.debug("Sending AddLiquidity by price to bundler",{fee:e.fee,tickRange:`${l}-${h}`,walletAddress:d});const p=await this.sendAddLiquidityToBundler({token0:f,token1:g,fee:e.fee,tickLower:l,tickUpper:h,amount0Desired:e.amount0Desired,amount1Desired:e.amount1Desired,amount0Min:e.amount0Min||"0",amount1Min:e.amount1Min||"0",owner:d}),m={transactionId:p};if(m.positionId&&p){this.logger.debug("Position ID returned directly from backend",{transactionId:p,positionId:m.positionId}),await this.ensureWebSocketConnected();const e=await this.webSocketService.waitForTransaction(p);this.logger.debug("Liquidity transaction confirmed on-chain",{transactionId:p,status:e.status});const t=this.getWalletAddress();if(t&&m.positionId)try{const n=await this.getLiquidityPositionById(t,m.positionId),{createdAt:r,updatedAt:i,...o}=n,s=r instanceof Date?r.getTime():"number"==typeof r?r:void 0,a={...m,...o,positionId:m.positionId,status:e.status,transactionId:e.transactionId,timestamp:new Date(e.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(p)}};return Ye(s)||(a.createdAt=s),a}catch(t){return{...m,positionId:m.positionId,status:e.status,transactionId:e.transactionId,timestamp:new Date(e.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(p)}}}}if(p){this.logger.debug("Monitoring liquidity transaction (discovery mode)",{transactionId:p}),await this.ensureWebSocketConnected();const t=await this.webSocketService.waitForTransaction(p);let n;this.logger.debug("Liquidity transaction confirmed on-chain",{transactionId:p,status:t.status});let r=null;await new Promise(e=>setTimeout(e,2e3));try{const t=this.getWalletAddress();if(!t)throw new R("No wallet address available","walletAddress");const i=(await this.getUserLiquidityPositions(t,10)).items;if(i&&i.length>0){const t=Hs(e.token0).collection.toUpperCase(),o=Hs(e.token1).collection.toUpperCase(),s=[];for(const n of i){if(!n||!n.positionId)continue;const r=n.token0?.toUpperCase(),i=n.token1?.toUpperCase();if(!r||!i)continue;const a=Cs(r,i,t,o),c=n.feeTier===e.fee;a&&c&&s.push(n)}s.length>0&&(r=s[s.length-1],n=r.positionId,this.logger.debug("Found newly created position",{positionId:n,expectedTokens:`${e.token0}/${e.token1}`,expectedFee:e.fee,positionCount:i.length}))}}catch(e){this.logger.debug("Error waiting for position indexing",{error:A(e)})}let i=r;if(n)try{i=await this.getLiquidityPositionById(d,n)}catch(e){}const o=i?{ownerAddress:i.ownerAddress,token0:i.token0,token1:i.token1,feeTier:i.feeTier,tickLower:i.tickLower,tickUpper:i.tickUpper,liquidity:i.liquidity,amount0:i.amount0,amount1:i.amount1,feeAmount0:i.feeAmount0,feeAmount1:i.feeAmount1}:{};return{...m,...o,...n&&{positionId:n},status:t.status,transactionId:t.transactionId,timestamp:new Date(t.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(p)}}}return this.logger.warn("No transaction ID in liquidity result, cannot confirm position creation"),m}catch(e){if(S(e)){const t=T(e);t?.split("\n").slice(0,3).join(" | ")}this.handleGSwapError("Failed to add liquidity by price",F,e)}}async addSwapLiquidityByTicks(e){try{if(!this.privateKey)throw new R("GSwapService not initialized with signing capability (privateKey required)","privateKey");const t=this.getWalletAddress();if(!t)throw new R("GSwapService: No wallet address available - cannot create position","walletAddress");this.logger.debug("Adding liquidity by ticks with direct bundler",{token0:e.token0,token1:e.token1,fee:e.fee,walletAddress:t,tickRange:`${e.tickLower}-${e.tickUpper}`});const n="string"==typeof e.token0?Hs(e.token0):e.token0,r="string"==typeof e.token1?Hs(e.token1):e.token1;await this.ensureWebSocketConnected();const i=await this.sendAddLiquidityToBundler({token0:n,token1:r,fee:e.fee,tickLower:e.tickLower,tickUpper:e.tickUpper,amount0Desired:e.amount0Desired,amount1Desired:e.amount1Desired,amount0Min:e.amount0Min||"0",amount1Min:e.amount1Min||"0",owner:t});this.logger.info("Liquidity transaction submitted to bundler",{transactionId:i});const o=this.webSocketService.waitForTransaction(i),s={transactionId:i};if(s.positionId&&i){this.logger.info("Position ID returned directly from backend",{transactionId:i,positionId:s.positionId});const e=await o;this.logger.debug("Liquidity transaction confirmed on-chain",{transactionId:i,status:e.status});const t=this.getWalletAddress();if(t&&s.positionId)try{this.logger.debug("Fetching full position details",{positionId:s.positionId});const n=await this.getLiquidityPositionById(t,s.positionId);this.logger.debug("Fetched full position data",{positionId:n.positionId,liquidity:n.liquidity,amount0:n.amount0,amount1:n.amount1});const{createdAt:r,updatedAt:o,...a}=n,c=r instanceof Date?r.getTime():"number"==typeof r?r:void 0,u={...s,...a,positionId:s.positionId,status:e.status,transactionId:e.transactionId,timestamp:new Date(e.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(i)}};return Ye(c)||(u.createdAt=c),u}catch(t){return this.logger.warn("Could not fetch full position details",{positionId:s.positionId,error:A(t)}),{...s,positionId:s.positionId,status:e.status,transactionId:e.transactionId,timestamp:new Date(e.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(i)}}}}if(i){this.logger.debug("Monitoring liquidity transaction (discovery mode)",{transactionId:i});const n=await o;let r;this.logger.debug("Liquidity transaction confirmed on-chain",{transactionId:i,status:n.status});let a=null;const c="string"==typeof e.token0?e.token0:e.token0?.type??"unknown",u="string"==typeof e.token1?e.token1:e.token1?.type??"unknown";this.logger.debug("Waiting for position indexing after WebSocket confirmation"),this.logger.debug("Looking for matching position",{token0:c,token1:u,fee:e.fee});try{const t=this.getWalletAddress();if(!t)throw new R("No wallet address available","walletAddress");this.logger.debug("Fetching positions from API",{walletAddress:t,pageSize:fc});const n=3,i=5e3,o=3e3;let s=[];for(let c=1;c<=n;c++){const u=1===c?i:o;this.logger.debug("Position discovery attempt",{attempt:c,maxAttempts:n,delayMs:u}),await new Promise(e=>setTimeout(e,u)),this.logger.debug("Querying positions from API",{attempt:c,pageSize:fc});if(s=(await this.getUserLiquidityPositions(t,fc)).items,this.logger.debug("Got positions from API",{count:s?.length||0}),s&&s.length>0){const t=("string"==typeof e.token0?Hs(e.token0).collection:e.token0.collection).toUpperCase(),n=("string"==typeof e.token1?Hs(e.token1).collection:e.token1.collection).toUpperCase(),i=[];for(const r of s){if(!r||!r.positionId)continue;const o=r.token0?.toUpperCase(),s=r.token1?.toUpperCase();if(!o||!s){this.logger.debug("Skipping position with empty tokens",{positionId:r.positionId});continue}const a=Cs(o,s,t,n),c=r.feeTier===e.fee;this.logger.debug("Checking position against target",{positionId:r.positionId,tokens:`${o}/${s}`,tokensMatch:a,fee:r.feeTier,feeMatches:c}),a&&c&&i.push(r)}if(i.length>0){a=i[i.length-1],r=a.positionId,this.logger.info("Found newly created position",{positionId:r,liquidity:a.liquidity,amount0:a.amount0,amount1:a.amount1,fee:a.feeTier}),this.logger.debug("Found newly created position",{positionId:r,expectedTokens:`${e.token0}/${e.token1}`,expectedFee:e.fee,positionCount:s.length});break}this.logger.debug("No matching position found in this attempt")}else this.logger.debug("No positions returned from API in this attempt")}}catch(e){this.logger.error("Error fetching positions during discovery",{error:A(e)}),this.logger.debug("Error waiting for position indexing",{error:A(e)})}this.logger.debug("Position discovery complete",{positionId:r||"not found",found:!!r}),this.logger.debug("Matched position data",{positionId:a?.positionId,liquidity:a?.liquidity,amount0:a?.amount0,amount1:a?.amount1,feeAmount0:a?.feeAmount0,feeAmount1:a?.feeAmount1,token0:a?.token0,token1:a?.token1,feeTier:a?.feeTier});let l=a;if(r)try{this.logger.debug("Fetching full position details",{positionId:r}),l=await this.getLiquidityPositionById(t,r),this.logger.debug("Fetched full position data",{positionId:l.positionId,liquidity:l.liquidity,amount0:l.amount0,amount1:l.amount1,feeAmount0:l.feeAmount0,feeAmount1:l.feeAmount1})}catch(e){this.logger.warn("Could not fetch full position details, using discovered data",{positionId:r,error:A(e)})}const h=l?{ownerAddress:l.ownerAddress,token0:l.token0,token1:l.token1,feeTier:l.feeTier,tickLower:l.tickLower,tickUpper:l.tickUpper,liquidity:l.liquidity,amount0:l.amount0,amount1:l.amount1,feeAmount0:l.feeAmount0,feeAmount1:l.feeAmount1}:{};return{...s,...h,...r&&{positionId:r},status:n.status,transactionId:n.transactionId,timestamp:new Date(n.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(i)}}}return this.logger.warn("No transaction ID in liquidity result, cannot confirm position creation"),s}catch(e){this.handleGSwapError("Failed to add liquidity by ticks",F,e)}}async monitorBundlerTransaction(e,t,n="bundler"){let r;try{const i=await t;r={status:i.status,transactionId:i.transactionId||e,timestamp:i.timestamp||Date.now(),data:i.data},this.logger.debug(`${n} transaction confirmed on-chain`,{transactionId:e,status:r.status})}catch(t){return this.logger.warn(`WebSocket monitoring timeout for ${n} transaction, returning result with transaction ID`,{transactionId:e,error:A(t)}),{transactionId:e,status:"SUBMITTED",timestamp:new Date,wait:async t=>{try{await this.webSocketService.waitForTransaction(e)}catch{this.logger.debug("Explicit wait also timed out",{transactionId:e})}}}}return{transactionId:r.transactionId,status:r.status,timestamp:new Date(r.timestamp),wait:async t=>{await this.webSocketService.waitForTransaction(e)}}}async removeLiquidity(e){try{if(!this.privateKey)throw new R("Private key not available for bundler-direct operations","privateKey");this.logger.debug("Removing liquidity via bundler",{token0:e.token0,token1:e.token1,liquidity:e.liquidity});try{const t=Re(e.liquidity,Number.NaN);if(isNaN(t))throw new _(`Invalid liquidity value: "${e.liquidity}". Must be a valid number. Position ID: ${e.positionId||"unknown"}`,"liquidity","INVALID_VALUE");if(0===t)throw new _(`Cannot remove zero liquidity from position. This would waste gas fees without any effect. Position ID: ${e.positionId||"unknown"}`,"liquidity","ZERO_VALUE")}catch(e){if(S(e)&&A(e).includes("Cannot remove zero liquidity"))throw e;if(S(e)&&A(e).includes("Invalid liquidity value"))throw e;throw e}const t="string"==typeof e.token0?Hs(e.token0):e.token0,n="string"==typeof e.token1?Hs(e.token1):e.token1;await this.ensureWebSocketConnected();const r=await this.sendRemoveLiquidityToBundler(e.tickLower,e.tickUpper,e.liquidity,t,n,e.fee,e.amount0Min||"0",e.amount1Min||"0",e.positionId||"");this.logger.debug("Liquidity removal submitted to bundler",{transactionId:r});const i=this.webSocketService.waitForTransaction(r);return this.monitorBundlerTransaction(r,i,"liquidity removal")}catch(e){this.handleGSwapError("Failed to remove liquidity",F,e)}}async collectPositionFees(e){try{if(!this.privateKey)throw new R("Private key not available for bundler-direct operations","privateKey");if(e.ownerAddress&&e.positionId&&!e.token0){this.logger.debug("Fetching position data before collecting fees",{ownerAddress:e.ownerAddress,positionId:e.positionId});const t=await this.getLiquidityPositionById(e.ownerAddress,e.positionId);if(!t)throw te(e.positionId);if(!t.token0||!t.token1)throw new F("Position missing token information",null,"INVALID_DATA");const{gswapToken0:n,gswapToken1:r}=this.convertTokenPair(t.token0,t.token1);return this.collectPositionFees({token0:n,token1:r,fee:t.feeTier,tickLower:t.tickLower,tickUpper:t.tickUpper,amount0Requested:e.amount0Max||e.amount0Requested||"0",amount1Requested:e.amount1Max||e.amount1Requested||"0",positionId:e.positionId})}if(!e.token0||!e.token1||void 0===e.fee||void 0===e.tickLower||void 0===e.tickUpper)throw z("parameters","token0, token1, fee, tickLower, tickUpper");this.logger.debug("Collecting position fees via bundler",{token0:"string"==typeof e.token0?e.token0:e.token0?.type??"unknown",token1:"string"==typeof e.token1?e.token1:e.token1?.type??"unknown",tickLower:e.tickLower,tickUpper:e.tickUpper});const t="string"==typeof e.token0?Hs(e.token0):e.token0,n="string"==typeof e.token1?Hs(e.token1):e.token1;await this.ensureWebSocketConnected();const r=await this.sendCollectPositionFeesToBundler(t,n,e.fee,e.amount0Requested||"0",e.amount1Requested||"0",e.tickLower,e.tickUpper,e.positionId||"");this.logger.debug("Fee collection submitted to bundler",{transactionId:r});const i=this.webSocketService.waitForTransaction(r);return this.monitorBundlerTransaction(r,i,"fee collection")}catch(e){this.handleGSwapError("Failed to collect position fees",F,e)}}async getPoolData(e,t,n){try{this.logger.debug("Getting pool data",{tokenA:e,tokenB:t,feeTier:n});const{gswapToken0:r,gswapToken1:i}=this.convertTokenPair(e,t),o=Hs(r),s=Hs(i),a=await this.gatewayClient.getPoolData({token0:o,token1:s,fee:n}),c=this.calculatePriceFromSqrtPriceX96(wo(a.sqrtPrice));return{tokenA:e,tokenB:t,feeTier:n,liquidity:a.liquidity.toString(),sqrtPriceX96:a.sqrtPrice.toString(),tick:a.tick,feeGrowthGlobal0X128:a.feeGrowthGlobal0.toString(),feeGrowthGlobal1X128:a.feeGrowthGlobal1.toString(),currentPrice:c.toFixed()}}catch(e){this.handleGSwapError("Failed to get pool data",U,e)}}async calculateDexPoolSpotPrice(e,t,n){try{this.logger.debug("Calculating spot price",{tokenA:e,tokenB:t,feeTier:n});const r=await this.getPoolData(e,t,n),i=wo(r.currentPrice);return{tokenA:e,tokenB:t,feeTier:n,price:i.toFixed(),invertedPrice:To(i,!0),tick:r.tick,liquidity:r.liquidity}}catch(e){this.handleGSwapError("Failed to calculate spot price",U,e)}}async calculateOptimalPositionSize(e,t,n,r,i,o,s){try{this.logger.debug("Calculating optimal position size",{tokenA:e,tokenB:t,desiredAmount0:r,desiredAmount1:i});const a=(await this.getPoolData(e,t,n)).tick,u=c.tickToSqrtPrice(o),l=c.tickToSqrtPrice(a),h=c.tickToSqrtPrice(s),d=c.getLiquidityForAmounts(wo(r),wo(i),u,l,h),f=c.getAmountsForLiquidity(d,l,u,h),g=f[0],p=f[1],m=wo(r),y=wo(i);return{amount0:g.toFixed(),amount1:p.toFixed(),liquidity:d.toFixed(),ratio:Oo(g,p).toFixed(),utilizationPercent:{amount0:Po(Oo(g,m),100).toFixed(2),amount1:Po(Oo(p,y),100).toFixed(2)}}}catch(e){this.handleGSwapError("Failed to calculate optimal position size",F,e)}}async validatePositionParameters(e,t,n,r,i,o,s){const a=[],c=[];try{this.logger.debug("Validating position parameters",{tokenA:e,tokenB:t,tickLower:r,tickUpper:i});const u=[500,3e3,1e4];u.includes(n)||a.push(`Invalid fee tier: ${n}. Must be one of: ${u.join(", ")}`);const l=this.getTickSpacing(n);let h;r%l!==0&&a.push(`tickLower must be multiple of ${l}`),i%l!==0&&a.push(`tickUpper must be multiple of ${l}`),r>=i&&a.push(`tickLower (${r}) must be less than tickUpper (${i})`);try{h=await this.getPoolData(e,t,n)}catch{return a.push(`Pool not found for ${e}/${t} at fee tier ${n}`),{valid:!1,errors:a,warnings:c,gasEstimate:0}}const d=wo(o),f=wo(s);if(d.isNaN()||f.isNaN())a.push("Amounts must be valid numbers");else try{Do(d,f)}catch(e){a.push(`Liquidity amounts must be non-negative: ${e.message}`)}const g=h.tick;(g<r||g>i)&&c.push("Position is out of current price range - will not earn fees until price moves into range");wo(h.liquidity).lt("1000000")&&c.push("Low pool liquidity - consider higher slippage tolerance");const p=0===a.length?35e4:0;return{valid:0===a.length,errors:a,warnings:c,gasEstimate:p,tickSpacing:l,currentTick:g,poolLiquidity:h.liquidity}}catch(e){const t=A(e);return a.includes(t)||a.push(`Validation failed: ${t}`),{valid:!1,errors:a,warnings:c,gasEstimate:0}}}async calculateTicksForPrice(e,t,n,r,i){try{this.logger.debug("Calculating ticks for price range",{tokenA:e,tokenB:t,minPrice:n,maxPrice:r});const o=this.getTickSpacing(i),s=wo(n),a=wo(r);ce(n,r,"priceRange");const c=Math.floor(Ao(s)),u=Math.ceil(Ao(a)),l=Uo(c,o),h=Uo(u,o),d=Math.pow(1.0001,l),f=Math.pow(1.0001,h),g=wo(d),p=wo(f);return{tokenA:e,tokenB:t,feeTier:i,tickLower:l,tickUpper:h,tickSpacing:o,requestedMinPrice:n,requestedMaxPrice:r,actualMinPrice:g.toFixed(8),actualMaxPrice:p.toFixed(8),priceDeviation:{minPriceDeviation:Po(g.minus(s).dividedBy(s),100).toFixed(4),maxPriceDeviation:Po(p.minus(a).dividedBy(a),100).toFixed(4)}}}catch(e){this.handleGSwapError("Failed to calculate ticks for price",F,e)}}async calculatePriceForTicks(e,t,n,r){try{this.logger.debug("Calculating price for ticks",{tokenA:e,tokenB:t,tickLower:n,tickUpper:r});const i=Math.pow(1.0001,n),o=Math.pow(1.0001,r);let s;try{s=(await this.getPoolData(e,t,3e3)).currentPrice}catch{}const a=wo(i),c=wo(o),u={tokenA:e,tokenB:t,tickLower:n,tickUpper:r,minPrice:a.toFixed(8),maxPrice:c.toFixed(8),priceRange:`${a.toFixed(4)} - ${c.toFixed(4)}`,tickSpread:r-n};return Ye(s)||(u.currentPrice=s),u}catch(e){this.handleGSwapError("Failed to calculate price for ticks",F,e)}}calculateExecutionPrice(e,t){try{const n=wo(e);return Oo(wo(t),n,"0").toFixed()}catch{return"0"}}getTickSpacing(e){switch(e){case 500:return 10;case 3e3:return 60;case 1e4:return 200;default:throw W("feeTier","500, 3000, or 10000","Fee tier")}}validateTickSpacing(e,t,n){const r=this.getTickSpacing(n);if(e%r!==0)throw new _(`Invalid tickLower: ${e} must be a multiple of ${r} for fee tier ${n}. Tip: Use getAllSwapUserLiquidityPositions() to discover valid positions with correct tick spacing.`,"tickLower","INVALID_TICK_SPACING");if(t%r!==0)throw new _(`Invalid tickUpper: ${t} must be a multiple of ${r} for fee tier ${n}. Tip: Use getAllSwapUserLiquidityPositions() to discover valid positions with correct tick spacing.`,"tickUpper","INVALID_TICK_SPACING")}calculatePriceFromSqrtPriceX96(e){try{const t=Eo();return Oo(e,t).pow(2)}catch{return wo(0)}}calculatePriceFromSqrtPriceDecimal(e){try{return e.pow(2)}catch{return wo(0)}}async getPoolSlot0(e,t,n){try{this.logger.debug("Fetching pool slot0 data",{token0:e,token1:t,fee:n});const r="string"==typeof e?Hs(e):e,i="string"==typeof t?Hs(t):t,o=await this.gatewayClient.getSlot0({token0:r,token1:i,fee:n}),s={sqrtPrice:o.sqrtPrice||"0",tick:o.tick||0,liquidity:o.liquidity||"0",grossPoolLiquidity:o.grossPoolLiquidity||"0"};return this.logger.debug("Retrieved pool slot0 data",{sqrtPrice:s.sqrtPrice,tick:s.tick,liquidity:s.liquidity}),s}catch(r){this.handleGSwapError("Failed to fetch pool slot0 data",U,r,{token0:e,token1:t,fee:n})}}async getPositionCurrentPrice(e){try{this.logger.debug("Fetching position current price",{token0:e.token0,token1:e.token1,feeTier:e.feeTier});const t=await this.getPoolSlot0(e.token0,e.token1,e.feeTier),n=wo(t.sqrtPrice),r={price:this.calculatePriceFromSqrtPriceDecimal(n).toFixed(18),sqrtPrice:t.sqrtPrice,tick:t.tick,liquidity:t.liquidity};return this.logger.debug("Calculated position current price",{price:r.price,tick:r.tick}),r}catch(t){this.handleGSwapError("Failed to fetch position current price",U,t,{token0:e.token0,token1:e.token1})}}calculateLiquidityFromAmount0(e,t,n){try{const r=c.tickToSqrtPrice(t),i=c.tickToSqrtPrice(n);return c.liquidity0(e,r,i)}catch{return wo(0)}}calculateLiquidityFromAmount1(e,t,n){try{const r=c.tickToSqrtPrice(t),i=c.tickToSqrtPrice(n);return c.liquidity1(e,r,i)}catch{return wo(0)}}calculateAmount0FromLiquidity(e,t,n){try{const r=c.tickToSqrtPrice(t),i=c.tickToSqrtPrice(n);return c.getAmount0Delta(r,i,e)}catch{return wo(0)}}calculateAmount1FromLiquidity(e,t,n){try{const r=c.tickToSqrtPrice(t),i=c.tickToSqrtPrice(n);return c.getAmount1Delta(r,i,e)}catch{return wo(0)}}convertTokenPair(e,t){return{gswapToken0:this.tokenConverter.toLaunchpadFormat(e),gswapToken1:this.tokenConverter.toLaunchpadFormat(t)}}async sendAddLiquidityToBundler(t){if(!this.privateKey)throw new R("GSwapService: AddLiquidity requires wallet (full-access mode)","privateKey");if(!this.bundlerBaseUrl)throw new R("GSwapService: Bundler URL not configured","bundlerBaseUrl");try{this.logger.debug("Sending AddLiquidity to bundler",{token0:t.token0?.type??"unknown",token1:t.token1?.type??"unknown",fee:t.fee,tickRange:`${t.tickLower}-${t.tickUpper}`});const n=`galaswap - operation - ${o.v4()}-${Date.now()}-${t.owner}`,r={token0:t.token0,token1:t.token1,fee:t.fee,owner:t.owner,tickLower:t.tickLower,tickUpper:t.tickUpper,amount0Desired:t.amount0Desired,amount1Desired:t.amount1Desired,amount0Min:t.amount0Min,amount1Min:t.amount1Min,positionId:"",uniqueKey:n},i=new e.ethers.Wallet(this.privateKey),s={AddLiquidity:[{name:"token0",type:"token0"},{name:"token1",type:"token1"},{name:"fee",type:"int256"},{name:"owner",type:"string"},{name:"tickLower",type:"int256"},{name:"tickUpper",type:"int256"},{name:"amount0Desired",type:"string"},{name:"amount1Desired",type:"string"},{name:"amount0Min",type:"string"},{name:"amount1Min",type:"string"},{name:"positionId",type:"string"},{name:"uniqueKey",type:"string"}],token0:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}],token1:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}]},a={name:"ethereum",chainId:1},c=this.calculatePersonalSignPrefix(r),u={...r,prefix:c},l=await i.signTypedData(a,s,u),h={...u,signature:l,types:s,domain:a};this.logger.debug("AddLiquidity DTO signed with manual types",{signature:h.signature?.substring(0,20)+"...",prefix:h.prefix,tickLower:r.tickLower,tickUpper:r.tickUpper});const d=this.buildLiquidityStringsInstructions(t.token0,t.token1,t.fee,t.owner),f=hc.createClient(this.bundlerBaseUrl,3e4),g=await f.post("/bundle",{method:"AddLiquidity",signedDto:h,stringsInstructions:d}),p=mr(g),m=p?.data||p?.transactionId||p?.id;if(!m)throw this.logger.error("Bundler response structure",{status:g.status,data:p,dataType:typeof p}),new D(`Bundler response does not contain transaction ID. Response: ${JSON.stringify(p)}`,void 0,"INVALID_RESPONSE");return this.logger.debug("AddLiquidity transaction sent to bundler",{transactionId:m}),m}catch(e){throw this.logger.error("Failed to send AddLiquidity to bundler",e),e}}async sendRemoveLiquidityToBundler(t,n,r,i,s,a,c,u,l){try{if(!this.bundlerBaseUrl)throw new R("GSwapService: Bundler URL not configured","bundlerBaseUrl");const h=new e.ethers.Wallet(this.privateKey),d=await h.getAddress(),f=`galaswap - operation - ${o.v4()}-${Date.now()}-${d}`,g={tickLower:t,tickUpper:n,amount:r,token0:i,token1:s,fee:a,amount0Min:c,amount1Min:u,positionId:l,uniqueKey:f},p={RemoveLiquidity:[{name:"tickLower",type:"int256"},{name:"tickUpper",type:"int256"},{name:"amount",type:"string"},{name:"token0",type:"token0"},{name:"token1",type:"token1"},{name:"fee",type:"int256"},{name:"amount0Min",type:"string"},{name:"amount1Min",type:"string"},{name:"positionId",type:"string"},{name:"uniqueKey",type:"string"}],token0:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}],token1:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}]},m={name:"ethereum",chainId:1},y=this.calculatePersonalSignPrefix(g),w={...g,prefix:y},b=await h.signTypedData(m,p,w),k={...w,signature:b,types:p,domain:m},v=this.buildLiquidityStringsInstructions(i,s,a,d);this.logger.debug("Submitting RemoveLiquidity to bundler",{tickLower:t,tickUpper:n,amount:r,fee:a,positionId:l,transactionId:f});const S=hc.createClient(this.bundlerBaseUrl,3e4),A=await S.post("/bundle",{method:"RemoveLiquidity",signedDto:k,stringsInstructions:v}),T=mr(A),E=T?.data||T?.transactionId||T?.id;if(!E)throw this.logger.error("Bundler response structure",{status:A.status,data:T,dataType:typeof T}),new D(`Bundler response does not contain transaction ID. Response: ${JSON.stringify(T)}`,void 0,"INVALID_RESPONSE");return this.logger.info("RemoveLiquidity transaction sent to bundler",{transactionId:E}),E}catch(e){throw this.logger.error("Failed to send RemoveLiquidity to bundler",e),e}}async sendCollectPositionFeesToBundler(t,n,r,i,s,a,c,u){try{if(!this.bundlerBaseUrl)throw new R("GSwapService: Bundler URL not configured","bundlerBaseUrl");const l=new e.ethers.Wallet(this.privateKey),h=await l.getAddress(),d=`galaswap - operation - ${o.v4()}-${Date.now()}-${h}`,f={token0:t,token1:n,fee:r,amount0Requested:i,amount1Requested:s,tickLower:a,tickUpper:c,positionId:u,uniqueKey:d},g={CollectPositionFees:[{name:"token0",type:"token0"},{name:"token1",type:"token1"},{name:"fee",type:"int256"},{name:"amount0Requested",type:"string"},{name:"amount1Requested",type:"string"},{name:"tickLower",type:"int256"},{name:"tickUpper",type:"int256"},{name:"positionId",type:"string"},{name:"uniqueKey",type:"string"}],token0:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}],token1:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}]},p={name:"ethereum",chainId:1},m=this.calculatePersonalSignPrefix(f),y={...f,prefix:m},w=await l.signTypedData(p,g,y),b={...y,signature:w,types:g,domain:p},k=this.buildLiquidityStringsInstructions(t,n,r,h);this.logger.debug("Submitting CollectPositionFees to bundler",{fee:r,amount0Requested:i,amount1Requested:s,tickLower:a,tickUpper:c,positionId:u,transactionId:d});const v=hc.createClient(this.bundlerBaseUrl,3e4),S=await v.post("/bundle",{method:"CollectPositionFees",signedDto:b,stringsInstructions:k}),A=mr(S),T=A?.data||A?.transactionId||A?.id;if(!T)throw this.logger.error("Bundler response structure",{status:S.status,data:A,dataType:typeof A}),new D(`Bundler response does not contain transaction ID. Response: ${JSON.stringify(A)}`,void 0,"INVALID_RESPONSE");return this.logger.info("CollectPositionFees transaction sent to bundler",{transactionId:T}),T}catch(e){throw this.logger.error("Failed to send CollectPositionFees to bundler",e),e}}async sendSwapToBundler(t){if(!this.privateKey)throw new R("GSwapService: Swap requires wallet (full-access mode)","privateKey");if(!this.bundlerBaseUrl)throw new R("GSwapService: Bundler URL not configured","bundlerBaseUrl");const n=[500,3e3,1e4];if(!n.includes(t.feeTier))throw new _(`GSwapService: Invalid fee tier ${t.feeTier}. Must be one of: ${n.join(", ")} (basis points)`,"feeTier","INVALID_FEE_TIER");try{this.logger.debug("Sending Swap to bundler",{fromToken:"string"==typeof t.fromToken?t.fromToken:t.fromToken?.type??"unknown",toToken:"string"==typeof t.toToken?t.toToken:t.toToken?.type??"unknown",inputAmount:t.inputAmount,minOutput:t.minOutput,feeTier:t.feeTier});let n=t.fromToken,r=t.toToken;"string"==typeof n&&(n=Hs(n)),"string"==typeof r&&(r=Hs(r));const i=Ks(n),s=Ks(r),a=i<s?[n,r,i,s]:[r,n,s,i],[c,u,l,h]=a,d=Ks("string"==typeof t.fromToken?Hs(t.fromToken):t.fromToken),f=d===l,g=`galaswap - operation - ${o.v4()}-${Date.now()}-${t.walletAddress}`;let p;if(!t.currentSqrtPrice)throw new _("GSwapService: currentSqrtPrice is required for sqrtPriceLimit calculation","currentSqrtPrice",B.REQUIRED);const m=wo(t.currentSqrtPrice),y=t.slippageTolerance??.01;if(f){const e=vo(y);p=m.multipliedBy(e).toString()}else{const e=So(y);p=m.multipliedBy(e).toString()}this.logger.debug("Calculated sqrtPriceLimit based on slippage tolerance",{currentSqrtPrice:t.currentSqrtPrice,slippageTolerance:100*y+"%",zeroForOne:f,sqrtPriceLimit:p,direction:f?"token0→token1 (downward price movement)":"token1→token0 (upward price movement)",reason:"sqrtPriceLimit sets price boundaries, amountOutMinimum provides volume protection"});const w={token0:c,token1:u,fee:t.feeTier,amount:wo(t.inputAmount).toFixed(),zeroForOne:f,sqrtPriceLimit:p,recipient:t.walletAddress,amountOutMinimum:wo(t.minOutput).multipliedBy(-1).toFixed(),uniqueKey:g};this.logger.info("🔄 SWAP DTO DETAILS (what we're sending to bundler)",{orderedToken0String:l,orderedToken1String:h,fromTokenStr:d,zeroForOne:f?`TRUE (${l} → ${h})`:`FALSE (${h} → ${l})`,inputAmount:t.inputAmount,expectedOutput:t.minOutput,slippageTolerance:100*(t.slippageTolerance||.01)+"%",currentSqrtPrice:t.currentSqrtPrice,swapDto:{amount:w.amount,zeroForOne:w.zeroForOne,sqrtPriceLimit:w.sqrtPriceLimit,amountOutMinimum:w.amountOutMinimum}});const b=new e.ethers.Wallet(this.privateKey),k={Swap:[{name:"token0",type:"token0"},{name:"token1",type:"token1"},{name:"fee",type:"int256"},{name:"amount",type:"string"},{name:"zeroForOne",type:"bool"},{name:"sqrtPriceLimit",type:"string"},{name:"recipient",type:"string"},{name:"amountOutMinimum",type:"string"},{name:"uniqueKey",type:"string"}],token0:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}],token1:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}]},v={name:"ethereum",chainId:1},S=this.calculatePersonalSignPrefix(w),A={...w,prefix:S},T=await b.signTypedData(v,k,A),E={...A,signature:T,types:k,domain:v};this.logger.debug("Swap DTO signed",{signature:E.signature?.substring(0,20)+"...",prefix:E.prefix,zeroForOne:w.zeroForOne});const I=this.buildLiquidityStringsInstructions(c,u,t.feeTier,t.walletAddress),x=hc.createClient(this.bundlerBaseUrl,3e4),C=await x.post("/bundle",{method:"Swap",signedDto:E,stringsInstructions:I}),N=mr(C),P=N?.data||N?.transactionId||N?.id;if(!P)throw this.logger.error("Bundler response structure",{status:C.status,data:N,dataType:typeof N}),new D(`Bundler response does not contain transaction ID. Response: ${JSON.stringify(N)}`,void 0,"INVALID_RESPONSE");return this.logger.debug("Swap transaction sent to bundler",{transactionId:P,inputAmount:t.inputAmount,minOutput:t.minOutput}),P}catch(e){throw this.logger.error("Failed to send Swap to bundler",e),e}}buildLiquidityStringsInstructions(e,t,n,r){const i=zs(e),o=zs(t),s=`$pool${i}${o}$${n}`;return[s,`$userPosition${r}`,`$tokenBalance${i}${r}`,`$tokenBalance${o}${r}`,`$tokenBalance${i}${s}`,`$tokenBalance${o}${s}`]}createGSwapErrorHandler(e,t){return(n,r,i)=>{this.handleGSwapError(r,e,n,t)}}handleGSwapError(e,t,n,r){this.logger.error(e,n);const i=this.extractGSwapErrorCode(n),o=n,s=[`${e}: ${o?.message||A(n)}`,n];throw r&&("GSwapSwapError"===t.name&&r.transactionHash&&s.push(r.transactionHash),"GSwapPoolError"===t.name&&(r.tokenA&&s.push(r.tokenA),r.tokenB&&s.push(r.tokenB)),"GSwapAssetError"===t.name&&r.walletAddress&&s.push(r.walletAddress)),i&&s.push(i),new t(...s)}extractGSwapErrorCode(e){const t=E(e);return void 0!==t?String(t):void 0}async ensureWebSocketConnected(){this.webSocketService.isConnected()||await this.webSocketService.connect()}calculatePersonalSignPrefix(e){return`Ethereum Signed Message:\n${JSON.stringify(e).length}${JSON.stringify(e)}`}}class pc{}pc.BASE_PRICE=1650667151e-14,pc.PRICE_SCALING_FACTOR=1166069e-12,pc.TRADING_FEE_FACTOR=.001,pc.GAS_FEE="1",pc.MIN_UNBONDING_FEE_FACTOR=0,pc.MAX_UNBONDING_FEE_FACTOR=.5,pc.NET_UNBONDING_FEE_FACTOR=.5,pc.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY=1e7;class mc extends ds{constructor(e=!1){super(e),this.cache=new Map}get(e){const t=this.normalizeKey(e);return this.cache.get(t)}set(e,t){const n=this.normalizeKey(e);this.cache.set(n,t)}has(e){const t=this.normalizeKey(e);return this.cache.has(t)}clear(){this.cache.clear(),this.logger.debug("Cleared cache")}dump(){return new Map(this.cache)}size(){return this.cache.size}isEmpty(){return 0===this.cache.size}buildBaseStats(){return{totalItems:this.cache.size}}}class yc extends mc{constructor(e=!1){super(e)}normalizeKey(e){return rs(e).replace(/\s+/g," ").replace(/[\u0000-\u001F\u007F-\u009F\u200B-\u200D\uFEFF]/g,"")}getLRUKey(){const e=this.cache.keys().next().value;return void 0!==e?e:null}updateCacheEntry(e,t){const n=this.cache.get(e);if(this.cache.has(e)&&this.cache.delete(e),this.cache.size>=yc.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||pc.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY.toString()}has(e){const t=this.normalizeKey(e);return this.cache.has(t)}clear(e){if(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,n.vaultAddress&&(i+=2*n.vaultAddress.length),n.maxSupply&&(i+=2*n.maxSupply.length),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:${rs(e)}`;return this.cache.get(t)||null}setByTokenId(e,t){const n=`token:${rs(e)}`;this.updateCacheEntry(n,t)}hasByTokenId(e){const t=`token:${rs(e)}`;return this.cache.has(t)}}yc.MAX_CACHE_SIZE=1e4;class wc extends hs{constructor(e,t,n=void 0,r=5,i=!1){super(e,i),this.pricingConcurrency=5,this.dexBackendBaseUrl=t,this.gswapService=n,this.pricingConcurrency=r}setGSwapService(e){this.gswapService=e}setPricingConcurrency(e){this.pricingConcurrency=Math.max(1,Math.min(e,20))}async enrichPoolsWithPricing(e){if(!this.gswapService)return this.logger.warn("GSwap service not available, skipping pricing enrichment"),e;if(0===e.length)return e;this.logger.debug("Starting pricing enrichment",{poolCount:e.length,concurrency:this.pricingConcurrency});const t=[];for(let n=0;n<e.length;n++){const r=e[n];t.push({poolIndex:n,token:r.token0,isToken0:!0,task:this.gswapService.getSwapQuoteExactInput({fromToken:r.token0,toToken:"GUSDC",amount:"1"}).then(e=>e.estimatedOutput).catch(e=>{this.logger.debug(`Failed to price ${r.token0}`,{error:A(e)})})}),t.push({poolIndex:n,token:r.token1,isToken0:!1,task:this.gswapService.getSwapQuoteExactInput({fromToken:r.token1,toToken:"GUSDC",amount:"1"}).then(e=>e.estimatedOutput).catch(e=>{this.logger.debug(`Failed to price ${r.token1}`,{error:A(e)})})})}const n=new Map;for(let t=0;t<e.length;t++)n.set(t,{});for(let e=0;e<t.length;e+=this.pricingConcurrency){const r=t.slice(e,e+this.pricingConcurrency),i=await Promise.allSettled(r.map(e=>e.task));for(let e=0;e<r.length;e++){const t=r[e],o=i[e],s=n.get(t.poolIndex)||{};"fulfilled"===o.status&&o.value&&(t.isToken0?s.token0Price=o.value:s.token1Price=o.value),n.set(t.poolIndex,s)}}const r=e.map((e,t)=>{const r=n.get(t)||{},i={...e};return void 0!==r.token0Price&&(i.token0Price=r.token0Price),void 0!==r.token1Price&&(i.token1Price=r.token1Price),i}),i=r.filter(e=>e.token0Price&&e.token1Price).length;return this.logger.debug("Pricing enrichment complete",{total:e.length,successful:i,failed:e.length-i}),r}async fetchDexPools(e={}){const{search:t,sortBy:n="tvl",sortOrder:r="desc",page:i=Wo.DEFAULT_PAGE,limit:o=Wo.DEFAULT_LIMIT,withPrices:s=!1}=e;this.logger.debug("Fetching DEX pools",{search:t,sortBy:n,sortOrder:r,page:i,limit:o,withPrices:s});const a=Ss({page:i,limit:o},20),c=new URLSearchParams({...a,sortBy:n,sortOrder:r});t&&c.append("search",t);const u=`${this.dexBackendBaseUrl}/explore/pools?${c}`,l=await es(()=>this.http.get(u),{errorContext:"Failed to fetch DEX pools",logger:this.logger});let h=l.pools;const d=l.count,f=Math.min(o,20),g=void 0!==d?function(e,t=1,n=20){return{page:t,limit:n,total:e,totalPages:Xo(e,n)}}(d,i,f):{page:i,limit:f,total:void 0,totalPages:void 0};return s&&(h=await this.enrichPoolsWithPricing(h)),this.logger.debug("DEX pools fetched successfully",{poolCount:h.length,total:d,totalPages:g.totalPages,withPrices:s}),{items:h,meta:g}}async fetchAllDexPools(e={}){this.logger.debug("Fetching all DEX pools (auto-paginated)",e);const t=await Zo((t,n)=>this.fetchDexPools({...e,page:t,limit:n}).then(e=>({items:e.items,page:e.meta.page,limit:e.meta.limit,total:e.meta.total,totalPages:e.meta.totalPages,hasNext:t<e.meta.totalPages,hasPrevious:t>1})),{maxPages:1e4,logger:this.logger,pageSize:20});return this.logger.debug("All DEX pools fetched",{totalPoolsFetched:t.items.length,totalCount:t.total,withPrices:e.withPrices}),{items:t.items,meta:As(t.items,t.total)}}}class bc extends hs{constructor(e,t,n=!1,r=3e4){super(e,n),this.compositePoolFetchConcurrency=5,this.galaChainBaseUrl=t,this.networkTimeout=r}validateFetchCompositePoolDataInput(e,t,n){if(!Qe(e))throw new $("token0 must be a non-empty string",{token0:e});if(!Qe(t))throw new $("token1 must be a non-empty string",{token1:t});try{js(e),js(t)}catch(n){throw new $(`Token format must be: collection|category|type|additionalKey (4 pipe-separated parts). ${A(n)}`,{token0:e,token1:t})}try{ae(n,"fee")}catch{throw new $(`fee must be a positive integer (got ${n})`,{fee:n})}const r=[500,3e3,1e4];if(!r.includes(n))throw new $(`fee must be one of: ${r.join(", ")} (got ${n})`,{fee:n})}validateQuoteAmount(e){if(!Qe(e))throw new $("amount must be a non-empty string",{amount:e});const t=wo(e);try{Lo(t,"amount")}catch(t){throw new $(t.message,{amount:e})}}convertTokenClassKey(e){const t=new s.TokenClassKey;return t.collection=e.collection,t.category=e.category,t.type=e.type,t.additionalKey=e.additionalKey,t}setCompositePoolFetchConcurrency(e){this.compositePoolFetchConcurrency=Math.max(1,Math.min(e,20)),this.logger.debug(`Composite pool fetch concurrency set to ${this.compositePoolFetchConcurrency}`)}async fetchCompositePoolData(e){const{token0:t,token1:n,fee:r,gatewayBaseUrl:i}=e;this.logger.debug("Fetching composite pool data",{token0:t,token1:n,fee:r}),this.validateFetchCompositePoolDataInput(t,n,r);try{const e=dc(t),o=dc(n),a=this.convertTokenClassKey(e),u=this.convertTokenClassKey(o),l=new c.GetCompositePoolDto(a,u,r),h=`${i||this.galaChainBaseUrl}/api/asset/dexv3-contract/GetCompositePool`,d=await this.http.post(h,l);x(d,`Pool not found: ${t}/${n} with fee ${r}`);const f=function(e){return{pool:e.pool,tickDataMap:e.tickDataMap,token0Balance:e.token0Balance,token1Balance:e.token1Balance,token0Decimals:e.token0Decimals,token1Decimals:e.token1Decimals,compositePoolDto:e}}(function(e){const t=new c.Pool(e.pool.token0,e.pool.token1,e.pool.token0ClassKey,e.pool.token1ClassKey,e.pool.fee,wo(e.pool.sqrtPrice),e.pool.protocolFees);t.bitmap=e.pool.bitmap,t.grossPoolLiquidity=wo(e.pool.grossPoolLiquidity),t.liquidity=wo(e.pool.liquidity),t.feeGrowthGlobal0=wo(e.pool.feeGrowthGlobal0),t.feeGrowthGlobal1=wo(e.pool.feeGrowthGlobal1),t.protocolFeesToken0=wo(e.pool.protocolFeesToken0),t.protocolFeesToken1=wo(e.pool.protocolFeesToken1),t.tickSpacing=e.pool.tickSpacing,t.maxLiquidityPerTick=wo(e.pool.maxLiquidityPerTick);const n={};Object.keys(e.tickDataMap).forEach(t=>{const r=e.tickDataMap[t],i=new c.TickData(r.poolHash,r.tick);i.initialised=r.initialised,i.liquidityNet=wo(r.liquidityNet),i.liquidityGross=wo(r.liquidityGross),i.feeGrowthOutside0=wo(r.feeGrowthOutside0),i.feeGrowthOutside1=wo(r.feeGrowthOutside1),n[t]=i});const r={...e.token0Balance},i=new s.TokenBalance(r);i.quantity=wo(e.token0Balance.quantity);const o={...e.token1Balance},a=new s.TokenBalance(o);return a.quantity=wo(e.token1Balance.quantity),new c.CompositePoolDto(t,n,i,a,e.token0Decimals,e.token1Decimals)}(d.Data),d.Data);return this.logger.debug("Composite pool data fetched successfully",{token0:t,token1:n,fee:r,liquidity:f.pool.liquidity.toString()}),f}catch(e){if(e instanceof q)throw e;const i=A(e);if(i.includes("status indicates failure")||i.includes("Pool not found"))throw new q(i);throw this.logger.error("Failed to fetch composite pool data",e),new $(`Failed to fetch composite pool data: ${i}`,{token0:t,token1:n,fee:r})}}async calculateDexPoolQuoteExactAmountLocal(e){const{compositePoolData:t,fromToken:n,toToken:r,amount:i}=e;if(this.logger.debug("Calculating local DEX quote",{fromToken:n,toToken:r,amount:i}),this.validateQuoteAmount(i),!t)throw new $("compositePoolData is required for local quote calculation",{compositePoolData:t});try{const e=n===t.pool.token0.replace(/\$/g,"|"),o=dc(n),s=dc(r),a=this.convertTokenClassKey(o),u=this.convertTokenClassKey(s),[l,h]=n<r?[a,u]:[u,a],d=new c.QuoteExactAmountDto(l,h,t.pool.fee,wo(i),e,t.compositePoolDto),f=await c.quoteExactAmount(void 0,d);return this.logger.debug("Local quote calculated",{amount0:f.amount0,amount1:f.amount1}),{amount0:f.amount0.toString(),amount1:f.amount1.toString(),currentSqrtPrice:f.currentSqrtPrice.toString(),newSqrtPrice:f.newSqrtPrice.toString()}}catch(e){throw this.logger.error("Local quote calculation failed",e),new $(`Local quote calculation failed: ${A(e)}`,{fromToken:n,toToken:r,amount:i})}}async calculateDexPoolQuoteExactAmountExternal(e){const{compositePoolData:t,fromToken:n,toToken:r,amount:i}=e;if(this.logger.debug("Calculating external DEX quote",{fromToken:n,toToken:r,amount:i}),this.validateQuoteAmount(i),!t)throw new $("compositePoolData is required for external quote calculation (token format info)",{compositePoolData:t});try{const e=n===t.pool.token0.replace(/\$/g,"|"),o=dc(n),s=dc(r),a=this.convertTokenClassKey(o),u=this.convertTokenClassKey(s),l=new c.QuoteExactAmountDto(a,u,t.pool.fee,wo(i),e,void 0),h=`${this.galaChainBaseUrl}/api/asset/dexv3-contract/QuoteExactAmount`,d=await this.http.post(h,l);x(d,"External quote failed");const f=d.Data;return this.logger.debug("External quote calculated",{amount0:f.amount0,amount1:f.amount1}),{amount0:f.amount0.toString(),amount1:f.amount1.toString(),currentSqrtPrice:f.currentSqrtPrice.toString(),newSqrtPrice:f.newSqrtPrice.toString()}}catch(e){throw this.logger.error("External quote calculation failed",e),new $(`External quote calculation failed: ${A(e)}`,{fromToken:n,toToken:r,amount:i})}}async calculateDexPoolQuoteExactAmount(e,t="local"){return"external"===t?this.calculateDexPoolQuoteExactAmountExternal(e):this.calculateDexPoolQuoteExactAmountLocal(e)}}class kc{constructor(){this.eventLatencies=[],this.maxLatencySamples=1e4,this.eventsProcessed=0,this.eventsDropped=0,this.queueDepth=0,this.maxQueueDepth=0,this.startTime=Date.now(),this.perPoolMetrics=new Map,this.memorySnapshots=[],this.maxMemorySnapshots=100,this.recordMemory()}recordEventLatency(e){this.eventLatencies.push(e),this.eventLatencies.length>this.maxLatencySamples&&this.eventLatencies.shift(),this.eventsProcessed++,this.lastEventTime=new Date}recordEventDropped(){this.eventsDropped++}updateQueueDepth(e){this.queueDepth=e,this.maxQueueDepth=Math.max(this.maxQueueDepth,e)}recordPoolCacheHit(e,t){const n=this.getPoolMetrics(e);n.cacheHits++,n.eventsProcessed++,n.totalLatency+=t,n.lastEventTime=new Date}recordPoolCacheMiss(e,t){const n=this.getPoolMetrics(e);n.cacheMisses++,n.eventsProcessed++,n.totalLatency+=t,n.lastEventTime=new Date}getLatencyPercentiles(){if(0===this.eventLatencies.length)return{p50:0,p95:0,p99:0};const e=[...this.eventLatencies].sort((e,t)=>e-t),t=De(Math.floor(.5*e.length),0),n=De(Math.floor(.95*e.length),0),r=De(Math.floor(.99*e.length),0);return{p50:e[t]??0,p95:e[n]??0,p99:e[r]??0}}getCacheHitRate(){if(0===this.eventsProcessed)return 0;let e=0;for(const t of this.perPoolMetrics.values())e+=t.cacheHits;return De(e/this.eventsProcessed*100,NaN)}getThroughputPerSecond(){const e=De(Ve(this.startTime)/1e3,0);return 0===e?0:De(this.eventsProcessed/e,0)}recordMemory(){if("undefined"!=typeof process&&process.memoryUsage){const e=De(process.memoryUsage().heapUsed/1024/1024,0);this.memorySnapshots.push(e),this.memorySnapshots.length>this.maxMemorySnapshots&&this.memorySnapshots.shift()}}getMemoryUsedMB(){return"undefined"!=typeof process&&process.memoryUsage?De(process.memoryUsage().heapUsed/1024/1024,0):0}getPoolAverageLatency(e){const t=this.perPoolMetrics.get(e);return t&&0!==t.eventsProcessed?De(t.totalLatency/t.eventsProcessed,0):0}getPoolCacheHitRate(e){const t=this.perPoolMetrics.get(e);if(!t)return 0;const n=t.cacheHits+t.cacheMisses;return 0===n?0:De(t.cacheHits/n*100,0)}getHealthMetrics(e,t,n,r,i){const o=this.getLatencyPercentiles(),s=this.getMemoryUsedMB();return{eventProcessing:{queueDepth:this.queueDepth,eventsProcessed:this.eventsProcessed,eventsDropped:this.eventsDropped,throughputPerSecond:this.getThroughputPerSecond()},metrics:{latencyP50:o.p50,latencyP95:o.p95,latencyP99:o.p99,cacheHitRate:this.getCacheHitRate()},memory:{usedMB:De(bo(s,1),0),maxMB:i,percentUsed:Math.min(100,De(bo(s/i*100,1),0))},pools:{totalMonitored:e,hotCacheSize:t,warmCacheSize:n,coldCacheSize:r}}}reset(){this.eventLatencies=[],this.eventsProcessed=0,this.eventsDropped=0,this.queueDepth=0,this.maxQueueDepth=0,this.startTime=Date.now(),this.lastEventTime=void 0,this.perPoolMetrics.clear(),this.memorySnapshots=[]}getSummary(){const e=this.eventLatencies.length>0?De(this.eventLatencies.reduce((e,t)=>e+t,0)/this.eventLatencies.length,0):0;return{eventsProcessed:this.eventsProcessed,eventsDropped:this.eventsDropped,cacheHitRate:this.getCacheHitRate(),averageLatency:De(bo(e,0),0),memoryUsedMB:De(bo(this.getMemoryUsedMB(),1),0),throughputPerSecond:De(bo(this.getThroughputPerSecond(),2),0)}}getPoolMetrics(e){let t=this.perPoolMetrics.get(e);return t||(t={eventsProcessed:0,totalLatency:0,cacheHits:0,cacheMisses:0},this.perPoolMetrics.set(e,t)),t}}class vc{static createPoolKey(e,t,n){return`${e}/${t}/${n}`}static parsePoolKey(e){if(!Qe(e))return null;const t=e.split("/");if(3!==t.length)return null;const n=t[0]?.trim(),r=t[1]?.trim(),i=t[2]?.trim();if(!n||!r||!i)return null;const o=Le(i,-1);return o<0?null:{token0:n,token1:r,feeTier:o}}static isValidPoolKey(e){if("string"!=typeof e)return!1;return null!==this.parsePoolKey(e)}static getToken0(e){const t=this.parsePoolKey(e);return t?.token0??null}static getToken1(e){const t=this.parsePoolKey(e);return t?.token1??null}static getFeeTier(e){const t=this.parsePoolKey(e);return t?.feeTier??null}static containsToken(e,t){const n=this.parsePoolKey(e);return!!n&&(n.token0===t||n.token1===t)}static containsTokenPair(e,t,n){const r=this.parsePoolKey(e);if(!r)return!1;const i=r.token0===t||r.token1===t,o=r.token0===n||r.token1===n;return i&&o&&t!==n}static normalizeFee(e){if(Ye(e))return null;const t="number"==typeof e?e:Fe(String(e),NaN);return Number.isNaN(t)?null:1===t||1e4===t?1e4:.3===t||3e3===t?3e3:.05===t||500===t?500:Number.isInteger(t)&&t>0?t:null}static formatFeeAsPercentage(e){return`${bo(wo(e).dividedBy(1e4),2)}%`}static isValidTokenPair(e,t){return Boolean(e)&&Boolean(t)&&e!==t}}class Sc{constructor(e){this.logger=e||new ze({debug:!1,context:"SwapEventExtractor"})}walkPayloadForSwaps(e,t){const n=[],r=new WeakSet,i=(e,o=0)=>{if(o>50)this.logger.debug("Payload nesting exceeded maximum depth of 50");else if(e&&"string"!=typeof e&&"object"==typeof e){if(r.has(e))return;r.add(e);const s=this.extractSwapFromObject(e);s&&!t.has(s.transactionId)&&(n.push(s),t.add(s.transactionId));for(const t of Object.values(e))i(t,o+1)}};return i(e,0),n}extractSwapFromObject(e){const t=this.extractTransactionId(e);if(!t)return null;const n=e.Data,r=n&&"object"==typeof n&&!Array.isArray(n)?n:e,i=this.extractToken(r,"token0","fromToken","source"),o=this.extractToken(r,"token1","toToken","destination");if(!i||!o)return null;const s=this.extractAmount(r,"amount0","amountIn","inputAmount"),a=this.extractAmount(r,"amount1","amountOut","outputAmount");if(!s||!a)return null;const c=this.extractFeeTier(r);if(null===c)return null;const u=this.extractTimestamp(r),l=this.buildPoolKey(i,o,c),h=this.determineDirection(r,i,o),d={transactionId:t,poolKey:l,token0:i,token1:o,amount0:s,amount1:a,feeTier:c,direction:h,timestamp:u,exactInput:this.determineExactInput(r,h)},f=this.extractUser(r);return void 0!==f&&(d.user=f),d}extractTransactionId(e){const t=["transactionId","txId","tx_id","hash","txHash","id"];for(const n of t){const t=e[n];if(Qe(t))return t}return null}extractToken(e,...t){for(const n of t){const t=e[n];if(Qe(t))return t}return null}extractAmount(e,...t){for(const n of t){const t=e[n];if(!Ye(t)){const e=String(t).trim();if(/^-?\d+(\.\d+)?([eE]-?\d+)?$/.test(e))return e}}return null}extractFeeTier(e){const t=["poolFee","feeTier","fee","feeTierBps","liquidityFeeBps","feeAmount"];for(const n of t){const t=e[n],r=this.normalizeFee(t);if(null!==r)return r}return null}normalizeFee(e){if(Ye(e))return null;const t="number"==typeof e?e:Fe(String(e),NaN);return Number.isNaN(t)?null:1===t||1e4===t?1e4:.3===t||3e3===t?3e3:.05===t||500===t?500:Number.isInteger(t)?t:null}extractTimestamp(e){const t=["timeStamp","timestamp","time","createdAt","date"];for(const n of t){const t=e[n];if("number"==typeof t)return t;if("string"==typeof t){const e=new Date(t).getTime();if(!Number.isNaN(e))return e}}return Date.now()}extractUser(e){const t=["userAddress","user","from","sender","wallet","address"];for(const n of t){const t=e[n];if(Qe(t))return t}}determineDirection(e,t,n){const r=e.zeroForOne||e.direction;if("boolean"==typeof r)return r?"zeroForOne":"oneForZero";if("string"==typeof r){if(Is(r,"zerotoone")||"0to1"===r)return"zeroForOne";if(Is(r,"onetozero")||"1to0"===r)return"oneForZero"}if(e.fromToken===t||e.inputToken===t)return"zeroForOne";if(e.fromToken===n||e.inputToken===n)return"oneForZero";const i=this.extractAmount(e,"amount0","amountIn");return i&&Re(i,0),"zeroForOne"}determineExactInput(e,t){if("boolean"==typeof e.exactInput)return e.exactInput;if("boolean"==typeof e.exactOutput)return!e.exactOutput;const n=void 0!==e.amountIn&&null!==e.amountIn,r=void 0!==e.amountOut&&null!==e.amountOut,i=void 0!==e.inputAmount&&null!==e.inputAmount,o=void 0!==e.outputAmount&&null!==e.outputAmount;return!(!n||r)||!(r&&!n)&&(!(!i||o)||!(o&&!i))}buildPoolKey(e,t,n){return`${e}/${t}/${n}`}}class Ac{static getCached(e){const t=e.toString();return this.CACHE.has(t)||this.CACHE.set(t,wo(e)),this.CACHE.get(t)}static clearCache(){this.CACHE.clear()}static getCacheStats(){return{size:this.CACHE.size,entries:Array.from(this.CACHE.keys())}}static trimCache(e=1e3){if(this.CACHE.size>e){const t=this.CACHE.size-e,n=Array.from(this.CACHE.keys());for(let e=0;e<t;e++)this.CACHE.delete(n[e])}}}Ac.CACHE=new Map,Ac.ZERO=Ue(0),Ac.ONE=Ue(1),Ac.FEE_PIPS=Ue(1e6),Ac.MIN_SQRT_RATIO=Ue("4295128739"),Ac.MAX_SQRT_RATIO=new i("1461446703485210103287273052203988822378723970342");const Tc={maxIterations:100,enableBigNumberCache:!0,roundingMode:i.ROUND_DOWN,debugLogging:!1};class Ec{static calculateSwapDelta(e,t,n={}){const r=Date.now(),i={...Tc,...n};try{const n=this.initializeSwapState(e,t,i);i.debugLogging&&this.logger.debug("Initialized swap state",{sqrtPrice:n.sqrtPrice.toString(),liquidity:n.liquidity.toString(),tick:n.tick,zeroForOne:t.zeroForOne});const o=this.computeSwapLoop(n,e,t,i);i.debugLogging&&this.logger.debug("Swap loop completed",{stepCount:o.stepCount,ticksCrossed:o.ticksCrossed.length,priceHitLimit:o.priceHitLimit});const s=this.createUpdatedPool(e.pool,o.state,t,i),a=this.calculateFinalAmounts(n,o.state,t);let c;if(t.actualSqrtPrice){const e=wo(s.sqrtPrice),n=wo(t.actualSqrtPrice),r=e.minus(n).abs();c=De(Oo(r,n).times(100).toNumber(),0)}const u=Ve(r);i.debugLogging&&this.logger.debug("Swap delta calculated",{calculationTimeMs:u,amount0:a.amount0.toString(),amount1:a.amount1.toString(),driftPercentage:c}),u>100&&this.logger.warn("Swap calculation exceeded 100ms",{calculationTimeMs:u,stepCount:o.stepCount,ticksCrossed:o.ticksCrossed.length}),o.priceHitLimit&&this.logger.warn("Swap price hit limit - partially fulfilled",{zeroForOne:t.zeroForOne,stepCount:o.stepCount}),o.stepCount>50&&this.logger.warn("Unusually complex swap detected",{stepCount:o.stepCount,ticksCrossed:o.ticksCrossed.length});return{updatedPool:s,updatedTicks:o.updatedTicks,amount0:a.amount0,amount1:a.amount1,feeAmount0:a.feeAmount0,feeAmount1:a.feeAmount1,ticksCrossed:o.ticksCrossed,metadata:{calculationTimeMs:u,swapSteps:o.stepCount,priceHitLimit:o.priceHitLimit,...void 0!==c&&{driftPercentage:c}}}}catch(e){throw this.logger.error("Swap delta calculation failed",e),new Error(`Swap delta calculation failed: ${A(e)}`)}}static initializeSwapState(e,t,n){const{pool:r}=e;if(!r.sqrtPrice||!r.liquidity)throw new Error("Invalid pool data: missing sqrtPrice or liquidity");const i=n.enableBigNumberCache?Ac.getCached.bind(Ac):e=>Ue(e),o="string"==typeof r.sqrtPrice?r.sqrtPrice:bo(r.sqrtPrice,0),s="string"==typeof r.liquidity?r.liquidity:bo(r.liquidity,0),a=i(o),u=i(s),l=r.tick??0,h=c.sqrtPriceToTick(wo(o)),d=Math.abs(h-l);d>100&&this.logger.warn("Significant tick/price mismatch detected in pool state",{poolTick:l,calculatedTick:h,drift:d,threshold:100});const f=i(t.amountSpecified);Lo(f,"amountSpecified");const g="string"==typeof r.feeGrowthGlobal1?r.feeGrowthGlobal1:bo(r.feeGrowthGlobal1,0),p="string"==typeof r.feeGrowthGlobal0?r.feeGrowthGlobal0:bo(r.feeGrowthGlobal0,0),m=t.zeroForOne?i(g):i(p);return{sqrtPrice:a,liquidity:u,tick:l,amountSpecifiedRemaining:f,amountCalculated:Ac.ZERO,feeGrowthGlobalX:m,protocolFee:Ac.ZERO}}static computeSwapLoop(e,t,n,r){const{pool:o,tickDataMap:s}=t,a=[],u={};let l=0;const h=n.zeroForOne?Ac.MIN_SQRT_RATIO:Ac.MAX_SQRT_RATIO,d=wo("0.000001");for(;e.amountSpecifiedRemaining.gt(d)&&!e.sqrtPrice.eq(h)&&l<r.maxIterations;){l++;const[t,d]=this.findNextInitializedTick(s,e.tick,o.tickSpacing,n.zeroForOne);let f;if(r.debugLogging&&this.logger.debug(`Swap step ${l}`,{currentTick:e.tick,tickNext:t,initialized:d,sqrtPrice:e.sqrtPrice.toString(),liquidity:e.liquidity.toString(),amountRemaining:e.amountSpecifiedRemaining.toString()}),d&&t>=-887272&&t<=887272){const e=c.tickToSqrtPrice(t);f=e instanceof i?e:wo(String(e))}else f=h;const g=n.zeroForOne?xo(f,h):Io(f,h),p=this.executeSwapStep(e.sqrtPrice,g,e.liquidity,e.amountSpecifiedRemaining,o.fee,n.exactInput);if(e.sqrtPrice=p.sqrtPriceNext,n.exactInput){const t=p.amountIn.plus(p.feeAmount);t.lte(0)?e.amountSpecifiedRemaining=Ac.ZERO:(e.amountSpecifiedRemaining=e.amountSpecifiedRemaining.minus(t),e.amountSpecifiedRemaining.lt(0)&&(e.amountSpecifiedRemaining=Ac.ZERO)),e.amountCalculated=e.amountCalculated.minus(p.amountOut)}else{p.amountOut.lte(0)?e.amountSpecifiedRemaining=Ac.ZERO:e.amountSpecifiedRemaining=e.amountSpecifiedRemaining.plus(p.amountOut),e.amountCalculated=e.amountCalculated.plus(p.amountIn.plus(p.feeAmount))}if(e.liquidity.gt(0)){const t=Oo(p.feeAmount,e.liquidity);e.feeGrowthGlobalX=e.feeGrowthGlobalX.plus(t)}if(e.sqrtPrice.eq(f)&&d){const i=s[t.toString()];if(!i)throw new Error(`Missing tick data for initialized tick ${t}`);const o=n.zeroForOne?wo(i.liquidityNet).negated():wo(i.liquidityNet);if(e.liquidity=e.liquidity.plus(o),e.liquidity.lt(0))throw new Error(`Negative liquidity after crossing tick ${t}: ${e.liquidity.toString()}`);a.push(t),u[t.toString()]=i,r.debugLogging&&this.logger.debug(`Crossed tick ${t}`,{liquidityNet:o.toString(),newLiquidity:e.liquidity.toString()})}if(e.sqrtPrice.eq(f))e.tick=n.zeroForOne?t-1:t;else{const t=c.sqrtPriceToTick(wo(e.sqrtPrice.toString()));e.tick=t}}if(l>=r.maxIterations)throw new Error(`Swap calculation exceeded maximum iterations (${r.maxIterations}). Possible infinite loop or very complex swap.`);const f=e.sqrtPrice.eq(h);return{state:e,ticksCrossed:a,priceHitLimit:f,stepCount:l,updatedTicks:u}}static createUpdatedPool(e,t,n,r){const i=Object.assign(Object.create(Object.getPrototypeOf(e)),e);if(i.sqrtPrice=bo(t.sqrtPrice,0),i.liquidity=bo(t.liquidity,0),i.tick=t.tick,n.zeroForOne?i.feeGrowthGlobal1=bo(t.feeGrowthGlobalX,0):i.feeGrowthGlobal0=bo(t.feeGrowthGlobalX,0),n.zeroForOne){const n=wo(e.protocolFeesToken0);i.protocolFeesToken0=bo(n.plus(t.protocolFee),0)}else{const n=wo(e.protocolFeesToken1);i.protocolFeesToken1=bo(n.plus(t.protocolFee),0)}return i}static calculateFinalAmounts(e,t,n){let r,i,o,s;if(n.exactInput){const e=wo(n.amountSpecified),a=t.amountCalculated.abs();n.zeroForOne?(r=e.negated(),i=a,o=Ac.ZERO,s=Ac.ZERO):(r=a,i=e.negated(),o=Ac.ZERO,s=Ac.ZERO)}else{const e=wo(n.amountSpecified),a=t.amountCalculated.abs();n.zeroForOne?(r=a.negated(),i=e,o=Ac.ZERO,s=Ac.ZERO):(r=e,i=a.negated(),o=Ac.ZERO,s=Ac.ZERO)}const a=t.feeGrowthGlobalX.minus(e.feeGrowthGlobalX).times(e.liquidity);return n.zeroForOne?s=a:o=a,{amount0:r,amount1:i,feeAmount0:o,feeAmount1:s}}static findNextInitializedTick(e,t,n,r){const i=Object.keys(e).map(e=>Oe(e,0)).sort((e,t)=>e-t);if(0===i.length){return[r?-887272:887272,!1]}if(r){const e=i.reverse().find(e=>e<t);return void 0!==e?[e,!0]:[-887272,!1]}{const e=i.find(e=>e>t);return void 0!==e?[e,!0]:[887272,!1]}}static executeSwapStep(e,t,n,r,o,s){Do(n),Lo(r,"amountRemaining");const a=[500,3e3,1e4];if(!a.includes(o))throw new Error(`Invalid fee tier: ${o}. Must be one of: ${a.join(", ")}`);const u=c.computeSwapStep(e,t,n,r,o,t.lt(e)),l=u[0],h=u[1],d=u[2],f=u[3],g=i.isBigNumber(l)?l:wo(String(l)),p=i.isBigNumber(h)?h:wo(String(h)),m=i.isBigNumber(d)?d:wo(String(d)),y=i.isBigNumber(f)?f:wo(String(f));return{sqrtPriceStart:e,tickNext:c.sqrtPriceToTick(g),sqrtPriceNext:g,initialised:!1,amountIn:p,amountOut:m,feeAmount:y}}}Ec.logger=new ze({debug:!1,context:"SwapDeltaCalculator"});class Ic extends ds{constructor(e,t,n,r){super(!1,r),this.cache=new Map,this.tierSizes={hot:50,warm:200,cold:0},this.tierTTLs={hot:1/0,warm:18e5,cold:3e5},this.refetchThresholds={swapCount:50,driftPercent:.05},this.fetchPoolFn=e,this.config=t,this.metrics=n,this.tierSizes.cold=Math.max(0,this.config.maxPools-this.tierSizes.hot-this.tierSizes.warm),this.logger.debug(`Initialized with cache limits: hot=${this.tierSizes.hot}, warm=${this.tierSizes.warm}, cold=${this.tierSizes.cold}, max=${this.config.maxPools}`)}async getPool(e){const t=this.cache.get(e);if(t){if(!(Date.now()>t.expiresAt))return t.lastAccessTime=Date.now(),this.checkRefetchNeeded(e,t),this.metrics.recordPoolCacheHit(e,0),t.poolData;this.cache.delete(e),this.logger.debug(`Cache expired for pool ${e}`)}this.metrics.recordPoolCacheMiss(e,0);try{const t=await this.fetchPoolFn(e),n=this.determineTier(),r={poolData:t,tier:n,lastAccessTime:Date.now(),expiresAt:Date.now()+this.tierTTLs[n],swapsSinceRefetch:0,cumulativeDrift:0,lastDeltaAppliedTime:Date.now()};return this.cache.set(e,r),this.cache.size>this.config.maxPools&&this.evictLRU(),this.logger.debug(`Fetched pool ${e} (tier: ${n})`),t}catch(t){throw this.logger.error(`Failed to fetch pool ${e}:`,t),t}}updatePoolWithSwapDelta(e,t,n,r,i){const o=this.cache.get(e);if(!o)return this.logger.debug(`Pool ${e} not in cache for delta update`),!1;try{if(i){const s="zeroForOne"===t,a=s?n:r,c={transactionId:i.transactionId,timestamp:i.timestamp,amountSpecified:a,zeroForOne:s,exactInput:i.exactInput},u=Ec.calculateSwapDelta(o.poolData,c);o.poolData={...o.poolData,pool:u.updatedPool},o.swapsSinceRefetch++,o.lastDeltaAppliedTime=Date.now(),void 0!==u.metadata.driftPercentage?(o.cumulativeDrift+=u.metadata.driftPercentage,this.logger.debug(`Delta applied for ${e}: drift=${u.metadata.driftPercentage.toFixed(4)}%, cumulative=${o.cumulativeDrift.toFixed(2)}%`)):this.logger.debug(`Delta applied for ${e}: ${u.ticksCrossed.length} ticks crossed`)}else o.swapsSinceRefetch++,o.lastDeltaAppliedTime=Date.now();return this.shouldRefetch(o)&&(this.logger.debug(`Refetch needed for ${e}: swaps=${o.swapsSinceRefetch}, drift=${(100*o.cumulativeDrift).toFixed(2)}%`),o.expiresAt=Date.now()),!0}catch(t){return this.logger.error(`Failed to update pool ${e}:`,t),o.expiresAt=Date.now(),!1}}getStats(){const e={totalCached:this.cache.size,hotCacheSize:0,warmCacheSize:0,coldCacheSize:0,memoryUsedMB:this.metrics.getMemoryUsedMB()};for(const t of this.cache.values())"hot"===t.tier?e.hotCacheSize++:"warm"===t.tier?e.warmCacheSize++:e.coldCacheSize++;return e}getPoolInfo(e){const t=this.cache.get(e);return t?{poolKey:e,tier:t.tier,lastAccessTime:new Date(t.lastAccessTime),expiresAt:new Date(t.expiresAt),swapsSinceRefetch:t.swapsSinceRefetch,cumulativeDrift:t.cumulativeDrift,isExpired:Date.now()>t.expiresAt}:null}async warmCache(e){if(!e)throw z("poolKey","Pool key");if(this.cache.has(e))return!0;try{return await wr(async()=>{await this.getPool(e),this.logger.debug(`Cache warmed for ${e}`)},`Failed to warm cache for ${e}`,this.logger),!0}catch{return!1}}async warmCacheBatch(e,t=5){if(!e)throw z("poolKeys","Pool keys array");return wr(async()=>{const n={succeeded:0,failed:0,total:e.length};let r=0;const i=new Set;for(;r<e.length||i.size>0;){for(;r<e.length&&i.size<t;){const t=e[r];r++;const o=this.warmCache(t).then(e=>{e?n.succeeded++:n.failed++});i.add(o),o.finally(()=>i.delete(o))}i.size>0&&await Promise.race(i)}return this.logger.debug(`Cache warming complete: ${n.succeeded}/${n.total} succeeded`),n},"Failed to warm cache batch",this.logger)}clear(){this.cache.clear(),this.logger.debug("Cache cleared")}clearExpired(){const e=Date.now();let t=0;for(const[n,r]of this.cache)e>r.expiresAt&&(this.cache.delete(n),t++);t>0&&this.logger.debug(`Cleared ${t} expired entries`)}determineTier(){const e=Array.from(this.cache.values()).filter(e=>"hot"===e.tier).length,t=Array.from(this.cache.values()).filter(e=>"warm"===e.tier).length;return e<this.tierSizes.hot?"hot":t<this.tierSizes.warm?"warm":"cold"}checkRefetchNeeded(e,t){this.shouldRefetch(t)&&(this.logger.debug(`Scheduling refetch for ${e}: swaps=${t.swapsSinceRefetch}, drift=${(100*t.cumulativeDrift).toFixed(2)}%`),t.expiresAt=Date.now())}shouldRefetch(e){return e.swapsSinceRefetch>=this.refetchThresholds.swapCount||e.cumulativeDrift>=this.refetchThresholds.driftPercent}evictLRU(){const e=Array.from(this.cache.entries()).filter(([e,t])=>"cold"===t.tier).sort((e,t)=>e[1].lastAccessTime-t[1].lastAccessTime);if(0===e.length){this.logger.warn("No cold cache entries to evict, trying warm cache");const e=Array.from(this.cache.entries()).filter(([e,t])=>"warm"===t.tier).sort((e,t)=>e[1].lastAccessTime-t[1].lastAccessTime);if(e.length>0){const[t]=e[0];this.cache.delete(t),this.logger.debug(`Evicted warm cache entry: ${t}`)}return}const[t]=e[0];this.cache.delete(t),this.logger.debug(`Evicted cold cache entry: ${t}`)}async refreshWarmAndHotTiers(){const e=Array.from(this.cache.entries()).filter(([e,t])=>"hot"===t.tier||"warm"===t.tier).sort((e,t)=>t[1].lastAccessTime-e[1].lastAccessTime).slice(0,10);if(0===e.length)return;const t=e.map(([e,t])=>this.fetchPoolFn(e).then(n=>{t&&(t.poolData=n,t.lastAccessTime=Date.now(),t.swapsSinceRefetch=0,t.cumulativeDrift=0),this.logger.debug(`Refreshed ${e} during background warming`)}).catch(t=>{this.logger.debug(`Failed to refresh ${e} during background warming:`,t)})),n=new Promise(e=>setTimeout(()=>e(),5e3));await Promise.race([Promise.all(t),n])}}class xc extends ds{constructor(e,t,n){super(!1,n),this.queue=[],this.isShuttingDown=!1,this.currentConcurrency=0,this.maxConcurrencyReached=0,this.eventsDropped=0,this.totalBatchesProcessed=0,this.totalBatchSize=0,this.eventsProcessedCount=0,this.processor=null,this.processingScheduled=!1,this.scheduleProcessing=e=>{"undefined"!=typeof setImmediate?setImmediate(e):Promise.resolve().then(e)},this.config=e,this.metrics=t,this.logger.debug(`Initialized with maxQueueSize=${this.config.maxQueueSize}, batchSize=${this.config.batchSize}, maxConcurrent=${this.config.maxConcurrent}`)}setProcessor(e){this.processor=e}enqueue(e){return this.isShuttingDown?(this.logger.debug(`Rejecting event (queue shutting down): ${e.transactionId}`),this.metrics.recordEventDropped(),this.eventsDropped++,!1):this.queue.length>=this.config.maxQueueSize?(this.logger.warn(`Queue full (${this.queue.length}/${this.config.maxQueueSize}), dropping event: ${e.transactionId}`),this.metrics.recordEventDropped(),this.eventsDropped++,!1):(this.queue.push(e),this.metrics.updateQueueDepth(this.queue.length),this.processingScheduled||this.isShuttingDown||(this.processingScheduled=!0,this.scheduleProcessing(()=>this.processNextBatch())),!0)}getQueueSize(){return this.queue.length}getStats(){return{queueSize:this.queue.length,eventsProcessed:this.eventsProcessedCount,eventsDropped:this.eventsDropped,currentConcurrent:this.currentConcurrency,maxConcurrentReached:this.maxConcurrencyReached,averageBatchSize:this.totalBatchesProcessed>0?Math.floor(this.totalBatchSize/this.totalBatchesProcessed):0,totalBatchesProcessed:this.totalBatchesProcessed}}async waitForEmpty(e){return new Promise(t=>{const n=()=>{0!==this.queue.length||0!==this.currentConcurrency?setTimeout(n,10):t()};e&&setTimeout(()=>t(),e),n()})}async shutdown(e=3e4){this.isShuttingDown=!0,this.logger.debug("Shutting down queue...");const t=Date.now();for(;this.queue.length>0||this.currentConcurrency>0;){if(Ve(t)>e){this.logger.warn(`Queue shutdown timeout: ${this.queue.length} events remaining, ${this.currentConcurrency} processing`);break}await new Promise(e=>setTimeout(e,50))}this.logger.debug("Queue shutdown complete")}clear(){const e=this.queue.length;this.queue.length=0,this.eventsDropped+=e,this.metrics.updateQueueDepth(0),this.logger.warn(`Cleared ${e} events from queue`)}async processNextBatch(){if(this.processingScheduled=!1,this.isShuttingDown&&0===this.queue.length)return;if(this.currentConcurrency>=this.config.maxConcurrent)return void setTimeout(()=>{this.processingScheduled||(this.processingScheduled=!0,setImmediate(()=>this.processNextBatch()))},10);const e=Math.min(this.config.batchSize,this.queue.length,this.config.maxConcurrent-this.currentConcurrency);if(0===e)return;const t=this.queue.splice(0,e);this.metrics.updateQueueDepth(this.queue.length),this.currentConcurrency+=t.length,this.currentConcurrency>this.maxConcurrencyReached&&(this.maxConcurrencyReached=this.currentConcurrency),this.totalBatchSize+=t.length,this.totalBatchesProcessed++;try{const e=await Promise.allSettled(t.map(e=>this.processEvent(e)));for(let n=0;n<e.length;n++){const r=e[n];this.eventsProcessedCount++,"rejected"===r.status&&this.logger.error(`Failed to process event ${t[n].transactionId}:`,r.reason)}}finally{this.currentConcurrency-=t.length}this.queue.length>0&&!this.processingScheduled&&(this.processingScheduled=!0,this.scheduleProcessing(()=>this.processNextBatch()))}async processEvent(e){if(!this.processor)return void this.logger.warn("No processor set, discarding event:",e.transactionId);const t=Date.now();try{await this.processor(e);const n=Ve(t);this.metrics.recordEventLatency(n)}catch(t){throw this.logger.error(`Event processing failed for ${e.transactionId}:`,t),t}}}class Cc extends ds{constructor(e,t,n,r={},i){super(!1,i),this.socket=null,this.maxSeenTransactions=1e4,this.listeners=[],this.onErrorCallbacks=[],this.isActive=!1,this.listenerRegistered=!1,this.handleSwapEvent=null,this.warmingIntervalHandle=null,e instanceof Promise?this.socketReady=e.then(e=>(this.socket=e,this.setupConnectionMonitoring(),e)).catch(e=>{throw this.logger.error("Failed to resolve socket promise:",e),e}):(this.socket=e,this.socketReady=Promise.resolve(e),this.setupConnectionMonitoring()),this.metrics=new kc,this.config=this.applyDefaults(r),this.eventExtractor=new Sc(this.logger),this.quoteService=n,this.cacheManager=new Ic(t,this.config,this.metrics,this.logger),this.eventQueue=new xc(this.config,this.metrics,this.logger),this.seenTransactions=new Nc(this.maxSeenTransactions),this.reconnectionManager=new nc({maxAttempts:3,baseDelayMs:1e3,useExponentialBackoff:!0,maxDelayMs:3e4}),this.eventQueue.setProcessor(e=>this.processSwapEvent(e)),this.logger.debug("Initialized MultiPoolStateManager")}subscribe(e,t){this.listeners.push(t),e.onError&&this.onErrorCallbacks.push(e.onError),this.isActive||(this.setupWebSocketListener(e),this.isActive=!0);const n=this;return()=>{n.listeners=n.listeners.filter(e=>e!==t),e.onError&&(n.onErrorCallbacks=n.onErrorCallbacks.filter(t=>t!==e.onError)),0===n.listeners.length&&0===n.onErrorCallbacks.length&&n.unsubscribe()}}getHealth(){const e=this.cacheManager.getStats(),t=this.eventQueue.getStats(),n=this.metrics.getHealthMetrics(e.totalCached,e.hotCacheSize,e.warmCacheSize,e.coldCacheSize,this.getMaxMemoryMB()),r=this.determineHealthStatus(t,e),i={connected:this.socket?.connected??!1,reconnectAttempts:this.reconnectionManager.getAttempts()};this.socket?.connected&&(i.lastConnectionTime=new Date);const o=t.queueSize/this.config.maxQueueSize*100,s=e.totalCached/this.config.maxPools*100,a=e.memoryUsedMB/this.getMaxMemoryMB()*100,c=this.generateHealthRecommendations(r,o,s,a,n.metrics.cacheHitRate);return{...n,status:r,websocket:i,recommendations:c,detailedMetrics:{eventQueueUtilization:o,cacheUtilization:s,memoryUtilization:a}}}generateHealthRecommendations(e,t,n,r,i){const o=[];return"failed"===e&&(o.push("🔴 System is in FAILED state - immediate action required"),this.socket?.connected||o.push("Reconnect WebSocket - connection lost"),t>90&&o.push("Reduce incoming event rate or increase maxQueueSize")),"degraded"===e&&(o.push("⚠️ System is DEGRADED - performance may be impacted"),t>75&&o.push(`Queue utilization ${t.toFixed(1)}% - consider increasing maxQueueSize`),r>80&&o.push(`Memory usage ${r.toFixed(1)}% - consider reducing cache size or memory profile`)),"healthy"===e&&(i<50&&o.push(`Cache hit rate ${i.toFixed(1)}% is low - consider warming more pools`),r>50&&o.push("Memory usage is moderate - monitor for growth trends"),t>50&&o.push("Queue utilization is elevated - monitor for bottlenecks")),o}getSummary(){return{...this.metrics.getSummary(),queueStats:this.eventQueue.getStats(),cacheStats:this.cacheManager.getStats()}}startBackgroundWarming(){if(this.warmingIntervalHandle)return;const e=this.config.refreshIntervalMs;this.warmingIntervalHandle=setInterval(()=>{this.performBackgroundWarming().catch(e=>{this.logger.error("Background warming error:",e)})},e),this.logger.debug(`Background warming started (interval: ${e}ms)`)}stopBackgroundWarming(){this.warmingIntervalHandle&&(clearInterval(this.warmingIntervalHandle),this.warmingIntervalHandle=null,this.logger.debug("Background warming stopped"))}async performBackgroundWarming(){const e=this.cacheManager.getStats();if(0!==e.totalCached)try{await this.cacheManager.refreshWarmAndHotTiers(),this.logger.debug(`Background warming completed: ${e.totalCached} pools in cache (hot: ${e.hotCacheSize}, warm: ${e.warmCacheSize})`)}catch(e){this.logger.debug("Background warming encountered an error:",e)}}async shutdown(){this.stopBackgroundWarming(),await this.unsubscribe(),await this.eventQueue.shutdown(),this.cacheManager.clear(),this.metrics.reset()}setupConnectionMonitoring(){this.socket&&(this.socket.on("disconnect",()=>{this.logger.warn("WebSocket disconnected"),this.notifyError(new Error("WebSocket disconnected")),this.config.autoRecover&&this.attemptReconnection().catch(e=>{this.logger.error("Reconnection failed:",e)})}),this.socket.on("connect_error",e=>{this.logger.error("WebSocket connection error:",e),this.notifyError(S(e)?e:new Error(A(e)))}))}async attemptReconnection(){const e=this.reconnectionManager.getAttempts(),t=this.reconnectionManager.getMaxAttempts();if(this.logger.debug(`Reconnection attempt ${e+1}/${t}`),this.reconnectionManager.isExhausted())return this.logger.error(`Max reconnection attempts (${t}) exceeded - performing full reset`),void await this.performFullReset();if(e<2)if(0===e)this.logger.debug("Tier 1: Quick reconnect");else{const e=this.reconnectionManager.getNextDelay();this.logger.debug(`Tier 2: Exponential backoff (${e}ms)`),await new Promise(t=>setTimeout(t,e))}try{this.socket?.disconnect&&(this.socket.disconnect(),this.logger.debug("Disconnected for reconnection")),this.socket?.connect?.(),this.logger.debug("Reconnection initiated"),this.reconnectionManager.recordAttempt()}catch(e){throw this.logger.error("Failed to initiate reconnection:",e),e}}async performFullReset(){this.logger.warn("Performing full system reset due to connection failures"),this.stopBackgroundWarming();const e=this.getHealth();this.logger.debug("System state before reset:",{status:e.status,queueSize:e.eventProcessing.eventsProcessed,cachedPools:e.pools.totalMonitored,memory:`${e.memory.usedMB}MB / ${e.memory.maxMB}MB`,cacheHitRate:`${e.metrics.cacheHitRate.toFixed(2)}%`}),this.cacheManager.clear(),this.metrics.reset(),this.reconnectionManager.reset(),this.notifyError(new Error("System reset: connection lost and recovery failed - please restart monitoring")),this.logger.info("System reset complete - ready for restart")}setupWebSocketListener(e){if(this.listenerRegistered)return void this.logger.debug("WebSocket listener already registered");const t=this;this.handleSwapEvent=(n,...r)=>{try{const n=Date.now(),i=r[0],o=t.eventExtractor.walkPayloadForSwaps(i,t.seenTransactions);if(0===o.length)return;t.logger.debug(`Extracted ${o.length} swaps from payload`);for(const n of o){if(t.filterSwap(n,e)){t.eventQueue.enqueue(n)||t.logger.debug(`Swap dropped due to queue overflow: ${n.transactionId}`)}}const s=Ve(n);t.metrics.recordEventLatency(s)}catch(e){t.logger.error("Error processing WebSocket payload:",e),t.notifyError(S(e)?e:new Error(A(e)))}},this.socket?(this.socket.onAny(this.handleSwapEvent),this.listenerRegistered=!0,this.setupConnectionMonitoring()):this.logger.warn("Socket not available for listener registration"),this.startBackgroundWarming(),this.logger.debug("WebSocket listener registered for all events")}async unsubscribe(){this.stopBackgroundWarming(),this.handleSwapEvent&&this.listenerRegistered&&this.socket&&(this.socket.offAny(this.handleSwapEvent),this.listenerRegistered=!1),this.isActive=!1,this.listeners=[],this.onErrorCallbacks=[],this.logger.debug("Unsubscribed from swap events")}filterSwap(e,t){if(t.tokenFilter){if(!vc.containsToken(e.poolKey,t.tokenFilter))return!1}if(t.pairTokens){const[n,r]=t.pairTokens;if(!vc.containsTokenPair(e.poolKey,n,r))return!1}if(t.feeTierFilter){if(vc.normalizeFee(t.feeTierFilter)!==e.feeTier)return!1}return!t.userFilter||e.user===t.userFilter}async processSwapEvent(e){const t=Date.now();try{const n=this.cacheManager.updatePoolWithSwapDelta(e.poolKey,e.direction,e.amount0,e.amount1,e);e.poolStateUpdated=n;const r=Ve(t);this.metrics.recordEventLatency(r);for(const t of this.listeners)try{const n=t(e);n instanceof Promise&&await n}catch(t){this.logger.error(`Listener error for swap ${e.transactionId}:`,t)}}catch(t){this.logger.error(`Failed to process swap ${e.transactionId}:`,t),this.notifyError(S(t)?t:new Error(A(t)))}}notifyError(e){for(const t of this.onErrorCallbacks)try{t(e)}catch(e){this.logger.error("Error in error callback:",e)}}determineHealthStatus(e,t){return!this.socket?.connected||e.queueSize>.9*this.config.maxQueueSize?"failed":e.queueSize>.75*this.config.maxQueueSize||t.memoryUsedMB>.9*this.getMaxMemoryMB()?"degraded":"healthy"}getMaxMemoryMB(){switch(this.config.memoryProfile){case"conservative":return 55;case"aggressive":return 530;default:return 250}}applyDefaults(e){return{memoryProfile:e.memoryProfile??"moderate",maxPools:e.maxPools??500,softLimit:e.softLimit??200,preloadTopN:e.preloadTopN??200,warmingTimeoutMs:e.warmingTimeoutMs??3e4,refreshIntervalMs:e.refreshIntervalMs??3e5,maxQueueSize:e.maxQueueSize??1e4,batchSize:e.batchSize??100,maxConcurrent:e.maxConcurrent??10,autoRecover:e.autoRecover??!0,maxParallelRefetch:e.maxParallelRefetch??20,enableDeltaOptimization:e.enableDeltaOptimization??!0,enableOfflineQuotes:e.enableOfflineQuotes??!0,metricsEnabled:e.metricsEnabled??!0,debug:e.debug??!1}}}class Nc{constructor(e){this.map=new Map,this.maxSize=e}has(e){return this.map.has(e)}add(e){if(this.map.has(e))return this.map.delete(e),this.map.set(e,Date.now()),this;if(this.map.size>=this.maxSize){const e=this.map.keys().next().value;this.map.delete(e)}return this.map.set(e,Date.now()),this}delete(e){return this.map.delete(e)}clear(){this.map.clear()}get size(){return this.map.size}}class Bc extends ds{constructor(e=!1){super(e),this.primaryIndex=new Map,this.secondaryIndex=new Map,this.fetchTimestamps=new Map}normalizeKey(e){return is(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,o]of this.primaryIndex){t.push(e),n+=o.size,r[e]=o.size;const s=this.fetchTimestamps.get(e);s&&(i[e]=s)}return{networks:t,totalItems:n,itemsByNetwork:r,fetchTimestamps:i}}clear(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 _c=["ETHEREUM","SOLANA"];class Pc extends Bc{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(_c);return{...e,totalTokens:e.totalItems,tokensByNetwork:e.itemsByNetwork}}}class Rc{constructor(e,t=!1,n){this.dexApiHttp=e,this.logger=new ze({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),o=await this.dexApiHttp.request({method:"GET",url:this.getApiEndpoint(),params:{...i,limit:r,offset:e}});if(Ye(o)||!Array.isArray(o.tokens))throw new _("Invalid API response: expected { tokens: array }","response","INVALID_RESPONSE");return{items:this.transformApiResponse(o.tokens),rawCount:o.tokens.length}}async autoPaginateFetch(e){return async function(e,t){const{maxLimit:n,logger:r,maxPages:i=1e4}=t,o=[];let s=0,a=!0,c=0;for(;a&&c<i;){r&&r.debug(`Auto-pagination (offset): fetching at offset ${s} with limit ${n}`);const t=await e(s,n);if(!t||!Array.isArray(t.items)){r&&r.warn("Auto-pagination (offset): received invalid result structure, stopping");break}o.push(...t.items),a=t.rawCount===n,s+=n,c++,r&&r.debug(`Auto-pagination (offset): fetched ${o.length} items so far (hasMore=${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: ${o.length}`),o}(async(t,n)=>this.executePaginatedRequest(t,n,e),{maxLimit:this.getMaxLimit(),logger:this.logger})}handleError(e,t){throw X(e,t,this.logger)}}class Dc extends Rc{constructor(e,t=!1){super(e,t,"BridgeableTokenService"),this.cache=new Pc(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 t?.contractAddress&&(i.ethereumContractAddress=t.contractAddress),t?.symbol&&(i.ethereumSymbol=t.symbol),void 0!==t?.allowanceStorageSlot&&(i.ethereumAllowanceSlot=t.allowanceStorageSlot),n?.contractAddress&&(i.solanaContractAddress=n.contractAddress),n?.symbol&&(i.solanaSymbol=n.symbol),e.image&&(i.image=e.image),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})`),wr(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 wr(async()=>{const t=await async function(e){const{network:t,cache:n,fetchFn:r,logger:i,itemTypeName:o="items"}=e;if(n.has(t)){const e=n.getAll(t);return i&&i.debug(`Returning ${e.length} cached ${o} for ${t}`),{items:e,fetchedAt:n.getFetchTimestamp(t)??Date.now(),itemCount:e.length}}i&&i.debug(`Fetching all ${o} for ${t} (no cache)`);const s=await r();return n.set(t,s),{items:s,fetchedAt:Date.now(),itemCount:s.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=ia(t);this.cache.has(n)||await this.fetchAllBridgeableTokensByNetwork(n);const i=this.cache.getByTokenId(n,r),o=void 0!==i,s=o?"ETHEREUM"===n?i.ethereumContractAddress:i.solanaContractAddress:void 0,a={isBridgeable:o,tokenSymbol:i?.symbol??js(r).collection,network:n};return void 0!==s&&(a.contractAddress=s),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)}}class Lc extends mc{constructor(e=!1){super(e),this.lastFetchedAt=null}normalizeKey(e){return is(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 Oc extends Lc{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 Uc extends Rc{constructor(e,t=!1){super(e,t,"WrappableTokenService"),this.cache=new Oc(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 e.channel&&(t.channel=e.channel),void 0!==e.trending&&(t.trending=e.trending),e.image&&(t.image=e.image),e.description&&(t.description=e.description),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())})`),wr(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 wr(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 o=await n();try{t.setAll(o)}catch(e){r&&r.error("Cache operation failed (non-fatal):",e)}return{items:o,fetchedAt:Date.now(),itemCount:o.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=ia(e),n=this.cache.getByTokenId(t);return n||(await Ya("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=ia(e);await Ya("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&&n&&(i.wrapCounterpart=n.wrapCounterpart),i}getCacheStats(){return this.cache.getStats()}clearCache(){this.cache.clear()}}function Mc(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function Fc(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 $c,qc,Kc,Gc,zc,Wc;function Hc(){return Gc?Kc:(Gc=1,Kc={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})}var jc=function(){if(Wc)return zc;Wc=1;const e=qc?$c:(qc=1,$c={space:"",cycles:!1,replacer:(e,t)=>t,stringify:JSON.stringify}),t=Hc().isFunction,n=Hc().isBoolean,r=Hc().isObject,i=Hc().isArray,o=Hc().isRegex,s=Hc().assign,a=Hc().keys;return zc=function(c,u){u=u||s({},e),t(u)&&(u={compare:u});const l=u.space||e.space,h=n(u.cycles)?u.cycles:e.cycles,d=u.replacer||e.replacer,f=u.stringify||e.stringify,g=u.compare&&(p=u.compare,function(e){return function(t,n){const r={key:t,value:e[t]},i={key:n,value:e[n]};return p(r,i)}});var p;h||f(c);const m=[];return function e(t,n,s,c){const u=l?"\n"+new Array(c+1).join(l):"",p=l?": ":":";if(s=function(e){return null==e?e:o(e)?e.toString():e.toJSON?e.toJSON():e}(s),void 0!==(s=d.call(t,n,s))){if(!r(s)||null===s)return f(s);if(i(s)){const t=[];for(let n=0;n<s.length;n++){const r=e(s,n,s[n],c+1)||f(null);t.push(u+l+r)}return"["+t.join(",")+u+"]"}{if(h){if(-1!==m.indexOf(s))return f("[Circular]");m.push(s)}const t=a(s).sort(g&&g(s)),n=[];for(let r=0;r<t.length;r++){const i=t[r],o=e(s,i,s[i],c+1);if(!o)continue;const a=f(i)+p+o;n.push(u+l+a)}return m.splice(m.indexOf(s),1),"{"+n.join(",")+u+"}"}}}({"":c},"",c,0)},zc}(),Vc=Mc(jc);const Xc={GALA_CHAIN:1,ETHEREUM:2,SOLANA:1002},Qc={ASSET:1,MUSIC:3};const Jc="0x9f452b7cC24e6e6FA690fe77CF5dD2ba3DbF1ED9",Yc="0x6a1734E09f3099a3675645D214ce547080ea67e0",Zc="https://dex-api-platform-dex-prod-gala.gala.com",eu=[{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}],tu=[{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 nu(e){return"PROD"===e?eu:tu}function ru(e){return"PROD"===e?Jc:Yc}const iu=eu,ou=[{symbol:"GALA",amount:"1",mintAddress:"eEUiUs4JWYZrp72djAGF1A8PhpR6rHphGeGN7GbVLp6",isNative:!1,decimals:8},{symbol:"GSOL",amount:"0.001",mintAddress:"So11111111111111111111111111111111111111111",isNative:!0,decimals:9}],su={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"}},au=["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)"],cu=["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"],uu={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])};const lu={name:"GalaConnect",chainId:1},hu=[{name:"destinationChainId",type:"uint256"},{name:"destinationChainTxFee",type:"destinationChainTxFee"},{name:"quantity",type:"string"},{name:"recipient",type:"string"},{name:"tokenInstance",type:"tokenInstance"},{name:"uniqueKey",type:"string"}],du=[{name:"collection",type:"string"},{name:"category",type:"string"},{name:"type",type:"string"},{name:"additionalKey",type:"string"}],fu=[{name:"collection",type:"string"},{name:"category",type:"string"},{name:"type",type:"string"},{name:"additionalKey",type:"string"},{name:"instance",type:"string"}],gu=[{name:"name",type:"string"},{name:"symbol",type:"string"}],pu={GalaTransaction:hu,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:du,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:fu,externalQuoteToken:gu,tokenInstance:fu},mu={GalaTransaction:hu,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:du,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:gu,externalQuoteToken:gu,externalCrossRateToken:gu,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:fu,tokenInstance:fu};function yu(e){return e?mu:pu}const wu={GalaTransaction:[{name:"quantity",type:"string"},{name:"tokenInstance",type:"tokenInstance"},{name:"destinationChainId",type:"uint256"},{name:"recipient",type:"string"},{name:"wrap",type:"bool"},{name:"uniqueKey",type:"string"}],tokenInstance:fu};class bu extends ds{constructor(e){super(!1,e.logger),this.galaConnectClient=e.galaConnectClient,this.wrappableTokenService=e.wrappableTokenService,this.wallet=e.wallet,this.walletAddress=e.walletAddress}async wrapToken(e){this.requireWallet();const t=await this.wrappableTokenService.getWrappableToken(e.tokenId);if(!t)throw new _(`Token not found or not wrappable: ${this.formatTokenId(e.tokenId)}`,"tokenId","TOKEN_NOT_WRAPPABLE");if("asset"===t.channel)throw new _(`Cannot wrap ${t.symbol} - it's already on asset channel. Use unwrapToken() instead.`,"tokenId","ALREADY_ON_ASSET_CHANNEL");const n=await this.wrappableTokenService.getWrapCounterpart(e.tokenId);if(!n)throw new _(`Counterpart token not found for ${t.symbol}`,"tokenId","COUNTERPART_NOT_FOUND");return this.executeChannelBridge({sourceToken:t,destinationToken:n,amount:e.amount,...e.recipient&&{recipient:e.recipient},...e.memo&&{memo:e.memo},isWrap:!0})}async unwrapToken(e){this.requireWallet();const t=await this.wrappableTokenService.getWrappableToken(e.tokenId);if(!t)throw new _(`Token not found or not wrappable: ${this.formatTokenId(e.tokenId)}`,"tokenId","TOKEN_NOT_WRAPPABLE");if("asset"!==t.channel)throw new _(`Cannot unwrap ${t.symbol} - it's not on asset channel. Use wrapToken() instead.`,"tokenId","NOT_ON_ASSET_CHANNEL");const n=await this.wrappableTokenService.getWrapCounterpart(e.tokenId);if(!n)throw new _(`Counterpart token not found for ${t.symbol}`,"tokenId","COUNTERPART_NOT_FOUND");return this.executeChannelBridge({sourceToken:t,destinationToken:n,amount:e.amount,...e.recipient&&{recipient:e.recipient},...e.memo&&{memo:e.memo},isWrap:!1})}async estimateWrapFee(e,t){if(!e)throw z("tokenId","Token identifier");if(!t)throw z("amount");const n=await this.wrappableTokenService.getWrappableToken(e);if(!n)throw new _(`Token not found or not wrappable: ${this.formatTokenId(e)}`,"tokenId","TOKEN_NOT_WRAPPABLE");if("asset"===n.channel)throw new _(`Cannot wrap ${n.symbol} - it's already on asset channel`,"tokenId","ALREADY_ON_ASSET_CHANNEL");const r=this.determineChannelRouting(n,!0);return{fee:"0",feeToken:"GALA",authorizationType:r.authType,feeChannel:r.sourceChannel}}async estimateUnwrapFee(e,t){if(!e)throw z("tokenId","Token identifier");if(!t)throw z("amount");const n=await this.wrappableTokenService.getWrappableToken(e);if(!n)throw new _(`Token not found or not wrappable: ${this.formatTokenId(e)}`,"tokenId","TOKEN_NOT_WRAPPABLE");if("asset"!==n.channel)throw new _(`Cannot unwrap ${n.symbol} - it's not on asset channel`,"tokenId","NOT_ON_ASSET_CHANNEL");const r=this.determineChannelRouting(n,!1);return{fee:"0",feeToken:"GALA",authorizationType:r.authType,feeChannel:r.sourceChannel}}async getWrapStatus(e){if(!e)throw z("transactionId");return{success:!0,status:"completed",transactionId:e,fromToken:"",toToken:"",amount:"",fromChannel:"",toChannel:""}}async executeChannelBridge(e){const{sourceToken:t,destinationToken:n,amount:r,recipient:i,isWrap:o}=e;if(!this.wallet||!this.walletAddress)throw new _("Wallet required for wrap/unwrap operations. Initialize SDK with a private key.","wallet","WALLET_REQUIRED");const s=this.walletAddress,a=this.determineChannelRouting(t,o),c=`galaswap-operation-${u.randomUUID()}`,l=wu,h={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||s,wrap:!0,uniqueKey:c};return this.logger.debug?.(`[WrapService] ${o?"Wrap":"Unwrap"} message (pre-signing):`,JSON.stringify(h,null,2)),this.executeWrapBridgeRequest({sourceToken:t,destinationToken:n,amount:r,message:h,routing:a,isWrap:o,senderAddress:s,typedDataTypes:l})}async executeWrapBridgeRequest(e){const{sourceToken:t,destinationToken:n,amount:r,message:i,routing:o,isWrap:s,typedDataTypes:a}=e;try{const e=await this.wallet.signTypedData(lu,a,i),c=`Ethereum Signed Message:\n${Vc({domain:lu,message:i,primaryType:"GalaTransaction",types:a}).length}`,u={...i,signature:e,prefix:c,types:a,domain:lu};this.logger.debug?.(`[WrapService] ${s?"Wrap":"Unwrap"} request (signed):`,JSON.stringify(u,null,2));const l=await this.galaConnectClient.requestBridgeOut(u);if(this.logger.debug?.("[WrapService] Response:",JSON.stringify(l,null,2)),function(e){return"object"==typeof e&&null!==e&&"Status"in e&&"number"==typeof e.Status&&1!==e.Status}(l)){const e=`Status=${l.Status}`,i=l.Message?`: ${l.Message}`:"";return{success:!1,fromToken:t.symbol,toToken:n.symbol,amount:r,fromChannel:o.sourceChannel,toChannel:s?"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}(l)){const e=l.Data;this.logger.debug?.("[WrapService] Step 1 complete, bridgeRequestId:",e);const i={bridgeFromChannel:o.sourceChannel,bridgeRequestId:e};this.logger.debug?.("[WrapService] Step 2 - BridgeTokenOut payload:",JSON.stringify(i,null,2));const a=await this.galaConnectClient.bridgeTokenOut(i);return this.logger.debug?.("[WrapService] BridgeTokenOut response:",JSON.stringify(a,null,2)),1!==a.Status?{success:!1,fromToken:t.symbol,toToken:n.symbol,amount:r,fromChannel:o.sourceChannel,toChannel:s?"asset":n.channel||"music",error:`BridgeTokenOut failed: ${JSON.stringify(a)}`}:{success:!0,transactionId:a.Hash||e,fromToken:t.symbol,toToken:n.symbol,amount:r,fromChannel:o.sourceChannel,toChannel:s?"asset":n.channel||"music",completedAt:Date.now()}}return{success:!1,fromToken:t.symbol,toToken:n.symbol,amount:r,fromChannel:o.sourceChannel,toChannel:s?"asset":n.channel||"music",error:`Unexpected response format from GalaChain: ${JSON.stringify(l)}`}}catch(e){const i=A(e);return this.logger.error?.(`[WrapService] ${s?"Wrap":"Unwrap"} operation failed:`,i),{success:!1,fromToken:t.symbol,toToken:n.symbol,amount:r,fromChannel:o.sourceChannel,toChannel:s?"asset":n.channel||"music",error:i}}}determineChannelRouting(e,t){if(t){return{sourceChannel:e.channel||"music",destinationChannelId:Qc.ASSET,authType:"cross_channel_authorization"}}return{sourceChannel:"asset",destinationChannelId:Qc.MUSIC,authType:"automatic"}}requireWallet(){if(!this.walletAddress)throw new _("Wallet required for wrap/unwrap operations. Initialize SDK with a private key.","wallet","WALLET_REQUIRED")}formatTokenId(e){return"string"==typeof e?e:Ks(e)}}const ku="x-api-key";class vu extends hs{constructor(e,t,n,r=!1){super(e,r),this.adminApiKey=t??void 0,this.jwtAuth=n}setJwtAuth(e){this.jwtAuth=e}validateTokenName(e,t){!function(e,t){if(!Qe(e))throw z("tokenName","Token name");const n=rs(e);if(!t.PATTERN.test(n))throw W("tokenName",`${t.MIN_LENGTH}-${t.MAX_LENGTH} alphanumeric characters`,"Token name")}(e,t)}validateRequiredString(e,t,n){!function(e,t,n){if(!Qe(e))throw z(t,n)}(e,t,n)}validateOptionalString(e,t,n,r){!function(e,t,n,r){if(null!=e){if("string"!=typeof e)throw Z(t,"string",typeof e,n);if(e.length>r)throw Y(t,r,e.length,n)}}(e,t,n,r)}validateOptionalNumber(e,t,n,r,i,o,s){!function(e,t,n,r,i){if(null!=e){if("number"!=typeof e)throw Z(t,"number",typeof e,n);if(e<r||e>i)throw Q(t,r,i,e,n)}}(e,t,n,r,i)}validateOptionalDate(e,t,n){!function(e,t,n){if(null!=e&&!je(e))throw W(t,"a valid ISO 8601 date string",n)}(e,t,n)}validatePositiveInteger(e,t,n){us(e,t,n)}validateStatusFilter(e,t,n="status"){ls(e,t,n)}buildPaginationParams(e,t){return Ss(e,t)}addOptionalFilterParams(e,t,n){return Ts(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(!this.adminApiKey)throw new R("Admin API key required for this operation. Set streamAdminApiKey in SDK config.");return{[ku]:this.adminApiKey}}getJwtHeaders(){if(!this.jwtAuth)throw new R("JWT authentication required. Call sdk.login() first.");return this.jwtAuth.getJwtHeaders()}hasJwtAuth(){return this.jwtAuth?.isValid()??!1}hasAdminApiKey(){return!!this.adminApiKey}getDualAuthHeaders(){return this.adminApiKey?this.getAdminHeaders():this.getJwtHeaders()}extractData(e){return pr(e,"Backend request failed",!0),yr(e,"No data in backend response")}async toggleFeature(e,t,n){this.validateTokenName(e,n);const r=this.buildEndpoint(t,{tokenName:e}),i=await this.http.post(r,{},this.getAdminHeaders()),o=this.extractData(i);return{enabled:o.enabled,tokenName:o.tokenName??rs(e)}}}const Su={IDLE:"IDLE",ACTIVE:"ACTIVE",DISABLED:"DISABLED"},Au={READY:"READY",PROCESSING:"PROCESSING",ERRORED:"ERRORED",DELETED:"DELETED"},Tu={YOUTUBE:"YOUTUBE",TWITCH:"TWITCH",FACEBOOK:"FACEBOOK",CUSTOM:"CUSTOM"},Eu=et(Su),Iu=et(Au),xu=et(Tu);const Cu={OWNER:"OWNER",MANAGER:"MANAGER",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MODERATOR:"MODERATOR"},Nu={OWNER:"OWNER",MODERATOR:"MODERATOR"};et(Cu),et(Nu);const Bu={...Cu,OVERSEER:"OVERSEER"},_u={OWNERSHIP:"ownership",MODERATOR_INVITE:"moderator_invite",OVERSEER:"overseer"};function Pu(e){if(!e||"object"!=typeof e)return!1;const t=e;return"boolean"==typeof t.canStream&&"boolean"==typeof t.canModerate&&"boolean"==typeof t.canManageTeam&&"boolean"==typeof t.canViewRecordings&&"boolean"==typeof t.canSimulcast&&"boolean"==typeof t.canViewAnalytics}const Ru=et(Bu),Du=et(_u);function Lu(e,t="tokenName"){rt(e,t,de)}function Ou(e){if(Lu(e.tokenName),!Qe(e.language))throw z("language");if(!function(e){return!!Qe(e)&&/^[a-z]{2}(-[A-Z]{2})?$/.test(e)}(e.language))throw new _('language must be a valid ISO 639-1 code (e.g., "en", "es", "zh-CN")',"language",B.INVALID_FORMAT)}class Uu extends vu{constructor(e,t,n,r=!1){super(e,t,n,r)}async getStreamInfo(e){this.validateTokenName(e,de);const t=this.buildEndpoint(Gt,{tokenName:e}),n=await this.http.get(t);return this.extractData(n)}async startStream(e){this.validateTokenName(e,de);const t=this.buildEndpoint(qt,{tokenName:e}),n=await this.http.post(t,{},this.getJwtHeaders());return this.extractData(n)}async stopStream(e){this.validateTokenName(e,de);const t=this.buildEndpoint(Kt,{tokenName:e});await this.http.post(t,{},this.getJwtHeaders())}async disableStream(e){return this.toggleFeature(e,zt,de)}async enableStream(e){return this.toggleFeature(e,Wt,de)}async resetStreamKey(e){this.validateTokenName(e,de);const t=this.buildEndpoint(Ht,{tokenName:e}),n=await this.http.post(t,{},this.getJwtHeaders());return this.extractData(n)}async getRecordings(e){!function(e){Lu(e.tokenName),Ze(e.page,e.limit,Ce)}(e);const t=this.buildEndpoint(jt,{tokenName:e.tokenName}),n=this.buildPaginationParams(e,Ce),r=await this.http.get(t,n),i=this.extractData(r);return{recordings:i.recordings,tokenName:rs(e.tokenName),page:i.page??e.page??1,limit:i.limit??e.limit??20,total:i.total,hasNext:i.recordings.length===(i.limit??e.limit??20)}}async getRecordingDownload(e,t){this.validateTokenName(e,de),this.validateRequiredString(t,"assetId","Asset ID");const n=this.buildEndpoint(Vt,{tokenName:e,assetId:t}),r=await this.http.get(n,this.getJwtHeaders());return this.extractData(r)}async deleteRecording(e,t){this.validateTokenName(e,de),this.validateRequiredString(t,"assetId","Asset ID");const n=this.buildEndpoint(Xt,{tokenName:e,assetId:t});await this.http.delete(n,void 0,this.getJwtHeaders())}async getSimulcastTargets(e){this.validateTokenName(e,de);const t=this.buildEndpoint(Qt,{tokenName:e}),n=await this.http.get(t);return this.extractData(n)}async addSimulcastTarget(e){!function(e){if(Lu(e.tokenName),!Qe(e.platform))throw z("platform");if(!xu(e.platform))throw new _("platform must be one of: 'YOUTUBE', 'TWITCH', 'FACEBOOK', 'CUSTOM'","platform",B.INVALID_VALUE);if(!Qe(e.rtmpUrl))throw z("rtmpUrl");if(!xe.STREAM_URL_PATTERN.test(e.rtmpUrl))throw new _("rtmpUrl must be a valid RTMP, RTMPS, or SRT URL","rtmpUrl",B.INVALID_FORMAT);if(!Qe(e.streamKey))throw z("streamKey");if(void 0!==e.name&&"string"!=typeof e.name)throw new _("name must be a string","name",B.INVALID_TYPE)}(e);const t=this.buildEndpoint(Jt,{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,de),this.validateRequiredString(t,"targetId","Target ID");const n=this.buildEndpoint(Yt,{tokenName:e,targetId:t});await this.http.delete(n,void 0,this.getJwtHeaders())}async getGlobalStreamingStatus(){const e=await this.http.get(Zt);return this.extractData(e)}async disableGlobalStreaming(){const e=await this.http.post(en,{},this.getAdminHeaders());return this.extractData(e)}async enableGlobalStreaming(){const e=await this.http.post(tn,{},this.getAdminHeaders());return this.extractData(e)}async setNextLiveStream(e){let t;!function(e){if(Lu(e.tokenName),null!==e.nextLiveStreamAt){if(!(e.nextLiveStreamAt instanceof Date||Qe(e.nextLiveStreamAt)))throw new _("nextLiveStreamAt must be a Date, ISO 8601 string, or null","nextLiveStreamAt",B.INVALID_TYPE);if("string"==typeof e.nextLiveStreamAt){const t=Date.parse(e.nextLiveStreamAt);if(isNaN(t))throw new _("nextLiveStreamAt must be a valid ISO 8601 date string","nextLiveStreamAt",B.INVALID_FORMAT)}}}(e),t=null===e.nextLiveStreamAt?null:e.nextLiveStreamAt instanceof Date?e.nextLiveStreamAt.toISOString():e.nextLiveStreamAt;const n=this.buildEndpoint(nn,{tokenName:e.tokenName}),r=await this.http.post(n,{nextLiveStreamAt:t},this.getDualAuthHeaders());return this.extractData(r)}async clearNextLiveStream(e){this.validateTokenName(e,de);const t=this.buildEndpoint(rn,{tokenName:e}),n=await this.http.delete(t,void 0,this.getDualAuthHeaders());return this.extractData(n)}async setStreamLanguage(e){Ou(e);const t=this.buildEndpoint(on,{tokenName:e.tokenName}),n=await this.http.put(t,{language:e.language},this.getDualAuthHeaders());return this.extractData(n)}async getStreamRole(e){!function(e){Lu(e.tokenName)}(e);const t=this.buildEndpoint(sn,{tokenName:e.tokenName}),n=this.jwtAuth?this.getJwtHeaders():void 0,r=await this.http.get(t,n);return this.extractData(r)}async getAvailableRoles(){const e=await this.http.get(an);return this.extractData(e)}async getTokenAccess(e){!function(e){Lu(e.tokenName)}(e);const t=this.buildEndpoint(cn,{tokenName:e.tokenName}),n=this.jwtAuth?this.getJwtHeaders():void 0;this.jwtAuth||this.logger.debug("getTokenAccess called without JWT authentication - will return hasAccess: false",{tokenName:e.tokenName});const r=await this.http.get(t,n);return this.extractData(r)}async setNextLiveStreamCountdown(e,t){return this.setNextLiveStream({tokenName:e,nextLiveStreamAt:t})}}de.MIN_LENGTH,de.MAX_LENGTH,de.PATTERN;et({ENABLED:"ENABLED",DISABLED:"DISABLED",ADMIN_DISABLED:"ADMIN_DISABLED"});function Mu(e){return"global"===e||"token"===e}function Fu(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.messageId&&"string"==typeof t.content&&"string"==typeof t.userAddress&&"number"==typeof t.poolId&&"string"==typeof t.createdAt}function $u(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.messageId&&"string"==typeof t.content&&"string"==typeof t.userAddress&&"string"==typeof t.pinnedBy&&"string"==typeof t.pinnedAt}const qu=et({RATE_LIMITED:"RATE_LIMITED",INVALID_EMOJI:"INVALID_EMOJI",NOT_AUTHENTICATED:"NOT_AUTHENTICATED",STREAM_NOT_LIVE:"STREAM_NOT_LIVE"});function Ku(e){if(!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)}class Gu extends vu{constructor(e,t,n,r=!1){super(e,t,n,r)}async getMessages(e){if(!e)throw z("options","Fetch options");return function(e){if(!Qe(e.tokenName))throw z("tokenName","Token name");const t=e.tokenName.trim();if(0===t.length)throw z("tokenName","Token name");if(!de.PATTERN.test(t))throw W("tokenName",`match pattern ${de.PATTERN}`,"Token name");if(Ze(e.page,e.limit,we),void 0!==e.cursor&&!Qe(e.cursor))throw Z("cursor","a non-empty string",typeof e.cursor);if(void 0!==e.sortOrder&&"asc"!==e.sortOrder&&"desc"!==e.sortOrder)throw W("sortOrder","'asc' or 'desc'")}(e),wr(async()=>{const t=this.buildEndpoint(un,{tokenName:e.tokenName}),n=this.buildPaginationParams(e,we);e.cursor&&(n.cursor=e.cursor),e.sortOrder&&(n.sortOrder=e.sortOrder);const r=await this.http.get(t,n),i=this.extractData(r),o=Vo(e.limit),s=i.page??jo(e.page),a={messages:i.messages,tokenName:rs(e.tokenName),page:s,limit:i.limit??o,total:i.total,hasNext:i.messages.length===o||!!i.nextCursor,pinnedMessage:i.pinnedMessage??null};return i.nextCursor&&(a.nextCursor=i.nextCursor),a},"Failed to fetch chat messages",this.logger)}async sendMessage(e){if(!e)throw z("options","Send message options");return function(e){if(!Qe(e.tokenName))throw z("tokenName","Token name");const t=e.tokenName.trim();if(0===t.length)throw z("tokenName","Token name");if(!de.PATTERN.test(t))throw W("tokenName",`match pattern ${de.PATTERN}`,"Token name");if(t.length>de.MAX_LENGTH)throw Y("tokenName",de.MAX_LENGTH,t.length,"Token name");if(!Qe(e.content))throw z("content","Message content");if(e.content.length<ve.CHAT_MESSAGE.MIN_LENGTH)throw J("content",ve.CHAT_MESSAGE.MIN_LENGTH,e.content.length,"Message content");if(e.content.length>ve.CHAT_MESSAGE.MAX_LENGTH)throw Y("content",ve.CHAT_MESSAGE.MAX_LENGTH,e.content.length,"Message content")}(e),wr(async()=>{const t=this.buildEndpoint(ln,{tokenName:e.tokenName}),n=await this.http.post(t,{content:e.content},this.getJwtHeaders());return{message:this.extractData(n),tokenName:rs(e.tokenName)}},"Failed to send chat message",this.logger)}async deleteMessage(e){if(!e)throw z("options","Delete message options");return function(e){if(!Qe(e.tokenName))throw z("tokenName","Token name");const t=e.tokenName.trim();if(0===t.length)throw z("tokenName","Token name");if(!de.PATTERN.test(t))throw W("tokenName",`match pattern ${de.PATTERN}`,"Token name");if(!Qe(e.messageId))throw z("messageId","Message ID")}(e),wr(async()=>{const t=this.buildEndpoint(hn,{tokenName:e.tokenName,messageId:e.messageId}),n=this.adminApiKey?this.getAdminHeaders():this.getJwtHeaders(),r=await this.http.delete(t,n),i=this.extractData(r);return{messageId:i.messageId,deleted:i.deleted,tokenName:rs(e.tokenName)}},"Failed to delete chat message",this.logger)}async getChatStatus(e){if(!e)throw z("tokenName","Token name");return this.validateTokenName(e,de),wr(async()=>{const t=this.buildEndpoint(dn,{tokenName:e}),n=await this.http.get(t);return this.extractData(n)},`Failed to get chat status for token: ${e}`,this.logger)}async disableChat(e){if(!e)throw z("tokenName","Token name");return this.validateTokenName(e,de),wr(async()=>{const t=this.buildEndpoint(fn,{tokenName:e}),n=await this.http.post(t,{},this.getDualAuthHeaders()),r=this.extractData(n),i={enabled:r.enabled,tokenName:r.tokenName??rs(e)};return r.status&&(i.status=r.status),i},`Failed to disable chat for token: ${e}`,this.logger)}async enableChat(e){if(!e)throw z("tokenName","Token name");return this.validateTokenName(e,de),wr(async()=>{const t=this.buildEndpoint(gn,{tokenName:e}),n=await this.http.post(t,{},this.getDualAuthHeaders()),r=this.extractData(n),i={enabled:r.enabled,tokenName:r.tokenName??rs(e)};return r.status&&(i.status=r.status),i},`Failed to enable chat for token: ${e}`,this.logger)}async getGlobalChatStatus(){const e=await this.http.get(wn);return this.extractData(e)}async disableGlobalChat(){const e=await this.http.post(bn,{},this.getAdminHeaders());return this.extractData(e)}async enableGlobalChat(){const e=await this.http.post(kn,{},this.getAdminHeaders());return this.extractData(e)}async getPinnedMessage(e){this.validateTokenName(e,de);const t=this.buildEndpoint(pn,{tokenName:e}),n=await this.http.get(t),r=this.extractData(n);return{tokenName:r.tokenName??rs(e),pinnedMessage:r.pinnedMessage}}async pinMessage(e){!function(e){if(!Qe(e.tokenName))throw z("tokenName","Token name");const t=e.tokenName.trim();if(0===t.length)throw z("tokenName","Token name");if(!de.PATTERN.test(t))throw W("tokenName",`match pattern ${de.PATTERN}`,"Token name");if(!Qe(e.messageId))throw z("messageId","Message ID")}(e);const t=this.buildEndpoint(mn,{tokenName:e.tokenName}),n=await this.http.post(t,{messageId:e.messageId},this.getAdminHeaders()),r=this.extractData(n);return{tokenName:r.tokenName??rs(e.tokenName),pinnedMessage:r.pinnedMessage}}async unpinMessage(e){this.validateTokenName(e,de);const t=this.buildEndpoint(yn,{tokenName:e}),n=await this.http.delete(t,this.getAdminHeaders()),r=this.extractData(n),i={tokenName:r.tokenName??rs(e),unpinned:r.unpinned};return r.unpinnedMessageId&&(i.unpinnedMessageId=r.unpinnedMessageId),i}async getEngagementStats(e){if(!e)throw z("options","Engagement stats options");return function(e){if(!Qe(e.tokenName))throw z("tokenName","Token name");const t=e.tokenName.trim();if(0===t.length)throw z("tokenName","Token name");if(!de.PATTERN.test(t))throw W("tokenName",`match pattern ${de.PATTERN}`,"Token name")}(e),wr(async()=>{const t=this.buildEndpoint(vn,{tokenName:e.tokenName}),n=await this.http.get(t,void 0,this.getDualAuthHeaders()),r=this.extractData(n);return{tokenName:rs(e.tokenName),chat:r.chat,comments:r.comments}},"Failed to get engagement stats",this.logger)}}const zu={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",STREAM_SUBSCRIBED:"token_subscribed",STREAM_UNSUBSCRIBED:"token_unsubscribed",VIEWER_COUNT:"viewer_count",STREAM_GLOBAL_STATUS:"stream_global_status",CHAT_MESSAGE:"stream_chat_message",CHAT_SENT:"stream_chat_sent",CHAT_ERROR:"stream_chat_error",CHAT_STATUS:"stream_chat_status",CHAT_GLOBAL_STATUS:"stream_chat_global_status",CHAT_AUTHENTICATED:"stream_chat_authenticated",CHAT_AUTH_ERROR:"stream_chat_auth_error",REACTION:"stream_reaction",REACTION_ERROR:"stream_reaction_error",USER_TYPING:"user_typing",CHAT_PINNED:"stream_chat_pinned",CHAT_UNPINNED:"stream_chat_unpinned",COUNTDOWN_UPDATED:"stream_countdown_updated",LANGUAGE_UPDATED:"stream_language_updated"};class Wu extends ds{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={},!e.url)throw new R("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 nc({maxAttempts:this.config.reconnectAttempts,baseDelayMs:this.config.reconnectDelay}),this.isSocketIOAvailable=this.checkSocketIOAvailability()}checkSocketIOAvailability(){try{return"function"==typeof a.io||(this.logger.warn('⚠️ Socket.IO client not available. Install "socket.io-client" package.'),!1)}catch(e){return this.logger.warn("⚠️ Socket.IO availability check failed:",A(e)),!1}}getRoomName(e){return`token:${rs(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 o=this.eventBufferTimeouts.get(r);o&&clearTimeout(o);const s=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,s)}processBufferedEvents(e,t){const n=rs(e),r=[{key:`${zu.STREAM_STATUS}:${n}`,callback:t.onStreamStatus},{key:`${zu.VIEWER_COUNT}:${n}`,callback:t.onViewerCount},{key:`${zu.CHAT_MESSAGE}:${n}`,callback:t.onChatMessage},{key:`${zu.CHAT_STATUS}:${n}`,callback:t.onChatStatus},{key:`${zu.CHAT_PINNED}:${n}`,callback:t.onChatPinned},{key:`${zu.CHAT_UNPINNED}:${n}`,callback:t.onChatUnpinned},{key:`${zu.COUNTDOWN_UPDATED}:${n}`,callback:t.onCountdownUpdated},{key:`${zu.LANGUAGE_UPDATED}:${n}`,callback:t.onLanguageUpdated}];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(zu.STREAM_STATUS,e=>{this.logger.debug(`📡 [Stream Status] ${e.tokenName}: ${e.status}`),this.bufferEvent(zu.STREAM_STATUS,e.tokenName,e);const t=this.roomCallbacks.get(rs(e.tokenName));t?.onStreamStatus&&t.onStreamStatus(e),this.globalCallbacks.onStreamStatus&&this.globalCallbacks.onStreamStatus(e)}),this.socket.on(zu.STREAM_SUBSCRIBED,e=>{this.logger.debug(`📡 [Subscribed] ${e.tokenName}`);const t=rs(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(zu.STREAM_UNSUBSCRIBED,e=>{const t=e.room.replace("token:","");this.logger.debug(`📡 [Unsubscribed] ${t}`);const n=this.roomCallbacks.get(rs(t));n?.onStreamUnsubscribed&&n.onStreamUnsubscribed(e)}),this.socket.on(zu.VIEWER_COUNT,e=>{this.logger.debug(`📡 [Viewer Count] ${e.tokenName}: ${e.viewerCount}`),this.bufferEvent(zu.VIEWER_COUNT,e.tokenName,e);const t=this.roomCallbacks.get(rs(e.tokenName));t?.onViewerCount&&t.onViewerCount(e),this.globalCallbacks.onViewerCount&&this.globalCallbacks.onViewerCount(e)}),this.socket.on(zu.STREAM_GLOBAL_STATUS,e=>{this.logger.debug(`📡 [Global Stream Status] enabled: ${e.enabled}`),this.globalCallbacks.onStreamGlobalStatus&&this.globalCallbacks.onStreamGlobalStatus(e)}),this.socket.on(zu.CHAT_MESSAGE,e=>{this.logger.debug(`📡 [Chat Message] ${e.tokenName}: ${e.message.content.slice(0,50)}...`),this.bufferEvent(zu.CHAT_MESSAGE,e.tokenName,e);const t=this.roomCallbacks.get(rs(e.tokenName));t?.onChatMessage&&t.onChatMessage(e),this.globalCallbacks.onChatMessage&&this.globalCallbacks.onChatMessage(e)}),this.socket.on(zu.CHAT_SENT,e=>{this.logger.debug(`📡 [Chat Sent] ${e.tokenName}: ${e.messageId}`);const t=this.roomCallbacks.get(rs(e.tokenName));t?.onChatSent&&t.onChatSent(e)}),this.socket.on(zu.CHAT_ERROR,e=>{this.logger.error(`📡 [Chat Error] ${e.tokenName}: ${e.message}`);const t=this.roomCallbacks.get(rs(e.tokenName));t?.onChatError&&t.onChatError(e),this.globalCallbacks.onChatError&&this.globalCallbacks.onChatError(e)}),this.socket.on(zu.CHAT_STATUS,e=>{this.logger.debug(`📡 [Chat Status] ${e.tokenName}: ${e.enabled}`),this.bufferEvent(zu.CHAT_STATUS,e.tokenName,e);const t=this.roomCallbacks.get(rs(e.tokenName));t?.onChatStatus&&t.onChatStatus(e),this.globalCallbacks.onChatStatus&&this.globalCallbacks.onChatStatus(e)}),this.socket.on(zu.CHAT_GLOBAL_STATUS,e=>{this.logger.debug(`📡 [Global Chat Status] enabled: ${e.enabled}`),this.globalCallbacks.onChatGlobalStatus&&this.globalCallbacks.onChatGlobalStatus(e)}),this.socket.on(zu.CHAT_AUTHENTICATED,e=>{this.logger.debug(`📡 [Authenticated] ${e.address}`),this.isAuthenticated=!0,this.globalCallbacks.onChatAuthenticated&&this.globalCallbacks.onChatAuthenticated(e)}),this.socket.on(zu.CHAT_AUTH_ERROR,e=>{this.logger.error(`📡 [Auth Error] ${e.message}`),this.isAuthenticated=!1,this.globalCallbacks.onChatAuthError&&this.globalCallbacks.onChatAuthError(e)}),this.socket.on(zu.REACTION,e=>{this.logger.debug(`📡 [Reaction] ${e.tokenName}: ${e.emoji}`);const t=this.roomCallbacks.get(rs(e.tokenName));t?.onReaction&&t.onReaction(e),this.globalCallbacks.onReaction&&this.globalCallbacks.onReaction(e)}),this.socket.on(zu.REACTION_ERROR,e=>{this.logger.error(`📡 [Reaction Error] ${e.tokenName}: ${e.message}`);const t=this.roomCallbacks.get(rs(e.tokenName));t?.onReactionError&&t.onReactionError(e),this.globalCallbacks.onReactionError&&this.globalCallbacks.onReactionError(e)}),this.socket.on(zu.USER_TYPING,e=>{const t=e.typingUsers.length;this.logger.debug(`📡 [Typing] ${e.tokenName}: ${t} user(s) typing`);const n=this.roomCallbacks.get(rs(e.tokenName));n?.onTypingIndicator&&n.onTypingIndicator(e),this.globalCallbacks.onTypingIndicator&&this.globalCallbacks.onTypingIndicator(e)}),this.socket.on(zu.CHAT_PINNED,e=>{this.logger.debug(`📡 [Chat Pinned] ${e.tokenName}: ${e.pinnedMessage.messageId}`),this.bufferEvent(zu.CHAT_PINNED,e.tokenName,e);const t=this.roomCallbacks.get(rs(e.tokenName));t?.onChatPinned&&t.onChatPinned(e),this.globalCallbacks.onChatPinned&&this.globalCallbacks.onChatPinned(e)}),this.socket.on(zu.CHAT_UNPINNED,e=>{this.logger.debug(`📡 [Chat Unpinned] ${e.tokenName}: ${e.unpinnedMessageId}`),this.bufferEvent(zu.CHAT_UNPINNED,e.tokenName,e);const t=this.roomCallbacks.get(rs(e.tokenName));t?.onChatUnpinned&&t.onChatUnpinned(e),this.globalCallbacks.onChatUnpinned&&this.globalCallbacks.onChatUnpinned(e)}),this.socket.on(zu.COUNTDOWN_UPDATED,e=>{const t=e.nextLiveStreamAt??"cleared";this.logger.debug(`📡 [Countdown Updated] ${e.tokenName}: ${t}`),this.bufferEvent(zu.COUNTDOWN_UPDATED,e.tokenName,e);const n=this.roomCallbacks.get(rs(e.tokenName));n?.onCountdownUpdated&&n.onCountdownUpdated(e),this.globalCallbacks.onCountdownUpdated&&this.globalCallbacks.onCountdownUpdated(e)}),this.socket.on(zu.LANGUAGE_UPDATED,e=>{this.logger.debug(`📡 [Language Updated] ${e.tokenName}: ${e.language}`),this.bufferEvent(zu.LANGUAGE_UPDATED,e.tokenName,e);const t=this.roomCallbacks.get(rs(e.tokenName));t?.onLanguageUpdated&&t.onLanguageUpdated(e),this.globalCallbacks.onLanguageUpdated&&this.globalCallbacks.onLanguageUpdated(e)}))}async 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(zu.SUBSCRIBE,{tokenName:t})}catch(e){this.logger.error(`Failed to re-subscribe to ${t}:`,e)}}async connect(){return new Promise((e,t)=>{wr(async()=>{if(!this.isSocketIOAvailable)throw new R('Socket.IO not available. Install "socket.io-client" package.');this.logger.debug(`🔌 Connecting to Stream WebSocket: ${this.config.url}`);const n={};this.config.authToken&&(n.token=this.config.authToken),this.socket=a.io(this.config.url,{transports:["websocket"],reconnection:!0,reconnectionAttempts:this.config.reconnectAttempts,reconnectionDelay:this.config.reconnectDelay,auth:n}),this.socket.on("connect",()=>{this.logger.debug(`✅ Stream WebSocket connected: ${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")})},"Stream WebSocket connection setup",this.logger,e=>{throw t(e),e})})}authenticate(e){if(!this.socket?.connected)throw new _("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(!e)throw z("token","Authentication token");this.logger.debug("📡 Authenticating with stream server"),this.socket.emit(zu.AUTHENTICATE,{token:e}),this.config.authToken=e}async subscribeToStream(e,t={}){if(!e)throw z("tokenName","Token name");if(!this.socket?.connected)throw new _("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");const n=rs(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 o=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:o}),this.roomCallbacks.set(n,t),this.subscribedRooms.set(n,{tokenName:n,subscribedAt:Date.now()}),this.logger.debug(`📡 Subscribing to stream: ${n}`),this.socket.emit(zu.SUBSCRIBE,{tokenName:n})})}unsubscribeFromStream(e){const t=rs(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(zu.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 z("tokenName","Token name");if(!t)throw z("content","Message content");if(!this.socket?.connected)throw new _("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(!this.isAuthenticated)throw new _("Not authenticated. Call authenticate() first.","auth","NOT_AUTHENTICATED");const n=rs(e);this.logger.debug(`📡 Sending chat message to ${n}: ${t.slice(0,30)}...`),this.socket.emit(zu.SEND_CHAT,{tokenName:n,content:t})}sendReaction(e,t,n=0){if(!e)throw z("tokenName","Token name");if(!t)throw z("emoji");if(!this.socket?.connected)throw new _("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(!this.isAuthenticated)throw new _("Not authenticated. Call authenticate() first.","auth","NOT_AUTHENTICATED");const r=rs(e);this.logger.debug(`📡 Sending reaction to ${r}: ${t}`),this.socket.emit(zu.SEND_REACTION,{tokenName:r,emoji:t,streamTime:n})}sendTypingStart(e){if(!e)throw z("tokenName","Token name");if(!this.socket?.connected)throw new _("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(!this.isAuthenticated)throw new _("Not authenticated. Call authenticate() first.","auth","NOT_AUTHENTICATED");const t=rs(e);this.logger.debug(`📡 Sending typing_start to ${t}`),this.socket.emit(zu.TYPING_START,{tokenName:t})}sendTypingStop(e){if(!e)throw z("tokenName","Token name");if(!this.socket?.connected)throw new _("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(!this.isAuthenticated)throw new _("Not authenticated. Call authenticate() first.","auth","NOT_AUTHENTICATED");const t=rs(e);this.logger.debug(`📡 Sending typing_stop to ${t}`),this.socket.emit(zu.TYPING_STOP,{tokenName:t})}setGlobalCallbacks(e){this.globalCallbacks=e}getSubscribedTokens(){return Array.from(this.subscribedRooms.keys())}isConnected(){return this.socket?.connected??!1}isAuthenticatedForChat(){return this.isAuthenticated}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.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")}}}class Hu extends ds{constructor(e=!1){super(e),this.socket=null,this.isConnected=!1,this.eventRegistry=this.createEmptyRegistry()}setSocket(e){this.socket=e,this.isConnected=!0,this.logger.debug("📡 [Events] Socket attached to StreamingEventService")}clearSocket(){this.socket=null,this.isConnected=!1,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,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)}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 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 ju={VIEWERS:"viewers",CHAT_PARTICIPANTS:"chat_participants"},Vu=et(ju),Xu=ot([{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}]),Qu=ot([{field:"userAddress",type:"string"},{field:"isPermanent",type:"boolean"}]),Ju=ot([{field:"userAddress",type:"string"}]),Yu=ot([{field:"tokenName",type:"string"},{field:"action",type:"string",validator:e=>"chat"===e||"comment"===e||"reaction"===e}]);function Zu(e){return null==e||""===e||"string"==typeof e&&(!at(e)&&e.length<=ve.BAN_REASON.MAX_LENGTH)}function el(e){return!!Ye(e)||"number"==typeof e&&(e>=Ae&&e<=Te)}class tl extends vu{constructor(e,t,n,r=!1){super(e,t,n,r)}async createBan(e){!function(e){if(rt(e.tokenName,"tokenName",de),!Qe(e.userAddress))throw z("userAddress");if(!Zu(e.reason))throw new _(`reason must be at most ${ve.BAN_REASON.MAX_LENGTH} characters`,"reason","TOO_LONG");if(!el(e.durationSeconds))throw new _(`durationSeconds must be between ${Ae} and ${Te} seconds`,"durationSeconds","OUT_OF_RANGE")}(e);const t=this.buildEndpoint(En,{tokenName:e.tokenName}),n={userAddress:e.userAddress};void 0!==e.reason&&(n.reason=e.reason),void 0!==e.durationSeconds&&(n.durationSeconds=e.durationSeconds);const r=await this.http.post(t,n,this.getDualAuthHeaders());return{ban:this.extractData(r),tokenName:rs(e.tokenName)}}async removeBan(e){!function(e){if(rt(e.tokenName,"tokenName",de),!Qe(e.userAddress))throw z("userAddress")}(e);const t=this.buildEndpoint(Cn,{tokenName:e.tokenName,userAddress:e.userAddress}),n=await this.http.delete(t,this.getDualAuthHeaders()),r=this.extractData(n);return{removed:r.removed,tokenName:rs(e.tokenName),userAddress:r.userAddress}}async listBans(e){!function(e){rt(e.tokenName,"tokenName",de),Ze(e.page,e.limit,pe)}(e);const t=this.buildEndpoint(In,{tokenName:e.tokenName}),n=this.buildPaginationParams(e,pe);this.addOptionalFilterParams(n,e,["search","name","userAddress"]);const r=await this.http.get(t,n,this.getDualAuthHeaders()),i=this.extractData(r);return{items:i.bans,meta:i.meta}}async getBanStatus(e){!function(e){if(rt(e.tokenName,"tokenName",de),!Qe(e.userAddress))throw z("userAddress")}(e);const t=this.buildEndpoint(xn,{tokenName:e.tokenName,userAddress:e.userAddress}),n=await this.http.get(t,{},this.getDualAuthHeaders()),r=this.extractData(n);return{banned:null!==r,...null!==r&&{ban:r},tokenName:rs(e.tokenName),userAddress:e.userAddress.toLowerCase()}}async getActiveUsers(e){!function(e){if(rt(e.tokenName,"tokenName",de),void 0!==e.type&&!Vu(e.type))throw new _(`type must be one of: ${Object.values(ju).join(", ")}`,"type",B.INVALID_VALUE)}(e);const t=this.buildEndpoint(Nn,{tokenName:e.tokenName}),n={};this.addOptionalFilterParams(n,e,["type","search","name","userAddress"]);const r=await this.http.get(t,n,this.getDualAuthHeaders());return this.extractData(r)}}function nl(e){return null==e||""===e||"string"==typeof e&&(!at(e)&&e.length<=ve.BAN_REASON.MAX_LENGTH)}function rl(e){if(rt(e.tokenName,"tokenName",de),!nl(e.reason))throw new _(`reason must be at most ${ve.BAN_REASON.MAX_LENGTH} characters`,"reason","TOO_LONG")}function il(e){rt(e.tokenName,"tokenName",de)}function ol(e){Ze(e.page,e.limit,pe)}function sl(e){rt(e.tokenName,"tokenName",de)}class al extends vu{constructor(e,t,n,r=!1){super(e,t,n,r)}async banToken(e){rl(e);const t=Qn,n={tokenName:rs(e.tokenName)};if(void 0!==e.reason)try{ue(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:rs(e.tokenName)}}async unbanToken(e){il(e);const t=this.buildEndpoint(Zn,{tokenName:e.tokenName}),n=await this.http.delete(t,this.getDualAuthHeaders());return{removed:this.extractData(n).removed,tokenName:rs(e.tokenName)}}async listTokenBans(e={}){ol(e);const t=Jn,n=this.buildPaginationParams(e,pe);this.addOptionalFilterParams(n,e,["search"]);const r=await this.http.get(t,n,this.getDualAuthHeaders()),i=this.extractData(r);return{items:i.bans,meta:i.meta}}async getTokenBan(e){sl(e);const t=this.buildEndpoint(Yn,{tokenName:e.tokenName}),n=await this.http.get(t,{},this.getDualAuthHeaders()),r=this.extractData(n);return{banned:null!==r,...null!==r&&{ban:r},tokenName:rs(e.tokenName)}}async isTokenBanned(e){return this.getTokenBan(e)}}const cl={MODERATOR:"MODERATOR",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MANAGER:"MANAGER",OWNER:"OWNER"},ul=tt(cl);function ll(e){return ul.includes(e)}function hl(e){const t=[];e.role?ll(e.role)||t.push(`Invalid role. Must be one of: ${ul.join(", ")}`):t.push(z("role").message);const n=t.length;if(N(t,()=>{ss(e.description,"description",255)}),t.length>n&&(t[n]="Description must be 255 characters or less"),void 0!==e.tokenNames){const n=t.length;N(t,()=>{if(!Array.isArray(e.tokenNames))throw Z("tokenNames","an array",e.tokenNames);if(!e.tokenNames.every(e=>"string"==typeof e))throw Z("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){const n=t.length;N(t,()=>{cs(e.expiresAt,"expiresAt")}),t.length>n&&(t[n]="expiresAt must be a valid ISO 8601 date string")}return t}function dl(e){const t=[];["role","description","delegateAllTokens","tokenNames","expiresAt"].some(t=>void 0!==e[t])||t.push("At least one field must be provided for update"),void 0===e.role||ll(e.role)||t.push(`Invalid role. Must be one of: ${ul.join(", ")}`);const n=t.length;if(N(t,()=>{ss(e.description,"description",255)}),t.length>n&&(t[n]="Description must be 255 characters or less"),void 0!==e.tokenNames){const n=t.length;N(t,()=>{if(!Array.isArray(e.tokenNames))throw Z("tokenNames","an array",e.tokenNames);if(!e.tokenNames.every(e=>"string"==typeof e))throw Z("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&&null!==e.expiresAt){const n=t.length;N(t,()=>{cs(e.expiresAt,"expiresAt")}),t.length>n&&(t[n]="expiresAt must be a valid ISO 8601 date string")}return t}function fl(e){Ze(e.page,e.limit,pe)}const gl={[cl.MODERATOR]:1,[cl.TECHNICAL_PRODUCER]:1,[cl.MANAGER]:2,[cl.OWNER]:3};class pl extends hs{constructor(e,t,n=!1){super(e,n,t)}extractData(e){const t={error:"error"in e?e.error:!e.success,data:e.data};return void 0!==e.message&&(t.message=e.message),pr(t,"API key operation failed",!0),e.data}validateApiKeyId(e){this.validatePositiveInteger(e,"id","API key ID")}async create(e){const t=hl(e);if(t.length>0)throw new _(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);const r=await this.http.post(Bn.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={}){fl(e),this.logger.debug("Listing API keys",e);const t=void 0!==e.limit?Vo(e.limit,1,pe):void 0,n={};void 0!==e.page&&(n.page=e.page),void 0!==t&&(n.limit=t);const r={...Ss(n,pe)},i=await this.http.get(Bn.LIST,r,this.getJwtHeaders()),o=this.extractData(i);return this.logger.debug("Listed API keys",{count:o.apiKeys.length,total:o.meta.total}),o}async findOne(e){this.validateApiKeyId(e),this.logger.debug("Getting API key",{id:e});const t=Bn.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=dl(t);if(n.length>0)throw new _(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);const i=Bn.UPDATE.replace(":id",String(e)),o=await this.http.patch(i,r,this.getJwtHeaders()),s=this.extractData(o);return this.logger.debug("Updated API key",{id:s.id,keyPrefix:s.keyPrefix}),s}async revoke(e){this.validateApiKeyId(e),this.logger.debug("Revoking API key",{id:e});const t=Bn.REVOKE.replace(":id",String(e));await this.http.delete(t,this.getJwtHeaders()),this.logger.debug("API key revoked",{id:e})}getRoles(){return[...ul]}}const ml={MODERATOR:"MODERATOR",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MANAGER:"MANAGER"},yl=tt(ml),wl={TOKEN:"TOKEN",ALL_OWNER_TOKENS:"ALL_OWNER_TOKENS"},bl=tt(wl),kl={PENDING:"PENDING",CLAIMED:"CLAIMED",REVOKED:"REVOKED",EXPIRED:"EXPIRED"},vl=tt(kl);function Sl(e){return yl.includes(e)}function Al(e){return vl.includes(e)}function Tl(e){return Ie.PATTERN.test(e)}const El=ot([{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"}]),Il=ot([{field:"tokenName",type:"string"},{field:"tokenSymbol",type:"string"},{field:"role",type:"string"},{field:"inviteScope",type:"string"},{field:"creatorAddress",type:"string"},{field:"claimedAt",type:"string"}]),xl=ot([{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:"object"}]);function Cl(e){return bl.includes(e)}class Nl extends vu{constructor(e,t,n,r=!1){super(e,t,n,r)}validateRole(e){if(!Qe(e))throw z("role","Role");if(!Sl(e))throw W("role",`one of: ${yl.join(", ")}`,"Role")}validateInviteCodeFormat(e){if(!Qe(e))throw z("inviteCode","Invite code");if(!Tl(e))throw W("inviteCode","valid invite code format","Invite code")}validateInviteScope(e){if(void 0!==e&&!Cl(e))throw new _(`Invalid invite scope. Must be one of: ${bl.join(", ")}`,"inviteScope","INVALID_VALUE")}async createInvite(e){this.validateInviteScope(e.inviteScope);const t=e.inviteScope??wl.TOKEN;if(t===wl.TOKEN){if(!e.tokenName)throw new _("Token name is required for TOKEN scope invites","tokenName","REQUIRED");this.validateTokenName(e.tokenName,de)}else if(t===wl.ALL_OWNER_TOKENS&&e.tokenName)throw new _("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",ve.DESCRIPTION.MAX_LENGTH),this.validateOptionalDate(e.expiresAt,"expiresAt","Expiration date");const n=_n,r={inviteScope:t,role:e.role};t===wl.TOKEN&&e.tokenName&&(r.tokenName=rs(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.getJwtHeaders());return{invite:this.extractData(i)}}async listInvites(e){e.tokenName&&this.validateTokenName(e.tokenName,de),this.validateStatusFilter(e.status,kl);const t=Dn,n={...this.buildPaginationParams(e,ye.MAX_LIMIT)};e.tokenName&&(n.tokenName=rs(e.tokenName)),e.status&&(n.status=e.status);const r=await this.http.get(t,n,this.getJwtHeaders()),i=this.extractData(r);return{items:i.invites,meta:i.meta}}async revokeInvite(e){this.validatePositiveInteger(e,"inviteId","Invite ID");const t=this.buildEndpoint(Ln,{id:String(e)});pr(await this.http.delete(t,this.getJwtHeaders()),"Failed to revoke invite")}async updateInviteRole(e){this.validatePositiveInteger(e.inviteId,"inviteId","Invite ID"),this.validateRole(e.role);const t=this.buildEndpoint(On,{id:String(e.inviteId)}),n={role:e.role},r=await this.http.patch(t,n,this.getJwtHeaders());return{invite:this.extractData(r)}}async claimInvite(e){this.validateInviteCodeFormat(e.inviteCode);const t=Pn,n={inviteCode:e.inviteCode},r=await this.http.post(t,n,this.getJwtHeaders()),i=this.extractData(r);return"tokenName"in i&&void 0!==i.tokenName?{token:i}:{blanketAccess:i}}async getModeratedTokens(e){const t=Rn,n=this.buildPaginationParams(e??{},ye.MAX_LIMIT),r=await this.http.get(t,n,this.getJwtHeaders()),i=this.extractData(r);return{items:i.tokens,meta:i.meta}}async getInviteByCode(e){this.validateInviteCodeFormat(e);const t=this.buildEndpoint(Un,{code:e}),n=await this.http.get(t,{});return this.extractData(n)}}var Bl,_l,Pl,Rl;exports.ContentType=void 0,(Bl=exports.ContentType||(exports.ContentType={})).CHAT_MESSAGE="CHAT_MESSAGE",Bl.COMMENT="COMMENT",Bl.STREAM="STREAM",exports.FlagReason=void 0,(_l=exports.FlagReason||(exports.FlagReason={})).INAPPROPRIATE_CONTENT="INAPPROPRIATE_CONTENT",_l.SPAM="SPAM",_l.HARASSMENT="HARASSMENT",_l.SCAM="SCAM",_l.OTHER="OTHER",exports.FlagStatus=void 0,(Pl=exports.FlagStatus||(exports.FlagStatus={})).PENDING="PENDING",Pl.DISMISSED="DISMISSED",Pl.ACTIONED="ACTIONED",exports.FlagAction=void 0,(Rl=exports.FlagAction||(exports.FlagAction={})).DELETE_CONTENT="DELETE_CONTENT",Rl.BAN_USER="BAN_USER",Rl.DELETE_AND_BAN="DELETE_AND_BAN";const Dl={[exports.FlagReason.INAPPROPRIATE_CONTENT]:"Inappropriate Content",[exports.FlagReason.SPAM]:"Spam",[exports.FlagReason.HARASSMENT]:"Harassment",[exports.FlagReason.SCAM]:"Scam",[exports.FlagReason.OTHER]:"Other"},Ll={[exports.FlagStatus.PENDING]:"Pending",[exports.FlagStatus.DISMISSED]:"Dismissed",[exports.FlagStatus.ACTIONED]:"Actioned"},Ol={[exports.FlagAction.DELETE_CONTENT]:"Delete Content",[exports.FlagAction.BAN_USER]:"Ban User",[exports.FlagAction.DELETE_AND_BAN]:"Delete & Ban"},Ul={[exports.ContentType.CHAT_MESSAGE]:"Chat Message",[exports.ContentType.COMMENT]:"Comment",[exports.ContentType.STREAM]:"Stream"},Ml=et(exports.ContentType),Fl=et(exports.FlagReason),$l=et(exports.FlagStatus),ql=et(exports.FlagAction),Kl=ot([{field:"id",type:"number"},{field:"tokenName",type:"string"},{field:"contentType",type:"string",validator:Ml},{field:"contentId",type:"string"},{field:"reporterAddress",type:"string"},{field:"reportedUserAddress",type:"string"},{field:"status",type:"string",validator:$l}]),Gl={TOKEN_NAME:fe,CONTENT_ID:ve.CONTENT_ID,DETAILS:ve.FLAG_DETAILS,PAGINATION:{MAX_LIMIT:pe}};function zl(e,t="tokenName"){rt(e,t,Gl.TOKEN_NAME)}class Wl extends vu{constructor(e,t,n,r=!1){super(e,t,n,r)}async createFlag(e){!function(e){if(zl(e.tokenName),!e.contentType)throw z("contentType","Content type");if(!Ml(e.contentType))throw W("contentType",`one of: ${Object.values(exports.ContentType).join(", ")}`,"Content type");if(!Qe(e.contentId))throw z("contentId","Content ID");if(e.contentId.length>Gl.CONTENT_ID.MAX_LENGTH)throw Y("contentId",Gl.CONTENT_ID.MAX_LENGTH,e.contentId.length,"Content ID");if(!Qe(e.reportedUserAddress))throw z("reportedUserAddress","Reported user address");if(yt(e.reportedUserAddress,"reportedUserAddress"),e.contentType===exports.ContentType.STREAM&&!e.reason)throw z("reason","Reason");if(void 0!==e.reason&&!Fl(e.reason))throw W("reason",`one of: ${Object.values(exports.FlagReason).join(", ")}`,"Reason");if(void 0!==e.details&&!Qe(e.details))throw Z("details","a non-empty string",typeof e.details);if(void 0!==e.details&&e.details.length>Gl.DETAILS.MAX_LENGTH)throw Y("details",Gl.DETAILS.MAX_LENGTH,e.details.length)}(e);const t={tokenName:e.tokenName,contentType:e.contentType,contentId:e.contentId,reportedUserAddress:e.reportedUserAddress};e.reason&&(t.reason=e.reason),e.details&&(t.details=e.details);const n=await this.http.post(Mn.CREATE,t,this.getJwtHeaders());return{flag:this.extractData(n).flag}}async listFlags(e){!function(e){if(zl(e.tokenName),void 0!==e.contentType&&!Ml(e.contentType))throw W("contentType",`one of: ${Object.values(exports.ContentType).join(", ")}`,"Content type");if(void 0!==e.status&&!$l(e.status))throw W("status",`one of: ${Object.values(exports.FlagStatus).join(", ")}`);if(void 0!==e.reason&&!Fl(e.reason))throw W("reason",`one of: ${Object.values(exports.FlagReason).join(", ")}`);if(void 0!==e.reporterAddress&&!Qe(e.reporterAddress))throw Z("reporterAddress","a non-empty string",typeof e.reporterAddress);if(void 0!==e.reporterAddress&&yt(e.reporterAddress,"reporterAddress"),void 0!==e.reportedUserAddress&&!Qe(e.reportedUserAddress))throw Z("reportedUserAddress","a non-empty string",typeof e.reportedUserAddress);void 0!==e.reportedUserAddress&&yt(e.reportedUserAddress,"reportedUserAddress"),Ze(e.page,e.limit,Gl.PAGINATION.MAX_LIMIT)}(e);const t={};void 0!==e.page&&(t.page=e.page),void 0!==e.limit&&(t.limit=e.limit);const n=Ss(t,pe);Ts(n,e,["contentType","status","reason","reporterAddress","reportedUserAddress"]);const r=Mn.LIST.replace(":tokenName",encodeURIComponent(e.tokenName)),i=await this.http.get(r,n,this.getDualAuthHeaders()),o=this.extractData(i);return{items:o.flags,meta:o.meta}}async listGlobalFlags(e={}){!function(e){if(void 0!==e.tokenName&&zl(e.tokenName),void 0!==e.contentType&&!Ml(e.contentType))throw W("contentType",`one of: ${Object.values(exports.ContentType).join(", ")}`,"Content type");if(void 0!==e.status&&!$l(e.status))throw W("status",`one of: ${Object.values(exports.FlagStatus).join(", ")}`);if(void 0!==e.reason&&!Fl(e.reason))throw W("reason",`one of: ${Object.values(exports.FlagReason).join(", ")}`);if(void 0!==e.reporterAddress&&!Qe(e.reporterAddress))throw Z("reporterAddress","a non-empty string",typeof e.reporterAddress);if(void 0!==e.reporterAddress&&yt(e.reporterAddress,"reporterAddress"),void 0!==e.reportedUserAddress&&!Qe(e.reportedUserAddress))throw Z("reportedUserAddress","a non-empty string",typeof e.reportedUserAddress);void 0!==e.reportedUserAddress&&yt(e.reportedUserAddress,"reportedUserAddress"),Ze(e.page,e.limit,Gl.PAGINATION.MAX_LIMIT)}(e);const t={};void 0!==e.page&&(t.page=e.page),void 0!==e.limit&&(t.limit=e.limit);const n=Ss(t,pe);Ts(n,e,["tokenName","contentType","status","reason","reporterAddress","reportedUserAddress"]);const r=await this.http.get(Mn.LIST_GLOBAL,n,this.getDualAuthHeaders()),i=this.extractData(r);return{items:i.flags,meta:i.meta}}async dismissFlag(e){!function(e){if(void 0===e.flagId||null===e.flagId)throw z("flagId","Flag ID");try{ae(e.flagId,"flagId")}catch{throw W("flagId","a positive integer","Flag ID")}}(e);const t=Mn.DISMISS.replace(":id",e.flagId.toString()),n=await this.http.post(t,{},this.getDualAuthHeaders());return{flag:this.extractData(n).flag}}async actionFlag(e){!function(e){if(void 0===e.flagId||null===e.flagId)throw z("flagId","Flag ID");try{ae(e.flagId,"flagId")}catch{throw W("flagId","a positive integer","Flag ID")}if(!e.action)throw z("action","Action");if(!ql(e.action))throw W("action",`one of: ${Object.values(exports.FlagAction).join(", ")}`,"Action")}(e);const t=Mn.ACTION.replace(":id",e.flagId.toString()),n=await this.http.post(t,{action:e.action},this.getDualAuthHeaders());return{flag:this.extractData(n).flag}}}const Hl={PENDING:"PENDING",CLAIMED:"CLAIMED",REVOKED:"REVOKED",EXPIRED:"EXPIRED"},jl={ACTIVE:"ACTIVE",REVOKED:"REVOKED"},Vl=et(Hl),Xl=et(jl);function Ql(e){try{ss(e.description,"description",255)}catch(e){if(e instanceof _){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(!Qe(e.expiresAt))throw new Error("expiresAt must be a non-empty string");try{cs(e.expiresAt,"expiresAt")}catch(e){if(e instanceof _)throw new Error("expiresAt must be a valid ISO 8601 date string");throw e}if(je(e.expiresAt)){if(He(e.expiresAt)<=new Date)throw new Error("expiresAt must be in the future")}}}function Jl(e){if(void 0!==e.status&&!Vl(e.status))throw ne("status",e.status,Object.values(Hl),"status");Ze(e.page,e.limit,50)}function Yl(e){if(void 0!==e.status&&!Xl(e.status))throw ne("status",e.status,Object.values(jl),"status");Ze(e.page,e.limit,50)}function Zl(e){if(!Qe(e))throw new Error("Invite code must be a non-empty string");se(e,100,"code")}function eh(e){if(!Qe(e))throw new Error("Address must be a non-empty string");try{yt(e,"address")}catch{throw new Error("Invalid wallet address format. Must be eth|..., 0x..., or client|... format")}}function th(e){try{as(e,"id")}catch(e){if(e instanceof _)throw new Error("Invite ID must be a positive integer");throw e}}function nh(e){if(!e||"object"!=typeof e)throw new _("Options are required");if(void 0===e.page&&void 0===e.limit||Ze(e.page,e.limit,100),void 0!==e.search){if("string"!=typeof e.search)throw new _("Search must be a string");if(0===e.search.length)throw new _("Search query cannot be empty string")}if(void 0!==e.sortBy){if("string"!=typeof e.sortBy)throw new _("Sort field must be a string");if(0===e.sortBy.length)throw new _("Sort field cannot be empty string")}if(void 0!==e.sortOrder&&"asc"!==e.sortOrder&&"desc"!==e.sortOrder)throw new _('Sort order must be "asc" or "desc"')}class rh extends vu{constructor(e,t,n,r=!1){super(e,t,n,r)}validateInviteCodeFormat(e){if(!Qe(e))throw z("inviteCode","Invite code");Zl(e)}validateWalletAddressFormat(e){if(!Qe(e))throw z("address","Address");eh(e)}async createInvite(e={}){Ql(e),this.validateOptionalString(e.description,"description","Description",ve.DESCRIPTION.MAX_LENGTH),this.validateOptionalDate(e.expiresAt,"expiresAt","Expiration date");const t=Fn,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={}){Jl(e),this.validateStatusFilter(e.status,Hl);const t=$n,n={...this.buildPaginationParams(e,ye.MAX_LIMIT)};e.status&&(n.status=e.status);const r=await this.http.get(t,n,this.getDualAuthHeaders()),i=this.extractData(r);return{items:i.invites,meta:i.meta}}async getInviteByCode(e){this.validateInviteCodeFormat(e);const t=this.buildEndpoint(qn,{code:e}),n=await this.http.get(t,{});return this.extractData(n)}async revokeInvite(e){th(e);const t=this.buildEndpoint(Gn,{id:String(e)});pr(await this.http.delete(t,this.getDualAuthHeaders()),"Failed to revoke invite")}async claimInvite(e){this.validateInviteCodeFormat(e);const t=Kn,n={inviteCode:e},r=await this.http.post(t,n,this.getJwtHeaders());return{invite:this.extractData(r)}}async listOverseers(e={}){Yl(e),this.validateStatusFilter(e.status,jl);const t=zn,n={...this.buildPaginationParams(e,ye.MAX_LIMIT)};e.status&&(n.status=e.status);const r=await this.http.get(t,n,this.getDualAuthHeaders()),i=this.extractData(r);return{items:i.overseers,meta:i.meta}}async revokeOverseer(e){this.validateWalletAddressFormat(e);const t=this.buildEndpoint(Wn,{address:e});pr(await this.http.delete(t,this.getDualAuthHeaders()),"Failed to revoke overseer")}async getMyStatus(){const e=Hn,t=await this.http.get(e,{},this.getJwtHeaders());return this.extractData(t)}async getSummary(){const e=jn,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async listOverseerUsers(e){const t=e||{};Object.keys(t).length>0&&nh(t);const n=Vn,r={};void 0!==t.page&&(r.page=t.page),void 0!==t.limit&&(r.limit=t.limit),t.search&&(r.search=t.search),t.sortBy&&(r.sortBy=t.sortBy),t.sortOrder&&(r.sortOrder=t.sortOrder);const i=await this.http.get(n,r,this.getDualAuthHeaders()),o=this.extractData(i);return{items:o.items,meta:o.meta}}async getOverseerUserSummary(e){if(!Qe(e))throw z("address","User address");eh(e);const t=this.buildEndpoint(Xn,{address:e}),n=await this.http.get(t,{},this.getDualAuthHeaders());return this.extractData(n)}}class ih extends vu{constructor(e,t,n,r=!1){super(e,t,n,r)}async fetchComments(e){!function(e){rt(e.tokenName,"tokenName",fe),Ze(e.page,e.limit,pe)}(e);const t=rs(e.tokenName),n=void 0!==e.limit?Vo(e.limit,1,pe):void 0,r={};void 0!==e.page&&(r.page=e.page),void 0!==n&&(r.limit=n);const i={tokenName:t,...Ss(r,pe)},o=await this.http.get(er,i),s=this.extractData(o);return{items:(s.comments||[]).map(e=>{const t={id:e.id,messageId:e.messageId,content:e.content,userAddress:e.userAddress,poolId:e.poolId,createdAt:e.createdAt};if(e.user){const n={fullName:e.user.fullName};void 0!==e.user.profileImage&&(n.profileImage=e.user.profileImage),t.user=n}return e.reactions&&(t.reactions=e.reactions),e.holderTier&&(t.holderTier=e.holderTier),t}),meta:s.meta}}async postComment(e){!function(e){if(rt(e.tokenName,"tokenName",fe),!Qe(e.content))throw z("content");if(e.content.length>ve.COMMENT.MAX_LENGTH)throw new _(`content must be at most ${ve.COMMENT.MAX_LENGTH} characters`,"content",B.TOO_LONG)}(e);const t=tr,n={content:e.content.trim(),tokenName:rs(e.tokenName)},r=await this.http.post(t,n,this.getJwtHeaders()),i=this.extractData(r);return{comment:{id:i.id,messageId:i.messageId,content:i.content,userAddress:i.userAddress,poolId:i.poolId,createdAt:i.createdAt}}}async deleteComment(e){!function(e){if(void 0===e.commentId||null===e.commentId)throw z("commentId");as(e.commentId,"commentId")}(e);const t=this.buildEndpoint(nr,{commentId:String(e.commentId)});return await this.http.delete(t,void 0,this.getJwtHeaders()),{success:!0}}}const oh=["heart","fire","laugh","wow","thumbs_up"];class sh extends vu{constructor(e,t,n,r=!1){super(e,t,n,r)}validateReactionTokenName(e){this.validateTokenName(e,fe)}validateMessageId(e){if(!Qe(e))throw z("messageId","Message ID");if(se(e,Se.CONTENT_REACTION.MAX_LENGTH,"messageId"),!Se.CONTENT_REACTION.PATTERN.test(e))throw W("messageId","msg-{timestamp}-{uuid} or chat-{timestamp}-{uuid} format","Message ID")}validateReactionType(e){if(!Qe(e))throw z("reactionType","Reaction type");if(!oh.includes(e))throw W("reactionType",`one of: ${oh.join(", ")}`,"Reaction type")}async addContentReaction(e){this.validateReactionTokenName(e.tokenName),this.validateMessageId(e.messageId),this.validateReactionType(e.reactionType);const t={tokenName:rs(e.tokenName),messageId:e.messageId,reactionType:e.reactionType},n=await this.http.post(rr,t,this.getDualAuthHeaders()),r=this.extractData(n),{created:i,...o}=r;return{data:o,created:i}}async removeContentReaction(e){this.validateReactionTokenName(e.tokenName),this.validateMessageId(e.messageId),this.validateReactionType(e.reactionType);const t=this.buildEndpoint(ir,{messageId:e.messageId,reactionType:e.reactionType}),n={tokenName:rs(e.tokenName)};return await this.http.delete(t,n,this.getDualAuthHeaders()),{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 ah extends vu{constructor(e,t,n,r=!1){super(e,t,n,r)}validateContent(e){if(!Qe(e))throw z("content","Comment content");if(0===e.trim().length)throw z("content","Comment content");se(e,ve.COMMENTS_V1.MAX_LENGTH,"content")}validateMessageId(e){if(!Qe(e))throw z("id","Message ID");if(e.length<10||e.length>64)throw W("id","valid message ID format","Message ID")}async getComments(e){if(!e.tokenName&&!e.userAddress)throw new _("At least one of tokenName or userAddress must be provided","filter","REQUIRED");e.tokenName&&this.validateTokenName(e.tokenName,fe);const t={};void 0!==e.page&&(t.page=e.page),void 0!==e.limit&&(t.limit=e.limit);const n={...Ss(t,ye.MAX_LIMIT)};e.tokenName&&(n.tokenName=rs(e.tokenName)),e.userAddress&&(n.userAddress=e.userAddress);const r=await this.http.get(lr,n),i=this.extractData(r);return{messages:i.messages,meta:i.meta}}async createComment(e){this.validateTokenName(e.tokenName,fe),this.validateContent(e.content);const t={tokenName:rs(e.tokenName),content:e.content.trim()},n=await this.http.post(hr,t,this.getJwtHeaders()),r=this.extractData(n);return{comment:{id:r.messageId,tokenName:r.pool?.tokenName??"",tokenImage:r.pool?.tokenImage??null,userAddress:r.userAddress,userProfile:r.user?{fullName:r.user.fullName,profileImage:r.user.profileImage}:null,content:r.content,createdAt:r.createdAt,updatedAt:r.updatedAt,deletedAt:r.deletedAt,flagCount:0,reactions:{}}}}async updateComment(e,t){this.validateMessageId(e),this.validateContent(t.content);const n=this.buildEndpointWithId(dr,e),r={content:t.content.trim()},i=await this.http.put(n,r,this.getJwtHeaders()),o=this.extractData(i);return{comment:{id:o.messageId,tokenName:o.pool?.tokenName??"",tokenImage:o.pool?.tokenImage??null,userAddress:o.userAddress,userProfile:o.user?{fullName:o.user.fullName,profileImage:o.user.profileImage}:null,content:o.content,createdAt:o.createdAt,updatedAt:o.updatedAt,deletedAt:o.deletedAt,flagCount:0,reactions:{}}}}async deleteComment(e){this.validateMessageId(e);const t=this.buildEndpointWithId(fr,e);return await this.http.delete(t,void 0,this.getDualAuthHeaders()),{success:!0}}}function ch(e){if(!e.tokenName&&!e.userAddress)throw new _("At least one of tokenName or userAddress is required","options",B.REQUIRED);if(void 0!==e.tokenName){if(!Qe(e.tokenName))throw Z("tokenName","string");if(e.tokenName.length>ge.MAX_LENGTH)throw new _(`tokenName must be at most ${ge.MAX_LENGTH} characters`,"tokenName",B.TOO_LONG)}if(void 0!==e.userAddress){if(!Qe(e.userAddress))throw Z("userAddress","string");if(e.userAddress.length>ke.MAX_LENGTH)throw new _(`userAddress must be at most ${ke.MAX_LENGTH} characters`,"userAddress",B.TOO_LONG)}Ze(e.page,e.limit,ye.MAX_LIMIT)}function uh(e){if(!Qe(e.tokenName))throw z("tokenName");if(e.tokenName.length>ge.MAX_LENGTH)throw new _(`tokenName must be at most ${ge.MAX_LENGTH} characters`,"tokenName",B.TOO_LONG);if(!Qe(e.content))throw z("content");if(0===e.content.trim().length)throw new _("content cannot be empty","content",B.REQUIRED);if(e.content.length>ve.CHAT_MESSAGES_V1.MAX_LENGTH)throw new _(`content must be at most ${ve.CHAT_MESSAGES_V1.MAX_LENGTH} characters`,"content",B.TOO_LONG)}function lh(e){if(!Qe(e.content))throw z("content");if(0===e.content.trim().length)throw new _("content cannot be empty","content",B.REQUIRED);if(e.content.length>ve.CHAT_MESSAGES_V1.MAX_LENGTH)throw new _(`content must be at most ${ve.CHAT_MESSAGES_V1.MAX_LENGTH} characters`,"content",B.TOO_LONG)}function hh(e){if(!Qe(e))throw z("id","Message ID");if(!Se.CHAT_MESSAGE.PATTERN.test(e))throw new _("Invalid message ID format. Expected: chat-{timestamp}-{uuid}","id",B.INVALID_FORMAT)}class dh extends vu{constructor(e,t,n,r=!1){super(e,t,n,r)}async getChatMessages(e){ch(e);const t=this.buildPaginationParams(e,ye.MAX_LIMIT);e.tokenName&&(t.tokenName=rs(e.tokenName)),e.userAddress&&(t.userAddress=e.userAddress);const n=await this.http.get(sr,t);return this.extractData(n)}async sendMessage(e){uh(e);const t={tokenName:rs(e.tokenName),content:e.content.trim()},n=await this.http.post(ar,t,this.getJwtHeaders());return{message:this.extractData(n)}}async updateMessage(e,t){hh(e),lh(t);const n=this.buildEndpointWithId(cr,e),r={content:t.content.trim()},i=await this.http.put(n,r,this.getJwtHeaders());return{message:this.extractData(i)}}async deleteMessage(e){hh(e);const t=this.buildEndpointWithId(ur,e);pr(await this.http.delete(t,this.getDualAuthHeaders()),"Failed to delete message")}}function fh(e){const t=function(e){const t=eo(e);return t.success?[]:t.errors||["Unknown validation error"]}(e);if(t.length>0)throw new Error(`LaunchTokenData validation failed:\n${t.map(e=>`- ${e}`).join("\n")}`)}const gh="/api/asset/launchpad-contract/CallNativeTokenIn",ph="/api/asset/launchpad-contract/CallNativeTokenOut",mh="/api/asset/launchpad-contract/CallMemeTokenIn",yh="/api/asset/launchpad-contract/CallMemeTokenOut";class wh extends n.ChainCallDTO{constructor(e){super(),this.tokenName=e.tokenName,this.tokenSymbol=e.tokenSymbol,this.tokenDescription=e.tokenDescription,this.tokenImage=e.tokenImage,this.preBuyQuantity=e.preBuyQuantity,e.websiteUrl&&(this.websiteUrl=e.websiteUrl),e.telegramUrl&&(this.telegramUrl=e.telegramUrl),e.twitterUrl&&(this.twitterUrl=e.twitterUrl),e.instagramUrl&&(this.instagramUrl=e.instagramUrl),e.facebookUrl&&(this.facebookUrl=e.facebookUrl),e.redditUrl&&(this.redditUrl=e.redditUrl),e.tiktokUrl&&(this.tiktokUrl=e.tiktokUrl),this.tokenCategory=e.tokenCategory,this.tokenCollection=e.tokenCollection,this.uniqueKey=e.uniqueKey,e.reverseBondingCurveConfiguration&&(this.reverseBondingCurveConfiguration=e.reverseBondingCurveConfiguration)}}function bh(e){if(!e||"object"!=typeof e)return!1;const t=e;return"number"==typeof t.Status&&void 0!==t.Data&&"object"==typeof t.Data&&null!==t.Data&&"string"==typeof t.Data.calculatedQuantity&&void 0!==t.Data.extraFees&&"object"==typeof t.Data.extraFees&&null!==t.Data.extraFees&&"string"==typeof t.Data.extraFees.reverseBondingCurve&&"string"==typeof t.Data.extraFees.transactionFees}const kh={NATIVE:"native",EXACT:"exact"},vh={LOCAL:"local",EXTERNAL:"external"};class Sh{static calculateBuyWithExact(e,t){const n=Re(e),r=Re(t),{BASE_PRICE:i,PRICE_SCALING_FACTOR:o,TRADING_FEE_FACTOR:s,GAS_FEE:a}=pc,c=this.roundUp(i*(Math.exp((r+n)*o)-Math.exp(r*o))/o,8),u=bo(wo(c).multipliedBy(s));return{amount:c.toString(),reverseBondingCurveFee:"0",transactionFee:u,gasFee:a}}static calculateBuyWithNative(e,t){const n=Re(e),r=Re(t),{BASE_PRICE:i,PRICE_SCALING_FACTOR:o,TRADING_FEE_FACTOR:s,GAS_FEE:a}=pc,c=Math.log(n*o/i+Math.exp(r*o))/o-r,u=bo(wo(c).multipliedBy(s));return{amount:c.toString(),reverseBondingCurveFee:"0",transactionFee:u,gasFee:a}}static calculateSellWithExact(e,t,n,r,i){const o=Re(e),s=Re(t),a=Re(n),{BASE_PRICE:c,PRICE_SCALING_FACTOR:u,TRADING_FEE_FACTOR:l,GAS_FEE:h}=pc,d=c*(Math.exp(s*u)-Math.exp((s-o)*u))/u,f=wo(d),g=r+s/a*(i-r),p=bo(f.multipliedBy(g),8),m=bo(f.multipliedBy(l));return{amount:d.toString(),reverseBondingCurveFee:p,transactionFee:m,gasFee:h}}static calculateSellWithNative(e,t,n,r,i){const o=Re(e),s=Re(t),a=Re(n),{BASE_PRICE:c,PRICE_SCALING_FACTOR:u,TRADING_FEE_FACTOR:l,GAS_FEE:h}=pc;if(o>=c*(Math.exp(s*u)-1)/u){const e=wo(o),t=r+s/a*(i-r),n=bo(e.multipliedBy(t),8),c=bo(e.multipliedBy(l));return{amount:s.toString(),reverseBondingCurveFee:n,transactionFee:c,gasFee:h}}const d=s-Math.log(Math.exp(s*u)-o*u/c)/u,f=wo(o),g=r+s/a*(i-r),p=bo(f.multipliedBy(g),8),m=bo(f.multipliedBy(l));return{amount:d.toString(),reverseBondingCurveFee:p,transactionFee:m,gasFee:h}}static roundUp(e,t){const n=Math.pow(10,t);return Math.ceil(e*n)/n}}class Ah{constructor(e,t,n,r,i,o,s="local"){this.http=e,this.tokenResolver=t,this.logger=n,this.bundleHttp=r,this.galaChainHttp=i,this.dexApiHttp=o,this.defaultCalculateAmountMode=s,this.metadataCache=new yc}addIfDefined(e,t,n){return void 0!==n&&(e[t]=n),e}async uploadImageByTokenName(e){const{tokenName:t,options:n}=e;$o(t);const r=`${t}.png`;Ls(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 W("file","a File object (browser) or Buffer (Node.js)");{const r=`${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(n.tokenName||t)}`,data:e,headers:{}});if(!0===r.error||200!==r.status)throw H(r.message||"Image upload failed - no URL returned",r.status);const i=mr(r);if(!i?.imageUrl)throw H("Image upload failed - no URL returned",r.status);return i.imageUrl}catch(e){if(S(e)&&e.message.includes("FormData"))throw j("File upload failed: FormData not supported in this environment. Ensure you have proper polyfills for Node.js environments.","FormData");throw e}}async fetchPoolsFromAPI(e){Ze(e.page,e.limit),e.tokenName&&$o(e.tokenName);const t={page:e.page.toString(),limit:e.limit.toString()};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=vr(t),r=await this.http.get("/launchpad/fetch-pool",n);if(!0===r.error||200!==r.status)throw H(r.message||"Failed to fetch pools",r.status);const i=mr(r);if(!i)throw H("Failed to fetch pools - no data returned",r.status);let o=[];if(i.tokens)if(Array.isArray(i.tokens))o=i.tokens.map(e=>{const t=e.reverseBondingCurveMinFeePortion??"0",n=e.reverseBondingCurveMaxFeePortion??"0",r=!Co(t)||!Co(n);return{...e,reverseBondingCurveMinFeePortion:t,reverseBondingCurveMaxFeePortion:n,hasReverseBondingCurveFee:r,createdAt:e.created_at||e.createdAt||""}});else{const e=i.tokens,t=e.reverseBondingCurveMinFeePortion??"0",n=e.reverseBondingCurveMaxFeePortion??"0",r=!Co(t)||!Co(n);o=[{...e,reverseBondingCurveMinFeePortion:t,reverseBondingCurveMaxFeePortion:n,hasReverseBondingCurveFee:r,createdAt:e.created_at||e.createdAt||""}]}else i.pools&&Array.isArray(i.pools)&&(o=i.pools.map(e=>{const t=e.reverseBondingCurveMinFeePortion??"0",n=e.reverseBondingCurveMaxFeePortion??"0",r=!Co(t)||!Co(n);return{...e,reverseBondingCurveMinFeePortion:t,reverseBondingCurveMaxFeePortion:n,hasReverseBondingCurveFee:r,createdAt:e.created_at||e.createdAt||""}}));const{extractMetadataFromPoolData:s,isValidPoolForCaching:a}=await Promise.resolve().then(function(){return WE});o.forEach(e=>{if(!a(e))return void this.logger.debug("Skipping pool with invalid structure for caching",e);const t=s(e,this.logger);t&&this.warmCacheFromPoolData(e.tokenName,t)});const c=i.count??i.total??0,u=i.page??e.page??1,l=i.limit??e.limit??10;return{items:o,meta:{page:u,limit:l,total:c,totalPages:Xo(c,l)}}}async _getAmount(e){if(function(e){const t=po(e);!t.success&&t.errors&&Fo(t.errors,"options")}(e),!this.galaChainHttp)throw j("GalaChain client not configured. Direct GalaChain calls require galaChainHttp client.","galaChainHttp");const{endpoint:t,body:n}=((e,t,n,r)=>{if("NATIVE"===e&&"IN"===t)return{endpoint:gh,body:{vaultAddress:n,tokenQuantity:r,IsPreMint:!1}};if("NATIVE"===e&&"OUT"===t)return{endpoint:ph,body:{vaultAddress:n,tokenQuantity:r,IsPreMint:!1}};if("MEME"===e&&"IN"===t)return{endpoint:mh,body:{vaultAddress:n,nativeTokenQuantity:r,IsPreMint:!1}};if("MEME"===e&&"OUT"===t)return{endpoint:yh,body:{vaultAddress:n,nativeTokenQuantity:r,IsPreMint:!1}};throw W("type-method","one of: NATIVE-IN, NATIVE-OUT, MEME-IN, MEME-OUT")})(e.type,e.method,e.vaultAddress,e.amount);try{const e=await this.galaChainHttp.post(t,n);if(!bh(e))throw H("Malformed response data from GalaChain gateway");try{x(e,"GalaChain calculation")}catch(e){throw H(A(e),500)}const{calculatedQuantity:r,extraFees:i}=e.Data;return{amount:r,reverseBondingCurveFee:i.reverseBondingCurve,transactionFee:i.transactionFees,gasFee:"1"}}catch(r){throw this.logger.error(`GalaChain ${e.type}-${e.method} operation failed:`,{endpoint:t,requestBody:n,error:A(r)}),H(A(r),500)}}async checkPool(e){qo(e),e.tokenName&&$o(e.tokenName);const t=vr(e),n=await this.http.get("/launchpad/check-pool",t);if(!0===n.error||200!==n.status)throw H(n.message||"Failed to check pool",n.status);const r=n.data;return e.symbol?r?.isSymbolExist??!1:e.tokenName?r?.isNameExist??!1:r?.exists??!1}async fetchVolumeData(e){if(!ms(e))throw W("options","{ tokenName: string, from?: number, to?: number, resolution?: number }");const{tokenName:t,from:n,to:r,resolution:i}=e;if($o(t),!n||!r||!i)throw z("graphOptions","Graph options (from, to, resolution)");const o={tokenName:t,from:n,to:r,resolution:i};Ko(o);const s=vr(o),a=await this.http.get("/launchpad/get-graph-data",s);if(!0===a.error||200!==a.status)throw H(a.message||"Failed to fetch graph data",a.status);const c=mr(a);if(!c)throw H("Failed to fetch graph data - no data returned",a.status);return{dataPoints:c}}async fetchPools(e={}){let t;"recent"===e.type?t="RECENT":"popular"===e.type&&(t="POPULAR");const n={page:e.page||1,limit:e.limit||10};return e.search&&(n.search=e.search),e.tokenName&&(n.tokenName=e.tokenName),t&&(n.type=t),void 0!==e.hasUpcomingShows&&(n.hasUpcomingShows=e.hasUpcomingShows),e.language&&(n.language=e.language),void 0!==e.recentlyStreamed&&(n.recentlyStreamed=e.recentlyStreamed),this.fetchPoolsFromAPI(n)}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 calculateBuyAmount(e){if(!e||"object"!=typeof e)throw W("options","an options object");const{tokenName:t,amount:n,type:r,currentSupply:i}=e,o=e.mode??this.defaultCalculateAmountMode;if("local"!==o&&"external"!==o)throw Z("mode",'"local" or "external"',o);if(!Qe(t))throw z("tokenName","Token name");if(!Qe(n))throw z("amount","Amount");if(r!==kh.NATIVE&&r!==kh.EXACT)throw Z("type",'"native" or "exact"',r);return"external"===o?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,i=await this.tokenResolver.resolveTokenToVault(t);if(!i)throw z("tokenName",`Token "${t}" not found. Please verify the token name is correct.`);return r===kh.EXACT?this._getAmount({type:"NATIVE",method:"IN",vaultAddress:i,amount:n}):this._getAmount({type:"MEME",method:"OUT",vaultAddress:i,amount:n})}async calculateSellAmount(e){const{tokenName:t,amount:n,type:r,currentSupply:i,maxSupply:o,reverseBondingCurveMaxFeeFactor:s,reverseBondingCurveMinFeeFactor:a}=e,c=e.mode??this.defaultCalculateAmountMode;if("local"!==c&&"external"!==c)throw Z("mode",'"local" or "external"',c);if(!Qe(t))throw z("tokenName","Token name");if(!Qe(n))throw z("amount","Amount");if(r!==kh.EXACT&&r!==kh.NATIVE)throw Z("type",'"exact" or "native"',r);if("external"===c)return this.calculateSellAmountExternal({tokenName:t,amount:n,type:r});{const e={tokenName:t,amount:n,type:r,...void 0!==i&&{currentSupply:i},...void 0!==o&&{maxSupply:o},...void 0!==s&&{reverseBondingCurveMaxFeeFactor:s},...void 0!==a&&{reverseBondingCurveMinFeeFactor:a}};return this.calculateSellAmountLocal(e)}}async calculateSellAmountExternal(e){const{tokenName:t,amount:n,type:r}=e,i=await this.tokenResolver.resolveTokenToVault(t);if(!i)throw z("tokenName",`Token "${t}" not found. Please verify the token name is correct.`);return r===kh.EXACT?this._getAmount({type:"NATIVE",method:"OUT",vaultAddress:i,amount:n}):this._getAmount({type:"MEME",method:"IN",vaultAddress:i,amount:n})}async calculateBuyAmountLocal(e){const{tokenName:t,amount:n,type:r,currentSupply:i}=e;if(!Qe(n))throw z("amount","Amount");if(r!==kh.NATIVE&&r!==kh.EXACT)throw Z("type",'"native" or "exact"',r);void 0!==i&&Go(i,"currentSupply");const o=!i;if(o&&!t)throw z("tokenName","Token name (required when currentSupply is not provided)");t&&$o(t);let s=i;if(o){s=(await this.fetchPoolDetailsForCalculation(t)).currentSupply}return r===kh.EXACT?Sh.calculateBuyWithExact(n,s):Sh.calculateBuyWithNative(n,s)}async calculateSellAmountLocal(e){const{tokenName:t,amount:n,type:r,currentSupply:i,maxSupply:o,reverseBondingCurveMaxFeeFactor:s,reverseBondingCurveMinFeeFactor:a}=e;if(!Qe(n))throw z("amount","Amount");if(r!==kh.EXACT&&r!==kh.NATIVE)throw Z("type",'"exact" or "native"',r);void 0!==i&&Go(i,"currentSupply");const c=!i||!o||void 0===s||void 0===a;if(c&&!t)throw z("tokenName","Token name (required when currentSupply, maxSupply, or fee factors are not provided)");t&&$o(t);let u=i,l=o,h=s,d=a;if(c&&t){const e=this.metadataCache.getByName(t);l=l??this.metadataCache.getMaxSupply(t),h=h??e?.reverseBondingCurveMaxFeeFactor,d=d??e?.reverseBondingCurveMinFeeFactor,u||(u=await this.fetchCurrentSupply(t));if(void 0===h||void 0===d){const e=await this.fetchPoolDetailsForCalculation(t);h=h??e.reverseBondingCurveMaxFeeFactor,d=d??e.reverseBondingCurveMinFeeFactor}}return r===kh.EXACT?Sh.calculateSellWithExact(n,u,l,d,h):Sh.calculateSellWithNative(n,u,l,d,h)}async calculateBuyAmountForGraduation(e){const t="string"==typeof e?{tokenName:e}:e;if("object"==typeof e&&!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return fs(t,"tokenName")&&function(e){return void 0===e.calculateAmountMode||"local"===e.calculateAmountMode||"external"===e.calculateAmountMode}(t)&&gs(t,"currentSupply")}(e))throw Z("options","CalculateBuyAmountForGraduationOptions or string (token name)",typeof e);const{tokenName:n,calculateAmountMode:r,currentSupply:i}=t;$o(n);const o=await this.tokenResolver.resolveTokenToVault(n);if(!o)throw new _(Tr(n),"tokenName","VAULT_NOT_FOUND");if(!this.galaChainHttp)throw j("GalaChain HTTP client not configured");const s=await this.galaChainHttp.post("/api/asset/launchpad-contract/FetchSaleDetails",{vaultAddress:o});if(1!==s.Status)throw H(`Failed to fetch pool details: Status ${s.Status}`,s.Status);const a=s.Data,c=i??bo(wo(a.maxSupply).minus(a.sellingTokenQuantity)),u=a.sellingTokenQuantity;if("0"===u)throw z("tokenName",`Token ${n} is already graduated (no tokens remaining in pool)`);const l={tokenName:n,amount:u,type:"exact",currentSupply:c,...void 0!==r&&{mode:r}};return{...await this.calculateBuyAmount(l),remainingTokens:u}}async launchToken(e){if(!this.bundleHttp)throw j("Bundle backend client not configured. LaunchToken requires bundleHttp client.","bundleHttp");fh(e);const t=e.preBuyQuantity||"0",r=Re(t);if(0===r&&"0"!==t)throw ee("preBuyQuantity",t,"Pre-buy quantity");if(r<0)throw ee("preBuyQuantity",t,"Pre-buy quantity");if(e.reverseBondingCurveConfiguration){const{minFeePortion:t,maxFeePortion:n}=e.reverseBondingCurveConfiguration;he(t,n,"reverseBondingCurve")}let i="";if(e.tokenImage)if(e.tokenImage instanceof File||Buffer.isBuffer(e.tokenImage)){const t=await this.uploadImageByTokenName({tokenName:e.tokenName,options:{file:e.tokenImage,tokenName:e.tokenName}});if(!t)throw H("Image upload failed: No URL returned");i=t}else"string"==typeof e.tokenImage&&(i=e.tokenImage);const s=`galaswap - operation - ${o.v4()}-${Date.now()}-${this.http.getAddress()}`,a={tokenName:e.tokenName.trim(),tokenSymbol:os(e.tokenSymbol),tokenDescription:e.tokenDescription.trim(),tokenImage:i.trim(),preBuyQuantity:t.toString(),tokenCategory:e.tokenCategory||"Unit",tokenCollection:e.tokenCollection||"Token",uniqueKey:s},c=Es(e.websiteUrl);null!==c&&(a.websiteUrl=c);const u=Es(e.telegramUrl);null!==u&&(a.telegramUrl=u);const l=Es(e.twitterUrl);null!==l&&(a.twitterUrl=l);const h=Es(e.instagramUrl);null!==h&&(a.instagramUrl=h);const d=Es(e.facebookUrl);null!==d&&(a.facebookUrl=d);const f=Es(e.redditUrl);null!==f&&(a.redditUrl=f);const g=Es(e.tiktokUrl);null!==g&&(a.tiktokUrl=g),a.reverseBondingCurveConfiguration={minFeePortion:e.reverseBondingCurveConfiguration?.minFeePortion?.toString()||"0.1",maxFeePortion:e.reverseBondingCurveConfiguration?.maxFeePortion?.toString()||"0.5"};const p=new wh(a),m=await this.http.signWithGalaChain("CreateSale",p,n.SigningType.SIGN_TYPED_DATA),{signature:y,types:w,domain:b,prefix:k}=m,v={tokenName:p.tokenName,tokenSymbol:p.tokenSymbol,tokenDescription:p.tokenDescription,tokenImage:p.tokenImage,preBuyQuantity:p.preBuyQuantity,...p.websiteUrl&&{websiteUrl:p.websiteUrl},...p.telegramUrl&&{telegramUrl:p.telegramUrl},...p.twitterUrl&&{twitterUrl:p.twitterUrl},...p.instagramUrl&&{instagramUrl:p.instagramUrl},...p.facebookUrl&&{facebookUrl:p.facebookUrl},...p.redditUrl&&{redditUrl:p.redditUrl},...p.tiktokUrl&&{tiktokUrl:p.tiktokUrl},tokenCategory:p.tokenCategory,tokenCollection:p.tokenCollection,uniqueKey:p.uniqueKey,signature:y,types:w,domain:b,...k&&{prefix:k},...p.reverseBondingCurveConfiguration&&{reverseBondingCurveConfiguration:p.reverseBondingCurveConfiguration}},S=`${e.tokenName.trim()}$Unit$none$none`,A="GALA$Unit$none$none";let T;if(Re(t,0)>0){const e=`$service$${S}$launchpad`;T=[e,`$token$${S}$${e}`,`$tokenBalance$${S}$${e}`,`$tokenBalance$${S}$${e}`,`$tokenBalance$${A}$${e}`,`$tokenBalance$${A}$${e}`]}else{const e=`$service$${S}$launchpad`;T=[e,`$token$${S}$${e}`,`$tokenBalance$${S}$${e}`]}const E={signedDto:v,stringsInstructions:T,method:"CreateSale"},I=await this.bundleHttp.post("/bundle",E);if(I.error)throw H(I.message||"Token launch failed");const x=mr(I);if(!x)throw H("Token launch failed - no transaction ID returned");return x}async fetchTokenDistribution(e){if(!e)throw z("tokenName","Token name");$o(e);const t=await this.http.get(`/holders/${e}`);if(!0===t.error||200!==t.status)throw H(t.message||"Failed to fetch token distribution",t.status);const n=mr(t);if(!n)throw H("Failed to fetch token distribution - no data returned",t.status);if(!Array.isArray(n))throw H("Invalid API response: expected array of holders",t.status);for(const e of n){if(!e.owner||"string"!=typeof e.owner)throw H("Invalid holder data: missing or invalid owner field",t.status);if(!e.quantity||"string"!=typeof e.quantity)throw H("Invalid holder data: missing or invalid quantity field",t.status);const n=Re(e.quantity,NaN);if(isNaN(n)||!isFinite(n))throw H(`Invalid holder quantity: "${e.quantity}"`,t.status)}const r=n.reduce((e,t)=>e.plus(t.quantity),wo(0));return{holders:n.map(e=>{const t=Oo(wo(e.quantity),r,wo(0)).multipliedBy(100).toNumber();return{address:e.owner,balance:e.quantity,percentage:t}}),totalSupply:bo(r),totalHolders:n.length,lastUpdated:new Date}}async fetchTokenBadges(e){if(!e)throw z("tokenName","Token name");$o(e);const t=await this.http.get("/launchpad/get-badge/",{tokenName:e});if(t.error)throw H(t.message||"Failed to fetch token badges");const n=mr(t);if(!n)throw H("Failed to fetch token badges - no data returned");return{volumeBadges:n.volumeBadge||[],engagementBadges:n.engagementBadge||[]}}async hasTokenBadgeByTokenName(e){const{tokenName:t,badgeType:n,badgeName:r}=e;try{const e=await this.fetchTokenBadges(t);if(!e)return!1;const i=("volume"===n?e.volumeBadges:e.engagementBadges).find(e=>e.badgeName===r);return i?.isActive||!1}catch{return!1}}async calculateInitialBuyAmount(e){if(!qs(e))throw W("data","valid pre-mint calculation data");if(!this.galaChainHttp)throw j("GalaChain HTTP client not available. Please initialize SDK with galaChainBaseUrl.","galaChainHttp");try{const t={vaultAddress:"service|testToken",nativeTokenQuantity:e.nativeTokenQuantity,IsPreMint:!0},n=await this.galaChainHttp.post("/api/asset/launchpad-contract/CallMemeTokenOut",t);if(!bh(n))throw H("Malformed response data from GalaChain gateway");try{x(n,"Pre-mint calculation")}catch(e){throw H(A(e),500)}const{calculatedQuantity:r,extraFees:i}=n.Data;return{amount:r,reverseBondingCurveFee:i.reverseBondingCurve,transactionFee:i.transactionFees,gasFee:"1"}}catch(e){if(S(e)&&e instanceof P)throw e;throw H(A(e),500)}}async fetchPoolDetailsForCalculation(e){const t=await this.tokenResolver.resolveTokenToVault(e);if(!t)throw new _(Tr(e),"tokenName","VAULT_NOT_FOUND");if(!this.galaChainHttp)throw j("GalaChain HTTP client not configured");const n=await this.galaChainHttp.post("/api/asset/launchpad-contract/FetchSaleDetails",{vaultAddress:t});if(1!==n.Status)throw H(`Failed to fetch pool details: Status ${n.Status}`,n.Status);const r=n.Data,i=bo(wo(r.maxSupply).minus(r.sellingTokenQuantity)),o=r.sellingTokenQuantity,s=r.maxSupply;let a=.5,c=0;r.reverseBondingCurveConfiguration?(a=Fe(r.reverseBondingCurveConfiguration.maxFeePortion,.5),c=Fe(r.reverseBondingCurveConfiguration.minFeePortion,0)):this.logger.debug(`Pool details missing reverseBondingCurveConfiguration for token ${e}, using defaults (min: 0.0, max: 0.5)`);const u=a-c;return this.metadataCache.set(e,{maxSupply:s,reverseBondingCurveMaxFeeFactor:a,reverseBondingCurveMinFeeFactor:c,reverseBondingCurveNetFeeFactor:u}),{currentSupply:i,remainingTokens:o,maxSupply:s,reverseBondingCurveMaxFeeFactor:a,reverseBondingCurveMinFeeFactor:c,reverseBondingCurveNetFeeFactor:u}}async fetchCurrentSupply(e){$o(e);const t=await this.tokenResolver.resolveTokenToVault(e);if(!t)throw new _(Tr(e),"tokenName","VAULT_NOT_FOUND");if(!this.galaChainHttp)throw j("GalaChain HTTP client not configured");const n=await this.galaChainHttp.post("/api/asset/launchpad-contract/FetchSaleDetails",{vaultAddress:t});if(1!==n.Status)throw H(`Failed to fetch pool details: Status ${n.Status}`,n.Status);const r=n.Data,i=bo(wo(r.maxSupply).minus(r.sellingTokenQuantity)),o=r.maxSupply;return this.metadataCache.set(e,{maxSupply:o}),i}getAddress(){return this.http.getAddress()}formatAddressForBackend(e){return ft(e)}validateTokenName(e){return $o(e)}validatePagination(e){return Ze(e.page,e.limit)}async fetchTokenPrice(e){if(!this.dexApiHttp)throw j("DEX API client not configured. Token price fetching requires dexApiHttp client.","dexApiHttp");if(!e||Array.isArray(e)&&0===e.length)throw z("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 e.tokens&&Array.isArray(e.tokens)&&e.tokens.forEach(e=>{e.currentPrices&&e.symbol&&n.push({symbol:e.symbol,price:e.currentPrices.usd})}),n}catch(e){throw H(`Failed to fetch token prices: ${A(e)}`,void 0,S(e)?e:void 0)}}warmCacheFromPoolData(e,t){this.metadataCache.warmFromPoolData(e,t)}getCacheStats(){return this.metadataCache.getStats()}clearCache(e){this.metadataCache.clear(e)}}class Th{constructor(e){if(this.lastTimestamp=0,this.pendingPromise=Promise.resolve(),this.chainLength=0,this.maxChainLength=1e3,e<=0)throw J("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(S(e)?e:new Error(A(e)))}}),this.chainLength++,this.chainLength>=this.maxChainLength){this.chainLength=0;const e=this.pendingPromise;this.pendingPromise=e.then(()=>Promise.resolve())}return r}}function Eh(e,t){let n;try{n=Me(e,"amount")}catch(t){throw ee("amount",`${e} (${A(t)})`)}if(!n.isFinite())throw ee("amount",e);const r=n.multipliedBy(wo(10).pow(t));if(!r.isInteger())throw ee("amount",`${e} (cannot be represented with ${t} decimals)`);return BigInt(r.toFixed(0))}function Ih(e,t){return wo(e.toString()).dividedBy(wo(10).pow(t)).toFixed(t).replace(/\.?0+$/,"")}const xh={maxRetries:3,initialDelayMs:1e3,maxDelayMs:3e4,backoffMultiplier:2,jitterFactor:.1},Ch=new Set([408,429,500,502,503,504]),Nh=[/ECONNRESET/i,/ECONNREFUSED/i,/ETIMEDOUT/i,/ENOTFOUND/i,/EAI_AGAIN/i,/socket hang up/i,/network/i,/timeout/i,/aborted/i];function Bh(e){if(e&&"object"==typeof e){const t=e;if("number"==typeof t.status)return Ch.has(t.status);if("number"==typeof t.statusCode)return Ch.has(t.statusCode);const n=E(e);if("string"==typeof n&&("ECONNRESET"===n||"ECONNREFUSED"===n||"ETIMEDOUT"===n||"ENOTFOUND"===n||"EAI_AGAIN"===n))return!0}const t=A(e);return Nh.some(e=>e.test(t))}function _h(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 Ph(e){return new Promise(t=>setTimeout(t,e))}function Rh(e){let t;if("string"==typeof e)t=js(e);else{if(!Qs(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:Ks(t)}}function Dh(e){const t={};for(const[n,r]of Object.entries(e))void 0!==r&&(r&&"object"==typeof r&&!Array.isArray(r)?t[n]=Dh(r):t[n]=r);return t}function Lh(e,t){const n=Re(e,-1);if(n<=0)throw new Error(`Invalid bridge amount for ${t}: "${e}". Amount must be a positive number.`);return n}function Oh(e){const t="string"==typeof e.timestamp?Oe(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}}var Uh,Mh={},Fh={};function $h(){if(Uh)return Fh;Uh=1,Fh.byteLength=function(e){var t=o(e),n=t[0],r=t[1];return 3*(n+r)/4-r},Fh.toByteArray=function(e){var r,i,s=o(e),a=s[0],c=s[1],u=new n(function(e,t,n){return 3*(t+n)/4-n}(0,a,c)),l=0,h=c>0?a-4:a;for(i=0;i<h;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)],u[l++]=r>>16&255,u[l++]=r>>8&255,u[l++]=255&r;2===c&&(r=t[e.charCodeAt(i)]<<2|t[e.charCodeAt(i+1)]>>4,u[l++]=255&r);1===c&&(r=t[e.charCodeAt(i)]<<10|t[e.charCodeAt(i+1)]<<4|t[e.charCodeAt(i+2)]>>2,u[l++]=r>>8&255,u[l++]=255&r);return u},Fh.fromByteArray=function(t){for(var n,r=t.length,i=r%3,o=[],s=16383,c=0,u=r-i;c<u;c+=s)o.push(a(t,c,c+s>u?u:c+s));1===i?(n=t[r-1],o.push(e[n>>2]+e[n<<4&63]+"==")):2===i&&(n=(t[r-2]<<8)+t[r-1],o.push(e[n>>10]+e[n>>4&63]+e[n<<2&63]+"="));return o.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 o(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 s(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=[],o=t;o<n;o+=3)r=(e[o]<<16&16711680)+(e[o+1]<<8&65280)+(255&e[o+2]),i.push(s(r));return i.join("")}return t["-".charCodeAt(0)]=62,t["_".charCodeAt(0)]=63,Fh}var qh,Kh,Gh={};function zh(){return qh||(qh=1,Gh.read=function(e,t,n,r,i){var o,s,a=8*i-r-1,c=(1<<a)-1,u=c>>1,l=-7,h=n?i-1:0,d=n?-1:1,f=e[t+h];for(h+=d,o=f&(1<<-l)-1,f>>=-l,l+=a;l>0;o=256*o+e[t+h],h+=d,l-=8);for(s=o&(1<<-l)-1,o>>=-l,l+=r;l>0;s=256*s+e[t+h],h+=d,l-=8);if(0===o)o=1-u;else{if(o===c)return s?NaN:1/0*(f?-1:1);s+=Math.pow(2,r),o-=u}return(f?-1:1)*s*Math.pow(2,o-r)},Gh.write=function(e,t,n,r,i,o){var s,a,c,u=8*o-i-1,l=(1<<u)-1,h=l>>1,d=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,f=r?0:o-1,g=r?1:-1,p=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,s=l):(s=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-s))<1&&(s--,c*=2),(t+=s+h>=1?d/c:d*Math.pow(2,1-h))*c>=2&&(s++,c/=2),s+h>=l?(a=0,s=l):s+h>=1?(a=(t*c-1)*Math.pow(2,i),s+=h):(a=t*Math.pow(2,h-1)*Math.pow(2,i),s=0));i>=8;e[n+f]=255&a,f+=g,a/=256,i-=8);for(s=s<<i|a,u+=i;u>0;e[n+f]=255&s,f+=g,s/=256,u-=8);e[n+f-g]|=128*p}),Gh}var Wh=(Kh||(Kh=1,function(e){const t=$h(),n=zh(),r="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;e.Buffer=s,e.SlowBuffer=function(e){return+e!=e&&(e=0),s.alloc(+e)},e.INSPECT_MAX_BYTES=50;const i=2147483647;function o(e){if(e>i)throw new RangeError('The value "'+e+'" is invalid for option "size"');const t=new Uint8Array(e);return Object.setPrototypeOf(t,s.prototype),t}function s(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 u(e)}return a(e,t,n)}function a(e,t,n){if("string"==typeof e)return function(e,t){if("string"==typeof t&&""!==t||(t="utf8"),!s.isEncoding(t))throw new TypeError("Unknown encoding: "+t);const n=0|f(e,t);let r=o(n);const i=r.write(e,t);return i!==n&&(r=r.slice(0,i)),r}(e,t);if(ArrayBuffer.isView(e))return function(e){if(j(e,Uint8Array)){const t=new Uint8Array(e);return h(t.buffer,t.byteOffset,t.byteLength)}return l(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(j(e,ArrayBuffer)||e&&j(e.buffer,ArrayBuffer))return h(e,t,n);if("undefined"!=typeof SharedArrayBuffer&&(j(e,SharedArrayBuffer)||e&&j(e.buffer,SharedArrayBuffer)))return h(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 s.from(r,t,n);const i=function(e){if(s.isBuffer(e)){const t=0|d(e.length),n=o(t);return 0===n.length||e.copy(n,0,0,t),n}return void 0!==e.length?"number"!=typeof e.length||V(e.length)?o(0):l(e):"Buffer"===e.type&&Array.isArray(e.data)?l(e.data):void 0}(e);if(i)return i;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return s.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 u(e){return c(e),o(e<0?0:0|d(e))}function l(e){const t=e.length<0?0:0|d(e.length),n=o(t);for(let r=0;r<t;r+=1)n[r]=255&e[r];return n}function h(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,s.prototype),r}function d(e){if(e>=i)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i.toString(16)+" bytes");return 0|e}function f(e,t){if(s.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||j(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 z(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return W(e).length;default:if(i)return r?-1:z(e).length;t=(""+t).toLowerCase(),i=!0}}function g(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 T(this,t,n);case"ascii":return I(this,t,n);case"latin1":case"binary":return x(this,t,n);case"base64":return A(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return N(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function p(e,t,n){const r=e[t];e[t]=e[n],e[n]=r}function m(e,t,n,r,i){if(0===e.length)return-1;if("string"==typeof n?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),V(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=s.from(t,r)),s.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 o,s=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;s=2,a/=2,c/=2,n/=2}function u(e,t){return 1===s?e[t]:e.readUInt16BE(t*s)}if(i){let r=-1;for(o=n;o<a;o++)if(u(e,o)===u(t,-1===r?0:o-r)){if(-1===r&&(r=o),o-r+1===c)return r*s}else-1!==r&&(o-=o-r),r=-1}else for(n+c>a&&(n=a-c),o=n;o>=0;o--){let n=!0;for(let r=0;r<c;r++)if(u(e,o+r)!==u(t,r)){n=!1;break}if(n)return o}return-1}function w(e,t,n,r){n=Number(n)||0;const i=e.length-n;r?(r=Number(r))>i&&(r=i):r=i;const o=t.length;let s;for(r>o/2&&(r=o/2),s=0;s<r;++s){const r=parseInt(t.substr(2*s,2),16);if(V(r))return s;e[n+s]=r}return s}function b(e,t,n,r){return H(z(t,e.length-n),e,n,r)}function k(e,t,n,r){return H(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 v(e,t,n,r){return H(W(t),e,n,r)}function S(e,t,n,r){return H(function(e,t){let n,r,i;const o=[];for(let s=0;s<e.length&&!((t-=2)<0);++s)n=e.charCodeAt(s),r=n>>8,i=n%256,o.push(i),o.push(r);return o}(t,e.length-n),e,n,r)}function A(e,n,r){return 0===n&&r===e.length?t.fromByteArray(e):t.fromByteArray(e.slice(n,r))}function T(e,t,n){n=Math.min(e.length,n);const r=[];let i=t;for(;i<n;){const t=e[i];let o=null,s=t>239?4:t>223?3:t>191?2:1;if(i+s<=n){let n,r,a,c;switch(s){case 1:t<128&&(o=t);break;case 2:n=e[i+1],128==(192&n)&&(c=(31&t)<<6|63&n,c>127&&(o=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)&&(o=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&&(o=c))}}null===o?(o=65533,s=1):o>65535&&(o-=65536,r.push(o>>>10&1023|55296),o=56320|1023&o),r.push(o),i+=s}return function(e){const t=e.length;if(t<=E)return String.fromCharCode.apply(String,e);let n="",r=0;for(;r<t;)n+=String.fromCharCode.apply(String,e.slice(r,r+=E));return n}(r)}e.kMaxLength=i,s.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}}(),!s.TYPED_ARRAY_SUPPORT&&"undefined"!=typeof console&&console.error,Object.defineProperty(s.prototype,"parent",{enumerable:!0,get:function(){if(s.isBuffer(this))return this.buffer}}),Object.defineProperty(s.prototype,"offset",{enumerable:!0,get:function(){if(s.isBuffer(this))return this.byteOffset}}),s.poolSize=8192,s.from=function(e,t,n){return a(e,t,n)},Object.setPrototypeOf(s.prototype,Uint8Array.prototype),Object.setPrototypeOf(s,Uint8Array),s.alloc=function(e,t,n){return function(e,t,n){return c(e),e<=0?o(e):void 0!==t?"string"==typeof n?o(e).fill(t,n):o(e).fill(t):o(e)}(e,t,n)},s.allocUnsafe=function(e){return u(e)},s.allocUnsafeSlow=function(e){return u(e)},s.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==s.prototype},s.compare=function(e,t){if(j(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),j(t,Uint8Array)&&(t=s.from(t,t.offset,t.byteLength)),!s.isBuffer(e)||!s.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,o=Math.min(n,r);i<o;++i)if(e[i]!==t[i]){n=e[i],r=t[i];break}return n<r?-1:r<n?1:0},s.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}},s.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return s.alloc(0);let n;if(void 0===t)for(t=0,n=0;n<e.length;++n)t+=e[n].length;const r=s.allocUnsafe(t);let i=0;for(n=0;n<e.length;++n){let t=e[n];if(j(t,Uint8Array))i+t.length>r.length?(s.isBuffer(t)||(t=s.from(t)),t.copy(r,i)):Uint8Array.prototype.set.call(r,t,i);else{if(!s.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(r,i)}i+=t.length}return r},s.byteLength=f,s.prototype._isBuffer=!0,s.prototype.swap16=function(){const e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let t=0;t<e;t+=2)p(this,t,t+1);return this},s.prototype.swap32=function(){const e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let t=0;t<e;t+=4)p(this,t,t+3),p(this,t+1,t+2);return this},s.prototype.swap64=function(){const e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let t=0;t<e;t+=8)p(this,t,t+7),p(this,t+1,t+6),p(this,t+2,t+5),p(this,t+3,t+4);return this},s.prototype.toString=function(){const e=this.length;return 0===e?"":0===arguments.length?T(this,0,e):g.apply(this,arguments)},s.prototype.toLocaleString=s.prototype.toString,s.prototype.equals=function(e){if(!s.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===s.compare(this,e)},s.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&&(s.prototype[r]=s.prototype.inspect),s.prototype.compare=function(e,t,n,r,i){if(j(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),!s.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 o=(i>>>=0)-(r>>>=0),a=(n>>>=0)-(t>>>=0);const c=Math.min(o,a),u=this.slice(r,i),l=e.slice(t,n);for(let e=0;e<c;++e)if(u[e]!==l[e]){o=u[e],a=l[e];break}return o<a?-1:a<o?1:0},s.prototype.includes=function(e,t,n){return-1!==this.indexOf(e,t,n)},s.prototype.indexOf=function(e,t,n){return m(this,e,t,n,!0)},s.prototype.lastIndexOf=function(e,t,n){return m(this,e,t,n,!1)},s.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 o=!1;for(;;)switch(r){case"hex":return w(this,e,t,n);case"utf8":case"utf-8":return b(this,e,t,n);case"ascii":case"latin1":case"binary":return k(this,e,t,n);case"base64":return v(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return S(this,e,t,n);default:if(o)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),o=!0}},s.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const E=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 x(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 N(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 B(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 _(e,t,n,r,i,o){if(!s.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||t<o)throw new RangeError('"value" argument is out of bounds');if(n+r>e.length)throw new RangeError("Index out of range")}function P(e,t,n,r,i){$(t,r,i,e,n,7);let o=Number(t&BigInt(4294967295));e[n++]=o,o>>=8,e[n++]=o,o>>=8,e[n++]=o,o>>=8,e[n++]=o;let s=Number(t>>BigInt(32)&BigInt(4294967295));return e[n++]=s,s>>=8,e[n++]=s,s>>=8,e[n++]=s,s>>=8,e[n++]=s,n}function R(e,t,n,r,i){$(t,r,i,e,n,7);let o=Number(t&BigInt(4294967295));e[n+7]=o,o>>=8,e[n+6]=o,o>>=8,e[n+5]=o,o>>=8,e[n+4]=o;let s=Number(t>>BigInt(32)&BigInt(4294967295));return e[n+3]=s,s>>=8,e[n+2]=s,s>>=8,e[n+1]=s,s>>=8,e[n]=s,n+8}function D(e,t,n,r,i,o){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function L(e,t,r,i,o){return t=+t,r>>>=0,o||D(e,0,r,4),n.write(e,t,r,i,23,4),r+4}function O(e,t,r,i,o){return t=+t,r>>>=0,o||D(e,0,r,8),n.write(e,t,r,i,52,8),r+8}s.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,s.prototype),r},s.prototype.readUintLE=s.prototype.readUIntLE=function(e,t,n){e>>>=0,t>>>=0,n||B(e,t,this.length);let r=this[e],i=1,o=0;for(;++o<t&&(i*=256);)r+=this[e+o]*i;return r},s.prototype.readUintBE=s.prototype.readUIntBE=function(e,t,n){e>>>=0,t>>>=0,n||B(e,t,this.length);let r=this[e+--t],i=1;for(;t>0&&(i*=256);)r+=this[e+--t]*i;return r},s.prototype.readUint8=s.prototype.readUInt8=function(e,t){return e>>>=0,t||B(e,1,this.length),this[e]},s.prototype.readUint16LE=s.prototype.readUInt16LE=function(e,t){return e>>>=0,t||B(e,2,this.length),this[e]|this[e+1]<<8},s.prototype.readUint16BE=s.prototype.readUInt16BE=function(e,t){return e>>>=0,t||B(e,2,this.length),this[e]<<8|this[e+1]},s.prototype.readUint32LE=s.prototype.readUInt32LE=function(e,t){return e>>>=0,t||B(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},s.prototype.readUint32BE=s.prototype.readUInt32BE=function(e,t){return e>>>=0,t||B(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},s.prototype.readBigUInt64LE=Q(function(e){q(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||K(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))}),s.prototype.readBigUInt64BE=Q(function(e){q(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||K(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)}),s.prototype.readIntLE=function(e,t,n){e>>>=0,t>>>=0,n||B(e,t,this.length);let r=this[e],i=1,o=0;for(;++o<t&&(i*=256);)r+=this[e+o]*i;return i*=128,r>=i&&(r-=Math.pow(2,8*t)),r},s.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||B(e,t,this.length);let r=t,i=1,o=this[e+--r];for(;r>0&&(i*=256);)o+=this[e+--r]*i;return i*=128,o>=i&&(o-=Math.pow(2,8*t)),o},s.prototype.readInt8=function(e,t){return e>>>=0,t||B(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},s.prototype.readInt16LE=function(e,t){e>>>=0,t||B(e,2,this.length);const n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},s.prototype.readInt16BE=function(e,t){e>>>=0,t||B(e,2,this.length);const n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},s.prototype.readInt32LE=function(e,t){return e>>>=0,t||B(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},s.prototype.readInt32BE=function(e,t){return e>>>=0,t||B(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},s.prototype.readBigInt64LE=Q(function(e){q(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||K(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)}),s.prototype.readBigInt64BE=Q(function(e){q(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||K(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)}),s.prototype.readFloatLE=function(e,t){return e>>>=0,t||B(e,4,this.length),n.read(this,e,!0,23,4)},s.prototype.readFloatBE=function(e,t){return e>>>=0,t||B(e,4,this.length),n.read(this,e,!1,23,4)},s.prototype.readDoubleLE=function(e,t){return e>>>=0,t||B(e,8,this.length),n.read(this,e,!0,52,8)},s.prototype.readDoubleBE=function(e,t){return e>>>=0,t||B(e,8,this.length),n.read(this,e,!1,52,8)},s.prototype.writeUintLE=s.prototype.writeUIntLE=function(e,t,n,r){e=+e,t>>>=0,n>>>=0,r||_(this,e,t,n,Math.pow(2,8*n)-1,0);let i=1,o=0;for(this[t]=255&e;++o<n&&(i*=256);)this[t+o]=e/i&255;return t+n},s.prototype.writeUintBE=s.prototype.writeUIntBE=function(e,t,n,r){e=+e,t>>>=0,n>>>=0,r||_(this,e,t,n,Math.pow(2,8*n)-1,0);let i=n-1,o=1;for(this[t+i]=255&e;--i>=0&&(o*=256);)this[t+i]=e/o&255;return t+n},s.prototype.writeUint8=s.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||_(this,e,t,1,255,0),this[t]=255&e,t+1},s.prototype.writeUint16LE=s.prototype.writeUInt16LE=function(e,t,n){return e=+e,t>>>=0,n||_(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},s.prototype.writeUint16BE=s.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||_(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},s.prototype.writeUint32LE=s.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||_(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},s.prototype.writeUint32BE=s.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||_(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},s.prototype.writeBigUInt64LE=Q(function(e,t=0){return P(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),s.prototype.writeBigUInt64BE=Q(function(e,t=0){return R(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),s.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t>>>=0,!r){const r=Math.pow(2,8*n-1);_(this,e,t,n,r-1,-r)}let i=0,o=1,s=0;for(this[t]=255&e;++i<n&&(o*=256);)e<0&&0===s&&0!==this[t+i-1]&&(s=1),this[t+i]=(e/o|0)-s&255;return t+n},s.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t>>>=0,!r){const r=Math.pow(2,8*n-1);_(this,e,t,n,r-1,-r)}let i=n-1,o=1,s=0;for(this[t+i]=255&e;--i>=0&&(o*=256);)e<0&&0===s&&0!==this[t+i+1]&&(s=1),this[t+i]=(e/o|0)-s&255;return t+n},s.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||_(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},s.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||_(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},s.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||_(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},s.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||_(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},s.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||_(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},s.prototype.writeBigInt64LE=Q(function(e,t=0){return P(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),s.prototype.writeBigInt64BE=Q(function(e,t=0){return R(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),s.prototype.writeFloatLE=function(e,t,n){return L(this,e,t,!0,n)},s.prototype.writeFloatBE=function(e,t,n){return L(this,e,t,!1,n)},s.prototype.writeDoubleLE=function(e,t,n){return O(this,e,t,!0,n)},s.prototype.writeDoubleBE=function(e,t,n){return O(this,e,t,!1,n)},s.prototype.copy=function(e,t,n,r){if(!s.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},s.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&&!s.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 o=s.isBuffer(e)?e:s.from(e,r),a=o.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]=o[i%a]}return this};const U={};function M(e,t,n){U[e]=class extends n{constructor(){super(),Object.defineProperty(this,"message",{value:t.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${e}]`,this.stack,delete this.name}get code(){return e}set code(e){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:e,writable:!0})}toString(){return`${this.name} [${e}]: ${this.message}`}}}function F(e){let t="",n=e.length;const r="-"===e[0]?1:0;for(;n>=r+4;n-=3)t=`_${e.slice(n-3,n)}${t}`;return`${e.slice(0,n)}${t}`}function $(e,t,n,r,i,o){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*(o+1)}${n}`:`>= -(2${n} ** ${8*(o+1)-1}${n}) and < 2 ** ${8*(o+1)-1}${n}`,new U.ERR_OUT_OF_RANGE("value",r,e)}!function(e,t,n){q(t,"offset"),void 0!==e[t]&&void 0!==e[t+n]||K(t,e.length-(n+1))}(r,i,o)}function q(e,t){if("number"!=typeof e)throw new U.ERR_INVALID_ARG_TYPE(t,"number",e)}function K(e,t,n){if(Math.floor(e)!==e)throw q(e,n),new U.ERR_OUT_OF_RANGE("offset","an integer",e);if(t<0)throw new U.ERR_BUFFER_OUT_OF_BOUNDS;throw new U.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${t}`,e)}M("ERR_BUFFER_OUT_OF_BOUNDS",function(e){return e?`${e} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),M("ERR_INVALID_ARG_TYPE",function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`},TypeError),M("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 G=/[^+/0-9A-Za-z-_]/g;function z(e,t){let n;t=t||1/0;const r=e.length;let i=null;const o=[];for(let s=0;s<r;++s){if(n=e.charCodeAt(s),n>55295&&n<57344){if(!i){if(n>56319){(t-=3)>-1&&o.push(239,191,189);continue}if(s+1===r){(t-=3)>-1&&o.push(239,191,189);continue}i=n;continue}if(n<56320){(t-=3)>-1&&o.push(239,191,189),i=n;continue}n=65536+(i-55296<<10|n-56320)}else i&&(t-=3)>-1&&o.push(239,191,189);if(i=null,n<128){if((t-=1)<0)break;o.push(n)}else if(n<2048){if((t-=2)<0)break;o.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;o.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;o.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return o}function W(e){return t.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(G,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function H(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 j(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function V(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 Q(e){return"undefined"==typeof BigInt?J:e}function J(){throw new Error("BigInt not supported")}}(Mh)),Mh);const Hh="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0;function jh(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function Vh(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function Xh(e,...t){if(!jh(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 Qh(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.createHasher");Vh(e.outputLen),Vh(e.blockLen)}function Jh(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 Yh(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Zh(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function ed(e,t){return e<<32-t|e>>>t}const td=(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)(),nd=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function rd(e){if(Xh(e),td)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=nd[e[n]];return t}const id=48,od=57,sd=65,ad=70,cd=97,ud=102;function ld(e){return e>=id&&e<=od?e-id:e>=sd&&e<=ad?e-(sd-10):e>=cd&&e<=ud?e-(cd-10):void 0}function hd(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);if(td)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=ld(e.charCodeAt(i)),o=ld(e.charCodeAt(i+1));if(void 0===n||void 0===o){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+o}return r}function dd(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)),Xh(e),e}function fd(...e){let t=0;for(let n=0;n<e.length;n++){const r=e[n];Xh(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 gd{}function pd(e){const t=t=>e().update(dd(t)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function md(e=32){if(Hh&&"function"==typeof Hh.getRandomValues)return Hh.getRandomValues(new Uint8Array(e));if(Hh&&"function"==typeof Hh.randomBytes)return Uint8Array.from(Hh.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}function yd(e,t,n){return e&t^~e&n}function wd(e,t,n){return e&t^e&n^t&n}class bd extends gd{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=Zh(this.buffer)}update(e){Jh(this),Xh(e=dd(e));const{view:t,buffer:n,blockLen:r}=this,i=e.length;for(let o=0;o<i;){const s=Math.min(r-this.pos,i-o);if(s===r){const t=Zh(e);for(;r<=i-o;o+=r)this.process(t,o);continue}n.set(e.subarray(o,o+s),this.pos),this.pos+=s,o+=s,this.pos===r&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Jh(this),function(e,t){Xh(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:o}=this;t[o++]=128,Yh(this.buffer.subarray(o)),this.padOffset>r-o&&(this.process(n,0),o=0);for(let e=o;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),o=BigInt(4294967295),s=Number(n>>i&o),a=Number(n&o),c=r?4:0,u=r?0:4;e.setUint32(t+c,s,r),e.setUint32(t+u,a,r)}(n,r-8,BigInt(8*this.length),i),this.process(n,0);const s=Zh(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const c=a/4,u=this.get();if(c>u.length)throw new Error("_sha2: outputLen bigger than state");for(let e=0;e<c;e++)s.setUint32(4*e,u[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:o,pos:s}=this;return e.destroyed=o,e.finished=i,e.length=r,e.pos=s,r%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}}const kd=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),vd=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Sd=BigInt(2**32-1),Ad=BigInt(32);function Td(e,t=!1){return t?{h:Number(e&Sd),l:Number(e>>Ad&Sd)}:{h:0|Number(e>>Ad&Sd),l:0|Number(e&Sd)}}const Ed=(e,t,n)=>e>>>n,Id=(e,t,n)=>e<<32-n|t>>>n,xd=(e,t,n)=>e>>>n|t<<32-n,Cd=(e,t,n)=>e<<32-n|t>>>n,Nd=(e,t,n)=>e<<64-n|t>>>n-32,Bd=(e,t,n)=>e>>>n-32|t<<64-n;function _d(e,t,n,r){const i=(t>>>0)+(r>>>0);return{h:e+n+(i/2**32|0)|0,l:0|i}}const Pd=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),Rd=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,Dd=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),Ld=(e,t,n,r,i)=>t+n+r+i+(e/2**32|0)|0,Od=(e,t,n,r,i)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(i>>>0),Ud=(e,t,n,r,i,o)=>t+n+r+i+o+(e/2**32|0)|0,Md=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]),Fd=new Uint32Array(64);class $d extends bd{constructor(e=32){super(64,e,8,!1),this.A=0|kd[0],this.B=0|kd[1],this.C=0|kd[2],this.D=0|kd[3],this.E=0|kd[4],this.F=0|kd[5],this.G=0|kd[6],this.H=0|kd[7]}get(){const{A:e,B:t,C:n,D:r,E:i,F:o,G:s,H:a}=this;return[e,t,n,r,i,o,s,a]}set(e,t,n,r,i,o,s,a){this.A=0|e,this.B=0|t,this.C=0|n,this.D=0|r,this.E=0|i,this.F=0|o,this.G=0|s,this.H=0|a}process(e,t){for(let n=0;n<16;n++,t+=4)Fd[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){const t=Fd[e-15],n=Fd[e-2],r=ed(t,7)^ed(t,18)^t>>>3,i=ed(n,17)^ed(n,19)^n>>>10;Fd[e]=i+Fd[e-7]+r+Fd[e-16]|0}let{A:n,B:r,C:i,D:o,E:s,F:a,G:c,H:u}=this;for(let e=0;e<64;e++){const t=u+(ed(s,6)^ed(s,11)^ed(s,25))+yd(s,a,c)+Md[e]+Fd[e]|0,l=(ed(n,2)^ed(n,13)^ed(n,22))+wd(n,r,i)|0;u=c,c=a,a=s,s=o+t|0,o=i,i=r,r=n,n=t+l|0}n=n+this.A|0,r=r+this.B|0,i=i+this.C|0,o=o+this.D|0,s=s+this.E|0,a=a+this.F|0,c=c+this.G|0,u=u+this.H|0,this.set(n,r,i,o,s,a,c,u)}roundClean(){Yh(Fd)}destroy(){this.set(0,0,0,0,0,0,0,0),Yh(this.buffer)}}const qd=(()=>function(e,t=!1){const n=e.length;let r=new Uint32Array(n),i=new Uint32Array(n);for(let o=0;o<n;o++){const{h:n,l:s}=Td(e[o],t);[r[o],i[o]]=[n,s]}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))))(),Kd=(()=>qd[0])(),Gd=(()=>qd[1])(),zd=new Uint32Array(80),Wd=new Uint32Array(80);class Hd extends bd{constructor(e=64){super(128,e,16,!1),this.Ah=0|vd[0],this.Al=0|vd[1],this.Bh=0|vd[2],this.Bl=0|vd[3],this.Ch=0|vd[4],this.Cl=0|vd[5],this.Dh=0|vd[6],this.Dl=0|vd[7],this.Eh=0|vd[8],this.El=0|vd[9],this.Fh=0|vd[10],this.Fl=0|vd[11],this.Gh=0|vd[12],this.Gl=0|vd[13],this.Hh=0|vd[14],this.Hl=0|vd[15]}get(){const{Ah:e,Al:t,Bh:n,Bl:r,Ch:i,Cl:o,Dh:s,Dl:a,Eh:c,El:u,Fh:l,Fl:h,Gh:d,Gl:f,Hh:g,Hl:p}=this;return[e,t,n,r,i,o,s,a,c,u,l,h,d,f,g,p]}set(e,t,n,r,i,o,s,a,c,u,l,h,d,f,g,p){this.Ah=0|e,this.Al=0|t,this.Bh=0|n,this.Bl=0|r,this.Ch=0|i,this.Cl=0|o,this.Dh=0|s,this.Dl=0|a,this.Eh=0|c,this.El=0|u,this.Fh=0|l,this.Fl=0|h,this.Gh=0|d,this.Gl=0|f,this.Hh=0|g,this.Hl=0|p}process(e,t){for(let n=0;n<16;n++,t+=4)zd[n]=e.getUint32(t),Wd[n]=e.getUint32(t+=4);for(let e=16;e<80;e++){const t=0|zd[e-15],n=0|Wd[e-15],r=xd(t,n,1)^xd(t,n,8)^Ed(t,0,7),i=Cd(t,n,1)^Cd(t,n,8)^Id(t,n,7),o=0|zd[e-2],s=0|Wd[e-2],a=xd(o,s,19)^Nd(o,s,61)^Ed(o,0,6),c=Cd(o,s,19)^Bd(o,s,61)^Id(o,s,6),u=Dd(i,c,Wd[e-7],Wd[e-16]),l=Ld(u,r,a,zd[e-7],zd[e-16]);zd[e]=0|l,Wd[e]=0|u}let{Ah:n,Al:r,Bh:i,Bl:o,Ch:s,Cl:a,Dh:c,Dl:u,Eh:l,El:h,Fh:d,Fl:f,Gh:g,Gl:p,Hh:m,Hl:y}=this;for(let e=0;e<80;e++){const t=xd(l,h,14)^xd(l,h,18)^Nd(l,h,41),w=Cd(l,h,14)^Cd(l,h,18)^Bd(l,h,41),b=l&d^~l&g,k=Od(y,w,h&f^~h&p,Gd[e],Wd[e]),v=Ud(k,m,t,b,Kd[e],zd[e]),S=0|k,A=xd(n,r,28)^Nd(n,r,34)^Nd(n,r,39),T=Cd(n,r,28)^Bd(n,r,34)^Bd(n,r,39),E=n&i^n&s^i&s,I=r&o^r&a^o&a;m=0|g,y=0|p,g=0|d,p=0|f,d=0|l,f=0|h,({h:l,l:h}=_d(0|c,0|u,0|v,0|S)),c=0|s,u=0|a,s=0|i,a=0|o,i=0|n,o=0|r;const x=Pd(S,T,I);n=Rd(x,v,A,E),r=0|x}({h:n,l:r}=_d(0|this.Ah,0|this.Al,0|n,0|r)),({h:i,l:o}=_d(0|this.Bh,0|this.Bl,0|i,0|o)),({h:s,l:a}=_d(0|this.Ch,0|this.Cl,0|s,0|a)),({h:c,l:u}=_d(0|this.Dh,0|this.Dl,0|c,0|u)),({h:l,l:h}=_d(0|this.Eh,0|this.El,0|l,0|h)),({h:d,l:f}=_d(0|this.Fh,0|this.Fl,0|d,0|f)),({h:g,l:p}=_d(0|this.Gh,0|this.Gl,0|g,0|p)),({h:m,l:y}=_d(0|this.Hh,0|this.Hl,0|m,0|y)),this.set(n,r,i,o,s,a,c,u,l,h,d,f,g,p,m,y)}roundClean(){Yh(zd,Wd)}destroy(){Yh(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const jd=pd(()=>new $d),Vd=pd(()=>new Hd),Xd=BigInt(0),Qd=BigInt(1);function Jd(e,t=""){if("boolean"!=typeof e){throw new Error((t&&`"${t}"`)+"expected boolean, got type="+typeof e)}return e}function Yd(e,t,n=""){const r=jh(e),i=e?.length,o=void 0!==t;if(!r||o&&i!==t){throw new Error((n&&`"${n}" `)+"expected Uint8Array"+(o?` of length ${t}`:"")+", got "+(r?`length=${i}`:"type="+typeof e))}return e}function Zd(e){const t=e.toString(16);return 1&t.length?"0"+t:t}function ef(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);return""===e?Xd:BigInt("0x"+e)}function tf(e){return ef(rd(e))}function nf(e){return Xh(e),ef(rd(Uint8Array.from(e).reverse()))}function rf(e,t){return hd(e.toString(16).padStart(2*t,"0"))}function of(e,t){return rf(e,t).reverse()}function sf(e,t,n){let r;if("string"==typeof t)try{r=hd(t)}catch(t){throw new Error(e+" must be hex string or Uint8Array, cause: "+t)}else{if(!jh(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 af(e){return Uint8Array.from(e)}const cf=e=>"bigint"==typeof e&&Xd<=e;function uf(e,t,n,r){if(!function(e,t,n){return cf(e)&&cf(t)&&cf(n)&&t<=e&&e<n}(t,n,r))throw new Error("expected valid "+e+": "+n+" <= n < "+r+", got "+t)}function lf(e){let t;for(t=0;e>Xd;e>>=Qd,t+=1);return t}const hf=e=>(Qd<<BigInt(e))-Qd;function df(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 o=typeof i;if(o!==n||null===i)throw new Error(`param "${t}" is invalid: expected ${n}, got ${o}`)}Object.entries(t).forEach(([e,t])=>r(e,t,!1)),Object.entries(n).forEach(([e,t])=>r(e,t,!0))}function ff(e){const t=new WeakMap;return(n,...r)=>{const i=t.get(n);if(void 0!==i)return i;const o=e(n,...r);return t.set(n,o),o}}const gf=BigInt(0),pf=BigInt(1),mf=BigInt(2),yf=BigInt(3),wf=BigInt(4),bf=BigInt(5),kf=BigInt(7),vf=BigInt(8),Sf=BigInt(9),Af=BigInt(16);function Tf(e,t){const n=e%t;return n>=gf?n:t+n}function Ef(e,t,n){let r=e;for(;t-- >gf;)r*=r,r%=n;return r}function If(e,t){if(e===gf)throw new Error("invert: expected non-zero number");if(t<=gf)throw new Error("invert: expected positive modulus, got "+t);let n=Tf(e,t),r=t,i=gf,o=pf;for(;n!==gf;){const e=r%n,t=i-o*(r/n);r=n,n=e,i=o,o=t}if(r!==pf)throw new Error("invert: does not exist");return Tf(i,t)}function xf(e,t,n){if(!e.eql(e.sqr(t),n))throw new Error("Cannot find square root")}function Cf(e,t){const n=(e.ORDER+pf)/wf,r=e.pow(t,n);return xf(e,r,t),r}function Nf(e,t){const n=(e.ORDER-bf)/vf,r=e.mul(t,mf),i=e.pow(r,n),o=e.mul(t,i),s=e.mul(e.mul(o,mf),i),a=e.mul(o,e.sub(s,e.ONE));return xf(e,a,t),a}function Bf(e){if(e<yf)throw new Error("sqrt is not defined for small field");let t=e-pf,n=0;for(;t%mf===gf;)t/=mf,n++;let r=mf;const i=Of(e);for(;1===Df(i,r);)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(1===n)return Cf;let o=i.pow(r,t);const s=(t+pf)/mf;return function(e,r){if(e.is0(r))return r;if(1!==Df(e,r))throw new Error("Cannot find square root");let i=n,a=e.mul(e.ONE,o),c=e.pow(r,t),u=e.pow(r,s);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=pf<<BigInt(i-t-1),o=e.pow(a,r);i=t,a=e.sqr(o),c=e.mul(c,a),u=e.mul(u,o)}return u}}function _f(e){return e%wf===yf?Cf:e%vf===bf?Nf:e%Af===Sf?function(e){const t=Of(e),n=Bf(e),r=n(t,t.neg(t.ONE)),i=n(t,r),o=n(t,t.neg(r)),s=(e+kf)/Af;return(e,t)=>{let n=e.pow(t,s),a=e.mul(n,r);const c=e.mul(n,i),u=e.mul(n,o),l=e.eql(e.sqr(a),t),h=e.eql(e.sqr(c),t);n=e.cmov(n,a,l),a=e.cmov(u,c,h);const d=e.eql(e.sqr(a),t),f=e.cmov(n,a,d);return xf(e,f,t),f}}(e):Bf(e)}const Pf=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Rf(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),o=e.inv(i);return t.reduceRight((t,n,i)=>e.is0(n)?t:(r[i]=e.mul(t,r[i]),e.mul(t,n)),o),r}function Df(e,t){const n=(e.ORDER-pf)/mf,r=e.pow(t,n),i=e.eql(r,e.ONE),o=e.eql(r,e.ZERO),s=e.eql(r,e.neg(e.ONE));if(!i&&!o&&!s)throw new Error("invalid Legendre symbol result");return i?1:o?0:-1}function Lf(e,t){void 0!==t&&Vh(t);const n=void 0!==t?t:e.toString(2).length;return{nBitLength:n,nByteLength:Math.ceil(n/8)}}function Of(e,t,n=!1,r={}){if(e<=gf)throw new Error("invalid field: expected ORDER > 0, got "+e);let i,o,s,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&&(o=e.sqrt),"boolean"==typeof e.isLE&&(n=e.isLE),"boolean"==typeof e.modFromBytes&&(a=e.modFromBytes),s=e.allowedLengths}else"number"==typeof t&&(i=t),r.sqrt&&(o=r.sqrt);const{nBitLength:c,nByteLength:u}=Lf(e,i);if(u>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let l;const h=Object.freeze({ORDER:e,isLE:n,BITS:c,BYTES:u,MASK:hf(c),ZERO:gf,ONE:pf,allowedLengths:s,create:t=>Tf(t,e),isValid:t=>{if("bigint"!=typeof t)throw new Error("invalid field element: expected bigint, got "+typeof t);return gf<=t&&t<e},is0:e=>e===gf,isValidNot0:e=>!h.is0(e)&&h.isValid(e),isOdd:e=>(e&pf)===pf,neg:t=>Tf(-t,e),eql:(e,t)=>e===t,sqr:t=>Tf(t*t,e),add:(t,n)=>Tf(t+n,e),sub:(t,n)=>Tf(t-n,e),mul:(t,n)=>Tf(t*n,e),pow:(e,t)=>function(e,t,n){if(n<gf)throw new Error("invalid exponent, negatives unsupported");if(n===gf)return e.ONE;if(n===pf)return t;let r=e.ONE,i=t;for(;n>gf;)n&pf&&(r=e.mul(r,i)),i=e.sqr(i),n>>=pf;return r}(h,e,t),div:(t,n)=>Tf(t*If(n,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>If(t,e),sqrt:o||(t=>(l||(l=_f(e)),l(h,t))),toBytes:e=>n?of(e,u):rf(e,u),fromBytes:(t,r=!0)=>{if(s){if(!s.includes(t.length)||t.length>u)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+t.length);const e=new Uint8Array(u);e.set(t,n?0:e.length-t.length),t=e}if(t.length!==u)throw new Error("Field.fromBytes: expected "+u+" bytes, got "+t.length);let i=n?nf(t):tf(t);if(a&&(i=Tf(i,e)),!r&&!h.isValid(i))throw new Error("invalid field element: outside of range 0..ORDER");return i},invertBatch:e=>Rf(h,e),cmov:(e,t,n)=>n?t:e});return Object.freeze(h)}function Uf(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 Mf(e){const t=Uf(e);return t+Math.ceil(t/2)}const Ff=BigInt(0),$f=BigInt(1);function qf(e,t){const n=t.negate();return e?n:t}function Kf(e,t){const n=Rf(e.Fp,t.map(e=>e.Z));return t.map((t,r)=>e.fromAffine(t.toAffine(n[r])))}function Gf(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function zf(e,t){Gf(e,t);const n=2**e;return{windows:Math.ceil(t/e)+1,windowSize:2**(e-1),mask:hf(e),maxNumber:n,shiftBy:BigInt(e)}}function Wf(e,t,n){const{windowSize:r,mask:i,maxNumber:o,shiftBy:s}=n;let a=Number(e&i),c=e>>s;a>r&&(a-=o,c+=$f);const u=t*r;return{nextN:c,offset:u+Math.abs(a)-1,isZero:0===a,isNeg:a<0,isNegF:t%2!=0,offsetF:u}}const Hf=new WeakMap,jf=new WeakMap;function Vf(e){return jf.get(e)||1}function Xf(e){if(e!==Ff)throw new Error("invalid wNAF")}class Qf{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>Ff;)t&$f&&(n=n.add(r)),r=r.double(),t>>=$f;return n}precomputeWindow(e,t){const{windows:n,windowSize:r}=zf(t,this.bits),i=[];let o=e,s=o;for(let e=0;e<n;e++){s=o,i.push(s);for(let e=1;e<r;e++)s=s.add(o),i.push(s);o=s.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 o=zf(e,this.bits);for(let e=0;e<o.windows;e++){const{nextN:s,offset:a,isZero:c,isNeg:u,isNegF:l,offsetF:h}=Wf(n,e,o);n=s,c?i=i.add(qf(l,t[h])):r=r.add(qf(u,t[a]))}return Xf(n),{p:r,f:i}}wNAFUnsafe(e,t,n,r=this.ZERO){const i=zf(e,this.bits);for(let e=0;e<i.windows&&n!==Ff;e++){const{nextN:o,offset:s,isZero:a,isNeg:c}=Wf(n,e,i);if(n=o,!a){const e=t[s];r=r.add(c?e.negate():e)}}return Xf(n),r}getPrecomputes(e,t,n){let r=Hf.get(t);return r||(r=this.precomputeWindow(t,e),1!==e&&("function"==typeof n&&(r=n(r)),Hf.set(t,r))),r}cached(e,t,n){const r=Vf(e);return this.wNAF(r,this.getPrecomputes(r,e,n),t)}unsafe(e,t,n,r){const i=Vf(e);return 1===i?this._unsafeLadder(e,t,r):this.wNAFUnsafe(i,this.getPrecomputes(i,e,n),t,r)}createCache(e,t){Gf(t,this.bits),jf.set(e,t),Hf.delete(e)}hasCache(e){return 1!==Vf(e)}}function Jf(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,o=r.length;if(i!==o)throw new Error("arrays of points and scalars must have equal length");const s=e.ZERO,a=lf(BigInt(i));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const u=hf(c),l=new Array(Number(u)+1).fill(s);let h=s;for(let e=Math.floor((t.BITS-1)/c)*c;e>=0;e-=c){l.fill(s);for(let t=0;t<o;t++){const i=r[t],o=Number(i>>BigInt(e)&u);l[o]=l[o].add(n[t])}let t=s;for(let e=l.length-1,n=s;e>0;e--)n=n.add(l[e]),t=t.add(n);if(h=h.add(t),0!==e)for(let e=0;e<c;e++)h=h.double()}return h}function Yf(e,t,n){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return function(e){df(e,Pf.reduce((e,t)=>(e[t]="function",e),{ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"}))}(t),t}return Of(e,{isLE:n})}function Zf(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>Ff))throw new Error(`CURVE.${e} must be positive bigint`)}const i=Yf(t.p,n.Fp,r),o=Yf(t.n,n.Fn,r),s=["Gx","Gy","a","weierstrass"===e?"b":"d"];for(const e of s)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:o}}const eg=BigInt(0),tg=BigInt(1),ng=BigInt(2),rg=BigInt(8);function ig(e,t,n={}){if("function"!=typeof t)throw new Error('"hash" function param is required');df(n,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});const{prehash:r}=n,{BASE:i,Fp:o,Fn:s}=e,a=n.randomBytes||md,c=n.adjustScalarBytes||(e=>e),u=n.domain||((e,t,n)=>{if(Jd(n,"phflag"),t.length||n)throw new Error("Contexts/pre-hash are not supported");return e});function l(e){return s.create(nf(e))}function h(e){const{head:n,prefix:r,scalar:o}=function(e){const n=m.secretKey;e=sf("private key",e,n);const r=sf("hashed private key",t(e),2*n),i=c(r.slice(0,n));return{head:i,prefix:r.slice(n,2*n),scalar:l(i)}}(e),s=i.multiply(o),a=s.toBytes();return{head:n,prefix:r,scalar:o,point:s,pointBytes:a}}function d(e){return h(e).pointBytes}function f(e=Uint8Array.of(),...n){const i=fd(...n);return l(t(u(i,sf("context",e),!!r)))}const g={zip215:!0};const p=o.BYTES,m={secretKey:p,publicKey:p,signature:2*p,seed:p};function y(e=a(m.seed)){return Yd(e,m.seed,"seed")}const w={getExtendedPublicKey:h,randomSecretKey:y,isValidSecretKey:function(e){return jh(e)&&e.length===s.BYTES},isValidPublicKey:function(t,n){try{return!!e.fromBytes(t,n)}catch(e){return!1}},toMontgomery(t){const{y:n}=e.fromBytes(t),r=m.publicKey,i=32===r;if(!i&&57!==r)throw new Error("only defined for 25519 and 448");const s=i?o.div(tg+n,tg-n):o.div(n-tg,n+tg);return o.toBytes(s)},toMontgomerySecret(e){const n=m.secretKey;Yd(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=w.randomSecretKey(e);return{secretKey:t,publicKey:d(t)}},getPublicKey:d,sign:function(e,t,n={}){e=sf("message",e),r&&(e=r(e));const{prefix:o,scalar:a,pointBytes:c}=h(t),u=f(n.context,o,e),l=i.multiply(u).toBytes(),d=f(n.context,l,c,e),g=s.create(u+d*a);if(!s.isValid(g))throw new Error("sign failed: invalid s");return Yd(fd(l,s.toBytes(g)),m.signature,"result")},verify:function(t,n,o,s=g){const{context:a,zip215:c}=s,u=m.signature;t=sf("signature",t,u),n=sf("message",n),o=sf("publicKey",o,m.publicKey),void 0!==c&&Jd(c,"zip215"),r&&(n=r(n));const l=u/2,h=t.subarray(0,l),d=nf(t.subarray(l,u));let p,y,w;try{p=e.fromBytes(o,c),y=e.fromBytes(h,c),w=i.multiplyUnsafe(d)}catch(e){return!1}if(!c&&p.isSmallOrder())return!1;const b=f(a,y.toBytes(),p.toBytes(),n);return y.add(p.multiplyUnsafe(b)).subtract(w).clearCofactor().is0()},utils:w,Point:e,lengths:m})}function og(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:Of(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),o=function(e,t={}){const n=Zf("edwards",e,t,t.FpFnLE),{Fp:r,Fn:i}=n;let o=n.CURVE;const{h:s}=o;df(t,{},{uvRatio:"function"});const a=ng<<BigInt(8*i.BYTES)-tg,c=e=>r.create(e),u=t.uvRatio||((e,t)=>{try{return{isValid:!0,value:r.sqrt(r.div(e,t))}}catch(e){return{isValid:!1,value:eg}}});if(!function(e,t,n,r){const i=e.sqr(n),o=e.sqr(r),s=e.add(e.mul(t.a,i),o),a=e.add(e.ONE,e.mul(t.d,e.mul(i,o)));return e.eql(s,a)}(r,o,o.Gx,o.Gy))throw new Error("bad curve params: generator point");function l(e,t,n=!1){return uf("coordinate "+e,t,n?tg:eg,a),t}function h(e){if(!(e instanceof g))throw new Error("ExtendedPoint expected")}const d=ff((e,t)=>{const{X:n,Y:i,Z:o}=e,s=e.is0();null==t&&(t=s?rg:r.inv(o));const a=c(n*t),u=c(i*t),l=r.mul(o,t);if(s)return{x:eg,y:tg};if(l!==tg)throw new Error("invZ was invalid");return{x:a,y:u}}),f=ff(e=>{const{a:t,d:n}=o;if(e.is0())throw new Error("bad point: ZERO");const{X:r,Y:i,Z:s,T:a}=e,u=c(r*r),l=c(i*i),h=c(s*s),d=c(h*h),f=c(u*t);if(c(h*c(f+l))!==c(d+c(n*c(u*l))))throw new Error("bad point: equation left != right (1)");if(c(r*i)!==c(s*a))throw new Error("bad point: equation left != right (2)");return!0});class g{constructor(e,t,n,r){this.X=l("x",e),this.Y=l("y",t),this.Z=l("z",n,!0),this.T=l("t",r),Object.freeze(this)}static CURVE(){return o}static fromAffine(e){if(e instanceof g)throw new Error("extended point not allowed");const{x:t,y:n}=e||{};return l("x",t),l("y",n),new g(t,n,tg,c(t*n))}static fromBytes(e,t=!1){const n=r.BYTES,{a:i,d:s}=o;e=af(Yd(e,n,"point")),Jd(t,"zip215");const l=af(e),h=e[n-1];l[n-1]=-129&h;const d=nf(l),f=t?a:r.ORDER;uf("point.y",d,eg,f);const p=c(d*d),m=c(p-tg),y=c(s*p-i);let{isValid:w,value:b}=u(m,y);if(!w)throw new Error("bad point: invalid y coordinate");const k=(b&tg)===tg,v=!!(128&h);if(!t&&b===eg&&v)throw new Error("bad point: x=0 and x_0=1");return v!==k&&(b=c(-b)),g.fromAffine({x:b,y:d})}static fromHex(e,t=!1){return g.fromBytes(sf("point",e),t)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(e=8,t=!0){return p.createCache(this,e),t||this.multiply(ng),this}assertValidity(){f(this)}equals(e){h(e);const{X:t,Y:n,Z:r}=this,{X:i,Y:o,Z:s}=e,a=c(t*s),u=c(i*r),l=c(n*s),d=c(o*r);return a===u&&l===d}is0(){return this.equals(g.ZERO)}negate(){return new g(c(-this.X),this.Y,this.Z,c(-this.T))}double(){const{a:e}=o,{X:t,Y:n,Z:r}=this,i=c(t*t),s=c(n*n),a=c(ng*c(r*r)),u=c(e*i),l=t+n,h=c(c(l*l)-i-s),d=u+s,f=d-a,p=u-s,m=c(h*f),y=c(d*p),w=c(h*p),b=c(f*d);return new g(m,y,b,w)}add(e){h(e);const{a:t,d:n}=o,{X:r,Y:i,Z:s,T:a}=this,{X:u,Y:l,Z:d,T:f}=e,p=c(r*u),m=c(i*l),y=c(a*n*f),w=c(s*d),b=c((r+i)*(u+l)-p-m),k=w-y,v=w+y,S=c(m-t*p),A=c(b*k),T=c(v*S),E=c(b*S),I=c(k*v);return new g(A,T,I,E)}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}=p.cached(this,e,e=>Kf(g,e));return Kf(g,[t,n])[0]}multiplyUnsafe(e,t=g.ZERO){if(!i.isValid(e))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return e===eg?g.ZERO:this.is0()||e===tg?this:p.unsafe(this,e,e=>Kf(g,e),t)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}isTorsionFree(){return p.unsafe(this,o.n).is0()}toAffine(e){return d(this,e)}clearCofactor(){return s===tg?this:this.multiplyUnsafe(s)}toBytes(){const{x:e,y:t}=this.toAffine(),n=r.toBytes(t);return n[n.length-1]|=e&tg?128:0,n}toHex(){return rd(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 Kf(g,e)}static msm(e,t){return Jf(g,i,e,t)}_setWindowSize(e){this.precompute(e)}toRawBytes(){return this.toBytes()}}g.BASE=new g(o.Gx,o.Gy,tg,c(o.Gx*o.Gy)),g.ZERO=new g(eg,tg,tg,eg),g.Fp=r,g.Fn=i;const p=new Qf(g,i.BITS);return g.BASE.precompute(8),g}(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,ig(o,r,i))}const sg=BigInt(1),ag=BigInt(2);BigInt(3);const cg=BigInt(5),ug=BigInt(8),lg=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),hg=(()=>({p:lg,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:ug,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")}))();function dg(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}const fg=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function gg(e,t){const n=lg,r=Tf(t*t*t,n),i=function(e){const t=BigInt(10),n=BigInt(20),r=BigInt(40),i=BigInt(80),o=lg,s=e*e%o*e%o,a=Ef(s,ag,o)*s%o,c=Ef(a,sg,o)*e%o,u=Ef(c,cg,o)*c%o,l=Ef(u,t,o)*u%o,h=Ef(l,n,o)*l%o,d=Ef(h,r,o)*h%o,f=Ef(d,i,o)*d%o,g=Ef(f,i,o)*d%o,p=Ef(g,t,o)*u%o;return{pow_p_5_8:Ef(p,ag,o)*e%o,b2:s}}(e*Tf(r*r*t,n)).pow_p_5_8;let o=Tf(e*r*i,n);const s=Tf(t*o*o,n),a=o,c=Tf(o*fg,n),u=s===e,l=s===Tf(-e,n),h=s===Tf(-e*fg,n);return u&&(o=a),(l||h)&&(o=c),(Tf(o,n)&pf)===pf&&(o=Tf(-o,n)),{isValid:u||l,value:o}}const pg=(()=>Of(hg.p,{isLE:!0}))(),mg=(()=>({...hg,Fp:pg,hash:Vd,adjustScalarBytes:dg,uvRatio:gg}))(),yg=(()=>og(mg))();var wg,bg={exports:{}},kg=Fc(Object.freeze({__proto__:null,default:{}})),vg=bg.exports;function Sg(){return wg||(wg=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 o;"object"==typeof e?e.exports=i:t.BN=i,i.BN=i,i.wordSize=26;try{o="undefined"!=typeof window&&void 0!==window.Buffer?window.Buffer:kg.Buffer}catch(e){}function s(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=s(e,n);return n-1>=t&&(r|=s(e,n-1)<<4),r}function c(e,t,r,i){for(var o=0,s=0,a=Math.min(e.length,r),c=t;c<a;c++){var u=e.charCodeAt(c)-48;o*=i,s=u>=49?u-49+10:u>=17?u-17+10:u,n(u>=0&&s<i,"Invalid character"),o+=s}return o}function u(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 o,s,a=0;if("be"===r)for(i=e.length-1,o=0;i>=0;i-=3)s=e[i]|e[i-1]<<8|e[i-2]<<16,this.words[o]|=s<<a&67108863,this.words[o+1]=s>>>26-a&67108863,(a+=24)>=26&&(a-=26,o++);else if("le"===r)for(i=0,o=0;i<e.length;i+=3)s=e[i]|e[i+1]<<8|e[i+2]<<16,this.words[o]|=s<<a&67108863,this.words[o+1]=s>>>26-a&67108863,(a+=24)>=26&&(a-=26,o++);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,o=0,s=0;if("be"===n)for(r=e.length-1;r>=t;r-=2)i=a(e,t,r)<<o,this.words[s]|=67108863&i,o>=18?(o-=18,s+=1,this.words[s]|=i>>>26):o+=8;else for(r=(e.length-t)%2==0?t+1:t;r<e.length;r+=2)i=a(e,t,r)<<o,this.words[s]|=67108863&i,o>=18?(o-=18,s+=1,this.words[s]|=i>>>26):o+=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 o=e.length-n,s=o%r,a=Math.min(o,o-s)+n,u=0,l=n;l<a;l+=r)u=c(e,l,l+r,t),this.imuln(i),this.words[0]+u<67108864?this.words[0]+=u:this._iaddn(u);if(0!==s){var h=1;for(u=c(e,l,e.length,t),l=0;l<s;l++)h*=t;this.imuln(h),this.words[0]+u<67108864?this.words[0]+=u:this._iaddn(u)}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){u(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")]=l}catch(e){i.prototype.inspect=l}else i.prototype.inspect=l;function l(){return(this.red?"<BN-R: ":"<BN: ")+this.toString(16)+">"}var h=["","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"],d=[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],f=[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 g(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],o=0|t.words[0],s=i*o,a=67108863&s,c=s/67108864|0;n.words[0]=a;for(var u=1;u<r;u++){for(var l=c>>>26,h=67108863&c,d=Math.min(u,t.length-1),f=Math.max(0,u-e.length+1);f<=d;f++){var g=u-f|0;l+=(s=(i=0|e.words[g])*(o=0|t.words[f])+h)/67108864|0,h=67108863&s}n.words[u]=0|h,c=0|l}return 0!==c?n.words[u]=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,o=0,s=0;s<this.length;s++){var a=this.words[s],c=(16777215&(a<<i|o)).toString(16);o=a>>>24-i&16777215,(i+=2)>=26&&(i-=26,s--),r=0!==o||s!==this.length-1?h[6-c.length]+c+r:c+r}for(0!==o&&(r=o.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 u=d[e],l=f[e];r="";var g=this.clone();for(g.negative=0;!g.isZero();){var p=g.modrn(l).toString(e);r=(g=g.idivn(l)).isZero()?p+r:h[u-p.length]+p+r}for(this.isZero()&&(r="0"+r);r.length%t!==0;)r="0"+r;return 0!==this.negative&&(r="-"+r),r}n(!1,"Base should be between 2 and 36")},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)},o&&(i.prototype.toBuffer=function(e,t){return this.toArrayLike(o,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(),o=r||Math.max(1,i);n(i<=o,"byte array longer than desired length"),n(o>0,"Requested array length <= 0");var s=function(e,t){return e.allocUnsafe?e.allocUnsafe(t):new e(t)}(e,o);return this["_toArrayLike"+("le"===t?"LE":"BE")](s,i),s},i.prototype._toArrayLikeLE=function(e,t){for(var n=0,r=0,i=0,o=0;i<this.length;i++){var s=this.words[i]<<o|r;e[n++]=255&s,n<e.length&&(e[n++]=s>>8&255),n<e.length&&(e[n++]=s>>16&255),6===o?(n<e.length&&(e[n++]=s>>24&255),r=0,o=0):(r=s>>>24,o+=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,o=0;i<this.length;i++){var s=this.words[i]<<o|r;e[n--]=255&s,n>=0&&(e[n--]=s>>8&255),n>=0&&(e[n--]=s>>16&255),6===o?(n>=0&&(e[n--]=s>>24&255),r=0,o=0):(r=s>>>24,o+=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];return r>0&&(this.words[i]=~this.words[i]&67108863>>26-r),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,o=0;o<r.length;o++)t=(0|n.words[o])+(0|r.words[o])+i,this.words[o]=67108863&t,i=t>>>26;for(;0!==i&&o<n.length;o++)t=(0|n.words[o])+i,this.words[o]=67108863&t,i=t>>>26;if(this.length=n.length,0!==i)this.words[this.length]=i,this.length++;else if(n!==this)for(;o<n.length;o++)this.words[o]=n.words[o];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 o=0,s=0;s<r.length;s++)o=(t=(0|n.words[s])-(0|r.words[s])+o)>>26,this.words[s]=67108863&t;for(;0!==o&&s<n.length;s++)o=(t=(0|n.words[s])+o)>>26,this.words[s]=67108863&t;if(0===o&&s<n.length&&n!==this)for(;s<n.length;s++)this.words[s]=n.words[s];return this.length=Math.max(this.length,s),n!==this&&(this.negative=1),this._strip()},i.prototype.sub=function(e){return this.clone().isub(e)};var p=function(e,t,n){var r,i,o,s=e.words,a=t.words,c=n.words,u=0,l=0|s[0],h=8191&l,d=l>>>13,f=0|s[1],g=8191&f,p=f>>>13,m=0|s[2],y=8191&m,w=m>>>13,b=0|s[3],k=8191&b,v=b>>>13,S=0|s[4],A=8191&S,T=S>>>13,E=0|s[5],I=8191&E,x=E>>>13,C=0|s[6],N=8191&C,B=C>>>13,_=0|s[7],P=8191&_,R=_>>>13,D=0|s[8],L=8191&D,O=D>>>13,U=0|s[9],M=8191&U,F=U>>>13,$=0|a[0],q=8191&$,K=$>>>13,G=0|a[1],z=8191&G,W=G>>>13,H=0|a[2],j=8191&H,V=H>>>13,X=0|a[3],Q=8191&X,J=X>>>13,Y=0|a[4],Z=8191&Y,ee=Y>>>13,te=0|a[5],ne=8191&te,re=te>>>13,ie=0|a[6],oe=8191&ie,se=ie>>>13,ae=0|a[7],ce=8191&ae,ue=ae>>>13,le=0|a[8],he=8191&le,de=le>>>13,fe=0|a[9],ge=8191&fe,pe=fe>>>13;n.negative=e.negative^t.negative,n.length=19;var me=(u+(r=Math.imul(h,q))|0)+((8191&(i=(i=Math.imul(h,K))+Math.imul(d,q)|0))<<13)|0;u=((o=Math.imul(d,K))+(i>>>13)|0)+(me>>>26)|0,me&=67108863,r=Math.imul(g,q),i=(i=Math.imul(g,K))+Math.imul(p,q)|0,o=Math.imul(p,K);var ye=(u+(r=r+Math.imul(h,z)|0)|0)+((8191&(i=(i=i+Math.imul(h,W)|0)+Math.imul(d,z)|0))<<13)|0;u=((o=o+Math.imul(d,W)|0)+(i>>>13)|0)+(ye>>>26)|0,ye&=67108863,r=Math.imul(y,q),i=(i=Math.imul(y,K))+Math.imul(w,q)|0,o=Math.imul(w,K),r=r+Math.imul(g,z)|0,i=(i=i+Math.imul(g,W)|0)+Math.imul(p,z)|0,o=o+Math.imul(p,W)|0;var we=(u+(r=r+Math.imul(h,j)|0)|0)+((8191&(i=(i=i+Math.imul(h,V)|0)+Math.imul(d,j)|0))<<13)|0;u=((o=o+Math.imul(d,V)|0)+(i>>>13)|0)+(we>>>26)|0,we&=67108863,r=Math.imul(k,q),i=(i=Math.imul(k,K))+Math.imul(v,q)|0,o=Math.imul(v,K),r=r+Math.imul(y,z)|0,i=(i=i+Math.imul(y,W)|0)+Math.imul(w,z)|0,o=o+Math.imul(w,W)|0,r=r+Math.imul(g,j)|0,i=(i=i+Math.imul(g,V)|0)+Math.imul(p,j)|0,o=o+Math.imul(p,V)|0;var be=(u+(r=r+Math.imul(h,Q)|0)|0)+((8191&(i=(i=i+Math.imul(h,J)|0)+Math.imul(d,Q)|0))<<13)|0;u=((o=o+Math.imul(d,J)|0)+(i>>>13)|0)+(be>>>26)|0,be&=67108863,r=Math.imul(A,q),i=(i=Math.imul(A,K))+Math.imul(T,q)|0,o=Math.imul(T,K),r=r+Math.imul(k,z)|0,i=(i=i+Math.imul(k,W)|0)+Math.imul(v,z)|0,o=o+Math.imul(v,W)|0,r=r+Math.imul(y,j)|0,i=(i=i+Math.imul(y,V)|0)+Math.imul(w,j)|0,o=o+Math.imul(w,V)|0,r=r+Math.imul(g,Q)|0,i=(i=i+Math.imul(g,J)|0)+Math.imul(p,Q)|0,o=o+Math.imul(p,J)|0;var ke=(u+(r=r+Math.imul(h,Z)|0)|0)+((8191&(i=(i=i+Math.imul(h,ee)|0)+Math.imul(d,Z)|0))<<13)|0;u=((o=o+Math.imul(d,ee)|0)+(i>>>13)|0)+(ke>>>26)|0,ke&=67108863,r=Math.imul(I,q),i=(i=Math.imul(I,K))+Math.imul(x,q)|0,o=Math.imul(x,K),r=r+Math.imul(A,z)|0,i=(i=i+Math.imul(A,W)|0)+Math.imul(T,z)|0,o=o+Math.imul(T,W)|0,r=r+Math.imul(k,j)|0,i=(i=i+Math.imul(k,V)|0)+Math.imul(v,j)|0,o=o+Math.imul(v,V)|0,r=r+Math.imul(y,Q)|0,i=(i=i+Math.imul(y,J)|0)+Math.imul(w,Q)|0,o=o+Math.imul(w,J)|0,r=r+Math.imul(g,Z)|0,i=(i=i+Math.imul(g,ee)|0)+Math.imul(p,Z)|0,o=o+Math.imul(p,ee)|0;var ve=(u+(r=r+Math.imul(h,ne)|0)|0)+((8191&(i=(i=i+Math.imul(h,re)|0)+Math.imul(d,ne)|0))<<13)|0;u=((o=o+Math.imul(d,re)|0)+(i>>>13)|0)+(ve>>>26)|0,ve&=67108863,r=Math.imul(N,q),i=(i=Math.imul(N,K))+Math.imul(B,q)|0,o=Math.imul(B,K),r=r+Math.imul(I,z)|0,i=(i=i+Math.imul(I,W)|0)+Math.imul(x,z)|0,o=o+Math.imul(x,W)|0,r=r+Math.imul(A,j)|0,i=(i=i+Math.imul(A,V)|0)+Math.imul(T,j)|0,o=o+Math.imul(T,V)|0,r=r+Math.imul(k,Q)|0,i=(i=i+Math.imul(k,J)|0)+Math.imul(v,Q)|0,o=o+Math.imul(v,J)|0,r=r+Math.imul(y,Z)|0,i=(i=i+Math.imul(y,ee)|0)+Math.imul(w,Z)|0,o=o+Math.imul(w,ee)|0,r=r+Math.imul(g,ne)|0,i=(i=i+Math.imul(g,re)|0)+Math.imul(p,ne)|0,o=o+Math.imul(p,re)|0;var Se=(u+(r=r+Math.imul(h,oe)|0)|0)+((8191&(i=(i=i+Math.imul(h,se)|0)+Math.imul(d,oe)|0))<<13)|0;u=((o=o+Math.imul(d,se)|0)+(i>>>13)|0)+(Se>>>26)|0,Se&=67108863,r=Math.imul(P,q),i=(i=Math.imul(P,K))+Math.imul(R,q)|0,o=Math.imul(R,K),r=r+Math.imul(N,z)|0,i=(i=i+Math.imul(N,W)|0)+Math.imul(B,z)|0,o=o+Math.imul(B,W)|0,r=r+Math.imul(I,j)|0,i=(i=i+Math.imul(I,V)|0)+Math.imul(x,j)|0,o=o+Math.imul(x,V)|0,r=r+Math.imul(A,Q)|0,i=(i=i+Math.imul(A,J)|0)+Math.imul(T,Q)|0,o=o+Math.imul(T,J)|0,r=r+Math.imul(k,Z)|0,i=(i=i+Math.imul(k,ee)|0)+Math.imul(v,Z)|0,o=o+Math.imul(v,ee)|0,r=r+Math.imul(y,ne)|0,i=(i=i+Math.imul(y,re)|0)+Math.imul(w,ne)|0,o=o+Math.imul(w,re)|0,r=r+Math.imul(g,oe)|0,i=(i=i+Math.imul(g,se)|0)+Math.imul(p,oe)|0,o=o+Math.imul(p,se)|0;var Ae=(u+(r=r+Math.imul(h,ce)|0)|0)+((8191&(i=(i=i+Math.imul(h,ue)|0)+Math.imul(d,ce)|0))<<13)|0;u=((o=o+Math.imul(d,ue)|0)+(i>>>13)|0)+(Ae>>>26)|0,Ae&=67108863,r=Math.imul(L,q),i=(i=Math.imul(L,K))+Math.imul(O,q)|0,o=Math.imul(O,K),r=r+Math.imul(P,z)|0,i=(i=i+Math.imul(P,W)|0)+Math.imul(R,z)|0,o=o+Math.imul(R,W)|0,r=r+Math.imul(N,j)|0,i=(i=i+Math.imul(N,V)|0)+Math.imul(B,j)|0,o=o+Math.imul(B,V)|0,r=r+Math.imul(I,Q)|0,i=(i=i+Math.imul(I,J)|0)+Math.imul(x,Q)|0,o=o+Math.imul(x,J)|0,r=r+Math.imul(A,Z)|0,i=(i=i+Math.imul(A,ee)|0)+Math.imul(T,Z)|0,o=o+Math.imul(T,ee)|0,r=r+Math.imul(k,ne)|0,i=(i=i+Math.imul(k,re)|0)+Math.imul(v,ne)|0,o=o+Math.imul(v,re)|0,r=r+Math.imul(y,oe)|0,i=(i=i+Math.imul(y,se)|0)+Math.imul(w,oe)|0,o=o+Math.imul(w,se)|0,r=r+Math.imul(g,ce)|0,i=(i=i+Math.imul(g,ue)|0)+Math.imul(p,ce)|0,o=o+Math.imul(p,ue)|0;var Te=(u+(r=r+Math.imul(h,he)|0)|0)+((8191&(i=(i=i+Math.imul(h,de)|0)+Math.imul(d,he)|0))<<13)|0;u=((o=o+Math.imul(d,de)|0)+(i>>>13)|0)+(Te>>>26)|0,Te&=67108863,r=Math.imul(M,q),i=(i=Math.imul(M,K))+Math.imul(F,q)|0,o=Math.imul(F,K),r=r+Math.imul(L,z)|0,i=(i=i+Math.imul(L,W)|0)+Math.imul(O,z)|0,o=o+Math.imul(O,W)|0,r=r+Math.imul(P,j)|0,i=(i=i+Math.imul(P,V)|0)+Math.imul(R,j)|0,o=o+Math.imul(R,V)|0,r=r+Math.imul(N,Q)|0,i=(i=i+Math.imul(N,J)|0)+Math.imul(B,Q)|0,o=o+Math.imul(B,J)|0,r=r+Math.imul(I,Z)|0,i=(i=i+Math.imul(I,ee)|0)+Math.imul(x,Z)|0,o=o+Math.imul(x,ee)|0,r=r+Math.imul(A,ne)|0,i=(i=i+Math.imul(A,re)|0)+Math.imul(T,ne)|0,o=o+Math.imul(T,re)|0,r=r+Math.imul(k,oe)|0,i=(i=i+Math.imul(k,se)|0)+Math.imul(v,oe)|0,o=o+Math.imul(v,se)|0,r=r+Math.imul(y,ce)|0,i=(i=i+Math.imul(y,ue)|0)+Math.imul(w,ce)|0,o=o+Math.imul(w,ue)|0,r=r+Math.imul(g,he)|0,i=(i=i+Math.imul(g,de)|0)+Math.imul(p,he)|0,o=o+Math.imul(p,de)|0;var Ee=(u+(r=r+Math.imul(h,ge)|0)|0)+((8191&(i=(i=i+Math.imul(h,pe)|0)+Math.imul(d,ge)|0))<<13)|0;u=((o=o+Math.imul(d,pe)|0)+(i>>>13)|0)+(Ee>>>26)|0,Ee&=67108863,r=Math.imul(M,z),i=(i=Math.imul(M,W))+Math.imul(F,z)|0,o=Math.imul(F,W),r=r+Math.imul(L,j)|0,i=(i=i+Math.imul(L,V)|0)+Math.imul(O,j)|0,o=o+Math.imul(O,V)|0,r=r+Math.imul(P,Q)|0,i=(i=i+Math.imul(P,J)|0)+Math.imul(R,Q)|0,o=o+Math.imul(R,J)|0,r=r+Math.imul(N,Z)|0,i=(i=i+Math.imul(N,ee)|0)+Math.imul(B,Z)|0,o=o+Math.imul(B,ee)|0,r=r+Math.imul(I,ne)|0,i=(i=i+Math.imul(I,re)|0)+Math.imul(x,ne)|0,o=o+Math.imul(x,re)|0,r=r+Math.imul(A,oe)|0,i=(i=i+Math.imul(A,se)|0)+Math.imul(T,oe)|0,o=o+Math.imul(T,se)|0,r=r+Math.imul(k,ce)|0,i=(i=i+Math.imul(k,ue)|0)+Math.imul(v,ce)|0,o=o+Math.imul(v,ue)|0,r=r+Math.imul(y,he)|0,i=(i=i+Math.imul(y,de)|0)+Math.imul(w,he)|0,o=o+Math.imul(w,de)|0;var Ie=(u+(r=r+Math.imul(g,ge)|0)|0)+((8191&(i=(i=i+Math.imul(g,pe)|0)+Math.imul(p,ge)|0))<<13)|0;u=((o=o+Math.imul(p,pe)|0)+(i>>>13)|0)+(Ie>>>26)|0,Ie&=67108863,r=Math.imul(M,j),i=(i=Math.imul(M,V))+Math.imul(F,j)|0,o=Math.imul(F,V),r=r+Math.imul(L,Q)|0,i=(i=i+Math.imul(L,J)|0)+Math.imul(O,Q)|0,o=o+Math.imul(O,J)|0,r=r+Math.imul(P,Z)|0,i=(i=i+Math.imul(P,ee)|0)+Math.imul(R,Z)|0,o=o+Math.imul(R,ee)|0,r=r+Math.imul(N,ne)|0,i=(i=i+Math.imul(N,re)|0)+Math.imul(B,ne)|0,o=o+Math.imul(B,re)|0,r=r+Math.imul(I,oe)|0,i=(i=i+Math.imul(I,se)|0)+Math.imul(x,oe)|0,o=o+Math.imul(x,se)|0,r=r+Math.imul(A,ce)|0,i=(i=i+Math.imul(A,ue)|0)+Math.imul(T,ce)|0,o=o+Math.imul(T,ue)|0,r=r+Math.imul(k,he)|0,i=(i=i+Math.imul(k,de)|0)+Math.imul(v,he)|0,o=o+Math.imul(v,de)|0;var xe=(u+(r=r+Math.imul(y,ge)|0)|0)+((8191&(i=(i=i+Math.imul(y,pe)|0)+Math.imul(w,ge)|0))<<13)|0;u=((o=o+Math.imul(w,pe)|0)+(i>>>13)|0)+(xe>>>26)|0,xe&=67108863,r=Math.imul(M,Q),i=(i=Math.imul(M,J))+Math.imul(F,Q)|0,o=Math.imul(F,J),r=r+Math.imul(L,Z)|0,i=(i=i+Math.imul(L,ee)|0)+Math.imul(O,Z)|0,o=o+Math.imul(O,ee)|0,r=r+Math.imul(P,ne)|0,i=(i=i+Math.imul(P,re)|0)+Math.imul(R,ne)|0,o=o+Math.imul(R,re)|0,r=r+Math.imul(N,oe)|0,i=(i=i+Math.imul(N,se)|0)+Math.imul(B,oe)|0,o=o+Math.imul(B,se)|0,r=r+Math.imul(I,ce)|0,i=(i=i+Math.imul(I,ue)|0)+Math.imul(x,ce)|0,o=o+Math.imul(x,ue)|0,r=r+Math.imul(A,he)|0,i=(i=i+Math.imul(A,de)|0)+Math.imul(T,he)|0,o=o+Math.imul(T,de)|0;var Ce=(u+(r=r+Math.imul(k,ge)|0)|0)+((8191&(i=(i=i+Math.imul(k,pe)|0)+Math.imul(v,ge)|0))<<13)|0;u=((o=o+Math.imul(v,pe)|0)+(i>>>13)|0)+(Ce>>>26)|0,Ce&=67108863,r=Math.imul(M,Z),i=(i=Math.imul(M,ee))+Math.imul(F,Z)|0,o=Math.imul(F,ee),r=r+Math.imul(L,ne)|0,i=(i=i+Math.imul(L,re)|0)+Math.imul(O,ne)|0,o=o+Math.imul(O,re)|0,r=r+Math.imul(P,oe)|0,i=(i=i+Math.imul(P,se)|0)+Math.imul(R,oe)|0,o=o+Math.imul(R,se)|0,r=r+Math.imul(N,ce)|0,i=(i=i+Math.imul(N,ue)|0)+Math.imul(B,ce)|0,o=o+Math.imul(B,ue)|0,r=r+Math.imul(I,he)|0,i=(i=i+Math.imul(I,de)|0)+Math.imul(x,he)|0,o=o+Math.imul(x,de)|0;var Ne=(u+(r=r+Math.imul(A,ge)|0)|0)+((8191&(i=(i=i+Math.imul(A,pe)|0)+Math.imul(T,ge)|0))<<13)|0;u=((o=o+Math.imul(T,pe)|0)+(i>>>13)|0)+(Ne>>>26)|0,Ne&=67108863,r=Math.imul(M,ne),i=(i=Math.imul(M,re))+Math.imul(F,ne)|0,o=Math.imul(F,re),r=r+Math.imul(L,oe)|0,i=(i=i+Math.imul(L,se)|0)+Math.imul(O,oe)|0,o=o+Math.imul(O,se)|0,r=r+Math.imul(P,ce)|0,i=(i=i+Math.imul(P,ue)|0)+Math.imul(R,ce)|0,o=o+Math.imul(R,ue)|0,r=r+Math.imul(N,he)|0,i=(i=i+Math.imul(N,de)|0)+Math.imul(B,he)|0,o=o+Math.imul(B,de)|0;var Be=(u+(r=r+Math.imul(I,ge)|0)|0)+((8191&(i=(i=i+Math.imul(I,pe)|0)+Math.imul(x,ge)|0))<<13)|0;u=((o=o+Math.imul(x,pe)|0)+(i>>>13)|0)+(Be>>>26)|0,Be&=67108863,r=Math.imul(M,oe),i=(i=Math.imul(M,se))+Math.imul(F,oe)|0,o=Math.imul(F,se),r=r+Math.imul(L,ce)|0,i=(i=i+Math.imul(L,ue)|0)+Math.imul(O,ce)|0,o=o+Math.imul(O,ue)|0,r=r+Math.imul(P,he)|0,i=(i=i+Math.imul(P,de)|0)+Math.imul(R,he)|0,o=o+Math.imul(R,de)|0;var _e=(u+(r=r+Math.imul(N,ge)|0)|0)+((8191&(i=(i=i+Math.imul(N,pe)|0)+Math.imul(B,ge)|0))<<13)|0;u=((o=o+Math.imul(B,pe)|0)+(i>>>13)|0)+(_e>>>26)|0,_e&=67108863,r=Math.imul(M,ce),i=(i=Math.imul(M,ue))+Math.imul(F,ce)|0,o=Math.imul(F,ue),r=r+Math.imul(L,he)|0,i=(i=i+Math.imul(L,de)|0)+Math.imul(O,he)|0,o=o+Math.imul(O,de)|0;var Pe=(u+(r=r+Math.imul(P,ge)|0)|0)+((8191&(i=(i=i+Math.imul(P,pe)|0)+Math.imul(R,ge)|0))<<13)|0;u=((o=o+Math.imul(R,pe)|0)+(i>>>13)|0)+(Pe>>>26)|0,Pe&=67108863,r=Math.imul(M,he),i=(i=Math.imul(M,de))+Math.imul(F,he)|0,o=Math.imul(F,de);var Re=(u+(r=r+Math.imul(L,ge)|0)|0)+((8191&(i=(i=i+Math.imul(L,pe)|0)+Math.imul(O,ge)|0))<<13)|0;u=((o=o+Math.imul(O,pe)|0)+(i>>>13)|0)+(Re>>>26)|0,Re&=67108863;var De=(u+(r=Math.imul(M,ge))|0)+((8191&(i=(i=Math.imul(M,pe))+Math.imul(F,ge)|0))<<13)|0;return u=((o=Math.imul(F,pe))+(i>>>13)|0)+(De>>>26)|0,De&=67108863,c[0]=me,c[1]=ye,c[2]=we,c[3]=be,c[4]=ke,c[5]=ve,c[6]=Se,c[7]=Ae,c[8]=Te,c[9]=Ee,c[10]=Ie,c[11]=xe,c[12]=Ce,c[13]=Ne,c[14]=Be,c[15]=_e,c[16]=Pe,c[17]=Re,c[18]=De,0!==u&&(c[19]=u,n.length++),n};function m(e,t,n){n.negative=t.negative^e.negative,n.length=e.length+t.length;for(var r=0,i=0,o=0;o<n.length-1;o++){var s=i;i=0;for(var a=67108863&r,c=Math.min(o,t.length-1),u=Math.max(0,o-e.length+1);u<=c;u++){var l=o-u,h=(0|e.words[l])*(0|t.words[u]),d=67108863&h;a=67108863&(d=d+a|0),i+=(s=(s=s+(h/67108864|0)|0)+(d>>>26)|0)>>>26,s&=67108863}n.words[o]=a,r=s,s=i}return 0!==r?n.words[o]=r:n.length--,n._strip()}function y(e,t,n){return m(e,t,n)}Math.imul||(p=g),i.prototype.mulTo=function(e,t){var n=this.length+e.length;return 10===this.length&&10===e.length?p(this,e,t):n<63?g(this,e,t):n<1024?m(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 o=(0|this.words[i])*e,s=(67108863&o)+(67108863&r);r>>=26,r+=o/67108864|0,r+=s>>>26,this.words[i]=67108863&s}return 0!==r&&(this.words[i]=r,this.length++),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 o=n.sqr();r<t.length;r++,o=o.sqr())0!==t[r]&&(n=n.mul(o));return n},i.prototype.iushln=function(e){n("number"==typeof e&&e>=0);var t,r=e%26,i=(e-r)/26,o=67108863>>>26-r<<26-r;if(0!==r){var s=0;for(t=0;t<this.length;t++){var a=this.words[t]&o,c=(0|this.words[t])-a<<r;this.words[t]=c|s,s=a>>>26-r}s&&(this.words[t]=s,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 o=e%26,s=Math.min((e-o)/26,this.length),a=67108863^67108863>>>o<<o,c=r;if(i-=s,i=Math.max(0,i),c){for(var u=0;u<s;u++)c.words[u]=this.words[u];c.length=s}if(0===s);else if(this.length>s)for(this.length-=s,u=0;u<this.length;u++)this.words[u]=this.words[u+s];else this.words[0]=0,this.length=1;var l=0;for(u=this.length-1;u>=0&&(0!==l||u>=i);u--){var h=0|this.words[u];this.words[u]=l<<26-o|h>>>o,l=h&a}return c&&0!==l&&(c.words[c.length++]=l),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 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,o,s=e.length+r;this._expand(s);var a=0;for(i=0;i<e.length;i++){o=(0|this.words[i+r])+a;var c=(0|e.words[i])*t;a=((o-=67108863&c)>>26)-(c/67108864|0),this.words[i+r]=67108863&o}for(;i<this.length-r;i++)a=(o=(0|this.words[i+r])+a)>>26,this.words[i+r]=67108863&o;if(0===a)return this._strip();for(n(-1===a),a=0,i=0;i<this.length;i++)a=(o=-(0|this.words[i])+a)>>26,this.words[i]=67108863&o;return this.negative=1,this._strip()},i.prototype._wordDiv=function(e,t){var n=(this.length,e.length),r=this.clone(),o=e,s=0|o.words[o.length-1];0!=(n=26-this._countBits(s))&&(o=o.ushln(n),r.iushln(n),s=0|o.words[o.length-1]);var a,c=r.length-o.length;if("mod"!==t){(a=new i(null)).length=c+1,a.words=new Array(a.length);for(var u=0;u<a.length;u++)a.words[u]=0}var l=r.clone()._ishlnsubmul(o,1,c);0===l.negative&&(r=l,a&&(a.words[c]=1));for(var h=c-1;h>=0;h--){var d=67108864*(0|r.words[o.length+h])+(0|r.words[o.length+h-1]);for(d=Math.min(d/s|0,67108863),r._ishlnsubmul(o,d,h);0!==r.negative;)d--,r.negative=0,r._ishlnsubmul(o,1,h),r.isZero()||(r.negative^=1);a&&(a.words[h]=d)}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&&(o=a.div.neg()),"div"!==t&&(s=a.mod.neg(),r&&0!==s.negative&&s.iadd(e)),{div:o,mod:s}):0===this.negative&&0!==e.negative?(a=this.divmod(e.neg(),t),"mod"!==t&&(o=a.div.neg()),{div:o,mod:a.mod}):0!==(this.negative&e.negative)?(a=this.neg().divmod(e.neg(),t),"div"!==t&&(s=a.mod.neg(),r&&0!==s.negative&&s.isub(e)),{div:a.div,mod:s}):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 o,s,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=0!==t.div.negative?t.mod.isub(e):t.mod,r=e.ushrn(1),i=e.andln(1),o=n.cmp(r);return o<0||1===i&&0===o?t.div:0!==t.div.negative?t.div.isubn(1):t.div.iaddn(1)},i.prototype.modrn=function(e){var t=e<0;t&&(e=-e),n(e<=67108863);for(var r=(1<<26)%e,i=0,o=this.length-1;o>=0;o--)i=(r*i+(0|this.words[o]))%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 o=(0|this.words[i])+67108864*r;this.words[i]=o/e|0,r=o%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 o=new i(1),s=new i(0),a=new i(0),c=new i(1),u=0;t.isEven()&&r.isEven();)t.iushrn(1),r.iushrn(1),++u;for(var l=r.clone(),h=t.clone();!t.isZero();){for(var d=0,f=1;0===(t.words[0]&f)&&d<26;++d,f<<=1);if(d>0)for(t.iushrn(d);d-- >0;)(o.isOdd()||s.isOdd())&&(o.iadd(l),s.isub(h)),o.iushrn(1),s.iushrn(1);for(var g=0,p=1;0===(r.words[0]&p)&&g<26;++g,p<<=1);if(g>0)for(r.iushrn(g);g-- >0;)(a.isOdd()||c.isOdd())&&(a.iadd(l),c.isub(h)),a.iushrn(1),c.iushrn(1);t.cmp(r)>=0?(t.isub(r),o.isub(a),s.isub(c)):(r.isub(t),a.isub(o),c.isub(s))}return{a:a,b:c,gcd:r.iushln(u)}},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 o,s=new i(1),a=new i(0),c=r.clone();t.cmpn(1)>0&&r.cmpn(1)>0;){for(var u=0,l=1;0===(t.words[0]&l)&&u<26;++u,l<<=1);if(u>0)for(t.iushrn(u);u-- >0;)s.isOdd()&&s.iadd(c),s.iushrn(1);for(var h=0,d=1;0===(r.words[0]&d)&&h<26;++h,d<<=1);if(h>0)for(r.iushrn(h);h-- >0;)a.isOdd()&&a.iadd(c),a.iushrn(1);t.cmp(r)>=0?(t.isub(r),s.isub(a)):(r.isub(t),a.isub(s))}return(o=0===t.cmpn(1)?s:a).cmpn(0)<0&&o.iadd(e),o},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 o=t;t=n,n=o}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 o=i,s=r;0!==o&&s<this.length;s++){var a=0|this.words[s];o=(a+=o)>>>26,a&=67108863,this.words[s]=a}return 0!==o&&(this.words[s]=o,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 T(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 w={k256:null,p224:null,p192:null,p25519:null};function b(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 k(){b.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function v(){b.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function S(){b.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function A(){b.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function T(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 E(e){T.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)}b.prototype._tmp=function(){var e=new i(null);return e.words=new Array(Math.ceil(this.n/13)),e},b.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},b.prototype.split=function(e,t){e.iushrn(this.n,0,t)},b.prototype.imulK=function(e){return e.imul(this.k)},r(k,b),k.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 o=e.words[9];for(t.words[t.length++]=o&n,i=10;i<e.length;i++){var s=0|e.words[i];e.words[i-10]=(s&n)<<4|o>>>22,o=s}o>>>=22,e.words[i-10]=o,0===o&&e.length>10?e.length-=10:e.length-=9},k.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(v,b),r(S,b),r(A,b),A.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(w[e])return w[e];var t;if("k256"===e)t=new k;else if("p224"===e)t=new v;else if("p192"===e)t=new S;else{if("p25519"!==e)throw new Error("Unknown prime "+e);t=new A}return w[e]=t,t},T.prototype._verify1=function(e){n(0===e.negative,"red works only with positives"),n(e.red,"red works only with red numbers")},T.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")},T.prototype.imod=function(e){return this.prime?this.prime.ireduce(e)._forceRed(this):(u(e,e.umod(this.m)._forceRed(this)),e)},T.prototype.neg=function(e){return e.isZero()?e.clone():this.m.sub(e)._forceRed(this)},T.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)},T.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},T.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)},T.prototype.isub=function(e,t){this._verify2(e,t);var n=e.isub(t);return n.cmpn(0)<0&&n.iadd(this.m),n},T.prototype.shl=function(e,t){return this._verify1(e),this.imod(e.ushln(t))},T.prototype.imul=function(e,t){return this._verify2(e,t),this.imod(e.imul(t))},T.prototype.mul=function(e,t){return this._verify2(e,t),this.imod(e.mul(t))},T.prototype.isqr=function(e){return this.imul(e,e.clone())},T.prototype.sqr=function(e){return this.mul(e,e)},T.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 o=this.m.subn(1),s=0;!o.isZero()&&0===o.andln(1);)s++,o.iushrn(1);n(!o.isZero());var a=new i(1).toRed(this),c=a.redNeg(),u=this.m.subn(1).iushrn(1),l=this.m.bitLength();for(l=new i(2*l*l).toRed(this);0!==this.pow(l,u).cmp(c);)l.redIAdd(c);for(var h=this.pow(l,o),d=this.pow(e,o.addn(1).iushrn(1)),f=this.pow(e,o),g=s;0!==f.cmp(a);){for(var p=f,m=0;0!==p.cmp(a);m++)p=p.redSqr();n(m<g);var y=this.pow(h,new i(1).iushln(g-m-1));d=d.redMul(y),h=y.redSqr(),f=f.redMul(h),g=m}return d},T.prototype.invm=function(e){var t=e._invmp(this.m);return 0!==t.negative?(t.negative=0,this.imod(t).redNeg()):this.imod(t)},T.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 o=n[0],s=0,a=0,c=t.bitLength()%26;for(0===c&&(c=26),r=t.length-1;r>=0;r--){for(var u=t.words[r],l=c-1;l>=0;l--){var h=u>>l&1;o!==n[0]&&(o=this.sqr(o)),0!==h||0!==s?(s<<=1,s|=h,(4===++a||0===r&&0===l)&&(o=this.mul(o,n[s]),a=0,s=0)):a=0}c=26}return o},T.prototype.convertTo=function(e){var t=e.umod(this.m);return t===e?t.clone():t},T.prototype.convertFrom=function(e){var t=e.clone();return t.red=null,t},i.mont=function(e){return new E(e)},r(E,T),E.prototype.convertTo=function(e){return this.imod(e.ushln(this.shift))},E.prototype.convertFrom=function(e){var t=this.imod(e.mul(this.rinv));return t.red=null,t},E.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),o=i;return i.cmp(this.m)>=0?o=i.isub(this.m):i.cmpn(0)<0&&(o=i.iadd(this.m)),o._forceRed(this)},E.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),o=n.isub(r).iushrn(this.shift),s=o;return o.cmp(this.m)>=0?s=o.isub(this.m):o.cmpn(0)<0&&(s=o.iadd(this.m)),s._forceRed(this)},E.prototype.invm=function(e){return this.imod(e._invmp(this.m).mul(this.r2))._forceRed(this)}}(bg,vg)),bg.exports}var Ag,Tg,Eg,Ig,xg,Cg,Ng=Mc(Sg()),Bg={exports:{}},_g={};function Pg(){return Ag||(Ag=1,function(e){var t=$h(),n=zh(),r="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;e.Buffer=s,e.SlowBuffer=function(e){+e!=e&&(e=0);return s.alloc(+e)},e.INSPECT_MAX_BYTES=50;var i=2147483647;function o(e){if(e>i)throw new RangeError('The value "'+e+'" is invalid for option "size"');var t=new Uint8Array(e);return Object.setPrototypeOf(t,s.prototype),t}function s(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 u(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(!s.isEncoding(t))throw new TypeError("Unknown encoding: "+t);var n=0|f(e,t),r=o(n),i=r.write(e,t);i!==n&&(r=r.slice(0,i));return r}(e,t);if(ArrayBuffer.isView(e))return function(e){if(F(e,Uint8Array)){var t=new Uint8Array(e);return h(t.buffer,t.byteOffset,t.byteLength)}return l(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(F(e,ArrayBuffer)||e&&F(e.buffer,ArrayBuffer))return h(e,t,n);if("undefined"!=typeof SharedArrayBuffer&&(F(e,SharedArrayBuffer)||e&&F(e.buffer,SharedArrayBuffer)))return h(e,t,n);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');var r=e.valueOf&&e.valueOf();if(null!=r&&r!==e)return s.from(r,t,n);var i=function(e){if(s.isBuffer(e)){var t=0|d(e.length),n=o(t);return 0===n.length||e.copy(n,0,0,t),n}if(void 0!==e.length)return"number"!=typeof e.length||$(e.length)?o(0):l(e);if("Buffer"===e.type&&Array.isArray(e.data))return l(e.data)}(e);if(i)return i;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return s.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 u(e){return c(e),o(e<0?0:0|d(e))}function l(e){for(var t=e.length<0?0:0|d(e.length),n=o(t),r=0;r<t;r+=1)n[r]=255&e[r];return n}function h(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');var 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,s.prototype),r}function d(e){if(e>=i)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i.toString(16)+" bytes");return 0|e}function f(e,t){if(s.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||F(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);var n=e.length,r=arguments.length>2&&!0===arguments[2];if(!r&&0===n)return 0;for(var i=!1;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":return O(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return U(e).length;default:if(i)return r?-1:O(e).length;t=(""+t).toLowerCase(),i=!0}}function g(e,t,n){var 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 T(this,t,n);case"ascii":return I(this,t,n);case"latin1":case"binary":return x(this,t,n);case"base64":return A(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return N(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function p(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function m(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),$(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=s.from(t,r)),s.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){var o,s=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;s=2,a/=2,c/=2,n/=2}function u(e,t){return 1===s?e[t]:e.readUInt16BE(t*s)}if(i){var l=-1;for(o=n;o<a;o++)if(u(e,o)===u(t,-1===l?0:o-l)){if(-1===l&&(l=o),o-l+1===c)return l*s}else-1!==l&&(o-=o-l),l=-1}else for(n+c>a&&(n=a-c),o=n;o>=0;o--){for(var h=!0,d=0;d<c;d++)if(u(e,o+d)!==u(t,d)){h=!1;break}if(h)return o}return-1}function w(e,t,n,r){n=Number(n)||0;var i=e.length-n;r?(r=Number(r))>i&&(r=i):r=i;var o=t.length;r>o/2&&(r=o/2);for(var s=0;s<r;++s){var a=parseInt(t.substr(2*s,2),16);if($(a))return s;e[n+s]=a}return s}function b(e,t,n,r){return M(O(t,e.length-n),e,n,r)}function k(e,t,n,r){return M(function(e){for(var t=[],n=0;n<e.length;++n)t.push(255&e.charCodeAt(n));return t}(t),e,n,r)}function v(e,t,n,r){return M(U(t),e,n,r)}function S(e,t,n,r){return M(function(e,t){for(var n,r,i,o=[],s=0;s<e.length&&!((t-=2)<0);++s)r=(n=e.charCodeAt(s))>>8,i=n%256,o.push(i),o.push(r);return o}(t,e.length-n),e,n,r)}function A(e,n,r){return 0===n&&r===e.length?t.fromByteArray(e):t.fromByteArray(e.slice(n,r))}function T(e,t,n){n=Math.min(e.length,n);for(var r=[],i=t;i<n;){var o,s,a,c,u=e[i],l=null,h=u>239?4:u>223?3:u>191?2:1;if(i+h<=n)switch(h){case 1:u<128&&(l=u);break;case 2:128==(192&(o=e[i+1]))&&(c=(31&u)<<6|63&o)>127&&(l=c);break;case 3:o=e[i+1],s=e[i+2],128==(192&o)&&128==(192&s)&&(c=(15&u)<<12|(63&o)<<6|63&s)>2047&&(c<55296||c>57343)&&(l=c);break;case 4:o=e[i+1],s=e[i+2],a=e[i+3],128==(192&o)&&128==(192&s)&&128==(192&a)&&(c=(15&u)<<18|(63&o)<<12|(63&s)<<6|63&a)>65535&&c<1114112&&(l=c)}null===l?(l=65533,h=1):l>65535&&(l-=65536,r.push(l>>>10&1023|55296),l=56320|1023&l),r.push(l),i+=h}return function(e){var t=e.length;if(t<=E)return String.fromCharCode.apply(String,e);var n="",r=0;for(;r<t;)n+=String.fromCharCode.apply(String,e.slice(r,r+=E));return n}(r)}e.kMaxLength=i,s.TYPED_ARRAY_SUPPORT=function(){try{var 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}}(),!s.TYPED_ARRAY_SUPPORT&&"undefined"!=typeof console&&console.error,Object.defineProperty(s.prototype,"parent",{enumerable:!0,get:function(){if(s.isBuffer(this))return this.buffer}}),Object.defineProperty(s.prototype,"offset",{enumerable:!0,get:function(){if(s.isBuffer(this))return this.byteOffset}}),s.poolSize=8192,s.from=function(e,t,n){return a(e,t,n)},Object.setPrototypeOf(s.prototype,Uint8Array.prototype),Object.setPrototypeOf(s,Uint8Array),s.alloc=function(e,t,n){return function(e,t,n){return c(e),e<=0?o(e):void 0!==t?"string"==typeof n?o(e).fill(t,n):o(e).fill(t):o(e)}(e,t,n)},s.allocUnsafe=function(e){return u(e)},s.allocUnsafeSlow=function(e){return u(e)},s.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==s.prototype},s.compare=function(e,t){if(F(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),F(t,Uint8Array)&&(t=s.from(t,t.offset,t.byteLength)),!s.isBuffer(e)||!s.isBuffer(t))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;for(var n=e.length,r=t.length,i=0,o=Math.min(n,r);i<o;++i)if(e[i]!==t[i]){n=e[i],r=t[i];break}return n<r?-1:r<n?1:0},s.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}},s.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return s.alloc(0);var n;if(void 0===t)for(t=0,n=0;n<e.length;++n)t+=e[n].length;var r=s.allocUnsafe(t),i=0;for(n=0;n<e.length;++n){var o=e[n];if(F(o,Uint8Array))i+o.length>r.length?s.from(o).copy(r,i):Uint8Array.prototype.set.call(r,o,i);else{if(!s.isBuffer(o))throw new TypeError('"list" argument must be an Array of Buffers');o.copy(r,i)}i+=o.length}return r},s.byteLength=f,s.prototype._isBuffer=!0,s.prototype.swap16=function(){var e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var t=0;t<e;t+=2)p(this,t,t+1);return this},s.prototype.swap32=function(){var e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var t=0;t<e;t+=4)p(this,t,t+3),p(this,t+1,t+2);return this},s.prototype.swap64=function(){var e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var t=0;t<e;t+=8)p(this,t,t+7),p(this,t+1,t+6),p(this,t+2,t+5),p(this,t+3,t+4);return this},s.prototype.toString=function(){var e=this.length;return 0===e?"":0===arguments.length?T(this,0,e):g.apply(this,arguments)},s.prototype.toLocaleString=s.prototype.toString,s.prototype.equals=function(e){if(!s.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===s.compare(this,e)},s.prototype.inspect=function(){var t="",n=e.INSPECT_MAX_BYTES;return t=this.toString("hex",0,n).replace(/(.{2})/g,"$1 ").trim(),this.length>n&&(t+=" ... "),"<Buffer "+t+">"},r&&(s.prototype[r]=s.prototype.inspect),s.prototype.compare=function(e,t,n,r,i){if(F(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),!s.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;for(var o=(i>>>=0)-(r>>>=0),a=(n>>>=0)-(t>>>=0),c=Math.min(o,a),u=this.slice(r,i),l=e.slice(t,n),h=0;h<c;++h)if(u[h]!==l[h]){o=u[h],a=l[h];break}return o<a?-1:a<o?1:0},s.prototype.includes=function(e,t,n){return-1!==this.indexOf(e,t,n)},s.prototype.indexOf=function(e,t,n){return m(this,e,t,n,!0)},s.prototype.lastIndexOf=function(e,t,n){return m(this,e,t,n,!1)},s.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)}var 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");for(var o=!1;;)switch(r){case"hex":return w(this,e,t,n);case"utf8":case"utf-8":return b(this,e,t,n);case"ascii":case"latin1":case"binary":return k(this,e,t,n);case"base64":return v(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return S(this,e,t,n);default:if(o)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),o=!0}},s.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var E=4096;function I(e,t,n){var r="";n=Math.min(e.length,n);for(var i=t;i<n;++i)r+=String.fromCharCode(127&e[i]);return r}function x(e,t,n){var r="";n=Math.min(e.length,n);for(var i=t;i<n;++i)r+=String.fromCharCode(e[i]);return r}function C(e,t,n){var r=e.length;(!t||t<0)&&(t=0),(!n||n<0||n>r)&&(n=r);for(var i="",o=t;o<n;++o)i+=q[e[o]];return i}function N(e,t,n){for(var r=e.slice(t,n),i="",o=0;o<r.length-1;o+=2)i+=String.fromCharCode(r[o]+256*r[o+1]);return i}function B(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 _(e,t,n,r,i,o){if(!s.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||t<o)throw new RangeError('"value" argument is out of bounds');if(n+r>e.length)throw new RangeError("Index out of range")}function P(e,t,n,r,i,o){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function R(e,t,r,i,o){return t=+t,r>>>=0,o||P(e,0,r,4),n.write(e,t,r,i,23,4),r+4}function D(e,t,r,i,o){return t=+t,r>>>=0,o||P(e,0,r,8),n.write(e,t,r,i,52,8),r+8}s.prototype.slice=function(e,t){var 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);var r=this.subarray(e,t);return Object.setPrototypeOf(r,s.prototype),r},s.prototype.readUintLE=s.prototype.readUIntLE=function(e,t,n){e>>>=0,t>>>=0,n||B(e,t,this.length);for(var r=this[e],i=1,o=0;++o<t&&(i*=256);)r+=this[e+o]*i;return r},s.prototype.readUintBE=s.prototype.readUIntBE=function(e,t,n){e>>>=0,t>>>=0,n||B(e,t,this.length);for(var r=this[e+--t],i=1;t>0&&(i*=256);)r+=this[e+--t]*i;return r},s.prototype.readUint8=s.prototype.readUInt8=function(e,t){return e>>>=0,t||B(e,1,this.length),this[e]},s.prototype.readUint16LE=s.prototype.readUInt16LE=function(e,t){return e>>>=0,t||B(e,2,this.length),this[e]|this[e+1]<<8},s.prototype.readUint16BE=s.prototype.readUInt16BE=function(e,t){return e>>>=0,t||B(e,2,this.length),this[e]<<8|this[e+1]},s.prototype.readUint32LE=s.prototype.readUInt32LE=function(e,t){return e>>>=0,t||B(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},s.prototype.readUint32BE=s.prototype.readUInt32BE=function(e,t){return e>>>=0,t||B(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},s.prototype.readIntLE=function(e,t,n){e>>>=0,t>>>=0,n||B(e,t,this.length);for(var r=this[e],i=1,o=0;++o<t&&(i*=256);)r+=this[e+o]*i;return r>=(i*=128)&&(r-=Math.pow(2,8*t)),r},s.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||B(e,t,this.length);for(var r=t,i=1,o=this[e+--r];r>0&&(i*=256);)o+=this[e+--r]*i;return o>=(i*=128)&&(o-=Math.pow(2,8*t)),o},s.prototype.readInt8=function(e,t){return e>>>=0,t||B(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},s.prototype.readInt16LE=function(e,t){e>>>=0,t||B(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},s.prototype.readInt16BE=function(e,t){e>>>=0,t||B(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},s.prototype.readInt32LE=function(e,t){return e>>>=0,t||B(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},s.prototype.readInt32BE=function(e,t){return e>>>=0,t||B(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},s.prototype.readFloatLE=function(e,t){return e>>>=0,t||B(e,4,this.length),n.read(this,e,!0,23,4)},s.prototype.readFloatBE=function(e,t){return e>>>=0,t||B(e,4,this.length),n.read(this,e,!1,23,4)},s.prototype.readDoubleLE=function(e,t){return e>>>=0,t||B(e,8,this.length),n.read(this,e,!0,52,8)},s.prototype.readDoubleBE=function(e,t){return e>>>=0,t||B(e,8,this.length),n.read(this,e,!1,52,8)},s.prototype.writeUintLE=s.prototype.writeUIntLE=function(e,t,n,r){(e=+e,t>>>=0,n>>>=0,r)||_(this,e,t,n,Math.pow(2,8*n)-1,0);var i=1,o=0;for(this[t]=255&e;++o<n&&(i*=256);)this[t+o]=e/i&255;return t+n},s.prototype.writeUintBE=s.prototype.writeUIntBE=function(e,t,n,r){(e=+e,t>>>=0,n>>>=0,r)||_(this,e,t,n,Math.pow(2,8*n)-1,0);var i=n-1,o=1;for(this[t+i]=255&e;--i>=0&&(o*=256);)this[t+i]=e/o&255;return t+n},s.prototype.writeUint8=s.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||_(this,e,t,1,255,0),this[t]=255&e,t+1},s.prototype.writeUint16LE=s.prototype.writeUInt16LE=function(e,t,n){return e=+e,t>>>=0,n||_(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},s.prototype.writeUint16BE=s.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||_(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},s.prototype.writeUint32LE=s.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||_(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},s.prototype.writeUint32BE=s.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||_(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},s.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t>>>=0,!r){var i=Math.pow(2,8*n-1);_(this,e,t,n,i-1,-i)}var o=0,s=1,a=0;for(this[t]=255&e;++o<n&&(s*=256);)e<0&&0===a&&0!==this[t+o-1]&&(a=1),this[t+o]=(e/s|0)-a&255;return t+n},s.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t>>>=0,!r){var i=Math.pow(2,8*n-1);_(this,e,t,n,i-1,-i)}var o=n-1,s=1,a=0;for(this[t+o]=255&e;--o>=0&&(s*=256);)e<0&&0===a&&0!==this[t+o+1]&&(a=1),this[t+o]=(e/s|0)-a&255;return t+n},s.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||_(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},s.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||_(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},s.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||_(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},s.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||_(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},s.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||_(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},s.prototype.writeFloatLE=function(e,t,n){return R(this,e,t,!0,n)},s.prototype.writeFloatBE=function(e,t,n){return R(this,e,t,!1,n)},s.prototype.writeDoubleLE=function(e,t,n){return D(this,e,t,!0,n)},s.prototype.writeDoubleBE=function(e,t,n){return D(this,e,t,!1,n)},s.prototype.copy=function(e,t,n,r){if(!s.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);var 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},s.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&&!s.isEncoding(r))throw new TypeError("Unknown encoding: "+r);if(1===e.length){var i=e.charCodeAt(0);("utf8"===r&&i<128||"latin1"===r)&&(e=i)}}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;var o;if(t>>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(o=t;o<n;++o)this[o]=e;else{var a=s.isBuffer(e)?e:s.from(e,r),c=a.length;if(0===c)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(o=0;o<n-t;++o)this[o+t]=a[o%c]}return this};var L=/[^+/0-9A-Za-z-_]/g;function O(e,t){var n;t=t||1/0;for(var r=e.length,i=null,o=[],s=0;s<r;++s){if((n=e.charCodeAt(s))>55295&&n<57344){if(!i){if(n>56319){(t-=3)>-1&&o.push(239,191,189);continue}if(s+1===r){(t-=3)>-1&&o.push(239,191,189);continue}i=n;continue}if(n<56320){(t-=3)>-1&&o.push(239,191,189),i=n;continue}n=65536+(i-55296<<10|n-56320)}else i&&(t-=3)>-1&&o.push(239,191,189);if(i=null,n<128){if((t-=1)<0)break;o.push(n)}else if(n<2048){if((t-=2)<0)break;o.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;o.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;o.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return o}function U(e){return t.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(L,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function M(e,t,n,r){for(var i=0;i<r&&!(i+n>=t.length||i>=e.length);++i)t[i+n]=e[i];return i}function F(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function $(e){return e!=e}var q=function(){for(var e="0123456789abcdef",t=new Array(256),n=0;n<16;++n)for(var r=16*n,i=0;i<16;++i)t[r+i]=e[n]+e[i];return t}()}(_g)),_g}function Rg(){return Tg||(Tg=1,function(e,t){var n=Pg(),r=n.Buffer;function i(e,t){for(var n in e)t[n]=e[n]}function o(e,t,n){return r(e,t,n)}r.from&&r.alloc&&r.allocUnsafe&&r.allocUnsafeSlow?e.exports=n:(i(n,t),t.Buffer=o),i(r,o),o.from=function(e,t,n){if("number"==typeof e)throw new TypeError("Argument must not be a number");return r(e,t,n)},o.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},o.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return r(e)},o.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return n.SlowBuffer(e)}}(Bg,Bg.exports)),Bg.exports}var Dg=function(){if(Cg)return xg;Cg=1;var e=function(){if(Ig)return Eg;Ig=1;var e=Rg().Buffer;return Eg=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 o=t.charAt(i),s=o.charCodeAt(0);if(255!==n[s])throw new TypeError(o+" is ambiguous");n[s]=i}var a=t.length,c=t.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function h(t){if("string"!=typeof t)throw new TypeError("Expected String");if(0===t.length)return e.alloc(0);for(var r=0,i=0,o=0;t[r]===c;)i++,r++;for(var s=(t.length-r)*u+1>>>0,l=new Uint8Array(s);r<t.length;){var h=t.charCodeAt(r);if(h>255)return;var d=n[h];if(255===d)return;for(var f=0,g=s-1;(0!==d||f<o)&&-1!==g;g--,f++)d+=a*l[g]>>>0,l[g]=d%256>>>0,d=d/256>>>0;if(0!==d)throw new Error("Non-zero carry");o=f,r++}for(var p=s-o;p!==s&&0===l[p];)p++;var m=e.allocUnsafe(i+(s-p));m.fill(0,0,i);for(var y=i;p!==s;)m[y++]=l[p++];return m}return{encode:function(n){if((Array.isArray(n)||n instanceof Uint8Array)&&(n=e.from(n)),!e.isBuffer(n))throw new TypeError("Expected Buffer");if(0===n.length)return"";for(var r=0,i=0,o=0,s=n.length;o!==s&&0===n[o];)o++,r++;for(var u=(s-o)*l+1>>>0,h=new Uint8Array(u);o!==s;){for(var d=n[o],f=0,g=u-1;(0!==d||f<i)&&-1!==g;g--,f++)d+=256*h[g]>>>0,h[g]=d%a>>>0,d=d/a>>>0;if(0!==d)throw new Error("Non-zero carry");i=f,o++}for(var p=u-i;p!==u&&0===h[p];)p++;for(var m=c.repeat(r);p<u;++p)m+=t.charAt(h[p]);return m},decodeUnsafe:h,decode:function(e){var t=h(e);if(t)return t;throw new Error("Non-base"+a+" character")}}},Eg}();return xg=e("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")}(),Lg=Mc(Dg);const Og=jd;var Ug,Mg,Fg,$g,qg={};function Kg(){if($g)return Fg;$g=1;var e=function(){if(Mg)return Ug;Mg=1;var e=Rg().Buffer;return Ug=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 o=t.charAt(i),s=o.charCodeAt(0);if(255!==n[s])throw new TypeError(o+" is ambiguous");n[s]=i}var a=t.length,c=t.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function h(t){if("string"!=typeof t)throw new TypeError("Expected String");if(0===t.length)return e.alloc(0);for(var r=0,i=0,o=0;t[r]===c;)i++,r++;for(var s=(t.length-r)*u+1>>>0,l=new Uint8Array(s);r<t.length;){var h=t.charCodeAt(r);if(h>255)return;var d=n[h];if(255===d)return;for(var f=0,g=s-1;(0!==d||f<o)&&-1!==g;g--,f++)d+=a*l[g]>>>0,l[g]=d%256>>>0,d=d/256>>>0;if(0!==d)throw new Error("Non-zero carry");o=f,r++}for(var p=s-o;p!==s&&0===l[p];)p++;var m=e.allocUnsafe(i+(s-p));m.fill(0,0,i);for(var y=i;p!==s;)m[y++]=l[p++];return m}return{encode:function(n){if((Array.isArray(n)||n instanceof Uint8Array)&&(n=e.from(n)),!e.isBuffer(n))throw new TypeError("Expected Buffer");if(0===n.length)return"";for(var r=0,i=0,o=0,s=n.length;o!==s&&0===n[o];)o++,r++;for(var u=(s-o)*l+1>>>0,h=new Uint8Array(u);o!==s;){for(var d=n[o],f=0,g=u-1;(0!==d||f<i)&&-1!==g;g--,f++)d+=256*h[g]>>>0,h[g]=d%a>>>0,d=d/a>>>0;if(0!==d)throw new Error("Non-zero carry");i=f,o++}for(var p=u-i;p!==u&&0===h[p];)p++;for(var m=c.repeat(r);p<u;++p)m+=t.charAt(h[p]);return m},decodeUnsafe:h,decode:function(e){var t=h(e);if(t)return t;throw new Error("Non-base"+a+" character")}}},Ug}();return Fg=e("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")}function Gg(e,t,n){return t<=e&&e<=n}function zg(e){if(void 0===e)return{};if(e===Object(e))return e;throw TypeError("Could not convert argument to dictionary")}function Wg(e){this.tokens=[].slice.call(e)}Wg.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 Hg=-1;function jg(e,t){if(e)throw TypeError("Decoder error");return t||65533}var Vg="utf-8";function Xg(e,t){if(!(this instanceof Xg))return new Xg(e,t);if((e=void 0!==e?String(e).toLowerCase():Vg)!==Vg)throw new Error("Encoding not supported. Only utf-8 is supported");t=zg(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 Qg(e,t){if(!(this instanceof Qg))return new Qg(e,t);if((e=void 0!==e?String(e).toLowerCase():Vg)!==Vg)throw new Error("Encoding not supported. Only utf-8 is supported");t=zg(t),this._streaming=!1,this._encoder=null,this._options={fatal:Boolean(t.fatal)},Object.defineProperty(this,"encoding",{value:"utf-8"})}function Jg(e){var t=e.fatal,n=0,r=0,i=0,o=128,s=191;this.handler=function(e,a){if(-1===a&&0!==i)return i=0,jg(t);if(-1===a)return Hg;if(0===i){if(Gg(a,0,127))return a;if(Gg(a,194,223))i=1,n=a-192;else if(Gg(a,224,239))224===a&&(o=160),237===a&&(s=159),i=2,n=a-224;else{if(!Gg(a,240,244))return jg(t);240===a&&(o=144),244===a&&(s=143),i=3,n=a-240}return n<<=6*i,null}if(!Gg(a,o,s))return n=i=r=0,o=128,s=191,e.prepend(a),jg(t);if(o=128,s=191,n+=a-128<<6*(i-(r+=1)),r!==i)return null;var c=n;return n=i=r=0,c}}function Yg(e){e.fatal,this.handler=function(e,t){if(-1===t)return Hg;if(Gg(t,0,127))return t;var n,r;Gg(t,128,2047)?(n=1,r=192):Gg(t,2048,65535)?(n=2,r=224):Gg(t,65536,1114111)&&(n=3,r=240);for(var i=[(t>>6*n)+r];n>0;){var o=t>>6*(n-1);i.push(128|63&o),n-=1}return i}}Xg.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=zg(t),this._streaming||(this._decoder=new Jg({fatal:this._fatal}),this._BOMseen=!1),this._streaming=Boolean(t.stream);for(var r,i=new Wg(n),o=[];!i.endOfStream()&&(r=this._decoder.handler(i,i.read()))!==Hg;)null!==r&&(Array.isArray(r)?o.push.apply(o,r):o.push(r));if(!this._streaming){do{if((r=this._decoder.handler(i,i.read()))===Hg)break;null!==r&&(Array.isArray(r)?o.push.apply(o,r):o.push(r))}while(!i.endOfStream());this._decoder=null}return o.length&&(-1===["utf-8"].indexOf(this.encoding)||this._ignoreBOM||this._BOMseen||(65279===o[0]?(this._BOMseen=!0,o.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}(o)}},Qg.prototype={encode:function(e,t){e=e?String(e):"",t=zg(t),this._streaming||(this._encoder=new Yg(this._options)),this._streaming=Boolean(t.stream);for(var n,r=[],i=new Wg(function(e){for(var t=String(e),n=t.length,r=0,i=[];r<n;){var o=t.charCodeAt(r);if(o<55296||o>57343)i.push(o);else if(56320<=o&&o<=57343)i.push(65533);else if(55296<=o&&o<=56319)if(r===n-1)i.push(65533);else{var s=e.charCodeAt(r+1);if(56320<=s&&s<=57343){var a=1023&o,c=1023&s;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()))!==Hg;)Array.isArray(n)?r.push.apply(r,n):r.push(n);if(!this._streaming){for(;(n=this._encoder.handler(i,i.read()))!==Hg;)Array.isArray(n)?r.push.apply(r,n):r.push(n);this._encoder=null}return new Uint8Array(r)}};var Zg,ep=Fc(Object.freeze({__proto__:null,TextDecoder:Xg,TextEncoder:Qg}));var tp,np,rp=function(){if(Zg)return qg;Zg=1;var e=qg&&qg.__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=qg&&qg.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=qg&&qg.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},r=qg&&qg.__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=qg&&qg.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(qg,"__esModule",{value:!0}),qg.deserializeUnchecked=qg.deserialize=qg.serialize=qg.BinaryReader=qg.BinaryWriter=qg.BorshError=qg.baseDecode=qg.baseEncode=void 0;const o=i(Sg()),s=i(Kg()),a=r(ep),c=new("function"!=typeof TextDecoder?a.TextDecoder:TextDecoder)("utf-8",{fatal:!0});qg.baseEncode=function(e){return"string"==typeof e&&(e=Buffer.from(e,"utf8")),s.default.encode(Buffer.from(e))},qg.baseDecode=function(e){return Buffer.from(s.default.decode(e))};const u=1024;class l 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(".")}}qg.BorshError=l;class h{constructor(){this.buf=Buffer.alloc(u),this.length=0}maybeResize(){this.buf.length<16+this.length&&(this.buf=Buffer.concat([this.buf,Buffer.alloc(u)]))}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 o.default(e).toArray("le",8)))}writeU128(e){this.maybeResize(),this.writeBuffer(Buffer.from(new o.default(e).toArray("le",16)))}writeU256(e){this.maybeResize(),this.writeBuffer(Buffer.from(new o.default(e).toArray("le",32)))}writeU512(e){this.maybeResize(),this.writeBuffer(Buffer.from(new o.default(e).toArray("le",64)))}writeBuffer(e){this.buf=Buffer.concat([Buffer.from(this.buf.subarray(0,this.length)),e,Buffer.alloc(u)]),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 d(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 l("Reached the end of buffer when deserializing")}throw e}}}qg.BinaryWriter=h;class f{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 o.default(e,"le")}readU128(){const e=this.readBuffer(16);return new o.default(e,"le")}readU256(){const e=this.readBuffer(32);return new o.default(e,"le")}readU512(){const e=this.readBuffer(64);return new o.default(e,"le")}readBuffer(e){if(this.offset+e>this.buf.length)throw new l(`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 l(`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 g(e){return e.charAt(0).toUpperCase()+e.slice(1)}function p(e,t,n,r,i){try{if("string"==typeof r)i[`write${g(r)}`](n);else if(r instanceof Array)if("number"==typeof r[0]){if(n.length!==r[0])throw new l(`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 l(`Expecting byte array of length ${r[1]}, but got ${n.length} bytes`);for(let t=0;t<r[1];t++)p(e,null,n[t],r[0],i)}else i.writeArray(n,n=>{p(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),p(e,t,n,r.type,i));break;case"map":i.writeU32(n.size),n.forEach((n,o)=>{p(e,t,o,r.key,i),p(e,t,n,r.value,i)});break;default:throw new l(`FieldType ${r} unrecognized`)}else m(e,n,i)}catch(e){throw e instanceof l&&e.addToFieldPath(t),e}}function m(e,t,n){if("function"==typeof t.borshSerialize)return void t.borshSerialize(n);const r=e.get(t.constructor);if(!r)throw new l(`Class ${t.constructor.name} is missing in schema`);if("struct"===r.kind)r.fields.map(([r,i])=>{p(e,r,t[r],i,n)});else{if("enum"!==r.kind)throw new l(`Unexpected schema kind: ${r.kind} for ${t.constructor.name}`);{const i=t[r.field];for(let o=0;o<r.values.length;++o){const[s,a]=r.values[o];if(s===i){n.writeU8(o),p(e,s,t[s],a,n);break}}}}}function y(e,t,n,r){try{if("string"==typeof n)return r[`read${g(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 o=r.readU32();for(let s=0;s<o;s++){const o=y(e,t,n.key,r),s=y(e,t,n.value,r);i.set(o,s)}return i}return w(e,n,r)}catch(e){throw e instanceof l&&e.addToFieldPath(t),e}}function w(e,t,n){if("function"==typeof t.borshDeserialize)return t.borshDeserialize(n);const r=e.get(t);if(!r)throw new l(`Class ${t.name} is missing in schema`);if("struct"===r.kind){const r={};for(const[i,o]of e.get(t).fields)r[i]=y(e,i,o,n);return new t(r)}if("enum"===r.kind){const i=n.readU8();if(i>=r.values.length)throw new l(`Enum index: ${i} is out of range`);const[o,s]=r.values[i],a=y(e,o,s,n);return new t({[o]:a})}throw new l(`Unexpected schema kind: ${r.kind} for ${t.constructor.name}`)}return n([d],f.prototype,"readU8",null),n([d],f.prototype,"readU16",null),n([d],f.prototype,"readU32",null),n([d],f.prototype,"readU64",null),n([d],f.prototype,"readU128",null),n([d],f.prototype,"readU256",null),n([d],f.prototype,"readU512",null),n([d],f.prototype,"readString",null),n([d],f.prototype,"readFixedArray",null),n([d],f.prototype,"readArray",null),qg.BinaryReader=f,qg.serialize=function(e,t,n=h){const r=new n;return m(e,t,r),r.toArray()},qg.deserialize=function(e,t,n,r=f){const i=new r(n),o=w(e,t,i);if(i.offset<n.length)throw new l(`Unexpected ${n.length-i.offset} bytes after deserialized data`);return o},qg.deserializeUnchecked=function(e,t,n,r=f){return w(e,t,new r(n))},qg}(),ip={},op={};function sp(){return tp||(tp=1,function(e){const t=$h(),n=zh(),r="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;e.Buffer=s,e.SlowBuffer=function(e){+e!=e&&(e=0);return s.alloc(+e)},e.INSPECT_MAX_BYTES=50;const i=2147483647;function o(e){if(e>i)throw new RangeError('The value "'+e+'" is invalid for option "size"');const t=new Uint8Array(e);return Object.setPrototypeOf(t,s.prototype),t}function s(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 u(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(!s.isEncoding(t))throw new TypeError("Unknown encoding: "+t);const n=0|f(e,t);let r=o(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(j(e,Uint8Array)){const t=new Uint8Array(e);return h(t.buffer,t.byteOffset,t.byteLength)}return l(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(j(e,ArrayBuffer)||e&&j(e.buffer,ArrayBuffer))return h(e,t,n);if("undefined"!=typeof SharedArrayBuffer&&(j(e,SharedArrayBuffer)||e&&j(e.buffer,SharedArrayBuffer)))return h(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 s.from(r,t,n);const i=function(e){if(s.isBuffer(e)){const t=0|d(e.length),n=o(t);return 0===n.length||e.copy(n,0,0,t),n}if(void 0!==e.length)return"number"!=typeof e.length||V(e.length)?o(0):l(e);if("Buffer"===e.type&&Array.isArray(e.data))return l(e.data)}(e);if(i)return i;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return s.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 u(e){return c(e),o(e<0?0:0|d(e))}function l(e){const t=e.length<0?0:0|d(e.length),n=o(t);for(let r=0;r<t;r+=1)n[r]=255&e[r];return n}function h(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,s.prototype),r}function d(e){if(e>=i)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i.toString(16)+" bytes");return 0|e}function f(e,t){if(s.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||j(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 z(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return W(e).length;default:if(i)return r?-1:z(e).length;t=(""+t).toLowerCase(),i=!0}}function g(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 T(this,t,n);case"ascii":return I(this,t,n);case"latin1":case"binary":return x(this,t,n);case"base64":return A(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return N(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function p(e,t,n){const r=e[t];e[t]=e[n],e[n]=r}function m(e,t,n,r,i){if(0===e.length)return-1;if("string"==typeof n?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),V(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=s.from(t,r)),s.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 o,s=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;s=2,a/=2,c/=2,n/=2}function u(e,t){return 1===s?e[t]:e.readUInt16BE(t*s)}if(i){let r=-1;for(o=n;o<a;o++)if(u(e,o)===u(t,-1===r?0:o-r)){if(-1===r&&(r=o),o-r+1===c)return r*s}else-1!==r&&(o-=o-r),r=-1}else for(n+c>a&&(n=a-c),o=n;o>=0;o--){let n=!0;for(let r=0;r<c;r++)if(u(e,o+r)!==u(t,r)){n=!1;break}if(n)return o}return-1}function w(e,t,n,r){n=Number(n)||0;const i=e.length-n;r?(r=Number(r))>i&&(r=i):r=i;const o=t.length;let s;for(r>o/2&&(r=o/2),s=0;s<r;++s){const r=parseInt(t.substr(2*s,2),16);if(V(r))return s;e[n+s]=r}return s}function b(e,t,n,r){return H(z(t,e.length-n),e,n,r)}function k(e,t,n,r){return H(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 v(e,t,n,r){return H(W(t),e,n,r)}function S(e,t,n,r){return H(function(e,t){let n,r,i;const o=[];for(let s=0;s<e.length&&!((t-=2)<0);++s)n=e.charCodeAt(s),r=n>>8,i=n%256,o.push(i),o.push(r);return o}(t,e.length-n),e,n,r)}function A(e,n,r){return 0===n&&r===e.length?t.fromByteArray(e):t.fromByteArray(e.slice(n,r))}function T(e,t,n){n=Math.min(e.length,n);const r=[];let i=t;for(;i<n;){const t=e[i];let o=null,s=t>239?4:t>223?3:t>191?2:1;if(i+s<=n){let n,r,a,c;switch(s){case 1:t<128&&(o=t);break;case 2:n=e[i+1],128==(192&n)&&(c=(31&t)<<6|63&n,c>127&&(o=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)&&(o=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&&(o=c))}}null===o?(o=65533,s=1):o>65535&&(o-=65536,r.push(o>>>10&1023|55296),o=56320|1023&o),r.push(o),i+=s}return function(e){const t=e.length;if(t<=E)return String.fromCharCode.apply(String,e);let n="",r=0;for(;r<t;)n+=String.fromCharCode.apply(String,e.slice(r,r+=E));return n}(r)}e.kMaxLength=i,s.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}}(),!s.TYPED_ARRAY_SUPPORT&&"undefined"!=typeof console&&console.error,Object.defineProperty(s.prototype,"parent",{enumerable:!0,get:function(){if(s.isBuffer(this))return this.buffer}}),Object.defineProperty(s.prototype,"offset",{enumerable:!0,get:function(){if(s.isBuffer(this))return this.byteOffset}}),s.poolSize=8192,s.from=function(e,t,n){return a(e,t,n)},Object.setPrototypeOf(s.prototype,Uint8Array.prototype),Object.setPrototypeOf(s,Uint8Array),s.alloc=function(e,t,n){return function(e,t,n){return c(e),e<=0?o(e):void 0!==t?"string"==typeof n?o(e).fill(t,n):o(e).fill(t):o(e)}(e,t,n)},s.allocUnsafe=function(e){return u(e)},s.allocUnsafeSlow=function(e){return u(e)},s.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==s.prototype},s.compare=function(e,t){if(j(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),j(t,Uint8Array)&&(t=s.from(t,t.offset,t.byteLength)),!s.isBuffer(e)||!s.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,o=Math.min(n,r);i<o;++i)if(e[i]!==t[i]){n=e[i],r=t[i];break}return n<r?-1:r<n?1:0},s.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}},s.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return s.alloc(0);let n;if(void 0===t)for(t=0,n=0;n<e.length;++n)t+=e[n].length;const r=s.allocUnsafe(t);let i=0;for(n=0;n<e.length;++n){let t=e[n];if(j(t,Uint8Array))i+t.length>r.length?(s.isBuffer(t)||(t=s.from(t)),t.copy(r,i)):Uint8Array.prototype.set.call(r,t,i);else{if(!s.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(r,i)}i+=t.length}return r},s.byteLength=f,s.prototype._isBuffer=!0,s.prototype.swap16=function(){const e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let t=0;t<e;t+=2)p(this,t,t+1);return this},s.prototype.swap32=function(){const e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let t=0;t<e;t+=4)p(this,t,t+3),p(this,t+1,t+2);return this},s.prototype.swap64=function(){const e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let t=0;t<e;t+=8)p(this,t,t+7),p(this,t+1,t+6),p(this,t+2,t+5),p(this,t+3,t+4);return this},s.prototype.toString=function(){const e=this.length;return 0===e?"":0===arguments.length?T(this,0,e):g.apply(this,arguments)},s.prototype.toLocaleString=s.prototype.toString,s.prototype.equals=function(e){if(!s.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===s.compare(this,e)},s.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&&(s.prototype[r]=s.prototype.inspect),s.prototype.compare=function(e,t,n,r,i){if(j(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),!s.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 o=(i>>>=0)-(r>>>=0),a=(n>>>=0)-(t>>>=0);const c=Math.min(o,a),u=this.slice(r,i),l=e.slice(t,n);for(let e=0;e<c;++e)if(u[e]!==l[e]){o=u[e],a=l[e];break}return o<a?-1:a<o?1:0},s.prototype.includes=function(e,t,n){return-1!==this.indexOf(e,t,n)},s.prototype.indexOf=function(e,t,n){return m(this,e,t,n,!0)},s.prototype.lastIndexOf=function(e,t,n){return m(this,e,t,n,!1)},s.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 o=!1;for(;;)switch(r){case"hex":return w(this,e,t,n);case"utf8":case"utf-8":return b(this,e,t,n);case"ascii":case"latin1":case"binary":return k(this,e,t,n);case"base64":return v(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return S(this,e,t,n);default:if(o)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),o=!0}},s.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const E=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 x(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 N(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 B(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 _(e,t,n,r,i,o){if(!s.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||t<o)throw new RangeError('"value" argument is out of bounds');if(n+r>e.length)throw new RangeError("Index out of range")}function P(e,t,n,r,i){$(t,r,i,e,n,7);let o=Number(t&BigInt(4294967295));e[n++]=o,o>>=8,e[n++]=o,o>>=8,e[n++]=o,o>>=8,e[n++]=o;let s=Number(t>>BigInt(32)&BigInt(4294967295));return e[n++]=s,s>>=8,e[n++]=s,s>>=8,e[n++]=s,s>>=8,e[n++]=s,n}function R(e,t,n,r,i){$(t,r,i,e,n,7);let o=Number(t&BigInt(4294967295));e[n+7]=o,o>>=8,e[n+6]=o,o>>=8,e[n+5]=o,o>>=8,e[n+4]=o;let s=Number(t>>BigInt(32)&BigInt(4294967295));return e[n+3]=s,s>>=8,e[n+2]=s,s>>=8,e[n+1]=s,s>>=8,e[n]=s,n+8}function D(e,t,n,r,i,o){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function L(e,t,r,i,o){return t=+t,r>>>=0,o||D(e,0,r,4),n.write(e,t,r,i,23,4),r+4}function O(e,t,r,i,o){return t=+t,r>>>=0,o||D(e,0,r,8),n.write(e,t,r,i,52,8),r+8}s.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,s.prototype),r},s.prototype.readUintLE=s.prototype.readUIntLE=function(e,t,n){e>>>=0,t>>>=0,n||B(e,t,this.length);let r=this[e],i=1,o=0;for(;++o<t&&(i*=256);)r+=this[e+o]*i;return r},s.prototype.readUintBE=s.prototype.readUIntBE=function(e,t,n){e>>>=0,t>>>=0,n||B(e,t,this.length);let r=this[e+--t],i=1;for(;t>0&&(i*=256);)r+=this[e+--t]*i;return r},s.prototype.readUint8=s.prototype.readUInt8=function(e,t){return e>>>=0,t||B(e,1,this.length),this[e]},s.prototype.readUint16LE=s.prototype.readUInt16LE=function(e,t){return e>>>=0,t||B(e,2,this.length),this[e]|this[e+1]<<8},s.prototype.readUint16BE=s.prototype.readUInt16BE=function(e,t){return e>>>=0,t||B(e,2,this.length),this[e]<<8|this[e+1]},s.prototype.readUint32LE=s.prototype.readUInt32LE=function(e,t){return e>>>=0,t||B(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},s.prototype.readUint32BE=s.prototype.readUInt32BE=function(e,t){return e>>>=0,t||B(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},s.prototype.readBigUInt64LE=Q(function(e){q(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||K(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))}),s.prototype.readBigUInt64BE=Q(function(e){q(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||K(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)}),s.prototype.readIntLE=function(e,t,n){e>>>=0,t>>>=0,n||B(e,t,this.length);let r=this[e],i=1,o=0;for(;++o<t&&(i*=256);)r+=this[e+o]*i;return i*=128,r>=i&&(r-=Math.pow(2,8*t)),r},s.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||B(e,t,this.length);let r=t,i=1,o=this[e+--r];for(;r>0&&(i*=256);)o+=this[e+--r]*i;return i*=128,o>=i&&(o-=Math.pow(2,8*t)),o},s.prototype.readInt8=function(e,t){return e>>>=0,t||B(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},s.prototype.readInt16LE=function(e,t){e>>>=0,t||B(e,2,this.length);const n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},s.prototype.readInt16BE=function(e,t){e>>>=0,t||B(e,2,this.length);const n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},s.prototype.readInt32LE=function(e,t){return e>>>=0,t||B(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},s.prototype.readInt32BE=function(e,t){return e>>>=0,t||B(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},s.prototype.readBigInt64LE=Q(function(e){q(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||K(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)}),s.prototype.readBigInt64BE=Q(function(e){q(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||K(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)}),s.prototype.readFloatLE=function(e,t){return e>>>=0,t||B(e,4,this.length),n.read(this,e,!0,23,4)},s.prototype.readFloatBE=function(e,t){return e>>>=0,t||B(e,4,this.length),n.read(this,e,!1,23,4)},s.prototype.readDoubleLE=function(e,t){return e>>>=0,t||B(e,8,this.length),n.read(this,e,!0,52,8)},s.prototype.readDoubleBE=function(e,t){return e>>>=0,t||B(e,8,this.length),n.read(this,e,!1,52,8)},s.prototype.writeUintLE=s.prototype.writeUIntLE=function(e,t,n,r){if(e=+e,t>>>=0,n>>>=0,!r){_(this,e,t,n,Math.pow(2,8*n)-1,0)}let i=1,o=0;for(this[t]=255&e;++o<n&&(i*=256);)this[t+o]=e/i&255;return t+n},s.prototype.writeUintBE=s.prototype.writeUIntBE=function(e,t,n,r){if(e=+e,t>>>=0,n>>>=0,!r){_(this,e,t,n,Math.pow(2,8*n)-1,0)}let i=n-1,o=1;for(this[t+i]=255&e;--i>=0&&(o*=256);)this[t+i]=e/o&255;return t+n},s.prototype.writeUint8=s.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||_(this,e,t,1,255,0),this[t]=255&e,t+1},s.prototype.writeUint16LE=s.prototype.writeUInt16LE=function(e,t,n){return e=+e,t>>>=0,n||_(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},s.prototype.writeUint16BE=s.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||_(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},s.prototype.writeUint32LE=s.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||_(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},s.prototype.writeUint32BE=s.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||_(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},s.prototype.writeBigUInt64LE=Q(function(e,t=0){return P(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),s.prototype.writeBigUInt64BE=Q(function(e,t=0){return R(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),s.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t>>>=0,!r){const r=Math.pow(2,8*n-1);_(this,e,t,n,r-1,-r)}let i=0,o=1,s=0;for(this[t]=255&e;++i<n&&(o*=256);)e<0&&0===s&&0!==this[t+i-1]&&(s=1),this[t+i]=(e/o|0)-s&255;return t+n},s.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t>>>=0,!r){const r=Math.pow(2,8*n-1);_(this,e,t,n,r-1,-r)}let i=n-1,o=1,s=0;for(this[t+i]=255&e;--i>=0&&(o*=256);)e<0&&0===s&&0!==this[t+i+1]&&(s=1),this[t+i]=(e/o|0)-s&255;return t+n},s.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||_(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},s.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||_(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},s.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||_(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},s.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||_(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},s.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||_(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},s.prototype.writeBigInt64LE=Q(function(e,t=0){return P(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),s.prototype.writeBigInt64BE=Q(function(e,t=0){return R(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),s.prototype.writeFloatLE=function(e,t,n){return L(this,e,t,!0,n)},s.prototype.writeFloatBE=function(e,t,n){return L(this,e,t,!1,n)},s.prototype.writeDoubleLE=function(e,t,n){return O(this,e,t,!0,n)},s.prototype.writeDoubleBE=function(e,t,n){return O(this,e,t,!1,n)},s.prototype.copy=function(e,t,n,r){if(!s.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},s.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&&!s.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 o=s.isBuffer(e)?e:s.from(e,r),a=o.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]=o[i%a]}return this};const U={};function M(e,t,n){U[e]=class extends n{constructor(){super(),Object.defineProperty(this,"message",{value:t.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${e}]`,this.stack,delete this.name}get code(){return e}set code(e){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:e,writable:!0})}toString(){return`${this.name} [${e}]: ${this.message}`}}}function F(e){let t="",n=e.length;const r="-"===e[0]?1:0;for(;n>=r+4;n-=3)t=`_${e.slice(n-3,n)}${t}`;return`${e.slice(0,n)}${t}`}function $(e,t,n,r,i,o){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*(o+1)}${n}`:`>= -(2${n} ** ${8*(o+1)-1}${n}) and < 2 ** ${8*(o+1)-1}${n}`,new U.ERR_OUT_OF_RANGE("value",r,e)}!function(e,t,n){q(t,"offset"),void 0!==e[t]&&void 0!==e[t+n]||K(t,e.length-(n+1))}(r,i,o)}function q(e,t){if("number"!=typeof e)throw new U.ERR_INVALID_ARG_TYPE(t,"number",e)}function K(e,t,n){if(Math.floor(e)!==e)throw q(e,n),new U.ERR_OUT_OF_RANGE("offset","an integer",e);if(t<0)throw new U.ERR_BUFFER_OUT_OF_BOUNDS;throw new U.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${t}`,e)}M("ERR_BUFFER_OUT_OF_BOUNDS",function(e){return e?`${e} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),M("ERR_INVALID_ARG_TYPE",function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`},TypeError),M("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 G=/[^+/0-9A-Za-z-_]/g;function z(e,t){let n;t=t||1/0;const r=e.length;let i=null;const o=[];for(let s=0;s<r;++s){if(n=e.charCodeAt(s),n>55295&&n<57344){if(!i){if(n>56319){(t-=3)>-1&&o.push(239,191,189);continue}if(s+1===r){(t-=3)>-1&&o.push(239,191,189);continue}i=n;continue}if(n<56320){(t-=3)>-1&&o.push(239,191,189),i=n;continue}n=65536+(i-55296<<10|n-56320)}else i&&(t-=3)>-1&&o.push(239,191,189);if(i=null,n<128){if((t-=1)<0)break;o.push(n)}else if(n<2048){if((t-=2)<0)break;o.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;o.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;o.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return o}function W(e){return t.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(G,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function H(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 j(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function V(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 Q(e){return"undefined"==typeof BigInt?J:e}function J(){throw new Error("BigInt not supported")}}(op)),op}var ap=function(){if(np)return ip;np=1,Object.defineProperty(ip,"__esModule",{value:!0}),ip.s16=ip.s8=ip.nu64be=ip.u48be=ip.u40be=ip.u32be=ip.u24be=ip.u16be=ip.nu64=ip.u48=ip.u40=ip.u32=ip.u24=ip.u16=ip.u8=ip.offset=ip.greedy=ip.Constant=ip.UTF8=ip.CString=ip.Blob=ip.Boolean=ip.BitField=ip.BitStructure=ip.VariantLayout=ip.Union=ip.UnionLayoutDiscriminator=ip.UnionDiscriminator=ip.Structure=ip.Sequence=ip.DoubleBE=ip.Double=ip.FloatBE=ip.Float=ip.NearInt64BE=ip.NearInt64=ip.NearUInt64BE=ip.NearUInt64=ip.IntBE=ip.Int=ip.UIntBE=ip.UInt=ip.OffsetLayout=ip.GreedyCount=ip.ExternalLayout=ip.bindConstructorLayout=ip.nameWithProperty=ip.Layout=ip.uint8ArrayToBuffer=ip.checkUint8Array=void 0,ip.constant=ip.utf8=ip.cstr=ip.blob=ip.unionLayoutDiscriminator=ip.union=ip.seq=ip.bits=ip.struct=ip.f64be=ip.f64=ip.f32be=ip.f32=ip.ns64be=ip.s48be=ip.s40be=ip.s32be=ip.s24be=ip.s16be=ip.ns64=ip.s48=ip.s40=ip.s32=ip.s24=void 0;const e=sp();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)}ip.checkUint8Array=t,ip.uint8ArrayToBuffer=n;class r{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}ip.Layout=r,ip.nameWithProperty=i,ip.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 o extends r{isCount(){throw new Error("ExternalLayout is abstract")}}ip.ExternalLayout=o;class s extends o{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}}ip.GreedyCount=s;class a extends o{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 u}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)}}ip.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}}ip.UInt=c;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).readUIntBE(t,this.span)}encode(e,t,r=0){return n(t).writeUIntBE(e,r,this.span),this.span}}ip.UIntBE=u;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).readIntLE(t,this.span)}encode(e,t,r=0){return n(t).writeIntLE(e,r,this.span),this.span}}ip.Int=l;class h 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}}ip.IntBE=h;const d=Math.pow(2,32);function f(e){const t=Math.floor(e/d);return{hi32:t,lo32:e-t*d}}function g(e,t){return e*d+t}class p extends r{constructor(e){super(8,e)}decode(e,t=0){const r=n(e),i=r.readUInt32LE(t);return g(r.readUInt32LE(t+4),i)}encode(e,t,r=0){const i=f(e),o=n(t);return o.writeUInt32LE(i.lo32,r),o.writeUInt32LE(i.hi32,r+4),8}}ip.NearUInt64=p;class m extends r{constructor(e){super(8,e)}decode(e,t=0){const r=n(e);return g(r.readUInt32BE(t),r.readUInt32BE(t+4))}encode(e,t,r=0){const i=f(e),o=n(t);return o.writeUInt32BE(i.hi32,r),o.writeUInt32BE(i.lo32,r+4),8}}ip.NearUInt64BE=m;class y extends r{constructor(e){super(8,e)}decode(e,t=0){const r=n(e),i=r.readUInt32LE(t);return g(r.readInt32LE(t+4),i)}encode(e,t,r=0){const i=f(e),o=n(t);return o.writeUInt32LE(i.lo32,r),o.writeInt32LE(i.hi32,r+4),8}}ip.NearInt64=y;class w extends r{constructor(e){super(8,e)}decode(e,t=0){const r=n(e);return g(r.readInt32BE(t),r.readUInt32BE(t+4))}encode(e,t,r=0){const i=f(e),o=n(t);return o.writeInt32BE(i.hi32,r),o.writeUInt32BE(i.lo32,r+4),8}}ip.NearInt64BE=w;class b 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}}ip.Float=b;class k 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}}ip.FloatBE=k;class v 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}}ip.Double=v;class S 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}}ip.DoubleBE=S;class A extends r{constructor(e,t,n){if(!(e instanceof r))throw new TypeError("elementLayout must be a Layout");if(!(t instanceof o&&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 o)&&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 o&&(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 o&&(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 o&&this.count.encode(e.length,t,n),i}}ip.Sequence=A;class T 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,o=0;for(const r of this.fields){let s=r.span;if(o=0<s?s:0,void 0!==r.property){const i=e[r.property];void 0!==i&&(o=r.encode(i,t,n),0>s&&(s=r.getSpan(t,n)))}i=n,n+=s}return i+o-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)}}}ip.Structure=T;class E{constructor(e){this.property=e}decode(e,t){throw new Error("UnionDiscriminator is abstract")}encode(e,t,n){throw new Error("UnionDiscriminator is abstract")}}ip.UnionDiscriminator=E;class I extends E{constructor(e,t){if(!(e instanceof o&&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)}}ip.UnionLayoutDiscriminator=I;class x extends r{constructor(e,t,n){let i;if(e instanceof c||e instanceof u)i=new I(new a(e));else if(e instanceof o&&e.isCount())i=new I(e);else{if(!(e instanceof E))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 s=-1;t&&(s=t.span,0<=s&&(e instanceof c||e instanceof u)&&(s+=i.layout.span)),super(s,n),this.discriminator=i,this.usesPrefixDiscriminator=e instanceof c||e instanceof u,this.defaultLayout=t,this.registry={};let l=this.defaultGetSourceVariant.bind(this);this.getSourceVariant=function(e){return l(e)},this.configGetSourceVariant=function(e){l=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),o=this.registry[i];if(void 0===o){const o=this.defaultLayout;let s=0;this.usesPrefixDiscriminator&&(s=r.layout.span),n=this.makeDestinationObject(),n[r.property]=i,n[o.property]=o.decode(e,t+s)}else n=o.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 o=0;return this.usesPrefixDiscriminator&&(o=r.layout.span),r.encode(e[r.property],t,n),o+i.encode(e[i.property],t,n+o)}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]}}ip.Union=x;class C extends r{constructor(e,t,n,i){if(!(e instanceof x))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 o=e.span;0>e.span&&(o=n?n.span:0,0<=o&&e.usesPrefixDiscriminator&&(o+=e.discriminator.layout.span)),super(o,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 N(e){return 0>e&&(e+=4294967296),e}ip.VariantLayout=C;class B extends r{constructor(e,t,n){if(!(e instanceof c||e instanceof u))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=N(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 _(this,e,t);return this.fields.push(n),n}addBoolean(e){const t=new P(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}}ip.BitStructure=B;class _{constructor(e,t,n){if(!(e instanceof B))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=N(this.valueMask<<this.start),this.property=n}decode(e,t){return N(this.container._packedGetValue()&this.wordMask)>>>this.start}encode(e){if("number"!=typeof e||!Number.isInteger(e)||e!==N(e&this.valueMask))throw new TypeError(i("BitField.encode",this)+" value must be integer not exceeding "+this.valueMask);const t=this.container._packedGetValue(),n=N(e<<this.start);this.container._packedSetValue(N(t&~this.wordMask)|n)}}ip.BitField=_;class P extends _{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)}}ip.Boolean=P;class R extends r{constructor(e,t){if(!(e instanceof o&&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 o||(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 s=this.length;if(this.length instanceof o&&(s=e.length),!(e instanceof Uint8Array&&s===e.length))throw new TypeError(i("Blob.encode",this)+" requires (length "+s+") Uint8Array as src");if(r+s>t.length)throw new RangeError("encoding overruns Uint8Array");const a=n(e);return n(t).write(a.toString("hex"),r,s,"hex"),this.length instanceof o&&this.length.encode(s,t,r),s}}ip.Blob=R;class D 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 o=e.Buffer.from(t,"utf8"),s=o.length;if(i+s>r.length)throw new RangeError("encoding overruns Buffer");const a=n(r);return o.copy(a,i),a[i+s]=0,s+1}}ip.CString=D;class L 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 o=e.Buffer.from(t,"utf8"),s=o.length;if(0<=this.maxSpan&&this.maxSpan<s)throw new RangeError("text length exceeds maxSpan");if(i+s>r.length)throw new RangeError("encoding overruns Buffer");return o.copy(n(r),i),s}}ip.UTF8=L;class O extends r{constructor(e,t){super(0,t),this.value=e}decode(e,t){return this.value}encode(e,t,n){return 0}}return ip.Constant=O,ip.greedy=(e,t)=>new s(e,t),ip.offset=(e,t,n)=>new a(e,t,n),ip.u8=e=>new c(1,e),ip.u16=e=>new c(2,e),ip.u24=e=>new c(3,e),ip.u32=e=>new c(4,e),ip.u40=e=>new c(5,e),ip.u48=e=>new c(6,e),ip.nu64=e=>new p(e),ip.u16be=e=>new u(2,e),ip.u24be=e=>new u(3,e),ip.u32be=e=>new u(4,e),ip.u40be=e=>new u(5,e),ip.u48be=e=>new u(6,e),ip.nu64be=e=>new m(e),ip.s8=e=>new l(1,e),ip.s16=e=>new l(2,e),ip.s24=e=>new l(3,e),ip.s32=e=>new l(4,e),ip.s40=e=>new l(5,e),ip.s48=e=>new l(6,e),ip.ns64=e=>new y(e),ip.s16be=e=>new h(2,e),ip.s24be=e=>new h(3,e),ip.s32be=e=>new h(4,e),ip.s40be=e=>new h(5,e),ip.s48be=e=>new h(6,e),ip.ns64be=e=>new w(e),ip.f32=e=>new b(e),ip.f32be=e=>new k(e),ip.f64=e=>new v(e),ip.f64be=e=>new S(e),ip.struct=(e,t,n)=>new T(e,t,n),ip.bits=(e,t,n)=>new B(e,t,n),ip.seq=(e,t,n)=>new A(e,t,n),ip.union=(e,t,n)=>new x(e,t,n),ip.unionLayoutDiscriminator=(e,t)=>new I(e,t),ip.blob=(e,t)=>new R(e,t),ip.cstr=e=>new D(e),ip.utf8=(e,t)=>new L(e,t),ip.constant=(e,t)=>new O(e,t),ip}(),cp=1,up=2,lp=3,hp=4,dp=5,fp=6,gp=7,pp=8,mp=9,yp=10,wp=-32700,bp=-32603,kp=-32602,vp=-32601,Sp=-32600,Ap=-32016,Tp=-32015,Ep=-32014,Ip=-32013,xp=-32012,Cp=-32011,Np=-32010,Bp=-32009,_p=-32008,Pp=-32007,Rp=-32006,Dp=-32005,Lp=-32004,Op=-32003,Up=-32002,Mp=-32001,Fp=28e5,$p=2800001,qp=2800002,Kp=2800003,Gp=2800004,zp=2800005,Wp=2800006,Hp=2800007,jp=2800008,Vp=2800009,Xp=2800010,Qp=2800011,Jp=323e4,Yp=32300001,Zp=3230002,em=3230003,tm=3230004,nm=361e4,rm=3610001,im=3610002,om=3610003,sm=3610004,am=3610005,cm=3610006,um=3610007,lm=3611e3,hm=3704e3,dm=3704001,fm=3704002,gm=3704003,pm=3704004,mm=4128e3,ym=4128001,wm=4128002,bm=4615e3,km=4615001,vm=4615002,Sm=4615003,Am=4615004,Tm=4615005,Em=4615006,Im=4615007,xm=4615008,Cm=4615009,Nm=4615010,Bm=4615011,_m=4615012,Pm=4615013,Rm=4615014,Dm=4615015,Lm=4615016,Om=4615017,Um=4615018,Mm=4615019,Fm=4615020,$m=4615021,qm=4615022,Km=4615023,Gm=4615024,zm=4615025,Wm=4615026,Hm=4615027,jm=4615028,Vm=4615029,Xm=4615030,Qm=4615031,Jm=4615032,Ym=4615033,Zm=4615034,ey=4615035,ty=4615036,ny=4615037,ry=4615038,iy=4615039,oy=4615040,sy=4615041,ay=4615042,cy=4615043,uy=4615044,ly=4615045,hy=4615046,dy=4615047,fy=4615048,gy=4615049,py=4615050,my=4615051,yy=4615052,wy=4615053,by=4615054,ky=5508e3,vy=5508001,Sy=5508002,Ay=5508003,Ty=5508004,Ey=5508005,Iy=5508006,xy=5508007,Cy=5508008,Ny=5508009,By=5508010,_y=5508011,Py=5663e3,Ry=5663001,Dy=5663002,Ly=5663003,Oy=5663004,Uy=5663005,My=5663006,Fy=5663007,$y=5663008,qy=5663009,Ky=5663010,Gy=5663011,zy=5663012,Wy=5663013,Hy=5663014,jy=5663015,Vy=5663016,Xy=5663017,Qy=5663018,Jy=5663019,Yy=5663020,Zy=705e4,ew=7050001,tw=7050002,nw=7050003,rw=7050004,iw=7050005,ow=7050006,sw=7050007,aw=7050008,cw=7050009,uw=7050010,lw=7050011,hw=7050012,dw=7050013,fw=7050014,gw=7050015,pw=7050016,mw=7050017,yw=7050018,ww=7050019,bw=7050020,kw=7050021,vw=7050022,Sw=7050023,Aw=7050024,Tw=7050025,Ew=7050026,Iw=7050027,xw=7050028,Cw=7050029,Nw=7050030,Bw=7050031,_w=7050032,Pw=7050033,Rw=7050034,Dw=7050035,Lw=7050036,Ow=8078e3,Uw=8078001,Mw=8078002,Fw=8078003,$w=8078004,qw=8078005,Kw=8078006,Gw=8078007,zw=8078008,Ww=8078009,Hw=8078010,jw=8078011,Vw=8078012,Xw=8078013,Qw=8078014,Jw=8078015,Yw=8078016,Zw=8078017,eb=8078018,tb=8078019,nb=8078020,rb=8078021,ib=8078022,ob=81e5,sb=8100001,ab=8100002,cb=8100003,ub=819e4,lb=8190001,hb=8190002,db=8190003,fb=8190004,gb=99e5,pb=9900001,mb=9900002,yb=9900003,wb=9900004;function bb(e){if(Array.isArray(e)){return"%5B"+e.map(bb).join("%2C%20")+"%5D"}return"bigint"==typeof e?`${e}n`:encodeURIComponent(String(null!=e&&null===Object.getPrototypeOf(e)?{...e}:e))}function kb([e,t]){return`${e}=${bb(t)}`}var vb={[Jp]:"Account not found at address: $address",[tm]:"Not all accounts were decoded. Encoded accounts found at addresses: $addresses.",[em]:"Expected decoded account at address: $address",[Zp]:"Failed to decode account data at address: $address",[Yp]:"Accounts not found at addresses: $addresses",[Vp]:"Unable to find a viable program address bump seed.",[qp]:"$putativeAddress is not a base58-encoded address.",[Fp]:"Expected base58 encoded address to decode to a byte array of length 32. Actual length: $actualLength.",[Kp]:"The `CryptoKey` must be an `Ed25519` public key.",[Qp]:"$putativeOffCurveAddress is not a base58-encoded off-curve address.",[jp]:"Invalid seeds; point must fall off the Ed25519 curve.",[Gp]:"Expected given program derived address to have the following format: [Address, ProgramDerivedAddressBump].",[Wp]:"A maximum of $maxSeeds seeds, including the bump seed, may be supplied when creating an address. Received: $actual.",[Hp]:"The seed at index $index with length $actual exceeds the maximum length of $maxSeedLength bytes.",[zp]:"Expected program derived address bump to be in the range [0, 255], got: $bump.",[Xp]:"Program address cannot end with PDA marker.",[$p]:"Expected base58-encoded address string of length in the range [32, 44]. Actual length: $actualLength.",[hp]:"Expected base58-encoded blockash string of length in the range [32, 44]. Actual length: $actualLength.",[cp]:"The network has progressed past the last block for which this transaction could have been committed.",[Ow]:"Codec [$codecDescription] cannot decode empty byte arrays.",[ib]:"Enum codec cannot use lexical values [$stringValues] as discriminators. Either remove all lexical values or set `useValuesAsDiscriminators` to `false`.",[nb]:"Sentinel [$hexSentinel] must not be present in encoded bytes [$hexEncodedBytes].",[qw]:"Encoder and decoder must have the same fixed size, got [$encoderFixedSize] and [$decoderFixedSize].",[Kw]:"Encoder and decoder must have the same max size, got [$encoderMaxSize] and [$decoderMaxSize].",[$w]:"Encoder and decoder must either both be fixed-size or variable-size.",[zw]:"Enum discriminator out of range. Expected a number in [$formattedValidDiscriminators], got $discriminator.",[Mw]:"Expected a fixed-size codec, got a variable-size one.",[Xw]:"Codec [$codecDescription] expected a positive byte length, got $bytesLength.",[Fw]:"Expected a variable-size codec, got a fixed-size one.",[tb]:"Codec [$codecDescription] expected zero-value [$hexZeroValue] to have the same size as the provided fixed-size item [$expectedSize bytes].",[Uw]:"Codec [$codecDescription] expected $expected bytes, got $bytesLength.",[eb]:"Expected byte array constant [$hexConstant] to be present in data [$hexData] at offset [$offset].",[Ww]:"Invalid discriminated union variant. Expected one of [$variants], got $value.",[Hw]:"Invalid enum variant. Expected one of [$stringValues] or a number in [$formattedNumericalValues], got $variant.",[Jw]:"Invalid literal union variant. Expected one of [$variants], got $value.",[Gw]:"Expected [$codecDescription] to have $expected items, got $actual.",[Vw]:"Invalid value $value for base $base with alphabet $alphabet.",[Yw]:"Literal union discriminator out of range. Expected a number between $minRange and $maxRange, got $discriminator.",[jw]:"Codec [$codecDescription] expected number to be in the range [$min, $max], got $value.",[Qw]:"Codec [$codecDescription] expected offset to be in the range [0, $bytesLength], got $offset.",[rb]:"Expected sentinel [$hexSentinel] to be present in decoded bytes [$hexDecodedBytes].",[Zw]:"Union variant out of range. Expected an index between $minRange and $maxRange, got $variant.",[lm]:"No random values implementation could be found.",[Cm]:"instruction requires an uninitialized account",[Km]:"instruction tries to borrow reference for an account which is already borrowed",[Gm]:"instruction left account with an outstanding borrowed reference",[$m]:"program other than the account's owner changed the size of the account data",[Tm]:"account data too small for instruction",[qm]:"instruction expected an executable account",[hy]:"An account does not have enough lamports to be rent-exempt",[fy]:"Program arithmetic overflowed",[ly]:"Failed to serialize or deserialize account data: $encodedData",[by]:"Builtin programs must consume compute units",[Jm]:"Cross-program invocation call depth too deep",[ry]:"Computational budget exceeded",[Wm]:"custom program error: #$code",[Om]:"instruction contains duplicate accounts",[zm]:"instruction modifications of multiply-passed account differ",[Xm]:"executable accounts must be rent exempt",[jm]:"instruction changed executable accounts data",[Vm]:"instruction changed the balance of an executable account",[Um]:"instruction changed executable bit of an account",[Rm]:"instruction modified data of an account it does not own",[Pm]:"instruction spent from the balance of an account it does not own",[km]:"generic instruction error",[py]:"Provided owner is not allowed",[cy]:"Account is immutable",[uy]:"Incorrect authority provided",[Im]:"incorrect program id for instruction",[Em]:"insufficient funds for instruction",[Am]:"invalid account data for instruction",[dy]:"Invalid account owner",[vm]:"invalid program argument",[Hm]:"program returned invalid error code",[Sm]:"invalid instruction data",[ny]:"Failed to reallocate account data",[ty]:"Provided seeds do not result in a valid address",[my]:"Accounts data allocations exceeded the maximum allowed per transaction",[yy]:"Max accounts exceeded",[wy]:"Max instruction trace length exceeded",[ey]:"Length of the seed is too long for address generation",[Ym]:"An account required by the instruction is missing",[xm]:"missing required signature for instruction",[_m]:"instruction illegally modified the program id of an account",[Fm]:"insufficient account keys for instruction",[iy]:"Cross-program invocation with unauthorized signer or writable account",[oy]:"Failed to create program execution environment",[ay]:"Program failed to compile",[sy]:"Program failed to complete",[Lm]:"instruction modified data of a read-only account",[Dm]:"instruction changed the balance of a read-only account",[Zm]:"Cross-program invocation reentrancy not allowed for this instruction",[Mm]:"instruction modified rent epoch of an account",[Bm]:"sum of account balances before and after instruction do not match",[Nm]:"instruction requires an initialized account",[bm]:"",[Qm]:"Unsupported program id",[gy]:"Unsupported sysvar",[mm]:"The instruction does not have any accounts.",[ym]:"The instruction does not have any data.",[wm]:"Expected instruction to have progress address $expectedProgramAddress, got $actualProgramAddress.",[dp]:"Expected base58 encoded blockhash to decode to a byte array of length 32. Actual length: $actualLength.",[up]:"The nonce `$expectedNonceValue` is no longer valid. It has advanced to `$actualNonceValue`",[mb]:"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",[wb]:"Invariant violation: This data publisher does not publish to the channel named `$channelName`. Supported channels include $supportedChannelNames.",[pb]:"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",[gb]:"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",[yb]:"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",[bp]:"JSON-RPC error: Internal JSON-RPC error ($__serverMessage)",[kp]:"JSON-RPC error: Invalid method parameter(s) ($__serverMessage)",[Sp]:"JSON-RPC error: The JSON sent is not a valid `Request` object ($__serverMessage)",[vp]:"JSON-RPC error: The method does not exist / is not available ($__serverMessage)",[wp]:"JSON-RPC error: An error occurred on the server while parsing the JSON text ($__serverMessage)",[xp]:"$__serverMessage",[Mp]:"$__serverMessage",[Lp]:"$__serverMessage",[Ep]:"$__serverMessage",[Np]:"$__serverMessage",[Bp]:"$__serverMessage",[Ap]:"Minimum context slot has not been reached",[Dp]:"Node is unhealthy; behind by $numSlotsBehind slots",[_p]:"No snapshot",[Up]:"Transaction simulation failed",[Pp]:"$__serverMessage",[Cp]:"Transaction history is not available from this node",[Rp]:"$__serverMessage",[Ip]:"Transaction signature length mismatch",[Op]:"Transaction signature verification failure",[Tp]:"$__serverMessage",[hm]:"Key pair bytes must be of length 64, got $byteLength.",[dm]:"Expected private key bytes with length 32. Actual length: $actualLength.",[fm]:"Expected base58-encoded signature to decode to a byte array of length 64. Actual length: $actualLength.",[pm]:"The provided private key does not match the provided public key.",[gm]:"Expected base58-encoded signature string of length in the range [64, 88]. Actual length: $actualLength.",[fp]:"Lamports value must be in the range [0, 2e64-1]",[gp]:"`$value` cannot be parsed as a `BigInt`",[yp]:"$message",[pp]:"`$value` cannot be parsed as a `Number`",[lp]:"No nonce account could be found at address `$nonceAccountAddress`",[ub]:"The notification name must end in 'Notifications' and the API must supply a subscription plan creator function for the notification '$notificationName'.",[hb]:"WebSocket was closed before payload could be added to the send buffer",[db]:"WebSocket connection closed",[fb]:"WebSocket failed to connect",[lb]:"Failed to obtain a subscription id from the server",[cb]:"Could not find an API plan for RPC method: `$method`",[ob]:"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`.",[ab]:"HTTP error ($statusCode): $message",[sb]:"HTTP header(s) forbidden: $headers. Learn more at https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name.",[ky]:"Multiple distinct signers were identified for address `$address`. Please ensure that you are using the same signer instance for each address.",[vy]:"The provided value does not implement the `KeyPairSigner` interface",[Ay]:"The provided value does not implement the `MessageModifyingSigner` interface",[Ty]:"The provided value does not implement the `MessagePartialSigner` interface",[Sy]:"The provided value does not implement any of the `MessageSigner` interfaces",[Iy]:"The provided value does not implement the `TransactionModifyingSigner` interface",[xy]:"The provided value does not implement the `TransactionPartialSigner` interface",[Cy]:"The provided value does not implement the `TransactionSendingSigner` interface",[Ey]:"The provided value does not implement any of the `TransactionSigner` interfaces",[Ny]:"More than one `TransactionSendingSigner` was identified.",[By]:"No `TransactionSendingSigner` was identified. Please provide a valid `TransactionWithSingleSendingSigner` transaction.",[_y]:"Wallet account signers do not support signing multiple messages/transactions in a single operation",[um]:"Cannot export a non-extractable key.",[rm]:"No digest implementation could be found.",[nm]:"Cryptographic operations are only allowed in secure browser contexts. Read more here: https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts.",[im]:"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.",[om]:"No signature verification implementation could be found.",[sm]:"No key generation implementation could be found.",[am]:"No signing implementation could be found.",[cm]:"No key export implementation could be found.",[mp]:"Timestamp value must be in the range [-(2n ** 63n), (2n ** 63n) - 1]. `$value` given",[pw]:"Transaction processing left an account with an outstanding borrowed reference",[ew]:"Account in use",[tw]:"Account loaded twice",[nw]:"Attempt to debit an account but found no record of a prior credit.",[Sw]:"Transaction loads an address table account that doesn't exist",[sw]:"This transaction has already been processed",[aw]:"Blockhash not found",[cw]:"Loader call chain is too deep",[gw]:"Transactions are currently disabled due to cluster maintenance",[Nw]:"Transaction contains a duplicate instruction ($index) that is not allowed",[iw]:"Insufficient funds for fee",[Bw]:"Transaction results in an account ($accountIndex) with insufficient funds for rent",[ow]:"This account may not be used to pay transaction fees",[lw]:"Transaction contains an invalid account reference",[Tw]:"Transaction loads an address table account with invalid data",[Ew]:"Transaction address table lookup uses an invalid index",[Aw]:"Transaction loads an address table account with an invalid owner",[Pw]:"LoadedAccountsDataSizeLimit set for transaction must be greater than 0.",[dw]:"This program may not be used for executing instructions",[Iw]:"Transaction leaves an account with a lower balance than rent-exempt minimum",[ww]:"Transaction loads a writable account that cannot be written",[_w]:"Transaction exceeded max loaded accounts data size cap",[uw]:"Transaction requires a fee but has no signature present",[rw]:"Attempt to load a program that does not exist",[Dw]:"Execution of the program referenced by account at index $accountIndex is temporarily restricted.",[Rw]:"ResanitizationNeeded",[fw]:"Transaction failed to sanitize accounts offsets correctly",[hw]:"Transaction did not pass signature verification",[vw]:"Transaction locked too many accounts",[Lw]:"Sum of account balances before and after transaction do not match",[Zy]:"The transaction failed with the error `$errorName`",[yw]:"Transaction version is unsupported",[kw]:"Transaction would exceed account data limit within the block",[Cw]:"Transaction would exceed total account data limit",[bw]:"Transaction would exceed max account limit within the block",[mw]:"Transaction would exceed max Block Cost Limit",[xw]:"Transaction would exceed max Vote Cost Limit",[jy]:"Attempted to sign a transaction with an address that is not a signer for it",[Ky]:"Transaction is missing an address at index: $index.",[Vy]:"Transaction has no expected signers therefore it cannot be encoded",[Yy]:"Transaction size $transactionSize exceeds limit of $transactionSizeLimit bytes",[Dy]:"Transaction does not have a blockhash lifetime",[Ly]:"Transaction is not a durable nonce transaction",[Uy]:"Contents of these address lookup tables unknown: $lookupTableAddresses",[My]:"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",[$y]:"No fee payer set in CompiledTransaction",[Fy]:"Could not find program address at index $index",[Qy]:"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",[Jy]:"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",[Gy]:"Transaction is missing a fee payer.",[zy]:"Could not determine this transaction's signature. Make sure that the transaction has been signed by its fee payer.",[Hy]:"Transaction first instruction is not advance nonce account instruction.",[Wy]:"Transaction with no instructions cannot be durable nonce transaction.",[Py]:"This transaction includes an address (`$programAddress`) which is both invoked and set as the fee payer. Program addresses may not pay fees",[Ry]:"This transaction includes an address (`$programAddress`) which is both invoked and marked writable. Program addresses may not be writable",[Xy]:"The transaction message expected the transaction to have $signerAddressesLength signatures, got $signaturesLength.",[qy]:"Transaction is missing signatures for addresses: $addresses.",[Oy]:"Transaction version must be in the range [0, 127]. `$actualVersion` given"},Sb="i",Ab="t";function Tb(e,t={}){if("production"!==process.env.NODE_ENV)return function(e,t={}){const n=vb[e];if(0===n.length)return"";let r;function i(e){if(2===r[Ab]){const i=n.slice(r[Sb]+1,e);o.push(i in t?`${t[i]}`:`$${i}`)}else 1===r[Ab]&&o.push(n.slice(r[Sb],e))}const o=[];return n.split("").forEach((e,t)=>{if(0===t)return void(r={[Sb]:0,[Ab]:"\\"===n[0]?0:"$"===n[0]?2:1});let o;switch(r[Ab]){case 0:o={[Sb]:t,[Ab]:1};break;case 1:"\\"===e?o={[Sb]:t,[Ab]:0}:"$"===e&&(o={[Sb]:t,[Ab]:2});break;case 2:"\\"===e?o={[Sb]:t,[Ab]:0}:"$"===e?o={[Sb]:t,[Ab]:2}:e.match(/\w/)||(o={[Sb]:t,[Ab]:1})}o&&(r!==o&&i(t),r=o)}),i(),o.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(kb).join("&");return btoa(t)}(t)}'`),`${n}\``}}var Eb=class extends Error{cause=this.cause;context;constructor(...[e,t]){let n,r;if(t){const{cause:e,...i}=t;e&&(r={cause:e}),Object.keys(i).length>0&&(n=i)}super(Tb(e,n),r),this.context={__code:e,...n},this.name="SolanaError"}};function Ib(e){return"fixedSize"in e&&"number"==typeof e.fixedSize}function xb(e){return 1!==e?.endian}function Cb(e){return t={fixedSize:e.size,write(t,n,r){e.range&&function(e,t,n,r){if(r<t||r>n)throw new Eb(jw,{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,xb(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 Nb(e){return t={fixedSize:e.size,read(t,n=0){!function(e,t,n=0){if(t.length-n<=0)throw new Eb(Ow,{codecDescription:e})}(e.name,t,n),function(e,t,n,r=0){const i=n.length-r;if(i<t)throw new Eb(Uw,{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;return e.buffer.slice(r,r+i)}(t,n,e.size));return[e.get(r,xb(e.config)),n+e.size]}},Object.freeze({...t,decode:(e,n=0)=>t.read(e,n)[0]});var t}var Bb=(e={})=>function(e,t){if(Ib(e)!==Ib(t))throw new Eb($w);if(Ib(e)&&Ib(t)&&e.fixedSize!==t.fixedSize)throw new Eb(qw,{decoderFixedSize:t.fixedSize,encoderFixedSize:e.fixedSize});if(!Ib(e)&&!Ib(t)&&e.maxSize!==t.maxSize)throw new Eb(Kw,{decoderMaxSize:t.maxSize,encoderMaxSize:e.maxSize});return{...t,...e,decode:t.decode,encode:e.encode,read:t.read,write:e.write}}(((e={})=>Cb({config:e,name:"u64",range:[0n,BigInt("0xffffffffffffffff")],set:(e,t,n)=>e.setBigUint64(0,BigInt(t),n),size:8}))(e),((e={})=>Nb({config:e,get:(e,t)=>e.getBigUint64(0,t),name:"u64",size:8}))(e));class _b extends TypeError{constructor(e,t){let n;const{message:r,explanation:i,...o}=e,{path:s}=e,a=0===s.length?r:`At path: ${s.join(".")} -- ${r}`;super(i??a),null!=i&&(this.cause=a),Object.assign(this,o),this.name=this.constructor.name,this.failures=()=>n??(n=[e,...t()])}}function Pb(e){return"object"==typeof e&&null!=e}function Rb(e){return Pb(e)&&!Array.isArray(e)}function Db(e){return"symbol"==typeof e?e.toString():"string"==typeof e?JSON.stringify(e):`${e}`}function Lb(e,t,n,r){if(!0===e)return;!1===e?e={}:"string"==typeof e&&(e={message:e});const{path:i,branch:o}=t,{type:s}=n,{refinement:a,message:c=`Expected a value of type \`${s}\`${a?` with refinement \`${a}\``:""}, but received: \`${Db(r)}\``}=e;return{value:r,type:s,refinement:a,key:i[i.length-1],path:i,branch:o,...e,message:c}}function*Ob(e,t,n,r){var i;Pb(i=e)&&"function"==typeof i[Symbol.iterator]||(e=[e]);for(const i of e){const e=Lb(i,t,n,r);e&&(yield e)}}function*Ub(e,t,n={}){const{path:r=[],branch:i=[e],coerce:o=!1,mask:s=!1}=n,a={path:r,branch:i,mask:s};o&&(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[u,l,h]of t.entries(e,a)){const t=Ub(l,h,{path:void 0===u?r:[...r,u],branch:void 0===u?i:[...i,l],coerce:o,mask:s,message:n.message});for(const n of t)n[0]?(c=null!=n[0].refinement?"not_refined":"not_valid",yield[n[0],void 0]):o&&(l=n[1],void 0===u?e=l:e instanceof Map?e.set(u,l):e instanceof Set?e.add(l):Pb(e)&&(void 0!==l||u in e)&&(e[u]=l))}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 Mb=class{constructor(e){const{type:t,schema:n,validator:r,refiner:i,coercer:o=e=>e,entries:s=function*(){}}=e;this.type=t,this.schema=n,this.entries=s,this.coercer=o,this.validator=r?(e,t)=>Ob(r(e,t),t,this,e):()=>[],this.refiner=i?(e,t)=>Ob(i(e,t),t,this,e):()=>[]}assert(e,t){return function(e,t,n){const r=qb(e,t,{message:n});if(r[0])throw r[0]}(e,this,t)}create(e,t){return Fb(e,this,t)}is(e){return $b(e,this)}mask(e,t){return function(e,t,n){const r=qb(e,t,{coerce:!0,mask:!0,message:n});if(r[0])throw r[0];return r[1]}(e,this,t)}validate(e,t={}){return qb(e,this,t)}};function Fb(e,t,n){const r=qb(e,t,{coerce:!0,message:n});if(r[0])throw r[0];return r[1]}function $b(e,t){return!qb(e,t)[0]}function qb(e,t,n={}){const r=Ub(e,t,n),i=function(e){const{done:t,value:n}=e.next();return t?void 0:n}(r);if(i[0]){return[new _b(i[0],function*(){for(const e of r)e[0]&&(yield e[0])}),void 0]}return[void 0,i[1]]}function Kb(e,t){return new Mb({type:e,schema:null,validator:t})}function Gb(e){return new Mb({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: ${Db(e)}`})}function zb(){return Kb("boolean",e=>"boolean"==typeof e)}function Wb(e){return Kb("instance",t=>t instanceof e||`Expected a \`${e.name}\` instance, but received: ${Db(t)}`)}function Hb(e){const t=Db(e),n=typeof e;return new Mb({type:"literal",schema:"string"===n||"number"===n||"boolean"===n?e:null,validator:n=>n===e||`Expected the literal \`${t}\`, but received: ${Db(n)}`})}function jb(e){return new Mb({...e,validator:(t,n)=>null===t||e.validator(t,n),refiner:(t,n)=>null===t||e.refiner(t,n)})}function Vb(){return Kb("number",e=>"number"==typeof e&&!isNaN(e)||`Expected a number, but received: ${Db(e)}`)}function Xb(e){return new Mb({...e,validator:(t,n)=>void 0===t||e.validator(t,n),refiner:(t,n)=>void 0===t||e.refiner(t,n)})}function Qb(e,t){return new Mb({type:"record",schema:null,*entries(n){if(Pb(n))for(const r in n){const i=n[r];yield[r,r,e],yield[r,i,t]}},validator:e=>Rb(e)||`Expected an object, but received: ${Db(e)}`,coercer:e=>Rb(e)?{...e}:e})}function Jb(){return Kb("string",e=>"string"==typeof e||`Expected a string, but received: ${Db(e)}`)}function Yb(e){const t=Kb("never",()=>!1);return new Mb({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: ${Db(e)}`,coercer:e=>Array.isArray(e)?e.slice():e})}function Zb(e){const t=Object.keys(e);return new Mb({type:"type",schema:e,*entries(n){if(Pb(n))for(const r of t)yield[r,n[r],e[r]]},validator:e=>Rb(e)||`Expected an object, but received: ${Db(e)}`,coercer:e=>Rb(e)?{...e}:e})}function ek(e){const t=e.map(e=>e.type).join(" | ");return new Mb({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]=Ub(n,t,r),[o]=e;if(!o[0])return[];for(const[t]of e)t&&i.push(t)}return[`Expected the value to satisfy a union of \`${t}\`, but received: ${Db(n)}`,...i]}})}function tk(){return Kb("unknown",()=>!0)}function nk(e,t,n){return new Mb({...e,coercer:(r,i)=>$b(r,t)?e.coercer(n(r,i),i):e.coercer(r,i)})}var rk,ik,ok,sk;var ak,ck=function(){if(sk)return ok;sk=1;const e=o.v4,t=function(){if(ik)return rk;ik=1;const e=o.v4;return rk=function(t,n,r,i){if("string"!=typeof t)throw new TypeError(t+" must be a string");const o="number"==typeof(i=i||{}).version?i.version:2;if(1!==o&&2!==o)throw new TypeError(o+" must be 1 or 2");const s={method:t};if(2===o&&(s.jsonrpc="2.0"),n){if("object"!=typeof n&&!Array.isArray(n))throw new TypeError(n+" must be an object, array or omitted");s.params=n}if(void 0===r){const t="function"==typeof i.generator?i.generator:function(){return e()};s.id=t(s,i)}else 2===o&&null===r?i.notificationIdNull&&(s.id=null):s.id=r;return s}}(),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 ok=n,n.prototype.request=function(e,n,r,i){const o=this;let s=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,s=e;else{"function"==typeof r&&(i=r,r=void 0);const o="function"==typeof i;try{s=t(e,n,r,{generator:this.options.generator,version:this.options.version,notificationIdNull:this.options.notificationIdNull})}catch(e){if(o)return void i(e);throw e}if(!o)return s}let c;try{c=JSON.stringify(s,this.options.replacer)}catch(e){return void i(e)}return this.callServer(c,function(e,t){o._parseResponse(e,t,i)}),s},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)}},ok}(),uk=Mc(ck),lk={};var hk,dk=(ak||(ak=1,function(e){const t=$h(),n=zh(),r="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;e.Buffer=s,e.SlowBuffer=function(e){return+e!=e&&(e=0),s.alloc(+e)},e.INSPECT_MAX_BYTES=50;const i=2147483647;function o(e){if(e>i)throw new RangeError('The value "'+e+'" is invalid for option "size"');const t=new Uint8Array(e);return Object.setPrototypeOf(t,s.prototype),t}function s(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 u(e)}return a(e,t,n)}function a(e,t,n){if("string"==typeof e)return function(e,t){if("string"==typeof t&&""!==t||(t="utf8"),!s.isEncoding(t))throw new TypeError("Unknown encoding: "+t);const n=0|f(e,t);let r=o(n);const i=r.write(e,t);return i!==n&&(r=r.slice(0,i)),r}(e,t);if(ArrayBuffer.isView(e))return function(e){if(j(e,Uint8Array)){const t=new Uint8Array(e);return h(t.buffer,t.byteOffset,t.byteLength)}return l(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(j(e,ArrayBuffer)||e&&j(e.buffer,ArrayBuffer))return h(e,t,n);if("undefined"!=typeof SharedArrayBuffer&&(j(e,SharedArrayBuffer)||e&&j(e.buffer,SharedArrayBuffer)))return h(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 s.from(r,t,n);const i=function(e){if(s.isBuffer(e)){const t=0|d(e.length),n=o(t);return 0===n.length||e.copy(n,0,0,t),n}return void 0!==e.length?"number"!=typeof e.length||V(e.length)?o(0):l(e):"Buffer"===e.type&&Array.isArray(e.data)?l(e.data):void 0}(e);if(i)return i;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return s.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 u(e){return c(e),o(e<0?0:0|d(e))}function l(e){const t=e.length<0?0:0|d(e.length),n=o(t);for(let r=0;r<t;r+=1)n[r]=255&e[r];return n}function h(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,s.prototype),r}function d(e){if(e>=i)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i.toString(16)+" bytes");return 0|e}function f(e,t){if(s.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||j(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 z(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return W(e).length;default:if(i)return r?-1:z(e).length;t=(""+t).toLowerCase(),i=!0}}function g(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 T(this,t,n);case"ascii":return I(this,t,n);case"latin1":case"binary":return x(this,t,n);case"base64":return A(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return N(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function p(e,t,n){const r=e[t];e[t]=e[n],e[n]=r}function m(e,t,n,r,i){if(0===e.length)return-1;if("string"==typeof n?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),V(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=s.from(t,r)),s.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 o,s=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;s=2,a/=2,c/=2,n/=2}function u(e,t){return 1===s?e[t]:e.readUInt16BE(t*s)}if(i){let r=-1;for(o=n;o<a;o++)if(u(e,o)===u(t,-1===r?0:o-r)){if(-1===r&&(r=o),o-r+1===c)return r*s}else-1!==r&&(o-=o-r),r=-1}else for(n+c>a&&(n=a-c),o=n;o>=0;o--){let n=!0;for(let r=0;r<c;r++)if(u(e,o+r)!==u(t,r)){n=!1;break}if(n)return o}return-1}function w(e,t,n,r){n=Number(n)||0;const i=e.length-n;r?(r=Number(r))>i&&(r=i):r=i;const o=t.length;let s;for(r>o/2&&(r=o/2),s=0;s<r;++s){const r=parseInt(t.substr(2*s,2),16);if(V(r))return s;e[n+s]=r}return s}function b(e,t,n,r){return H(z(t,e.length-n),e,n,r)}function k(e,t,n,r){return H(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 v(e,t,n,r){return H(W(t),e,n,r)}function S(e,t,n,r){return H(function(e,t){let n,r,i;const o=[];for(let s=0;s<e.length&&!((t-=2)<0);++s)n=e.charCodeAt(s),r=n>>8,i=n%256,o.push(i),o.push(r);return o}(t,e.length-n),e,n,r)}function A(e,n,r){return 0===n&&r===e.length?t.fromByteArray(e):t.fromByteArray(e.slice(n,r))}function T(e,t,n){n=Math.min(e.length,n);const r=[];let i=t;for(;i<n;){const t=e[i];let o=null,s=t>239?4:t>223?3:t>191?2:1;if(i+s<=n){let n,r,a,c;switch(s){case 1:t<128&&(o=t);break;case 2:n=e[i+1],128==(192&n)&&(c=(31&t)<<6|63&n,c>127&&(o=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)&&(o=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&&(o=c))}}null===o?(o=65533,s=1):o>65535&&(o-=65536,r.push(o>>>10&1023|55296),o=56320|1023&o),r.push(o),i+=s}return function(e){const t=e.length;if(t<=E)return String.fromCharCode.apply(String,e);let n="",r=0;for(;r<t;)n+=String.fromCharCode.apply(String,e.slice(r,r+=E));return n}(r)}e.kMaxLength=i,s.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}}(),!s.TYPED_ARRAY_SUPPORT&&"undefined"!=typeof console&&console.error,Object.defineProperty(s.prototype,"parent",{enumerable:!0,get:function(){if(s.isBuffer(this))return this.buffer}}),Object.defineProperty(s.prototype,"offset",{enumerable:!0,get:function(){if(s.isBuffer(this))return this.byteOffset}}),s.poolSize=8192,s.from=function(e,t,n){return a(e,t,n)},Object.setPrototypeOf(s.prototype,Uint8Array.prototype),Object.setPrototypeOf(s,Uint8Array),s.alloc=function(e,t,n){return function(e,t,n){return c(e),e<=0?o(e):void 0!==t?"string"==typeof n?o(e).fill(t,n):o(e).fill(t):o(e)}(e,t,n)},s.allocUnsafe=function(e){return u(e)},s.allocUnsafeSlow=function(e){return u(e)},s.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==s.prototype},s.compare=function(e,t){if(j(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),j(t,Uint8Array)&&(t=s.from(t,t.offset,t.byteLength)),!s.isBuffer(e)||!s.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,o=Math.min(n,r);i<o;++i)if(e[i]!==t[i]){n=e[i],r=t[i];break}return n<r?-1:r<n?1:0},s.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}},s.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return s.alloc(0);let n;if(void 0===t)for(t=0,n=0;n<e.length;++n)t+=e[n].length;const r=s.allocUnsafe(t);let i=0;for(n=0;n<e.length;++n){let t=e[n];if(j(t,Uint8Array))i+t.length>r.length?(s.isBuffer(t)||(t=s.from(t)),t.copy(r,i)):Uint8Array.prototype.set.call(r,t,i);else{if(!s.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(r,i)}i+=t.length}return r},s.byteLength=f,s.prototype._isBuffer=!0,s.prototype.swap16=function(){const e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let t=0;t<e;t+=2)p(this,t,t+1);return this},s.prototype.swap32=function(){const e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let t=0;t<e;t+=4)p(this,t,t+3),p(this,t+1,t+2);return this},s.prototype.swap64=function(){const e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let t=0;t<e;t+=8)p(this,t,t+7),p(this,t+1,t+6),p(this,t+2,t+5),p(this,t+3,t+4);return this},s.prototype.toString=function(){const e=this.length;return 0===e?"":0===arguments.length?T(this,0,e):g.apply(this,arguments)},s.prototype.toLocaleString=s.prototype.toString,s.prototype.equals=function(e){if(!s.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===s.compare(this,e)},s.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&&(s.prototype[r]=s.prototype.inspect),s.prototype.compare=function(e,t,n,r,i){if(j(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),!s.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 o=(i>>>=0)-(r>>>=0),a=(n>>>=0)-(t>>>=0);const c=Math.min(o,a),u=this.slice(r,i),l=e.slice(t,n);for(let e=0;e<c;++e)if(u[e]!==l[e]){o=u[e],a=l[e];break}return o<a?-1:a<o?1:0},s.prototype.includes=function(e,t,n){return-1!==this.indexOf(e,t,n)},s.prototype.indexOf=function(e,t,n){return m(this,e,t,n,!0)},s.prototype.lastIndexOf=function(e,t,n){return m(this,e,t,n,!1)},s.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 o=!1;for(;;)switch(r){case"hex":return w(this,e,t,n);case"utf8":case"utf-8":return b(this,e,t,n);case"ascii":case"latin1":case"binary":return k(this,e,t,n);case"base64":return v(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return S(this,e,t,n);default:if(o)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),o=!0}},s.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const E=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 x(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 N(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 B(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 _(e,t,n,r,i,o){if(!s.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||t<o)throw new RangeError('"value" argument is out of bounds');if(n+r>e.length)throw new RangeError("Index out of range")}function P(e,t,n,r,i){$(t,r,i,e,n,7);let o=Number(t&BigInt(4294967295));e[n++]=o,o>>=8,e[n++]=o,o>>=8,e[n++]=o,o>>=8,e[n++]=o;let s=Number(t>>BigInt(32)&BigInt(4294967295));return e[n++]=s,s>>=8,e[n++]=s,s>>=8,e[n++]=s,s>>=8,e[n++]=s,n}function R(e,t,n,r,i){$(t,r,i,e,n,7);let o=Number(t&BigInt(4294967295));e[n+7]=o,o>>=8,e[n+6]=o,o>>=8,e[n+5]=o,o>>=8,e[n+4]=o;let s=Number(t>>BigInt(32)&BigInt(4294967295));return e[n+3]=s,s>>=8,e[n+2]=s,s>>=8,e[n+1]=s,s>>=8,e[n]=s,n+8}function D(e,t,n,r,i,o){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function L(e,t,r,i,o){return t=+t,r>>>=0,o||D(e,0,r,4),n.write(e,t,r,i,23,4),r+4}function O(e,t,r,i,o){return t=+t,r>>>=0,o||D(e,0,r,8),n.write(e,t,r,i,52,8),r+8}s.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,s.prototype),r},s.prototype.readUintLE=s.prototype.readUIntLE=function(e,t,n){e>>>=0,t>>>=0,n||B(e,t,this.length);let r=this[e],i=1,o=0;for(;++o<t&&(i*=256);)r+=this[e+o]*i;return r},s.prototype.readUintBE=s.prototype.readUIntBE=function(e,t,n){e>>>=0,t>>>=0,n||B(e,t,this.length);let r=this[e+--t],i=1;for(;t>0&&(i*=256);)r+=this[e+--t]*i;return r},s.prototype.readUint8=s.prototype.readUInt8=function(e,t){return e>>>=0,t||B(e,1,this.length),this[e]},s.prototype.readUint16LE=s.prototype.readUInt16LE=function(e,t){return e>>>=0,t||B(e,2,this.length),this[e]|this[e+1]<<8},s.prototype.readUint16BE=s.prototype.readUInt16BE=function(e,t){return e>>>=0,t||B(e,2,this.length),this[e]<<8|this[e+1]},s.prototype.readUint32LE=s.prototype.readUInt32LE=function(e,t){return e>>>=0,t||B(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},s.prototype.readUint32BE=s.prototype.readUInt32BE=function(e,t){return e>>>=0,t||B(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},s.prototype.readBigUInt64LE=Q(function(e){q(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||K(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))}),s.prototype.readBigUInt64BE=Q(function(e){q(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||K(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)}),s.prototype.readIntLE=function(e,t,n){e>>>=0,t>>>=0,n||B(e,t,this.length);let r=this[e],i=1,o=0;for(;++o<t&&(i*=256);)r+=this[e+o]*i;return i*=128,r>=i&&(r-=Math.pow(2,8*t)),r},s.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||B(e,t,this.length);let r=t,i=1,o=this[e+--r];for(;r>0&&(i*=256);)o+=this[e+--r]*i;return i*=128,o>=i&&(o-=Math.pow(2,8*t)),o},s.prototype.readInt8=function(e,t){return e>>>=0,t||B(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},s.prototype.readInt16LE=function(e,t){e>>>=0,t||B(e,2,this.length);const n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},s.prototype.readInt16BE=function(e,t){e>>>=0,t||B(e,2,this.length);const n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},s.prototype.readInt32LE=function(e,t){return e>>>=0,t||B(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},s.prototype.readInt32BE=function(e,t){return e>>>=0,t||B(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},s.prototype.readBigInt64LE=Q(function(e){q(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||K(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)}),s.prototype.readBigInt64BE=Q(function(e){q(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||K(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)}),s.prototype.readFloatLE=function(e,t){return e>>>=0,t||B(e,4,this.length),n.read(this,e,!0,23,4)},s.prototype.readFloatBE=function(e,t){return e>>>=0,t||B(e,4,this.length),n.read(this,e,!1,23,4)},s.prototype.readDoubleLE=function(e,t){return e>>>=0,t||B(e,8,this.length),n.read(this,e,!0,52,8)},s.prototype.readDoubleBE=function(e,t){return e>>>=0,t||B(e,8,this.length),n.read(this,e,!1,52,8)},s.prototype.writeUintLE=s.prototype.writeUIntLE=function(e,t,n,r){e=+e,t>>>=0,n>>>=0,r||_(this,e,t,n,Math.pow(2,8*n)-1,0);let i=1,o=0;for(this[t]=255&e;++o<n&&(i*=256);)this[t+o]=e/i&255;return t+n},s.prototype.writeUintBE=s.prototype.writeUIntBE=function(e,t,n,r){e=+e,t>>>=0,n>>>=0,r||_(this,e,t,n,Math.pow(2,8*n)-1,0);let i=n-1,o=1;for(this[t+i]=255&e;--i>=0&&(o*=256);)this[t+i]=e/o&255;return t+n},s.prototype.writeUint8=s.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||_(this,e,t,1,255,0),this[t]=255&e,t+1},s.prototype.writeUint16LE=s.prototype.writeUInt16LE=function(e,t,n){return e=+e,t>>>=0,n||_(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},s.prototype.writeUint16BE=s.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||_(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},s.prototype.writeUint32LE=s.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||_(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},s.prototype.writeUint32BE=s.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||_(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},s.prototype.writeBigUInt64LE=Q(function(e,t=0){return P(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),s.prototype.writeBigUInt64BE=Q(function(e,t=0){return R(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),s.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t>>>=0,!r){const r=Math.pow(2,8*n-1);_(this,e,t,n,r-1,-r)}let i=0,o=1,s=0;for(this[t]=255&e;++i<n&&(o*=256);)e<0&&0===s&&0!==this[t+i-1]&&(s=1),this[t+i]=(e/o|0)-s&255;return t+n},s.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t>>>=0,!r){const r=Math.pow(2,8*n-1);_(this,e,t,n,r-1,-r)}let i=n-1,o=1,s=0;for(this[t+i]=255&e;--i>=0&&(o*=256);)e<0&&0===s&&0!==this[t+i+1]&&(s=1),this[t+i]=(e/o|0)-s&255;return t+n},s.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||_(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},s.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||_(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},s.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||_(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},s.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||_(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},s.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||_(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},s.prototype.writeBigInt64LE=Q(function(e,t=0){return P(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),s.prototype.writeBigInt64BE=Q(function(e,t=0){return R(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),s.prototype.writeFloatLE=function(e,t,n){return L(this,e,t,!0,n)},s.prototype.writeFloatBE=function(e,t,n){return L(this,e,t,!1,n)},s.prototype.writeDoubleLE=function(e,t,n){return O(this,e,t,!0,n)},s.prototype.writeDoubleBE=function(e,t,n){return O(this,e,t,!1,n)},s.prototype.copy=function(e,t,n,r){if(!s.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},s.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&&!s.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 o=s.isBuffer(e)?e:s.from(e,r),a=o.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]=o[i%a]}return this};const U={};function M(e,t,n){U[e]=class extends n{constructor(){super(),Object.defineProperty(this,"message",{value:t.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${e}]`,this.stack,delete this.name}get code(){return e}set code(e){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:e,writable:!0})}toString(){return`${this.name} [${e}]: ${this.message}`}}}function F(e){let t="",n=e.length;const r="-"===e[0]?1:0;for(;n>=r+4;n-=3)t=`_${e.slice(n-3,n)}${t}`;return`${e.slice(0,n)}${t}`}function $(e,t,n,r,i,o){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*(o+1)}${n}`:`>= -(2${n} ** ${8*(o+1)-1}${n}) and < 2 ** ${8*(o+1)-1}${n}`,new U.ERR_OUT_OF_RANGE("value",r,e)}!function(e,t,n){q(t,"offset"),void 0!==e[t]&&void 0!==e[t+n]||K(t,e.length-(n+1))}(r,i,o)}function q(e,t){if("number"!=typeof e)throw new U.ERR_INVALID_ARG_TYPE(t,"number",e)}function K(e,t,n){if(Math.floor(e)!==e)throw q(e,n),new U.ERR_OUT_OF_RANGE("offset","an integer",e);if(t<0)throw new U.ERR_BUFFER_OUT_OF_BOUNDS;throw new U.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${t}`,e)}M("ERR_BUFFER_OUT_OF_BOUNDS",function(e){return e?`${e} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),M("ERR_INVALID_ARG_TYPE",function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`},TypeError),M("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 G=/[^+/0-9A-Za-z-_]/g;function z(e,t){let n;t=t||1/0;const r=e.length;let i=null;const o=[];for(let s=0;s<r;++s){if(n=e.charCodeAt(s),n>55295&&n<57344){if(!i){if(n>56319){(t-=3)>-1&&o.push(239,191,189);continue}if(s+1===r){(t-=3)>-1&&o.push(239,191,189);continue}i=n;continue}if(n<56320){(t-=3)>-1&&o.push(239,191,189),i=n;continue}n=65536+(i-55296<<10|n-56320)}else i&&(t-=3)>-1&&o.push(239,191,189);if(i=null,n<128){if((t-=1)<0)break;o.push(n)}else if(n<2048){if((t-=2)<0)break;o.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;o.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;o.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return o}function W(e){return t.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(G,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function H(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 j(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function V(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 Q(e){return"undefined"==typeof BigInt?J:e}function J(){throw new Error("BigInt not supported")}}(lk)),lk),fk={exports:{}};var gk=(hk||(hk=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 o(e,t,r,o,s){if("function"!=typeof r)throw new TypeError("The listener must be a function");var a=new i(r,o||e,s),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 s(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,o=r.length,s=new Array(o);i<o;i++)s[i]=r[i].fn;return s},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,o,s){var a=n?n+e:e;if(!this._events[a])return!1;var c,u,l=this._events[a],h=arguments.length;if(l.fn){switch(l.once&&this.removeListener(e,l.fn,void 0,!0),h){case 1:return l.fn.call(l.context),!0;case 2:return l.fn.call(l.context,t),!0;case 3:return l.fn.call(l.context,t,r),!0;case 4:return l.fn.call(l.context,t,r,i),!0;case 5:return l.fn.call(l.context,t,r,i,o),!0;case 6:return l.fn.call(l.context,t,r,i,o,s),!0}for(u=1,c=new Array(h-1);u<h;u++)c[u-1]=arguments[u];l.fn.apply(l.context,c)}else{var d,f=l.length;for(u=0;u<f;u++)switch(l[u].once&&this.removeListener(e,l[u].fn,void 0,!0),h){case 1:l[u].fn.call(l[u].context);break;case 2:l[u].fn.call(l[u].context,t);break;case 3:l[u].fn.call(l[u].context,t,r);break;case 4:l[u].fn.call(l[u].context,t,r,i);break;default:if(!c)for(d=1,c=new Array(h-1);d<h;d++)c[d-1]=arguments[d];l[u].fn.apply(l[u].context,c)}}return!0},a.prototype.on=function(e,t,n){return o(this,e,t,n,!1)},a.prototype.once=function(e,t,n){return o(this,e,t,n,!0)},a.prototype.removeListener=function(e,t,r,i){var o=n?n+e:e;if(!this._events[o])return this;if(!t)return s(this,o),this;var a=this._events[o];if(a.fn)a.fn!==t||i&&!a.once||r&&a.context!==r||s(this,o);else{for(var c=0,u=[],l=a.length;c<l;c++)(a[c].fn!==t||i&&!a[c].once||r&&a[c].context!==r)&&u.push(a[c]);u.length?this._events[o]=1===u.length?u[0]:u:s(this,o)}return this},a.prototype.removeAllListeners=function(e){var t;return e?(t=n?n+e:e,this._events[t]&&s(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}(fk)),fk.exports),pk=Mc(gk),mk=class extends pk{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 yk=class{encode(e){return JSON.stringify(e)}decode(e){return JSON.parse(e)}},wk=class extends pk{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:o=5,...s}={},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=o,this.rest_options=s,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 yk,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,o)=>{if(!this.ready)return o(new Error("socket not ready"));const s=this.generate_request_id(e,t),a={jsonrpc:"2.0",method:e,params:t||void 0,id:s};this.socket.send(this.dataPack.encode(a),r,e=>{if(e)return o(e);this.queue[s]={promise:[i,o]},n&&(this.queue[s].timeout=setTimeout(()=>{delete this.queue[s],o(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=dk.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 bk extends gd{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,Qh(e);const n=dd(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),Yh(i)}update(e){return Jh(this),this.iHash.update(e),this}digestInto(e){Jh(this),Xh(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:o,outputLen:s}=this;return e.finished=r,e.destroyed=i,e.blockLen=o,e.outputLen=s,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 kk=(e,t,n)=>new bk(e,t).update(n).digest();kk.create=(e,t)=>new bk(e,t);const vk=(e,t)=>(e+(e>=0?t:-t)/Ck)/t;function Sk(e){if(!["compact","recovered","der"].includes(e))throw new Error('Signature format must be "compact", "recovered", or "der"');return e}function Ak(e,t){const n={};for(let r of Object.keys(t))n[r]=void 0===e[r]?t[r]:e[r];return Jd(n.lowS,"lowS"),Jd(n.prehash,"prehash"),void 0!==n.format&&Sk(n.format),n}class Tk extends Error{constructor(e=""){super(e)}}const Ek={Err:Tk,_tlv:{encode:(e,t)=>{const{Err:n}=Ek;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=Zd(r);if(i.length/2&128)throw new n("tlv.encode: long form length too big");const o=r>127?Zd(i.length/2|128):"";return Zd(e)+o+i+t},decode(e,t){const{Err:n}=Ek;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 o=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 s=t.subarray(r,r+e);if(s.length!==e)throw new n("tlv.decode: length bytes not complete");if(0===s[0])throw new n("tlv.decode(long): zero leftmost byte");for(const e of s)o=o<<8|e;if(r+=e,o<128)throw new n("tlv.decode(long): not minimal encoding")}else o=i;const s=t.subarray(r,r+o);if(s.length!==o)throw new n("tlv.decode: wrong value length");return{v:s,l:t.subarray(r+o)}}},_int:{encode(e){const{Err:t}=Ek;if(e<Ik)throw new t("integer: negative integers are not allowed");let n=Zd(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}=Ek;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 tf(e)}},toSig(e){const{Err:t,_int:n,_tlv:r}=Ek,i=sf("signature",e),{v:o,l:s}=r.decode(48,i);if(s.length)throw new t("invalid signature: left bytes after parsing");const{v:a,l:c}=r.decode(2,o),{v:u,l:l}=r.decode(2,c);if(l.length)throw new t("invalid signature: left bytes after parsing");return{r:n.decode(a),s:n.decode(u)}},hexFromSig(e){const{_tlv:t,_int:n}=Ek,r=t.encode(2,n.encode(e.r))+t.encode(2,n.encode(e.s));return t.encode(48,r)}},Ik=BigInt(0),xk=BigInt(1),Ck=BigInt(2),Nk=BigInt(3),Bk=BigInt(4);function _k(e,t){const{BYTES:n}=e;let r;if("bigint"==typeof t)r=t;else{let i=sf("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 Pk(e,t={}){const n=Zf("weierstrass",e,t),{Fp:r,Fn:i}=n;let o=n.CURVE;const{h:s,n:a}=o;df(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:c}=t;if(c&&(!r.is0(o.a)||"bigint"!=typeof c.beta||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const u=Dk(r,i);function l(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}const h=t.toBytes||function(e,t,n){const{x:i,y:o}=t.toAffine(),s=r.toBytes(i);if(Jd(n,"isCompressed"),n){l();return fd(Rk(!r.isOdd(o)),s)}return fd(Uint8Array.of(4),s,r.toBytes(o))},d=t.fromBytes||function(e){Yd(e,void 0,"Point");const{publicKey:t,publicKeyUncompressed:n}=u,i=e.length,o=e[0],s=e.subarray(1);if(i!==t||2!==o&&3!==o){if(i===n&&4===o){const e=r.BYTES,t=r.fromBytes(s.subarray(0,e)),n=r.fromBytes(s.subarray(e,2*e));if(!g(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(s);if(!r.isValid(e))throw new Error("bad point: is not on curve, wrong x");const t=f(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)}l();return!(1&~o)!==r.isOdd(n)&&(n=r.neg(n)),{x:e,y:n}}};function f(e){const t=r.sqr(e),n=r.mul(t,e);return r.add(r.add(n,r.mul(e,o.a)),o.b)}function g(e,t){const n=r.sqr(t),i=f(e);return r.eql(n,i)}if(!g(o.Gx,o.Gy))throw new Error("bad curve params: generator point");const p=r.mul(r.pow(o.a,Nk),Bk),m=r.mul(r.sqr(o.b),BigInt(27));if(r.is0(r.add(p,m)))throw new Error("bad curve params: a or b");function y(e,t,n=!1){if(!r.isValid(t)||n&&r.is0(t))throw new Error(`bad point coordinate ${e}`);return t}function w(e){if(!(e instanceof A))throw new Error("ProjectivePoint expected")}function b(e){if(!c||!c.basises)throw new Error("no endo");return function(e,t,n){const[[r,i],[o,s]]=t,a=vk(s*e,n),c=vk(-i*e,n);let u=e-a*r-c*o,l=-a*i-c*s;const h=u<Ik,d=l<Ik;h&&(u=-u),d&&(l=-l);const f=hf(Math.ceil(lf(n)/2))+xk;if(u<Ik||u>=f||l<Ik||l>=f)throw new Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:h,k1:u,k2neg:d,k2:l}}(e,c.basises,i.ORDER)}const k=ff((e,t)=>{const{X:n,Y:i,Z:o}=e;if(r.eql(o,r.ONE))return{x:n,y:i};const s=e.is0();null==t&&(t=s?r.ONE:r.inv(o));const a=r.mul(n,t),c=r.mul(i,t),u=r.mul(o,t);if(s)return{x:r.ZERO,y:r.ZERO};if(!r.eql(u,r.ONE))throw new Error("invZ was invalid");return{x:a,y:c}}),v=ff(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(!g(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 S(e,t,n,i,o){return n=new A(r.mul(n.X,e),n.Y,n.Z),t=qf(i,t),n=qf(o,n),t.add(n)}class A{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 o}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 A)throw new Error("projective point not allowed");return r.is0(t)&&r.is0(n)?A.ZERO:new A(t,n,r.ONE)}static fromBytes(e){const t=A.fromAffine(d(Yd(e,void 0,"point")));return t.assertValidity(),t}static fromHex(e){return A.fromBytes(sf("pointHex",e))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(e=8,t=!0){return E.createCache(this,e),t||this.multiply(Nk),this}assertValidity(){v(this)}hasEvenY(){const{y:e}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(e)}equals(e){w(e);const{X:t,Y:n,Z:i}=this,{X:o,Y:s,Z:a}=e,c=r.eql(r.mul(t,a),r.mul(o,i)),u=r.eql(r.mul(n,a),r.mul(s,i));return c&&u}negate(){return new A(this.X,r.neg(this.Y),this.Z)}double(){const{a:e,b:t}=o,n=r.mul(t,Nk),{X:i,Y:s,Z:a}=this;let c=r.ZERO,u=r.ZERO,l=r.ZERO,h=r.mul(i,i),d=r.mul(s,s),f=r.mul(a,a),g=r.mul(i,s);return g=r.add(g,g),l=r.mul(i,a),l=r.add(l,l),c=r.mul(e,l),u=r.mul(n,f),u=r.add(c,u),c=r.sub(d,u),u=r.add(d,u),u=r.mul(c,u),c=r.mul(g,c),l=r.mul(n,l),f=r.mul(e,f),g=r.sub(h,f),g=r.mul(e,g),g=r.add(g,l),l=r.add(h,h),h=r.add(l,h),h=r.add(h,f),h=r.mul(h,g),u=r.add(u,h),f=r.mul(s,a),f=r.add(f,f),h=r.mul(f,g),c=r.sub(c,h),l=r.mul(f,d),l=r.add(l,l),l=r.add(l,l),new A(c,u,l)}add(e){w(e);const{X:t,Y:n,Z:i}=this,{X:s,Y:a,Z:c}=e;let u=r.ZERO,l=r.ZERO,h=r.ZERO;const d=o.a,f=r.mul(o.b,Nk);let g=r.mul(t,s),p=r.mul(n,a),m=r.mul(i,c),y=r.add(t,n),b=r.add(s,a);y=r.mul(y,b),b=r.add(g,p),y=r.sub(y,b),b=r.add(t,i);let k=r.add(s,c);return b=r.mul(b,k),k=r.add(g,m),b=r.sub(b,k),k=r.add(n,i),u=r.add(a,c),k=r.mul(k,u),u=r.add(p,m),k=r.sub(k,u),h=r.mul(d,b),u=r.mul(f,m),h=r.add(u,h),u=r.sub(p,h),h=r.add(p,h),l=r.mul(u,h),p=r.add(g,g),p=r.add(p,g),m=r.mul(d,m),b=r.mul(f,b),p=r.add(p,m),m=r.sub(g,m),m=r.mul(d,m),b=r.add(b,m),g=r.mul(p,b),l=r.add(l,g),g=r.mul(k,b),u=r.mul(y,u),u=r.sub(u,g),g=r.mul(y,p),h=r.mul(k,h),h=r.add(h,g),new A(u,l,h)}subtract(e){return this.add(e.negate())}is0(){return this.equals(A.ZERO)}multiply(e){const{endo:n}=t;if(!i.isValidNot0(e))throw new Error("invalid scalar: out of range");let r,o;const s=e=>E.cached(this,e,e=>Kf(A,e));if(n){const{k1neg:t,k1:i,k2neg:a,k2:c}=b(e),{p:u,f:l}=s(i),{p:h,f:d}=s(c);o=l.add(d),r=S(n.beta,u,h,t,a)}else{const{p:t,f:n}=s(e);r=t,o=n}return Kf(A,[r,o])[0]}multiplyUnsafe(e){const{endo:n}=t,r=this;if(!i.isValid(e))throw new Error("invalid scalar: out of range");if(e===Ik||r.is0())return A.ZERO;if(e===xk)return r;if(E.hasCache(this))return this.multiply(e);if(n){const{k1neg:t,k1:i,k2neg:o,k2:s}=b(e),{p1:a,p2:c}=function(e,t,n,r){let i=t,o=e.ZERO,s=e.ZERO;for(;n>Ff||r>Ff;)n&$f&&(o=o.add(i)),r&$f&&(s=s.add(i)),i=i.double(),n>>=$f,r>>=$f;return{p1:o,p2:s}}(A,r,i,s);return S(n.beta,a,c,t,o)}return E.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 k(this,e)}isTorsionFree(){const{isTorsionFree:e}=t;return s===xk||(e?e(A,this):E.unsafe(this,a).is0())}clearCofactor(){const{clearCofactor:e}=t;return s===xk?this:e?e(A,this):this.multiplyUnsafe(s)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}toBytes(e=!0){return Jd(e,"isCompressed"),this.assertValidity(),h(A,this,e)}toHex(e=!0){return rd(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 Kf(A,e)}static msm(e,t){return Jf(A,i,e,t)}static fromPrivateKey(e){return A.BASE.multiply(_k(i,e))}}A.BASE=new A(o.Gx,o.Gy,r.ONE),A.ZERO=new A(r.ZERO,r.ONE,r.ZERO),A.Fp=r,A.Fn=i;const T=i.BITS,E=new Qf(A,t.endo?Math.ceil(T/2):T);return A.BASE.precompute(8),A}function Rk(e){return Uint8Array.of(e?2:3)}function Dk(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function Lk(e,t={}){const{Fn:n}=e,r=t.randomBytes||md,i=Object.assign(Dk(e.Fp,n),{seed:Mf(n.ORDER)});function o(e){try{return!!_k(n,e)}catch(e){return!1}}function s(e=r(i.seed)){return function(e,t,n=!1){const r=e.length,i=Uf(t),o=Mf(t);if(r<16||r<o||r>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+r);const s=Tf(n?nf(e):tf(e),t-pf)+pf;return n?of(s,i):rf(s,i)}(Yd(e,i.seed,"seed"),n.ORDER)}function a(t,r=!0){return e.BASE.multiply(_k(n,t)).toBytes(r)}function c(t){if("bigint"==typeof t)return!1;if(t instanceof e)return!0;const{secretKey:r,publicKey:o,publicKeyUncompressed:s}=i;if(n.allowedLengths||r===o)return;const a=sf("key",t).length;return a===o||a===s}const u={isValidSecretKey:o,isValidPublicKey:function(t,n){const{publicKey:r,publicKeyUncompressed:o}=i;try{const i=t.length;return(!0!==n||i===r)&&((!1!==n||i===o)&&!!e.fromBytes(t))}catch(e){return!1}},randomSecretKey:s,isValidPrivateKey:o,randomPrivateKey:s,normPrivateKeyToScalar:e=>_k(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 o=_k(n,t);return e.fromHex(r).multiply(o).toBytes(i)},keygen:function(e){const t=s(e);return{secretKey:t,publicKey:a(t)}},Point:e,utils:u,lengths:i})}function Ok(e,t,n={}){Qh(t),df(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const r=n.randomBytes||md,i=n.hmac||((e,...n)=>kk(t,e,fd(...n))),{Fp:o,Fn:s}=e,{ORDER:a,BITS:c}=s,{keygen:u,getPublicKey:l,getSharedSecret:h,utils:d,lengths:f}=Lk(e,n),g={prehash:!1,lowS:"boolean"==typeof n.lowS&&n.lowS,format:void 0,extraEntropy:!1},p="compact";function m(e){return e>a>>xk}function y(e,t){if(!s.isValidNot0(t))throw new Error(`invalid signature ${e}: out of range 1..Point.Fn.ORDER`);return t}class w{constructor(e,t,n){this.r=y("r",e),this.s=y("s",t),null!=n&&(this.recovery=n),Object.freeze(this)}static fromBytes(e,t=p){let n;if(function(e,t){Sk(t);const n=f.signature;Yd(e,"compact"===t?n:"recovered"===t?n+1:void 0,`${t} signature`)}(e,t),"der"===t){const{r:t,s:n}=Ek.toSig(Yd(e));return new w(t,n)}"recovered"===t&&(n=e[0],t="compact",e=e.subarray(1));const r=s.BYTES,i=e.subarray(0,r),o=e.subarray(r,2*r);return new w(s.fromBytes(i),s.fromBytes(o),n)}static fromHex(e,t){return this.fromBytes(hd(e),t)}addRecoveryBit(e){return new w(this.r,this.s,e)}recoverPublicKey(t){const n=o.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*Ck<n&&c>1)throw new Error("recovery id is ambiguous for h>1 curve");const u=2===c||3===c?r+a:r;if(!o.isValid(u))throw new Error("recovery id 2 or 3 invalid");const l=o.toBytes(u),h=e.fromBytes(fd(Rk(!(1&c)),l)),d=s.inv(u),f=k(sf("msgHash",t)),g=s.create(-f*d),p=s.create(i*d),m=e.BASE.multiplyUnsafe(g).add(h.multiplyUnsafe(p));if(m.is0())throw new Error("point at infinify");return m.assertValidity(),m}hasHighS(){return m(this.s)}toBytes(e=p){if(Sk(e),"der"===e)return hd(Ek.hexFromSig(this));const t=s.toBytes(this.r),n=s.toBytes(this.s);if("recovered"===e){if(null==this.recovery)throw new Error("recovery bit must be present");return fd(Uint8Array.of(this.recovery),t,n)}return fd(t,n)}toHex(e){return rd(this.toBytes(e))}assertValidity(){}static fromCompact(e){return w.fromBytes(sf("sig",e),"compact")}static fromDER(e){return w.fromBytes(sf("sig",e),"der")}normalizeS(){return this.hasHighS()?new w(this.r,s.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return rd(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return rd(this.toBytes("compact"))}}const b=n.bits2int||function(e){if(e.length>8192)throw new Error("input is too large");const t=tf(e),n=8*e.length-c;return n>0?t>>BigInt(n):t},k=n.bits2int_modN||function(e){return s.create(b(e))},v=hf(c);function S(e){return uf("num < 2^"+c,e,Ik,v),s.toBytes(e)}function A(e,n){return Yd(e,void 0,"message"),n?Yd(t(e),void 0,"prehashed message"):e}return Object.freeze({keygen:u,getPublicKey:l,getSharedSecret:h,utils:d,lengths:f,Point:e,sign:function(n,o,a={}){n=sf("message",n);const{seed:c,k2sig:u}=function(t,n,i){if(["recovered","canonical"].some(e=>e in i))throw new Error("sign() legacy options not supported");const{lowS:o,prehash:a,extraEntropy:c}=Ak(i,g);t=A(t,a);const u=k(t),l=_k(s,n),h=[S(l),S(u)];if(null!=c&&!1!==c){const e=!0===c?r(f.secretKey):c;h.push(sf("extraEntropy",e))}const d=fd(...h),p=u;return{seed:d,k2sig:function(t){const n=b(t);if(!s.isValidNot0(n))return;const r=s.inv(n),i=e.BASE.multiply(n).toAffine(),a=s.create(i.x);if(a===Ik)return;const c=s.create(r*s.create(p+a*l));if(c===Ik)return;let u=(i.x===a?0:2)|Number(i.y&xk),h=c;return o&&m(c)&&(h=s.neg(c),u^=1),new w(a,h,u)}}}(n,o,a),l=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 o=r(e),s=r(e),a=0;const c=()=>{o.fill(1),s.fill(0),a=0},u=(...e)=>n(s,o,...e),l=(e=r(0))=>{s=u(i(0),e),o=u(),0!==e.length&&(s=u(i(1),e),o=u())},h=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let e=0;const n=[];for(;e<t;){o=u();const t=o.slice();n.push(t),e+=o.length}return fd(...n)};return(e,t)=>{let n;for(c(),l(e);!(n=t(h()));)l();return c(),n}}(t.outputLen,s.BYTES,i);return l(c,u)},verify:function(t,n,r,i={}){const{lowS:o,prehash:a,format:c}=Ak(i,g);if(r=sf("publicKey",r),n=A(sf("message",n),a),"strict"in i)throw new Error("options.strict was renamed to lowS");const u=void 0===c?function(e){let t;const n="string"==typeof e||jh(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 w(e.r,e.s);else if(n){try{t=w.fromBytes(sf("sig",e),"der")}catch(e){if(!(e instanceof Ek.Err))throw e}if(!t)try{t=w.fromBytes(sf("sig",e),"compact")}catch(e){return!1}}return t||!1}(t):w.fromBytes(sf("sig",t),c);if(!1===u)return!1;try{const t=e.fromBytes(r);if(o&&u.hasHighS())return!1;const{r:i,s:a}=u,c=k(n),l=s.inv(a),h=s.create(c*l),d=s.create(i*l),f=e.BASE.multiplyUnsafe(h).add(t.multiplyUnsafe(d));if(f.is0())return!1;return s.create(f.x)===i}catch(e){return!1}},recoverPublicKey:function(e,t,n={}){const{prehash:r}=Ak(n,g);return t=A(t,r),w.fromBytes(e,"recovered").recoverPublicKey(t).toBytes()},Signature:w,hash:t})}function Uk(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:Of(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 Mk(e){const{CURVE:t,curveOpts:n,hash:r,ecdsaOpts:i}=Uk(e);return function(e,t){const n=t.Point;return Object.assign({},t,{ProjectivePoint:n,CURVE:Object.assign({},e,Lf(n.Fn.ORDER,n.Fn.BITS))})}(e,Ok(Pk(t,n),r,i))}const Fk={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},$k={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},qk=BigInt(2);const Kk=Of(Fk.p,{sqrt:function(e){const t=Fk.p,n=BigInt(3),r=BigInt(6),i=BigInt(11),o=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),u=e*e*e%t,l=u*u*e%t,h=Ef(l,n,t)*l%t,d=Ef(h,n,t)*l%t,f=Ef(d,qk,t)*u%t,g=Ef(f,i,t)*f%t,p=Ef(g,o,t)*g%t,m=Ef(p,a,t)*p%t,y=Ef(m,c,t)*m%t,w=Ef(y,a,t)*p%t,b=Ef(w,n,t)*l%t,k=Ef(b,s,t)*g%t,v=Ef(k,r,t)*u%t,S=Ef(v,qk,t);if(!Kk.eql(Kk.sqr(S),e))throw new Error("Cannot find square root");return S}}),Gk=function(e,t){const n=t=>Mk({...e,hash:t});return{...n(t),create:n}}({...Fk,Fp:Kk,lowS:!0,endo:$k},jd);yg.utils.randomPrivateKey;const zk=()=>{const e=yg.utils.randomPrivateKey(),t=Wk(e),n=new Uint8Array(64);return n.set(e),n.set(t,32),{publicKey:t,secretKey:n}},Wk=yg.getPublicKey;function Hk(e){try{return yg.ExtendedPoint.fromHex(e),!0}catch{return!1}}const jk=yg.verify,Vk=e=>Wh.Buffer.isBuffer(e)?e:e instanceof Uint8Array?Wh.Buffer.from(e.buffer,e.byteOffset,e.byteLength):Wh.Buffer.from(e);class Xk{constructor(e){Object.assign(this,e)}encode(){return Wh.Buffer.from(rp.serialize(Qk,this))}static decode(e){return rp.deserialize(Qk,this,e)}static decodeUnchecked(e){return rp.deserializeUnchecked(Qk,this,e)}}const Qk=new Map;var Jk;const Yk=32;let Zk=1;class ev extends Xk{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=Lg.decode(e);if(t.length!=Yk)throw new Error("Invalid public key input");this._bn=new Ng(t)}else this._bn=new Ng(e);if(this._bn.byteLength()>Yk)throw new Error("Invalid public key input")}}static unique(){const e=new ev(Zk);return Zk+=1,new ev(e.toBuffer())}equals(e){return this._bn.eq(e._bn)}toBase58(){return Lg.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(Wh.Buffer);if(e.length===Yk)return e;const t=Wh.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=Wh.Buffer.concat([e.toBuffer(),Wh.Buffer.from(t),n.toBuffer()]),i=Og(r);return new ev(i)}static createProgramAddressSync(e,t){let n=Wh.Buffer.alloc(0);e.forEach(function(e){if(e.length>32)throw new TypeError("Max seed length exceeded");n=Wh.Buffer.concat([n,Vk(e)])}),n=Wh.Buffer.concat([n,t.toBuffer(),Wh.Buffer.from("ProgramDerivedAddress")]);const r=Og(n);if(Hk(r))throw new Error("Invalid seeds, address must fall off the curve");return new ev(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(Wh.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 Hk(new ev(e).toBytes())}}Jk=ev,ev.default=new Jk("11111111111111111111111111111111"),Qk.set(ev,{kind:"struct",fields:[["_bn","u256"]]}),new ev("BPFLoader1111111111111111111111111111111111");const tv=1232;class nv extends Error{constructor(e){super(`Signature ${e} has expired: block height exceeded.`),this.signature=void 0,this.signature=e}}Object.defineProperty(nv.prototype,"name",{value:"TransactionExpiredBlockheightExceededError"});class rv 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(rv.prototype,"name",{value:"TransactionExpiredTimeoutError"});class iv extends Error{constructor(e){super(`Signature ${e} has expired: the nonce is no longer valid.`),this.signature=void 0,this.signature=e}}Object.defineProperty(iv.prototype,"name",{value:"TransactionExpiredNonceInvalidError"});class ov{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 sv=(e="publicKey")=>ap.blob(32,e),av=(e="string")=>{const t=ap.struct([ap.u32("length"),ap.u32("lengthPadding"),ap.blob(ap.offset(ap.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:Wh.Buffer.from(e,"utf8")};return r(i,t,n)},i.alloc=e=>ap.u32().span+ap.u32().span+Wh.Buffer.from(e,"utf8").length,i};function cv(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 cv({layout:e},t[e.property]);return 0};let r=0;return e.layout.fields.forEach(e=>{r+=n(e)}),r}function uv(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 lv(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 hv(e,t){if(!e)throw new Error(t||"Assertion failed")}class dv{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 dv(t,n)}getMessageComponents(){const e=[...this.keyMetaMap.entries()];hv(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),o={numRequiredSignatures:t.length+n.length,numReadonlySignedAccounts:n.length,numReadonlyUnsignedAccounts:i.length};{hv(t.length>0,"Expected at least one writable signer key");const[e]=t[0];hv(e===this.payer.toBase58(),"Expected first writable signer key to be the fee payer")}return[o,[...t.map(([e])=>new ev(e)),...n.map(([e])=>new ev(e)),...r.map(([e])=>new ev(e)),...i.map(([e])=>new ev(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,o]of this.keyMetaMap.entries())if(t(o)){const t=new ev(i),o=e.findIndex(e=>e.equals(t));o>=0&&(hv(o<256,"Max lookup table index exceeded"),n.push(o),r.push(t),this.keyMetaMap.delete(i))}return[n,r]}}const fv="Reached end of buffer unexpectedly";function gv(e){if(0===e.length)throw new Error(fv);return e.shift()}function pv(e,...t){const[n]=t;if(2===t.length?n+(t[1]??0)>e.length:n>=e.length)throw new Error(fv);return e.splice(...t)}class mv{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 ev(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:Lg.decode(e.data)}))}get addressTableLookups(){return[]}getAccountKeys(){return new ov(this.staticAccountKeys)}static compile(e){const t=dv.compile(e.instructions,e.payerKey),[n,r]=t.getMessageComponents(),i=new ov(r).compileInstructions(e.instructions).map(e=>({programIdIndex:e.programIdIndex,accounts:e.accountKeyIndexes,data:Lg.encode(e.data)}));return new mv({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=[];lv(t,e);const n=this.instructions.map(e=>{const{accounts:t,programIdIndex:n}=e,r=Array.from(Lg.decode(e.data));let i=[];lv(i,t.length);let o=[];return lv(o,r.length),{programIdIndex:n,keyIndicesCount:Wh.Buffer.from(i),keyIndices:t,dataLength:Wh.Buffer.from(o),data:r}});let r=[];lv(r,n.length);let i=Wh.Buffer.alloc(tv);Wh.Buffer.from(r).copy(i);let o=r.length;n.forEach(e=>{const t=ap.struct([ap.u8("programIdIndex"),ap.blob(e.keyIndicesCount.length,"keyIndicesCount"),ap.seq(ap.u8("keyIndex"),e.keyIndices.length,"keyIndices"),ap.blob(e.dataLength.length,"dataLength"),ap.seq(ap.u8("userdatum"),e.data.length,"data")]).encode(e,i,o);o+=t}),i=i.slice(0,o);const s=ap.struct([ap.blob(1,"numRequiredSignatures"),ap.blob(1,"numReadonlySignedAccounts"),ap.blob(1,"numReadonlyUnsignedAccounts"),ap.blob(t.length,"keyCount"),ap.seq(sv("key"),e,"keys"),sv("recentBlockhash")]),a={numRequiredSignatures:Wh.Buffer.from([this.header.numRequiredSignatures]),numReadonlySignedAccounts:Wh.Buffer.from([this.header.numReadonlySignedAccounts]),numReadonlyUnsignedAccounts:Wh.Buffer.from([this.header.numReadonlyUnsignedAccounts]),keyCount:Wh.Buffer.from(t),keys:this.accountKeys.map(e=>Vk(e.toBytes())),recentBlockhash:Lg.decode(this.recentBlockhash)};let c=Wh.Buffer.alloc(2048);const u=s.encode(a,c);return i.copy(c,u),c.slice(0,u+i.length)}static from(e){let t=[...e];const n=gv(t);if(n!==(127&n))throw new Error("Versioned messages must be deserialized with VersionedMessage.deserialize()");const r=gv(t),i=gv(t),o=uv(t);let s=[];for(let e=0;e<o;e++){const e=pv(t,0,Yk);s.push(new ev(Wh.Buffer.from(e)))}const a=pv(t,0,Yk),c=uv(t);let u=[];for(let e=0;e<c;e++){const e=gv(t),n=pv(t,0,uv(t)),r=pv(t,0,uv(t)),i=Lg.encode(Wh.Buffer.from(r));u.push({programIdIndex:e,accounts:n,data:i})}const l={header:{numRequiredSignatures:n,numReadonlySignedAccounts:r,numReadonlyUnsignedAccounts:i},recentBlockhash:Lg.encode(Wh.Buffer.from(a)),accountKeys:s,instructions:u};return new mv(l)}}class yv{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 ov(this.staticAccountKeys,t)}isAccountSigner(e){return e<this.header.numRequiredSignatures}isAccountWritable(e){const t=this.header.numRequiredSignatures,n=this.staticAccountKeys.length;if(e>=n){const t=e-n,r=this.addressTableLookups.reduce((e,t)=>e+t.writableIndexes.length,0);return t<r}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=dv.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:o}]=i;n.push(e),r.writable.push(...t),r.readonly.push(...o)}}const[o,s]=t.getMessageComponents(),a=new ov(s,r).compileInstructions(e.instructions);return new yv({header:o,staticAccountKeys:s,recentBlockhash:e.recentBlockhash,compiledInstructions:a,addressTableLookups:n})}serialize(){const e=Array();lv(e,this.staticAccountKeys.length);const t=this.serializeInstructions(),n=Array();lv(n,this.compiledInstructions.length);const r=this.serializeAddressTableLookups(),i=Array();lv(i,this.addressTableLookups.length);const o=ap.struct([ap.u8("prefix"),ap.struct([ap.u8("numRequiredSignatures"),ap.u8("numReadonlySignedAccounts"),ap.u8("numReadonlyUnsignedAccounts")],"header"),ap.blob(e.length,"staticAccountKeysLength"),ap.seq(sv(),this.staticAccountKeys.length,"staticAccountKeys"),sv("recentBlockhash"),ap.blob(n.length,"instructionsLength"),ap.blob(t.length,"serializedInstructions"),ap.blob(i.length,"addressTableLookupsLength"),ap.blob(r.length,"serializedAddressTableLookups")]),s=new Uint8Array(tv),a=o.encode({prefix:128,header:this.header,staticAccountKeysLength:new Uint8Array(e),staticAccountKeys:this.staticAccountKeys.map(e=>e.toBytes()),recentBlockhash:Lg.decode(this.recentBlockhash),instructionsLength:new Uint8Array(n),serializedInstructions:t,addressTableLookupsLength:new Uint8Array(i),serializedAddressTableLookups:r},s);return s.slice(0,a)}serializeInstructions(){let e=0;const t=new Uint8Array(tv);for(const n of this.compiledInstructions){const r=Array();lv(r,n.accountKeyIndexes.length);const i=Array();lv(i,n.data.length);e+=ap.struct([ap.u8("programIdIndex"),ap.blob(r.length,"encodedAccountKeyIndexesLength"),ap.seq(ap.u8(),n.accountKeyIndexes.length,"accountKeyIndexes"),ap.blob(i.length,"encodedDataLength"),ap.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(tv);for(const n of this.addressTableLookups){const r=Array();lv(r,n.writableIndexes.length);const i=Array();lv(i,n.readonlyIndexes.length);e+=ap.struct([sv("accountKey"),ap.blob(r.length,"encodedWritableIndexesLength"),ap.seq(ap.u8(),n.writableIndexes.length,"writableIndexes"),ap.blob(i.length,"encodedReadonlyIndexesLength"),ap.seq(ap.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=gv(t),r=127&n;hv(n!==r,"Expected versioned message but received legacy message");hv(0===r,`Expected versioned message with version 0 but found version ${r}`);const i={numRequiredSignatures:gv(t),numReadonlySignedAccounts:gv(t),numReadonlyUnsignedAccounts:gv(t)},o=[],s=uv(t);for(let e=0;e<s;e++)o.push(new ev(pv(t,0,Yk)));const a=Lg.encode(pv(t,0,Yk)),c=uv(t),u=[];for(let e=0;e<c;e++){const e=gv(t),n=pv(t,0,uv(t)),r=uv(t),i=new Uint8Array(pv(t,0,r));u.push({programIdIndex:e,accountKeyIndexes:n,data:i})}const l=uv(t),h=[];for(let e=0;e<l;e++){const e=new ev(pv(t,0,Yk)),n=pv(t,0,uv(t)),r=pv(t,0,uv(t));h.push({accountKey:e,writableIndexes:n,readonlyIndexes:r})}return new yv({header:i,staticAccountKeys:o,recentBlockhash:a,compiledInstructions:u,addressTableLookups:h})}}let wv=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 bv=Wh.Buffer.alloc(64).fill(0);class kv{constructor(e){this.keys=void 0,this.programId=void 0,this.data=Wh.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 vv{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 kv(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 ev(e),isSigner:!1,isWritable:!1})});const o=[];i.forEach(e=>{const t=e.pubkey.toString(),n=o.findIndex(e=>e.pubkey.toString()===t);n>-1?(o[n].isWritable=o[n].isWritable||e.isWritable,o[n].isSigner=o[n].isSigner||e.isSigner):o.push(e)}),o.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 s=o.findIndex(e=>e.pubkey.equals(n));if(s>-1){const[e]=o.splice(s,1);e.isSigner=!0,e.isWritable=!0,o.unshift(e)}else o.unshift({pubkey:n,isSigner:!0,isWritable:!0});for(const e of this.signatures){const t=o.findIndex(t=>t.pubkey.equals(e.publicKey));if(!(t>-1))throw new Error(`unknown signer: ${e.publicKey.toString()}`);o[t].isSigner||(o[t].isSigner=!0)}let a=0,c=0,u=0;const l=[],h=[];o.forEach(({pubkey:e,isSigner:t,isWritable:n})=>{t?(l.push(e.toString()),a+=1,n||(c+=1)):(h.push(e.toString()),n||(u+=1))});const d=l.concat(h),f=t.map(e=>{const{data:t,programId:n}=e;return{programIdIndex:d.indexOf(n.toString()),accounts:e.keys.map(e=>d.indexOf(e.pubkey.toString())),data:Lg.encode(t)}});return f.forEach(e=>{hv(e.programIdIndex>=0),e.accounts.forEach(e=>hv(e>=0))}),new mv({header:{numRequiredSignatures:a,numReadonlySignedAccounts:c,numReadonlyUnsignedAccounts:u},accountKeys:d,recentBlockhash:e,instructions:f})}_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)=>yg.sign(e,t.slice(0,32)))(n,e.secretKey);this._addSignature(e.publicKey,Vk(t))})}addSignature(e,t){this._compile(),this._addSignature(e,t)}_addSignature(e,t){hv(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=Wh.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):jk(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=[];lv(n,t.length);const r=n.length+64*t.length+e.length,i=Wh.Buffer.alloc(r);return hv(t.length<256),Wh.Buffer.from(n).copy(i,0),t.forEach(({signature:e},t)=>{null!==e&&(hv(64===e.length,"signature has invalid length"),Wh.Buffer.from(e).copy(i,n.length+64*t))}),e.copy(i,n.length+64*t.length),hv(i.length<=tv,`Transaction too large: ${i.length} > 1232`),i}get keys(){return hv(1===this.instructions.length),this.instructions[0].keys.map(e=>e.pubkey)}get programId(){return hv(1===this.instructions.length),this.instructions[0].programId}get data(){return hv(1===this.instructions.length),this.instructions[0].data}static from(e){let t=[...e];const n=uv(t);let r=[];for(let e=0;e<n;e++){const e=pv(t,0,64);r.push(Lg.encode(Wh.Buffer.from(e)))}return vv.populate(mv.from(t),r)}static populate(e,t=[]){const n=new vv;return n.recentBlockhash=e.recentBlockhash,e.header.numRequiredSignatures>0&&(n.feePayer=e.accountKeys[0]),t.forEach((t,r)=>{const i={signature:t==Lg.encode(bv)?null:Lg.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 kv({keys:r,programId:e.accountKeys[t.programIdIndex],data:Lg.decode(t.data)}))}),n._message=e,n._json=n.toJSON(),n}}new ev("SysvarC1ock11111111111111111111111111111111"),new ev("SysvarEpochSchedu1e111111111111111111111111"),new ev("Sysvar1nstructions1111111111111111111111111");const Sv=new ev("SysvarRecentB1ockHashes11111111111111111111"),Av=new ev("SysvarRent111111111111111111111111111111111");new ev("SysvarRewards111111111111111111111111111111"),new ev("SysvarS1otHashes111111111111111111111111111"),new ev("SysvarS1otHistory11111111111111111111111111"),new ev("SysvarStakeHistory1111111111111111111111111");class Tv extends Error{constructor({action:e,signature:t,transactionMessage:n,logs:r}){const i=r?`Logs: \n${JSON.stringify(r.slice(-10),null,2)}. `:"",o="\nCatch the `SendTransactionError` and call `getLogs()` on it for full details.";let s;switch(e){case"send":s=`Transaction ${t} resulted in an error. \n${n}. `+i+o;break;case"simulate":s=`Simulation failed. \nMessage: ${n}. \n`+i+o;break;default:s=`Unknown action '${e}'`}super(s),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 Ev 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 Iv(e){return new Promise(t=>setTimeout(t,e))}function xv(e,t){const n=e.layout.span>=0?e.layout.span:cv(e,t),r=Wh.Buffer.alloc(n),i=Object.assign({instruction:e.index},t);return e.layout.encode(i,r),r}const Cv=ap.nu64("lamportsPerSignature"),Nv=ap.struct([ap.u32("version"),ap.u32("state"),sv("authorizedPubkey"),sv("nonce"),ap.struct([Cv],"feeCalculator")]),Bv=Nv.span;class _v{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=Nv.decode(Vk(e),0);return new _v({authorizedPubkey:new ev(t.authorizedPubkey),nonce:new ev(t.nonce).toString(),feeCalculator:t.feeCalculator})}}function Pv(e){const t=ap.blob(8,e),n=t.decode.bind(t),r=t.encode.bind(t),i=t,o=Bb();return i.decode=(e,t)=>{const r=n(e,t);return o.decode(r)},i.encode=(e,t,n)=>{const i=o.encode(e);return r(i,t,n)},i}const Rv=Object.freeze({Create:{index:0,layout:ap.struct([ap.u32("instruction"),ap.ns64("lamports"),ap.ns64("space"),sv("programId")])},Assign:{index:1,layout:ap.struct([ap.u32("instruction"),sv("programId")])},Transfer:{index:2,layout:ap.struct([ap.u32("instruction"),Pv("lamports")])},CreateWithSeed:{index:3,layout:ap.struct([ap.u32("instruction"),sv("base"),av("seed"),ap.ns64("lamports"),ap.ns64("space"),sv("programId")])},AdvanceNonceAccount:{index:4,layout:ap.struct([ap.u32("instruction")])},WithdrawNonceAccount:{index:5,layout:ap.struct([ap.u32("instruction"),ap.ns64("lamports")])},InitializeNonceAccount:{index:6,layout:ap.struct([ap.u32("instruction"),sv("authorized")])},AuthorizeNonceAccount:{index:7,layout:ap.struct([ap.u32("instruction"),sv("authorized")])},Allocate:{index:8,layout:ap.struct([ap.u32("instruction"),ap.ns64("space")])},AllocateWithSeed:{index:9,layout:ap.struct([ap.u32("instruction"),sv("base"),av("seed"),ap.ns64("space"),sv("programId")])},AssignWithSeed:{index:10,layout:ap.struct([ap.u32("instruction"),sv("base"),av("seed"),sv("programId")])},TransferWithSeed:{index:11,layout:ap.struct([ap.u32("instruction"),Pv("lamports"),av("seed"),sv("programId")])},UpgradeNonceAccount:{index:12,layout:ap.struct([ap.u32("instruction")])}});class Dv{constructor(){}static createAccount(e){const t=xv(Rv.Create,{lamports:e.lamports,space:e.space,programId:Vk(e.programId.toBuffer())});return new kv({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=xv(Rv.TransferWithSeed,{lamports:BigInt(e.lamports),seed:e.seed,programId:Vk(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=xv(Rv.Transfer,{lamports:BigInt(e.lamports)}),n=[{pubkey:e.fromPubkey,isSigner:!0,isWritable:!0},{pubkey:e.toPubkey,isSigner:!1,isWritable:!0}]}return new kv({keys:n,programId:this.programId,data:t})}static assign(e){let t,n;if("basePubkey"in e){t=xv(Rv.AssignWithSeed,{base:Vk(e.basePubkey.toBuffer()),seed:e.seed,programId:Vk(e.programId.toBuffer())}),n=[{pubkey:e.accountPubkey,isSigner:!1,isWritable:!0},{pubkey:e.basePubkey,isSigner:!0,isWritable:!1}]}else{t=xv(Rv.Assign,{programId:Vk(e.programId.toBuffer())}),n=[{pubkey:e.accountPubkey,isSigner:!0,isWritable:!0}]}return new kv({keys:n,programId:this.programId,data:t})}static createAccountWithSeed(e){const t=xv(Rv.CreateWithSeed,{base:Vk(e.basePubkey.toBuffer()),seed:e.seed,lamports:e.lamports,space:e.space,programId:Vk(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 kv({keys:n,programId:this.programId,data:t})}static createNonceAccount(e){const t=new vv;"basePubkey"in e&&"seed"in e?t.add(Dv.createAccountWithSeed({fromPubkey:e.fromPubkey,newAccountPubkey:e.noncePubkey,basePubkey:e.basePubkey,seed:e.seed,lamports:e.lamports,space:Bv,programId:this.programId})):t.add(Dv.createAccount({fromPubkey:e.fromPubkey,newAccountPubkey:e.noncePubkey,lamports:e.lamports,space:Bv,programId:this.programId}));const n={noncePubkey:e.noncePubkey,authorizedPubkey:e.authorizedPubkey};return t.add(this.nonceInitialize(n)),t}static nonceInitialize(e){const t=xv(Rv.InitializeNonceAccount,{authorized:Vk(e.authorizedPubkey.toBuffer())}),n={keys:[{pubkey:e.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:Sv,isSigner:!1,isWritable:!1},{pubkey:Av,isSigner:!1,isWritable:!1}],programId:this.programId,data:t};return new kv(n)}static nonceAdvance(e){const t=xv(Rv.AdvanceNonceAccount),n={keys:[{pubkey:e.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:Sv,isSigner:!1,isWritable:!1},{pubkey:e.authorizedPubkey,isSigner:!0,isWritable:!1}],programId:this.programId,data:t};return new kv(n)}static nonceWithdraw(e){const t=xv(Rv.WithdrawNonceAccount,{lamports:e.lamports});return new kv({keys:[{pubkey:e.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:e.toPubkey,isSigner:!1,isWritable:!0},{pubkey:Sv,isSigner:!1,isWritable:!1},{pubkey:Av,isSigner:!1,isWritable:!1},{pubkey:e.authorizedPubkey,isSigner:!0,isWritable:!1}],programId:this.programId,data:t})}static nonceAuthorize(e){const t=xv(Rv.AuthorizeNonceAccount,{authorized:Vk(e.newAuthorizedPubkey.toBuffer())});return new kv({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=xv(Rv.AllocateWithSeed,{base:Vk(e.basePubkey.toBuffer()),seed:e.seed,space:e.space,programId:Vk(e.programId.toBuffer())}),n=[{pubkey:e.accountPubkey,isSigner:!1,isWritable:!0},{pubkey:e.basePubkey,isSigner:!0,isWritable:!1}]}else{t=xv(Rv.Allocate,{space:e.space}),n=[{pubkey:e.accountPubkey,isSigner:!0,isWritable:!0}]}return new kv({keys:n,programId:this.programId,data:t})}}function Lv(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Ov,Uv;function Mv(){if(Uv)return Ov;Uv=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 o,s,a,c,u,l,h;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]"===(h=e.call(r))){for(a="[",s=r.length-1,o=0;o<s;o++)a+=n(r[o],!0)+",";return s>-1&&(a+=n(r[o],!0)),a+"]"}if("[object Object]"===h){for(s=(c=t(r).sort()).length,a="",o=0;o<s;)void 0!==(l=n(r[u=c[o]],!1))&&(a&&(a+=","),a+=JSON.stringify(u)+":"+l),o++;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 Ov=function(e){var t=n(e,!1);if(void 0!==t)return""+t}}Dv.programId=new ev("11111111111111111111111111111111"),new ev("BPFLoader2111111111111111111111111111111111");var Fv=Lv(Mv());function $v(e){let t=0;for(;e>1;)e/=2,t++;return t}class qv{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=$v(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)))-$v(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+$v(32)):this.slotsPerEpoch}}var Kv=globalThis.fetch;class Gv extends wk{constructor(e,t,n){super(e=>{const n=function(e,t){return new mk(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 zv{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}(Wv,e),n=e.length-56;hv(n>=0,"lookup table is invalid"),hv(n%32==0,"lookup table is invalid");const r=n/32,{addresses:i}=ap.struct([ap.seq(sv(),r,"addresses")]).decode(e.slice(56));return{deactivationSlot:t.deactivationSlot,lastExtendedSlot:t.lastExtendedSlot,lastExtendedSlotStartIndex:t.lastExtendedStartIndex,authority:0!==t.authority.length?new ev(t.authority[0]):void 0,addresses:i.map(e=>new ev(e))}}}const Wv={index:1,layout:ap.struct([ap.u32("typeIndex"),Pv("deactivationSlot"),ap.nu64("lastExtendedSlot"),ap.u8("lastExtendedStartIndex"),ap.u8(),ap.seq(sv(),ap.offset(ap.u8(),-1),"authority")])},Hv=/^[^:]+:\/\/([^:[]+|\[[^\]]+\])(:\d+)?(.*)/i;const jv=nk(Wb(ev),Jb(),e=>new ev(e)),Vv=Yb([Jb(),Hb("base64")]),Xv=nk(Wb(Wh.Buffer),Vv,e=>Wh.Buffer.from(e[0],"base64"));function Qv(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 Jv(e){return e.map(e=>"memcmp"in e?{...e,memcmp:{...e.memcmp,encoding:e.memcmp.encoding??"base58"}}:e)}function Yv(e){return ek([Zb({jsonrpc:Hb("2.0"),id:Jb(),result:e}),Zb({jsonrpc:Hb("2.0"),id:Jb(),error:Zb({code:tk(),message:Jb(),data:Xb(Kb("any",()=>!0))})})])}const Zv=Yv(tk());function eS(e){return nk(Yv(e),Zv,t=>"error"in t?t:{...t,result:Fb(t.result,e)})}function tS(e){return eS(Zb({context:Zb({slot:Vb()}),value:e}))}function nS(e){return Zb({context:Zb({slot:Vb()}),value:e})}function rS(e,t){return 0===e?new yv({header:t.header,staticAccountKeys:t.accountKeys.map(e=>new ev(e)),recentBlockhash:t.recentBlockhash,compiledInstructions:t.instructions.map(e=>({programIdIndex:e.programIdIndex,accountKeyIndexes:e.accounts,data:Lg.decode(e.data)})),addressTableLookups:t.addressTableLookups}):new mv(t)}const iS=Zb({foundation:Vb(),foundationTerm:Vb(),initial:Vb(),taper:Vb(),terminal:Vb()}),oS=eS(Gb(jb(Zb({epoch:Vb(),effectiveSlot:Vb(),amount:Vb(),postBalance:Vb(),commission:Xb(jb(Vb()))})))),sS=Gb(Zb({slot:Vb(),prioritizationFee:Vb()})),aS=Zb({total:Vb(),validator:Vb(),foundation:Vb(),epoch:Vb()}),cS=Zb({epoch:Vb(),slotIndex:Vb(),slotsInEpoch:Vb(),absoluteSlot:Vb(),blockHeight:Xb(Vb()),transactionCount:Xb(Vb())}),uS=Zb({slotsPerEpoch:Vb(),leaderScheduleSlotOffset:Vb(),warmup:zb(),firstNormalEpoch:Vb(),firstNormalSlot:Vb()}),lS=Qb(Jb(),Gb(Vb())),hS=jb(ek([Zb({}),Jb()])),dS=Zb({err:hS}),fS=Hb("receivedSignature"),gS=Zb({"solana-core":Jb(),"feature-set":Xb(Vb())}),pS=Zb({program:Jb(),programId:jv,parsed:tk()}),mS=Zb({programId:jv,accounts:Gb(jv),data:Jb()}),yS=tS(Zb({err:jb(ek([Zb({}),Jb()])),logs:jb(Gb(Jb())),accounts:Xb(jb(Gb(jb(Zb({executable:zb(),owner:Jb(),lamports:Vb(),data:Gb(Jb()),rentEpoch:Xb(Vb())}))))),unitsConsumed:Xb(Vb()),returnData:Xb(jb(Zb({programId:Jb(),data:Yb([Jb(),Hb("base64")])}))),innerInstructions:Xb(jb(Gb(Zb({index:Vb(),instructions:Gb(ek([pS,mS]))}))))})),wS=tS(Zb({byIdentity:Qb(Jb(),Gb(Vb())),range:Zb({firstSlot:Vb(),lastSlot:Vb()})}));const bS=eS(iS),kS=eS(aS),vS=eS(sS),SS=eS(cS),AS=eS(uS),TS=eS(lS),ES=eS(Vb()),IS=tS(Zb({total:Vb(),circulating:Vb(),nonCirculating:Vb(),nonCirculatingAccounts:Gb(jv)})),xS=Zb({amount:Jb(),uiAmount:jb(Vb()),decimals:Vb(),uiAmountString:Xb(Jb())}),CS=tS(Gb(Zb({address:jv,amount:Jb(),uiAmount:jb(Vb()),decimals:Vb(),uiAmountString:Xb(Jb())}))),NS=tS(Gb(Zb({pubkey:jv,account:Zb({executable:zb(),owner:jv,lamports:Vb(),data:Xv,rentEpoch:Vb()})}))),BS=Zb({program:Jb(),parsed:tk(),space:Vb()}),_S=tS(Gb(Zb({pubkey:jv,account:Zb({executable:zb(),owner:jv,lamports:Vb(),data:BS,rentEpoch:Vb()})}))),PS=tS(Gb(Zb({lamports:Vb(),address:jv}))),RS=Zb({executable:zb(),owner:jv,lamports:Vb(),data:Xv,rentEpoch:Vb()}),DS=Zb({pubkey:jv,account:RS}),LS=nk(ek([Wb(Wh.Buffer),BS]),ek([Vv,BS]),e=>Array.isArray(e)?Fb(e,Xv):e),OS=Zb({executable:zb(),owner:jv,lamports:Vb(),data:LS,rentEpoch:Vb()}),US=Zb({pubkey:jv,account:OS}),MS=Zb({state:ek([Hb("active"),Hb("inactive"),Hb("activating"),Hb("deactivating")]),active:Vb(),inactive:Vb()}),FS=eS(Gb(Zb({signature:Jb(),slot:Vb(),err:hS,memo:jb(Jb()),blockTime:Xb(jb(Vb()))}))),$S=eS(Gb(Zb({signature:Jb(),slot:Vb(),err:hS,memo:jb(Jb()),blockTime:Xb(jb(Vb()))}))),qS=Zb({subscription:Vb(),result:nS(RS)}),KS=Zb({pubkey:jv,account:RS}),GS=Zb({subscription:Vb(),result:nS(KS)}),zS=Zb({parent:Vb(),slot:Vb(),root:Vb()}),WS=Zb({subscription:Vb(),result:zS}),HS=ek([Zb({type:ek([Hb("firstShredReceived"),Hb("completed"),Hb("optimisticConfirmation"),Hb("root")]),slot:Vb(),timestamp:Vb()}),Zb({type:Hb("createdBank"),parent:Vb(),slot:Vb(),timestamp:Vb()}),Zb({type:Hb("frozen"),slot:Vb(),timestamp:Vb(),stats:Zb({numTransactionEntries:Vb(),numSuccessfulTransactions:Vb(),numFailedTransactions:Vb(),maxTransactionsPerEntry:Vb()})}),Zb({type:Hb("dead"),slot:Vb(),timestamp:Vb(),err:Jb()})]),jS=Zb({subscription:Vb(),result:HS}),VS=Zb({subscription:Vb(),result:nS(ek([dS,fS]))}),XS=Zb({subscription:Vb(),result:Vb()}),QS=Zb({pubkey:Jb(),gossip:jb(Jb()),tpu:jb(Jb()),rpc:jb(Jb()),version:jb(Jb())}),JS=Zb({votePubkey:Jb(),nodePubkey:Jb(),activatedStake:Vb(),epochVoteAccount:zb(),epochCredits:Gb(Yb([Vb(),Vb(),Vb()])),commission:Vb(),lastVote:Vb(),rootSlot:jb(Vb())}),YS=eS(Zb({current:Gb(JS),delinquent:Gb(JS)})),ZS=ek([Hb("processed"),Hb("confirmed"),Hb("finalized")]),eA=Zb({slot:Vb(),confirmations:jb(Vb()),err:hS,confirmationStatus:Xb(ZS)}),tA=tS(Gb(jb(eA))),nA=eS(Vb()),rA=Zb({accountKey:jv,writableIndexes:Gb(Vb()),readonlyIndexes:Gb(Vb())}),iA=Zb({signatures:Gb(Jb()),message:Zb({accountKeys:Gb(Jb()),header:Zb({numRequiredSignatures:Vb(),numReadonlySignedAccounts:Vb(),numReadonlyUnsignedAccounts:Vb()}),instructions:Gb(Zb({accounts:Gb(Vb()),data:Jb(),programIdIndex:Vb()})),recentBlockhash:Jb(),addressTableLookups:Xb(Gb(rA))})}),oA=Zb({pubkey:jv,signer:zb(),writable:zb(),source:Xb(ek([Hb("transaction"),Hb("lookupTable")]))}),sA=Zb({accountKeys:Gb(oA),signatures:Gb(Jb())}),aA=Zb({parsed:tk(),program:Jb(),programId:jv}),cA=Zb({accounts:Gb(jv),data:Jb(),programId:jv}),uA=nk(ek([cA,aA]),ek([Zb({parsed:tk(),program:Jb(),programId:Jb()}),Zb({accounts:Gb(Jb()),data:Jb(),programId:Jb()})]),e=>Fb(e,"accounts"in e?cA:aA)),lA=Zb({signatures:Gb(Jb()),message:Zb({accountKeys:Gb(oA),instructions:Gb(uA),recentBlockhash:Jb(),addressTableLookups:Xb(jb(Gb(rA)))})}),hA=Zb({accountIndex:Vb(),mint:Jb(),owner:Xb(Jb()),programId:Xb(Jb()),uiTokenAmount:xS}),dA=Zb({writable:Gb(jv),readonly:Gb(jv)}),fA=Zb({err:hS,fee:Vb(),innerInstructions:Xb(jb(Gb(Zb({index:Vb(),instructions:Gb(Zb({accounts:Gb(Vb()),data:Jb(),programIdIndex:Vb()}))})))),preBalances:Gb(Vb()),postBalances:Gb(Vb()),logMessages:Xb(jb(Gb(Jb()))),preTokenBalances:Xb(jb(Gb(hA))),postTokenBalances:Xb(jb(Gb(hA))),loadedAddresses:Xb(dA),computeUnitsConsumed:Xb(Vb()),costUnits:Xb(Vb())}),gA=Zb({err:hS,fee:Vb(),innerInstructions:Xb(jb(Gb(Zb({index:Vb(),instructions:Gb(uA)})))),preBalances:Gb(Vb()),postBalances:Gb(Vb()),logMessages:Xb(jb(Gb(Jb()))),preTokenBalances:Xb(jb(Gb(hA))),postTokenBalances:Xb(jb(Gb(hA))),loadedAddresses:Xb(dA),computeUnitsConsumed:Xb(Vb()),costUnits:Xb(Vb())}),pA=ek([Hb(0),Hb("legacy")]),mA=Zb({pubkey:Jb(),lamports:Vb(),postBalance:jb(Vb()),rewardType:jb(Jb()),commission:Xb(jb(Vb()))}),yA=eS(jb(Zb({blockhash:Jb(),previousBlockhash:Jb(),parentSlot:Vb(),transactions:Gb(Zb({transaction:iA,meta:jb(fA),version:Xb(pA)})),rewards:Xb(Gb(mA)),blockTime:jb(Vb()),blockHeight:jb(Vb())}))),wA=eS(jb(Zb({blockhash:Jb(),previousBlockhash:Jb(),parentSlot:Vb(),rewards:Xb(Gb(mA)),blockTime:jb(Vb()),blockHeight:jb(Vb())}))),bA=eS(jb(Zb({blockhash:Jb(),previousBlockhash:Jb(),parentSlot:Vb(),transactions:Gb(Zb({transaction:sA,meta:jb(fA),version:Xb(pA)})),rewards:Xb(Gb(mA)),blockTime:jb(Vb()),blockHeight:jb(Vb())}))),kA=eS(jb(Zb({blockhash:Jb(),previousBlockhash:Jb(),parentSlot:Vb(),transactions:Gb(Zb({transaction:lA,meta:jb(gA),version:Xb(pA)})),rewards:Xb(Gb(mA)),blockTime:jb(Vb()),blockHeight:jb(Vb())}))),vA=eS(jb(Zb({blockhash:Jb(),previousBlockhash:Jb(),parentSlot:Vb(),transactions:Gb(Zb({transaction:sA,meta:jb(gA),version:Xb(pA)})),rewards:Xb(Gb(mA)),blockTime:jb(Vb()),blockHeight:jb(Vb())}))),SA=eS(jb(Zb({blockhash:Jb(),previousBlockhash:Jb(),parentSlot:Vb(),rewards:Xb(Gb(mA)),blockTime:jb(Vb()),blockHeight:jb(Vb())}))),AA=eS(jb(Zb({blockhash:Jb(),previousBlockhash:Jb(),parentSlot:Vb(),transactions:Gb(Zb({transaction:iA,meta:jb(fA)})),rewards:Xb(Gb(mA)),blockTime:jb(Vb())}))),TA=eS(jb(Zb({blockhash:Jb(),previousBlockhash:Jb(),parentSlot:Vb(),signatures:Gb(Jb()),blockTime:jb(Vb())}))),EA=eS(jb(Zb({slot:Vb(),meta:jb(fA),blockTime:Xb(jb(Vb())),transaction:iA,version:Xb(pA)}))),IA=eS(jb(Zb({slot:Vb(),transaction:lA,meta:jb(gA),blockTime:Xb(jb(Vb())),version:Xb(pA)}))),xA=tS(Zb({blockhash:Jb(),lastValidBlockHeight:Vb()})),CA=tS(zb()),NA=eS(Gb(Zb({slot:Vb(),numTransactions:Vb(),numSlots:Vb(),samplePeriodSecs:Vb()}))),BA=tS(jb(Zb({feeCalculator:Zb({lamportsPerSignature:Vb()})}))),_A=eS(Jb()),PA=eS(Jb()),RA=Zb({err:hS,logs:Gb(Jb()),signature:Jb()}),DA=Zb({result:nS(RA),subscription:Vb()}),LA={"solana-client":"js/1.0.0-maintenance"};class OA{constructor(e,t){let n,r,i,o,s,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}=Qv(t),i=this._buildArgs([],n,void 0,r),o=Fv(i);return e[o]=e[o]??(async()=>{try{const e=Fb(await this._rpcRequest("getBlockHeight",i),eS(Vb()));if("error"in e)throw new Ev(e.error,"failed to get block height information");return e.result}finally{delete e[o]}})(),await e[o]}})(),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,o=t.fetchMiddleware,s=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(Hv);if(null==t)throw TypeError(`Failed to validate endpoint URL \`${e}\``);const[n,r,i,o]=t,s=e.startsWith("https:")?"wss:":"ws:",a=null==i?null:parseInt(i.slice(1),10);return`${s}//${r}${null==a?"":`:${a+1}`}${o}`}(e),this._rpcClient=function(e,t,n,r,i){const o=n||Kv;let s;return r&&(s=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 o(...n)}),new uk(async(n,r)=>{const a={method:"POST",body:n,agent:void 0,headers:Object.assign({"Content-Type":"application/json"},t||{},LA)};try{let t,n=5,c=500;for(;t=s?await s(e,a):await o(e,a),429===t.status&&!0!==i&&(n-=1,0!==n);)await Iv(c),c*=2;const u=await t.text();t.ok?r(null,u):r(new Error(`${t.status} ${t.statusText}: ${u}`))}catch(e){e instanceof Error&&r(e)}},{})}(e,r,i,o,s),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 Gv(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}=Qv(t),i=this._buildArgs([e.toBase58()],n,void 0,r),o=Fb(await this._rpcRequest("getBalance",i),tS(Vb()));if("error"in o)throw new Ev(o.error,`failed to get balance for ${e.toBase58()}`);return o.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=Fb(await this._rpcRequest("getBlockTime",[e]),eS(jb(Vb())));if("error"in t)throw new Ev(t.error,`failed to get block time for slot ${e}`);return t.result}async getMinimumLedgerSlot(){const e=Fb(await this._rpcRequest("minimumLedgerSlot",[]),eS(Vb()));if("error"in e)throw new Ev(e.error,"failed to get minimum ledger slot");return e.result}async getFirstAvailableBlock(){const e=Fb(await this._rpcRequest("getFirstAvailableBlock",[]),ES);if("error"in e)throw new Ev(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=Fb(await this._rpcRequest("getSupply",[t]),IS);if("error"in n)throw new Ev(n.error,"failed to get supply");return n.result}async getTokenSupply(e,t){const n=this._buildArgs([e.toBase58()],t),r=Fb(await this._rpcRequest("getTokenSupply",n),tS(xS));if("error"in r)throw new Ev(r.error,"failed to get token supply");return r.result}async getTokenAccountBalance(e,t){const n=this._buildArgs([e.toBase58()],t),r=Fb(await this._rpcRequest("getTokenAccountBalance",n),tS(xS));if("error"in r)throw new Ev(r.error,"failed to get token account balance");return r.result}async getTokenAccountsByOwner(e,t,n){const{commitment:r,config:i}=Qv(n);let o=[e.toBase58()];"mint"in t?o.push({mint:t.mint.toBase58()}):o.push({programId:t.programId.toBase58()});const s=this._buildArgs(o,r,"base64",i),a=Fb(await this._rpcRequest("getTokenAccountsByOwner",s),NS);if("error"in a)throw new Ev(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"),o=Fb(await this._rpcRequest("getTokenAccountsByOwner",i),_S);if("error"in o)throw new Ev(o.error,`failed to get token accounts owned by account ${e.toBase58()}`);return o.result}async getLargestAccounts(e){const t={...e,commitment:e&&e.commitment||this.commitment},n=t.filter||t.commitment?[t]:[],r=Fb(await this._rpcRequest("getLargestAccounts",n),PS);if("error"in r)throw new Ev(r.error,"failed to get largest accounts");return r.result}async getTokenLargestAccounts(e,t){const n=this._buildArgs([e.toBase58()],t),r=Fb(await this._rpcRequest("getTokenLargestAccounts",n),CS);if("error"in r)throw new Ev(r.error,"failed to get token largest accounts");return r.result}async getAccountInfoAndContext(e,t){const{commitment:n,config:r}=Qv(t),i=this._buildArgs([e.toBase58()],n,"base64",r),o=Fb(await this._rpcRequest("getAccountInfo",i),tS(jb(RS)));if("error"in o)throw new Ev(o.error,`failed to get info about account ${e.toBase58()}`);return o.result}async getParsedAccountInfo(e,t){const{commitment:n,config:r}=Qv(t),i=this._buildArgs([e.toBase58()],n,"jsonParsed",r),o=Fb(await this._rpcRequest("getAccountInfo",i),tS(jb(OS)));if("error"in o)throw new Ev(o.error,`failed to get info about account ${e.toBase58()}`);return o.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}=Qv(t),i=e.map(e=>e.toBase58()),o=this._buildArgs([i],n,"jsonParsed",r),s=Fb(await this._rpcRequest("getMultipleAccounts",o),tS(Gb(jb(OS))));if("error"in s)throw new Ev(s.error,`failed to get info for accounts ${i}`);return s.result}async getMultipleAccountsInfoAndContext(e,t){const{commitment:n,config:r}=Qv(t),i=e.map(e=>e.toBase58()),o=this._buildArgs([i],n,"base64",r),s=Fb(await this._rpcRequest("getMultipleAccounts",o),tS(Gb(jb(RS))));if("error"in s)throw new Ev(s.error,`failed to get info for accounts ${i}`);return s.result}async getMultipleAccountsInfo(e,t){return(await this.getMultipleAccountsInfoAndContext(e,t)).value}async getStakeActivation(e,t,n){const{commitment:r,config:i}=Qv(t),o=this._buildArgs([e.toBase58()],r,void 0,{...i,epoch:null!=n?n:i?.epoch}),s=Fb(await this._rpcRequest("getStakeActivation",o),eS(MS));if("error"in s)throw new Ev(s.error,`failed to get Stake Activation ${e.toBase58()}`);return s.result}async getProgramAccounts(e,t){const{commitment:n,config:r}=Qv(t),{encoding:i,...o}=r||{},s=this._buildArgs([e.toBase58()],n,i||"base64",{...o,...o.filters?{filters:Jv(o.filters)}:null}),a=await this._rpcRequest("getProgramAccounts",s),c=Gb(DS),u=!0===o.withContext?Fb(a,tS(c)):Fb(a,eS(c));if("error"in u)throw new Ev(u.error,`failed to get accounts owned by program ${e.toBase58()}`);return u.result}async getParsedProgramAccounts(e,t){const{commitment:n,config:r}=Qv(t),i=this._buildArgs([e.toBase58()],n,"jsonParsed",r),o=Fb(await this._rpcRequest("getProgramAccounts",i),eS(Gb(US)));if("error"in o)throw new Ev(o.error,`failed to get accounts owned by program ${e.toBase58()}`);return o.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=Lg.decode(n)}catch(e){throw new Error("signature must be base58 encoded: "+n)}return hv(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((o,s)=>{try{n=this.onSignature(t,(e,t)=>{n=void 0;const r={context:t,value:e};o({__type:wv.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)s(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,o({__type:wv.PROCESSED,response:{context:r,value:c}})}})()}catch(e){s(e)}})}}async confirmTransactionUsingBlockHeightExceedanceStrategy({commitment:e,strategy:{abortSignal:t,lastValidBlockHeight:n,signature:r}}){let i=!1;const o=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 Iv(1e3),i)return;if(e=await r(),i)return}t({__type:wv.BLOCKHEIGHT_EXCEEDED})}})()}),{abortConfirmation:s,confirmationPromise:a}=this.getTransactionConfirmationPromise({commitment:e,signature:r}),c=this.getCancellationPromise(t);let u;try{const e=await Promise.race([c,a,o]);if(e.__type!==wv.PROCESSED)throw new nv(r);u=e.response}finally{i=!0,s()}return u}async confirmTransactionUsingDurableNonceStrategy({commitment:e,strategy:{abortSignal:t,minContextSlot:n,nonceAccountPubkey:r,nonceValue:i,signature:o}}){let s=!1;const a=new Promise(t=>{let o=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 o}};(async()=>{if(o=await c(),!s)for(;;){if(i!==o)return void t({__type:wv.NONCE_INVALID,slotInWhichNonceDidAdvance:a});if(await Iv(2e3),s)return;if(o=await c(),s)return}})()}),{abortConfirmation:c,confirmationPromise:u}=this.getTransactionConfirmationPromise({commitment:e,signature:o}),l=this.getCancellationPromise(t);let h;try{const t=await Promise.race([l,u,a]);if(t.__type===wv.PROCESSED)h=t.response;else{let r;for(;;){const e=await this.getSignatureStatus(o);if(null==e)break;if(!(e.context.slot<(t.slotInWhichNonceDidAdvance??n))){r=e;break}await Iv(400)}if(!r?.value)throw new iv(o);{const t=e||"finalized",{confirmationStatus:n}=r.value;switch(t){case"processed":case"recent":if("processed"!==n&&"confirmed"!==n&&"finalized"!==n)throw new iv(o);break;case"confirmed":case"single":case"singleGossip":if("confirmed"!==n&&"finalized"!==n)throw new iv(o);break;case"finalized":case"max":case"root":if("finalized"!==n)throw new iv(o)}h={context:r.context,value:{err:r.value.err}}}}}finally{s=!0,c()}return h}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:wv.TIMED_OUT,timeoutMs:r}),r)}),{abortConfirmation:i,confirmationPromise:o}=this.getTransactionConfirmationPromise({commitment:e,signature:t});let s;try{const e=await Promise.race([o,r]);if(e.__type!==wv.PROCESSED)throw new rv(t,e.timeoutMs/1e3);s=e.response}finally{clearTimeout(n),i()}return s}async getClusterNodes(){const e=Fb(await this._rpcRequest("getClusterNodes",[]),eS(Gb(QS)));if("error"in e)throw new Ev(e.error,"failed to get cluster nodes");return e.result}async getVoteAccounts(e){const t=this._buildArgs([],e),n=Fb(await this._rpcRequest("getVoteAccounts",t),YS);if("error"in n)throw new Ev(n.error,"failed to get vote accounts");return n.result}async getSlot(e){const{commitment:t,config:n}=Qv(e),r=this._buildArgs([],t,void 0,n),i=Fb(await this._rpcRequest("getSlot",r),eS(Vb()));if("error"in i)throw new Ev(i.error,"failed to get slot");return i.result}async getSlotLeader(e){const{commitment:t,config:n}=Qv(e),r=this._buildArgs([],t,void 0,n),i=Fb(await this._rpcRequest("getSlotLeader",r),eS(Jb()));if("error"in i)throw new Ev(i.error,"failed to get slot leader");return i.result}async getSlotLeaders(e,t){const n=[e,t],r=Fb(await this._rpcRequest("getSlotLeaders",n),eS(Gb(jv)));if("error"in r)throw new Ev(r.error,"failed to get slot leaders");return r.result}async getSignatureStatus(e,t){const{context:n,value:r}=await this.getSignatureStatuses([e],t);hv(1===r.length);return{context:n,value:r[0]}}async getSignatureStatuses(e,t){const n=[e];t&&n.push(t);const r=Fb(await this._rpcRequest("getSignatureStatuses",n),tA);if("error"in r)throw new Ev(r.error,"failed to get signature status");return r.result}async getTransactionCount(e){const{commitment:t,config:n}=Qv(e),r=this._buildArgs([],t,void 0,n),i=Fb(await this._rpcRequest("getTransactionCount",r),eS(Vb()));if("error"in i)throw new Ev(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=Fb(await this._rpcRequest("getInflationGovernor",t),bS);if("error"in n)throw new Ev(n.error,"failed to get inflation");return n.result}async getInflationReward(e,t,n){const{commitment:r,config:i}=Qv(n),o=this._buildArgs([e.map(e=>e.toBase58())],r,void 0,{...i,epoch:null!=t?t:i?.epoch}),s=Fb(await this._rpcRequest("getInflationReward",o),oS);if("error"in s)throw new Ev(s.error,"failed to get inflation reward");return s.result}async getInflationRate(){const e=Fb(await this._rpcRequest("getInflationRate",[]),kS);if("error"in e)throw new Ev(e.error,"failed to get inflation rate");return e.result}async getEpochInfo(e){const{commitment:t,config:n}=Qv(e),r=this._buildArgs([],t,void 0,n),i=Fb(await this._rpcRequest("getEpochInfo",r),SS);if("error"in i)throw new Ev(i.error,"failed to get epoch info");return i.result}async getEpochSchedule(){const e=Fb(await this._rpcRequest("getEpochSchedule",[]),AS);if("error"in e)throw new Ev(e.error,"failed to get epoch schedule");const t=e.result;return new qv(t.slotsPerEpoch,t.leaderScheduleSlotOffset,t.warmup,t.firstNormalEpoch,t.firstNormalSlot)}async getLeaderSchedule(){const e=Fb(await this._rpcRequest("getLeaderSchedule",[]),TS);if("error"in e)throw new Ev(e.error,"failed to get leader schedule");return e.result}async getMinimumBalanceForRentExemption(e,t){const n=this._buildArgs([e],t),r=Fb(await this._rpcRequest("getMinimumBalanceForRentExemption",n),nA);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=Fb(await this._rpcRequest("getRecentPerformanceSamples",e?[e]:[]),NA);if("error"in t)throw new Ev(t.error,"failed to get recent performance samples");return t.result}async getFeeCalculatorForBlockhash(e,t){const n=this._buildArgs([e],t),r=Fb(await this._rpcRequest("getFeeCalculatorForBlockhash",n),BA);if("error"in r)throw new Ev(r.error,"failed to get fee calculator");const{context:i,value:o}=r.result;return{context:i,value:null!==o?o.feeCalculator:null}}async getFeeForMessage(e,t){const n=Vk(e.serialize()).toString("base64"),r=this._buildArgs([n],t),i=Fb(await this._rpcRequest("getFeeForMessage",r),tS(jb(Vb())));if("error"in i)throw new Ev(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=Fb(await this._rpcRequest("getRecentPrioritizationFees",n),vS);if("error"in r)throw new Ev(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}=Qv(e),r=this._buildArgs([],t,void 0,n),i=Fb(await this._rpcRequest("getLatestBlockhash",r),xA);if("error"in i)throw new Ev(i.error,"failed to get latest blockhash");return i.result}async isBlockhashValid(e,t){const{commitment:n,config:r}=Qv(t),i=this._buildArgs([e],n,void 0,r),o=Fb(await this._rpcRequest("isBlockhashValid",i),CA);if("error"in o)throw new Ev(o.error,"failed to determine if the blockhash `"+e+"`is valid");return o.result}async getVersion(){const e=Fb(await this._rpcRequest("getVersion",[]),eS(gS));if("error"in e)throw new Ev(e.error,"failed to get version");return e.result}async getGenesisHash(){const e=Fb(await this._rpcRequest("getGenesisHash",[]),eS(Jb()));if("error"in e)throw new Ev(e.error,"failed to get genesis hash");return e.result}async getBlock(e,t){const{commitment:n,config:r}=Qv(t),i=this._buildArgsAtLeastConfirmed([e],n,void 0,r),o=await this._rpcRequest("getBlock",i);try{switch(r?.transactionDetails){case"accounts":{const e=Fb(o,bA);if("error"in e)throw e.error;return e.result}case"none":{const e=Fb(o,wA);if("error"in e)throw e.error;return e.result}default:{const e=Fb(o,yA);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:rS(n,e.message)},version:n}))}:null}}}catch(e){throw new Ev(e,"failed to get confirmed block")}}async getParsedBlock(e,t){const{commitment:n,config:r}=Qv(t),i=this._buildArgsAtLeastConfirmed([e],n,"jsonParsed",r),o=await this._rpcRequest("getBlock",i);try{switch(r?.transactionDetails){case"accounts":{const e=Fb(o,vA);if("error"in e)throw e.error;return e.result}case"none":{const e=Fb(o,SA);if("error"in e)throw e.error;return e.result}default:{const e=Fb(o,kA);if("error"in e)throw e.error;return e.result}}}catch(e){throw new Ev(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=Fb(await this._rpcRequest("getBlockProduction",r),wS);if("error"in i)throw new Ev(i.error,"failed to get block production information");return i.result}async getTransaction(e,t){const{commitment:n,config:r}=Qv(t),i=this._buildArgsAtLeastConfirmed([e],n,void 0,r),o=Fb(await this._rpcRequest("getTransaction",i),EA);if("error"in o)throw new Ev(o.error,"failed to get transaction");const s=o.result;return s?{...s,transaction:{...s.transaction,message:rS(s.version,s.transaction.message)}}:s}async getParsedTransaction(e,t){const{commitment:n,config:r}=Qv(t),i=this._buildArgsAtLeastConfirmed([e],n,"jsonParsed",r),o=Fb(await this._rpcRequest("getTransaction",i),IA);if("error"in o)throw new Ev(o.error,"failed to get transaction");return o.result}async getParsedTransactions(e,t){const{commitment:n,config:r}=Qv(t),i=e.map(e=>({methodName:"getTransaction",args:this._buildArgsAtLeastConfirmed([e],n,"jsonParsed",r)}));return(await this._rpcBatchRequest(i)).map(e=>{const t=Fb(e,IA);if("error"in t)throw new Ev(t.error,"failed to get transactions");return t.result})}async getTransactions(e,t){const{commitment:n,config:r}=Qv(t),i=e.map(e=>({methodName:"getTransaction",args:this._buildArgsAtLeastConfirmed([e],n,void 0,r)}));return(await this._rpcBatchRequest(i)).map(e=>{const t=Fb(e,EA);if("error"in t)throw new Ev(t.error,"failed to get transactions");const n=t.result;return n?{...n,transaction:{...n.transaction,message:rS(n.version,n.transaction.message)}}:n})}async getConfirmedBlock(e,t){const n=this._buildArgsAtLeastConfirmed([e],t),r=Fb(await this._rpcRequest("getBlock",n),AA);if("error"in r)throw new Ev(r.error,"failed to get confirmed block");const i=r.result;if(!i)throw new Error("Confirmed block "+e+" not found");const o={...i,transactions:i.transactions.map(({transaction:e,meta:t})=>{const n=new mv(e.message);return{meta:t,transaction:{...e,message:n}}})};return{...o,transactions:o.transactions.map(({transaction:e,meta:t})=>({meta:t,transaction:vv.populate(e.message,e.signatures)}))}}async getBlocks(e,t,n){const r=this._buildArgsAtLeastConfirmed(void 0!==t?[e,t]:[e],n),i=Fb(await this._rpcRequest("getBlocks",r),eS(Gb(Vb())));if("error"in i)throw new Ev(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=Fb(await this._rpcRequest("getBlock",n),TA);if("error"in r)throw new Ev(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=Fb(await this._rpcRequest("getBlock",n),TA);if("error"in r)throw new Ev(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=Fb(await this._rpcRequest("getTransaction",n),EA);if("error"in r)throw new Ev(r.error,"failed to get transaction");const i=r.result;if(!i)return i;const o=new mv(i.transaction.message),s=i.transaction.signatures;return{...i,transaction:vv.populate(o,s)}}async getParsedConfirmedTransaction(e,t){const n=this._buildArgsAtLeastConfirmed([e],t,"jsonParsed"),r=Fb(await this._rpcRequest("getTransaction",n),IA);if("error"in r)throw new Ev(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=Fb(e,IA);if("error"in t)throw new Ev(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 o=await this.getSlot("finalized");for(;!("before"in r||++n>o);)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=Fb(await this._rpcRequest("getConfirmedSignaturesForAddress2",r),FS);if("error"in i)throw new Ev(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=Fb(await this._rpcRequest("getSignaturesForAddress",r),$S);if("error"in i)throw new Ev(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 zv({key:e,state:zv.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=_v.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=Fb(await this._rpcRequest("requestAirdrop",[e.toBase58(),t]),_A);if("error"in n)throw new Ev(n.error,`airdrop to ${e.toBase58()} failed`);return n.result}async _blockhashWithExpiryBlockHeight(e){if(!e){for(;this._pollingBlockhash;)await Iv(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 Iv(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}=Qv(e),r=this._buildArgs([],t,"base64",n),i=Fb(await this._rpcRequest("getStakeMinimumDelegation",r),tS(Vb()));if("error"in i)throw new Ev(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=Wh.Buffer.from(r).toString("base64");if(Array.isArray(t)||void 0!==n)throw new Error("Invalid arguments");const o=t||{};o.encoding="base64","commitment"in o||(o.commitment=this.commitment),t&&"object"==typeof t&&"innerInstructions"in t&&(o.innerInstructions=t.innerInstructions);const s=[i,o],a=Fb(await this._rpcRequest("simulateTransaction",s),yS);if("error"in a)throw new Error("failed to simulate transaction: "+a.error.message);return a.result}let r;if(e instanceof vv){let t=e;r=new vv,r.feePayer=t.feePayer,r.instructions=e.instructions,r.nonceInfo=t.nonceInfo,r.signatures=t.signatures}else r=vv.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 o=r._compile(),s=o.serialize(),a=r._serialize(s).toString("base64"),c={encoding:"base64",commitment:this.commitment};if(n){const e=(Array.isArray(n)?n:o.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 u=[a,c],l=Fb(await this._rpcRequest("simulateTransaction",u),yS);if("error"in l){let e;if("data"in l.error&&(e=l.error.data.logs,e&&Array.isArray(e))){const t="\n ";e.join(t)}throw new Tv({action:"simulate",signature:"",transactionMessage:l.error.message,logs:e})}return l.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=Vk(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 o=[e,n],s=Fb(await this._rpcRequest("sendTransaction",o),PA);if("error"in s){let e;throw"data"in s.error&&(e=s.error.data.logs),new Tv({action:r?"send":"simulate",signature:"",transactionMessage:s.error.message,logs:e})}return s.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}=Fb(e,qS);this._handleServerNotification(n,[t.value,t.context])}_makeSubscription(e,t){const n=this._nextClientSubscriptionId++,r=Fv([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];hv(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}=Qv(n),o=this._buildArgs([e.toBase58()],r||this._commitment||"finalized","base64",i);return this._makeSubscription({callback:t,method:"accountSubscribe",unsubscribeMethod:"accountUnsubscribe"},o)}async removeAccountChangeListener(e){await this._unsubscribeClientSubscription(e,"account change")}_wsOnProgramAccountNotification(e){const{result:t,subscription:n}=Fb(e,GS);this._handleServerNotification(n,[{accountId:t.value.pubkey,accountInfo:t.value.account},t.context])}onProgramAccountChange(e,t,n,r){const{commitment:i,config:o}=Qv(n),s=this._buildArgs([e.toBase58()],i||this._commitment||"finalized","base64",o||(r?{filters:Jv(r)}:void 0));return this._makeSubscription({callback:t,method:"programSubscribe",unsubscribeMethod:"programUnsubscribe"},s)}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}=Fb(e,DA);this._handleServerNotification(n,[t.value,t.context])}_wsOnSlotNotification(e){const{result:t,subscription:n}=Fb(e,WS);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}=Fb(e,jS);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}=Fb(e,VS);"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"},o=this._buildArgs([e],r,void 0,i),s=this._makeSubscription({callback:(e,n)=>{t(e,n);try{this.removeSignatureListener(s)}catch(e){}},method:"signatureSubscribe",unsubscribeMethod:"signatureUnsubscribe"},o);return s}async removeSignatureListener(e){await this._unsubscribeClientSubscription(e,"signature result")}_wsOnRootNotification(e){const{result:t,subscription:n}=Fb(e,XS);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 UA{constructor(e){this._keypair=void 0,this._keypair=e??zk()}static generate(){return new UA(zk())}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=Wk(t);for(let e=0;e<32;e++)if(n[e]!==r[e])throw new Error("provided secretKey is invalid")}return new UA({publicKey:n,secretKey:e})}static fromSeed(e){const t=Wk(e),n=new Uint8Array(64);return n.set(e),n.set(t,32),new UA({publicKey:t,secretKey:n})}get publicKey(){return new ev(this._keypair.publicKey)}get secretKey(){return new Uint8Array(this._keypair.secretKey)}}Object.freeze({CreateLookupTable:{index:0,layout:ap.struct([ap.u32("instruction"),Pv("recentSlot"),ap.u8("bumpSeed")])},FreezeLookupTable:{index:1,layout:ap.struct([ap.u32("instruction")])},ExtendLookupTable:{index:2,layout:ap.struct([ap.u32("instruction"),Pv(),ap.seq(sv(),ap.offset(ap.u32(),-8),"addresses")])},DeactivateLookupTable:{index:3,layout:ap.struct([ap.u32("instruction")])},CloseLookupTable:{index:4,layout:ap.struct([ap.u32("instruction")])}}),new ev("AddressLookupTab1e1111111111111111111111111");const MA=Object.freeze({RequestUnits:{index:0,layout:ap.struct([ap.u8("instruction"),ap.u32("units"),ap.u32("additionalFee")])},RequestHeapFrame:{index:1,layout:ap.struct([ap.u8("instruction"),ap.u32("bytes")])},SetComputeUnitLimit:{index:2,layout:ap.struct([ap.u8("instruction"),ap.u32("units")])},SetComputeUnitPrice:{index:3,layout:ap.struct([ap.u8("instruction"),Pv("microLamports")])}});class FA{constructor(){}static requestUnits(e){const t=xv(MA.RequestUnits,e);return new kv({keys:[],programId:this.programId,data:t})}static requestHeapFrame(e){const t=xv(MA.RequestHeapFrame,e);return new kv({keys:[],programId:this.programId,data:t})}static setComputeUnitLimit(e){const t=xv(MA.SetComputeUnitLimit,e);return new kv({keys:[],programId:this.programId,data:t})}static setComputeUnitPrice(e){const t=xv(MA.SetComputeUnitPrice,{microLamports:BigInt(e.microLamports)});return new kv({keys:[],programId:this.programId,data:t})}}var $A;FA.programId=new ev("ComputeBudget111111111111111111111111111111"),ap.struct([ap.u8("numSignatures"),ap.u8("padding"),ap.u16("signatureOffset"),ap.u16("signatureInstructionIndex"),ap.u16("publicKeyOffset"),ap.u16("publicKeyInstructionIndex"),ap.u16("messageDataOffset"),ap.u16("messageDataSize"),ap.u16("messageInstructionIndex")]),new ev("Ed25519SigVerify111111111111111111111111111"),Gk.utils.isValidPrivateKey,ap.struct([ap.u8("numSignatures"),ap.u16("signatureOffset"),ap.u8("signatureInstructionIndex"),ap.u16("ethAddressOffset"),ap.u8("ethAddressInstructionIndex"),ap.u16("messageDataOffset"),ap.u16("messageDataSize"),ap.u8("messageInstructionIndex"),ap.blob(20,"ethAddress"),ap.blob(64,"signature"),ap.u8("recoveryId")]),new ev("KeccakSecp256k11111111111111111111111111111"),new ev("StakeConfig11111111111111111111111111111111");class qA{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}}$A=qA,qA.default=new $A(0,0,ev.default),Object.freeze({Initialize:{index:0,layout:ap.struct([ap.u32("instruction"),((e="authorized")=>ap.struct([sv("staker"),sv("withdrawer")],e))(),((e="lockup")=>ap.struct([ap.ns64("unixTimestamp"),ap.ns64("epoch"),sv("custodian")],e))()])},Authorize:{index:1,layout:ap.struct([ap.u32("instruction"),sv("newAuthorized"),ap.u32("stakeAuthorizationType")])},Delegate:{index:2,layout:ap.struct([ap.u32("instruction")])},Split:{index:3,layout:ap.struct([ap.u32("instruction"),ap.ns64("lamports")])},Withdraw:{index:4,layout:ap.struct([ap.u32("instruction"),ap.ns64("lamports")])},Deactivate:{index:5,layout:ap.struct([ap.u32("instruction")])},Merge:{index:7,layout:ap.struct([ap.u32("instruction")])},AuthorizeWithSeed:{index:8,layout:ap.struct([ap.u32("instruction"),sv("newAuthorized"),ap.u32("stakeAuthorizationType"),av("authoritySeed"),sv("authorityOwner")])}}),new ev("Stake11111111111111111111111111111111111111"),Object.freeze({InitializeAccount:{index:0,layout:ap.struct([ap.u32("instruction"),((e="voteInit")=>ap.struct([sv("nodePubkey"),sv("authorizedVoter"),sv("authorizedWithdrawer"),ap.u8("commission")],e))()])},Authorize:{index:1,layout:ap.struct([ap.u32("instruction"),sv("newAuthorized"),ap.u32("voteAuthorizationType")])},Withdraw:{index:3,layout:ap.struct([ap.u32("instruction"),ap.ns64("lamports")])},UpdateValidatorIdentity:{index:4,layout:ap.struct([ap.u32("instruction")])},AuthorizeWithSeed:{index:10,layout:ap.struct([ap.u32("instruction"),((e="voteAuthorizeWithSeedArgs")=>ap.struct([ap.u32("voteAuthorizationType"),sv("currentAuthorityDerivedKeyOwnerPubkey"),av("currentAuthorityDerivedKeySeed"),sv("newAuthorized")],e))()])}}),new ev("Vote111111111111111111111111111111111111111"),new ev("Va1idator1nfo111111111111111111111111111111"),Zb({name:Jb(),website:Xb(Jb()),details:Xb(Jb()),iconUrl:Xb(Jb()),keybaseUsername:Xb(Jb())}),new ev("Vote111111111111111111111111111111111111111"),ap.struct([sv("nodePubkey"),sv("authorizedWithdrawer"),ap.u8("commission"),ap.nu64(),ap.seq(ap.struct([ap.nu64("slot"),ap.u32("confirmationCount")]),ap.offset(ap.u32(),-8),"votes"),ap.u8("rootSlotValid"),ap.nu64("rootSlot"),ap.nu64(),ap.seq(ap.struct([ap.nu64("epoch"),sv("authorizedVoter")]),ap.offset(ap.u32(),-8),"authorizedVoters"),ap.struct([ap.seq(ap.struct([sv("authorizedPubkey"),ap.nu64("epochOfLastAuthorizedSwitch"),ap.nu64("targetEpoch")]),32,"buf"),ap.nu64("idx"),ap.u8("isEmpty")],"priorVoters"),ap.nu64(),ap.seq(ap.struct([ap.nu64("epoch"),ap.nu64("credits"),ap.nu64("prevCredits")]),ap.offset(ap.u32(),-8),"epochCredits"),ap.struct([ap.nu64("slot"),ap.nu64("timestamp")],"lastTimestamp")]);function KA(e){return/^0x[a-fA-F0-9]{64}$/.test(e)}function GA(e){const t=new Map;for(const n of e)t.set(is(n.symbol),n);return t}function zA(e,t,n){const r=function(e,t){return e.get(is(t))}(e,t);if(!r){throw j(`Token ${t} not supported for ${n}. Supported: ${Array.from(e.keys()).join(", ")}`,"tokenSymbol")}return r}function WA(e){if(!e||!KA(e))throw W("privateKey","a 0x-prefixed 64-character hex string (e.g., 0x1234...abcd)","Ethereum private key")}class HA{constructor(e){this.cache=new Map,this.galaConnectClient=e.galaConnectClient}async getTokenMetadata(e){const t=os(e),n=this.cache.get(t);if(n)return n;const r=su[t];if(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=os(e);return this.cache.has(t)||t in su}clearCache(){this.cache.clear()}async fetchFromApi(e){let t=e,n=await this.galaConnectClient.getBridgeConfigurations(t),r=n.find(e=>os(e.symbol)===os(t)&&e.verified);if(r||e.startsWith("G")||(t=`G${e}`,n=await this.galaConnectClient.getBridgeConfigurations(t),r=n.find(e=>os(e.symbol)===os(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},o=r.decimals,s=r.channel,{descriptor:{collection:i.collection,category:i.category,type:i.type,additionalKey:i.additionalKey},decimals:o,...s&&{channel:s}};var i,o,s}}async function jA(e,t){const{wallet:n}=t,r=e.uniqueKey??`galaconnect-operation-${m.randomUUID()}`,i="string"==typeof e.destinationChainId?Oe(e.destinationChainId,1):e.destinationChainId,o=function(e){const t={...e,galaDecimals:"string"==typeof e.galaDecimals?Oe(e.galaDecimals,0):e.galaDecimals,timestamp:"string"==typeof e.timestamp?Oe(e.timestamp,0):e.timestamp};if(e.galaExchangeRate&&(t.galaExchangeRate={...e.galaExchangeRate,timestamp:"string"==typeof e.galaExchangeRate.timestamp?Oe(e.galaExchangeRate.timestamp,0):e.galaExchangeRate.timestamp}),e.galaExchangeCrossRate){const n=e.galaExchangeCrossRate;t.galaExchangeCrossRate={...n,timestamp:"string"==typeof n.timestamp?Oe(n.timestamp,0):n.timestamp},n.baseTokenCrossRate&&(t.galaExchangeCrossRate.baseTokenCrossRate={...n.baseTokenCrossRate,timestamp:"string"==typeof n.baseTokenCrossRate.timestamp?Oe(n.baseTokenCrossRate.timestamp,0):n.baseTokenCrossRate.timestamp}),n.quoteTokenCrossRate&&(t.galaExchangeCrossRate.quoteTokenCrossRate={...n.quoteTokenCrossRate,timestamp:"string"==typeof n.quoteTokenCrossRate.timestamp?Oe(n.quoteTokenCrossRate.timestamp,0):n.quoteTokenCrossRate.timestamp})}return t}(e.destinationChainTxFee),s=Boolean(o.galaExchangeCrossRate),a={destinationChainId:i,destinationChainTxFee:Dh(s?{...o,galaExchangeRate:void 0}:{...o,galaExchangeCrossRate:void 0}),quantity:e.quantity,recipient:e.recipient,tokenInstance:e.tokenInstance,uniqueKey:r},c=yu(s),u=await n.signTypedData(lu,c,a),l=`Ethereum Signed Message:\n${Vc({domain:lu,message:a,primaryType:"GalaTransaction",types:c}).length}`;return{...a,signature:u,prefix:l,types:c,domain:lu}}const VA=5,XA=6,QA=7;function JA(e){const t=Oe(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===VA,isFailed:t===XA||t===QA}}const YA="Token symbol resolution failed. This is an internal error - BridgeService should resolve tokenId to symbol before calling strategy.",ZA="Bridge request ID missing from RequestTokenBridgeOut response",eT="BridgeTokenOut response missing transaction hash";function tT(e){if(!e)throw j(YA,"tokenSymbol");return e}function nT(t,n){if(!e.isAddress(t)){throw W(n||"address","a valid 0x-prefixed Ethereum address",t)}}function rT(e,t){try{return new ev(e)}catch{throw W(t||"address","a valid Solana address (base58)",e)}}function iT(e){try{return new ev(e)}catch{throw W("address","a valid Solana address (base58)",e)}}function oT(e,t,n){return{symbol:e,quantity:t,decimals:n,contractAddress:null,isNative:!0}}function sT(e,t){return{symbol:e.symbol,quantity:t,decimals:e.decimals??18,contractAddress:e.contractAddress,isNative:!1}}function aT(e,t){return{symbol:e.symbol,quantity:t,decimals:e.decimals??9,contractAddress:e.mintAddress,isNative:e.isNative??!1}}function cT(e,t,n){const r=e.find(e=>e.symbol===t);if(!r){const r=e.map(e=>e.symbol).join(", ");throw z("tokenSymbol",`Unsupported ${n} token: ${t}. Supported: ${r}`)}return r}const uT={Ethereum:"Ethereum bridging not configured. Provide ethereumPrivateKey in config.",Solana:"Solana bridging not configured. Provide solanaPrivateKey in config."};function lT(e,t,n){if(!e)throw j(n??uT[t],`${t.toLowerCase()}Strategy`);return e}function hT(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}`}}function dT(e,t){return lT(e.get("Ethereum"),"Ethereum",t)}function fT(e,t){return lT(e.get("Solana"),"Solana",t)}function gT(e,t){return e??t.getWalletAddress()}async function pT(e,t){const{amount:n,recipientAddress:r,tokenSymbol:i}=e,{galaConnectClient:o,tokenMetadataResolver:s,ethereumWallet:a,destinationChainId:c,destinationChain:u,validateRecipientAddress:l}=t,h=tT(i);Lh(n,h),l(r,"recipient");const d=await s.getTokenMetadata(h),f=await o.fetchBridgeFee({chainId:u,bridgeToken:d.descriptor}),g=function(e){return{destinationChainId:e.destinationChainId,destinationChainTxFee:e.bridgeFee,quantity:e.amount,recipient:e.recipientAddress,tokenInstance:{...e.tokenDescriptor,instance:"0"}}}({destinationChainId:c,bridgeFee:f,amount:n,recipientAddress:r,tokenDescriptor:d.descriptor}),p=await jA(g,{wallet:a}),m=function(e){if(!e)throw j(ZA,"bridgeRequestId");return e}(function(e){if("string"==typeof e.Data)return e.Data;if(null!=e.data){if("string"==typeof e.data)return e.data;if("object"==typeof e.data){const t=e.data;if("string"==typeof t.Data)return t.Data}}}(await o.requestBridgeOut(p)));return function(e){return{direction:"outbound",fromChain:"GalaChain",toChain:e.toChain,transactionHash:e.transactionHash,tokenSymbol:e.tokenSymbol,amount:e.amount,feePaid:e.feePaid,timestamp:Date.now(),statusUrl:`${e.baseUrl}/v1/bridge/transaction?hash=${e.transactionHash}`}}({toChain:u,transactionHash:function(e){const t=e.Hash??e.hash??"";if(!t)throw j(eT,"transactionHash");return t}(await o.bridgeTokenOut({bridgeFromChannel:"asset",bridgeRequestId:m})),tokenSymbol:h,amount:n,feePaid:f.estimatedTotalTxFeeInGala,baseUrl:o.getBaseUrl()})}class mT extends Error{constructor(e,t,n){super(`GalaConnect request to ${t} failed with status ${e}${n?`: ${JSON.stringify(n)}`:""}`),this.status=e,this.path=t,this.responseBody=n,this.name="GalaConnectHttpError"}}const yT=Zc,wT="https://galachain-gateway-chain-platform-galachain-mainnet.gala.com",bT=12,kT=!0,vT=3,ST=1e3;class AT{constructor(e){this.baseUrl=e.baseUrl??yT,this.galachainBaseUrl=e.galachainBaseUrl??wT,this.walletAddress=e.walletAddress,this.rateLimiter=new Th(e.requestsPerSecond??bT),this.defaultHeaders={"Content-Type":"application/json","X-Wallet-Address":this.walletAddress};const t=e.enableRetry??kT;this.retryOptions=t?{maxRetries:e.maxRetries??vT,initialDelayMs:e.retryInitialDelayMs??ST,...e.onRetry&&{onRetry:e.onRetry},shouldRetry:e=>Bh(e instanceof mT?{status:e.status}:e)}:null}getBaseUrl(){return this.baseUrl}async getBridgeConfigurations(e){return wr(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?Pe(e,{rawBody:e}):{message:"Failed to fetch bridge configurations"},new mT(n.status,"/v1/connect/bridge-configurations",t)}return(await n.json()).data.tokens},"GalaConnectClient.getBridgeConfigurations",void 0,(e,t,n)=>{if(e instanceof mT)throw e;throw X(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 wr(async()=>{const r=n.baseUrl??this.baseUrl,i=new URL(e,r),o=n.skipWalletHeader?{"Content-Type":"application/json","X-Wallet-Address":""}:this.defaultHeaders,s=await this.request(i.toString(),{method:"POST",headers:o,body:JSON.stringify(t,(e,t)=>"bigint"==typeof t?t.toString():t)});if(!s.ok){const t=await s.text(),n=500,r=Pe(t,{rawBody:t.slice(0,n)});throw new mT(s.status,e,r)}const a=await s.text();if(a){const t=function(e){if(Je(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: ${A(e)}`}}}(a);if(!t.success)throw new Error(`Failed to parse JSON response from ${e}: ${t.error}`);return t.value}},`Failed to execute POST request to ${e}`,void 0,(e,t,n)=>{if(e instanceof mT)throw e;throw X(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 mT(t,e,i)}}return r});return this.retryOptions?async function(e,t={}){const n={...xh,...t},r=t.shouldRetry??(e=>Bh(e));let i;for(let o=1;o<=n.maxRetries+1;o++)try{return await e()}catch(e){if(i=e,o>n.maxRetries)break;if(!r(e,o))break;const s=_h(o,n);t.onRetry&&t.onRetry(e,o,s),await new Promise(e=>setTimeout(e,s))}throw i}(n,this.retryOptions):n()}async safeParseJson(e){const t=await e.text();try{return JSON.parse(t)}catch{return{rawBody:t}}}}var TT;exports.BridgeStatusCode=void 0,(TT=exports.BridgeStatusCode||(exports.BridgeStatusCode={}))[TT.PENDING=0]="PENDING",TT[TT.SUBMITTED=1]="SUBMITTED",TT[TT.CONFIRMED=2]="CONFIRMED",TT[TT.PROCESSING=3]="PROCESSING",TT[TT.FINALIZING=4]="FINALIZING",TT[TT.COMPLETED=5]="COMPLETED",TT[TT.FAILED=6]="FAILED",TT[TT.DELIVERY_FAILED=7]="DELIVERY_FAILED";class ET{async waitForCompletion(e,t={}){const{pollInterval:n=15e3,timeout:r=27e5,onStatusUpdate:i}=t,o=Date.now();for(;;){const t=await this.getStatus(e);if(i&&i(t),t.status===exports.BridgeStatusCode.COMPLETED||t.status===exports.BridgeStatusCode.FAILED||t.status===exports.BridgeStatusCode.DELIVERY_FAILED)return t;if(Ve(o)>r)throw V(`Bridge transaction timed out after ${r}ms. Last status: ${t.status}`,e,"TIMEOUT");await new Promise(e=>setTimeout(e,n))}}}class IT extends ET{constructor(t){super(),this.network="Ethereum",this.galaConnectClient=t.galaConnectClient,this.galaChainWalletAddress=t.galaChainWalletAddress,WA(t.ethereumPrivateKey);const n=t.ethereumRpcUrl??"https://ethereum.publicnode.com";this.ethereumProvider=new e.JsonRpcProvider(n),this.ethereumWallet=new e.Wallet(t.ethereumPrivateKey,this.ethereumProvider),this.ethereumWalletAddress=t.ethereumWalletAddress??this.ethereumWallet.address,this.ethereumBridgeContract=t.ethereumBridgeContract??"0x3F98b5A26EF3f04E1DA3B0B41dD350E8C8F3A7c2";const r=t.tokenConfigs??iu;this.tokenConfigs=GA(r),this.tokenMetadataResolver=new HA({galaConnectClient:this.galaConnectClient})}async estimateFee(e,t){const n=await this.tokenMetadataResolver.getTokenMetadata(e);return Oh(await this.galaConnectClient.fetchBridgeFee({chainId:"Ethereum",bridgeToken:n.descriptor}))}async bridgeOut(e){return pT(e,{galaConnectClient:this.galaConnectClient,tokenMetadataResolver:this.tokenMetadataResolver,ethereumWallet:this.ethereumWallet,destinationChainId:Xc.ETHEREUM,destinationChain:"Ethereum",validateRecipientAddress:nT})}async bridgeIn(t){const{amount:n,sourcePrivateKey:r,recipientAddress:i,tokenSymbol:o}=t,s=tT(o);if(Lh(n,s),r&&!KA(r))throw W("sourcePrivateKey","0x-prefixed 64-character hex string",r.slice(0,10)+"...");const a=r?new e.Wallet(r,this.ethereumProvider):this.ethereumWallet,c=zA(this.tokenConfigs,s,"Ethereum bridge"),u=await this.tokenMetadataResolver.getTokenMetadata(s),l=new e.Contract(c.contractAddress,au,a),h=Oe(await l.decimals(),18),d=Eh(n,h),f=BigInt(await l.balanceOf(a.address));if(f<d){throw j(`Insufficient ${s} balance on Ethereum. Needed ${Ih(d,h)}, have ${Ih(f,h)}`,"amount")}const g=function(t){const n=new lt;if("client"===n.detectFormat(t))return t;const r=n.normalizeInput(t);if(!r)throw W("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.getAddress("0x"+i).slice(2)}`}(i??this.galaChainWalletAddress);return hT({fromChain:"Ethereum",transactionHash:(await this.executeBridgeDeposit({wallet:a,tokenContract:l,tokenConfig:c,amountBaseUnits:d,decimals:h,recipient:g,metadata:u})).txHash,tokenSymbol:s,amount:n,baseUrl:this.galaConnectClient.getBaseUrl()})}async getStatus(e){return JA(await this.galaConnectClient.getBridgeStatus(e))}getSupportedTokens(){return Array.from(this.tokenConfigs.keys())}isTokenSupported(e){return this.tokenConfigs.has(is(e))}isValidAddress(e){return Xe.ETH_ADDRESS.test(e)}getWalletAddress(){return this.ethereumWalletAddress}async getEthereumTokenBalance(t,n){const r=zA(this.tokenConfigs,t,"Ethereum"),i=n??this.ethereumWalletAddress;nT(i);const o=new e.Contract(r.contractAddress,au,this.ethereumProvider);return Ih(await o.balanceOf(i),r.decimals??18)}async getEthereumNativeBalance(e){const t=e??this.ethereumWalletAddress;nT(t);return Ih(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 W("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>=IT.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: ${A(e)}`}}}async executeBridgeDeposit(t){const n=new e.Contract(this.ethereumBridgeContract,cu,t.wallet),r=(new TextEncoder).encode(t.recipient);let i;i=t.tokenConfig.bridgeUsesPermit?await this.bridgeWithPermit(t.wallet,t.tokenContract,t.tokenConfig,n,t.amountBaseUnits,r):await this.bridgeWithApproval(t.wallet,t.tokenContract,n,t.tokenConfig,t.amountBaseUnits,r);if(!await i.wait())throw j("Bridge transaction receipt not available","ethereumRpcUrl");await Ph(3e4);const o={collection:t.metadata.descriptor.collection,category:t.metadata.descriptor.category,type:t.metadata.descriptor.type,additionalKey:t.metadata.descriptor.additionalKey,instance:"0"};return await this.galaConnectClient.registerBridgeTransaction({quantity:Ih(t.amountBaseUnits,t.decimals),tokenInstance:o,fromChain:"Ethereum",toChain:"GC",hash:i.hash}),{txHash:i.hash}}async bridgeWithPermit(t,n,r,i,o,s){const a=await this.ethereumProvider.getNetwork(),c=await n.name(),u=await n.nonces(t.address),l=BigInt(Math.floor(Date.now()/1e3)+3600),h=await t.signTypedData({name:c,version:"1",chainId:Oe(a.chainId,1),verifyingContract:r.contractAddress},{Permit:[{name:"owner",type:"address"},{name:"spender",type:"address"},{name:"value",type:"uint256"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}]},{owner:t.address,spender:this.ethereumBridgeContract,value:o,nonce:u,deadline:l}),d=e.Signature.from(h);return i.bridgeOutWithPermit(r.contractAddress,o,Xc.GALA_CHAIN,s,l,d.v,d.r,d.s)}async bridgeWithApproval(e,t,n,r,i,o){const s=await t.allowance(e.address,this.ethereumBridgeContract);if(BigInt(s)<i){const e=await t.approve(this.ethereumBridgeContract,i);await e.wait()}return n.bridgeOut(r.contractAddress,i,0,Xc.GALA_CHAIN,o)}}IT.ETHEREUM_FINALITY_THRESHOLD=12;for(var xT={},CT={byteLength:function(e){var t=DT(e),n=t[0],r=t[1];return 3*(n+r)/4-r},toByteArray:function(e){var t,n,r=DT(e),i=r[0],o=r[1],s=new _T(function(e,t,n){return 3*(t+n)/4-n}(0,i,o)),a=0,c=o>0?i-4:i;for(n=0;n<c;n+=4)t=BT[e.charCodeAt(n)]<<18|BT[e.charCodeAt(n+1)]<<12|BT[e.charCodeAt(n+2)]<<6|BT[e.charCodeAt(n+3)],s[a++]=t>>16&255,s[a++]=t>>8&255,s[a++]=255&t;2===o&&(t=BT[e.charCodeAt(n)]<<2|BT[e.charCodeAt(n+1)]>>4,s[a++]=255&t);1===o&&(t=BT[e.charCodeAt(n)]<<10|BT[e.charCodeAt(n+1)]<<4|BT[e.charCodeAt(n+2)]>>2,s[a++]=t>>8&255,s[a++]=255&t);return s},fromByteArray:function(e){for(var t,n=e.length,r=n%3,i=[],o=16383,s=0,a=n-r;s<a;s+=o)i.push(OT(e,s,s+o>a?a:s+o));1===r?(t=e[n-1],i.push(NT[t>>2]+NT[t<<4&63]+"==")):2===r&&(t=(e[n-2]<<8)+e[n-1],i.push(NT[t>>10]+NT[t>>4&63]+NT[t<<2&63]+"="));return i.join("")}},NT=[],BT=[],_T="undefined"!=typeof Uint8Array?Uint8Array:Array,PT="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",RT=0;RT<64;++RT)NT[RT]=PT[RT],BT[PT.charCodeAt(RT)]=RT;function DT(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 LT(e){return NT[e>>18&63]+NT[e>>12&63]+NT[e>>6&63]+NT[63&e]}function OT(e,t,n){for(var r,i=[],o=t;o<n;o+=3)r=(e[o]<<16&16711680)+(e[o+1]<<8&65280)+(255&e[o+2]),i.push(LT(r));return i.join("")}BT["-".charCodeAt(0)]=62,BT["_".charCodeAt(0)]=63;var UT={};UT.read=function(e,t,n,r,i){var o,s,a=8*i-r-1,c=(1<<a)-1,u=c>>1,l=-7,h=n?i-1:0,d=n?-1:1,f=e[t+h];for(h+=d,o=f&(1<<-l)-1,f>>=-l,l+=a;l>0;o=256*o+e[t+h],h+=d,l-=8);for(s=o&(1<<-l)-1,o>>=-l,l+=r;l>0;s=256*s+e[t+h],h+=d,l-=8);if(0===o)o=1-u;else{if(o===c)return s?NaN:1/0*(f?-1:1);s+=Math.pow(2,r),o-=u}return(f?-1:1)*s*Math.pow(2,o-r)},UT.write=function(e,t,n,r,i,o){var s,a,c,u=8*o-i-1,l=(1<<u)-1,h=l>>1,d=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,f=r?0:o-1,g=r?1:-1,p=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,s=l):(s=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-s))<1&&(s--,c*=2),(t+=s+h>=1?d/c:d*Math.pow(2,1-h))*c>=2&&(s++,c/=2),s+h>=l?(a=0,s=l):s+h>=1?(a=(t*c-1)*Math.pow(2,i),s+=h):(a=t*Math.pow(2,h-1)*Math.pow(2,i),s=0));i>=8;e[n+f]=255&a,f+=g,a/=256,i-=8);for(s=s<<i|a,u+=i;u>0;e[n+f]=255&s,f+=g,s/=256,u-=8);e[n+f-g]|=128*p},function(e){const t=CT,n=UT,r="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;e.Buffer=s,e.SlowBuffer=function(e){+e!=e&&(e=0);return s.alloc(+e)},e.INSPECT_MAX_BYTES=50;const i=2147483647;function o(e){if(e>i)throw new RangeError('The value "'+e+'" is invalid for option "size"');const t=new Uint8Array(e);return Object.setPrototypeOf(t,s.prototype),t}function s(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 u(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(!s.isEncoding(t))throw new TypeError("Unknown encoding: "+t);const n=0|f(e,t);let r=o(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(j(e,Uint8Array)){const t=new Uint8Array(e);return h(t.buffer,t.byteOffset,t.byteLength)}return l(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(j(e,ArrayBuffer)||e&&j(e.buffer,ArrayBuffer))return h(e,t,n);if("undefined"!=typeof SharedArrayBuffer&&(j(e,SharedArrayBuffer)||e&&j(e.buffer,SharedArrayBuffer)))return h(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 s.from(r,t,n);const i=function(e){if(s.isBuffer(e)){const t=0|d(e.length),n=o(t);return 0===n.length||e.copy(n,0,0,t),n}if(void 0!==e.length)return"number"!=typeof e.length||V(e.length)?o(0):l(e);if("Buffer"===e.type&&Array.isArray(e.data))return l(e.data)}(e);if(i)return i;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return s.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 u(e){return c(e),o(e<0?0:0|d(e))}function l(e){const t=e.length<0?0:0|d(e.length),n=o(t);for(let r=0;r<t;r+=1)n[r]=255&e[r];return n}function h(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,s.prototype),r}function d(e){if(e>=i)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i.toString(16)+" bytes");return 0|e}function f(e,t){if(s.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||j(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 z(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return W(e).length;default:if(i)return r?-1:z(e).length;t=(""+t).toLowerCase(),i=!0}}function g(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 T(this,t,n);case"ascii":return I(this,t,n);case"latin1":case"binary":return x(this,t,n);case"base64":return A(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return N(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function p(e,t,n){const r=e[t];e[t]=e[n],e[n]=r}function m(e,t,n,r,i){if(0===e.length)return-1;if("string"==typeof n?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),V(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=s.from(t,r)),s.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 o,s=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;s=2,a/=2,c/=2,n/=2}function u(e,t){return 1===s?e[t]:e.readUInt16BE(t*s)}if(i){let r=-1;for(o=n;o<a;o++)if(u(e,o)===u(t,-1===r?0:o-r)){if(-1===r&&(r=o),o-r+1===c)return r*s}else-1!==r&&(o-=o-r),r=-1}else for(n+c>a&&(n=a-c),o=n;o>=0;o--){let n=!0;for(let r=0;r<c;r++)if(u(e,o+r)!==u(t,r)){n=!1;break}if(n)return o}return-1}function w(e,t,n,r){n=Number(n)||0;const i=e.length-n;r?(r=Number(r))>i&&(r=i):r=i;const o=t.length;let s;for(r>o/2&&(r=o/2),s=0;s<r;++s){const r=parseInt(t.substr(2*s,2),16);if(V(r))return s;e[n+s]=r}return s}function b(e,t,n,r){return H(z(t,e.length-n),e,n,r)}function k(e,t,n,r){return H(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 v(e,t,n,r){return H(W(t),e,n,r)}function S(e,t,n,r){return H(function(e,t){let n,r,i;const o=[];for(let s=0;s<e.length&&!((t-=2)<0);++s)n=e.charCodeAt(s),r=n>>8,i=n%256,o.push(i),o.push(r);return o}(t,e.length-n),e,n,r)}function A(e,n,r){return 0===n&&r===e.length?t.fromByteArray(e):t.fromByteArray(e.slice(n,r))}function T(e,t,n){n=Math.min(e.length,n);const r=[];let i=t;for(;i<n;){const t=e[i];let o=null,s=t>239?4:t>223?3:t>191?2:1;if(i+s<=n){let n,r,a,c;switch(s){case 1:t<128&&(o=t);break;case 2:n=e[i+1],128==(192&n)&&(c=(31&t)<<6|63&n,c>127&&(o=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)&&(o=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&&(o=c))}}null===o?(o=65533,s=1):o>65535&&(o-=65536,r.push(o>>>10&1023|55296),o=56320|1023&o),r.push(o),i+=s}return function(e){const t=e.length;if(t<=E)return String.fromCharCode.apply(String,e);let n="",r=0;for(;r<t;)n+=String.fromCharCode.apply(String,e.slice(r,r+=E));return n}(r)}e.kMaxLength=i,s.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}}(),!s.TYPED_ARRAY_SUPPORT&&"undefined"!=typeof console&&console.error,Object.defineProperty(s.prototype,"parent",{enumerable:!0,get:function(){if(s.isBuffer(this))return this.buffer}}),Object.defineProperty(s.prototype,"offset",{enumerable:!0,get:function(){if(s.isBuffer(this))return this.byteOffset}}),s.poolSize=8192,s.from=function(e,t,n){return a(e,t,n)},Object.setPrototypeOf(s.prototype,Uint8Array.prototype),Object.setPrototypeOf(s,Uint8Array),s.alloc=function(e,t,n){return function(e,t,n){return c(e),e<=0?o(e):void 0!==t?"string"==typeof n?o(e).fill(t,n):o(e).fill(t):o(e)}(e,t,n)},s.allocUnsafe=function(e){return u(e)},s.allocUnsafeSlow=function(e){return u(e)},s.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==s.prototype},s.compare=function(e,t){if(j(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),j(t,Uint8Array)&&(t=s.from(t,t.offset,t.byteLength)),!s.isBuffer(e)||!s.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,o=Math.min(n,r);i<o;++i)if(e[i]!==t[i]){n=e[i],r=t[i];break}return n<r?-1:r<n?1:0},s.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}},s.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return s.alloc(0);let n;if(void 0===t)for(t=0,n=0;n<e.length;++n)t+=e[n].length;const r=s.allocUnsafe(t);let i=0;for(n=0;n<e.length;++n){let t=e[n];if(j(t,Uint8Array))i+t.length>r.length?(s.isBuffer(t)||(t=s.from(t)),t.copy(r,i)):Uint8Array.prototype.set.call(r,t,i);else{if(!s.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(r,i)}i+=t.length}return r},s.byteLength=f,s.prototype._isBuffer=!0,s.prototype.swap16=function(){const e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let t=0;t<e;t+=2)p(this,t,t+1);return this},s.prototype.swap32=function(){const e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let t=0;t<e;t+=4)p(this,t,t+3),p(this,t+1,t+2);return this},s.prototype.swap64=function(){const e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let t=0;t<e;t+=8)p(this,t,t+7),p(this,t+1,t+6),p(this,t+2,t+5),p(this,t+3,t+4);return this},s.prototype.toString=function(){const e=this.length;return 0===e?"":0===arguments.length?T(this,0,e):g.apply(this,arguments)},s.prototype.toLocaleString=s.prototype.toString,s.prototype.equals=function(e){if(!s.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===s.compare(this,e)},s.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&&(s.prototype[r]=s.prototype.inspect),s.prototype.compare=function(e,t,n,r,i){if(j(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),!s.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 o=(i>>>=0)-(r>>>=0),a=(n>>>=0)-(t>>>=0);const c=Math.min(o,a),u=this.slice(r,i),l=e.slice(t,n);for(let e=0;e<c;++e)if(u[e]!==l[e]){o=u[e],a=l[e];break}return o<a?-1:a<o?1:0},s.prototype.includes=function(e,t,n){return-1!==this.indexOf(e,t,n)},s.prototype.indexOf=function(e,t,n){return m(this,e,t,n,!0)},s.prototype.lastIndexOf=function(e,t,n){return m(this,e,t,n,!1)},s.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 o=!1;for(;;)switch(r){case"hex":return w(this,e,t,n);case"utf8":case"utf-8":return b(this,e,t,n);case"ascii":case"latin1":case"binary":return k(this,e,t,n);case"base64":return v(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return S(this,e,t,n);default:if(o)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),o=!0}},s.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const E=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 x(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 N(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 B(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 _(e,t,n,r,i,o){if(!s.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||t<o)throw new RangeError('"value" argument is out of bounds');if(n+r>e.length)throw new RangeError("Index out of range")}function P(e,t,n,r,i){$(t,r,i,e,n,7);let o=Number(t&BigInt(4294967295));e[n++]=o,o>>=8,e[n++]=o,o>>=8,e[n++]=o,o>>=8,e[n++]=o;let s=Number(t>>BigInt(32)&BigInt(4294967295));return e[n++]=s,s>>=8,e[n++]=s,s>>=8,e[n++]=s,s>>=8,e[n++]=s,n}function R(e,t,n,r,i){$(t,r,i,e,n,7);let o=Number(t&BigInt(4294967295));e[n+7]=o,o>>=8,e[n+6]=o,o>>=8,e[n+5]=o,o>>=8,e[n+4]=o;let s=Number(t>>BigInt(32)&BigInt(4294967295));return e[n+3]=s,s>>=8,e[n+2]=s,s>>=8,e[n+1]=s,s>>=8,e[n]=s,n+8}function D(e,t,n,r,i,o){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function L(e,t,r,i,o){return t=+t,r>>>=0,o||D(e,0,r,4),n.write(e,t,r,i,23,4),r+4}function O(e,t,r,i,o){return t=+t,r>>>=0,o||D(e,0,r,8),n.write(e,t,r,i,52,8),r+8}s.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,s.prototype),r},s.prototype.readUintLE=s.prototype.readUIntLE=function(e,t,n){e>>>=0,t>>>=0,n||B(e,t,this.length);let r=this[e],i=1,o=0;for(;++o<t&&(i*=256);)r+=this[e+o]*i;return r},s.prototype.readUintBE=s.prototype.readUIntBE=function(e,t,n){e>>>=0,t>>>=0,n||B(e,t,this.length);let r=this[e+--t],i=1;for(;t>0&&(i*=256);)r+=this[e+--t]*i;return r},s.prototype.readUint8=s.prototype.readUInt8=function(e,t){return e>>>=0,t||B(e,1,this.length),this[e]},s.prototype.readUint16LE=s.prototype.readUInt16LE=function(e,t){return e>>>=0,t||B(e,2,this.length),this[e]|this[e+1]<<8},s.prototype.readUint16BE=s.prototype.readUInt16BE=function(e,t){return e>>>=0,t||B(e,2,this.length),this[e]<<8|this[e+1]},s.prototype.readUint32LE=s.prototype.readUInt32LE=function(e,t){return e>>>=0,t||B(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},s.prototype.readUint32BE=s.prototype.readUInt32BE=function(e,t){return e>>>=0,t||B(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},s.prototype.readBigUInt64LE=Q(function(e){q(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||K(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))}),s.prototype.readBigUInt64BE=Q(function(e){q(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||K(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)}),s.prototype.readIntLE=function(e,t,n){e>>>=0,t>>>=0,n||B(e,t,this.length);let r=this[e],i=1,o=0;for(;++o<t&&(i*=256);)r+=this[e+o]*i;return i*=128,r>=i&&(r-=Math.pow(2,8*t)),r},s.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||B(e,t,this.length);let r=t,i=1,o=this[e+--r];for(;r>0&&(i*=256);)o+=this[e+--r]*i;return i*=128,o>=i&&(o-=Math.pow(2,8*t)),o},s.prototype.readInt8=function(e,t){return e>>>=0,t||B(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},s.prototype.readInt16LE=function(e,t){e>>>=0,t||B(e,2,this.length);const n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},s.prototype.readInt16BE=function(e,t){e>>>=0,t||B(e,2,this.length);const n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},s.prototype.readInt32LE=function(e,t){return e>>>=0,t||B(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},s.prototype.readInt32BE=function(e,t){return e>>>=0,t||B(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},s.prototype.readBigInt64LE=Q(function(e){q(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||K(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)}),s.prototype.readBigInt64BE=Q(function(e){q(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||K(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)}),s.prototype.readFloatLE=function(e,t){return e>>>=0,t||B(e,4,this.length),n.read(this,e,!0,23,4)},s.prototype.readFloatBE=function(e,t){return e>>>=0,t||B(e,4,this.length),n.read(this,e,!1,23,4)},s.prototype.readDoubleLE=function(e,t){return e>>>=0,t||B(e,8,this.length),n.read(this,e,!0,52,8)},s.prototype.readDoubleBE=function(e,t){return e>>>=0,t||B(e,8,this.length),n.read(this,e,!1,52,8)},s.prototype.writeUintLE=s.prototype.writeUIntLE=function(e,t,n,r){if(e=+e,t>>>=0,n>>>=0,!r){_(this,e,t,n,Math.pow(2,8*n)-1,0)}let i=1,o=0;for(this[t]=255&e;++o<n&&(i*=256);)this[t+o]=e/i&255;return t+n},s.prototype.writeUintBE=s.prototype.writeUIntBE=function(e,t,n,r){if(e=+e,t>>>=0,n>>>=0,!r){_(this,e,t,n,Math.pow(2,8*n)-1,0)}let i=n-1,o=1;for(this[t+i]=255&e;--i>=0&&(o*=256);)this[t+i]=e/o&255;return t+n},s.prototype.writeUint8=s.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||_(this,e,t,1,255,0),this[t]=255&e,t+1},s.prototype.writeUint16LE=s.prototype.writeUInt16LE=function(e,t,n){return e=+e,t>>>=0,n||_(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},s.prototype.writeUint16BE=s.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||_(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},s.prototype.writeUint32LE=s.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||_(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},s.prototype.writeUint32BE=s.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||_(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},s.prototype.writeBigUInt64LE=Q(function(e,t=0){return P(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),s.prototype.writeBigUInt64BE=Q(function(e,t=0){return R(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),s.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t>>>=0,!r){const r=Math.pow(2,8*n-1);_(this,e,t,n,r-1,-r)}let i=0,o=1,s=0;for(this[t]=255&e;++i<n&&(o*=256);)e<0&&0===s&&0!==this[t+i-1]&&(s=1),this[t+i]=(e/o|0)-s&255;return t+n},s.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t>>>=0,!r){const r=Math.pow(2,8*n-1);_(this,e,t,n,r-1,-r)}let i=n-1,o=1,s=0;for(this[t+i]=255&e;--i>=0&&(o*=256);)e<0&&0===s&&0!==this[t+i+1]&&(s=1),this[t+i]=(e/o|0)-s&255;return t+n},s.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||_(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},s.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||_(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},s.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||_(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},s.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||_(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},s.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||_(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},s.prototype.writeBigInt64LE=Q(function(e,t=0){return P(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),s.prototype.writeBigInt64BE=Q(function(e,t=0){return R(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),s.prototype.writeFloatLE=function(e,t,n){return L(this,e,t,!0,n)},s.prototype.writeFloatBE=function(e,t,n){return L(this,e,t,!1,n)},s.prototype.writeDoubleLE=function(e,t,n){return O(this,e,t,!0,n)},s.prototype.writeDoubleBE=function(e,t,n){return O(this,e,t,!1,n)},s.prototype.copy=function(e,t,n,r){if(!s.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},s.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&&!s.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 o=s.isBuffer(e)?e:s.from(e,r),a=o.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]=o[i%a]}return this};const U={};function M(e,t,n){U[e]=class extends n{constructor(){super(),Object.defineProperty(this,"message",{value:t.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${e}]`,this.stack,delete this.name}get code(){return e}set code(e){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:e,writable:!0})}toString(){return`${this.name} [${e}]: ${this.message}`}}}function F(e){let t="",n=e.length;const r="-"===e[0]?1:0;for(;n>=r+4;n-=3)t=`_${e.slice(n-3,n)}${t}`;return`${e.slice(0,n)}${t}`}function $(e,t,n,r,i,o){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*(o+1)}${n}`:`>= -(2${n} ** ${8*(o+1)-1}${n}) and < 2 ** ${8*(o+1)-1}${n}`,new U.ERR_OUT_OF_RANGE("value",r,e)}!function(e,t,n){q(t,"offset"),void 0!==e[t]&&void 0!==e[t+n]||K(t,e.length-(n+1))}(r,i,o)}function q(e,t){if("number"!=typeof e)throw new U.ERR_INVALID_ARG_TYPE(t,"number",e)}function K(e,t,n){if(Math.floor(e)!==e)throw q(e,n),new U.ERR_OUT_OF_RANGE("offset","an integer",e);if(t<0)throw new U.ERR_BUFFER_OUT_OF_BOUNDS;throw new U.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${t}`,e)}M("ERR_BUFFER_OUT_OF_BOUNDS",function(e){return e?`${e} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),M("ERR_INVALID_ARG_TYPE",function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`},TypeError),M("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 G=/[^+/0-9A-Za-z-_]/g;function z(e,t){let n;t=t||1/0;const r=e.length;let i=null;const o=[];for(let s=0;s<r;++s){if(n=e.charCodeAt(s),n>55295&&n<57344){if(!i){if(n>56319){(t-=3)>-1&&o.push(239,191,189);continue}if(s+1===r){(t-=3)>-1&&o.push(239,191,189);continue}i=n;continue}if(n<56320){(t-=3)>-1&&o.push(239,191,189),i=n;continue}n=65536+(i-55296<<10|n-56320)}else i&&(t-=3)>-1&&o.push(239,191,189);if(i=null,n<128){if((t-=1)<0)break;o.push(n)}else if(n<2048){if((t-=2)<0)break;o.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;o.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;o.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return o}function W(e){return t.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(G,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function H(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 j(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function V(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 Q(e){return"undefined"==typeof BigInt?J:e}function J(){throw new Error("BigInt not supported")}}(xT);var MT,FT="function"==typeof Object.create?function(e,t){e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})}:function(e,t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e};function $T(e,t){var n={seen:[],stylize:KT};return arguments.length>=3&&(n.depth=arguments[2]),arguments.length>=4&&(n.colors=arguments[3]),HT(t)?n.showHidden=t:t&&function(e,t){if(!t||!JT(t))return e;var n=Object.keys(t),r=n.length;for(;r--;)e[n[r]]=t[n[r]]}(n,t),XT(n.showHidden)&&(n.showHidden=!1),XT(n.depth)&&(n.depth=2),XT(n.colors)&&(n.colors=!1),XT(n.customInspect)&&(n.customInspect=!0),n.colors&&(n.stylize=qT),GT(n,e,n.depth)}function qT(e,t){var n=$T.styles[t];return n?"["+$T.colors[n][0]+"m"+e+"["+$T.colors[n][1]+"m":e}function KT(e,t){return e}function GT(e,t,n){if(e.customInspect&&t&&eE(t.inspect)&&t.inspect!==$T&&(!t.constructor||t.constructor.prototype!==t)){var r=t.inspect(n,e);return VT(r)||(r=GT(e,r,n)),r}var i=function(e,t){if(XT(t))return e.stylize("undefined","undefined");if(VT(t)){var n="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(n,"string")}if(r=t,"number"==typeof r)return e.stylize(""+t,"number");var r;if(HT(t))return e.stylize(""+t,"boolean");if(jT(t))return e.stylize("null","null")}(e,t);if(i)return i;var o=Object.keys(t),s=function(e){var t={};return e.forEach(function(e,n){t[e]=!0}),t}(o);if(e.showHidden&&(o=Object.getOwnPropertyNames(t)),ZT(t)&&(o.indexOf("message")>=0||o.indexOf("description")>=0))return zT(t);if(0===o.length){if(eE(t)){var a=t.name?": "+t.name:"";return e.stylize("[Function"+a+"]","special")}if(QT(t))return e.stylize(RegExp.prototype.toString.call(t),"regexp");if(YT(t))return e.stylize(Date.prototype.toString.call(t),"date");if(ZT(t))return zT(t)}var c,u,l="",h=!1,d=["{","}"];(c=t,Array.isArray(c)&&(h=!0,d=["[","]"]),eE(t))&&(l=" [Function"+(t.name?": "+t.name:"")+"]");return QT(t)&&(l=" "+RegExp.prototype.toString.call(t)),YT(t)&&(l=" "+Date.prototype.toUTCString.call(t)),ZT(t)&&(l=" "+zT(t)),0!==o.length||h&&0!=t.length?n<0?QT(t)?e.stylize(RegExp.prototype.toString.call(t),"regexp"):e.stylize("[Object]","special"):(e.seen.push(t),u=h?function(e,t,n,r,i){for(var o=[],s=0,a=t.length;s<a;++s)nE(t,String(s))?o.push(WT(e,t,n,r,String(s),!0)):o.push("");return i.forEach(function(i){i.match(/^\d+$/)||o.push(WT(e,t,n,r,i,!0))}),o}(e,t,n,s,o):o.map(function(r){return WT(e,t,n,s,r,h)}),e.seen.pop(),function(e,t,n){var r=e.reduce(function(e,t){return t.indexOf("\n"),e+t.replace(/\u001b\[\d\d?m/g,"").length+1},0);if(r>60)return n[0]+(""===t?"":t+"\n ")+" "+e.join(",\n ")+" "+n[1];return n[0]+t+" "+e.join(", ")+" "+n[1]}(u,l,d)):d[0]+l+d[1]}function zT(e){return"["+Error.prototype.toString.call(e)+"]"}function WT(e,t,n,r,i,o){var s,a,c;if((c=Object.getOwnPropertyDescriptor(t,i)||{value:t[i]}).get?a=c.set?e.stylize("[Getter/Setter]","special"):e.stylize("[Getter]","special"):c.set&&(a=e.stylize("[Setter]","special")),nE(r,i)||(s="["+i+"]"),a||(e.seen.indexOf(c.value)<0?(a=jT(n)?GT(e,c.value,null):GT(e,c.value,n-1)).indexOf("\n")>-1&&(a=o?a.split("\n").map(function(e){return" "+e}).join("\n").substr(2):"\n"+a.split("\n").map(function(e){return" "+e}).join("\n")):a=e.stylize("[Circular]","special")),XT(s)){if(o&&i.match(/^\d+$/))return a;(s=JSON.stringify(""+i)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(s=s.substr(1,s.length-2),s=e.stylize(s,"name")):(s=s.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),s=e.stylize(s,"string"))}return s+": "+a}function HT(e){return"boolean"==typeof e}function jT(e){return null===e}function VT(e){return"string"==typeof e}function XT(e){return void 0===e}function QT(e){return JT(e)&&"[object RegExp]"===tE(e)}function JT(e){return"object"==typeof e&&null!==e}function YT(e){return JT(e)&&"[object Date]"===tE(e)}function ZT(e){return JT(e)&&("[object Error]"===tE(e)||e instanceof Error)}function eE(e){return"function"==typeof e}function tE(e){return Object.prototype.toString.call(e)}function nE(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function rE(){return void 0!==MT?MT:MT="foo"===function(){}.name}$T.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},$T.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};var iE=/\s*function\s+([^\(\s]*)\s*/;function oE(e){if(eE(e)){if(rE())return e.name;var t=e.toString().match(iE);return t&&t[1]}}function sE(e){var t;this.name="AssertionError",this.actual=e.actual,this.expected=e.expected,this.operator=e.operator,e.message?(this.message=e.message,this.generatedMessage=!1):(this.message=aE(cE((t=this).actual),128)+" "+t.operator+" "+aE(cE(t.expected),128),this.generatedMessage=!0);var n=e.stackStartFunction||uE;if(Error.captureStackTrace)Error.captureStackTrace(this,n);else{var r=new Error;if(r.stack){var i=r.stack,o=oE(n),s=i.indexOf("\n"+o);if(s>=0){var a=i.indexOf("\n",s+1);i=i.substring(a+1)}this.stack=i}}}function aE(e,t){return"string"==typeof e?e.length<t?e:e.slice(0,t):e}function cE(e){if(rE()||!eE(e))return $T(e);var t=oE(e);return"[Function"+(t?": "+t:"")+"]"}function uE(e,t,n,r,i){throw new sE({message:n,actual:e,expected:t,operator:r,stackStartFunction:i})}FT(sE,Error);class lE{constructor(e,t){if(!Number.isInteger(e))throw new TypeError("span must be an integer");this.span=e,this.property=t}makeDestinationObject(){return{}}decode(e,t){throw new Error("Layout is abstract")}encode(e,t,n){throw new Error("Layout is abstract")}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){}}class hE extends lE{isCount(){throw new Error("ExternalLayout is abstract")}}class dE extends lE{constructor(e,t){if(super(e,t),6<this.span)throw new RangeError("span must not exceed 6 bytes")}decode(e,t){return void 0===t&&(t=0),e.readUIntLE(t,this.span)}encode(e,t,n){return void 0===n&&(n=0),t.writeUIntLE(e,n,this.span),this.span}}class fE extends lE{constructor(e,t,n){if(!Array.isArray(e)||!e.reduce((e,t)=>e&&t instanceof lE,!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 r=-1;try{r=e.reduce((e,t)=>e+t.getSpan(),0)}catch(e){}super(r,t),this.fields=e,this.decodePrefixes=!!n}getSpan(e,t){if(0<=this.span)return this.span;void 0===t&&(t=0);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,t){void 0===t&&(t=0);const n=this.makeDestinationObject();for(const r of this.fields)if(void 0!==r.property&&(n[r.property]=r.decode(e,t)),t+=r.getSpan(e,t),this.decodePrefixes&&e.length===t)break;return n}encode(e,t,n){void 0===n&&(n=0);const r=n;let i=0,o=0;for(const r of this.fields){let s=r.span;if(o=0<s?s:0,void 0!==r.property){const i=e[r.property];void 0!==i&&(o=r.encode(i,t,n),0>s&&(s=r.getSpan(t,n)))}i=n,n+=s}return i+o-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)}}}let gE=class extends lE{constructor(e,t){if(!(e instanceof hE&&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 hE||(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){void 0===t&&(t=0);let n=this.span;return 0>n&&(n=this.length.decode(e,t)),e.slice(t,t+n)}encode(e,t,n){let r=this.length;if(this.length instanceof hE&&(r=e.length),!xT.Buffer.isBuffer(e)||r!==e.length)throw new TypeError((i="Blob.encode",((o=this).property?i+"["+o.property+"]":i)+" requires (length "+r+") Buffer as src"));var i,o;if(n+r>t.length)throw new RangeError("encoding overruns Buffer");return t.write(e.toString("hex"),n,r,"hex"),this.length instanceof hE&&this.length.encode(r,t,n),r}};var pE=e=>new dE(1,e),mE=e=>new dE(4,e),yE=(e,t,n)=>new fE(e,t,n),wE=(e,t)=>new gE(e,t);const bE=(e="publicKey")=>wE(32,e),kE=(e="uint64")=>wE(8,e),vE=new ev("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"),SE=new ev("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL");new ev("So11111111111111111111111111111111111111112"),yE([mE("mintAuthorityOption"),bE("mintAuthority"),kE("supply"),pE("decimals"),pE("isInitialized"),mE("freezeAuthorityOption"),bE("freezeAuthority")]);const AE=yE([bE("mint"),bE("owner"),kE("amount"),mE("delegateOption"),bE("delegate"),pE("state"),mE("isNativeOption"),kE("isNative"),kE("delegatedAmount"),mE("closeAuthorityOption"),bE("closeAuthority")]);yE([pE("m"),pE("n"),pE("is_initialized"),bE("signer1"),bE("signer2"),bE("signer3"),bE("signer4"),bE("signer5"),bE("signer6"),bE("signer7"),bE("signer8"),bE("signer9"),bE("signer10"),bE("signer11")]);var TE=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),o=Math.log(256)/Math.log(n);function s(e){if("string"!=typeof e)throw new TypeError("Expected String");if(0===e.length)return new Uint8Array;let o=0,s=0,a=0;for(;e[o]===r;)s++,o++;const c=(e.length-o)*i+1>>>0,u=new Uint8Array(c);for(;o<e.length;){const r=e.charCodeAt(o);if(r>255)return;let i=t[r];if(255===i)return;let s=0;for(let e=c-1;(0!==i||s<a)&&-1!==e;e--,s++)i+=n*u[e]>>>0,u[e]=i%256>>>0,i=i/256>>>0;if(0!==i)throw new Error("Non-zero carry");a=s,o++}let l=c-a;for(;l!==c&&0===u[l];)l++;const h=new Uint8Array(s+(c-l));let d=s;for(;l!==c;)h[d++]=u[l++];return h}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,s=0,a=0;const c=t.length;for(;a!==c&&0===t[a];)a++,i++;const u=(c-a)*o+1>>>0,l=new Uint8Array(u);for(;a!==c;){let e=t[a],r=0;for(let t=u-1;(0!==e||r<s)&&-1!==t;t--,r++)e+=256*l[t]>>>0,l[t]=e%n>>>0,e=e/n>>>0;if(0!==e)throw new Error("Non-zero carry");s=r,a++}let h=u-s;for(;h!==u&&0===l[h];)h++;let d=r.repeat(i);for(;h<u;++h)d+=e.charAt(l[h]);return d},decodeUnsafe:s,decode:function(e){const t=s(e);if(t)return t;throw new Error("Non-base"+n+" character")}}}("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");function EE(e,t,n,r,i){const[o]=ev.findProgramAddressSync([t.toBuffer(),r.toBuffer(),e.toBuffer()],i);return o}class IE extends ET{constructor(t){super(),this.network="Solana",this.solanaBridgeAccountCache=new Map,this.galaConnectClient=t.galaConnectClient,this.galaChainWalletAddress=t.galaChainWalletAddress,WA(t.ethereumPrivateKey);const n=new e.JsonRpcProvider("https://ethereum.publicnode.com");this.ethereumWallet=new e.Wallet(t.ethereumPrivateKey,n);const r=t.solanaRpcUrl??"https://api.mainnet-beta.solana.com";let i;this.solanaConnection=new OA(r,"confirmed");try{i=TE.decode(t.solanaPrivateKeyBase58)}catch{throw W("solanaPrivateKeyBase58","base58-encoded string",t.solanaPrivateKeyBase58.slice(0,20)+"...")}if(64!==i.length)throw W("solanaPrivateKeyBase58","64 bytes when decoded",`${i.length} bytes`);this.solanaKeypair=UA.fromSecretKey(i);const o=t.solanaBridgeProgram??"AaE4dTnL75XqgUJpdxBKg6vS9sTJgBPJwBQRVhD29WwS";this.solanaBridgeProgramId=new ev(o),[this.solanaBridgeTokenAuthority]=ev.findProgramAddressSync([Buffer.from("bridge_token_authority")],this.solanaBridgeProgramId),[this.solanaBridgeConfigPda]=ev.findProgramAddressSync([Buffer.from("configv1")],this.solanaBridgeProgramId),[this.solanaNativeBridgePda]=ev.findProgramAddressSync([Buffer.from("native_sol_bridge")],this.solanaBridgeProgramId);const s=t.tokenConfigs??ou;this.tokenConfigs=GA(s),this.tokenMetadataResolver=new HA({galaConnectClient:this.galaConnectClient})}async estimateFee(e,t){const n=await this.tokenMetadataResolver.getTokenMetadata(e);return Oh(await this.galaConnectClient.fetchBridgeFee({chainId:"Solana",bridgeToken:n.descriptor}))}async bridgeOut(e){return pT(e,{galaConnectClient:this.galaConnectClient,tokenMetadataResolver:this.tokenMetadataResolver,ethereumWallet:this.ethereumWallet,destinationChainId:Xc.SOLANA,destinationChain:"Solana",validateRecipientAddress:rT})}async bridgeIn(e){const{amount:t,sourcePrivateKey:n,recipientAddress:r,tokenSymbol:i}=e,o=tT(i);Lh(t,o);let s=this.solanaKeypair;if(n){let e;try{e=TE.decode(n)}catch{throw W("sourcePrivateKey","base58-encoded string",n.slice(0,20)+"...")}if(64!==e.length)throw W("sourcePrivateKey","64 bytes when decoded",`${e.length} bytes`);s=UA.fromSecretKey(e)}const a=zA(this.tokenConfigs,o,"Solana bridge"),c=await this.tokenMetadataResolver.getTokenMetadata(o),u=Eh(t,c.decimals),l=r??this.galaChainWalletAddress;return hT({fromChain:"Solana",transactionHash:await this.executeSolanaBridgeOut({keypair:s,tokenConfig:a,metadata:c,amountBaseUnits:u,recipient:l,amount:t}),tokenSymbol:o,amount:t,baseUrl:this.galaConnectClient.getBaseUrl()})}async getStatus(e){return JA(await this.galaConnectClient.getBridgeStatus(e))}getSupportedTokens(){return Array.from(this.tokenConfigs.keys())}isTokenSupported(e){return this.tokenConfigs.has(is(e))}isValidAddress(e){try{return new ev(e),!0}catch{return!1}}getWalletAddress(){return this.solanaKeypair.publicKey.toBase58()}async getSolanaTokenBalance(e,t){const n=zA(this.tokenConfigs,e,"Solana");if(n.isNative)return this.getSolanaNativeBalance(t);const r=t??this.solanaKeypair.publicKey.toBase58(),i=iT(r),o=EE(new ev(n.mintAddress),i,0,vE,SE);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,o,0,vE),t=n.decimals??8;return Ih(e.amount,t)}catch(t){if(S(t)&&t.message.includes("could not find")){return Ih(0n,n.decimals??8)}throw j(`Failed to fetch ${e} balance for ${r}: ${A(t)}`,`${e}Account`)}}async getSolanaNativeBalance(e){const t=iT(e??this.solanaKeypair.publicKey.toBase58()),n=await this.solanaConnection.getBalance(t,"confirmed");return Ih(BigInt(n),9)}async requestDevnetAirdrop(e=1,t){oe(e,1e-5,2,"amount");const n=t?iT(t):this.solanaKeypair.publicKey,r=this.solanaConnection.rpcEndpoint;if(!r.includes("devnet"))throw j(`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(!Qe(e))throw W("signature","a non-empty string");if(!/^[1-9A-HJ-NP-Za-km-z]{80,90}$/.test(e))throw W("signature","a base58-encoded string (87-88 characters)",e.slice(0,20)+"...");const t=(await this.solanaConnection.getSignatureStatuses([e])).value[0];return t?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 ev(e.tokenConfig.mintAddress),n=Boolean(e.tokenConfig.isNative),r=n?void 0:await this.getSolanaBridgeAccounts(t),i=n?void 0:EE(t,e.keypair.publicKey,0,vE,SE),o=Buffer.from(e.recipient,"utf8"),s=Buffer.alloc(8);s.writeBigUInt64LE(e.amountBaseUnits);const a=Buffer.alloc(4);a.writeUInt32LE(o.length);const c=n?this.buildNativeBridgeInstruction(e.keypair.publicKey,s,a,o):this.buildTokenBridgeInstruction(e.keypair.publicKey,i,t,r,s,a,o),u=new vv;u.add(FA.setComputeUnitPrice({microLamports:375e3}),FA.setComputeUnitLimit({units:2e5}),c),u.feePayer=e.keypair.publicKey;const l=await this.sendAndConfirmWithFallback(u,e.keypair),h={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:h,fromChain:"Solana",toChain:"GC",hash:l}),l}async sendAndConfirmWithFallback(e,t,n=3){let r=null;for(let i=1;i<=n;i++){try{const o=await this.solanaConnection.getLatestBlockhash("confirmed");e.recentBlockhash=o.blockhash,e.feePayer=t.publicKey,e.signatures=[],e.sign(t);const s=await this.solanaConnection.sendRawTransaction(e.serialize(),{skipPreflight:!1,preflightCommitment:"confirmed"});try{return await this.solanaConnection.confirmTransaction({signature:s,blockhash:o.blockhash,lastValidBlockHeight:o.lastValidBlockHeight},"confirmed"),s}catch(e){const t=S(e)?e.message.toLowerCase():"";if(!(t.includes("block height exceeded")||t.includes("blockhash not found")||t.includes("expired")))throw e;const o=await this.solanaConnection.getSignatureStatuses([s]);if("confirmed"===o.value[0]?.confirmationStatus||"finalized"===o.value[0]?.confirmationStatus)return s;r=new Error(`Transaction ${s} not confirmed - block height exceeded (attempt ${i}/${n})`)}}catch(e){r=S(e)?e:new Error(A(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 o=Math.min(1e3*Math.pow(2,i-1),5e3);await Ph(o)}throw r??new Error("Transaction confirmation failed after max retries")}buildNativeBridgeInstruction(e,t,n,r){const i=Buffer.concat([uu.BRIDGE_OUT_NATIVE,t,n,r]);return new kv({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:Dv.programId,isSigner:!1,isWritable:!1}],data:i})}buildTokenBridgeInstruction(e,t,n,r,i,o,s){const a=Buffer.concat([uu.BRIDGE_OUT,i,o,s]);return new kv({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:Dv.programId,isSigner:!1,isWritable:!1},{pubkey:vE,isSigner:!1,isWritable:!1}],data:a})}async getSolanaBridgeAccounts(e){const t=e.toBase58(),n=this.solanaBridgeAccountCache.get(t);if(n)return n;const[r]=ev.findProgramAddressSync([Buffer.from("mint_lookup_v1"),e.toBuffer()],this.solanaBridgeProgramId),i=await this.solanaConnection.getAccountInfo(r,"confirmed");if(!i)throw j(`Mint lookup account not found for ${r.toBase58()}`,"solanaBridgeProgram");if(!i.owner.equals(this.solanaBridgeProgramId))throw j("Mint lookup account owner mismatch for Solana bridge program","solanaBridgeProgram");if(i.data.length<40)throw j("Mint lookup account data is unexpectedly short","solanaBridgeProgram");const o={mintLookup:r,tokenBridge:new ev(i.data.slice(8,40)),bridgeTokenAccount:EE(e,this.solanaBridgeTokenAuthority,0,vE,SE)};return this.solanaBridgeAccountCache.set(t,o),o}}const xE={PROD:{launchpadBaseUrl:"https://lpad-backend-prod1.defi.gala.com",galaChainBaseUrl:"https://gateway-mainnet.galachain.com",bundleBaseUrl:"https://bundle-backend-prod1.defi.gala.com",webSocketUrl:"https://bundle-backend-prod1.defi.gala.com",dexApiBaseUrl:"https://dex-api-platform-dex-prod-gala.gala.com",dexBackendBaseUrl:"https://dex-backend-prod1.defi.gala.com",launchpadFrontendUrl:"https://lpad-frontend-prod1.defi.gala.com"},STAGE:{launchpadBaseUrl:"https://lpad-backend-dev1.defi.gala.com",galaChainBaseUrl:"https://galachain-gateway-chain-platform-stage-chain-platform-eks.stage.galachain.com",bundleBaseUrl:"https://bundle-backend-dev1.defi.gala.com",webSocketUrl:"https://bundle-backend-dev1.defi.gala.com",dexApiBaseUrl:"https://dex-api-platform-dex-stage-gala.gala.com",dexBackendBaseUrl:"https://dex-backend-dev1.defi.gala.com",launchpadFrontendUrl:"https://lpad-frontend-test1.defi.gala.com"}};function CE(e){return xE[e]}const NE={PROD:{ethereum:"https://ethereum.publicnode.com",solana:"https://api.mainnet-beta.solana.com"},STAGE:{ethereum:"https://ethereum-sepolia.publicnode.com",solana:"https://api.devnet.solana.com"}},BE={solanaBridgeProgram:"AaE4dTnL75XqgUJpdxBKg6vS9sTJgBPJwBQRVhD29WwS",rateLimit:12,pollInterval:15e3,pollTimeout:27e5};class _E{static normalizeGalaChainAddress(e){const t=new lt;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 j(`Invalid GalaChain address format: ${e}`,"galaChainWalletAddress");const i=t.extractHex(r);return`eth|${_E.checksumAddress(i)}`}static checksumAddress(t){const n=t.toLowerCase(),r=ct(e.keccak256(e.toUtf8Bytes(n)));let i="";for(let e=0;e<n.length;e++){const t=n[e];parseInt(r[e],16)>=8?i+=t.toUpperCase():i+=t}return i}constructor(e){const t=_E.normalizeGalaChainAddress(e.galaChainWalletAddress),n=e.environment??"STAGE",r=xE[n],i=NE[n],o={galaConnectBaseUrl:e.galaConnectBaseUrl??r.dexApiBaseUrl,galaChainApiBaseUrl:e.galaChainApiBaseUrl??r.galaChainBaseUrl,ethereumRpcUrl:e.ethereumRpcUrl??i.ethereum,solanaRpcUrl:e.solanaRpcUrl??i.solana,ethereumBridgeContract:e.ethereumBridgeContract??ru(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?{...o,solanaPrivateKey:e.solanaPrivateKey}:o,this.galaConnectClient=new AT({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=nu(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 IT(t)),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:ou};this.strategies.set("Solana",new IE(e))}}async resolveTokenSymbol(e,t){return wr(async()=>{if(!this.bridgeableTokenService)throw j("BridgeableTokenService is required for tokenId resolution. Pass bridgeableTokenService in BridgeServiceConfig or use the SDK's bridge methods.","bridgeableTokenService");const n=Rh(e).stringified,r="Ethereum"===t?"ETHEREUM":"SOLANA",i=await this.bridgeableTokenService.getTokenByTokenId(n,r);if(!i){throw j([`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 wr(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 wr(async()=>{const t=await this.resolveTokenSymbol(e.tokenId,e.destinationChain),n=this.getStrategy(e.destinationChain);if(!n.isValidAddress(e.recipientAddress))throw j(`Invalid recipient address for ${e.destinationChain}: ${e.recipientAddress}`,"recipientAddress");if(!n.isTokenSupported(t))throw j(`Token ${t} is not supported for ${e.destinationChain} bridging`,"tokenSymbol");return n.bridgeOut({...e,tokenSymbol:t})},"BridgeService.bridgeOut")}async bridgeIn(e){return wr(async()=>{const t=await this.resolveTokenSymbol(e.tokenId,e.sourceChain),n=this.getStrategy(e.sourceChain);if(!n.isTokenSupported(t))throw j(`Token ${t} is not supported for ${e.sourceChain} bridging`,"tokenSymbol");return n.bridgeIn({...e,tokenSymbol:t})},"BridgeService.bridgeIn")}async getBridgeStatus(e,t){return wr(async()=>{if(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=S(e)?e:new Error(A(e))}const i=this.strategies.get("Solana");if(i)try{return await i.getStatus(e)}catch(e){r=S(e)?e:new Error(A(e))}const o=r?` (last error: ${r.message})`:"";throw V(`Unable to get status for transaction ${e}${o}`,e)},"BridgeService.getBridgeStatus")}async waitForBridgeCompletion(e,t){return wr(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 V(`Unable to wait for transaction ${e}: no suitable strategy found`,e)},"BridgeService.waitForBridgeCompletion")}getSupportedBridgeTokens(e){const t=[],n=nu(this.config.environment);if(!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(!e||"Solana"===e)for(const e of ou){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(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 wr(async()=>dT(this.strategies).getEthereumTokenBalance(e,t),"BridgeService.getEthereumTokenBalance")}async getEthereumNativeBalance(e){return wr(async()=>dT(this.strategies).getEthereumNativeBalance(e),"BridgeService.getEthereumNativeBalance")}async getSolanaTokenBalance(e,t){return wr(async()=>fT(this.strategies).getSolanaTokenBalance(e,t),"BridgeService.getSolanaTokenBalance")}async getSolanaNativeBalance(e){return wr(async()=>fT(this.strategies).getSolanaNativeBalance(e),"BridgeService.getSolanaNativeBalance")}async fetchEthereumWalletTokenBalance(e,t){return wr(async()=>{const n=dT(this.strategies),r=cT(nu(this.config.environment),e,"Ethereum"),i=gT(t,n);return sT(r,await n.getEthereumTokenBalance(e,i))},"BridgeService.fetchEthereumWalletTokenBalance")}async fetchEthereumWalletNativeBalance(e){return wr(async()=>{const t=dT(this.strategies),n=gT(e,t);return oT("ETH",await t.getEthereumNativeBalance(n),18)},"BridgeService.fetchEthereumWalletNativeBalance")}async fetchSolanaWalletTokenBalance(e,t){return wr(async()=>{const n=fT(this.strategies),r=cT(ou,e,"Solana"),i=gT(t,n);return aT(r,await n.getSolanaTokenBalance(e,i))},"BridgeService.fetchSolanaWalletTokenBalance")}async fetchSolanaWalletNativeBalance(e){return wr(async()=>{const t=fT(this.strategies),n=gT(e,t);return oT("SOL",await t.getSolanaNativeBalance(n),9)},"BridgeService.fetchSolanaWalletNativeBalance")}async requestSolanaDevnetAirdrop(e,t){return wr(async()=>fT(this.strategies).requestDevnetAirdrop(e,t),"BridgeService.requestSolanaDevnetAirdrop")}async getSolanaTransactionStatus(e){return wr(async()=>fT(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 wr(async()=>dT(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 wr(async()=>{const t=dT(this.strategies),n=gT(e,t),r=nu(this.config.environment),[i,...o]=await Promise.all([t.getEthereumNativeBalance(n),...r.map(async e=>sT(e,await t.getEthereumTokenBalance(e.symbol,n)))]);return{address:n,native:oT("ETH",i,18),tokens:o,timestamp:Date.now()}},"BridgeService.fetchEthereumWalletAllBalances")}async fetchSolanaWalletAllBalances(e){return wr(async()=>{const t=fT(this.strategies),n=gT(e,t),[r,...i]=await Promise.all([t.getSolanaNativeBalance(n),...ou.map(async e=>aT(e,await t.getSolanaTokenBalance(e.symbol,n)))]);return{address:n,native:oT("SOL",r,9),tokens:i,timestamp:Date.now()}},"BridgeService.fetchSolanaWalletAllBalances")}getStrategy(e){const t=this.strategies.get(e);if(!t)throw j(`Bridging to ${e} is not configured. `+("Solana"===e?"Please provide solanaPrivateKey in config.":"Please check your configuration."),`${e.toLowerCase()}PrivateKey`);return t}}class PE extends Error{constructor(e,t){super(e),this.cause=t,this.name="WebSocketError"}}class RE extends Error{constructor(e,t,n){super(`Transaction ${e} failed with status: ${t}${n?` - ${n}`:""}`),this.transactionId=e,this.status=t,this.name="TransactionFailedError"}}function DE(e,t){if(Ye(e))throw new PE(`Invalid WebSocket response received for transaction ${t}: response is null or undefined`);if("object"!=typeof e)throw new PE(`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 PE(`Invalid WebSocket response received for transaction ${t}: missing status field`)}function LE(e,t,n,r){DE(e,t);const i=e,o=i.data||{};if(!function(e){if(Ye(e)||"object"!=typeof e)return!1;const t=e;return!(void 0!==t.inputQuantity&&"string"!=typeof t.inputQuantity||void 0!==t.outputQuantity&&"string"!=typeof t.outputQuantity||void 0!==t.totalFees&&"string"!=typeof t.totalFees||void 0!==t.vaultAddress&&"string"!=typeof t.vaultAddress)}(o))throw new PE(`Invalid trade data received for transaction ${t}`);const s={transactionId:t,type:n,method:"native"===r.type?"native":"exact",inputAmount:o.inputQuantity||r.amount,outputAmount:o.outputQuantity||r.expectedAmount||"0",totalFees:o.totalFees||"0",tokenName:r.tokenName,vaultAddress:o.vaultAddress||"",timestamp:Date.now()};return void 0!==i.blockHash&&(s.blockHash=i.blockHash),void 0!==i.gasUsed&&(s.gasUsed=i.gasUsed),void 0!==r.slippageToleranceFactor&&(s.slippageTolerance=r.slippageToleranceFactor),s}const OE="5.0.4-beta.1";class UE{constructor(e){this.logger=e||new ze({debug:!1,context:"LiquidityEventExtractor"})}walkPayloadForLiquidityEvents(e,t){const n=[],r=new WeakSet,i=(e,o=0)=>{if(o>50)this.logger.debug("Payload nesting exceeded maximum depth of 50");else if(e&&!Qe(e)&&"object"==typeof e){if(r.has(e))return;r.add(e);const s=this.extractLiquidityFromObject(e);s&&!t.has(s.transactionId)&&(n.push(s),t.add(s.transactionId));for(const t of Object.values(e))i(t,o+1)}};return i(e,0),n}extractLiquidityFromObject(e){const t=this.extractTransactionId(e);if(!t)return null;const n=e.Data,r=n&&"object"==typeof n&&!Array.isArray(n)?n:e,i=this.extractPositionId(r),o=this.extractPoolHash(r),s=this.extractAmounts(r),a=this.extractUserAddress(r),c=this.extractPoolFee(r);if(!(i&&o&&s&&a&&null!==c))return null;const u=this.extractPoolAlias(r),l=this.extractUserBalanceDelta(r),h=this.extractTimestamp(r),d=l?.token0Balance?.collection,f=l?.token1Balance?.collection,g={transactionId:t,positionId:i,poolHash:o,poolFee:c,amounts:s,userAddress:a};return void 0!==d&&(g.token0=d),void 0!==f&&(g.token1=f),void 0!==h&&(g.timestamp=h),void 0!==u&&(g.poolAlias=u),void 0!==l&&(g.userBalanceDelta=l),g}extractTransactionId(e){const t=["transactionId","txId","tx_id","hash","txHash","id"];for(const n of t){const t=e[n];if(Qe(t))return t}return null}extractPositionId(e){const t=["positionId","position_id","tokenId","nftId"];for(const n of t){const t=e[n];if(Qe(t))return t}return null}extractPoolHash(e){const t=["poolHash","pool_hash","poolId","pool"];for(const n of t){const t=e[n];if(Qe(t))return t}return null}extractPoolAlias(e){const t=["poolAlias","pool_alias"];for(const n of t){const t=e[n];if(Qe(t))return t}}extractAmounts(e){const t=e.amounts;if(Array.isArray(t)&&t.length>=2){const e=String(t[0]).trim(),n=String(t[1]).trim();if(e&&n)return[e,n]}const n=e.amount0||e.amount0Desired,r=e.amount1||e.amount1Desired;return void 0!==n&&void 0!==r?[String(n),String(r)]:null}extractUserAddress(e){const t=["userAddress","user","owner","from","sender","wallet","address"];for(const n of t){const t=e[n];if(Qe(t))return t}return null}extractPoolFee(e){const t=["poolFee","fee","feeTier","feeTierBps"];for(const n of t){const t=e[n];if("number"==typeof t)return this.normalizeFee(t);if(Qe(t)){const e=Re(t,NaN);if(isFinite(e))return this.normalizeFee(e)}}return null}normalizeFee(e){return 1===e||1e4===e?1e4:.3===e||3e3===e?3e3:.05===e||500===e?500:Number.isInteger(e)?e:e<1?Math.round(1e4*e):e}extractTimestamp(e){const t=["timeStamp","timestamp","time","createdAt","date"];for(const n of t){const t=e[n];if("number"==typeof t)return t;if(Qe(t)){const e=new Date(t).getTime();if(isFinite(e))return e}}}extractUserBalanceDelta(e){const t=e.userBalanceDelta;if(!t||"object"!=typeof t)return;const n=t,r=this.extractBalanceObject(n.token0Balance),i=this.extractBalanceObject(n.token1Balance);if(!r&&!i)return;const o={};return void 0!==r&&(o.token0Balance=r),void 0!==i&&(o.token1Balance=i),o}extractBalanceObject(e){if(!e||"object"!=typeof e)return;const t=e,n=t.collection,r=t.category,i=t.type,o=t.additionalKey,s=t.quantity,a=t.owner;return Qe(n)&&Qe(r)&&Qe(i)&&Qe(o)&&Qe(s)&&Qe(a)?{collection:n,category:r,type:i,additionalKey:o,quantity:s,owner:a}:void 0}}class ME{constructor(e){this.wallet=e.wallet;let t=null,n="STAGE";if(e.env?(n=e.env,t=CE(e.env)):e.baseUrl?.includes("prod")?(n="PROD",t=CE("PROD")):(n="STAGE",t=CE("STAGE")),this.environment=n,this.config={baseUrl:t.launchpadBaseUrl,galaChainBaseUrl:t.galaChainBaseUrl,bundleBaseUrl:t.bundleBaseUrl,webSocketUrl:t.webSocketUrl,dexApiBaseUrl:t.dexApiBaseUrl,dexBackendBaseUrl:t.dexBackendBaseUrl,launchpadFrontendUrl:t.launchpadFrontendUrl,timeout:3e4,debug:!1,...e},this.logger=new ze({debug:this.config.debug??!1,context:"LaunchpadSDK"}),this.validateConfiguration(),this.slippageToleranceFactor=void 0===e.slippageToleranceFactor?ME.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR:this.parseSlippageToleranceFactor(e.slippageToleranceFactor),this.maxAcceptableReverseBondingCurveFeeSlippageFactor=void 0===e.maxAcceptableReverseBondingCurveFeeSlippageFactor?ME.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR:this.parseFeeSlippageFactor(e.maxAcceptableReverseBondingCurveFeeSlippageFactor),this.calculateAmountMode=e.calculateAmountMode||ME.DEFAULT_CALCULATE_AMOUNT_MODE,this.pricingConcurrency=e.pricingConcurrency||5,this.galaChainAddressOverride=e.galaChainAddress,this.auth=new vt({wallet:e.wallet,messagePrefix:"Create a GalaChain Wallet"}),this.jwtAuth=new At,e.accessToken){const t=e.accessTokenExpiresIn??86400;this.jwtAuth.setToken(e.accessToken,t)}this.http=new Sr(this.auth,this.config),this.sessionAuth=new kr(this.http,this.auth,this.jwtAuth,e.debug||!1),this.galaChainHttp=new Sr(this.auth,{...this.config,baseUrl:this.config.galaChainBaseUrl}),this.bundleHttp=new Sr(this.auth,{...this.config,baseUrl:this.config.bundleBaseUrl}),this.dexApiHttp=new Sr(this.auth,{...this.config,baseUrl:this.config.dexApiBaseUrl}),this.dexBackendHttp=new Sr(this.auth,{...this.config,baseUrl:this.config.dexBackendBaseUrl}),this.galaChainPublicAxios=k(this.config.galaChainBaseUrl,this.config.timeout||3e4),this.cache=new yc(e.debug||!1),this.launchpadService=new Us(this.http,this.jwtAuth),this.tokenResolverService=new ic(this.launchpadService.poolService),this.launchpadAPI=new Ah(this.http,this.tokenResolverService,this.logger,this.bundleHttp,this.galaChainHttp,this.dexApiHttp,this.calculateAmountMode),this.galaChainService=new Fa(this.galaChainHttp,e.wallet,this.tokenResolverService,e.debug||!1,this.galaChainPublicAxios),this.dexService=new $a(this.dexBackendHttp,this.cache,this.galaChainService,e.debug||!1),this.bundleService=new Qa(this.bundleHttp,this.tokenResolverService,this.config.debug||!1,e.wallet,e.wallet?this.getAddress():void 0,this.slippageToleranceFactor,this.maxAcceptableReverseBondingCurveFeeSlippageFactor),this.websocketService=new rc({url:this.config.webSocketUrl},this.config.debug),this.priceHistoryService=new oc(this.dexBackendHttp,this.config.debug||!1,this.tokenResolverService),this.dexQuoteService=new bc(this.galaChainHttp,this.config.galaChainBaseUrl,e.debug||!1,e.dexQuoteNetworkTimeout||3e4),this.gswapService=new gc({privateKey:e.wallet?.privateKey,getWalletAddress:()=>this.wallet?this.getAddress():void 0,gatewayBaseUrl:this.config.galaChainBaseUrl,bundlerBaseUrl:this.config.bundleBaseUrl,galaChainBaseUrl:this.config.galaChainBaseUrl,dexBackendBaseUrl:this.config.dexBackendBaseUrl,dexBackendHttp:this.dexBackendHttp},this.websocketService,this.dexQuoteService),this.dexPoolService=new wc(this.dexBackendHttp,this.config.dexBackendBaseUrl,this.gswapService,this.pricingConcurrency,e.debug||!1)}createOverrideSdk(t){if(!Qe(t))throw j("Invalid privateKey: must be a non-empty string","privateKey");if(!t.match(/^0x[a-fA-F0-9]{64}$/))throw j('Invalid privateKey format: must be "0x" followed by 64 hexadecimal characters',"privateKey");const n=new e.Wallet(t),r={...this.config,wallet:n};return new ME(r)}getAddress(){return this.galaChainAddressOverride?this.galaChainAddressOverride:(this.validateWallet(),this.auth.getAddress())}getEthereumAddress(){return this.validateWallet(),this.wallet.address}validateWallet(){if(!this.wallet)throw z("wallet","Wallet");return this.wallet}setWallet(e){if(!e||"object"!=typeof e||!("address"in e))throw new _("Invalid wallet: must be an ethers Wallet instance, received "+typeof e,"wallet","INVALID_WALLET");this.wallet=e,this.auth.setWallet(e)}getWallet(){return this.wallet}hasWallet(){return void 0!==this.wallet}getConfig(){const{wallet:e,...t}=this.config;return{...t,environment:this.environment,slippageToleranceFactor:this.slippageToleranceFactor,maxAcceptableReverseBondingCurveFeeSlippageFactor:this.maxAcceptableReverseBondingCurveFeeSlippageFactor,calculateAmountMode:this.calculateAmountMode,gasFee:pc.GAS_FEE}}getVersion(){return OE}getUrlByTokenName(e){const t=this.config.launchpadFrontendUrl;if(!t)throw j("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 fetchDexPools(e={}){return this.dexPoolService.fetchDexPools(e)}async fetchAllDexPools(e={}){return this.dexPoolService.fetchAllDexPools(e)}async fetchCompositePoolData(e){return this.dexQuoteService.fetchCompositePoolData(e)}async calculateDexPoolQuoteExactAmountLocal(e){return this.dexQuoteService.calculateDexPoolQuoteExactAmountLocal(e)}async calculateDexPoolQuoteExactAmountExternal(e){return this.dexQuoteService.calculateDexPoolQuoteExactAmountExternal(e)}async calculateDexPoolQuoteExactAmount(e,t="local"){return this.dexQuoteService.calculateDexPoolQuoteExactAmount(e,t)}async fetchTokenDistribution(e){return this.launchpadService.fetchTokenDistribution(e)}async fetchUserHolderContext(e,t){return this.launchpadService.fetchUserHolderContext(e,t)}async fetchTokenBadges(e){return this.launchpadService.fetchTokenBadges(e)}async fetchTokenPrice(e){const{tokenName:t,tokenId:n}=e,{hasA:r}=nt(e,"tokenName","tokenId",{description:"token identifier"});if(r&&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(I(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=rs((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: ${A(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(!t)throw new Error(Tr(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 kt}),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??process.env.SOLANA_PRIVATE_KEY;this._bridgeService=new _E({galaConnectBaseUrl:this.config.dexApiBaseUrl,galaChainWalletAddress:this.getAddress(),ethereumPrivateKey:e?.ethereumPrivateKey??t.privateKey,...n&&{solanaPrivateKey:n},bridgeableTokenService:this.getBridgeableTokenService(),environment:this.environment,...this.config.ethereumRpcUrl&&{ethereumRpcUrl:this.config.ethereumRpcUrl},...this.config.solanaRpcUrl&&{solanaRpcUrl:this.config.solanaRpcUrl}})}return this._bridgeService}getBridgeableTokenService(){return this._bridgeableTokenService||(this._bridgeableTokenService=new Dc(this.dexApiHttp,this.config.debug??!1)),this._bridgeableTokenService}getWrappableTokenService(){return this._wrappableTokenService||(this._wrappableTokenService=new Uc(this.dexApiHttp,this.config.debug??!1)),this._wrappableTokenService}getGalaConnectClient(){if(!this._galaConnectClient){const e=this.getAddress();if(!e)throw new Error("GalaConnectClient requires a wallet. Configure SDK with a wallet first.");if(!this.config.dexApiBaseUrl)throw new Error("DEX API base URL is required for GalaConnectClient. Check SDK configuration.");this._galaConnectClient=new AT({baseUrl:this.config.dexApiBaseUrl,...this.config.galaChainBaseUrl&&{galachainBaseUrl:this.config.galaChainBaseUrl},walletAddress:e})}return this._galaConnectClient}getWrapService(){if(!this._wrapService){const e=this.getWallet();this._wrapService=new bu({galaConnectClient:this.getGalaConnectClient(),wrappableTokenService:this.getWrappableTokenService(),...e&&{walletAddress:this.getAddress(),wallet:e}})}return this._wrapService}getStreamingService(){return this._streamingService||(this._streamingService=new Uu(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1)),this._streamingService}getStreamChatService(){return this._streamChatService||(this._streamChatService=new Gu(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1)),this._streamChatService}getBanService(){return this._banService||(this._banService=new tl(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1)),this._banService}getTokenBanService(){return this._tokenBanService||(this._tokenBanService=new al(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1)),this._tokenBanService}getApiKeyService(){return this._apiKeyService||(this._apiKeyService=new pl(this.http,this.jwtAuth,this.config.debug??!1)),this._apiKeyService}getModeratorService(){return this._moderatorService||(this._moderatorService=new Nl(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1)),this._moderatorService}getFlagService(){return this._flagService||(this._flagService=new Wl(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1)),this._flagService}getOverseerService(){return this._overseerService||(this._overseerService=new rh(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1)),this._overseerService}getCommentService(){return this._commentService||(this._commentService=new ih(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1)),this._commentService}getContentReactionService(){return this._contentReactionService||(this._contentReactionService=new sh(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1)),this._contentReactionService}getCommentsService(){return this._commentsService||(this._commentsService=new ah(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1)),this._commentsService}getChatMessagesService(){return this._chatMessagesService||(this._chatMessagesService=new dh(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1)),this._chatMessagesService}getStreamWebSocketService(){if(!this._streamWebSocketService){if(!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: "wss://stream.gala.com"\n });\n\nFor MCP Server, set STREAM_WEBSOCKET_URL environment variable.\nSee SDK documentation for streaming configuration details.');this._streamWebSocketService=new Wu({url:this.config.streamWebSocketUrl},this.config.debug??!1)}return this._streamWebSocketService}getStreamingEventService(){return this._streamingEventService||(this._streamingEventService=new Hu(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)}async getWrapStatus(e){return this.getWrapService().getWrapStatus(e)}async login(){return this.sessionAuth.login()}async refreshToken(){return this.sessionAuth.refresh()}logout(){this.sessionAuth.logout()}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 getStreamInfo(e){return this.getStreamingService().getStreamInfo(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 getStreamRecordings(e){return this.getStreamingService().getRecordings(e)}async getRecordingDownload(e,t){return this.getStreamingService().getRecordingDownload(e,t)}async deleteRecording(e,t){return this.getStreamingService().deleteRecording(e,t)}async getSimulcastTargets(e){return this.getStreamingService().getSimulcastTargets(e)}async addSimulcastTarget(e){return this.getStreamingService().addSimulcastTarget(e)}async removeSimulcastTarget(e,t){return this.getStreamingService().removeSimulcastTarget(e,t)}async getGlobalStreamingStatus(){return this.getStreamingService().getGlobalStreamingStatus()}async setNextLiveStreamCountdown(e,t){return this.getStreamingService().setNextLiveStreamCountdown(e,t)}async setGlobalStreamingEnabled(e){const t=this.getStreamingService();return e?t.enableGlobalStreaming():t.disableGlobalStreaming()}async getStreamRole(e){return this.getStreamingService().getStreamRole(e)}async getAvailableRoles(){return this.getStreamingService().getAvailableRoles()}async getTokenAccess(e){return this.getStreamingService().getTokenAccess(e)}async getChatStatus(e){return this.getStreamChatService().getChatStatus(e)}async getEngagementStats(e){if(null===Es(e.tokenName))throw z("tokenName","tokenName is required and cannot be empty");return this.getStreamChatService().getEngagementStats(e)}async disableChat(e){return this.getStreamChatService().disableChat(e)}async enableChat(e){return this.getStreamChatService().enableChat(e)}async getGlobalChatStatus(){return this.getStreamChatService().getGlobalChatStatus()}async setGlobalChatEnabled(e){const t=this.getStreamChatService();return e?t.enableGlobalChat():t.disableGlobalChat()}async getPinnedChatMessage(e){return this.getStreamChatService().getPinnedMessage(e)}async pinChatMessage(e,t){return this.getStreamChatService().pinMessage({tokenName:e,messageId:t})}async unpinChatMessage(e){return this.getStreamChatService().unpinMessage(e)}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 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 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 revokeOverseer(e){return this.getOverseerService().revokeOverseer(e)}async getMyOverseerStatus(){return this.getOverseerService().getMyStatus()}async getOverseerSummary(){return this.getOverseerService().getSummary()}async listOverseerUsers(e){return this.getOverseerService().listOverseerUsers(e)}async getOverseerUserSummary(e){return this.getOverseerService().getOverseerUserSummary(e)}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 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){return this.getCommentsService().getComments(e)}async createComment(e){return this.getCommentsService().createComment(e)}async updateComment(e,t){return this.getCommentsService().updateComment(e,t)}async deleteComment(e){return this.getCommentsService().deleteComment(e)}async getChatMessages(e){return this.getChatMessagesService().getChatMessages(e)}async sendChatMessage(e){return this.getChatMessagesService().sendMessage(e)}async updateChatMessage(e,t){return this.getChatMessagesService().updateMessage(e,t)}async deleteChatMessage(e){return this.getChatMessagesService().deleteMessage(e)}async getTrades(e){return this.launchpadService.getTrades(e)}async connectStreamWebSocket(e){const t=this.getStreamWebSocketService();await t.connect(),e&&t.setGlobalCallbacks(e)}async authenticateStreamWebSocket(){const e=this.getWallet();if(!e)throw new Error("WebSocket authentication requires a wallet. Configure SDK with a wallet first.");const t=this.getStreamWebSocketService(),n=this.getAddress(),r=Date.now(),i=`Authenticate stream access for ${n} at ${r}`,o=await e.signMessage(i),s=JSON.stringify({address:n,timestamp:r,message:i,signature:o});t.authenticate(s)}async subscribeToStream(e){return this.getStreamWebSocketService().subscribeToStream(e)}async unsubscribeFromStream(e){return this.getStreamWebSocketService().unsubscribeFromStream(e)}async sendStreamChatViaWebSocket(e,t){return this.getStreamWebSocketService().sendChatMessage(e,t)}async sendStreamReaction(e,t,n=0){return 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)}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)}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)}async getSupportedBridgeTokens(){const e=this.getBridgeService(),t=e.getSupportedBridgeTokens();return{tokens:t,totalCount:t.length,supportedChains:e.getSupportedBridgeChains()}}async fetchTokenBalance(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return kt}),n=t(e.address);if(e.tokenId){const{normalizeToTokenInstanceKey:t}=await Promise.resolve().then(function(){return oa}),r=t(e.tokenId),{collection:i,category:o,type:s,additionalKey:a}=r;return this.galaChainService.fetchTokenBalance({owner:n,collection:i,category:o,additionalKey:a,type:s,instance:"0"},e.withExpired??!1)}if(e.tokenName){const t=os(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(e.tokenName){const t=(await this.fetchTokensHeld({tokenName:e.tokenName,page:1,limit:1,...n&&{address:n}})).tokens[0];if(!t)return null;const r=t.collection||"Token",i={collection:r,category:"Unit",type:t.symbol,additionalKey:"none"};return{quantity:t.quantity,collection:r,category:"Unit",tokenId:Ks(i),symbol:t.symbol,name:t.name}}throw z("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:o,currentSupply:s}=e;let a=t;void 0===o&&void 0===s||(a={tokenName:t,...void 0!==o&&{calculateAmountMode:o},...void 0!==s&&{currentSupply:s}});const c=await this.calculateBuyAmountForGraduation(a),u={tokenName:t,amount:c.remainingTokens,type:"exact",expectedAmount:c.amount,maxAcceptableReverseBondingCurveFee:c.reverseBondingCurveFee,slippageToleranceFactor:this.slippageToleranceFactor};return void 0!==n&&(u.slippageToleranceFactor=n),void 0!==r&&(u.maxAcceptableReverseBondingCurveFeeSlippageFactor=r),void 0!==i&&(u.privateKey=i),await this.buy(u)}async calculateInitialBuyAmount(e){const t={nativeTokenQuantity:e};return this.launchpadAPI.calculateInitialBuyAmount(t)}async buy(e){if(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(!n)throw V("No transaction ID returned from buy operation");return this.waitForConfirmation(n,t=>LE(t,n,"buy",e))}async sell(e){if(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(!n)throw V("No transaction ID returned from sell operation");return this.waitForConfirmation(n,t=>LE(t,n,"sell",e))}async getBundlerTransactionResult(e){return this.bundleService.getBundlerTransactionResult(e)}async launchToken(e){if(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=>{DE(n,t);const r=n?.data||{};if(!function(e){if(Ye(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 PE(`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(),...n.blockHash&&{blockHash:n.blockHash},...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(e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...r}=e;return t.uploadTokenImage(r)}return this.validateWallet(),this.launchpadService.uploadImageByTokenName(e)}async updateTokenSocials(e){return this.launchpadService.updateTokenSocials(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 fetchProfile(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return kt}),n=t(e)||this.getAddress();return this.launchpadService.fetchProfile(n)}async fetchReferralUrl(){this.validateWallet();const e=this.getAddress();return await this.dexApiHttp.get(Ut,void 0,{"x-wallet-address":e})}async fetchReferrals(e){let t;if(e?.address)if(e.address.startsWith("client|"))t=e.address;else{const{normalizeAddressInput:n}=await Promise.resolve().then(function(){return kt}),r=n(e.address);if(!r)throw new _(`Invalid address format: "${e.address}". Expected formats: eth|0x..., 0x..., or client|...`);t=r}else t=this.getAddress();const n=e?.page??1,r=e?.limit??10,i={pageNumber:n,limit:r,sortBy:e?.sortBy??"joined",sortDir:e?.sortDir??"desc"},o=await this.dexApiHttp.get(Mt,i,{"x-wallet-address":t});if(!Array.isArray(o))throw new P("Unexpected API response: expected array, got "+typeof o);return{referrals:o,page:n,limit:r,hasMore:o.length===r}}async fetchAllReferrals(e){const t=await Zo((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){let t;if(e?.address)if(e.address.startsWith("client|"))t=e.address;else{const{normalizeAddressInput:n}=await Promise.resolve().then(function(){return kt}),r=n(e.address);if(!r)throw new _(`Invalid address format: "${e.address}". Expected formats: eth|0x..., 0x..., or client|...`);t=r}else t=this.getAddress();const n=await this.dexApiHttp.get(Ft,void 0,{"x-wallet-address":t});if(!n||"number"!=typeof n.referralCount||!n.rewardTotals)throw new P(`Unexpected API response: expected { referralCount, rewardTotals }, got ${JSON.stringify(n)}`);return n}async registerAccount(e){let t;if(e?.address)if(e.address.startsWith("client|"))t=e.address;else{const{normalizeAddressInput:n}=await Promise.resolve().then(function(){return kt}),r=n(e.address);if(!r)throw new _(`Invalid address format: "${e.address}". Expected formats: eth|0x..., 0x..., or client|...`);t=r}else t=this.getAddress();const n=await this.dexApiHttp.post($t,{address:t});if(!n||"boolean"!=typeof n.exists)throw new P(`Unexpected API response: expected { exists, walletAlias? }, got ${JSON.stringify(n)}`);if(n.exists){if(!n.walletAlias)throw new P(`Unexpected API response: exists=true but walletAlias is missing, got ${JSON.stringify(n)}`);return{exists:!0,walletAlias:n.walletAlias}}return{exists:!1,walletAlias:n.walletAlias||t}}async updateProfile(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return kt}),n={...e,address:t(e.address)};if(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 kt}),n={...e,address:t(e.address)||this.getAddress()};if(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 kt}),n=t(e?.address)||this.getAddress(),r={page:e?.page||1,limit:e?.limit||10,address:n};return e?.tokenName&&(r.tokenName=e.tokenName),e?.search&&(r.search=e.search),this.launchpadService.fetchTokensHeld(r)}async fetchTokensCreated(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return kt}),n={type:"DEFI",address:t(e?.address)||this.getAddress(),page:e?.page||1,limit:e?.limit||10};return e?.tokenName&&(n.tokenName=e.tokenName),e?.search&&(n.search=e.search),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 kt}),n={...e,recipientAddress:t(e.recipientAddress)};if(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 kt}),n={...e,to:t(e.to)};if(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 lockTokens(e){const t=await Promise.all(e.tokens.map(async e=>{if(e.lockAuthority){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return kt});return{...e,lockAuthority:t(e.lockAuthority)}}return e})),n={...e,tokens:t};if(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(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(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),e||(this._bridgeableTokenService&&this._bridgeableTokenService.clearCache(),this._wrappableTokenService&&this._wrappableTokenService.clearCache())}validateConfiguration(){try{oe(this.config.timeout,1,3e5,"timeout")}catch{this.logger.warn(`Invalid timeout value: ${this.config.timeout}. Using default 30000ms.`),this.config.timeout=3e4}if(!this.config.baseUrl)throw j("baseUrl is required in configuration","baseUrl");if(!this.config.webSocketUrl)throw j("webSocketUrl is required in configuration","webSocketUrl");try{new URL(this.config.baseUrl)}catch{throw j(`Invalid baseUrl format: ${this.config.baseUrl}`,"baseUrl")}try{new URL(this.config.webSocketUrl)}catch{throw j(`Invalid webSocketUrl format: ${this.config.webSocketUrl}`,"webSocketUrl")}if(this.config.galaChainBaseUrl)try{new URL(this.config.galaChainBaseUrl)}catch{throw j(`Invalid galaChainBaseUrl format: ${this.config.galaChainBaseUrl}`,"galaChainBaseUrl")}if(this.config.bundleBaseUrl)try{new URL(this.config.bundleBaseUrl)}catch{throw j(`Invalid bundleBaseUrl format: ${this.config.bundleBaseUrl}`,"bundleBaseUrl")}if(this.config.launchpadFrontendUrl)try{new URL(this.config.launchpadFrontendUrl)}catch{throw j(`Invalid launchpadFrontendUrl format: ${this.config.launchpadFrontendUrl}`,"launchpadFrontendUrl")}}parseSlippageToleranceFactor(e){const t=Re("string"==typeof e||"number"==typeof e?e:String(e),ME.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR);return t<0||t>1?(this.logger.warn(`Invalid slippage tolerance factor: ${e}, using default: ${ME.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR}`),ME.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR):t}parseFeeSlippageFactor(e){const t=Re("string"==typeof e||"number"==typeof e?e:String(e),ME.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR);return t<0||t>1?(this.logger.warn(`Invalid fee slippage factor: ${e}, using default: ${ME.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR}`),ME.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("completed"!==n.status)throw new RE(e,n.status,n.message);let r;try{r=t(n)}catch(t){if(t instanceof PE)throw t;throw new PE(`Failed to transform WebSocket response for transaction ${e}`,S(t)?t:new Error(A(t)))}return this.logger.debug(`Transaction confirmed: ${e}`,r),r}catch(t){if(this.logger.error(`Transaction confirmation failed: ${e}`,t),t instanceof RE||t instanceof PE)throw t;throw new PE(`WebSocket confirmation failed for transaction ${e}`,S(t)?t:new Error(A(t)))}}async warmCacheFromPools(e){if(!e||!Array.isArray(e))return;const{extractMetadataFromPoolData:t,isValidPoolForCaching:n}=await Promise.resolve().then(function(){return WE});e.forEach(e=>{if(!n(e))return;const r=t(e,this.logger);r&&this.launchpadAPI.warmCacheFromPoolData(e.tokenName,r)})}async getSwapQuoteExactInput(e,t,n){return this.gswapService.getSwapQuoteExactInput({fromToken:e,toToken:t,amount:n})}async getSwapQuoteExactOutput(e,t,n){return this.gswapService.getSwapQuoteExactOutput({fromToken:e,toToken:t,amount:n})}async executeSwap(e,t,n,r,i,o=.01){return this.validateWallet(),this.gswapService.executeSwap({fromToken:e,toToken:t,inputAmount:n,estimatedOutput:r,feeTier:i,slippageTolerance:o})}async getSwapUserAssets(e){return this.gswapService.getUserAssets(e)}async getAllSwapUserAssets(e){return this.gswapService.getAllUserAssets(e)}async fetchAvailableDexTokens(e={}){return this.gswapService.fetchAvailableDexTokens(e)}async fetchAllAvailableDexTokens(e={}){return this.gswapService.fetchAllAvailableDexTokens(e)}async getSwapPoolInfo(e,t){return this.gswapService.getPoolInfo(e,t)}async getSwapPoolPrice(e,t,n){return this.gswapService.getPositionCurrentPrice({token0:e,token1:t,feeTier:n})}async getSwapUserLiquidityPositions(e,t,n,r){let i,o;"string"==typeof n?(i=n,o=r):"object"==typeof n?o=n:r&&(o=r);return await this.gswapService.getUserLiquidityPositions(e,t,i,o)}async getAllSwapUserLiquidityPositions(e,t){const n=await this.gswapService.getAllSwapUserLiquidityPositions(e,t);if(!t?.withPrices){if(Array.isArray(n))return n;if(n&&"items"in n)return n.items}return n}async getSwapLiquidityPosition(e,t){return this.gswapService.getLiquidityPosition(e,t)}async getSwapLiquidityPositionById(e,t,n,r,i,o,s){return this.gswapService.getLiquidityPositionById(e,t,n,r,i,o,s)}async fetchSwapPositionDirect(e){return this.gswapService.fetchSwapPositionDirect(e)}async getSwapEstimateRemoveLiquidity(e){return this.gswapService.estimateRemoveLiquidity(e)}async addSwapLiquidityByPrice(e){return this.gswapService.addLiquidityByPrice(e)}async addSwapLiquidityByTicks(e){this.validateWallet();const t={token0:e.token0,token1:e.token1,fee:e.feeTier,tickLower:e.tickLower,tickUpper:e.tickUpper,amount0Desired:e.amount0Desired,amount1Desired:e.amount1Desired};return void 0!==e.amount0Min&&(t.amount0Min=e.amount0Min),void 0!==e.amount1Min&&(t.amount1Min=e.amount1Min),this.gswapService.addSwapLiquidityByTicks(t)}async removeSwapLiquidity(e){return this.validateWallet(),this.gswapService.removeLiquidity(e)}async collectSwapPositionFees(e){return this.validateWallet(),this.gswapService.collectPositionFees(e)}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`),()=>{})}onDexPoolCreation(e,t){const n=1e3,r=Math.max(t?.intervalMs??3e4,n);t?.intervalMs&&t.intervalMs<n&&this.logger.warn(`Poll interval ${t.intervalMs}ms is below minimum 1000ms. Using minimum interval instead.`);const i=t?.minTVL,o=t?.tokens,s=new Map;let a=!0,c=null;let u=0;const l=async()=>{if(a){try{const t=await this.fetchDexPools({limit:20});u>0&&(this.logger.debug("Successfully recovered from polling errors"),u=0),t.items.forEach(t=>{const n=(e=>`${e.token0}-${e.token1}-${e.fee}`)(t);if(!s.has(n)){if((e=>{if(s.set(e,!0),s.size>1e3){const e=s.keys().next().value;void 0!==e&&s.delete(e)}})(n),i){if((t.token0Tvl+t.token1Tvl)/2<i)return}if(o&&o.length>0){if(!(o.includes(t.token0)||o.includes(t.token1)))return}e(t)}})}catch(e){u++;const t=A(e);u>=5?this.logger.error(`Polling for new DEX pools failed ${u} consecutive times. Last error: ${t}. Continuing to retry...`):u>1?this.logger.warn(`Error polling for new DEX pools (attempt ${u}/5): ${t}`):this.logger.debug(`Error polling for new DEX pools: ${t}`)}if(a){const e=Math.min(Math.max(u-1,0),2),t=r*Math.pow(2,e);c=setTimeout(l,t)}}};return l(),()=>{a=!1,c&&clearTimeout(c),this.logger.debug("Stopped watching for DEX pool creation")}}onLaunchpadTokenCreation(e,t){const n=1e3,r=Math.max(t?.intervalMs??3e4,n);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,o=new Map;let s=!0,a=null;let c=0;const u=async()=>{if(s){try{const t=await this.fetchPools({type:"recent",limit:20});c>0&&(this.logger.debug("Successfully recovered from polling errors"),c=0),t.items.forEach(t=>{o.has(t.tokenName)||((e=>{if(o.set(e,!0),o.size>1e3){const e=o.keys().next().value;void 0!==e&&o.delete(e)}})(t.tokenName),i&&t.creatorAddress!==i||e(t))})}catch(e){c++;const t=A(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(s){const e=Math.min(Math.max(c-1,0),2),t=r*Math.pow(2,e);a=setTimeout(u,t)}}};return u(),()=>{s=!1,a&&clearTimeout(a),this.logger.debug("Stopped watching for launchpad token creation")}}normalizeFee(e){if(null==e)return null;const t=Fe("string"==typeof e||"number"==typeof e?e:String(e),Number.NaN);return Number.isNaN(t)?null:1===t||1e4===t?1e4:.3===t||3e3===t?3e3:.05===t||500===t?500:!Number.isInteger(t)||500!==t&&3e3!==t&&1e4!==t?null:t}extractField(e,...t){if("object"!=typeof e||null===e)return"";const n=e;for(const e of t)if(n[e])return String(n[e]);return""}looksLikePoolPair(e){if("string"!=typeof e)return null;const t=e.trim();return vc.isValidPoolKey(t)?t:null}buildPoolPairFromObject(e){if("object"!=typeof e||null===e)return null;const t=e,n=this.extractField(t,"token0ClassKey","token0Class","token0","token0Symbol")||"",r=this.extractField(t,"token1ClassKey","token1Class","token1","token1Symbol")||"",i=this.normalizeFee(t.feeTier??t.fee??t.feeTierBps??t.liquidityFeeBps??t.feeBps);return n&&r&&null!==i?`${n}/${r}/${i}`:null}parsePoolPairString(e){const t=vc.parsePoolKey(e);if(!t)return null;const n=Vs(t.token0)?js(t.token0).collection:t.token0,r=Vs(t.token1)?js(t.token1).collection:t.token1,i=t.feeTier.toString();return n&&r&&i?{token0:n,token1:r,fee:i,poolPair:e}:null}serializeBalanceToken(e){if(!e||"object"!=typeof e)return"";const t=e;return[(t.collection??t.token??"")||"",(t.category??"")||"none",(t.type??"")||"none",(t.additionalKey??"none")||"none"].join("|")}buildPoolPairFromBalances(e){if("object"!=typeof e||null===e)return null;const t=e,n=t.userBalanceDelta??t.balanceDelta??t.delta;if(!n||"object"!=typeof n||null===n)return null;const r=n,i=r.token0Balance??r.token0??r.baseBalance??r.primaryBalance,o=r.token1Balance??r.token1??r.quoteBalance??r.secondaryBalance,s=this.serializeBalanceToken(i),a=this.serializeBalanceToken(o),c=this.normalizeFee(t.poolFee??t.feeTier??t.fee??t.feeTierBps??t.liquidityFeeBps);return s&&a&&null!==c?`${s}/${a}/${c}`:null}extractPoolDataFromPayload(e){if("string"==typeof e){const t=this.looksLikePoolPair(e);return t?this.parsePoolPairString(t):null}if("object"!=typeof e||null===e)return null;const t=e,n=this.looksLikePoolPair(t.poolPair);if(n)return this.parsePoolPairString(n);const r=this.buildPoolPairFromBalances(t);if(r)return this.parsePoolPairString(r);const i=this.buildPoolPairFromObject(t);if(i)return this.parsePoolPairString(i);if(t.pool&&"object"==typeof t.pool&&null!==t.pool){const e=this.extractPoolDataFromPayload(t.pool);if(e)return e}return null}matchesPoolFilter(e,t){if(t?.tokenFilter){if(!(e.token0===t.tokenFilter||e.token1===t.tokenFilter))return!1}if(t?.pairTokens){const[n,r]=t.pairTokens,i=e.token0===n||e.token1===n,o=e.token0===r||e.token1===r;if(!i||!o||n===r)return!1}if(void 0!==t?.feeTierFilter){if(this.normalizeFee(t.feeTierFilter)!==this.normalizeFee(e.fee))return!1}return!0}matchesCreatorFilter(e,t){return!t||e.creatorAddress===t}subscribeToTokenCreations(e,t){if(this.logger.debug("Subscribing to token creation broadcasts"+(t?.creatorFilter?` (filter: ${t.creatorFilter})`:"")),!this.websocketService)throw j("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(n&&n.Data&&"object"==typeof n.Data){const r=n.Data;if("CreateSale"===r.functionName){const n={tokenName:r.tokenName||"",symbol:r.symbol||"",creatorAddress:r.creatorAddress||"",description:r.description||"",image:r.image||"",vaultAddress:r.vaultAddress||"",tokenStringKey:r.tokenStringKey||"",preBuyQuantity:r.initialBuyQuantity||"0",websiteUrl:r.websiteUrl||"",telegramUrl:r.telegramUrl||"",twitterUrl:r.twitterUrl||"",instagramUrl:r.instagramUrl||"",facebookUrl:r.facebookUrl||"",redditUrl:r.redditUrl||"",tiktokUrl:r.tiktokUrl||"",isFinalized:r.isFinalized||!1};this.matchesCreatorFilter(n,t?.creatorFilter)&&e(n)}}}}catch(e){this.logger.warn(`Error processing token creation broadcast: ${A(e)}`)}};let o=this.websocketService.getSocket();if(o)o.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: ${A(e)}`);this.logger.warn("Failed to establish WebSocket connection:",e),t?.onError&&t.onError(n)});let e=0;const s=()=>{if(o=this.websocketService.getSocket(),!o&&e<ME.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS)return e++,void(r=setTimeout(()=>s(),ME.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS));if(!o&&e>=ME.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS){const e=new Error(`WebSocket not available after ${ME.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS*ME.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS}ms`);return this.logger.warn("Token creation broadcast subscription timeout:",e.message),void(t?.onError&&t.onError(e))}o&&(o.onAny(i),n=!0,this.logger.debug("Token creation broadcast listener registered"))};s()}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)}}}walkPayloadForPools(e,t,n=new WeakSet){const r=[];if("string"==typeof e){const n=this.looksLikePoolPair(e);if(n){const e=this.parsePoolPairString(n);e&&!t.has(e.poolPair)&&(t.add(e.poolPair),r.push(e))}return r}if("object"!=typeof e||null===e)return r;if(n.has(e))return r;n.add(e);const i=this.extractPoolDataFromPayload(e);i&&!t.has(i.poolPair)&&(t.add(i.poolPair),r.push(i));for(const i of Object.values(e)){const e=this.walkPayloadForPools(i,t,n);r.push(...e)}return r}subscribeToDexPoolAdded(e,t){if(this.logger.debug("Subscribing to DEX pool creation broadcasts"+(t?.tokenFilter?` (filter: ${t.tokenFilter})`:t?.pairTokens?` (pair: ${t.pairTokens.join("/")})`:"")),!this.websocketService)throw j("WebSocket service not initialized. Ensure websocketUrl is configured and the service is connected.","websocketService");let n=!1,r=null;const i=new Set,o=(n,...r)=>{try{for(const n of r){const r=this.walkPayloadForPools(n,i);for(const n of r)this.matchesPoolFilter(n,t)&&e(n)}}catch(e){this.logger.warn(`Error processing DEX pool broadcast: ${A(e)}`)}};let s=this.websocketService.getSocket();if(s)s.onAny(o),n=!0,this.logger.debug("DEX pool 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: ${A(e)}`);this.logger.warn("Failed to establish WebSocket connection:",e),t?.onError&&t.onError(n)});let e=0;const i=()=>{if(s=this.websocketService.getSocket(),!s&&e<ME.DEX_POOL_SOCKET_WAIT_ATTEMPTS)return e++,void(r=setTimeout(()=>i(),ME.DEX_POOL_SOCKET_POLL_INTERVAL_MS));if(!s&&e>=ME.DEX_POOL_SOCKET_WAIT_ATTEMPTS){const e=new Error(`WebSocket not available after ${ME.DEX_POOL_SOCKET_WAIT_ATTEMPTS*ME.DEX_POOL_SOCKET_POLL_INTERVAL_MS}ms`);return this.logger.warn("DEX pool subscription timeout:",e.message),void(t?.onError&&t.onError(e))}s&&(s.onAny(o),n=!0,this.logger.debug("DEX pool broadcast listener registered"))};i()}return()=>{try{if(null!==r&&(clearTimeout(r),r=null,this.logger.debug("Cleared DEX pool polling timeout")),!n)return void this.logger.debug("Cleanup called before listener registration - no action needed");const e=this.websocketService.getSocket();e&&(e.offAny(o),n=!1,this.logger.debug("Stopped listening to DEX pool broadcasts"))}catch(e){this.logger.warn("Error removing DEX pool listener:",e)}}}subscribeToDexSwapExecuted(e,t){if(this.logger.debug("Subscribing to DEX swap execution broadcasts"+(t?.tokenFilter?` (filter: ${t.tokenFilter})`:t?.pairTokens?` (pair: ${t.pairTokens.join("/")})`:"")),!this.websocketService)throw j("WebSocket service not initialized. Ensure websocketUrl is configured and the service is connected.","websocketService");let n=null,r=null,i=null,o=!1;const s=async e=>{const t=vc.parsePoolKey(e);if(!t)throw new Error(`Invalid pool key format: ${e}`);return await this.dexQuoteService.fetchCompositePoolData({token0:t.token0,token1:t.token1,fee:t.feeTier})},a=()=>{const c=this.websocketService.getSocket();if(!c)return this.logger.debug("WebSocket not yet ready for swap monitoring, polling..."),void(n=setTimeout(()=>a(),100));o=!0,r=new Cc(c,s,this.dexQuoteService,t||{},this.logger),i=r.subscribe(t||{},e),this.logger.debug("DEX swap monitoring subscription established")};return this.websocketService.getSocket()||(this.logger.debug("WebSocket not yet connected, initiating connection for swap monitoring..."),this.websocketService.connect().catch(e=>{const n=new Error(`WebSocket connection failed for swap monitoring: ${A(e)}`);this.logger.warn("Failed to establish WebSocket connection:",e),t?.onError&&t.onError(n)})),a(),()=>{try{n&&clearTimeout(n),i&&o&&i(),r&&r.shutdown().catch(e=>{this.logger.warn("Error shutting down swap monitor:",e)})}catch(e){this.logger.warn("Error cleaning up swap monitor:",e)}}}subscribeToDexLiquidityAdded(e,t){return this.subscribeToDexLiquidityEvents(e,t)}subscribeToDexLiquidityRemoved(e,t){return this.subscribeToDexLiquidityEvents(e,t)}subscribeToDexLiquidityChanged(e,t){return this.subscribeToDexLiquidityEvents(e,t)}subscribeToDexLiquidityEvents(e,t){if(this.logger.debug("Subscribing to DEX liquidity broadcasts"+(t?.tokenFilter?` (filter: ${t.tokenFilter})`:t?.pairTokens?` (pair: ${t.pairTokens.join("/")})`:"")),!this.websocketService)throw j("WebSocket service not initialized. Ensure websocketUrl is configured and the service is connected.","websocketService");let n=!1,r=null;const i=new Set,o=new UE(this.logger),s=(n,...r)=>{try{for(const n of r){const r=o.walkPayloadForLiquidityEvents(n,i);for(const n of r)if(this.matchesLiquidityFilter(n,t))try{const t=e(n);t instanceof Promise&&t.catch(e=>{this.logger.warn(`Error in liquidity event callback: ${A(e)}`)})}catch(e){this.logger.warn(`Error in liquidity event callback: ${A(e)}`)}}}catch(e){this.logger.warn(`Error processing DEX liquidity broadcast: ${A(e)}`)}};let a=this.websocketService.getSocket();if(a)a.onAny(s),n=!0,this.logger.debug("DEX liquidity broadcast listener registered");else{this.logger.debug("WebSocket not yet connected, initiating connection for liquidity monitoring..."),this.websocketService.connect().catch(e=>{const n=new Error(`WebSocket connection failed: ${A(e)}`);this.logger.warn("Failed to establish WebSocket connection:",e),t?.onError&&t.onError(n)});let e=0;const i=()=>{if(a=this.websocketService.getSocket(),!a&&e<ME.DEX_POOL_SOCKET_WAIT_ATTEMPTS)return e++,void(r=setTimeout(()=>i(),ME.DEX_POOL_SOCKET_POLL_INTERVAL_MS));if(!a&&e>=ME.DEX_POOL_SOCKET_WAIT_ATTEMPTS){const e=new Error(`WebSocket not available after ${ME.DEX_POOL_SOCKET_WAIT_ATTEMPTS*ME.DEX_POOL_SOCKET_POLL_INTERVAL_MS}ms`);return this.logger.warn("DEX liquidity subscription timeout:",e.message),void(t?.onError&&t.onError(e))}a&&(a.onAny(s),n=!0,this.logger.debug("DEX liquidity broadcast listener registered"))};i()}return async()=>{try{if(null!==r&&(clearTimeout(r),r=null,this.logger.debug("Cleared DEX liquidity polling timeout")),!n)return void this.logger.debug("Cleanup called before listener registration - no action needed");const e=this.websocketService.getSocket();e&&(e.offAny(s),n=!1,this.logger.debug("Stopped listening to DEX liquidity broadcasts"))}catch(e){this.logger.warn("Error removing DEX liquidity listener:",e)}}}matchesLiquidityFilter(e,t){if(!t)return!0;if(t.positionId&&e.positionId!==t.positionId)return!1;if(t.poolHash&&e.poolHash!==t.poolHash)return!1;if(void 0!==t.feeTierFilter){const n=this.normalizeFeeTier(t.feeTierFilter);if(e.poolFee!==n)return!1}if(t.userFilter&&e.userAddress!==t.userFilter)return!1;if(t.tokenFilter){const n=!!e.token0&&xs(e.token0,t.tokenFilter),r=!!e.token1&&xs(e.token1,t.tokenFilter);if(!n&&!r)return!1}if(t.pairTokens){const[n,r]=t.pairTokens,i=e.token0||"",o=e.token1||"",s=xs(i,n)&&xs(o,r),a=xs(i,r)&&xs(o,n);if(!s&&!a)return!1}if(t.minAmount){const n=Re(t.minAmount),r=Re(e.amounts[0]),i=Re(e.amounts[1]);if(Math.abs(r)<n&&Math.abs(i)<n)return!1}return!0}normalizeFeeTier(e){if("number"==typeof e)return e>=100?e:Math.round(1e4*e);return function(e,t=3e3){if(Ye(e))return t;if("number"==typeof e)return isNaN(e)?t:Math.floor(e);const n=String(e).trim();if(n.endsWith("%")){const e=Re(n.replace("%",""));return Math.floor(1e4*e)}const r=parseFloat(n);return isNaN(r)?t:r<100?Math.floor(1e4*r):Math.floor(r)}(e)}async cleanup(){try{this.logger.debug("Starting cleanup..."),this.http.cleanup(),this.websocketService&&this.websocketService.disconnect(),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 ze({debug:e,context:"LaunchpadSDK"});t.debug("Starting global cleanup...");const{WebSocketService:n}=require("./services/WebSocketService");n.cleanupAll(e),t.debug("Global cleanup completed")}}ME.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR=.15,ME.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR=.01,ME.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY=pc.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY,ME.DEFAULT_CALCULATE_AMOUNT_MODE=vh.LOCAL,ME.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS=30,ME.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS=100,ME.DEX_POOL_SOCKET_WAIT_ATTEMPTS=30,ME.DEX_POOL_SOCKET_POLL_INTERVAL_MS=100;class FE{static generateWallet(){try{const t=e.Wallet.createRandom();if(!t.mnemonic?.phrase)throw z("mnemonic","Mnemonic phrase");const n=this.toGalaAddress(t.address);return{privateKey:t.privateKey,address:t.address,galaAddress:n,mnemonic:t.mnemonic.phrase,wallet:new e.Wallet(t.privateKey)}}catch(t){if("undefined"!=typeof process&&"test"===process.env.NODE_ENV){const t=`test-wallet-${Date.now()}-${++this.testCounter}`,n="0x"+Buffer.from(t).toString("hex").padStart(64,"1").slice(0,64),r=new e.Wallet(n),i=this.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 t}}static fromPrivateKey(t){const n=new e.Wallet(t),r=this.toGalaAddress(n.address);return{privateKey:n.privateKey,address:n.address,galaAddress:r,mnemonic:"",wallet:n}}static fromMnemonic(t,n=0){try{const r=e.Mnemonic.fromPhrase(t),i=e.HDNodeWallet.fromMnemonic(r,`m/44'/60'/0'/0/${n}`),o=new e.Wallet(i.privateKey),s=this.toGalaAddress(o.address);return{privateKey:o.privateKey,address:o.address,galaAddress:s,mnemonic:t,wallet:o}}catch(r){if("undefined"!=typeof process&&"test"===process.env.NODE_ENV){const r=`test-mnemonic-index-${n}-${t}`,i="0x"+Buffer.from(r).toString("hex").padStart(64,"1").slice(0,64),o=new e.Wallet(i),s=this.toGalaAddress(o.address);return{privateKey:o.privateKey,address:o.address,galaAddress:s,mnemonic:t,wallet:o}}throw r}}static toGalaAddress(e){const t=dt(e);if(!/^[a-fA-F0-9]{40}$/.test(t))throw W("address","a valid Ethereum address (40 hex characters)");return`eth|${t}`}static toEthereumAddress(e){try{return gt(e)}catch(t){const n=A(t);if(n.includes("required")||!e?.startsWith("eth|"))throw z("galaAddress","Gala address starting with eth|");if(n.includes("Invalid backend"))throw W("galaAddress","Gala format (eth|{40-hex-chars})");throw t}}static isValidEthereumAddress(e){try{const t=dt(e);return/^[a-fA-F0-9]{40}$/.test(t)}catch{return!1}}static isValidGalaAddress(e){return!!e&&"backend"===bt(e)}static generateMultipleWallets(e=1){oe(e,1,100,"count");const t=[];if("undefined"!=typeof process&&"test"===process.env.NODE_ENV)for(let n=0;n<e;n++){const e=`test-multi-${n}-${Date.now()}-${++this.testCounter}`,r="0x"+Buffer.from(e).toString("hex").padStart(64,"1").slice(0,64);t.push(this.fromPrivateKey(r))}else for(let n=0;n<e;n++)t.push(this.generateWallet());return t}static getWalletSummary(e,t=!1){const n=["🔐 Wallet Information","═".repeat(50),`📍 Address: ${e.address}`,`🎮 Gala Address: ${e.galaAddress}`,`🌱 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 $E(e){if(void 0===e)return FE.generateWallet();const t=e.trim();if(!Qe(t))throw W("input","a non-empty string");if(function(e){const t=dt(e);return/^[a-fA-F0-9]{64}$/.test(t)}(t))return FE.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 FE.fromMnemonic(t);throw W("input","a private key (64 hex characters) or mnemonic (12/24 words)","Wallet input")}FE.testCounter=0;function qE(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 KE(e){if(!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}class GE{static fastValidation(e,t,n,r=GE.DEFAULT_CONFIG){const i=Date.now();let o=!0;try{const s=wo(e.sqrtPrice),a=wo(t.sqrtPrice);n.zeroForOne?a.gte(s)&&(this.logger.error("Fast validation failed: price did not decrease for zeroForOne swap",{originalSqrtPrice:s.toString(),updatedSqrtPrice:a.toString(),zeroForOne:n.zeroForOne}),o=!1):a.lte(s)&&(this.logger.error("Fast validation failed: price did not increase for oneForZero swap",{originalSqrtPrice:s.toString(),updatedSqrtPrice:a.toString(),zeroForOne:n.zeroForOne}),o=!1);const c=wo(e.liquidity),u=wo(t.liquidity);if(!Co(c)){const e=Oo(u.minus(c).abs(),c);e.gt(r.maxLiquidityChangePct)&&this.logger.warn("Fast validation warning: large liquidity change detected (could be legitimate)",{originalLiquidity:c.toString(),updatedLiquidity:u.toString(),changePct:bo(e.times(100),2)})}const l=wo(e.feeGrowthGlobal0),h=wo(t.feeGrowthGlobal0),d=wo(e.feeGrowthGlobal1),f=wo(t.feeGrowthGlobal1);n.zeroForOne?f.lt(d)&&(this.logger.error("Fast validation failed: feeGrowthGlobal1 decreased for zeroForOne",{originalFeeGrowth1:d.toString(),updatedFeeGrowth1:f.toString()}),o=!1):h.lt(l)&&(this.logger.error("Fast validation failed: feeGrowthGlobal0 decreased for oneForZero",{originalFeeGrowth0:l.toString(),updatedFeeGrowth0:h.toString()}),o=!1);const g=wo(e.protocolFeesToken0),p=wo(t.protocolFeesToken0),m=wo(e.protocolFeesToken1),y=wo(t.protocolFeesToken1);p.lt(g)&&(this.logger.error("Fast validation failed: protocolFeesToken0 decreased",{originalProtocolFees0:g.toString(),updatedProtocolFees0:p.toString()}),o=!1),y.lt(m)&&(this.logger.error("Fast validation failed: protocolFeesToken1 decreased",{originalProtocolFees1:m.toString(),updatedProtocolFees1:y.toString()}),o=!1);const w=Ve(i);return this.logger.debug("Fast validation completed",{passed:o,elapsedMs:w}),o}catch(e){return this.logger.error("Fast validation exception",e),!1}}static moderateValidation(e,t,n=GE.DEFAULT_CONFIG){const r=Date.now(),i=[];let o=0;try{if(t.actualSqrtPrice){const r=wo(e.sqrtPrice),s=wo(t.actualSqrtPrice),a=this.calculateDriftPercentage(r,s);o=a,a>100*n.maxDriftThreshold&&i.push(`Price drift detected: ${bo(a,4)}% (threshold: ${bo(100*n.maxDriftThreshold,4)}%)`),this.logger.debug("Price drift comparison",{calculatedSqrtPrice:r.toString(),actualSqrtPrice:s.toString(),driftPct:a.toFixed(4)})}const s=wo(e.sqrtPrice),a=Oo(s,Eo()),u=c.sqrtPriceToTick(a),l=e.tick??0,h=Math.abs(u-l);h>n.maxTickDrift&&i.push(`Tick/price mismatch: tick=${l}, calculated=${u}, drift=${h}`);const d=wo(e.feeGrowthGlobal0),f=wo(e.feeGrowthGlobal1),g=wo(e.liquidity);try{Do(d,f,g)}catch(e){i.push(e.message)}const p=0===i.length,m=!p||o>100*n.maxDriftThreshold,y=Ve(r);return this.logger.debug("Moderate validation completed",{isValid:p,shouldRefetch:m,driftPercentage:o,errorCount:i.length,elapsedMs:y}),this.buildValidationResult(p,o,m,i)}catch(e){return this.logger.error("Moderate validation exception",e),this.buildValidationResult(!1,0,!0,[`Exception during validation: ${A(e)}`])}}static async fullValidation(e,t,n){const r=Date.now(),i=[];let o=0;try{this.logger.debug("Starting full validation with fresh pool data fetch",{poolKey:e});const s=await n(),a=wo(t.pool.sqrtPrice),c=wo(s.pool.sqrtPrice),u=this.calculateDriftPercentage(a,c);o=Math.max(o,u),u>100*this.DEFAULT_CONFIG.maxPriceDriftPct&&i.push(`Price drift: ${u.toFixed(4)}% (cached: ${a.toString()}, fresh: ${c.toString()})`);const l=wo(t.pool.liquidity),h=wo(s.pool.liquidity),d=this.calculateDriftPercentage(l,h);o=Math.max(o,d),d>100*this.DEFAULT_CONFIG.maxLiquidityDriftPct&&i.push(`Liquidity drift: ${d.toFixed(4)}% (cached: ${l.toString()}, fresh: ${h.toString()})`);const f=Object.keys(t.tickDataMap).length,g=Object.keys(s.tickDataMap).length;if(g>0){const e=Math.abs(g-f)/g;e>this.DEFAULT_CONFIG.maxTickCountDriftPct&&i.push(`Tick data incomplete: cached has ${f} ticks, fresh has ${g} ticks (${(100*e).toFixed(2)}% difference)`)}const p=0===i.length,m=!p,y=Ve(r);return this.logger.debug("Full validation completed",{poolKey:e,isValid:p,shouldRefetch:m,maxDriftPercentage:o,priceDrift:u,liquidityDrift:d,cachedTickCount:f,freshTickCount:g,errorCount:i.length,elapsedMs:y}),this.buildValidationResult(p,o,m,i)}catch(t){return this.logger.error("Full validation exception",{poolKey:e,error:t}),this.buildValidationResult(!1,0,!0,[`Exception during full validation: ${A(t)}`])}}static calculateDriftPercentage(e,t){if(Co(t))return this.logger.warn("Cannot calculate drift: actual value is zero"),1/0;return Oo(t.minus(e).abs(),t).times(100).toNumber()}static buildValidationResult(e,t,n,r=[]){let i;if(n&&r.length>0){const e=r.join(" ").toLowerCase();i=e.includes("drift")?"drift":e.includes("tick")&&e.includes("mismatch")?"tick-mismatch":e.includes("tick")?"missing-tick-data":"manual"}const o={isValid:e,driftPercentage:t,shouldRefetch:n,validationErrors:r};return void 0!==i&&(o.refetchReason=i),o}}GE.logger=new ze({debug:!1,context:"PoolStateValidator"}),GE.DEFAULT_CONFIG={maxDriftThreshold:.001,maxLiquidityChangePct:.5,maxTickDrift:1,maxTickCountDriftPct:.1,maxPriceDriftPct:.001,maxLiquidityDriftPct:.01};class zE extends ds{static calculatePoolStateHash(e){const t=`${e.sqrtPrice.toString()}|${e.liquidity.toString()}|${e.tick||0}`;return f.createHash("sha256").update(t).digest("hex").substring(0,16)}constructor(e,t){super(t?.debug??!1);const n={maxIterations:t?.maxIterations??100,enableBigNumberCache:t?.enableBigNumberCache??!0,roundingMode:t?.roundingMode??i.ROUND_DOWN,debug:t?.debug??!1,maxSwapsSinceRefetch:t?.maxSwapsSinceRefetch??50,maxCumulativeDrift:t?.maxCumulativeDrift??5,strictValidation:t?.strictValidation??!1,enablePerformanceWarnings:t?.enablePerformanceWarnings??!0,performanceWarningThreshold:t?.performanceWarningThreshold??100};this.config={...n,...t?.onRefetchNeeded?{onRefetchNeeded:t.onRefetchNeeded}:{}},this.validationConfig=GE.DEFAULT_CONFIG,this.pool=e.pool,this.tickDataMap=e.tickDataMap,this.metadata={lastFullRefetch:Date.now(),swapsSinceRefetch:0,cumulativeDrift:0,processedTransactions:[],stateHash:zE.calculatePoolStateHash(this.pool)};if(!GE.fastValidation(this.pool,this.pool,{transactionId:"init",timestamp:Date.now(),amountSpecified:"0",zeroForOne:!1,exactInput:!0},this.validationConfig)&&this.config.strictValidation)throw new _("Initial pool state validation failed","poolState","VALIDATION_FAILED");this.logger.info("PoolStateManager initialized",{pool:{sqrtPrice:this.pool.sqrtPrice.toString(),liquidity:this.pool.liquidity.toString(),tick:this.pool.tick},config:this.config})}async applySwapDelta(e){if(!e)throw z("swapEvent","Swap event");if(!e.transactionId)throw z("transactionId","Transaction ID");const t=Date.now();if(this.metadata.processedTransactions.includes(e.transactionId))throw this.logger.warn("Duplicate swap transaction",{transactionId:e.transactionId}),new D(`Duplicate transaction ID: ${e.transactionId}`,e.transactionId,"DUPLICATE_TRANSACTION");try{const t={pool:this.pool,tickDataMap:this.tickDataMap},n={maxIterations:this.config.maxIterations,enableBigNumberCache:this.config.enableBigNumberCache,roundingMode:this.config.roundingMode,debugLogging:this.config.debug},r=Ec.calculateSwapDelta(t,e,n);this.lastSwapMetrics={calculationTimeMs:r.metadata.calculationTimeMs,swapSteps:r.metadata.swapSteps,timestamp:Date.now()},this.config.enablePerformanceWarnings&&r.metadata.calculationTimeMs>this.config.performanceWarningThreshold&&this.logger.warn("Slow swap calculation",{calculationTimeMs:r.metadata.calculationTimeMs,swapSteps:r.metadata.swapSteps,threshold:this.config.performanceWarningThreshold});if(!GE.fastValidation(t.pool,r.updatedPool,e,this.validationConfig)&&this.config.strictValidation)throw new _("Swap validation failed","swapResult","VALIDATION_FAILED");if(e.actualAmount0&&e.actualAmount1&&e.actualSqrtPrice){const t=wo(e.actualAmount0),n=wo(e.actualAmount1),i=r.amount0.minus(t).abs(),o=r.amount1.minus(n).abs(),s=Oo(i,t.abs(),wo(0)).times(100).toNumber(),a=Oo(o,n.abs(),wo(0)).times(100).toNumber(),c=Math.max(s,a);c>1&&(this.logger.warn("Drift detected in swap delta",{driftPercentage:c.toFixed(2),swapId:e.transactionId}),this.metadata.cumulativeDrift+=c)}if((this.metadata.swapsSinceRefetch>this.config.maxSwapsSinceRefetch||this.metadata.cumulativeDrift>this.config.maxCumulativeDrift)&&(this.logger.info("Triggering full refetch due to drift accumulation",{swapsSinceRefetch:this.metadata.swapsSinceRefetch,cumulativeDrift:this.metadata.cumulativeDrift.toFixed(2)}),this.config.onRefetchNeeded)){const e=await this.config.onRefetchNeeded(this.pool,this.tickDataMap);this.pool=e.pool,this.tickDataMap=e.tickDataMap,this.metadata.lastFullRefetch=Date.now(),this.metadata.swapsSinceRefetch=0,this.metadata.cumulativeDrift=0,this.metadata.stateHash=zE.calculatePoolStateHash(this.pool),this.logger.info("Full refetch completed",{sqrtPrice:this.pool.sqrtPrice.toString()})}return this.pool=r.updatedPool,Object.assign(this.tickDataMap,r.updatedTicks),this.metadata.swapsSinceRefetch++,this.metadata.stateHash=zE.calculatePoolStateHash(this.pool),this.metadata.processedTransactions.push(e.transactionId),this.metadata.processedTransactions.length>1e3&&(this.metadata.processedTransactions=this.metadata.processedTransactions.slice(-1e3)),this.logger.debug("Swap delta applied",{transactionId:e.transactionId,amount0:r.amount0.toString(),amount1:r.amount1.toString(),sqrtPriceNew:this.pool.sqrtPrice.toString()}),r}catch(n){const r=A(n);if(this.logger.error("Failed to apply swap delta",{transactionId:e.transactionId,error:r}),this.config.strictValidation)throw n;return{updatedPool:this.pool,updatedTicks:{},amount0:wo(0),amount1:wo(0),feeAmount0:wo(0),feeAmount1:wo(0),ticksCrossed:[],metadata:{calculationTimeMs:Ve(t),swapSteps:0,priceHitLimit:!1}}}}forceFullRefetch(e){this.pool=e.pool,this.tickDataMap=e.tickDataMap,this.metadata.lastFullRefetch=Date.now(),this.metadata.swapsSinceRefetch=0,this.metadata.cumulativeDrift=0,this.logger.info("Full refetch forced",{sqrtPrice:this.pool.sqrtPrice.toString()})}getPoolState(){return this.pool}getTickDataMap(){return{...this.tickDataMap}}getMetadata(){return{...this.metadata}}getLastSwapMetrics(){if(this.lastSwapMetrics)return{...this.lastSwapMetrics}}isRefetchRecommended(){return this.metadata.swapsSinceRefetch>this.config.maxSwapsSinceRefetch||this.metadata.cumulativeDrift>this.config.maxCumulativeDrift}reset(e){this.pool=e.pool,this.tickDataMap=e.tickDataMap,this.metadata={lastFullRefetch:Date.now(),swapsSinceRefetch:0,cumulativeDrift:0,processedTransactions:[],stateHash:zE.calculatePoolStateHash(this.pool)},this.logger.info("PoolStateManager reset",{sqrtPrice:this.pool.sqrtPrice.toString()})}}"undefined"!=typeof process&&process.env&&(process.env.CORE_CHAINCODE_LOGGING_LEVEL=process.env.CORE_CHAINCODE_LOGGING_LEVEL||"ERROR");var WE=Object.freeze({__proto__:null,extractMetadataFromPoolData:function(e,t){const n={};if(e.vaultAddress&&(n.vaultAddress=e.vaultAddress),void 0!==e.reverseBondingCurveMinFeePortion){const r=Re(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=Re(e.reverseBondingCurveMaxFeePortion,NaN);isNaN(r)?t&&t.debug(`Skipping invalid reverseBondingCurveMaxFeePortion for ${e.tokenName}: "${e.reverseBondingCurveMaxFeePortion}"`):n.reverseBondingCurveMaxFeeFactor=r}return void 0!==n.reverseBondingCurveMaxFeeFactor&&void 0!==n.reverseBondingCurveMinFeeFactor&&(n.reverseBondingCurveNetFeeFactor=n.reverseBondingCurveMaxFeeFactor-n.reverseBondingCurveMinFeeFactor),Object.keys(n).length>0?n:null},isValidPoolForCaching:function(e){if(null===e||"object"!=typeof e)return!1;const t=e;return"tokenName"in t&&"string"==typeof t.tokenName&&t.tokenName.length>0}});exports.ACCESS_SOURCE=_u,exports.ACTIVE_USER_TYPE=ju,exports.API_KEY_PERMISSION={MANAGE_COMMENTS:"MANAGE_COMMENTS",MANAGE_CHAT:"MANAGE_CHAT",BAN_USERS:"BAN_USERS",UNBAN_USERS:"UNBAN_USERS",MANAGE_SIMULCAST:"MANAGE_SIMULCAST",GET_STREAM_KEY:"GET_STREAM_KEY",STOP_STREAM:"STOP_STREAM",RESET_STREAM_KEY:"RESET_STREAM_KEY",START_STREAM:"START_STREAM",DELETE_RECORDINGS:"DELETE_RECORDINGS",MANAGE_STREAM_SETTINGS:"MANAGE_STREAM_SETTINGS"},exports.API_KEY_ROLE=cl,exports.API_KEY_ROLES=ul,exports.API_KEY_ROLE_HIERARCHY=gl,exports.AddressFormatter=lt,exports.AgentConfig=class{static async quickSetup(e={}){const t=e.environment||this.detectEnvironment(),n=this.setupWallet(e.privateKey),r=e.galaChainAddress||process.env.WALLET_ADDRESS,i={wallet:n.wallet,baseUrl:e.baseUrl||this.getDefaultBaseUrl(t),timeout:e.timeout||this.getDefaultTimeout(t),debug:e.debug??"production"!==t,...this.getEnvironmentDefaults(t),...e.config||{},...r?{galaChainAddress:r}:{}},o=new ME(i),s={sdk:o,wallet:n,config:i};if(!1!==e.autoValidate){const e=await this.validateSetup(o,n);return{...s,validation:e}}return s}static async readOnlySetup(e={}){const t=e.environment||this.detectEnvironment(),n=e.galaChainAddress||process.env.WALLET_ADDRESS,r={wallet:void 0,baseUrl:e.baseUrl||this.getDefaultBaseUrl(t),timeout:e.timeout||this.getDefaultTimeout(t),debug:e.debug??"production"!==t,...this.getEnvironmentDefaults(t),...e.config||{},...n?{galaChainAddress:n}:{}};return{sdk:new ME(r),config:r}}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,t&&t.quantity){const e=Re(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: ${A(e)}`)}try{const t=await e.fetchPools({type:"recent",page:1,limit:1});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: ${A(e)}`)}return{ready:0===n.length&&i.connectionHealthy,sdk:e,wallet:t||FE.generateWallet(),issues:n,warnings:r,capabilities:i}}static getRecommendedConfig(e,t="general"){const n={environment:e,autoValidate:!0};switch(e){case"production":Object.assign(n,{debug:!1,timeout:3e4});break;case"development":Object.assign(n,{debug:!0,timeout:45e3});break;case"testing":Object.assign(n,{debug:!0,timeout:6e4})}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)}return n}static async multiWalletSetup(e,t="development"){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(){const e=process.env.NODE_ENV?.toLowerCase();return"development"===e?"development":"test"===e||"testing"===e?"testing":"production"}static setupWallet(e){if(!e){const e=process.env.PRIVATE_KEY;return e?FE.fromPrivateKey(e):FE.generateWallet()}return"generate"===e?FE.generateWallet():FE.fromPrivateKey(e)}static getDefaultBaseUrl(e){return"production"===e?"https://lpad-backend-prod1.defi.gala.com":"https://lpad-backend-dev1.defi.gala.com"}static getDefaultTimeout(e){switch(e){case"production":default:return 3e4;case"development":return 45e3;case"testing":return 6e4}}static getEnvironmentDefaults(e){const t={};if("production"===e)t.bundleBaseUrl="https://bundle-backend-prod1.defi.gala.com",t.galaChainBaseUrl="https://galachain-gateway-chain-platform-prod-chain-platform-eks.prod.galachain.com";else t.bundleBaseUrl="https://bundle-backend-dev1.defi.gala.com",t.galaChainBaseUrl="https://galachain-gateway-chain-platform-stage-chain-platform-eks.stage.galachain.com";return t}},exports.AuthError=v,exports.BAN_DURATIONS={ONE_HOUR:3600,ONE_DAY:86400,ONE_WEEK:604800,ONE_MONTH:2592e3},exports.BRIDGE_CONTRACT_ABI=cu,exports.BRIDGE_TOKEN_METADATA=su,exports.BaseBridgeStrategy=ET,exports.BridgeRateLimiter=Th,exports.BurnError=_a,exports.CALCULATION_MODES=vh,exports.CHAIN_IDS=Xc,exports.COMPOSITE_POOL_FETCH_CONCURRENCY=5,exports.CONTENT_REACTION_TYPES=oh,exports.CONTENT_TYPE_LABELS=Ul,exports.CROSS_RATE_TYPED_DATA_TYPES=mu,exports.ChatMessagesService=dh,exports.ConfigurationError=R,exports.DEFAULT_ETHEREUM_BRIDGE_CONTRACT=Jc,exports.DEFAULT_ETHEREUM_RPC_URL="https://ethereum.publicnode.com",exports.DEFAULT_ETHEREUM_TOKENS=iu,exports.DEFAULT_POLL_INTERVAL_MS=15e3,exports.DEFAULT_POLL_TIMEOUT_MS=27e5,exports.DEFAULT_PRICING_CONCURRENCY=5,exports.DEFAULT_RATE_LIMIT_RPS=12,exports.DEFAULT_SOLANA_BRIDGE_PROGRAM="AaE4dTnL75XqgUJpdxBKg6vS9sTJgBPJwBQRVhD29WwS",exports.DEFAULT_SOLANA_RPC_URL="https://api.mainnet-beta.solana.com",exports.DEFAULT_SOLANA_TOKENS=ou,exports.DEFAULT_WEBSOCKET_RECONNECT_ATTEMPTS=5,exports.DexPoolNotFoundError=q,exports.DexQuoteError=$,exports.ERC20_ABI=au,exports.ERROR_CODES=B,exports.ETHEREUM_BRIDGE_CONTRACT_SEPOLIA=Yc,exports.ETHEREUM_TOKENS_PROD=eu,exports.ETHEREUM_TOKENS_STAGE=tu,exports.EXTENDED_STREAM_ROLE=Bu,exports.EthereumBridgeStrategy=IT,exports.EventBufferWithAutoCleanup=class{constructor(e={},t){this.events=[],this.timeouts=new Map,this.maxSize=e.maxSize??100,this.defaultTtlMs=e.defaultTtlMs??3e4,this.logger=t}push(e){if(this.events.length>=this.maxSize){const e=0;this.events.shift();const t=this.timeouts.get(e);t&&(clearTimeout(t),this.timeouts.delete(e)),this.logger?.warn(`Buffer full (${this.maxSize}), dropped oldest event`)}this.events.push(e);const t=this.events.length-1,n=setTimeout(()=>{this.events[t]===e&&this.events.splice(t,1),this.timeouts.delete(t)},this.defaultTtlMs);this.timeouts.set(t,n)}getAll(){return[...this.events]}clear(){for(const e of this.timeouts.values())clearTimeout(e);this.events=[],this.timeouts.clear()}get size(){return this.events.length}},exports.FLAG_ACTION_LABELS=Ol,exports.FLAG_DETAILS_MAX_LENGTH=500,exports.FLAG_REASON_LABELS=Dl,exports.FLAG_STATUS_LABELS=Ll,exports.FileValidationError=Ds,exports.GALACHAIN_CHANNELS=Qc,exports.GALACONNECT_PRODUCTION_URL=Zc,exports.GALA_BRIDGE_TYPED_DATA_DOMAIN=lu,exports.GALA_DECIMALS=8,exports.GALA_TOKEN_CLASS_KEY={collection:"GALA",category:"Unit",type:"none",additionalKey:"none"},exports.GSwapAssetError=M,exports.GSwapAssetService=class extends ds{constructor(e){super(e.debugMode||!1),this.dexBackendBaseUrl=e.dexBackendBaseUrl,e.dexBackendHttp?this.dexBackendHttp=e.dexBackendHttp:this.dexBackendHttp=k(e.dexBackendBaseUrl,3e4)}parseTokenFlexible(e){try{return Hs(e)}catch{return{collection:e,category:"Unit",type:"none",additionalKey:"none"}}}transformRawTokenToDexToken(e){return{image:e.image||"",name:e.name||"",symbol:e.symbol||"",decimals:e.decimals||8,description:e.description||"",verified:e.verified||!1,compositeKey:e.compositeKey||"",additionalKey:e.additionalKey||"none",category:e.category||"Unit",type:e.type||"none",collection:e.collection||e.symbol||"",subscribePrice:e.subscribePrice||!1}}transformRawTokenToUserAsset(e){const t=this.transformRawTokenToDexToken(e);let n;try{n=e.compositeKey?this.parseTokenFlexible(e.compositeKey):{collection:e.collection||e.symbol||"",category:e.category||"Unit",type:e.type||"none",additionalKey:e.additionalKey||"none"}}catch{n={collection:e.symbol||"",category:"Unit",type:"none",additionalKey:"none"}}return{...t,tokenId:n,balance:e.balance||"0"}}async getUserAssets(e,t=20,n=1){try{this.logger.debug("Fetching user assets",{walletAddress:e,limit:t,page:n});const r=mr(await this.dexBackendHttp.get("/api/tokens/balances",{params:{wallet:e,limit:t,page:n}})),i=r?.data||r||{},o=i.tokens||[],s=i.count||o.length;return{assets:o.map(e=>this.transformRawTokenToUserAsset(e)),count:s,page:n,limit:t,hasMore:n*t<s}}catch(t){throw this.logger.error("Failed to fetch user assets",t),new M(`Failed to fetch user assets: ${A(t)}`,t,e)}}async getAllUserAssets(e){try{this.logger.debug("Fetching all user assets",{walletAddress:e});return(await Zo(async(t,n)=>{const r=await this.getUserAssets(e,n,t);return{items:r.assets,page:t,limit:n,total:r.count,totalPages:Xo(r.count,n),hasNext:r.hasMore,hasPrevious:t>1}},{maxPages:100,pageSize:100,logger:this.logger})).items}catch(t){throw this.logger.error("Failed to fetch all user assets",t),new M(`Failed to fetch all user assets: ${A(t)}`,t,e)}}async fetchAvailableDexTokens(e={}){try{const{search:t,limit:n=20,page:r=1}=e;this.logger.debug("Fetching available DEX tokens",{search:t,limit:n,page:r});const i={limit:n,page:r};t&&(i.search=t);const o=mr(await this.dexBackendHttp.get("/api/tokens",{params:i})),s=o?.data||o||{},a=s.tokens||[],c=s.count||a.length;return{tokens:a.map(e=>this.transformRawTokenToDexToken(e)),count:c,page:r,limit:n,hasMore:r*n<c}}catch(e){throw this.logger.error("Failed to fetch available DEX tokens",e),new M(`Failed to fetch available DEX tokens: ${A(e)}`,e)}}async fetchAllAvailableDexTokens(e={}){try{this.logger.debug("Fetching all available DEX tokens",e);return(await Zo(async(t,n)=>{const r=await this.fetchAvailableDexTokens({...e,limit:n,page:t});return{items:r.tokens,page:t,limit:n,total:r.count,totalPages:Xo(r.count,n),hasNext:r.hasMore,hasPrevious:t>1}},{maxPages:100,pageSize:100,logger:this.logger})).items}catch(e){throw this.logger.error("Failed to fetch all available DEX tokens",e),new M(`Failed to fetch all available DEX tokens: ${A(e)}`,e)}}},exports.GSwapLiquidityMutationService=class extends ds{constructor(e){super(e.debugMode||!1),this.bundlerClient=null,this.privateKey=e.privateKey,this.getWalletAddress=e.getWalletAddress,this.gatewayClient=e.gatewayClient,this.bundlerBaseUrl=e.bundlerBaseUrl,this.galaChainBaseUrl=e.galaChainBaseUrl,this.webSocketService=e.webSocketService,this.calculationService=e.calculationService,this.liquidityQueryService=e.liquidityQueryService,this.tokenConverter=new aa,e.bundlerBaseUrl&&(this.bundlerClient=hc.createClient(e.bundlerBaseUrl,3e4))}getBundlerClient(){if(!this.bundlerBaseUrl)throw new R("Bundler URL not configured","bundlerBaseUrl");return this.bundlerClient||(this.bundlerClient=hc.createClient(this.bundlerBaseUrl,3e4)),this.bundlerClient}convertTokenPair(e,t){return{gswapToken0:this.tokenConverter.toLaunchpadFormat(e),gswapToken1:this.tokenConverter.toLaunchpadFormat(t)}}calculatePersonalSignPrefix(e){return`Ethereum Signed Message:\n${JSON.stringify(e).length}${JSON.stringify(e)}`}async ensureWebSocketConnected(){this.webSocketService.isConnected()||await this.webSocketService.connect()}buildLiquidityStringsInstructions(e,t,n,r){const i=zs(e),o=zs(t),s=`$pool${i}${o}$${n}`;return[s,`$userPosition${r}`,`$tokenBalance${i}${r}`,`$tokenBalance${o}${r}`,`$tokenBalance${i}${s}`,`$tokenBalance${o}${s}`]}async monitorBundlerTransaction(e,t,n){return{...{transactionId:e,liquidity:"0",amount0:"0",amount1:"0",status:"pending"},wait:async(r=12e4)=>wr(async()=>{const i=new Promise((t,n)=>{setTimeout(()=>n(new Error(`Transaction ${e} timed out after ${r}ms`)),r)});await Promise.race([t,i]),this.logger.debug(`${n} confirmed`,{transactionId:e})},`${n} failed or timed out`,this.logger,(t,r,i)=>{throw i?.error(`GSwapLiquidityMutationService: ${r}`,{error:A(t),operationType:n,transactionId:e}),t})}}async sendAddLiquidityToBundler(t){if(!this.privateKey)throw new R("AddLiquidity requires wallet (full-access mode)","privateKey");if(!this.bundlerBaseUrl)throw new R("Bundler URL not configured","bundlerBaseUrl");return wr(async()=>{const n=`galaswap - operation - ${o.v4()}-${Date.now()}-${t.owner}`,r={token0:t.token0,token1:t.token1,fee:t.fee,owner:t.owner,tickLower:t.tickLower,tickUpper:t.tickUpper,amount0Desired:t.amount0Desired,amount1Desired:t.amount1Desired,amount0Min:t.amount0Min,amount1Min:t.amount1Min,positionId:"",uniqueKey:n},i=new e.ethers.Wallet(this.privateKey),s={AddLiquidity:[{name:"token0",type:"token0"},{name:"token1",type:"token1"},{name:"fee",type:"int256"},{name:"owner",type:"string"},{name:"tickLower",type:"int256"},{name:"tickUpper",type:"int256"},{name:"amount0Desired",type:"string"},{name:"amount1Desired",type:"string"},{name:"amount0Min",type:"string"},{name:"amount1Min",type:"string"},{name:"positionId",type:"string"},{name:"uniqueKey",type:"string"}],token0:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}],token1:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}]},a={name:"ethereum",chainId:1},c=this.calculatePersonalSignPrefix(r),u={...r,prefix:c},l=await i.signTypedData(a,s,u),h={...u,signature:l,types:s,domain:a},d=this.buildLiquidityStringsInstructions(t.token0,t.token1,t.fee,t.owner),f=mr(await this.getBundlerClient().post("/bundle",{method:"AddLiquidity",signedDto:h,stringsInstructions:d})),g="string"==typeof f?.data?f.data:f?.data?.transactionId||f?.data?.id||f?.transactionId||f?.id;if(!g)throw new D("Bundler response does not contain transaction ID",void 0,"INVALID_RESPONSE");return g},"Failed to send AddLiquidity to bundler",this.logger)}async sendRemoveLiquidityToBundler(t,n,r,i,s,a,c,u,l){if(!this.privateKey)throw new R("RemoveLiquidity requires wallet (full-access mode)","privateKey");return wr(async()=>{const h=new e.ethers.Wallet(this.privateKey),d=await h.getAddress(),f=`galaswap - operation - ${o.v4()}-${Date.now()}-${d}`,g={tickLower:t,tickUpper:n,amount:r,token0:i,token1:s,fee:a,amount0Min:c,amount1Min:u,positionId:l,uniqueKey:f},p={RemoveLiquidity:[{name:"tickLower",type:"int256"},{name:"tickUpper",type:"int256"},{name:"amount",type:"string"},{name:"token0",type:"token0"},{name:"token1",type:"token1"},{name:"fee",type:"int256"},{name:"amount0Min",type:"string"},{name:"amount1Min",type:"string"},{name:"positionId",type:"string"},{name:"uniqueKey",type:"string"}],token0:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}],token1:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}]},m={name:"ethereum",chainId:1},y=this.calculatePersonalSignPrefix(g),w={...g,prefix:y},b=await h.signTypedData(m,p,w),k={...w,signature:b,types:p,domain:m},v=this.buildLiquidityStringsInstructions(i,s,a,d),S=mr(await this.getBundlerClient().post("/bundle",{method:"RemoveLiquidity",signedDto:k,stringsInstructions:v})),A="string"==typeof S?.data?S.data:S?.data?.transactionId||S?.data?.id||S?.transactionId||S?.id;if(!A)throw new D("Bundler response does not contain transaction ID",void 0,"INVALID_RESPONSE");return A},"Failed to send RemoveLiquidity to bundler",this.logger)}async sendCollectPositionFeesToBundler(t,n,r,i,s,a,c,u){if(!this.privateKey)throw new R("CollectPositionFees requires wallet (full-access mode)","privateKey");return wr(async()=>{const l=new e.ethers.Wallet(this.privateKey),h=await l.getAddress(),d=`galaswap - operation - ${o.v4()}-${Date.now()}-${h}`,f={token0:t,token1:n,fee:r,amount0Requested:i,amount1Requested:s,tickLower:a,tickUpper:c,positionId:u,uniqueKey:d},g={CollectPositionFees:[{name:"token0",type:"token0"},{name:"token1",type:"token1"},{name:"fee",type:"int256"},{name:"amount0Requested",type:"string"},{name:"amount1Requested",type:"string"},{name:"tickLower",type:"int256"},{name:"tickUpper",type:"int256"},{name:"positionId",type:"string"},{name:"uniqueKey",type:"string"}],token0:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}],token1:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}]},p={name:"ethereum",chainId:1},m=this.calculatePersonalSignPrefix(f),y={...f,prefix:m},w=await l.signTypedData(p,g,y),b={...y,signature:w,types:g,domain:p},k=this.buildLiquidityStringsInstructions(t,n,r,h),v=mr(await this.getBundlerClient().post("/bundle",{method:"CollectPositionFees",signedDto:b,stringsInstructions:k})),S="string"==typeof v?.data?v.data:v?.data?.transactionId||v?.data?.id||v?.transactionId||v?.id;if(!S)throw new D("Bundler response does not contain transaction ID",void 0,"INVALID_RESPONSE");return S},"Failed to send CollectPositionFees to bundler",this.logger)}async addLiquidityByPrice(e){if(!this.privateKey)throw new R("AddLiquidity requires wallet (full-access mode)","privateKey");if(!e.token0)throw z("token0","Token 0");if(!e.token1)throw z("token1","Token 1");if(!e.minPrice)throw z("minPrice","Minimum price");if(!e.maxPrice)throw z("maxPrice","Maximum price");if(!e.amount0Desired)throw z("amount0Desired","Desired amount 0");if(!e.amount1Desired)throw z("amount1Desired","Desired amount 1");return wr(async()=>{this.logger.debug("Adding liquidity by price",{token0:e.token0,token1:e.token1,priceRange:`${e.minPrice}-${e.maxPrice}`});const{gswapToken0:t,gswapToken1:n}=this.convertTokenPair(e.token0,e.token1);await this.ensureWebSocketConnected();const r=Hs(t),i=Hs(n),o=(await this.gatewayClient.getPoolData({token0:r,token1:i,fee:e.fee})).tickSpacing,s=wo(e.minPrice),a=wo(e.maxPrice),c=Math.floor(Ao(s)),u=Math.ceil(Ao(a)),l=Uo(c,o),h=Uo(u,o),d=this.getWalletAddress();if(!d)throw new R("Wallet address not available","walletAddress");const f=await this.sendAddLiquidityToBundler({token0:r,token1:i,fee:e.fee,tickLower:l,tickUpper:h,amount0Desired:e.amount0Desired,amount1Desired:e.amount1Desired,amount0Min:e.amount0Min||"0",amount1Min:e.amount1Min||"0",owner:d}),g=this.webSocketService.waitForTransaction(f);return this.monitorBundlerTransaction(f,g,"addLiquidityByPrice")},"Failed to add liquidity by price",this.logger,(e,t,n)=>{throw n?.error(t,{error:A(e)}),new F(`${t}: ${A(e)}`,e,"ADD_FAILED")})}async addSwapLiquidityByTicks(e){if(!this.privateKey)throw new R("AddLiquidity requires wallet (full-access mode)","privateKey");if(!e.token0)throw z("token0","Token 0");if(!e.token1)throw z("token1","Token 1");if(!e.amount0Desired)throw z("amount0Desired","Desired amount 0");if(!e.amount1Desired)throw z("amount1Desired","Desired amount 1");return wr(async()=>{this.logger.debug("Adding liquidity by ticks",{token0:e.token0,token1:e.token1,tickRange:`${e.tickLower}-${e.tickUpper}`}),this.calculationService.validateTickSpacing(e.tickLower,e.tickUpper,e.feeTier);const{gswapToken0:t,gswapToken1:n}=this.convertTokenPair(e.token0,e.token1);await this.ensureWebSocketConnected();const r=Hs(t),i=Hs(n),o=this.getWalletAddress();if(!o)throw new R("Wallet address not available","walletAddress");const s=await this.sendAddLiquidityToBundler({token0:r,token1:i,fee:e.feeTier,tickLower:e.tickLower,tickUpper:e.tickUpper,amount0Desired:e.amount0Desired,amount1Desired:e.amount1Desired,amount0Min:e.amount0Min||"0",amount1Min:e.amount1Min||"0",owner:o}),a=this.webSocketService.waitForTransaction(s);return this.monitorBundlerTransaction(s,a,"addSwapLiquidityByTicks")},"Failed to add liquidity by ticks",this.logger,(e,t,n)=>{throw n?.error(t,{error:A(e)}),new F(`${t}: ${A(e)}`,e,"ADD_FAILED")})}async removeLiquidity(e){if(!this.privateKey)throw new R("RemoveLiquidity requires wallet (full-access mode)","privateKey");if(!e.token0)throw z("token0","Token 0");if(!e.token1)throw z("token1","Token 1");if(!e.liquidity)throw z("liquidity","Liquidity amount");return wr(async()=>{this.logger.debug("Removing liquidity via bundler",{token0:e.token0,token1:e.token1,liquidity:e.liquidity});const t=wo(e.liquidity);try{Do(t)}catch(t){const n=`Invalid liquidity value: "${e.liquidity}". Must be a valid number.`;throw this.logger.error(n,{error:A(t)}),new _(n,"liquidity","INVALID_VALUE")}if(Co(t))throw new _("Cannot remove zero liquidity from position.","liquidity","ZERO_VALUE");const n="string"==typeof e.token0?Hs(e.token0):e.token0,r="string"==typeof e.token1?Hs(e.token1):e.token1;await this.ensureWebSocketConnected();const i=await this.sendRemoveLiquidityToBundler(e.tickLower,e.tickUpper,e.liquidity,n,r,e.fee,e.amount0Min||"0",e.amount1Min||"0",e.positionId||""),o=this.webSocketService.waitForTransaction(i);return this.monitorBundlerTransaction(i,o,"removeLiquidity")},"Failed to remove liquidity",this.logger,(e,t,n)=>{throw n?.error(t,{error:A(e)}),new F(`${t}: ${A(e)}`,e,"REMOVE_FAILED")})}async collectPositionFees(e){if(!this.privateKey)throw new R("CollectPositionFees requires wallet (full-access mode)","privateKey");if(!e.positionId)throw z("positionId","Position ID");return wr(async()=>{if(e.ownerAddress&&e.positionId&&!e.token0)throw new _("collectPositionFees requires direct parameters: token0, token1, fee, tickLower, tickUpper. Use GSwapService.collectPositionFees() for automatic position lookup.","parameters",B.REQUIRED);if(!e.token0||!e.token1||void 0===e.fee||void 0===e.tickLower||void 0===e.tickUpper)throw new _("Missing required parameters: token0, token1, fee, tickLower, tickUpper are required","parameters",B.REQUIRED);this.logger.debug("Collecting position fees via bundler",{token0:"string"==typeof e.token0?e.token0:e.token0?.type??"unknown",token1:"string"==typeof e.token1?e.token1:e.token1?.type??"unknown",tickLower:e.tickLower,tickUpper:e.tickUpper});const t="string"==typeof e.token0?Hs(e.token0):e.token0,n="string"==typeof e.token1?Hs(e.token1):e.token1;await this.ensureWebSocketConnected();const r=await this.sendCollectPositionFeesToBundler(t,n,e.fee,e.amount0Requested||"0",e.amount1Requested||"0",e.tickLower,e.tickUpper,e.positionId||""),i=this.webSocketService.waitForTransaction(r);return this.monitorBundlerTransaction(r,i,"collectPositionFees")},"Failed to collect position fees",this.logger,(e,t,n)=>{throw n?.error(t,{error:A(e)}),new F(`${t}: ${A(e)}`,e,"COLLECT_FAILED")})}},exports.GSwapLiquidityQueryService=class extends ds{constructor(e){super(e.debugMode||!1),this.gatewayClient=e.gatewayClient,this.galaChainBaseUrl=e.galaChainBaseUrl,this.calculationService=e.calculationService,this.tokenConverter=new aa}convertTokenPair(e,t){return{gswapToken0:this.tokenConverter.toLaunchpadFormat(e),gswapToken1:this.tokenConverter.toLaunchpadFormat(t)}}parseTokenFlexible(e){try{return Hs(e)}catch{return{collection:e,category:"Unit",type:"none",additionalKey:"none"}}}extractTokenSymbol(e){return e?"string"==typeof e?e:"object"==typeof e&&(e.type||e.collection||e.symbol||e.tokenSymbol||e.name)||"":""}normalizePositionResponse(e,t){const n=e;let r=n;n.positions&&Array.isArray(n.positions)&&n.positions.length>0&&(r=n.positions[0]);const i=r.positionId||r.id||n.positionId||n.id||"",o=this.extractTokenSymbol(r.token0||r.tokenA),s=this.extractTokenSymbol(r.token1||r.tokenB),a=r.feeTier??r.fee??r.feeAmount??3e3,c=r.tickLower??r.lowerTick??0,u=r.tickUpper??r.upperTick??0,l=r.liquidity?.toString()||r.liquidityAmount?.toString()||"0",h=r.amount0?.toString()||r.amountA?.toString()||"0",d=r.amount1?.toString()||r.amountB?.toString()||"0",f=r.feeAmount0?.toString()||r.feesA?.toString()||r.tokensOwed0?.toString()||"0",g=r.feeAmount1?.toString()||r.feesB?.toString()||r.tokensOwed1?.toString()||"0";return{positionId:i,ownerAddress:t,token0:o,token1:s,feeTier:Oe(a,3e3),tickLower:Oe(c,0),tickUpper:Oe(u,0),liquidity:l,amount0:h,amount1:d,feeAmount0:f,feeAmount1:g}}async getLiquidityPosition(e,t){try{this.logger.debug("Fetching liquidity position",{ownerAddress:e,position:t}),this.calculationService.validateTickSpacing(t.tickLower,t.tickUpper,t.fee);const{gswapToken0:n,gswapToken1:r}=this.convertTokenPair(t.token0,t.token1),i=dc(n),o=dc(r),s=(await this.gatewayClient.getPositions({owner:e,token0:i,token1:o,fee:t.fee,tickLower:t.tickLower,tickUpper:t.tickUpper})).positions.find(e=>e.tickLower===t.tickLower&&e.tickUpper===t.tickUpper);if(!s||"object"!=typeof s||!("positionId"in s)&&!("id"in s))throw new F("Invalid position data returned from API",null,"INVALID_DATA");return this.normalizePositionResponse(s,e)}catch(e){throw this.logger.error("Failed to fetch liquidity position",{error:A(e)}),new F(`Failed to fetch liquidity position: ${A(e)}`,e,"FETCH_FAILED")}}async fetchSwapPositionDirect(e){try{this.logger.debug("Fetching swap position via direct compound key",{token0:e.token0,token1:e.token1,fee:e.fee,owner:e.owner});const t=this.parseTokenFlexible(e.token0),n=this.parseTokenFlexible(e.token1),r=await this.gatewayClient.getPositions({token0:t,token1:n,fee:e.fee,tickLower:e.tickLower,tickUpper:e.tickUpper,owner:e.owner});if(!r.positions||0===r.positions.length)throw new F("Position not found: API returned no position data",null,"NOT_FOUND");const i=r.positions[0];return this.normalizePositionResponse(i,e.owner)}catch(e){throw this.logger.error("Failed to fetch swap position via compound key",{error:A(e)}),new F(`Failed to fetch swap position: ${A(e)}`,e,"FETCH_FAILED")}}async estimateRemoveLiquidity(e){try{this.logger.debug("Estimating liquidity removal",{token0:e.token0,token1:e.token1,owner:e.owner}),this.calculationService.validateTickSpacing(e.tickLower,e.tickUpper,e.fee);const{gswapToken0:t,gswapToken1:n}=this.convertTokenPair(e.token0,e.token1),r=dc(t),i=dc(n);return await this.gatewayClient.getRemoveLiquidityEstimation({token0:r,token1:i,fee:e.fee,amount:e.liquidity,tickLower:e.tickLower,tickUpper:e.tickUpper,owner:e.owner})}catch(e){throw this.logger.error("Failed to estimate liquidity removal",{error:A(e)}),new F(`Failed to estimate liquidity removal: ${A(e)}`,e,"ESTIMATE_FAILED")}}},exports.GSwapPoolCalculationService=class{constructor(e){this.logger=e?.logger}getTickSpacing(e){switch(e){case 500:return 10;case 3e3:return 60;case 1e4:return 200;default:throw new _(`Invalid fee tier: ${e}. Valid values are 500, 3000, or 10000.`,"feeTier",B.INVALID_FEE_TIER)}}validateTickSpacing(e,t,n){const r=this.getTickSpacing(n);if(e%r!==0)throw new _(`Invalid tickLower: ${e} must be a multiple of ${r} for fee tier ${n}. Tip: Use getAllSwapUserLiquidityPositions() to discover valid positions with correct tick spacing.`,"tickLower","INVALID_TICK_SPACING");if(t%r!==0)throw new _(`Invalid tickUpper: ${t} must be a multiple of ${r} for fee tier ${n}. Tip: Use getAllSwapUserLiquidityPositions() to discover valid positions with correct tick spacing.`,"tickUpper","INVALID_TICK_SPACING")}calculatePriceFromSqrtPriceX96(e){return br(()=>{const t=Eo();return Oo(e,t).pow(2)},"calculatePriceFromSqrtPriceX96 failed",this.logger)}calculatePriceFromSqrtPriceDecimal(e){return br(()=>e.pow(2),"calculatePriceFromSqrtPriceDecimal failed",this.logger)}calculateLiquidityFromAmount0(e,t,n){return br(()=>{const r=c.tickToSqrtPrice(t),i=c.tickToSqrtPrice(n);return c.liquidity0(e,r,i)},"calculateLiquidityFromAmount0 failed",this.logger)}calculateLiquidityFromAmount1(e,t,n){return br(()=>{const r=c.tickToSqrtPrice(t),i=c.tickToSqrtPrice(n);return c.liquidity1(e,r,i)},"calculateLiquidityFromAmount1 failed",this.logger)}calculateAmount0FromLiquidity(e,t,n){return br(()=>{const r=c.tickToSqrtPrice(t),i=c.tickToSqrtPrice(n);return c.getAmount0Delta(r,i,e)},"calculateAmount0FromLiquidity failed",this.logger)}calculateAmount1FromLiquidity(e,t,n){return br(()=>{const r=c.tickToSqrtPrice(t),i=c.tickToSqrtPrice(n);return c.getAmount1Delta(r,i,e)},"calculateAmount1FromLiquidity failed",this.logger)}calculateOptimalPositionSize(e,t,n,r,i){if(!t)throw z("desiredAmount0","Desired amount 0");if(!n)throw z("desiredAmount1","Desired amount 1");const o=c.tickToSqrtPrice(r),s=c.tickToSqrtPrice(e),a=c.tickToSqrtPrice(i),u=c.getLiquidityForAmounts(wo(t),wo(n),o,s,a),l=c.getAmountsForLiquidity(u,s,o,a),h=l[0],d=l[1],f=wo(t),g=wo(n);Co(wo(d))&&this.logger?.warn("GSwapPoolCalculationService: Calculated amount1 is zero - position may be heavily skewed to amount0",{desiredAmount0:t,desiredAmount1:n,currentTick:r,tickUpper:i});const p=Oo(h,d,wo(0));return{amount0:bo(h),amount1:bo(d),liquidity:bo(u),ratio:bo(p),utilizationPercent:{amount0:bo(Po(Oo(h,f),100),2),amount1:bo(Po(Oo(d,g),100),2)}}}validatePositionParameters(e,t,n,r,i,o,s){if(!r)throw z("amount0","Amount 0");if(!i)throw z("amount1","Amount 1");const a=[],c=[],u=[500,3e3,1e4];let l;u.includes(e)||a.push(`Invalid fee tier: ${e}. Must be one of: ${u.join(", ")}`);try{l=br(()=>this.getTickSpacing(e),"validatePositionParameters tick spacing lookup",this.logger),void 0!==l&&(t%l!==0&&a.push(`tickLower must be multiple of ${l}`),n%l!==0&&a.push(`tickUpper must be multiple of ${l}`))}catch{}t>=n&&a.push(`tickLower (${t}) must be less than tickUpper (${n})`);const h=wo(r),d=wo(i);if(h.isNaN()||d.isNaN())a.push("Amounts must be valid numbers");else try{br(()=>Do(h,d),"validatePositionParameters amounts validation",this.logger)}catch(e){a.push(`Liquidity amounts must be non-negative: ${e.message}`)}if(void 0!==o&&(o<t||o>n)&&c.push("Position is out of current price range - will not earn fees until price moves into range"),void 0!==s){wo(s).lt("1000000")&&c.push("Low pool liquidity - consider higher slippage tolerance")}const f=0===a.length?35e4:0,g={valid:0===a.length,errors:a,warnings:c,gasEstimate:f};return void 0!==l&&(g.tickSpacing=l),void 0!==o&&(g.currentTick=o),void 0!==s&&(g.poolLiquidity=s),g}calculateTicksForPrice(e,t,n){if(!e)throw z("minPrice","Minimum price");if(!t)throw z("maxPrice","Maximum price");const r=this.getTickSpacing(n),i=wo(e),o=wo(t);ce(e,t,"priceRange");const s=De(Math.floor(Ao(i)),0),a=De(Math.ceil(Ao(o)),0),c=De(Uo(s,r),0),u=De(Uo(a,r),0),l=De(Math.pow(1.0001,c),0===c?1:NaN),h=De(Math.pow(1.0001,u),0===u?1:NaN),d=wo(l),f=wo(h);return{tickLower:c,tickUpper:u,tickSpacing:r,requestedMinPrice:e,requestedMaxPrice:t,actualMinPrice:d.toFixed(8),actualMaxPrice:f.toFixed(8),priceDeviation:{minPriceDeviation:Po(Oo(d.minus(i),i),100).toFixed(4),maxPriceDeviation:Po(Oo(f.minus(o),o),100).toFixed(4)}}}calculatePriceForTicks(e,t){const n=De(Math.pow(1.0001,e),1),r=De(Math.pow(1.0001,t),1),i=wo(n),o=wo(r);return{tickLower:e,tickUpper:t,minPrice:i.toFixed(8),maxPrice:o.toFixed(8),priceRange:`${i.toFixed(4)} - ${o.toFixed(4)}`,tickSpread:De(t-e,0)}}calculateExecutionPrice(e,t){if(!e)throw z("inputAmount","Input amount");if(!t)throw z("outputAmount","Output amount");return br(()=>{const n=wo(e);return bo(Oo(wo(t),n,wo("0")))},"calculateExecutionPrice failed",this.logger)}},exports.GSwapPoolError=U,exports.GSwapPoolQueryService=class extends ds{constructor(e){super(e.debugMode||!1),this.gatewayClient=e.gatewayClient,this.galaChainBaseUrl=e.galaChainBaseUrl,this.calculationService=e.calculationService,this.tokenConverter=new aa}convertTokenPair(e,t){return{gswapToken0:this.tokenConverter.toLaunchpadFormat(e),gswapToken1:this.tokenConverter.toLaunchpadFormat(t)}}async getPoolData(e,t,n){try{this.logger.debug("Getting pool data",{tokenA:e,tokenB:t,feeTier:n});const{gswapToken0:r,gswapToken1:i}=this.convertTokenPair(e,t),o=Hs(r),s=Hs(i),a=await this.gatewayClient.getPoolData({token0:o,token1:s,fee:n}),c=this.calculationService.calculatePriceFromSqrtPriceX96(wo(a.sqrtPrice));return{tokenA:e,tokenB:t,feeTier:n,liquidity:a.liquidity.toString(),sqrtPriceX96:a.sqrtPrice.toString(),tick:a.tick,feeGrowthGlobal0X128:a.feeGrowthGlobal0.toString(),feeGrowthGlobal1X128:a.feeGrowthGlobal1.toString(),currentPrice:c.toFixed()}}catch(n){throw this.logger.error("Failed to get pool data",n),new U(`Failed to get pool data: ${A(n)}`,n,e,t)}}async getPoolInfo(e,t){try{this.logger.debug("Fetching pool info",{tokenA:e,tokenB:t});const{gswapToken0:n,gswapToken1:r}=this.convertTokenPair(e,t),i=[500,3e3,1e4];let o=wo(0),s=0;for(const a of i)try{const e=Hs(n),t=Hs(r),i=await this.gatewayClient.getPoolData({token0:e,token1:t,fee:a});i&&(o=o.plus(wo(i.liquidity)),s++)}catch{this.logger.debug("Pool not found for fee tier",{tokenA:e,tokenB:t,feeTier:a})}return{tokenA:e,tokenB:t,liquidity:o.toFixed(),feeTiers:i,swapCount:s}}catch(n){return this.logger.warn("Failed to fetch pool info",n),this.logger.debug("Pool error details",{error:new U(`Failed to fetch pool info: ${A(n)}`,n,e,t)}),{tokenA:e,tokenB:t,liquidity:"0",feeTiers:[500,3e3,1e4],swapCount:0}}}async getPoolSlot0(e,t,n){try{this.logger.debug("Fetching pool slot0 data",{token0:e,token1:t,fee:n});const r="string"==typeof e?Hs(e):e,i="string"==typeof t?Hs(t):t,o=await this.gatewayClient.getSlot0({token0:r,token1:i,fee:n}),s={sqrtPrice:o.sqrtPrice||"0",tick:o.tick||0,liquidity:o.liquidity||"0",grossPoolLiquidity:o.grossPoolLiquidity||"0"};return this.logger.debug("Retrieved pool slot0 data",{sqrtPrice:s.sqrtPrice,tick:s.tick,liquidity:s.liquidity}),s}catch(e){throw this.logger.error("Failed to fetch pool slot0 data",e),new U(`Failed to fetch pool slot0 data: ${A(e)}`,e)}}async calculateDexPoolSpotPrice(e,t,n){try{this.logger.debug("Calculating spot price",{tokenA:e,tokenB:t,feeTier:n});const r=await this.getPoolData(e,t,n),i=wo(r.currentPrice);return{tokenA:e,tokenB:t,feeTier:n,price:i.toFixed(),invertedPrice:To(i,!0),tick:r.tick,liquidity:r.liquidity}}catch(n){throw this.logger.error("Failed to calculate spot price",n),new U(`Failed to calculate spot price: ${A(n)}`,n,e,t)}}async getPositionCurrentPrice(e){try{this.logger.debug("Fetching position current price",{token0:e.token0,token1:e.token1,feeTier:e.feeTier});const t=await this.getPoolSlot0(e.token0,e.token1,e.feeTier),n=wo(t.sqrtPrice),r={price:this.calculationService.calculatePriceFromSqrtPriceDecimal(n).toFixed(18),sqrtPrice:t.sqrtPrice,tick:t.tick,liquidity:t.liquidity};return this.logger.debug("Calculated position current price",{price:r.price,tick:r.tick}),r}catch(e){throw this.logger.error("Failed to fetch position current price",e),new U(`Failed to fetch position current price: ${A(e)}`,e)}}chunkArray(e,t){const n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}},exports.GSwapQuoteError=L,exports.GSwapSwapError=O,exports.GSwapSwapService=class extends ds{constructor(e){super(e.debugMode||!1),this.privateKey=e.privateKey,this.getWalletAddress=e.getWalletAddress,this.bundlerBaseUrl=e.bundlerBaseUrl,this.gatewayBaseUrl=e.gatewayBaseUrl,this.webSocketService=e.webSocketService,this.dexQuoteService=e.dexQuoteService,this.tokenConverter=new aa}convertTokenPair(e,t){return{gswapToken0:this.tokenConverter.toLaunchpadFormat(e),gswapToken1:this.tokenConverter.toLaunchpadFormat(t)}}calculatePersonalSignPrefix(e){return`Ethereum Signed Message:\n${JSON.stringify(e).length}${JSON.stringify(e)}`}calculateExecutionPrice(e,t){try{const n=wo(e),r=wo(t);return bo(Oo(r,n,wo("0")))}catch(n){return this.logger.warn("Failed to calculate execution price",{inputAmount:e,outputAmount:t,error:A(n)}),"0"}}async ensureWebSocketConnected(){this.webSocketService.isConnected()||await this.webSocketService.connect()}buildSwapStringsInstructions(e,t,n,r){const i=zs(e),o=zs(t),s=`$pool${i}${o}$${n}`;return[s,`$userPosition${r}`,`$tokenBalance${i}${r}`,`$tokenBalance${o}${r}`,`$tokenBalance${i}${s}`,`$tokenBalance${o}${s}`]}async sendSwapToBundler(t){return wr(async()=>{if(!this.privateKey)throw new R("Swap requires wallet (full-access mode)","privateKey");if(!this.bundlerBaseUrl)throw new R("Bundler URL not configured","bundlerBaseUrl");const n=[500,3e3,1e4];if(!n.includes(t.feeTier))throw new _(`Invalid fee tier ${t.feeTier}. Must be one of: ${n.join(", ")}`,"feeTier","INVALID_FEE_TIER");this.logger.debug("Sending Swap to bundler",{fromToken:"string"==typeof t.fromToken?t.fromToken:t.fromToken?.type??"unknown",toToken:"string"==typeof t.toToken?t.toToken:t.toToken?.type??"unknown",inputAmount:t.inputAmount,minOutput:t.minOutput,feeTier:t.feeTier});let r=t.fromToken,i=t.toToken;"string"==typeof r&&(r=Hs(r)),"string"==typeof i&&(i=Hs(i));const s=Ks(r),a=Ks(i),c=s<a?[r,i,s,a]:[i,r,a,s],[u,l,h,d]=c,f=Ks("string"==typeof t.fromToken?Hs(t.fromToken):t.fromToken),g=f===h,p=`galaswap - operation - ${o.v4()}-${Date.now()}-${t.walletAddress}`;let m;if(!t.currentSqrtPrice)throw z("currentSqrtPrice","Current sqrt price");const y=wo(t.currentSqrtPrice),w=t.slippageTolerance??.01;if(g){const e=vo(w);m=bo(y.multipliedBy(e))}else{const e=So(w);m=bo(y.multipliedBy(e))}const b={token0:u,token1:l,fee:t.feeTier,amount:bo(wo(t.inputAmount)),zeroForOne:g,sqrtPriceLimit:m,recipient:t.walletAddress,amountOutMinimum:bo(wo(t.minOutput).multipliedBy(-1)),uniqueKey:p};this.logger.info("SWAP DTO DETAILS",{orderedToken0String:h,orderedToken1String:d,fromTokenStr:f,zeroForOne:g?`TRUE (${h} -> ${d})`:`FALSE (${d} -> ${h})`,inputAmount:t.inputAmount,expectedOutput:t.minOutput,slippageTolerance:100*(t.slippageTolerance||.01)+"%"});const k=new e.ethers.Wallet(this.privateKey),v={Swap:[{name:"token0",type:"token0"},{name:"token1",type:"token1"},{name:"fee",type:"int256"},{name:"amount",type:"string"},{name:"zeroForOne",type:"bool"},{name:"sqrtPriceLimit",type:"string"},{name:"recipient",type:"string"},{name:"amountOutMinimum",type:"string"},{name:"uniqueKey",type:"string"}],token0:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}],token1:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}]},S={name:"ethereum",chainId:1},A=this.calculatePersonalSignPrefix(b),T={...b,prefix:A},E=await k.signTypedData(S,v,T),I={...T,signature:E,types:v,domain:S},x=this.buildSwapStringsInstructions(u,l,t.feeTier,t.walletAddress),C=hc.createClient(this.bundlerBaseUrl,3e4),N=mr(await C.post("/bundle",{method:"Swap",signedDto:I,stringsInstructions:x})),B=N?.data||N?.transactionId||N?.id;if(!B)throw new D("Bundler response does not contain transaction ID",void 0,"INVALID_RESPONSE");return B},"Failed to send Swap to bundler",this.logger)}async getSwapQuoteExactInput(e){return wr(async()=>{if(wo(e.amount).isLessThanOrEqualTo(0))throw new L("Amount must be greater than zero",{amount:e.amount,fromToken:e.fromToken,toToken:e.toToken});if(!this.dexQuoteService)throw new L("DexQuoteService not configured. Quote operations require DexQuoteService.",{fromToken:e.fromToken,toToken:e.toToken});this.logger.debug("Getting exact input quote",e);const t=this.tokenConverter.toLaunchpadFormat(e.fromToken),n=this.tokenConverter.toLaunchpadFormat(e.toToken),[r,i]=t<n?[t,n]:[n,t],o=[3e3,500,1e4];let s;const a=this.dexQuoteService;for(const c of o)try{return await wr(async()=>{const o=await a.fetchCompositePoolData({token0:r,token1:i,fee:c,gatewayBaseUrl:this.gatewayBaseUrl}),s=await a.calculateDexPoolQuoteExactAmount({compositePoolData:o,fromToken:t,toToken:n,amount:e.amount}),u=wo(s.currentSqrtPrice),l=wo(s.newSqrtPrice),h=u.gt(l)?Oo(u.minus(l),u,"0"):wo(0),d=wo(s.amount0),f=wo(s.amount1);if(!Bo(d)&&!Bo(f))throw new L("Unexpected quote result: neither amount is negative (no output from pool)",{amount0:s.amount0,amount1:s.amount1,fromToken:e.fromToken,toToken:e.toToken});const g=(Bo(d)?d:f).absoluteValue().toFixed();return{fromToken:e.fromToken,toToken:e.toToken,inputAmount:e.amount,estimatedOutput:g,feeTier:c,priceImpact:h.toFixed(),executionPrice:this.calculateExecutionPrice(e.amount,g),currentSqrtPrice:s.currentSqrtPrice,newSqrtPrice:s.newSqrtPrice}},`Quote calculation for fee tier ${c}`,this.logger)}catch(e){s=e,this.logger.debug("Fee tier failed, trying next",{feeTier:c,error:A(e)})}throw s||new L("No available fee tiers for quote",{feeTiers:o,fromToken:e.fromToken,toToken:e.toToken})},"Failed to get exact input quote",this.logger,(t,n,r)=>{throw r?.error(n,t),new L(`${n}: ${A(t)}`,{fromToken:e.fromToken,toToken:e.toToken})})}async getSwapQuoteExactOutput(e){return wr(async()=>{if(wo(e.amount).isLessThanOrEqualTo(0))throw new L("Amount must be greater than zero",{amount:e.amount,fromToken:e.fromToken,toToken:e.toToken});if(!this.dexQuoteService)throw new L("DexQuoteService not configured. Quote operations require DexQuoteService.",{fromToken:e.fromToken,toToken:e.toToken});this.logger.debug("Getting exact output quote",e);const t=this.tokenConverter.toLaunchpadFormat(e.fromToken),n=this.tokenConverter.toLaunchpadFormat(e.toToken),[r,i]=t<n?[t,n]:[n,t],o=[3e3,500,1e4];let s;const a=this.dexQuoteService;for(const c of o)try{return await wr(async()=>{const o=await a.fetchCompositePoolData({token0:r,token1:i,fee:c,gatewayBaseUrl:this.gatewayBaseUrl}),s=await a.calculateDexPoolQuoteExactAmount({compositePoolData:o,fromToken:t,toToken:n,amount:e.amount}),u=wo(s.currentSqrtPrice),l=wo(s.newSqrtPrice),h=u.gt(l)?Oo(u.minus(l),u,"0"):wo(0),d=wo(s.amount0),f=wo(s.amount1),g=(No(d)?d:No(f)?f:d).absoluteValue().toFixed();return{fromToken:e.fromToken,toToken:e.toToken,inputAmount:g,estimatedOutput:e.amount,feeTier:c,priceImpact:h.toFixed(),executionPrice:this.calculateExecutionPrice(g,e.amount),currentSqrtPrice:s.currentSqrtPrice,newSqrtPrice:s.newSqrtPrice}},`Quote calculation for fee tier ${c}`,this.logger)}catch(e){s=e,this.logger.debug("Fee tier failed, trying next",{feeTier:c,error:A(e)})}throw s||new L("No available fee tiers for quote",{feeTiers:o,fromToken:e.fromToken,toToken:e.toToken})},"Failed to get exact output quote",this.logger,(t,n,r)=>{throw r?.error(n,t),new L(`${n}: ${A(t)}`,{fromToken:e.fromToken,toToken:e.toToken})})}async executeSwap(e){return wr(async()=>{if(!this.privateKey)throw new R("ExecuteSwap requires wallet (full-access mode)","privateKey");this.logger.debug("Executing swap",e);const{gswapToken0:t,gswapToken1:n}=this.convertTokenPair(e.fromToken,e.toToken),r=e.slippageTolerance??.01,i=await this.getSwapQuoteExactInput({fromToken:e.fromToken,toToken:e.toToken,amount:e.inputAmount}),o=ko(e.estimatedOutput,r).toFixed();await this.ensureWebSocketConnected();const s=this.getWalletAddress();if(!s)throw new R("Wallet address not available","walletAddress");const a=await this.sendSwapToBundler({fromToken:t,toToken:n,inputAmount:e.inputAmount,minOutput:o,feeTier:e.feeTier,walletAddress:s,currentSqrtPrice:i.currentSqrtPrice,slippageTolerance:r}),c=this.webSocketService.waitForTransaction(a);return{transactionId:a,status:"pending",fromToken:e.fromToken,toToken:e.toToken,inputAmount:e.inputAmount,outputAmount:e.estimatedOutput,feeTier:e.feeTier,slippageTolerance:r,timestamp:new Date,wait:async(e=12e4)=>{await wr(async()=>{const t=new Promise((t,n)=>{setTimeout(()=>n(new Error(`Transaction ${a} timed out after ${e}ms`)),e)});await Promise.race([c,t]),this.logger.debug("Swap confirmed",{transactionId:a})},"Swap failed or timed out",this.logger,(e,t,n)=>{throw n?.error(t,{transactionId:a,error:A(e)}),e})}}},"Failed to execute swap",this.logger,(e,t,n)=>{throw n?.error(t,e),new O(`${t}: ${A(e)}`,e)})}},exports.GalaConnectClient=AT,exports.GalaConnectHttpError=mT,exports.GlobalAndRoomCallbackDispatcher=class{constructor(e){this.globalCallbacks=[],this.roomCallbacks=new Map,this.logger=e}registerGlobalCallback(e){this.globalCallbacks.push(e)}registerRoomCallback(e,t){const n=this.roomCallbacks.get(e)??[];n.push(t),this.roomCallbacks.set(e,n)}dispatch(e,t){for(const e of this.globalCallbacks)try{e(t)}catch(e){this.logger?.error(`Error in global callback: ${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}: ${t}`)}}clear(){this.globalCallbacks=[],this.roomCallbacks.clear()}clearRoom(e){this.roomCallbacks.delete(e)}},exports.IMAGE_EXTENSIONS=li,exports.INVITE_STATUS=kl,exports.INVITE_STATUSES=vl,exports.JWT_CONSTANTS=St,exports.LAUNCHPAD_TOKEN_DECIMALS=18,exports.LEGACY_TYPED_DATA_TYPES=pu,exports.LaunchpadSDK=ME,exports.ListenerCleanupManager=class{constructor(e){this.listeners=[],this.logger=e}register(e,t){this.listeners.push({id:e,cleanup:t})}async cleanup(){const e=[];for(let t=this.listeners.length-1;t>=0;t--){const{id:n,cleanup:r}=this.listeners[t];try{await r()}catch(t){const r=t instanceof Error?t:new Error(String(t));e.push(r),this.logger?.error(`Cleanup error for listener ${n}:`,r)}}return this.listeners=[],e}clear(){this.listeners=[]}get size(){return this.listeners.length}},exports.LockError=ka,exports.MAX_BURN_BATCH_SIZE=50,exports.MAX_CONCURRENT_POOL_FETCHES=5,exports.MAX_LOCK_BATCH_SIZE=100,exports.MAX_UNLOCK_BATCH_SIZE=100,exports.MODERATOR_ROLE=ml,exports.MODERATOR_ROLES=yl,exports.NetworkError=P,exports.OVERSEER_INVITE_STATUS=Hl,exports.OVERSEER_STATUS=jl,exports.PAGINATION_DEFAULTS=Wo,exports.POOL_FETCH_CONFIG={MAX_CONCURRENT_FETCHES:5,BACKEND_PAGE_SIZE:20},exports.POOL_TYPES={RECENT:"recent",POPULAR:"popular"},exports.PayloadWalkerWithDeduplication=class{constructor(e,t,n=50){this.seen=new Set,this.extractor=e,this.dedupeKeyFn=t,this.maxDepth=n}walk(e){const t=[],n=new WeakSet,r=(e,i=0)=>{if(i>this.maxDepth)return;if(!e||"object"!=typeof e)return;if(n.has(e))return;n.add(e);const o=this.extractor(e);if(o){const e=this.dedupeKeyFn(o);this.seen.has(e)||(this.seen.add(e),t.push(o))}for(const t of Object.values(e))r(t,i+1)};return r(e,0),t}reset(){this.seen.clear()}getSeenCount(){return this.seen.size}},exports.PendingSubscriptionTracker=class{constructor(){this.pending=new Map}addPending(e,t){this.removePending(e);const n=setTimeout(()=>{this.pending.delete(e)},t);this.pending.set(e,{timeoutId:n,addedAt:Date.now()})}removePending(e){const t=this.pending.get(e);t&&(clearTimeout(t.timeoutId),this.pending.delete(e))}isPending(e){return this.pending.has(e)}getPendingCount(){return this.pending.size}clearExpired(){for(const[e,t]of this.pending.entries())t||this.pending.delete(e)}clear(){for(const e of this.pending.values())clearTimeout(e.timeoutId);this.pending.clear()}},exports.PoolStateManager=zE,exports.QUERY_FIELD_NAMES={PAGE:"page",LIMIT:"limit",TOKEN_NAME:"tokenName",VAULT_ADDRESS:"vaultAddress",USER_ADDRESS:"userAddress",TRADE_TYPE:"tradeType",POOL_TYPE:"type",SEARCH:"search",SORT_ORDER:"sortOrder",START_DATE:"startDate",END_DATE:"endDate"},exports.REACTION_EMOJI_MAP={heart:"❤️",fire:"🔥",laugh:"😂",wow:"😮",thumbs_up:"👍"},exports.RECORDING_STATUS=Au,exports.ROLE_SOURCE=Nu,exports.RoomSubscriptionManager=class{constructor(){this.rooms=new Set}addRoom(e){this.rooms.add(e)}removeRoom(e){this.rooms.delete(e)}getRooms(){return Array.from(this.rooms)}isSubscribedTo(e){return this.rooms.has(e)}clear(){this.rooms.clear()}get size(){return this.rooms.size}},exports.SDK_VERSION=OE,exports.SIMULATE_EVENT_TYPE={STREAM_STARTED:"stream.started",STREAM_STOPPED:"stream.stopped",RECORDING_READY:"recording.ready",SIMULCAST_ERROR:"simulcast.error"},exports.SIMULCAST_PLATFORM=Tu,exports.SIMULCAST_STATUS={ACTIVE:"ACTIVE",IDLE:"IDLE",ERRORED:"ERRORED",DISABLED:"DISABLED"},exports.SOLANA_COMPUTE={UNIT_LIMIT:2e5,UNIT_PRICE_MICROLAMPORTS:375e3},exports.SOLANA_DISCRIMINATORS=uu,exports.STREAM_EVENTS=zu,exports.STREAM_PERMISSION={MANAGE_COMMENTS:"MANAGE_COMMENTS",MANAGE_CHAT:"MANAGE_CHAT",BAN_USERS:"BAN_USERS",UNBAN_USERS:"UNBAN_USERS",MANAGE_SIMULCAST:"MANAGE_SIMULCAST",GET_STREAM_KEY:"GET_STREAM_KEY",STOP_STREAM:"STOP_STREAM",RESET_STREAM_KEY:"RESET_STREAM_KEY",START_STREAM:"START_STREAM",DELETE_RECORDINGS:"DELETE_RECORDINGS",MANAGE_STREAM_SETTINGS:"MANAGE_STREAM_SETTINGS"},exports.STREAM_ROLE=Cu,exports.STREAM_STATUS=Su,exports.SelectiveEventForwarding=class{constructor(){this.filters=[]}addFilter(e){return this.filters.push(e),this}forward(e){for(const t of this.filters)if(!t(e))return!1;return!0}clearFilters(){this.filters=[]}get filterCount(){return this.filters.length}},exports.SolanaBridgeStrategy=IE,exports.StreamWebSocketService=Wu,exports.StreamingEventService=Hu,exports.TIME_CONSTANTS={ONE_SECOND_MS:1e3,ONE_MINUTE_MS:6e4,ONE_HOUR_MS:36e5,ONE_DAY_MS:864e5,ONE_WEEK_MS:6048e5,ONE_MONTH_MS:2592e6},exports.TRADES_QUERY_CONSTRAINTS=bs,exports.TRADING_TYPES=kh,exports.TokenMetadataService=class extends ds{constructor(e=!1){super(e),this.cache={},this.cacheExpiry=36e5}async resolveTokenMetadata(e){const t=this.getCacheKey(e),n=this.cache[t];if(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}async getTokenSymbol(e){return(await this.resolveTokenMetadata(e)).symbol}async getTokenDecimals(e){return(await this.resolveTokenMetadata(e)).decimals}clearCache(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 rs(e);return rs(`${e.type||e.symbol||"unknown"}|${e.additionalKey||"none"}`)}extractMetadata(e){let t,n,r="Token",i="Unit",o="none";if("string"==typeof e)if(Vs(e)){const s=js(e);"Token"===s.collection&&s.type?(r=s.collection,i=s.category||"Unit",t=s.type,o=s.additionalKey||"none",n=t):(t=s.collection,n=t,i=s.category||"Unit",o=s.additionalKey||"none")}else t=e,n=e;else t=e.type||"unknown",r=e.collection||"Token",i=e.category||"Unit",o=e.additionalKey||"none",n=e.symbol||("Token"===r?t:r)||"unknown";const s=this.getDecimalsForToken(n);return{symbol:n.toUpperCase(),decimals:s,collection:r,category:i,type:t.toUpperCase(),additionalKey:o,verified:!1}}getDecimalsForToken(e){return{GALA:8,GUSDC:6,USDC:6,USDT:6,WETH:18,DAI:18}[e.toUpperCase()]??18}isCacheExpired(e){return Ve(e)>this.cacheExpiry}setCacheExpiry(e){this.cacheExpiry=e,this.logger.debug(`Set token metadata cache expiry to ${e}ms`)}},exports.TransactionError=D,exports.TransactionFailedError=RE,exports.TypingIndicatorDebouncer=class{constructor(e={},t){this.pendingIndicators=new Map,this.activeIndicators=new Set,this.delayMs=e.delayMs??3e3,this.onTyping=e.onTyping,this.onStopTyping=e.onStopTyping,this.logger=t}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}},exports.ValidationError=_,exports.WebSocketError=PE,exports.WebSocketTimeoutError=class extends PE{constructor(e,t){super(`WebSocket confirmation timeout for transaction ${e} after ${t}ms`),this.name="WebSocketTimeoutError"}},exports.addressFormatSchema=_r,exports.aggregateMultipleApiSources=async function(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 o=e.map(async(t,n)=>{try{const o=await i(t);return r?.debug(`Endpoint [${n+1}/${e.length}] succeeded: ${t}`),o}catch(i){return void r?.warn(`Endpoint [${n+1}/${e.length}] failed: ${t} - ${A(i)}`)}}),s=(await Promise.allSettled(o)).map(e=>{if("fulfilled"===e.status)return e.value});return r?.debug(`Aggregating ${s.filter(e=>void 0!==e).length} successful results`),t(s)},exports.amountMethodSchema=ai,exports.amountTypeSchema=si,exports.assertValidWalletAddress=yt,exports.bidirectionalTokenMatch=Cs,exports.browserFileSchema=di,exports.bufferFileSchema=fi,exports.buildConcurrentBatchRequests=async function(e,t,n,r){const i=r?.logger,o=new Array(e.length);let s=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),u=r;try{const t=c.map((t,r)=>{const c=u+r;return(async()=>{try{const r=await n(t);return o[c]=r,s++,i?.debug(`Fetched [${c+1}/${e.length}]: ${t}`),r}catch(n){throw a++,i?.warn(`Failed [${c+1}/${e.length}]: ${t} - ${A(n)}`),n}})()}),r=await Promise.allSettled(t);for(let e=0;e<r.length;e++){"rejected"===r[e].status&&i?.debug(`Promise rejected in batch at index ${u+e}`)}}catch(e){i?.error(`Batch processing error at index ${r}: ${A(e)}`)}}return i?.debug(`Batch complete: ${s} succeeded, ${a} failed`),o},exports.buildQueryParametersWithValidation=function(e){if(!e||"object"!=typeof e)return"";const t=[];for(const[n,r]of Object.entries(e)){if(Je(r))continue;let e;e="string"==typeof r?r:"number"==typeof r||"boolean"==typeof r?String(r):Array.isArray(r)?r.map(e=>String(e)).join(","):"object"==typeof r?JSON.stringify(r):String(r);const i=encodeURIComponent(n),o=encodeURIComponent(e);t.push(`${i}=${o}`)}return t.length>0?`?${t.join("&")}`:""},exports.buyTokensDataSchema=Di,exports.calculateLinearFeeInterpolation=function(e,t,n){const r="number"==typeof e?new i(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 o=n-t;return new i(t).plus(new i(o).multipliedBy(r))},exports.calculatePaginationOffset=Ho,exports.calculatePreMintDataSchema=qi,exports.calculateScaledFeeAmount=function(e,t){if(t<0)throw new Error(`feeFactor must be >= 0, got: ${t}`);return wo(e).multipliedBy(t).integerValue(i.ROUND_DOWN)},exports.calculateTotalPages=Xo,exports.capitalize=K,exports.caseInsensitiveTokenComparison=Is,exports.checkPoolOptionsSchema=oi,exports.commonValidators=st,exports.compareAmounts=function(e,t){const n=wo(e),r=wo(t);return n.comparedTo(r)},exports.conditionalSpreadBuilder=function(e,t){const n={...e};for(const[e,r]of Object.entries(t))void 0!==r&&(n[e]=r);return n},exports.conditionalTrimAndValidateString=Es,exports.createLaunchpadSDK=function(t){Ye(t)&&(t={});const{wallet:n,env:r,config:i={},...o}=t,s={...o,...i},{wallet:a,env:c,config:u,...l}=s;let h;if(Ye(n)){h=$E().wallet}else if("string"==typeof n){h=$E(n).wallet}else{if(!(n instanceof e.Wallet))throw j("Invalid wallet input. Expected string (private key or mnemonic) or Wallet instance.","wallet");h=n}const d={wallet:h,...r&&{env:r},debug:!1,timeout:3e4,...l};return new ME(d)},exports.createLimitSchema=$r,exports.createOptionsValidator=function(e){return t=>{const n=[],r=t;for(const t of e){const{field:e,required:i,type:o,validator:s}=t,a=r[e];if(i){if(Ye(a)){n.push(`${e} is required`);continue}if("string"===o){if("string"!=typeof a){n.push(`${e} must be a string`);continue}if(0===a.trim().length){n.push(`${e} is required`);continue}}}if(!Ye(a))if(o&&typeof a!==o)n.push(`${e} must be a ${o}`);else if(s){const e=s(a,r);e&&n.push(e)}}return n}},exports.createPaginatedResultSchema=function(e){return r.z.object({data:r.z.array(e),page:r.z.number().int().min(1),limit:r.z.number().int().min(1),total:r.z.number().int().min(0),totalPages:r.z.number().int().min(0),hasNext:r.z.boolean(),hasPrevious:r.z.boolean()})},exports.createPaginationQuery=function(e,t=Wo.DEFAULT_LIMIT){return{offset:Ho(e,t),limit:t}},exports.createPoolStateManager=function(e,t){return new zE(e,t)},exports.createSolanaWallet=function(){const e=UA.generate();return{privateKey:TE.encode(e.secretKey),publicKey:e.publicKey.toBase58(),address:e.publicKey.toBase58()}},exports.createTradeDataSchema=Ri,exports.createWallet=$E,exports.decimalRoundingUp=function(e,t){if(t<0)throw new Error(`decimals must be >= 0, got: ${t}`);const n=wo(e),r=new i(10).pow(t);return n.multipliedBy(r).integerValue(i.ROUND_UP).dividedBy(r)},exports.deduplicateByKey=function(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})},exports.errorMessageCaseNormalization=function(e){return e.toLowerCase()},exports.ethereumAddressSchema=Pr,exports.extractFieldWithFallbackPath=function(e,t,n=null){if(!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(!n||"object"!=typeof n){n=null;break}n=n[e]}if(Qe(n))return n;if(null!=n&&""!==n)return n}return n},exports.extractPaginationMetadata=function(e){const t={page:1,pageSize:20,totalCount:-1,hasMore:!1};if(!e||"object"!=typeof e)return t;const n=e,r=Oe(String(n.page??n.Page??n.current??1),t.page),i=Oe(String(n.pageSize??n.limit??n.size??t.pageSize),t.pageSize),o=n.data,s=o?.meta;let a;a="number"==typeof n.totalCount?n.totalCount:"number"==typeof n.total?n.total:"number"==typeof s?.totalItems?s.totalItems:"number"==typeof o?.count?o.count:Oe(String(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 s?.hasMore&&(c=s.hasMore),{page:r,pageSize:i,totalCount:a,hasMore:c}},exports.fetchGalaBalanceOptionsSchema=Ii,exports.fetchPoolDetailsDataSchema=Ki,exports.fetchTokenBalanceOptionsSchema=Bi,exports.fileSizeSchema=zr,exports.fileUploadSchema=hi,exports.filenameSchema=Wr,exports.filterByFeeTier=function(e,t){return e.filter(e=>e.feeTier===t)},exports.filterByLiquidity=function(e){return e.filter(e=>No(e.liquidity))},exports.filterByMinLiquidity=function(e,t){const n=wo(t);return e.filter(e=>wo(e.liquidity).isGreaterThanOrEqualTo(n))},exports.filterByPoolKey=function(e,t,n,r){const i=t.toUpperCase(),o=n.toUpperCase();return e.filter(e=>{const t=e.token0.toUpperCase(),n=e.token1.toUpperCase();return(t===i&&n===o||t===o&&n===i)&&e.feeTier===r})},exports.filterByToken=function(e,t){return e.filter(e=>Is(e.token0,t)||Is(e.token1,t))},exports.filterByTokenPair=function(e,t,n){const r=t.toUpperCase(),i=n.toUpperCase();return e.filter(e=>{const t=e.token0.toUpperCase(),n=e.token1.toUpperCase();return t===r&&n===i||t===i&&n===r})},exports.flexibleAddressSchema=Rr,exports.flexibleFileSchema=gi,exports.formatGalaForDTO=qe,exports.formatLaunchpadTokenForDTO=Ke,exports.formatTokenAmount=function(e,t=6){const n=wo(e);if(!n.isFinite())return"0";if(n.abs().lt(1e-6)&&!Co(n))return n.toExponential(2);const r=Math.min(t,n.abs().lt(1)?t:n.abs().lt(100)?4:2);return n.toFixed(r).replace(/\.?0+$/,"")},exports.formatTokenDescriptor=function(e){return Ks(e)},exports.fromBackendAddressFormat=gt,exports.fromBaseUnits=Ih,exports.fullNameSchema=Br,exports.generateUniqueKey=la,exports.getAmountOptionsSchema=$i,exports.getEnv=function(e,t){return process.env[e]??t},exports.getEnvOrThrow=function(e,t){const n=process.env[e];if(Ye(n)||!Qe(n)){throw z(e,`${e} (${t?`${t} (checked root .env and local .env)`:"checked root .env and local .env"})`)}return n},exports.getEthereumAddressFromPrivateKey=function(t){if(!t.match(/^0x[a-fA-F0-9]{64}$/))throw W("privateKey","0x-prefixed 64 hexadecimal characters","Private key");return e.getAddress(e.computeAddress(t))},exports.getEthereumBridgeContractByEnvironment=ru,exports.getEthereumTokenConfig=function(e){const t=os(e);return iu.find(e=>os(e.symbol)===t||os(e.symbol)===`G${t}`)},exports.getEthereumTokensByEnvironment=nu,exports.getGalaBridgeTypedDataTypes=yu,exports.getPublicKeyFromPrivateKey=function(t){if(!t.match(/^0x[a-fA-F0-9]{64}$/))throw W("privateKey","0x-prefixed 64 hexadecimal characters","Private key");const n=new e.SigningKey(t);return{publicKey:n.publicKey,compressedPublicKey:n.compressedPublicKey}},exports.getSolanaTokenConfig=function(e){const t=os(e);return ou.find(e=>os(e.symbol)===t||os(e.symbol)===`G${t}`)},exports.getStaticTokenMetadata=function(e){const t=os(e),n=su[t];if(n)return n;if(!t.startsWith("G")){const e=su[`G${t}`];if(e)return e}},exports.getTradeOptionsSchema=Oi,exports.graduateTokenOptionsSchema=ui,exports.graphDataOptionsSchema=ci,exports.groupByFeeTier=function(e){return qE(e,e=>e.feeTier)},exports.groupByKey=qE,exports.groupByPoolKey=function(e){return qE(e,e=>`${e.token0.toUpperCase()}|${e.token1.toUpperCase()}|${e.feeTier}`)},exports.groupByTokenPair=function(e){return qE(e,e=>`${e.token0.toUpperCase()}/${e.token1.toUpperCase()}`)},exports.hasMorePages=Qo,exports.hexStringExtractionAndNormalization=function(e){if(!e||"string"!=typeof e)return null;if(e.includes("|")){const t=e.split("|");if(t.length>=2){const e=t[1];if(Ns(e))return Bs(e)}return null}return Ns(e)?Bs(e):null},exports.imageExtensionSchema=pi,exports.imageFilenameSchema=mi,exports.imageMimeTypeSchema=Hr,exports.imageUploadOptionsSchema=ri,exports.isAccessSource=Du,exports.isActiveUserType=Vu,exports.isBanData=Xu,exports.isBanEnforcementEvent=Yu,exports.isBurnTokenEntry=Ca,exports.isBurnTokensData=Na,exports.isChatDisabledReason=Mu,exports.isChatMessageItem=function(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.id&&"string"==typeof t.tokenName&&"string"==typeof t.userAddress&&"string"==typeof t.content&&"string"==typeof t.createdAt&&"number"==typeof t.flagCount&&"object"==typeof t.reactions},exports.isChatStatusResponse=function(e){if(!e||"object"!=typeof e)return!1;const t=e;return"boolean"==typeof t.enabled&&(void 0===t.reason||Mu(t.reason))},exports.isClaimableInvite=function(e){if(e.status!==Hl.PENDING)return!1;if(e.expiresAt){if(He(e.expiresAt)<=new Date)return!1}return!0},exports.isContentType=Ml,exports.isEmptyValue=Je,exports.isExtendedStreamRole=Ru,exports.isFlagAction=ql,exports.isFlagData=Kl,exports.isFlagReason=Fl,exports.isFlagStatus=$l,exports.isLockTokenEntry=ga,exports.isLockTokensData=ma,exports.isModeratedToken=Il,exports.isModeratorInvite=El,exports.isNonEmptyString=Qe,exports.isOverseerInviteStatus=Vl,exports.isOverseerStatus=Xl,exports.isPinnedMessage=$u,exports.isPublicInviteInfo=xl,exports.isReactionErrorCode=qu,exports.isRecordingStatus=Iu,exports.isSimulcastPlatform=xu,exports.isStreamChatDeletedEvent=function(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.messageId&&"string"==typeof t.deletedAt},exports.isStreamChatErrorEvent=function(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.message},exports.isStreamChatMessage=Fu,exports.isStreamChatMessageEvent=function(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&Fu(t.message)},exports.isStreamChatPinnedEvent=function(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&$u(t.pinnedMessage)},exports.isStreamChatUnpinnedEvent=function(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.unpinnedMessageId},exports.isStreamReactionErrorEvent=function(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.message},exports.isStreamReactionEvent=function(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.emoji&&"number"==typeof t.timestamp&&"number"==typeof t.streamTime},exports.isStreamStatus=Eu,exports.isStreamStatusEvent=function(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&Eu(t.status)&&(null===t.playbackId||"string"==typeof t.playbackId)&&"boolean"==typeof t.isLive},exports.isStreamingEvent=function(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.type&&["stream_status","user_banned","user_unbanned","ban_enforcement","content_flagged","flag_resolved","stream_chat_message","stream_chat_updated","stream_chat_deleted","stream_chat_pinned","stream_chat_unpinned","chat_status_changed","viewer_count","recording_status","simulcast_status","download_ready","user_typing","stream_reaction","content_reaction_added","content_reaction_removed","stream_countdown_updated","stream_language_updated","stream_control_status_changed","connection","authenticated","token_subscribed","token_unsubscribed","room_subscribed","room_left"].includes(t.type)},exports.isTokenAccessPermissions=Pu,exports.isTokenAccessResult=function(e){if(!e||"object"!=typeof e)return!1;const t=e;return"boolean"==typeof t.hasAccess&&(null===t.role||Ru(t.role))&&Pu(t.permissions)&&(null===t.accessSource||Du(t.accessSource))&&"boolean"==typeof t.isOwner&&"boolean"==typeof t.isOverseer},exports.isTokenBanData=function(e){if(!e||"object"!=typeof e)return!1;const t=e;return"number"==typeof t.id&&"string"==typeof t.tokenName&&"string"==typeof t.bannedBy&&"string"==typeof t.createdAt&&(null===t.reason||"string"==typeof t.reason)},exports.isTypingIndicatorEvent=function(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&Array.isArray(t.typingUsers)&&t.typingUsers.every(Ku)},exports.isTypingUser=Ku,exports.isUnlockTokenEntry=pa,exports.isUnlockTokensData=ya,exports.isUserBannedEvent=Qu,exports.isUserUnbannedEvent=Ju,exports.isValidAddress=mt,exports.isValidApiKeyRole=ll,exports.isValidBanDuration=el,exports.isValidBanReason=Zu,exports.isValidChatContent=function(e){return!!Qe(e)&&(e.length>=ve.CHAT_MESSAGE.MIN_LENGTH&&e.length<=ve.CHAT_MESSAGE.MAX_LENGTH)},exports.isValidChatTokenName=function(e){return!!Qe(e)&&de.PATTERN.test(e)},exports.isValidGalaChainChannel=function(e){return Object.values(Qc).includes(e)},exports.isValidInviteCode=Tl,exports.isValidInviteStatus=Al,exports.isValidModeratorRole=Sl,exports.isValidTokenBanReason=nl,exports.isValidTokenName=function(e,t=de){if("string"!=typeof e)return!1;const n=e.trim();return 0!==n.length&&t.PATTERN.test(n)},exports.isViewerCountEvent=function(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"number"==typeof t.viewerCount},exports.isoDateStringSchema=jr,exports.launchTokenDataSchema=ni,exports.loadEnvWithFallback=function(){const e=y.join(process.cwd(),"..","..",".env");w.existsSync(e)&&b.config({path:e});const t=y.join(process.cwd(),".env");w.existsSync(t)&&b.config({path:t})},exports.nonNegativeDecimalStringSchema=Or,exports.normalizeAddressInput=pt,exports.normalizeDataWithMapping=function(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})},exports.normalizeErrorMessage=xs,exports.normalizeLimit=Vo,exports.normalizePage=jo,exports.normalizeTokenKey=is,exports.normalizeTokenName=rs,exports.normalizeTokenSymbol=os,exports.optionalUrlSchema=Mr,exports.pageNumberSchema=Fr,exports.paginationResultMetaSchema=Ai,exports.parseHttpErrorResponse=function(e){const t={statusCode:0,errorMessage:"Unknown error",raw:e};if(!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,o=t.errorMessage;"string"==typeof n.message?o=n.message:"string"==typeof n.error?o=n.error:e instanceof Error?o=e.message:"string"==typeof e&&(o=e);const s=n.response;if(s){const e=s.data;if("object"==typeof e&&null!==e){i=e;const t=e;"string"==typeof t.message?o=t.message:"string"==typeof t.error&&(o=t.error)}}const a={statusCode:r,errorMessage:o,raw:e};return i&&(a.errorData=i),a},exports.percentileIndexCalculation=function(e,t){if(0===e.length)return-1;if(t<0||t>100)throw new Error(`Percentile must be between 0 and 100, got: ${t}`);const n=(e.length-1)*(t/100),r=Math.floor(n);return Math.min(r,e.length-1)},exports.poolFetchTypeSchema=ii,exports.poolPaginationSchema=ki,exports.positiveDecimalStringSchema=Lr,exports.priceTickRangeMapping=function(e,t,n=60){const r=wo(e),o=wo(t);if(r.isLessThanOrEqualTo(0)||o.isLessThanOrEqualTo(0))throw new Error("Prices must be positive");if(r.isGreaterThanOrEqualTo(o))throw new Error(`minPrice must be < maxPrice, got: ${r.toString()} >= ${o.toString()}`);const s=Math.floor(Ao(r)),a=Math.ceil(Ao(o)),c=Math.floor(s/n)*n,u=Math.ceil(a/n)*n;return{minTick:c,maxTick:u,actualMinPrice:new i(1.0001).pow(c),actualMaxPrice:new i(1.0001).pow(u)}},exports.privateKeySchema=Xr,exports.requireNonNegative=Do,exports.requirePositive=Ro,exports.requirePositiveWithContext=Lo,exports.retryableHttpRequest=async function(e,t){const n=t?.maxRetries??3,r=t?.backoffMs??100,i=t?.retryableStatus??[429,503,504];let o,s=0;for(;s<=n;)try{return await e()}catch(e){o=e,s++;const t=KE(e),a=i.includes(t);if(s>n||!a)throw e;const c=r*Math.pow(2,s-1);await new Promise(e=>setTimeout(e,c))}throw o},exports.reverseBondingCurveConfigSchema=ti,exports.reverseBondingCurveConfigurationSchema=Gi,exports.roleHasSufficientPermission=function(e,t){return e===cl.MANAGER?t!==cl.OWNER:e===cl.OWNER||e===t},exports.roundTickBoundaries=function(e,t,n){if(e>=t)throw new Error(`tickLower must be < tickUpper, got: ${e} >= ${t}`);if(n<=0)throw new Error(`tickSpacing must be > 0, got: ${n}`);return{tickLower:Math.floor(e/n)*n,tickUpper:Math.ceil(t/n)*n}},exports.roundTickToSpacing=function(e,t){if(t<=0)throw new Error(`tickSpacing must be > 0, got: ${t}`);return Math.floor(e/t)*t},exports.safeDivideWithMinimum=function(e,t,n,r="0"){const i=wo(t);if(Co(i))return wo(r);const o=wo(e).dividedBy(i);if(null!=n){const e=wo(n);if(e.isLessThan(0))throw new Error(`minimum must be >= 0, got: ${e.toString()}`);if(o.isLessThan(e))return e}return o},exports.searchQuerySchema=Nr,exports.sellTokensDataSchema=Li,exports.sortByLiquidity=function(e,t="desc"){return[...e].sort((e,n)=>{const r=wo(e.liquidity),i=wo(n.liquidity);return"desc"===t?i.minus(r).toNumber():r.minus(i).toNumber()})},exports.standardLimitSchema=qr,exports.standardPaginationSchema=yi,exports.stripHexPrefix=ct,exports.timestampSchema=Vr,exports.toBackendAddressFormat=ft,exports.toBackendAddressFromEthers=wt,exports.toBaseUnits=Eh,exports.tokenCategorySchema=Zr,exports.tokenCollectionSchema=ei,exports.tokenDescriptionSchema=xr,exports.tokenHoldSchema=Ni,exports.tokenListOptionsSchema=Ei,exports.tokenNameSchema=Er,exports.tokenSymbolSchema=Ir,exports.tokenUrlsSchema=Yr,exports.tradeCalculationMethodSchema=Fi,exports.tradeCalculationTypeSchema=Mi,exports.tradeLimitSchema=Gr,exports.tradeListParamsSchema=Ui,exports.tradePaginationSchema=bi,exports.tradePaginationWithFiltersSchema=Si,exports.tradeTypeBackendSchema=Pi,exports.tradeTypeSchema=_i,exports.transactionIdSchema=Qr,exports.transformRawApiTokenToDomainModel=function(e){if(!e||"object"!=typeof e)throw new Error("Token must be an object");const t=e,n=(Qe(t.name)?t.name:null)||(Qe(t.tokenName)?t.tokenName:null)||"";if(!Qe(n))throw new Error("Token name is required and must be a non-empty string");const r=(Qe(t.symbol)?t.symbol:null)||(Qe(t.tokenSymbol)?t.tokenSymbol:null)||(Qe(t.collection)?t.collection:null)||"";if(!Qe(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 o={name:n,symbol:r,decimals:i};return Qe(t.address)&&(o.address=t.address),"boolean"==typeof t.verified&&(o.verified=t.verified),o},exports.trimmedLengthValidation=function(e){return!e||"string"!=typeof e||0===e.trim().length},exports.uniqueKeySchema=Jr,exports.updateProfileDataSchema=xi,exports.uploadProfileImageOptionsSchema=Ci,exports.urlSchema=Ur,exports.userLimitSchema=Kr,exports.userPaginationSchema=wi,exports.userTokenNameSchema=Cr,exports.userTokenTypeSchema=Ti,exports.userTokensPaginationSchema=vi,exports.validateAddress=Vi,exports.validateAmountString=Qi,exports.validateBanTokenOptions=rl,exports.validateBuyTokensData=lo,exports.validateCalculatePreMintData=mo,exports.validateChatMessageId=hh,exports.validateCheckPoolOptions=ro,exports.validateConstrainedEnumVariant=function(e,t,n){if(!t.includes(e))throw new _(`${n} must be one of [${t.join(", ")}], received "${e}"`,n,"INVALID_ENUM_VALUE")},exports.validateCreateApiKeyOptions=hl,exports.validateCreateChatMessageOptions=uh,exports.validateCreateCommentOptions=function(e){if(!Qe(e.tokenName))throw z("tokenName","Token name");const{MIN_LENGTH:t,MAX_LENGTH:n,PATTERN:r}=fe;if(e.tokenName.length<t||e.tokenName.length>n||!r.test(e.tokenName))throw W("tokenName",`${t}-${n} alphanumeric characters`,"Token name");if(!Qe(e.content))throw z("content");if(0===e.content.trim().length)throw ie("content","Content");if(e.content.length>ve.COMMENTS_V1.MAX_LENGTH)throw re("content",ve.COMMENTS_V1.MAX_LENGTH,e.content.length)},exports.validateCreateModeratorInviteOptions=function(e){const t=[],n=e.inviteScope??wl.TOKEN;return void 0===e.inviteScope||Cl(e.inviteScope)||N(t,()=>{throw ne("inviteScope",e.inviteScope,bl,"Invite scope")}),n===wl.TOKEN?N(t,()=>{rt(e.tokenName??"","tokenName",de)}):n===wl.ALL_OWNER_TOKENS&&e.tokenName&&t.push("Token name should not be provided for ALL_OWNER_TOKENS scope invites"),e.role?Sl(e.role)||N(t,()=>{throw ne("role",e.role,yl,"Role")}):N(t,()=>{throw z("role","Role")}),e.description&&N(t,()=>{se(e.description,ve.DESCRIPTION.MAX_LENGTH,"description")}),e.expiresAt&&!je(e.expiresAt)&&N(t,()=>{throw function(e,t="a valid date",n){const r=K(e,n);return new _(`${r} must be ${t}`,e,"INVALID_DATE")}("expiresAt","ISO 8601 format")}),t},exports.validateCreateOverseerInviteOptions=Ql,exports.validateCreateTradeData=uo,exports.validateDecimalRangeStrict=function(e,t,n,r){const i="string"==typeof e?parseFloat(e):e;if(!isFinite(i))throw new _(`${r} must be a valid finite number between ${t} and ${n}`,r,"INVALID_NUMBER");if(i<t||i>n)throw Q(r,t,n,i,r)},exports.validateFeePortionConstraints=he,exports.validateFetchGalaBalanceOptions=oo,exports.validateFetchPoolDetailsData=yo,exports.validateFetchTokenBalanceOptions=co,exports.validateFullName=Ji,exports.validateGetAmountOptions=po,exports.validateGetChatMessagesOptions=ch,exports.validateGetCommentsOptions=function(e){if(!e.tokenName&&!e.userAddress)throw function(e){if(e.length<2)return z(e[0]||"field");let t;t=2===e.length?e.join(" or "):`${e.slice(0,-1).join(", ")} or ${e[e.length-1]}`;return new _(`At least one of ${t} must be provided`,e[0],"REQUIRED")}(["tokenName","userAddress"]);if(e.tokenName){const{MIN_LENGTH:t,MAX_LENGTH:n,PATTERN:r}=fe;if(e.tokenName.length<t||e.tokenName.length>n||!r.test(e.tokenName))throw W("tokenName",`${t}-${n} alphanumeric characters`,"Token name")}Ze(e.page,e.limit,ye.MAX_LIMIT)},exports.validateGetTokenBanOptions=sl,exports.validateGetTradeOptions=fo,exports.validateGetTradesOptions=ks,exports.validateImageUploadOptions=no,exports.validateInviteCode=function(e){const t=[];return Qe(e)?Tl(e)||t.push("Invalid invite code format"):t.push(z("inviteCode","Invite code").message),t},exports.validateLaunchTokenData=eo,exports.validateListApiKeysOptions=fl,exports.validateListModeratorInvitesOptions=function(e){const t=[];return N(t,()=>{rt(e.tokenName??"","tokenName",de)}),void 0===e.status||Al(e.status)||N(t,()=>{throw ne("status",e.status,vl,"Status")}),N(t,()=>{Ze(e.page,e.limit,pe)}),t},exports.validateListOverseerInvitesOptions=Jl,exports.validateListOverseersOptions=Yl,exports.validateListTokenBansOptions=ol,exports.validateListUsersOptions=nh,exports.validateMinMaxRelationship=function(e,t,n,r){const i="string"==typeof e?parseFloat(e):e,o="string"==typeof t?parseFloat(t):t;if(!isFinite(i))throw new _(`${n} must be a valid finite number`,n,"INVALID_MIN_VALUE");if(!isFinite(o))throw new _(`${r} must be a valid finite number`,r,"INVALID_MAX_VALUE");if(i>o)throw new _(`${n} (${i}) must be less than or equal to ${r} (${o})`,n,"INVALID_RANGE")},exports.validateOptionalTokenName=function(e,t="tokenName",n=de){if(null==e)return;if("string"!=typeof e)throw Z(t,"a string",e);const r=e.trim();if(0!==r.length&&!n.PATTERN.test(r))throw new _(`${t} must be ${n.MIN_LENGTH}-${n.MAX_LENGTH} alphanumeric characters`,t,B.INVALID_FORMAT)},exports.validateOverseerInviteCode=Zl,exports.validateOverseerInviteId=th,exports.validateOverseerWalletAddress=eh,exports.validatePaginationParams=function(e,t,n){ae(e,"page"),ae(t,"limit")},exports.validateSearchQuery=Yi,exports.validateSellTokensData=ho,exports.validateSortOrderDirection=le,exports.validateTokenDescription=ji,exports.validateTokenListOptions=io,exports.validateTokenName=it,exports.validateTokenSymbol=Hi,exports.validateTokenUrls=to,exports.validateTradeListParams=go,exports.validateUnbanTokenOptions=il,exports.validateUpdateApiKeyOptions=dl,exports.validateUpdateChatMessageOptions=lh,exports.validateUpdateCommentOptions=function(e){if(!Qe(e.content))throw z("content");if(0===e.content.trim().length)throw ie("content","Content");if(e.content.length>ve.COMMENTS_V1.MAX_LENGTH)throw re("content",ve.COMMENTS_V1.MAX_LENGTH,e.content.length)},exports.validateUpdateProfileData=so,exports.validateUploadProfileImageOptions=ao,exports.validateUserTokenName=Zi,exports.validateVaultAddress=Xi,exports.vaultAddressSchema=Dr;
1
+ "use strict";var e=require("ethers"),t=require("axios"),n=require("@gala-chain/connect"),r=require("zod"),i=require("bignumber.js"),o=require("uuid"),s=require("@gala-chain/api"),a=require("socket.io-client"),c=require("@gala-chain/dex"),l=require("node:crypto"),u=require("path"),d=require("fs"),h=require("dotenv"),g=require("crypto");function p(e){var t=Object.create(null);return e&&Object.keys(e).forEach(function(n){if("default"!==n){var r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:function(){return e[n]}})}}),t.default=e,Object.freeze(t)}var f,m=p(l),y=p(u),w=p(d),k=p(h);if("undefined"==typeof File){const{File:e}=require("web-file-polyfill");global.File=e}function b(e,n=3e4){return t.create({baseURL:e,timeout:n,headers:{"Content-Type":"application/json"}})}exports.AuthErrorType=void 0,(f=exports.AuthErrorType||(exports.AuthErrorType={})).WALLET_NOT_CONNECTED="WALLET_NOT_CONNECTED",f.SIGNATURE_FAILED="SIGNATURE_FAILED",f.INVALID_ADDRESS="INVALID_ADDRESS",f.MESSAGE_GENERATION_FAILED="MESSAGE_GENERATION_FAILED";class v extends Error{constructor(e,t,n){super(t),this.type=e,this.originalError=n,this.name="AuthError"}}function S(e){return e instanceof Error}function A(e){return S(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 T(e){return S(e)||"object"==typeof e&&null!==e&&"stack"in e&&"string"==typeof e.stack?e.stack:void 0}function E(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 I(e){return"object"==typeof e&&null!==e&&"message"in e&&("response"in e||"request"in e||"config"in e)}function x(e,t){if(!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 C(e){if(!e||"object"!=typeof e)return"";const t=e.Message;return"string"==typeof t&&t.trim()?` - ${t}`:""}function N(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 _={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 B extends Error{constructor(e,t,n){super(e),this.field=t,this.code=n,this.name="ValidationError"}}class P extends Error{constructor(e,t,n){super(e),this.statusCode=t,this.originalError=n,this.name="NetworkError"}}class D extends Error{constructor(e,t){super(e),this.field=t,this.name="ConfigurationError"}}class R extends Error{constructor(e,t,n){super(e),this.transactionId=t,this.code=n,this.name="TransactionError"}}class M extends Error{constructor(e,t,n){super(e),this.originalError=t,this.code=n,this.name="GSwapQuoteError"}}class L extends Error{constructor(e,t,n,r){super(e),this.originalError=t,this.transactionHash=n,this.code=r,this.name="GSwapSwapError"}}class O extends Error{constructor(e,t,n,r,i){super(e),this.originalError=t,this.tokenA=n,this.tokenB=r,this.code=i,this.name="GSwapPoolError"}}class F extends Error{constructor(e,t,n,r){super(e),this.originalError=t,this.walletAddress=n,this.code=r,this.name="GSwapAssetError"}}class U extends Error{constructor(e,t,n){super(e),this.originalError=t,this.code=n,this.name="GSwapPositionError"}}class $ extends B{constructor(e,t){super(e,"dexQuote","DEX_QUOTE_ERROR"),this.context=t,this.name="DexQuoteError"}}class q extends B{constructor(e){super(e,"dexPool","DEX_POOL_NOT_FOUND"),this.name="DexPoolNotFoundError"}}function K(e,t){return t||e.charAt(0).toUpperCase()+e.slice(1)}function G(e,t){return new B(`Token "${e}" not found. Please verify the token name is correct.`,"tokenName","TOKEN_NOT_FOUND")}function W(e,t){const n=K(e,t);return new B(`${n} is required`,e,"REQUIRED")}function z(e,t,n){const r=K(e,n);return new B(`${r} must be ${t}`,e,"INVALID_FORMAT")}function H(e,t,n){return new P(e,t,n)}function j(e,t){return new D(e,t)}function V(e,t,n){return new R(e,t,n)}function X(e,t,n,r){return n&&n.error(`${t}:`,e),H(`${t}: ${A(e)}`,r,S(e)?e:void 0)}function Q(e,t,n,r,i){const o=K(e,i);return new B(`${o} must be between ${t} and ${n}${void 0!==r?`, received: ${r}`:""}`,e,"OUT_OF_RANGE")}function J(e,t,n,r){const i=K(e,r);return new B(`${i} must be at least ${t}${void 0!==n?`, received: ${n}`:""}`,e,"TOO_SMALL")}function Z(e,t,n,r){const i=K(e,r);return new B(`${i} must be at most ${t}${void 0!==n?`, received: ${n}`:""}`,e,"TOO_LARGE")}function Y(e,t,n,r){const i=K(e,r),o=void 0!==n?`, received: ${"object"==typeof n?"object":String(n)}`:"";return new B(`${i} must be ${t}${o}`,e,"INVALID_TYPE")}function ee(e,t,n){const r=K(e,n);return new B(`${r} must be a valid number${void 0!==t?`: "${t}"`:""}`,e,"INVALID_NUMBER")}function te(e){return new B(`Liquidity position not found: ${e}`,"positionId","POSITION_NOT_FOUND")}function ne(e,t,n,r){const i=K(e,r);return new B(`Invalid ${i}: ${t}. Must be one of: ${n.join(", ")}`,e,"INVALID_ENUM")}function re(e,t,n,r){const i=K(e,r);return new B(`${i} must be at most ${t} characters${void 0!==n?`, received: ${n}`:""}`,e,"TOO_LONG")}function ie(e,t){const n=K(e,t);return new B(`${n} cannot be empty`,e,"EMPTY_STRING")}function oe(e,t,n,r){if("number"!=typeof e)throw Y(r,"a number",e,r);if(e<t||e>n)throw Q(r,t,n,e)}function se(e,t,n){if("string"!=typeof e)throw Y(n,"a string",e,n);if(e.length>t)throw Z(n,t,e.length)}function ae(e,t){if("number"!=typeof e)throw Y(t,"a number",e,t);if(!Number.isInteger(e))throw Y(t,"an integer",e,t);if(e<=0)throw J(t,1,e,t)}function ce(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 Y(n,"numeric values",void 0,n);if(r>i)throw new B(`Minimum value (${r}) must be less than or equal to maximum value (${i}) for ${n}`,n,_.INVALID_RANGE)}function le(e,t,n=!1){if("string"!=typeof e)throw Y(t,"a string",e,t);if(!n&&0===e.trim().length)throw W(t,`${t} (non-empty string)`)}function ue(e,t){if("ASC"!==e&&"DESC"!==e)throw new B(`${t} must be either 'ASC' or 'DESC'`,t,"INVALID_ENUM_VALUE")}function de(e,t,n){const r="string"==typeof e?parseFloat(e):e,i="string"==typeof t?parseFloat(t):t;if(!isFinite(r))throw new B(`${n} minFee must be a valid finite number`,n,"INVALID_FEE_MINIMUM");if(!isFinite(i))throw new B(`${n} maxFee must be a valid finite number`,n,"INVALID_FEE_MAXIMUM");if(r<.1)throw new B(`${n} minFee must be >= 0.1, received ${r}`,n,"INVALID_FEE_MINIMUM");if(i>.5)throw new B(`${n} maxFee must be <= 0.5, received ${i}`,n,"INVALID_FEE_MAXIMUM");if(r>i)throw new B(`${n} minFee (${r}) must be <= maxFee (${i})`,n,"INVALID_FEE_RANGE")}const he={MIN_LENGTH:3,MAX_LENGTH:20,PATTERN:/^[a-zA-Z0-9]{3,20}$/},ge={MIN_LENGTH:2,MAX_LENGTH:20,PATTERN:/^[a-zA-Z0-9]+$/},pe={MIN_LENGTH:1,MAX_LENGTH:50},fe=100,me=20,ye={MAX_LIMIT:50,DEFAULT_PAGE:1,DEFAULT_LIMIT:20},we=100,ke={PATTERN:/^eth\|[0-9a-fA-F]{40}$/},be={MAX_LENGTH:100},ve={COMMENT:{MAX_LENGTH:1e3},COMMENTS_V1:{MAX_LENGTH:2e3},CHAT_MESSAGE:{MIN_LENGTH:1,MAX_LENGTH:500,PATTERN:/^[\s\S]{1,500}$/},CHAT_MESSAGES_V1:{MAX_LENGTH:500},BAN_REASON:{MAX_LENGTH:500},DESCRIPTION:{MAX_LENGTH:255},TOKEN_DESCRIPTION:{MIN_LENGTH:1,MAX_LENGTH:500},FLAG_DETAILS:{MAX_LENGTH:1e3},CONTENT_ID:{MAX_LENGTH:100}},Se={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})$/}},Ae=60,Te=31536e3,Ee={MAX_LENGTH:64,PATTERN:/^(galaswap-operation-|galaconnect-operation-)/},Ie={PATTERN:/^[a-fA-F0-9]{64}$/},xe={STREAM_URL_PATTERN:/^(rtmps?|srt):\/\/.+/},Ce=50,Ne=1,_e=100,Be={FULL_NAME:{MIN_LENGTH:1,MAX_LENGTH:100,ALPHABETS_ONLY_PATTERN:/^[a-zA-Z]+(?:\s[a-zA-Z]+)?$/}};function Pe(e,t){if(Je(e))return t;try{return JSON.parse(e)}catch{return t}}function De(e,t=0){if(Je(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 Re(e,t,n){if(Ze(e))return t;if("number"==typeof e)return isNaN(e)?t:e;const r=Number(e);return isNaN(r)?t:r}function Me(e,t=0){if(Je(e))return t;if("bigint"==typeof e)try{return Number(e)}catch{return t}if("number"==typeof e)return isNaN(e)||!isFinite(e)?t:Math.floor(e);const n=parseInt(String(e),10);return isNaN(n)?t:n}function Le(e,t,n){if(Ze(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 Oe(e,t="0"){if(Je(e))return new i(t);if(i.isBigNumber(e))return e.isNaN()?new i(t):e;try{const n=new i(e);return n.isNaN()||!n.isFinite()?new i(t):n}catch{return new i(t)}}function Fe(e,t){if(Ze(e)||""===e)throw W(t);if(i.isBigNumber(e)){if(e.isNaN())throw ee(t,"NaN");return e}try{const n=new i(e);if(n.isNaN())throw ee(t,e);if(!n.isFinite())throw ee(t,e);return n}catch(n){if(n instanceof B)throw n;throw ee(t,e)}}function Ue(e,t=0){if(Ze(e))return t;if("number"==typeof e)return isNaN(e)?t:e;return De(String(e).replace("%","").trim(),t)}function $e(e,t=18){const n=De(e,0);if(0===n)return"0";return n.toFixed(t).replace(/\.?0+$/,"")}function qe(e){return $e(e,8)}function Ke(e){return $e(e,18)}var Ge;!function(e){e.DEBUG="DEBUG",e.INFO="INFO",e.WARN="WARN",e.ERROR="ERROR"}(Ge||(Ge={}));class We{constructor(e){this.levelPriority={[Ge.DEBUG]:0,[Ge.INFO]:1,[Ge.WARN]:2,[Ge.ERROR]:3},this.debugEnabled=e.debug,this.context=e.context||"SDK",this.minLevel=e.minLevel||(e.debug?Ge.DEBUG:Ge.INFO)}debug(e,t){this.log(Ge.DEBUG,e,t)}info(e,t){this.log(Ge.INFO,e,t)}warn(e,t){this.log(Ge.WARN,e,t)}error(e,t){this.log(Ge.ERROR,e,t)}log(e,t,n){if(this.levelPriority[e]<this.levelPriority[this.minLevel])return;if(e===Ge.DEBUG&&!this.debugEnabled)return;const r=`[${(new Date).toISOString()}] [${this.context}] [${e}]`,i=this.getConsoleMethod(e);void 0!==n?S(n)?i(`${r} ${t}`,n.message,T(n)??""):i(`${r} ${t}`,n):i(`${r} ${t}`)}getConsoleMethod(e){switch(e){case Ge.DEBUG:return console.debug;case Ge.INFO:return console.info;case Ge.WARN:return console.warn;case Ge.ERROR:return console.error;default:return console.log}}child(e){return new We({debug:this.debugEnabled,context:`${this.context}:${e}`,minLevel:this.minLevel})}isDebugEnabled(){return this.debugEnabled&&this.levelPriority[Ge.DEBUG]>=this.levelPriority[this.minLevel]}}const ze=new We({debug:!1,context:"DateUtils"});function He(e,t){if(!e)return new Date;if(e instanceof Date)return isNaN(e.getTime())?new Date:e;try{const n=new Date(e);return isNaN(n.getTime())?(ze.warn(`Invalid date string received: "${e}". Using fallback.`),t||new Date):n}catch(t){return ze.warn(`Date parsing error for "${e}":`,t),new Date}}function je(e){if(!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 Ve(e){return Date.now()-e}const Xe={ETH_ADDRESS:/^0x[0-9a-fA-F]{40}$/,BACKEND_ADDRESS:/^eth\|(0x)?[0-9a-fA-F]{40}$/,CLIENT_ADDRESS:/^client\|[a-zA-Z0-9_-]+$/};function Qe(e){return"string"==typeof e&&e.trim().length>0}function Je(e){return null==e||""===e}function Ze(e){return null==e}function Ye(e,t,n=100){if(void 0!==e&&ae(e,"page"),void 0!==t&&(ae(t,"limit"),t>n))throw new B(`limit must be at most ${n}`,"limit",_.TOO_LARGE)}function et(e){const t=Object.values(e);return e=>"string"==typeof e&&t.includes(e)}function tt(e){return Object.values(e)}function nt(e,t,n,r={}){const{description:i="parameter",treatEmptyAsNull:o=!0}=r,s=e[t],a=e[n],c=null!=s&&(!o||""!==s),l=null!=a&&(!o||""!==a);if(!c&&!l)throw j(`Either ${t} or ${n} must be provided (${i})`,n);if(c&&l)throw j(`Cannot provide both ${t} and ${n}. Provide exactly one (${i}).`,n);return{chosen:c?t:n,hasA:c,hasB:l}}function rt(e,t="tokenName",n=he){if(!Qe(e))throw W(t);const r=e.trim();if(0===r.length)throw W(t);if(r.length<n.MIN_LENGTH)throw Q(t,n.MIN_LENGTH,n.MAX_LENGTH,r.length,`${t} length`);if(r.length>n.MAX_LENGTH)throw Q(t,n.MIN_LENGTH,n.MAX_LENGTH,r.length,`${t} length`);if(!n.PATTERN.test(r))throw new B(`${t} must contain only alphanumeric characters`,t,_.INVALID_FORMAT)}function it(e,t="tokenName",n=he){if(null==e)throw W(t,t);if("string"!=typeof e)throw Y(t,"a string",e);const r=e.trim();if(0===r.length)throw W(t,t);if(!n.PATTERN.test(r))throw new B(`${t} must be ${n.MIN_LENGTH}-${n.MAX_LENGTH} alphanumeric characters`,t,_.INVALID_FORMAT)}function ot(e){return t=>{if(!t||"object"!=typeof t)return!1;const n=t;for(const{field:t,type:r,nullable:i=!1,optional:o=!1,validator:s}of e){const e=n[t];if((!o||void 0!==e)&&(!i||null!==e)){if(typeof e!==r)return!1;if(s&&!s(e))return!1}}return!0}}const st={requiredString:e=>t=>Ze(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(!Je(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(!Ze(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=>Ze(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(!Ze(n))return t.includes(n)?void 0:`${e} must be one of: ${t.join(", ")}`},requiredEnumValue:(e,t)=>n=>Ze(n)?`${e} is required`:t.includes(n)?void 0:`${e} must be one of: ${t.join(", ")}`,isoDate:e=>t=>{if(!Ze(t))return"string"!=typeof t?`${e} must be a string`:je(t)?void 0:`${e} must be a valid ISO 8601 date string`},walletAddress:(e,t=!1)=>n=>{if(Ze(n))return t?`${e} is required`:void 0;if("string"!=typeof n)return`${e} must be a string`;return Xe.ETH_ADDRESS.test(n)||Xe.BACKEND_ADDRESS.test(n)||Xe.CLIENT_ADDRESS.test(n)?void 0:`${e} must be a valid wallet address`}};function at(e){return!e||0===e.trim().length}function ct(e){return e?e.startsWith("0x")?e.slice(2):e:""}const lt={ETHEREUM:Xe.ETH_ADDRESS,ETHEREUM_NO_PREFIX:/^[a-fA-F0-9]{40}$/,BACKEND:Xe.BACKEND_ADDRESS,CLIENT:Xe.CLIENT_ADDRESS};class ut{toBackendFormat(e){if(!Qe(e))throw new B("Address is required and must be a string","address","REQUIRED");const t=ct(e);if(!/^[a-fA-F0-9]{40}$/.test(t))throw new B(`Invalid Ethereum address format. Expected 40 hex characters (with or without 0x prefix). Got: "${e}"`,"address","INVALID_FORMAT");return`eth|${t.toLowerCase()}`}toEthereumFormat(e){if(!Qe(e))throw new B("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 B(`Invalid backend address format. Expected "eth|{40-hex-characters}" or "eth|0x{40-hex-characters}". Got: "${e}"`,"address","INVALID_FORMAT");const n=t[1]?6:4;return`0x${e.substring(n)}`}normalizeInput(e){if(e){if(e.startsWith("eth|")){if(!lt.BACKEND.test(e))throw new B(`Invalid backend address format: "${e}"`,"address","INVALID_FORMAT");return e}return this.toBackendFormat(e)}}isValid(e){return!!Qe(e)&&(!!lt.ETHEREUM.test(e)||(!!lt.ETHEREUM_NO_PREFIX.test(e)||(!!lt.BACKEND.test(e)||!!lt.CLIENT.test(e))))}assertValid(e,t="address"){if(!this.isValid(e))throw new B(`${t} must be a valid wallet address (Ethereum or backend format)`,t,"INVALID_FORMAT")}detectFormat(e){return Qe(e)?lt.ETHEREUM.test(e)||lt.ETHEREUM_NO_PREFIX.test(e)?"ethereum":lt.BACKEND.test(e)?"backend":lt.CLIENT.test(e)?"client":null:null}normalize(e){if(e)return e.toLowerCase()}extractHex(e){if(e.startsWith("eth|"))return e.substring(4).toLowerCase();if(e.startsWith("0x"))return ct(e).toLowerCase();if(/^[a-fA-F0-9]{40}$/.test(e))return e.toLowerCase();throw new B(`Cannot extract hex from address: "${e}". Expected Ethereum or backend format.`,"address","INVALID_FORMAT")}}const dt=new ut,ht=ct;function gt(e){return dt.toBackendFormat(e)}function pt(e){return dt.toEthereumFormat(e)}function ft(e){return dt.normalizeInput(e)}function mt(e){return dt.isValid(e)}function yt(e,t="address"){dt.assertValid(e,t)}function wt(e){const t="string"==typeof e?e:e.address;return dt.toBackendFormat(t)}function kt(e){return dt.detectFormat(e)}var bt=Object.freeze({__proto__:null,AddressFormatter:ut,assertValidWalletAddress:yt,detectFormat:kt,fromBackendAddressFormat:pt,isValidAddress:mt,normalizeAddressInput:ft,stripHexPrefix:ht,toBackendAddressFormat:gt,toBackendAddressFromEthers:wt});class vt{constructor(e){if(this.wallet=e.wallet,this.messagePrefix=e.messagePrefix||"Create a GalaChain Wallet",void 0!==e.messagePrefix)try{le(e.messagePrefix,"messagePrefix",!1)}catch{throw new v(exports.AuthErrorType.SIGNATURE_FAILED,"Message prefix cannot be empty")}}hasWallet(){return void 0!==this.wallet}setWallet(e){if(void 0!==e){if("object"!=typeof e||!("address"in e))throw new v(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Invalid wallet: must be an ethers Wallet instance or undefined");if(!e.address||"string"!=typeof e.address)throw new v(exports.AuthErrorType.INVALID_ADDRESS,"Wallet address is not available")}this.wallet=e}async generateSignature(){this.validateWallet();try{const e=Date.now(),t=`${this.messagePrefix} ${e}`,n=await this.wallet.signMessage(t);return{message:t,signature:n,address:this.formatAddress(this.wallet.address),timestamp:e}}catch(e){if(e instanceof v)throw e;throw new v(exports.AuthErrorType.SIGNATURE_FAILED,"Failed to generate signature for authentication",S(e)?e:new Error(A(e)))}}getAddress(){return this.validateWallet(),this.formatAddress(this.wallet.address)}getEthereumAddress(){return this.validateWallet(),this.wallet.address}getPrivateKey(){if(this.validateWallet(),!this.wallet.privateKey)throw new v(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Wallet private key not available for @gala-chain signing");return this.wallet.privateKey}formatAddress(e){try{return gt(e)}catch{throw new v(exports.AuthErrorType.INVALID_ADDRESS,`Invalid Ethereum address format: ${e}`)}}async signMessage(e){this.validateWallet();try{return{message:e,signature:await this.wallet.signMessage(e),address:this.wallet.address,timestamp:Date.now()}}catch(e){if(e instanceof v)throw e;throw new v(exports.AuthErrorType.SIGNATURE_FAILED,A(e),S(e)?e:new Error(A(e)))}}async generateAuthHeaders(e,t){this.validateWallet();try{const n=Date.now(),r=`${this.messagePrefix} ${t.toUpperCase()} ${e} ${n}`,i=await this.wallet.signMessage(r);return{"x-signature":i,"x-address":this.formatAddress(this.wallet.address),"x-message":r,"x-timestamp":n.toString()}}catch(e){if(e instanceof v)throw e;throw new v(exports.AuthErrorType.SIGNATURE_FAILED,"Failed to generate authentication headers",S(e)?e:new Error(A(e)))}}async signTypedData(e,t,n){this.validateWallet();try{return await this.wallet.signTypedData(e,t,n)}catch(e){if(e instanceof v)throw e;throw new v(exports.AuthErrorType.SIGNATURE_FAILED,"Failed to sign typed data",S(e)?e:new Error(A(e)))}}async generateCustomSignature(e){if(!Qe(e))throw new v(exports.AuthErrorType.SIGNATURE_FAILED,"Custom message must be a non-empty string");this.validateWallet();try{const t=await this.wallet.signMessage(e);return{message:e,signature:t,address:this.formatAddress(this.wallet.address),timestamp:Date.now()}}catch(e){if(e instanceof v)throw e;throw new v(exports.AuthErrorType.SIGNATURE_FAILED,"Failed to generate custom message signature",S(e)?e:new Error(A(e)))}}validateWallet(){if(!this.wallet)throw new v(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Wallet is required for authentication");if(!this.wallet.address)throw new v(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Wallet address is not available");if(!this.wallet.privateKey&&!this.wallet.signMessage)throw new v(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Wallet must have a private key for signing messages")}}const St={REFRESH_THRESHOLD_MS:3e5,DEFAULT_EXPIRY_S:86400,LOGIN_MESSAGE_PREFIX:"Sign in to Launchpad t:",AUTH_HEADER:"Authorization",BEARER_PREFIX:"Bearer "};class At{constructor(e=St.REFRESH_THRESHOLD_MS){this.tokenState=null,this.refreshThresholdMs=e}setToken(e,t){if(!Qe(e))throw new v(exports.AuthErrorType.SIGNATURE_FAILED,"JWT token must be a non-empty string");if("number"!=typeof t)throw new v(exports.AuthErrorType.SIGNATURE_FAILED,"Token expiration must be a positive finite number (seconds)");if(!isFinite(t))throw new v(exports.AuthErrorType.SIGNATURE_FAILED,"Token expiration must be a positive finite number (seconds)");if(t<=0)throw new v(exports.AuthErrorType.SIGNATURE_FAILED,"Token expiration must be a positive finite number (seconds)");const n=Date.now();this.tokenState={token:e.trim(),issuedAt:n,expiresAt:n+1e3*t}}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 e?`${St.BEARER_PREFIX}${e}`:null}getJwtHeaders(){const e=this.getAuthorizationHeader();if(!e)throw new v(exports.AuthErrorType.WALLET_NOT_CONNECTED,"No JWT token available. Call login() first.");return{[St.AUTH_HEADER]:e}}clear(){this.tokenState=null}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}}}const Tt="/launchpad/upload-image",Et="/launchpad/fetch-pool",It="/launchpad/check-pool",xt="/launchpad/get-graph-data",Ct="/holders",Nt="/launchpad/get-badge/",_t="/launchpad/socials",Bt="/trade/",Pt="/user/profile",Dt="/user/profile",Rt="/user/token-list",Mt="/user/token-hold",Lt="/v1/user/managed-tokens",Ot="/v1/users/referrals/url",Ft="/v1/users/referrals",Ut="/v1/users/referrals/summary",$t="/v1/registered",qt="/live/:tokenName/start",Kt="/live/:tokenName/stop",Gt="/live/:tokenName",Wt="/live/:tokenName/disable",zt="/live/:tokenName/enable",Ht="/live/:tokenName/reset-key",jt="/live/:tokenName/recordings",Vt="/live/:tokenName/recordings/:assetId/download",Xt="/live/:tokenName/recordings/:assetId",Qt="/live/:tokenName/simulcast",Jt="/live/:tokenName/simulcast",Zt="/live/:tokenName/simulcast/:targetId",Yt="/live/global/streaming/status",en="/live/global/streaming/disable",tn="/live/global/streaming/enable",nn="/live/:tokenName/stream/countdown",rn="/live/:tokenName/stream/countdown",on="/live/:tokenName/stream/language",sn="/live/:tokenName/role",an="/live/roles",cn="/live/:tokenName/access",ln="/live/:tokenName/chat",un="/live/:tokenName/chat",dn="/live/:tokenName/chat/:messageId",hn="/live/:tokenName/chat/status",gn="/live/:tokenName/chat/disable",pn="/live/:tokenName/chat/enable",fn="/live/:tokenName/chat/pinned",mn="/live/:tokenName/chat/pin",yn="/live/:tokenName/chat/pin",wn="/live/chat/global/status",kn="/live/chat/global/disable",bn="/live/chat/global/enable",vn="/live/:tokenName/engagement/stats",Sn="/auth/login",An="/auth/refresh",Tn="/auth/session",En="/live/:tokenName/bans",In="/live/:tokenName/bans",xn="/live/:tokenName/bans/:userAddress",Cn="/live/:tokenName/bans/:userAddress",Nn="/live/:tokenName/active-users",_n={CREATE:"/v1/api-keys",LIST:"/v1/api-keys",GET:"/v1/api-keys/:id",UPDATE:"/v1/api-keys/:id",REVOKE:"/v1/api-keys/:id"},Bn="/v1/moderators/invites",Pn="/v1/moderators/invites/claim",Dn="/v1/moderators/tokens",Rn="/v1/moderators/invites",Mn="/v1/moderators/invites/:id",Ln="/v1/moderators/invites/:id/role",On="/v1/moderators/invites/code/:code",Fn={CREATE:"/v1/flags",LIST_GLOBAL:"/v1/flags/global",LIST:"/v1/flags/:tokenName",DISMISS:"/v1/flags/:id/dismiss",ACTION:"/v1/flags/:id/action"},Un="/v1/overseer/invites",$n="/v1/overseer/invites",qn="/v1/overseer/invites/code/:code",Kn="/v1/overseer/invites/claim",Gn="/v1/overseer/invites/:id",Wn="/v1/overseer",zn="/v1/overseer/:address",Hn="/v1/overseer/me",jn="/v1/overseer/summary",Vn="/v1/overseer/users",Xn="/v1/overseer/users/:address",Qn="/v1/overseer/token-bans",Jn="/v1/overseer/token-bans",Zn="/v1/overseer/token-bans/:tokenName",Yn="/v1/overseer/token-bans/:tokenName",er="/token/comment",tr="/token/comment",nr="/token/comment/:commentId",rr="/reactions",ir="/reactions/:messageId/:reactionType",or="/v1/trades",sr="/v1/chat-messages",ar="/v1/chat-messages",cr="/v1/chat-messages/:id",lr="/v1/chat-messages/:id",ur="/v1/comments",dr="/v1/comments",hr="/v1/comments/:id",gr="/v1/comments/:id";function pr(e){return null!=e&&"object"==typeof e&&"data"in e}function fr(e,t,n=!1){const r=!0===e.error,i=n&&!e.data;if(r||i)throw H(e?.message||t)}function mr(e){if(pr(e))return e.data}function yr(e,t="No data found in response"){if(!pr(e))throw H(t);const n=e.data;if(null==n)throw H(t);return n}async function wr(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),X(e,t,n))}}function kr(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),X(e,t,n))}}class br{constructor(e,t,n,r=!1){this.http=e,this.signatureAuth=t,this.jwtAuth=n,this.refreshPromise=null,this.loginPromise=null,this.logger=new We({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 v(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Wallet is required for login. Configure privateKey in SDK.");this.loginPromise=this.performLogin();try{return await this.loginPromise}finally{this.loginPromise=null}}async performLogin(){return wr(async()=>{const e=Date.now(),t=`${St.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();yt(r,"address");const i={address:r,message:t,signature:n.signature};this.logger.debug("Sending login request",{address:r,message:t});const o=await this.http.post(Sn,i),s=this.extractLoginData(o);return this.jwtAuth.setToken(s.accessToken,s.expiresIn),this.logger.debug("Login successful",{address:s.address,expiresIn:s.expiresIn}),s},"SessionAuthService.performLogin",this.logger,(e,t,n)=>{if(e instanceof v)throw e;throw new v(exports.AuthErrorType.SIGNATURE_FAILED,`Login failed: ${A(e)}`,S(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 v(exports.AuthErrorType.WALLET_NOT_CONNECTED,"No token to refresh. Call login() first.");this.refreshPromise=this.performRefresh();try{return await this.refreshPromise}finally{this.refreshPromise=null}}async performRefresh(){return wr(async()=>{this.logger.debug("Refreshing JWT token");const e=await this.http.post(An,{},this.jwtAuth.getJwtHeaders()),t=this.extractLoginData(e);return this.jwtAuth.setToken(t.accessToken,t.expiresIn),this.logger.debug("Token refreshed successfully",{address:t.address,expiresIn:t.expiresIn}),t},"SessionAuthService.performRefresh",this.logger,(e,t,n)=>{if(e instanceof v)throw e;throw new v(exports.AuthErrorType.SIGNATURE_FAILED,`Token refresh failed: ${A(e)}`,S(e)?e:void 0)})}logout(){this.logger.debug("Logging out"),this.jwtAuth.clear()}async getSession(){if(!this.jwtAuth.hasToken())throw new v(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Not authenticated. Call login() first.");return wr(async()=>{const e=await this.http.get(Tn,void 0,this.jwtAuth.getJwtHeaders());return this.extractSessionData(e)},"SessionAuthService.getSession",this.logger,(e,t,n)=>{if(e instanceof v)throw e;throw new v(exports.AuthErrorType.SIGNATURE_FAILED,`Failed to get session: ${A(e)}`,S(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 v(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Not authenticated. Call login() first.");if(this.jwtAuth.isExpired()){this.logger.debug("Token expired - 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 v(exports.AuthErrorType.SIGNATURE_FAILED,A(e)||"Authentication failed");const t=yr(e,"No data in authentication response"),{accessToken:n,expiresIn:r,address:i}=t;if(!Qe(n))throw new v(exports.AuthErrorType.SIGNATURE_FAILED,"Invalid access token in response");if(!r||"number"!=typeof r)throw new v(exports.AuthErrorType.SIGNATURE_FAILED,"Invalid expiration in response");return{accessToken:n,expiresIn:r,address:i}}extractSessionData(e){if(e.error)throw new v(exports.AuthErrorType.SIGNATURE_FAILED,A(e)||"Failed to get session");return yr(e,"No data in session response")}}function vr(e){if(Ze(e)||"object"!=typeof e)return{};const t={};for(const[n,r]of Object.entries(e))Ze(r)||(Qe(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}class Sr{constructor(e,t={}){this.auth=e,this.debug=t.debug??!1,this.logger=new We({debug:this.debug,context:"HttpClient"});const n=t.baseUrl||"https://lpad-backend-dev1.defi.gala.com",r=t.timeout||3e4;this.axios=b(n,r),t.headers&&(this.axios.defaults.headers.common={...this.axios.defaults.headers.common,...t.headers}),this.setupInterceptors()}async request(e){return wr(async()=>{const t={method:e.method,url:e.url,data:e.data,...e.params&&{params:vr(e.params)},...e.headers&&{headers:e.headers},...e.timeout&&{timeout:e.timeout}};e.headers&&this.logger.debug("Custom headers provided:",e.headers),e.data instanceof FormData&&(t.headers&&t.headers["Content-Type"]&&delete t.headers["Content-Type"],this.logger.debug("FormData detected - removing Content-Type header for multipart upload"));const n=e.data instanceof FormData?"[FormData object - multipart/form-data]":e.data;this.logger.debug("Request:",{method:e.method,url:e.url,fullUrl:`${this.axios.defaults.baseURL}${e.url}`,baseURL:this.axios.defaults.baseURL,params:t.params,data:n,isFormData:e.data instanceof FormData,contentType:t.headers?.["Content-Type"]||"not set"});const r=await this.axios.request(t);return this.logger.debug("Response:",{status:r.status,data:r.data}),r.data},`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 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 wr(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)}async signWithGalaChain(e,t,r=n.SigningType.SIGN_TYPED_DATA){const i=this.auth.getPrivateKey(),o=new n.SigningClient(i);return await o.sign(e,t,r)}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 headers being sent:",e.headers),e},e=>Promise.reject(e)),this.responseInterceptorId=this.axios.interceptors.response.use(e=>e,e=>{if(e.response){const t={message:e.response.data?.message||A(e),error:e.response.data?.error,statusCode:e.response.status,details:e.response.data?.details,timestamp:e.response.data?.timestamp,path:e.response.data?.path};e.launchpadError=t,this.logger.error("Backend error:",t)}else e.request?this.logger.error("Network error:",e.message):this.logger.error("Request setup error:",e.message);return Promise.reject(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")}}const Ar="Token name is required and must be a string",Tr=e=>`Could not find vault address for token: ${e}`,Er=r.z.string("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"),Ir=r.z.string("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"),xr=r.z.string("Token description is required").min(1,"Token description is required").max(500,"Token description must be at most 500 characters"),Cr=r.z.string().min(1,"Token name must be at least 1 character").max(50,"Token name must be at most 50 characters"),Nr=r.z.string().min(1,"Search query must be at least 1 character").max(100,"Search query must be at most 100 characters"),_r=r.z.string().min(1,"Full name is required").max(100,"Full name must be at most 100 characters").regex(/^[a-zA-Z\s]+$/,"Full name can only contain letters and spaces"),Br=r.z.string().regex(Xe.BACKEND_ADDRESS,"Address must be in format: eth|[40-hex-chars]"),Pr=r.z.string().regex(Xe.ETH_ADDRESS,"Invalid Ethereum address format"),Dr=r.z.string().refine(e=>Xe.BACKEND_ADDRESS.test(e)||Xe.ETH_ADDRESS.test(e),"Address must be either eth|[40-hex-chars] or 0x[40-hex-chars] format").transform(e=>(new ut).normalizeInput(e)||e),Rr=r.z.string().refine(e=>Xe.BACKEND_ADDRESS.test(e)||/^service\|Token\$Unit\$[A-Z0-9]+\$eth:[0-9a-fA-F]{40}\$launchpad$/.test(e),"Invalid vault address format"),Mr=r.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>De(e,0)>0,"Amount must be greater than zero"),Lr=r.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>De(e,0)>=0,"Amount must be zero or greater"),Or=r.z.string().url("Must be a valid URL").regex(/^https?:\/\//,"URL must start with http:// or https://"),Fr=r.z.string().optional().refine(e=>!e||/^https?:\/\/.+\..+/.test(e),"Must be a valid URL if provided"),Ur=r.z.number().int("Page must be an integer").min(1,"Page must be at least 1").max(1e3,"Page must be at most 1000").default(1);function $r(e=100){return r.z.number().int("Limit must be an integer").min(1,"Limit must be at least 1").max(e,`Limit must be at most ${e}`).default(10)}const qr=$r(100),Kr=$r(20),Gr=$r(20),Wr=r.z.number().int("File size must be an integer").min(1,"File must be at least 1 byte").max(10485760,"File must be at most 10MB"),zr=r.z.string().max(255,"Filename must be at most 255 characters"),Hr=r.z.enum(["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"]),jr=r.z.string().datetime("Must be a valid ISO 8601 date string"),Vr=r.z.number().int("Timestamp must be an integer").min(0,"Timestamp must be non-negative"),Xr=r.z.string().regex(/^0x[a-fA-F0-9]{64}$/,"Private key must be format: 0x + 64 hex characters"),Qr=r.z.string().regex(/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/,"Transaction ID must be in UUID format"),Jr=r.z.string().regex(/^galaconnect-operation-[a-z0-9-]+$/,"Unique key must be format: galaconnect-operation-{unique-id}"),Zr=r.z.object({websiteUrl:Fr,telegramUrl:Fr,twitterUrl:Fr,instagramUrl:Fr,facebookUrl:Fr,redditUrl:Fr,tiktokUrl:Fr}).refine(e=>e.websiteUrl||e.telegramUrl||e.twitterUrl||e.instagramUrl||e.facebookUrl||e.redditUrl||e.tiktokUrl,"At least one social URL (website, telegram, twitter, instagram, facebook, reddit, or tiktok) is required"),Yr=r.z.string().min(1,"Token category must not be empty").default("Unit"),ei=r.z.string().min(1,"Token collection must not be empty").default("Token"),ti=r.z.object({minFeePortion:r.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal string").refine(e=>De(e,0)>=.1,"Minimum fee must be >= 0.1").refine(e=>De(e,0)<=.5,"Minimum fee must be <= 0.5"),maxFeePortion:r.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal string").refine(e=>De(e,0)>=.1,"Maximum fee must be >= 0.1").refine(e=>De(e,0)<=.5,"Maximum fee must be <= 0.5")}).refine(e=>De(e.maxFeePortion,0)>=De(e.minFeePortion,0),{message:"Maximum fee must be >= minimum fee",path:["maxFeePortion"]}),ni=r.z.object({tokenName:Er,tokenSymbol:Ir,tokenDescription:xr,tokenImage:r.z.union([r.z.instanceof(File),r.z.instanceof(Buffer),r.z.string().url("Token image must be a valid URL")]).optional(),preBuyQuantity:Lr.default("0"),websiteUrl:Fr,telegramUrl:Fr,twitterUrl:Fr,instagramUrl:Fr,facebookUrl:Fr,redditUrl:Fr,tiktokUrl:Fr,tokenCategory:Yr,tokenCollection:ei,reverseBondingCurveConfiguration:ti.optional(),privateKey:Xr.optional()}),ri=r.z.object({file:r.z.union([r.z.instanceof(File),r.z.instanceof(Buffer)]),tokenName:Er}),ii=r.z.enum(["RECENT","POPULAR"]),oi=r.z.object({tokenName:Er.optional(),symbol:Ir.optional()}).refine(e=>e.tokenName||e.symbol,"At least one of tokenName or symbol is required"),si=r.z.enum(["NATIVE","MEME"]),ai=r.z.enum(["IN","OUT"]),ci=r.z.object({from:r.z.number().int("From timestamp must be an integer").min(173e6,"From timestamp must be at least 173000000"),to:r.z.number().int("To timestamp must be an integer").min(173e6,"To timestamp must be at least 173000000"),resolution:r.z.number().int("Resolution must be an integer").min(1,"Resolution must be at least 1"),tokenName:Er}),li=r.z.object({tokenName:Er,slippageToleranceFactor:r.z.number().min(0).max(1).optional(),maxAcceptableReverseBondingCurveFeeSlippageFactor:r.z.number().min(0).max(1).optional(),privateKey:Xr.optional()}),ui=[".png",".jpg",".jpeg",".gif",".webp",".svg"],di=r.z.object({file:r.z.union([r.z.instanceof(File),r.z.instanceof(Buffer)]),name:zr,size:Wr,type:Hr}),hi=r.z.instanceof(File).refine(e=>e.size>=1&&e.size<=10485760,"File size must be between 1 byte and 10MB").refine(e=>["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"].includes(e.type),"File must be a valid image type (PNG, JPG, JPEG, GIF, WebP, or SVG)").refine(e=>e.name.length<=255,"Filename must be at most 255 characters"),gi=r.z.instanceof(Buffer).refine(e=>e.length>=1&&e.length<=10485760,"Buffer size must be between 1 byte and 10MB"),pi=r.z.union([hi,gi]),fi=r.z.enum([".png",".jpg",".jpeg",".gif",".webp",".svg"]),mi=zr.refine(e=>{const t=e.slice(e.lastIndexOf(".")).toLowerCase();return ui.includes(t)},`Filename must end with one of: ${ui.join(", ")}`),yi=r.z.object({page:Ur,limit:qr}),wi=r.z.object({page:Ur,limit:Kr}),ki=r.z.object({page:Ur,limit:Gr}),bi=yi.extend({type:r.z.enum(["RECENT","POPULAR"]).optional(),tokenName:r.z.string().min(1).max(50).optional(),search:r.z.string().min(1).max(100).optional()}),vi=wi.extend({tokenName:r.z.string().min(1).max(50).optional(),search:r.z.string().min(1).max(100).optional()}),Si=ki.extend({tradeType:r.z.enum(["BUY","SELL"]).optional(),tokenName:r.z.string().min(1).max(50).optional(),userAddress:r.z.string().regex(/^(0x[a-fA-F0-9]{40}|eth\|[a-fA-F0-9]{40})$/).optional(),startDate:r.z.string().datetime().optional(),endDate:r.z.string().datetime().optional(),sortOrder:r.z.enum(["ASC","DESC"]).default("DESC")}),Ai=r.z.object({page:r.z.number().int().min(1),limit:r.z.number().int().min(1),total:r.z.number().int().min(0),totalPages:r.z.number().int().min(0),hasNext:r.z.boolean(),hasPrevious:r.z.boolean()});const Ti=r.z.enum(["all","DEFI","ASSET"]),Ei=wi.extend({type:Ti.optional(),address:Dr.optional(),search:Nr.optional(),tokenName:Cr.optional()}),Ii=r.z.object({address:Dr.optional(),refresh:r.z.boolean().optional()}),xi=r.z.object({profileImage:r.z.string(),fullName:_r,address:Dr,privateKey:Xr.optional()}),Ci=r.z.object({file:r.z.union([r.z.instanceof(File),r.z.instanceof(Buffer)]),address:Dr.optional(),privateKey:Xr.optional()}),Ni=r.z.object({created:r.z.number(),createdBy:r.z.string(),expires:r.z.number(),instanceId:r.z.string(),lockAuthority:r.z.string(),name:r.z.string(),quantity:r.z.string(),vestingPeriodStart:r.z.number()}),_i=r.z.object({address:Dr,tokenId:r.z.union([r.z.string(),r.z.object({collection:r.z.string(),category:r.z.string(),type:r.z.string(),additionalKey:r.z.string()}),r.z.object({collection:r.z.string(),category:r.z.string(),type:r.z.string(),additionalKey:r.z.string(),instance:r.z.string()})]).optional(),tokenName:Cr.optional(),withExpired:r.z.boolean().optional()}).refine(e=>void 0!==e.tokenId||void 0!==e.tokenName,"At least one token identifier (tokenId or tokenName) is required"),Bi=r.z.enum(["buy","sell"]),Pi=r.z.enum(["BUY","SELL"]),Di=r.z.object({tradeType:Bi,tokenAmount:Mr,vaultAddress:Rr,userAddress:Dr,slippageTolerance:Mr.optional(),deadline:r.z.number().int().positive().optional()}),Ri=r.z.object({tokenSymbol:Ir,nativeTokenQuantity:Mr,expectedToken:Mr,maxAcceptableReverseBondingCurveFee:Lr.default("0").optional()}),Mi=r.z.object({tokenSymbol:Ir,tokenQuantity:Mr,expectedNativeToken:Mr,maxAcceptableReverseBondingCurveFee:Lr.default("0").optional()}),Li=ki.extend({tokenName:Cr.optional()}),Oi=r.z.object({page:r.z.number().int().min(1).max(1e3).default(1).optional(),limit:r.z.number().int().min(1).max(20).default(10).optional()}),Fi=r.z.enum(["NATIVE","MEME"]),Ui=r.z.enum(["IN","OUT"]),$i=r.z.object({type:Fi,method:Ui,vaultAddress:Rr,amount:Mr}),qi=r.z.object({nativeTokenQuantity:Mr}),Ki=r.z.object({vaultAddress:Rr}),Gi=r.z.object({minFeePortion:Mr,maxFeePortion:Mr});function Wi(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 zi=Wi(Er),Hi=Wi(Ir),ji=Wi(xr),Vi=Wi(Dr),Xi=Wi(Rr),Qi=Wi(Mr),Ji=Wi(_r),Zi=Wi(Nr),Yi=Wi(Cr),eo=Wi(ni),to=Wi(Zr),no=Wi(ri),ro=Wi(oi),io=Wi(Ei),oo=Wi(Ii),so=Wi(xi),ao=Wi(Ci),co=Wi(_i),lo=Wi(Di),uo=Wi(Ri),ho=Wi(Mi),go=Wi(Li),po=Wi(Oi),fo=Wi($i),mo=Wi(qi),yo=Wi(Ki);function wo(e,t="0"){return Oe(e,t)}function ko(e,t){return void 0!==t?wo(e).toFixed(t):wo(e).toFixed()}function bo(e,t=.01){const n=wo(e),r=new i(1).minus(t);return n.multipliedBy(r)}function vo(e=.01){return new i(1).minus(e)}function So(e=.01){return new i(1).plus(e)}function Ao(e){const t=wo(e),n=Math.log(1.0001),r=t.toNumber();return Math.log(r)/n}function To(e,t=!1){const n=wo(e),r=new i(1).dividedBy(n);return t?r.toFixed():r}function Eo(){return new i(2).pow(96)}function Io(e,t){return i.min(wo(e),wo(t))}function xo(e,t){return i.max(wo(e),wo(t))}function Co(e){return wo(e).isZero()}function No(e){return wo(e).isGreaterThan(0)}function _o(e){return wo(e).isLessThan(0)}function Bo(e,t){return wo(e).isLessThan(wo(t))}function Po(e,t){return wo(e).multipliedBy(t).dividedBy(100)}function Do(...e){e.forEach(e=>{if(e.isNaN())throw ee("value","NaN");if(!e.isFinite())throw Z("value","finite");if(e.isLessThanOrEqualTo(0))throw J("value","0",e.toString())})}function Ro(...e){e.forEach(e=>{if(e.isNaN())throw ee("value","NaN");if(!e.isFinite())throw Z("value","finite");if(e.isLessThan(0))throw J("value","0",e.toString())})}function Mo(e,t,n){if(e.isNaN())throw ee(t,"NaN");if(!e.isFinite())throw Z(t,"finite");if(e.isLessThanOrEqualTo(0))throw J(t,"0",e.toString())}function Lo(e,t,n="0"){const r=wo(t);return Co(r)?wo(n):wo(e).dividedBy(r)}function Oo(e,t){return Math.floor(e/t)*t}class Fo{validate(e,t={}){const{allowZero:n=!0,minimum:r,maximum:i,maxDecimals:o=Fo.MAX_DECIMAL_PLACES,fieldName:s="amount"}=t;if(!Qe(e))throw new B(`${s} cannot be empty or whitespace-only. Provide a valid numeric string.`,s,"INVALID_NUMERIC_STRING");if(/[eE]/.test(e))throw new B(`${s} cannot use scientific notation. Use standard decimal format (e.g., "1000" instead of "1e3").`,s,"INVALID_NUMERIC_STRING");const a=De(e,NaN);if(isNaN(a))throw new B(`${s} must be a valid numeric string. Received: "${e}"`,s,"INVALID_NUMERIC_STRING");if(!isFinite(a))throw new B(`${s} must be a finite number. Cannot be Infinity or -Infinity.`,s,"INVALID_NUMERIC_STRING");if(a<0)throw new B(`${s} must be non-negative. Received: "${e}"`,s,"INVALID_NUMERIC_STRING");if(!n&&0===a)throw new B(`${s} must be greater than zero. Received: "${e}"`,s,"INVALID_NUMERIC_STRING");const c=wo(e),l=c.decimalPlaces()??0;if(l>o)throw new B(`${s} cannot exceed ${o} decimal places. Received: ${l} decimal places`,s,"PRECISION_EXCEEDED");if(void 0!==r&&Bo(c,r))throw new B(`${s} must be at least ${r}. Received: "${e}"`,s,"BELOW_MINIMUM");if(void 0!==i&&(u=i,wo(c).isGreaterThan(wo(u))))throw new B(`${s} cannot exceed ${i}. Received: "${e}"`,s,"EXCEEDS_MAXIMUM");var u}parseAmount(e,t="0"){return wo(e,t)}isValid(e,t={}){try{return e?(this.validate(e,t),!0):!1!==t.allowZero}catch{return!1}}formatAmount(e,t){return ko(e,t)}clampAmount(e,t,n){const r=wo(e),i=wo(t),o=wo(n);return function(e,t,n){const r=wo(e),i=wo(t),o=wo(n);return r.isGreaterThanOrEqualTo(i)&&r.isLessThanOrEqualTo(o)}(r,i,o)?ko(r):Bo(r,i)?ko(i):ko(o)}}function Uo(e,t){throw new B(e.join("; "),t,"VALIDATION_ERROR")}function $o(e){const t=zi(e);!t.success&&t.errors&&Uo(t.errors,"tokenName")}function qo(e){const t=ro(e);!t.success&&t.errors&&Uo(t.errors,"options")}function Ko(e){const t=ci.safeParse(e);var n;t.success||Uo((n=t.error.issues,Array.isArray(n)?n.map(e=>e&&"object"==typeof e&&"message"in e&&"string"==typeof e.message?e.message:String(e)).filter(Boolean):[]),"options")}function Go(e,t,n=!0){Wo.validate(e,{fieldName:t,allowZero:n})}Fo.MAX_DECIMAL_PLACES=18,Fo.MIN_POSITIVE="0.00000000000000001";const Wo=new Fo;const zo={DEFAULT_PAGE:1,DEFAULT_LIMIT:10,BACKEND_MAX_PAGE_SIZE:20,SAFETY_MAX_PAGES:100};function Ho(e,t){return ae(e,"page"),ae(t,"limit"),(e-1)*t}function jo(e,t=1){return Math.max(t,Math.ceil(e||t))}function Vo(e,t=1,n=zo.BACKEND_MAX_PAGE_SIZE){return Math.max(t,Math.min(n,Math.ceil(e||t)))}function Xo(e,t){if("number"!=typeof e||!Number.isInteger(e))throw Y("total","a non-negative integer",e);if(e<0)throw Q("total",0,1/0,e);if("number"!=typeof t||!Number.isInteger(t))throw Y("limit","a non-negative integer",t);if(t<0)throw Q("limit",0,1/0,t);return 0===t?1:0===e?0:Math.ceil(e/t)}function Qo(e,t,n){if("number"!=typeof e||!Number.isInteger(e))throw Y("offset","a non-negative integer",e);if(e<0)throw Q("offset",0,1/0,e);return e+t<n}function Jo(e,t){if(!e)return[];if(Array.isArray(e))return e;const n=e[t];return Array.isArray(n)?n:[]}function Zo(e,t){const n=e,r=Le(String(n.page),t.page),i=Le(String(n.limit),t.limit),o=n.data,s=o?.meta,a=Le(String(o?.count),0),c=Le(String(s?.totalItems),a),l=Le(String(n.total),c);return{page:r,limit:i,total:l,totalPages:Xo(l,i)}}async function Yo(e,t={}){const{maxPages:n=1e4,logger:r,pageSize:i=20,concurrency:o=1,startPage:s=1}=t,a=[];let c=s;const l=s+n-1;let u=!0,d=0;if(o<=1)for(;u&&c<=l;){r&&r.debug(`Auto-pagination: fetching page ${c} with limit ${i}`);const t=await e(c,i);if(!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: ${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=${o}`);u&&c<=l;){const t=[];for(let e=0;e<o&&c+e<=l;e++)t.push(c+e);r&&r.debug(`Auto-pagination: fetching pages ${t.join(", ")} concurrently`);const n=t.map(t=>e(t,i).catch(e=>{if(400===e?.launchpadError?.statusCode||400===e?.status)return r&&r.debug(`Auto-pagination: page ${t} returned 400 (end of pagination)`,{statusCode:e?.launchpadError?.statusCode??e?.status}),{items:[],total:0,totalPages:0,page:t,limit:i,hasNext:!1,hasPrevious:!1};throw e})),s=await Promise.all(n);for(const e of s){if(!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}}async function es(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();if(null==t)throw new B(`${n}: No response from server`,"response","NO_RESPONSE");if(fr(t,n,!0),i&&r&&r.debug(`${n}: completed successfully`),void 0===t.data)throw new B(`${n}: No data returned from API`,"data","NO_DATA");return t.data}catch(e){throw r&&r.error(n,{error:e}),e}}async function ts(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 ns(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();if(null==t)throw new B(`${n}: No response from server`,"response","NO_RESPONSE");return fr(t,n,!0),i&&r&&r.debug(`${n}: completed successfully`),t}catch(e){throw r&&r.error(n,{error:e}),e}}function rs(e){return e.trim().toLowerCase()}function is(e){return e.trim().toUpperCase()}function os(e){return e.trim().toUpperCase()}function ss(e,t,n){if(!Ze(e)){if("string"!=typeof e)throw Y(t,"a string",e,t);if(e.length>n)throw new B(`${t} must be at most ${n} characters`,t,_.TOO_LARGE)}}function as(e,t){ae(e,t)}function cs(e,t){if(Ze(e))return;let n;if(e instanceof Date)n=e;else if("string"==typeof e)n=new Date(e);else{if("number"!=typeof e)throw Y(t,"a date",e,t);n=new Date(e)}if(isNaN(n.getTime()))throw new B(`${t} must be a valid date`,t,_.INVALID_FORMAT)}function ls(e,t,n){try{ae(e,t)}catch{throw function(e,t,n,r="OPERATION_FAILED"){return new B(`${e} failed: ${t}`,n,r)}(n,"must be a positive integer",t)}}function us(e,t,n="status"){void 0!==e&&function(e,t,n){const r=Object.values(t);if(!r.includes(e))throw new B(`${n} must be one of: ${r.join(", ")}`,n,_.INVALID_FORMAT)}(e,t,n)}class ds{constructor(e,t=!1,n){this.http=e,this.logger=new We({debug:t,context:this.constructor.name}),this.jwtAuth=n}setJwtAuth(e){this.jwtAuth=e}getJwtHeaders(){if(!this.jwtAuth){if("test"===process.env.NODE_ENV&&!this.isCalledFromUserCode())return{};throw new D("JWT authentication required. Call sdk.login() first.")}return this.jwtAuth.getJwtHeaders()}isCalledFromUserCode(){const e=T(new Error)||"";return!(!e.includes("expect")&&!e.includes("jest"))||!(!e.includes("tests/")&&!e.includes(".test.ts"))}validatePositiveInteger(e,t,n){ls(e,t,n)}}class hs{constructor(e=!1,t){this.logger=t||new We({debug:e,context:this.constructor.name})}}function gs(e,t){return"string"==typeof e[t]}function ps(e,t){return void 0===e[t]||"string"==typeof e[t]}function fs(e,t){return void 0===e[t]||"number"==typeof e[t]}function ms(e){if(!e||"object"!=typeof e)return!1;const t=e;return gs(t,"tokenName")&&fs(t,"from")&&fs(t,"to")&&fs(t,"resolution")}class ys extends ds{constructor(e,t=!1){super(e,t)}buildPoolFilters(e){return{...!Ze(e.search)&&{search:e.search},...!Ze(e.tokenName)&&{tokenName:e.tokenName},...!Ze(e.type)&&{type:e.type},...!Ze(e.hasUpcomingShows)&&{hasUpcomingShows:e.hasUpcomingShows},...!Ze(e.language)&&{language:e.language},...!Ze(e.recentlyStreamed)&&{recentlyStreamed:e.recentlyStreamed},...!Ze(e.hasRecordings)&&{hasRecordings:e.hasRecordings},...!Ze(e.streamStatus)&&{streamStatus:e.streamStatus}}}async fetchSinglePage(e){const t={page:e.page.toString(),limit:e.limit.toString()};Ze(e.type)||(t.type=e.type),Ze(e.tokenName)||(t.tokenName=e.tokenName),Ze(e.search)||(t.search=e.search),Ze(e.hasUpcomingShows)||(t.hasUpcomingShows=e.hasUpcomingShows.toString()),Ze(e.language)||(t.language=e.language),Ze(e.recentlyStreamed)||(t.recentlyStreamed=e.recentlyStreamed.toString()),Ze(e.hasRecordings)||(t.hasRecordings=e.hasRecordings.toString()),Ze(e.streamStatus)||(t.streamStatus=e.streamStatus);const n=vr(t),r=mr(await ns(()=>this.http.get(Et,n),{errorContext:"Failed to fetch pools"})),i=function(e){if(!e)return[];let t=[];if(e.tokens)if(Array.isArray(e.tokens))t=e.tokens.map(e=>({...e,createdAt:e.created_at||e.createdAt||""}));else{const n=e.tokens;t=[{...n,createdAt:n.created_at||n.createdAt||""}]}else e.pools&&Array.isArray(e.pools)&&(t=e.pools.map(e=>({...e,createdAt:e.created_at||e.createdAt||""})));return t}(r),o=r.count??r.total??0,s=Xo(o,e.limit);return{items:i,meta:{page:e.page,limit:e.limit,total:o,totalPages:s}}}async fetchPageForAutoPaginate(e,t,n){const r=await this.fetchSinglePage({...e,page:t,limit:n}),i=Ho(t,n),o=r.items.length===n&&Qo(i,n,r.meta.total);return{items:r.items,page:t,limit:n,total:r.meta.total,totalPages:r.meta.totalPages,hasNext:o,hasPrevious:t>1}}async fetchPools(e={}){const t=e.page||zo.DEFAULT_PAGE,n=e.limit??zo.DEFAULT_LIMIT;0!==n&&Ye(t,n),Qe(e.tokenName)&&$o(e.tokenName);const r=e.type?{recent:"RECENT",popular:"POPULAR",recordings:"RECORDINGS",seconds_streamed:"SECONDS_STREAMED"}[e.type]:void 0,i=e.streamStatus?{idle:"IDLE",active:"ACTIVE",disabled:"DISABLED"}[e.streamStatus]:void 0,o=this.buildPoolFilters({search:e.search,tokenName:e.tokenName,type:r,hasUpcomingShows:e.hasUpcomingShows,language:e.language,recentlyStreamed:e.recentlyStreamed,hasRecordings:e.hasRecordings,streamStatus:i});if(n>0&&n<=20){const e=await this.fetchSinglePage({...o,page:t,limit:n});return{items:e.items,meta:{page:t,limit:n,total:e.meta.total,totalPages:e.meta.totalPages}}}if(0===n){const e=zo.BACKEND_MAX_PAGE_SIZE,t=await Yo((e,t)=>this.fetchPageForAutoPaginate(o,e,t),{pageSize:e,concurrency:5,logger:this.logger});return{items:t.items,meta:{page:1,limit:t.items.length,total:t.total||t.items.length,totalPages:1}}}const s=zo.BACKEND_MAX_PAGE_SIZE,a=Xo(n,s),c=await Yo((e,t)=>this.fetchPageForAutoPaginate(o,e,t),{startPage:t,maxPages:a,pageSize:s,concurrency:5,logger:this.logger}),l=c.items.slice(0,n),u=Xo(c.total,s);return{items:l,meta:{page:t,limit:n,total:c.total,totalPages:u}}}async fetchAllPools(e){return this.fetchPools({...e,limit:0})}async checkPool(e){qo(e),Qe(e.tokenName)&&$o(e.tokenName);const t=vr(e),n=await es(()=>this.http.get(It,t),{errorContext:"Failed to check pool"});return Qe(e.symbol)?n?.isSymbolExist??!1:Qe(e.tokenName)?n?.isNameExist??!1:n?.exists??!1}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(!ms(e))throw new B("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($o(t),!n||!r||!i)throw new B("Graph options (from, to, resolution) are required","options","MISSING_GRAPH_OPTIONS");const o={tokenName:t,from:n,to:r,resolution:i};Ko(o);const s=vr(o);return{dataPoints:await es(()=>this.http.get(xt,s),{errorContext:"Failed to fetch graph data"})}}async fetchTokenDistribution(e){if(!e)throw W("tokenName","Token name");let t;$o(e);try{t=await ns(()=>this.http.get(`${Ct}/${e}`),{errorContext:"Failed to fetch token distribution"})}catch(t){if(I(t)&&500===t.response?.status)throw H(`Token distribution data temporarily unavailable for ${e}. This is a backend issue - please try again later.`,500);throw t}const n=mr(t);if(!Array.isArray(n))throw H("Invalid API response: expected array of holders",t.status);for(const e of n){if(!e.owner||"string"!=typeof e.owner)throw H("Invalid holder data: missing or invalid owner field",t.status);if(!e.quantity||"string"!=typeof e.quantity)throw H("Invalid holder data: missing or invalid quantity field",t.status);const n=De(e.quantity,NaN);if(isNaN(n)||!isFinite(n))throw H(`Invalid holder quantity: "${e.quantity}"`,t.status)}const r=n.reduce((e,t)=>e.plus(t.quantity),wo(0));return{holders:n.map(e=>{const t=Lo(wo(e.quantity),r,wo(0)).multipliedBy(100).toNumber();return{address:e.owner,balance:e.quantity,percentage:t}}),totalSupply:r.toFixed(),totalHolders:n.length,lastUpdated:new Date}}async fetchUserHolderContext(e,t){if(!e)throw W("tokenName","Token name");if(!t)throw W("userAddress","User address");return $o(e),es(()=>this.http.get(`${Ct}/${e}`,{userAddress:t}),{errorContext:"Failed to fetch user holder context"})}async fetchTokenBadges(e){if(!e)throw W("tokenName","Token name");$o(e);const t=await es(()=>this.http.get(Nt,{tokenName:e}),{errorContext:"Failed to fetch token badges"});return{volumeBadges:t.volumeBadge||[],engagementBadges:t.engagementBadge||[]}}async hasTokenBadge(e){const{tokenName:t,badgeType:n,badgeName:r}=e;try{const e=await this.fetchTokenBadges(t);if(!e)return!1;const i=("volume"===n?e.volumeBadges:e.engagementBadges).find(e=>e.badgeName===r);return i?.isActive||!1}catch{return!1}}async resolveTokenNameToVault(e){try{const t=await this.fetchPools({tokenName:e});if(t.items&&Array.isArray(t.items)&&t.items.length>0)return t.items[0].vaultAddress||null;if(t.items&&"object"==typeof t.items){const e=t.items.tokens;return e?.vaultAddress||null}return null}catch{return null}}}function ws(e,t,n){return function(e,t={}){const{stringifyFields:n=[],optionalFields:r=[],fieldMappings:i={}}=t,o={};for(const[t,s]of Object.entries(e)){const e=t;if(r.includes(e)){if(void 0===s)continue;if("string"==typeof s&&!Qe(s))continue}const a=i[e],c=a?String(a):t;n.includes(e)?o[c]=String(s):o[c]=s}return vr(o)}({tokenName:e,page:t,limit:n},{stringifyFields:["page","limit"]})}const ks={PAGINATION:ye,TOKEN_NAME:pe,USER_ADDRESS:be};function bs(e){if(!e.tokenName&&!e.userAddress)throw new B("At least one of tokenName or userAddress is required","options","MISSING_FILTER");if(void 0!==e.tokenName){if(!Qe(e.tokenName))throw Y("tokenName","a non-empty string",typeof e.tokenName);if(e.tokenName.length>ks.TOKEN_NAME.MAX_LENGTH)throw Z("tokenName",ks.TOKEN_NAME.MAX_LENGTH,e.tokenName.length)}if(void 0!==e.userAddress){if(!Qe(e.userAddress))throw Y("userAddress","a non-empty string",typeof e.userAddress);if(e.userAddress.length>ks.USER_ADDRESS.MAX_LENGTH)throw Z("userAddress",ks.USER_ADDRESS.MAX_LENGTH,e.userAddress.length)}if(Ye(e.page,e.limit,ks.PAGINATION.MAX_LIMIT),void 0!==e.txnType&&"BUY"!==e.txnType&&"SELL"!==e.txnType)throw z("txnType",'"BUY" or "SELL"');if(void 0!==e.startDate){if(!Qe(e.startDate))throw Y("startDate","a non-empty string",typeof e.startDate);if(isNaN(Date.parse(e.startDate)))throw z("startDate","a valid ISO 8601 date")}if(void 0!==e.endDate){if(!Qe(e.endDate))throw Y("endDate","a non-empty string",typeof e.endDate);if(isNaN(Date.parse(e.endDate)))throw z("endDate","a valid ISO 8601 date")}if(void 0!==e.minAmount)try{oe(e.minAmount,0,Number.MAX_SAFE_INTEGER,"minAmount")}catch{throw z("minAmount","a non-negative number")}if(void 0!==e.maxAmount)try{oe(e.maxAmount,0,Number.MAX_SAFE_INTEGER,"maxAmount")}catch{throw z("maxAmount","a non-negative number")}void 0!==e.minAmount&&void 0!==e.maxAmount&&ce(e.minAmount,e.maxAmount,"amountRange")}class vs extends ds{constructor(e,t=!1){super(e,t)}async fetchTrades(e){if(!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return gs(t,"tokenName")&&(void 0===t.tradeType||"buy"===t.tradeType||"sell"===t.tradeType)&&ps(t,"userAddress")&&fs(t,"page")&&fs(t,"limit")}(e))throw new B("Invalid options provided. Expected { tokenName: string, tradeType?: string, userAddress?: string, page?: number, limit?: number, startDate?: Date, endDate?: Date, sortOrder?: string }","options","INVALID_OPTIONS");const{tokenName:t,tradeType:n,userAddress:r,page:i=zo.DEFAULT_PAGE,limit:o=zo.DEFAULT_LIMIT,startDate:s,endDate:a,sortOrder:c}=e;if(!Qe(t))throw W("tokenName","Token name");Ye(i,o,me);const l=ws(t,i,o),u=await this.http.get(Bt,l);if(!u)throw new B("No response from trade service","response","NO_RESPONSE");return{items:Jo(mr(u),"trades"),meta:Zo(u,{page:i,limit:o})}}buildTradesQueryParams(e){const t={};if(e.tokenName&&(t.tokenName=rs(e.tokenName)),e.userAddress&&(t.userAddress=e.userAddress),void 0!==e.page&&(t.page=String(e.page)),void 0!==e.limit){const n=Vo(e.limit,1,ks.PAGINATION.MAX_LIMIT);t.limit=String(n)}return e.txnType&&(t.txnType=e.txnType),e.startDate&&(t.startDate=e.startDate),e.endDate&&(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){bs(e);const t=this.buildTradesQueryParams(e);return es(()=>this.http.get(or,t),{errorContext:"Failed to fetch trades"})}}function Ss(e,t){const n={};return e.page&&(n.page=String(e.page)),e.limit&&(n.limit=String(Math.min(e.limit,t))),n}function As(e,t=e.length){return{page:1,limit:e.length,total:t,totalPages:e.length>0?Xo(t,e.length):1}}function Ts(e,t,n){for(const r of n){const n=t[r];null!=n&&""!==n&&(e[r]=String(n))}return e}function Es(e,t,n=1){if(!e)return null;if("string"!=typeof e)return null;const r=e.trim();return r.length<n?null:r}function Is(e,t){return e.toLowerCase()===t.toLowerCase()}function xs(e,t){return e.toLowerCase().includes(t.toLowerCase())}function Cs(e,t,n,r){return e===n&&t===r||e===r&&t===n}function Ns(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 _s(e){return e.startsWith("0x")?e.slice(2):e}function Bs(e,t="image",n){const r=new FormData;if("undefined"!=typeof File&&e instanceof File)r.append(t,e);else{if(!Buffer.isBuffer(e))throw z("file","a File object (browser) or Buffer (Node.js)");{const i=new Blob([e],{type:"image/png"});r.append(t,i,n)}}return r}function Ps(e){return!!Qe(e)&&ke.PATTERN.test(e)}et({ALL:"all",DEFI:"DEFI",ASSET:"ASSET"});class Ds extends ds{constructor(e,t,n=!1){super(e,n,t)}async fetchProfile(e){const t=e??this.http.getAddress();if(!t||!Ps(t))throw z("address","eth|[40-hex-chars]","Address");const n={userAddress:t},r=await this.http.get(Pt,n);if(!r)throw new B("No response from user service","response","NO_RESPONSE");return r}async updateProfile(e){this.validateUpdateProfileData(e);let t=e.profileImage;if(!Qe(t))try{const n=await this.fetchProfile(e.address);t=n.data?.profileImage||""}catch{t=""}const n={profileImage:t,fullName:e.fullName,userAddress:e.address};await es(()=>this.http.put(Dt,n,this.getJwtHeaders()),{errorContext:"Profile update failed"})}async uploadProfileImage(e){this.validateUploadProfileImageOptions(e);const t=e.address??this.http.getAddress();if(!t)throw new B("Wallet address not available - wallet not configured","address","NO_WALLET");try{const n=`profile-image-${t}.png`,r=Bs(e.file,"image",n),i=await es(()=>this.http.request({method:"POST",url:`${Tt}?tokenName=${encodeURIComponent(t)}`,data:r,headers:this.getJwtHeaders()}),{errorContext:"Image upload failed"});return"string"==typeof i?i:""}catch(e){if(e instanceof B||e instanceof D)throw e;throw new B(`Profile image upload failed: ${A(e)}`,"file","UPLOAD_FAILED")}}async fetchTokenList(e){return this.buildFetchRequest(Rt,e,{includeType:!0,errorMessage:"Failed to fetch token list"})}async fetchTokensHeld(e){return this.buildFetchRequest(Mt,e,{includeType:!1,errorMessage:"Failed to fetch tokens held"})}async fetchTokensCreated(e={}){const{page:t=zo.DEFAULT_PAGE,limit:n=zo.DEFAULT_LIMIT,search:r,tokenName:i}=e,o=this.http.getAddress();if(!o)throw new B("Wallet address not available - wallet not configured","address","NO_WALLET");const s={type:"DEFI",address:o,page:t,limit:n};return void 0!==r&&(s.search=r),void 0!==i&&(s.tokenName=i),this.fetchTokenList(s)}async getManagedTokens(e={}){const t=jo(e.page),n=Vo(e.limit);Ye(t,n,me);const r={};void 0!==t&&(r.page=t),void 0!==n&&(r.limit=n);const i=Ss(r,me);return es(()=>this.http.get(Lt,{...i,...this.getJwtHeaders()}),{errorContext:"Failed to fetch managed tokens"})}async buildFetchRequest(e,t,n){this.validateGetTokenListOptions(t);const r={};void 0!==t.page&&(r.page=t.page),void 0!==t.limit&&(r.limit=t.limit);const i=Ss(r,me);Ts(i,t,["address","search","tokenName"]),n.includeType&&(i.type="all"!==t.type&&t.type?t.type:"DEFI");const o=await ns(()=>this.http.get(e,i),{errorContext:n.errorMessage}),s=Jo(mr(o),"token"),a=Zo(o,{page:t.page||zo.DEFAULT_PAGE,limit:t.limit||zo.DEFAULT_LIMIT}),c=(l=a.page,u=a.totalPages,{hasNext:l<u,hasPrevious:l>1});var l,u;return{tokens:s,...a,...c}}validateGetTokenListOptions(e){if(Ye(e.page,e.limit,me),void 0!==e.address&&!Ps(e.address))throw z("address","eth|[40-hex-chars]","Address");const t=Es(e.search);if(null!==t&&!(Qe(n=t)&&n.length>=Ne&&n.length<=_e))throw Q("search",Ne,_e,t.length,"Search query");var n;const r=Es(e.tokenName);if(null!==r&&!(Qe(i=r)&&i.length>=pe.MIN_LENGTH&&i.length<=pe.MAX_LENGTH))throw Q("tokenName",pe.MIN_LENGTH,pe.MAX_LENGTH,r.length,"Token name");var i}validateUpdateProfileData(e){if(!Ps(e.address))throw z("address","eth|[40-hex-chars]","Address");if(!(Qe(t=e.fullName)&&t.length>=Be.FULL_NAME.MIN_LENGTH&&t.length<=Be.FULL_NAME.MAX_LENGTH&&Be.FULL_NAME.ALPHABETS_ONLY_PATTERN.test(t)))throw Q("fullName",Be.FULL_NAME.MIN_LENGTH,Be.FULL_NAME.MAX_LENGTH,e.fullName.length,"Full name");var t}validateUploadProfileImageOptions(e){if(e.address&&!Ps(e.address))throw z("address","eth|[40-hex-chars]","Address")}}class Rs extends Error{constructor(e,t,n){super(e),this.filename=t,this.mimeType=n,this.name="FileValidationError"}}function Ms(e,t,n){if(!e)throw new Rs("File is required",t,n);if("undefined"!=typeof File&&e instanceof File){const t=hi.safeParse(e);if(!t.success){const n=t.error.issues.map(e=>e.message).join("; ");throw new Rs(n,e.name,e.type)}return}if(Buffer.isBuffer(e)){if(!t)throw new Rs("Filename is required when uploading Buffer objects",t,n);const r=gi.safeParse(e);if(!r.success){const e=r.error.issues.map(e=>e.message).join("; ");throw new Rs(e,t,n)}try{se(t,255,"filename")}catch(e){throw new Rs(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 Rs(`Invalid file type "${n}" is not allowed. Allowed types: ${i.join(", ")}`,t,n);const o=function(e){if(!e)return"";const t=e.lastIndexOf(".");if(-1===t)return"";return e.substring(t).toLowerCase()}(t),s=[".png",".jpg",".jpeg",".gif",".webp",".svg"];if(!s.includes(o))throw new Rs(`File extension "${o}" is not allowed. Allowed extensions: ${s.join(", ")}`,t,n);const a=function(e){switch(e.toLowerCase()){case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";case".gif":return"image/gif";case".webp":return"image/webp";case".svg":return"image/svg+xml";default:return"application/octet-stream"}}(o);if(a!==n&&"application/octet-stream"!==a)throw new Rs(`File extension "${o}" does not match MIME type "${n}"`,t,n);return}throw new Rs("File must be a File object (browser) or Buffer (Node.js)",t,n)}class Ls extends ds{constructor(e,t,n=!1){super(e,n,t)}async uploadImageByTokenName(e){const{tokenName:t,options:n}=e;$o(t);const r=`${t}.png`;Ms(n.file,r,"image/png");try{const e=`${n.tokenName??t}.png`,r=Bs(n.file,"image",e),i=await es(()=>this.http.request({method:"POST",url:`${Tt}?tokenName=${encodeURIComponent(n.tokenName??t)}`,data:r,headers:this.getJwtHeaders()}),{errorContext:"Image upload failed"});return"string"==typeof i?i:""}catch(e){if(e instanceof D)throw e;if(S(e)&&A(e).includes("FormData"))throw j("File upload failed: FormData not supported in this environment. Ensure you have proper polyfills for Node.js environments.","FormData");throw e}}async updateTokenSocials(e){if(!Qe(e.tokenName))throw W("tokenName","Token name");if($o(e.tokenName),!this.jwtAuth)throw j("JWT authentication required for updating token social links. Initialize SDK with a wallet or provide JWT token.","JWT_AUTH_REQUIRED");const t=_t,n=mr(await this.http.put(t,e,this.getJwtHeaders()));if(!n)throw new Error("Failed to update token social links: no data returned");return n}}class Os{constructor(e,t,n=!1){this.http=e,this.poolService=new ys(e,n),this.tradeService=new vs(e,n),this.userService=new Ds(e,t,n),this.imageService=new Ls(e,t,n)}setJwtAuth(e){this.userService.setJwtAuth(e),this.imageService.setJwtAuth(e)}async uploadImageByTokenName(e){return this.imageService.uploadImageByTokenName(e)}async updateTokenSocials(e){return this.imageService.updateTokenSocials(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 fetchTokenBadges(e){return this.poolService.fetchTokenBadges(e)}async hasTokenBadge(e){return this.poolService.hasTokenBadge(e)}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 $o(e)}}function Fs(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 Us(e){return t=>{if(!t||"object"!=typeof t||Array.isArray(t))return!1;const n=t;for(const[t,r]of Object.entries(e)){if(!Fs(n[t],r))return!1}return!0}}et({BUY:"buy",SELL:"sell"});const $s=Us({vaultAddress:"string"}),qs=Us({nativeTokenQuantity:"string"});function Ks(e){return`${e.collection}|${e.category}|${e.type}|${e.additionalKey}`}function Gs(e){return`${e.collection}$${e.category}$${e.type}$${e.additionalKey}`}function Ws(e){return`$${e.collection}$${e.category}$${e.type}$${e.additionalKey}`}function zs(e,t,n){const r=n?` (${n})`:"";try{if(!Qe(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}`);const[r,i,o,...s]=n;if(!r||!i||!o)throw new Error("Collection, category, and type must be non-empty");const a=s.join(t);if(!a)throw new Error("AdditionalKey must be non-empty");return{collection:r,category:i,type:o,additionalKey:a}}catch(n){const i=e?.split?.(t)??[];throw new B(`Invalid ${"|"===t?"pipe":"dollar"}-delimited token: "${e}" (${i.length} parts)${r}. Expected format: "collection${t}category${t}type${t}additionalKey" (4 parts minimum). Received: [${i.map(e=>`"${e}"`).join(", ")}]. Error: ${A(n)}`,"token",`INVALID_${"|"===t?"PIPE":"DOLLAR"}_DELIMITED_TOKEN`)}}function Hs(e){if("object"==typeof e&&null!==e)return function(e){if(!e||"object"!=typeof e)throw new B("Token object must be a non-null object, got "+typeof e,"token","INVALID_TOKEN_OBJECT");const{collection:t,category:n,type:r,additionalKey:i}=e;if(!Qe(t))throw new B("Token.collection must be a non-empty string, got "+typeof t,"token.collection","MISSING_OR_INVALID_COLLECTION");if(!Qe(n))throw new B("Token.category must be a non-empty string, got "+typeof n,"token.category","MISSING_OR_INVALID_CATEGORY");if(!Qe(r))throw new B("Token.type must be a non-empty string, got "+typeof r,"token.type","MISSING_OR_INVALID_TYPE");if(!Qe(i))throw new B("Token.additionalKey must be a non-empty string, got "+typeof i,"token.additionalKey","MISSING_OR_INVALID_ADDITIONAL_KEY");return{collection:t,category:n,type:r,additionalKey:i}}(e);if(!e)throw new B(`Token cannot be null, undefined, or empty. Received: ${JSON.stringify(e)}`,"token","EMPTY_TOKEN");if("string"!=typeof e)throw new B("Token must be a string or TokenClassKey object, got "+typeof e,"token","INVALID_TOKEN_TYPE");if(Vs(e))return js(e);if(Xs(e))return function(e){return function(e,t,n){const r=` (${n})`;try{if(!Qe(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}`);const r=n[n.length-1],i=n[n.length-2],o=n[n.length-3],s=n.slice(0,n.length-3).join(t);if(!(s&&o&&i&&r))throw new Error("All components (collection, category, type, additionalKey) must be non-empty");return{collection:s,category:o,type:i,additionalKey:r}}catch(n){const i=e?.split?.(t)??[];throw new B(`Invalid dollar-delimited token: "${e}" (${i.length} parts)${r}. Expected format: "collection${t}category${t}type${t}additionalKey" (4 parts minimum). Received: [${i.map(e=>`"${e}"`).join(", ")}]. Error: ${A(n)}`,"token","INVALID_DOLLAR_DELIMITED_TOKEN")}}(e,"$","dollar-delimited token")}(e);throw new B(`Plain token string "${e}" (length: ${e.length}) is not allowed - tokens must be delimited with | or $. Expected format: "GALA|Unit|none|none" or "GALA$Unit$none$none". Input: "${e}"`,"token","PLAIN_STRING_NOT_ALLOWED")}function js(e){return zs(e,"|","pipe-delimited token")}function Vs(e){return Qe(e)&&e.includes("|")}function Xs(e){return"string"==typeof e&&e.includes("$")}function Qs(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.collection&&"string"==typeof t.category&&"string"==typeof t.type&&"string"==typeof t.additionalKey&&t.collection.length>0&&t.category.length>0&&t.type.length>0&&t.additionalKey.length>0}function Js(e){return e&&0!==e.length?e.reduce((e,t)=>i(e).plus(t.quantity).toString(),"0"):"0"}function Zs(e,t){if(!e||0===e.length)return[];if(t)return e;const n=Date.now();return e.filter(e=>0===e.expires||e.expires>n)}class Ys extends ds{constructor(e,t=!1){super(e,t)}getChannelForCollection(e){return"MUSIC"===(Xs(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(!r)return null;try{x(r,"Fetch balances")}catch{return null}if(!r.Data||0===r.Data.length)return null;const o=r.Data.find(t=>t.collection===e.collection&&t.category===e.category&&t.additionalKey===e.additionalKey&&t.type===e.type);if(!o||"0"===o.quantity)return null;const s=Ks(o),a={quantity:o.quantity,collection:o.collection,category:o.category,tokenId:s};if(o.inUseHolds?.length){const e=Zs(o.inUseHolds??[],t);e.length>0&&(a.inUseHolds=e,a.inUseQuantity=Js(e))}if(o.lockedHolds?.length){const e=Zs(o.lockedHolds??[],t);e.length>0&&(a.lockedHolds=e,a.lockedQuantity=Js(e))}return(a.lockedQuantity||a.inUseQuantity)&&(a.availableQuantity=function(e,t="0",n="0"){return i(e).minus(t).minus(n).toString()}(a.quantity,a.lockedQuantity,a.inUseQuantity)),a}catch(e){throw H(`Failed to fetch token balance from GalaChain: ${A(e)}`,void 0,S(e)?e:void 0)}}}function ea(e){if("string"==typeof e){if(!Vs(e))throw new B(`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){return{...js(t.slice(0,4).join("|")),instance:t[4]||"0"}}return{...js(e),instance:"0"}}if("object"==typeof e&&null!==e){if("instance"in e&&void 0!==e.instance){if(!Qs(e))throw new B("Invalid tokenId object format. All fields (collection, category, type, additionalKey) must be non-empty strings","tokenId","INVALID_TOKEN_ID_FORMAT");return e}if(!Qs(e))throw new B("Invalid tokenId object format. All fields (collection, category, type, additionalKey) are required","tokenId","INVALID_TOKEN_ID_FORMAT");return{...e,instance:"0"}}throw new B(`Invalid tokenId type: ${typeof e}. Expected string, TokenClassKey, or TokenInstanceKey`,"tokenId","INVALID_TOKEN_ID_TYPE")}function ta(e){return function(e){try{if(!Qe(e))throw new Error("Vault address must be a non-empty string");const[t,n]=e.split("|");if(!n)throw new Error("Missing token part after service prefix");const r=n.split("$");if(r.length<4)throw new Error(`Invalid vault address format: expected at least 4 parts separated by $, got ${r.length}`);const[i,o,s,...a]=r;if(!i||!o||!s)throw new Error("Collection, category, and type must be non-empty");const c=a.slice(0,-1),l=c.length>0?c.join("$"):a[0];if(!l)throw new Error("AdditionalKey must be non-empty");return{collection:i,category:o,type:s,additionalKey:l}}catch(t){throw new B(`Invalid vault address: "${e}". Expected format: "service|Token$Unit$SYMBOL$additionalKey$launchpad". Error: ${A(t)}`,"vaultAddress","INVALID_VAULT_ADDRESS_FORMAT")}}(e)}function na(e){return{...ta(e),instance:"0"}}function ra(e){return ta(e).type}function ia(e){return Ks(ea(e))}var oa=Object.freeze({__proto__:null,extractTokenSymbolFromVault:ra,isTokenClassKeyStrict:Qs,normalizeToTokenInstanceKey:ea,normalizeTokenIdToString:ia,parseVaultAddressToTokenClassKey:ta,parseVaultAddressToTokenInstance:na});class sa extends ds{constructor(e,t=!1,n){super(e,t),this.publicAxios=n}async fetchTokenClassFromChain(e){try{const t="string"==typeof e?ea(e):e,n={tokenClasses:[{collection:t.collection,category:t.category,type:t.type,additionalKey:t.additionalKey}]};if(!this.publicAxios)throw W("publicAxios","Public Axios instance");const r=(await this.publicAxios.post("/api/asset/token-contract/FetchTokenClasses",n)).data;if(x(r,"Failed to fetch token class from GalaChain"),!r.Data||0===r.Data.length)throw H(`Token not found on GalaChain: ${Ks(t)}`,404);return r.Data[0]}catch(e){if(e instanceof B)throw e;if(I(e)&&404===e.response?.status)throw H("Token not found on GalaChain",404,S(e)?e:void 0);if(S(e)&&"Error"===e.name&&A(e).includes("status indicates failure"))throw H(A(e),400,S(e)?e:void 0);const t=A(e);if(t.includes("Token not found"))throw e;throw H(`Failed to fetch token class from GalaChain: ${t}`,void 0,S(e)?e:void 0)}}async fetchTokenClassesWithSupply(e){try{if(!e||0===e.length)throw W("tokenClasses","Token classes array");const t={tokenClasses:e};if(!this.publicAxios)throw W("publicAxios","Public Axios instance");const n=(await this.publicAxios.post("/api/asset/token-contract/FetchTokenClassesWithSupply",t)).data;if(x(n,"Failed to fetch token classes with supply from GalaChain"),!n.Data||0===n.Data.length)throw H("No token supply data found for requested token classes",404);return n.Data}catch(e){if(e instanceof B)throw e;if(I(e)&&404===e.response?.status)throw H("Token supply data not found on GalaChain",404,S(e)?e:void 0);if(S(e)&&"Error"===e.name&&A(e).includes("status indicates failure"))throw H(A(e),400,S(e)?e:void 0);const t=A(e);if(t.includes("Token not found"))throw e;throw H(`Failed to fetch token classes with supply from GalaChain: ${t}`,void 0,S(e)?e:void 0)}}}class aa{toLaunchpadFormat(e){if(!e)throw new B('Token is required. Use full tokenId format: "GALA|Unit|none|none"',"token","MISSING_TOKEN");if("string"==typeof e){if(Vs(e))return e;throw new B(`Invalid token format "${e}". Use full tokenId format: "${e}|Unit|none|none". For launchpad bonding curve tokens, use tokenName parameter instead (e.g., "anime").`,"token","INVALID_TOKEN_FORMAT")}return Ks({collection:e.collection||e.symbol||"unknown",category:e.category||"Unit",type:e.type||"none",additionalKey:e.additionalKey||"none"})}toTokenClass(e){if("object"==typeof e&&null!==e)return{collection:e.collection||"Token",category:e.category||"Unit",type:e.type||e.symbol||"unknown",additionalKey:e.additionalKey||"none"};if("string"!=typeof e)throw new Error("Invalid token format: expected string or object, got "+typeof e);const t=zs(e,"|","token format conversion");return{collection:t.collection,category:t.category,type:t.type,additionalKey:t.additionalKey}}normalizeInternalApiResponse(e){return e?Vs(e)?e:`${e}|Unit|none|none`:""}normalize(e){return"string"==typeof e&&Vs(e)?e:this.toLaunchpadFormat(e)}}function ca(e){if(!Qe(e))throw new Error("Invalid token format: token must be a non-empty string");return e.replace(/\|/g,"$")}function la(e){return zs(e,"$","dollar-delimited token")}function ua(){return`galaconnect-operation-${Date.now()}_${Math.random().toString(36).substring(2,8)}`}class da extends n.ChainCallDTO{constructor(e){super(),this.lockAuthority=e.lockAuthority,this.tokenInstances=e.tokenInstances,this.uniqueKey=e.uniqueKey,void 0!==e.expires&&(this.expires=e.expires),void 0!==e.name&&(this.name=e.name),e.signedPayload&&(this.signature=e.signedPayload.signature,this.domain=e.signedPayload.domain,this.types=e.signedPayload.types,e.signedPayload.prefix&&(this.prefix=e.signedPayload.prefix))}static fromTokenClassKey(e,t,n,r,i){let o;if("string"==typeof r){o={...la(r),instance:"0"}}else o={collection:r.collection,category:r.category,type:r.type,additionalKey:r.additionalKey,instance:"0"};return new da({lockAuthority:t||e,tokenInstances:[{owner:e,quantity:n,tokenInstanceKey:o}],...void 0!==i?.expires&&{expires:i.expires},...void 0!==i?.name&&{name:i.name},uniqueKey:i?.uniqueKey||ua()})}static forGALA(e,t,n,r){return new da({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||ua()})}getTokenClassKey(){if(0===this.tokenInstances.length)return;return Gs(this.tokenInstances[0].tokenInstanceKey)}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 ha extends n.ChainCallDTO{constructor(e){super(),this.tokenInstances=e.tokenInstances,this.uniqueKey=e.uniqueKey,void 0!==e.name&&(this.name=e.name),e.signedPayload&&(this.signature=e.signedPayload.signature,this.domain=e.signedPayload.domain,this.types=e.signedPayload.types,e.signedPayload.prefix&&(this.prefix=e.signedPayload.prefix))}static fromTokenClassKey(e,t,n,r){let i;if("string"==typeof n){i={...la(n),instance:"0"}}else i={collection:n.collection,category:n.category,type:n.type,additionalKey:n.additionalKey,instance:"0"};return new ha({tokenInstances:[{owner:e,quantity:t,tokenInstanceKey:i}],...void 0!==r?.name&&{name:r.name},uniqueKey:r?.uniqueKey||ua()})}static forGALA(e,t,n){return new ha({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||ua()})}getTokenClassKey(){if(0===this.tokenInstances.length)return;return Gs(this.tokenInstances[0].tokenInstanceKey)}toSigningPayload(){return{tokenInstances:this.tokenInstances,...void 0!==this.name&&{name:this.name},uniqueKey:this.uniqueKey}}}class ga{constructor(e){this.wallet=e}static generateUniqueKey(){return`${Date.now()}_${Math.random().toString(36).substring(2,8)}`}async signTransferToken(e){const t={name:"GalaChain",chainId:1},n={TransferToken:[{name:"from",type:"string"},{name:"to",type:"string"},{name:"quantity",type:"string"},{name:"tokenInstance",type:"TokenInstance"},{name:"uniqueKey",type:"string"}],TokenInstance:[{name:"collection",type:"string"},{name:"category",type:"string"},{name:"type",type:"string"},{name:"additionalKey",type:"string"},{name:"instance",type:"string"}]};return{signature:await this.wallet.signTypedData(t,n,e),domain:t,types:n,signerPublicKey:this.wallet.signingKey.publicKey}}async signLockToken(e){const t={name:"GalaChain",chainId:1},n={LockToken:[{name:"lockAuthority",type:"string"},{name:"tokenInstances",type:"TokenInstanceQuantity[]"},{name:"uniqueKey",type:"string"},...void 0!==e.expires?[{name:"expires",type:"uint256"}]:[],...void 0!==e.name?[{name:"name",type:"string"}]:[]],TokenInstanceQuantity:[{name:"owner",type:"string"},{name:"quantity",type:"string"},{name:"tokenInstanceKey",type:"TokenInstanceKey"}],TokenInstanceKey:[{name:"collection",type:"string"},{name:"category",type:"string"},{name:"type",type:"string"},{name:"additionalKey",type:"string"},{name:"instance",type:"string"}]},r={lockAuthority:e.lockAuthority,tokenInstances:e.tokenInstances,uniqueKey:e.uniqueKey};void 0!==e.expires&&(r.expires=e.expires),void 0!==e.name&&(r.name=e.name);return{signature:await this.wallet.signTypedData(t,n,r),domain:t,types:n,signerPublicKey:this.wallet.signingKey.publicKey}}async signBurnTokens(e){const t={name:"GalaChain",chainId:1},n={BurnTokens:[{name:"tokenInstances",type:"TokenInstanceQuantity[]"},{name:"uniqueKey",type:"string"}],TokenInstanceQuantity:[{name:"quantity",type:"string"},{name:"tokenInstanceKey",type:"TokenInstanceKey"}],TokenInstanceKey:[{name:"collection",type:"string"},{name:"category",type:"string"},{name:"type",type:"string"},{name:"additionalKey",type:"string"},{name:"instance",type:"string"}]},r={tokenInstances:e.tokenInstances,uniqueKey:e.uniqueKey};return{signature:await this.wallet.signTypedData(t,n,r),domain:t,types:n,signerPublicKey:this.wallet.signingKey.publicKey}}async signUnlockToken(e){const t={name:"GalaChain",chainId:1},n={UnlockToken:[{name:"tokenInstances",type:"TokenInstanceQuantity[]"},{name:"uniqueKey",type:"string"},...void 0!==e.name?[{name:"name",type:"string"}]:[]],TokenInstanceQuantity:[{name:"owner",type:"string"},{name:"quantity",type:"string"},{name:"tokenInstanceKey",type:"TokenInstanceKey"}],TokenInstanceKey:[{name:"collection",type:"string"},{name:"category",type:"string"},{name:"type",type:"string"},{name:"additionalKey",type:"string"},{name:"instance",type:"string"}]},r={tokenInstances:e.tokenInstances,uniqueKey:e.uniqueKey};void 0!==e.name&&(r.name=e.name);return{signature:await this.wallet.signTypedData(t,n,r),domain:t,types:n,signerPublicKey:this.wallet.signingKey.publicKey}}static toGalaChainAddress(e){return(new ut).toBackendFormat(e)}static fromGalaChainAddress(e){try{return(new ut).toEthereumFormat(e)}catch{try{return pt(e)}catch{return e}}}static createGALATokenInstance(){return{collection:"GALA",category:"Unit",type:"none",additionalKey:"none",instance:"0"}}static createTokenInstanceFromClassKey(e){return{...la(e),instance:"0"}}}function pa(e){if(!e||"object"!=typeof e)return!1;const t=e;return Qe(t.amount)&&(void 0!==t.tokenId||Qe(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 fa(e){if(!e||"object"!=typeof e)return!1;const t=e;return Qe(t.amount)&&(void 0!==t.tokenId||Qe(t.tokenName))&&(void 0===t.name||"string"==typeof t.name)}function ma(e){if(!e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every(pa)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}function ya(e){if(!e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every(fa)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}var wa,ka;exports.LockErrorType=void 0,(wa=exports.LockErrorType||(exports.LockErrorType={})).TOKEN_NOT_FOUND="TOKEN_NOT_FOUND",wa.INVALID_AMOUNT="INVALID_AMOUNT",wa.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",wa.SIGNATURE_FAILED="SIGNATURE_FAILED",wa.NETWORK_ERROR="NETWORK_ERROR",wa.WALLET_REQUIRED="WALLET_REQUIRED",wa.VALIDATION_ERROR="VALIDATION_ERROR",wa.LOCK_NOT_FOUND="LOCK_NOT_FOUND",wa.LOCK_EXPIRED="LOCK_EXPIRED",wa.INSUFFICIENT_LOCKED_BALANCE="INSUFFICIENT_LOCKED_BALANCE",wa.NOT_LOCK_AUTHORITY="NOT_LOCK_AUTHORITY",wa.LOCK_NAME_MISMATCH="LOCK_NAME_MISMATCH";class ba 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"}(ka||(ka={}));class va extends Error{constructor(e,t,n){super(e),this.type=t,this.details=n,this.name="TransferError"}}const Sa=100,Aa=100;class Ta extends ds{constructor(e,t,n,r=!1){super(e,r),this.wallet=t,this.tokenResolver=n,this.signatureHelper=t?new ga(t):void 0}async lockTokens(e){if(this.validateLockTokensData(e),!this.wallet||!this.signatureHelper)throw new ba("Wallet required for token lock operations",exports.LockErrorType.WALLET_REQUIRED);return wr(async()=>{const t=gt(this.wallet.address),n=[],r=[];let i=t;const o=e.tokens.find(e=>e.lockAuthority);o?.lockAuthority&&(i=gt(o.lockAuthority));const s=e.tokens.find(e=>void 0!==e.expires),a=e.tokens.find(e=>void 0!==e.name);for(const o of e.tokens){let e;if(o.tokenId)e=ea(o.tokenId),this.logger.debug("[DEBUG] Using provided tokenId:",o.tokenId);else{if(!o.tokenName)throw new ba("Must provide either tokenId or tokenName for token identification",exports.LockErrorType.TOKEN_NOT_FOUND);e=await this.resolveTokenInstance(o.tokenName)}n.push({owner:t,quantity:o.amount,tokenInstanceKey:e}),r.push({tokenClassKey:{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey},quantity:o.amount,lockAuthority:o.lockAuthority?gt(o.lockAuthority):i})}const c=new da({lockAuthority:i,tokenInstances:n,...void 0!==s?.expires&&{expires:s.expires},...void 0!==a?.name&&{name:a.name},uniqueKey:e.uniqueKey||ua()}),l=await this.signatureHelper.signLockToken(c.toSigningPayload()),u=new da({...c.toSigningPayload(),signedPayload:l});this.logger.debug("[DEBUG] Full Lock Request Payload:",JSON.stringify(u,null,2));const d=await this.http.post("/api/asset/token-contract/LockTokens",u);try{x(d,"Token lock failed")}catch(e){const t=C(d);throw new ba(`${A(e)}${t}`,exports.LockErrorType.NETWORK_ERROR)}return this.logger.debug("[DEBUG] Token lock response:",JSON.stringify(d,null,2)),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.signatureHelper)throw new ba("Wallet required for token unlock operations",exports.LockErrorType.WALLET_REQUIRED);return wr(async()=>{const t=gt(this.wallet.address),n=[],r=[],i=e.tokens.find(e=>void 0!==e.name);for(const i of e.tokens){let e;if(i.tokenId)e=ea(i.tokenId),this.logger.debug("[DEBUG] Using provided tokenId:",i.tokenId);else{if(!i.tokenName)throw new ba("Must provide either tokenId or tokenName for token identification",exports.LockErrorType.TOKEN_NOT_FOUND);e=await this.resolveTokenInstance(i.tokenName)}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 o=new ha({tokenInstances:n,...void 0!==i?.name&&{name:i.name},uniqueKey:e.uniqueKey||ua()}),s=await this.signatureHelper.signUnlockToken(o.toSigningPayload()),a=new ha({...o.toSigningPayload(),signedPayload:s});this.logger.debug("[DEBUG] Full Unlock Request Payload:",JSON.stringify(a,null,2));const c=await this.http.post("/api/asset/token-contract/UnlockTokens",a);try{x(c,"Token unlock failed")}catch(e){const t=C(c);throw new ba(`${A(e)}${t}`,exports.LockErrorType.NETWORK_ERROR)}return this.logger.debug("[DEBUG] Token unlock response:",JSON.stringify(c,null,2)),this.extractUnlockResult(c,r)},"Token unlock failed",this.logger,t=>{throw this.handleLockError(t,"Token unlock failed",e)})}validateLockTokensData(e){if(!ma(e))throw new ba("Invalid lock data: missing required fields",exports.LockErrorType.VALIDATION_ERROR);if(e.tokens.length>Sa)throw new ba(`Batch size exceeds maximum limit of ${Sa} tokens per lock operation`,exports.LockErrorType.VALIDATION_ERROR);for(const t of e.tokens){if(!t.tokenId&&!t.tokenName)throw new ba("Must provide either tokenId or tokenName for token identification",exports.LockErrorType.TOKEN_NOT_FOUND);if(t.tokenName)try{it(t.tokenName,"tokenName")}catch{throw new ba("Invalid token name format",exports.LockErrorType.TOKEN_NOT_FOUND,{tokenName:t.tokenName})}const e=wo(t.amount);try{Do(e)}catch{throw new ba(z("lockAmount","a positive number","Lock amount").message,exports.LockErrorType.INVALID_AMOUNT,{amount:t.amount})}if(t.lockAuthority&&!mt(t.lockAuthority))throw new ba("Invalid lock authority address format",exports.LockErrorType.VALIDATION_ERROR,{lockAuthority:t.lockAuthority});if(void 0!==t.expires)try{ae(t.expires,"expires")}catch{throw new ba(z("expires","a positive integer (epoch milliseconds)","Expires").message,exports.LockErrorType.VALIDATION_ERROR)}}}validateUnlockTokensData(e){if(!ya(e))throw new ba("Invalid unlock data: missing required fields",exports.LockErrorType.VALIDATION_ERROR);if(e.tokens.length>Aa)throw new ba(`Batch size exceeds maximum limit of ${Aa} tokens per unlock operation`,exports.LockErrorType.VALIDATION_ERROR);for(const t of e.tokens){if(!t.tokenId&&!t.tokenName)throw new ba("Must provide either tokenId or tokenName for token identification",exports.LockErrorType.TOKEN_NOT_FOUND);if(t.tokenName)try{it(t.tokenName,"tokenName")}catch{throw new ba("Invalid token name format",exports.LockErrorType.TOKEN_NOT_FOUND,{tokenName:t.tokenName})}const e=wo(t.amount);try{Do(e)}catch{throw new ba(z("unlockAmount","a positive number","Unlock amount").message,exports.LockErrorType.INVALID_AMOUNT,{amount:t.amount})}}}extractLockResult(e,t){let n;if(e.Data&&e.Data.length>0){const t=e.Data[0];n=t.transactionId||t.txnId||t.TxnId||t.id||void 0}return{...void 0!==n&&{transactionId:n},locked:t}}extractUnlockResult(e,t){let n;if(e.Data&&e.Data.length>0){const t=e.Data[0];n=t.transactionId||t.txnId||t.TxnId||t.id||void 0}return{...void 0!==n&&{transactionId:n},unlocked:t}}handleLockError(e,t,n){if(e instanceof ba)return e;let r=t,i=exports.LockErrorType.NETWORK_ERROR;if(I(e)){const n=e.response?.data;if("object"==typeof n&&null!==n){const e=n;e.Message&&"string"==typeof e.Message&&(r=`${t}: ${e.Message}`);const o=String(e.Message||"").toLowerCase();o.includes("insufficient")||o.includes("balance")?i=exports.LockErrorType.INSUFFICIENT_BALANCE:o.includes("lock")&&o.includes("not found")?i=exports.LockErrorType.LOCK_NOT_FOUND:o.includes("not found")||o.includes("token")?i=exports.LockErrorType.TOKEN_NOT_FOUND:o.includes("authority")?i=exports.LockErrorType.NOT_LOCK_AUTHORITY:o.includes("expired")&&(i=exports.LockErrorType.LOCK_EXPIRED)}}else S(e)&&(r=`${t}: ${A(e)}`);const o={};return void 0!==n?.tokens?.[0]?.tokenName&&(o.tokenName=n.tokens[0].tokenName),void 0!==n?.tokens?.[0]?.amount&&(o.amount=n.tokens[0].amount),new ba(r,i,Object.keys(o).length>0?o:void 0)}async resolveTokenInstance(e){return wr(async()=>{const t=await this.tokenResolver.resolveTokenToVault(e);if(t){const n=na(t);return this.logger.debug(`[DEBUG] Token resolution for '${e}' (launchpad):\n Vault Address: ${t}\n Token Instance: ${JSON.stringify(n,null,2)}`),n}const n={collection:is(e),category:"Unit",type:"none",additionalKey:"none",instance:"0"};return this.logger.debug(`[DEBUG] Token resolution for '${e}' (standard format):\n Token Instance: ${JSON.stringify(n,null,2)}`),n},`Failed to resolve token '${e}'`,this.logger,t=>{if(t instanceof va)throw new ba(A(t),exports.LockErrorType.TOKEN_NOT_FOUND);throw new ba(`Failed to resolve token '${e}': ${A(t)}`,exports.LockErrorType.TOKEN_NOT_FOUND,{tokenName:e})})}}class Ea{static validateAmount(e){const t=wo(e);try{Mo(t,"amount")}catch(t){throw new va(t.message,ka.INVALID_AMOUNT,{amount:e})}}static validateUniqueKey(e){if(!Ze(e)&&Qe(e)){if(e.length>Ee.MAX_LENGTH)throw new B(`Unique key too long. Maximum length: ${Ee.MAX_LENGTH}`);if(!Ee.PATTERN.test(e))throw new va('Invalid unique key format. Must start with "galaswap-operation-" or "galaconnect-operation-"',ka.INVALID_AMOUNT,{uniqueKey:e})}}}class Ia extends n.ChainCallDTO{constructor(e){super(),this.from=e.from,this.to=e.to,this.quantity=e.quantity,this.tokenInstance=e.tokenInstance,this.uniqueKey=e.uniqueKey,e.signedPayload&&(this.signature=e.signedPayload.signature,this.domain=e.signedPayload.domain,this.types=e.signedPayload.types,e.signedPayload.prefix&&(this.prefix=e.signedPayload.prefix))}static fromTokenClassKey(e,t,n,r,i){let o;if("string"==typeof r){o={...la(r),instance:"0"}}else o={collection:r.collection,category:r.category,type:r.type,additionalKey:r.additionalKey,instance:"0"};return new Ia({from:e,to:t,quantity:n,tokenInstance:o,uniqueKey:i||ua()})}static forGALA(e,t,n,r){return new Ia({from:e,to:t,quantity:n,tokenInstance:{collection:"GALA",category:"Unit",type:"none",additionalKey:"none",instance:"0"},uniqueKey:r||ua()})}getTokenClassKey(){return Gs(this.tokenInstance)}toSigningPayload(){return{from:this.from,to:this.to,quantity:this.quantity,tokenInstance:this.tokenInstance,uniqueKey:this.uniqueKey}}}class xa extends n.ChainCallDTO{constructor(e){super(),this.tokenInstances=e.tokenInstances,this.uniqueKey=e.uniqueKey,e.signedPayload&&(this.signature=e.signedPayload.signature,this.domain=e.signedPayload.domain,this.types=e.signedPayload.types,e.signedPayload.prefix&&(this.prefix=e.signedPayload.prefix))}static fromTokens(e,t){const n=e.map(e=>{let t;if("string"==typeof e.tokenClassKey){t={...la(e.tokenClassKey),instance:"0"}}else t={collection:e.tokenClassKey.collection,category:e.tokenClassKey.category,type:e.tokenClassKey.type,additionalKey:e.tokenClassKey.additionalKey,instance:"0"};return{quantity:e.quantity,tokenInstanceKey:t}});return new xa({tokenInstances:n,uniqueKey:t?.uniqueKey||ua()})}static fromTokenClassKey(e,t,n){return xa.fromTokens([{tokenClassKey:t,quantity:e}],n)}static forGALA(e,t){return new xa({tokenInstances:[{quantity:e,tokenInstanceKey:{collection:"GALA",category:"Unit",type:"none",additionalKey:"none",instance:"0"}}],uniqueKey:t?.uniqueKey||ua()})}getTokenClassKey(){if(0===this.tokenInstances.length)return;return Gs(this.tokenInstances[0].tokenInstanceKey)}toSigningPayload(){return{tokenInstances:this.tokenInstances,uniqueKey:this.uniqueKey}}}function Ca(e){if(!e||"object"!=typeof e)return!1;const t=e;return Qe(t.amount)&&(void 0!==t.tokenId||Qe(t.tokenName))}function Na(e){if(!e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every(Ca)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}var _a;exports.BurnErrorType=void 0,(_a=exports.BurnErrorType||(exports.BurnErrorType={})).TOKEN_NOT_FOUND="TOKEN_NOT_FOUND",_a.INVALID_AMOUNT="INVALID_AMOUNT",_a.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",_a.SIGNATURE_FAILED="SIGNATURE_FAILED",_a.NETWORK_ERROR="NETWORK_ERROR",_a.WALLET_REQUIRED="WALLET_REQUIRED",_a.VALIDATION_ERROR="VALIDATION_ERROR";class Ba extends Error{constructor(e,t,n){super(e),this.type=t,this.details=n,this.name="BurnError"}}const Pa="gala-transfer-successful",Da="token-transfer-successful",Ra="token-locked-successfully",Ma="token-unlocked-successfully",La="transfer-successful-no-id",Oa=50;class Fa extends ds{constructor(e,t,n,r=!1){super(e,r),this.wallet=t,this.tokenResolver=n,this.signatureHelper=t?new ga(t):void 0}async transferGala(e){if(this.validateTransferGalaData(e),!this.wallet||!this.signatureHelper)throw new va("Wallet required for GALA transfer operations",ka.WALLET_REQUIRED);try{const t=gt(e.recipientAddress),n=gt(this.wallet.address),r=Ia.forGALA(n,t,e.amount,e.uniqueKey),i=await this.signatureHelper.signTransferToken(r.toSigningPayload()),o=new Ia({...r.toSigningPayload(),signedPayload:i});this.logger.debug("[DEBUG] Full GALA Transfer Request Payload:",JSON.stringify(o,null,2));const s=await this.http.post("/api/asset/token-contract/TransferToken",o);if(!s)throw new va("No response from GalaChain transfer service",ka.NETWORK_ERROR);return this.logger.debug("[DEBUG] Transfer response:",JSON.stringify(s,null,2)),this.extractTransactionIdFromResponse(s,"gala")}catch(t){throw this.handleTransferError(t,"GALA transfer failed",e)}}async transferToken(e){if(this.validateTransferTokenData(e),!this.wallet||!this.signatureHelper)throw new va("Wallet required for token transfer operations",ka.WALLET_REQUIRED);try{const t=gt(e.to),n=gt(this.wallet.address);let r;if(e.tokenId)r=ea(e.tokenId),this.logger.debug("[DEBUG] Using provided tokenId:",e.tokenId),this.logger.debug("[DEBUG] Normalized Token Instance:",JSON.stringify(r,null,2));else{if(!e.tokenName)throw new va("Must provide either tokenId or tokenName for token identification",ka.TOKEN_NOT_FOUND);r=await this.resolveTokenInstance(e.tokenName)}const i=new Ia({from:n,to:t,quantity:e.amount,tokenInstance:r,uniqueKey:e.uniqueKey||ua()}),o=await this.signatureHelper.signTransferToken(i.toSigningPayload()),s=new Ia({...i.toSigningPayload(),signedPayload:o});this.logger.debug("[DEBUG] Full Transfer Request Payload:",JSON.stringify(s,null,2));const a=await this.http.post("/api/asset/token-contract/TransferToken",s);if(!a)throw new va("No response from GalaChain transfer service",ka.NETWORK_ERROR);return this.logger.debug("[DEBUG] Token transfer response:",JSON.stringify(a,null,2)),this.extractTransactionIdFromResponse(a,"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}':`,JSON.stringify(t,null,2)),t}catch(t){if(t instanceof va)throw t;throw new va(`Failed to resolve token class key for '${e}': ${A(t)}`,ka.TOKEN_NOT_FOUND,{tokenName:e})}}async burnTokens(e){if(this.validateBurnTokensData(e),!this.wallet||!this.signatureHelper)throw new Ba("Wallet required for token burn operations",exports.BurnErrorType.WALLET_REQUIRED);try{const t=[];for(const n of e.tokens){let e;if(n.tokenId)e=ea(n.tokenId),this.logger.debug("[DEBUG] Using provided tokenId:",n.tokenId);else{if(!n.tokenName)throw new Ba("Must provide either tokenId or tokenName for token identification",exports.BurnErrorType.TOKEN_NOT_FOUND);e=await this.resolveTokenInstance(n.tokenName)}t.push({quantity:n.amount,tokenInstanceKey:e})}const n=new xa({tokenInstances:t,uniqueKey:e.uniqueKey||ua()}),r=await this.signatureHelper.signBurnTokens(n.toSigningPayload()),i=new xa({...n.toSigningPayload(),signedPayload:r});this.logger.debug("[DEBUG] Full Burn Request Payload:",JSON.stringify(i,null,2));const o=await this.http.post("/api/asset/token-contract/BurnTokens",i);if(!o)throw new Ba("No response from GalaChain burn service",exports.BurnErrorType.NETWORK_ERROR);try{x(o,"Token burn operation")}catch(e){throw new P(A(e),500)}return this.logger.debug("[DEBUG] Token burn response:",JSON.stringify(o,null,2)),this.extractBurnResult(o)}catch(t){throw this.handleBurnError(t,"Token burn failed",e)}}validateTransferGalaData(e){if(!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return Qe(t.recipientAddress)&&Qe(t.amount)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)}(e))throw new B("Invalid GALA transfer data: missing required fields");if(!mt(e.recipientAddress))throw new va("Invalid recipient address format",ka.INVALID_RECIPIENT,{recipientAddress:e.recipientAddress});Ea.validateAmount(e.amount),Ea.validateUniqueKey(e.uniqueKey)}validateTransferTokenData(e){if(!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return Qe(t.to)&&Qe(t.amount)&&(void 0!==t.tokenId||Qe(t.tokenName))&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)}(e))throw new B("Invalid token transfer data: missing required fields");if(!mt(e.to))throw new va("Invalid recipient address format",ka.INVALID_RECIPIENT,{recipientAddress:e.to});if(!e.tokenId&&!e.tokenName)throw new va("Must provide either tokenId or tokenName for token identification",ka.TOKEN_NOT_FOUND);if(e.tokenName)try{it(e.tokenName,"tokenName")}catch{throw new va("Invalid token name format",ka.TOKEN_NOT_FOUND,{tokenName:e.tokenName})}Ea.validateAmount(e.amount),Ea.validateUniqueKey(e.uniqueKey)}validateBurnTokensData(e){if(!Na(e))throw new Ba("Invalid burn data: missing required fields",exports.BurnErrorType.VALIDATION_ERROR);if(e.tokens.length>Oa)throw new Ba(`Batch size exceeds maximum limit of ${Oa} tokens per burn operation`,exports.BurnErrorType.VALIDATION_ERROR);for(const t of e.tokens){if(!t.tokenId&&!t.tokenName)throw new Ba("Must provide either tokenId or tokenName for token identification",exports.BurnErrorType.TOKEN_NOT_FOUND);const e=wo(t.amount);try{Do(e)}catch{throw new Ba("Burn amount must be a positive number",exports.BurnErrorType.INVALID_AMOUNT,{amount:t.amount})}}}async resolveTokenInstance(e){try{const t=await this.tokenResolver.resolveTokenToVault(e);if(t){const n=na(t);return this.logger.debug(`[DEBUG] Token resolution for '${e}' (launchpad):\n Vault Address: ${t}\n Token Instance: ${JSON.stringify(n,null,2)}`),n}const n={collection:is(e),category:"Unit",type:"none",additionalKey:"none",instance:"0"};return this.logger.debug(`[DEBUG] Token resolution for '${e}' (standard format):\n Token Instance: ${JSON.stringify(n,null,2)}`),n}catch(t){if(t instanceof va)throw t;throw new va(`Failed to resolve token '${e}': ${A(t)}`,ka.TOKEN_NOT_FOUND,{tokenName:e})}}extractTransactionIdFromResponse(e,t){if(e&&"object"==typeof e){if("Status"in e&&"Data"in e)try{x(e,"Extract transaction ID");const n=e;if(Array.isArray(n.Data)&&n.Data.length>0)switch(t){case"gala":return Pa;case"token":return Da;case"lock":return Ra;case"unlock":return Ma}return La}catch{}if("transactionId"in e&&"string"==typeof e.transactionId&&e.transactionId)return e.transactionId}throw new va("Operation succeeded but transaction ID could not be extracted",ka.NETWORK_ERROR)}extractBurnResult(e){const t=[];if(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(e.Data&&e.Data.length>0){const t=e.Data[0];n=t.transactionId||t.txnId||t.TxnId||t.id||void 0}return{...void 0!==n&&{transactionId:n},burned:t}}handleTransferError(e,t,n){if(e instanceof va)return e;if(e instanceof B)return new va(A(e),ka.INVALID_AMOUNT);if(I(e)&&e.response){const t=e.response.status,r=e.response.data;if(400===t)return new va(("string"==typeof r?.message?r.message:void 0)||"Invalid transfer request",ka.INVALID_AMOUNT);if(403===t)return new va("Insufficient balance for transfer",ka.INSUFFICIENT_BALANCE);if(404===t){const e={};return"tokenName"in n&&(e.tokenName=n.tokenName),new va("Token not found",ka.TOKEN_NOT_FOUND,e)}}if("object"==typeof e&&null!==e&&"code"in e&&("ECONNABORTED"===E(e)||"ETIMEDOUT"===E(e)))return new va("Transfer request timed out",ka.NETWORK_ERROR);const r=A(e);return new va(r||t,ka.NETWORK_ERROR)}handleBurnError(e,t,n){if(e instanceof Ba)return e;let r=t,i=exports.BurnErrorType.NETWORK_ERROR;if(I(e)){const n=e.response?.data;if("object"==typeof n&&null!==n&&n.Message&&"string"==typeof n.Message){r=`${t}: ${n.Message}`;const e=n.Message.toLowerCase();e.includes("insufficient")||e.includes("balance")?i=exports.BurnErrorType.INSUFFICIENT_BALANCE:(e.includes("not found")||e.includes("token"))&&(i=exports.BurnErrorType.TOKEN_NOT_FOUND)}}else S(e)&&(r=`${t}: ${A(e)}`);const o={};return void 0!==n?.tokens?.[0]?.tokenName&&(o.tokenName=n.tokens[0].tokenName),void 0!==n?.tokens?.[0]?.amount&&(o.amount=n.tokens[0].amount),new Ba(r,i,Object.keys(o).length>0?o:void 0)}}class Ua extends ds{constructor(e,t,n,r=!1,i){super(e,r),this.wallet=t,this.tokenResolver=n,this.publicAxios=i,this.balanceService=new Ys(e,r),this.tokenService=new sa(e,r,i),this.lockService=new Ta(e,t,n,r),this.transferService=new Fa(e,t,n,r)}async fetchPoolDetails(e){this.validateFetchPoolDetailsData(e);const t=await this.http.post("/api/asset/launchpad-contract/FetchSaleDetails",e);if(!t)throw H("No response from GalaChain service",500);kr(()=>x(t,"Failed to fetch pool details"),"Failed to fetch pool details",this.logger,e=>{throw H(A(e),500)});const n=t.Data.reverseBondingCurveConfiguration,r=n?.minFeePortion??"0",i=n?.maxFeePortion??"0",o=!Co(r)||!Co(i),s=t.Data;return s.reverseBondingCurveMinFeePortion=r,s.reverseBondingCurveMaxFeePortion=i,s.hasReverseBondingCurveFee=o,s.isGraduated="Finished"===t.Data.saleStatus,delete s.reverseBondingCurveConfiguration,t}async fetchLaunchTokenFee(){const e=await this.http.post("/api/asset/launchpad-contract/FetchLaunchpadFeeAmount",{});if(!e)throw H("No response from GalaChain service",500);return kr(()=>x(e,"Failed to fetch launch token fee"),"Failed to fetch launch token fee",this.logger,e=>{throw H(A(e),500)}),e.Data.feeAmount}validateFetchPoolDetailsData(e){if(!$s(e))throw W("data","Fetch pool details data");if(!e.vaultAddress||"string"!=typeof e.vaultAddress)throw W("vaultAddress","Vault address");if(!e.vaultAddress.startsWith("service|Token$Unit$"))throw new B("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 $a extends hs{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}=nt(e,"tokenName","tokenId",{description:"token identifier"});if(n&&t)return this.logger.debug(`Fetching spot price by tokenId: ${t}`),this._fetchDexTokenSpotPrice(t);throw new B("tokenName parameter requires LaunchpadSDK routing - call LaunchpadSDK.fetchTokenPrice({tokenName}) instead","tokenName","INVALID_PARAMS")}async _fetchDexTokenSpotPrice(e){if(!e)throw W("tokenId","Token ID");try{const t=ea(e),n=Ks(t),r=ca(n);if(this.logger.debug(`Fetching DEX spot price for token: ${r}`),!this.dexBackendHttp)throw H("DEX Backend API client not configured");const i=mr(await this.dexBackendHttp.request({method:"GET",url:"/v1/trade/price",params:{token:r}}));if(!i||"string"!=typeof i)throw new B("Invalid price response: data must be a string, got "+typeof i,"data","INVALID_RESPONSE");const o=function(e,t){if(Ze(e)||""===e)throw W(t);const n="number"==typeof e?e:parseFloat(String(e));if(isNaN(n))throw ee(t,e);if(!isFinite(n))throw ee(t,e);return n}(i,"price"),s=n;let a;try{if(this.cache){const e=this.cache.getByTokenId(s);if(e?.symbol)return a=e.symbol,this.logger.debug(`DEX spot price for ${a} (cached): $${o}`),{symbol:a,price:o}}this.logger.debug(`Symbol cache miss for ${s}, fetching from API`);a=(await this.fetchTokenDetails(e)).symbol,this.cache&&(this.cache.setByTokenId(s,{symbol:a}),this.logger.debug(`Cached symbol for ${s}: ${a}`)),this.logger.debug(`DEX spot price for ${a}: $${o}`)}catch(e){this.logger.debug(`Could not fetch token details for symbol, falling back to token format parsing: ${S(e)?e.message:String(e)}`),a=os("Token"===t.collection?t.type:t.collection),this.logger.debug(`DEX spot price for ${a} (fallback): $${o}`)}return{symbol:a,price:o}}catch(e){if(e instanceof B)throw e;throw H(`Failed to fetch DEX spot price: ${A(e)}`)}}async fetchLaunchpadTokenSpotPrice(e,t,n){if(!Qe(e))throw new B(Ar,"tokenName",_.REQUIRED);try{if(n)try{this.logger.debug(`Checking graduation status for token: ${e}`);const t=await n(e);if(t&&t.isGraduated){this.logger.debug(`Token ${e} is graduated, using DEX spot price`);const n=Ks(t.sellingToken);return this._fetchDexTokenSpotPrice(n)}}catch(t){this.logger.debug(`Could not determine graduation status for ${e}, falling back to bonding curve: ${A(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(!i)throw H("GALA price not available");const o=De(r.amount,0)/1e18;if(o<=0)throw new B(`Invalid token amount calculation: ${o}`,"amount","INVALID_CALCULATION");const s=i.price/o;return{symbol:os(e),price:s}}catch(t){if(S(t))throw H(`Failed to calculate launchpad token spot price for ${e}: ${A(t)}`);throw H(`Failed to calculate launchpad token spot price for ${e}: ${A(t)}`)}}async fetchTokenDetails(e){this.logger.debug("Fetching token details from GalaChain for tokenId:",e);try{if(!this.galaChainService)throw H("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 B||S(t))&&("NetworkError"===t.name||A(t).includes("Token not found")))throw t;throw H(`Failed to fetch token details from GalaChain for ${e}: ${A(t)}`,500)}}async fetchAllDexSeasons(){try{if(!this.dexBackendHttp)throw H("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(!e||"object"!=typeof e)return this.logger.warn("Seasons endpoint returned invalid data:",e),[];{const n=mr(e);if(Array.isArray(n))t=n;else if(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=>({id:e?.id??0,name:e?.name??"",start:He(e?.start),end:He(e?.end),rulesId:e?.rules_id??0}));return this.logger.debug(`Fetched ${n.length} DEX seasons`),n}catch(e){if(S(e)&&A(e).includes("not configured"))throw e;if(I(e)&&404===e.response?.status)return this.logger.warn("Seasons endpoint not available"),[];throw H(`Failed to fetch DEX seasons: ${A(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{ae(e,"seasonId")}catch{throw W("seasonId","Season ID must be a positive number")}try{if(!this.dexBackendHttp)throw H("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(!t||"object"!=typeof t)return this.logger.warn("Leaderboard endpoint returned invalid data:",t),{entries:[],seasonId:e,totalEntries:0};{const r=mr(t);if(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=>({wallet:e?.wallet??"",rank:e?.rank??0,totalXp:e?.total_xp??0,distributionPercent:e?.distribution_percent??0,liquidityXp:e?.liquidity_xp??0,tradingXp:e?.trading_xp??0,masteryTitles:(e?.mastery_titles??[]).map(e=>({name:e?.name??"",type:e?.type??"trade",order:e?.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(S(t)&&A(t).includes("must be a positive number"))throw t;throw H(`Failed to fetch DEX leaderboard for season ${e}: ${A(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 H("DEX Backend API client not configured");const e=mr(await this.dexBackendHttp.request({method:"GET",url:"/explore/volume"}));if(!e)throw H("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 H(`Failed to fetch DEX volume summary: ${A(e)}`)}}}function qa(e){return{maxAcceptableReverseBondingCurveFee:qe(e.maxAcceptableReverseBondingCurveFee)}}class Ka extends n.ChainCallDTO{constructor(e,t,n="0",r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=qe(t),this.expectedToken=Ke(n),this.extraFees=qa(r)}}class Ga extends n.ChainCallDTO{constructor(e,t,n,r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=Ke(t),this.expectedNativeToken=qe(n),this.extraFees=qa(r)}}class Wa extends n.ChainCallDTO{constructor(e,t,n="0",r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=Ke(t),this.expectedNativeToken=qe(n),this.extraFees=qa(r)}}class za extends n.ChainCallDTO{constructor(e,t,n,r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=qe(t),this.expectedToken=Ke(n),this.extraFees=qa(r)}}const Ha={BuyNativeDto:Ka,BuyExactDto:Ga,SellExactDto:Wa,SellNativeDto:za};class ja extends hs{constructor(e,t=!1){super(t),this.walletProvider=e}async signDTO(e,t,r){try{this.logger.debug("🔐 Signing DTO:",{methodName:t,dtoKeys:Object.keys(e)});const r=this.generateEIP712Types(t,e),i=n.calculatePersonalSignPrefix(e),o={...e,prefix:i},{signature:s,domain:a}=await this.signWithEthersWallet(r,o),c={...e,signature:s,types:r,domain:a};return this.logger.debug("✅ DTO signed successfully:",{payloadKeys:Object.keys(c),signatureLength:s.length}),c}catch(e){this.logger.error("❌ Signature generation failed:",e);throw V(`Failed to sign DTO: ${A(e)}`)}}async signWithEthersWallet(e,t){try{let n,r;if(this.walletProvider.signTypedData&&!this.walletProvider.getNetwork)n={name:"ethereum",chainId:1},r=await this.walletProvider.signTypedData(n,e,t);else{if(!this.walletProvider.getNetwork||!this.walletProvider.signTypedData)throw j("Wallet provider does not support typed data signing","walletProvider");{const i=await this.walletProvider.getNetwork();n={name:i.name,chainId:Le(i.chainId,1)},r=await this.walletProvider.signTypedData(n,e,t)}}return{signature:r,domain:n}}catch(e){throw V(`Ethers.js signing failed: ${A(e)}`)}}generateEIP712Types(e,t){const n={};n[e]=[];const r=Object.fromEntries(Object.entries(t).filter(([e,t])=>void 0!==t)),i=(e,t,r,o=!1)=>{if(void 0!==t){if(Array.isArray(t)){if(0===t.length)return;const s=i(e,t[0],r,!0);return o||n[r].push({name:e,type:(s??e)+"[]"}),s?s+"[]":void 0}if("object"==typeof t&&null!==t){if(n[e])throw new B(`Type name collision not supported: ${e}`,"fieldValue","TYPE_COLLISION");return n[e]=[],Object.entries(t).forEach(([t,n])=>{i(t,n,e)}),o||n[r].push({name:e,type:e}),e}{let i;switch(typeof t){case"string":i="string";break;case"number":i="uint256";break;case"boolean":i="bool";break;default:throw new B(`Unsupported type for field "${e}": ${typeof t} (value: ${JSON.stringify(t)})`,"fieldValue","UNSUPPORTED_TYPE")}return o||n[r].push({name:e,type:i}),i}}};return Object.entries(r).forEach(([t,n])=>{i(t,n,e)}),this.logger.debug("📝 Generated EIP-712 types:",n),n}}class Va extends hs{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`,o=`$tokenBalance$${n.toStringKey()}$${e}`,s=`$tokenBalance$${n.toStringKey()}$${e}`,a=`$tokenBalance$${r.toStringKey()}$${e}`,c=[i,o,s,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=A(e);throw new B(`Failed to generate stringsInstructions: ${t}`,"vaultAddress","INVALID_VAULT_ADDRESS")}}createTokenInstance(e){const t=new s.TokenClassKey;return t.collection=e.toLowerCase(),t.category="Unit",t.type="none",t.additionalKey="none",this.logger.debug("🪙 Created token instance:",{symbol:e,lowercaseCollection:e.toLowerCase(),stringKey:t.toStringKey()}),t}createGalaInstance(){const e=new s.TokenClassKey;return e.collection="GALA",e.category="Unit",e.type="none",e.additionalKey="none",this.logger.debug("🟡 Created GALA instance:",{stringKey:e.toStringKey()}),e}extractTokenSymbolFromVault(e){if(!Qe(e))throw W("vaultAddress","Vault address");try{const t=ra(e);return this.logger.debug("🔍 Extracted token symbol:",{vaultAddress:e,tokenSymbol:t}),t}catch(e){if(e instanceof B)throw z("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad");throw e}}validateVaultAddress(e){if(!Qe(e))throw W("vaultAddress","Vault address");if(!e.startsWith("service|Token$Unit$"))throw z("vaultAddress",'starting with "service|Token$Unit$"');if(!e.endsWith("$launchpad"))throw z("vaultAddress",'ending with "$launchpad"');const t=function(e){if(!Qe(e))return null;const t=e.match(/^service\|Token\$Unit\$([^$]+)\$eth:([a-fA-F0-9]{40})\$launchpad$/);return t?{tokenSymbol:t[1],creatorAddress:t[2].toLowerCase()}:null}(e);if(!t)throw z("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 z("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 la(e)}catch(e){if(e instanceof B)throw z("stringKey","format: collection$category$type$additionalKey (4 parts)");throw e}}}function Xa(e,t,n){let r;oe(t,0,1,"slippageToleranceFactor");try{r=Fe(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 o;switch(n){case"buy-native":case"sell-exact":o=r.minus(i);break;case"buy-exact":case"sell-native":o=r.plus(i);break;default:throw new Error(`Unknown operation type: ${n}`)}return _o(o)&&(o=wo(0)),ko(o)}class Qa extends ds{constructor(e,t,n=!1,r,i,o=.05,s=.01){super(e,n),this.tokenResolver=t,this.walletProvider=r,this.userAddress=i,this.defaultSlippageToleranceFactor=o,this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor=s,this.bundleEndpoint="/bundle",r&&i&&(this.signatureService=new ja(r,n),this.tokenKeyService=new Va(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 ts(()=>this.http.post(this.bundleEndpoint,t),{errorContext:"Bundle transaction submission failed",logger:this.logger})}catch(e){return{success:!1,error:this.formatErrorMessage(e)}}return n?(this.logger.debug("📥 Bundle API response:",{success:n.success,hasData:pr(n),error:n.error}),this.handleBundleResponse(n)):{success:!1,error:"No response from bundle API"}}catch(e){if(e instanceof B)return{success:!1,error:A(e)};throw e}}validateBundleData(e){if(!e)throw W("bundleData","Bundle data");if(!e.signedDto)throw W("signedDto","Signed DTO");if(!Qe(e.method))throw W("method","Method name");if(!Array.isArray(e.stringsInstructions))throw z("stringsInstructions","an array of resource tracking strings");if(0===e.stringsInstructions.length)throw new B("stringsInstructions cannot be empty","stringsInstructions","EMPTY_ARRAY");const t=["BuyWithNative","BuyExactToken","SellExactToken","SellWithNative"];if(!t.includes(e.method))throw z("method",`one of: ${t.join(", ")}`);e.stringsInstructions.forEach((e,t)=>{if(!Qe(e))throw new B(`stringsInstructions[${t}] must be a non-empty string`,`stringsInstructions[${t}]`,"INVALID_INSTRUCTION");if(!Xs(e))throw new B(`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=mr(e);if(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(I(e)&&e.response){const t=mr(e.response);if(t&&"object"==typeof t){const e=t;if(e.error)return String(e.error);if(e.message)return String(e.message)}}return A(e)||"Unknown bundle transaction error"}async getBundlerTransactionResult(e){try{if(!Qe(e))throw W("transactionId","Transaction ID");let t;this.logger.debug("🔍 Checking bundler transaction result:",e);try{t=await ts(()=>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 t?(this.logger.debug("📊 Bundler transaction result:",t),{success:!0,data:t}):{success:!1,error:"No response from bundler transaction query"}}catch(e){if(e instanceof B)return{success:!1,error:A(e)};throw e}}async cancelTransaction(e){try{if(!Qe(e))throw W("transactionId","Transaction ID");let t;this.logger.debug("🚫 Cancelling transaction:",e);try{t=await ts(()=>this.http.delete(`${this.bundleEndpoint}/${e}`),{errorContext:"Failed to cancel transaction",logger:this.logger})}catch(e){return{success:!1,error:this.formatErrorMessage(e)}}return t?(this.logger.debug("🗑️ Transaction cancellation response:",t),{success:!0,data:t}):{success:!1,error:"No response from transaction cancellation"}}catch(e){if(e instanceof B)return{success:!1,error:A(e)};throw e}}async getHealthStatus(){this.logger.debug("🏥 Checking bundle service health");try{const e=await ts(()=>this.http.get(`${this.bundleEndpoint}/health`),{errorContext:"Bundle service health check failed",logger:this.logger});return e?(this.logger.debug("💚 Bundle service health:",e),{success:!0,data:e}):{success:!1,error:"No response from bundle service health check"}}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:o,effectiveMaxFee:s,vaultAddress:a}=await this.prepareTradingOperation(t,e.maxAcceptableReverseBondingCurveFee,e.maxAcceptableReverseBondingCurveFeeSlippageFactor,e.slippageToleranceFactor);if("native"===r){if(!i)throw new B("expectedAmount is required for native buy operations. Use getBuyTokenAmount() first to calculate expected tokens.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Xa(i,o,"buy-native");this.logger.debug("BuyNative slippage applied:",{originalExpectedTokens:i,slippageFactor:o,adjustedMinTokens:e});const t=new Ha.BuyNativeDto(a,n,e,{maxAcceptableReverseBondingCurveFee:s});return await this.executeBundleTransaction(t,"BuyWithNative",a)}{if(!i)throw new B("expectedAmount is required for exact buy operations. Use getBuyTokenAmount() first to calculate expected GALA cost.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Xa(i,o,"buy-exact");this.logger.debug("BuyExact slippage applied:",{originalExpectedGalaCost:i,slippageFactor:o,adjustedMaxGalaCost:e});const t=new Ha.BuyExactDto(a,n,e,{maxAcceptableReverseBondingCurveFee:s});return await this.executeBundleTransaction(t,"BuyExactToken",a)}}async sellToken(e){this.ensureTradingServicesAvailable();const{tokenName:t,amount:n,type:r,expectedAmount:i}=e,{effectiveSlippageFactor:o,effectiveMaxFee:s,vaultAddress:a}=await this.prepareTradingOperation(t,e.maxAcceptableReverseBondingCurveFee,e.maxAcceptableReverseBondingCurveFeeSlippageFactor,e.slippageToleranceFactor);if("exact"===r){if(!i)throw new B("expectedAmount is required for exact sell operations. Use getSellTokenAmount() first to calculate expected GALA.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Xa(i,o,"sell-exact");this.logger.debug("SellExact slippage applied:",{originalExpectedGala:i,slippageFactor:o,adjustedMinGala:e});const t=new Ha.SellExactDto(a,n,e,{maxAcceptableReverseBondingCurveFee:s});return await this.executeBundleTransaction(t,"SellExactToken",a)}{if(!i)throw new B("expectedAmount is required for native sell operations. Use getSellTokenAmount() first to calculate tokens to sell.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Xa(i,o,"sell-native");this.logger.debug("SellNative slippage applied:",{originalExpectedTokensToSell:i,slippageFactor:o,adjustedMaxTokensToSell:e});const t=new Ha.SellNativeDto(a,n,e,{maxAcceptableReverseBondingCurveFee:s});return await this.executeBundleTransaction(t,"SellWithNative",a)}}async prepareTradingOperation(e,t,n,r){const{effectiveSlippageFactor:i,effectiveMaxFee:o}=this.calculateEffectiveSlippage(t,n,r),s=await this.resolveTokenNameToVault(e);if(!s)throw G(e);return{effectiveSlippageFactor:i,effectiveMaxFee:o,vaultAddress:s}}calculateEffectiveSlippage(e,t,n){const r=n??this.defaultSlippageToleranceFactor,i=t??this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor;let o=e||"0";return e&&(o=Xa(e,i,"buy-exact"),this.logger.debug("Reverse bonding curve fee slippage applied:",{baseFee:e,slippageFactor:i,adjustedMaxFee:o})),{effectiveSlippageFactor:r,effectiveFeeSlippageFactor:i,effectiveMaxFee:o}}ensureTradingServicesAvailable(){if(!this.signatureService||!this.tokenKeyService)throw j("Trading services not available. BundleService requires walletProvider and userAddress for trading operations.","walletProvider");if(!this.userAddress)throw W("userAddress","User address")}async executeBundleTransaction(e,t,n){this.ensureTradingServicesAvailable();try{e.uniqueKey=`galaswap - operation - ${o.v4()}-${Date.now()}-${this.userAddress}`;const r=await this.signatureService.signDTO(e,t,this.userAddress),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 a=await this.submitTransaction(s);if(a.success){const e=mr(a);if(e)return this.logger.debug("✅ Bundle transaction submitted:",e),{success:!0,data:{transactionId:e,message:"Transaction submitted successfully. Monitor WebSocket for completion."}}}throw new R(String(a.error||"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 Ja{constructor(e=0){this.defaultTtlMs=e,this.cache=new Map}get(e){const t=this.cache.get(e);if(t){if(!(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 Za(e,t,n,r={}){const{logger:i,cacheNullish:o=!1,keyGenerator:s}=r,a=s?s(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}`)):o&&(n.set(a,l),i&&i.debug(`Cached nullish result for key: ${a}`)),l}var Ya,ec;!function(e){e.PROCESSED="PROCESSED",e.COMPLETED="COMPLETED",e.SUCCESS="SUCCESS",e.FAILED="FAILED",e.ERROR="ERROR",e.PROCESSING="PROCESSING",e.PENDING="PENDING"}(Ya||(Ya={})),exports.SDKTransactionStatus=void 0,(ec=exports.SDKTransactionStatus||(exports.SDKTransactionStatus={})).PENDING="pending",ec.PROCESSING="processing",ec.COMPLETED="completed",ec.FAILED="failed",ec.TIMEOUT="timeout";const tc={[Ya.PROCESSED]:exports.SDKTransactionStatus.COMPLETED,[Ya.COMPLETED]:exports.SDKTransactionStatus.COMPLETED,[Ya.SUCCESS]:exports.SDKTransactionStatus.COMPLETED,[Ya.FAILED]:exports.SDKTransactionStatus.FAILED,[Ya.ERROR]:exports.SDKTransactionStatus.FAILED,[Ya.PROCESSING]:exports.SDKTransactionStatus.PROCESSING,[Ya.PENDING]:exports.SDKTransactionStatus.PENDING};class nc{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 rc extends hs{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 nc({maxAttempts:this.config.reconnectAttempts??5,baseDelayMs:this.config.reconnectDelay??2e3}),this.eventBuffer=new Ja(3e4),this.isSocketIOAvailable=this.checkSocketIOAvailability()}checkSocketIOAvailability(){try{return"function"==typeof a.io||(this.logger.warn('⚠️ Socket.IO client not available. Install "socket.io-client" package.'),!1)}catch(e){return this.logger.warn("⚠️ Socket.IO availability check failed:",e),!1}}async connect(){return new Promise((e,t)=>{wr(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:",A(e)),e}this.logger.debug("🔌 Connecting to Socket.IO server:",this.config.url),this.socket=a.io(this.config.url,{transports:["websocket"],reconnection:!0,reconnectionAttempts:this.config.reconnectAttempts||5,reconnectionDelay:this.config.reconnectDelay||2e3}),this.socket.on("connect",()=>{this.logger.debug("✅ Socket.IO connected successfully:",this.socket?.id),this.logger.debug("📡 Connected to bundle backend WebSocket:",this.config.url),this.logger.debug("🔗 Ready to monitor transaction updates"),this.reconnectionManager.reset(),e()}),this.socket.on("connect_error",e=>{this.logger.error("❌ Socket.IO connection error:",e),t(e)}),this.socket.on("disconnect",e=>{this.logger.debug(`🔌 Socket.IO disconnected: ${e}`),this.handleReconnect()}),this.socket.on("error",e=>{this.logger.error("❌ Socket.IO error:",e)}),this.socket.onAny((e,...t)=>{if(e&&t.length>0&&"object"==typeof t[0]&&null!==t[0]){const n=t[0],r=n.status||n.Status;r&&"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=>{throw this.logger.error("Socket.IO connection failed:",e),t(e),e}).catch(t)})}async monitorTransaction(e,t){this.listeners.set(e,t),this.logger.debug(`📡 Starting to monitor transaction: ${e}`),this.logger.debug(`📡 WebSocket connected: ${!!this.socket&&this.socket.connected}`);const n=this.eventBuffer.get(e);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:exports.SDKTransactionStatus.TIMEOUT,message:`Transaction monitoring timeout - no response after ${n} seconds`,timestamp:Date.now()};this.logger.debug(`📡 Transaction timeout for ${e} (${n}s)`),t(i),this.listeners.delete(e),this.timeouts.delete(e),this.socket?.off(e)}},r);if(this.timeouts.set(e,i),this.socket&&this.socket.connected)this.socket.off(e),this.logger.debug(`📡 Listening for transaction updates: ${e}`),this.logger.debug(`📡 WebSocket connection ID: ${this.socket.id}`),this.logger.debug(`📡 WebSocket URL: ${this.config.url}`),this.socket.on(e,n=>{this.processTransactionEvent(e,n,t)});else{const n={transactionId:e,status:exports.SDKTransactionStatus.FAILED,message:"WebSocket not connected - cannot monitor transaction",timestamp:Date.now()};t(n),this.listeners.delete(e),this.timeouts.delete(e)}}processTransactionEvent(e,t,n){this.logger.debug(`📡 Socket.IO transaction update for ${e}:`,JSON.stringify(t,null,2));const r=t,i=r?.data,o=r?.status||r?.Status||i?.status||i?.Status;let s=r?.message||r?.Message||i?.message||i?.Message||r?.error||i?.error;Qe(s)||(s=o===Ya.FAILED||o===Ya.ERROR?"Transaction failed - check transaction details":o===Ya.COMPLETED||o===Ya.PROCESSED||o===Ya.SUCCESS?"Transaction completed successfully":o?`Transaction status: ${o}`:"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(o),message:"string"==typeof s?s:"Transaction update received",timestamp:Date.now(),...a&&{blockHash:a},...c&&{gasUsed:c},...l&&{data:l}};if(this.logger.debug(`📡 Mapped status for ${e}: ${o} -> ${u.status}`),this.logger.debug(`📡 Final message: "${s}"`),n(u),u.status===exports.SDKTransactionStatus.COMPLETED||u.status===exports.SDKTransactionStatus.FAILED){this.listeners.delete(e);const t=this.timeouts.get(e);t&&(clearTimeout(t),this.timeouts.delete(e)),this.socket?.off(e),this.logger.debug(`📡 Cleaned up listener for ${e} (${u.status})`)}}async waitForTransaction(e){return new Promise((t,n)=>{this.monitorTransaction(e,e=>{e.status===exports.SDKTransactionStatus.COMPLETED?t(e):e.status!==exports.SDKTransactionStatus.FAILED&&e.status!==exports.SDKTransactionStatus.TIMEOUT||n(new Error(`Transaction ${e.status}: ${e.message}`))})})}mapSocketStatus(e){const t=e?.toUpperCase();return tc[t]||exports.SDKTransactionStatus.PENDING}async handleReconnect(){this.reconnectionManager.shouldRetry()?(this.reconnectionManager.recordAttempt(),this.logger.debug(`🔄 Attempting Socket.IO reconnect ${this.reconnectionManager.getStatusString()}`),setTimeout(()=>{this.socket&&!this.socket.connected&&this.socket.connect()},this.reconnectionManager.getNextDelay())):this.logger.error("❌ Socket.IO max reconnection attempts reached")}disconnect(){this.socket&&(this.listeners.forEach((e,t)=>{this.socket?.off(t)}),this.listeners.clear(),this.timeouts.forEach(e=>{clearTimeout(e)}),this.timeouts.clear(),this.eventBuffer.clear(),this.logger.debug("🧹 Cleared event buffer"),this.hasOnAnyListener&&(this.socket.offAny(),this.hasOnAnyListener=!1,this.logger.debug("🧹 Removed onAny debug listener")),this.socket.disconnect(),this.socket=null,this.logger.debug("🔌 Socket.IO disconnected"))}isConnected(){return this.socket?.connected||!1}getSocket(){return this.socket}}class ic extends hs{constructor(e,t=!1){super(t),this.poolService=e,this.cache=new Map}async resolveTokenToVault(e){if(!Qe(e))throw W("tokenName","Token name");const t=rs(e),n=this.get(t);if(n)return n;try{const n=await this.poolService.resolveTokenNameToVault(e);return n&&this.set(t,n),n}catch{return null}}async resolveTokenClassKey(e){const t=await this.resolveTokenToVault(e);if(!t)throw G(e);return this.parseVaultAddressToTokenClassKey(t)}get(e){return this.cache.get(rs(e))||null}set(e,t){this.cache.set(rs(e),t)}clear(){this.cache.clear()}getStats(){return{size:this.cache.size,keys:Array.from(this.cache.keys())}}preWarm(e){for(const{tokenName:t,vaultAddress:n}of e)this.set(t,n)}parseVaultAddressToTokenClassKey(e){try{return ta(e)}catch(e){if(e instanceof B)throw z("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad","Vault address");throw e}}}class oc extends ds{constructor(e,t=!1,n){super(e,t),this.tokenResolverService=n}async fetchTokenClassKeyByTokenName(e){if(!e)throw W("tokenName","Token name");if(!this.tokenResolverService)throw j("TokenResolverService is required for token name resolution. Ensure it is passed to PriceHistoryService constructor.","tokenResolverService");try{rt(e)}catch(e){throw j(A(e),"tokenName")}this.logger.debug(`Resolving token name '${e}' to token class key`);try{const t=await this.tokenResolverService.resolveTokenToVault(e);if(!t)throw j(`Token '${e}' not found or could not be resolved to vault address`,"tokenName");this.logger.debug(`Resolved '${e}' to vault address: ${t}`);const n=Ks(ta(t));return this.logger.debug(`Extracted token class key: ${n}`),n}catch(t){if(S(t)&&A(t).includes("ConfigurationError"))throw t;throw H(`Failed to resolve token name '${e}': ${A(t)}`,500)}}async fetchPriceHistory(e){if(!e)throw W("options","Fetch options");return this.logger.debug("Fetching price history from DEX Backend API with options:",e),this.validateOptions(e),wr(async()=>{let t=e.tokenId;if(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(!t)throw j("Token ID is required but was not provided or resolved","tokenId");const{normalizeToTokenInstanceKey:n}=await Promise.resolve().then(function(){return oa}),r=ca(Ks(n(t))),{from:i,to:o,sortOrder:s="DESC"}=e,a=Re(e.page,1),c=Re(e.limit,10),l={token:r,page:String(a),limit:String(c)};i&&(l.from=i.toISOString()),o&&(l.to=o.toISOString());const u=function(e){if(e)return e.toLowerCase()}(s);u&&(l.order=u),this.logger.debug(`Querying price snapshots for token ${r}, page ${a}, limit ${c}`);const d=await this.http.get("/price-oracle/fetch-price",l);if(!d)throw H("No response from price history service",500);const h=this.transformApiResponseToPriceHistory(d);return this.logger.debug(`Found ${h.snapshots.length} price snapshots, total ${h.total}`),h},"Failed to fetch price history",this.logger)}transformApiResponseToPriceHistory(e){if(!pr(e))throw H("Invalid API response: missing data wrapper",500);const t=mr(e);if(!t||"object"!=typeof t)throw H("Invalid API response: data is not an object",500);const n=t,r=n.data;if(!Array.isArray(r))throw H("Invalid API response: missing or invalid data.data array",500);const i=n.meta;if(!i||"object"!=typeof i)throw H("Invalid API response: missing data.meta pagination info",500);const o=i,s=r.map(e=>{if("object"!=typeof e||null===e)throw H("Invalid API response: invalid snapshot item",500);const t=e;return{price:t.price,timestamp:He(t.createdAt),tokenId:Ks({collection:t.collection,category:t.category,type:t.type,additionalKey:t.additionalKey})}}),a=Me(o.currentPage,1),c=Me(o.totalPages,1);return{snapshots:s,page:a,limit:Me(o.pageSize,50),total:Me(o.totalItems,0),totalPages:c,hasNext:a<c,hasPrevious:a>1}}async fetchAllPriceHistory(e){if(!e)throw W("options","Fetch options");return this.logger.debug("Fetching all price history with options:",e),wr(async()=>{const t=await Yo((t,n)=>this.fetchPriceHistory({...e,page: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});return function(e,t=e.length,n="items"){const r=e.length||0;return{page:1,limit:r,total:t,totalPages:r>0?Xo(t,r):1,hasNext:!1,hasPrevious:!1,[n]:e}}(t.items,t.total,"snapshots")},"Failed to fetch all price history",this.logger)}validateOptions(e){const t=Re(e.page,1),n=Re(e.limit,10),{from:r,to:i,sortOrder:o}=e;if(nt(e,"tokenName","tokenId",{description:"token identifier"}),r&&!je(r))throw j("from must be a valid Date","from");if(i&&!je(i))throw j("to must be a valid Date","to");o&&ue(o,"sortOrder"),Ye(t,n,50)}}class sc extends Error{constructor(e,t,n){super(`API Error [${e}]: ${t}`),this.status=e,this.message=t,this.details=n,this.name="ApiError"}}function ac(e){return"object"==typeof e&&null!==e&&"collection"in e&&"category"in e&&"type"in e&&"additionalKey"in e&&"string"==typeof e.collection&&"string"==typeof e.category&&"string"==typeof e.type&&"string"==typeof e.additionalKey}function cc(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.positionId&&ac(t.token0ClassKey)&&ac(t.token1ClassKey)&&"number"==typeof t.fee&&"number"==typeof t.tickLower&&"number"==typeof t.tickUpper&&"string"==typeof t.liquidity&&"string"==typeof t.feeGrowthInside0Last&&"string"==typeof t.feeGrowthInside1Last&&"string"==typeof t.tokensOwed0&&"string"==typeof t.tokensOwed1}class lc{constructor(e){this.client=b(e.baseUrl,e.timeout??3e4)}async getPoolData(e){return wr(async()=>{if("string"==typeof e.token0||"string"==typeof e.token1)throw new B(`GalaChain API getPoolData requires TokenClassKey objects, not strings. Received: token0="${"string"==typeof e.token0?e.token0:"[object]"}", token1="${"string"==typeof e.token1?e.token1:"[object]"}". Convert pipe-delimited tokens using parseToken() before calling getPoolData(). Example: parseToken("GALA|Unit|none|none") → { collection: "GALA", category: "Unit", type: "none", additionalKey: "none" }`,"token","INVALID_TOKEN_FORMAT");const t=await this.client.post("/api/asset/dexv3-contract/GetPoolData",e);this.validateResponse(t.data);const n=t.data.Data;if(!function(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.token0&&"string"==typeof t.token1&&ac(t.token0ClassKey)&&ac(t.token1ClassKey)&&"number"==typeof t.fee&&"number"==typeof t.tickSpacing&&"string"==typeof t.liquidity&&"string"==typeof t.sqrtPrice&&"number"==typeof t.tick&&"string"==typeof t.feeGrowthGlobal0&&"string"==typeof t.feeGrowthGlobal1}(n))throw new sc(t.status,"Invalid pool data response format",n);return n},"GalaChainGatewayClient.getPoolData",void 0,e=>{throw this.handleError(e,"getPoolData")})}async getSlot0(e){return wr(async()=>{if("string"==typeof e.token0||"string"==typeof e.token1)throw new B(`GalaChain API getSlot0 requires TokenClassKey objects, not strings. Received: token0="${"string"==typeof e.token0?e.token0:"[object]"}", token1="${"string"==typeof e.token1?e.token1:"[object]"}". Convert pipe-delimited tokens using parseToken() before calling getSlot0(). Example: parseToken("GALA|Unit|none|none") → { collection: "GALA", category: "Unit", type: "none", additionalKey: "none" }`,"token","INVALID_TOKEN_FORMAT");const t=await this.client.post("/api/asset/dexv3-contract/GetSlot0",e);this.validateResponse(t.data);const n=t.data.Data;if(!function(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.sqrtPrice&&"number"==typeof t.tick&&"string"==typeof t.liquidity}(n))throw new sc(t.status,"Invalid slot0 data response format",n);return n},"GalaChainGatewayClient.getSlot0",void 0,e=>{throw this.handleError(e,"getSlot0")})}async getPositions(e){return wr(async()=>{const t=await this.client.post("/api/asset/dexv3-contract/GetPositions",e);this.validateResponse(t.data);const n=t.data.Data;let r;r=n&&"object"==typeof n&&"positions"in n&&Array.isArray(n.positions)?n.positions:n&&"object"==typeof n&&"positionId"in n?[n]:Array.isArray(n)?n:[];for(const e of r)if(!cc(e))throw new sc(t.status,"Invalid position in response",e);return{positions:r,count:r.length}},"GalaChainGatewayClient.getPositions",void 0,e=>{throw this.handleError(e,"getPositions")})}async getPositionById(e,t,n,r,i,o,s){return wr(async()=>{let a,c;if(void 0!==t&&void 0!==n&&void 0!==r&&void 0!==i&&void 0!==o){a={owner:e,token0:"string"==typeof t?{collection:t,category:"Unit",type:"none",additionalKey:"none"}:t,token1:"string"==typeof n?{collection:n,category:"Unit",type:"none",additionalKey:"none"}:n,fee:r,tickLower:i,tickUpper:o},s&&(a.positionId=s),c=`${e}/${t}/${n}/${r}`}else a={positionId:e},c=e;const l=await this.client.post("/api/asset/dexv3-contract/GetPositions",a);this.validateResponse(l.data);const u=l.data.Data;let d;if(u&&"object"==typeof u&&"positionId"in u&&!("positions"in u))d=u;else{if(!(u&&Array.isArray(u.positions)&&u.positions.length>0))throw new sc(404,`Position not found: ${c}`);d=u.positions[0]}const h={Data:d,Status:l.status};return void 0!==l.data.Message&&(h.Message=l.data.Message),h},"GalaChainGatewayClient.getPositionById",void 0,t=>{throw this.handleError(t,`getPositionById(${e})`)})}async getRemoveLiquidityEstimation(e){return wr(async()=>{const t=await this.client.post("/api/asset/dexv3-contract/GetRemoveLiquidityEstimation",e);this.validateResponse(t.data);const n=t.data.Data;if("string"!=typeof n.amount0||"string"!=typeof n.amount1)throw new sc(t.status,"Invalid removal estimation response format",n);return n},"GalaChainGatewayClient.getRemoveLiquidityEstimation",void 0,e=>{throw this.handleError(e,"getRemoveLiquidityEstimation")})}validateResponse(e){if(!e||"object"!=typeof e)throw new sc(500,"Invalid response format: not an object");if(!("Data"in e)||!("Status"in e))throw new sc(500,"Invalid response format: missing Data or Status field");if(e.Status>=400)throw new sc(e.Status,e.Message??"Gateway error",e.Data)}handleError(e,t){if(e instanceof sc)return e;if(I(e)){const n=e.response?.status??500,r=e.response?.data,i=r?.Message??A(e);return new sc(n,`${t}: ${i}`,r?.Data??void 0)}return new sc(500,`${t}: ${A(e)}`)}}class uc{constructor(e){this.http=e}async getUserAssets(e,t=20,n=0){return wr(async()=>{if(!Qe(e))throw W("walletAddress","Wallet address");const r=jo(Math.floor(n/t)+1),i={};i.address=e,i.page=r,i.limit=t;const o=await this.http.get("/user/assets",i);if(!o||"object"!=typeof o)throw new sc(500,"Invalid response format: not an object");const s=mr(o);if(!s||"object"!=typeof s)throw new sc(500,"Invalid response format: missing data wrapper");const a=s.token;if(!Array.isArray(a))throw new sc(500,"Invalid response format: token array must be an array");const c=[];for(const e of a){if("object"!=typeof e||null===e)throw new sc(500,"Invalid asset in response: asset must be an object");const t=e;if(!Qe(t.symbol)||!Qe(t.name))throw new sc(500,"Invalid asset in response: missing symbol or name",t);const n="number"==typeof t.decimals?t.decimals:"string"==typeof t.decimals?parseInt(t.decimals,10):void 0;if("number"!=typeof n||isNaN(n))throw new sc(500,"Invalid asset in response: decimals must be a number",t);const r={tokenId:t.compositeKey||`${t.symbol}$Unit$none$none`,symbol:t.symbol,name:t.name,decimals:n,balance:t.quantity||"0"};t.image&&(r.imageUrl=t.image),t.verify&&(r.verified=t.verify),c.push(r)}const l={tokens:c,count:"number"==typeof s.count?s.count:c.length};return void 0!==s.totalValue&&(l.totalValue=String(s.totalValue)),l},`getUserAssets(${e})`,void 0,t=>{throw this.handleError(t,`getUserAssets(${e})`)})}async fetchTokenList(e={}){return wr(async()=>{const{address:t,search:n,page:r=1,limit:i=20}=e,o={page:r,limit:Vo(i,1,20)};t&&(o.address=t),n&&(o.search=n);const s=await this.http.get("/user/token-list",o);if(!s||"object"!=typeof s)throw new sc(500,"Invalid response format: not an object");const a=mr(s);if(!a||"object"!=typeof a)throw new sc(500,"Invalid response format: missing data wrapper");const c=a.token;if(!Array.isArray(c))throw new sc(500,"Invalid response format: token array must be an array");const l=[];for(const e of c){if("object"!=typeof e||null===e)throw new sc(500,"Invalid token in response: must be an object");const t=e;if(!Qe(t.symbol))throw new sc(500,'Invalid token in response: missing required field "symbol"',{token:t});if(!Qe(t.name))throw new sc(500,'Invalid token in response: missing required field "name"',{token:t});const n=t.decimals;if("string"!=typeof n&&"number"!=typeof n)throw new sc(500,'Invalid token in response: missing required field "decimals"',{token:t});if(!Qe(t.compositeKey))throw new sc(500,'Invalid token in response: missing required field "compositeKey"',{token:t});l.push({image:"string"==typeof t.image?t.image:"",name:t.name,symbol:t.symbol,decimals:String(n),description:"string"==typeof t.description?t.description:"",verify:"boolean"==typeof t.verify&&t.verify,compositeKey:t.compositeKey,additionalKey:"string"==typeof t.additionalKey?t.additionalKey:"",category:"string"==typeof t.category?t.category:"",type:"string"==typeof t.type?t.type:"",collection:"string"==typeof t.collection?t.collection:"",subscribePrice:"boolean"==typeof t.subscribePrice&&t.subscribePrice,quantity:"string"==typeof t.quantity?t.quantity:"0"})}return{token:l,count:"number"==typeof a.count?a.count:l.length}},"fetchTokenList",void 0,e=>{throw this.handleError(e,"fetchTokenList")})}handleError(e,t){if(e instanceof sc)return e;if(I(e)){const n=e.response?.status??500,r=e.response?.data,i=r?.message??r?.Message??A(e),o=r?.Data??r?.data??void 0;if(r){e.config}return new sc(n,`${t}: ${i}`,o)}return new sc(500,`${t}: ${A(e)}`)}}class dc{static createClient(e,t=6e4){return b(e,t)}}function hc(e){try{if(!Qe(e))throw new Error("Token must be a non-empty string");return js(e)}catch(t){throw new B(`Invalid pipe-delimited token: "${e}". Expected format: "collection|category|type|additionalKey". Error: ${A(t)}`,"pipeDelimitedToken","INVALID_PIPE_DELIMITED_TOKEN_FORMAT")}}const gc=10;class pc extends hs{constructor(e,t,n){if(super(!1),this.pricingConcurrency=5,this.tokenConverter=new aa,this.webSocketService=t,this.dexQuoteService=n,this.getWalletAddress=e.getWalletAddress,this.galaChainBaseUrl=e.galaChainBaseUrl,this.bundlerBaseUrl=e.bundlerBaseUrl,this.gatewayBaseUrl=e.gatewayBaseUrl,this.privateKey=e.privateKey,!(e.gatewayBaseUrl&&e.bundlerBaseUrl&&e.dexBackendBaseUrl&&e.dexBackendHttp))throw new D("GSwapService requires explicit gatewayBaseUrl, bundlerBaseUrl, dexBackendBaseUrl, and dexBackendHttp configuration. These must be provided by LaunchpadSDK to ensure environment alignment.","gswapConfig");try{this.gatewayClient=new lc({baseUrl:e.gatewayBaseUrl,timeout:3e4}),this.dexBackendClient=new uc(e.dexBackendHttp),this.logger.debug("HTTP clients initialized successfully",{gatewayUrl:e.gatewayBaseUrl,dexBackendUrl:e.dexBackendBaseUrl})}catch(e){throw this.logger.error("Failed to initialize HTTP clients",e),new D("Failed to initialize GSwapService HTTP clients","httpClients")}}setPricingConcurrency(e){if(e<1)throw J("pricingConcurrency",1,e,"Pricing concurrency");e>100&&this.logger.warn("Pricing concurrency > 100 may cause performance issues",{concurrency:e}),this.pricingConcurrency=e,this.logger.debug("Updated pricing concurrency",{concurrency:this.pricingConcurrency})}async getSwapQuoteExactInput(e){try{if(wo(e.amount).isLessThanOrEqualTo(0))throw new M("Amount must be greater than zero",{amount:e.amount,fromToken:e.fromToken,toToken:e.toToken});if(!this.dexQuoteService)throw new M("DexQuoteService not configured - cannot provide quotes",{fromToken:e.fromToken,toToken:e.toToken});this.logger.debug("Getting swap quote for exact input",{fromToken:e.fromToken,toToken:e.toToken,amount:e.amount});const t=this.tokenConverter.toLaunchpadFormat(e.fromToken),n=this.tokenConverter.toLaunchpadFormat(e.toToken),[r,i]=t<n?[t,n]:[n,t],o=[3e3,500,1e4];let s;for(const a of o)try{const o=await this.dexQuoteService.fetchCompositePoolData({token0:r,token1:i,fee:a,gatewayBaseUrl:this.gatewayBaseUrl}),s=await this.dexQuoteService.calculateDexPoolQuoteExactAmount({compositePoolData:o,fromToken:t,toToken:n,amount:e.amount}),c=wo(s.currentSqrtPrice),l=wo(s.newSqrtPrice),u=c.gt(l)?c.minus(l).dividedBy(c):wo(0),d=wo(s.amount0),h=wo(s.amount1),g=_o(d),p=_o(h);this.logger.debug("=== AMOUNT SELECTION RAW DATA ===",{"quoteResult.amount0":s.amount0,"quoteResult.amount1":s.amount1,"amount0BN.isNegative()":g,"amount1BN.isNegative()":p});const f=g?d:h;this.logger.debug("=== AMOUNT SELECTION RESULT ===",{selectedFromAmount0:g,selectedAmount:f.toFixed(),selectedAmountAbs:f.absoluteValue().toFixed()});const m=f.absoluteValue().toFixed();return{fromToken:e.fromToken,toToken:e.toToken,inputAmount:e.amount,estimatedOutput:m,feeTier:a,priceImpact:u.toFixed(),executionPrice:this.calculateExecutionPrice(e.amount,m),currentSqrtPrice:s.currentSqrtPrice,newSqrtPrice:s.newSqrtPrice}}catch(e){s=e,this.logger.debug("DexQuoteService failed for fee tier, trying next",{feeTier:a,error:S(e)?e.message:"Unknown error"})}throw s||new M("No available fee tiers for quote",{feeTiers:o,fromToken:e.fromToken,toToken:e.toToken})}catch(e){this.handleGSwapError("Failed to get swap quote for exact input",M,e)}}async getSwapQuoteExactOutput(e){try{if(wo(e.amount).isLessThanOrEqualTo(0))throw new M("Amount must be greater than zero",{amount:e.amount,fromToken:e.fromToken,toToken:e.toToken});if(!this.dexQuoteService)throw new M("DexQuoteService not configured - cannot provide quotes",{fromToken:e.fromToken,toToken:e.toToken});this.logger.debug("Getting swap quote for exact output",{fromToken:e.fromToken,toToken:e.toToken,amount:e.amount});const t=this.tokenConverter.toLaunchpadFormat(e.fromToken),n=this.tokenConverter.toLaunchpadFormat(e.toToken),[r,i]=t<n?[t,n]:[n,t],o=[3e3,500,1e4];let s;for(const a of o)try{const o=await this.dexQuoteService.fetchCompositePoolData({token0:r,token1:i,fee:a,gatewayBaseUrl:this.gatewayBaseUrl}),s=await this.dexQuoteService.calculateDexPoolQuoteExactAmount({compositePoolData:o,fromToken:t,toToken:n,amount:e.amount}),c=wo(s.currentSqrtPrice),l=wo(s.newSqrtPrice),u=c.gt(l)?c.minus(l).dividedBy(c):wo(0),d=o.pool.token0,h="string"==typeof d?Hs(d).collection:"object"==typeof d&&null!==d&&"tokenName"in d?d.tokenName:String(d),g=Hs(n).collection===h?s.amount1:s.amount0;return{fromToken:e.fromToken,toToken:e.toToken,inputAmount:g,estimatedOutput:e.amount,feeTier:a,priceImpact:u.toFixed(),executionPrice:this.calculateExecutionPrice(g,e.amount),currentSqrtPrice:s.currentSqrtPrice,newSqrtPrice:s.newSqrtPrice}}catch(e){s=e,this.logger.debug("DexQuoteService failed for fee tier, trying next",{feeTier:a,error:S(e)?e.message:"Unknown error"})}throw s||new M("No available fee tiers for quote",{feeTiers:o,fromToken:e.fromToken,toToken:e.toToken})}catch(e){this.handleGSwapError("Failed to get swap quote for exact output",M,e)}}async executeSwap(e){try{if(!this.privateKey)throw new D("GSwapService not initialized with signing capability (privateKey required)","privateKey");this.logger.debug("Executing swap",{fromToken:e.fromToken,toToken:e.toToken,inputAmount:e.inputAmount});const{gswapToken0:t,gswapToken1:n}=this.convertTokenPair(e.fromToken,e.toToken),r=bo(e.estimatedOutput,e.slippageTolerance||.01),i=this.getWalletAddress();if(!i)throw new B("Wallet address required for swap execution","walletAddress",_.REQUIRED);let o;try{const t=await this.getSwapQuoteExactInput({fromToken:e.fromToken,toToken:e.toToken,amount:e.inputAmount});o=t.currentSqrtPrice,this.logger.debug("Quote refetch successful - extracted sqrtPrices",{currentSqrtPrice:o,newSqrtPrice:t.newSqrtPrice,feeTier:t.feeTier})}catch(t){this.logger.debug("Could not re-fetch quote for sqrtPrice, using default",{fromToken:e.fromToken,toToken:e.toToken,error:A(t)})}const s={fromToken:t,toToken:n,inputAmount:e.inputAmount,minOutput:r.toFixed(),feeTier:e.feeTier,walletAddress:i,slippageTolerance:e.slippageTolerance||.01,...!Ze(o)&&{currentSqrtPrice:o}},a=await this.sendSwapToBundler(s);this.logger.debug("Swap submitted, monitoring transaction",{transactionId:a,fromToken:e.fromToken,toToken:e.toToken}),await this.ensureWebSocketConnected();const c=await this.webSocketService.waitForTransaction(a);return{transactionId:c.transactionId,status:c.status,fromToken:e.fromToken,toToken:e.toToken,inputAmount:e.inputAmount,outputAmount:e.estimatedOutput,feeTier:e.feeTier,slippageTolerance:e.slippageTolerance||.01,timestamp:new Date(c.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(a)}}}catch(e){const t=e;this.handleGSwapError("Failed to execute swap",L,e,{transactionHash:t?.txHash})}}async getUserAssets(e,t=1,n=20){return wr(async()=>{if(!mt(e))throw new F(z("walletAddress","a valid address (0x..., eth|..., or client|...)").message,new Error("INVALID_ADDRESS_FORMAT"),e,"INVALID_ADDRESS");this.logger.debug("Fetching user assets",{walletAddress:e,page:t,limit:n});return(await this.dexBackendClient.fetchTokenList({address:e,page:t,limit:n})).token.filter(e=>"0"!==e.quantity).map(e=>this.transformRawTokenToUserAsset(e)).filter(e=>null!==e)},"Failed to fetch user assets",this.logger,this.createGSwapErrorHandler(F,{walletAddress:e,page:t,limit:n}))}async getAllUserAssets(e){return wr(async()=>{if(!mt(e))throw new F(z("walletAddress","a valid address (0x..., eth|..., or client|...)").message,new Error("INVALID_ADDRESS_FORMAT"),e,"INVALID_ADDRESS");this.logger.debug("Fetching all user assets (auto-paginated with optimization)",{walletAddress:e});let t=!1;const n=await Yo(async(n,r)=>{const i=await this.dexBackendClient.fetchTokenList({address:e,page:n,limit:r}),o=[];for(const e of i.token){if("0"===e.quantity){t=!0;break}const n=this.transformRawTokenToUserAsset(e);n&&o.push(n)}return{items:o,page:n,limit:r,total:o.length,totalPages:1,hasNext:!t&&i.token.length===r,hasPrevious:n>1}},{maxPages:20,pageSize:20,logger:this.logger});return this.logger.debug("Fetched all user assets",{walletAddress:e,totalAssets:n.items.length}),n.items},"Failed to fetch all user assets",this.logger,this.createGSwapErrorHandler(F,{walletAddress:e}))}async fetchAvailableDexTokens(e={}){return wr(async()=>{const{search:t,page:n=1,limit:r=20}=e;this.logger.debug("Fetching available DEX tokens",{search:t,page:n,limit:r});const i=await this.dexBackendClient.fetchTokenList({...!Ze(t)&&{search:t},page:n,limit:r}),o=i.token.map(e=>this.transformRawTokenToDexToken(e)),s=Qo(Ho(n,r),r,i.count);return{tokens:o,count:i.count,page:n,limit:r,hasMore:s}},"Failed to fetch available DEX tokens",this.logger,this.createGSwapErrorHandler(F,{...e}))}async fetchAllAvailableDexTokens(e={}){return wr(async()=>{const{search:t}=e;this.logger.debug("Fetching all available DEX tokens (auto-paginated)",{search:t});const n=await Yo(async(e,n)=>{const r=await this.dexBackendClient.fetchTokenList({...!Ze(t)&&{search:t},page:e,limit:n});return{items:r.token.map(e=>this.transformRawTokenToDexToken(e)),page:e,limit:n,total:r.token.length,totalPages:1,hasNext:r.token.length===n,hasPrevious:e>1}},{maxPages:20,pageSize:20,logger:this.logger});return this.logger.debug("Fetched all available DEX tokens",{search:t,totalTokens:n.items.length}),n.items},"Failed to fetch all available DEX tokens",this.logger,this.createGSwapErrorHandler(F,e))}async getPoolInfo(e,t){try{if(!e)throw W("tokenA","Token A");if(!t)throw W("tokenB","Token B");this.logger.debug("Fetching pool info",{tokenA:e,tokenB:t});const{gswapToken0:n,gswapToken1:r}=this.convertTokenPair(e,t),i=[500,3e3,1e4];let o=wo(0),s=0;for(const a of i)try{const e="string"==typeof n?Hs(n):n,t="string"==typeof r?Hs(r):r,i=await this.gatewayClient.getPoolData({token0:e,token1:t,fee:a});i&&(o=o.plus(wo(i.liquidity)),s++)}catch{this.logger.debug("Pool not found for fee tier",{tokenA:e,tokenB:t,feeTier:a})}return{tokenA:e,tokenB:t,liquidity:o.toFixed(),feeTiers:i,swapCount:s}}catch(n){return this.logger.warn("Failed to fetch pool info",n),this.logger.debug("Pool error details",{error:new O(`Failed to fetch pool info: ${A(n)}`,n,e,t,this.extractGSwapErrorCode(n))}),{tokenA:e,tokenB:t,liquidity:"0",feeTiers:[500,3e3,1e4],swapCount:0}}}chunkArray(e,t){const n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}async fetchPositionPrices(e){const t=this.pricingConcurrency;if(0===e.length)return new Map;const n=new Map;for(const t of e){const e=`${t.token0}|${t.token1}|${t.feeTier}`;n.has(e)||n.set(e,{token0:t.token0,token1:t.token1,feeTier:t.feeTier})}const r=Array.from(n.values()),i=this.chunkArray(r,t);this.logger.debug("Fetching pricing for positions",{totalPositions:e.length,uniquePoolsToPrice:n.size,chunks:i.length,concurrency:t});const o=new Map;for(let e=0;e<i.length;e++){const t=i[e];(await Promise.allSettled(t.map(async e=>{const t=await this.getSwapQuoteExactInput({fromToken:e.token0,toToken:e.token1,amount:"1"});return{key:`${e.token0}|${e.token1}|${e.feeTier}`,data:{token0:e.token0,token1:e.token1,feeTier:e.feeTier,currentPrice:t.executionPrice,executionPrice:t.executionPrice,priceImpact:t.priceImpact,estimatedOutput:t.estimatedOutput,pricedAt:new Date}}}))).forEach(e=>{"fulfilled"===e.status?o.set(e.value.key,e.value.data):this.logger.warn("Failed to fetch price for pool",{error:e.reason})})}return o}normalizePositionResponse(e,t){const n=e=>{if(!e)return"";if("string"==typeof e)return e;if("object"==typeof e){if(e.type&&"none"!==e.type)return e.type;if(e.collection)return e.collection;if(e.symbol)return e.symbol;if(e.tokenSymbol)return e.tokenSymbol;if(e.name)return e.name}return""},r=e.token0Symbol||n(e.token0)||n(e.tokenA)||e.tokenSymbol0||"",i=e.token1Symbol||n(e.token1)||n(e.tokenB)||e.tokenSymbol1||"",o=r?this.tokenConverter.normalizeInternalApiResponse(r):"",s=i?this.tokenConverter.normalizeInternalApiResponse(i):"";return{positionId:e.positionId||e.id||"",ownerAddress:t||e.ownerAddress||e.owner||"",token0:o,token1:s,feeTier:e.feeTier||e.fee||e.feeAmount||0,tickLower:e.tickLower||e.lowerTick||0,tickUpper:e.tickUpper||e.upperTick||0,liquidity:String(e.liquidity||e.liquidityAmount||"0"),amount0:String(e.amount0||e.amountA||"0"),amount1:String(e.amount1||e.amountB||"0"),feeAmount0:String(e.feeAmount0||e.feesA||"0"),feeAmount1:String(e.feeAmount1||e.feesB||"0"),...e.createdAt&&{createdAt:new Date(e.createdAt)},...e.updatedAt&&{updatedAt:new Date(e.updatedAt)}}}parseTokenFlexible(e){try{return Hs(e)}catch(t){if(S(t)&&A(t).includes("Plain token string"))return this.logger.debug("Using default TokenClassKey for simple token symbol",{token:e}),{collection:"Token",category:"Unit",type:e,additionalKey:"none"};throw t}}transformRawTokenToDexToken(e){return{image:e.image,name:e.name,symbol:e.symbol,decimals:Le(e.decimals,18),description:e.description,verified:e.verify,compositeKey:e.compositeKey,additionalKey:e.additionalKey,category:e.category,type:e.type,collection:e.collection,subscribePrice:e.subscribePrice}}transformRawTokenToUserAsset(e){const t=e.symbol||"UNKNOWN";try{const n=e.compositeKey?Hs(e.compositeKey.replace(/\$/g,"|")):Hs(`${t}|Unit|none|none`);return{...this.transformRawTokenToDexToken(e),tokenId:n,balance:ko(e.quantity||"0")}}catch(e){return this.logger.debug(`Skipping asset with processing error: ${t}`,{error:A(e)}),null}}async getUserLiquidityPositions(e,n=10,r,i){try{if(!e)throw W("ownerAddress","Owner address");this.logger.debug("Fetching user liquidity positions",{ownerAddress:e,limit:n,bookmark:r});const o=`${this.galaChainBaseUrl}/api/asset/dexv3-contract/GetUserPositions`,s={user:e,limit:n,bookmark:r||""};this.logger.debug("Sending position query request",{endpoint:o,payload:s});const a=await t.post(o,s,{headers:{"Content-Type":"application/json",Accept:"application/json"}}),c=mr(a);if(200!==a.status||1!==c?.Status)return this.logger.warn("Unexpected API response status",{httpStatus:a.status,apiStatus:c?.Status}),{items:[]};const l=c?.Data||{},u=l.positions||[],d=l.nextBookMark,h=u.filter(e=>null!=e&&"object"==typeof e&&("positionId"in e||"id"in e)).map(t=>this.normalizePositionResponse(t,e));let g;this.logger.debug("Retrieved liquidity positions",{count:h.length,hasNextBookmark:!!d,nextBookmark:d}),i?.withPrices&&h.length>0&&(g=await this.fetchPositionPrices(h));const p={items:h};return Ze(d)||(p.nextBookmark=d),Ze(g)||(p.prices=g),p}catch(t){I(t)&&this.logger.error("Position query failed with HTTP error",{status:t.response?.status,statusText:t.response?.statusText,data:t.response?.data,endpoint:this.galaChainBaseUrl,ownerAddress:e}),this.handleGSwapError("Failed to fetch user liquidity positions",U,t)}}async getAllSwapUserLiquidityPositions(e,t){try{if(!e)throw W("ownerAddress","Owner address");this.logger.debug("Fetching all user liquidity positions (auto-paginated)",{ownerAddress:e});const n=async t=>{const n=await this.getUserLiquidityPositions(e,gc,t,void 0);return{items:n.items,nextBookmark:n.nextBookmark}},r=await async function(e,t={}){const{maxPages:n=1e4,logger:r,pageSize:i=20}=t,o=[];let s,a=0;for(;a<n;){r&&r.debug(`Auto-pagination (bookmark): fetching page ${a+1} with pageSize ${i}`,{bookmark:s});const t=await e(s,i);let n,c,l;if(Array.isArray(t))n=t,c=void 0,l=!1;else{if(!t||"object"!=typeof t||!("items"in t)){r&&r.warn("Auto-pagination (bookmark): received invalid result structure, stopping");break}n=t.items,c=t.nextBookmark,l=!0}if(!Array.isArray(n)){r&&r.warn("Auto-pagination (bookmark): received invalid items array, stopping");break}if(0===n.length){r&&r.debug(`Auto-pagination (bookmark): no items returned on page ${a+1}, exiting loop`);break}o.push(...n),a++,r&&r.debug(`Auto-pagination (bookmark): page ${a} returned ${n.length} items`,{hasNextBookmark:!!c,format:l?"BookmarkPaginationResult":"legacy-array"});const u=n.length<i;if(l&&(""===c||void 0===c)){r&&r.debug("Auto-pagination (bookmark): no nextBookmark returned, reached end of results",{nextBookmark:""===c?"(empty string)":"(undefined)"});break}if(u){r&&r.debug("Auto-pagination (bookmark): received fewer items than limit, reached last page",{received:n.length,pageSize:i,format:l?"BookmarkPaginationResult":"legacy-array"});break}s=c}return a>=n&&r&&r.warn(`Auto-pagination (bookmark): exceeded maxPages limit of ${n}, stopping iteration`),r&&r.debug(`Auto-pagination (bookmark): completed with total items: ${o.length}`,{pageCount:a}),{items:o,total:o.length}}(n,{maxPages:1e4,logger:this.logger,pageSize:gc}),i=r.items;if(this.logger.debug("Fetched all user liquidity positions",{ownerAddress:e,totalPositions:i.length}),t?.withPrices&&i.length>0){return{items:i,prices:await this.fetchPositionPrices(i)}}return i}catch(t){this.handleGSwapError("Failed to fetch all user liquidity positions",U,t,{ownerAddress:e})}}async getLiquidityPosition(e,t){try{if(!e)throw W("ownerAddress","Owner address");if(!t.token0)throw W("token0","Token 0");if(!t.token1)throw W("token1","Token 1");this.logger.debug("Fetching liquidity position",{ownerAddress:e,position:t}),this.validateTickSpacing(t.tickLower,t.tickUpper,t.fee);const{gswapToken0:n,gswapToken1:r}=this.convertTokenPair(t.token0,t.token1),i=hc(n),o=hc(r),s=(await this.gatewayClient.getPositions({owner:e,token0:i,token1:o,fee:t.fee,tickLower:t.tickLower,tickUpper:t.tickUpper})).positions.find(e=>e.tickLower===t.tickLower&&e.tickUpper===t.tickUpper);if(!s||"object"!=typeof s||!("positionId"in s)&&!("id"in s))throw new U("Invalid position data returned from API",null,"INVALID_DATA");const a=this.normalizePositionResponse(s,e);return this.logger.debug("Retrieved liquidity position",{positionId:a.positionId}),a}catch(e){this.handleGSwapError("Failed to fetch liquidity position",U,e)}}async getLiquidityPositionById(e,t,n,r,i,o,s){try{if(!e)throw W("ownerAddress","Owner address");if(!t)throw W("positionId","Position ID");let a;this.logger.debug("Fetching liquidity position by ID",{ownerAddress:e,positionId:t,hasToken0:!!n,hasToken1:!!r,hasFee:!!i,hasTickLower:!Ze(o),hasTickUpper:!Ze(s)});let c=null;const l=5,u=2e3;for(let d=1;d<=l;d++)try{if(n&&r&&!Ze(i)&&!Ze(o)&&!Ze(s))try{this.logger.debug("Attempting compound key lookup",{ownerAddress:e,token0:n,token1:r,feeTier:i,tickLower:o,tickUpper:s});if(a=(await this.gatewayClient.getPositionById(e,n,r,i,o,s,t)).Data,a&&"object"==typeof a&&("positionId"in a||"id"in a)){this.logger.debug("Successfully fetched position via compound key",{attempt:d,positionId:t});break}throw new U("Invalid position data from compound key lookup",null,"INVALID_DATA")}catch(e){this.logger.debug("Compound key lookup failed, trying fallback",{attempt:d,error:S(e)?e.message:e})}try{if(a=(await this.gatewayClient.getPositionById(t)).Data,a&&"object"==typeof a&&("positionId"in a||"id"in a)){this.logger.debug("Successfully fetched position on attempt",{attempt:d,positionId:t});break}throw new U("Invalid position data from direct lookup",null,"INVALID_DATA")}catch(n){this.logger.debug("Direct position lookup failed, trying fallback via GetUserPositions",{attempt:d,positionId:t,error:S(n)?n.message:n});const r=await this.getAllSwapUserLiquidityPositions(e),i=Array.isArray(r)?r:r.items;if(i.length>0){const e=i.find(e=>Is(e.positionId||"",t));if(e){a=e,this.logger.debug("Found position via fallback (GetUserPositions)",{attempt:d,positionId:t,totalPositions:i.length});break}}if(c=te(t),d<l){this.logger.warn("Fallback query did not find position, retrying",{attempt:d,positionId:t,ownerAddress:e,foundCount:i.length}),await new Promise(e=>setTimeout(e,u));continue}}}catch(e){if(d<l){this.logger.warn("Error fetching position, retrying",{attempt:d,positionId:t,error:A(e)}),await new Promise(e=>setTimeout(e,u));continue}c=S(e)?e:new Error(String(e))}if(!a||"object"!=typeof a||!("positionId"in a)&&!("id"in a))throw this.logger.error("Invalid position data returned from API after retries",{positionId:t,resultType:typeof a,resultKeys:a?Object.keys(a):"null",resultValue:JSON.stringify(a),lastError:c?.message}),c||te(t);const d=this.normalizePositionResponse(a,e);return this.logger.debug("Retrieved liquidity position by ID",{positionId:d.positionId}),d}catch(e){this.handleGSwapError("Failed to fetch liquidity position by ID",U,e)}}async fetchSwapPositionDirect(e){try{this.logger.debug("Fetching swap position via direct compound key",{token0:e.token0,token1:e.token1,fee:e.fee,owner:e.owner});const t="string"==typeof e.token0?this.parseTokenFlexible(e.token0):e.token0,n="string"==typeof e.token1?this.parseTokenFlexible(e.token1):e.token1;this.logger.debug("Fetching position via compound key",{token0:e.token0,token1:e.token1,fee:e.fee,owner:e.owner});const r=await this.gatewayClient.getPositions({token0:t,token1:n,fee:e.fee,tickLower:e.tickLower,tickUpper:e.tickUpper,owner:e.owner});if(!r.positions||0===r.positions.length)throw new U("Position not found: No position exists for this compound key",null,"NOT_FOUND");const i=r.positions[0],o=this.normalizePositionResponse(i,e.owner);return this.logger.debug("Retrieved swap position via compound key",{positionId:o.positionId,token0:o.token0,token1:o.token1}),o}catch(e){this.handleGSwapError("Failed to fetch swap position via compound key",U,e)}}async estimateRemoveLiquidity(e){try{if(!e.token0)throw W("token0","Token 0");if(!e.token1)throw W("token1","Token 1");if(!e.liquidity)throw W("liquidity","Liquidity amount");if(!e.owner)throw W("owner","Owner address");this.logger.debug("Estimating liquidity removal",{token0:e.token0,token1:e.token1,owner:e.owner}),this.validateTickSpacing(e.tickLower,e.tickUpper,e.fee);const{gswapToken0:t,gswapToken1:n}=this.convertTokenPair(e.token0,e.token1),r=hc(t),i=hc(n),o=await this.gatewayClient.getRemoveLiquidityEstimation({token0:r,token1:i,fee:e.fee,amount:e.liquidity,tickLower:e.tickLower,tickUpper:e.tickUpper,owner:e.owner});return this.logger.debug("Estimated removal",{result:o}),o}catch(e){this.handleGSwapError("Failed to estimate liquidity removal",U,e)}}async addLiquidityByPrice(e){try{if(!this.privateKey)throw new D("GSwapService not initialized with signing capability (privateKey required)","privateKey");this.logger.debug("Adding liquidity by price",{token0:e.token0,token1:e.token1,priceRange:`${e.minPrice}-${e.maxPrice}`});const{gswapToken0:t,gswapToken1:n}=this.convertTokenPair(e.token0,e.token1);await this.ensureWebSocketConnected(),this.logger.debug("Converting price range to ticks",{token0:e.token0,token1:e.token1,minPrice:e.minPrice,maxPrice:e.maxPrice,fee:e.fee});const r=Hs(t),i=Hs(n),o=(await this.gatewayClient.getPoolData({token0:r,token1:i,fee:e.fee})).tickSpacing;this.logger.debug("Retrieved tick spacing from pool",{tickSpacing:o,fee:e.fee});const s=wo(e.minPrice),a=wo(e.maxPrice),c=Math.floor(Ao(s)),l=Math.ceil(Ao(a)),u=Oo(c,o),d=Oo(l,o);this.logger.debug("Converted price range to ticks",{minPrice:e.minPrice,maxPrice:e.maxPrice,tickLower:u,tickUpper:d,tickSpacing:o});const h=this.getWalletAddress();if(!h)throw new D("GSwapService: No wallet address available - cannot create position","walletAddress");const g="string"==typeof e.token0?Hs(e.token0):e.token0,p="string"==typeof e.token1?Hs(e.token1):e.token1;this.logger.debug("Sending AddLiquidity by price to bundler",{fee:e.fee,tickRange:`${u}-${d}`,walletAddress:h});const f=await this.sendAddLiquidityToBundler({token0:g,token1:p,fee:e.fee,tickLower:u,tickUpper:d,amount0Desired:e.amount0Desired,amount1Desired:e.amount1Desired,amount0Min:e.amount0Min||"0",amount1Min:e.amount1Min||"0",owner:h}),m={transactionId:f};if(m.positionId&&f){this.logger.debug("Position ID returned directly from backend",{transactionId:f,positionId:m.positionId}),await this.ensureWebSocketConnected();const e=await this.webSocketService.waitForTransaction(f);this.logger.debug("Liquidity transaction confirmed on-chain",{transactionId:f,status:e.status});const t=this.getWalletAddress();if(t&&m.positionId)try{const n=await this.getLiquidityPositionById(t,m.positionId),{createdAt:r,updatedAt:i,...o}=n,s=r instanceof Date?r.getTime():"number"==typeof r?r:void 0,a={...m,...o,positionId:m.positionId,status:e.status,transactionId:e.transactionId,timestamp:new Date(e.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(f)}};return Ze(s)||(a.createdAt=s),a}catch(t){return{...m,positionId:m.positionId,status:e.status,transactionId:e.transactionId,timestamp:new Date(e.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(f)}}}}if(f){this.logger.debug("Monitoring liquidity transaction (discovery mode)",{transactionId:f}),await this.ensureWebSocketConnected();const t=await this.webSocketService.waitForTransaction(f);let n;this.logger.debug("Liquidity transaction confirmed on-chain",{transactionId:f,status:t.status});let r=null;await new Promise(e=>setTimeout(e,2e3));try{const t=this.getWalletAddress();if(!t)throw new D("No wallet address available","walletAddress");const i=(await this.getUserLiquidityPositions(t,10)).items;if(i&&i.length>0){const t=Hs(e.token0).collection.toUpperCase(),o=Hs(e.token1).collection.toUpperCase(),s=[];for(const n of i){if(!n||!n.positionId)continue;const r=n.token0?.toUpperCase(),i=n.token1?.toUpperCase();if(!r||!i)continue;const a=Cs(r,i,t,o),c=n.feeTier===e.fee;a&&c&&s.push(n)}s.length>0&&(r=s[s.length-1],n=r.positionId,this.logger.debug("Found newly created position",{positionId:n,expectedTokens:`${e.token0}/${e.token1}`,expectedFee:e.fee,positionCount:i.length}))}}catch(e){this.logger.debug("Error waiting for position indexing",{error:A(e)})}let i=r;if(n)try{i=await this.getLiquidityPositionById(h,n)}catch(e){}const o=i?{ownerAddress:i.ownerAddress,token0:i.token0,token1:i.token1,feeTier:i.feeTier,tickLower:i.tickLower,tickUpper:i.tickUpper,liquidity:i.liquidity,amount0:i.amount0,amount1:i.amount1,feeAmount0:i.feeAmount0,feeAmount1:i.feeAmount1}:{};return{...m,...o,...n&&{positionId:n},status:t.status,transactionId:t.transactionId,timestamp:new Date(t.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(f)}}}return this.logger.warn("No transaction ID in liquidity result, cannot confirm position creation"),m}catch(e){if(S(e)){const t=T(e);t?.split("\n").slice(0,3).join(" | ")}this.handleGSwapError("Failed to add liquidity by price",U,e)}}async addSwapLiquidityByTicks(e){try{if(!this.privateKey)throw new D("GSwapService not initialized with signing capability (privateKey required)","privateKey");const t=this.getWalletAddress();if(!t)throw new D("GSwapService: No wallet address available - cannot create position","walletAddress");this.logger.debug("Adding liquidity by ticks with direct bundler",{token0:e.token0,token1:e.token1,fee:e.fee,walletAddress:t,tickRange:`${e.tickLower}-${e.tickUpper}`});const n="string"==typeof e.token0?Hs(e.token0):e.token0,r="string"==typeof e.token1?Hs(e.token1):e.token1;await this.ensureWebSocketConnected();const i=await this.sendAddLiquidityToBundler({token0:n,token1:r,fee:e.fee,tickLower:e.tickLower,tickUpper:e.tickUpper,amount0Desired:e.amount0Desired,amount1Desired:e.amount1Desired,amount0Min:e.amount0Min||"0",amount1Min:e.amount1Min||"0",owner:t});this.logger.info("Liquidity transaction submitted to bundler",{transactionId:i});const o=this.webSocketService.waitForTransaction(i),s={transactionId:i};if(s.positionId&&i){this.logger.info("Position ID returned directly from backend",{transactionId:i,positionId:s.positionId});const e=await o;this.logger.debug("Liquidity transaction confirmed on-chain",{transactionId:i,status:e.status});const t=this.getWalletAddress();if(t&&s.positionId)try{this.logger.debug("Fetching full position details",{positionId:s.positionId});const n=await this.getLiquidityPositionById(t,s.positionId);this.logger.debug("Fetched full position data",{positionId:n.positionId,liquidity:n.liquidity,amount0:n.amount0,amount1:n.amount1});const{createdAt:r,updatedAt:o,...a}=n,c=r instanceof Date?r.getTime():"number"==typeof r?r:void 0,l={...s,...a,positionId:s.positionId,status:e.status,transactionId:e.transactionId,timestamp:new Date(e.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(i)}};return Ze(c)||(l.createdAt=c),l}catch(t){return this.logger.warn("Could not fetch full position details",{positionId:s.positionId,error:A(t)}),{...s,positionId:s.positionId,status:e.status,transactionId:e.transactionId,timestamp:new Date(e.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(i)}}}}if(i){this.logger.debug("Monitoring liquidity transaction (discovery mode)",{transactionId:i});const n=await o;let r;this.logger.debug("Liquidity transaction confirmed on-chain",{transactionId:i,status:n.status});let a=null;const c="string"==typeof e.token0?e.token0:e.token0?.type??"unknown",l="string"==typeof e.token1?e.token1:e.token1?.type??"unknown";this.logger.debug("Waiting for position indexing after WebSocket confirmation"),this.logger.debug("Looking for matching position",{token0:c,token1:l,fee:e.fee});try{const t=this.getWalletAddress();if(!t)throw new D("No wallet address available","walletAddress");this.logger.debug("Fetching positions from API",{walletAddress:t,pageSize:gc});const n=3,i=5e3,o=3e3;let s=[];for(let c=1;c<=n;c++){const l=1===c?i:o;this.logger.debug("Position discovery attempt",{attempt:c,maxAttempts:n,delayMs:l}),await new Promise(e=>setTimeout(e,l)),this.logger.debug("Querying positions from API",{attempt:c,pageSize:gc});if(s=(await this.getUserLiquidityPositions(t,gc)).items,this.logger.debug("Got positions from API",{count:s?.length||0}),s&&s.length>0){const t=("string"==typeof e.token0?Hs(e.token0).collection:e.token0.collection).toUpperCase(),n=("string"==typeof e.token1?Hs(e.token1).collection:e.token1.collection).toUpperCase(),i=[];for(const r of s){if(!r||!r.positionId)continue;const o=r.token0?.toUpperCase(),s=r.token1?.toUpperCase();if(!o||!s){this.logger.debug("Skipping position with empty tokens",{positionId:r.positionId});continue}const a=Cs(o,s,t,n),c=r.feeTier===e.fee;this.logger.debug("Checking position against target",{positionId:r.positionId,tokens:`${o}/${s}`,tokensMatch:a,fee:r.feeTier,feeMatches:c}),a&&c&&i.push(r)}if(i.length>0){a=i[i.length-1],r=a.positionId,this.logger.info("Found newly created position",{positionId:r,liquidity:a.liquidity,amount0:a.amount0,amount1:a.amount1,fee:a.feeTier}),this.logger.debug("Found newly created position",{positionId:r,expectedTokens:`${e.token0}/${e.token1}`,expectedFee:e.fee,positionCount:s.length});break}this.logger.debug("No matching position found in this attempt")}else this.logger.debug("No positions returned from API in this attempt")}}catch(e){this.logger.error("Error fetching positions during discovery",{error:A(e)}),this.logger.debug("Error waiting for position indexing",{error:A(e)})}this.logger.debug("Position discovery complete",{positionId:r||"not found",found:!!r}),this.logger.debug("Matched position data",{positionId:a?.positionId,liquidity:a?.liquidity,amount0:a?.amount0,amount1:a?.amount1,feeAmount0:a?.feeAmount0,feeAmount1:a?.feeAmount1,token0:a?.token0,token1:a?.token1,feeTier:a?.feeTier});let u=a;if(r)try{this.logger.debug("Fetching full position details",{positionId:r}),u=await this.getLiquidityPositionById(t,r),this.logger.debug("Fetched full position data",{positionId:u.positionId,liquidity:u.liquidity,amount0:u.amount0,amount1:u.amount1,feeAmount0:u.feeAmount0,feeAmount1:u.feeAmount1})}catch(e){this.logger.warn("Could not fetch full position details, using discovered data",{positionId:r,error:A(e)})}const d=u?{ownerAddress:u.ownerAddress,token0:u.token0,token1:u.token1,feeTier:u.feeTier,tickLower:u.tickLower,tickUpper:u.tickUpper,liquidity:u.liquidity,amount0:u.amount0,amount1:u.amount1,feeAmount0:u.feeAmount0,feeAmount1:u.feeAmount1}:{};return{...s,...d,...r&&{positionId:r},status:n.status,transactionId:n.transactionId,timestamp:new Date(n.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(i)}}}return this.logger.warn("No transaction ID in liquidity result, cannot confirm position creation"),s}catch(e){this.handleGSwapError("Failed to add liquidity by ticks",U,e)}}async monitorBundlerTransaction(e,t,n="bundler"){let r;try{const i=await t;r={status:i.status,transactionId:i.transactionId||e,timestamp:i.timestamp||Date.now(),data:i.data},this.logger.debug(`${n} transaction confirmed on-chain`,{transactionId:e,status:r.status})}catch(t){return this.logger.warn(`WebSocket monitoring timeout for ${n} transaction, returning result with transaction ID`,{transactionId:e,error:A(t)}),{transactionId:e,status:"SUBMITTED",timestamp:new Date,wait:async t=>{try{await this.webSocketService.waitForTransaction(e)}catch{this.logger.debug("Explicit wait also timed out",{transactionId:e})}}}}return{transactionId:r.transactionId,status:r.status,timestamp:new Date(r.timestamp),wait:async t=>{await this.webSocketService.waitForTransaction(e)}}}async removeLiquidity(e){try{if(!this.privateKey)throw new D("Private key not available for bundler-direct operations","privateKey");this.logger.debug("Removing liquidity via bundler",{token0:e.token0,token1:e.token1,liquidity:e.liquidity});try{const t=De(e.liquidity,Number.NaN);if(isNaN(t))throw new B(`Invalid liquidity value: "${e.liquidity}". Must be a valid number. Position ID: ${e.positionId||"unknown"}`,"liquidity","INVALID_VALUE");if(0===t)throw new B(`Cannot remove zero liquidity from position. This would waste gas fees without any effect. Position ID: ${e.positionId||"unknown"}`,"liquidity","ZERO_VALUE")}catch(e){if(S(e)&&A(e).includes("Cannot remove zero liquidity"))throw e;if(S(e)&&A(e).includes("Invalid liquidity value"))throw e;throw e}const t="string"==typeof e.token0?Hs(e.token0):e.token0,n="string"==typeof e.token1?Hs(e.token1):e.token1;await this.ensureWebSocketConnected();const r=await this.sendRemoveLiquidityToBundler(e.tickLower,e.tickUpper,e.liquidity,t,n,e.fee,e.amount0Min||"0",e.amount1Min||"0",e.positionId||"");this.logger.debug("Liquidity removal submitted to bundler",{transactionId:r});const i=this.webSocketService.waitForTransaction(r);return this.monitorBundlerTransaction(r,i,"liquidity removal")}catch(e){this.handleGSwapError("Failed to remove liquidity",U,e)}}async collectPositionFees(e){try{if(!this.privateKey)throw new D("Private key not available for bundler-direct operations","privateKey");if(e.ownerAddress&&e.positionId&&!e.token0){this.logger.debug("Fetching position data before collecting fees",{ownerAddress:e.ownerAddress,positionId:e.positionId});const t=await this.getLiquidityPositionById(e.ownerAddress,e.positionId);if(!t)throw te(e.positionId);if(!t.token0||!t.token1)throw new U("Position missing token information",null,"INVALID_DATA");const{gswapToken0:n,gswapToken1:r}=this.convertTokenPair(t.token0,t.token1);return this.collectPositionFees({token0:n,token1:r,fee:t.feeTier,tickLower:t.tickLower,tickUpper:t.tickUpper,amount0Requested:e.amount0Max||e.amount0Requested||"0",amount1Requested:e.amount1Max||e.amount1Requested||"0",positionId:e.positionId})}if(!e.token0||!e.token1||void 0===e.fee||void 0===e.tickLower||void 0===e.tickUpper)throw W("parameters","token0, token1, fee, tickLower, tickUpper");this.logger.debug("Collecting position fees via bundler",{token0:"string"==typeof e.token0?e.token0:e.token0?.type??"unknown",token1:"string"==typeof e.token1?e.token1:e.token1?.type??"unknown",tickLower:e.tickLower,tickUpper:e.tickUpper});const t="string"==typeof e.token0?Hs(e.token0):e.token0,n="string"==typeof e.token1?Hs(e.token1):e.token1;await this.ensureWebSocketConnected();const r=await this.sendCollectPositionFeesToBundler(t,n,e.fee,e.amount0Requested||"0",e.amount1Requested||"0",e.tickLower,e.tickUpper,e.positionId||"");this.logger.debug("Fee collection submitted to bundler",{transactionId:r});const i=this.webSocketService.waitForTransaction(r);return this.monitorBundlerTransaction(r,i,"fee collection")}catch(e){this.handleGSwapError("Failed to collect position fees",U,e)}}async getPoolData(e,t,n){try{this.logger.debug("Getting pool data",{tokenA:e,tokenB:t,feeTier:n});const{gswapToken0:r,gswapToken1:i}=this.convertTokenPair(e,t),o=Hs(r),s=Hs(i),a=await this.gatewayClient.getPoolData({token0:o,token1:s,fee:n}),c=this.calculatePriceFromSqrtPriceX96(wo(a.sqrtPrice));return{tokenA:e,tokenB:t,feeTier:n,liquidity:a.liquidity.toString(),sqrtPriceX96:a.sqrtPrice.toString(),tick:a.tick,feeGrowthGlobal0X128:a.feeGrowthGlobal0.toString(),feeGrowthGlobal1X128:a.feeGrowthGlobal1.toString(),currentPrice:c.toFixed()}}catch(e){this.handleGSwapError("Failed to get pool data",O,e)}}async calculateDexPoolSpotPrice(e,t,n){try{this.logger.debug("Calculating spot price",{tokenA:e,tokenB:t,feeTier:n});const r=await this.getPoolData(e,t,n),i=wo(r.currentPrice);return{tokenA:e,tokenB:t,feeTier:n,price:i.toFixed(),invertedPrice:To(i,!0),tick:r.tick,liquidity:r.liquidity}}catch(e){this.handleGSwapError("Failed to calculate spot price",O,e)}}async calculateOptimalPositionSize(e,t,n,r,i,o,s){try{this.logger.debug("Calculating optimal position size",{tokenA:e,tokenB:t,desiredAmount0:r,desiredAmount1:i});const a=(await this.getPoolData(e,t,n)).tick,l=c.tickToSqrtPrice(o),u=c.tickToSqrtPrice(a),d=c.tickToSqrtPrice(s),h=c.getLiquidityForAmounts(wo(r),wo(i),l,u,d),g=c.getAmountsForLiquidity(h,u,l,d),p=g[0],f=g[1],m=wo(r),y=wo(i);return{amount0:p.toFixed(),amount1:f.toFixed(),liquidity:h.toFixed(),ratio:Lo(p,f).toFixed(),utilizationPercent:{amount0:Po(Lo(p,m),100).toFixed(2),amount1:Po(Lo(f,y),100).toFixed(2)}}}catch(e){this.handleGSwapError("Failed to calculate optimal position size",U,e)}}async validatePositionParameters(e,t,n,r,i,o,s){const a=[],c=[];try{this.logger.debug("Validating position parameters",{tokenA:e,tokenB:t,tickLower:r,tickUpper:i});const l=[500,3e3,1e4];l.includes(n)||a.push(`Invalid fee tier: ${n}. Must be one of: ${l.join(", ")}`);const u=this.getTickSpacing(n);let d;r%u!==0&&a.push(`tickLower must be multiple of ${u}`),i%u!==0&&a.push(`tickUpper must be multiple of ${u}`),r>=i&&a.push(`tickLower (${r}) must be less than tickUpper (${i})`);try{d=await this.getPoolData(e,t,n)}catch{return a.push(`Pool not found for ${e}/${t} at fee tier ${n}`),{valid:!1,errors:a,warnings:c,gasEstimate:0}}const h=wo(o),g=wo(s);if(h.isNaN()||g.isNaN())a.push("Amounts must be valid numbers");else try{Ro(h,g)}catch(e){a.push(`Liquidity amounts must be non-negative: ${e.message}`)}const p=d.tick;(p<r||p>i)&&c.push("Position is out of current price range - will not earn fees until price moves into range");wo(d.liquidity).lt("1000000")&&c.push("Low pool liquidity - consider higher slippage tolerance");const f=0===a.length?35e4:0;return{valid:0===a.length,errors:a,warnings:c,gasEstimate:f,tickSpacing:u,currentTick:p,poolLiquidity:d.liquidity}}catch(e){const t=A(e);return a.includes(t)||a.push(`Validation failed: ${t}`),{valid:!1,errors:a,warnings:c,gasEstimate:0}}}async calculateTicksForPrice(e,t,n,r,i){try{this.logger.debug("Calculating ticks for price range",{tokenA:e,tokenB:t,minPrice:n,maxPrice:r});const o=this.getTickSpacing(i),s=wo(n),a=wo(r);ce(n,r,"priceRange");const c=Math.floor(Ao(s)),l=Math.ceil(Ao(a)),u=Oo(c,o),d=Oo(l,o),h=Math.pow(1.0001,u),g=Math.pow(1.0001,d),p=wo(h),f=wo(g);return{tokenA:e,tokenB:t,feeTier:i,tickLower:u,tickUpper:d,tickSpacing:o,requestedMinPrice:n,requestedMaxPrice:r,actualMinPrice:p.toFixed(8),actualMaxPrice:f.toFixed(8),priceDeviation:{minPriceDeviation:Po(p.minus(s).dividedBy(s),100).toFixed(4),maxPriceDeviation:Po(f.minus(a).dividedBy(a),100).toFixed(4)}}}catch(e){this.handleGSwapError("Failed to calculate ticks for price",U,e)}}async calculatePriceForTicks(e,t,n,r){try{this.logger.debug("Calculating price for ticks",{tokenA:e,tokenB:t,tickLower:n,tickUpper:r});const i=Math.pow(1.0001,n),o=Math.pow(1.0001,r);let s;try{s=(await this.getPoolData(e,t,3e3)).currentPrice}catch{}const a=wo(i),c=wo(o),l={tokenA:e,tokenB:t,tickLower:n,tickUpper:r,minPrice:a.toFixed(8),maxPrice:c.toFixed(8),priceRange:`${a.toFixed(4)} - ${c.toFixed(4)}`,tickSpread:r-n};return Ze(s)||(l.currentPrice=s),l}catch(e){this.handleGSwapError("Failed to calculate price for ticks",U,e)}}calculateExecutionPrice(e,t){try{const n=wo(e);return Lo(wo(t),n,"0").toFixed()}catch{return"0"}}getTickSpacing(e){switch(e){case 500:return 10;case 3e3:return 60;case 1e4:return 200;default:throw z("feeTier","500, 3000, or 10000","Fee tier")}}validateTickSpacing(e,t,n){const r=this.getTickSpacing(n);if(e%r!==0)throw new B(`Invalid tickLower: ${e} must be a multiple of ${r} for fee tier ${n}. Tip: Use getAllSwapUserLiquidityPositions() to discover valid positions with correct tick spacing.`,"tickLower","INVALID_TICK_SPACING");if(t%r!==0)throw new B(`Invalid tickUpper: ${t} must be a multiple of ${r} for fee tier ${n}. Tip: Use getAllSwapUserLiquidityPositions() to discover valid positions with correct tick spacing.`,"tickUpper","INVALID_TICK_SPACING")}calculatePriceFromSqrtPriceX96(e){try{const t=Eo();return Lo(e,t).pow(2)}catch{return wo(0)}}calculatePriceFromSqrtPriceDecimal(e){try{return e.pow(2)}catch{return wo(0)}}async getPoolSlot0(e,t,n){try{this.logger.debug("Fetching pool slot0 data",{token0:e,token1:t,fee:n});const r="string"==typeof e?Hs(e):e,i="string"==typeof t?Hs(t):t,o=await this.gatewayClient.getSlot0({token0:r,token1:i,fee:n}),s={sqrtPrice:o.sqrtPrice||"0",tick:o.tick||0,liquidity:o.liquidity||"0",grossPoolLiquidity:o.grossPoolLiquidity||"0"};return this.logger.debug("Retrieved pool slot0 data",{sqrtPrice:s.sqrtPrice,tick:s.tick,liquidity:s.liquidity}),s}catch(r){this.handleGSwapError("Failed to fetch pool slot0 data",O,r,{token0:e,token1:t,fee:n})}}async getPositionCurrentPrice(e){try{this.logger.debug("Fetching position current price",{token0:e.token0,token1:e.token1,feeTier:e.feeTier});const t=await this.getPoolSlot0(e.token0,e.token1,e.feeTier),n=wo(t.sqrtPrice),r={price:this.calculatePriceFromSqrtPriceDecimal(n).toFixed(18),sqrtPrice:t.sqrtPrice,tick:t.tick,liquidity:t.liquidity};return this.logger.debug("Calculated position current price",{price:r.price,tick:r.tick}),r}catch(t){this.handleGSwapError("Failed to fetch position current price",O,t,{token0:e.token0,token1:e.token1})}}calculateLiquidityFromAmount0(e,t,n){try{const r=c.tickToSqrtPrice(t),i=c.tickToSqrtPrice(n);return c.liquidity0(e,r,i)}catch{return wo(0)}}calculateLiquidityFromAmount1(e,t,n){try{const r=c.tickToSqrtPrice(t),i=c.tickToSqrtPrice(n);return c.liquidity1(e,r,i)}catch{return wo(0)}}calculateAmount0FromLiquidity(e,t,n){try{const r=c.tickToSqrtPrice(t),i=c.tickToSqrtPrice(n);return c.getAmount0Delta(r,i,e)}catch{return wo(0)}}calculateAmount1FromLiquidity(e,t,n){try{const r=c.tickToSqrtPrice(t),i=c.tickToSqrtPrice(n);return c.getAmount1Delta(r,i,e)}catch{return wo(0)}}convertTokenPair(e,t){return{gswapToken0:this.tokenConverter.toLaunchpadFormat(e),gswapToken1:this.tokenConverter.toLaunchpadFormat(t)}}async sendAddLiquidityToBundler(t){if(!this.privateKey)throw new D("GSwapService: AddLiquidity requires wallet (full-access mode)","privateKey");if(!this.bundlerBaseUrl)throw new D("GSwapService: Bundler URL not configured","bundlerBaseUrl");try{this.logger.debug("Sending AddLiquidity to bundler",{token0:t.token0?.type??"unknown",token1:t.token1?.type??"unknown",fee:t.fee,tickRange:`${t.tickLower}-${t.tickUpper}`});const n=`galaswap - operation - ${o.v4()}-${Date.now()}-${t.owner}`,r={token0:t.token0,token1:t.token1,fee:t.fee,owner:t.owner,tickLower:t.tickLower,tickUpper:t.tickUpper,amount0Desired:t.amount0Desired,amount1Desired:t.amount1Desired,amount0Min:t.amount0Min,amount1Min:t.amount1Min,positionId:"",uniqueKey:n},i=new e.ethers.Wallet(this.privateKey),s={AddLiquidity:[{name:"token0",type:"token0"},{name:"token1",type:"token1"},{name:"fee",type:"int256"},{name:"owner",type:"string"},{name:"tickLower",type:"int256"},{name:"tickUpper",type:"int256"},{name:"amount0Desired",type:"string"},{name:"amount1Desired",type:"string"},{name:"amount0Min",type:"string"},{name:"amount1Min",type:"string"},{name:"positionId",type:"string"},{name:"uniqueKey",type:"string"}],token0:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}],token1:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}]},a={name:"ethereum",chainId:1},c=this.calculatePersonalSignPrefix(r),l={...r,prefix:c},u=await i.signTypedData(a,s,l),d={...l,signature:u,types:s,domain:a};this.logger.debug("AddLiquidity DTO signed with manual types",{signature:d.signature?.substring(0,20)+"...",prefix:d.prefix,tickLower:r.tickLower,tickUpper:r.tickUpper});const h=this.buildLiquidityStringsInstructions(t.token0,t.token1,t.fee,t.owner),g=dc.createClient(this.bundlerBaseUrl,3e4),p=await g.post("/bundle",{method:"AddLiquidity",signedDto:d,stringsInstructions:h}),f=mr(p),m=f?.data||f?.transactionId||f?.id;if(!m)throw this.logger.error("Bundler response structure",{status:p.status,data:f,dataType:typeof f}),new R(`Bundler response does not contain transaction ID. Response: ${JSON.stringify(f)}`,void 0,"INVALID_RESPONSE");return this.logger.debug("AddLiquidity transaction sent to bundler",{transactionId:m}),m}catch(e){throw this.logger.error("Failed to send AddLiquidity to bundler",e),e}}async sendRemoveLiquidityToBundler(t,n,r,i,s,a,c,l,u){try{if(!this.bundlerBaseUrl)throw new D("GSwapService: Bundler URL not configured","bundlerBaseUrl");const d=new e.ethers.Wallet(this.privateKey),h=await d.getAddress(),g=`galaswap - operation - ${o.v4()}-${Date.now()}-${h}`,p={tickLower:t,tickUpper:n,amount:r,token0:i,token1:s,fee:a,amount0Min:c,amount1Min:l,positionId:u,uniqueKey:g},f={RemoveLiquidity:[{name:"tickLower",type:"int256"},{name:"tickUpper",type:"int256"},{name:"amount",type:"string"},{name:"token0",type:"token0"},{name:"token1",type:"token1"},{name:"fee",type:"int256"},{name:"amount0Min",type:"string"},{name:"amount1Min",type:"string"},{name:"positionId",type:"string"},{name:"uniqueKey",type:"string"}],token0:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}],token1:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}]},m={name:"ethereum",chainId:1},y=this.calculatePersonalSignPrefix(p),w={...p,prefix:y},k=await d.signTypedData(m,f,w),b={...w,signature:k,types:f,domain:m},v=this.buildLiquidityStringsInstructions(i,s,a,h);this.logger.debug("Submitting RemoveLiquidity to bundler",{tickLower:t,tickUpper:n,amount:r,fee:a,positionId:u,transactionId:g});const S=dc.createClient(this.bundlerBaseUrl,3e4),A=await S.post("/bundle",{method:"RemoveLiquidity",signedDto:b,stringsInstructions:v}),T=mr(A),E=T?.data||T?.transactionId||T?.id;if(!E)throw this.logger.error("Bundler response structure",{status:A.status,data:T,dataType:typeof T}),new R(`Bundler response does not contain transaction ID. Response: ${JSON.stringify(T)}`,void 0,"INVALID_RESPONSE");return this.logger.info("RemoveLiquidity transaction sent to bundler",{transactionId:E}),E}catch(e){throw this.logger.error("Failed to send RemoveLiquidity to bundler",e),e}}async sendCollectPositionFeesToBundler(t,n,r,i,s,a,c,l){try{if(!this.bundlerBaseUrl)throw new D("GSwapService: Bundler URL not configured","bundlerBaseUrl");const u=new e.ethers.Wallet(this.privateKey),d=await u.getAddress(),h=`galaswap - operation - ${o.v4()}-${Date.now()}-${d}`,g={token0:t,token1:n,fee:r,amount0Requested:i,amount1Requested:s,tickLower:a,tickUpper:c,positionId:l,uniqueKey:h},p={CollectPositionFees:[{name:"token0",type:"token0"},{name:"token1",type:"token1"},{name:"fee",type:"int256"},{name:"amount0Requested",type:"string"},{name:"amount1Requested",type:"string"},{name:"tickLower",type:"int256"},{name:"tickUpper",type:"int256"},{name:"positionId",type:"string"},{name:"uniqueKey",type:"string"}],token0:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}],token1:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}]},f={name:"ethereum",chainId:1},m=this.calculatePersonalSignPrefix(g),y={...g,prefix:m},w=await u.signTypedData(f,p,y),k={...y,signature:w,types:p,domain:f},b=this.buildLiquidityStringsInstructions(t,n,r,d);this.logger.debug("Submitting CollectPositionFees to bundler",{fee:r,amount0Requested:i,amount1Requested:s,tickLower:a,tickUpper:c,positionId:l,transactionId:h});const v=dc.createClient(this.bundlerBaseUrl,3e4),S=await v.post("/bundle",{method:"CollectPositionFees",signedDto:k,stringsInstructions:b}),A=mr(S),T=A?.data||A?.transactionId||A?.id;if(!T)throw this.logger.error("Bundler response structure",{status:S.status,data:A,dataType:typeof A}),new R(`Bundler response does not contain transaction ID. Response: ${JSON.stringify(A)}`,void 0,"INVALID_RESPONSE");return this.logger.info("CollectPositionFees transaction sent to bundler",{transactionId:T}),T}catch(e){throw this.logger.error("Failed to send CollectPositionFees to bundler",e),e}}async sendSwapToBundler(t){if(!this.privateKey)throw new D("GSwapService: Swap requires wallet (full-access mode)","privateKey");if(!this.bundlerBaseUrl)throw new D("GSwapService: Bundler URL not configured","bundlerBaseUrl");const n=[500,3e3,1e4];if(!n.includes(t.feeTier))throw new B(`GSwapService: Invalid fee tier ${t.feeTier}. Must be one of: ${n.join(", ")} (basis points)`,"feeTier","INVALID_FEE_TIER");try{this.logger.debug("Sending Swap to bundler",{fromToken:"string"==typeof t.fromToken?t.fromToken:t.fromToken?.type??"unknown",toToken:"string"==typeof t.toToken?t.toToken:t.toToken?.type??"unknown",inputAmount:t.inputAmount,minOutput:t.minOutput,feeTier:t.feeTier});let n=t.fromToken,r=t.toToken;"string"==typeof n&&(n=Hs(n)),"string"==typeof r&&(r=Hs(r));const i=Ks(n),s=Ks(r),a=i<s?[n,r,i,s]:[r,n,s,i],[c,l,u,d]=a,h=Ks("string"==typeof t.fromToken?Hs(t.fromToken):t.fromToken),g=h===u,p=`galaswap - operation - ${o.v4()}-${Date.now()}-${t.walletAddress}`;let f;if(!t.currentSqrtPrice)throw new B("GSwapService: currentSqrtPrice is required for sqrtPriceLimit calculation","currentSqrtPrice",_.REQUIRED);const m=wo(t.currentSqrtPrice),y=t.slippageTolerance??.01;if(g){const e=vo(y);f=m.multipliedBy(e).toString()}else{const e=So(y);f=m.multipliedBy(e).toString()}this.logger.debug("Calculated sqrtPriceLimit based on slippage tolerance",{currentSqrtPrice:t.currentSqrtPrice,slippageTolerance:100*y+"%",zeroForOne:g,sqrtPriceLimit:f,direction:g?"token0→token1 (downward price movement)":"token1→token0 (upward price movement)",reason:"sqrtPriceLimit sets price boundaries, amountOutMinimum provides volume protection"});const w={token0:c,token1:l,fee:t.feeTier,amount:wo(t.inputAmount).toFixed(),zeroForOne:g,sqrtPriceLimit:f,recipient:t.walletAddress,amountOutMinimum:wo(t.minOutput).multipliedBy(-1).toFixed(),uniqueKey:p};this.logger.info("🔄 SWAP DTO DETAILS (what we're sending to bundler)",{orderedToken0String:u,orderedToken1String:d,fromTokenStr:h,zeroForOne:g?`TRUE (${u} → ${d})`:`FALSE (${d} → ${u})`,inputAmount:t.inputAmount,expectedOutput:t.minOutput,slippageTolerance:100*(t.slippageTolerance||.01)+"%",currentSqrtPrice:t.currentSqrtPrice,swapDto:{amount:w.amount,zeroForOne:w.zeroForOne,sqrtPriceLimit:w.sqrtPriceLimit,amountOutMinimum:w.amountOutMinimum}});const k=new e.ethers.Wallet(this.privateKey),b={Swap:[{name:"token0",type:"token0"},{name:"token1",type:"token1"},{name:"fee",type:"int256"},{name:"amount",type:"string"},{name:"zeroForOne",type:"bool"},{name:"sqrtPriceLimit",type:"string"},{name:"recipient",type:"string"},{name:"amountOutMinimum",type:"string"},{name:"uniqueKey",type:"string"}],token0:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}],token1:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}]},v={name:"ethereum",chainId:1},S=this.calculatePersonalSignPrefix(w),A={...w,prefix:S},T=await k.signTypedData(v,b,A),E={...A,signature:T,types:b,domain:v};this.logger.debug("Swap DTO signed",{signature:E.signature?.substring(0,20)+"...",prefix:E.prefix,zeroForOne:w.zeroForOne});const I=this.buildLiquidityStringsInstructions(c,l,t.feeTier,t.walletAddress),x=dc.createClient(this.bundlerBaseUrl,3e4),C=await x.post("/bundle",{method:"Swap",signedDto:E,stringsInstructions:I}),N=mr(C),P=N?.data||N?.transactionId||N?.id;if(!P)throw this.logger.error("Bundler response structure",{status:C.status,data:N,dataType:typeof N}),new R(`Bundler response does not contain transaction ID. Response: ${JSON.stringify(N)}`,void 0,"INVALID_RESPONSE");return this.logger.debug("Swap transaction sent to bundler",{transactionId:P,inputAmount:t.inputAmount,minOutput:t.minOutput}),P}catch(e){throw this.logger.error("Failed to send Swap to bundler",e),e}}buildLiquidityStringsInstructions(e,t,n,r){const i=Ws(e),o=Ws(t),s=`$pool${i}${o}$${n}`;return[s,`$userPosition${r}`,`$tokenBalance${i}${r}`,`$tokenBalance${o}${r}`,`$tokenBalance${i}${s}`,`$tokenBalance${o}${s}`]}createGSwapErrorHandler(e,t){return(n,r,i)=>{this.handleGSwapError(r,e,n,t)}}handleGSwapError(e,t,n,r){this.logger.error(e,n);const i=this.extractGSwapErrorCode(n),o=n,s=[`${e}: ${o?.message||A(n)}`,n];throw r&&("GSwapSwapError"===t.name&&r.transactionHash&&s.push(r.transactionHash),"GSwapPoolError"===t.name&&(r.tokenA&&s.push(r.tokenA),r.tokenB&&s.push(r.tokenB)),"GSwapAssetError"===t.name&&r.walletAddress&&s.push(r.walletAddress)),i&&s.push(i),new t(...s)}extractGSwapErrorCode(e){const t=E(e);return void 0!==t?String(t):void 0}async ensureWebSocketConnected(){this.webSocketService.isConnected()||await this.webSocketService.connect()}calculatePersonalSignPrefix(e){return`Ethereum Signed Message:\n${JSON.stringify(e).length}${JSON.stringify(e)}`}}class fc{}fc.BASE_PRICE=1650667151e-14,fc.PRICE_SCALING_FACTOR=1166069e-12,fc.TRADING_FEE_FACTOR=.001,fc.GAS_FEE="1",fc.MIN_UNBONDING_FEE_FACTOR=0,fc.MAX_UNBONDING_FEE_FACTOR=.5,fc.NET_UNBONDING_FEE_FACTOR=.5,fc.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY=1e7;class mc extends hs{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 yc extends mc{constructor(e=!1){super(e)}normalizeKey(e){return rs(e).replace(/\s+/g," ").replace(/[\u0000-\u001F\u007F-\u009F\u200B-\u200D\uFEFF]/g,"")}getLRUKey(){const e=this.cache.keys().next().value;return void 0!==e?e:null}updateCacheEntry(e,t){const n=this.cache.get(e);if(this.cache.has(e)&&this.cache.delete(e),this.cache.size>=yc.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||fc.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY.toString()}has(e){const t=this.normalizeKey(e);return this.cache.has(t)}clear(e){if(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,n.vaultAddress&&(i+=2*n.vaultAddress.length),n.maxSupply&&(i+=2*n.maxSupply.length),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:${rs(e)}`;return this.cache.get(t)||null}setByTokenId(e,t){const n=`token:${rs(e)}`;this.updateCacheEntry(n,t)}hasByTokenId(e){const t=`token:${rs(e)}`;return this.cache.has(t)}}yc.MAX_CACHE_SIZE=1e4;class wc extends ds{constructor(e,t,n=void 0,r=5,i=!1){super(e,i),this.pricingConcurrency=5,this.dexBackendBaseUrl=t,this.gswapService=n,this.pricingConcurrency=r}setGSwapService(e){this.gswapService=e}setPricingConcurrency(e){this.pricingConcurrency=Math.max(1,Math.min(e,20))}async enrichPoolsWithPricing(e){if(!this.gswapService)return this.logger.warn("GSwap service not available, skipping pricing enrichment"),e;if(0===e.length)return e;this.logger.debug("Starting pricing enrichment",{poolCount:e.length,concurrency:this.pricingConcurrency});const t=[];for(let n=0;n<e.length;n++){const r=e[n];t.push({poolIndex:n,token:r.token0,isToken0:!0,task:this.gswapService.getSwapQuoteExactInput({fromToken:r.token0,toToken:"GUSDC",amount:"1"}).then(e=>e.estimatedOutput).catch(e=>{this.logger.debug(`Failed to price ${r.token0}`,{error:A(e)})})}),t.push({poolIndex:n,token:r.token1,isToken0:!1,task:this.gswapService.getSwapQuoteExactInput({fromToken:r.token1,toToken:"GUSDC",amount:"1"}).then(e=>e.estimatedOutput).catch(e=>{this.logger.debug(`Failed to price ${r.token1}`,{error:A(e)})})})}const n=new Map;for(let t=0;t<e.length;t++)n.set(t,{});for(let e=0;e<t.length;e+=this.pricingConcurrency){const r=t.slice(e,e+this.pricingConcurrency),i=await Promise.allSettled(r.map(e=>e.task));for(let e=0;e<r.length;e++){const t=r[e],o=i[e],s=n.get(t.poolIndex)||{};"fulfilled"===o.status&&o.value&&(t.isToken0?s.token0Price=o.value:s.token1Price=o.value),n.set(t.poolIndex,s)}}const r=e.map((e,t)=>{const r=n.get(t)||{},i={...e};return void 0!==r.token0Price&&(i.token0Price=r.token0Price),void 0!==r.token1Price&&(i.token1Price=r.token1Price),i}),i=r.filter(e=>e.token0Price&&e.token1Price).length;return this.logger.debug("Pricing enrichment complete",{total:e.length,successful:i,failed:e.length-i}),r}async fetchDexPools(e={}){const{search:t,sortBy:n="tvl",sortOrder:r="desc",page:i=zo.DEFAULT_PAGE,limit:o=zo.DEFAULT_LIMIT,withPrices:s=!1}=e;this.logger.debug("Fetching DEX pools",{search:t,sortBy:n,sortOrder:r,page:i,limit:o,withPrices:s});const a=Ss({page:i,limit:o},20),c=new URLSearchParams({...a,sortBy:n,sortOrder:r});t&&c.append("search",t);const l=`${this.dexBackendBaseUrl}/explore/pools?${c}`,u=await es(()=>this.http.get(l),{errorContext:"Failed to fetch DEX pools",logger:this.logger});let d=u.pools;const h=u.count,g=Math.min(o,20),p=void 0!==h?function(e,t=1,n=20){return{page:t,limit:n,total:e,totalPages:Xo(e,n)}}(h,i,g):{page:i,limit:g,total:void 0,totalPages:void 0};return s&&(d=await this.enrichPoolsWithPricing(d)),this.logger.debug("DEX pools fetched successfully",{poolCount:d.length,total:h,totalPages:p.totalPages,withPrices:s}),{items:d,meta:p}}async fetchAllDexPools(e={}){this.logger.debug("Fetching all DEX pools (auto-paginated)",e);const t=await Yo((t,n)=>this.fetchDexPools({...e,page:t,limit:n}).then(e=>({items:e.items,page:e.meta.page,limit:e.meta.limit,total:e.meta.total,totalPages:e.meta.totalPages,hasNext:t<e.meta.totalPages,hasPrevious:t>1})),{maxPages:1e4,logger:this.logger,pageSize:20});return this.logger.debug("All DEX pools fetched",{totalPoolsFetched:t.items.length,totalCount:t.total,withPrices:e.withPrices}),{items:t.items,meta:As(t.items,t.total)}}}class kc extends ds{constructor(e,t,n=!1,r=3e4){super(e,n),this.compositePoolFetchConcurrency=5,this.galaChainBaseUrl=t,this.networkTimeout=r}validateFetchCompositePoolDataInput(e,t,n){if(!Qe(e))throw new $("token0 must be a non-empty string",{token0:e});if(!Qe(t))throw new $("token1 must be a non-empty string",{token1:t});try{js(e),js(t)}catch(n){throw new $(`Token format must be: collection|category|type|additionalKey (4 pipe-separated parts). ${A(n)}`,{token0:e,token1:t})}try{ae(n,"fee")}catch{throw new $(`fee must be a positive integer (got ${n})`,{fee:n})}const r=[500,3e3,1e4];if(!r.includes(n))throw new $(`fee must be one of: ${r.join(", ")} (got ${n})`,{fee:n})}validateQuoteAmount(e){if(!Qe(e))throw new $("amount must be a non-empty string",{amount:e});const t=wo(e);try{Mo(t,"amount")}catch(t){throw new $(t.message,{amount:e})}}convertTokenClassKey(e){const t=new s.TokenClassKey;return t.collection=e.collection,t.category=e.category,t.type=e.type,t.additionalKey=e.additionalKey,t}setCompositePoolFetchConcurrency(e){this.compositePoolFetchConcurrency=Math.max(1,Math.min(e,20)),this.logger.debug(`Composite pool fetch concurrency set to ${this.compositePoolFetchConcurrency}`)}async fetchCompositePoolData(e){const{token0:t,token1:n,fee:r,gatewayBaseUrl:i}=e;this.logger.debug("Fetching composite pool data",{token0:t,token1:n,fee:r}),this.validateFetchCompositePoolDataInput(t,n,r);try{const e=hc(t),o=hc(n),a=this.convertTokenClassKey(e),l=this.convertTokenClassKey(o),u=new c.GetCompositePoolDto(a,l,r),d=`${i||this.galaChainBaseUrl}/api/asset/dexv3-contract/GetCompositePool`,h=await this.http.post(d,u);x(h,`Pool not found: ${t}/${n} with fee ${r}`);const g=function(e){return{pool:e.pool,tickDataMap:e.tickDataMap,token0Balance:e.token0Balance,token1Balance:e.token1Balance,token0Decimals:e.token0Decimals,token1Decimals:e.token1Decimals,compositePoolDto:e}}(function(e){const t=new c.Pool(e.pool.token0,e.pool.token1,e.pool.token0ClassKey,e.pool.token1ClassKey,e.pool.fee,wo(e.pool.sqrtPrice),e.pool.protocolFees);t.bitmap=e.pool.bitmap,t.grossPoolLiquidity=wo(e.pool.grossPoolLiquidity),t.liquidity=wo(e.pool.liquidity),t.feeGrowthGlobal0=wo(e.pool.feeGrowthGlobal0),t.feeGrowthGlobal1=wo(e.pool.feeGrowthGlobal1),t.protocolFeesToken0=wo(e.pool.protocolFeesToken0),t.protocolFeesToken1=wo(e.pool.protocolFeesToken1),t.tickSpacing=e.pool.tickSpacing,t.maxLiquidityPerTick=wo(e.pool.maxLiquidityPerTick);const n={};Object.keys(e.tickDataMap).forEach(t=>{const r=e.tickDataMap[t],i=new c.TickData(r.poolHash,r.tick);i.initialised=r.initialised,i.liquidityNet=wo(r.liquidityNet),i.liquidityGross=wo(r.liquidityGross),i.feeGrowthOutside0=wo(r.feeGrowthOutside0),i.feeGrowthOutside1=wo(r.feeGrowthOutside1),n[t]=i});const r={...e.token0Balance},i=new s.TokenBalance(r);i.quantity=wo(e.token0Balance.quantity);const o={...e.token1Balance},a=new s.TokenBalance(o);return a.quantity=wo(e.token1Balance.quantity),new c.CompositePoolDto(t,n,i,a,e.token0Decimals,e.token1Decimals)}(h.Data),h.Data);return this.logger.debug("Composite pool data fetched successfully",{token0:t,token1:n,fee:r,liquidity:g.pool.liquidity.toString()}),g}catch(e){if(e instanceof q)throw e;const i=A(e);if(i.includes("status indicates failure")||i.includes("Pool not found"))throw new q(i);throw this.logger.error("Failed to fetch composite pool data",e),new $(`Failed to fetch composite pool data: ${i}`,{token0:t,token1:n,fee:r})}}async calculateDexPoolQuoteExactAmountLocal(e){const{compositePoolData:t,fromToken:n,toToken:r,amount:i}=e;if(this.logger.debug("Calculating local DEX quote",{fromToken:n,toToken:r,amount:i}),this.validateQuoteAmount(i),!t)throw new $("compositePoolData is required for local quote calculation",{compositePoolData:t});try{const e=n===t.pool.token0.replace(/\$/g,"|"),o=hc(n),s=hc(r),a=this.convertTokenClassKey(o),l=this.convertTokenClassKey(s),[u,d]=n<r?[a,l]:[l,a],h=new c.QuoteExactAmountDto(u,d,t.pool.fee,wo(i),e,t.compositePoolDto),g=await c.quoteExactAmount(void 0,h);return this.logger.debug("Local quote calculated",{amount0:g.amount0,amount1:g.amount1}),{amount0:g.amount0.toString(),amount1:g.amount1.toString(),currentSqrtPrice:g.currentSqrtPrice.toString(),newSqrtPrice:g.newSqrtPrice.toString()}}catch(e){throw this.logger.error("Local quote calculation failed",e),new $(`Local quote calculation failed: ${A(e)}`,{fromToken:n,toToken:r,amount:i})}}async calculateDexPoolQuoteExactAmountExternal(e){const{compositePoolData:t,fromToken:n,toToken:r,amount:i}=e;if(this.logger.debug("Calculating external DEX quote",{fromToken:n,toToken:r,amount:i}),this.validateQuoteAmount(i),!t)throw new $("compositePoolData is required for external quote calculation (token format info)",{compositePoolData:t});try{const e=n===t.pool.token0.replace(/\$/g,"|"),o=hc(n),s=hc(r),a=this.convertTokenClassKey(o),l=this.convertTokenClassKey(s),u=new c.QuoteExactAmountDto(a,l,t.pool.fee,wo(i),e,void 0),d=`${this.galaChainBaseUrl}/api/asset/dexv3-contract/QuoteExactAmount`,h=await this.http.post(d,u);x(h,"External quote failed");const g=h.Data;return this.logger.debug("External quote calculated",{amount0:g.amount0,amount1:g.amount1}),{amount0:g.amount0.toString(),amount1:g.amount1.toString(),currentSqrtPrice:g.currentSqrtPrice.toString(),newSqrtPrice:g.newSqrtPrice.toString()}}catch(e){throw this.logger.error("External quote calculation failed",e),new $(`External quote calculation failed: ${A(e)}`,{fromToken:n,toToken:r,amount:i})}}async calculateDexPoolQuoteExactAmount(e,t="local"){return"external"===t?this.calculateDexPoolQuoteExactAmountExternal(e):this.calculateDexPoolQuoteExactAmountLocal(e)}}class bc{constructor(){this.eventLatencies=[],this.maxLatencySamples=1e4,this.eventsProcessed=0,this.eventsDropped=0,this.queueDepth=0,this.maxQueueDepth=0,this.startTime=Date.now(),this.perPoolMetrics=new Map,this.memorySnapshots=[],this.maxMemorySnapshots=100,this.recordMemory()}recordEventLatency(e){this.eventLatencies.push(e),this.eventLatencies.length>this.maxLatencySamples&&this.eventLatencies.shift(),this.eventsProcessed++,this.lastEventTime=new Date}recordEventDropped(){this.eventsDropped++}updateQueueDepth(e){this.queueDepth=e,this.maxQueueDepth=Math.max(this.maxQueueDepth,e)}recordPoolCacheHit(e,t){const n=this.getPoolMetrics(e);n.cacheHits++,n.eventsProcessed++,n.totalLatency+=t,n.lastEventTime=new Date}recordPoolCacheMiss(e,t){const n=this.getPoolMetrics(e);n.cacheMisses++,n.eventsProcessed++,n.totalLatency+=t,n.lastEventTime=new Date}getLatencyPercentiles(){if(0===this.eventLatencies.length)return{p50:0,p95:0,p99:0};const e=[...this.eventLatencies].sort((e,t)=>e-t),t=Re(Math.floor(.5*e.length),0),n=Re(Math.floor(.95*e.length),0),r=Re(Math.floor(.99*e.length),0);return{p50:e[t]??0,p95:e[n]??0,p99:e[r]??0}}getCacheHitRate(){if(0===this.eventsProcessed)return 0;let e=0;for(const t of this.perPoolMetrics.values())e+=t.cacheHits;return Re(e/this.eventsProcessed*100,NaN)}getThroughputPerSecond(){const e=Re(Ve(this.startTime)/1e3,0);return 0===e?0:Re(this.eventsProcessed/e,0)}recordMemory(){if("undefined"!=typeof process&&process.memoryUsage){const e=Re(process.memoryUsage().heapUsed/1024/1024,0);this.memorySnapshots.push(e),this.memorySnapshots.length>this.maxMemorySnapshots&&this.memorySnapshots.shift()}}getMemoryUsedMB(){return"undefined"!=typeof process&&process.memoryUsage?Re(process.memoryUsage().heapUsed/1024/1024,0):0}getPoolAverageLatency(e){const t=this.perPoolMetrics.get(e);return t&&0!==t.eventsProcessed?Re(t.totalLatency/t.eventsProcessed,0):0}getPoolCacheHitRate(e){const t=this.perPoolMetrics.get(e);if(!t)return 0;const n=t.cacheHits+t.cacheMisses;return 0===n?0:Re(t.cacheHits/n*100,0)}getHealthMetrics(e,t,n,r,i){const o=this.getLatencyPercentiles(),s=this.getMemoryUsedMB();return{eventProcessing:{queueDepth:this.queueDepth,eventsProcessed:this.eventsProcessed,eventsDropped:this.eventsDropped,throughputPerSecond:this.getThroughputPerSecond()},metrics:{latencyP50:o.p50,latencyP95:o.p95,latencyP99:o.p99,cacheHitRate:this.getCacheHitRate()},memory:{usedMB:Re(ko(s,1),0),maxMB:i,percentUsed:Math.min(100,Re(ko(s/i*100,1),0))},pools:{totalMonitored:e,hotCacheSize:t,warmCacheSize:n,coldCacheSize:r}}}reset(){this.eventLatencies=[],this.eventsProcessed=0,this.eventsDropped=0,this.queueDepth=0,this.maxQueueDepth=0,this.startTime=Date.now(),this.lastEventTime=void 0,this.perPoolMetrics.clear(),this.memorySnapshots=[]}getSummary(){const e=this.eventLatencies.length>0?Re(this.eventLatencies.reduce((e,t)=>e+t,0)/this.eventLatencies.length,0):0;return{eventsProcessed:this.eventsProcessed,eventsDropped:this.eventsDropped,cacheHitRate:this.getCacheHitRate(),averageLatency:Re(ko(e,0),0),memoryUsedMB:Re(ko(this.getMemoryUsedMB(),1),0),throughputPerSecond:Re(ko(this.getThroughputPerSecond(),2),0)}}getPoolMetrics(e){let t=this.perPoolMetrics.get(e);return t||(t={eventsProcessed:0,totalLatency:0,cacheHits:0,cacheMisses:0},this.perPoolMetrics.set(e,t)),t}}class vc{static createPoolKey(e,t,n){return`${e}/${t}/${n}`}static parsePoolKey(e){if(!Qe(e))return null;const t=e.split("/");if(3!==t.length)return null;const n=t[0]?.trim(),r=t[1]?.trim(),i=t[2]?.trim();if(!n||!r||!i)return null;const o=Me(i,-1);return o<0?null:{token0:n,token1:r,feeTier:o}}static isValidPoolKey(e){if("string"!=typeof e)return!1;return null!==this.parsePoolKey(e)}static getToken0(e){const t=this.parsePoolKey(e);return t?.token0??null}static getToken1(e){const t=this.parsePoolKey(e);return t?.token1??null}static getFeeTier(e){const t=this.parsePoolKey(e);return t?.feeTier??null}static containsToken(e,t){const n=this.parsePoolKey(e);return!!n&&(n.token0===t||n.token1===t)}static containsTokenPair(e,t,n){const r=this.parsePoolKey(e);if(!r)return!1;const i=r.token0===t||r.token1===t,o=r.token0===n||r.token1===n;return i&&o&&t!==n}static normalizeFee(e){if(Ze(e))return null;const t="number"==typeof e?e:Ue(String(e),NaN);return Number.isNaN(t)?null:1===t||1e4===t?1e4:.3===t||3e3===t?3e3:.05===t||500===t?500:Number.isInteger(t)&&t>0?t:null}static formatFeeAsPercentage(e){return`${ko(wo(e).dividedBy(1e4),2)}%`}static isValidTokenPair(e,t){return Boolean(e)&&Boolean(t)&&e!==t}}class Sc{constructor(e){this.logger=e||new We({debug:!1,context:"SwapEventExtractor"})}walkPayloadForSwaps(e,t){const n=[],r=new WeakSet,i=(e,o=0)=>{if(o>50)this.logger.debug("Payload nesting exceeded maximum depth of 50");else if(e&&"string"!=typeof e&&"object"==typeof e){if(r.has(e))return;r.add(e);const s=this.extractSwapFromObject(e);s&&!t.has(s.transactionId)&&(n.push(s),t.add(s.transactionId));for(const t of Object.values(e))i(t,o+1)}};return i(e,0),n}extractSwapFromObject(e){const t=this.extractTransactionId(e);if(!t)return null;const n=e.Data,r=n&&"object"==typeof n&&!Array.isArray(n)?n:e,i=this.extractToken(r,"token0","fromToken","source"),o=this.extractToken(r,"token1","toToken","destination");if(!i||!o)return null;const s=this.extractAmount(r,"amount0","amountIn","inputAmount"),a=this.extractAmount(r,"amount1","amountOut","outputAmount");if(!s||!a)return null;const c=this.extractFeeTier(r);if(null===c)return null;const l=this.extractTimestamp(r),u=this.buildPoolKey(i,o,c),d=this.determineDirection(r,i,o),h={transactionId:t,poolKey:u,token0:i,token1:o,amount0:s,amount1:a,feeTier:c,direction:d,timestamp:l,exactInput:this.determineExactInput(r,d)},g=this.extractUser(r);return void 0!==g&&(h.user=g),h}extractTransactionId(e){const t=["transactionId","txId","tx_id","hash","txHash","id"];for(const n of t){const t=e[n];if(Qe(t))return t}return null}extractToken(e,...t){for(const n of t){const t=e[n];if(Qe(t))return t}return null}extractAmount(e,...t){for(const n of t){const t=e[n];if(!Ze(t)){const e=String(t).trim();if(/^-?\d+(\.\d+)?([eE]-?\d+)?$/.test(e))return e}}return null}extractFeeTier(e){const t=["poolFee","feeTier","fee","feeTierBps","liquidityFeeBps","feeAmount"];for(const n of t){const t=e[n],r=this.normalizeFee(t);if(null!==r)return r}return null}normalizeFee(e){if(Ze(e))return null;const t="number"==typeof e?e:Ue(String(e),NaN);return Number.isNaN(t)?null:1===t||1e4===t?1e4:.3===t||3e3===t?3e3:.05===t||500===t?500:Number.isInteger(t)?t:null}extractTimestamp(e){const t=["timeStamp","timestamp","time","createdAt","date"];for(const n of t){const t=e[n];if("number"==typeof t)return t;if("string"==typeof t){const e=new Date(t).getTime();if(!Number.isNaN(e))return e}}return Date.now()}extractUser(e){const t=["userAddress","user","from","sender","wallet","address"];for(const n of t){const t=e[n];if(Qe(t))return t}}determineDirection(e,t,n){const r=e.zeroForOne||e.direction;if("boolean"==typeof r)return r?"zeroForOne":"oneForZero";if("string"==typeof r){if(Is(r,"zerotoone")||"0to1"===r)return"zeroForOne";if(Is(r,"onetozero")||"1to0"===r)return"oneForZero"}if(e.fromToken===t||e.inputToken===t)return"zeroForOne";if(e.fromToken===n||e.inputToken===n)return"oneForZero";const i=this.extractAmount(e,"amount0","amountIn");return i&&De(i,0),"zeroForOne"}determineExactInput(e,t){if("boolean"==typeof e.exactInput)return e.exactInput;if("boolean"==typeof e.exactOutput)return!e.exactOutput;const n=void 0!==e.amountIn&&null!==e.amountIn,r=void 0!==e.amountOut&&null!==e.amountOut,i=void 0!==e.inputAmount&&null!==e.inputAmount,o=void 0!==e.outputAmount&&null!==e.outputAmount;return!(!n||r)||!(r&&!n)&&(!(!i||o)||!(o&&!i))}buildPoolKey(e,t,n){return`${e}/${t}/${n}`}}class Ac{static getCached(e){const t=e.toString();return this.CACHE.has(t)||this.CACHE.set(t,wo(e)),this.CACHE.get(t)}static clearCache(){this.CACHE.clear()}static getCacheStats(){return{size:this.CACHE.size,entries:Array.from(this.CACHE.keys())}}static trimCache(e=1e3){if(this.CACHE.size>e){const t=this.CACHE.size-e,n=Array.from(this.CACHE.keys());for(let e=0;e<t;e++)this.CACHE.delete(n[e])}}}Ac.CACHE=new Map,Ac.ZERO=Oe(0),Ac.ONE=Oe(1),Ac.FEE_PIPS=Oe(1e6),Ac.MIN_SQRT_RATIO=Oe("4295128739"),Ac.MAX_SQRT_RATIO=new i("1461446703485210103287273052203988822378723970342");const Tc={maxIterations:100,enableBigNumberCache:!0,roundingMode:i.ROUND_DOWN,debugLogging:!1};class Ec{static calculateSwapDelta(e,t,n={}){const r=Date.now(),i={...Tc,...n};try{const n=this.initializeSwapState(e,t,i);i.debugLogging&&this.logger.debug("Initialized swap state",{sqrtPrice:n.sqrtPrice.toString(),liquidity:n.liquidity.toString(),tick:n.tick,zeroForOne:t.zeroForOne});const o=this.computeSwapLoop(n,e,t,i);i.debugLogging&&this.logger.debug("Swap loop completed",{stepCount:o.stepCount,ticksCrossed:o.ticksCrossed.length,priceHitLimit:o.priceHitLimit});const s=this.createUpdatedPool(e.pool,o.state,t,i),a=this.calculateFinalAmounts(n,o.state,t);let c;if(t.actualSqrtPrice){const e=wo(s.sqrtPrice),n=wo(t.actualSqrtPrice),r=e.minus(n).abs();c=Re(Lo(r,n).times(100).toNumber(),0)}const l=Ve(r);i.debugLogging&&this.logger.debug("Swap delta calculated",{calculationTimeMs:l,amount0:a.amount0.toString(),amount1:a.amount1.toString(),driftPercentage:c}),l>100&&this.logger.warn("Swap calculation exceeded 100ms",{calculationTimeMs:l,stepCount:o.stepCount,ticksCrossed:o.ticksCrossed.length}),o.priceHitLimit&&this.logger.warn("Swap price hit limit - partially fulfilled",{zeroForOne:t.zeroForOne,stepCount:o.stepCount}),o.stepCount>50&&this.logger.warn("Unusually complex swap detected",{stepCount:o.stepCount,ticksCrossed:o.ticksCrossed.length});return{updatedPool:s,updatedTicks:o.updatedTicks,amount0:a.amount0,amount1:a.amount1,feeAmount0:a.feeAmount0,feeAmount1:a.feeAmount1,ticksCrossed:o.ticksCrossed,metadata:{calculationTimeMs:l,swapSteps:o.stepCount,priceHitLimit:o.priceHitLimit,...void 0!==c&&{driftPercentage:c}}}}catch(e){throw this.logger.error("Swap delta calculation failed",e),new Error(`Swap delta calculation failed: ${A(e)}`)}}static initializeSwapState(e,t,n){const{pool:r}=e;if(!r.sqrtPrice||!r.liquidity)throw new Error("Invalid pool data: missing sqrtPrice or liquidity");const i=n.enableBigNumberCache?Ac.getCached.bind(Ac):e=>Oe(e),o="string"==typeof r.sqrtPrice?r.sqrtPrice:ko(r.sqrtPrice,0),s="string"==typeof r.liquidity?r.liquidity:ko(r.liquidity,0),a=i(o),l=i(s),u=r.tick??0,d=c.sqrtPriceToTick(wo(o)),h=Math.abs(d-u);h>100&&this.logger.warn("Significant tick/price mismatch detected in pool state",{poolTick:u,calculatedTick:d,drift:h,threshold:100});const g=i(t.amountSpecified);Mo(g,"amountSpecified");const p="string"==typeof r.feeGrowthGlobal1?r.feeGrowthGlobal1:ko(r.feeGrowthGlobal1,0),f="string"==typeof r.feeGrowthGlobal0?r.feeGrowthGlobal0:ko(r.feeGrowthGlobal0,0),m=t.zeroForOne?i(p):i(f);return{sqrtPrice:a,liquidity:l,tick:u,amountSpecifiedRemaining:g,amountCalculated:Ac.ZERO,feeGrowthGlobalX:m,protocolFee:Ac.ZERO}}static computeSwapLoop(e,t,n,r){const{pool:o,tickDataMap:s}=t,a=[],l={};let u=0;const d=n.zeroForOne?Ac.MIN_SQRT_RATIO:Ac.MAX_SQRT_RATIO,h=wo("0.000001");for(;e.amountSpecifiedRemaining.gt(h)&&!e.sqrtPrice.eq(d)&&u<r.maxIterations;){u++;const[t,h]=this.findNextInitializedTick(s,e.tick,o.tickSpacing,n.zeroForOne);let g;if(r.debugLogging&&this.logger.debug(`Swap step ${u}`,{currentTick:e.tick,tickNext:t,initialized:h,sqrtPrice:e.sqrtPrice.toString(),liquidity:e.liquidity.toString(),amountRemaining:e.amountSpecifiedRemaining.toString()}),h&&t>=-887272&&t<=887272){const e=c.tickToSqrtPrice(t);g=e instanceof i?e:wo(String(e))}else g=d;const p=n.zeroForOne?xo(g,d):Io(g,d),f=this.executeSwapStep(e.sqrtPrice,p,e.liquidity,e.amountSpecifiedRemaining,o.fee,n.exactInput);if(e.sqrtPrice=f.sqrtPriceNext,n.exactInput){const t=f.amountIn.plus(f.feeAmount);t.lte(0)?e.amountSpecifiedRemaining=Ac.ZERO:(e.amountSpecifiedRemaining=e.amountSpecifiedRemaining.minus(t),e.amountSpecifiedRemaining.lt(0)&&(e.amountSpecifiedRemaining=Ac.ZERO)),e.amountCalculated=e.amountCalculated.minus(f.amountOut)}else{f.amountOut.lte(0)?e.amountSpecifiedRemaining=Ac.ZERO:e.amountSpecifiedRemaining=e.amountSpecifiedRemaining.plus(f.amountOut),e.amountCalculated=e.amountCalculated.plus(f.amountIn.plus(f.feeAmount))}if(e.liquidity.gt(0)){const t=Lo(f.feeAmount,e.liquidity);e.feeGrowthGlobalX=e.feeGrowthGlobalX.plus(t)}if(e.sqrtPrice.eq(g)&&h){const i=s[t.toString()];if(!i)throw new Error(`Missing tick data for initialized tick ${t}`);const o=n.zeroForOne?wo(i.liquidityNet).negated():wo(i.liquidityNet);if(e.liquidity=e.liquidity.plus(o),e.liquidity.lt(0))throw new Error(`Negative liquidity after crossing tick ${t}: ${e.liquidity.toString()}`);a.push(t),l[t.toString()]=i,r.debugLogging&&this.logger.debug(`Crossed tick ${t}`,{liquidityNet:o.toString(),newLiquidity:e.liquidity.toString()})}if(e.sqrtPrice.eq(g))e.tick=n.zeroForOne?t-1:t;else{const t=c.sqrtPriceToTick(wo(e.sqrtPrice.toString()));e.tick=t}}if(u>=r.maxIterations)throw new Error(`Swap calculation exceeded maximum iterations (${r.maxIterations}). Possible infinite loop or very complex swap.`);const g=e.sqrtPrice.eq(d);return{state:e,ticksCrossed:a,priceHitLimit:g,stepCount:u,updatedTicks:l}}static createUpdatedPool(e,t,n,r){const i=Object.assign(Object.create(Object.getPrototypeOf(e)),e);if(i.sqrtPrice=ko(t.sqrtPrice,0),i.liquidity=ko(t.liquidity,0),i.tick=t.tick,n.zeroForOne?i.feeGrowthGlobal1=ko(t.feeGrowthGlobalX,0):i.feeGrowthGlobal0=ko(t.feeGrowthGlobalX,0),n.zeroForOne){const n=wo(e.protocolFeesToken0);i.protocolFeesToken0=ko(n.plus(t.protocolFee),0)}else{const n=wo(e.protocolFeesToken1);i.protocolFeesToken1=ko(n.plus(t.protocolFee),0)}return i}static calculateFinalAmounts(e,t,n){let r,i,o,s;if(n.exactInput){const e=wo(n.amountSpecified),a=t.amountCalculated.abs();n.zeroForOne?(r=e.negated(),i=a,o=Ac.ZERO,s=Ac.ZERO):(r=a,i=e.negated(),o=Ac.ZERO,s=Ac.ZERO)}else{const e=wo(n.amountSpecified),a=t.amountCalculated.abs();n.zeroForOne?(r=a.negated(),i=e,o=Ac.ZERO,s=Ac.ZERO):(r=e,i=a.negated(),o=Ac.ZERO,s=Ac.ZERO)}const a=t.feeGrowthGlobalX.minus(e.feeGrowthGlobalX).times(e.liquidity);return n.zeroForOne?s=a:o=a,{amount0:r,amount1:i,feeAmount0:o,feeAmount1:s}}static findNextInitializedTick(e,t,n,r){const i=Object.keys(e).map(e=>Le(e,0)).sort((e,t)=>e-t);if(0===i.length){return[r?-887272:887272,!1]}if(r){const e=i.reverse().find(e=>e<t);return void 0!==e?[e,!0]:[-887272,!1]}{const e=i.find(e=>e>t);return void 0!==e?[e,!0]:[887272,!1]}}static executeSwapStep(e,t,n,r,o,s){Ro(n),Mo(r,"amountRemaining");const a=[500,3e3,1e4];if(!a.includes(o))throw new Error(`Invalid fee tier: ${o}. Must be one of: ${a.join(", ")}`);const l=c.computeSwapStep(e,t,n,r,o,t.lt(e)),u=l[0],d=l[1],h=l[2],g=l[3],p=i.isBigNumber(u)?u:wo(String(u)),f=i.isBigNumber(d)?d:wo(String(d)),m=i.isBigNumber(h)?h:wo(String(h)),y=i.isBigNumber(g)?g:wo(String(g));return{sqrtPriceStart:e,tickNext:c.sqrtPriceToTick(p),sqrtPriceNext:p,initialised:!1,amountIn:f,amountOut:m,feeAmount:y}}}Ec.logger=new We({debug:!1,context:"SwapDeltaCalculator"});class Ic extends hs{constructor(e,t,n,r){super(!1,r),this.cache=new Map,this.tierSizes={hot:50,warm:200,cold:0},this.tierTTLs={hot:1/0,warm:18e5,cold:3e5},this.refetchThresholds={swapCount:50,driftPercent:.05},this.fetchPoolFn=e,this.config=t,this.metrics=n,this.tierSizes.cold=Math.max(0,this.config.maxPools-this.tierSizes.hot-this.tierSizes.warm),this.logger.debug(`Initialized with cache limits: hot=${this.tierSizes.hot}, warm=${this.tierSizes.warm}, cold=${this.tierSizes.cold}, max=${this.config.maxPools}`)}async getPool(e){const t=this.cache.get(e);if(t){if(!(Date.now()>t.expiresAt))return t.lastAccessTime=Date.now(),this.checkRefetchNeeded(e,t),this.metrics.recordPoolCacheHit(e,0),t.poolData;this.cache.delete(e),this.logger.debug(`Cache expired for pool ${e}`)}this.metrics.recordPoolCacheMiss(e,0);try{const t=await this.fetchPoolFn(e),n=this.determineTier(),r={poolData:t,tier:n,lastAccessTime:Date.now(),expiresAt:Date.now()+this.tierTTLs[n],swapsSinceRefetch:0,cumulativeDrift:0,lastDeltaAppliedTime:Date.now()};return this.cache.set(e,r),this.cache.size>this.config.maxPools&&this.evictLRU(),this.logger.debug(`Fetched pool ${e} (tier: ${n})`),t}catch(t){throw this.logger.error(`Failed to fetch pool ${e}:`,t),t}}updatePoolWithSwapDelta(e,t,n,r,i){const o=this.cache.get(e);if(!o)return this.logger.debug(`Pool ${e} not in cache for delta update`),!1;try{if(i){const s="zeroForOne"===t,a=s?n:r,c={transactionId:i.transactionId,timestamp:i.timestamp,amountSpecified:a,zeroForOne:s,exactInput:i.exactInput},l=Ec.calculateSwapDelta(o.poolData,c);o.poolData={...o.poolData,pool:l.updatedPool},o.swapsSinceRefetch++,o.lastDeltaAppliedTime=Date.now(),void 0!==l.metadata.driftPercentage?(o.cumulativeDrift+=l.metadata.driftPercentage,this.logger.debug(`Delta applied for ${e}: drift=${l.metadata.driftPercentage.toFixed(4)}%, cumulative=${o.cumulativeDrift.toFixed(2)}%`)):this.logger.debug(`Delta applied for ${e}: ${l.ticksCrossed.length} ticks crossed`)}else o.swapsSinceRefetch++,o.lastDeltaAppliedTime=Date.now();return this.shouldRefetch(o)&&(this.logger.debug(`Refetch needed for ${e}: swaps=${o.swapsSinceRefetch}, drift=${(100*o.cumulativeDrift).toFixed(2)}%`),o.expiresAt=Date.now()),!0}catch(t){return this.logger.error(`Failed to update pool ${e}:`,t),o.expiresAt=Date.now(),!1}}getStats(){const e={totalCached:this.cache.size,hotCacheSize:0,warmCacheSize:0,coldCacheSize:0,memoryUsedMB:this.metrics.getMemoryUsedMB()};for(const t of this.cache.values())"hot"===t.tier?e.hotCacheSize++:"warm"===t.tier?e.warmCacheSize++:e.coldCacheSize++;return e}getPoolInfo(e){const t=this.cache.get(e);return t?{poolKey:e,tier:t.tier,lastAccessTime:new Date(t.lastAccessTime),expiresAt:new Date(t.expiresAt),swapsSinceRefetch:t.swapsSinceRefetch,cumulativeDrift:t.cumulativeDrift,isExpired:Date.now()>t.expiresAt}:null}async warmCache(e){if(!e)throw W("poolKey","Pool key");if(this.cache.has(e))return!0;try{return await wr(async()=>{await this.getPool(e),this.logger.debug(`Cache warmed for ${e}`)},`Failed to warm cache for ${e}`,this.logger),!0}catch{return!1}}async warmCacheBatch(e,t=5){if(!e)throw W("poolKeys","Pool keys array");return wr(async()=>{const n={succeeded:0,failed:0,total:e.length};let r=0;const i=new Set;for(;r<e.length||i.size>0;){for(;r<e.length&&i.size<t;){const t=e[r];r++;const o=this.warmCache(t).then(e=>{e?n.succeeded++:n.failed++});i.add(o),o.finally(()=>i.delete(o))}i.size>0&&await Promise.race(i)}return this.logger.debug(`Cache warming complete: ${n.succeeded}/${n.total} succeeded`),n},"Failed to warm cache batch",this.logger)}clear(){this.cache.clear(),this.logger.debug("Cache cleared")}clearExpired(){const e=Date.now();let t=0;for(const[n,r]of this.cache)e>r.expiresAt&&(this.cache.delete(n),t++);t>0&&this.logger.debug(`Cleared ${t} expired entries`)}determineTier(){const e=Array.from(this.cache.values()).filter(e=>"hot"===e.tier).length,t=Array.from(this.cache.values()).filter(e=>"warm"===e.tier).length;return e<this.tierSizes.hot?"hot":t<this.tierSizes.warm?"warm":"cold"}checkRefetchNeeded(e,t){this.shouldRefetch(t)&&(this.logger.debug(`Scheduling refetch for ${e}: swaps=${t.swapsSinceRefetch}, drift=${(100*t.cumulativeDrift).toFixed(2)}%`),t.expiresAt=Date.now())}shouldRefetch(e){return e.swapsSinceRefetch>=this.refetchThresholds.swapCount||e.cumulativeDrift>=this.refetchThresholds.driftPercent}evictLRU(){const e=Array.from(this.cache.entries()).filter(([e,t])=>"cold"===t.tier).sort((e,t)=>e[1].lastAccessTime-t[1].lastAccessTime);if(0===e.length){this.logger.warn("No cold cache entries to evict, trying warm cache");const e=Array.from(this.cache.entries()).filter(([e,t])=>"warm"===t.tier).sort((e,t)=>e[1].lastAccessTime-t[1].lastAccessTime);if(e.length>0){const[t]=e[0];this.cache.delete(t),this.logger.debug(`Evicted warm cache entry: ${t}`)}return}const[t]=e[0];this.cache.delete(t),this.logger.debug(`Evicted cold cache entry: ${t}`)}async refreshWarmAndHotTiers(){const e=Array.from(this.cache.entries()).filter(([e,t])=>"hot"===t.tier||"warm"===t.tier).sort((e,t)=>t[1].lastAccessTime-e[1].lastAccessTime).slice(0,10);if(0===e.length)return;const t=e.map(([e,t])=>this.fetchPoolFn(e).then(n=>{t&&(t.poolData=n,t.lastAccessTime=Date.now(),t.swapsSinceRefetch=0,t.cumulativeDrift=0),this.logger.debug(`Refreshed ${e} during background warming`)}).catch(t=>{this.logger.debug(`Failed to refresh ${e} during background warming:`,t)})),n=new Promise(e=>setTimeout(()=>e(),5e3));await Promise.race([Promise.all(t),n])}}class xc extends hs{constructor(e,t,n){super(!1,n),this.queue=[],this.isShuttingDown=!1,this.currentConcurrency=0,this.maxConcurrencyReached=0,this.eventsDropped=0,this.totalBatchesProcessed=0,this.totalBatchSize=0,this.eventsProcessedCount=0,this.processor=null,this.processingScheduled=!1,this.scheduleProcessing=e=>{"undefined"!=typeof setImmediate?setImmediate(e):Promise.resolve().then(e)},this.config=e,this.metrics=t,this.logger.debug(`Initialized with maxQueueSize=${this.config.maxQueueSize}, batchSize=${this.config.batchSize}, maxConcurrent=${this.config.maxConcurrent}`)}setProcessor(e){this.processor=e}enqueue(e){return this.isShuttingDown?(this.logger.debug(`Rejecting event (queue shutting down): ${e.transactionId}`),this.metrics.recordEventDropped(),this.eventsDropped++,!1):this.queue.length>=this.config.maxQueueSize?(this.logger.warn(`Queue full (${this.queue.length}/${this.config.maxQueueSize}), dropping event: ${e.transactionId}`),this.metrics.recordEventDropped(),this.eventsDropped++,!1):(this.queue.push(e),this.metrics.updateQueueDepth(this.queue.length),this.processingScheduled||this.isShuttingDown||(this.processingScheduled=!0,this.scheduleProcessing(()=>this.processNextBatch())),!0)}getQueueSize(){return this.queue.length}getStats(){return{queueSize:this.queue.length,eventsProcessed:this.eventsProcessedCount,eventsDropped:this.eventsDropped,currentConcurrent:this.currentConcurrency,maxConcurrentReached:this.maxConcurrencyReached,averageBatchSize:this.totalBatchesProcessed>0?Math.floor(this.totalBatchSize/this.totalBatchesProcessed):0,totalBatchesProcessed:this.totalBatchesProcessed}}async waitForEmpty(e){return new Promise(t=>{const n=()=>{0!==this.queue.length||0!==this.currentConcurrency?setTimeout(n,10):t()};e&&setTimeout(()=>t(),e),n()})}async shutdown(e=3e4){this.isShuttingDown=!0,this.logger.debug("Shutting down queue...");const t=Date.now();for(;this.queue.length>0||this.currentConcurrency>0;){if(Ve(t)>e){this.logger.warn(`Queue shutdown timeout: ${this.queue.length} events remaining, ${this.currentConcurrency} processing`);break}await new Promise(e=>setTimeout(e,50))}this.logger.debug("Queue shutdown complete")}clear(){const e=this.queue.length;this.queue.length=0,this.eventsDropped+=e,this.metrics.updateQueueDepth(0),this.logger.warn(`Cleared ${e} events from queue`)}async processNextBatch(){if(this.processingScheduled=!1,this.isShuttingDown&&0===this.queue.length)return;if(this.currentConcurrency>=this.config.maxConcurrent)return void setTimeout(()=>{this.processingScheduled||(this.processingScheduled=!0,setImmediate(()=>this.processNextBatch()))},10);const e=Math.min(this.config.batchSize,this.queue.length,this.config.maxConcurrent-this.currentConcurrency);if(0===e)return;const t=this.queue.splice(0,e);this.metrics.updateQueueDepth(this.queue.length),this.currentConcurrency+=t.length,this.currentConcurrency>this.maxConcurrencyReached&&(this.maxConcurrencyReached=this.currentConcurrency),this.totalBatchSize+=t.length,this.totalBatchesProcessed++;try{const e=await Promise.allSettled(t.map(e=>this.processEvent(e)));for(let n=0;n<e.length;n++){const r=e[n];this.eventsProcessedCount++,"rejected"===r.status&&this.logger.error(`Failed to process event ${t[n].transactionId}:`,r.reason)}}finally{this.currentConcurrency-=t.length}this.queue.length>0&&!this.processingScheduled&&(this.processingScheduled=!0,this.scheduleProcessing(()=>this.processNextBatch()))}async processEvent(e){if(!this.processor)return void this.logger.warn("No processor set, discarding event:",e.transactionId);const t=Date.now();try{await this.processor(e);const n=Ve(t);this.metrics.recordEventLatency(n)}catch(t){throw this.logger.error(`Event processing failed for ${e.transactionId}:`,t),t}}}class Cc extends hs{constructor(e,t,n,r={},i){super(!1,i),this.socket=null,this.maxSeenTransactions=1e4,this.listeners=[],this.onErrorCallbacks=[],this.isActive=!1,this.listenerRegistered=!1,this.handleSwapEvent=null,this.warmingIntervalHandle=null,e instanceof Promise?this.socketReady=e.then(e=>(this.socket=e,this.setupConnectionMonitoring(),e)).catch(e=>{throw this.logger.error("Failed to resolve socket promise:",e),e}):(this.socket=e,this.socketReady=Promise.resolve(e),this.setupConnectionMonitoring()),this.metrics=new bc,this.config=this.applyDefaults(r),this.eventExtractor=new Sc(this.logger),this.quoteService=n,this.cacheManager=new Ic(t,this.config,this.metrics,this.logger),this.eventQueue=new xc(this.config,this.metrics,this.logger),this.seenTransactions=new Nc(this.maxSeenTransactions),this.reconnectionManager=new nc({maxAttempts:3,baseDelayMs:1e3,useExponentialBackoff:!0,maxDelayMs:3e4}),this.eventQueue.setProcessor(e=>this.processSwapEvent(e)),this.logger.debug("Initialized MultiPoolStateManager")}subscribe(e,t){this.listeners.push(t),e.onError&&this.onErrorCallbacks.push(e.onError),this.isActive||(this.setupWebSocketListener(e),this.isActive=!0);const n=this;return()=>{n.listeners=n.listeners.filter(e=>e!==t),e.onError&&(n.onErrorCallbacks=n.onErrorCallbacks.filter(t=>t!==e.onError)),0===n.listeners.length&&0===n.onErrorCallbacks.length&&n.unsubscribe()}}getHealth(){const e=this.cacheManager.getStats(),t=this.eventQueue.getStats(),n=this.metrics.getHealthMetrics(e.totalCached,e.hotCacheSize,e.warmCacheSize,e.coldCacheSize,this.getMaxMemoryMB()),r=this.determineHealthStatus(t,e),i={connected:this.socket?.connected??!1,reconnectAttempts:this.reconnectionManager.getAttempts()};this.socket?.connected&&(i.lastConnectionTime=new Date);const o=t.queueSize/this.config.maxQueueSize*100,s=e.totalCached/this.config.maxPools*100,a=e.memoryUsedMB/this.getMaxMemoryMB()*100,c=this.generateHealthRecommendations(r,o,s,a,n.metrics.cacheHitRate);return{...n,status:r,websocket:i,recommendations:c,detailedMetrics:{eventQueueUtilization:o,cacheUtilization:s,memoryUtilization:a}}}generateHealthRecommendations(e,t,n,r,i){const o=[];return"failed"===e&&(o.push("🔴 System is in FAILED state - immediate action required"),this.socket?.connected||o.push("Reconnect WebSocket - connection lost"),t>90&&o.push("Reduce incoming event rate or increase maxQueueSize")),"degraded"===e&&(o.push("⚠️ System is DEGRADED - performance may be impacted"),t>75&&o.push(`Queue utilization ${t.toFixed(1)}% - consider increasing maxQueueSize`),r>80&&o.push(`Memory usage ${r.toFixed(1)}% - consider reducing cache size or memory profile`)),"healthy"===e&&(i<50&&o.push(`Cache hit rate ${i.toFixed(1)}% is low - consider warming more pools`),r>50&&o.push("Memory usage is moderate - monitor for growth trends"),t>50&&o.push("Queue utilization is elevated - monitor for bottlenecks")),o}getSummary(){return{...this.metrics.getSummary(),queueStats:this.eventQueue.getStats(),cacheStats:this.cacheManager.getStats()}}startBackgroundWarming(){if(this.warmingIntervalHandle)return;const e=this.config.refreshIntervalMs;this.warmingIntervalHandle=setInterval(()=>{this.performBackgroundWarming().catch(e=>{this.logger.error("Background warming error:",e)})},e),this.logger.debug(`Background warming started (interval: ${e}ms)`)}stopBackgroundWarming(){this.warmingIntervalHandle&&(clearInterval(this.warmingIntervalHandle),this.warmingIntervalHandle=null,this.logger.debug("Background warming stopped"))}async performBackgroundWarming(){const e=this.cacheManager.getStats();if(0!==e.totalCached)try{await this.cacheManager.refreshWarmAndHotTiers(),this.logger.debug(`Background warming completed: ${e.totalCached} pools in cache (hot: ${e.hotCacheSize}, warm: ${e.warmCacheSize})`)}catch(e){this.logger.debug("Background warming encountered an error:",e)}}async shutdown(){this.stopBackgroundWarming(),await this.unsubscribe(),await this.eventQueue.shutdown(),this.cacheManager.clear(),this.metrics.reset()}setupConnectionMonitoring(){this.socket&&(this.socket.on("disconnect",()=>{this.logger.warn("WebSocket disconnected"),this.notifyError(new Error("WebSocket disconnected")),this.config.autoRecover&&this.attemptReconnection().catch(e=>{this.logger.error("Reconnection failed:",e)})}),this.socket.on("connect_error",e=>{this.logger.error("WebSocket connection error:",e),this.notifyError(S(e)?e:new Error(A(e)))}))}async attemptReconnection(){const e=this.reconnectionManager.getAttempts(),t=this.reconnectionManager.getMaxAttempts();if(this.logger.debug(`Reconnection attempt ${e+1}/${t}`),this.reconnectionManager.isExhausted())return this.logger.error(`Max reconnection attempts (${t}) exceeded - performing full reset`),void await this.performFullReset();if(e<2)if(0===e)this.logger.debug("Tier 1: Quick reconnect");else{const e=this.reconnectionManager.getNextDelay();this.logger.debug(`Tier 2: Exponential backoff (${e}ms)`),await new Promise(t=>setTimeout(t,e))}try{this.socket?.disconnect&&(this.socket.disconnect(),this.logger.debug("Disconnected for reconnection")),this.socket?.connect?.(),this.logger.debug("Reconnection initiated"),this.reconnectionManager.recordAttempt()}catch(e){throw this.logger.error("Failed to initiate reconnection:",e),e}}async performFullReset(){this.logger.warn("Performing full system reset due to connection failures"),this.stopBackgroundWarming();const e=this.getHealth();this.logger.debug("System state before reset:",{status:e.status,queueSize:e.eventProcessing.eventsProcessed,cachedPools:e.pools.totalMonitored,memory:`${e.memory.usedMB}MB / ${e.memory.maxMB}MB`,cacheHitRate:`${e.metrics.cacheHitRate.toFixed(2)}%`}),this.cacheManager.clear(),this.metrics.reset(),this.reconnectionManager.reset(),this.notifyError(new Error("System reset: connection lost and recovery failed - please restart monitoring")),this.logger.info("System reset complete - ready for restart")}setupWebSocketListener(e){if(this.listenerRegistered)return void this.logger.debug("WebSocket listener already registered");const t=this;this.handleSwapEvent=(n,...r)=>{try{const n=Date.now(),i=r[0],o=t.eventExtractor.walkPayloadForSwaps(i,t.seenTransactions);if(0===o.length)return;t.logger.debug(`Extracted ${o.length} swaps from payload`);for(const n of o){if(t.filterSwap(n,e)){t.eventQueue.enqueue(n)||t.logger.debug(`Swap dropped due to queue overflow: ${n.transactionId}`)}}const s=Ve(n);t.metrics.recordEventLatency(s)}catch(e){t.logger.error("Error processing WebSocket payload:",e),t.notifyError(S(e)?e:new Error(A(e)))}},this.socket?(this.socket.onAny(this.handleSwapEvent),this.listenerRegistered=!0,this.setupConnectionMonitoring()):this.logger.warn("Socket not available for listener registration"),this.startBackgroundWarming(),this.logger.debug("WebSocket listener registered for all events")}async unsubscribe(){this.stopBackgroundWarming(),this.handleSwapEvent&&this.listenerRegistered&&this.socket&&(this.socket.offAny(this.handleSwapEvent),this.listenerRegistered=!1),this.isActive=!1,this.listeners=[],this.onErrorCallbacks=[],this.logger.debug("Unsubscribed from swap events")}filterSwap(e,t){if(t.tokenFilter){if(!vc.containsToken(e.poolKey,t.tokenFilter))return!1}if(t.pairTokens){const[n,r]=t.pairTokens;if(!vc.containsTokenPair(e.poolKey,n,r))return!1}if(t.feeTierFilter){if(vc.normalizeFee(t.feeTierFilter)!==e.feeTier)return!1}return!t.userFilter||e.user===t.userFilter}async processSwapEvent(e){const t=Date.now();try{const n=this.cacheManager.updatePoolWithSwapDelta(e.poolKey,e.direction,e.amount0,e.amount1,e);e.poolStateUpdated=n;const r=Ve(t);this.metrics.recordEventLatency(r);for(const t of this.listeners)try{const n=t(e);n instanceof Promise&&await n}catch(t){this.logger.error(`Listener error for swap ${e.transactionId}:`,t)}}catch(t){this.logger.error(`Failed to process swap ${e.transactionId}:`,t),this.notifyError(S(t)?t:new Error(A(t)))}}notifyError(e){for(const t of this.onErrorCallbacks)try{t(e)}catch(e){this.logger.error("Error in error callback:",e)}}determineHealthStatus(e,t){return!this.socket?.connected||e.queueSize>.9*this.config.maxQueueSize?"failed":e.queueSize>.75*this.config.maxQueueSize||t.memoryUsedMB>.9*this.getMaxMemoryMB()?"degraded":"healthy"}getMaxMemoryMB(){switch(this.config.memoryProfile){case"conservative":return 55;case"aggressive":return 530;default:return 250}}applyDefaults(e){return{memoryProfile:e.memoryProfile??"moderate",maxPools:e.maxPools??500,softLimit:e.softLimit??200,preloadTopN:e.preloadTopN??200,warmingTimeoutMs:e.warmingTimeoutMs??3e4,refreshIntervalMs:e.refreshIntervalMs??3e5,maxQueueSize:e.maxQueueSize??1e4,batchSize:e.batchSize??100,maxConcurrent:e.maxConcurrent??10,autoRecover:e.autoRecover??!0,maxParallelRefetch:e.maxParallelRefetch??20,enableDeltaOptimization:e.enableDeltaOptimization??!0,enableOfflineQuotes:e.enableOfflineQuotes??!0,metricsEnabled:e.metricsEnabled??!0,debug:e.debug??!1}}}class Nc{constructor(e){this.map=new Map,this.maxSize=e}has(e){return this.map.has(e)}add(e){if(this.map.has(e))return this.map.delete(e),this.map.set(e,Date.now()),this;if(this.map.size>=this.maxSize){const e=this.map.keys().next().value;this.map.delete(e)}return this.map.set(e,Date.now()),this}delete(e){return this.map.delete(e)}clear(){this.map.clear()}get size(){return this.map.size}}class _c extends hs{constructor(e=!1){super(e),this.primaryIndex=new Map,this.secondaryIndex=new Map,this.fetchTimestamps=new Map}normalizeKey(e){return is(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,o]of this.primaryIndex){t.push(e),n+=o.size,r[e]=o.size;const s=this.fetchTimestamps.get(e);s&&(i[e]=s)}return{networks:t,totalItems:n,itemsByNetwork:r,fetchTimestamps:i}}clear(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 Bc=["ETHEREUM","SOLANA"];class Pc extends _c{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(Bc);return{...e,totalTokens:e.totalItems,tokensByNetwork:e.itemsByNetwork}}}class Dc{constructor(e,t=!1,n){this.dexApiHttp=e,this.logger=new We({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),o=await this.dexApiHttp.request({method:"GET",url:this.getApiEndpoint(),params:{...i,limit:r,offset:e}});if(Ze(o)||!Array.isArray(o.tokens))throw new B("Invalid API response: expected { tokens: array }","response","INVALID_RESPONSE");return{items:this.transformApiResponse(o.tokens),rawCount:o.tokens.length}}async autoPaginateFetch(e){return async function(e,t){const{maxLimit:n,logger:r,maxPages:i=1e4}=t,o=[];let s=0,a=!0,c=0;for(;a&&c<i;){r&&r.debug(`Auto-pagination (offset): fetching at offset ${s} with limit ${n}`);const t=await e(s,n);if(!t||!Array.isArray(t.items)){r&&r.warn("Auto-pagination (offset): received invalid result structure, stopping");break}o.push(...t.items),a=t.rawCount===n,s+=n,c++,r&&r.debug(`Auto-pagination (offset): fetched ${o.length} items so far (hasMore=${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: ${o.length}`),o}(async(t,n)=>this.executePaginatedRequest(t,n,e),{maxLimit:this.getMaxLimit(),logger:this.logger})}handleError(e,t){throw X(e,t,this.logger)}}class Rc extends Dc{constructor(e,t=!1){super(e,t,"BridgeableTokenService"),this.cache=new Pc(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 t?.contractAddress&&(i.ethereumContractAddress=t.contractAddress),t?.symbol&&(i.ethereumSymbol=t.symbol),void 0!==t?.allowanceStorageSlot&&(i.ethereumAllowanceSlot=t.allowanceStorageSlot),n?.contractAddress&&(i.solanaContractAddress=n.contractAddress),n?.symbol&&(i.solanaSymbol=n.symbol),e.image&&(i.image=e.image),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})`),wr(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 wr(async()=>{const t=await async function(e){const{network:t,cache:n,fetchFn:r,logger:i,itemTypeName:o="items"}=e;if(n.has(t)){const e=n.getAll(t);return i&&i.debug(`Returning ${e.length} cached ${o} for ${t}`),{items:e,fetchedAt:n.getFetchTimestamp(t)??Date.now(),itemCount:e.length}}i&&i.debug(`Fetching all ${o} for ${t} (no cache)`);const s=await r();return n.set(t,s),{items:s,fetchedAt:Date.now(),itemCount:s.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=ia(t);this.cache.has(n)||await this.fetchAllBridgeableTokensByNetwork(n);const i=this.cache.getByTokenId(n,r),o=void 0!==i,s=o?"ETHEREUM"===n?i.ethereumContractAddress:i.solanaContractAddress:void 0,a={isBridgeable:o,tokenSymbol:i?.symbol??js(r).collection,network:n};return void 0!==s&&(a.contractAddress=s),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)}}class Mc extends mc{constructor(e=!1){super(e),this.lastFetchedAt=null}normalizeKey(e){return is(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 Lc extends Mc{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 Oc extends Dc{constructor(e,t=!1){super(e,t,"WrappableTokenService"),this.cache=new Lc(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 e.channel&&(t.channel=e.channel),void 0!==e.trending&&(t.trending=e.trending),e.image&&(t.image=e.image),e.description&&(t.description=e.description),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())})`),wr(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 wr(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 o=await n();try{t.setAll(o)}catch(e){r&&r.error("Cache operation failed (non-fatal):",e)}return{items:o,fetchedAt:Date.now(),itemCount:o.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=ia(e),n=this.cache.getByTokenId(t);return n||(await Za("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=ia(e);await Za("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&&n&&(i.wrapCounterpart=n.wrapCounterpart),i}getCacheStats(){return this.cache.getStats()}clearCache(){this.cache.clear()}}function Fc(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function Uc(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 $c,qc,Kc,Gc,Wc,zc;function Hc(){return Gc?Kc:(Gc=1,Kc={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})}var jc=function(){if(zc)return Wc;zc=1;const e=qc?$c:(qc=1,$c={space:"",cycles:!1,replacer:(e,t)=>t,stringify:JSON.stringify}),t=Hc().isFunction,n=Hc().isBoolean,r=Hc().isObject,i=Hc().isArray,o=Hc().isRegex,s=Hc().assign,a=Hc().keys;return Wc=function(c,l){l=l||s({},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,p=l.compare&&(f=l.compare,function(e){return function(t,n){const r={key:t,value:e[t]},i={key:n,value:e[n]};return f(r,i)}});var f;d||g(c);const m=[];return function e(t,n,s,c){const l=u?"\n"+new Array(c+1).join(u):"",f=u?": ":":";if(s=function(e){return null==e?e:o(e)?e.toString():e.toJSON?e.toJSON():e}(s),void 0!==(s=h.call(t,n,s))){if(!r(s)||null===s)return g(s);if(i(s)){const t=[];for(let n=0;n<s.length;n++){const r=e(s,n,s[n],c+1)||g(null);t.push(l+u+r)}return"["+t.join(",")+l+"]"}{if(d){if(-1!==m.indexOf(s))return g("[Circular]");m.push(s)}const t=a(s).sort(p&&p(s)),n=[];for(let r=0;r<t.length;r++){const i=t[r],o=e(s,i,s[i],c+1);if(!o)continue;const a=g(i)+f+o;n.push(l+u+a)}return m.splice(m.indexOf(s),1),"{"+n.join(",")+l+"}"}}}({"":c},"",c,0)},Wc}(),Vc=Fc(jc);const Xc={GALA_CHAIN:1,ETHEREUM:2,SOLANA:1002},Qc={ASSET:1,MUSIC:3};const Jc="0x9f452b7cC24e6e6FA690fe77CF5dD2ba3DbF1ED9",Zc="0x6a1734E09f3099a3675645D214ce547080ea67e0",Yc="https://dex-api-platform-dex-prod-gala.gala.com",el=[{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}],tl=[{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 nl(e){return"PROD"===e?el:tl}function rl(e){return"PROD"===e?Jc:Zc}const il=el,ol=[{symbol:"GALA",amount:"1",mintAddress:"eEUiUs4JWYZrp72djAGF1A8PhpR6rHphGeGN7GbVLp6",isNative:!1,decimals:8},{symbol:"GSOL",amount:"0.001",mintAddress:"So11111111111111111111111111111111111111111",isNative:!0,decimals:9}],sl={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"}},al=["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)"],cl=["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"],ll={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])};const ul={name:"GalaConnect",chainId:1},dl=[{name:"destinationChainId",type:"uint256"},{name:"destinationChainTxFee",type:"destinationChainTxFee"},{name:"quantity",type:"string"},{name:"recipient",type:"string"},{name:"tokenInstance",type:"tokenInstance"},{name:"uniqueKey",type:"string"}],hl=[{name:"collection",type:"string"},{name:"category",type:"string"},{name:"type",type:"string"},{name:"additionalKey",type:"string"}],gl=[{name:"collection",type:"string"},{name:"category",type:"string"},{name:"type",type:"string"},{name:"additionalKey",type:"string"},{name:"instance",type:"string"}],pl=[{name:"name",type:"string"},{name:"symbol",type:"string"}],fl={GalaTransaction:dl,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:hl,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:gl,externalQuoteToken:pl,tokenInstance:gl},ml={GalaTransaction:dl,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:hl,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:pl,externalQuoteToken:pl,externalCrossRateToken:pl,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:gl,tokenInstance:gl};function yl(e){return e?ml:fl}const wl={GalaTransaction:[{name:"quantity",type:"string"},{name:"tokenInstance",type:"tokenInstance"},{name:"destinationChainId",type:"uint256"},{name:"recipient",type:"string"},{name:"wrap",type:"bool"},{name:"uniqueKey",type:"string"}],tokenInstance:gl};class kl extends hs{constructor(e){super(!1,e.logger),this.galaConnectClient=e.galaConnectClient,this.wrappableTokenService=e.wrappableTokenService,this.wallet=e.wallet,this.walletAddress=e.walletAddress}async wrapToken(e){this.requireWallet();const t=await this.wrappableTokenService.getWrappableToken(e.tokenId);if(!t)throw new B(`Token not found or not wrappable: ${this.formatTokenId(e.tokenId)}`,"tokenId","TOKEN_NOT_WRAPPABLE");if("asset"===t.channel)throw new B(`Cannot wrap ${t.symbol} - it's already on asset channel. Use unwrapToken() instead.`,"tokenId","ALREADY_ON_ASSET_CHANNEL");const n=await this.wrappableTokenService.getWrapCounterpart(e.tokenId);if(!n)throw new B(`Counterpart token not found for ${t.symbol}`,"tokenId","COUNTERPART_NOT_FOUND");return this.executeChannelBridge({sourceToken:t,destinationToken:n,amount:e.amount,...e.recipient&&{recipient:e.recipient},...e.memo&&{memo:e.memo},isWrap:!0})}async unwrapToken(e){this.requireWallet();const t=await this.wrappableTokenService.getWrappableToken(e.tokenId);if(!t)throw new B(`Token not found or not wrappable: ${this.formatTokenId(e.tokenId)}`,"tokenId","TOKEN_NOT_WRAPPABLE");if("asset"!==t.channel)throw new B(`Cannot unwrap ${t.symbol} - it's not on asset channel. Use wrapToken() instead.`,"tokenId","NOT_ON_ASSET_CHANNEL");const n=await this.wrappableTokenService.getWrapCounterpart(e.tokenId);if(!n)throw new B(`Counterpart token not found for ${t.symbol}`,"tokenId","COUNTERPART_NOT_FOUND");return this.executeChannelBridge({sourceToken:t,destinationToken:n,amount:e.amount,...e.recipient&&{recipient:e.recipient},...e.memo&&{memo:e.memo},isWrap:!1})}async estimateWrapFee(e,t){if(!e)throw W("tokenId","Token identifier");if(!t)throw W("amount");const n=await this.wrappableTokenService.getWrappableToken(e);if(!n)throw new B(`Token not found or not wrappable: ${this.formatTokenId(e)}`,"tokenId","TOKEN_NOT_WRAPPABLE");if("asset"===n.channel)throw new B(`Cannot wrap ${n.symbol} - it's already on asset channel`,"tokenId","ALREADY_ON_ASSET_CHANNEL");const r=this.determineChannelRouting(n,!0);return{fee:"0",feeToken:"GALA",authorizationType:r.authType,feeChannel:r.sourceChannel}}async estimateUnwrapFee(e,t){if(!e)throw W("tokenId","Token identifier");if(!t)throw W("amount");const n=await this.wrappableTokenService.getWrappableToken(e);if(!n)throw new B(`Token not found or not wrappable: ${this.formatTokenId(e)}`,"tokenId","TOKEN_NOT_WRAPPABLE");if("asset"!==n.channel)throw new B(`Cannot unwrap ${n.symbol} - it's not on asset channel`,"tokenId","NOT_ON_ASSET_CHANNEL");const r=this.determineChannelRouting(n,!1);return{fee:"0",feeToken:"GALA",authorizationType:r.authType,feeChannel:r.sourceChannel}}async getWrapStatus(e){if(!e)throw W("transactionId");return{success:!0,status:"completed",transactionId:e,fromToken:"",toToken:"",amount:"",fromChannel:"",toChannel:""}}async executeChannelBridge(e){const{sourceToken:t,destinationToken:n,amount:r,recipient:i,isWrap:o}=e;if(!this.wallet||!this.walletAddress)throw new B("Wallet required for wrap/unwrap operations. Initialize SDK with a private key.","wallet","WALLET_REQUIRED");const s=this.walletAddress,a=this.determineChannelRouting(t,o),c=`galaswap-operation-${l.randomUUID()}`,u=wl,d={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||s,wrap:!0,uniqueKey:c};return this.logger.debug?.(`[WrapService] ${o?"Wrap":"Unwrap"} message (pre-signing):`,JSON.stringify(d,null,2)),this.executeWrapBridgeRequest({sourceToken:t,destinationToken:n,amount:r,message:d,routing:a,isWrap:o,senderAddress:s,typedDataTypes:u})}async executeWrapBridgeRequest(e){const{sourceToken:t,destinationToken:n,amount:r,message:i,routing:o,isWrap:s,typedDataTypes:a}=e;try{const e=await this.wallet.signTypedData(ul,a,i),c=`Ethereum Signed Message:\n${Vc({domain:ul,message:i,primaryType:"GalaTransaction",types:a}).length}`,l={...i,signature:e,prefix:c,types:a,domain:ul};this.logger.debug?.(`[WrapService] ${s?"Wrap":"Unwrap"} request (signed):`,JSON.stringify(l,null,2));const u=await this.galaConnectClient.requestBridgeOut(l);if(this.logger.debug?.("[WrapService] Response:",JSON.stringify(u,null,2)),function(e){return"object"==typeof e&&null!==e&&"Status"in e&&"number"==typeof e.Status&&1!==e.Status}(u)){const e=`Status=${u.Status}`,i=u.Message?`: ${u.Message}`:"";return{success:!1,fromToken:t.symbol,toToken:n.symbol,amount:r,fromChannel:o.sourceChannel,toChannel:s?"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}(u)){const e=u.Data;this.logger.debug?.("[WrapService] Step 1 complete, bridgeRequestId:",e);const i={bridgeFromChannel:o.sourceChannel,bridgeRequestId:e};this.logger.debug?.("[WrapService] Step 2 - BridgeTokenOut payload:",JSON.stringify(i,null,2));const a=await this.galaConnectClient.bridgeTokenOut(i);return this.logger.debug?.("[WrapService] BridgeTokenOut response:",JSON.stringify(a,null,2)),1!==a.Status?{success:!1,fromToken:t.symbol,toToken:n.symbol,amount:r,fromChannel:o.sourceChannel,toChannel:s?"asset":n.channel||"music",error:`BridgeTokenOut failed: ${JSON.stringify(a)}`}:{success:!0,transactionId:a.Hash||e,fromToken:t.symbol,toToken:n.symbol,amount:r,fromChannel:o.sourceChannel,toChannel:s?"asset":n.channel||"music",completedAt:Date.now()}}return{success:!1,fromToken:t.symbol,toToken:n.symbol,amount:r,fromChannel:o.sourceChannel,toChannel:s?"asset":n.channel||"music",error:`Unexpected response format from GalaChain: ${JSON.stringify(u)}`}}catch(e){const i=A(e);return this.logger.error?.(`[WrapService] ${s?"Wrap":"Unwrap"} operation failed:`,i),{success:!1,fromToken:t.symbol,toToken:n.symbol,amount:r,fromChannel:o.sourceChannel,toChannel:s?"asset":n.channel||"music",error:i}}}determineChannelRouting(e,t){if(t){return{sourceChannel:e.channel||"music",destinationChannelId:Qc.ASSET,authType:"cross_channel_authorization"}}return{sourceChannel:"asset",destinationChannelId:Qc.MUSIC,authType:"automatic"}}requireWallet(){if(!this.walletAddress)throw new B("Wallet required for wrap/unwrap operations. Initialize SDK with a private key.","wallet","WALLET_REQUIRED")}formatTokenId(e){return"string"==typeof e?e:Ks(e)}}const bl="x-api-key";class vl extends ds{constructor(e,t,n,r=!1){super(e,r),this.adminApiKey=t??void 0,this.jwtAuth=n}setJwtAuth(e){this.jwtAuth=e}validateTokenName(e,t){!function(e,t){if(!Qe(e))throw W("tokenName","Token name");const n=rs(e);if(!t.PATTERN.test(n))throw z("tokenName",`${t.MIN_LENGTH}-${t.MAX_LENGTH} alphanumeric characters`,"Token name")}(e,t)}validateRequiredString(e,t,n){!function(e,t,n){if(!Qe(e))throw W(t,n)}(e,t,n)}validateOptionalString(e,t,n,r){!function(e,t,n,r){if(null!=e){if("string"!=typeof e)throw Y(t,"string",typeof e,n);if(e.length>r)throw Z(t,r,e.length,n)}}(e,t,n,r)}validateOptionalNumber(e,t,n,r,i,o,s){!function(e,t,n,r,i){if(null!=e){if("number"!=typeof e)throw Y(t,"number",typeof e,n);if(e<r||e>i)throw Q(t,r,i,e,n)}}(e,t,n,r,i)}validateOptionalDate(e,t,n){!function(e,t,n){if(null!=e&&!je(e))throw z(t,"a valid ISO 8601 date string",n)}(e,t,n)}validatePositiveInteger(e,t,n){ls(e,t,n)}validateStatusFilter(e,t,n="status"){us(e,t,n)}buildPaginationParams(e,t){return Ss(e,t)}addOptionalFilterParams(e,t,n){return Ts(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(!this.adminApiKey)throw new D("Admin API key required for this operation. Set streamAdminApiKey in SDK config.");return{[bl]:this.adminApiKey}}getJwtHeaders(){if(!this.jwtAuth)throw new D("JWT authentication required. Call sdk.login() first.");return this.jwtAuth.getJwtHeaders()}hasJwtAuth(){return this.jwtAuth?.isValid()??!1}hasAdminApiKey(){return!!this.adminApiKey}getDualAuthHeaders(){return this.adminApiKey?this.getAdminHeaders():this.getJwtHeaders()}extractData(e){return fr(e,"Backend request failed",!0),yr(e,"No data in backend response")}async toggleFeature(e,t,n){this.validateTokenName(e,n);const r=this.buildEndpoint(t,{tokenName:e}),i=await this.http.post(r,{},this.getAdminHeaders()),o=this.extractData(i);return{enabled:o.enabled,tokenName:o.tokenName??rs(e)}}}const Sl={IDLE:"IDLE",ACTIVE:"ACTIVE",DISABLED:"DISABLED"},Al={READY:"READY",PROCESSING:"PROCESSING",ERRORED:"ERRORED",DELETED:"DELETED"},Tl={YOUTUBE:"YOUTUBE",TWITCH:"TWITCH",FACEBOOK:"FACEBOOK",CUSTOM:"CUSTOM"},El=et(Sl),Il=et(Al),xl=et(Tl);const Cl={OWNER:"OWNER",MANAGER:"MANAGER",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MODERATOR:"MODERATOR"},Nl={OWNER:"OWNER",MODERATOR:"MODERATOR"};et(Cl),et(Nl);const _l={...Cl,OVERSEER:"OVERSEER"},Bl={OWNERSHIP:"ownership",MODERATOR_INVITE:"moderator_invite",OVERSEER:"overseer"};function Pl(e){if(!e||"object"!=typeof e)return!1;const t=e;return"boolean"==typeof t.canStream&&"boolean"==typeof t.canModerate&&"boolean"==typeof t.canManageTeam&&"boolean"==typeof t.canViewRecordings&&"boolean"==typeof t.canSimulcast&&"boolean"==typeof t.canViewAnalytics}const Dl=et(_l),Rl=et(Bl);function Ml(e,t="tokenName"){rt(e,t,he)}function Ll(e){if(Ml(e.tokenName),!Qe(e.language))throw W("language");if(!Qe(t=e.language)||!/^[a-z]{2}(-[A-Z]{2})?$/.test(t))throw new B('language must be a valid ISO 639-1 code (e.g., "en", "es", "zh-CN")',"language",_.INVALID_FORMAT);var t}class Ol extends vl{constructor(e,t,n,r=!1){super(e,t,n,r)}async getStreamInfo(e){this.validateTokenName(e,he);const t=this.buildEndpoint(Gt,{tokenName:e}),n=await this.http.get(t);return this.extractData(n)}async startStream(e){this.validateTokenName(e,he);const t=this.buildEndpoint(qt,{tokenName:e}),n=await this.http.post(t,{},this.getJwtHeaders());return this.extractData(n)}async stopStream(e){this.validateTokenName(e,he);const t=this.buildEndpoint(Kt,{tokenName:e});await this.http.post(t,{},this.getJwtHeaders())}async disableStream(e){return this.toggleFeature(e,Wt,he)}async enableStream(e){return this.toggleFeature(e,zt,he)}async resetStreamKey(e){this.validateTokenName(e,he);const t=this.buildEndpoint(Ht,{tokenName:e}),n=await this.http.post(t,{},this.getJwtHeaders());return this.extractData(n)}async getRecordings(e){!function(e){Ml(e.tokenName),Ye(e.page,e.limit,Ce)}(e);const t=this.buildEndpoint(jt,{tokenName:e.tokenName}),n=this.buildPaginationParams(e,Ce),r=await this.http.get(t,n),i=this.extractData(r);return{recordings:i.recordings,tokenName:rs(e.tokenName),page:i.page??e.page??1,limit:i.limit??e.limit??20,total:i.total,hasNext:i.recordings.length===(i.limit??e.limit??20)}}async getRecordingDownload(e,t){this.validateTokenName(e,he),this.validateRequiredString(t,"assetId","Asset ID");const n=this.buildEndpoint(Vt,{tokenName:e,assetId:t}),r=await this.http.get(n,this.getJwtHeaders());return this.extractData(r)}async deleteRecording(e,t){this.validateTokenName(e,he),this.validateRequiredString(t,"assetId","Asset ID");const n=this.buildEndpoint(Xt,{tokenName:e,assetId:t});await this.http.delete(n,void 0,this.getJwtHeaders())}async getSimulcastTargets(e){this.validateTokenName(e,he);const t=this.buildEndpoint(Qt,{tokenName:e}),n=await this.http.get(t);return this.extractData(n)}async addSimulcastTarget(e){!function(e){if(Ml(e.tokenName),!Qe(e.platform))throw W("platform");if(!xl(e.platform))throw new B("platform must be one of: 'YOUTUBE', 'TWITCH', 'FACEBOOK', 'CUSTOM'","platform",_.INVALID_VALUE);if(!Qe(e.rtmpUrl))throw W("rtmpUrl");if(!xe.STREAM_URL_PATTERN.test(e.rtmpUrl))throw new B("rtmpUrl must be a valid RTMP, RTMPS, or SRT URL","rtmpUrl",_.INVALID_FORMAT);if(!Qe(e.streamKey))throw W("streamKey");if(void 0!==e.name&&"string"!=typeof e.name)throw new B("name must be a string","name",_.INVALID_TYPE)}(e);const t=this.buildEndpoint(Jt,{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,he),this.validateRequiredString(t,"targetId","Target ID");const n=this.buildEndpoint(Zt,{tokenName:e,targetId:t});await this.http.delete(n,void 0,this.getJwtHeaders())}async getGlobalStreamingStatus(){const e=await this.http.get(Yt);return this.extractData(e)}async disableGlobalStreaming(){const e=await this.http.post(en,{},this.getAdminHeaders());return this.extractData(e)}async enableGlobalStreaming(){const e=await this.http.post(tn,{},this.getAdminHeaders());return this.extractData(e)}async setNextLiveStream(e){let t;!function(e){if(Ml(e.tokenName),null!==e.nextLiveStreamAt){if(!(e.nextLiveStreamAt instanceof Date||Qe(e.nextLiveStreamAt)))throw new B("nextLiveStreamAt must be a Date, ISO 8601 string, or null","nextLiveStreamAt",_.INVALID_TYPE);if("string"==typeof e.nextLiveStreamAt){const t=Date.parse(e.nextLiveStreamAt);if(isNaN(t))throw new B("nextLiveStreamAt must be a valid ISO 8601 date string","nextLiveStreamAt",_.INVALID_FORMAT)}}}(e),t=null===e.nextLiveStreamAt?null:e.nextLiveStreamAt instanceof Date?e.nextLiveStreamAt.toISOString():e.nextLiveStreamAt;const n=this.buildEndpoint(nn,{tokenName:e.tokenName}),r=await this.http.post(n,{nextLiveStreamAt:t},this.getDualAuthHeaders());return this.extractData(r)}async clearNextLiveStream(e){this.validateTokenName(e,he);const t=this.buildEndpoint(rn,{tokenName:e}),n=await this.http.delete(t,void 0,this.getDualAuthHeaders());return this.extractData(n)}async setStreamLanguage(e){Ll(e);const t=this.buildEndpoint(on,{tokenName:e.tokenName}),n=await this.http.put(t,{language:e.language},this.getDualAuthHeaders());return this.extractData(n)}async getStreamRole(e){!function(e){Ml(e.tokenName)}(e);const t=this.buildEndpoint(sn,{tokenName:e.tokenName}),n=this.jwtAuth?this.getJwtHeaders():void 0,r=await this.http.get(t,n);return this.extractData(r)}async getAvailableRoles(){const e=await this.http.get(an);return this.extractData(e)}async getTokenAccess(e){!function(e){Ml(e.tokenName)}(e);const t=this.buildEndpoint(cn,{tokenName:e.tokenName}),n=this.jwtAuth?this.getJwtHeaders():void 0;this.jwtAuth||this.logger.debug("getTokenAccess called without JWT authentication - will return hasAccess: false",{tokenName:e.tokenName});const r=await this.http.get(t,n);return this.extractData(r)}async setNextLiveStreamCountdown(e,t){return this.setNextLiveStream({tokenName:e,nextLiveStreamAt:t})}}he.MIN_LENGTH,he.MAX_LENGTH,he.PATTERN;et({ENABLED:"ENABLED",DISABLED:"DISABLED",ADMIN_DISABLED:"ADMIN_DISABLED"});function Fl(e){return"global"===e||"token"===e}function Ul(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.messageId&&"string"==typeof t.content&&"string"==typeof t.userAddress&&"number"==typeof t.poolId&&"string"==typeof t.createdAt}function $l(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.messageId&&"string"==typeof t.content&&"string"==typeof t.userAddress&&"string"==typeof t.pinnedBy&&"string"==typeof t.pinnedAt}const ql=et({RATE_LIMITED:"RATE_LIMITED",INVALID_EMOJI:"INVALID_EMOJI",NOT_AUTHENTICATED:"NOT_AUTHENTICATED",STREAM_NOT_LIVE:"STREAM_NOT_LIVE"});function Kl(e){if(!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)}class Gl extends vl{constructor(e,t,n,r=!1){super(e,t,n,r)}async getMessages(e){if(!e)throw W("options","Fetch options");return function(e){if(!Qe(e.tokenName))throw W("tokenName","Token name");const t=e.tokenName.trim();if(0===t.length)throw W("tokenName","Token name");if(!he.PATTERN.test(t))throw z("tokenName",`match pattern ${he.PATTERN}`,"Token name");if(Ye(e.page,e.limit,we),void 0!==e.cursor&&!Qe(e.cursor))throw Y("cursor","a non-empty string",typeof e.cursor);if(void 0!==e.sortOrder&&"asc"!==e.sortOrder&&"desc"!==e.sortOrder)throw z("sortOrder","'asc' or 'desc'")}(e),wr(async()=>{const t=this.buildEndpoint(ln,{tokenName:e.tokenName}),n=this.buildPaginationParams(e,we);e.cursor&&(n.cursor=e.cursor),e.sortOrder&&(n.sortOrder=e.sortOrder);const r=await this.http.get(t,n),i=this.extractData(r),o=Vo(e.limit),s=i.page??jo(e.page),a={messages:i.messages,tokenName:rs(e.tokenName),page:s,limit:i.limit??o,total:i.total,hasNext:i.messages.length===o||!!i.nextCursor,pinnedMessage:i.pinnedMessage??null};return i.nextCursor&&(a.nextCursor=i.nextCursor),a},"Failed to fetch chat messages",this.logger)}async sendMessage(e){if(!e)throw W("options","Send message options");return function(e){if(!Qe(e.tokenName))throw W("tokenName","Token name");const t=e.tokenName.trim();if(0===t.length)throw W("tokenName","Token name");if(!he.PATTERN.test(t))throw z("tokenName",`match pattern ${he.PATTERN}`,"Token name");if(t.length>he.MAX_LENGTH)throw Z("tokenName",he.MAX_LENGTH,t.length,"Token name");if(!Qe(e.content))throw W("content","Message content");if(e.content.length<ve.CHAT_MESSAGE.MIN_LENGTH)throw J("content",ve.CHAT_MESSAGE.MIN_LENGTH,e.content.length,"Message content");if(e.content.length>ve.CHAT_MESSAGE.MAX_LENGTH)throw Z("content",ve.CHAT_MESSAGE.MAX_LENGTH,e.content.length,"Message content")}(e),wr(async()=>{const t=this.buildEndpoint(un,{tokenName:e.tokenName}),n=await this.http.post(t,{content:e.content},this.getJwtHeaders());return{message:this.extractData(n),tokenName:rs(e.tokenName)}},"Failed to send chat message",this.logger)}async deleteMessage(e){if(!e)throw W("options","Delete message options");return function(e){if(!Qe(e.tokenName))throw W("tokenName","Token name");const t=e.tokenName.trim();if(0===t.length)throw W("tokenName","Token name");if(!he.PATTERN.test(t))throw z("tokenName",`match pattern ${he.PATTERN}`,"Token name");if(!Qe(e.messageId))throw W("messageId","Message ID")}(e),wr(async()=>{const t=this.buildEndpoint(dn,{tokenName:e.tokenName,messageId:e.messageId}),n=this.adminApiKey?this.getAdminHeaders():this.getJwtHeaders(),r=await this.http.delete(t,n),i=this.extractData(r);return{messageId:i.messageId,deleted:i.deleted,tokenName:rs(e.tokenName)}},"Failed to delete chat message",this.logger)}async getChatStatus(e){if(!e)throw W("tokenName","Token name");return this.validateTokenName(e,he),wr(async()=>{const t=this.buildEndpoint(hn,{tokenName:e}),n=await this.http.get(t);return this.extractData(n)},`Failed to get chat status for token: ${e}`,this.logger)}async disableChat(e){if(!e)throw W("tokenName","Token name");return this.validateTokenName(e,he),wr(async()=>{const t=this.buildEndpoint(gn,{tokenName:e}),n=await this.http.post(t,{},this.getDualAuthHeaders()),r=this.extractData(n),i={enabled:r.enabled,tokenName:r.tokenName??rs(e)};return r.status&&(i.status=r.status),i},`Failed to disable chat for token: ${e}`,this.logger)}async enableChat(e){if(!e)throw W("tokenName","Token name");return this.validateTokenName(e,he),wr(async()=>{const t=this.buildEndpoint(pn,{tokenName:e}),n=await this.http.post(t,{},this.getDualAuthHeaders()),r=this.extractData(n),i={enabled:r.enabled,tokenName:r.tokenName??rs(e)};return r.status&&(i.status=r.status),i},`Failed to enable chat for token: ${e}`,this.logger)}async getGlobalChatStatus(){const e=await this.http.get(wn);return this.extractData(e)}async disableGlobalChat(){const e=await this.http.post(kn,{},this.getAdminHeaders());return this.extractData(e)}async enableGlobalChat(){const e=await this.http.post(bn,{},this.getAdminHeaders());return this.extractData(e)}async getPinnedMessage(e){this.validateTokenName(e,he);const t=this.buildEndpoint(fn,{tokenName:e}),n=await this.http.get(t),r=this.extractData(n);return{tokenName:r.tokenName??rs(e),pinnedMessage:r.pinnedMessage}}async pinMessage(e){!function(e){if(!Qe(e.tokenName))throw W("tokenName","Token name");const t=e.tokenName.trim();if(0===t.length)throw W("tokenName","Token name");if(!he.PATTERN.test(t))throw z("tokenName",`match pattern ${he.PATTERN}`,"Token name");if(!Qe(e.messageId))throw W("messageId","Message ID")}(e);const t=this.buildEndpoint(mn,{tokenName:e.tokenName}),n=await this.http.post(t,{messageId:e.messageId},this.getAdminHeaders()),r=this.extractData(n);return{tokenName:r.tokenName??rs(e.tokenName),pinnedMessage:r.pinnedMessage}}async unpinMessage(e){this.validateTokenName(e,he);const t=this.buildEndpoint(yn,{tokenName:e}),n=await this.http.delete(t,this.getAdminHeaders()),r=this.extractData(n),i={tokenName:r.tokenName??rs(e),unpinned:r.unpinned};return r.unpinnedMessageId&&(i.unpinnedMessageId=r.unpinnedMessageId),i}async getEngagementStats(e){if(!e)throw W("options","Engagement stats options");return function(e){if(!Qe(e.tokenName))throw W("tokenName","Token name");const t=e.tokenName.trim();if(0===t.length)throw W("tokenName","Token name");if(!he.PATTERN.test(t))throw z("tokenName",`match pattern ${he.PATTERN}`,"Token name")}(e),wr(async()=>{const t=this.buildEndpoint(vn,{tokenName:e.tokenName}),n=await this.http.get(t,void 0,this.getDualAuthHeaders()),r=this.extractData(n);return{tokenName:rs(e.tokenName),chat:r.chat,comments:r.comments}},"Failed to get engagement stats",this.logger)}}const Wl={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",STREAM_SUBSCRIBED:"token_subscribed",STREAM_UNSUBSCRIBED:"token_unsubscribed",VIEWER_COUNT:"viewer_count",STREAM_GLOBAL_STATUS:"stream_global_status",CHAT_MESSAGE:"stream_chat_message",CHAT_SENT:"stream_chat_sent",CHAT_ERROR:"stream_chat_error",CHAT_STATUS:"stream_chat_status",CHAT_GLOBAL_STATUS:"stream_chat_global_status",CHAT_AUTHENTICATED:"stream_chat_authenticated",CHAT_AUTH_ERROR:"stream_chat_auth_error",REACTION:"stream_reaction",REACTION_ERROR:"stream_reaction_error",USER_TYPING:"user_typing",CHAT_PINNED:"stream_chat_pinned",CHAT_UNPINNED:"stream_chat_unpinned",COUNTDOWN_UPDATED:"stream_countdown_updated",LANGUAGE_UPDATED:"stream_language_updated"};class zl extends hs{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={},!e.url)throw new D("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 nc({maxAttempts:this.config.reconnectAttempts,baseDelayMs:this.config.reconnectDelay}),this.isSocketIOAvailable=this.checkSocketIOAvailability()}checkSocketIOAvailability(){try{return"function"==typeof a.io||(this.logger.warn('⚠️ Socket.IO client not available. Install "socket.io-client" package.'),!1)}catch(e){return this.logger.warn("⚠️ Socket.IO availability check failed:",A(e)),!1}}getRoomName(e){return`token:${rs(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 o=this.eventBufferTimeouts.get(r);o&&clearTimeout(o);const s=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,s)}processBufferedEvents(e,t){const n=rs(e),r=[{key:`${Wl.STREAM_STATUS}:${n}`,callback:t.onStreamStatus},{key:`${Wl.VIEWER_COUNT}:${n}`,callback:t.onViewerCount},{key:`${Wl.CHAT_MESSAGE}:${n}`,callback:t.onChatMessage},{key:`${Wl.CHAT_STATUS}:${n}`,callback:t.onChatStatus},{key:`${Wl.CHAT_PINNED}:${n}`,callback:t.onChatPinned},{key:`${Wl.CHAT_UNPINNED}:${n}`,callback:t.onChatUnpinned},{key:`${Wl.COUNTDOWN_UPDATED}:${n}`,callback:t.onCountdownUpdated},{key:`${Wl.LANGUAGE_UPDATED}:${n}`,callback:t.onLanguageUpdated}];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(Wl.STREAM_STATUS,e=>{this.logger.debug(`📡 [Stream Status] ${e.tokenName}: ${e.status}`),this.bufferEvent(Wl.STREAM_STATUS,e.tokenName,e);const t=this.roomCallbacks.get(rs(e.tokenName));t?.onStreamStatus&&t.onStreamStatus(e),this.globalCallbacks.onStreamStatus&&this.globalCallbacks.onStreamStatus(e)}),this.socket.on(Wl.STREAM_SUBSCRIBED,e=>{this.logger.debug(`📡 [Subscribed] ${e.tokenName}`);const t=rs(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(Wl.STREAM_UNSUBSCRIBED,e=>{const t=e.room.replace("token:","");this.logger.debug(`📡 [Unsubscribed] ${t}`);const n=this.roomCallbacks.get(rs(t));n?.onStreamUnsubscribed&&n.onStreamUnsubscribed(e)}),this.socket.on(Wl.VIEWER_COUNT,e=>{this.logger.debug(`📡 [Viewer Count] ${e.tokenName}: ${e.viewerCount}`),this.bufferEvent(Wl.VIEWER_COUNT,e.tokenName,e);const t=this.roomCallbacks.get(rs(e.tokenName));t?.onViewerCount&&t.onViewerCount(e),this.globalCallbacks.onViewerCount&&this.globalCallbacks.onViewerCount(e)}),this.socket.on(Wl.STREAM_GLOBAL_STATUS,e=>{this.logger.debug(`📡 [Global Stream Status] enabled: ${e.enabled}`),this.globalCallbacks.onStreamGlobalStatus&&this.globalCallbacks.onStreamGlobalStatus(e)}),this.socket.on(Wl.CHAT_MESSAGE,e=>{this.logger.debug(`📡 [Chat Message] ${e.tokenName}: ${e.message.content.slice(0,50)}...`),this.bufferEvent(Wl.CHAT_MESSAGE,e.tokenName,e);const t=this.roomCallbacks.get(rs(e.tokenName));t?.onChatMessage&&t.onChatMessage(e),this.globalCallbacks.onChatMessage&&this.globalCallbacks.onChatMessage(e)}),this.socket.on(Wl.CHAT_SENT,e=>{this.logger.debug(`📡 [Chat Sent] ${e.tokenName}: ${e.messageId}`);const t=this.roomCallbacks.get(rs(e.tokenName));t?.onChatSent&&t.onChatSent(e)}),this.socket.on(Wl.CHAT_ERROR,e=>{this.logger.error(`📡 [Chat Error] ${e.tokenName}: ${e.message}`);const t=this.roomCallbacks.get(rs(e.tokenName));t?.onChatError&&t.onChatError(e),this.globalCallbacks.onChatError&&this.globalCallbacks.onChatError(e)}),this.socket.on(Wl.CHAT_STATUS,e=>{this.logger.debug(`📡 [Chat Status] ${e.tokenName}: ${e.enabled}`),this.bufferEvent(Wl.CHAT_STATUS,e.tokenName,e);const t=this.roomCallbacks.get(rs(e.tokenName));t?.onChatStatus&&t.onChatStatus(e),this.globalCallbacks.onChatStatus&&this.globalCallbacks.onChatStatus(e)}),this.socket.on(Wl.CHAT_GLOBAL_STATUS,e=>{this.logger.debug(`📡 [Global Chat Status] enabled: ${e.enabled}`),this.globalCallbacks.onChatGlobalStatus&&this.globalCallbacks.onChatGlobalStatus(e)}),this.socket.on(Wl.CHAT_AUTHENTICATED,e=>{this.logger.debug(`📡 [Authenticated] ${e.address}`),this.isAuthenticated=!0,this.globalCallbacks.onChatAuthenticated&&this.globalCallbacks.onChatAuthenticated(e)}),this.socket.on(Wl.CHAT_AUTH_ERROR,e=>{this.logger.error(`📡 [Auth Error] ${e.message}`),this.isAuthenticated=!1,this.globalCallbacks.onChatAuthError&&this.globalCallbacks.onChatAuthError(e)}),this.socket.on(Wl.REACTION,e=>{this.logger.debug(`📡 [Reaction] ${e.tokenName}: ${e.emoji}`);const t=this.roomCallbacks.get(rs(e.tokenName));t?.onReaction&&t.onReaction(e),this.globalCallbacks.onReaction&&this.globalCallbacks.onReaction(e)}),this.socket.on(Wl.REACTION_ERROR,e=>{this.logger.error(`📡 [Reaction Error] ${e.tokenName}: ${e.message}`);const t=this.roomCallbacks.get(rs(e.tokenName));t?.onReactionError&&t.onReactionError(e),this.globalCallbacks.onReactionError&&this.globalCallbacks.onReactionError(e)}),this.socket.on(Wl.USER_TYPING,e=>{const t=e.typingUsers.length;this.logger.debug(`📡 [Typing] ${e.tokenName}: ${t} user(s) typing`);const n=this.roomCallbacks.get(rs(e.tokenName));n?.onTypingIndicator&&n.onTypingIndicator(e),this.globalCallbacks.onTypingIndicator&&this.globalCallbacks.onTypingIndicator(e)}),this.socket.on(Wl.CHAT_PINNED,e=>{this.logger.debug(`📡 [Chat Pinned] ${e.tokenName}: ${e.pinnedMessage.messageId}`),this.bufferEvent(Wl.CHAT_PINNED,e.tokenName,e);const t=this.roomCallbacks.get(rs(e.tokenName));t?.onChatPinned&&t.onChatPinned(e),this.globalCallbacks.onChatPinned&&this.globalCallbacks.onChatPinned(e)}),this.socket.on(Wl.CHAT_UNPINNED,e=>{this.logger.debug(`📡 [Chat Unpinned] ${e.tokenName}: ${e.unpinnedMessageId}`),this.bufferEvent(Wl.CHAT_UNPINNED,e.tokenName,e);const t=this.roomCallbacks.get(rs(e.tokenName));t?.onChatUnpinned&&t.onChatUnpinned(e),this.globalCallbacks.onChatUnpinned&&this.globalCallbacks.onChatUnpinned(e)}),this.socket.on(Wl.COUNTDOWN_UPDATED,e=>{const t=e.nextLiveStreamAt??"cleared";this.logger.debug(`📡 [Countdown Updated] ${e.tokenName}: ${t}`),this.bufferEvent(Wl.COUNTDOWN_UPDATED,e.tokenName,e);const n=this.roomCallbacks.get(rs(e.tokenName));n?.onCountdownUpdated&&n.onCountdownUpdated(e),this.globalCallbacks.onCountdownUpdated&&this.globalCallbacks.onCountdownUpdated(e)}),this.socket.on(Wl.LANGUAGE_UPDATED,e=>{this.logger.debug(`📡 [Language Updated] ${e.tokenName}: ${e.language}`),this.bufferEvent(Wl.LANGUAGE_UPDATED,e.tokenName,e);const t=this.roomCallbacks.get(rs(e.tokenName));t?.onLanguageUpdated&&t.onLanguageUpdated(e),this.globalCallbacks.onLanguageUpdated&&this.globalCallbacks.onLanguageUpdated(e)}))}async 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(Wl.SUBSCRIBE,{tokenName:t})}catch(e){this.logger.error(`Failed to re-subscribe to ${t}:`,e)}}async connect(){return new Promise((e,t)=>{wr(async()=>{if(!this.isSocketIOAvailable)throw new D('Socket.IO not available. Install "socket.io-client" package.');this.logger.debug(`🔌 Connecting to Stream WebSocket: ${this.config.url}`);const n={};this.config.authToken&&(n.token=this.config.authToken),this.socket=a.io(this.config.url,{transports:["websocket"],reconnection:!0,reconnectionAttempts:this.config.reconnectAttempts,reconnectionDelay:this.config.reconnectDelay,auth:n}),this.socket.on("connect",()=>{this.logger.debug(`✅ Stream WebSocket connected: ${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")})},"Stream WebSocket connection setup",this.logger,e=>{throw t(e),e})})}authenticate(e){if(!this.socket?.connected)throw new B("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(!e)throw W("token","Authentication token");this.logger.debug("📡 Authenticating with stream server"),this.socket.emit(Wl.AUTHENTICATE,{token:e}),this.config.authToken=e}async subscribeToStream(e,t={}){if(!e)throw W("tokenName","Token name");if(!this.socket?.connected)throw new B("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");const n=rs(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 o=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:o}),this.roomCallbacks.set(n,t),this.subscribedRooms.set(n,{tokenName:n,subscribedAt:Date.now()}),this.logger.debug(`📡 Subscribing to stream: ${n}`),this.socket.emit(Wl.SUBSCRIBE,{tokenName:n})})}unsubscribeFromStream(e){const t=rs(e);if(!this.subscribedRooms.has(t))return void this.logger.debug(`📡 Not subscribed to ${t}, skipping unsubscribe`);this.logger.debug(`📡 Unsubscribing from stream: ${t}`),this.socket?.connected&&this.socket.emit(Wl.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 W("tokenName","Token name");if(!t)throw W("content","Message content");if(!this.socket?.connected)throw new B("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(!this.isAuthenticated)throw new B("Not authenticated. Call authenticate() first.","auth","NOT_AUTHENTICATED");const n=rs(e);this.logger.debug(`📡 Sending chat message to ${n}: ${t.slice(0,30)}...`),this.socket.emit(Wl.SEND_CHAT,{tokenName:n,content:t})}sendReaction(e,t,n=0){if(!e)throw W("tokenName","Token name");if(!t)throw W("emoji");if(!this.socket?.connected)throw new B("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(!this.isAuthenticated)throw new B("Not authenticated. Call authenticate() first.","auth","NOT_AUTHENTICATED");const r=rs(e);this.logger.debug(`📡 Sending reaction to ${r}: ${t}`),this.socket.emit(Wl.SEND_REACTION,{tokenName:r,emoji:t,streamTime:n})}sendTypingStart(e){if(!e)throw W("tokenName","Token name");if(!this.socket?.connected)throw new B("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(!this.isAuthenticated)throw new B("Not authenticated. Call authenticate() first.","auth","NOT_AUTHENTICATED");const t=rs(e);this.logger.debug(`📡 Sending typing_start to ${t}`),this.socket.emit(Wl.TYPING_START,{tokenName:t})}sendTypingStop(e){if(!e)throw W("tokenName","Token name");if(!this.socket?.connected)throw new B("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(!this.isAuthenticated)throw new B("Not authenticated. Call authenticate() first.","auth","NOT_AUTHENTICATED");const t=rs(e);this.logger.debug(`📡 Sending typing_stop to ${t}`),this.socket.emit(Wl.TYPING_STOP,{tokenName:t})}setGlobalCallbacks(e){this.globalCallbacks=e}getSubscribedTokens(){return Array.from(this.subscribedRooms.keys())}isConnected(){return this.socket?.connected??!1}isAuthenticatedForChat(){return this.isAuthenticated}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.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")}}}class Hl extends hs{constructor(e=!1){super(e),this.socket=null,this.isConnected=!1,this.eventRegistry=this.createEmptyRegistry()}setSocket(e){this.socket=e,this.isConnected=!0,this.logger.debug("📡 [Events] Socket attached to StreamingEventService")}clearSocket(){this.socket=null,this.isConnected=!1,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,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)}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 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 jl={VIEWERS:"viewers",CHAT_PARTICIPANTS:"chat_participants"},Vl=et(jl),Xl=ot([{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}]),Ql=ot([{field:"userAddress",type:"string"},{field:"isPermanent",type:"boolean"}]),Jl=ot([{field:"userAddress",type:"string"}]),Zl=ot([{field:"tokenName",type:"string"},{field:"action",type:"string",validator:e=>"chat"===e||"comment"===e||"reaction"===e}]);function Yl(e){return null==e||""===e||"string"==typeof e&&(!at(e)&&e.length<=ve.BAN_REASON.MAX_LENGTH)}function eu(e){return!!Ze(e)||"number"==typeof e&&(e>=Ae&&e<=Te)}class tu extends vl{constructor(e,t,n,r=!1){super(e,t,n,r)}async createBan(e){!function(e){if(rt(e.tokenName,"tokenName",he),!Qe(e.userAddress))throw W("userAddress");if(!Yl(e.reason))throw new B(`reason must be at most ${ve.BAN_REASON.MAX_LENGTH} characters`,"reason","TOO_LONG");if(!eu(e.durationSeconds))throw new B(`durationSeconds must be between ${Ae} and ${Te} seconds`,"durationSeconds","OUT_OF_RANGE")}(e);const t=this.buildEndpoint(En,{tokenName:e.tokenName}),n={userAddress:e.userAddress};void 0!==e.reason&&(n.reason=e.reason),void 0!==e.durationSeconds&&(n.durationSeconds=e.durationSeconds);const r=await this.http.post(t,n,this.getDualAuthHeaders());return{ban:this.extractData(r),tokenName:rs(e.tokenName)}}async removeBan(e){!function(e){if(rt(e.tokenName,"tokenName",he),!Qe(e.userAddress))throw W("userAddress")}(e);const t=this.buildEndpoint(Cn,{tokenName:e.tokenName,userAddress:e.userAddress}),n=await this.http.delete(t,this.getDualAuthHeaders()),r=this.extractData(n);return{removed:r.removed,tokenName:rs(e.tokenName),userAddress:r.userAddress}}async listBans(e){!function(e){rt(e.tokenName,"tokenName",he),Ye(e.page,e.limit,fe)}(e);const t=this.buildEndpoint(In,{tokenName:e.tokenName}),n=this.buildPaginationParams(e,fe);this.addOptionalFilterParams(n,e,["search","name","userAddress"]);const r=await this.http.get(t,n,this.getDualAuthHeaders()),i=this.extractData(r);return{items:i.bans,meta:i.meta}}async getBanStatus(e){!function(e){if(rt(e.tokenName,"tokenName",he),!Qe(e.userAddress))throw W("userAddress")}(e);const t=this.buildEndpoint(xn,{tokenName:e.tokenName,userAddress:e.userAddress}),n=await this.http.get(t,{},this.getDualAuthHeaders()),r=this.extractData(n);return{banned:null!==r,...null!==r&&{ban:r},tokenName:rs(e.tokenName),userAddress:e.userAddress.toLowerCase()}}async getActiveUsers(e){!function(e){if(rt(e.tokenName,"tokenName",he),void 0!==e.type&&!Vl(e.type))throw new B(`type must be one of: ${Object.values(jl).join(", ")}`,"type",_.INVALID_VALUE)}(e);const t=this.buildEndpoint(Nn,{tokenName:e.tokenName}),n={};this.addOptionalFilterParams(n,e,["type","search","name","userAddress"]);const r=await this.http.get(t,n,this.getDualAuthHeaders());return this.extractData(r)}}function nu(e){return null==e||""===e||"string"==typeof e&&(!at(e)&&e.length<=ve.BAN_REASON.MAX_LENGTH)}function ru(e){if(rt(e.tokenName,"tokenName",he),!nu(e.reason))throw new B(`reason must be at most ${ve.BAN_REASON.MAX_LENGTH} characters`,"reason","TOO_LONG")}function iu(e){rt(e.tokenName,"tokenName",he)}function ou(e){Ye(e.page,e.limit,fe)}function su(e){rt(e.tokenName,"tokenName",he)}class au extends vl{constructor(e,t,n,r=!1){super(e,t,n,r)}async banToken(e){ru(e);const t=Qn,n={tokenName:rs(e.tokenName)};if(void 0!==e.reason)try{le(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:rs(e.tokenName)}}async unbanToken(e){iu(e);const t=this.buildEndpoint(Yn,{tokenName:e.tokenName}),n=await this.http.delete(t,this.getDualAuthHeaders());return{removed:this.extractData(n).removed,tokenName:rs(e.tokenName)}}async listTokenBans(e={}){ou(e);const t=Jn,n=this.buildPaginationParams(e,fe);this.addOptionalFilterParams(n,e,["search"]);const r=await this.http.get(t,n,this.getDualAuthHeaders()),i=this.extractData(r);return{items:i.bans,meta:i.meta}}async getTokenBan(e){su(e);const t=this.buildEndpoint(Zn,{tokenName:e.tokenName}),n=await this.http.get(t,{},this.getDualAuthHeaders()),r=this.extractData(n);return{banned:null!==r,...null!==r&&{ban:r},tokenName:rs(e.tokenName)}}async isTokenBanned(e){return this.getTokenBan(e)}}const cu={MODERATOR:"MODERATOR",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MANAGER:"MANAGER",OWNER:"OWNER"},lu=tt(cu);function uu(e){return lu.includes(e)}function du(e){const t=[];e.role?uu(e.role)||t.push(`Invalid role. Must be one of: ${lu.join(", ")}`):t.push(W("role").message);const n=t.length;if(N(t,()=>{ss(e.description,"description",255)}),t.length>n&&(t[n]="Description must be 255 characters or less"),void 0!==e.tokenNames){const n=t.length;N(t,()=>{if(!Array.isArray(e.tokenNames))throw Y("tokenNames","an array",e.tokenNames);if(!e.tokenNames.every(e=>"string"==typeof e))throw Y("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){const n=t.length;N(t,()=>{cs(e.expiresAt,"expiresAt")}),t.length>n&&(t[n]="expiresAt must be a valid ISO 8601 date string")}return t}function hu(e){const t=[];["role","description","delegateAllTokens","tokenNames","expiresAt"].some(t=>void 0!==e[t])||t.push("At least one field must be provided for update"),void 0===e.role||uu(e.role)||t.push(`Invalid role. Must be one of: ${lu.join(", ")}`);const n=t.length;if(N(t,()=>{ss(e.description,"description",255)}),t.length>n&&(t[n]="Description must be 255 characters or less"),void 0!==e.tokenNames){const n=t.length;N(t,()=>{if(!Array.isArray(e.tokenNames))throw Y("tokenNames","an array",e.tokenNames);if(!e.tokenNames.every(e=>"string"==typeof e))throw Y("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&&null!==e.expiresAt){const n=t.length;N(t,()=>{cs(e.expiresAt,"expiresAt")}),t.length>n&&(t[n]="expiresAt must be a valid ISO 8601 date string")}return t}function gu(e){Ye(e.page,e.limit,fe)}const pu={[cu.MODERATOR]:1,[cu.TECHNICAL_PRODUCER]:1,[cu.MANAGER]:2,[cu.OWNER]:3};class fu extends ds{constructor(e,t,n=!1){super(e,n,t)}extractData(e){const t={error:"error"in e?e.error:!e.success,data:e.data};return void 0!==e.message&&(t.message=e.message),fr(t,"API key operation failed",!0),e.data}validateApiKeyId(e){this.validatePositiveInteger(e,"id","API key ID")}async create(e){const t=du(e);if(t.length>0)throw new B(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);const r=await this.http.post(_n.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={}){gu(e),this.logger.debug("Listing API keys",e);const t=void 0!==e.limit?Vo(e.limit,1,fe):void 0,n={};void 0!==e.page&&(n.page=e.page),void 0!==t&&(n.limit=t);const r={...Ss(n,fe)},i=await this.http.get(_n.LIST,r,this.getJwtHeaders()),o=this.extractData(i);return this.logger.debug("Listed API keys",{count:o.apiKeys.length,total:o.meta.total}),o}async findOne(e){this.validateApiKeyId(e),this.logger.debug("Getting API key",{id:e});const t=_n.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=hu(t);if(n.length>0)throw new B(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);const i=_n.UPDATE.replace(":id",String(e)),o=await this.http.patch(i,r,this.getJwtHeaders()),s=this.extractData(o);return this.logger.debug("Updated API key",{id:s.id,keyPrefix:s.keyPrefix}),s}async revoke(e){this.validateApiKeyId(e),this.logger.debug("Revoking API key",{id:e});const t=_n.REVOKE.replace(":id",String(e));await this.http.delete(t,this.getJwtHeaders()),this.logger.debug("API key revoked",{id:e})}getRoles(){return[...lu]}}const mu={MODERATOR:"MODERATOR",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MANAGER:"MANAGER"},yu=tt(mu),wu={TOKEN:"TOKEN",ALL_OWNER_TOKENS:"ALL_OWNER_TOKENS"},ku=tt(wu),bu={PENDING:"PENDING",CLAIMED:"CLAIMED",REVOKED:"REVOKED",EXPIRED:"EXPIRED"},vu=tt(bu);function Su(e){return yu.includes(e)}function Au(e){return vu.includes(e)}function Tu(e){return Ie.PATTERN.test(e)}const Eu=ot([{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"}]),Iu=ot([{field:"tokenName",type:"string"},{field:"tokenSymbol",type:"string"},{field:"role",type:"string"},{field:"inviteScope",type:"string"},{field:"creatorAddress",type:"string"},{field:"claimedAt",type:"string"}]),xu=ot([{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:"object"}]);function Cu(e){return ku.includes(e)}class Nu extends vl{constructor(e,t,n,r=!1){super(e,t,n,r)}validateRole(e){if(!Qe(e))throw W("role","Role");if(!Su(e))throw z("role",`one of: ${yu.join(", ")}`,"Role")}validateInviteCodeFormat(e){if(!Qe(e))throw W("inviteCode","Invite code");if(!Tu(e))throw z("inviteCode","valid invite code format","Invite code")}validateInviteScope(e){if(void 0!==e&&!Cu(e))throw new B(`Invalid invite scope. Must be one of: ${ku.join(", ")}`,"inviteScope","INVALID_VALUE")}async createInvite(e){this.validateInviteScope(e.inviteScope);const t=e.inviteScope??wu.TOKEN;if(t===wu.TOKEN){if(!e.tokenName)throw new B("Token name is required for TOKEN scope invites","tokenName","REQUIRED");this.validateTokenName(e.tokenName,he)}else if(t===wu.ALL_OWNER_TOKENS&&e.tokenName)throw new B("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",ve.DESCRIPTION.MAX_LENGTH),this.validateOptionalDate(e.expiresAt,"expiresAt","Expiration date");const n=Bn,r={inviteScope:t,role:e.role};t===wu.TOKEN&&e.tokenName&&(r.tokenName=rs(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.getJwtHeaders());return{invite:this.extractData(i)}}async listInvites(e){e.tokenName&&this.validateTokenName(e.tokenName,he),this.validateStatusFilter(e.status,bu);const t=Rn,n={...this.buildPaginationParams(e,ye.MAX_LIMIT)};e.tokenName&&(n.tokenName=rs(e.tokenName)),e.status&&(n.status=e.status);const r=await this.http.get(t,n,this.getJwtHeaders()),i=this.extractData(r);return{items:i.invites,meta:i.meta}}async revokeInvite(e){this.validatePositiveInteger(e,"inviteId","Invite ID");const t=this.buildEndpoint(Mn,{id:String(e)});fr(await this.http.delete(t,this.getJwtHeaders()),"Failed to revoke invite")}async updateInviteRole(e){this.validatePositiveInteger(e.inviteId,"inviteId","Invite ID"),this.validateRole(e.role);const t=this.buildEndpoint(Ln,{id:String(e.inviteId)}),n={role:e.role},r=await this.http.patch(t,n,this.getJwtHeaders());return{invite:this.extractData(r)}}async claimInvite(e){this.validateInviteCodeFormat(e.inviteCode);const t=Pn,n={inviteCode:e.inviteCode},r=await this.http.post(t,n,this.getJwtHeaders()),i=this.extractData(r);return"tokenName"in i&&void 0!==i.tokenName?{token:i}:{blanketAccess:i}}async getModeratedTokens(e){const t=Dn,n=this.buildPaginationParams(e??{},ye.MAX_LIMIT),r=await this.http.get(t,n,this.getJwtHeaders()),i=this.extractData(r);return{items:i.tokens,meta:i.meta}}async getInviteByCode(e){this.validateInviteCodeFormat(e);const t=this.buildEndpoint(On,{code:e}),n=await this.http.get(t,{});return this.extractData(n)}}var _u,Bu,Pu,Du;exports.ContentType=void 0,(_u=exports.ContentType||(exports.ContentType={})).CHAT_MESSAGE="CHAT_MESSAGE",_u.COMMENT="COMMENT",_u.STREAM="STREAM",exports.FlagReason=void 0,(Bu=exports.FlagReason||(exports.FlagReason={})).INAPPROPRIATE_CONTENT="INAPPROPRIATE_CONTENT",Bu.SPAM="SPAM",Bu.HARASSMENT="HARASSMENT",Bu.SCAM="SCAM",Bu.OTHER="OTHER",exports.FlagStatus=void 0,(Pu=exports.FlagStatus||(exports.FlagStatus={})).PENDING="PENDING",Pu.DISMISSED="DISMISSED",Pu.ACTIONED="ACTIONED",exports.FlagAction=void 0,(Du=exports.FlagAction||(exports.FlagAction={})).DELETE_CONTENT="DELETE_CONTENT",Du.BAN_USER="BAN_USER",Du.DELETE_AND_BAN="DELETE_AND_BAN";const Ru={[exports.FlagReason.INAPPROPRIATE_CONTENT]:"Inappropriate Content",[exports.FlagReason.SPAM]:"Spam",[exports.FlagReason.HARASSMENT]:"Harassment",[exports.FlagReason.SCAM]:"Scam",[exports.FlagReason.OTHER]:"Other"},Mu={[exports.FlagStatus.PENDING]:"Pending",[exports.FlagStatus.DISMISSED]:"Dismissed",[exports.FlagStatus.ACTIONED]:"Actioned"},Lu={[exports.FlagAction.DELETE_CONTENT]:"Delete Content",[exports.FlagAction.BAN_USER]:"Ban User",[exports.FlagAction.DELETE_AND_BAN]:"Delete & Ban"},Ou={[exports.ContentType.CHAT_MESSAGE]:"Chat Message",[exports.ContentType.COMMENT]:"Comment",[exports.ContentType.STREAM]:"Stream"},Fu=et(exports.ContentType),Uu=et(exports.FlagReason),$u=et(exports.FlagStatus),qu=et(exports.FlagAction),Ku=ot([{field:"id",type:"number"},{field:"tokenName",type:"string"},{field:"contentType",type:"string",validator:Fu},{field:"contentId",type:"string"},{field:"reporterAddress",type:"string"},{field:"reportedUserAddress",type:"string"},{field:"status",type:"string",validator:$u}]),Gu={TOKEN_NAME:ge,CONTENT_ID:ve.CONTENT_ID,DETAILS:ve.FLAG_DETAILS,PAGINATION:{MAX_LIMIT:fe}};function Wu(e,t="tokenName"){rt(e,t,Gu.TOKEN_NAME)}class zu extends vl{constructor(e,t,n,r=!1){super(e,t,n,r)}async createFlag(e){!function(e){if(Wu(e.tokenName),!e.contentType)throw W("contentType","Content type");if(!Fu(e.contentType))throw z("contentType",`one of: ${Object.values(exports.ContentType).join(", ")}`,"Content type");if(!Qe(e.contentId))throw W("contentId","Content ID");if(e.contentId.length>Gu.CONTENT_ID.MAX_LENGTH)throw Z("contentId",Gu.CONTENT_ID.MAX_LENGTH,e.contentId.length,"Content ID");if(!Qe(e.reportedUserAddress))throw W("reportedUserAddress","Reported user address");if(yt(e.reportedUserAddress,"reportedUserAddress"),e.contentType===exports.ContentType.STREAM&&!e.reason)throw W("reason","Reason");if(void 0!==e.reason&&!Uu(e.reason))throw z("reason",`one of: ${Object.values(exports.FlagReason).join(", ")}`,"Reason");if(void 0!==e.details&&!Qe(e.details))throw Y("details","a non-empty string",typeof e.details);if(void 0!==e.details&&e.details.length>Gu.DETAILS.MAX_LENGTH)throw Z("details",Gu.DETAILS.MAX_LENGTH,e.details.length)}(e);const t={tokenName:e.tokenName,contentType:e.contentType,contentId:e.contentId,reportedUserAddress:e.reportedUserAddress};e.reason&&(t.reason=e.reason),e.details&&(t.details=e.details);const n=await this.http.post(Fn.CREATE,t,this.getJwtHeaders());return{flag:this.extractData(n).flag}}async listFlags(e){!function(e){if(Wu(e.tokenName),void 0!==e.contentType&&!Fu(e.contentType))throw z("contentType",`one of: ${Object.values(exports.ContentType).join(", ")}`,"Content type");if(void 0!==e.status&&!$u(e.status))throw z("status",`one of: ${Object.values(exports.FlagStatus).join(", ")}`);if(void 0!==e.reason&&!Uu(e.reason))throw z("reason",`one of: ${Object.values(exports.FlagReason).join(", ")}`);if(void 0!==e.reporterAddress&&!Qe(e.reporterAddress))throw Y("reporterAddress","a non-empty string",typeof e.reporterAddress);if(void 0!==e.reporterAddress&&yt(e.reporterAddress,"reporterAddress"),void 0!==e.reportedUserAddress&&!Qe(e.reportedUserAddress))throw Y("reportedUserAddress","a non-empty string",typeof e.reportedUserAddress);void 0!==e.reportedUserAddress&&yt(e.reportedUserAddress,"reportedUserAddress"),Ye(e.page,e.limit,Gu.PAGINATION.MAX_LIMIT)}(e);const t={};void 0!==e.page&&(t.page=e.page),void 0!==e.limit&&(t.limit=e.limit);const n=Ss(t,fe);Ts(n,e,["contentType","status","reason","reporterAddress","reportedUserAddress"]);const r=Fn.LIST.replace(":tokenName",encodeURIComponent(e.tokenName)),i=await this.http.get(r,n,this.getDualAuthHeaders()),o=this.extractData(i);return{items:o.flags,meta:o.meta}}async listGlobalFlags(e={}){!function(e){if(void 0!==e.tokenName&&Wu(e.tokenName),void 0!==e.contentType&&!Fu(e.contentType))throw z("contentType",`one of: ${Object.values(exports.ContentType).join(", ")}`,"Content type");if(void 0!==e.status&&!$u(e.status))throw z("status",`one of: ${Object.values(exports.FlagStatus).join(", ")}`);if(void 0!==e.reason&&!Uu(e.reason))throw z("reason",`one of: ${Object.values(exports.FlagReason).join(", ")}`);if(void 0!==e.reporterAddress&&!Qe(e.reporterAddress))throw Y("reporterAddress","a non-empty string",typeof e.reporterAddress);if(void 0!==e.reporterAddress&&yt(e.reporterAddress,"reporterAddress"),void 0!==e.reportedUserAddress&&!Qe(e.reportedUserAddress))throw Y("reportedUserAddress","a non-empty string",typeof e.reportedUserAddress);void 0!==e.reportedUserAddress&&yt(e.reportedUserAddress,"reportedUserAddress"),Ye(e.page,e.limit,Gu.PAGINATION.MAX_LIMIT)}(e);const t={};void 0!==e.page&&(t.page=e.page),void 0!==e.limit&&(t.limit=e.limit);const n=Ss(t,fe);Ts(n,e,["tokenName","contentType","status","reason","reporterAddress","reportedUserAddress"]);const r=await this.http.get(Fn.LIST_GLOBAL,n,this.getDualAuthHeaders()),i=this.extractData(r);return{items:i.flags,meta:i.meta}}async dismissFlag(e){!function(e){if(void 0===e.flagId||null===e.flagId)throw W("flagId","Flag ID");try{ae(e.flagId,"flagId")}catch{throw z("flagId","a positive integer","Flag ID")}}(e);const t=Fn.DISMISS.replace(":id",e.flagId.toString()),n=await this.http.post(t,{},this.getDualAuthHeaders());return{flag:this.extractData(n).flag}}async actionFlag(e){!function(e){if(void 0===e.flagId||null===e.flagId)throw W("flagId","Flag ID");try{ae(e.flagId,"flagId")}catch{throw z("flagId","a positive integer","Flag ID")}if(!e.action)throw W("action","Action");if(!qu(e.action))throw z("action",`one of: ${Object.values(exports.FlagAction).join(", ")}`,"Action")}(e);const t=Fn.ACTION.replace(":id",e.flagId.toString()),n=await this.http.post(t,{action:e.action},this.getDualAuthHeaders());return{flag:this.extractData(n).flag}}}const Hu={PENDING:"PENDING",CLAIMED:"CLAIMED",REVOKED:"REVOKED",EXPIRED:"EXPIRED"},ju={ACTIVE:"ACTIVE",REVOKED:"REVOKED"},Vu=et(Hu),Xu=et(ju);function Qu(e){try{ss(e.description,"description",255)}catch(e){if(e instanceof B){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(!Qe(e.expiresAt))throw new Error("expiresAt must be a non-empty string");try{cs(e.expiresAt,"expiresAt")}catch(e){if(e instanceof B)throw new Error("expiresAt must be a valid ISO 8601 date string");throw e}if(je(e.expiresAt)){if(He(e.expiresAt)<=new Date)throw new Error("expiresAt must be in the future")}}}function Ju(e){if(void 0!==e.status&&!Vu(e.status))throw ne("status",e.status,Object.values(Hu),"status");Ye(e.page,e.limit,50)}function Zu(e){if(void 0!==e.status&&!Xu(e.status))throw ne("status",e.status,Object.values(ju),"status");Ye(e.page,e.limit,50)}function Yu(e){if(!Qe(e))throw new Error("Invite code must be a non-empty string");se(e,100,"code")}function ed(e){if(!Qe(e))throw new Error("Address must be a non-empty string");try{yt(e,"address")}catch{throw new Error("Invalid wallet address format. Must be eth|..., 0x..., or client|... format")}}function td(e){try{as(e,"id")}catch(e){if(e instanceof B)throw new Error("Invite ID must be a positive integer");throw e}}function nd(e){if(!e||"object"!=typeof e)throw new B("Options are required");if(void 0===e.page&&void 0===e.limit||Ye(e.page,e.limit,100),void 0!==e.search){if("string"!=typeof e.search)throw new B("Search must be a string");if(0===e.search.length)throw new B("Search query cannot be empty string")}if(void 0!==e.sortBy){if("string"!=typeof e.sortBy)throw new B("Sort field must be a string");if(0===e.sortBy.length)throw new B("Sort field cannot be empty string")}if(void 0!==e.sortOrder&&"asc"!==e.sortOrder&&"desc"!==e.sortOrder)throw new B('Sort order must be "asc" or "desc"')}class rd extends vl{constructor(e,t,n,r=!1){super(e,t,n,r)}validateInviteCodeFormat(e){if(!Qe(e))throw W("inviteCode","Invite code");Yu(e)}validateWalletAddressFormat(e){if(!Qe(e))throw W("address","Address");ed(e)}async createInvite(e={}){Qu(e),this.validateOptionalString(e.description,"description","Description",ve.DESCRIPTION.MAX_LENGTH),this.validateOptionalDate(e.expiresAt,"expiresAt","Expiration date");const t=Un,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={}){Ju(e),this.validateStatusFilter(e.status,Hu);const t=$n,n={...this.buildPaginationParams(e,ye.MAX_LIMIT)};e.status&&(n.status=e.status);const r=await this.http.get(t,n,this.getDualAuthHeaders()),i=this.extractData(r);return{items:i.invites,meta:i.meta}}async getInviteByCode(e){this.validateInviteCodeFormat(e);const t=this.buildEndpoint(qn,{code:e}),n=await this.http.get(t,{});return this.extractData(n)}async revokeInvite(e){td(e);const t=this.buildEndpoint(Gn,{id:String(e)});fr(await this.http.delete(t,this.getDualAuthHeaders()),"Failed to revoke invite")}async claimInvite(e){this.validateInviteCodeFormat(e);const t=Kn,n={inviteCode:e},r=await this.http.post(t,n,this.getJwtHeaders());return{invite:this.extractData(r)}}async listOverseers(e={}){Zu(e),this.validateStatusFilter(e.status,ju);const t=Wn,n={...this.buildPaginationParams(e,ye.MAX_LIMIT)};e.status&&(n.status=e.status);const r=await this.http.get(t,n,this.getDualAuthHeaders()),i=this.extractData(r);return{items:i.overseers,meta:i.meta}}async revokeOverseer(e){this.validateWalletAddressFormat(e);const t=this.buildEndpoint(zn,{address:e});fr(await this.http.delete(t,this.getDualAuthHeaders()),"Failed to revoke overseer")}async getMyStatus(){const e=Hn,t=await this.http.get(e,{},this.getJwtHeaders());return this.extractData(t)}async getSummary(){const e=jn,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async listOverseerUsers(e){const t=e||{};Object.keys(t).length>0&&nd(t);const n=Vn,r={};void 0!==t.page&&(r.page=t.page),void 0!==t.limit&&(r.limit=t.limit),t.search&&(r.search=t.search),t.sortBy&&(r.sortBy=t.sortBy),t.sortOrder&&(r.sortOrder=t.sortOrder);const i=await this.http.get(n,r,this.getDualAuthHeaders()),o=this.extractData(i);return{items:o.items,meta:o.meta}}async getOverseerUserSummary(e){if(!Qe(e))throw W("address","User address");ed(e);const t=this.buildEndpoint(Xn,{address:e}),n=await this.http.get(t,{},this.getDualAuthHeaders());return this.extractData(n)}}class id extends vl{constructor(e,t,n,r=!1){super(e,t,n,r)}async fetchComments(e){!function(e){rt(e.tokenName,"tokenName",ge),Ye(e.page,e.limit,fe)}(e);const t=rs(e.tokenName),n=void 0!==e.limit?Vo(e.limit,1,fe):void 0,r={};void 0!==e.page&&(r.page=e.page),void 0!==n&&(r.limit=n);const i={tokenName:t,...Ss(r,fe)},o=await this.http.get(er,i),s=this.extractData(o);return{items:(s.comments||[]).map(e=>{const t={id:e.id,messageId:e.messageId,content:e.content,userAddress:e.userAddress,poolId:e.poolId,createdAt:e.createdAt};if(e.user){const n={fullName:e.user.fullName};void 0!==e.user.profileImage&&(n.profileImage=e.user.profileImage),t.user=n}return e.reactions&&(t.reactions=e.reactions),e.holderTier&&(t.holderTier=e.holderTier),t}),meta:s.meta}}async postComment(e){!function(e){if(rt(e.tokenName,"tokenName",ge),!Qe(e.content))throw W("content");if(e.content.length>ve.COMMENT.MAX_LENGTH)throw new B(`content must be at most ${ve.COMMENT.MAX_LENGTH} characters`,"content",_.TOO_LONG)}(e);const t=tr,n={content:e.content.trim(),tokenName:rs(e.tokenName)},r=await this.http.post(t,n,this.getJwtHeaders()),i=this.extractData(r);return{comment:{id:i.id,messageId:i.messageId,content:i.content,userAddress:i.userAddress,poolId:i.poolId,createdAt:i.createdAt}}}async deleteComment(e){!function(e){if(void 0===e.commentId||null===e.commentId)throw W("commentId");as(e.commentId,"commentId")}(e);const t=this.buildEndpoint(nr,{commentId:String(e.commentId)});return await this.http.delete(t,void 0,this.getJwtHeaders()),{success:!0}}}const od=["heart","fire","laugh","wow","thumbs_up"];class sd extends vl{constructor(e,t,n,r=!1){super(e,t,n,r)}validateReactionTokenName(e){this.validateTokenName(e,ge)}validateMessageId(e){if(!Qe(e))throw W("messageId","Message ID");if(se(e,Se.CONTENT_REACTION.MAX_LENGTH,"messageId"),!Se.CONTENT_REACTION.PATTERN.test(e))throw z("messageId","msg-{timestamp}-{uuid} or chat-{timestamp}-{uuid} format","Message ID")}validateReactionType(e){if(!Qe(e))throw W("reactionType","Reaction type");if(!od.includes(e))throw z("reactionType",`one of: ${od.join(", ")}`,"Reaction type")}async addContentReaction(e){this.validateReactionTokenName(e.tokenName),this.validateMessageId(e.messageId),this.validateReactionType(e.reactionType);const t={tokenName:rs(e.tokenName),messageId:e.messageId,reactionType:e.reactionType},n=await this.http.post(rr,t,this.getDualAuthHeaders()),r=this.extractData(n),{created:i,...o}=r;return{data:o,created:i}}async removeContentReaction(e){this.validateReactionTokenName(e.tokenName),this.validateMessageId(e.messageId),this.validateReactionType(e.reactionType);const t=this.buildEndpoint(ir,{messageId:e.messageId,reactionType:e.reactionType}),n={tokenName:rs(e.tokenName)};return await this.http.delete(t,n,this.getDualAuthHeaders()),{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 ad extends vl{constructor(e,t,n,r=!1){super(e,t,n,r)}validateContent(e){if(!Qe(e))throw W("content","Comment content");if(0===e.trim().length)throw W("content","Comment content");se(e,ve.COMMENTS_V1.MAX_LENGTH,"content")}validateMessageId(e){if(!Qe(e))throw W("id","Message ID");if(e.length<10||e.length>64)throw z("id","valid message ID format","Message ID")}async getComments(e){if(!e.tokenName&&!e.userAddress)throw new B("At least one of tokenName or userAddress must be provided","filter","REQUIRED");e.tokenName&&this.validateTokenName(e.tokenName,ge);const t={};void 0!==e.page&&(t.page=e.page),void 0!==e.limit&&(t.limit=e.limit);const n={...Ss(t,ye.MAX_LIMIT)};e.tokenName&&(n.tokenName=rs(e.tokenName)),e.userAddress&&(n.userAddress=e.userAddress);const r=await this.http.get(ur,n),i=this.extractData(r);return{messages:i.messages,meta:i.meta}}async createComment(e){this.validateTokenName(e.tokenName,ge),this.validateContent(e.content);const t={tokenName:rs(e.tokenName),content:e.content.trim()},n=await this.http.post(dr,t,this.getJwtHeaders()),r=this.extractData(n);return{comment:{id:r.messageId,tokenName:r.pool?.tokenName??"",tokenImage:r.pool?.tokenImage??null,userAddress:r.userAddress,userProfile:r.user?{fullName:r.user.fullName,profileImage:r.user.profileImage}:null,content:r.content,createdAt:r.createdAt,updatedAt:r.updatedAt,deletedAt:r.deletedAt,flagCount:0,reactions:{}}}}async updateComment(e,t){this.validateMessageId(e),this.validateContent(t.content);const n=this.buildEndpointWithId(hr,e),r={content:t.content.trim()},i=await this.http.put(n,r,this.getJwtHeaders()),o=this.extractData(i);return{comment:{id:o.messageId,tokenName:o.pool?.tokenName??"",tokenImage:o.pool?.tokenImage??null,userAddress:o.userAddress,userProfile:o.user?{fullName:o.user.fullName,profileImage:o.user.profileImage}:null,content:o.content,createdAt:o.createdAt,updatedAt:o.updatedAt,deletedAt:o.deletedAt,flagCount:0,reactions:{}}}}async deleteComment(e){this.validateMessageId(e);const t=this.buildEndpointWithId(gr,e);return await this.http.delete(t,void 0,this.getDualAuthHeaders()),{success:!0}}}function cd(e){if(!e.tokenName&&!e.userAddress)throw new B("At least one of tokenName or userAddress is required","options",_.REQUIRED);if(void 0!==e.tokenName){if(!Qe(e.tokenName))throw Y("tokenName","string");if(e.tokenName.length>pe.MAX_LENGTH)throw new B(`tokenName must be at most ${pe.MAX_LENGTH} characters`,"tokenName",_.TOO_LONG)}if(void 0!==e.userAddress){if(!Qe(e.userAddress))throw Y("userAddress","string");if(e.userAddress.length>be.MAX_LENGTH)throw new B(`userAddress must be at most ${be.MAX_LENGTH} characters`,"userAddress",_.TOO_LONG)}Ye(e.page,e.limit,ye.MAX_LIMIT)}function ld(e){if(!Qe(e.tokenName))throw W("tokenName");if(e.tokenName.length>pe.MAX_LENGTH)throw new B(`tokenName must be at most ${pe.MAX_LENGTH} characters`,"tokenName",_.TOO_LONG);if(!Qe(e.content))throw W("content");if(0===e.content.trim().length)throw new B("content cannot be empty","content",_.REQUIRED);if(e.content.length>ve.CHAT_MESSAGES_V1.MAX_LENGTH)throw new B(`content must be at most ${ve.CHAT_MESSAGES_V1.MAX_LENGTH} characters`,"content",_.TOO_LONG)}function ud(e){if(!Qe(e.content))throw W("content");if(0===e.content.trim().length)throw new B("content cannot be empty","content",_.REQUIRED);if(e.content.length>ve.CHAT_MESSAGES_V1.MAX_LENGTH)throw new B(`content must be at most ${ve.CHAT_MESSAGES_V1.MAX_LENGTH} characters`,"content",_.TOO_LONG)}function dd(e){if(!Qe(e))throw W("id","Message ID");if(!Se.CHAT_MESSAGE.PATTERN.test(e))throw new B("Invalid message ID format. Expected: chat-{timestamp}-{uuid}","id",_.INVALID_FORMAT)}class hd extends vl{constructor(e,t,n,r=!1){super(e,t,n,r)}async getChatMessages(e){cd(e);const t=this.buildPaginationParams(e,ye.MAX_LIMIT);e.tokenName&&(t.tokenName=rs(e.tokenName)),e.userAddress&&(t.userAddress=e.userAddress);const n=await this.http.get(sr,t);return this.extractData(n)}async sendMessage(e){ld(e);const t={tokenName:rs(e.tokenName),content:e.content.trim()},n=await this.http.post(ar,t,this.getJwtHeaders());return{message:this.extractData(n)}}async updateMessage(e,t){dd(e),ud(t);const n=this.buildEndpointWithId(cr,e),r={content:t.content.trim()},i=await this.http.put(n,r,this.getJwtHeaders());return{message:this.extractData(i)}}async deleteMessage(e){dd(e);const t=this.buildEndpointWithId(lr,e);fr(await this.http.delete(t,this.getDualAuthHeaders()),"Failed to delete message")}}const gd={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 pd(e){return`${e}-${Date.now()}-${Math.random().toString(36).substring(2,11)}`}function fd(){return Date.now()+6e4}function md(e){return!(!e||"string"!=typeof e)&&/^[a-zA-Z0-9]{3,50}$/.test(e)}function yd(e){try{return Math.floor(parseFloat(String(e))||0).toString()}catch{return"0"}}function wd(e){return!(!e||"string"!=typeof e)&&/^eth\|[0-9a-fA-F]{40}$/.test(e)}class kd extends ds{constructor(e,t){super(e),this.galaChainClient=t}getCollectionClaimFee(){return gd.COLLECTION_CLAIM_FEE}getTokenClassCreateFee(){return gd.TOKEN_CLASS_CREATE_FEE}async estimateMintFee(e){try{if(this.logger.debug("Estimating mint fee",e),!(e.collection&&e.type&&e.category&&e.quantity))throw new Error("Missing required parameters for mint fee estimation");if(!wd(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=gd.COLLECTION_CLAIM_FEE;n.collectionClaim=e,t=String(BigInt(t)+BigInt(e))}if(e.createTokenClasses&&e.createTokenClasses>0){const r=gd.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),!md(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:fd(),uniqueKey:pd("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),!wd(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),!md(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),!e.collection||!e.type||!e.category)throw new Error("Missing required parameters: collection, type, category");if(!md(e.collection))throw new Error(`Invalid collection name: ${e.collection}`);if(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:e.maxSupply?yd(e.maxSupply):void 0,maxCapacity:e.maxCapacity?yd(e.maxCapacity):void 0,additionalKey:e.additionalKey,expiresAt:fd(),uniqueKey:pd("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),!md(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),!(e.collection&&e.type&&e.category&&e.quantity))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(!wd(e.ownerAddress))throw new Error(`Invalid owner address: ${e.ownerAddress}`);const n=await 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:fd(),uniqueKey:pd("mint")};this.logger.debug("Built mint DTO",r);const i=`mint-${Date.now()}`,o=Array.from({length:t},(e,t)=>t+1);return{transactionId:i,mintedQuantity:e.quantity,owner:e.ownerAddress,tokenInstances:o,tokenClass:{collection:e.collection,type:e.type,category:e.category}}}catch(e){throw this.logger.error("Failed to mint NFT",e),e}}async fetchNftBalances(e,t){try{if(this.logger.debug("Fetching NFT balances for",{ownerAddress:e,collectionFilter:t}),!wd(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}}}function bd(e){const t=eo(e);return t.success?[]:t.errors||["Unknown validation error"]}function vd(e){const t=bd(e);if(t.length>0)throw new Error(`LaunchTokenData validation failed:\n${t.map(e=>`- ${e}`).join("\n")}`)}const Sd="/api/asset/launchpad-contract/CallNativeTokenIn",Ad="/api/asset/launchpad-contract/CallNativeTokenOut",Td="/api/asset/launchpad-contract/CallMemeTokenIn",Ed="/api/asset/launchpad-contract/CallMemeTokenOut";class Id extends n.ChainCallDTO{constructor(e){super(),this.tokenName=e.tokenName,this.tokenSymbol=e.tokenSymbol,this.tokenDescription=e.tokenDescription,this.tokenImage=e.tokenImage,this.preBuyQuantity=e.preBuyQuantity,e.websiteUrl&&(this.websiteUrl=e.websiteUrl),e.telegramUrl&&(this.telegramUrl=e.telegramUrl),e.twitterUrl&&(this.twitterUrl=e.twitterUrl),e.instagramUrl&&(this.instagramUrl=e.instagramUrl),e.facebookUrl&&(this.facebookUrl=e.facebookUrl),e.redditUrl&&(this.redditUrl=e.redditUrl),e.tiktokUrl&&(this.tiktokUrl=e.tiktokUrl),this.tokenCategory=e.tokenCategory,this.tokenCollection=e.tokenCollection,this.uniqueKey=e.uniqueKey,e.reverseBondingCurveConfiguration&&(this.reverseBondingCurveConfiguration=e.reverseBondingCurveConfiguration)}}function xd(e){if(!e||"object"!=typeof e)return!1;const t=e;return"number"==typeof t.Status&&void 0!==t.Data&&"object"==typeof t.Data&&null!==t.Data&&"string"==typeof t.Data.calculatedQuantity&&void 0!==t.Data.extraFees&&"object"==typeof t.Data.extraFees&&null!==t.Data.extraFees&&"string"==typeof t.Data.extraFees.reverseBondingCurve&&"string"==typeof t.Data.extraFees.transactionFees}const Cd={NATIVE:"native",EXACT:"exact"},Nd={LOCAL:"local",EXTERNAL:"external"};class _d{static calculateBuyWithExact(e,t){const n=De(e),r=De(t),{BASE_PRICE:i,PRICE_SCALING_FACTOR:o,TRADING_FEE_FACTOR:s,GAS_FEE:a}=fc,c=this.roundUp(i*(Math.exp((r+n)*o)-Math.exp(r*o))/o,8),l=ko(wo(c).multipliedBy(s));return{amount:c.toString(),reverseBondingCurveFee:"0",transactionFee:l,gasFee:a}}static calculateBuyWithNative(e,t){const n=De(e),r=De(t),{BASE_PRICE:i,PRICE_SCALING_FACTOR:o,TRADING_FEE_FACTOR:s,GAS_FEE:a}=fc,c=Math.log(n*o/i+Math.exp(r*o))/o-r,l=ko(wo(c).multipliedBy(s));return{amount:c.toString(),reverseBondingCurveFee:"0",transactionFee:l,gasFee:a}}static calculateSellWithExact(e,t,n,r,i){const o=De(e),s=De(t),a=De(n),{BASE_PRICE:c,PRICE_SCALING_FACTOR:l,TRADING_FEE_FACTOR:u,GAS_FEE:d}=fc,h=c*(Math.exp(s*l)-Math.exp((s-o)*l))/l,g=wo(h),p=r+s/a*(i-r),f=ko(g.multipliedBy(p),8),m=ko(g.multipliedBy(u));return{amount:h.toString(),reverseBondingCurveFee:f,transactionFee:m,gasFee:d}}static calculateSellWithNative(e,t,n,r,i){const o=De(e),s=De(t),a=De(n),{BASE_PRICE:c,PRICE_SCALING_FACTOR:l,TRADING_FEE_FACTOR:u,GAS_FEE:d}=fc;if(o>=c*(Math.exp(s*l)-1)/l){const e=wo(o),t=r+s/a*(i-r),n=ko(e.multipliedBy(t),8),c=ko(e.multipliedBy(u));return{amount:s.toString(),reverseBondingCurveFee:n,transactionFee:c,gasFee:d}}const h=s-Math.log(Math.exp(s*l)-o*l/c)/l,g=wo(o),p=r+s/a*(i-r),f=ko(g.multipliedBy(p),8),m=ko(g.multipliedBy(u));return{amount:h.toString(),reverseBondingCurveFee:f,transactionFee:m,gasFee:d}}static roundUp(e,t){const n=Math.pow(10,t);return Math.ceil(e*n)/n}}class Bd{constructor(e,t,n,r,i,o,s="local"){this.http=e,this.tokenResolver=t,this.logger=n,this.bundleHttp=r,this.galaChainHttp=i,this.dexApiHttp=o,this.defaultCalculateAmountMode=s,this.metadataCache=new yc}addIfDefined(e,t,n){return void 0!==n&&(e[t]=n),e}async uploadImageByTokenName(e){const{tokenName:t,options:n}=e;$o(t);const r=`${t}.png`;Ms(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 z("file","a File object (browser) or Buffer (Node.js)");{const r=`${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(n.tokenName||t)}`,data:e,headers:{}});if(!0===r.error||200!==r.status)throw H(r.message||"Image upload failed - no URL returned",r.status);const i=mr(r);if(!i?.imageUrl)throw H("Image upload failed - no URL returned",r.status);return i.imageUrl}catch(e){if(S(e)&&e.message.includes("FormData"))throw j("File upload failed: FormData not supported in this environment. Ensure you have proper polyfills for Node.js environments.","FormData");throw e}}async fetchPoolsFromAPI(e){Ye(e.page,e.limit),e.tokenName&&$o(e.tokenName);const t={page:e.page.toString(),limit:e.limit.toString()};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=vr(t),r=await this.http.get("/launchpad/fetch-pool",n);if(!0===r.error||200!==r.status)throw H(r.message||"Failed to fetch pools",r.status);const i=mr(r);if(!i)throw H("Failed to fetch pools - no data returned",r.status);let o=[];if(i.tokens)if(Array.isArray(i.tokens))o=i.tokens.map(e=>{const t=e.reverseBondingCurveMinFeePortion??"0",n=e.reverseBondingCurveMaxFeePortion??"0",r=!Co(t)||!Co(n);return{...e,reverseBondingCurveMinFeePortion:t,reverseBondingCurveMaxFeePortion:n,hasReverseBondingCurveFee:r,createdAt:e.created_at||e.createdAt||""}});else{const e=i.tokens,t=e.reverseBondingCurveMinFeePortion??"0",n=e.reverseBondingCurveMaxFeePortion??"0",r=!Co(t)||!Co(n);o=[{...e,reverseBondingCurveMinFeePortion:t,reverseBondingCurveMaxFeePortion:n,hasReverseBondingCurveFee:r,createdAt:e.created_at||e.createdAt||""}]}else i.pools&&Array.isArray(i.pools)&&(o=i.pools.map(e=>{const t=e.reverseBondingCurveMinFeePortion??"0",n=e.reverseBondingCurveMaxFeePortion??"0",r=!Co(t)||!Co(n);return{...e,reverseBondingCurveMinFeePortion:t,reverseBondingCurveMaxFeePortion:n,hasReverseBondingCurveFee:r,createdAt:e.created_at||e.createdAt||""}}));const{extractMetadataFromPoolData:s,isValidPoolForCaching:a}=await Promise.resolve().then(function(){return iE});o.forEach(e=>{if(!a(e))return void this.logger.debug("Skipping pool with invalid structure for caching",e);const t=s(e,this.logger);t&&this.warmCacheFromPoolData(e.tokenName,t)});const c=i.count??i.total??0,l=i.page??e.page??1,u=i.limit??e.limit??10;return{items:o,meta:{page:l,limit:u,total:c,totalPages:Xo(c,u)}}}async _getAmount(e){if(function(e){const t=fo(e);!t.success&&t.errors&&Uo(t.errors,"options")}(e),!this.galaChainHttp)throw j("GalaChain client not configured. Direct GalaChain calls require galaChainHttp client.","galaChainHttp");const{endpoint:t,body:n}=((e,t,n,r)=>{if("NATIVE"===e&&"IN"===t)return{endpoint:Sd,body:{vaultAddress:n,tokenQuantity:r,IsPreMint:!1}};if("NATIVE"===e&&"OUT"===t)return{endpoint:Ad,body:{vaultAddress:n,tokenQuantity:r,IsPreMint:!1}};if("MEME"===e&&"IN"===t)return{endpoint:Td,body:{vaultAddress:n,nativeTokenQuantity:r,IsPreMint:!1}};if("MEME"===e&&"OUT"===t)return{endpoint:Ed,body:{vaultAddress:n,nativeTokenQuantity:r,IsPreMint:!1}};throw z("type-method","one of: NATIVE-IN, NATIVE-OUT, MEME-IN, MEME-OUT")})(e.type,e.method,e.vaultAddress,e.amount);try{const e=await this.galaChainHttp.post(t,n);if(!xd(e))throw H("Malformed response data from GalaChain gateway");try{x(e,"GalaChain calculation")}catch(e){throw H(A(e),500)}const{calculatedQuantity:r,extraFees:i}=e.Data;return{amount:r,reverseBondingCurveFee:i.reverseBondingCurve,transactionFee:i.transactionFees,gasFee:"1"}}catch(r){throw this.logger.error(`GalaChain ${e.type}-${e.method} operation failed:`,{endpoint:t,requestBody:n,error:A(r)}),H(A(r),500)}}async checkPool(e){qo(e),e.tokenName&&$o(e.tokenName);const t=vr(e),n=await this.http.get("/launchpad/check-pool",t);if(!0===n.error||200!==n.status)throw H(n.message||"Failed to check pool",n.status);const r=n.data;return e.symbol?r?.isSymbolExist??!1:e.tokenName?r?.isNameExist??!1:r?.exists??!1}async fetchVolumeData(e){if(!ms(e))throw z("options","{ tokenName: string, from?: number, to?: number, resolution?: number }");const{tokenName:t,from:n,to:r,resolution:i}=e;if($o(t),!n||!r||!i)throw W("graphOptions","Graph options (from, to, resolution)");const o={tokenName:t,from:n,to:r,resolution:i};Ko(o);const s=vr(o),a=await this.http.get("/launchpad/get-graph-data",s);if(!0===a.error||200!==a.status)throw H(a.message||"Failed to fetch graph data",a.status);const c=mr(a);if(!c)throw H("Failed to fetch graph data - no data returned",a.status);return{dataPoints:c}}async fetchPools(e={}){let t;"recent"===e.type?t="RECENT":"popular"===e.type&&(t="POPULAR");const n={page:e.page||1,limit:e.limit||10};return e.search&&(n.search=e.search),e.tokenName&&(n.tokenName=e.tokenName),t&&(n.type=t),void 0!==e.hasUpcomingShows&&(n.hasUpcomingShows=e.hasUpcomingShows),e.language&&(n.language=e.language),void 0!==e.recentlyStreamed&&(n.recentlyStreamed=e.recentlyStreamed),this.fetchPoolsFromAPI(n)}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 calculateBuyAmount(e){if(!e||"object"!=typeof e)throw z("options","an options object");const{tokenName:t,amount:n,type:r,currentSupply:i}=e,o=e.mode??this.defaultCalculateAmountMode;if("local"!==o&&"external"!==o)throw Y("mode",'"local" or "external"',o);if(!Qe(t))throw W("tokenName","Token name");if(!Qe(n))throw W("amount","Amount");if(r!==Cd.NATIVE&&r!==Cd.EXACT)throw Y("type",'"native" or "exact"',r);return"external"===o?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,i=await this.tokenResolver.resolveTokenToVault(t);if(!i)throw W("tokenName",`Token "${t}" not found. Please verify the token name is correct.`);return r===Cd.EXACT?this._getAmount({type:"NATIVE",method:"IN",vaultAddress:i,amount:n}):this._getAmount({type:"MEME",method:"OUT",vaultAddress:i,amount:n})}async calculateSellAmount(e){const{tokenName:t,amount:n,type:r,currentSupply:i,maxSupply:o,reverseBondingCurveMaxFeeFactor:s,reverseBondingCurveMinFeeFactor:a}=e,c=e.mode??this.defaultCalculateAmountMode;if("local"!==c&&"external"!==c)throw Y("mode",'"local" or "external"',c);if(!Qe(t))throw W("tokenName","Token name");if(!Qe(n))throw W("amount","Amount");if(r!==Cd.EXACT&&r!==Cd.NATIVE)throw Y("type",'"exact" or "native"',r);if("external"===c)return this.calculateSellAmountExternal({tokenName:t,amount:n,type:r});{const e={tokenName:t,amount:n,type:r,...void 0!==i&&{currentSupply:i},...void 0!==o&&{maxSupply:o},...void 0!==s&&{reverseBondingCurveMaxFeeFactor:s},...void 0!==a&&{reverseBondingCurveMinFeeFactor:a}};return this.calculateSellAmountLocal(e)}}async calculateSellAmountExternal(e){const{tokenName:t,amount:n,type:r}=e,i=await this.tokenResolver.resolveTokenToVault(t);if(!i)throw W("tokenName",`Token "${t}" not found. Please verify the token name is correct.`);return r===Cd.EXACT?this._getAmount({type:"NATIVE",method:"OUT",vaultAddress:i,amount:n}):this._getAmount({type:"MEME",method:"IN",vaultAddress:i,amount:n})}async calculateBuyAmountLocal(e){const{tokenName:t,amount:n,type:r,currentSupply:i}=e;if(!Qe(n))throw W("amount","Amount");if(r!==Cd.NATIVE&&r!==Cd.EXACT)throw Y("type",'"native" or "exact"',r);void 0!==i&&Go(i,"currentSupply");const o=!i;if(o&&!t)throw W("tokenName","Token name (required when currentSupply is not provided)");t&&$o(t);let s=i;if(o){s=(await this.fetchPoolDetailsForCalculation(t)).currentSupply}return r===Cd.EXACT?_d.calculateBuyWithExact(n,s):_d.calculateBuyWithNative(n,s)}async calculateSellAmountLocal(e){const{tokenName:t,amount:n,type:r,currentSupply:i,maxSupply:o,reverseBondingCurveMaxFeeFactor:s,reverseBondingCurveMinFeeFactor:a}=e;if(!Qe(n))throw W("amount","Amount");if(r!==Cd.EXACT&&r!==Cd.NATIVE)throw Y("type",'"exact" or "native"',r);void 0!==i&&Go(i,"currentSupply");const c=!i||!o||void 0===s||void 0===a;if(c&&!t)throw W("tokenName","Token name (required when currentSupply, maxSupply, or fee factors are not provided)");t&&$o(t);let l=i,u=o,d=s,h=a;if(c&&t){const e=this.metadataCache.getByName(t);u=u??this.metadataCache.getMaxSupply(t),d=d??e?.reverseBondingCurveMaxFeeFactor,h=h??e?.reverseBondingCurveMinFeeFactor,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===Cd.EXACT?_d.calculateSellWithExact(n,l,u,h,d):_d.calculateSellWithNative(n,l,u,h,d)}async calculateBuyAmountForGraduation(e){const t="string"==typeof e?{tokenName:e}:e;if("object"==typeof e&&!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return gs(t,"tokenName")&&function(e){return void 0===e.calculateAmountMode||"local"===e.calculateAmountMode||"external"===e.calculateAmountMode}(t)&&ps(t,"currentSupply")}(e))throw Y("options","CalculateBuyAmountForGraduationOptions or string (token name)",typeof e);const{tokenName:n,calculateAmountMode:r,currentSupply:i}=t;$o(n);const o=await this.tokenResolver.resolveTokenToVault(n);if(!o)throw new B(Tr(n),"tokenName","VAULT_NOT_FOUND");if(!this.galaChainHttp)throw j("GalaChain HTTP client not configured");const s=await this.galaChainHttp.post("/api/asset/launchpad-contract/FetchSaleDetails",{vaultAddress:o});if(1!==s.Status)throw H(`Failed to fetch pool details: Status ${s.Status}`,s.Status);const a=s.Data,c=i??ko(wo(a.maxSupply).minus(a.sellingTokenQuantity)),l=a.sellingTokenQuantity;if("0"===l)throw W("tokenName",`Token ${n} is already graduated (no tokens remaining in pool)`);const u={tokenName:n,amount:l,type:"exact",currentSupply:c,...void 0!==r&&{mode:r}};return{...await this.calculateBuyAmount(u),remainingTokens:l}}async launchToken(e){if(!this.bundleHttp)throw j("Bundle backend client not configured. LaunchToken requires bundleHttp client.","bundleHttp");vd(e);const t=e.preBuyQuantity||"0",r=De(t);if(0===r&&"0"!==t)throw ee("preBuyQuantity",t,"Pre-buy quantity");if(r<0)throw ee("preBuyQuantity",t,"Pre-buy quantity");if(e.reverseBondingCurveConfiguration){const{minFeePortion:t,maxFeePortion:n}=e.reverseBondingCurveConfiguration;de(t,n,"reverseBondingCurve")}let i="";if(e.tokenImage)if(e.tokenImage instanceof File||Buffer.isBuffer(e.tokenImage)){const t=await this.uploadImageByTokenName({tokenName:e.tokenName,options:{file:e.tokenImage,tokenName:e.tokenName}});if(!t)throw H("Image upload failed: No URL returned");i=t}else"string"==typeof e.tokenImage&&(i=e.tokenImage);const s=`galaswap - operation - ${o.v4()}-${Date.now()}-${this.http.getAddress()}`,a={tokenName:e.tokenName.trim(),tokenSymbol:os(e.tokenSymbol),tokenDescription:e.tokenDescription.trim(),tokenImage:i.trim(),preBuyQuantity:t.toString(),tokenCategory:e.tokenCategory||"Unit",tokenCollection:e.tokenCollection||"Token",uniqueKey:s},c=Es(e.websiteUrl);null!==c&&(a.websiteUrl=c);const l=Es(e.telegramUrl);null!==l&&(a.telegramUrl=l);const u=Es(e.twitterUrl);null!==u&&(a.twitterUrl=u);const d=Es(e.instagramUrl);null!==d&&(a.instagramUrl=d);const h=Es(e.facebookUrl);null!==h&&(a.facebookUrl=h);const g=Es(e.redditUrl);null!==g&&(a.redditUrl=g);const p=Es(e.tiktokUrl);null!==p&&(a.tiktokUrl=p),a.reverseBondingCurveConfiguration={minFeePortion:e.reverseBondingCurveConfiguration?.minFeePortion?.toString()||"0.1",maxFeePortion:e.reverseBondingCurveConfiguration?.maxFeePortion?.toString()||"0.5"};const f=new Id(a),m=await this.http.signWithGalaChain("CreateSale",f,n.SigningType.SIGN_TYPED_DATA),{signature:y,types:w,domain:k,prefix:b}=m,v={tokenName:f.tokenName,tokenSymbol:f.tokenSymbol,tokenDescription:f.tokenDescription,tokenImage:f.tokenImage,preBuyQuantity:f.preBuyQuantity,...f.websiteUrl&&{websiteUrl:f.websiteUrl},...f.telegramUrl&&{telegramUrl:f.telegramUrl},...f.twitterUrl&&{twitterUrl:f.twitterUrl},...f.instagramUrl&&{instagramUrl:f.instagramUrl},...f.facebookUrl&&{facebookUrl:f.facebookUrl},...f.redditUrl&&{redditUrl:f.redditUrl},...f.tiktokUrl&&{tiktokUrl:f.tiktokUrl},tokenCategory:f.tokenCategory,tokenCollection:f.tokenCollection,uniqueKey:f.uniqueKey,signature:y,types:w,domain:k,...b&&{prefix:b},...f.reverseBondingCurveConfiguration&&{reverseBondingCurveConfiguration:f.reverseBondingCurveConfiguration}},S=`${e.tokenName.trim()}$Unit$none$none`,A="GALA$Unit$none$none";let T;if(De(t,0)>0){const e=`$service$${S}$launchpad`;T=[e,`$token$${S}$${e}`,`$tokenBalance$${S}$${e}`,`$tokenBalance$${S}$${e}`,`$tokenBalance$${A}$${e}`,`$tokenBalance$${A}$${e}`]}else{const e=`$service$${S}$launchpad`;T=[e,`$token$${S}$${e}`,`$tokenBalance$${S}$${e}`]}const E={signedDto:v,stringsInstructions:T,method:"CreateSale"},I=await this.bundleHttp.post("/bundle",E);if(I.error)throw H(I.message||"Token launch failed");const x=mr(I);if(!x)throw H("Token launch failed - no transaction ID returned");return x}async fetchTokenDistribution(e){if(!e)throw W("tokenName","Token name");$o(e);const t=await this.http.get(`/holders/${e}`);if(!0===t.error||200!==t.status)throw H(t.message||"Failed to fetch token distribution",t.status);const n=mr(t);if(!n)throw H("Failed to fetch token distribution - no data returned",t.status);if(!Array.isArray(n))throw H("Invalid API response: expected array of holders",t.status);for(const e of n){if(!e.owner||"string"!=typeof e.owner)throw H("Invalid holder data: missing or invalid owner field",t.status);if(!e.quantity||"string"!=typeof e.quantity)throw H("Invalid holder data: missing or invalid quantity field",t.status);const n=De(e.quantity,NaN);if(isNaN(n)||!isFinite(n))throw H(`Invalid holder quantity: "${e.quantity}"`,t.status)}const r=n.reduce((e,t)=>e.plus(t.quantity),wo(0));return{holders:n.map(e=>{const t=Lo(wo(e.quantity),r,wo(0)).multipliedBy(100).toNumber();return{address:e.owner,balance:e.quantity,percentage:t}}),totalSupply:ko(r),totalHolders:n.length,lastUpdated:new Date}}async fetchTokenBadges(e){if(!e)throw W("tokenName","Token name");$o(e);const t=await this.http.get("/launchpad/get-badge/",{tokenName:e});if(t.error)throw H(t.message||"Failed to fetch token badges");const n=mr(t);if(!n)throw H("Failed to fetch token badges - no data returned");return{volumeBadges:n.volumeBadge||[],engagementBadges:n.engagementBadge||[]}}async hasTokenBadgeByTokenName(e){const{tokenName:t,badgeType:n,badgeName:r}=e;try{const e=await this.fetchTokenBadges(t);if(!e)return!1;const i=("volume"===n?e.volumeBadges:e.engagementBadges).find(e=>e.badgeName===r);return i?.isActive||!1}catch{return!1}}async calculateInitialBuyAmount(e){if(!qs(e))throw z("data","valid pre-mint calculation data");if(!this.galaChainHttp)throw j("GalaChain HTTP client not available. Please initialize SDK with galaChainBaseUrl.","galaChainHttp");try{const t={vaultAddress:"service|testToken",nativeTokenQuantity:e.nativeTokenQuantity,IsPreMint:!0},n=await this.galaChainHttp.post("/api/asset/launchpad-contract/CallMemeTokenOut",t);if(!xd(n))throw H("Malformed response data from GalaChain gateway");try{x(n,"Pre-mint calculation")}catch(e){throw H(A(e),500)}const{calculatedQuantity:r,extraFees:i}=n.Data;return{amount:r,reverseBondingCurveFee:i.reverseBondingCurve,transactionFee:i.transactionFees,gasFee:"1"}}catch(e){if(S(e)&&e instanceof P)throw e;throw H(A(e),500)}}async fetchPoolDetailsForCalculation(e){const t=await this.tokenResolver.resolveTokenToVault(e);if(!t)throw new B(Tr(e),"tokenName","VAULT_NOT_FOUND");if(!this.galaChainHttp)throw j("GalaChain HTTP client not configured");const n=await this.galaChainHttp.post("/api/asset/launchpad-contract/FetchSaleDetails",{vaultAddress:t});if(1!==n.Status)throw H(`Failed to fetch pool details: Status ${n.Status}`,n.Status);const r=n.Data,i=ko(wo(r.maxSupply).minus(r.sellingTokenQuantity)),o=r.sellingTokenQuantity,s=r.maxSupply;let a=.5,c=0;r.reverseBondingCurveConfiguration?(a=Ue(r.reverseBondingCurveConfiguration.maxFeePortion,.5),c=Ue(r.reverseBondingCurveConfiguration.minFeePortion,0)):this.logger.debug(`Pool details missing reverseBondingCurveConfiguration for token ${e}, using defaults (min: 0.0, max: 0.5)`);const l=a-c;return this.metadataCache.set(e,{maxSupply:s,reverseBondingCurveMaxFeeFactor:a,reverseBondingCurveMinFeeFactor:c,reverseBondingCurveNetFeeFactor:l}),{currentSupply:i,remainingTokens:o,maxSupply:s,reverseBondingCurveMaxFeeFactor:a,reverseBondingCurveMinFeeFactor:c,reverseBondingCurveNetFeeFactor:l}}async fetchCurrentSupply(e){$o(e);const t=await this.tokenResolver.resolveTokenToVault(e);if(!t)throw new B(Tr(e),"tokenName","VAULT_NOT_FOUND");if(!this.galaChainHttp)throw j("GalaChain HTTP client not configured");const n=await this.galaChainHttp.post("/api/asset/launchpad-contract/FetchSaleDetails",{vaultAddress:t});if(1!==n.Status)throw H(`Failed to fetch pool details: Status ${n.Status}`,n.Status);const r=n.Data,i=ko(wo(r.maxSupply).minus(r.sellingTokenQuantity)),o=r.maxSupply;return this.metadataCache.set(e,{maxSupply:o}),i}getAddress(){return this.http.getAddress()}formatAddressForBackend(e){return gt(e)}validateTokenName(e){return $o(e)}validatePagination(e){return Ye(e.page,e.limit)}async fetchTokenPrice(e){if(!this.dexApiHttp)throw j("DEX API client not configured. Token price fetching requires dexApiHttp client.","dexApiHttp");if(!e||Array.isArray(e)&&0===e.length)throw W("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 e.tokens&&Array.isArray(e.tokens)&&e.tokens.forEach(e=>{e.currentPrices&&e.symbol&&n.push({symbol:e.symbol,price:e.currentPrices.usd})}),n}catch(e){throw H(`Failed to fetch token prices: ${A(e)}`,void 0,S(e)?e:void 0)}}warmCacheFromPoolData(e,t){this.metadataCache.warmFromPoolData(e,t)}getCacheStats(){return this.metadataCache.getStats()}clearCache(e){this.metadataCache.clear(e)}}class Pd{constructor(e){if(this.lastTimestamp=0,this.pendingPromise=Promise.resolve(),this.chainLength=0,this.maxChainLength=1e3,e<=0)throw J("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(S(e)?e:new Error(A(e)))}}),this.chainLength++,this.chainLength>=this.maxChainLength){this.chainLength=0;const e=this.pendingPromise;this.pendingPromise=e.then(()=>Promise.resolve())}return r}}function Dd(e,t){let n;try{n=Fe(e,"amount")}catch(t){throw ee("amount",`${e} (${A(t)})`)}if(!n.isFinite())throw ee("amount",e);const r=n.multipliedBy(wo(10).pow(t));if(!r.isInteger())throw ee("amount",`${e} (cannot be represented with ${t} decimals)`);return BigInt(r.toFixed(0))}function Rd(e,t){return wo(e.toString()).dividedBy(wo(10).pow(t)).toFixed(t).replace(/\.?0+$/,"")}const Md={maxRetries:3,initialDelayMs:1e3,maxDelayMs:3e4,backoffMultiplier:2,jitterFactor:.1},Ld=new Set([408,429,500,502,503,504]),Od=[/ECONNRESET/i,/ECONNREFUSED/i,/ETIMEDOUT/i,/ENOTFOUND/i,/EAI_AGAIN/i,/socket hang up/i,/network/i,/timeout/i,/aborted/i];function Fd(e){if(e&&"object"==typeof e){const t=e;if("number"==typeof t.status)return Ld.has(t.status);if("number"==typeof t.statusCode)return Ld.has(t.statusCode);const n=E(e);if("string"==typeof n&&("ECONNRESET"===n||"ECONNREFUSED"===n||"ETIMEDOUT"===n||"ENOTFOUND"===n||"EAI_AGAIN"===n))return!0}const t=A(e);return Od.some(e=>e.test(t))}function Ud(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 $d(e){return new Promise(t=>setTimeout(t,e))}function qd(e){let t;if("string"==typeof e)t=js(e);else{if(!Qs(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:Ks(t)}}function Kd(e){const t={};for(const[n,r]of Object.entries(e))void 0!==r&&(r&&"object"==typeof r&&!Array.isArray(r)?t[n]=Kd(r):t[n]=r);return t}function Gd(e,t){const n=De(e,-1);if(n<=0)throw new Error(`Invalid bridge amount for ${t}: "${e}". Amount must be a positive number.`);return n}function Wd(e){const t="string"==typeof e.timestamp?Le(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}}var zd,Hd={},jd={};var Vd,Xd,Qd={};function Jd(){return Vd||(Vd=1,Qd.read=function(e,t,n,r,i){var o,s,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,o=g&(1<<-u)-1,g>>=-u,u+=a;u>0;o=256*o+e[t+d],d+=h,u-=8);for(s=o&(1<<-u)-1,o>>=-u,u+=r;u>0;s=256*s+e[t+d],d+=h,u-=8);if(0===o)o=1-l;else{if(o===c)return s?NaN:1/0*(g?-1:1);s+=Math.pow(2,r),o-=l}return(g?-1:1)*s*Math.pow(2,o-r)},Qd.write=function(e,t,n,r,i,o){var s,a,c,l=8*o-i-1,u=(1<<l)-1,d=u>>1,h=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,g=r?0:o-1,p=r?1:-1,f=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,s=u):(s=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-s))<1&&(s--,c*=2),(t+=s+d>=1?h/c:h*Math.pow(2,1-d))*c>=2&&(s++,c/=2),s+d>=u?(a=0,s=u):s+d>=1?(a=(t*c-1)*Math.pow(2,i),s+=d):(a=t*Math.pow(2,d-1)*Math.pow(2,i),s=0));i>=8;e[n+g]=255&a,g+=p,a/=256,i-=8);for(s=s<<i|a,l+=i;l>0;e[n+g]=255&s,g+=p,s/=256,l-=8);e[n+g-p]|=128*f}),Qd}function Zd(){return Xd||(Xd=1,function(e){const t=function(){if(zd)return jd;zd=1,jd.byteLength=function(e){var t=o(e),n=t[0],r=t[1];return 3*(n+r)/4-r},jd.toByteArray=function(e){var r,i,s=o(e),a=s[0],c=s[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;return 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),l},jd.fromByteArray=function(t){for(var n,r=t.length,i=r%3,o=[],s=16383,c=0,l=r-i;c<l;c+=s)o.push(a(t,c,c+s>l?l:c+s));return 1===i?(n=t[r-1],o.push(e[n>>2]+e[n<<4&63]+"==")):2===i&&(n=(t[r-2]<<8)+t[r-1],o.push(e[n>>10]+e[n>>4&63]+e[n<<2&63]+"=")),o.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 o(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 s(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=[],o=t;o<n;o+=3)r=(e[o]<<16&16711680)+(e[o+1]<<8&65280)+(255&e[o+2]),i.push(s(r));return i.join("")}return t["-".charCodeAt(0)]=62,t["_".charCodeAt(0)]=63,jd}(),n=Jd(),r="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;e.Buffer=s,e.SlowBuffer=function(e){+e!=e&&(e=0);return s.alloc(+e)},e.INSPECT_MAX_BYTES=50;const i=2147483647;function o(e){if(e>i)throw new RangeError('The value "'+e+'" is invalid for option "size"');const t=new Uint8Array(e);return Object.setPrototypeOf(t,s.prototype),t}function s(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(!s.isEncoding(t))throw new TypeError("Unknown encoding: "+t);const n=0|g(e,t);let r=o(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(j(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(j(e,ArrayBuffer)||e&&j(e.buffer,ArrayBuffer))return d(e,t,n);if("undefined"!=typeof SharedArrayBuffer&&(j(e,SharedArrayBuffer)||e&&j(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 s.from(r,t,n);const i=function(e){if(s.isBuffer(e)){const t=0|h(e.length),n=o(t);return 0===n.length||e.copy(n,0,0,t),n}if(void 0!==e.length)return"number"!=typeof e.length||V(e.length)?o(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 s.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),o(e<0?0:0|h(e))}function u(e){const t=e.length<0?0:0|h(e.length),n=o(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,s.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(s.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||j(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 z(e).length;default:if(i)return r?-1:W(e).length;t=(""+t).toLowerCase(),i=!0}}function p(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 T(this,t,n);case"ascii":return I(this,t,n);case"latin1":case"binary":return x(this,t,n);case"base64":return A(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return N(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function f(e,t,n){const r=e[t];e[t]=e[n],e[n]=r}function m(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),V(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=s.from(t,r)),s.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 o,s=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;s=2,a/=2,c/=2,n/=2}function l(e,t){return 1===s?e[t]:e.readUInt16BE(t*s)}if(i){let r=-1;for(o=n;o<a;o++)if(l(e,o)===l(t,-1===r?0:o-r)){if(-1===r&&(r=o),o-r+1===c)return r*s}else-1!==r&&(o-=o-r),r=-1}else for(n+c>a&&(n=a-c),o=n;o>=0;o--){let n=!0;for(let r=0;r<c;r++)if(l(e,o+r)!==l(t,r)){n=!1;break}if(n)return o}return-1}function w(e,t,n,r){n=Number(n)||0;const i=e.length-n;r?(r=Number(r))>i&&(r=i):r=i;const o=t.length;let s;for(r>o/2&&(r=o/2),s=0;s<r;++s){const r=parseInt(t.substr(2*s,2),16);if(V(r))return s;e[n+s]=r}return s}function k(e,t,n,r){return H(W(t,e.length-n),e,n,r)}function b(e,t,n,r){return H(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 v(e,t,n,r){return H(z(t),e,n,r)}function S(e,t,n,r){return H(function(e,t){let n,r,i;const o=[];for(let s=0;s<e.length&&!((t-=2)<0);++s)n=e.charCodeAt(s),r=n>>8,i=n%256,o.push(i),o.push(r);return o}(t,e.length-n),e,n,r)}function A(e,n,r){return 0===n&&r===e.length?t.fromByteArray(e):t.fromByteArray(e.slice(n,r))}function T(e,t,n){n=Math.min(e.length,n);const r=[];let i=t;for(;i<n;){const t=e[i];let o=null,s=t>239?4:t>223?3:t>191?2:1;if(i+s<=n){let n,r,a,c;switch(s){case 1:t<128&&(o=t);break;case 2:n=e[i+1],128==(192&n)&&(c=(31&t)<<6|63&n,c>127&&(o=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)&&(o=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&&(o=c))}}null===o?(o=65533,s=1):o>65535&&(o-=65536,r.push(o>>>10&1023|55296),o=56320|1023&o),r.push(o),i+=s}return function(e){const t=e.length;if(t<=E)return String.fromCharCode.apply(String,e);let n="",r=0;for(;r<t;)n+=String.fromCharCode.apply(String,e.slice(r,r+=E));return n}(r)}e.kMaxLength=i,s.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}}(),!s.TYPED_ARRAY_SUPPORT&&"undefined"!=typeof console&&console.error,Object.defineProperty(s.prototype,"parent",{enumerable:!0,get:function(){if(s.isBuffer(this))return this.buffer}}),Object.defineProperty(s.prototype,"offset",{enumerable:!0,get:function(){if(s.isBuffer(this))return this.byteOffset}}),s.poolSize=8192,s.from=function(e,t,n){return a(e,t,n)},Object.setPrototypeOf(s.prototype,Uint8Array.prototype),Object.setPrototypeOf(s,Uint8Array),s.alloc=function(e,t,n){return function(e,t,n){return c(e),e<=0?o(e):void 0!==t?"string"==typeof n?o(e).fill(t,n):o(e).fill(t):o(e)}(e,t,n)},s.allocUnsafe=function(e){return l(e)},s.allocUnsafeSlow=function(e){return l(e)},s.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==s.prototype},s.compare=function(e,t){if(j(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),j(t,Uint8Array)&&(t=s.from(t,t.offset,t.byteLength)),!s.isBuffer(e)||!s.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,o=Math.min(n,r);i<o;++i)if(e[i]!==t[i]){n=e[i],r=t[i];break}return n<r?-1:r<n?1:0},s.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}},s.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return s.alloc(0);let n;if(void 0===t)for(t=0,n=0;n<e.length;++n)t+=e[n].length;const r=s.allocUnsafe(t);let i=0;for(n=0;n<e.length;++n){let t=e[n];if(j(t,Uint8Array))i+t.length>r.length?(s.isBuffer(t)||(t=s.from(t)),t.copy(r,i)):Uint8Array.prototype.set.call(r,t,i);else{if(!s.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(r,i)}i+=t.length}return r},s.byteLength=g,s.prototype._isBuffer=!0,s.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)f(this,t,t+1);return this},s.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)f(this,t,t+3),f(this,t+1,t+2);return this},s.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)f(this,t,t+7),f(this,t+1,t+6),f(this,t+2,t+5),f(this,t+3,t+4);return this},s.prototype.toString=function(){const e=this.length;return 0===e?"":0===arguments.length?T(this,0,e):p.apply(this,arguments)},s.prototype.toLocaleString=s.prototype.toString,s.prototype.equals=function(e){if(!s.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===s.compare(this,e)},s.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&&(s.prototype[r]=s.prototype.inspect),s.prototype.compare=function(e,t,n,r,i){if(j(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),!s.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 o=(i>>>=0)-(r>>>=0),a=(n>>>=0)-(t>>>=0);const c=Math.min(o,a),l=this.slice(r,i),u=e.slice(t,n);for(let e=0;e<c;++e)if(l[e]!==u[e]){o=l[e],a=u[e];break}return o<a?-1:a<o?1:0},s.prototype.includes=function(e,t,n){return-1!==this.indexOf(e,t,n)},s.prototype.indexOf=function(e,t,n){return m(this,e,t,n,!0)},s.prototype.lastIndexOf=function(e,t,n){return m(this,e,t,n,!1)},s.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 o=!1;for(;;)switch(r){case"hex":return w(this,e,t,n);case"utf8":case"utf-8":return k(this,e,t,n);case"ascii":case"latin1":case"binary":return b(this,e,t,n);case"base64":return v(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return S(this,e,t,n);default:if(o)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),o=!0}},s.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const E=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 x(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 N(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 _(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 B(e,t,n,r,i,o){if(!s.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||t<o)throw new RangeError('"value" argument is out of bounds');if(n+r>e.length)throw new RangeError("Index out of range")}function P(e,t,n,r,i){$(t,r,i,e,n,7);let o=Number(t&BigInt(4294967295));e[n++]=o,o>>=8,e[n++]=o,o>>=8,e[n++]=o,o>>=8,e[n++]=o;let s=Number(t>>BigInt(32)&BigInt(4294967295));return e[n++]=s,s>>=8,e[n++]=s,s>>=8,e[n++]=s,s>>=8,e[n++]=s,n}function D(e,t,n,r,i){$(t,r,i,e,n,7);let o=Number(t&BigInt(4294967295));e[n+7]=o,o>>=8,e[n+6]=o,o>>=8,e[n+5]=o,o>>=8,e[n+4]=o;let s=Number(t>>BigInt(32)&BigInt(4294967295));return e[n+3]=s,s>>=8,e[n+2]=s,s>>=8,e[n+1]=s,s>>=8,e[n]=s,n+8}function R(e,t,n,r,i,o){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function M(e,t,r,i,o){return t=+t,r>>>=0,o||R(e,0,r,4),n.write(e,t,r,i,23,4),r+4}function L(e,t,r,i,o){return t=+t,r>>>=0,o||R(e,0,r,8),n.write(e,t,r,i,52,8),r+8}s.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,s.prototype),r},s.prototype.readUintLE=s.prototype.readUIntLE=function(e,t,n){e>>>=0,t>>>=0,n||_(e,t,this.length);let r=this[e],i=1,o=0;for(;++o<t&&(i*=256);)r+=this[e+o]*i;return r},s.prototype.readUintBE=s.prototype.readUIntBE=function(e,t,n){e>>>=0,t>>>=0,n||_(e,t,this.length);let r=this[e+--t],i=1;for(;t>0&&(i*=256);)r+=this[e+--t]*i;return r},s.prototype.readUint8=s.prototype.readUInt8=function(e,t){return e>>>=0,t||_(e,1,this.length),this[e]},s.prototype.readUint16LE=s.prototype.readUInt16LE=function(e,t){return e>>>=0,t||_(e,2,this.length),this[e]|this[e+1]<<8},s.prototype.readUint16BE=s.prototype.readUInt16BE=function(e,t){return e>>>=0,t||_(e,2,this.length),this[e]<<8|this[e+1]},s.prototype.readUint32LE=s.prototype.readUInt32LE=function(e,t){return e>>>=0,t||_(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},s.prototype.readUint32BE=s.prototype.readUInt32BE=function(e,t){return e>>>=0,t||_(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},s.prototype.readBigUInt64LE=Q(function(e){q(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||K(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))}),s.prototype.readBigUInt64BE=Q(function(e){q(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||K(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)}),s.prototype.readIntLE=function(e,t,n){e>>>=0,t>>>=0,n||_(e,t,this.length);let r=this[e],i=1,o=0;for(;++o<t&&(i*=256);)r+=this[e+o]*i;return i*=128,r>=i&&(r-=Math.pow(2,8*t)),r},s.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||_(e,t,this.length);let r=t,i=1,o=this[e+--r];for(;r>0&&(i*=256);)o+=this[e+--r]*i;return i*=128,o>=i&&(o-=Math.pow(2,8*t)),o},s.prototype.readInt8=function(e,t){return e>>>=0,t||_(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},s.prototype.readInt16LE=function(e,t){e>>>=0,t||_(e,2,this.length);const n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},s.prototype.readInt16BE=function(e,t){e>>>=0,t||_(e,2,this.length);const n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},s.prototype.readInt32LE=function(e,t){return e>>>=0,t||_(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},s.prototype.readInt32BE=function(e,t){return e>>>=0,t||_(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},s.prototype.readBigInt64LE=Q(function(e){q(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||K(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)}),s.prototype.readBigInt64BE=Q(function(e){q(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||K(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)}),s.prototype.readFloatLE=function(e,t){return e>>>=0,t||_(e,4,this.length),n.read(this,e,!0,23,4)},s.prototype.readFloatBE=function(e,t){return e>>>=0,t||_(e,4,this.length),n.read(this,e,!1,23,4)},s.prototype.readDoubleLE=function(e,t){return e>>>=0,t||_(e,8,this.length),n.read(this,e,!0,52,8)},s.prototype.readDoubleBE=function(e,t){return e>>>=0,t||_(e,8,this.length),n.read(this,e,!1,52,8)},s.prototype.writeUintLE=s.prototype.writeUIntLE=function(e,t,n,r){if(e=+e,t>>>=0,n>>>=0,!r){B(this,e,t,n,Math.pow(2,8*n)-1,0)}let i=1,o=0;for(this[t]=255&e;++o<n&&(i*=256);)this[t+o]=e/i&255;return t+n},s.prototype.writeUintBE=s.prototype.writeUIntBE=function(e,t,n,r){if(e=+e,t>>>=0,n>>>=0,!r){B(this,e,t,n,Math.pow(2,8*n)-1,0)}let i=n-1,o=1;for(this[t+i]=255&e;--i>=0&&(o*=256);)this[t+i]=e/o&255;return t+n},s.prototype.writeUint8=s.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||B(this,e,t,1,255,0),this[t]=255&e,t+1},s.prototype.writeUint16LE=s.prototype.writeUInt16LE=function(e,t,n){return e=+e,t>>>=0,n||B(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},s.prototype.writeUint16BE=s.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||B(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},s.prototype.writeUint32LE=s.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||B(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},s.prototype.writeUint32BE=s.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||B(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},s.prototype.writeBigUInt64LE=Q(function(e,t=0){return P(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),s.prototype.writeBigUInt64BE=Q(function(e,t=0){return D(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),s.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t>>>=0,!r){const r=Math.pow(2,8*n-1);B(this,e,t,n,r-1,-r)}let i=0,o=1,s=0;for(this[t]=255&e;++i<n&&(o*=256);)e<0&&0===s&&0!==this[t+i-1]&&(s=1),this[t+i]=(e/o|0)-s&255;return t+n},s.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t>>>=0,!r){const r=Math.pow(2,8*n-1);B(this,e,t,n,r-1,-r)}let i=n-1,o=1,s=0;for(this[t+i]=255&e;--i>=0&&(o*=256);)e<0&&0===s&&0!==this[t+i+1]&&(s=1),this[t+i]=(e/o|0)-s&255;return t+n},s.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||B(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},s.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||B(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},s.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||B(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},s.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||B(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},s.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||B(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},s.prototype.writeBigInt64LE=Q(function(e,t=0){return P(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),s.prototype.writeBigInt64BE=Q(function(e,t=0){return D(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),s.prototype.writeFloatLE=function(e,t,n){return M(this,e,t,!0,n)},s.prototype.writeFloatBE=function(e,t,n){return M(this,e,t,!1,n)},s.prototype.writeDoubleLE=function(e,t,n){return L(this,e,t,!0,n)},s.prototype.writeDoubleBE=function(e,t,n){return L(this,e,t,!1,n)},s.prototype.copy=function(e,t,n,r){if(!s.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},s.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&&!s.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 o=s.isBuffer(e)?e:s.from(e,r),a=o.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]=o[i%a]}return this};const O={};function F(e,t,n){O[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 U(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,o){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*(o+1)}${n}`:`>= -(2${n} ** ${8*(o+1)-1}${n}) and < 2 ** ${8*(o+1)-1}${n}`,new O.ERR_OUT_OF_RANGE("value",r,e)}!function(e,t,n){q(t,"offset"),void 0!==e[t]&&void 0!==e[t+n]||K(t,e.length-(n+1))}(r,i,o)}function q(e,t){if("number"!=typeof e)throw new O.ERR_INVALID_ARG_TYPE(t,"number",e)}function K(e,t,n){if(Math.floor(e)!==e)throw q(e,n),new O.ERR_OUT_OF_RANGE("offset","an integer",e);if(t<0)throw new O.ERR_BUFFER_OUT_OF_BOUNDS;throw new O.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${t}`,e)}F("ERR_BUFFER_OUT_OF_BOUNDS",function(e){return e?`${e} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),F("ERR_INVALID_ARG_TYPE",function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`},TypeError),F("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=U(String(n)):"bigint"==typeof n&&(i=String(n),(n>BigInt(2)**BigInt(32)||n<-(BigInt(2)**BigInt(32)))&&(i=U(i)),i+="n"),r+=` It must be ${t}. Received ${i}`,r},RangeError);const G=/[^+/0-9A-Za-z-_]/g;function W(e,t){let n;t=t||1/0;const r=e.length;let i=null;const o=[];for(let s=0;s<r;++s){if(n=e.charCodeAt(s),n>55295&&n<57344){if(!i){if(n>56319){(t-=3)>-1&&o.push(239,191,189);continue}if(s+1===r){(t-=3)>-1&&o.push(239,191,189);continue}i=n;continue}if(n<56320){(t-=3)>-1&&o.push(239,191,189),i=n;continue}n=65536+(i-55296<<10|n-56320)}else i&&(t-=3)>-1&&o.push(239,191,189);if(i=null,n<128){if((t-=1)<0)break;o.push(n)}else if(n<2048){if((t-=2)<0)break;o.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;o.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;o.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return o}function z(e){return t.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(G,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function H(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 j(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function V(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 Q(e){return"undefined"==typeof BigInt?J:e}function J(){throw new Error("BigInt not supported")}}(Hd)),Hd}var Yd=Zd();const eh="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0;function th(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function nh(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function rh(e,...t){if(!th(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 ih(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.createHasher");nh(e.outputLen),nh(e.blockLen)}function oh(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 sh(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function ah(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function ch(e,t){return e<<32-t|e>>>t}const lh=(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)(),uh=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function dh(e){if(rh(e),lh)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=uh[e[n]];return t}const hh=48,gh=57,ph=65,fh=70,mh=97,yh=102;function wh(e){return e>=hh&&e<=gh?e-hh:e>=ph&&e<=fh?e-(ph-10):e>=mh&&e<=yh?e-(mh-10):void 0}function kh(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);if(lh)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=wh(e.charCodeAt(i)),o=wh(e.charCodeAt(i+1));if(void 0===n||void 0===o){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+o}return r}function bh(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)),rh(e),e}function vh(...e){let t=0;for(let n=0;n<e.length;n++){const r=e[n];rh(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 Sh{}function Ah(e){const t=t=>e().update(bh(t)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function Th(e=32){if(eh&&"function"==typeof eh.getRandomValues)return eh.getRandomValues(new Uint8Array(e));if(eh&&"function"==typeof eh.randomBytes)return Uint8Array.from(eh.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}function Eh(e,t,n){return e&t^~e&n}function Ih(e,t,n){return e&t^e&n^t&n}class xh extends Sh{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=ah(this.buffer)}update(e){oh(this),rh(e=bh(e));const{view:t,buffer:n,blockLen:r}=this,i=e.length;for(let o=0;o<i;){const s=Math.min(r-this.pos,i-o);if(s===r){const t=ah(e);for(;r<=i-o;o+=r)this.process(t,o);continue}n.set(e.subarray(o,o+s),this.pos),this.pos+=s,o+=s,this.pos===r&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){oh(this),function(e,t){rh(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:o}=this;t[o++]=128,sh(this.buffer.subarray(o)),this.padOffset>r-o&&(this.process(n,0),o=0);for(let e=o;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),o=BigInt(4294967295),s=Number(n>>i&o),a=Number(n&o),c=r?4:0,l=r?0:4;e.setUint32(t+c,s,r),e.setUint32(t+l,a,r)}(n,r-8,BigInt(8*this.length),i),this.process(n,0);const s=ah(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++)s.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:o,pos:s}=this;return e.destroyed=o,e.finished=i,e.length=r,e.pos=s,r%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}}const Ch=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Nh=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),_h=BigInt(2**32-1),Bh=BigInt(32);function Ph(e,t=!1){return t?{h:Number(e&_h),l:Number(e>>Bh&_h)}:{h:0|Number(e>>Bh&_h),l:0|Number(e&_h)}}const Dh=(e,t,n)=>e>>>n,Rh=(e,t,n)=>e<<32-n|t>>>n,Mh=(e,t,n)=>e>>>n|t<<32-n,Lh=(e,t,n)=>e<<32-n|t>>>n,Oh=(e,t,n)=>e<<64-n|t>>>n-32,Fh=(e,t,n)=>e>>>n-32|t<<64-n;function Uh(e,t,n,r){const i=(t>>>0)+(r>>>0);return{h:e+n+(i/2**32|0)|0,l:0|i}}const $h=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),qh=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,Kh=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),Gh=(e,t,n,r,i)=>t+n+r+i+(e/2**32|0)|0,Wh=(e,t,n,r,i)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(i>>>0),zh=(e,t,n,r,i,o)=>t+n+r+i+o+(e/2**32|0)|0,Hh=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]),jh=new Uint32Array(64);class Vh extends xh{constructor(e=32){super(64,e,8,!1),this.A=0|Ch[0],this.B=0|Ch[1],this.C=0|Ch[2],this.D=0|Ch[3],this.E=0|Ch[4],this.F=0|Ch[5],this.G=0|Ch[6],this.H=0|Ch[7]}get(){const{A:e,B:t,C:n,D:r,E:i,F:o,G:s,H:a}=this;return[e,t,n,r,i,o,s,a]}set(e,t,n,r,i,o,s,a){this.A=0|e,this.B=0|t,this.C=0|n,this.D=0|r,this.E=0|i,this.F=0|o,this.G=0|s,this.H=0|a}process(e,t){for(let n=0;n<16;n++,t+=4)jh[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){const t=jh[e-15],n=jh[e-2],r=ch(t,7)^ch(t,18)^t>>>3,i=ch(n,17)^ch(n,19)^n>>>10;jh[e]=i+jh[e-7]+r+jh[e-16]|0}let{A:n,B:r,C:i,D:o,E:s,F:a,G:c,H:l}=this;for(let e=0;e<64;e++){const t=l+(ch(s,6)^ch(s,11)^ch(s,25))+Eh(s,a,c)+Hh[e]+jh[e]|0,u=(ch(n,2)^ch(n,13)^ch(n,22))+Ih(n,r,i)|0;l=c,c=a,a=s,s=o+t|0,o=i,i=r,r=n,n=t+u|0}n=n+this.A|0,r=r+this.B|0,i=i+this.C|0,o=o+this.D|0,s=s+this.E|0,a=a+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(n,r,i,o,s,a,c,l)}roundClean(){sh(jh)}destroy(){this.set(0,0,0,0,0,0,0,0),sh(this.buffer)}}const Xh=(()=>function(e,t=!1){const n=e.length;let r=new Uint32Array(n),i=new Uint32Array(n);for(let o=0;o<n;o++){const{h:n,l:s}=Ph(e[o],t);[r[o],i[o]]=[n,s]}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))))(),Qh=(()=>Xh[0])(),Jh=(()=>Xh[1])(),Zh=new Uint32Array(80),Yh=new Uint32Array(80);class eg extends xh{constructor(e=64){super(128,e,16,!1),this.Ah=0|Nh[0],this.Al=0|Nh[1],this.Bh=0|Nh[2],this.Bl=0|Nh[3],this.Ch=0|Nh[4],this.Cl=0|Nh[5],this.Dh=0|Nh[6],this.Dl=0|Nh[7],this.Eh=0|Nh[8],this.El=0|Nh[9],this.Fh=0|Nh[10],this.Fl=0|Nh[11],this.Gh=0|Nh[12],this.Gl=0|Nh[13],this.Hh=0|Nh[14],this.Hl=0|Nh[15]}get(){const{Ah:e,Al:t,Bh:n,Bl:r,Ch:i,Cl:o,Dh:s,Dl:a,Eh:c,El:l,Fh:u,Fl:d,Gh:h,Gl:g,Hh:p,Hl:f}=this;return[e,t,n,r,i,o,s,a,c,l,u,d,h,g,p,f]}set(e,t,n,r,i,o,s,a,c,l,u,d,h,g,p,f){this.Ah=0|e,this.Al=0|t,this.Bh=0|n,this.Bl=0|r,this.Ch=0|i,this.Cl=0|o,this.Dh=0|s,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|p,this.Hl=0|f}process(e,t){for(let n=0;n<16;n++,t+=4)Zh[n]=e.getUint32(t),Yh[n]=e.getUint32(t+=4);for(let e=16;e<80;e++){const t=0|Zh[e-15],n=0|Yh[e-15],r=Mh(t,n,1)^Mh(t,n,8)^Dh(t,0,7),i=Lh(t,n,1)^Lh(t,n,8)^Rh(t,n,7),o=0|Zh[e-2],s=0|Yh[e-2],a=Mh(o,s,19)^Oh(o,s,61)^Dh(o,0,6),c=Lh(o,s,19)^Fh(o,s,61)^Rh(o,s,6),l=Kh(i,c,Yh[e-7],Yh[e-16]),u=Gh(l,r,a,Zh[e-7],Zh[e-16]);Zh[e]=0|u,Yh[e]=0|l}let{Ah:n,Al:r,Bh:i,Bl:o,Ch:s,Cl:a,Dh:c,Dl:l,Eh:u,El:d,Fh:h,Fl:g,Gh:p,Gl:f,Hh:m,Hl:y}=this;for(let e=0;e<80;e++){const t=Mh(u,d,14)^Mh(u,d,18)^Oh(u,d,41),w=Lh(u,d,14)^Lh(u,d,18)^Fh(u,d,41),k=u&h^~u&p,b=Wh(y,w,d&g^~d&f,Jh[e],Yh[e]),v=zh(b,m,t,k,Qh[e],Zh[e]),S=0|b,A=Mh(n,r,28)^Oh(n,r,34)^Oh(n,r,39),T=Lh(n,r,28)^Fh(n,r,34)^Fh(n,r,39),E=n&i^n&s^i&s,I=r&o^r&a^o&a;m=0|p,y=0|f,p=0|h,f=0|g,h=0|u,g=0|d,({h:u,l:d}=Uh(0|c,0|l,0|v,0|S)),c=0|s,l=0|a,s=0|i,a=0|o,i=0|n,o=0|r;const x=$h(S,T,I);n=qh(x,v,A,E),r=0|x}({h:n,l:r}=Uh(0|this.Ah,0|this.Al,0|n,0|r)),({h:i,l:o}=Uh(0|this.Bh,0|this.Bl,0|i,0|o)),({h:s,l:a}=Uh(0|this.Ch,0|this.Cl,0|s,0|a)),({h:c,l:l}=Uh(0|this.Dh,0|this.Dl,0|c,0|l)),({h:u,l:d}=Uh(0|this.Eh,0|this.El,0|u,0|d)),({h:h,l:g}=Uh(0|this.Fh,0|this.Fl,0|h,0|g)),({h:p,l:f}=Uh(0|this.Gh,0|this.Gl,0|p,0|f)),({h:m,l:y}=Uh(0|this.Hh,0|this.Hl,0|m,0|y)),this.set(n,r,i,o,s,a,c,l,u,d,h,g,p,f,m,y)}roundClean(){sh(Zh,Yh)}destroy(){sh(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const tg=Ah(()=>new Vh),ng=Ah(()=>new eg),rg=BigInt(0),ig=BigInt(1);function og(e,t=""){if("boolean"!=typeof e){throw new Error((t&&`"${t}"`)+"expected boolean, got type="+typeof e)}return e}function sg(e,t,n=""){const r=th(e),i=e?.length,o=void 0!==t;if(!r||o&&i!==t){throw new Error((n&&`"${n}" `)+"expected Uint8Array"+(o?` of length ${t}`:"")+", got "+(r?`length=${i}`:"type="+typeof e))}return e}function ag(e){const t=e.toString(16);return 1&t.length?"0"+t:t}function cg(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);return""===e?rg:BigInt("0x"+e)}function lg(e){return cg(dh(e))}function ug(e){return rh(e),cg(dh(Uint8Array.from(e).reverse()))}function dg(e,t){return kh(e.toString(16).padStart(2*t,"0"))}function hg(e,t){return dg(e,t).reverse()}function gg(e,t,n){let r;if("string"==typeof t)try{r=kh(t)}catch(t){throw new Error(e+" must be hex string or Uint8Array, cause: "+t)}else{if(!th(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 pg(e){return Uint8Array.from(e)}const fg=e=>"bigint"==typeof e&&rg<=e;function mg(e,t,n,r){if(!function(e,t,n){return fg(e)&&fg(t)&&fg(n)&&t<=e&&e<n}(t,n,r))throw new Error("expected valid "+e+": "+n+" <= n < "+r+", got "+t)}function yg(e){let t;for(t=0;e>rg;e>>=ig,t+=1);return t}const wg=e=>(ig<<BigInt(e))-ig;function kg(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 o=typeof i;if(o!==n||null===i)throw new Error(`param "${t}" is invalid: expected ${n}, got ${o}`)}Object.entries(t).forEach(([e,t])=>r(e,t,!1)),Object.entries(n).forEach(([e,t])=>r(e,t,!0))}function bg(e){const t=new WeakMap;return(n,...r)=>{const i=t.get(n);if(void 0!==i)return i;const o=e(n,...r);return t.set(n,o),o}}const vg=BigInt(0),Sg=BigInt(1),Ag=BigInt(2),Tg=BigInt(3),Eg=BigInt(4),Ig=BigInt(5),xg=BigInt(7),Cg=BigInt(8),Ng=BigInt(9),_g=BigInt(16);function Bg(e,t){const n=e%t;return n>=vg?n:t+n}function Pg(e,t,n){let r=e;for(;t-- >vg;)r*=r,r%=n;return r}function Dg(e,t){if(e===vg)throw new Error("invert: expected non-zero number");if(t<=vg)throw new Error("invert: expected positive modulus, got "+t);let n=Bg(e,t),r=t,i=vg,o=Sg;for(;n!==vg;){const e=r%n,t=i-o*(r/n);r=n,n=e,i=o,o=t}if(r!==Sg)throw new Error("invert: does not exist");return Bg(i,t)}function Rg(e,t,n){if(!e.eql(e.sqr(t),n))throw new Error("Cannot find square root")}function Mg(e,t){const n=(e.ORDER+Sg)/Eg,r=e.pow(t,n);return Rg(e,r,t),r}function Lg(e,t){const n=(e.ORDER-Ig)/Cg,r=e.mul(t,Ag),i=e.pow(r,n),o=e.mul(t,i),s=e.mul(e.mul(o,Ag),i),a=e.mul(o,e.sub(s,e.ONE));return Rg(e,a,t),a}function Og(e){if(e<Tg)throw new Error("sqrt is not defined for small field");let t=e-Sg,n=0;for(;t%Ag===vg;)t/=Ag,n++;let r=Ag;const i=Gg(e);for(;1===qg(i,r);)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(1===n)return Mg;let o=i.pow(r,t);const s=(t+Sg)/Ag;return function(e,r){if(e.is0(r))return r;if(1!==qg(e,r))throw new Error("Cannot find square root");let i=n,a=e.mul(e.ONE,o),c=e.pow(r,t),l=e.pow(r,s);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=Sg<<BigInt(i-t-1),o=e.pow(a,r);i=t,a=e.sqr(o),c=e.mul(c,a),l=e.mul(l,o)}return l}}function Fg(e){return e%Eg===Tg?Mg:e%Cg===Ig?Lg:e%_g===Ng?function(e){const t=Gg(e),n=Og(e),r=n(t,t.neg(t.ONE)),i=n(t,r),o=n(t,t.neg(r)),s=(e+xg)/_g;return(e,t)=>{let n=e.pow(t,s),a=e.mul(n,r);const c=e.mul(n,i),l=e.mul(n,o),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 Rg(e,g,t),g}}(e):Og(e)}const Ug=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function $g(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),o=e.inv(i);return t.reduceRight((t,n,i)=>e.is0(n)?t:(r[i]=e.mul(t,r[i]),e.mul(t,n)),o),r}function qg(e,t){const n=(e.ORDER-Sg)/Ag,r=e.pow(t,n),i=e.eql(r,e.ONE),o=e.eql(r,e.ZERO),s=e.eql(r,e.neg(e.ONE));if(!i&&!o&&!s)throw new Error("invalid Legendre symbol result");return i?1:o?0:-1}function Kg(e,t){void 0!==t&&nh(t);const n=void 0!==t?t:e.toString(2).length;return{nBitLength:n,nByteLength:Math.ceil(n/8)}}function Gg(e,t,n=!1,r={}){if(e<=vg)throw new Error("invalid field: expected ORDER > 0, got "+e);let i,o,s,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&&(o=e.sqrt),"boolean"==typeof e.isLE&&(n=e.isLE),"boolean"==typeof e.modFromBytes&&(a=e.modFromBytes),s=e.allowedLengths}else"number"==typeof t&&(i=t),r.sqrt&&(o=r.sqrt);const{nBitLength:c,nByteLength:l}=Kg(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:wg(c),ZERO:vg,ONE:Sg,allowedLengths:s,create:t=>Bg(t,e),isValid:t=>{if("bigint"!=typeof t)throw new Error("invalid field element: expected bigint, got "+typeof t);return vg<=t&&t<e},is0:e=>e===vg,isValidNot0:e=>!d.is0(e)&&d.isValid(e),isOdd:e=>(e&Sg)===Sg,neg:t=>Bg(-t,e),eql:(e,t)=>e===t,sqr:t=>Bg(t*t,e),add:(t,n)=>Bg(t+n,e),sub:(t,n)=>Bg(t-n,e),mul:(t,n)=>Bg(t*n,e),pow:(e,t)=>function(e,t,n){if(n<vg)throw new Error("invalid exponent, negatives unsupported");if(n===vg)return e.ONE;if(n===Sg)return t;let r=e.ONE,i=t;for(;n>vg;)n&Sg&&(r=e.mul(r,i)),i=e.sqr(i),n>>=Sg;return r}(d,e,t),div:(t,n)=>Bg(t*Dg(n,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>Dg(t,e),sqrt:o||(t=>(u||(u=Fg(e)),u(d,t))),toBytes:e=>n?hg(e,l):dg(e,l),fromBytes:(t,r=!0)=>{if(s){if(!s.includes(t.length)||t.length>l)throw new Error("Field.fromBytes: expected "+s+" 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?ug(t):lg(t);if(a&&(i=Bg(i,e)),!r&&!d.isValid(i))throw new Error("invalid field element: outside of range 0..ORDER");return i},invertBatch:e=>$g(d,e),cmov:(e,t,n)=>n?t:e});return Object.freeze(d)}function Wg(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 zg(e){const t=Wg(e);return t+Math.ceil(t/2)}const Hg=BigInt(0),jg=BigInt(1);function Vg(e,t){const n=t.negate();return e?n:t}function Xg(e,t){const n=$g(e.Fp,t.map(e=>e.Z));return t.map((t,r)=>e.fromAffine(t.toAffine(n[r])))}function Qg(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function Jg(e,t){Qg(e,t);const n=2**e;return{windows:Math.ceil(t/e)+1,windowSize:2**(e-1),mask:wg(e),maxNumber:n,shiftBy:BigInt(e)}}function Zg(e,t,n){const{windowSize:r,mask:i,maxNumber:o,shiftBy:s}=n;let a=Number(e&i),c=e>>s;a>r&&(a-=o,c+=jg);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 Yg=new WeakMap,ep=new WeakMap;function tp(e){return ep.get(e)||1}function np(e){if(e!==Hg)throw new Error("invalid wNAF")}class rp{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>Hg;)t&jg&&(n=n.add(r)),r=r.double(),t>>=jg;return n}precomputeWindow(e,t){const{windows:n,windowSize:r}=Jg(t,this.bits),i=[];let o=e,s=o;for(let e=0;e<n;e++){s=o,i.push(s);for(let e=1;e<r;e++)s=s.add(o),i.push(s);o=s.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 o=Jg(e,this.bits);for(let e=0;e<o.windows;e++){const{nextN:s,offset:a,isZero:c,isNeg:l,isNegF:u,offsetF:d}=Zg(n,e,o);n=s,c?i=i.add(Vg(u,t[d])):r=r.add(Vg(l,t[a]))}return np(n),{p:r,f:i}}wNAFUnsafe(e,t,n,r=this.ZERO){const i=Jg(e,this.bits);for(let e=0;e<i.windows&&n!==Hg;e++){const{nextN:o,offset:s,isZero:a,isNeg:c}=Zg(n,e,i);if(n=o,!a){const e=t[s];r=r.add(c?e.negate():e)}}return np(n),r}getPrecomputes(e,t,n){let r=Yg.get(t);return r||(r=this.precomputeWindow(t,e),1!==e&&("function"==typeof n&&(r=n(r)),Yg.set(t,r))),r}cached(e,t,n){const r=tp(e);return this.wNAF(r,this.getPrecomputes(r,e,n),t)}unsafe(e,t,n,r){const i=tp(e);return 1===i?this._unsafeLadder(e,t,r):this.wNAFUnsafe(i,this.getPrecomputes(i,e,n),t,r)}createCache(e,t){Qg(t,this.bits),ep.set(e,t),Yg.delete(e)}hasCache(e){return 1!==tp(e)}}function ip(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,o=r.length;if(i!==o)throw new Error("arrays of points and scalars must have equal length");const s=e.ZERO,a=yg(BigInt(i));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const l=wg(c),u=new Array(Number(l)+1).fill(s);let d=s;for(let e=Math.floor((t.BITS-1)/c)*c;e>=0;e-=c){u.fill(s);for(let t=0;t<o;t++){const i=r[t],o=Number(i>>BigInt(e)&l);u[o]=u[o].add(n[t])}let t=s;for(let e=u.length-1,n=s;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 op(e,t,n){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return function(e){kg(e,Ug.reduce((e,t)=>(e[t]="function",e),{ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"}))}(t),t}return Gg(e,{isLE:n})}function sp(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>Hg))throw new Error(`CURVE.${e} must be positive bigint`)}const i=op(t.p,n.Fp,r),o=op(t.n,n.Fn,r),s=["Gx","Gy","a","weierstrass"===e?"b":"d"];for(const e of s)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:o}}const ap=BigInt(0),cp=BigInt(1),lp=BigInt(2),up=BigInt(8);function dp(e,t,n={}){if("function"!=typeof t)throw new Error('"hash" function param is required');kg(n,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});const{prehash:r}=n,{BASE:i,Fp:o,Fn:s}=e,a=n.randomBytes||Th,c=n.adjustScalarBytes||(e=>e),l=n.domain||((e,t,n)=>{if(og(n,"phflag"),t.length||n)throw new Error("Contexts/pre-hash are not supported");return e});function u(e){return s.create(ug(e))}function d(e){const{head:n,prefix:r,scalar:o}=function(e){const n=m.secretKey;e=gg("private key",e,n);const r=gg("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),s=i.multiply(o),a=s.toBytes();return{head:n,prefix:r,scalar:o,point:s,pointBytes:a}}function h(e){return d(e).pointBytes}function g(e=Uint8Array.of(),...n){const i=vh(...n);return u(t(l(i,gg("context",e),!!r)))}const p={zip215:!0};const f=o.BYTES,m={secretKey:f,publicKey:f,signature:2*f,seed:f};function y(e=a(m.seed)){return sg(e,m.seed,"seed")}const w={getExtendedPublicKey:d,randomSecretKey:y,isValidSecretKey:function(e){return th(e)&&e.length===s.BYTES},isValidPublicKey:function(t,n){try{return!!e.fromBytes(t,n)}catch(e){return!1}},toMontgomery(t){const{y:n}=e.fromBytes(t),r=m.publicKey,i=32===r;if(!i&&57!==r)throw new Error("only defined for 25519 and 448");const s=i?o.div(cp+n,cp-n):o.div(n-cp,n+cp);return o.toBytes(s)},toMontgomerySecret(e){const n=m.secretKey;sg(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=w.randomSecretKey(e);return{secretKey:t,publicKey:h(t)}},getPublicKey:h,sign:function(e,t,n={}){e=gg("message",e),r&&(e=r(e));const{prefix:o,scalar:a,pointBytes:c}=d(t),l=g(n.context,o,e),u=i.multiply(l).toBytes(),h=g(n.context,u,c,e),p=s.create(l+h*a);if(!s.isValid(p))throw new Error("sign failed: invalid s");return sg(vh(u,s.toBytes(p)),m.signature,"result")},verify:function(t,n,o,s=p){const{context:a,zip215:c}=s,l=m.signature;t=gg("signature",t,l),n=gg("message",n),o=gg("publicKey",o,m.publicKey),void 0!==c&&og(c,"zip215"),r&&(n=r(n));const u=l/2,d=t.subarray(0,u),h=ug(t.subarray(u,l));let f,y,w;try{f=e.fromBytes(o,c),y=e.fromBytes(d,c),w=i.multiplyUnsafe(h)}catch(e){return!1}if(!c&&f.isSmallOrder())return!1;const k=g(a,y.toBytes(),f.toBytes(),n);return y.add(f.multiplyUnsafe(k)).subtract(w).clearCofactor().is0()},utils:w,Point:e,lengths:m})}function hp(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:Gg(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),o=function(e,t={}){const n=sp("edwards",e,t,t.FpFnLE),{Fp:r,Fn:i}=n;let o=n.CURVE;const{h:s}=o;kg(t,{},{uvRatio:"function"});const a=lp<<BigInt(8*i.BYTES)-cp,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:ap}}});if(!function(e,t,n,r){const i=e.sqr(n),o=e.sqr(r),s=e.add(e.mul(t.a,i),o),a=e.add(e.ONE,e.mul(t.d,e.mul(i,o)));return e.eql(s,a)}(r,o,o.Gx,o.Gy))throw new Error("bad curve params: generator point");function u(e,t,n=!1){return mg("coordinate "+e,t,n?cp:ap,a),t}function d(e){if(!(e instanceof p))throw new Error("ExtendedPoint expected")}const h=bg((e,t)=>{const{X:n,Y:i,Z:o}=e,s=e.is0();null==t&&(t=s?up:r.inv(o));const a=c(n*t),l=c(i*t),u=r.mul(o,t);if(s)return{x:ap,y:cp};if(u!==cp)throw new Error("invZ was invalid");return{x:a,y:l}}),g=bg(e=>{const{a:t,d:n}=o;if(e.is0())throw new Error("bad point: ZERO");const{X:r,Y:i,Z:s,T:a}=e,l=c(r*r),u=c(i*i),d=c(s*s),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(s*a))throw new Error("bad point: equation left != right (2)");return!0});class p{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 o}static fromAffine(e){if(e instanceof p)throw new Error("extended point not allowed");const{x:t,y:n}=e||{};return u("x",t),u("y",n),new p(t,n,cp,c(t*n))}static fromBytes(e,t=!1){const n=r.BYTES,{a:i,d:s}=o;e=pg(sg(e,n,"point")),og(t,"zip215");const u=pg(e),d=e[n-1];u[n-1]=-129&d;const h=ug(u),g=t?a:r.ORDER;mg("point.y",h,ap,g);const f=c(h*h),m=c(f-cp),y=c(s*f-i);let{isValid:w,value:k}=l(m,y);if(!w)throw new Error("bad point: invalid y coordinate");const b=(k&cp)===cp,v=!!(128&d);if(!t&&k===ap&&v)throw new Error("bad point: x=0 and x_0=1");return v!==b&&(k=c(-k)),p.fromAffine({x:k,y:h})}static fromHex(e,t=!1){return p.fromBytes(gg("point",e),t)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(e=8,t=!0){return f.createCache(this,e),t||this.multiply(lp),this}assertValidity(){g(this)}equals(e){d(e);const{X:t,Y:n,Z:r}=this,{X:i,Y:o,Z:s}=e,a=c(t*s),l=c(i*r),u=c(n*s),h=c(o*r);return a===l&&u===h}is0(){return this.equals(p.ZERO)}negate(){return new p(c(-this.X),this.Y,this.Z,c(-this.T))}double(){const{a:e}=o,{X:t,Y:n,Z:r}=this,i=c(t*t),s=c(n*n),a=c(lp*c(r*r)),l=c(e*i),u=t+n,d=c(c(u*u)-i-s),h=l+s,g=h-a,f=l-s,m=c(d*g),y=c(h*f),w=c(d*f),k=c(g*h);return new p(m,y,k,w)}add(e){d(e);const{a:t,d:n}=o,{X:r,Y:i,Z:s,T:a}=this,{X:l,Y:u,Z:h,T:g}=e,f=c(r*l),m=c(i*u),y=c(a*n*g),w=c(s*h),k=c((r+i)*(l+u)-f-m),b=w-y,v=w+y,S=c(m-t*f),A=c(k*b),T=c(v*S),E=c(k*S),I=c(b*v);return new p(A,T,I,E)}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}=f.cached(this,e,e=>Xg(p,e));return Xg(p,[t,n])[0]}multiplyUnsafe(e,t=p.ZERO){if(!i.isValid(e))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return e===ap?p.ZERO:this.is0()||e===cp?this:f.unsafe(this,e,e=>Xg(p,e),t)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}isTorsionFree(){return f.unsafe(this,o.n).is0()}toAffine(e){return h(this,e)}clearCofactor(){return s===cp?this:this.multiplyUnsafe(s)}toBytes(){const{x:e,y:t}=this.toAffine(),n=r.toBytes(t);return n[n.length-1]|=e&cp?128:0,n}toHex(){return dh(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 Xg(p,e)}static msm(e,t){return ip(p,i,e,t)}_setWindowSize(e){this.precompute(e)}toRawBytes(){return this.toBytes()}}p.BASE=new p(o.Gx,o.Gy,cp,c(o.Gx*o.Gy)),p.ZERO=new p(ap,cp,cp,ap),p.Fp=r,p.Fn=i;const f=new rp(p,i.BITS);return p.BASE.precompute(8),p}(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,dp(o,r,i))}const gp=BigInt(1),pp=BigInt(2);BigInt(3);const fp=BigInt(5),mp=BigInt(8),yp=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),wp=(()=>({p:yp,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:mp,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")}))();function kp(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}const bp=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function vp(e,t){const n=yp,r=Bg(t*t*t,n),i=function(e){const t=BigInt(10),n=BigInt(20),r=BigInt(40),i=BigInt(80),o=yp,s=e*e%o*e%o,a=Pg(s,pp,o)*s%o,c=Pg(a,gp,o)*e%o,l=Pg(c,fp,o)*c%o,u=Pg(l,t,o)*l%o,d=Pg(u,n,o)*u%o,h=Pg(d,r,o)*d%o,g=Pg(h,i,o)*h%o,p=Pg(g,i,o)*h%o,f=Pg(p,t,o)*l%o;return{pow_p_5_8:Pg(f,pp,o)*e%o,b2:s}}(e*Bg(r*r*t,n)).pow_p_5_8;let o=Bg(e*r*i,n);const s=Bg(t*o*o,n),a=o,c=Bg(o*bp,n),l=s===e,u=s===Bg(-e,n),d=s===Bg(-e*bp,n);return l&&(o=a),(u||d)&&(o=c),(Bg(o,n)&Sg)===Sg&&(o=Bg(-o,n)),{isValid:l||u,value:o}}const Sp=(()=>Gg(wp.p,{isLE:!0}))(),Ap=(()=>({...wp,Fp:Sp,hash:ng,adjustScalarBytes:kp,uvRatio:vp}))(),Tp=(()=>hp(Ap))();var Ep,Ip={exports:{}},xp=Uc(Object.freeze({__proto__:null,default:{}})),Cp=Ip.exports;function Np(){return Ep||(Ep=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 o;"object"==typeof e?e.exports=i:t.BN=i,i.BN=i,i.wordSize=26;try{o="undefined"!=typeof window&&void 0!==window.Buffer?window.Buffer:xp.Buffer}catch(e){}function s(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=s(e,n);return n-1>=t&&(r|=s(e,n-1)<<4),r}function c(e,t,r,i){for(var o=0,s=0,a=Math.min(e.length,r),c=t;c<a;c++){var l=e.charCodeAt(c)-48;o*=i,s=l>=49?l-49+10:l>=17?l-17+10:l,n(l>=0&&s<i,"Invalid character"),o+=s}return o}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 o,s,a=0;if("be"===r)for(i=e.length-1,o=0;i>=0;i-=3)s=e[i]|e[i-1]<<8|e[i-2]<<16,this.words[o]|=s<<a&67108863,this.words[o+1]=s>>>26-a&67108863,(a+=24)>=26&&(a-=26,o++);else if("le"===r)for(i=0,o=0;i<e.length;i+=3)s=e[i]|e[i+1]<<8|e[i+2]<<16,this.words[o]|=s<<a&67108863,this.words[o+1]=s>>>26-a&67108863,(a+=24)>=26&&(a-=26,o++);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,o=0,s=0;if("be"===n)for(r=e.length-1;r>=t;r-=2)i=a(e,t,r)<<o,this.words[s]|=67108863&i,o>=18?(o-=18,s+=1,this.words[s]|=i>>>26):o+=8;else for(r=(e.length-t)%2==0?t+1:t;r<e.length;r+=2)i=a(e,t,r)<<o,this.words[s]|=67108863&i,o>=18?(o-=18,s+=1,this.words[s]|=i>>>26):o+=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 o=e.length-n,s=o%r,a=Math.min(o,o-s)+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!==s){var d=1;for(l=c(e,u,e.length,t),u=0;u<s;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 p(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],o=0|t.words[0],s=i*o,a=67108863&s,c=s/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 p=l-g|0;u+=(s=(i=0|e.words[p])*(o=0|t.words[g])+d)/67108864|0,d=67108863&s}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,o=0,s=0;s<this.length;s++){var a=this.words[s],c=(16777215&(a<<i|o)).toString(16);o=a>>>24-i&16777215,(i+=2)>=26&&(i-=26,s--),r=0!==o||s!==this.length-1?d[6-c.length]+c+r:c+r}for(0!==o&&(r=o.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 p=this.clone();for(p.negative=0;!p.isZero();){var f=p.modrn(u).toString(e);r=(p=p.idivn(u)).isZero()?f+r:d[l-f.length]+f+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)},o&&(i.prototype.toBuffer=function(e,t){return this.toArrayLike(o,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(),o=r||Math.max(1,i);n(i<=o,"byte array longer than desired length"),n(o>0,"Requested array length <= 0");var s=function(e,t){return e.allocUnsafe?e.allocUnsafe(t):new e(t)}(e,o);return this["_toArrayLike"+("le"===t?"LE":"BE")](s,i),s},i.prototype._toArrayLikeLE=function(e,t){for(var n=0,r=0,i=0,o=0;i<this.length;i++){var s=this.words[i]<<o|r;e[n++]=255&s,n<e.length&&(e[n++]=s>>8&255),n<e.length&&(e[n++]=s>>16&255),6===o?(n<e.length&&(e[n++]=s>>24&255),r=0,o=0):(r=s>>>24,o+=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,o=0;i<this.length;i++){var s=this.words[i]<<o|r;e[n--]=255&s,n>=0&&(e[n--]=s>>8&255),n>=0&&(e[n--]=s>>16&255),6===o?(n>=0&&(e[n--]=s>>24&255),r=0,o=0):(r=s>>>24,o+=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];return r>0&&(this.words[i]=~this.words[i]&67108863>>26-r),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,o=0;o<r.length;o++)t=(0|n.words[o])+(0|r.words[o])+i,this.words[o]=67108863&t,i=t>>>26;for(;0!==i&&o<n.length;o++)t=(0|n.words[o])+i,this.words[o]=67108863&t,i=t>>>26;if(this.length=n.length,0!==i)this.words[this.length]=i,this.length++;else if(n!==this)for(;o<n.length;o++)this.words[o]=n.words[o];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 o=0,s=0;s<r.length;s++)o=(t=(0|n.words[s])-(0|r.words[s])+o)>>26,this.words[s]=67108863&t;for(;0!==o&&s<n.length;s++)o=(t=(0|n.words[s])+o)>>26,this.words[s]=67108863&t;if(0===o&&s<n.length&&n!==this)for(;s<n.length;s++)this.words[s]=n.words[s];return this.length=Math.max(this.length,s),n!==this&&(this.negative=1),this._strip()},i.prototype.sub=function(e){return this.clone().isub(e)};var f=function(e,t,n){var r,i,o,s=e.words,a=t.words,c=n.words,l=0,u=0|s[0],d=8191&u,h=u>>>13,g=0|s[1],p=8191&g,f=g>>>13,m=0|s[2],y=8191&m,w=m>>>13,k=0|s[3],b=8191&k,v=k>>>13,S=0|s[4],A=8191&S,T=S>>>13,E=0|s[5],I=8191&E,x=E>>>13,C=0|s[6],N=8191&C,_=C>>>13,B=0|s[7],P=8191&B,D=B>>>13,R=0|s[8],M=8191&R,L=R>>>13,O=0|s[9],F=8191&O,U=O>>>13,$=0|a[0],q=8191&$,K=$>>>13,G=0|a[1],W=8191&G,z=G>>>13,H=0|a[2],j=8191&H,V=H>>>13,X=0|a[3],Q=8191&X,J=X>>>13,Z=0|a[4],Y=8191&Z,ee=Z>>>13,te=0|a[5],ne=8191&te,re=te>>>13,ie=0|a[6],oe=8191&ie,se=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],pe=8191&ge,fe=ge>>>13;n.negative=e.negative^t.negative,n.length=19;var me=(l+(r=Math.imul(d,q))|0)+((8191&(i=(i=Math.imul(d,K))+Math.imul(h,q)|0))<<13)|0;l=((o=Math.imul(h,K))+(i>>>13)|0)+(me>>>26)|0,me&=67108863,r=Math.imul(p,q),i=(i=Math.imul(p,K))+Math.imul(f,q)|0,o=Math.imul(f,K);var ye=(l+(r=r+Math.imul(d,W)|0)|0)+((8191&(i=(i=i+Math.imul(d,z)|0)+Math.imul(h,W)|0))<<13)|0;l=((o=o+Math.imul(h,z)|0)+(i>>>13)|0)+(ye>>>26)|0,ye&=67108863,r=Math.imul(y,q),i=(i=Math.imul(y,K))+Math.imul(w,q)|0,o=Math.imul(w,K),r=r+Math.imul(p,W)|0,i=(i=i+Math.imul(p,z)|0)+Math.imul(f,W)|0,o=o+Math.imul(f,z)|0;var we=(l+(r=r+Math.imul(d,j)|0)|0)+((8191&(i=(i=i+Math.imul(d,V)|0)+Math.imul(h,j)|0))<<13)|0;l=((o=o+Math.imul(h,V)|0)+(i>>>13)|0)+(we>>>26)|0,we&=67108863,r=Math.imul(b,q),i=(i=Math.imul(b,K))+Math.imul(v,q)|0,o=Math.imul(v,K),r=r+Math.imul(y,W)|0,i=(i=i+Math.imul(y,z)|0)+Math.imul(w,W)|0,o=o+Math.imul(w,z)|0,r=r+Math.imul(p,j)|0,i=(i=i+Math.imul(p,V)|0)+Math.imul(f,j)|0,o=o+Math.imul(f,V)|0;var ke=(l+(r=r+Math.imul(d,Q)|0)|0)+((8191&(i=(i=i+Math.imul(d,J)|0)+Math.imul(h,Q)|0))<<13)|0;l=((o=o+Math.imul(h,J)|0)+(i>>>13)|0)+(ke>>>26)|0,ke&=67108863,r=Math.imul(A,q),i=(i=Math.imul(A,K))+Math.imul(T,q)|0,o=Math.imul(T,K),r=r+Math.imul(b,W)|0,i=(i=i+Math.imul(b,z)|0)+Math.imul(v,W)|0,o=o+Math.imul(v,z)|0,r=r+Math.imul(y,j)|0,i=(i=i+Math.imul(y,V)|0)+Math.imul(w,j)|0,o=o+Math.imul(w,V)|0,r=r+Math.imul(p,Q)|0,i=(i=i+Math.imul(p,J)|0)+Math.imul(f,Q)|0,o=o+Math.imul(f,J)|0;var be=(l+(r=r+Math.imul(d,Y)|0)|0)+((8191&(i=(i=i+Math.imul(d,ee)|0)+Math.imul(h,Y)|0))<<13)|0;l=((o=o+Math.imul(h,ee)|0)+(i>>>13)|0)+(be>>>26)|0,be&=67108863,r=Math.imul(I,q),i=(i=Math.imul(I,K))+Math.imul(x,q)|0,o=Math.imul(x,K),r=r+Math.imul(A,W)|0,i=(i=i+Math.imul(A,z)|0)+Math.imul(T,W)|0,o=o+Math.imul(T,z)|0,r=r+Math.imul(b,j)|0,i=(i=i+Math.imul(b,V)|0)+Math.imul(v,j)|0,o=o+Math.imul(v,V)|0,r=r+Math.imul(y,Q)|0,i=(i=i+Math.imul(y,J)|0)+Math.imul(w,Q)|0,o=o+Math.imul(w,J)|0,r=r+Math.imul(p,Y)|0,i=(i=i+Math.imul(p,ee)|0)+Math.imul(f,Y)|0,o=o+Math.imul(f,ee)|0;var ve=(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=((o=o+Math.imul(h,re)|0)+(i>>>13)|0)+(ve>>>26)|0,ve&=67108863,r=Math.imul(N,q),i=(i=Math.imul(N,K))+Math.imul(_,q)|0,o=Math.imul(_,K),r=r+Math.imul(I,W)|0,i=(i=i+Math.imul(I,z)|0)+Math.imul(x,W)|0,o=o+Math.imul(x,z)|0,r=r+Math.imul(A,j)|0,i=(i=i+Math.imul(A,V)|0)+Math.imul(T,j)|0,o=o+Math.imul(T,V)|0,r=r+Math.imul(b,Q)|0,i=(i=i+Math.imul(b,J)|0)+Math.imul(v,Q)|0,o=o+Math.imul(v,J)|0,r=r+Math.imul(y,Y)|0,i=(i=i+Math.imul(y,ee)|0)+Math.imul(w,Y)|0,o=o+Math.imul(w,ee)|0,r=r+Math.imul(p,ne)|0,i=(i=i+Math.imul(p,re)|0)+Math.imul(f,ne)|0,o=o+Math.imul(f,re)|0;var Se=(l+(r=r+Math.imul(d,oe)|0)|0)+((8191&(i=(i=i+Math.imul(d,se)|0)+Math.imul(h,oe)|0))<<13)|0;l=((o=o+Math.imul(h,se)|0)+(i>>>13)|0)+(Se>>>26)|0,Se&=67108863,r=Math.imul(P,q),i=(i=Math.imul(P,K))+Math.imul(D,q)|0,o=Math.imul(D,K),r=r+Math.imul(N,W)|0,i=(i=i+Math.imul(N,z)|0)+Math.imul(_,W)|0,o=o+Math.imul(_,z)|0,r=r+Math.imul(I,j)|0,i=(i=i+Math.imul(I,V)|0)+Math.imul(x,j)|0,o=o+Math.imul(x,V)|0,r=r+Math.imul(A,Q)|0,i=(i=i+Math.imul(A,J)|0)+Math.imul(T,Q)|0,o=o+Math.imul(T,J)|0,r=r+Math.imul(b,Y)|0,i=(i=i+Math.imul(b,ee)|0)+Math.imul(v,Y)|0,o=o+Math.imul(v,ee)|0,r=r+Math.imul(y,ne)|0,i=(i=i+Math.imul(y,re)|0)+Math.imul(w,ne)|0,o=o+Math.imul(w,re)|0,r=r+Math.imul(p,oe)|0,i=(i=i+Math.imul(p,se)|0)+Math.imul(f,oe)|0,o=o+Math.imul(f,se)|0;var Ae=(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=((o=o+Math.imul(h,le)|0)+(i>>>13)|0)+(Ae>>>26)|0,Ae&=67108863,r=Math.imul(M,q),i=(i=Math.imul(M,K))+Math.imul(L,q)|0,o=Math.imul(L,K),r=r+Math.imul(P,W)|0,i=(i=i+Math.imul(P,z)|0)+Math.imul(D,W)|0,o=o+Math.imul(D,z)|0,r=r+Math.imul(N,j)|0,i=(i=i+Math.imul(N,V)|0)+Math.imul(_,j)|0,o=o+Math.imul(_,V)|0,r=r+Math.imul(I,Q)|0,i=(i=i+Math.imul(I,J)|0)+Math.imul(x,Q)|0,o=o+Math.imul(x,J)|0,r=r+Math.imul(A,Y)|0,i=(i=i+Math.imul(A,ee)|0)+Math.imul(T,Y)|0,o=o+Math.imul(T,ee)|0,r=r+Math.imul(b,ne)|0,i=(i=i+Math.imul(b,re)|0)+Math.imul(v,ne)|0,o=o+Math.imul(v,re)|0,r=r+Math.imul(y,oe)|0,i=(i=i+Math.imul(y,se)|0)+Math.imul(w,oe)|0,o=o+Math.imul(w,se)|0,r=r+Math.imul(p,ce)|0,i=(i=i+Math.imul(p,le)|0)+Math.imul(f,ce)|0,o=o+Math.imul(f,le)|0;var Te=(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=((o=o+Math.imul(h,he)|0)+(i>>>13)|0)+(Te>>>26)|0,Te&=67108863,r=Math.imul(F,q),i=(i=Math.imul(F,K))+Math.imul(U,q)|0,o=Math.imul(U,K),r=r+Math.imul(M,W)|0,i=(i=i+Math.imul(M,z)|0)+Math.imul(L,W)|0,o=o+Math.imul(L,z)|0,r=r+Math.imul(P,j)|0,i=(i=i+Math.imul(P,V)|0)+Math.imul(D,j)|0,o=o+Math.imul(D,V)|0,r=r+Math.imul(N,Q)|0,i=(i=i+Math.imul(N,J)|0)+Math.imul(_,Q)|0,o=o+Math.imul(_,J)|0,r=r+Math.imul(I,Y)|0,i=(i=i+Math.imul(I,ee)|0)+Math.imul(x,Y)|0,o=o+Math.imul(x,ee)|0,r=r+Math.imul(A,ne)|0,i=(i=i+Math.imul(A,re)|0)+Math.imul(T,ne)|0,o=o+Math.imul(T,re)|0,r=r+Math.imul(b,oe)|0,i=(i=i+Math.imul(b,se)|0)+Math.imul(v,oe)|0,o=o+Math.imul(v,se)|0,r=r+Math.imul(y,ce)|0,i=(i=i+Math.imul(y,le)|0)+Math.imul(w,ce)|0,o=o+Math.imul(w,le)|0,r=r+Math.imul(p,de)|0,i=(i=i+Math.imul(p,he)|0)+Math.imul(f,de)|0,o=o+Math.imul(f,he)|0;var Ee=(l+(r=r+Math.imul(d,pe)|0)|0)+((8191&(i=(i=i+Math.imul(d,fe)|0)+Math.imul(h,pe)|0))<<13)|0;l=((o=o+Math.imul(h,fe)|0)+(i>>>13)|0)+(Ee>>>26)|0,Ee&=67108863,r=Math.imul(F,W),i=(i=Math.imul(F,z))+Math.imul(U,W)|0,o=Math.imul(U,z),r=r+Math.imul(M,j)|0,i=(i=i+Math.imul(M,V)|0)+Math.imul(L,j)|0,o=o+Math.imul(L,V)|0,r=r+Math.imul(P,Q)|0,i=(i=i+Math.imul(P,J)|0)+Math.imul(D,Q)|0,o=o+Math.imul(D,J)|0,r=r+Math.imul(N,Y)|0,i=(i=i+Math.imul(N,ee)|0)+Math.imul(_,Y)|0,o=o+Math.imul(_,ee)|0,r=r+Math.imul(I,ne)|0,i=(i=i+Math.imul(I,re)|0)+Math.imul(x,ne)|0,o=o+Math.imul(x,re)|0,r=r+Math.imul(A,oe)|0,i=(i=i+Math.imul(A,se)|0)+Math.imul(T,oe)|0,o=o+Math.imul(T,se)|0,r=r+Math.imul(b,ce)|0,i=(i=i+Math.imul(b,le)|0)+Math.imul(v,ce)|0,o=o+Math.imul(v,le)|0,r=r+Math.imul(y,de)|0,i=(i=i+Math.imul(y,he)|0)+Math.imul(w,de)|0,o=o+Math.imul(w,he)|0;var Ie=(l+(r=r+Math.imul(p,pe)|0)|0)+((8191&(i=(i=i+Math.imul(p,fe)|0)+Math.imul(f,pe)|0))<<13)|0;l=((o=o+Math.imul(f,fe)|0)+(i>>>13)|0)+(Ie>>>26)|0,Ie&=67108863,r=Math.imul(F,j),i=(i=Math.imul(F,V))+Math.imul(U,j)|0,o=Math.imul(U,V),r=r+Math.imul(M,Q)|0,i=(i=i+Math.imul(M,J)|0)+Math.imul(L,Q)|0,o=o+Math.imul(L,J)|0,r=r+Math.imul(P,Y)|0,i=(i=i+Math.imul(P,ee)|0)+Math.imul(D,Y)|0,o=o+Math.imul(D,ee)|0,r=r+Math.imul(N,ne)|0,i=(i=i+Math.imul(N,re)|0)+Math.imul(_,ne)|0,o=o+Math.imul(_,re)|0,r=r+Math.imul(I,oe)|0,i=(i=i+Math.imul(I,se)|0)+Math.imul(x,oe)|0,o=o+Math.imul(x,se)|0,r=r+Math.imul(A,ce)|0,i=(i=i+Math.imul(A,le)|0)+Math.imul(T,ce)|0,o=o+Math.imul(T,le)|0,r=r+Math.imul(b,de)|0,i=(i=i+Math.imul(b,he)|0)+Math.imul(v,de)|0,o=o+Math.imul(v,he)|0;var xe=(l+(r=r+Math.imul(y,pe)|0)|0)+((8191&(i=(i=i+Math.imul(y,fe)|0)+Math.imul(w,pe)|0))<<13)|0;l=((o=o+Math.imul(w,fe)|0)+(i>>>13)|0)+(xe>>>26)|0,xe&=67108863,r=Math.imul(F,Q),i=(i=Math.imul(F,J))+Math.imul(U,Q)|0,o=Math.imul(U,J),r=r+Math.imul(M,Y)|0,i=(i=i+Math.imul(M,ee)|0)+Math.imul(L,Y)|0,o=o+Math.imul(L,ee)|0,r=r+Math.imul(P,ne)|0,i=(i=i+Math.imul(P,re)|0)+Math.imul(D,ne)|0,o=o+Math.imul(D,re)|0,r=r+Math.imul(N,oe)|0,i=(i=i+Math.imul(N,se)|0)+Math.imul(_,oe)|0,o=o+Math.imul(_,se)|0,r=r+Math.imul(I,ce)|0,i=(i=i+Math.imul(I,le)|0)+Math.imul(x,ce)|0,o=o+Math.imul(x,le)|0,r=r+Math.imul(A,de)|0,i=(i=i+Math.imul(A,he)|0)+Math.imul(T,de)|0,o=o+Math.imul(T,he)|0;var Ce=(l+(r=r+Math.imul(b,pe)|0)|0)+((8191&(i=(i=i+Math.imul(b,fe)|0)+Math.imul(v,pe)|0))<<13)|0;l=((o=o+Math.imul(v,fe)|0)+(i>>>13)|0)+(Ce>>>26)|0,Ce&=67108863,r=Math.imul(F,Y),i=(i=Math.imul(F,ee))+Math.imul(U,Y)|0,o=Math.imul(U,ee),r=r+Math.imul(M,ne)|0,i=(i=i+Math.imul(M,re)|0)+Math.imul(L,ne)|0,o=o+Math.imul(L,re)|0,r=r+Math.imul(P,oe)|0,i=(i=i+Math.imul(P,se)|0)+Math.imul(D,oe)|0,o=o+Math.imul(D,se)|0,r=r+Math.imul(N,ce)|0,i=(i=i+Math.imul(N,le)|0)+Math.imul(_,ce)|0,o=o+Math.imul(_,le)|0,r=r+Math.imul(I,de)|0,i=(i=i+Math.imul(I,he)|0)+Math.imul(x,de)|0,o=o+Math.imul(x,he)|0;var Ne=(l+(r=r+Math.imul(A,pe)|0)|0)+((8191&(i=(i=i+Math.imul(A,fe)|0)+Math.imul(T,pe)|0))<<13)|0;l=((o=o+Math.imul(T,fe)|0)+(i>>>13)|0)+(Ne>>>26)|0,Ne&=67108863,r=Math.imul(F,ne),i=(i=Math.imul(F,re))+Math.imul(U,ne)|0,o=Math.imul(U,re),r=r+Math.imul(M,oe)|0,i=(i=i+Math.imul(M,se)|0)+Math.imul(L,oe)|0,o=o+Math.imul(L,se)|0,r=r+Math.imul(P,ce)|0,i=(i=i+Math.imul(P,le)|0)+Math.imul(D,ce)|0,o=o+Math.imul(D,le)|0,r=r+Math.imul(N,de)|0,i=(i=i+Math.imul(N,he)|0)+Math.imul(_,de)|0,o=o+Math.imul(_,he)|0;var _e=(l+(r=r+Math.imul(I,pe)|0)|0)+((8191&(i=(i=i+Math.imul(I,fe)|0)+Math.imul(x,pe)|0))<<13)|0;l=((o=o+Math.imul(x,fe)|0)+(i>>>13)|0)+(_e>>>26)|0,_e&=67108863,r=Math.imul(F,oe),i=(i=Math.imul(F,se))+Math.imul(U,oe)|0,o=Math.imul(U,se),r=r+Math.imul(M,ce)|0,i=(i=i+Math.imul(M,le)|0)+Math.imul(L,ce)|0,o=o+Math.imul(L,le)|0,r=r+Math.imul(P,de)|0,i=(i=i+Math.imul(P,he)|0)+Math.imul(D,de)|0,o=o+Math.imul(D,he)|0;var Be=(l+(r=r+Math.imul(N,pe)|0)|0)+((8191&(i=(i=i+Math.imul(N,fe)|0)+Math.imul(_,pe)|0))<<13)|0;l=((o=o+Math.imul(_,fe)|0)+(i>>>13)|0)+(Be>>>26)|0,Be&=67108863,r=Math.imul(F,ce),i=(i=Math.imul(F,le))+Math.imul(U,ce)|0,o=Math.imul(U,le),r=r+Math.imul(M,de)|0,i=(i=i+Math.imul(M,he)|0)+Math.imul(L,de)|0,o=o+Math.imul(L,he)|0;var Pe=(l+(r=r+Math.imul(P,pe)|0)|0)+((8191&(i=(i=i+Math.imul(P,fe)|0)+Math.imul(D,pe)|0))<<13)|0;l=((o=o+Math.imul(D,fe)|0)+(i>>>13)|0)+(Pe>>>26)|0,Pe&=67108863,r=Math.imul(F,de),i=(i=Math.imul(F,he))+Math.imul(U,de)|0,o=Math.imul(U,he);var De=(l+(r=r+Math.imul(M,pe)|0)|0)+((8191&(i=(i=i+Math.imul(M,fe)|0)+Math.imul(L,pe)|0))<<13)|0;l=((o=o+Math.imul(L,fe)|0)+(i>>>13)|0)+(De>>>26)|0,De&=67108863;var Re=(l+(r=Math.imul(F,pe))|0)+((8191&(i=(i=Math.imul(F,fe))+Math.imul(U,pe)|0))<<13)|0;return l=((o=Math.imul(U,fe))+(i>>>13)|0)+(Re>>>26)|0,Re&=67108863,c[0]=me,c[1]=ye,c[2]=we,c[3]=ke,c[4]=be,c[5]=ve,c[6]=Se,c[7]=Ae,c[8]=Te,c[9]=Ee,c[10]=Ie,c[11]=xe,c[12]=Ce,c[13]=Ne,c[14]=_e,c[15]=Be,c[16]=Pe,c[17]=De,c[18]=Re,0!==l&&(c[19]=l,n.length++),n};function m(e,t,n){n.negative=t.negative^e.negative,n.length=e.length+t.length;for(var r=0,i=0,o=0;o<n.length-1;o++){var s=i;i=0;for(var a=67108863&r,c=Math.min(o,t.length-1),l=Math.max(0,o-e.length+1);l<=c;l++){var u=o-l,d=(0|e.words[u])*(0|t.words[l]),h=67108863&d;a=67108863&(h=h+a|0),i+=(s=(s=s+(d/67108864|0)|0)+(h>>>26)|0)>>>26,s&=67108863}n.words[o]=a,r=s,s=i}return 0!==r?n.words[o]=r:n.length--,n._strip()}function y(e,t,n){return m(e,t,n)}Math.imul||(f=p),i.prototype.mulTo=function(e,t){var n=this.length+e.length;return 10===this.length&&10===e.length?f(this,e,t):n<63?p(this,e,t):n<1024?m(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 o=(0|this.words[i])*e,s=(67108863&o)+(67108863&r);r>>=26,r+=o/67108864|0,r+=s>>>26,this.words[i]=67108863&s}return 0!==r&&(this.words[i]=r,this.length++),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 o=n.sqr();r<t.length;r++,o=o.sqr())0!==t[r]&&(n=n.mul(o));return n},i.prototype.iushln=function(e){n("number"==typeof e&&e>=0);var t,r=e%26,i=(e-r)/26,o=67108863>>>26-r<<26-r;if(0!==r){var s=0;for(t=0;t<this.length;t++){var a=this.words[t]&o,c=(0|this.words[t])-a<<r;this.words[t]=c|s,s=a>>>26-r}s&&(this.words[t]=s,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 o=e%26,s=Math.min((e-o)/26,this.length),a=67108863^67108863>>>o<<o,c=r;if(i-=s,i=Math.max(0,i),c){for(var l=0;l<s;l++)c.words[l]=this.words[l];c.length=s}if(0===s);else if(this.length>s)for(this.length-=s,l=0;l<this.length;l++)this.words[l]=this.words[l+s];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-o|d>>>o,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 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,o,s=e.length+r;this._expand(s);var a=0;for(i=0;i<e.length;i++){o=(0|this.words[i+r])+a;var c=(0|e.words[i])*t;a=((o-=67108863&c)>>26)-(c/67108864|0),this.words[i+r]=67108863&o}for(;i<this.length-r;i++)a=(o=(0|this.words[i+r])+a)>>26,this.words[i+r]=67108863&o;if(0===a)return this._strip();for(n(-1===a),a=0,i=0;i<this.length;i++)a=(o=-(0|this.words[i])+a)>>26,this.words[i]=67108863&o;return this.negative=1,this._strip()},i.prototype._wordDiv=function(e,t){var n=(this.length,e.length),r=this.clone(),o=e,s=0|o.words[o.length-1];0!=(n=26-this._countBits(s))&&(o=o.ushln(n),r.iushln(n),s=0|o.words[o.length-1]);var a,c=r.length-o.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(o,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[o.length+d])+(0|r.words[o.length+d-1]);for(h=Math.min(h/s|0,67108863),r._ishlnsubmul(o,h,d);0!==r.negative;)h--,r.negative=0,r._ishlnsubmul(o,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&&(o=a.div.neg()),"div"!==t&&(s=a.mod.neg(),r&&0!==s.negative&&s.iadd(e)),{div:o,mod:s}):0===this.negative&&0!==e.negative?(a=this.divmod(e.neg(),t),"mod"!==t&&(o=a.div.neg()),{div:o,mod:a.mod}):0!==(this.negative&e.negative)?(a=this.neg().divmod(e.neg(),t),"div"!==t&&(s=a.mod.neg(),r&&0!==s.negative&&s.isub(e)),{div:a.div,mod:s}):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 o,s,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=0!==t.div.negative?t.mod.isub(e):t.mod,r=e.ushrn(1),i=e.andln(1),o=n.cmp(r);return o<0||1===i&&0===o?t.div:0!==t.div.negative?t.div.isubn(1):t.div.iaddn(1)},i.prototype.modrn=function(e){var t=e<0;t&&(e=-e),n(e<=67108863);for(var r=(1<<26)%e,i=0,o=this.length-1;o>=0;o--)i=(r*i+(0|this.words[o]))%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 o=(0|this.words[i])+67108864*r;this.words[i]=o/e|0,r=o%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 o=new i(1),s=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;)(o.isOdd()||s.isOdd())&&(o.iadd(u),s.isub(d)),o.iushrn(1),s.iushrn(1);for(var p=0,f=1;0===(r.words[0]&f)&&p<26;++p,f<<=1);if(p>0)for(r.iushrn(p);p-- >0;)(a.isOdd()||c.isOdd())&&(a.iadd(u),c.isub(d)),a.iushrn(1),c.iushrn(1);t.cmp(r)>=0?(t.isub(r),o.isub(a),s.isub(c)):(r.isub(t),a.isub(o),c.isub(s))}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 o,s=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;)s.isOdd()&&s.iadd(c),s.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),s.isub(a)):(r.isub(t),a.isub(s))}return(o=0===t.cmpn(1)?s:a).cmpn(0)<0&&o.iadd(e),o},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 o=t;t=n,n=o}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 o=i,s=r;0!==o&&s<this.length;s++){var a=0|this.words[s];o=(a+=o)>>>26,a&=67108863,this.words[s]=a}return 0!==o&&(this.words[s]=o,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 T(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 w={k256:null,p224:null,p192:null,p25519:null};function k(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 b(){k.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function v(){k.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function S(){k.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function A(){k.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function T(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 E(e){T.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)}k.prototype._tmp=function(){var e=new i(null);return e.words=new Array(Math.ceil(this.n/13)),e},k.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},k.prototype.split=function(e,t){e.iushrn(this.n,0,t)},k.prototype.imulK=function(e){return e.imul(this.k)},r(b,k),b.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 o=e.words[9];for(t.words[t.length++]=o&n,i=10;i<e.length;i++){var s=0|e.words[i];e.words[i-10]=(s&n)<<4|o>>>22,o=s}o>>>=22,e.words[i-10]=o,0===o&&e.length>10?e.length-=10:e.length-=9},b.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(v,k),r(S,k),r(A,k),A.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(w[e])return w[e];var t;if("k256"===e)t=new b;else if("p224"===e)t=new v;else if("p192"===e)t=new S;else{if("p25519"!==e)throw new Error("Unknown prime "+e);t=new A}return w[e]=t,t},T.prototype._verify1=function(e){n(0===e.negative,"red works only with positives"),n(e.red,"red works only with red numbers")},T.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")},T.prototype.imod=function(e){return this.prime?this.prime.ireduce(e)._forceRed(this):(l(e,e.umod(this.m)._forceRed(this)),e)},T.prototype.neg=function(e){return e.isZero()?e.clone():this.m.sub(e)._forceRed(this)},T.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)},T.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},T.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)},T.prototype.isub=function(e,t){this._verify2(e,t);var n=e.isub(t);return n.cmpn(0)<0&&n.iadd(this.m),n},T.prototype.shl=function(e,t){return this._verify1(e),this.imod(e.ushln(t))},T.prototype.imul=function(e,t){return this._verify2(e,t),this.imod(e.imul(t))},T.prototype.mul=function(e,t){return this._verify2(e,t),this.imod(e.mul(t))},T.prototype.isqr=function(e){return this.imul(e,e.clone())},T.prototype.sqr=function(e){return this.mul(e,e)},T.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 o=this.m.subn(1),s=0;!o.isZero()&&0===o.andln(1);)s++,o.iushrn(1);n(!o.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,o),h=this.pow(e,o.addn(1).iushrn(1)),g=this.pow(e,o),p=s;0!==g.cmp(a);){for(var f=g,m=0;0!==f.cmp(a);m++)f=f.redSqr();n(m<p);var y=this.pow(d,new i(1).iushln(p-m-1));h=h.redMul(y),d=y.redSqr(),g=g.redMul(d),p=m}return h},T.prototype.invm=function(e){var t=e._invmp(this.m);return 0!==t.negative?(t.negative=0,this.imod(t).redNeg()):this.imod(t)},T.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 o=n[0],s=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;o!==n[0]&&(o=this.sqr(o)),0!==d||0!==s?(s<<=1,s|=d,(4===++a||0===r&&0===u)&&(o=this.mul(o,n[s]),a=0,s=0)):a=0}c=26}return o},T.prototype.convertTo=function(e){var t=e.umod(this.m);return t===e?t.clone():t},T.prototype.convertFrom=function(e){var t=e.clone();return t.red=null,t},i.mont=function(e){return new E(e)},r(E,T),E.prototype.convertTo=function(e){return this.imod(e.ushln(this.shift))},E.prototype.convertFrom=function(e){var t=this.imod(e.mul(this.rinv));return t.red=null,t},E.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),o=i;return i.cmp(this.m)>=0?o=i.isub(this.m):i.cmpn(0)<0&&(o=i.iadd(this.m)),o._forceRed(this)},E.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),o=n.isub(r).iushrn(this.shift),s=o;return o.cmp(this.m)>=0?s=o.isub(this.m):o.cmpn(0)<0&&(s=o.iadd(this.m)),s._forceRed(this)},E.prototype.invm=function(e){return this.imod(e._invmp(this.m).mul(this.r2))._forceRed(this)}}(Ip,Cp)),Ip.exports}var _p,Bp,Pp,Dp,Rp,Mp=Fc(Np()),Lp={exports:{}};function Op(){return _p||(_p=1,function(e,t){var n=Zd(),r=n.Buffer;function i(e,t){for(var n in e)t[n]=e[n]}function o(e,t,n){return r(e,t,n)}r.from&&r.alloc&&r.allocUnsafe&&r.allocUnsafeSlow?e.exports=n:(i(n,t),t.Buffer=o),i(r,o),o.from=function(e,t,n){if("number"==typeof e)throw new TypeError("Argument must not be a number");return r(e,t,n)},o.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},o.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return r(e)},o.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return n.SlowBuffer(e)}}(Lp,Lp.exports)),Lp.exports}var Fp=function(){if(Rp)return Dp;Rp=1;var e=function(){if(Pp)return Bp;Pp=1;var e=Op().Buffer;return Bp=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 o=t.charAt(i),s=o.charCodeAt(0);if(255!==n[s])throw new TypeError(o+" is ambiguous");n[s]=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,o=0;t[r]===c;)i++,r++;for(var s=(t.length-r)*l+1>>>0,u=new Uint8Array(s);r<t.length;){var d=t.charCodeAt(r);if(d>255)return;var h=n[d];if(255===h)return;for(var g=0,p=s-1;(0!==h||g<o)&&-1!==p;p--,g++)h+=a*u[p]>>>0,u[p]=h%256>>>0,h=h/256>>>0;if(0!==h)throw new Error("Non-zero carry");o=g,r++}for(var f=s-o;f!==s&&0===u[f];)f++;var m=e.allocUnsafe(i+(s-f));m.fill(0,0,i);for(var y=i;f!==s;)m[y++]=u[f++];return m}return{encode:function(n){if((Array.isArray(n)||n instanceof Uint8Array)&&(n=e.from(n)),!e.isBuffer(n))throw new TypeError("Expected Buffer");if(0===n.length)return"";for(var r=0,i=0,o=0,s=n.length;o!==s&&0===n[o];)o++,r++;for(var l=(s-o)*u+1>>>0,d=new Uint8Array(l);o!==s;){for(var h=n[o],g=0,p=l-1;(0!==h||g<i)&&-1!==p;p--,g++)h+=256*d[p]>>>0,d[p]=h%a>>>0,h=h/a>>>0;if(0!==h)throw new Error("Non-zero carry");i=g,o++}for(var f=l-i;f!==l&&0===d[f];)f++;for(var m=c.repeat(r);f<l;++f)m+=t.charAt(d[f]);return m},decodeUnsafe:d,decode:function(e){var t=d(e);if(t)return t;throw new Error("Non-base"+a+" character")}}},Bp}();return Dp=e("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")}(),Up=Fc(Fp);const $p=tg;var qp,Kp,Gp,Wp,zp={};function Hp(){if(Wp)return Gp;Wp=1;var e=function(){if(Kp)return qp;Kp=1;var e=Op().Buffer;return qp=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 o=t.charAt(i),s=o.charCodeAt(0);if(255!==n[s])throw new TypeError(o+" is ambiguous");n[s]=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,o=0;t[r]===c;)i++,r++;for(var s=(t.length-r)*l+1>>>0,u=new Uint8Array(s);r<t.length;){var d=t.charCodeAt(r);if(d>255)return;var h=n[d];if(255===h)return;for(var g=0,p=s-1;(0!==h||g<o)&&-1!==p;p--,g++)h+=a*u[p]>>>0,u[p]=h%256>>>0,h=h/256>>>0;if(0!==h)throw new Error("Non-zero carry");o=g,r++}for(var f=s-o;f!==s&&0===u[f];)f++;var m=e.allocUnsafe(i+(s-f));m.fill(0,0,i);for(var y=i;f!==s;)m[y++]=u[f++];return m}return{encode:function(n){if((Array.isArray(n)||n instanceof Uint8Array)&&(n=e.from(n)),!e.isBuffer(n))throw new TypeError("Expected Buffer");if(0===n.length)return"";for(var r=0,i=0,o=0,s=n.length;o!==s&&0===n[o];)o++,r++;for(var l=(s-o)*u+1>>>0,d=new Uint8Array(l);o!==s;){for(var h=n[o],g=0,p=l-1;(0!==h||g<i)&&-1!==p;p--,g++)h+=256*d[p]>>>0,d[p]=h%a>>>0,h=h/a>>>0;if(0!==h)throw new Error("Non-zero carry");i=g,o++}for(var f=l-i;f!==l&&0===d[f];)f++;for(var m=c.repeat(r);f<l;++f)m+=t.charAt(d[f]);return m},decodeUnsafe:d,decode:function(e){var t=d(e);if(t)return t;throw new Error("Non-base"+a+" character")}}},qp}();return Gp=e("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")}function jp(e,t,n){return t<=e&&e<=n}function Vp(e){if(void 0===e)return{};if(e===Object(e))return e;throw TypeError("Could not convert argument to dictionary")}function Xp(e){this.tokens=[].slice.call(e)}Xp.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 Qp=-1;function Jp(e,t){if(e)throw TypeError("Decoder error");return t||65533}var Zp="utf-8";function Yp(e,t){if(!(this instanceof Yp))return new Yp(e,t);if((e=void 0!==e?String(e).toLowerCase():Zp)!==Zp)throw new Error("Encoding not supported. Only utf-8 is supported");t=Vp(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 ef(e,t){if(!(this instanceof ef))return new ef(e,t);if((e=void 0!==e?String(e).toLowerCase():Zp)!==Zp)throw new Error("Encoding not supported. Only utf-8 is supported");t=Vp(t),this._streaming=!1,this._encoder=null,this._options={fatal:Boolean(t.fatal)},Object.defineProperty(this,"encoding",{value:"utf-8"})}function tf(e){var t=e.fatal,n=0,r=0,i=0,o=128,s=191;this.handler=function(e,a){if(-1===a&&0!==i)return i=0,Jp(t);if(-1===a)return Qp;if(0===i){if(jp(a,0,127))return a;if(jp(a,194,223))i=1,n=a-192;else if(jp(a,224,239))224===a&&(o=160),237===a&&(s=159),i=2,n=a-224;else{if(!jp(a,240,244))return Jp(t);240===a&&(o=144),244===a&&(s=143),i=3,n=a-240}return n<<=6*i,null}if(!jp(a,o,s))return n=i=r=0,o=128,s=191,e.prepend(a),Jp(t);if(o=128,s=191,n+=a-128<<6*(i-(r+=1)),r!==i)return null;var c=n;return n=i=r=0,c}}function nf(e){e.fatal,this.handler=function(e,t){if(-1===t)return Qp;if(jp(t,0,127))return t;var n,r;jp(t,128,2047)?(n=1,r=192):jp(t,2048,65535)?(n=2,r=224):jp(t,65536,1114111)&&(n=3,r=240);for(var i=[(t>>6*n)+r];n>0;){var o=t>>6*(n-1);i.push(128|63&o),n-=1}return i}}Yp.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=Vp(t),this._streaming||(this._decoder=new tf({fatal:this._fatal}),this._BOMseen=!1),this._streaming=Boolean(t.stream);for(var r,i=new Xp(n),o=[];!i.endOfStream()&&(r=this._decoder.handler(i,i.read()))!==Qp;)null!==r&&(Array.isArray(r)?o.push.apply(o,r):o.push(r));if(!this._streaming){do{if((r=this._decoder.handler(i,i.read()))===Qp)break;null!==r&&(Array.isArray(r)?o.push.apply(o,r):o.push(r))}while(!i.endOfStream());this._decoder=null}return o.length&&(-1===["utf-8"].indexOf(this.encoding)||this._ignoreBOM||this._BOMseen||(65279===o[0]?(this._BOMseen=!0,o.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}(o)}},ef.prototype={encode:function(e,t){e=e?String(e):"",t=Vp(t),this._streaming||(this._encoder=new nf(this._options)),this._streaming=Boolean(t.stream);for(var n,r=[],i=new Xp(function(e){for(var t=String(e),n=t.length,r=0,i=[];r<n;){var o=t.charCodeAt(r);if(o<55296||o>57343)i.push(o);else if(56320<=o&&o<=57343)i.push(65533);else if(55296<=o&&o<=56319)if(r===n-1)i.push(65533);else{var s=e.charCodeAt(r+1);if(56320<=s&&s<=57343){var a=1023&o,c=1023&s;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()))!==Qp;)Array.isArray(n)?r.push.apply(r,n):r.push(n);if(!this._streaming){for(;(n=this._encoder.handler(i,i.read()))!==Qp;)Array.isArray(n)?r.push.apply(r,n):r.push(n);this._encoder=null}return new Uint8Array(r)}};var rf,of=Uc(Object.freeze({__proto__:null,TextDecoder:Yp,TextEncoder:ef}));var sf,af=function(){if(rf)return zp;rf=1;var e=zp&&zp.__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=zp&&zp.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=zp&&zp.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},r=zp&&zp.__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=zp&&zp.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(zp,"__esModule",{value:!0}),zp.deserializeUnchecked=zp.deserialize=zp.serialize=zp.BinaryReader=zp.BinaryWriter=zp.BorshError=zp.baseDecode=zp.baseEncode=void 0;const o=i(Np()),s=i(Hp()),a=r(of),c=new("function"!=typeof TextDecoder?a.TextDecoder:TextDecoder)("utf-8",{fatal:!0});zp.baseEncode=function(e){return"string"==typeof e&&(e=Buffer.from(e,"utf8")),s.default.encode(Buffer.from(e))},zp.baseDecode=function(e){return Buffer.from(s.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(".")}}zp.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 o.default(e).toArray("le",8)))}writeU128(e){this.maybeResize(),this.writeBuffer(Buffer.from(new o.default(e).toArray("le",16)))}writeU256(e){this.maybeResize(),this.writeBuffer(Buffer.from(new o.default(e).toArray("le",32)))}writeU512(e){this.maybeResize(),this.writeBuffer(Buffer.from(new o.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}}}zp.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 o.default(e,"le")}readU128(){const e=this.readBuffer(16);return new o.default(e,"le")}readU256(){const e=this.readBuffer(32);return new o.default(e,"le")}readU512(){const e=this.readBuffer(64);return new o.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 p(e){return e.charAt(0).toUpperCase()+e.slice(1)}function f(e,t,n,r,i){try{if("string"==typeof r)i[`write${p(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++)f(e,null,n[t],r[0],i)}else i.writeArray(n,n=>{f(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),f(e,t,n,r.type,i));break;case"map":i.writeU32(n.size),n.forEach((n,o)=>{f(e,t,o,r.key,i),f(e,t,n,r.value,i)});break;default:throw new u(`FieldType ${r} unrecognized`)}else m(e,n,i)}catch(e){throw e instanceof u&&e.addToFieldPath(t),e}}function m(e,t,n){if("function"==typeof t.borshSerialize)return void t.borshSerialize(n);const r=e.get(t.constructor);if(!r)throw new u(`Class ${t.constructor.name} is missing in schema`);if("struct"===r.kind)r.fields.map(([r,i])=>{f(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 o=0;o<r.values.length;++o){const[s,a]=r.values[o];if(s===i){n.writeU8(o),f(e,s,t[s],a,n);break}}}}}function y(e,t,n,r){try{if("string"==typeof n)return r[`read${p(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 o=r.readU32();for(let s=0;s<o;s++){const o=y(e,t,n.key,r),s=y(e,t,n.value,r);i.set(o,s)}return i}return w(e,n,r)}catch(e){throw e instanceof u&&e.addToFieldPath(t),e}}function w(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,o]of e.get(t).fields)r[i]=y(e,i,o,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[o,s]=r.values[i],a=y(e,o,s,n);return new t({[o]: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),zp.BinaryReader=g,zp.serialize=function(e,t,n=d){const r=new n;return m(e,t,r),r.toArray()},zp.deserialize=function(e,t,n,r=g){const i=new r(n),o=w(e,t,i);if(i.offset<n.length)throw new u(`Unexpected ${n.length-i.offset} bytes after deserialized data`);return o},zp.deserializeUnchecked=function(e,t,n,r=g){return w(e,t,new r(n))},zp}(),cf={};var lf=function(){if(sf)return cf;sf=1,Object.defineProperty(cf,"__esModule",{value:!0}),cf.s16=cf.s8=cf.nu64be=cf.u48be=cf.u40be=cf.u32be=cf.u24be=cf.u16be=cf.nu64=cf.u48=cf.u40=cf.u32=cf.u24=cf.u16=cf.u8=cf.offset=cf.greedy=cf.Constant=cf.UTF8=cf.CString=cf.Blob=cf.Boolean=cf.BitField=cf.BitStructure=cf.VariantLayout=cf.Union=cf.UnionLayoutDiscriminator=cf.UnionDiscriminator=cf.Structure=cf.Sequence=cf.DoubleBE=cf.Double=cf.FloatBE=cf.Float=cf.NearInt64BE=cf.NearInt64=cf.NearUInt64BE=cf.NearUInt64=cf.IntBE=cf.Int=cf.UIntBE=cf.UInt=cf.OffsetLayout=cf.GreedyCount=cf.ExternalLayout=cf.bindConstructorLayout=cf.nameWithProperty=cf.Layout=cf.uint8ArrayToBuffer=cf.checkUint8Array=void 0,cf.constant=cf.utf8=cf.cstr=cf.blob=cf.unionLayoutDiscriminator=cf.union=cf.seq=cf.bits=cf.struct=cf.f64be=cf.f64=cf.f32be=cf.f32=cf.ns64be=cf.s48be=cf.s40be=cf.s32be=cf.s24be=cf.s16be=cf.ns64=cf.s48=cf.s40=cf.s32=cf.s24=void 0;const e=Zd();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)}cf.checkUint8Array=t,cf.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}cf.Layout=r,cf.nameWithProperty=i,cf.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 o extends r{isCount(){throw new Error("ExternalLayout is abstract")}}cf.ExternalLayout=o;class s extends o{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}}cf.GreedyCount=s;class a extends o{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)}}cf.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}}cf.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}}cf.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}}cf.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}}cf.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 p(e,t){return e*h+t}class f extends r{constructor(e){super(8,e)}decode(e,t=0){const r=n(e),i=r.readUInt32LE(t);return p(r.readUInt32LE(t+4),i)}encode(e,t,r=0){const i=g(e),o=n(t);return o.writeUInt32LE(i.lo32,r),o.writeUInt32LE(i.hi32,r+4),8}}cf.NearUInt64=f;class m extends r{constructor(e){super(8,e)}decode(e,t=0){const r=n(e);return p(r.readUInt32BE(t),r.readUInt32BE(t+4))}encode(e,t,r=0){const i=g(e),o=n(t);return o.writeUInt32BE(i.hi32,r),o.writeUInt32BE(i.lo32,r+4),8}}cf.NearUInt64BE=m;class y extends r{constructor(e){super(8,e)}decode(e,t=0){const r=n(e),i=r.readUInt32LE(t);return p(r.readInt32LE(t+4),i)}encode(e,t,r=0){const i=g(e),o=n(t);return o.writeUInt32LE(i.lo32,r),o.writeInt32LE(i.hi32,r+4),8}}cf.NearInt64=y;class w extends r{constructor(e){super(8,e)}decode(e,t=0){const r=n(e);return p(r.readInt32BE(t),r.readUInt32BE(t+4))}encode(e,t,r=0){const i=g(e),o=n(t);return o.writeInt32BE(i.hi32,r),o.writeUInt32BE(i.lo32,r+4),8}}cf.NearInt64BE=w;class k 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}}cf.Float=k;class b 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}}cf.FloatBE=b;class v 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}}cf.Double=v;class S 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}}cf.DoubleBE=S;class A extends r{constructor(e,t,n){if(!(e instanceof r))throw new TypeError("elementLayout must be a Layout");if(!(t instanceof o&&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 o)&&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 o&&(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 o&&(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 o&&this.count.encode(e.length,t,n),i}}cf.Sequence=A;class T 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,o=0;for(const r of this.fields){let s=r.span;if(o=0<s?s:0,void 0!==r.property){const i=e[r.property];void 0!==i&&(o=r.encode(i,t,n),0>s&&(s=r.getSpan(t,n)))}i=n,n+=s}return i+o-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)}}}cf.Structure=T;class E{constructor(e){this.property=e}decode(e,t){throw new Error("UnionDiscriminator is abstract")}encode(e,t,n){throw new Error("UnionDiscriminator is abstract")}}cf.UnionDiscriminator=E;class I extends E{constructor(e,t){if(!(e instanceof o&&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)}}cf.UnionLayoutDiscriminator=I;class x 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 o&&e.isCount())i=new I(e);else{if(!(e instanceof E))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 s=-1;t&&(s=t.span,0<=s&&(e instanceof c||e instanceof l)&&(s+=i.layout.span)),super(s,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),o=this.registry[i];if(void 0===o){const o=this.defaultLayout;let s=0;this.usesPrefixDiscriminator&&(s=r.layout.span),n=this.makeDestinationObject(),n[r.property]=i,n[o.property]=o.decode(e,t+s)}else n=o.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 o=0;return this.usesPrefixDiscriminator&&(o=r.layout.span),r.encode(e[r.property],t,n),o+i.encode(e[i.property],t,n+o)}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]}}cf.Union=x;class C extends r{constructor(e,t,n,i){if(!(e instanceof x))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 o=e.span;0>e.span&&(o=n?n.span:0,0<=o&&e.usesPrefixDiscriminator&&(o+=e.discriminator.layout.span)),super(o,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 N(e){return 0>e&&(e+=4294967296),e}cf.VariantLayout=C;class _ 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=N(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 B(this,e,t);return this.fields.push(n),n}addBoolean(e){const t=new P(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}}cf.BitStructure=_;class B{constructor(e,t,n){if(!(e instanceof _))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=N(this.valueMask<<this.start),this.property=n}decode(e,t){return N(this.container._packedGetValue()&this.wordMask)>>>this.start}encode(e){if("number"!=typeof e||!Number.isInteger(e)||e!==N(e&this.valueMask))throw new TypeError(i("BitField.encode",this)+" value must be integer not exceeding "+this.valueMask);const t=this.container._packedGetValue(),n=N(e<<this.start);this.container._packedSetValue(N(t&~this.wordMask)|n)}}cf.BitField=B;class P extends B{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)}}cf.Boolean=P;class D extends r{constructor(e,t){if(!(e instanceof o&&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 o||(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 s=this.length;if(this.length instanceof o&&(s=e.length),!(e instanceof Uint8Array&&s===e.length))throw new TypeError(i("Blob.encode",this)+" requires (length "+s+") Uint8Array as src");if(r+s>t.length)throw new RangeError("encoding overruns Uint8Array");const a=n(e);return n(t).write(a.toString("hex"),r,s,"hex"),this.length instanceof o&&this.length.encode(s,t,r),s}}cf.Blob=D;class R 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 o=e.Buffer.from(t,"utf8"),s=o.length;if(i+s>r.length)throw new RangeError("encoding overruns Buffer");const a=n(r);return o.copy(a,i),a[i+s]=0,s+1}}cf.CString=R;class M extends r{constructor(e,t){if("string"==typeof e&&void 0===t&&(t=e,e=void 0),void 0===e)e=-1;else if(!Number.isInteger(e))throw new TypeError("maxSpan must be an integer");super(-1,t),this.maxSpan=e}getSpan(e,n=0){return t(e),e.length-n}decode(e,t=0){const r=this.getSpan(e,t);if(0<=this.maxSpan&&this.maxSpan<r)throw new RangeError("text length exceeds maxSpan");return n(e).slice(t,t+r).toString("utf-8")}encode(t,r,i=0){"string"!=typeof t&&(t=String(t));const o=e.Buffer.from(t,"utf8"),s=o.length;if(0<=this.maxSpan&&this.maxSpan<s)throw new RangeError("text length exceeds maxSpan");if(i+s>r.length)throw new RangeError("encoding overruns Buffer");return o.copy(n(r),i),s}}cf.UTF8=M;class L extends r{constructor(e,t){super(0,t),this.value=e}decode(e,t){return this.value}encode(e,t,n){return 0}}return cf.Constant=L,cf.greedy=(e,t)=>new s(e,t),cf.offset=(e,t,n)=>new a(e,t,n),cf.u8=e=>new c(1,e),cf.u16=e=>new c(2,e),cf.u24=e=>new c(3,e),cf.u32=e=>new c(4,e),cf.u40=e=>new c(5,e),cf.u48=e=>new c(6,e),cf.nu64=e=>new f(e),cf.u16be=e=>new l(2,e),cf.u24be=e=>new l(3,e),cf.u32be=e=>new l(4,e),cf.u40be=e=>new l(5,e),cf.u48be=e=>new l(6,e),cf.nu64be=e=>new m(e),cf.s8=e=>new u(1,e),cf.s16=e=>new u(2,e),cf.s24=e=>new u(3,e),cf.s32=e=>new u(4,e),cf.s40=e=>new u(5,e),cf.s48=e=>new u(6,e),cf.ns64=e=>new y(e),cf.s16be=e=>new d(2,e),cf.s24be=e=>new d(3,e),cf.s32be=e=>new d(4,e),cf.s40be=e=>new d(5,e),cf.s48be=e=>new d(6,e),cf.ns64be=e=>new w(e),cf.f32=e=>new k(e),cf.f32be=e=>new b(e),cf.f64=e=>new v(e),cf.f64be=e=>new S(e),cf.struct=(e,t,n)=>new T(e,t,n),cf.bits=(e,t,n)=>new _(e,t,n),cf.seq=(e,t,n)=>new A(e,t,n),cf.union=(e,t,n)=>new x(e,t,n),cf.unionLayoutDiscriminator=(e,t)=>new I(e,t),cf.blob=(e,t)=>new D(e,t),cf.cstr=e=>new R(e),cf.utf8=(e,t)=>new M(e,t),cf.constant=(e,t)=>new L(e,t),cf}(),uf=1,df=2,hf=3,gf=4,pf=5,ff=6,mf=7,yf=8,wf=9,kf=10,bf=-32700,vf=-32603,Sf=-32602,Af=-32601,Tf=-32600,Ef=-32016,If=-32015,xf=-32014,Cf=-32013,Nf=-32012,_f=-32011,Bf=-32010,Pf=-32009,Df=-32008,Rf=-32007,Mf=-32006,Lf=-32005,Of=-32004,Ff=-32003,Uf=-32002,$f=-32001,qf=28e5,Kf=2800001,Gf=2800002,Wf=2800003,zf=2800004,Hf=2800005,jf=2800006,Vf=2800007,Xf=2800008,Qf=2800009,Jf=2800010,Zf=2800011,Yf=323e4,em=32300001,tm=3230002,nm=3230003,rm=3230004,im=361e4,om=3610001,sm=3610002,am=3610003,cm=3610004,lm=3610005,um=3610006,dm=3610007,hm=3611e3,gm=3704e3,pm=3704001,fm=3704002,mm=3704003,ym=3704004,wm=4128e3,km=4128001,bm=4128002,vm=4615e3,Sm=4615001,Am=4615002,Tm=4615003,Em=4615004,Im=4615005,xm=4615006,Cm=4615007,Nm=4615008,_m=4615009,Bm=4615010,Pm=4615011,Dm=4615012,Rm=4615013,Mm=4615014,Lm=4615015,Om=4615016,Fm=4615017,Um=4615018,$m=4615019,qm=4615020,Km=4615021,Gm=4615022,Wm=4615023,zm=4615024,Hm=4615025,jm=4615026,Vm=4615027,Xm=4615028,Qm=4615029,Jm=4615030,Zm=4615031,Ym=4615032,ey=4615033,ty=4615034,ny=4615035,ry=4615036,iy=4615037,oy=4615038,sy=4615039,ay=4615040,cy=4615041,ly=4615042,uy=4615043,dy=4615044,hy=4615045,gy=4615046,py=4615047,fy=4615048,my=4615049,yy=4615050,wy=4615051,ky=4615052,by=4615053,vy=4615054,Sy=5508e3,Ay=5508001,Ty=5508002,Ey=5508003,Iy=5508004,xy=5508005,Cy=5508006,Ny=5508007,_y=5508008,By=5508009,Py=5508010,Dy=5508011,Ry=5663e3,My=5663001,Ly=5663002,Oy=5663003,Fy=5663004,Uy=5663005,$y=5663006,qy=5663007,Ky=5663008,Gy=5663009,Wy=5663010,zy=5663011,Hy=5663012,jy=5663013,Vy=5663014,Xy=5663015,Qy=5663016,Jy=5663017,Zy=5663018,Yy=5663019,ew=5663020,tw=705e4,nw=7050001,rw=7050002,iw=7050003,ow=7050004,sw=7050005,aw=7050006,cw=7050007,lw=7050008,uw=7050009,dw=7050010,hw=7050011,gw=7050012,pw=7050013,fw=7050014,mw=7050015,yw=7050016,ww=7050017,kw=7050018,bw=7050019,vw=7050020,Sw=7050021,Aw=7050022,Tw=7050023,Ew=7050024,Iw=7050025,xw=7050026,Cw=7050027,Nw=7050028,_w=7050029,Bw=7050030,Pw=7050031,Dw=7050032,Rw=7050033,Mw=7050034,Lw=7050035,Ow=7050036,Fw=8078e3,Uw=8078001,$w=8078002,qw=8078003,Kw=8078004,Gw=8078005,Ww=8078006,zw=8078007,Hw=8078008,jw=8078009,Vw=8078010,Xw=8078011,Qw=8078012,Jw=8078013,Zw=8078014,Yw=8078015,ek=8078016,tk=8078017,nk=8078018,rk=8078019,ik=8078020,ok=8078021,sk=8078022,ak=81e5,ck=8100001,lk=8100002,uk=8100003,dk=819e4,hk=8190001,gk=8190002,pk=8190003,fk=8190004,mk=99e5,yk=9900001,wk=9900002,kk=9900003,bk=9900004;function vk(e){if(Array.isArray(e)){return"%5B"+e.map(vk).join("%2C%20")+"%5D"}return"bigint"==typeof e?`${e}n`:encodeURIComponent(String(null!=e&&null===Object.getPrototypeOf(e)?{...e}:e))}function Sk([e,t]){return`${e}=${vk(t)}`}var Ak={[Yf]:"Account not found at address: $address",[rm]:"Not all accounts were decoded. Encoded accounts found at addresses: $addresses.",[nm]:"Expected decoded account at address: $address",[tm]:"Failed to decode account data at address: $address",[em]:"Accounts not found at addresses: $addresses",[Qf]:"Unable to find a viable program address bump seed.",[Gf]:"$putativeAddress is not a base58-encoded address.",[qf]:"Expected base58 encoded address to decode to a byte array of length 32. Actual length: $actualLength.",[Wf]:"The `CryptoKey` must be an `Ed25519` public key.",[Zf]:"$putativeOffCurveAddress is not a base58-encoded off-curve address.",[Xf]:"Invalid seeds; point must fall off the Ed25519 curve.",[zf]:"Expected given program derived address to have the following format: [Address, ProgramDerivedAddressBump].",[jf]:"A maximum of $maxSeeds seeds, including the bump seed, may be supplied when creating an address. Received: $actual.",[Vf]:"The seed at index $index with length $actual exceeds the maximum length of $maxSeedLength bytes.",[Hf]:"Expected program derived address bump to be in the range [0, 255], got: $bump.",[Jf]:"Program address cannot end with PDA marker.",[Kf]:"Expected base58-encoded address string of length in the range [32, 44]. Actual length: $actualLength.",[gf]:"Expected base58-encoded blockash string of length in the range [32, 44]. Actual length: $actualLength.",[uf]:"The network has progressed past the last block for which this transaction could have been committed.",[Fw]:"Codec [$codecDescription] cannot decode empty byte arrays.",[sk]:"Enum codec cannot use lexical values [$stringValues] as discriminators. Either remove all lexical values or set `useValuesAsDiscriminators` to `false`.",[ik]:"Sentinel [$hexSentinel] must not be present in encoded bytes [$hexEncodedBytes].",[Gw]:"Encoder and decoder must have the same fixed size, got [$encoderFixedSize] and [$decoderFixedSize].",[Ww]:"Encoder and decoder must have the same max size, got [$encoderMaxSize] and [$decoderMaxSize].",[Kw]:"Encoder and decoder must either both be fixed-size or variable-size.",[Hw]:"Enum discriminator out of range. Expected a number in [$formattedValidDiscriminators], got $discriminator.",[$w]:"Expected a fixed-size codec, got a variable-size one.",[Jw]:"Codec [$codecDescription] expected a positive byte length, got $bytesLength.",[qw]:"Expected a variable-size codec, got a fixed-size one.",[rk]:"Codec [$codecDescription] expected zero-value [$hexZeroValue] to have the same size as the provided fixed-size item [$expectedSize bytes].",[Uw]:"Codec [$codecDescription] expected $expected bytes, got $bytesLength.",[nk]:"Expected byte array constant [$hexConstant] to be present in data [$hexData] at offset [$offset].",[jw]:"Invalid discriminated union variant. Expected one of [$variants], got $value.",[Vw]:"Invalid enum variant. Expected one of [$stringValues] or a number in [$formattedNumericalValues], got $variant.",[Yw]:"Invalid literal union variant. Expected one of [$variants], got $value.",[zw]:"Expected [$codecDescription] to have $expected items, got $actual.",[Qw]:"Invalid value $value for base $base with alphabet $alphabet.",[ek]:"Literal union discriminator out of range. Expected a number between $minRange and $maxRange, got $discriminator.",[Xw]:"Codec [$codecDescription] expected number to be in the range [$min, $max], got $value.",[Zw]:"Codec [$codecDescription] expected offset to be in the range [0, $bytesLength], got $offset.",[ok]:"Expected sentinel [$hexSentinel] to be present in decoded bytes [$hexDecodedBytes].",[tk]:"Union variant out of range. Expected an index between $minRange and $maxRange, got $variant.",[hm]:"No random values implementation could be found.",[_m]:"instruction requires an uninitialized account",[Wm]:"instruction tries to borrow reference for an account which is already borrowed",[zm]:"instruction left account with an outstanding borrowed reference",[Km]:"program other than the account's owner changed the size of the account data",[Im]:"account data too small for instruction",[Gm]:"instruction expected an executable account",[gy]:"An account does not have enough lamports to be rent-exempt",[fy]:"Program arithmetic overflowed",[hy]:"Failed to serialize or deserialize account data: $encodedData",[vy]:"Builtin programs must consume compute units",[Ym]:"Cross-program invocation call depth too deep",[oy]:"Computational budget exceeded",[jm]:"custom program error: #$code",[Fm]:"instruction contains duplicate accounts",[Hm]:"instruction modifications of multiply-passed account differ",[Jm]:"executable accounts must be rent exempt",[Xm]:"instruction changed executable accounts data",[Qm]:"instruction changed the balance of an executable account",[Um]:"instruction changed executable bit of an account",[Mm]:"instruction modified data of an account it does not own",[Rm]:"instruction spent from the balance of an account it does not own",[Sm]:"generic instruction error",[yy]:"Provided owner is not allowed",[uy]:"Account is immutable",[dy]:"Incorrect authority provided",[Cm]:"incorrect program id for instruction",[xm]:"insufficient funds for instruction",[Em]:"invalid account data for instruction",[py]:"Invalid account owner",[Am]:"invalid program argument",[Vm]:"program returned invalid error code",[Tm]:"invalid instruction data",[iy]:"Failed to reallocate account data",[ry]:"Provided seeds do not result in a valid address",[wy]:"Accounts data allocations exceeded the maximum allowed per transaction",[ky]:"Max accounts exceeded",[by]:"Max instruction trace length exceeded",[ny]:"Length of the seed is too long for address generation",[ey]:"An account required by the instruction is missing",[Nm]:"missing required signature for instruction",[Dm]:"instruction illegally modified the program id of an account",[qm]:"insufficient account keys for instruction",[sy]:"Cross-program invocation with unauthorized signer or writable account",[ay]:"Failed to create program execution environment",[ly]:"Program failed to compile",[cy]:"Program failed to complete",[Om]:"instruction modified data of a read-only account",[Lm]:"instruction changed the balance of a read-only account",[ty]:"Cross-program invocation reentrancy not allowed for this instruction",[$m]:"instruction modified rent epoch of an account",[Pm]:"sum of account balances before and after instruction do not match",[Bm]:"instruction requires an initialized account",[vm]:"",[Zm]:"Unsupported program id",[my]:"Unsupported sysvar",[wm]:"The instruction does not have any accounts.",[km]:"The instruction does not have any data.",[bm]:"Expected instruction to have progress address $expectedProgramAddress, got $actualProgramAddress.",[pf]:"Expected base58 encoded blockhash to decode to a byte array of length 32. Actual length: $actualLength.",[df]:"The nonce `$expectedNonceValue` is no longer valid. It has advanced to `$actualNonceValue`",[wk]:"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",[bk]:"Invariant violation: This data publisher does not publish to the channel named `$channelName`. Supported channels include $supportedChannelNames.",[yk]:"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",[mk]:"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",[kk]:"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",[vf]:"JSON-RPC error: Internal JSON-RPC error ($__serverMessage)",[Sf]:"JSON-RPC error: Invalid method parameter(s) ($__serverMessage)",[Tf]:"JSON-RPC error: The JSON sent is not a valid `Request` object ($__serverMessage)",[Af]:"JSON-RPC error: The method does not exist / is not available ($__serverMessage)",[bf]:"JSON-RPC error: An error occurred on the server while parsing the JSON text ($__serverMessage)",[Nf]:"$__serverMessage",[$f]:"$__serverMessage",[Of]:"$__serverMessage",[xf]:"$__serverMessage",[Bf]:"$__serverMessage",[Pf]:"$__serverMessage",[Ef]:"Minimum context slot has not been reached",[Lf]:"Node is unhealthy; behind by $numSlotsBehind slots",[Df]:"No snapshot",[Uf]:"Transaction simulation failed",[Rf]:"$__serverMessage",[_f]:"Transaction history is not available from this node",[Mf]:"$__serverMessage",[Cf]:"Transaction signature length mismatch",[Ff]:"Transaction signature verification failure",[If]:"$__serverMessage",[gm]:"Key pair bytes must be of length 64, got $byteLength.",[pm]:"Expected private key bytes with length 32. Actual length: $actualLength.",[fm]:"Expected base58-encoded signature to decode to a byte array of length 64. Actual length: $actualLength.",[ym]:"The provided private key does not match the provided public key.",[mm]:"Expected base58-encoded signature string of length in the range [64, 88]. Actual length: $actualLength.",[ff]:"Lamports value must be in the range [0, 2e64-1]",[mf]:"`$value` cannot be parsed as a `BigInt`",[kf]:"$message",[yf]:"`$value` cannot be parsed as a `Number`",[hf]:"No nonce account could be found at address `$nonceAccountAddress`",[dk]:"The notification name must end in 'Notifications' and the API must supply a subscription plan creator function for the notification '$notificationName'.",[gk]:"WebSocket was closed before payload could be added to the send buffer",[pk]:"WebSocket connection closed",[fk]:"WebSocket failed to connect",[hk]:"Failed to obtain a subscription id from the server",[uk]:"Could not find an API plan for RPC method: `$method`",[ak]:"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`.",[lk]:"HTTP error ($statusCode): $message",[ck]:"HTTP header(s) forbidden: $headers. Learn more at https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name.",[Sy]:"Multiple distinct signers were identified for address `$address`. Please ensure that you are using the same signer instance for each address.",[Ay]:"The provided value does not implement the `KeyPairSigner` interface",[Ey]:"The provided value does not implement the `MessageModifyingSigner` interface",[Iy]:"The provided value does not implement the `MessagePartialSigner` interface",[Ty]:"The provided value does not implement any of the `MessageSigner` interfaces",[Cy]:"The provided value does not implement the `TransactionModifyingSigner` interface",[Ny]:"The provided value does not implement the `TransactionPartialSigner` interface",[_y]:"The provided value does not implement the `TransactionSendingSigner` interface",[xy]:"The provided value does not implement any of the `TransactionSigner` interfaces",[By]:"More than one `TransactionSendingSigner` was identified.",[Py]:"No `TransactionSendingSigner` was identified. Please provide a valid `TransactionWithSingleSendingSigner` transaction.",[Dy]:"Wallet account signers do not support signing multiple messages/transactions in a single operation",[dm]:"Cannot export a non-extractable key.",[om]:"No digest implementation could be found.",[im]:"Cryptographic operations are only allowed in secure browser contexts. Read more here: https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts.",[sm]:"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.",[am]:"No signature verification implementation could be found.",[cm]:"No key generation implementation could be found.",[lm]:"No signing implementation could be found.",[um]:"No key export implementation could be found.",[wf]:"Timestamp value must be in the range [-(2n ** 63n), (2n ** 63n) - 1]. `$value` given",[yw]:"Transaction processing left an account with an outstanding borrowed reference",[nw]:"Account in use",[rw]:"Account loaded twice",[iw]:"Attempt to debit an account but found no record of a prior credit.",[Tw]:"Transaction loads an address table account that doesn't exist",[cw]:"This transaction has already been processed",[lw]:"Blockhash not found",[uw]:"Loader call chain is too deep",[mw]:"Transactions are currently disabled due to cluster maintenance",[Bw]:"Transaction contains a duplicate instruction ($index) that is not allowed",[sw]:"Insufficient funds for fee",[Pw]:"Transaction results in an account ($accountIndex) with insufficient funds for rent",[aw]:"This account may not be used to pay transaction fees",[hw]:"Transaction contains an invalid account reference",[Iw]:"Transaction loads an address table account with invalid data",[xw]:"Transaction address table lookup uses an invalid index",[Ew]:"Transaction loads an address table account with an invalid owner",[Rw]:"LoadedAccountsDataSizeLimit set for transaction must be greater than 0.",[pw]:"This program may not be used for executing instructions",[Cw]:"Transaction leaves an account with a lower balance than rent-exempt minimum",[bw]:"Transaction loads a writable account that cannot be written",[Dw]:"Transaction exceeded max loaded accounts data size cap",[dw]:"Transaction requires a fee but has no signature present",[ow]:"Attempt to load a program that does not exist",[Lw]:"Execution of the program referenced by account at index $accountIndex is temporarily restricted.",[Mw]:"ResanitizationNeeded",[fw]:"Transaction failed to sanitize accounts offsets correctly",[gw]:"Transaction did not pass signature verification",[Aw]:"Transaction locked too many accounts",[Ow]:"Sum of account balances before and after transaction do not match",[tw]:"The transaction failed with the error `$errorName`",[kw]:"Transaction version is unsupported",[Sw]:"Transaction would exceed account data limit within the block",[_w]:"Transaction would exceed total account data limit",[vw]:"Transaction would exceed max account limit within the block",[ww]:"Transaction would exceed max Block Cost Limit",[Nw]:"Transaction would exceed max Vote Cost Limit",[Xy]:"Attempted to sign a transaction with an address that is not a signer for it",[Wy]:"Transaction is missing an address at index: $index.",[Qy]:"Transaction has no expected signers therefore it cannot be encoded",[ew]:"Transaction size $transactionSize exceeds limit of $transactionSizeLimit bytes",[Ly]:"Transaction does not have a blockhash lifetime",[Oy]:"Transaction is not a durable nonce transaction",[Uy]:"Contents of these address lookup tables unknown: $lookupTableAddresses",[$y]:"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",[Ky]:"No fee payer set in CompiledTransaction",[qy]:"Could not find program address at index $index",[Zy]:"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",[Yy]:"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",[zy]:"Transaction is missing a fee payer.",[Hy]:"Could not determine this transaction's signature. Make sure that the transaction has been signed by its fee payer.",[Vy]:"Transaction first instruction is not advance nonce account instruction.",[jy]:"Transaction with no instructions cannot be durable nonce transaction.",[Ry]:"This transaction includes an address (`$programAddress`) which is both invoked and set as the fee payer. Program addresses may not pay fees",[My]:"This transaction includes an address (`$programAddress`) which is both invoked and marked writable. Program addresses may not be writable",[Jy]:"The transaction message expected the transaction to have $signerAddressesLength signatures, got $signaturesLength.",[Gy]:"Transaction is missing signatures for addresses: $addresses.",[Fy]:"Transaction version must be in the range [0, 127]. `$actualVersion` given"},Tk="i",Ek="t";function Ik(e,t={}){if("production"!==process.env.NODE_ENV)return function(e,t={}){const n=Ak[e];if(0===n.length)return"";let r;function i(e){if(2===r[Ek]){const i=n.slice(r[Tk]+1,e);o.push(i in t?`${t[i]}`:`$${i}`)}else 1===r[Ek]&&o.push(n.slice(r[Tk],e))}const o=[];return n.split("").forEach((e,t)=>{if(0===t)return void(r={[Tk]:0,[Ek]:"\\"===n[0]?0:"$"===n[0]?2:1});let o;switch(r[Ek]){case 0:o={[Tk]:t,[Ek]:1};break;case 1:"\\"===e?o={[Tk]:t,[Ek]:0}:"$"===e&&(o={[Tk]:t,[Ek]:2});break;case 2:"\\"===e?o={[Tk]:t,[Ek]:0}:"$"===e?o={[Tk]:t,[Ek]:2}:e.match(/\w/)||(o={[Tk]:t,[Ek]:1})}o&&(r!==o&&i(t),r=o)}),i(),o.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(Sk).join("&");return btoa(t)}(t)}'`),`${n}\``}}var xk=class extends Error{cause=this.cause;context;constructor(...[e,t]){let n,r;if(t){const{cause:e,...i}=t;e&&(r={cause:e}),Object.keys(i).length>0&&(n=i)}super(Ik(e,n),r),this.context={__code:e,...n},this.name="SolanaError"}};function Ck(e){return"fixedSize"in e&&"number"==typeof e.fixedSize}function Nk(e){return 1!==e?.endian}function _k(e){return t={fixedSize:e.size,write(t,n,r){e.range&&function(e,t,n,r){if(r<t||r>n)throw new xk(Xw,{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,Nk(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 Bk(e){return t={fixedSize:e.size,read(t,n=0){!function(e,t,n=0){if(t.length-n<=0)throw new xk(Fw,{codecDescription:e})}(e.name,t,n),function(e,t,n,r=0){const i=n.length-r;if(i<t)throw new xk(Uw,{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;return e.buffer.slice(r,r+i)}(t,n,e.size));return[e.get(r,Nk(e.config)),n+e.size]}},Object.freeze({...t,decode:(e,n=0)=>t.read(e,n)[0]});var t}var Pk=(e={})=>function(e,t){if(Ck(e)!==Ck(t))throw new xk(Kw);if(Ck(e)&&Ck(t)&&e.fixedSize!==t.fixedSize)throw new xk(Gw,{decoderFixedSize:t.fixedSize,encoderFixedSize:e.fixedSize});if(!Ck(e)&&!Ck(t)&&e.maxSize!==t.maxSize)throw new xk(Ww,{decoderMaxSize:t.maxSize,encoderMaxSize:e.maxSize});return{...t,...e,decode:t.decode,encode:e.encode,read:t.read,write:e.write}}(((e={})=>_k({config:e,name:"u64",range:[0n,BigInt("0xffffffffffffffff")],set:(e,t,n)=>e.setBigUint64(0,BigInt(t),n),size:8}))(e),((e={})=>Bk({config:e,get:(e,t)=>e.getBigUint64(0,t),name:"u64",size:8}))(e));class Dk extends TypeError{constructor(e,t){let n;const{message:r,explanation:i,...o}=e,{path:s}=e,a=0===s.length?r:`At path: ${s.join(".")} -- ${r}`;super(i??a),null!=i&&(this.cause=a),Object.assign(this,o),this.name=this.constructor.name,this.failures=()=>n??(n=[e,...t()])}}function Rk(e){return"object"==typeof e&&null!=e}function Mk(e){return Rk(e)&&!Array.isArray(e)}function Lk(e){return"symbol"==typeof e?e.toString():"string"==typeof e?JSON.stringify(e):`${e}`}function Ok(e,t,n,r){if(!0===e)return;!1===e?e={}:"string"==typeof e&&(e={message:e});const{path:i,branch:o}=t,{type:s}=n,{refinement:a,message:c=`Expected a value of type \`${s}\`${a?` with refinement \`${a}\``:""}, but received: \`${Lk(r)}\``}=e;return{value:r,type:s,refinement:a,key:i[i.length-1],path:i,branch:o,...e,message:c}}function*Fk(e,t,n,r){var i;Rk(i=e)&&"function"==typeof i[Symbol.iterator]||(e=[e]);for(const i of e){const e=Ok(i,t,n,r);e&&(yield e)}}function*Uk(e,t,n={}){const{path:r=[],branch:i=[e],coerce:o=!1,mask:s=!1}=n,a={path:r,branch:i,mask:s};o&&(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=Uk(u,d,{path:void 0===l?r:[...r,l],branch:void 0===l?i:[...i,u],coerce:o,mask:s,message:n.message});for(const n of t)n[0]?(c=null!=n[0].refinement?"not_refined":"not_valid",yield[n[0],void 0]):o&&(u=n[1],void 0===l?e=u:e instanceof Map?e.set(l,u):e instanceof Set?e.add(u):Rk(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 $k=class{constructor(e){const{type:t,schema:n,validator:r,refiner:i,coercer:o=e=>e,entries:s=function*(){}}=e;this.type=t,this.schema=n,this.entries=s,this.coercer=o,this.validator=r?(e,t)=>Fk(r(e,t),t,this,e):()=>[],this.refiner=i?(e,t)=>Fk(i(e,t),t,this,e):()=>[]}assert(e,t){return function(e,t,n){const r=Gk(e,t,{message:n});if(r[0])throw r[0]}(e,this,t)}create(e,t){return qk(e,this,t)}is(e){return Kk(e,this)}mask(e,t){return function(e,t,n){const r=Gk(e,t,{coerce:!0,mask:!0,message:n});if(r[0])throw r[0];return r[1]}(e,this,t)}validate(e,t={}){return Gk(e,this,t)}};function qk(e,t,n){const r=Gk(e,t,{coerce:!0,message:n});if(r[0])throw r[0];return r[1]}function Kk(e,t){return!Gk(e,t)[0]}function Gk(e,t,n={}){const r=Uk(e,t,n),i=function(e){const{done:t,value:n}=e.next();return t?void 0:n}(r);if(i[0]){return[new Dk(i[0],function*(){for(const e of r)e[0]&&(yield e[0])}),void 0]}return[void 0,i[1]]}function Wk(e,t){return new $k({type:e,schema:null,validator:t})}function zk(e){return new $k({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: ${Lk(e)}`})}function Hk(){return Wk("boolean",e=>"boolean"==typeof e)}function jk(e){return Wk("instance",t=>t instanceof e||`Expected a \`${e.name}\` instance, but received: ${Lk(t)}`)}function Vk(e){const t=Lk(e),n=typeof e;return new $k({type:"literal",schema:"string"===n||"number"===n||"boolean"===n?e:null,validator:n=>n===e||`Expected the literal \`${t}\`, but received: ${Lk(n)}`})}function Xk(e){return new $k({...e,validator:(t,n)=>null===t||e.validator(t,n),refiner:(t,n)=>null===t||e.refiner(t,n)})}function Qk(){return Wk("number",e=>"number"==typeof e&&!isNaN(e)||`Expected a number, but received: ${Lk(e)}`)}function Jk(e){return new $k({...e,validator:(t,n)=>void 0===t||e.validator(t,n),refiner:(t,n)=>void 0===t||e.refiner(t,n)})}function Zk(e,t){return new $k({type:"record",schema:null,*entries(n){if(Rk(n))for(const r in n){const i=n[r];yield[r,r,e],yield[r,i,t]}},validator:e=>Mk(e)||`Expected an object, but received: ${Lk(e)}`,coercer:e=>Mk(e)?{...e}:e})}function Yk(){return Wk("string",e=>"string"==typeof e||`Expected a string, but received: ${Lk(e)}`)}function eb(e){const t=Wk("never",()=>!1);return new $k({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: ${Lk(e)}`,coercer:e=>Array.isArray(e)?e.slice():e})}function tb(e){const t=Object.keys(e);return new $k({type:"type",schema:e,*entries(n){if(Rk(n))for(const r of t)yield[r,n[r],e[r]]},validator:e=>Mk(e)||`Expected an object, but received: ${Lk(e)}`,coercer:e=>Mk(e)?{...e}:e})}function nb(e){const t=e.map(e=>e.type).join(" | ");return new $k({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]=Uk(n,t,r),[o]=e;if(!o[0])return[];for(const[t]of e)t&&i.push(t)}return[`Expected the value to satisfy a union of \`${t}\`, but received: ${Lk(n)}`,...i]}})}function rb(){return Wk("unknown",()=>!0)}function ib(e,t,n){return new $k({...e,coercer:(r,i)=>Kk(r,t)?e.coercer(n(r,i),i):e.coercer(r,i)})}var ob,sb,ab,cb;var lb,ub=function(){if(cb)return ab;cb=1;const e=o.v4,t=function(){if(sb)return ob;sb=1;const e=o.v4;return ob=function(t,n,r,i){if("string"!=typeof t)throw new TypeError(t+" must be a string");const o="number"==typeof(i=i||{}).version?i.version:2;if(1!==o&&2!==o)throw new TypeError(o+" must be 1 or 2");const s={method:t};if(2===o&&(s.jsonrpc="2.0"),n){if("object"!=typeof n&&!Array.isArray(n))throw new TypeError(n+" must be an object, array or omitted");s.params=n}if(void 0===r){const t="function"==typeof i.generator?i.generator:function(){return e()};s.id=t(s,i)}else 2===o&&null===r?i.notificationIdNull&&(s.id=null):s.id=r;return s}}(),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 ab=n,n.prototype.request=function(e,n,r,i){const o=this;let s=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,s=e;else{"function"==typeof r&&(i=r,r=void 0);const o="function"==typeof i;try{s=t(e,n,r,{generator:this.options.generator,version:this.options.version,notificationIdNull:this.options.notificationIdNull})}catch(e){if(o)return void i(e);throw e}if(!o)return s}let c;try{c=JSON.stringify(s,this.options.replacer)}catch(e){return void i(e)}return this.callServer(c,function(e,t){o._parseResponse(e,t,i)}),s},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)}},ab}(),db=Fc(ub),hb={exports:{}};var gb=(lb||(lb=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 o(e,t,r,o,s){if("function"!=typeof r)throw new TypeError("The listener must be a function");var a=new i(r,o||e,s),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 s(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,o=r.length,s=new Array(o);i<o;i++)s[i]=r[i].fn;return s},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,o,s){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,o),!0;case 6:return u.fn.call(u.context,t,r,i,o,s),!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 o(this,e,t,n,!1)},a.prototype.once=function(e,t,n){return o(this,e,t,n,!0)},a.prototype.removeListener=function(e,t,r,i){var o=n?n+e:e;if(!this._events[o])return this;if(!t)return s(this,o),this;var a=this._events[o];if(a.fn)a.fn!==t||i&&!a.once||r&&a.context!==r||s(this,o);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[o]=1===l.length?l[0]:l:s(this,o)}return this},a.prototype.removeAllListeners=function(e){var t;return e?(t=n?n+e:e,this._events[t]&&s(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}(hb)),hb.exports),pb=Fc(gb),fb=class extends pb{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 mb=class{encode(e){return JSON.stringify(e)}decode(e){return JSON.parse(e)}},yb=class extends pb{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:o=5,...s}={},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=o,this.rest_options=s,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 mb,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,o)=>{if(!this.ready)return o(new Error("socket not ready"));const s=this.generate_request_id(e,t),a={jsonrpc:"2.0",method:e,params:t||void 0,id:s};this.socket.send(this.dataPack.encode(a),r,e=>{if(e)return o(e);this.queue[s]={promise:[i,o]},n&&(this.queue[s].timeout=setTimeout(()=>{delete this.queue[s],o(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=Yd.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 wb extends Sh{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,ih(e);const n=bh(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),sh(i)}update(e){return oh(this),this.iHash.update(e),this}digestInto(e){oh(this),rh(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:o,outputLen:s}=this;return e.finished=r,e.destroyed=i,e.blockLen=o,e.outputLen=s,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 kb=(e,t,n)=>new wb(e,t).update(n).digest();kb.create=(e,t)=>new wb(e,t);const bb=(e,t)=>(e+(e>=0?t:-t)/xb)/t;function vb(e){if(!["compact","recovered","der"].includes(e))throw new Error('Signature format must be "compact", "recovered", or "der"');return e}function Sb(e,t){const n={};for(let r of Object.keys(t))n[r]=void 0===e[r]?t[r]:e[r];return og(n.lowS,"lowS"),og(n.prehash,"prehash"),void 0!==n.format&&vb(n.format),n}class Ab extends Error{constructor(e=""){super(e)}}const Tb={Err:Ab,_tlv:{encode:(e,t)=>{const{Err:n}=Tb;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=ag(r);if(i.length/2&128)throw new n("tlv.encode: long form length too big");const o=r>127?ag(i.length/2|128):"";return ag(e)+o+i+t},decode(e,t){const{Err:n}=Tb;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 o=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 s=t.subarray(r,r+e);if(s.length!==e)throw new n("tlv.decode: length bytes not complete");if(0===s[0])throw new n("tlv.decode(long): zero leftmost byte");for(const e of s)o=o<<8|e;if(r+=e,o<128)throw new n("tlv.decode(long): not minimal encoding")}else o=i;const s=t.subarray(r,r+o);if(s.length!==o)throw new n("tlv.decode: wrong value length");return{v:s,l:t.subarray(r+o)}}},_int:{encode(e){const{Err:t}=Tb;if(e<Eb)throw new t("integer: negative integers are not allowed");let n=ag(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}=Tb;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 lg(e)}},toSig(e){const{Err:t,_int:n,_tlv:r}=Tb,i=gg("signature",e),{v:o,l:s}=r.decode(48,i);if(s.length)throw new t("invalid signature: left bytes after parsing");const{v:a,l:c}=r.decode(2,o),{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}=Tb,r=t.encode(2,n.encode(e.r))+t.encode(2,n.encode(e.s));return t.encode(48,r)}},Eb=BigInt(0),Ib=BigInt(1),xb=BigInt(2),Cb=BigInt(3),Nb=BigInt(4);function _b(e,t){const{BYTES:n}=e;let r;if("bigint"==typeof t)r=t;else{let i=gg("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 Bb(e,t={}){const n=sp("weierstrass",e,t),{Fp:r,Fn:i}=n;let o=n.CURVE;const{h:s,n:a}=o;kg(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:c}=t;if(c&&(!r.is0(o.a)||"bigint"!=typeof c.beta||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const l=Db(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:o}=t.toAffine(),s=r.toBytes(i);if(og(n,"isCompressed"),n){u();return vh(Pb(!r.isOdd(o)),s)}return vh(Uint8Array.of(4),s,r.toBytes(o))},h=t.fromBytes||function(e){sg(e,void 0,"Point");const{publicKey:t,publicKeyUncompressed:n}=l,i=e.length,o=e[0],s=e.subarray(1);if(i!==t||2!==o&&3!==o){if(i===n&&4===o){const e=r.BYTES,t=r.fromBytes(s.subarray(0,e)),n=r.fromBytes(s.subarray(e,2*e));if(!p(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(s);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&~o)!==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,o.a)),o.b)}function p(e,t){const n=r.sqr(t),i=g(e);return r.eql(n,i)}if(!p(o.Gx,o.Gy))throw new Error("bad curve params: generator point");const f=r.mul(r.pow(o.a,Cb),Nb),m=r.mul(r.sqr(o.b),BigInt(27));if(r.is0(r.add(f,m)))throw new Error("bad curve params: a or b");function y(e,t,n=!1){if(!r.isValid(t)||n&&r.is0(t))throw new Error(`bad point coordinate ${e}`);return t}function w(e){if(!(e instanceof A))throw new Error("ProjectivePoint expected")}function k(e){if(!c||!c.basises)throw new Error("no endo");return function(e,t,n){const[[r,i],[o,s]]=t,a=bb(s*e,n),c=bb(-i*e,n);let l=e-a*r-c*o,u=-a*i-c*s;const d=l<Eb,h=u<Eb;d&&(l=-l),h&&(u=-u);const g=wg(Math.ceil(yg(n)/2))+Ib;if(l<Eb||l>=g||u<Eb||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 b=bg((e,t)=>{const{X:n,Y:i,Z:o}=e;if(r.eql(o,r.ONE))return{x:n,y:i};const s=e.is0();null==t&&(t=s?r.ONE:r.inv(o));const a=r.mul(n,t),c=r.mul(i,t),l=r.mul(o,t);if(s)return{x:r.ZERO,y:r.ZERO};if(!r.eql(l,r.ONE))throw new Error("invZ was invalid");return{x:a,y:c}}),v=bg(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(!p(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 S(e,t,n,i,o){return n=new A(r.mul(n.X,e),n.Y,n.Z),t=Vg(i,t),n=Vg(o,n),t.add(n)}class A{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 o}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 A)throw new Error("projective point not allowed");return r.is0(t)&&r.is0(n)?A.ZERO:new A(t,n,r.ONE)}static fromBytes(e){const t=A.fromAffine(h(sg(e,void 0,"point")));return t.assertValidity(),t}static fromHex(e){return A.fromBytes(gg("pointHex",e))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(e=8,t=!0){return E.createCache(this,e),t||this.multiply(Cb),this}assertValidity(){v(this)}hasEvenY(){const{y:e}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(e)}equals(e){w(e);const{X:t,Y:n,Z:i}=this,{X:o,Y:s,Z:a}=e,c=r.eql(r.mul(t,a),r.mul(o,i)),l=r.eql(r.mul(n,a),r.mul(s,i));return c&&l}negate(){return new A(this.X,r.neg(this.Y),this.Z)}double(){const{a:e,b:t}=o,n=r.mul(t,Cb),{X:i,Y:s,Z:a}=this;let c=r.ZERO,l=r.ZERO,u=r.ZERO,d=r.mul(i,i),h=r.mul(s,s),g=r.mul(a,a),p=r.mul(i,s);return p=r.add(p,p),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(p,c),u=r.mul(n,u),g=r.mul(e,g),p=r.sub(d,g),p=r.mul(e,p),p=r.add(p,u),u=r.add(d,d),d=r.add(u,d),d=r.add(d,g),d=r.mul(d,p),l=r.add(l,d),g=r.mul(s,a),g=r.add(g,g),d=r.mul(g,p),c=r.sub(c,d),u=r.mul(g,h),u=r.add(u,u),u=r.add(u,u),new A(c,l,u)}add(e){w(e);const{X:t,Y:n,Z:i}=this,{X:s,Y:a,Z:c}=e;let l=r.ZERO,u=r.ZERO,d=r.ZERO;const h=o.a,g=r.mul(o.b,Cb);let p=r.mul(t,s),f=r.mul(n,a),m=r.mul(i,c),y=r.add(t,n),k=r.add(s,a);y=r.mul(y,k),k=r.add(p,f),y=r.sub(y,k),k=r.add(t,i);let b=r.add(s,c);return k=r.mul(k,b),b=r.add(p,m),k=r.sub(k,b),b=r.add(n,i),l=r.add(a,c),b=r.mul(b,l),l=r.add(f,m),b=r.sub(b,l),d=r.mul(h,k),l=r.mul(g,m),d=r.add(l,d),l=r.sub(f,d),d=r.add(f,d),u=r.mul(l,d),f=r.add(p,p),f=r.add(f,p),m=r.mul(h,m),k=r.mul(g,k),f=r.add(f,m),m=r.sub(p,m),m=r.mul(h,m),k=r.add(k,m),p=r.mul(f,k),u=r.add(u,p),p=r.mul(b,k),l=r.mul(y,l),l=r.sub(l,p),p=r.mul(y,f),d=r.mul(b,d),d=r.add(d,p),new A(l,u,d)}subtract(e){return this.add(e.negate())}is0(){return this.equals(A.ZERO)}multiply(e){const{endo:n}=t;if(!i.isValidNot0(e))throw new Error("invalid scalar: out of range");let r,o;const s=e=>E.cached(this,e,e=>Xg(A,e));if(n){const{k1neg:t,k1:i,k2neg:a,k2:c}=k(e),{p:l,f:u}=s(i),{p:d,f:h}=s(c);o=u.add(h),r=S(n.beta,l,d,t,a)}else{const{p:t,f:n}=s(e);r=t,o=n}return Xg(A,[r,o])[0]}multiplyUnsafe(e){const{endo:n}=t,r=this;if(!i.isValid(e))throw new Error("invalid scalar: out of range");if(e===Eb||r.is0())return A.ZERO;if(e===Ib)return r;if(E.hasCache(this))return this.multiply(e);if(n){const{k1neg:t,k1:i,k2neg:o,k2:s}=k(e),{p1:a,p2:c}=function(e,t,n,r){let i=t,o=e.ZERO,s=e.ZERO;for(;n>Hg||r>Hg;)n&jg&&(o=o.add(i)),r&jg&&(s=s.add(i)),i=i.double(),n>>=jg,r>>=jg;return{p1:o,p2:s}}(A,r,i,s);return S(n.beta,a,c,t,o)}return E.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 b(this,e)}isTorsionFree(){const{isTorsionFree:e}=t;return s===Ib||(e?e(A,this):E.unsafe(this,a).is0())}clearCofactor(){const{clearCofactor:e}=t;return s===Ib?this:e?e(A,this):this.multiplyUnsafe(s)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}toBytes(e=!0){return og(e,"isCompressed"),this.assertValidity(),d(A,this,e)}toHex(e=!0){return dh(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 Xg(A,e)}static msm(e,t){return ip(A,i,e,t)}static fromPrivateKey(e){return A.BASE.multiply(_b(i,e))}}A.BASE=new A(o.Gx,o.Gy,r.ONE),A.ZERO=new A(r.ZERO,r.ONE,r.ZERO),A.Fp=r,A.Fn=i;const T=i.BITS,E=new rp(A,t.endo?Math.ceil(T/2):T);return A.BASE.precompute(8),A}function Pb(e){return Uint8Array.of(e?2:3)}function Db(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function Rb(e,t={}){const{Fn:n}=e,r=t.randomBytes||Th,i=Object.assign(Db(e.Fp,n),{seed:zg(n.ORDER)});function o(e){try{return!!_b(n,e)}catch(e){return!1}}function s(e=r(i.seed)){return function(e,t,n=!1){const r=e.length,i=Wg(t),o=zg(t);if(r<16||r<o||r>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+r);const s=Bg(n?ug(e):lg(e),t-Sg)+Sg;return n?hg(s,i):dg(s,i)}(sg(e,i.seed,"seed"),n.ORDER)}function a(t,r=!0){return e.BASE.multiply(_b(n,t)).toBytes(r)}function c(t){if("bigint"==typeof t)return!1;if(t instanceof e)return!0;const{secretKey:r,publicKey:o,publicKeyUncompressed:s}=i;if(n.allowedLengths||r===o)return;const a=gg("key",t).length;return a===o||a===s}const l={isValidSecretKey:o,isValidPublicKey:function(t,n){const{publicKey:r,publicKeyUncompressed:o}=i;try{const i=t.length;return(!0!==n||i===r)&&((!1!==n||i===o)&&!!e.fromBytes(t))}catch(e){return!1}},randomSecretKey:s,isValidPrivateKey:o,randomPrivateKey:s,normPrivateKeyToScalar:e=>_b(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 o=_b(n,t);return e.fromHex(r).multiply(o).toBytes(i)},keygen:function(e){const t=s(e);return{secretKey:t,publicKey:a(t)}},Point:e,utils:l,lengths:i})}function Mb(e,t,n={}){ih(t),kg(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const r=n.randomBytes||Th,i=n.hmac||((e,...n)=>kb(t,e,vh(...n))),{Fp:o,Fn:s}=e,{ORDER:a,BITS:c}=s,{keygen:l,getPublicKey:u,getSharedSecret:d,utils:h,lengths:g}=Rb(e,n),p={prehash:!1,lowS:"boolean"==typeof n.lowS&&n.lowS,format:void 0,extraEntropy:!1},f="compact";function m(e){return e>a>>Ib}function y(e,t){if(!s.isValidNot0(t))throw new Error(`invalid signature ${e}: out of range 1..Point.Fn.ORDER`);return t}class w{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=f){let n;if(function(e,t){vb(t);const n=g.signature;sg(e,"compact"===t?n:"recovered"===t?n+1:void 0,`${t} signature`)}(e,t),"der"===t){const{r:t,s:n}=Tb.toSig(sg(e));return new w(t,n)}"recovered"===t&&(n=e[0],t="compact",e=e.subarray(1));const r=s.BYTES,i=e.subarray(0,r),o=e.subarray(r,2*r);return new w(s.fromBytes(i),s.fromBytes(o),n)}static fromHex(e,t){return this.fromBytes(kh(e),t)}addRecoveryBit(e){return new w(this.r,this.s,e)}recoverPublicKey(t){const n=o.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*xb<n&&c>1)throw new Error("recovery id is ambiguous for h>1 curve");const l=2===c||3===c?r+a:r;if(!o.isValid(l))throw new Error("recovery id 2 or 3 invalid");const u=o.toBytes(l),d=e.fromBytes(vh(Pb(!(1&c)),u)),h=s.inv(l),g=b(gg("msgHash",t)),p=s.create(-g*h),f=s.create(i*h),m=e.BASE.multiplyUnsafe(p).add(d.multiplyUnsafe(f));if(m.is0())throw new Error("point at infinify");return m.assertValidity(),m}hasHighS(){return m(this.s)}toBytes(e=f){if(vb(e),"der"===e)return kh(Tb.hexFromSig(this));const t=s.toBytes(this.r),n=s.toBytes(this.s);if("recovered"===e){if(null==this.recovery)throw new Error("recovery bit must be present");return vh(Uint8Array.of(this.recovery),t,n)}return vh(t,n)}toHex(e){return dh(this.toBytes(e))}assertValidity(){}static fromCompact(e){return w.fromBytes(gg("sig",e),"compact")}static fromDER(e){return w.fromBytes(gg("sig",e),"der")}normalizeS(){return this.hasHighS()?new w(this.r,s.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return dh(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return dh(this.toBytes("compact"))}}const k=n.bits2int||function(e){if(e.length>8192)throw new Error("input is too large");const t=lg(e),n=8*e.length-c;return n>0?t>>BigInt(n):t},b=n.bits2int_modN||function(e){return s.create(k(e))},v=wg(c);function S(e){return mg("num < 2^"+c,e,Eb,v),s.toBytes(e)}function A(e,n){return sg(e,void 0,"message"),n?sg(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,o,a={}){n=gg("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:o,prehash:a,extraEntropy:c}=Sb(i,p);t=A(t,a);const l=b(t),u=_b(s,n),d=[S(u),S(l)];if(null!=c&&!1!==c){const e=!0===c?r(g.secretKey):c;d.push(gg("extraEntropy",e))}const h=vh(...d),f=l;return{seed:h,k2sig:function(t){const n=k(t);if(!s.isValidNot0(n))return;const r=s.inv(n),i=e.BASE.multiply(n).toAffine(),a=s.create(i.x);if(a===Eb)return;const c=s.create(r*s.create(f+a*u));if(c===Eb)return;let l=(i.x===a?0:2)|Number(i.y&Ib),d=c;return o&&m(c)&&(d=s.neg(c),l^=1),new w(a,d,l)}}}(n,o,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 o=r(e),s=r(e),a=0;const c=()=>{o.fill(1),s.fill(0),a=0},l=(...e)=>n(s,o,...e),u=(e=r(0))=>{s=l(i(0),e),o=l(),0!==e.length&&(s=l(i(1),e),o=l())},d=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let e=0;const n=[];for(;e<t;){o=l();const t=o.slice();n.push(t),e+=o.length}return vh(...n)};return(e,t)=>{let n;for(c(),u(e);!(n=t(d()));)u();return c(),n}}(t.outputLen,s.BYTES,i)(c,l)},verify:function(t,n,r,i={}){const{lowS:o,prehash:a,format:c}=Sb(i,p);if(r=gg("publicKey",r),n=A(gg("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||th(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 w(e.r,e.s);else if(n){try{t=w.fromBytes(gg("sig",e),"der")}catch(e){if(!(e instanceof Tb.Err))throw e}if(!t)try{t=w.fromBytes(gg("sig",e),"compact")}catch(e){return!1}}return t||!1}(t):w.fromBytes(gg("sig",t),c);if(!1===l)return!1;try{const t=e.fromBytes(r);if(o&&l.hasHighS())return!1;const{r:i,s:a}=l,c=b(n),u=s.inv(a),d=s.create(c*u),h=s.create(i*u),g=e.BASE.multiplyUnsafe(d).add(t.multiplyUnsafe(h));if(g.is0())return!1;return s.create(g.x)===i}catch(e){return!1}},recoverPublicKey:function(e,t,n={}){const{prehash:r}=Sb(n,p);return t=A(t,r),w.fromBytes(e,"recovered").recoverPublicKey(t).toBytes()},Signature:w,hash:t})}function Lb(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:Gg(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 Ob(e){const{CURVE:t,curveOpts:n,hash:r,ecdsaOpts:i}=Lb(e);return function(e,t){const n=t.Point;return Object.assign({},t,{ProjectivePoint:n,CURVE:Object.assign({},e,Kg(n.Fn.ORDER,n.Fn.BITS))})}(e,Mb(Bb(t,n),r,i))}const Fb={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Ub={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},$b=BigInt(2);const qb=Gg(Fb.p,{sqrt:function(e){const t=Fb.p,n=BigInt(3),r=BigInt(6),i=BigInt(11),o=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),l=e*e*e%t,u=l*l*e%t,d=Pg(u,n,t)*u%t,h=Pg(d,n,t)*u%t,g=Pg(h,$b,t)*l%t,p=Pg(g,i,t)*g%t,f=Pg(p,o,t)*p%t,m=Pg(f,a,t)*f%t,y=Pg(m,c,t)*m%t,w=Pg(y,a,t)*f%t,k=Pg(w,n,t)*u%t,b=Pg(k,s,t)*p%t,v=Pg(b,r,t)*l%t,S=Pg(v,$b,t);if(!qb.eql(qb.sqr(S),e))throw new Error("Cannot find square root");return S}}),Kb=function(e,t){const n=t=>Ob({...e,hash:t});return{...n(t),create:n}}({...Fb,Fp:qb,lowS:!0,endo:Ub},tg);Tp.utils.randomPrivateKey;const Gb=()=>{const e=Tp.utils.randomPrivateKey(),t=Wb(e),n=new Uint8Array(64);return n.set(e),n.set(t,32),{publicKey:t,secretKey:n}},Wb=Tp.getPublicKey;function zb(e){try{return Tp.ExtendedPoint.fromHex(e),!0}catch{return!1}}const Hb=Tp.verify,jb=e=>Yd.Buffer.isBuffer(e)?e:e instanceof Uint8Array?Yd.Buffer.from(e.buffer,e.byteOffset,e.byteLength):Yd.Buffer.from(e);class Vb{constructor(e){Object.assign(this,e)}encode(){return Yd.Buffer.from(af.serialize(Xb,this))}static decode(e){return af.deserialize(Xb,this,e)}static decodeUnchecked(e){return af.deserializeUnchecked(Xb,this,e)}}const Xb=new Map;var Qb;const Jb=32;let Zb=1;class Yb extends Vb{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=Up.decode(e);if(t.length!=Jb)throw new Error("Invalid public key input");this._bn=new Mp(t)}else this._bn=new Mp(e);if(this._bn.byteLength()>Jb)throw new Error("Invalid public key input")}}static unique(){const e=new Yb(Zb);return Zb+=1,new Yb(e.toBuffer())}equals(e){return this._bn.eq(e._bn)}toBase58(){return Up.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(Yd.Buffer);if(e.length===Jb)return e;const t=Yd.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=Yd.Buffer.concat([e.toBuffer(),Yd.Buffer.from(t),n.toBuffer()]),i=$p(r);return new Yb(i)}static createProgramAddressSync(e,t){let n=Yd.Buffer.alloc(0);e.forEach(function(e){if(e.length>32)throw new TypeError("Max seed length exceeded");n=Yd.Buffer.concat([n,jb(e)])}),n=Yd.Buffer.concat([n,t.toBuffer(),Yd.Buffer.from("ProgramDerivedAddress")]);const r=$p(n);if(zb(r))throw new Error("Invalid seeds, address must fall off the curve");return new Yb(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(Yd.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 zb(new Yb(e).toBytes())}}Qb=Yb,Yb.default=new Qb("11111111111111111111111111111111"),Xb.set(Yb,{kind:"struct",fields:[["_bn","u256"]]}),new Yb("BPFLoader1111111111111111111111111111111111");const ev=1232;class tv extends Error{constructor(e){super(`Signature ${e} has expired: block height exceeded.`),this.signature=void 0,this.signature=e}}Object.defineProperty(tv.prototype,"name",{value:"TransactionExpiredBlockheightExceededError"});class nv 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(nv.prototype,"name",{value:"TransactionExpiredTimeoutError"});class rv extends Error{constructor(e){super(`Signature ${e} has expired: the nonce is no longer valid.`),this.signature=void 0,this.signature=e}}Object.defineProperty(rv.prototype,"name",{value:"TransactionExpiredNonceInvalidError"});class iv{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 ov=(e="publicKey")=>lf.blob(32,e),sv=(e="string")=>{const t=lf.struct([lf.u32("length"),lf.u32("lengthPadding"),lf.blob(lf.offset(lf.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:Yd.Buffer.from(e,"utf8")};return r(i,t,n)},i.alloc=e=>lf.u32().span+lf.u32().span+Yd.Buffer.from(e,"utf8").length,i};function av(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 av({layout:e},t[e.property]);return 0};let r=0;return e.layout.fields.forEach(e=>{r+=n(e)}),r}function cv(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 lv(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 uv(e,t){if(!e)throw new Error(t||"Assertion failed")}class dv{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 dv(t,n)}getMessageComponents(){const e=[...this.keyMetaMap.entries()];uv(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),o={numRequiredSignatures:t.length+n.length,numReadonlySignedAccounts:n.length,numReadonlyUnsignedAccounts:i.length};{uv(t.length>0,"Expected at least one writable signer key");const[e]=t[0];uv(e===this.payer.toBase58(),"Expected first writable signer key to be the fee payer")}return[o,[...t.map(([e])=>new Yb(e)),...n.map(([e])=>new Yb(e)),...r.map(([e])=>new Yb(e)),...i.map(([e])=>new Yb(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,o]of this.keyMetaMap.entries())if(t(o)){const t=new Yb(i),o=e.findIndex(e=>e.equals(t));o>=0&&(uv(o<256,"Max lookup table index exceeded"),n.push(o),r.push(t),this.keyMetaMap.delete(i))}return[n,r]}}const hv="Reached end of buffer unexpectedly";function gv(e){if(0===e.length)throw new Error(hv);return e.shift()}function pv(e,...t){const[n]=t;if(2===t.length?n+(t[1]??0)>e.length:n>=e.length)throw new Error(hv);return e.splice(...t)}class fv{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 Yb(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:Up.decode(e.data)}))}get addressTableLookups(){return[]}getAccountKeys(){return new iv(this.staticAccountKeys)}static compile(e){const t=dv.compile(e.instructions,e.payerKey),[n,r]=t.getMessageComponents(),i=new iv(r).compileInstructions(e.instructions).map(e=>({programIdIndex:e.programIdIndex,accounts:e.accountKeyIndexes,data:Up.encode(e.data)}));return new fv({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=[];lv(t,e);const n=this.instructions.map(e=>{const{accounts:t,programIdIndex:n}=e,r=Array.from(Up.decode(e.data));let i=[];lv(i,t.length);let o=[];return lv(o,r.length),{programIdIndex:n,keyIndicesCount:Yd.Buffer.from(i),keyIndices:t,dataLength:Yd.Buffer.from(o),data:r}});let r=[];lv(r,n.length);let i=Yd.Buffer.alloc(ev);Yd.Buffer.from(r).copy(i);let o=r.length;n.forEach(e=>{const t=lf.struct([lf.u8("programIdIndex"),lf.blob(e.keyIndicesCount.length,"keyIndicesCount"),lf.seq(lf.u8("keyIndex"),e.keyIndices.length,"keyIndices"),lf.blob(e.dataLength.length,"dataLength"),lf.seq(lf.u8("userdatum"),e.data.length,"data")]).encode(e,i,o);o+=t}),i=i.slice(0,o);const s=lf.struct([lf.blob(1,"numRequiredSignatures"),lf.blob(1,"numReadonlySignedAccounts"),lf.blob(1,"numReadonlyUnsignedAccounts"),lf.blob(t.length,"keyCount"),lf.seq(ov("key"),e,"keys"),ov("recentBlockhash")]),a={numRequiredSignatures:Yd.Buffer.from([this.header.numRequiredSignatures]),numReadonlySignedAccounts:Yd.Buffer.from([this.header.numReadonlySignedAccounts]),numReadonlyUnsignedAccounts:Yd.Buffer.from([this.header.numReadonlyUnsignedAccounts]),keyCount:Yd.Buffer.from(t),keys:this.accountKeys.map(e=>jb(e.toBytes())),recentBlockhash:Up.decode(this.recentBlockhash)};let c=Yd.Buffer.alloc(2048);const l=s.encode(a,c);return i.copy(c,l),c.slice(0,l+i.length)}static from(e){let t=[...e];const n=gv(t);if(n!==(127&n))throw new Error("Versioned messages must be deserialized with VersionedMessage.deserialize()");const r=gv(t),i=gv(t),o=cv(t);let s=[];for(let e=0;e<o;e++){const e=pv(t,0,Jb);s.push(new Yb(Yd.Buffer.from(e)))}const a=pv(t,0,Jb),c=cv(t);let l=[];for(let e=0;e<c;e++){const e=gv(t),n=pv(t,0,cv(t)),r=pv(t,0,cv(t)),i=Up.encode(Yd.Buffer.from(r));l.push({programIdIndex:e,accounts:n,data:i})}const u={header:{numRequiredSignatures:n,numReadonlySignedAccounts:r,numReadonlyUnsignedAccounts:i},recentBlockhash:Up.encode(Yd.Buffer.from(a)),accountKeys:s,instructions:l};return new fv(u)}}class mv{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 iv(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=dv.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:o}]=i;n.push(e),r.writable.push(...t),r.readonly.push(...o)}}const[o,s]=t.getMessageComponents(),a=new iv(s,r).compileInstructions(e.instructions);return new mv({header:o,staticAccountKeys:s,recentBlockhash:e.recentBlockhash,compiledInstructions:a,addressTableLookups:n})}serialize(){const e=Array();lv(e,this.staticAccountKeys.length);const t=this.serializeInstructions(),n=Array();lv(n,this.compiledInstructions.length);const r=this.serializeAddressTableLookups(),i=Array();lv(i,this.addressTableLookups.length);const o=lf.struct([lf.u8("prefix"),lf.struct([lf.u8("numRequiredSignatures"),lf.u8("numReadonlySignedAccounts"),lf.u8("numReadonlyUnsignedAccounts")],"header"),lf.blob(e.length,"staticAccountKeysLength"),lf.seq(ov(),this.staticAccountKeys.length,"staticAccountKeys"),ov("recentBlockhash"),lf.blob(n.length,"instructionsLength"),lf.blob(t.length,"serializedInstructions"),lf.blob(i.length,"addressTableLookupsLength"),lf.blob(r.length,"serializedAddressTableLookups")]),s=new Uint8Array(ev),a=o.encode({prefix:128,header:this.header,staticAccountKeysLength:new Uint8Array(e),staticAccountKeys:this.staticAccountKeys.map(e=>e.toBytes()),recentBlockhash:Up.decode(this.recentBlockhash),instructionsLength:new Uint8Array(n),serializedInstructions:t,addressTableLookupsLength:new Uint8Array(i),serializedAddressTableLookups:r},s);return s.slice(0,a)}serializeInstructions(){let e=0;const t=new Uint8Array(ev);for(const n of this.compiledInstructions){const r=Array();lv(r,n.accountKeyIndexes.length);const i=Array();lv(i,n.data.length);e+=lf.struct([lf.u8("programIdIndex"),lf.blob(r.length,"encodedAccountKeyIndexesLength"),lf.seq(lf.u8(),n.accountKeyIndexes.length,"accountKeyIndexes"),lf.blob(i.length,"encodedDataLength"),lf.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(ev);for(const n of this.addressTableLookups){const r=Array();lv(r,n.writableIndexes.length);const i=Array();lv(i,n.readonlyIndexes.length);e+=lf.struct([ov("accountKey"),lf.blob(r.length,"encodedWritableIndexesLength"),lf.seq(lf.u8(),n.writableIndexes.length,"writableIndexes"),lf.blob(i.length,"encodedReadonlyIndexesLength"),lf.seq(lf.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=gv(t),r=127&n;uv(n!==r,"Expected versioned message but received legacy message");uv(0===r,`Expected versioned message with version 0 but found version ${r}`);const i={numRequiredSignatures:gv(t),numReadonlySignedAccounts:gv(t),numReadonlyUnsignedAccounts:gv(t)},o=[],s=cv(t);for(let e=0;e<s;e++)o.push(new Yb(pv(t,0,Jb)));const a=Up.encode(pv(t,0,Jb)),c=cv(t),l=[];for(let e=0;e<c;e++){const e=gv(t),n=pv(t,0,cv(t)),r=cv(t),i=new Uint8Array(pv(t,0,r));l.push({programIdIndex:e,accountKeyIndexes:n,data:i})}const u=cv(t),d=[];for(let e=0;e<u;e++){const e=new Yb(pv(t,0,Jb)),n=pv(t,0,cv(t)),r=pv(t,0,cv(t));d.push({accountKey:e,writableIndexes:n,readonlyIndexes:r})}return new mv({header:i,staticAccountKeys:o,recentBlockhash:a,compiledInstructions:l,addressTableLookups:d})}}let yv=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 wv=Yd.Buffer.alloc(64).fill(0);class kv{constructor(e){this.keys=void 0,this.programId=void 0,this.data=Yd.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 bv{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 kv(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 Yb(e),isSigner:!1,isWritable:!1})});const o=[];i.forEach(e=>{const t=e.pubkey.toString(),n=o.findIndex(e=>e.pubkey.toString()===t);n>-1?(o[n].isWritable=o[n].isWritable||e.isWritable,o[n].isSigner=o[n].isSigner||e.isSigner):o.push(e)}),o.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 s=o.findIndex(e=>e.pubkey.equals(n));if(s>-1){const[e]=o.splice(s,1);e.isSigner=!0,e.isWritable=!0,o.unshift(e)}else o.unshift({pubkey:n,isSigner:!0,isWritable:!0});for(const e of this.signatures){const t=o.findIndex(t=>t.pubkey.equals(e.publicKey));if(!(t>-1))throw new Error(`unknown signer: ${e.publicKey.toString()}`);o[t].isSigner||(o[t].isSigner=!0)}let a=0,c=0,l=0;const u=[],d=[];o.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:Up.encode(t)}});return g.forEach(e=>{uv(e.programIdIndex>=0),e.accounts.forEach(e=>uv(e>=0))}),new fv({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)=>Tp.sign(e,t.slice(0,32)))(n,e.secretKey);this._addSignature(e.publicKey,jb(t))})}addSignature(e,t){this._compile(),this._addSignature(e,t)}_addSignature(e,t){uv(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=Yd.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):Hb(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=[];lv(n,t.length);const r=n.length+64*t.length+e.length,i=Yd.Buffer.alloc(r);return uv(t.length<256),Yd.Buffer.from(n).copy(i,0),t.forEach(({signature:e},t)=>{null!==e&&(uv(64===e.length,"signature has invalid length"),Yd.Buffer.from(e).copy(i,n.length+64*t))}),e.copy(i,n.length+64*t.length),uv(i.length<=ev,`Transaction too large: ${i.length} > 1232`),i}get keys(){return uv(1===this.instructions.length),this.instructions[0].keys.map(e=>e.pubkey)}get programId(){return uv(1===this.instructions.length),this.instructions[0].programId}get data(){return uv(1===this.instructions.length),this.instructions[0].data}static from(e){let t=[...e];const n=cv(t);let r=[];for(let e=0;e<n;e++){const e=pv(t,0,64);r.push(Up.encode(Yd.Buffer.from(e)))}return bv.populate(fv.from(t),r)}static populate(e,t=[]){const n=new bv;return n.recentBlockhash=e.recentBlockhash,e.header.numRequiredSignatures>0&&(n.feePayer=e.accountKeys[0]),t.forEach((t,r)=>{const i={signature:t==Up.encode(wv)?null:Up.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 kv({keys:r,programId:e.accountKeys[t.programIdIndex],data:Up.decode(t.data)}))}),n._message=e,n._json=n.toJSON(),n}}new Yb("SysvarC1ock11111111111111111111111111111111"),new Yb("SysvarEpochSchedu1e111111111111111111111111"),new Yb("Sysvar1nstructions1111111111111111111111111");const vv=new Yb("SysvarRecentB1ockHashes11111111111111111111"),Sv=new Yb("SysvarRent111111111111111111111111111111111");new Yb("SysvarRewards111111111111111111111111111111"),new Yb("SysvarS1otHashes111111111111111111111111111"),new Yb("SysvarS1otHistory11111111111111111111111111"),new Yb("SysvarStakeHistory1111111111111111111111111");class Av extends Error{constructor({action:e,signature:t,transactionMessage:n,logs:r}){const i=r?`Logs: \n${JSON.stringify(r.slice(-10),null,2)}. `:"",o="\nCatch the `SendTransactionError` and call `getLogs()` on it for full details.";let s;switch(e){case"send":s=`Transaction ${t} resulted in an error. \n${n}. `+i+o;break;case"simulate":s=`Simulation failed. \nMessage: ${n}. \n`+i+o;break;default:s=`Unknown action '${e}'`}super(s),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 Tv 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 Ev(e){return new Promise(t=>setTimeout(t,e))}function Iv(e,t){const n=e.layout.span>=0?e.layout.span:av(e,t),r=Yd.Buffer.alloc(n),i=Object.assign({instruction:e.index},t);return e.layout.encode(i,r),r}const xv=lf.nu64("lamportsPerSignature"),Cv=lf.struct([lf.u32("version"),lf.u32("state"),ov("authorizedPubkey"),ov("nonce"),lf.struct([xv],"feeCalculator")]),Nv=Cv.span;class _v{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=Cv.decode(jb(e),0);return new _v({authorizedPubkey:new Yb(t.authorizedPubkey),nonce:new Yb(t.nonce).toString(),feeCalculator:t.feeCalculator})}}function Bv(e){const t=lf.blob(8,e),n=t.decode.bind(t),r=t.encode.bind(t),i=t,o=Pk();return i.decode=(e,t)=>{const r=n(e,t);return o.decode(r)},i.encode=(e,t,n)=>{const i=o.encode(e);return r(i,t,n)},i}const Pv=Object.freeze({Create:{index:0,layout:lf.struct([lf.u32("instruction"),lf.ns64("lamports"),lf.ns64("space"),ov("programId")])},Assign:{index:1,layout:lf.struct([lf.u32("instruction"),ov("programId")])},Transfer:{index:2,layout:lf.struct([lf.u32("instruction"),Bv("lamports")])},CreateWithSeed:{index:3,layout:lf.struct([lf.u32("instruction"),ov("base"),sv("seed"),lf.ns64("lamports"),lf.ns64("space"),ov("programId")])},AdvanceNonceAccount:{index:4,layout:lf.struct([lf.u32("instruction")])},WithdrawNonceAccount:{index:5,layout:lf.struct([lf.u32("instruction"),lf.ns64("lamports")])},InitializeNonceAccount:{index:6,layout:lf.struct([lf.u32("instruction"),ov("authorized")])},AuthorizeNonceAccount:{index:7,layout:lf.struct([lf.u32("instruction"),ov("authorized")])},Allocate:{index:8,layout:lf.struct([lf.u32("instruction"),lf.ns64("space")])},AllocateWithSeed:{index:9,layout:lf.struct([lf.u32("instruction"),ov("base"),sv("seed"),lf.ns64("space"),ov("programId")])},AssignWithSeed:{index:10,layout:lf.struct([lf.u32("instruction"),ov("base"),sv("seed"),ov("programId")])},TransferWithSeed:{index:11,layout:lf.struct([lf.u32("instruction"),Bv("lamports"),sv("seed"),ov("programId")])},UpgradeNonceAccount:{index:12,layout:lf.struct([lf.u32("instruction")])}});class Dv{constructor(){}static createAccount(e){const t=Iv(Pv.Create,{lamports:e.lamports,space:e.space,programId:jb(e.programId.toBuffer())});return new kv({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=Iv(Pv.TransferWithSeed,{lamports:BigInt(e.lamports),seed:e.seed,programId:jb(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=Iv(Pv.Transfer,{lamports:BigInt(e.lamports)}),n=[{pubkey:e.fromPubkey,isSigner:!0,isWritable:!0},{pubkey:e.toPubkey,isSigner:!1,isWritable:!0}]}return new kv({keys:n,programId:this.programId,data:t})}static assign(e){let t,n;if("basePubkey"in e){t=Iv(Pv.AssignWithSeed,{base:jb(e.basePubkey.toBuffer()),seed:e.seed,programId:jb(e.programId.toBuffer())}),n=[{pubkey:e.accountPubkey,isSigner:!1,isWritable:!0},{pubkey:e.basePubkey,isSigner:!0,isWritable:!1}]}else{t=Iv(Pv.Assign,{programId:jb(e.programId.toBuffer())}),n=[{pubkey:e.accountPubkey,isSigner:!0,isWritable:!0}]}return new kv({keys:n,programId:this.programId,data:t})}static createAccountWithSeed(e){const t=Iv(Pv.CreateWithSeed,{base:jb(e.basePubkey.toBuffer()),seed:e.seed,lamports:e.lamports,space:e.space,programId:jb(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 kv({keys:n,programId:this.programId,data:t})}static createNonceAccount(e){const t=new bv;"basePubkey"in e&&"seed"in e?t.add(Dv.createAccountWithSeed({fromPubkey:e.fromPubkey,newAccountPubkey:e.noncePubkey,basePubkey:e.basePubkey,seed:e.seed,lamports:e.lamports,space:Nv,programId:this.programId})):t.add(Dv.createAccount({fromPubkey:e.fromPubkey,newAccountPubkey:e.noncePubkey,lamports:e.lamports,space:Nv,programId:this.programId}));const n={noncePubkey:e.noncePubkey,authorizedPubkey:e.authorizedPubkey};return t.add(this.nonceInitialize(n)),t}static nonceInitialize(e){const t=Iv(Pv.InitializeNonceAccount,{authorized:jb(e.authorizedPubkey.toBuffer())}),n={keys:[{pubkey:e.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:vv,isSigner:!1,isWritable:!1},{pubkey:Sv,isSigner:!1,isWritable:!1}],programId:this.programId,data:t};return new kv(n)}static nonceAdvance(e){const t=Iv(Pv.AdvanceNonceAccount),n={keys:[{pubkey:e.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:vv,isSigner:!1,isWritable:!1},{pubkey:e.authorizedPubkey,isSigner:!0,isWritable:!1}],programId:this.programId,data:t};return new kv(n)}static nonceWithdraw(e){const t=Iv(Pv.WithdrawNonceAccount,{lamports:e.lamports});return new kv({keys:[{pubkey:e.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:e.toPubkey,isSigner:!1,isWritable:!0},{pubkey:vv,isSigner:!1,isWritable:!1},{pubkey:Sv,isSigner:!1,isWritable:!1},{pubkey:e.authorizedPubkey,isSigner:!0,isWritable:!1}],programId:this.programId,data:t})}static nonceAuthorize(e){const t=Iv(Pv.AuthorizeNonceAccount,{authorized:jb(e.newAuthorizedPubkey.toBuffer())});return new kv({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=Iv(Pv.AllocateWithSeed,{base:jb(e.basePubkey.toBuffer()),seed:e.seed,space:e.space,programId:jb(e.programId.toBuffer())}),n=[{pubkey:e.accountPubkey,isSigner:!1,isWritable:!0},{pubkey:e.basePubkey,isSigner:!0,isWritable:!1}]}else{t=Iv(Pv.Allocate,{space:e.space}),n=[{pubkey:e.accountPubkey,isSigner:!0,isWritable:!0}]}return new kv({keys:n,programId:this.programId,data:t})}}function Rv(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Mv,Lv;function Ov(){if(Lv)return Mv;Lv=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 o,s,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="[",s=r.length-1,o=0;o<s;o++)a+=n(r[o],!0)+",";return s>-1&&(a+=n(r[o],!0)),a+"]"}if("[object Object]"===d){for(s=(c=t(r).sort()).length,a="",o=0;o<s;)void 0!==(u=n(r[l=c[o]],!1))&&(a&&(a+=","),a+=JSON.stringify(l)+":"+u),o++;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 Mv=function(e){var t=n(e,!1);if(void 0!==t)return""+t}}Dv.programId=new Yb("11111111111111111111111111111111"),new Yb("BPFLoader2111111111111111111111111111111111");var Fv=Rv(Ov());function Uv(e){let t=0;for(;e>1;)e/=2,t++;return t}class $v{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=Uv(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)))-Uv(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+Uv(32)):this.slotsPerEpoch}}var qv=globalThis.fetch;class Kv extends yb{constructor(e,t,n){super(e=>{const n=function(e,t){return new fb(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 Gv{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}(Wv,e),n=e.length-56;uv(n>=0,"lookup table is invalid"),uv(n%32==0,"lookup table is invalid");const r=n/32,{addresses:i}=lf.struct([lf.seq(ov(),r,"addresses")]).decode(e.slice(56));return{deactivationSlot:t.deactivationSlot,lastExtendedSlot:t.lastExtendedSlot,lastExtendedSlotStartIndex:t.lastExtendedStartIndex,authority:0!==t.authority.length?new Yb(t.authority[0]):void 0,addresses:i.map(e=>new Yb(e))}}}const Wv={index:1,layout:lf.struct([lf.u32("typeIndex"),Bv("deactivationSlot"),lf.nu64("lastExtendedSlot"),lf.u8("lastExtendedStartIndex"),lf.u8(),lf.seq(ov(),lf.offset(lf.u8(),-1),"authority")])},zv=/^[^:]+:\/\/([^:[]+|\[[^\]]+\])(:\d+)?(.*)/i;const Hv=ib(jk(Yb),Yk(),e=>new Yb(e)),jv=eb([Yk(),Vk("base64")]),Vv=ib(jk(Yd.Buffer),jv,e=>Yd.Buffer.from(e[0],"base64"));function Xv(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 Qv(e){return e.map(e=>"memcmp"in e?{...e,memcmp:{...e.memcmp,encoding:e.memcmp.encoding??"base58"}}:e)}function Jv(e){return nb([tb({jsonrpc:Vk("2.0"),id:Yk(),result:e}),tb({jsonrpc:Vk("2.0"),id:Yk(),error:tb({code:rb(),message:Yk(),data:Jk(Wk("any",()=>!0))})})])}const Zv=Jv(rb());function Yv(e){return ib(Jv(e),Zv,t=>"error"in t?t:{...t,result:qk(t.result,e)})}function eS(e){return Yv(tb({context:tb({slot:Qk()}),value:e}))}function tS(e){return tb({context:tb({slot:Qk()}),value:e})}function nS(e,t){return 0===e?new mv({header:t.header,staticAccountKeys:t.accountKeys.map(e=>new Yb(e)),recentBlockhash:t.recentBlockhash,compiledInstructions:t.instructions.map(e=>({programIdIndex:e.programIdIndex,accountKeyIndexes:e.accounts,data:Up.decode(e.data)})),addressTableLookups:t.addressTableLookups}):new fv(t)}const rS=tb({foundation:Qk(),foundationTerm:Qk(),initial:Qk(),taper:Qk(),terminal:Qk()}),iS=Yv(zk(Xk(tb({epoch:Qk(),effectiveSlot:Qk(),amount:Qk(),postBalance:Qk(),commission:Jk(Xk(Qk()))})))),oS=zk(tb({slot:Qk(),prioritizationFee:Qk()})),sS=tb({total:Qk(),validator:Qk(),foundation:Qk(),epoch:Qk()}),aS=tb({epoch:Qk(),slotIndex:Qk(),slotsInEpoch:Qk(),absoluteSlot:Qk(),blockHeight:Jk(Qk()),transactionCount:Jk(Qk())}),cS=tb({slotsPerEpoch:Qk(),leaderScheduleSlotOffset:Qk(),warmup:Hk(),firstNormalEpoch:Qk(),firstNormalSlot:Qk()}),lS=Zk(Yk(),zk(Qk())),uS=Xk(nb([tb({}),Yk()])),dS=tb({err:uS}),hS=Vk("receivedSignature"),gS=tb({"solana-core":Yk(),"feature-set":Jk(Qk())}),pS=tb({program:Yk(),programId:Hv,parsed:rb()}),fS=tb({programId:Hv,accounts:zk(Hv),data:Yk()}),mS=eS(tb({err:Xk(nb([tb({}),Yk()])),logs:Xk(zk(Yk())),accounts:Jk(Xk(zk(Xk(tb({executable:Hk(),owner:Yk(),lamports:Qk(),data:zk(Yk()),rentEpoch:Jk(Qk())}))))),unitsConsumed:Jk(Qk()),returnData:Jk(Xk(tb({programId:Yk(),data:eb([Yk(),Vk("base64")])}))),innerInstructions:Jk(Xk(zk(tb({index:Qk(),instructions:zk(nb([pS,fS]))}))))})),yS=eS(tb({byIdentity:Zk(Yk(),zk(Qk())),range:tb({firstSlot:Qk(),lastSlot:Qk()})}));const wS=Yv(rS),kS=Yv(sS),bS=Yv(oS),vS=Yv(aS),SS=Yv(cS),AS=Yv(lS),TS=Yv(Qk()),ES=eS(tb({total:Qk(),circulating:Qk(),nonCirculating:Qk(),nonCirculatingAccounts:zk(Hv)})),IS=tb({amount:Yk(),uiAmount:Xk(Qk()),decimals:Qk(),uiAmountString:Jk(Yk())}),xS=eS(zk(tb({address:Hv,amount:Yk(),uiAmount:Xk(Qk()),decimals:Qk(),uiAmountString:Jk(Yk())}))),CS=eS(zk(tb({pubkey:Hv,account:tb({executable:Hk(),owner:Hv,lamports:Qk(),data:Vv,rentEpoch:Qk()})}))),NS=tb({program:Yk(),parsed:rb(),space:Qk()}),_S=eS(zk(tb({pubkey:Hv,account:tb({executable:Hk(),owner:Hv,lamports:Qk(),data:NS,rentEpoch:Qk()})}))),BS=eS(zk(tb({lamports:Qk(),address:Hv}))),PS=tb({executable:Hk(),owner:Hv,lamports:Qk(),data:Vv,rentEpoch:Qk()}),DS=tb({pubkey:Hv,account:PS}),RS=ib(nb([jk(Yd.Buffer),NS]),nb([jv,NS]),e=>Array.isArray(e)?qk(e,Vv):e),MS=tb({executable:Hk(),owner:Hv,lamports:Qk(),data:RS,rentEpoch:Qk()}),LS=tb({pubkey:Hv,account:MS}),OS=tb({state:nb([Vk("active"),Vk("inactive"),Vk("activating"),Vk("deactivating")]),active:Qk(),inactive:Qk()}),FS=Yv(zk(tb({signature:Yk(),slot:Qk(),err:uS,memo:Xk(Yk()),blockTime:Jk(Xk(Qk()))}))),US=Yv(zk(tb({signature:Yk(),slot:Qk(),err:uS,memo:Xk(Yk()),blockTime:Jk(Xk(Qk()))}))),$S=tb({subscription:Qk(),result:tS(PS)}),qS=tb({pubkey:Hv,account:PS}),KS=tb({subscription:Qk(),result:tS(qS)}),GS=tb({parent:Qk(),slot:Qk(),root:Qk()}),WS=tb({subscription:Qk(),result:GS}),zS=nb([tb({type:nb([Vk("firstShredReceived"),Vk("completed"),Vk("optimisticConfirmation"),Vk("root")]),slot:Qk(),timestamp:Qk()}),tb({type:Vk("createdBank"),parent:Qk(),slot:Qk(),timestamp:Qk()}),tb({type:Vk("frozen"),slot:Qk(),timestamp:Qk(),stats:tb({numTransactionEntries:Qk(),numSuccessfulTransactions:Qk(),numFailedTransactions:Qk(),maxTransactionsPerEntry:Qk()})}),tb({type:Vk("dead"),slot:Qk(),timestamp:Qk(),err:Yk()})]),HS=tb({subscription:Qk(),result:zS}),jS=tb({subscription:Qk(),result:tS(nb([dS,hS]))}),VS=tb({subscription:Qk(),result:Qk()}),XS=tb({pubkey:Yk(),gossip:Xk(Yk()),tpu:Xk(Yk()),rpc:Xk(Yk()),version:Xk(Yk())}),QS=tb({votePubkey:Yk(),nodePubkey:Yk(),activatedStake:Qk(),epochVoteAccount:Hk(),epochCredits:zk(eb([Qk(),Qk(),Qk()])),commission:Qk(),lastVote:Qk(),rootSlot:Xk(Qk())}),JS=Yv(tb({current:zk(QS),delinquent:zk(QS)})),ZS=nb([Vk("processed"),Vk("confirmed"),Vk("finalized")]),YS=tb({slot:Qk(),confirmations:Xk(Qk()),err:uS,confirmationStatus:Jk(ZS)}),eA=eS(zk(Xk(YS))),tA=Yv(Qk()),nA=tb({accountKey:Hv,writableIndexes:zk(Qk()),readonlyIndexes:zk(Qk())}),rA=tb({signatures:zk(Yk()),message:tb({accountKeys:zk(Yk()),header:tb({numRequiredSignatures:Qk(),numReadonlySignedAccounts:Qk(),numReadonlyUnsignedAccounts:Qk()}),instructions:zk(tb({accounts:zk(Qk()),data:Yk(),programIdIndex:Qk()})),recentBlockhash:Yk(),addressTableLookups:Jk(zk(nA))})}),iA=tb({pubkey:Hv,signer:Hk(),writable:Hk(),source:Jk(nb([Vk("transaction"),Vk("lookupTable")]))}),oA=tb({accountKeys:zk(iA),signatures:zk(Yk())}),sA=tb({parsed:rb(),program:Yk(),programId:Hv}),aA=tb({accounts:zk(Hv),data:Yk(),programId:Hv}),cA=ib(nb([aA,sA]),nb([tb({parsed:rb(),program:Yk(),programId:Yk()}),tb({accounts:zk(Yk()),data:Yk(),programId:Yk()})]),e=>qk(e,"accounts"in e?aA:sA)),lA=tb({signatures:zk(Yk()),message:tb({accountKeys:zk(iA),instructions:zk(cA),recentBlockhash:Yk(),addressTableLookups:Jk(Xk(zk(nA)))})}),uA=tb({accountIndex:Qk(),mint:Yk(),owner:Jk(Yk()),programId:Jk(Yk()),uiTokenAmount:IS}),dA=tb({writable:zk(Hv),readonly:zk(Hv)}),hA=tb({err:uS,fee:Qk(),innerInstructions:Jk(Xk(zk(tb({index:Qk(),instructions:zk(tb({accounts:zk(Qk()),data:Yk(),programIdIndex:Qk()}))})))),preBalances:zk(Qk()),postBalances:zk(Qk()),logMessages:Jk(Xk(zk(Yk()))),preTokenBalances:Jk(Xk(zk(uA))),postTokenBalances:Jk(Xk(zk(uA))),loadedAddresses:Jk(dA),computeUnitsConsumed:Jk(Qk()),costUnits:Jk(Qk())}),gA=tb({err:uS,fee:Qk(),innerInstructions:Jk(Xk(zk(tb({index:Qk(),instructions:zk(cA)})))),preBalances:zk(Qk()),postBalances:zk(Qk()),logMessages:Jk(Xk(zk(Yk()))),preTokenBalances:Jk(Xk(zk(uA))),postTokenBalances:Jk(Xk(zk(uA))),loadedAddresses:Jk(dA),computeUnitsConsumed:Jk(Qk()),costUnits:Jk(Qk())}),pA=nb([Vk(0),Vk("legacy")]),fA=tb({pubkey:Yk(),lamports:Qk(),postBalance:Xk(Qk()),rewardType:Xk(Yk()),commission:Jk(Xk(Qk()))}),mA=Yv(Xk(tb({blockhash:Yk(),previousBlockhash:Yk(),parentSlot:Qk(),transactions:zk(tb({transaction:rA,meta:Xk(hA),version:Jk(pA)})),rewards:Jk(zk(fA)),blockTime:Xk(Qk()),blockHeight:Xk(Qk())}))),yA=Yv(Xk(tb({blockhash:Yk(),previousBlockhash:Yk(),parentSlot:Qk(),rewards:Jk(zk(fA)),blockTime:Xk(Qk()),blockHeight:Xk(Qk())}))),wA=Yv(Xk(tb({blockhash:Yk(),previousBlockhash:Yk(),parentSlot:Qk(),transactions:zk(tb({transaction:oA,meta:Xk(hA),version:Jk(pA)})),rewards:Jk(zk(fA)),blockTime:Xk(Qk()),blockHeight:Xk(Qk())}))),kA=Yv(Xk(tb({blockhash:Yk(),previousBlockhash:Yk(),parentSlot:Qk(),transactions:zk(tb({transaction:lA,meta:Xk(gA),version:Jk(pA)})),rewards:Jk(zk(fA)),blockTime:Xk(Qk()),blockHeight:Xk(Qk())}))),bA=Yv(Xk(tb({blockhash:Yk(),previousBlockhash:Yk(),parentSlot:Qk(),transactions:zk(tb({transaction:oA,meta:Xk(gA),version:Jk(pA)})),rewards:Jk(zk(fA)),blockTime:Xk(Qk()),blockHeight:Xk(Qk())}))),vA=Yv(Xk(tb({blockhash:Yk(),previousBlockhash:Yk(),parentSlot:Qk(),rewards:Jk(zk(fA)),blockTime:Xk(Qk()),blockHeight:Xk(Qk())}))),SA=Yv(Xk(tb({blockhash:Yk(),previousBlockhash:Yk(),parentSlot:Qk(),transactions:zk(tb({transaction:rA,meta:Xk(hA)})),rewards:Jk(zk(fA)),blockTime:Xk(Qk())}))),AA=Yv(Xk(tb({blockhash:Yk(),previousBlockhash:Yk(),parentSlot:Qk(),signatures:zk(Yk()),blockTime:Xk(Qk())}))),TA=Yv(Xk(tb({slot:Qk(),meta:Xk(hA),blockTime:Jk(Xk(Qk())),transaction:rA,version:Jk(pA)}))),EA=Yv(Xk(tb({slot:Qk(),transaction:lA,meta:Xk(gA),blockTime:Jk(Xk(Qk())),version:Jk(pA)}))),IA=eS(tb({blockhash:Yk(),lastValidBlockHeight:Qk()})),xA=eS(Hk()),CA=Yv(zk(tb({slot:Qk(),numTransactions:Qk(),numSlots:Qk(),samplePeriodSecs:Qk()}))),NA=eS(Xk(tb({feeCalculator:tb({lamportsPerSignature:Qk()})}))),_A=Yv(Yk()),BA=Yv(Yk()),PA=tb({err:uS,logs:zk(Yk()),signature:Yk()}),DA=tb({result:tS(PA),subscription:Qk()}),RA={"solana-client":"js/1.0.0-maintenance"};class MA{constructor(e,t){let n,r,i,o,s,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}=Xv(t),i=this._buildArgs([],n,void 0,r),o=Fv(i);return e[o]=e[o]??(async()=>{try{const e=qk(await this._rpcRequest("getBlockHeight",i),Yv(Qk()));if("error"in e)throw new Tv(e.error,"failed to get block height information");return e.result}finally{delete e[o]}})(),await e[o]}})(),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,o=t.fetchMiddleware,s=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(zv);if(null==t)throw TypeError(`Failed to validate endpoint URL \`${e}\``);const[n,r,i,o]=t,s=e.startsWith("https:")?"wss:":"ws:",a=null==i?null:parseInt(i.slice(1),10);return`${s}//${r}${null==a?"":`:${a+1}`}${o}`}(e),this._rpcClient=function(e,t,n,r,i){const o=n||qv;let s;return r&&(s=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 o(...n)}),new db(async(n,r)=>{const a={method:"POST",body:n,agent:void 0,headers:Object.assign({"Content-Type":"application/json"},t||{},RA)};try{let t,n=5,c=500;for(;t=s?await s(e,a):await o(e,a),429===t.status&&!0!==i&&(n-=1,0!==n);)await Ev(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,o,s),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 Kv(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}=Xv(t),i=this._buildArgs([e.toBase58()],n,void 0,r),o=qk(await this._rpcRequest("getBalance",i),eS(Qk()));if("error"in o)throw new Tv(o.error,`failed to get balance for ${e.toBase58()}`);return o.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=qk(await this._rpcRequest("getBlockTime",[e]),Yv(Xk(Qk())));if("error"in t)throw new Tv(t.error,`failed to get block time for slot ${e}`);return t.result}async getMinimumLedgerSlot(){const e=qk(await this._rpcRequest("minimumLedgerSlot",[]),Yv(Qk()));if("error"in e)throw new Tv(e.error,"failed to get minimum ledger slot");return e.result}async getFirstAvailableBlock(){const e=qk(await this._rpcRequest("getFirstAvailableBlock",[]),TS);if("error"in e)throw new Tv(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=qk(await this._rpcRequest("getSupply",[t]),ES);if("error"in n)throw new Tv(n.error,"failed to get supply");return n.result}async getTokenSupply(e,t){const n=this._buildArgs([e.toBase58()],t),r=qk(await this._rpcRequest("getTokenSupply",n),eS(IS));if("error"in r)throw new Tv(r.error,"failed to get token supply");return r.result}async getTokenAccountBalance(e,t){const n=this._buildArgs([e.toBase58()],t),r=qk(await this._rpcRequest("getTokenAccountBalance",n),eS(IS));if("error"in r)throw new Tv(r.error,"failed to get token account balance");return r.result}async getTokenAccountsByOwner(e,t,n){const{commitment:r,config:i}=Xv(n);let o=[e.toBase58()];"mint"in t?o.push({mint:t.mint.toBase58()}):o.push({programId:t.programId.toBase58()});const s=this._buildArgs(o,r,"base64",i),a=qk(await this._rpcRequest("getTokenAccountsByOwner",s),CS);if("error"in a)throw new Tv(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"),o=qk(await this._rpcRequest("getTokenAccountsByOwner",i),_S);if("error"in o)throw new Tv(o.error,`failed to get token accounts owned by account ${e.toBase58()}`);return o.result}async getLargestAccounts(e){const t={...e,commitment:e&&e.commitment||this.commitment},n=t.filter||t.commitment?[t]:[],r=qk(await this._rpcRequest("getLargestAccounts",n),BS);if("error"in r)throw new Tv(r.error,"failed to get largest accounts");return r.result}async getTokenLargestAccounts(e,t){const n=this._buildArgs([e.toBase58()],t),r=qk(await this._rpcRequest("getTokenLargestAccounts",n),xS);if("error"in r)throw new Tv(r.error,"failed to get token largest accounts");return r.result}async getAccountInfoAndContext(e,t){const{commitment:n,config:r}=Xv(t),i=this._buildArgs([e.toBase58()],n,"base64",r),o=qk(await this._rpcRequest("getAccountInfo",i),eS(Xk(PS)));if("error"in o)throw new Tv(o.error,`failed to get info about account ${e.toBase58()}`);return o.result}async getParsedAccountInfo(e,t){const{commitment:n,config:r}=Xv(t),i=this._buildArgs([e.toBase58()],n,"jsonParsed",r),o=qk(await this._rpcRequest("getAccountInfo",i),eS(Xk(MS)));if("error"in o)throw new Tv(o.error,`failed to get info about account ${e.toBase58()}`);return o.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}=Xv(t),i=e.map(e=>e.toBase58()),o=this._buildArgs([i],n,"jsonParsed",r),s=qk(await this._rpcRequest("getMultipleAccounts",o),eS(zk(Xk(MS))));if("error"in s)throw new Tv(s.error,`failed to get info for accounts ${i}`);return s.result}async getMultipleAccountsInfoAndContext(e,t){const{commitment:n,config:r}=Xv(t),i=e.map(e=>e.toBase58()),o=this._buildArgs([i],n,"base64",r),s=qk(await this._rpcRequest("getMultipleAccounts",o),eS(zk(Xk(PS))));if("error"in s)throw new Tv(s.error,`failed to get info for accounts ${i}`);return s.result}async getMultipleAccountsInfo(e,t){return(await this.getMultipleAccountsInfoAndContext(e,t)).value}async getStakeActivation(e,t,n){const{commitment:r,config:i}=Xv(t),o=this._buildArgs([e.toBase58()],r,void 0,{...i,epoch:null!=n?n:i?.epoch}),s=qk(await this._rpcRequest("getStakeActivation",o),Yv(OS));if("error"in s)throw new Tv(s.error,`failed to get Stake Activation ${e.toBase58()}`);return s.result}async getProgramAccounts(e,t){const{commitment:n,config:r}=Xv(t),{encoding:i,...o}=r||{},s=this._buildArgs([e.toBase58()],n,i||"base64",{...o,...o.filters?{filters:Qv(o.filters)}:null}),a=await this._rpcRequest("getProgramAccounts",s),c=zk(DS),l=!0===o.withContext?qk(a,eS(c)):qk(a,Yv(c));if("error"in l)throw new Tv(l.error,`failed to get accounts owned by program ${e.toBase58()}`);return l.result}async getParsedProgramAccounts(e,t){const{commitment:n,config:r}=Xv(t),i=this._buildArgs([e.toBase58()],n,"jsonParsed",r),o=qk(await this._rpcRequest("getProgramAccounts",i),Yv(zk(LS)));if("error"in o)throw new Tv(o.error,`failed to get accounts owned by program ${e.toBase58()}`);return o.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=Up.decode(n)}catch(e){throw new Error("signature must be base58 encoded: "+n)}return uv(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((o,s)=>{try{n=this.onSignature(t,(e,t)=>{n=void 0;const r={context:t,value:e};o({__type:yv.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)s(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,o({__type:yv.PROCESSED,response:{context:r,value:c}})}})()}catch(e){s(e)}})}}async confirmTransactionUsingBlockHeightExceedanceStrategy({commitment:e,strategy:{abortSignal:t,lastValidBlockHeight:n,signature:r}}){let i=!1;const o=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 Ev(1e3),i)return;if(e=await r(),i)return}t({__type:yv.BLOCKHEIGHT_EXCEEDED})}})()}),{abortConfirmation:s,confirmationPromise:a}=this.getTransactionConfirmationPromise({commitment:e,signature:r}),c=this.getCancellationPromise(t);let l;try{const e=await Promise.race([c,a,o]);if(e.__type!==yv.PROCESSED)throw new tv(r);l=e.response}finally{i=!0,s()}return l}async confirmTransactionUsingDurableNonceStrategy({commitment:e,strategy:{abortSignal:t,minContextSlot:n,nonceAccountPubkey:r,nonceValue:i,signature:o}}){let s=!1;const a=new Promise(t=>{let o=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 o}};(async()=>{if(o=await c(),!s)for(;;){if(i!==o)return void t({__type:yv.NONCE_INVALID,slotInWhichNonceDidAdvance:a});if(await Ev(2e3),s)return;if(o=await c(),s)return}})()}),{abortConfirmation:c,confirmationPromise:l}=this.getTransactionConfirmationPromise({commitment:e,signature:o}),u=this.getCancellationPromise(t);let d;try{const t=await Promise.race([u,l,a]);if(t.__type===yv.PROCESSED)d=t.response;else{let r;for(;;){const e=await this.getSignatureStatus(o);if(null==e)break;if(!(e.context.slot<(t.slotInWhichNonceDidAdvance??n))){r=e;break}await Ev(400)}if(!r?.value)throw new rv(o);{const t=e||"finalized",{confirmationStatus:n}=r.value;switch(t){case"processed":case"recent":if("processed"!==n&&"confirmed"!==n&&"finalized"!==n)throw new rv(o);break;case"confirmed":case"single":case"singleGossip":if("confirmed"!==n&&"finalized"!==n)throw new rv(o);break;case"finalized":case"max":case"root":if("finalized"!==n)throw new rv(o)}d={context:r.context,value:{err:r.value.err}}}}}finally{s=!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:yv.TIMED_OUT,timeoutMs:r}),r)}),{abortConfirmation:i,confirmationPromise:o}=this.getTransactionConfirmationPromise({commitment:e,signature:t});let s;try{const e=await Promise.race([o,r]);if(e.__type!==yv.PROCESSED)throw new nv(t,e.timeoutMs/1e3);s=e.response}finally{clearTimeout(n),i()}return s}async getClusterNodes(){const e=qk(await this._rpcRequest("getClusterNodes",[]),Yv(zk(XS)));if("error"in e)throw new Tv(e.error,"failed to get cluster nodes");return e.result}async getVoteAccounts(e){const t=this._buildArgs([],e),n=qk(await this._rpcRequest("getVoteAccounts",t),JS);if("error"in n)throw new Tv(n.error,"failed to get vote accounts");return n.result}async getSlot(e){const{commitment:t,config:n}=Xv(e),r=this._buildArgs([],t,void 0,n),i=qk(await this._rpcRequest("getSlot",r),Yv(Qk()));if("error"in i)throw new Tv(i.error,"failed to get slot");return i.result}async getSlotLeader(e){const{commitment:t,config:n}=Xv(e),r=this._buildArgs([],t,void 0,n),i=qk(await this._rpcRequest("getSlotLeader",r),Yv(Yk()));if("error"in i)throw new Tv(i.error,"failed to get slot leader");return i.result}async getSlotLeaders(e,t){const n=[e,t],r=qk(await this._rpcRequest("getSlotLeaders",n),Yv(zk(Hv)));if("error"in r)throw new Tv(r.error,"failed to get slot leaders");return r.result}async getSignatureStatus(e,t){const{context:n,value:r}=await this.getSignatureStatuses([e],t);uv(1===r.length);return{context:n,value:r[0]}}async getSignatureStatuses(e,t){const n=[e];t&&n.push(t);const r=qk(await this._rpcRequest("getSignatureStatuses",n),eA);if("error"in r)throw new Tv(r.error,"failed to get signature status");return r.result}async getTransactionCount(e){const{commitment:t,config:n}=Xv(e),r=this._buildArgs([],t,void 0,n),i=qk(await this._rpcRequest("getTransactionCount",r),Yv(Qk()));if("error"in i)throw new Tv(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=qk(await this._rpcRequest("getInflationGovernor",t),wS);if("error"in n)throw new Tv(n.error,"failed to get inflation");return n.result}async getInflationReward(e,t,n){const{commitment:r,config:i}=Xv(n),o=this._buildArgs([e.map(e=>e.toBase58())],r,void 0,{...i,epoch:null!=t?t:i?.epoch}),s=qk(await this._rpcRequest("getInflationReward",o),iS);if("error"in s)throw new Tv(s.error,"failed to get inflation reward");return s.result}async getInflationRate(){const e=qk(await this._rpcRequest("getInflationRate",[]),kS);if("error"in e)throw new Tv(e.error,"failed to get inflation rate");return e.result}async getEpochInfo(e){const{commitment:t,config:n}=Xv(e),r=this._buildArgs([],t,void 0,n),i=qk(await this._rpcRequest("getEpochInfo",r),vS);if("error"in i)throw new Tv(i.error,"failed to get epoch info");return i.result}async getEpochSchedule(){const e=qk(await this._rpcRequest("getEpochSchedule",[]),SS);if("error"in e)throw new Tv(e.error,"failed to get epoch schedule");const t=e.result;return new $v(t.slotsPerEpoch,t.leaderScheduleSlotOffset,t.warmup,t.firstNormalEpoch,t.firstNormalSlot)}async getLeaderSchedule(){const e=qk(await this._rpcRequest("getLeaderSchedule",[]),AS);if("error"in e)throw new Tv(e.error,"failed to get leader schedule");return e.result}async getMinimumBalanceForRentExemption(e,t){const n=this._buildArgs([e],t),r=qk(await this._rpcRequest("getMinimumBalanceForRentExemption",n),tA);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=qk(await this._rpcRequest("getRecentPerformanceSamples",e?[e]:[]),CA);if("error"in t)throw new Tv(t.error,"failed to get recent performance samples");return t.result}async getFeeCalculatorForBlockhash(e,t){const n=this._buildArgs([e],t),r=qk(await this._rpcRequest("getFeeCalculatorForBlockhash",n),NA);if("error"in r)throw new Tv(r.error,"failed to get fee calculator");const{context:i,value:o}=r.result;return{context:i,value:null!==o?o.feeCalculator:null}}async getFeeForMessage(e,t){const n=jb(e.serialize()).toString("base64"),r=this._buildArgs([n],t),i=qk(await this._rpcRequest("getFeeForMessage",r),eS(Xk(Qk())));if("error"in i)throw new Tv(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=qk(await this._rpcRequest("getRecentPrioritizationFees",n),bS);if("error"in r)throw new Tv(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}=Xv(e),r=this._buildArgs([],t,void 0,n),i=qk(await this._rpcRequest("getLatestBlockhash",r),IA);if("error"in i)throw new Tv(i.error,"failed to get latest blockhash");return i.result}async isBlockhashValid(e,t){const{commitment:n,config:r}=Xv(t),i=this._buildArgs([e],n,void 0,r),o=qk(await this._rpcRequest("isBlockhashValid",i),xA);if("error"in o)throw new Tv(o.error,"failed to determine if the blockhash `"+e+"`is valid");return o.result}async getVersion(){const e=qk(await this._rpcRequest("getVersion",[]),Yv(gS));if("error"in e)throw new Tv(e.error,"failed to get version");return e.result}async getGenesisHash(){const e=qk(await this._rpcRequest("getGenesisHash",[]),Yv(Yk()));if("error"in e)throw new Tv(e.error,"failed to get genesis hash");return e.result}async getBlock(e,t){const{commitment:n,config:r}=Xv(t),i=this._buildArgsAtLeastConfirmed([e],n,void 0,r),o=await this._rpcRequest("getBlock",i);try{switch(r?.transactionDetails){case"accounts":{const e=qk(o,wA);if("error"in e)throw e.error;return e.result}case"none":{const e=qk(o,yA);if("error"in e)throw e.error;return e.result}default:{const e=qk(o,mA);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:nS(n,e.message)},version:n}))}:null}}}catch(e){throw new Tv(e,"failed to get confirmed block")}}async getParsedBlock(e,t){const{commitment:n,config:r}=Xv(t),i=this._buildArgsAtLeastConfirmed([e],n,"jsonParsed",r),o=await this._rpcRequest("getBlock",i);try{switch(r?.transactionDetails){case"accounts":{const e=qk(o,bA);if("error"in e)throw e.error;return e.result}case"none":{const e=qk(o,vA);if("error"in e)throw e.error;return e.result}default:{const e=qk(o,kA);if("error"in e)throw e.error;return e.result}}}catch(e){throw new Tv(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=qk(await this._rpcRequest("getBlockProduction",r),yS);if("error"in i)throw new Tv(i.error,"failed to get block production information");return i.result}async getTransaction(e,t){const{commitment:n,config:r}=Xv(t),i=this._buildArgsAtLeastConfirmed([e],n,void 0,r),o=qk(await this._rpcRequest("getTransaction",i),TA);if("error"in o)throw new Tv(o.error,"failed to get transaction");const s=o.result;return s?{...s,transaction:{...s.transaction,message:nS(s.version,s.transaction.message)}}:s}async getParsedTransaction(e,t){const{commitment:n,config:r}=Xv(t),i=this._buildArgsAtLeastConfirmed([e],n,"jsonParsed",r),o=qk(await this._rpcRequest("getTransaction",i),EA);if("error"in o)throw new Tv(o.error,"failed to get transaction");return o.result}async getParsedTransactions(e,t){const{commitment:n,config:r}=Xv(t),i=e.map(e=>({methodName:"getTransaction",args:this._buildArgsAtLeastConfirmed([e],n,"jsonParsed",r)}));return(await this._rpcBatchRequest(i)).map(e=>{const t=qk(e,EA);if("error"in t)throw new Tv(t.error,"failed to get transactions");return t.result})}async getTransactions(e,t){const{commitment:n,config:r}=Xv(t),i=e.map(e=>({methodName:"getTransaction",args:this._buildArgsAtLeastConfirmed([e],n,void 0,r)}));return(await this._rpcBatchRequest(i)).map(e=>{const t=qk(e,TA);if("error"in t)throw new Tv(t.error,"failed to get transactions");const n=t.result;return n?{...n,transaction:{...n.transaction,message:nS(n.version,n.transaction.message)}}:n})}async getConfirmedBlock(e,t){const n=this._buildArgsAtLeastConfirmed([e],t),r=qk(await this._rpcRequest("getBlock",n),SA);if("error"in r)throw new Tv(r.error,"failed to get confirmed block");const i=r.result;if(!i)throw new Error("Confirmed block "+e+" not found");const o={...i,transactions:i.transactions.map(({transaction:e,meta:t})=>{const n=new fv(e.message);return{meta:t,transaction:{...e,message:n}}})};return{...o,transactions:o.transactions.map(({transaction:e,meta:t})=>({meta:t,transaction:bv.populate(e.message,e.signatures)}))}}async getBlocks(e,t,n){const r=this._buildArgsAtLeastConfirmed(void 0!==t?[e,t]:[e],n),i=qk(await this._rpcRequest("getBlocks",r),Yv(zk(Qk())));if("error"in i)throw new Tv(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=qk(await this._rpcRequest("getBlock",n),AA);if("error"in r)throw new Tv(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=qk(await this._rpcRequest("getBlock",n),AA);if("error"in r)throw new Tv(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=qk(await this._rpcRequest("getTransaction",n),TA);if("error"in r)throw new Tv(r.error,"failed to get transaction");const i=r.result;if(!i)return i;const o=new fv(i.transaction.message),s=i.transaction.signatures;return{...i,transaction:bv.populate(o,s)}}async getParsedConfirmedTransaction(e,t){const n=this._buildArgsAtLeastConfirmed([e],t,"jsonParsed"),r=qk(await this._rpcRequest("getTransaction",n),EA);if("error"in r)throw new Tv(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=qk(e,EA);if("error"in t)throw new Tv(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 o=await this.getSlot("finalized");for(;!("before"in r||++n>o);)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=qk(await this._rpcRequest("getConfirmedSignaturesForAddress2",r),FS);if("error"in i)throw new Tv(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=qk(await this._rpcRequest("getSignaturesForAddress",r),US);if("error"in i)throw new Tv(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 Gv({key:e,state:Gv.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=_v.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=qk(await this._rpcRequest("requestAirdrop",[e.toBase58(),t]),_A);if("error"in n)throw new Tv(n.error,`airdrop to ${e.toBase58()} failed`);return n.result}async _blockhashWithExpiryBlockHeight(e){if(!e){for(;this._pollingBlockhash;)await Ev(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 Ev(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}=Xv(e),r=this._buildArgs([],t,"base64",n),i=qk(await this._rpcRequest("getStakeMinimumDelegation",r),eS(Qk()));if("error"in i)throw new Tv(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=Yd.Buffer.from(r).toString("base64");if(Array.isArray(t)||void 0!==n)throw new Error("Invalid arguments");const o=t||{};o.encoding="base64","commitment"in o||(o.commitment=this.commitment),t&&"object"==typeof t&&"innerInstructions"in t&&(o.innerInstructions=t.innerInstructions);const s=[i,o],a=qk(await this._rpcRequest("simulateTransaction",s),mS);if("error"in a)throw new Error("failed to simulate transaction: "+a.error.message);return a.result}let r;if(e instanceof bv){let t=e;r=new bv,r.feePayer=t.feePayer,r.instructions=e.instructions,r.nonceInfo=t.nonceInfo,r.signatures=t.signatures}else r=bv.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 o=r._compile(),s=o.serialize(),a=r._serialize(s).toString("base64"),c={encoding:"base64",commitment:this.commitment};if(n){const e=(Array.isArray(n)?n:o.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=qk(await this._rpcRequest("simulateTransaction",l),mS);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 Av({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=jb(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 o=[e,n],s=qk(await this._rpcRequest("sendTransaction",o),BA);if("error"in s){let e;throw"data"in s.error&&(e=s.error.data.logs),new Av({action:r?"send":"simulate",signature:"",transactionMessage:s.error.message,logs:e})}return s.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}=qk(e,$S);this._handleServerNotification(n,[t.value,t.context])}_makeSubscription(e,t){const n=this._nextClientSubscriptionId++,r=Fv([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];uv(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}=Xv(n),o=this._buildArgs([e.toBase58()],r||this._commitment||"finalized","base64",i);return this._makeSubscription({callback:t,method:"accountSubscribe",unsubscribeMethod:"accountUnsubscribe"},o)}async removeAccountChangeListener(e){await this._unsubscribeClientSubscription(e,"account change")}_wsOnProgramAccountNotification(e){const{result:t,subscription:n}=qk(e,KS);this._handleServerNotification(n,[{accountId:t.value.pubkey,accountInfo:t.value.account},t.context])}onProgramAccountChange(e,t,n,r){const{commitment:i,config:o}=Xv(n),s=this._buildArgs([e.toBase58()],i||this._commitment||"finalized","base64",o||(r?{filters:Qv(r)}:void 0));return this._makeSubscription({callback:t,method:"programSubscribe",unsubscribeMethod:"programUnsubscribe"},s)}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}=qk(e,DA);this._handleServerNotification(n,[t.value,t.context])}_wsOnSlotNotification(e){const{result:t,subscription:n}=qk(e,WS);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}=qk(e,HS);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}=qk(e,jS);"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"},o=this._buildArgs([e],r,void 0,i),s=this._makeSubscription({callback:(e,n)=>{t(e,n);try{this.removeSignatureListener(s)}catch(e){}},method:"signatureSubscribe",unsubscribeMethod:"signatureUnsubscribe"},o);return s}async removeSignatureListener(e){await this._unsubscribeClientSubscription(e,"signature result")}_wsOnRootNotification(e){const{result:t,subscription:n}=qk(e,VS);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 LA{constructor(e){this._keypair=void 0,this._keypair=e??Gb()}static generate(){return new LA(Gb())}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=Wb(t);for(let e=0;e<32;e++)if(n[e]!==r[e])throw new Error("provided secretKey is invalid")}return new LA({publicKey:n,secretKey:e})}static fromSeed(e){const t=Wb(e),n=new Uint8Array(64);return n.set(e),n.set(t,32),new LA({publicKey:t,secretKey:n})}get publicKey(){return new Yb(this._keypair.publicKey)}get secretKey(){return new Uint8Array(this._keypair.secretKey)}}Object.freeze({CreateLookupTable:{index:0,layout:lf.struct([lf.u32("instruction"),Bv("recentSlot"),lf.u8("bumpSeed")])},FreezeLookupTable:{index:1,layout:lf.struct([lf.u32("instruction")])},ExtendLookupTable:{index:2,layout:lf.struct([lf.u32("instruction"),Bv(),lf.seq(ov(),lf.offset(lf.u32(),-8),"addresses")])},DeactivateLookupTable:{index:3,layout:lf.struct([lf.u32("instruction")])},CloseLookupTable:{index:4,layout:lf.struct([lf.u32("instruction")])}}),new Yb("AddressLookupTab1e1111111111111111111111111");const OA=Object.freeze({RequestUnits:{index:0,layout:lf.struct([lf.u8("instruction"),lf.u32("units"),lf.u32("additionalFee")])},RequestHeapFrame:{index:1,layout:lf.struct([lf.u8("instruction"),lf.u32("bytes")])},SetComputeUnitLimit:{index:2,layout:lf.struct([lf.u8("instruction"),lf.u32("units")])},SetComputeUnitPrice:{index:3,layout:lf.struct([lf.u8("instruction"),Bv("microLamports")])}});class FA{constructor(){}static requestUnits(e){const t=Iv(OA.RequestUnits,e);return new kv({keys:[],programId:this.programId,data:t})}static requestHeapFrame(e){const t=Iv(OA.RequestHeapFrame,e);return new kv({keys:[],programId:this.programId,data:t})}static setComputeUnitLimit(e){const t=Iv(OA.SetComputeUnitLimit,e);return new kv({keys:[],programId:this.programId,data:t})}static setComputeUnitPrice(e){const t=Iv(OA.SetComputeUnitPrice,{microLamports:BigInt(e.microLamports)});return new kv({keys:[],programId:this.programId,data:t})}}var UA;FA.programId=new Yb("ComputeBudget111111111111111111111111111111"),lf.struct([lf.u8("numSignatures"),lf.u8("padding"),lf.u16("signatureOffset"),lf.u16("signatureInstructionIndex"),lf.u16("publicKeyOffset"),lf.u16("publicKeyInstructionIndex"),lf.u16("messageDataOffset"),lf.u16("messageDataSize"),lf.u16("messageInstructionIndex")]),new Yb("Ed25519SigVerify111111111111111111111111111"),Kb.utils.isValidPrivateKey,lf.struct([lf.u8("numSignatures"),lf.u16("signatureOffset"),lf.u8("signatureInstructionIndex"),lf.u16("ethAddressOffset"),lf.u8("ethAddressInstructionIndex"),lf.u16("messageDataOffset"),lf.u16("messageDataSize"),lf.u8("messageInstructionIndex"),lf.blob(20,"ethAddress"),lf.blob(64,"signature"),lf.u8("recoveryId")]),new Yb("KeccakSecp256k11111111111111111111111111111"),new Yb("StakeConfig11111111111111111111111111111111");class $A{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}}UA=$A,$A.default=new UA(0,0,Yb.default),Object.freeze({Initialize:{index:0,layout:lf.struct([lf.u32("instruction"),((e="authorized")=>lf.struct([ov("staker"),ov("withdrawer")],e))(),((e="lockup")=>lf.struct([lf.ns64("unixTimestamp"),lf.ns64("epoch"),ov("custodian")],e))()])},Authorize:{index:1,layout:lf.struct([lf.u32("instruction"),ov("newAuthorized"),lf.u32("stakeAuthorizationType")])},Delegate:{index:2,layout:lf.struct([lf.u32("instruction")])},Split:{index:3,layout:lf.struct([lf.u32("instruction"),lf.ns64("lamports")])},Withdraw:{index:4,layout:lf.struct([lf.u32("instruction"),lf.ns64("lamports")])},Deactivate:{index:5,layout:lf.struct([lf.u32("instruction")])},Merge:{index:7,layout:lf.struct([lf.u32("instruction")])},AuthorizeWithSeed:{index:8,layout:lf.struct([lf.u32("instruction"),ov("newAuthorized"),lf.u32("stakeAuthorizationType"),sv("authoritySeed"),ov("authorityOwner")])}}),new Yb("Stake11111111111111111111111111111111111111"),Object.freeze({InitializeAccount:{index:0,layout:lf.struct([lf.u32("instruction"),((e="voteInit")=>lf.struct([ov("nodePubkey"),ov("authorizedVoter"),ov("authorizedWithdrawer"),lf.u8("commission")],e))()])},Authorize:{index:1,layout:lf.struct([lf.u32("instruction"),ov("newAuthorized"),lf.u32("voteAuthorizationType")])},Withdraw:{index:3,layout:lf.struct([lf.u32("instruction"),lf.ns64("lamports")])},UpdateValidatorIdentity:{index:4,layout:lf.struct([lf.u32("instruction")])},AuthorizeWithSeed:{index:10,layout:lf.struct([lf.u32("instruction"),((e="voteAuthorizeWithSeedArgs")=>lf.struct([lf.u32("voteAuthorizationType"),ov("currentAuthorityDerivedKeyOwnerPubkey"),sv("currentAuthorityDerivedKeySeed"),ov("newAuthorized")],e))()])}}),new Yb("Vote111111111111111111111111111111111111111"),new Yb("Va1idator1nfo111111111111111111111111111111"),tb({name:Yk(),website:Jk(Yk()),details:Jk(Yk()),iconUrl:Jk(Yk()),keybaseUsername:Jk(Yk())}),new Yb("Vote111111111111111111111111111111111111111"),lf.struct([ov("nodePubkey"),ov("authorizedWithdrawer"),lf.u8("commission"),lf.nu64(),lf.seq(lf.struct([lf.nu64("slot"),lf.u32("confirmationCount")]),lf.offset(lf.u32(),-8),"votes"),lf.u8("rootSlotValid"),lf.nu64("rootSlot"),lf.nu64(),lf.seq(lf.struct([lf.nu64("epoch"),ov("authorizedVoter")]),lf.offset(lf.u32(),-8),"authorizedVoters"),lf.struct([lf.seq(lf.struct([ov("authorizedPubkey"),lf.nu64("epochOfLastAuthorizedSwitch"),lf.nu64("targetEpoch")]),32,"buf"),lf.nu64("idx"),lf.u8("isEmpty")],"priorVoters"),lf.nu64(),lf.seq(lf.struct([lf.nu64("epoch"),lf.nu64("credits"),lf.nu64("prevCredits")]),lf.offset(lf.u32(),-8),"epochCredits"),lf.struct([lf.nu64("slot"),lf.nu64("timestamp")],"lastTimestamp")]);function qA(e){return/^0x[a-fA-F0-9]{64}$/.test(e)}function KA(e){const t=new Map;for(const n of e)t.set(is(n.symbol),n);return t}function GA(e,t,n){const r=function(e,t){return e.get(is(t))}(e,t);if(!r){throw j(`Token ${t} not supported for ${n}. Supported: ${Array.from(e.keys()).join(", ")}`,"tokenSymbol")}return r}function WA(e){if(!e||!qA(e))throw z("privateKey","a 0x-prefixed 64-character hex string (e.g., 0x1234...abcd)","Ethereum private key")}class zA{constructor(e){this.cache=new Map,this.galaConnectClient=e.galaConnectClient}async getTokenMetadata(e){const t=os(e),n=this.cache.get(t);if(n)return n;const r=sl[t];if(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=os(e);return this.cache.has(t)||t in sl}clearCache(){this.cache.clear()}async fetchFromApi(e){let t=e,n=await this.galaConnectClient.getBridgeConfigurations(t),r=n.find(e=>os(e.symbol)===os(t)&&e.verified);if(r||e.startsWith("G")||(t=`G${e}`,n=await this.galaConnectClient.getBridgeConfigurations(t),r=n.find(e=>os(e.symbol)===os(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},o=r.decimals,s=r.channel,{descriptor:{collection:i.collection,category:i.category,type:i.type,additionalKey:i.additionalKey},decimals:o,...s&&{channel:s}};var i,o,s}}async function HA(e,t){const{wallet:n}=t,r=e.uniqueKey??`galaconnect-operation-${m.randomUUID()}`,i="string"==typeof e.destinationChainId?Le(e.destinationChainId,1):e.destinationChainId,o=function(e){const t={...e,galaDecimals:"string"==typeof e.galaDecimals?Le(e.galaDecimals,0):e.galaDecimals,timestamp:"string"==typeof e.timestamp?Le(e.timestamp,0):e.timestamp};if(e.galaExchangeRate&&(t.galaExchangeRate={...e.galaExchangeRate,timestamp:"string"==typeof e.galaExchangeRate.timestamp?Le(e.galaExchangeRate.timestamp,0):e.galaExchangeRate.timestamp}),e.galaExchangeCrossRate){const n=e.galaExchangeCrossRate;t.galaExchangeCrossRate={...n,timestamp:"string"==typeof n.timestamp?Le(n.timestamp,0):n.timestamp},n.baseTokenCrossRate&&(t.galaExchangeCrossRate.baseTokenCrossRate={...n.baseTokenCrossRate,timestamp:"string"==typeof n.baseTokenCrossRate.timestamp?Le(n.baseTokenCrossRate.timestamp,0):n.baseTokenCrossRate.timestamp}),n.quoteTokenCrossRate&&(t.galaExchangeCrossRate.quoteTokenCrossRate={...n.quoteTokenCrossRate,timestamp:"string"==typeof n.quoteTokenCrossRate.timestamp?Le(n.quoteTokenCrossRate.timestamp,0):n.quoteTokenCrossRate.timestamp})}return t}(e.destinationChainTxFee),s=Boolean(o.galaExchangeCrossRate),a={destinationChainId:i,destinationChainTxFee:Kd(s?{...o,galaExchangeRate:void 0}:{...o,galaExchangeCrossRate:void 0}),quantity:e.quantity,recipient:e.recipient,tokenInstance:e.tokenInstance,uniqueKey:r},c=yl(s),l=await n.signTypedData(ul,c,a),u=`Ethereum Signed Message:\n${Vc({domain:ul,message:a,primaryType:"GalaTransaction",types:c}).length}`;return{...a,signature:l,prefix:u,types:c,domain:ul}}const jA=5,VA=6,XA=7;function QA(e){const t=Le(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===jA,isFailed:t===VA||t===XA}}const JA="Token symbol resolution failed. This is an internal error - BridgeService should resolve tokenId to symbol before calling strategy.",ZA="Bridge request ID missing from RequestTokenBridgeOut response",YA="BridgeTokenOut response missing transaction hash";function eT(e){if(!e)throw j(JA,"tokenSymbol");return e}function tT(t,n){if(!e.isAddress(t)){throw z(n||"address","a valid 0x-prefixed Ethereum address",t)}}function nT(e,t){try{return new Yb(e)}catch{throw z(t||"address","a valid Solana address (base58)",e)}}function rT(e){try{return new Yb(e)}catch{throw z("address","a valid Solana address (base58)",e)}}function iT(e,t,n){return{symbol:e,quantity:t,decimals:n,contractAddress:null,isNative:!0}}function oT(e,t){return{symbol:e.symbol,quantity:t,decimals:e.decimals??18,contractAddress:e.contractAddress,isNative:!1}}function sT(e,t){return{symbol:e.symbol,quantity:t,decimals:e.decimals??9,contractAddress:e.mintAddress,isNative:e.isNative??!1}}function aT(e,t,n){const r=e.find(e=>e.symbol===t);if(!r){const r=e.map(e=>e.symbol).join(", ");throw W("tokenSymbol",`Unsupported ${n} token: ${t}. Supported: ${r}`)}return r}const cT={Ethereum:"Ethereum bridging not configured. Provide ethereumPrivateKey in config.",Solana:"Solana bridging not configured. Provide solanaPrivateKey in config."};function lT(e,t,n){if(!e)throw j(n??cT[t],`${t.toLowerCase()}Strategy`);return e}function uT(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}`}}function dT(e,t){return lT(e.get("Ethereum"),"Ethereum",t)}function hT(e,t){return lT(e.get("Solana"),"Solana",t)}function gT(e,t){return e??t.getWalletAddress()}async function pT(e,t){const{amount:n,recipientAddress:r,tokenSymbol:i}=e,{galaConnectClient:o,tokenMetadataResolver:s,ethereumWallet:a,destinationChainId:c,destinationChain:l,validateRecipientAddress:u}=t,d=eT(i);Gd(n,d),u(r,"recipient");const h=await s.getTokenMetadata(d),g=await o.fetchBridgeFee({chainId:l,bridgeToken:h.descriptor}),p=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}),f=await HA(p,{wallet:a}),m=function(e){if(!e)throw j(ZA,"bridgeRequestId");return e}(function(e){if("string"==typeof e.Data)return e.Data;if(null!=e.data){if("string"==typeof e.data)return e.data;if("object"==typeof e.data){const t=e.data;if("string"==typeof t.Data)return t.Data}}}(await o.requestBridgeOut(f)));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 j(YA,"transactionHash");return t}(await o.bridgeTokenOut({bridgeFromChannel:"asset",bridgeRequestId:m})),tokenSymbol:d,amount:n,feePaid:g.estimatedTotalTxFeeInGala,baseUrl:o.getBaseUrl()})}class fT extends Error{constructor(e,t,n){super(`GalaConnect request to ${t} failed with status ${e}${n?`: ${JSON.stringify(n)}`:""}`),this.status=e,this.path=t,this.responseBody=n,this.name="GalaConnectHttpError"}}const mT=Yc,yT="https://galachain-gateway-chain-platform-galachain-mainnet.gala.com",wT=12,kT=!0,bT=3,vT=1e3;class ST{constructor(e){this.baseUrl=e.baseUrl??mT,this.galachainBaseUrl=e.galachainBaseUrl??yT,this.walletAddress=e.walletAddress,this.rateLimiter=new Pd(e.requestsPerSecond??wT),this.defaultHeaders={"Content-Type":"application/json","X-Wallet-Address":this.walletAddress};const t=e.enableRetry??kT;this.retryOptions=t?{maxRetries:e.maxRetries??bT,initialDelayMs:e.retryInitialDelayMs??vT,...e.onRetry&&{onRetry:e.onRetry},shouldRetry:e=>Fd(e instanceof fT?{status:e.status}:e)}:null}getBaseUrl(){return this.baseUrl}async getBridgeConfigurations(e){return wr(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?Pe(e,{rawBody:e}):{message:"Failed to fetch bridge configurations"},new fT(n.status,"/v1/connect/bridge-configurations",t)}return(await n.json()).data.tokens},"GalaConnectClient.getBridgeConfigurations",void 0,(e,t,n)=>{if(e instanceof fT)throw e;throw X(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 wr(async()=>{const r=n.baseUrl??this.baseUrl,i=new URL(e,r),o=n.skipWalletHeader?{"Content-Type":"application/json","X-Wallet-Address":""}:this.defaultHeaders,s=await this.request(i.toString(),{method:"POST",headers:o,body:JSON.stringify(t,(e,t)=>"bigint"==typeof t?t.toString():t)});if(!s.ok){const t=await s.text(),n=500,r=Pe(t,{rawBody:t.slice(0,n)});throw new fT(s.status,e,r)}const a=await s.text();if(a){const t=function(e){if(Je(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: ${A(e)}`}}}(a);if(!t.success)throw new Error(`Failed to parse JSON response from ${e}: ${t.error}`);return t.value}},`Failed to execute POST request to ${e}`,void 0,(e,t,n)=>{if(e instanceof fT)throw e;throw X(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 fT(t,e,i)}}return r});return this.retryOptions?async function(e,t={}){const n={...Md,...t},r=t.shouldRetry??(e=>Fd(e));let i;for(let o=1;o<=n.maxRetries+1;o++)try{return await e()}catch(e){if(i=e,o>n.maxRetries)break;if(!r(e,o))break;const s=Ud(o,n);t.onRetry&&t.onRetry(e,o,s),await new Promise(e=>setTimeout(e,s))}throw i}(n,this.retryOptions):n()}async safeParseJson(e){const t=await e.text();try{return JSON.parse(t)}catch{return{rawBody:t}}}}var AT;exports.BridgeStatusCode=void 0,(AT=exports.BridgeStatusCode||(exports.BridgeStatusCode={}))[AT.PENDING=0]="PENDING",AT[AT.SUBMITTED=1]="SUBMITTED",AT[AT.CONFIRMED=2]="CONFIRMED",AT[AT.PROCESSING=3]="PROCESSING",AT[AT.FINALIZING=4]="FINALIZING",AT[AT.COMPLETED=5]="COMPLETED",AT[AT.FAILED=6]="FAILED",AT[AT.DELIVERY_FAILED=7]="DELIVERY_FAILED";class TT{async waitForCompletion(e,t={}){const{pollInterval:n=15e3,timeout:r=27e5,onStatusUpdate:i}=t,o=Date.now();for(;;){const t=await this.getStatus(e);if(i&&i(t),t.status===exports.BridgeStatusCode.COMPLETED||t.status===exports.BridgeStatusCode.FAILED||t.status===exports.BridgeStatusCode.DELIVERY_FAILED)return t;if(Ve(o)>r)throw V(`Bridge transaction timed out after ${r}ms. Last status: ${t.status}`,e,"TIMEOUT");await new Promise(e=>setTimeout(e,n))}}}class ET extends TT{constructor(t){super(),this.network="Ethereum",this.galaConnectClient=t.galaConnectClient,this.galaChainWalletAddress=t.galaChainWalletAddress,WA(t.ethereumPrivateKey);const n=t.ethereumRpcUrl??"https://ethereum.publicnode.com";this.ethereumProvider=new e.JsonRpcProvider(n),this.ethereumWallet=new e.Wallet(t.ethereumPrivateKey,this.ethereumProvider),this.ethereumWalletAddress=t.ethereumWalletAddress??this.ethereumWallet.address,this.ethereumBridgeContract=t.ethereumBridgeContract??"0x3F98b5A26EF3f04E1DA3B0B41dD350E8C8F3A7c2";const r=t.tokenConfigs??il;this.tokenConfigs=KA(r),this.tokenMetadataResolver=new zA({galaConnectClient:this.galaConnectClient})}async estimateFee(e,t){const n=await this.tokenMetadataResolver.getTokenMetadata(e);return Wd(await this.galaConnectClient.fetchBridgeFee({chainId:"Ethereum",bridgeToken:n.descriptor}))}async bridgeOut(e){return pT(e,{galaConnectClient:this.galaConnectClient,tokenMetadataResolver:this.tokenMetadataResolver,ethereumWallet:this.ethereumWallet,destinationChainId:Xc.ETHEREUM,destinationChain:"Ethereum",validateRecipientAddress:tT})}async bridgeIn(t){const{amount:n,sourcePrivateKey:r,recipientAddress:i,tokenSymbol:o}=t,s=eT(o);if(Gd(n,s),r&&!qA(r))throw z("sourcePrivateKey","0x-prefixed 64-character hex string",r.slice(0,10)+"...");const a=r?new e.Wallet(r,this.ethereumProvider):this.ethereumWallet,c=GA(this.tokenConfigs,s,"Ethereum bridge"),l=await this.tokenMetadataResolver.getTokenMetadata(s),u=new e.Contract(c.contractAddress,al,a),d=Le(await u.decimals(),18),h=Dd(n,d),g=BigInt(await u.balanceOf(a.address));if(g<h){throw j(`Insufficient ${s} balance on Ethereum. Needed ${Rd(h,d)}, have ${Rd(g,d)}`,"amount")}const p=function(t){const n=new ut;if("client"===n.detectFormat(t))return t;const r=n.normalizeInput(t);if(!r)throw z("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.getAddress("0x"+i).slice(2)}`}(i??this.galaChainWalletAddress);return uT({fromChain:"Ethereum",transactionHash:(await this.executeBridgeDeposit({wallet:a,tokenContract:u,tokenConfig:c,amountBaseUnits:h,decimals:d,recipient:p,metadata:l})).txHash,tokenSymbol:s,amount:n,baseUrl:this.galaConnectClient.getBaseUrl()})}async getStatus(e){return QA(await this.galaConnectClient.getBridgeStatus(e))}getSupportedTokens(){return Array.from(this.tokenConfigs.keys())}isTokenSupported(e){return this.tokenConfigs.has(is(e))}isValidAddress(e){return Xe.ETH_ADDRESS.test(e)}getWalletAddress(){return this.ethereumWalletAddress}async getEthereumTokenBalance(t,n){const r=GA(this.tokenConfigs,t,"Ethereum"),i=n??this.ethereumWalletAddress;tT(i);const o=new e.Contract(r.contractAddress,al,this.ethereumProvider);return Rd(await o.balanceOf(i),r.decimals??18)}async getEthereumNativeBalance(e){const t=e??this.ethereumWalletAddress;tT(t);return Rd(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 z("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>=ET.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: ${A(e)}`}}}async executeBridgeDeposit(t){const n=new e.Contract(this.ethereumBridgeContract,cl,t.wallet),r=(new TextEncoder).encode(t.recipient);let i;i=t.tokenConfig.bridgeUsesPermit?await this.bridgeWithPermit(t.wallet,t.tokenContract,t.tokenConfig,n,t.amountBaseUnits,r):await this.bridgeWithApproval(t.wallet,t.tokenContract,n,t.tokenConfig,t.amountBaseUnits,r);if(!await i.wait())throw j("Bridge transaction receipt not available","ethereumRpcUrl");await $d(3e4);const o={collection:t.metadata.descriptor.collection,category:t.metadata.descriptor.category,type:t.metadata.descriptor.type,additionalKey:t.metadata.descriptor.additionalKey,instance:"0"};return await this.galaConnectClient.registerBridgeTransaction({quantity:Rd(t.amountBaseUnits,t.decimals),tokenInstance:o,fromChain:"Ethereum",toChain:"GC",hash:i.hash}),{txHash:i.hash}}async bridgeWithPermit(t,n,r,i,o,s){const a=await this.ethereumProvider.getNetwork(),c=await n.name(),l=await n.nonces(t.address),u=BigInt(Math.floor(Date.now()/1e3)+3600),d=await t.signTypedData({name:c,version:"1",chainId:Le(a.chainId,1),verifyingContract:r.contractAddress},{Permit:[{name:"owner",type:"address"},{name:"spender",type:"address"},{name:"value",type:"uint256"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}]},{owner:t.address,spender:this.ethereumBridgeContract,value:o,nonce:l,deadline:u}),h=e.Signature.from(d);return i.bridgeOutWithPermit(r.contractAddress,o,Xc.GALA_CHAIN,s,u,h.v,h.r,h.s)}async bridgeWithApproval(e,t,n,r,i,o){const s=await t.allowance(e.address,this.ethereumBridgeContract);if(BigInt(s)<i){const e=await t.approve(this.ethereumBridgeContract,i);await e.wait()}return n.bridgeOut(r.contractAddress,i,0,Xc.GALA_CHAIN,o)}}ET.ETHEREUM_FINALITY_THRESHOLD=12;const IT=new Yb("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA");new Yb("TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb");const xT=new Yb("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL");new Yb("So11111111111111111111111111111111111111112"),new Yb("9pan9bMn5HatX4EJdBwg9VgCa7Uz5HL8N1m5D3NdXejP");const CT=e=>({decode:e.decode.bind(e),encode:e.encode.bind(e)});var NT,_T={};var BT=(NT||(NT=1,Object.defineProperty(_T,"__esModule",{value:!0}),_T.toBigIntLE=function(e){{const t=Buffer.from(e);t.reverse();const n=t.toString("hex");return 0===n.length?BigInt(0):BigInt(`0x${n}`)}},_T.toBigIntBE=function(e){{const t=e.toString("hex");return 0===t.length?BigInt(0):BigInt(`0x${t}`)}},_T.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}},_T.toBufferBE=function(e,t){{const n=e.toString(16);return Buffer.from(n.padStart(2*t,"0").slice(0,2*t),"hex")}}),_T);const PT=(DT=8,e=>{const t=lf.blob(DT,e),{encode:n,decode:r}=CT(t),i=t;return i.decode=(e,t)=>{const n=r(e,t);return BT.toBigIntLE(Buffer.from(n))},i.encode=(e,t,r)=>{const i=BT.toBufferLE(e,DT);return n(i,t,r)},i});var DT;const RT=e=>{const t=lf.blob(32,e),{encode:n,decode:r}=CT(t),i=t;return i.decode=(e,t)=>{const n=r(e,t);return new Yb(n)},i.encode=(e,t,r)=>{const i=e.toBuffer();return n(i,t,r)},i};var MT;!function(e){e[e.Uninitialized=0]="Uninitialized",e[e.Initialized=1]="Initialized",e[e.Frozen=2]="Frozen"}(MT||(MT={}));const LT=lf.struct([RT("mint"),RT("owner"),PT("amount"),lf.u32("delegateOption"),RT("delegate"),lf.u8("state"),lf.u32("isNativeOption"),PT("isNative"),PT("delegatedAmount"),lf.u32("closeAuthorityOption"),RT("closeAuthority")]);LT.span;var OT=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),o=Math.log(256)/Math.log(n);function s(e){if("string"!=typeof e)throw new TypeError("Expected String");if(0===e.length)return new Uint8Array;let o=0,s=0,a=0;for(;e[o]===r;)s++,o++;const c=(e.length-o)*i+1>>>0,l=new Uint8Array(c);for(;o<e.length;){const r=e.charCodeAt(o);if(r>255)return;let i=t[r];if(255===i)return;let s=0;for(let e=c-1;(0!==i||s<a)&&-1!==e;e--,s++)i+=n*l[e]>>>0,l[e]=i%256>>>0,i=i/256>>>0;if(0!==i)throw new Error("Non-zero carry");a=s,o++}let u=c-a;for(;u!==c&&0===l[u];)u++;const d=new Uint8Array(s+(c-u));let h=s;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,s=0,a=0;const c=t.length;for(;a!==c&&0===t[a];)a++,i++;const l=(c-a)*o+1>>>0,u=new Uint8Array(l);for(;a!==c;){let e=t[a],r=0;for(let t=l-1;(0!==e||r<s)&&-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");s=r,a++}let d=l-s;for(;d!==l&&0===u[d];)d++;let h=r.repeat(i);for(;d<l;++d)h+=e.charAt(u[d]);return h},decodeUnsafe:s,decode:function(e){const t=s(e);if(t)return t;throw new Error("Non-base"+n+" character")}}}("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");function FT(e,t,n,r,i){const[o]=Yb.findProgramAddressSync([t.toBuffer(),r.toBuffer(),e.toBuffer()],i);return o}class UT extends TT{constructor(t){super(),this.network="Solana",this.solanaBridgeAccountCache=new Map,this.galaConnectClient=t.galaConnectClient,this.galaChainWalletAddress=t.galaChainWalletAddress,WA(t.ethereumPrivateKey);const n=new e.JsonRpcProvider("https://ethereum.publicnode.com");this.ethereumWallet=new e.Wallet(t.ethereumPrivateKey,n);const r=t.solanaRpcUrl??"https://api.mainnet-beta.solana.com";let i;this.solanaConnection=new MA(r,"confirmed");try{i=OT.decode(t.solanaPrivateKeyBase58)}catch{throw z("solanaPrivateKeyBase58","base58-encoded string",t.solanaPrivateKeyBase58.slice(0,20)+"...")}if(64!==i.length)throw z("solanaPrivateKeyBase58","64 bytes when decoded",`${i.length} bytes`);this.solanaKeypair=LA.fromSecretKey(i);const o=t.solanaBridgeProgram??"AaE4dTnL75XqgUJpdxBKg6vS9sTJgBPJwBQRVhD29WwS";this.solanaBridgeProgramId=new Yb(o),[this.solanaBridgeTokenAuthority]=Yb.findProgramAddressSync([Buffer.from("bridge_token_authority")],this.solanaBridgeProgramId),[this.solanaBridgeConfigPda]=Yb.findProgramAddressSync([Buffer.from("configv1")],this.solanaBridgeProgramId),[this.solanaNativeBridgePda]=Yb.findProgramAddressSync([Buffer.from("native_sol_bridge")],this.solanaBridgeProgramId);const s=t.tokenConfigs??ol;this.tokenConfigs=KA(s),this.tokenMetadataResolver=new zA({galaConnectClient:this.galaConnectClient})}async estimateFee(e,t){const n=await this.tokenMetadataResolver.getTokenMetadata(e);return Wd(await this.galaConnectClient.fetchBridgeFee({chainId:"Solana",bridgeToken:n.descriptor}))}async bridgeOut(e){return pT(e,{galaConnectClient:this.galaConnectClient,tokenMetadataResolver:this.tokenMetadataResolver,ethereumWallet:this.ethereumWallet,destinationChainId:Xc.SOLANA,destinationChain:"Solana",validateRecipientAddress:nT})}async bridgeIn(e){const{amount:t,sourcePrivateKey:n,recipientAddress:r,tokenSymbol:i}=e,o=eT(i);Gd(t,o);let s=this.solanaKeypair;if(n){let e;try{e=OT.decode(n)}catch{throw z("sourcePrivateKey","base58-encoded string",n.slice(0,20)+"...")}if(64!==e.length)throw z("sourcePrivateKey","64 bytes when decoded",`${e.length} bytes`);s=LA.fromSecretKey(e)}const a=GA(this.tokenConfigs,o,"Solana bridge"),c=await this.tokenMetadataResolver.getTokenMetadata(o),l=Dd(t,c.decimals),u=r??this.galaChainWalletAddress;return uT({fromChain:"Solana",transactionHash:await this.executeSolanaBridgeOut({keypair:s,tokenConfig:a,metadata:c,amountBaseUnits:l,recipient:u,amount:t}),tokenSymbol:o,amount:t,baseUrl:this.galaConnectClient.getBaseUrl()})}async getStatus(e){return QA(await this.galaConnectClient.getBridgeStatus(e))}getSupportedTokens(){return Array.from(this.tokenConfigs.keys())}isTokenSupported(e){return this.tokenConfigs.has(is(e))}isValidAddress(e){try{return new Yb(e),!0}catch{return!1}}getWalletAddress(){return this.solanaKeypair.publicKey.toBase58()}async getSolanaTokenBalance(e,t){const n=GA(this.tokenConfigs,e,"Solana");if(n.isNative)return this.getSolanaNativeBalance(t);const r=t??this.solanaKeypair.publicKey.toBase58(),i=rT(r),o=FT(new Yb(n.mintAddress),i,0,IT,xT);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:LT.decode(i.data).amount,decimals:0}}(this.solanaConnection,o,0,IT),t=n.decimals??8;return Rd(e.amount,t)}catch(t){if(S(t)&&t.message.includes("could not find")){return Rd(0n,n.decimals??8)}throw j(`Failed to fetch ${e} balance for ${r}: ${A(t)}`,`${e}Account`)}}async getSolanaNativeBalance(e){const t=rT(e??this.solanaKeypair.publicKey.toBase58()),n=await this.solanaConnection.getBalance(t,"confirmed");return Rd(BigInt(n),9)}async requestDevnetAirdrop(e=1,t){oe(e,1e-5,2,"amount");const n=t?rT(t):this.solanaKeypair.publicKey,r=this.solanaConnection.rpcEndpoint;if(!r.includes("devnet"))throw j(`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(!Qe(e))throw z("signature","a non-empty string");if(!/^[1-9A-HJ-NP-Za-km-z]{80,90}$/.test(e))throw z("signature","a base58-encoded string (87-88 characters)",e.slice(0,20)+"...");const t=(await this.solanaConnection.getSignatureStatuses([e])).value[0];return t?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 Yb(e.tokenConfig.mintAddress),n=Boolean(e.tokenConfig.isNative),r=n?void 0:await this.getSolanaBridgeAccounts(t),i=n?void 0:FT(t,e.keypair.publicKey,0,IT,xT),o=Buffer.from(e.recipient,"utf8"),s=Buffer.alloc(8);s.writeBigUInt64LE(e.amountBaseUnits);const a=Buffer.alloc(4);a.writeUInt32LE(o.length);const c=n?this.buildNativeBridgeInstruction(e.keypair.publicKey,s,a,o):this.buildTokenBridgeInstruction(e.keypair.publicKey,i,t,r,s,a,o),l=new bv;l.add(FA.setComputeUnitPrice({microLamports:375e3}),FA.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 o=await this.solanaConnection.getLatestBlockhash("confirmed");e.recentBlockhash=o.blockhash,e.feePayer=t.publicKey,e.signatures=[],e.sign(t);const s=await this.solanaConnection.sendRawTransaction(e.serialize(),{skipPreflight:!1,preflightCommitment:"confirmed"});try{return await this.solanaConnection.confirmTransaction({signature:s,blockhash:o.blockhash,lastValidBlockHeight:o.lastValidBlockHeight},"confirmed"),s}catch(e){const t=S(e)?e.message.toLowerCase():"";if(!(t.includes("block height exceeded")||t.includes("blockhash not found")||t.includes("expired")))throw e;const o=await this.solanaConnection.getSignatureStatuses([s]);if("confirmed"===o.value[0]?.confirmationStatus||"finalized"===o.value[0]?.confirmationStatus)return s;r=new Error(`Transaction ${s} not confirmed - block height exceeded (attempt ${i}/${n})`)}}catch(e){r=S(e)?e:new Error(A(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 o=Math.min(1e3*Math.pow(2,i-1),5e3);await $d(o)}throw r??new Error("Transaction confirmation failed after max retries")}buildNativeBridgeInstruction(e,t,n,r){const i=Buffer.concat([ll.BRIDGE_OUT_NATIVE,t,n,r]);return new kv({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:Dv.programId,isSigner:!1,isWritable:!1}],data:i})}buildTokenBridgeInstruction(e,t,n,r,i,o,s){const a=Buffer.concat([ll.BRIDGE_OUT,i,o,s]);return new kv({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:Dv.programId,isSigner:!1,isWritable:!1},{pubkey:IT,isSigner:!1,isWritable:!1}],data:a})}async getSolanaBridgeAccounts(e){const t=e.toBase58(),n=this.solanaBridgeAccountCache.get(t);if(n)return n;const[r]=Yb.findProgramAddressSync([Buffer.from("mint_lookup_v1"),e.toBuffer()],this.solanaBridgeProgramId),i=await this.solanaConnection.getAccountInfo(r,"confirmed");if(!i)throw j(`Mint lookup account not found for ${r.toBase58()}`,"solanaBridgeProgram");if(!i.owner.equals(this.solanaBridgeProgramId))throw j("Mint lookup account owner mismatch for Solana bridge program","solanaBridgeProgram");if(i.data.length<40)throw j("Mint lookup account data is unexpectedly short","solanaBridgeProgram");const o={mintLookup:r,tokenBridge:new Yb(i.data.slice(8,40)),bridgeTokenAccount:FT(e,this.solanaBridgeTokenAuthority,0,IT,xT)};return this.solanaBridgeAccountCache.set(t,o),o}}const $T={PROD:{launchpadBaseUrl:"https://lpad-backend-prod1.defi.gala.com",galaChainBaseUrl:"https://gateway-mainnet.galachain.com",bundleBaseUrl:"https://bundle-backend-prod1.defi.gala.com",webSocketUrl:"https://bundle-backend-prod1.defi.gala.com",dexApiBaseUrl:"https://dex-api-platform-dex-prod-gala.gala.com",dexBackendBaseUrl:"https://dex-backend-prod1.defi.gala.com",launchpadFrontendUrl:"https://lpad-frontend-prod1.defi.gala.com"},STAGE:{launchpadBaseUrl:"https://lpad-backend-dev1.defi.gala.com",galaChainBaseUrl:"https://galachain-gateway-chain-platform-stage-chain-platform-eks.stage.galachain.com",bundleBaseUrl:"https://bundle-backend-dev1.defi.gala.com",webSocketUrl:"https://bundle-backend-dev1.defi.gala.com",dexApiBaseUrl:"https://dex-api-platform-dex-stage-gala.gala.com",dexBackendBaseUrl:"https://dex-backend-dev1.defi.gala.com",launchpadFrontendUrl:"https://lpad-frontend-test1.defi.gala.com"}};function qT(e){return $T[e]}const KT={PROD:{ethereum:"https://ethereum.publicnode.com",solana:"https://api.mainnet-beta.solana.com"},STAGE:{ethereum:"https://ethereum-sepolia.publicnode.com",solana:"https://api.devnet.solana.com"}},GT={solanaBridgeProgram:"AaE4dTnL75XqgUJpdxBKg6vS9sTJgBPJwBQRVhD29WwS",rateLimit:12,pollInterval:15e3,pollTimeout:27e5};class WT{static normalizeGalaChainAddress(e){const t=new ut;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 j(`Invalid GalaChain address format: ${e}`,"galaChainWalletAddress");const i=t.extractHex(r);return`eth|${WT.checksumAddress(i)}`}static checksumAddress(t){const n=t.toLowerCase(),r=ct(e.keccak256(e.toUtf8Bytes(n)));let i="";for(let e=0;e<n.length;e++){const t=n[e];parseInt(r[e],16)>=8?i+=t.toUpperCase():i+=t}return i}constructor(e){const t=WT.normalizeGalaChainAddress(e.galaChainWalletAddress),n=e.environment??"STAGE",r=$T[n],i=KT[n],o={galaConnectBaseUrl:e.galaConnectBaseUrl??r.dexApiBaseUrl,galaChainApiBaseUrl:e.galaChainApiBaseUrl??r.galaChainBaseUrl,ethereumRpcUrl:e.ethereumRpcUrl??i.ethereum,solanaRpcUrl:e.solanaRpcUrl??i.solana,ethereumBridgeContract:e.ethereumBridgeContract??rl(n),solanaBridgeProgram:e.solanaBridgeProgram??GT.solanaBridgeProgram,rateLimit:e.rateLimit??GT.rateLimit,pollInterval:e.pollInterval??GT.pollInterval,pollTimeout:e.pollTimeout??GT.pollTimeout,galaChainWalletAddress:t,ethereumPrivateKey:e.ethereumPrivateKey,environment:n};this.config=e.solanaPrivateKey?{...o,solanaPrivateKey:e.solanaPrivateKey}:o,this.galaConnectClient=new ST({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=nl(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 ET(t)),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:ol};this.strategies.set("Solana",new UT(e))}}async resolveTokenSymbol(e,t){return wr(async()=>{if(!this.bridgeableTokenService)throw j("BridgeableTokenService is required for tokenId resolution. Pass bridgeableTokenService in BridgeServiceConfig or use the SDK's bridge methods.","bridgeableTokenService");const n=qd(e).stringified,r="Ethereum"===t?"ETHEREUM":"SOLANA",i=await this.bridgeableTokenService.getTokenByTokenId(n,r);if(!i){throw j([`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 wr(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 wr(async()=>{const t=await this.resolveTokenSymbol(e.tokenId,e.destinationChain),n=this.getStrategy(e.destinationChain);if(!n.isValidAddress(e.recipientAddress))throw j(`Invalid recipient address for ${e.destinationChain}: ${e.recipientAddress}`,"recipientAddress");if(!n.isTokenSupported(t))throw j(`Token ${t} is not supported for ${e.destinationChain} bridging`,"tokenSymbol");return n.bridgeOut({...e,tokenSymbol:t})},"BridgeService.bridgeOut")}async bridgeIn(e){return wr(async()=>{const t=await this.resolveTokenSymbol(e.tokenId,e.sourceChain),n=this.getStrategy(e.sourceChain);if(!n.isTokenSupported(t))throw j(`Token ${t} is not supported for ${e.sourceChain} bridging`,"tokenSymbol");return n.bridgeIn({...e,tokenSymbol:t})},"BridgeService.bridgeIn")}async getBridgeStatus(e,t){return wr(async()=>{if(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=S(e)?e:new Error(A(e))}const i=this.strategies.get("Solana");if(i)try{return await i.getStatus(e)}catch(e){r=S(e)?e:new Error(A(e))}const o=r?` (last error: ${r.message})`:"";throw V(`Unable to get status for transaction ${e}${o}`,e)},"BridgeService.getBridgeStatus")}async waitForBridgeCompletion(e,t){return wr(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 V(`Unable to wait for transaction ${e}: no suitable strategy found`,e)},"BridgeService.waitForBridgeCompletion")}getSupportedBridgeTokens(e){const t=[],n=nl(this.config.environment);if(!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(!e||"Solana"===e)for(const e of ol){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(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 wr(async()=>dT(this.strategies).getEthereumTokenBalance(e,t),"BridgeService.getEthereumTokenBalance")}async getEthereumNativeBalance(e){return wr(async()=>dT(this.strategies).getEthereumNativeBalance(e),"BridgeService.getEthereumNativeBalance")}async getSolanaTokenBalance(e,t){return wr(async()=>hT(this.strategies).getSolanaTokenBalance(e,t),"BridgeService.getSolanaTokenBalance")}async getSolanaNativeBalance(e){return wr(async()=>hT(this.strategies).getSolanaNativeBalance(e),"BridgeService.getSolanaNativeBalance")}async fetchEthereumWalletTokenBalance(e,t){return wr(async()=>{const n=dT(this.strategies),r=aT(nl(this.config.environment),e,"Ethereum"),i=gT(t,n);return oT(r,await n.getEthereumTokenBalance(e,i))},"BridgeService.fetchEthereumWalletTokenBalance")}async fetchEthereumWalletNativeBalance(e){return wr(async()=>{const t=dT(this.strategies),n=gT(e,t);return iT("ETH",await t.getEthereumNativeBalance(n),18)},"BridgeService.fetchEthereumWalletNativeBalance")}async fetchSolanaWalletTokenBalance(e,t){return wr(async()=>{const n=hT(this.strategies),r=aT(ol,e,"Solana"),i=gT(t,n);return sT(r,await n.getSolanaTokenBalance(e,i))},"BridgeService.fetchSolanaWalletTokenBalance")}async fetchSolanaWalletNativeBalance(e){return wr(async()=>{const t=hT(this.strategies),n=gT(e,t);return iT("SOL",await t.getSolanaNativeBalance(n),9)},"BridgeService.fetchSolanaWalletNativeBalance")}async requestSolanaDevnetAirdrop(e,t){return wr(async()=>hT(this.strategies).requestDevnetAirdrop(e,t),"BridgeService.requestSolanaDevnetAirdrop")}async getSolanaTransactionStatus(e){return wr(async()=>hT(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 wr(async()=>dT(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 wr(async()=>{const t=dT(this.strategies),n=gT(e,t),r=nl(this.config.environment),[i,...o]=await Promise.all([t.getEthereumNativeBalance(n),...r.map(async e=>oT(e,await t.getEthereumTokenBalance(e.symbol,n)))]);return{address:n,native:iT("ETH",i,18),tokens:o,timestamp:Date.now()}},"BridgeService.fetchEthereumWalletAllBalances")}async fetchSolanaWalletAllBalances(e){return wr(async()=>{const t=hT(this.strategies),n=gT(e,t),[r,...i]=await Promise.all([t.getSolanaNativeBalance(n),...ol.map(async e=>sT(e,await t.getSolanaTokenBalance(e.symbol,n)))]);return{address:n,native:iT("SOL",r,9),tokens:i,timestamp:Date.now()}},"BridgeService.fetchSolanaWalletAllBalances")}getStrategy(e){const t=this.strategies.get(e);if(!t)throw j(`Bridging to ${e} is not configured. `+("Solana"===e?"Please provide solanaPrivateKey in config.":"Please check your configuration."),`${e.toLowerCase()}PrivateKey`);return t}}class zT extends Error{constructor(e,t){super(e),this.cause=t,this.name="WebSocketError"}}class HT extends Error{constructor(e,t,n){super(`Transaction ${e} failed with status: ${t}${n?` - ${n}`:""}`),this.transactionId=e,this.status=t,this.name="TransactionFailedError"}}function jT(e,t){if(Ze(e))throw new zT(`Invalid WebSocket response received for transaction ${t}: response is null or undefined`);if("object"!=typeof e)throw new zT(`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 zT(`Invalid WebSocket response received for transaction ${t}: missing status field`)}function VT(e,t,n,r){jT(e,t);const i=e,o=i.data||{};if(!function(e){if(Ze(e)||"object"!=typeof e)return!1;const t=e;return!(void 0!==t.inputQuantity&&"string"!=typeof t.inputQuantity||void 0!==t.outputQuantity&&"string"!=typeof t.outputQuantity||void 0!==t.totalFees&&"string"!=typeof t.totalFees||void 0!==t.vaultAddress&&"string"!=typeof t.vaultAddress)}(o))throw new zT(`Invalid trade data received for transaction ${t}`);const s={transactionId:t,type:n,method:"native"===r.type?"native":"exact",inputAmount:o.inputQuantity||r.amount,outputAmount:o.outputQuantity||r.expectedAmount||"0",totalFees:o.totalFees||"0",tokenName:r.tokenName,vaultAddress:o.vaultAddress||"",timestamp:Date.now()};return void 0!==i.blockHash&&(s.blockHash=i.blockHash),void 0!==i.gasUsed&&(s.gasUsed=i.gasUsed),void 0!==r.slippageToleranceFactor&&(s.slippageTolerance=r.slippageToleranceFactor),s}const XT="5.0.4-beta.2";class QT{constructor(e){this.logger=e||new We({debug:!1,context:"LiquidityEventExtractor"})}walkPayloadForLiquidityEvents(e,t){const n=[],r=new WeakSet,i=(e,o=0)=>{if(o>50)this.logger.debug("Payload nesting exceeded maximum depth of 50");else if(e&&!Qe(e)&&"object"==typeof e){if(r.has(e))return;r.add(e);const s=this.extractLiquidityFromObject(e);s&&!t.has(s.transactionId)&&(n.push(s),t.add(s.transactionId));for(const t of Object.values(e))i(t,o+1)}};return i(e,0),n}extractLiquidityFromObject(e){const t=this.extractTransactionId(e);if(!t)return null;const n=e.Data,r=n&&"object"==typeof n&&!Array.isArray(n)?n:e,i=this.extractPositionId(r),o=this.extractPoolHash(r),s=this.extractAmounts(r),a=this.extractUserAddress(r),c=this.extractPoolFee(r);if(!(i&&o&&s&&a&&null!==c))return null;const l=this.extractPoolAlias(r),u=this.extractUserBalanceDelta(r),d=this.extractTimestamp(r),h=u?.token0Balance?.collection,g=u?.token1Balance?.collection,p={transactionId:t,positionId:i,poolHash:o,poolFee:c,amounts:s,userAddress:a};return void 0!==h&&(p.token0=h),void 0!==g&&(p.token1=g),void 0!==d&&(p.timestamp=d),void 0!==l&&(p.poolAlias=l),void 0!==u&&(p.userBalanceDelta=u),p}extractTransactionId(e){const t=["transactionId","txId","tx_id","hash","txHash","id"];for(const n of t){const t=e[n];if(Qe(t))return t}return null}extractPositionId(e){const t=["positionId","position_id","tokenId","nftId"];for(const n of t){const t=e[n];if(Qe(t))return t}return null}extractPoolHash(e){const t=["poolHash","pool_hash","poolId","pool"];for(const n of t){const t=e[n];if(Qe(t))return t}return null}extractPoolAlias(e){const t=["poolAlias","pool_alias"];for(const n of t){const t=e[n];if(Qe(t))return t}}extractAmounts(e){const t=e.amounts;if(Array.isArray(t)&&t.length>=2){const e=String(t[0]).trim(),n=String(t[1]).trim();if(e&&n)return[e,n]}const n=e.amount0||e.amount0Desired,r=e.amount1||e.amount1Desired;return void 0!==n&&void 0!==r?[String(n),String(r)]:null}extractUserAddress(e){const t=["userAddress","user","owner","from","sender","wallet","address"];for(const n of t){const t=e[n];if(Qe(t))return t}return null}extractPoolFee(e){const t=["poolFee","fee","feeTier","feeTierBps"];for(const n of t){const t=e[n];if("number"==typeof t)return this.normalizeFee(t);if(Qe(t)){const e=De(t,NaN);if(isFinite(e))return this.normalizeFee(e)}}return null}normalizeFee(e){return 1===e||1e4===e?1e4:.3===e||3e3===e?3e3:.05===e||500===e?500:Number.isInteger(e)?e:e<1?Math.round(1e4*e):e}extractTimestamp(e){const t=["timeStamp","timestamp","time","createdAt","date"];for(const n of t){const t=e[n];if("number"==typeof t)return t;if(Qe(t)){const e=new Date(t).getTime();if(isFinite(e))return e}}}extractUserBalanceDelta(e){const t=e.userBalanceDelta;if(!t||"object"!=typeof t)return;const n=t,r=this.extractBalanceObject(n.token0Balance),i=this.extractBalanceObject(n.token1Balance);if(!r&&!i)return;const o={};return void 0!==r&&(o.token0Balance=r),void 0!==i&&(o.token1Balance=i),o}extractBalanceObject(e){if(!e||"object"!=typeof e)return;const t=e,n=t.collection,r=t.category,i=t.type,o=t.additionalKey,s=t.quantity,a=t.owner;return Qe(n)&&Qe(r)&&Qe(i)&&Qe(o)&&Qe(s)&&Qe(a)?{collection:n,category:r,type:i,additionalKey:o,quantity:s,owner:a}:void 0}}class JT{constructor(e){this.wallet=e.wallet;let t=null,n="STAGE";if(e.env?(n=e.env,t=qT(e.env)):e.baseUrl?.includes("prod")?(n="PROD",t=qT("PROD")):(n="STAGE",t=qT("STAGE")),this.environment=n,this.config={baseUrl:t.launchpadBaseUrl,galaChainBaseUrl:t.galaChainBaseUrl,bundleBaseUrl:t.bundleBaseUrl,webSocketUrl:t.webSocketUrl,dexApiBaseUrl:t.dexApiBaseUrl,dexBackendBaseUrl:t.dexBackendBaseUrl,launchpadFrontendUrl:t.launchpadFrontendUrl,timeout:3e4,debug:!1,...e},this.logger=new We({debug:this.config.debug??!1,context:"LaunchpadSDK"}),this.validateConfiguration(),this.slippageToleranceFactor=void 0===e.slippageToleranceFactor?JT.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR:this.parseSlippageToleranceFactor(e.slippageToleranceFactor),this.maxAcceptableReverseBondingCurveFeeSlippageFactor=void 0===e.maxAcceptableReverseBondingCurveFeeSlippageFactor?JT.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR:this.parseFeeSlippageFactor(e.maxAcceptableReverseBondingCurveFeeSlippageFactor),this.calculateAmountMode=e.calculateAmountMode||JT.DEFAULT_CALCULATE_AMOUNT_MODE,this.pricingConcurrency=e.pricingConcurrency||5,this.galaChainAddressOverride=e.galaChainAddress,this.auth=new vt({wallet:e.wallet,messagePrefix:"Create a GalaChain Wallet"}),this.jwtAuth=new At,e.accessToken){const t=e.accessTokenExpiresIn??86400;this.jwtAuth.setToken(e.accessToken,t)}this.http=new Sr(this.auth,this.config),this.sessionAuth=new br(this.http,this.auth,this.jwtAuth,e.debug||!1),this.galaChainHttp=new Sr(this.auth,{...this.config,baseUrl:this.config.galaChainBaseUrl}),this.bundleHttp=new Sr(this.auth,{...this.config,baseUrl:this.config.bundleBaseUrl}),this.dexApiHttp=new Sr(this.auth,{...this.config,baseUrl:this.config.dexApiBaseUrl}),this.dexBackendHttp=new Sr(this.auth,{...this.config,baseUrl:this.config.dexBackendBaseUrl}),this.galaChainPublicAxios=b(this.config.galaChainBaseUrl,this.config.timeout||3e4),this.galaChainClient=new lc({baseUrl:this.config.galaChainBaseUrl,timeout:this.config.timeout||3e4}),this.cache=new yc(e.debug||!1),this.launchpadService=new Os(this.http,this.jwtAuth),this.tokenResolverService=new ic(this.launchpadService.poolService),this.launchpadAPI=new Bd(this.http,this.tokenResolverService,this.logger,this.bundleHttp,this.galaChainHttp,this.dexApiHttp,this.calculateAmountMode),this.galaChainService=new Ua(this.galaChainHttp,e.wallet,this.tokenResolverService,e.debug||!1,this.galaChainPublicAxios),this.dexService=new $a(this.dexBackendHttp,this.cache,this.galaChainService,e.debug||!1),this.bundleService=new Qa(this.bundleHttp,this.tokenResolverService,this.config.debug||!1,e.wallet,e.wallet?this.getAddress():void 0,this.slippageToleranceFactor,this.maxAcceptableReverseBondingCurveFeeSlippageFactor),this.websocketService=new rc({url:this.config.webSocketUrl},this.config.debug),this.priceHistoryService=new oc(this.dexBackendHttp,this.config.debug||!1,this.tokenResolverService),this.dexQuoteService=new kc(this.galaChainHttp,this.config.galaChainBaseUrl,e.debug||!1,e.dexQuoteNetworkTimeout||3e4),this.gswapService=new pc({privateKey:e.wallet?.privateKey,getWalletAddress:()=>this.wallet?this.getAddress():void 0,gatewayBaseUrl:this.config.galaChainBaseUrl,bundlerBaseUrl:this.config.bundleBaseUrl,galaChainBaseUrl:this.config.galaChainBaseUrl,dexBackendBaseUrl:this.config.dexBackendBaseUrl,dexBackendHttp:this.dexBackendHttp},this.websocketService,this.dexQuoteService),this.dexPoolService=new wc(this.dexBackendHttp,this.config.dexBackendBaseUrl,this.gswapService,this.pricingConcurrency,e.debug||!1),this.nftCollectionService=new kd(this.galaChainHttp,this.galaChainClient)}createOverrideSdk(t){if(!Qe(t))throw j("Invalid privateKey: must be a non-empty string","privateKey");if(!t.match(/^0x[a-fA-F0-9]{64}$/))throw j('Invalid privateKey format: must be "0x" followed by 64 hexadecimal characters',"privateKey");const n=new e.Wallet(t),r={...this.config,wallet:n};return new JT(r)}getAddress(){return this.galaChainAddressOverride?this.galaChainAddressOverride:(this.validateWallet(),this.auth.getAddress())}getEthereumAddress(){return this.validateWallet(),this.wallet.address}validateWallet(){if(!this.wallet)throw W("wallet","Wallet");return this.wallet}setWallet(e){if(!e||"object"!=typeof e||!("address"in e))throw new B("Invalid wallet: must be an ethers Wallet instance, received "+typeof e,"wallet","INVALID_WALLET");this.wallet=e,this.auth.setWallet(e)}getWallet(){return this.wallet}hasWallet(){return void 0!==this.wallet}getConfig(){const{wallet:e,...t}=this.config;return{...t,environment:this.environment,slippageToleranceFactor:this.slippageToleranceFactor,maxAcceptableReverseBondingCurveFeeSlippageFactor:this.maxAcceptableReverseBondingCurveFeeSlippageFactor,calculateAmountMode:this.calculateAmountMode,gasFee:fc.GAS_FEE}}getVersion(){return XT}getUrlByTokenName(e){const t=this.config.launchpadFrontendUrl;if(!t)throw j("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 fetchDexPools(e={}){return this.dexPoolService.fetchDexPools(e)}async fetchAllDexPools(e={}){return this.dexPoolService.fetchAllDexPools(e)}async fetchCompositePoolData(e){return this.dexQuoteService.fetchCompositePoolData(e)}async calculateDexPoolQuoteExactAmountLocal(e){return this.dexQuoteService.calculateDexPoolQuoteExactAmountLocal(e)}async calculateDexPoolQuoteExactAmountExternal(e){return this.dexQuoteService.calculateDexPoolQuoteExactAmountExternal(e)}async calculateDexPoolQuoteExactAmount(e,t="local"){return this.dexQuoteService.calculateDexPoolQuoteExactAmount(e,t)}async fetchTokenDistribution(e){return this.launchpadService.fetchTokenDistribution(e)}async fetchUserHolderContext(e,t){return this.launchpadService.fetchUserHolderContext(e,t)}async fetchTokenBadges(e){return this.launchpadService.fetchTokenBadges(e)}async fetchTokenPrice(e){const{tokenName:t,tokenId:n}=e,{hasA:r}=nt(e,"tokenName","tokenId",{description:"token identifier"});if(r&&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(I(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=rs((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: ${A(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(!t)throw new Error(Tr(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 bt}),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??process.env.SOLANA_PRIVATE_KEY;this._bridgeService=new WT({galaConnectBaseUrl:this.config.dexApiBaseUrl,galaChainWalletAddress:this.getAddress(),ethereumPrivateKey:e?.ethereumPrivateKey??t.privateKey,...n&&{solanaPrivateKey:n},bridgeableTokenService:this.getBridgeableTokenService(),environment:this.environment,...this.config.ethereumRpcUrl&&{ethereumRpcUrl:this.config.ethereumRpcUrl},...this.config.solanaRpcUrl&&{solanaRpcUrl:this.config.solanaRpcUrl}})}return this._bridgeService}getBridgeableTokenService(){return this._bridgeableTokenService||(this._bridgeableTokenService=new Rc(this.dexApiHttp,this.config.debug??!1)),this._bridgeableTokenService}getWrappableTokenService(){return this._wrappableTokenService||(this._wrappableTokenService=new Oc(this.dexApiHttp,this.config.debug??!1)),this._wrappableTokenService}getGalaConnectClient(){if(!this._galaConnectClient){const e=this.getAddress();if(!e)throw new Error("GalaConnectClient requires a wallet. Configure SDK with a wallet first.");if(!this.config.dexApiBaseUrl)throw new Error("DEX API base URL is required for GalaConnectClient. Check SDK configuration.");this._galaConnectClient=new ST({baseUrl:this.config.dexApiBaseUrl,...this.config.galaChainBaseUrl&&{galachainBaseUrl:this.config.galaChainBaseUrl},walletAddress:e})}return this._galaConnectClient}getWrapService(){if(!this._wrapService){const e=this.getWallet();this._wrapService=new kl({galaConnectClient:this.getGalaConnectClient(),wrappableTokenService:this.getWrappableTokenService(),...e&&{walletAddress:this.getAddress(),wallet:e}})}return this._wrapService}getStreamingService(){return this._streamingService||(this._streamingService=new Ol(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1)),this._streamingService}getStreamChatService(){return this._streamChatService||(this._streamChatService=new Gl(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1)),this._streamChatService}getBanService(){return this._banService||(this._banService=new tu(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1)),this._banService}getTokenBanService(){return this._tokenBanService||(this._tokenBanService=new au(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1)),this._tokenBanService}getApiKeyService(){return this._apiKeyService||(this._apiKeyService=new fu(this.http,this.jwtAuth,this.config.debug??!1)),this._apiKeyService}getModeratorService(){return this._moderatorService||(this._moderatorService=new Nu(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1)),this._moderatorService}getFlagService(){return this._flagService||(this._flagService=new zu(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1)),this._flagService}getOverseerService(){return this._overseerService||(this._overseerService=new rd(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1)),this._overseerService}getCommentService(){return this._commentService||(this._commentService=new id(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1)),this._commentService}getContentReactionService(){return this._contentReactionService||(this._contentReactionService=new sd(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1)),this._contentReactionService}getCommentsService(){return this._commentsService||(this._commentsService=new ad(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1)),this._commentsService}getChatMessagesService(){return this._chatMessagesService||(this._chatMessagesService=new hd(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1)),this._chatMessagesService}getStreamWebSocketService(){if(!this._streamWebSocketService){if(!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: "wss://stream.gala.com"\n });\n\nFor MCP Server, set STREAM_WEBSOCKET_URL environment variable.\nSee SDK documentation for streaming configuration details.');this._streamWebSocketService=new zl({url:this.config.streamWebSocketUrl},this.config.debug??!1)}return this._streamWebSocketService}getStreamingEventService(){return this._streamingEventService||(this._streamingEventService=new Hl(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)}async getWrapStatus(e){return this.getWrapService().getWrapStatus(e)}async login(){return this.sessionAuth.login()}async refreshToken(){return this.sessionAuth.refresh()}logout(){this.sessionAuth.logout()}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 getStreamInfo(e){return this.getStreamingService().getStreamInfo(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 getStreamRecordings(e){return this.getStreamingService().getRecordings(e)}async getRecordingDownload(e,t){return this.getStreamingService().getRecordingDownload(e,t)}async deleteRecording(e,t){return this.getStreamingService().deleteRecording(e,t)}async getSimulcastTargets(e){return this.getStreamingService().getSimulcastTargets(e)}async addSimulcastTarget(e){return this.getStreamingService().addSimulcastTarget(e)}async removeSimulcastTarget(e,t){return this.getStreamingService().removeSimulcastTarget(e,t)}async getGlobalStreamingStatus(){return this.getStreamingService().getGlobalStreamingStatus()}async setNextLiveStreamCountdown(e,t){return this.getStreamingService().setNextLiveStreamCountdown(e,t)}async setGlobalStreamingEnabled(e){const t=this.getStreamingService();return e?t.enableGlobalStreaming():t.disableGlobalStreaming()}async getStreamRole(e){return this.getStreamingService().getStreamRole(e)}async getAvailableRoles(){return this.getStreamingService().getAvailableRoles()}async getTokenAccess(e){return this.getStreamingService().getTokenAccess(e)}async getChatStatus(e){return this.getStreamChatService().getChatStatus(e)}async getEngagementStats(e){if(null===Es(e.tokenName))throw W("tokenName","tokenName is required and cannot be empty");return this.getStreamChatService().getEngagementStats(e)}async disableChat(e){return this.getStreamChatService().disableChat(e)}async enableChat(e){return this.getStreamChatService().enableChat(e)}async getGlobalChatStatus(){return this.getStreamChatService().getGlobalChatStatus()}async setGlobalChatEnabled(e){const t=this.getStreamChatService();return e?t.enableGlobalChat():t.disableGlobalChat()}async getPinnedChatMessage(e){return this.getStreamChatService().getPinnedMessage(e)}async pinChatMessage(e,t){return this.getStreamChatService().pinMessage({tokenName:e,messageId:t})}async unpinChatMessage(e){return this.getStreamChatService().unpinMessage(e)}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 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 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 revokeOverseer(e){return this.getOverseerService().revokeOverseer(e)}async getMyOverseerStatus(){return this.getOverseerService().getMyStatus()}async getOverseerSummary(){return this.getOverseerService().getSummary()}async listOverseerUsers(e){return this.getOverseerService().listOverseerUsers(e)}async getOverseerUserSummary(e){return this.getOverseerService().getOverseerUserSummary(e)}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 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){return this.getCommentsService().getComments(e)}async createComment(e){return this.getCommentsService().createComment(e)}async updateComment(e,t){return this.getCommentsService().updateComment(e,t)}async deleteComment(e){return this.getCommentsService().deleteComment(e)}async getChatMessages(e){return this.getChatMessagesService().getChatMessages(e)}async sendChatMessage(e){return this.getChatMessagesService().sendMessage(e)}async updateChatMessage(e,t){return this.getChatMessagesService().updateMessage(e,t)}async deleteChatMessage(e){return this.getChatMessagesService().deleteMessage(e)}async getTrades(e){return this.launchpadService.getTrades(e)}async connectStreamWebSocket(e){const t=this.getStreamWebSocketService();await t.connect(),e&&t.setGlobalCallbacks(e)}async authenticateStreamWebSocket(){const e=this.getWallet();if(!e)throw new Error("WebSocket authentication requires a wallet. Configure SDK with a wallet first.");const t=this.getStreamWebSocketService(),n=this.getAddress(),r=Date.now(),i=`Authenticate stream access for ${n} at ${r}`,o=await e.signMessage(i),s=JSON.stringify({address:n,timestamp:r,message:i,signature:o});t.authenticate(s)}async subscribeToStream(e){return this.getStreamWebSocketService().subscribeToStream(e)}async unsubscribeFromStream(e){return this.getStreamWebSocketService().unsubscribeFromStream(e)}async sendStreamChatViaWebSocket(e,t){return this.getStreamWebSocketService().sendChatMessage(e,t)}async sendStreamReaction(e,t,n=0){return 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)}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)}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)}async getSupportedBridgeTokens(){const e=this.getBridgeService(),t=e.getSupportedBridgeTokens();return{tokens:t,totalCount:t.length,supportedChains:e.getSupportedBridgeChains()}}async fetchTokenBalance(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return bt}),n=t(e.address);if(e.tokenId){const{normalizeToTokenInstanceKey:t}=await Promise.resolve().then(function(){return oa}),r=t(e.tokenId),{collection:i,category:o,type:s,additionalKey:a}=r;return this.galaChainService.fetchTokenBalance({owner:n,collection:i,category:o,additionalKey:a,type:s,instance:"0"},e.withExpired??!1)}if(e.tokenName){const t=os(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(e.tokenName){const t=(await this.fetchTokensHeld({tokenName:e.tokenName,page:1,limit:1,...n&&{address:n}})).tokens[0];if(!t)return null;const r=t.collection||"Token",i={collection:r,category:"Unit",type:t.symbol,additionalKey:"none"};return{quantity:t.quantity,collection:r,category:"Unit",tokenId:Ks(i),symbol:t.symbol,name:t.name}}throw W("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:o,currentSupply:s}=e;let a=t;void 0===o&&void 0===s||(a={tokenName:t,...void 0!==o&&{calculateAmountMode:o},...void 0!==s&&{currentSupply:s}});const c=await this.calculateBuyAmountForGraduation(a),l={tokenName:t,amount:c.remainingTokens,type:"exact",expectedAmount:c.amount,maxAcceptableReverseBondingCurveFee:c.reverseBondingCurveFee,slippageToleranceFactor:this.slippageToleranceFactor};return void 0!==n&&(l.slippageToleranceFactor=n),void 0!==r&&(l.maxAcceptableReverseBondingCurveFeeSlippageFactor=r),void 0!==i&&(l.privateKey=i),await this.buy(l)}async calculateInitialBuyAmount(e){const t={nativeTokenQuantity:e};return this.launchpadAPI.calculateInitialBuyAmount(t)}async buy(e){if(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(!n)throw V("No transaction ID returned from buy operation");return this.waitForConfirmation(n,t=>VT(t,n,"buy",e))}async sell(e){if(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(!n)throw V("No transaction ID returned from sell operation");return this.waitForConfirmation(n,t=>VT(t,n,"sell",e))}async getBundlerTransactionResult(e){return this.bundleService.getBundlerTransactionResult(e)}async launchToken(e){if(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=>{jT(n,t);const r=n?.data||{};if(!function(e){if(Ze(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 zT(`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(),...n.blockHash&&{blockHash:n.blockHash},...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(e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...r}=e;return t.uploadTokenImage(r)}return this.validateWallet(),this.launchpadService.uploadImageByTokenName(e)}async updateTokenSocials(e){return this.launchpadService.updateTokenSocials(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 fetchProfile(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return bt}),n=t(e)||this.getAddress();return this.launchpadService.fetchProfile(n)}async fetchReferralUrl(){this.validateWallet();const e=this.getAddress();return await this.dexApiHttp.get(Ot,void 0,{"x-wallet-address":e})}async fetchReferrals(e){let t;if(e?.address)if(e.address.startsWith("client|"))t=e.address;else{const{normalizeAddressInput:n}=await Promise.resolve().then(function(){return bt}),r=n(e.address);if(!r)throw new B(`Invalid address format: "${e.address}". Expected formats: eth|0x..., 0x..., or client|...`);t=r}else t=this.getAddress();const n=e?.page??1,r=e?.limit??10,i={pageNumber:n,limit:r,sortBy:e?.sortBy??"joined",sortDir:e?.sortDir??"desc"},o=await this.dexApiHttp.get(Ft,i,{"x-wallet-address":t});if(!Array.isArray(o))throw new P("Unexpected API response: expected array, got "+typeof o);return{referrals:o,page:n,limit:r,hasMore:o.length===r}}async fetchAllReferrals(e){const t=await Yo((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){let t;if(e?.address)if(e.address.startsWith("client|"))t=e.address;else{const{normalizeAddressInput:n}=await Promise.resolve().then(function(){return bt}),r=n(e.address);if(!r)throw new B(`Invalid address format: "${e.address}". Expected formats: eth|0x..., 0x..., or client|...`);t=r}else t=this.getAddress();const n=await this.dexApiHttp.get(Ut,void 0,{"x-wallet-address":t});if(!n||"number"!=typeof n.referralCount||!n.rewardTotals)throw new P(`Unexpected API response: expected { referralCount, rewardTotals }, got ${JSON.stringify(n)}`);return n}async registerAccount(e){let t;if(e?.address)if(e.address.startsWith("client|"))t=e.address;else{const{normalizeAddressInput:n}=await Promise.resolve().then(function(){return bt}),r=n(e.address);if(!r)throw new B(`Invalid address format: "${e.address}". Expected formats: eth|0x..., 0x..., or client|...`);t=r}else t=this.getAddress();const n=await this.dexApiHttp.post($t,{address:t});if(!n||"boolean"!=typeof n.exists)throw new P(`Unexpected API response: expected { exists, walletAlias? }, got ${JSON.stringify(n)}`);if(n.exists){if(!n.walletAlias)throw new P(`Unexpected API response: exists=true but walletAlias is missing, got ${JSON.stringify(n)}`);return{exists:!0,walletAlias:n.walletAlias}}return{exists:!1,walletAlias:n.walletAlias||t}}async updateProfile(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return bt}),n={...e,address:t(e.address)};if(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 bt}),n={...e,address:t(e.address)||this.getAddress()};if(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 bt}),n=t(e?.address)||this.getAddress(),r={page:e?.page||1,limit:e?.limit||10,address:n};return e?.tokenName&&(r.tokenName=e.tokenName),e?.search&&(r.search=e.search),this.launchpadService.fetchTokensHeld(r)}async fetchTokensCreated(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return bt}),n={type:"DEFI",address:t(e?.address)||this.getAddress(),page:e?.page||1,limit:e?.limit||10};return e?.tokenName&&(n.tokenName=e.tokenName),e?.search&&(n.search=e.search),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 bt}),n={...e,recipientAddress:t(e.recipientAddress)};if(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 bt}),n={...e,to:t(e.to)};if(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 lockTokens(e){const t=await Promise.all(e.tokens.map(async e=>{if(e.lockAuthority){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return bt});return{...e,lockAuthority:t(e.lockAuthority)}}return e})),n={...e,tokens:t};if(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(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(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),e||(this._bridgeableTokenService&&this._bridgeableTokenService.clearCache(),this._wrappableTokenService&&this._wrappableTokenService.clearCache())}validateConfiguration(){try{oe(this.config.timeout,1,3e5,"timeout")}catch{this.logger.warn(`Invalid timeout value: ${this.config.timeout}. Using default 30000ms.`),this.config.timeout=3e4}if(!this.config.baseUrl)throw j("baseUrl is required in configuration","baseUrl");if(!this.config.webSocketUrl)throw j("webSocketUrl is required in configuration","webSocketUrl");try{new URL(this.config.baseUrl)}catch{throw j(`Invalid baseUrl format: ${this.config.baseUrl}`,"baseUrl")}try{new URL(this.config.webSocketUrl)}catch{throw j(`Invalid webSocketUrl format: ${this.config.webSocketUrl}`,"webSocketUrl")}if(this.config.galaChainBaseUrl)try{new URL(this.config.galaChainBaseUrl)}catch{throw j(`Invalid galaChainBaseUrl format: ${this.config.galaChainBaseUrl}`,"galaChainBaseUrl")}if(this.config.bundleBaseUrl)try{new URL(this.config.bundleBaseUrl)}catch{throw j(`Invalid bundleBaseUrl format: ${this.config.bundleBaseUrl}`,"bundleBaseUrl")}if(this.config.launchpadFrontendUrl)try{new URL(this.config.launchpadFrontendUrl)}catch{throw j(`Invalid launchpadFrontendUrl format: ${this.config.launchpadFrontendUrl}`,"launchpadFrontendUrl")}}parseSlippageToleranceFactor(e){const t=De("string"==typeof e||"number"==typeof e?e:String(e),JT.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR);return t<0||t>1?(this.logger.warn(`Invalid slippage tolerance factor: ${e}, using default: ${JT.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR}`),JT.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR):t}parseFeeSlippageFactor(e){const t=De("string"==typeof e||"number"==typeof e?e:String(e),JT.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR);return t<0||t>1?(this.logger.warn(`Invalid fee slippage factor: ${e}, using default: ${JT.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR}`),JT.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("completed"!==n.status)throw new HT(e,n.status,n.message);let r;try{r=t(n)}catch(t){if(t instanceof zT)throw t;throw new zT(`Failed to transform WebSocket response for transaction ${e}`,S(t)?t:new Error(A(t)))}return this.logger.debug(`Transaction confirmed: ${e}`,r),r}catch(t){if(this.logger.error(`Transaction confirmation failed: ${e}`,t),t instanceof HT||t instanceof zT)throw t;throw new zT(`WebSocket confirmation failed for transaction ${e}`,S(t)?t:new Error(A(t)))}}async warmCacheFromPools(e){if(!e||!Array.isArray(e))return;const{extractMetadataFromPoolData:t,isValidPoolForCaching:n}=await Promise.resolve().then(function(){return iE});e.forEach(e=>{if(!n(e))return;const r=t(e,this.logger);r&&this.launchpadAPI.warmCacheFromPoolData(e.tokenName,r)})}async getSwapQuoteExactInput(e,t,n){return this.gswapService.getSwapQuoteExactInput({fromToken:e,toToken:t,amount:n})}async getSwapQuoteExactOutput(e,t,n){return this.gswapService.getSwapQuoteExactOutput({fromToken:e,toToken:t,amount:n})}async executeSwap(e,t,n,r,i,o=.01){return this.validateWallet(),this.gswapService.executeSwap({fromToken:e,toToken:t,inputAmount:n,estimatedOutput:r,feeTier:i,slippageTolerance:o})}async getSwapUserAssets(e){return this.gswapService.getUserAssets(e)}async getAllSwapUserAssets(e){return this.gswapService.getAllUserAssets(e)}async fetchAvailableDexTokens(e={}){return this.gswapService.fetchAvailableDexTokens(e)}async fetchAllAvailableDexTokens(e={}){return this.gswapService.fetchAllAvailableDexTokens(e)}async getSwapPoolInfo(e,t){return this.gswapService.getPoolInfo(e,t)}async getSwapPoolPrice(e,t,n){return this.gswapService.getPositionCurrentPrice({token0:e,token1:t,feeTier:n})}async getSwapUserLiquidityPositions(e,t,n,r){let i,o;"string"==typeof n?(i=n,o=r):"object"==typeof n?o=n:r&&(o=r);return await this.gswapService.getUserLiquidityPositions(e,t,i,o)}async getAllSwapUserLiquidityPositions(e,t){const n=await this.gswapService.getAllSwapUserLiquidityPositions(e,t);if(!t?.withPrices){if(Array.isArray(n))return n;if(n&&"items"in n)return n.items}return n}async getSwapLiquidityPosition(e,t){return this.gswapService.getLiquidityPosition(e,t)}async getSwapLiquidityPositionById(e,t,n,r,i,o,s){return this.gswapService.getLiquidityPositionById(e,t,n,r,i,o,s)}async fetchSwapPositionDirect(e){return this.gswapService.fetchSwapPositionDirect(e)}async getSwapEstimateRemoveLiquidity(e){return this.gswapService.estimateRemoveLiquidity(e)}async addSwapLiquidityByPrice(e){return this.gswapService.addLiquidityByPrice(e)}async addSwapLiquidityByTicks(e){this.validateWallet();const t={token0:e.token0,token1:e.token1,fee:e.feeTier,tickLower:e.tickLower,tickUpper:e.tickUpper,amount0Desired:e.amount0Desired,amount1Desired:e.amount1Desired};return void 0!==e.amount0Min&&(t.amount0Min=e.amount0Min),void 0!==e.amount1Min&&(t.amount1Min=e.amount1Min),this.gswapService.addSwapLiquidityByTicks(t)}async removeSwapLiquidity(e){return this.validateWallet(),this.gswapService.removeLiquidity(e)}async collectSwapPositionFees(e){return this.validateWallet(),this.gswapService.collectPositionFees(e)}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`),()=>{})}onDexPoolCreation(e,t){const n=1e3,r=Math.max(t?.intervalMs??3e4,n);t?.intervalMs&&t.intervalMs<n&&this.logger.warn(`Poll interval ${t.intervalMs}ms is below minimum 1000ms. Using minimum interval instead.`);const i=t?.minTVL,o=t?.tokens,s=new Map;let a=!0,c=null;let l=0;const u=async()=>{if(a){try{const t=await this.fetchDexPools({limit:20});l>0&&(this.logger.debug("Successfully recovered from polling errors"),l=0),t.items.forEach(t=>{const n=(e=>`${e.token0}-${e.token1}-${e.fee}`)(t);if(!s.has(n)){if((e=>{if(s.set(e,!0),s.size>1e3){const e=s.keys().next().value;void 0!==e&&s.delete(e)}})(n),i){if((t.token0Tvl+t.token1Tvl)/2<i)return}if(o&&o.length>0){if(!(o.includes(t.token0)||o.includes(t.token1)))return}e(t)}})}catch(e){l++;const t=A(e);l>=5?this.logger.error(`Polling for new DEX pools failed ${l} consecutive times. Last error: ${t}. Continuing to retry...`):l>1?this.logger.warn(`Error polling for new DEX pools (attempt ${l}/5): ${t}`):this.logger.debug(`Error polling for new DEX pools: ${t}`)}if(a){const e=Math.min(Math.max(l-1,0),2),t=r*Math.pow(2,e);c=setTimeout(u,t)}}};return u(),()=>{a=!1,c&&clearTimeout(c),this.logger.debug("Stopped watching for DEX pool creation")}}onLaunchpadTokenCreation(e,t){const n=1e3,r=Math.max(t?.intervalMs??3e4,n);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,o=new Map;let s=!0,a=null;let c=0;const l=async()=>{if(s){try{const t=await this.fetchPools({type:"recent",limit:20});c>0&&(this.logger.debug("Successfully recovered from polling errors"),c=0),t.items.forEach(t=>{o.has(t.tokenName)||((e=>{if(o.set(e,!0),o.size>1e3){const e=o.keys().next().value;void 0!==e&&o.delete(e)}})(t.tokenName),i&&t.creatorAddress!==i||e(t))})}catch(e){c++;const t=A(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(s){const e=Math.min(Math.max(c-1,0),2),t=r*Math.pow(2,e);a=setTimeout(l,t)}}};return l(),()=>{s=!1,a&&clearTimeout(a),this.logger.debug("Stopped watching for launchpad token creation")}}normalizeFee(e){if(null==e)return null;const t=Ue("string"==typeof e||"number"==typeof e?e:String(e),Number.NaN);return Number.isNaN(t)?null:1===t||1e4===t?1e4:.3===t||3e3===t?3e3:.05===t||500===t?500:!Number.isInteger(t)||500!==t&&3e3!==t&&1e4!==t?null:t}extractField(e,...t){if("object"!=typeof e||null===e)return"";const n=e;for(const e of t)if(n[e])return String(n[e]);return""}looksLikePoolPair(e){if("string"!=typeof e)return null;const t=e.trim();return vc.isValidPoolKey(t)?t:null}buildPoolPairFromObject(e){if("object"!=typeof e||null===e)return null;const t=e,n=this.extractField(t,"token0ClassKey","token0Class","token0","token0Symbol")||"",r=this.extractField(t,"token1ClassKey","token1Class","token1","token1Symbol")||"",i=this.normalizeFee(t.feeTier??t.fee??t.feeTierBps??t.liquidityFeeBps??t.feeBps);return n&&r&&null!==i?`${n}/${r}/${i}`:null}parsePoolPairString(e){const t=vc.parsePoolKey(e);if(!t)return null;const n=Vs(t.token0)?js(t.token0).collection:t.token0,r=Vs(t.token1)?js(t.token1).collection:t.token1,i=t.feeTier.toString();return n&&r&&i?{token0:n,token1:r,fee:i,poolPair:e}:null}serializeBalanceToken(e){if(!e||"object"!=typeof e)return"";const t=e;return[(t.collection??t.token??"")||"",(t.category??"")||"none",(t.type??"")||"none",(t.additionalKey??"none")||"none"].join("|")}buildPoolPairFromBalances(e){if("object"!=typeof e||null===e)return null;const t=e,n=t.userBalanceDelta??t.balanceDelta??t.delta;if(!n||"object"!=typeof n||null===n)return null;const r=n,i=r.token0Balance??r.token0??r.baseBalance??r.primaryBalance,o=r.token1Balance??r.token1??r.quoteBalance??r.secondaryBalance,s=this.serializeBalanceToken(i),a=this.serializeBalanceToken(o),c=this.normalizeFee(t.poolFee??t.feeTier??t.fee??t.feeTierBps??t.liquidityFeeBps);return s&&a&&null!==c?`${s}/${a}/${c}`:null}extractPoolDataFromPayload(e){if("string"==typeof e){const t=this.looksLikePoolPair(e);return t?this.parsePoolPairString(t):null}if("object"!=typeof e||null===e)return null;const t=e,n=this.looksLikePoolPair(t.poolPair);if(n)return this.parsePoolPairString(n);const r=this.buildPoolPairFromBalances(t);if(r)return this.parsePoolPairString(r);const i=this.buildPoolPairFromObject(t);if(i)return this.parsePoolPairString(i);if(t.pool&&"object"==typeof t.pool&&null!==t.pool){const e=this.extractPoolDataFromPayload(t.pool);if(e)return e}return null}matchesPoolFilter(e,t){if(t?.tokenFilter){if(!(e.token0===t.tokenFilter||e.token1===t.tokenFilter))return!1}if(t?.pairTokens){const[n,r]=t.pairTokens,i=e.token0===n||e.token1===n,o=e.token0===r||e.token1===r;if(!i||!o||n===r)return!1}if(void 0!==t?.feeTierFilter){if(this.normalizeFee(t.feeTierFilter)!==this.normalizeFee(e.fee))return!1}return!0}matchesCreatorFilter(e,t){return!t||e.creatorAddress===t}subscribeToTokenCreations(e,t){if(this.logger.debug("Subscribing to token creation broadcasts"+(t?.creatorFilter?` (filter: ${t.creatorFilter})`:"")),!this.websocketService)throw j("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(n&&n.Data&&"object"==typeof n.Data){const r=n.Data;if("CreateSale"===r.functionName){const n={tokenName:r.tokenName||"",symbol:r.symbol||"",creatorAddress:r.creatorAddress||"",description:r.description||"",image:r.image||"",vaultAddress:r.vaultAddress||"",tokenStringKey:r.tokenStringKey||"",preBuyQuantity:r.initialBuyQuantity||"0",websiteUrl:r.websiteUrl||"",telegramUrl:r.telegramUrl||"",twitterUrl:r.twitterUrl||"",instagramUrl:r.instagramUrl||"",facebookUrl:r.facebookUrl||"",redditUrl:r.redditUrl||"",tiktokUrl:r.tiktokUrl||"",isFinalized:r.isFinalized||!1};this.matchesCreatorFilter(n,t?.creatorFilter)&&e(n)}}}}catch(e){this.logger.warn(`Error processing token creation broadcast: ${A(e)}`)}};let o=this.websocketService.getSocket();if(o)o.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: ${A(e)}`);this.logger.warn("Failed to establish WebSocket connection:",e),t?.onError&&t.onError(n)});let e=0;const s=()=>{if(o=this.websocketService.getSocket(),!o&&e<JT.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS)return e++,void(r=setTimeout(()=>s(),JT.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS));if(!o&&e>=JT.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS){const e=new Error(`WebSocket not available after ${JT.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS*JT.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS}ms`);return this.logger.warn("Token creation broadcast subscription timeout:",e.message),void(t?.onError&&t.onError(e))}o&&(o.onAny(i),n=!0,this.logger.debug("Token creation broadcast listener registered"))};s()}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)}}}walkPayloadForPools(e,t,n=new WeakSet){const r=[];if("string"==typeof e){const n=this.looksLikePoolPair(e);if(n){const e=this.parsePoolPairString(n);e&&!t.has(e.poolPair)&&(t.add(e.poolPair),r.push(e))}return r}if("object"!=typeof e||null===e)return r;if(n.has(e))return r;n.add(e);const i=this.extractPoolDataFromPayload(e);i&&!t.has(i.poolPair)&&(t.add(i.poolPair),r.push(i));for(const i of Object.values(e)){const e=this.walkPayloadForPools(i,t,n);r.push(...e)}return r}subscribeToDexPoolAdded(e,t){if(this.logger.debug("Subscribing to DEX pool creation broadcasts"+(t?.tokenFilter?` (filter: ${t.tokenFilter})`:t?.pairTokens?` (pair: ${t.pairTokens.join("/")})`:"")),!this.websocketService)throw j("WebSocket service not initialized. Ensure websocketUrl is configured and the service is connected.","websocketService");let n=!1,r=null;const i=new Set,o=(n,...r)=>{try{for(const n of r){const r=this.walkPayloadForPools(n,i);for(const n of r)this.matchesPoolFilter(n,t)&&e(n)}}catch(e){this.logger.warn(`Error processing DEX pool broadcast: ${A(e)}`)}};let s=this.websocketService.getSocket();if(s)s.onAny(o),n=!0,this.logger.debug("DEX pool 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: ${A(e)}`);this.logger.warn("Failed to establish WebSocket connection:",e),t?.onError&&t.onError(n)});let e=0;const i=()=>{if(s=this.websocketService.getSocket(),!s&&e<JT.DEX_POOL_SOCKET_WAIT_ATTEMPTS)return e++,void(r=setTimeout(()=>i(),JT.DEX_POOL_SOCKET_POLL_INTERVAL_MS));if(!s&&e>=JT.DEX_POOL_SOCKET_WAIT_ATTEMPTS){const e=new Error(`WebSocket not available after ${JT.DEX_POOL_SOCKET_WAIT_ATTEMPTS*JT.DEX_POOL_SOCKET_POLL_INTERVAL_MS}ms`);return this.logger.warn("DEX pool subscription timeout:",e.message),void(t?.onError&&t.onError(e))}s&&(s.onAny(o),n=!0,this.logger.debug("DEX pool broadcast listener registered"))};i()}return()=>{try{if(null!==r&&(clearTimeout(r),r=null,this.logger.debug("Cleared DEX pool polling timeout")),!n)return void this.logger.debug("Cleanup called before listener registration - no action needed");const e=this.websocketService.getSocket();e&&(e.offAny(o),n=!1,this.logger.debug("Stopped listening to DEX pool broadcasts"))}catch(e){this.logger.warn("Error removing DEX pool listener:",e)}}}subscribeToDexSwapExecuted(e,t){if(this.logger.debug("Subscribing to DEX swap execution broadcasts"+(t?.tokenFilter?` (filter: ${t.tokenFilter})`:t?.pairTokens?` (pair: ${t.pairTokens.join("/")})`:"")),!this.websocketService)throw j("WebSocket service not initialized. Ensure websocketUrl is configured and the service is connected.","websocketService");let n=null,r=null,i=null,o=!1;const s=async e=>{const t=vc.parsePoolKey(e);if(!t)throw new Error(`Invalid pool key format: ${e}`);return await this.dexQuoteService.fetchCompositePoolData({token0:t.token0,token1:t.token1,fee:t.feeTier})},a=()=>{const c=this.websocketService.getSocket();if(!c)return this.logger.debug("WebSocket not yet ready for swap monitoring, polling..."),void(n=setTimeout(()=>a(),100));o=!0,r=new Cc(c,s,this.dexQuoteService,t||{},this.logger),i=r.subscribe(t||{},e),this.logger.debug("DEX swap monitoring subscription established")};return this.websocketService.getSocket()||(this.logger.debug("WebSocket not yet connected, initiating connection for swap monitoring..."),this.websocketService.connect().catch(e=>{const n=new Error(`WebSocket connection failed for swap monitoring: ${A(e)}`);this.logger.warn("Failed to establish WebSocket connection:",e),t?.onError&&t.onError(n)})),a(),()=>{try{n&&clearTimeout(n),i&&o&&i(),r&&r.shutdown().catch(e=>{this.logger.warn("Error shutting down swap monitor:",e)})}catch(e){this.logger.warn("Error cleaning up swap monitor:",e)}}}subscribeToDexLiquidityAdded(e,t){return this.subscribeToDexLiquidityEvents(e,t)}subscribeToDexLiquidityRemoved(e,t){return this.subscribeToDexLiquidityEvents(e,t)}subscribeToDexLiquidityChanged(e,t){return this.subscribeToDexLiquidityEvents(e,t)}subscribeToDexLiquidityEvents(e,t){if(this.logger.debug("Subscribing to DEX liquidity broadcasts"+(t?.tokenFilter?` (filter: ${t.tokenFilter})`:t?.pairTokens?` (pair: ${t.pairTokens.join("/")})`:"")),!this.websocketService)throw j("WebSocket service not initialized. Ensure websocketUrl is configured and the service is connected.","websocketService");let n=!1,r=null;const i=new Set,o=new QT(this.logger),s=(n,...r)=>{try{for(const n of r){const r=o.walkPayloadForLiquidityEvents(n,i);for(const n of r)if(this.matchesLiquidityFilter(n,t))try{const t=e(n);t instanceof Promise&&t.catch(e=>{this.logger.warn(`Error in liquidity event callback: ${A(e)}`)})}catch(e){this.logger.warn(`Error in liquidity event callback: ${A(e)}`)}}}catch(e){this.logger.warn(`Error processing DEX liquidity broadcast: ${A(e)}`)}};let a=this.websocketService.getSocket();if(a)a.onAny(s),n=!0,this.logger.debug("DEX liquidity broadcast listener registered");else{this.logger.debug("WebSocket not yet connected, initiating connection for liquidity monitoring..."),this.websocketService.connect().catch(e=>{const n=new Error(`WebSocket connection failed: ${A(e)}`);this.logger.warn("Failed to establish WebSocket connection:",e),t?.onError&&t.onError(n)});let e=0;const i=()=>{if(a=this.websocketService.getSocket(),!a&&e<JT.DEX_POOL_SOCKET_WAIT_ATTEMPTS)return e++,void(r=setTimeout(()=>i(),JT.DEX_POOL_SOCKET_POLL_INTERVAL_MS));if(!a&&e>=JT.DEX_POOL_SOCKET_WAIT_ATTEMPTS){const e=new Error(`WebSocket not available after ${JT.DEX_POOL_SOCKET_WAIT_ATTEMPTS*JT.DEX_POOL_SOCKET_POLL_INTERVAL_MS}ms`);return this.logger.warn("DEX liquidity subscription timeout:",e.message),void(t?.onError&&t.onError(e))}a&&(a.onAny(s),n=!0,this.logger.debug("DEX liquidity broadcast listener registered"))};i()}return async()=>{try{if(null!==r&&(clearTimeout(r),r=null,this.logger.debug("Cleared DEX liquidity polling timeout")),!n)return void this.logger.debug("Cleanup called before listener registration - no action needed");const e=this.websocketService.getSocket();e&&(e.offAny(s),n=!1,this.logger.debug("Stopped listening to DEX liquidity broadcasts"))}catch(e){this.logger.warn("Error removing DEX liquidity listener:",e)}}}matchesLiquidityFilter(e,t){if(!t)return!0;if(t.positionId&&e.positionId!==t.positionId)return!1;if(t.poolHash&&e.poolHash!==t.poolHash)return!1;if(void 0!==t.feeTierFilter){const n=this.normalizeFeeTier(t.feeTierFilter);if(e.poolFee!==n)return!1}if(t.userFilter&&e.userAddress!==t.userFilter)return!1;if(t.tokenFilter){const n=!!e.token0&&xs(e.token0,t.tokenFilter),r=!!e.token1&&xs(e.token1,t.tokenFilter);if(!n&&!r)return!1}if(t.pairTokens){const[n,r]=t.pairTokens,i=e.token0||"",o=e.token1||"",s=xs(i,n)&&xs(o,r),a=xs(i,r)&&xs(o,n);if(!s&&!a)return!1}if(t.minAmount){const n=De(t.minAmount),r=De(e.amounts[0]),i=De(e.amounts[1]);if(Math.abs(r)<n&&Math.abs(i)<n)return!1}return!0}normalizeFeeTier(e){if("number"==typeof e)return e>=100?e:Math.round(1e4*e);return function(e,t=3e3){if(Ze(e))return t;if("number"==typeof e)return isNaN(e)?t:Math.floor(e);const n=String(e).trim();if(n.endsWith("%")){const e=De(n.replace("%",""));return Math.floor(1e4*e)}const r=parseFloat(n);return isNaN(r)?t:r<100?Math.floor(1e4*r):Math.floor(r)}(e)}getNftCollectionClaimFee(){return this.nftCollectionService.getCollectionClaimFee()}getNftTokenClassCreateFee(){return this.nftCollectionService.getTokenClassCreateFee()}async estimateNftMintFee(e){return this.nftCollectionService.estimateMintFee(e)}estimateNftOperationFees(e){return this.nftCollectionService.estimateNftOperationFees(e)}async claimNftCollection(e){return this.nftCollectionService.claimCollection(e)}async fetchNftCollections(e){return this.nftCollectionService.fetchUserCollections(e)}async isNftCollectionAvailable(e){return this.nftCollectionService.isCollectionAvailable(e)}async createNftTokenClass(e){return this.nftCollectionService.createTokenClass(e)}async fetchNftTokenClasses(e){return this.nftCollectionService.fetchTokenClasses(e)}async mintNft(e){return this.nftCollectionService.mintNft(e)}async fetchNftBalances(e,t){return this.nftCollectionService.fetchNftBalances(e,t)}async cleanup(){try{this.logger.debug("Starting cleanup..."),this.http.cleanup(),this.websocketService&&this.websocketService.disconnect(),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 We({debug:e,context:"LaunchpadSDK"});t.debug("Starting global cleanup...");const{WebSocketService:n}=require("./services/WebSocketService");n.cleanupAll(e),t.debug("Global cleanup completed")}}JT.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR=.15,JT.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR=.01,JT.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY=fc.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY,JT.DEFAULT_CALCULATE_AMOUNT_MODE=Nd.LOCAL,JT.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS=30,JT.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS=100,JT.DEX_POOL_SOCKET_WAIT_ATTEMPTS=30,JT.DEX_POOL_SOCKET_POLL_INTERVAL_MS=100;class ZT{static generateWallet(){try{const t=e.Wallet.createRandom();if(!t.mnemonic?.phrase)throw W("mnemonic","Mnemonic phrase");const n=this.toGalaAddress(t.address);return{privateKey:t.privateKey,address:t.address,galaAddress:n,mnemonic:t.mnemonic.phrase,wallet:new e.Wallet(t.privateKey)}}catch(t){if("undefined"!=typeof process&&"test"===process.env.NODE_ENV){const t=`test-wallet-${Date.now()}-${++this.testCounter}`,n="0x"+Buffer.from(t).toString("hex").padStart(64,"1").slice(0,64),r=new e.Wallet(n),i=this.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 t}}static fromPrivateKey(t){const n=new e.Wallet(t),r=this.toGalaAddress(n.address);return{privateKey:n.privateKey,address:n.address,galaAddress:r,mnemonic:"",wallet:n}}static fromMnemonic(t,n=0){try{const r=e.Mnemonic.fromPhrase(t),i=e.HDNodeWallet.fromMnemonic(r,`m/44'/60'/0'/0/${n}`),o=new e.Wallet(i.privateKey),s=this.toGalaAddress(o.address);return{privateKey:o.privateKey,address:o.address,galaAddress:s,mnemonic:t,wallet:o}}catch(r){if("undefined"!=typeof process&&"test"===process.env.NODE_ENV){const r=`test-mnemonic-index-${n}-${t}`,i="0x"+Buffer.from(r).toString("hex").padStart(64,"1").slice(0,64),o=new e.Wallet(i),s=this.toGalaAddress(o.address);return{privateKey:o.privateKey,address:o.address,galaAddress:s,mnemonic:t,wallet:o}}throw r}}static toGalaAddress(e){const t=ht(e);if(!/^[a-fA-F0-9]{40}$/.test(t))throw z("address","a valid Ethereum address (40 hex characters)");return`eth|${t}`}static toEthereumAddress(e){try{return pt(e)}catch(t){const n=A(t);if(n.includes("required")||!e?.startsWith("eth|"))throw W("galaAddress","Gala address starting with eth|");if(n.includes("Invalid backend"))throw z("galaAddress","Gala format (eth|{40-hex-chars})");throw t}}static isValidEthereumAddress(e){try{const t=ht(e);return/^[a-fA-F0-9]{40}$/.test(t)}catch{return!1}}static isValidGalaAddress(e){return!!e&&"backend"===kt(e)}static generateMultipleWallets(e=1){oe(e,1,100,"count");const t=[];if("undefined"!=typeof process&&"test"===process.env.NODE_ENV)for(let n=0;n<e;n++){const e=`test-multi-${n}-${Date.now()}-${++this.testCounter}`,r="0x"+Buffer.from(e).toString("hex").padStart(64,"1").slice(0,64);t.push(this.fromPrivateKey(r))}else for(let n=0;n<e;n++)t.push(this.generateWallet());return t}static getWalletSummary(e,t=!1){const n=["🔐 Wallet Information","═".repeat(50),`📍 Address: ${e.address}`,`🎮 Gala Address: ${e.galaAddress}`,`🌱 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 YT(e){if(void 0===e)return ZT.generateWallet();const t=e.trim();if(!Qe(t))throw z("input","a non-empty string");if(function(e){const t=ht(e);return/^[a-fA-F0-9]{64}$/.test(t)}(t))return ZT.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 ZT.fromMnemonic(t);throw z("input","a private key (64 hex characters) or mnemonic (12/24 words)","Wallet input")}ZT.testCounter=0;function eE(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 tE(e){if(!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}class nE{static fastValidation(e,t,n,r=nE.DEFAULT_CONFIG){const i=Date.now();let o=!0;try{const s=wo(e.sqrtPrice),a=wo(t.sqrtPrice);n.zeroForOne?a.gte(s)&&(this.logger.error("Fast validation failed: price did not decrease for zeroForOne swap",{originalSqrtPrice:s.toString(),updatedSqrtPrice:a.toString(),zeroForOne:n.zeroForOne}),o=!1):a.lte(s)&&(this.logger.error("Fast validation failed: price did not increase for oneForZero swap",{originalSqrtPrice:s.toString(),updatedSqrtPrice:a.toString(),zeroForOne:n.zeroForOne}),o=!1);const c=wo(e.liquidity),l=wo(t.liquidity);if(!Co(c)){const e=Lo(l.minus(c).abs(),c);e.gt(r.maxLiquidityChangePct)&&this.logger.warn("Fast validation warning: large liquidity change detected (could be legitimate)",{originalLiquidity:c.toString(),updatedLiquidity:l.toString(),changePct:ko(e.times(100),2)})}const u=wo(e.feeGrowthGlobal0),d=wo(t.feeGrowthGlobal0),h=wo(e.feeGrowthGlobal1),g=wo(t.feeGrowthGlobal1);n.zeroForOne?g.lt(h)&&(this.logger.error("Fast validation failed: feeGrowthGlobal1 decreased for zeroForOne",{originalFeeGrowth1:h.toString(),updatedFeeGrowth1:g.toString()}),o=!1):d.lt(u)&&(this.logger.error("Fast validation failed: feeGrowthGlobal0 decreased for oneForZero",{originalFeeGrowth0:u.toString(),updatedFeeGrowth0:d.toString()}),o=!1);const p=wo(e.protocolFeesToken0),f=wo(t.protocolFeesToken0),m=wo(e.protocolFeesToken1),y=wo(t.protocolFeesToken1);f.lt(p)&&(this.logger.error("Fast validation failed: protocolFeesToken0 decreased",{originalProtocolFees0:p.toString(),updatedProtocolFees0:f.toString()}),o=!1),y.lt(m)&&(this.logger.error("Fast validation failed: protocolFeesToken1 decreased",{originalProtocolFees1:m.toString(),updatedProtocolFees1:y.toString()}),o=!1);const w=Ve(i);return this.logger.debug("Fast validation completed",{passed:o,elapsedMs:w}),o}catch(e){return this.logger.error("Fast validation exception",e),!1}}static moderateValidation(e,t,n=nE.DEFAULT_CONFIG){const r=Date.now(),i=[];let o=0;try{if(t.actualSqrtPrice){const r=wo(e.sqrtPrice),s=wo(t.actualSqrtPrice),a=this.calculateDriftPercentage(r,s);o=a,a>100*n.maxDriftThreshold&&i.push(`Price drift detected: ${ko(a,4)}% (threshold: ${ko(100*n.maxDriftThreshold,4)}%)`),this.logger.debug("Price drift comparison",{calculatedSqrtPrice:r.toString(),actualSqrtPrice:s.toString(),driftPct:a.toFixed(4)})}const s=wo(e.sqrtPrice),a=Lo(s,Eo()),l=c.sqrtPriceToTick(a),u=e.tick??0,d=Math.abs(l-u);d>n.maxTickDrift&&i.push(`Tick/price mismatch: tick=${u}, calculated=${l}, drift=${d}`);const h=wo(e.feeGrowthGlobal0),g=wo(e.feeGrowthGlobal1),p=wo(e.liquidity);try{Ro(h,g,p)}catch(e){i.push(e.message)}const f=0===i.length,m=!f||o>100*n.maxDriftThreshold,y=Ve(r);return this.logger.debug("Moderate validation completed",{isValid:f,shouldRefetch:m,driftPercentage:o,errorCount:i.length,elapsedMs:y}),this.buildValidationResult(f,o,m,i)}catch(e){return this.logger.error("Moderate validation exception",e),this.buildValidationResult(!1,0,!0,[`Exception during validation: ${A(e)}`])}}static async fullValidation(e,t,n){const r=Date.now(),i=[];let o=0;try{this.logger.debug("Starting full validation with fresh pool data fetch",{poolKey:e});const s=await n(),a=wo(t.pool.sqrtPrice),c=wo(s.pool.sqrtPrice),l=this.calculateDriftPercentage(a,c);o=Math.max(o,l),l>100*this.DEFAULT_CONFIG.maxPriceDriftPct&&i.push(`Price drift: ${l.toFixed(4)}% (cached: ${a.toString()}, fresh: ${c.toString()})`);const u=wo(t.pool.liquidity),d=wo(s.pool.liquidity),h=this.calculateDriftPercentage(u,d);o=Math.max(o,h),h>100*this.DEFAULT_CONFIG.maxLiquidityDriftPct&&i.push(`Liquidity drift: ${h.toFixed(4)}% (cached: ${u.toString()}, fresh: ${d.toString()})`);const g=Object.keys(t.tickDataMap).length,p=Object.keys(s.tickDataMap).length;if(p>0){const e=Math.abs(p-g)/p;e>this.DEFAULT_CONFIG.maxTickCountDriftPct&&i.push(`Tick data incomplete: cached has ${g} ticks, fresh has ${p} ticks (${(100*e).toFixed(2)}% difference)`)}const f=0===i.length,m=!f,y=Ve(r);return this.logger.debug("Full validation completed",{poolKey:e,isValid:f,shouldRefetch:m,maxDriftPercentage:o,priceDrift:l,liquidityDrift:h,cachedTickCount:g,freshTickCount:p,errorCount:i.length,elapsedMs:y}),this.buildValidationResult(f,o,m,i)}catch(t){return this.logger.error("Full validation exception",{poolKey:e,error:t}),this.buildValidationResult(!1,0,!0,[`Exception during full validation: ${A(t)}`])}}static calculateDriftPercentage(e,t){if(Co(t))return this.logger.warn("Cannot calculate drift: actual value is zero"),1/0;return Lo(t.minus(e).abs(),t).times(100).toNumber()}static buildValidationResult(e,t,n,r=[]){let i;if(n&&r.length>0){const e=r.join(" ").toLowerCase();i=e.includes("drift")?"drift":e.includes("tick")&&e.includes("mismatch")?"tick-mismatch":e.includes("tick")?"missing-tick-data":"manual"}const o={isValid:e,driftPercentage:t,shouldRefetch:n,validationErrors:r};return void 0!==i&&(o.refetchReason=i),o}}nE.logger=new We({debug:!1,context:"PoolStateValidator"}),nE.DEFAULT_CONFIG={maxDriftThreshold:.001,maxLiquidityChangePct:.5,maxTickDrift:1,maxTickCountDriftPct:.1,maxPriceDriftPct:.001,maxLiquidityDriftPct:.01};class rE extends hs{static calculatePoolStateHash(e){const t=`${e.sqrtPrice.toString()}|${e.liquidity.toString()}|${e.tick||0}`;return g.createHash("sha256").update(t).digest("hex").substring(0,16)}constructor(e,t){super(t?.debug??!1);const n={maxIterations:t?.maxIterations??100,enableBigNumberCache:t?.enableBigNumberCache??!0,roundingMode:t?.roundingMode??i.ROUND_DOWN,debug:t?.debug??!1,maxSwapsSinceRefetch:t?.maxSwapsSinceRefetch??50,maxCumulativeDrift:t?.maxCumulativeDrift??5,strictValidation:t?.strictValidation??!1,enablePerformanceWarnings:t?.enablePerformanceWarnings??!0,performanceWarningThreshold:t?.performanceWarningThreshold??100};this.config={...n,...t?.onRefetchNeeded?{onRefetchNeeded:t.onRefetchNeeded}:{}},this.validationConfig=nE.DEFAULT_CONFIG,this.pool=e.pool,this.tickDataMap=e.tickDataMap,this.metadata={lastFullRefetch:Date.now(),swapsSinceRefetch:0,cumulativeDrift:0,processedTransactions:[],stateHash:rE.calculatePoolStateHash(this.pool)};if(!nE.fastValidation(this.pool,this.pool,{transactionId:"init",timestamp:Date.now(),amountSpecified:"0",zeroForOne:!1,exactInput:!0},this.validationConfig)&&this.config.strictValidation)throw new B("Initial pool state validation failed","poolState","VALIDATION_FAILED");this.logger.info("PoolStateManager initialized",{pool:{sqrtPrice:this.pool.sqrtPrice.toString(),liquidity:this.pool.liquidity.toString(),tick:this.pool.tick},config:this.config})}async applySwapDelta(e){if(!e)throw W("swapEvent","Swap event");if(!e.transactionId)throw W("transactionId","Transaction ID");const t=Date.now();if(this.metadata.processedTransactions.includes(e.transactionId))throw this.logger.warn("Duplicate swap transaction",{transactionId:e.transactionId}),new R(`Duplicate transaction ID: ${e.transactionId}`,e.transactionId,"DUPLICATE_TRANSACTION");try{const t={pool:this.pool,tickDataMap:this.tickDataMap},n={maxIterations:this.config.maxIterations,enableBigNumberCache:this.config.enableBigNumberCache,roundingMode:this.config.roundingMode,debugLogging:this.config.debug},r=Ec.calculateSwapDelta(t,e,n);this.lastSwapMetrics={calculationTimeMs:r.metadata.calculationTimeMs,swapSteps:r.metadata.swapSteps,timestamp:Date.now()},this.config.enablePerformanceWarnings&&r.metadata.calculationTimeMs>this.config.performanceWarningThreshold&&this.logger.warn("Slow swap calculation",{calculationTimeMs:r.metadata.calculationTimeMs,swapSteps:r.metadata.swapSteps,threshold:this.config.performanceWarningThreshold});if(!nE.fastValidation(t.pool,r.updatedPool,e,this.validationConfig)&&this.config.strictValidation)throw new B("Swap validation failed","swapResult","VALIDATION_FAILED");if(e.actualAmount0&&e.actualAmount1&&e.actualSqrtPrice){const t=wo(e.actualAmount0),n=wo(e.actualAmount1),i=r.amount0.minus(t).abs(),o=r.amount1.minus(n).abs(),s=Lo(i,t.abs(),wo(0)).times(100).toNumber(),a=Lo(o,n.abs(),wo(0)).times(100).toNumber(),c=Math.max(s,a);c>1&&(this.logger.warn("Drift detected in swap delta",{driftPercentage:c.toFixed(2),swapId:e.transactionId}),this.metadata.cumulativeDrift+=c)}if((this.metadata.swapsSinceRefetch>this.config.maxSwapsSinceRefetch||this.metadata.cumulativeDrift>this.config.maxCumulativeDrift)&&(this.logger.info("Triggering full refetch due to drift accumulation",{swapsSinceRefetch:this.metadata.swapsSinceRefetch,cumulativeDrift:this.metadata.cumulativeDrift.toFixed(2)}),this.config.onRefetchNeeded)){const e=await this.config.onRefetchNeeded(this.pool,this.tickDataMap);this.pool=e.pool,this.tickDataMap=e.tickDataMap,this.metadata.lastFullRefetch=Date.now(),this.metadata.swapsSinceRefetch=0,this.metadata.cumulativeDrift=0,this.metadata.stateHash=rE.calculatePoolStateHash(this.pool),this.logger.info("Full refetch completed",{sqrtPrice:this.pool.sqrtPrice.toString()})}return this.pool=r.updatedPool,Object.assign(this.tickDataMap,r.updatedTicks),this.metadata.swapsSinceRefetch++,this.metadata.stateHash=rE.calculatePoolStateHash(this.pool),this.metadata.processedTransactions.push(e.transactionId),this.metadata.processedTransactions.length>1e3&&(this.metadata.processedTransactions=this.metadata.processedTransactions.slice(-1e3)),this.logger.debug("Swap delta applied",{transactionId:e.transactionId,amount0:r.amount0.toString(),amount1:r.amount1.toString(),sqrtPriceNew:this.pool.sqrtPrice.toString()}),r}catch(n){const r=A(n);if(this.logger.error("Failed to apply swap delta",{transactionId:e.transactionId,error:r}),this.config.strictValidation)throw n;return{updatedPool:this.pool,updatedTicks:{},amount0:wo(0),amount1:wo(0),feeAmount0:wo(0),feeAmount1:wo(0),ticksCrossed:[],metadata:{calculationTimeMs:Ve(t),swapSteps:0,priceHitLimit:!1}}}}forceFullRefetch(e){this.pool=e.pool,this.tickDataMap=e.tickDataMap,this.metadata.lastFullRefetch=Date.now(),this.metadata.swapsSinceRefetch=0,this.metadata.cumulativeDrift=0,this.logger.info("Full refetch forced",{sqrtPrice:this.pool.sqrtPrice.toString()})}getPoolState(){return this.pool}getTickDataMap(){return{...this.tickDataMap}}getMetadata(){return{...this.metadata}}getLastSwapMetrics(){if(this.lastSwapMetrics)return{...this.lastSwapMetrics}}isRefetchRecommended(){return this.metadata.swapsSinceRefetch>this.config.maxSwapsSinceRefetch||this.metadata.cumulativeDrift>this.config.maxCumulativeDrift}reset(e){this.pool=e.pool,this.tickDataMap=e.tickDataMap,this.metadata={lastFullRefetch:Date.now(),swapsSinceRefetch:0,cumulativeDrift:0,processedTransactions:[],stateHash:rE.calculatePoolStateHash(this.pool)},this.logger.info("PoolStateManager reset",{sqrtPrice:this.pool.sqrtPrice.toString()})}}"undefined"!=typeof process&&process.env&&(process.env.CORE_CHAINCODE_LOGGING_LEVEL=process.env.CORE_CHAINCODE_LOGGING_LEVEL||"ERROR");var iE=Object.freeze({__proto__:null,extractMetadataFromPoolData:function(e,t){const n={};if(e.vaultAddress&&(n.vaultAddress=e.vaultAddress),void 0!==e.reverseBondingCurveMinFeePortion){const r=De(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=De(e.reverseBondingCurveMaxFeePortion,NaN);isNaN(r)?t&&t.debug(`Skipping invalid reverseBondingCurveMaxFeePortion for ${e.tokenName}: "${e.reverseBondingCurveMaxFeePortion}"`):n.reverseBondingCurveMaxFeeFactor=r}return void 0!==n.reverseBondingCurveMaxFeeFactor&&void 0!==n.reverseBondingCurveMinFeeFactor&&(n.reverseBondingCurveNetFeeFactor=n.reverseBondingCurveMaxFeeFactor-n.reverseBondingCurveMinFeeFactor),Object.keys(n).length>0?n:null},isValidPoolForCaching:function(e){if(null===e||"object"!=typeof e)return!1;const t=e;return"tokenName"in t&&"string"==typeof t.tokenName&&t.tokenName.length>0}});exports.ACCESS_SOURCE=Bl,exports.ACTIVE_USER_TYPE=jl,exports.API_KEY_PERMISSION={MANAGE_COMMENTS:"MANAGE_COMMENTS",MANAGE_CHAT:"MANAGE_CHAT",BAN_USERS:"BAN_USERS",UNBAN_USERS:"UNBAN_USERS",MANAGE_SIMULCAST:"MANAGE_SIMULCAST",GET_STREAM_KEY:"GET_STREAM_KEY",STOP_STREAM:"STOP_STREAM",RESET_STREAM_KEY:"RESET_STREAM_KEY",START_STREAM:"START_STREAM",DELETE_RECORDINGS:"DELETE_RECORDINGS",MANAGE_STREAM_SETTINGS:"MANAGE_STREAM_SETTINGS"},exports.API_KEY_ROLE=cu,exports.API_KEY_ROLES=lu,exports.API_KEY_ROLE_HIERARCHY=pu,exports.AddressFormatter=ut,exports.AgentConfig=class{static async quickSetup(e={}){const t=e.environment||this.detectEnvironment(),n=this.setupWallet(e.privateKey),r=e.galaChainAddress||process.env.WALLET_ADDRESS,i={wallet:n.wallet,baseUrl:e.baseUrl||this.getDefaultBaseUrl(t),timeout:e.timeout||this.getDefaultTimeout(t),debug:e.debug??"production"!==t,...this.getEnvironmentDefaults(t),...e.config||{},...r?{galaChainAddress:r}:{}},o=new JT(i),s={sdk:o,wallet:n,config:i};if(!1!==e.autoValidate){const e=await this.validateSetup(o,n);return{...s,validation:e}}return s}static async readOnlySetup(e={}){const t=e.environment||this.detectEnvironment(),n=e.galaChainAddress||process.env.WALLET_ADDRESS,r={wallet:void 0,baseUrl:e.baseUrl||this.getDefaultBaseUrl(t),timeout:e.timeout||this.getDefaultTimeout(t),debug:e.debug??"production"!==t,...this.getEnvironmentDefaults(t),...e.config||{},...n?{galaChainAddress:n}:{}};return{sdk:new JT(r),config:r}}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,t&&t.quantity){const e=De(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: ${A(e)}`)}try{const t=await e.fetchPools({type:"recent",page:1,limit:1});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: ${A(e)}`)}return{ready:0===n.length&&i.connectionHealthy,sdk:e,wallet:t||ZT.generateWallet(),issues:n,warnings:r,capabilities:i}}static getRecommendedConfig(e,t="general"){const n={environment:e,autoValidate:!0};switch(e){case"production":Object.assign(n,{debug:!1,timeout:3e4});break;case"development":Object.assign(n,{debug:!0,timeout:45e3});break;case"testing":Object.assign(n,{debug:!0,timeout:6e4})}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)}return n}static async multiWalletSetup(e,t="development"){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(){const e=process.env.NODE_ENV?.toLowerCase();return"development"===e?"development":"test"===e||"testing"===e?"testing":"production"}static setupWallet(e){if(!e){const e=process.env.PRIVATE_KEY;return e?ZT.fromPrivateKey(e):ZT.generateWallet()}return"generate"===e?ZT.generateWallet():ZT.fromPrivateKey(e)}static getDefaultBaseUrl(e){return"production"===e?"https://lpad-backend-prod1.defi.gala.com":"https://lpad-backend-dev1.defi.gala.com"}static getDefaultTimeout(e){switch(e){case"production":default:return 3e4;case"development":return 45e3;case"testing":return 6e4}}static getEnvironmentDefaults(e){const t={};if("production"===e)t.bundleBaseUrl="https://bundle-backend-prod1.defi.gala.com",t.galaChainBaseUrl="https://galachain-gateway-chain-platform-prod-chain-platform-eks.prod.galachain.com";else t.bundleBaseUrl="https://bundle-backend-dev1.defi.gala.com",t.galaChainBaseUrl="https://galachain-gateway-chain-platform-stage-chain-platform-eks.stage.galachain.com";return t}},exports.AuthError=v,exports.BAN_DURATIONS={ONE_HOUR:3600,ONE_DAY:86400,ONE_WEEK:604800,ONE_MONTH:2592e3},exports.BRIDGE_CONTRACT_ABI=cl,exports.BRIDGE_TOKEN_METADATA=sl,exports.BaseBridgeStrategy=TT,exports.BridgeRateLimiter=Pd,exports.BurnError=Ba,exports.CALCULATION_MODES=Nd,exports.CHAIN_IDS=Xc,exports.COMPOSITE_POOL_FETCH_CONCURRENCY=5,exports.CONTENT_REACTION_TYPES=od,exports.CONTENT_TYPE_LABELS=Ou,exports.CROSS_RATE_TYPED_DATA_TYPES=ml,exports.ChatMessagesService=hd,exports.ConfigurationError=D,exports.DEFAULT_ETHEREUM_BRIDGE_CONTRACT=Jc,exports.DEFAULT_ETHEREUM_RPC_URL="https://ethereum.publicnode.com",exports.DEFAULT_ETHEREUM_TOKENS=il,exports.DEFAULT_POLL_INTERVAL_MS=15e3,exports.DEFAULT_POLL_TIMEOUT_MS=27e5,exports.DEFAULT_PRICING_CONCURRENCY=5,exports.DEFAULT_RATE_LIMIT_RPS=12,exports.DEFAULT_SOLANA_BRIDGE_PROGRAM="AaE4dTnL75XqgUJpdxBKg6vS9sTJgBPJwBQRVhD29WwS",exports.DEFAULT_SOLANA_RPC_URL="https://api.mainnet-beta.solana.com",exports.DEFAULT_SOLANA_TOKENS=ol,exports.DEFAULT_WEBSOCKET_RECONNECT_ATTEMPTS=5,exports.DexPoolNotFoundError=q,exports.DexQuoteError=$,exports.ERC20_ABI=al,exports.ERROR_CODES=_,exports.ETHEREUM_BRIDGE_CONTRACT_SEPOLIA=Zc,exports.ETHEREUM_TOKENS_PROD=el,exports.ETHEREUM_TOKENS_STAGE=tl,exports.EXTENDED_STREAM_ROLE=_l,exports.EthereumBridgeStrategy=ET,exports.EventBufferWithAutoCleanup=class{constructor(e={},t){this.events=[],this.timeouts=new Map,this.maxSize=e.maxSize??100,this.defaultTtlMs=e.defaultTtlMs??3e4,this.logger=t}push(e){if(this.events.length>=this.maxSize){const e=0;this.events.shift();const t=this.timeouts.get(e);t&&(clearTimeout(t),this.timeouts.delete(e)),this.logger?.warn(`Buffer full (${this.maxSize}), dropped oldest event`)}this.events.push(e);const t=this.events.length-1,n=setTimeout(()=>{this.events[t]===e&&this.events.splice(t,1),this.timeouts.delete(t)},this.defaultTtlMs);this.timeouts.set(t,n)}getAll(){return[...this.events]}clear(){for(const e of this.timeouts.values())clearTimeout(e);this.events=[],this.timeouts.clear()}get size(){return this.events.length}},exports.FLAG_ACTION_LABELS=Lu,exports.FLAG_DETAILS_MAX_LENGTH=500,exports.FLAG_REASON_LABELS=Ru,exports.FLAG_STATUS_LABELS=Mu,exports.FileValidationError=Rs,exports.GALACHAIN_CHANNELS=Qc,exports.GALACONNECT_PRODUCTION_URL=Yc,exports.GALA_BRIDGE_TYPED_DATA_DOMAIN=ul,exports.GALA_DECIMALS=8,exports.GALA_TOKEN_CLASS_KEY={collection:"GALA",category:"Unit",type:"none",additionalKey:"none"},exports.GSwapAssetError=F,exports.GSwapAssetService=class extends hs{constructor(e){super(e.debugMode||!1),this.dexBackendBaseUrl=e.dexBackendBaseUrl,e.dexBackendHttp?this.dexBackendHttp=e.dexBackendHttp:this.dexBackendHttp=b(e.dexBackendBaseUrl,3e4)}parseTokenFlexible(e){try{return Hs(e)}catch{return{collection:e,category:"Unit",type:"none",additionalKey:"none"}}}transformRawTokenToDexToken(e){return{image:e.image||"",name:e.name||"",symbol:e.symbol||"",decimals:e.decimals||8,description:e.description||"",verified:e.verified||!1,compositeKey:e.compositeKey||"",additionalKey:e.additionalKey||"none",category:e.category||"Unit",type:e.type||"none",collection:e.collection||e.symbol||"",subscribePrice:e.subscribePrice||!1}}transformRawTokenToUserAsset(e){const t=this.transformRawTokenToDexToken(e);let n;try{n=e.compositeKey?this.parseTokenFlexible(e.compositeKey):{collection:e.collection||e.symbol||"",category:e.category||"Unit",type:e.type||"none",additionalKey:e.additionalKey||"none"}}catch{n={collection:e.symbol||"",category:"Unit",type:"none",additionalKey:"none"}}return{...t,tokenId:n,balance:e.balance||"0"}}async getUserAssets(e,t=20,n=1){try{this.logger.debug("Fetching user assets",{walletAddress:e,limit:t,page:n});const r=mr(await this.dexBackendHttp.get("/api/tokens/balances",{params:{wallet:e,limit:t,page:n}})),i=r?.data||r||{},o=i.tokens||[],s=i.count||o.length;return{assets:o.map(e=>this.transformRawTokenToUserAsset(e)),count:s,page:n,limit:t,hasMore:n*t<s}}catch(t){throw this.logger.error("Failed to fetch user assets",t),new F(`Failed to fetch user assets: ${A(t)}`,t,e)}}async getAllUserAssets(e){try{this.logger.debug("Fetching all user assets",{walletAddress:e});return(await Yo(async(t,n)=>{const r=await this.getUserAssets(e,n,t);return{items:r.assets,page:t,limit:n,total:r.count,totalPages:Xo(r.count,n),hasNext:r.hasMore,hasPrevious:t>1}},{maxPages:100,pageSize:100,logger:this.logger})).items}catch(t){throw this.logger.error("Failed to fetch all user assets",t),new F(`Failed to fetch all user assets: ${A(t)}`,t,e)}}async fetchAvailableDexTokens(e={}){try{const{search:t,limit:n=20,page:r=1}=e;this.logger.debug("Fetching available DEX tokens",{search:t,limit:n,page:r});const i={limit:n,page:r};t&&(i.search=t);const o=mr(await this.dexBackendHttp.get("/api/tokens",{params:i})),s=o?.data||o||{},a=s.tokens||[],c=s.count||a.length;return{tokens:a.map(e=>this.transformRawTokenToDexToken(e)),count:c,page:r,limit:n,hasMore:r*n<c}}catch(e){throw this.logger.error("Failed to fetch available DEX tokens",e),new F(`Failed to fetch available DEX tokens: ${A(e)}`,e)}}async fetchAllAvailableDexTokens(e={}){try{this.logger.debug("Fetching all available DEX tokens",e);return(await Yo(async(t,n)=>{const r=await this.fetchAvailableDexTokens({...e,limit:n,page:t});return{items:r.tokens,page:t,limit:n,total:r.count,totalPages:Xo(r.count,n),hasNext:r.hasMore,hasPrevious:t>1}},{maxPages:100,pageSize:100,logger:this.logger})).items}catch(e){throw this.logger.error("Failed to fetch all available DEX tokens",e),new F(`Failed to fetch all available DEX tokens: ${A(e)}`,e)}}},exports.GSwapLiquidityMutationService=class extends hs{constructor(e){super(e.debugMode||!1),this.bundlerClient=null,this.privateKey=e.privateKey,this.getWalletAddress=e.getWalletAddress,this.gatewayClient=e.gatewayClient,this.bundlerBaseUrl=e.bundlerBaseUrl,this.galaChainBaseUrl=e.galaChainBaseUrl,this.webSocketService=e.webSocketService,this.calculationService=e.calculationService,this.liquidityQueryService=e.liquidityQueryService,this.tokenConverter=new aa,e.bundlerBaseUrl&&(this.bundlerClient=dc.createClient(e.bundlerBaseUrl,3e4))}getBundlerClient(){if(!this.bundlerBaseUrl)throw new D("Bundler URL not configured","bundlerBaseUrl");return this.bundlerClient||(this.bundlerClient=dc.createClient(this.bundlerBaseUrl,3e4)),this.bundlerClient}convertTokenPair(e,t){return{gswapToken0:this.tokenConverter.toLaunchpadFormat(e),gswapToken1:this.tokenConverter.toLaunchpadFormat(t)}}calculatePersonalSignPrefix(e){return`Ethereum Signed Message:\n${JSON.stringify(e).length}${JSON.stringify(e)}`}async ensureWebSocketConnected(){this.webSocketService.isConnected()||await this.webSocketService.connect()}buildLiquidityStringsInstructions(e,t,n,r){const i=Ws(e),o=Ws(t),s=`$pool${i}${o}$${n}`;return[s,`$userPosition${r}`,`$tokenBalance${i}${r}`,`$tokenBalance${o}${r}`,`$tokenBalance${i}${s}`,`$tokenBalance${o}${s}`]}async monitorBundlerTransaction(e,t,n){return{...{transactionId:e,liquidity:"0",amount0:"0",amount1:"0",status:"pending"},wait:async(r=12e4)=>wr(async()=>{const i=new Promise((t,n)=>{setTimeout(()=>n(new Error(`Transaction ${e} timed out after ${r}ms`)),r)});await Promise.race([t,i]),this.logger.debug(`${n} confirmed`,{transactionId:e})},`${n} failed or timed out`,this.logger,(t,r,i)=>{throw i?.error(`GSwapLiquidityMutationService: ${r}`,{error:A(t),operationType:n,transactionId:e}),t})}}async sendAddLiquidityToBundler(t){if(!this.privateKey)throw new D("AddLiquidity requires wallet (full-access mode)","privateKey");if(!this.bundlerBaseUrl)throw new D("Bundler URL not configured","bundlerBaseUrl");return wr(async()=>{const n=`galaswap - operation - ${o.v4()}-${Date.now()}-${t.owner}`,r={token0:t.token0,token1:t.token1,fee:t.fee,owner:t.owner,tickLower:t.tickLower,tickUpper:t.tickUpper,amount0Desired:t.amount0Desired,amount1Desired:t.amount1Desired,amount0Min:t.amount0Min,amount1Min:t.amount1Min,positionId:"",uniqueKey:n},i=new e.ethers.Wallet(this.privateKey),s={AddLiquidity:[{name:"token0",type:"token0"},{name:"token1",type:"token1"},{name:"fee",type:"int256"},{name:"owner",type:"string"},{name:"tickLower",type:"int256"},{name:"tickUpper",type:"int256"},{name:"amount0Desired",type:"string"},{name:"amount1Desired",type:"string"},{name:"amount0Min",type:"string"},{name:"amount1Min",type:"string"},{name:"positionId",type:"string"},{name:"uniqueKey",type:"string"}],token0:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}],token1:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}]},a={name:"ethereum",chainId:1},c=this.calculatePersonalSignPrefix(r),l={...r,prefix:c},u=await i.signTypedData(a,s,l),d={...l,signature:u,types:s,domain:a},h=this.buildLiquidityStringsInstructions(t.token0,t.token1,t.fee,t.owner),g=mr(await this.getBundlerClient().post("/bundle",{method:"AddLiquidity",signedDto:d,stringsInstructions:h})),p="string"==typeof g?.data?g.data:g?.data?.transactionId||g?.data?.id||g?.transactionId||g?.id;if(!p)throw new R("Bundler response does not contain transaction ID",void 0,"INVALID_RESPONSE");return p},"Failed to send AddLiquidity to bundler",this.logger)}async sendRemoveLiquidityToBundler(t,n,r,i,s,a,c,l,u){if(!this.privateKey)throw new D("RemoveLiquidity requires wallet (full-access mode)","privateKey");return wr(async()=>{const d=new e.ethers.Wallet(this.privateKey),h=await d.getAddress(),g=`galaswap - operation - ${o.v4()}-${Date.now()}-${h}`,p={tickLower:t,tickUpper:n,amount:r,token0:i,token1:s,fee:a,amount0Min:c,amount1Min:l,positionId:u,uniqueKey:g},f={RemoveLiquidity:[{name:"tickLower",type:"int256"},{name:"tickUpper",type:"int256"},{name:"amount",type:"string"},{name:"token0",type:"token0"},{name:"token1",type:"token1"},{name:"fee",type:"int256"},{name:"amount0Min",type:"string"},{name:"amount1Min",type:"string"},{name:"positionId",type:"string"},{name:"uniqueKey",type:"string"}],token0:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}],token1:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}]},m={name:"ethereum",chainId:1},y=this.calculatePersonalSignPrefix(p),w={...p,prefix:y},k=await d.signTypedData(m,f,w),b={...w,signature:k,types:f,domain:m},v=this.buildLiquidityStringsInstructions(i,s,a,h),S=mr(await this.getBundlerClient().post("/bundle",{method:"RemoveLiquidity",signedDto:b,stringsInstructions:v})),A="string"==typeof S?.data?S.data:S?.data?.transactionId||S?.data?.id||S?.transactionId||S?.id;if(!A)throw new R("Bundler response does not contain transaction ID",void 0,"INVALID_RESPONSE");return A},"Failed to send RemoveLiquidity to bundler",this.logger)}async sendCollectPositionFeesToBundler(t,n,r,i,s,a,c,l){if(!this.privateKey)throw new D("CollectPositionFees requires wallet (full-access mode)","privateKey");return wr(async()=>{const u=new e.ethers.Wallet(this.privateKey),d=await u.getAddress(),h=`galaswap - operation - ${o.v4()}-${Date.now()}-${d}`,g={token0:t,token1:n,fee:r,amount0Requested:i,amount1Requested:s,tickLower:a,tickUpper:c,positionId:l,uniqueKey:h},p={CollectPositionFees:[{name:"token0",type:"token0"},{name:"token1",type:"token1"},{name:"fee",type:"int256"},{name:"amount0Requested",type:"string"},{name:"amount1Requested",type:"string"},{name:"tickLower",type:"int256"},{name:"tickUpper",type:"int256"},{name:"positionId",type:"string"},{name:"uniqueKey",type:"string"}],token0:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}],token1:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}]},f={name:"ethereum",chainId:1},m=this.calculatePersonalSignPrefix(g),y={...g,prefix:m},w=await u.signTypedData(f,p,y),k={...y,signature:w,types:p,domain:f},b=this.buildLiquidityStringsInstructions(t,n,r,d),v=mr(await this.getBundlerClient().post("/bundle",{method:"CollectPositionFees",signedDto:k,stringsInstructions:b})),S="string"==typeof v?.data?v.data:v?.data?.transactionId||v?.data?.id||v?.transactionId||v?.id;if(!S)throw new R("Bundler response does not contain transaction ID",void 0,"INVALID_RESPONSE");return S},"Failed to send CollectPositionFees to bundler",this.logger)}async addLiquidityByPrice(e){if(!this.privateKey)throw new D("AddLiquidity requires wallet (full-access mode)","privateKey");if(!e.token0)throw W("token0","Token 0");if(!e.token1)throw W("token1","Token 1");if(!e.minPrice)throw W("minPrice","Minimum price");if(!e.maxPrice)throw W("maxPrice","Maximum price");if(!e.amount0Desired)throw W("amount0Desired","Desired amount 0");if(!e.amount1Desired)throw W("amount1Desired","Desired amount 1");return wr(async()=>{this.logger.debug("Adding liquidity by price",{token0:e.token0,token1:e.token1,priceRange:`${e.minPrice}-${e.maxPrice}`});const{gswapToken0:t,gswapToken1:n}=this.convertTokenPair(e.token0,e.token1);await this.ensureWebSocketConnected();const r=Hs(t),i=Hs(n),o=(await this.gatewayClient.getPoolData({token0:r,token1:i,fee:e.fee})).tickSpacing,s=wo(e.minPrice),a=wo(e.maxPrice),c=Math.floor(Ao(s)),l=Math.ceil(Ao(a)),u=Oo(c,o),d=Oo(l,o),h=this.getWalletAddress();if(!h)throw new D("Wallet address not available","walletAddress");const g=await this.sendAddLiquidityToBundler({token0:r,token1:i,fee:e.fee,tickLower:u,tickUpper:d,amount0Desired:e.amount0Desired,amount1Desired:e.amount1Desired,amount0Min:e.amount0Min||"0",amount1Min:e.amount1Min||"0",owner:h}),p=this.webSocketService.waitForTransaction(g);return this.monitorBundlerTransaction(g,p,"addLiquidityByPrice")},"Failed to add liquidity by price",this.logger,(e,t,n)=>{throw n?.error(t,{error:A(e)}),new U(`${t}: ${A(e)}`,e,"ADD_FAILED")})}async addSwapLiquidityByTicks(e){if(!this.privateKey)throw new D("AddLiquidity requires wallet (full-access mode)","privateKey");if(!e.token0)throw W("token0","Token 0");if(!e.token1)throw W("token1","Token 1");if(!e.amount0Desired)throw W("amount0Desired","Desired amount 0");if(!e.amount1Desired)throw W("amount1Desired","Desired amount 1");return wr(async()=>{this.logger.debug("Adding liquidity by ticks",{token0:e.token0,token1:e.token1,tickRange:`${e.tickLower}-${e.tickUpper}`}),this.calculationService.validateTickSpacing(e.tickLower,e.tickUpper,e.feeTier);const{gswapToken0:t,gswapToken1:n}=this.convertTokenPair(e.token0,e.token1);await this.ensureWebSocketConnected();const r=Hs(t),i=Hs(n),o=this.getWalletAddress();if(!o)throw new D("Wallet address not available","walletAddress");const s=await this.sendAddLiquidityToBundler({token0:r,token1:i,fee:e.feeTier,tickLower:e.tickLower,tickUpper:e.tickUpper,amount0Desired:e.amount0Desired,amount1Desired:e.amount1Desired,amount0Min:e.amount0Min||"0",amount1Min:e.amount1Min||"0",owner:o}),a=this.webSocketService.waitForTransaction(s);return this.monitorBundlerTransaction(s,a,"addSwapLiquidityByTicks")},"Failed to add liquidity by ticks",this.logger,(e,t,n)=>{throw n?.error(t,{error:A(e)}),new U(`${t}: ${A(e)}`,e,"ADD_FAILED")})}async removeLiquidity(e){if(!this.privateKey)throw new D("RemoveLiquidity requires wallet (full-access mode)","privateKey");if(!e.token0)throw W("token0","Token 0");if(!e.token1)throw W("token1","Token 1");if(!e.liquidity)throw W("liquidity","Liquidity amount");return wr(async()=>{this.logger.debug("Removing liquidity via bundler",{token0:e.token0,token1:e.token1,liquidity:e.liquidity});const t=wo(e.liquidity);try{Ro(t)}catch(t){const n=`Invalid liquidity value: "${e.liquidity}". Must be a valid number.`;throw this.logger.error(n,{error:A(t)}),new B(n,"liquidity","INVALID_VALUE")}if(Co(t))throw new B("Cannot remove zero liquidity from position.","liquidity","ZERO_VALUE");const n="string"==typeof e.token0?Hs(e.token0):e.token0,r="string"==typeof e.token1?Hs(e.token1):e.token1;await this.ensureWebSocketConnected();const i=await this.sendRemoveLiquidityToBundler(e.tickLower,e.tickUpper,e.liquidity,n,r,e.fee,e.amount0Min||"0",e.amount1Min||"0",e.positionId||""),o=this.webSocketService.waitForTransaction(i);return this.monitorBundlerTransaction(i,o,"removeLiquidity")},"Failed to remove liquidity",this.logger,(e,t,n)=>{throw n?.error(t,{error:A(e)}),new U(`${t}: ${A(e)}`,e,"REMOVE_FAILED")})}async collectPositionFees(e){if(!this.privateKey)throw new D("CollectPositionFees requires wallet (full-access mode)","privateKey");if(!e.positionId)throw W("positionId","Position ID");return wr(async()=>{if(e.ownerAddress&&e.positionId&&!e.token0)throw new B("collectPositionFees requires direct parameters: token0, token1, fee, tickLower, tickUpper. Use GSwapService.collectPositionFees() for automatic position lookup.","parameters",_.REQUIRED);if(!e.token0||!e.token1||void 0===e.fee||void 0===e.tickLower||void 0===e.tickUpper)throw new B("Missing required parameters: token0, token1, fee, tickLower, tickUpper are required","parameters",_.REQUIRED);this.logger.debug("Collecting position fees via bundler",{token0:"string"==typeof e.token0?e.token0:e.token0?.type??"unknown",token1:"string"==typeof e.token1?e.token1:e.token1?.type??"unknown",tickLower:e.tickLower,tickUpper:e.tickUpper});const t="string"==typeof e.token0?Hs(e.token0):e.token0,n="string"==typeof e.token1?Hs(e.token1):e.token1;await this.ensureWebSocketConnected();const r=await this.sendCollectPositionFeesToBundler(t,n,e.fee,e.amount0Requested||"0",e.amount1Requested||"0",e.tickLower,e.tickUpper,e.positionId||""),i=this.webSocketService.waitForTransaction(r);return this.monitorBundlerTransaction(r,i,"collectPositionFees")},"Failed to collect position fees",this.logger,(e,t,n)=>{throw n?.error(t,{error:A(e)}),new U(`${t}: ${A(e)}`,e,"COLLECT_FAILED")})}},exports.GSwapLiquidityQueryService=class extends hs{constructor(e){super(e.debugMode||!1),this.gatewayClient=e.gatewayClient,this.galaChainBaseUrl=e.galaChainBaseUrl,this.calculationService=e.calculationService,this.tokenConverter=new aa}convertTokenPair(e,t){return{gswapToken0:this.tokenConverter.toLaunchpadFormat(e),gswapToken1:this.tokenConverter.toLaunchpadFormat(t)}}parseTokenFlexible(e){try{return Hs(e)}catch{return{collection:e,category:"Unit",type:"none",additionalKey:"none"}}}extractTokenSymbol(e){return e?"string"==typeof e?e:"object"==typeof e&&(e.type||e.collection||e.symbol||e.tokenSymbol||e.name)||"":""}normalizePositionResponse(e,t){const n=e;let r=n;n.positions&&Array.isArray(n.positions)&&n.positions.length>0&&(r=n.positions[0]);const i=r.positionId||r.id||n.positionId||n.id||"",o=this.extractTokenSymbol(r.token0||r.tokenA),s=this.extractTokenSymbol(r.token1||r.tokenB),a=r.feeTier??r.fee??r.feeAmount??3e3,c=r.tickLower??r.lowerTick??0,l=r.tickUpper??r.upperTick??0,u=r.liquidity?.toString()||r.liquidityAmount?.toString()||"0",d=r.amount0?.toString()||r.amountA?.toString()||"0",h=r.amount1?.toString()||r.amountB?.toString()||"0",g=r.feeAmount0?.toString()||r.feesA?.toString()||r.tokensOwed0?.toString()||"0",p=r.feeAmount1?.toString()||r.feesB?.toString()||r.tokensOwed1?.toString()||"0";return{positionId:i,ownerAddress:t,token0:o,token1:s,feeTier:Le(a,3e3),tickLower:Le(c,0),tickUpper:Le(l,0),liquidity:u,amount0:d,amount1:h,feeAmount0:g,feeAmount1:p}}async getLiquidityPosition(e,t){try{this.logger.debug("Fetching liquidity position",{ownerAddress:e,position:t}),this.calculationService.validateTickSpacing(t.tickLower,t.tickUpper,t.fee);const{gswapToken0:n,gswapToken1:r}=this.convertTokenPair(t.token0,t.token1),i=hc(n),o=hc(r),s=(await this.gatewayClient.getPositions({owner:e,token0:i,token1:o,fee:t.fee,tickLower:t.tickLower,tickUpper:t.tickUpper})).positions.find(e=>e.tickLower===t.tickLower&&e.tickUpper===t.tickUpper);if(!s||"object"!=typeof s||!("positionId"in s)&&!("id"in s))throw new U("Invalid position data returned from API",null,"INVALID_DATA");return this.normalizePositionResponse(s,e)}catch(e){throw this.logger.error("Failed to fetch liquidity position",{error:A(e)}),new U(`Failed to fetch liquidity position: ${A(e)}`,e,"FETCH_FAILED")}}async fetchSwapPositionDirect(e){try{this.logger.debug("Fetching swap position via direct compound key",{token0:e.token0,token1:e.token1,fee:e.fee,owner:e.owner});const t=this.parseTokenFlexible(e.token0),n=this.parseTokenFlexible(e.token1),r=await this.gatewayClient.getPositions({token0:t,token1:n,fee:e.fee,tickLower:e.tickLower,tickUpper:e.tickUpper,owner:e.owner});if(!r.positions||0===r.positions.length)throw new U("Position not found: API returned no position data",null,"NOT_FOUND");const i=r.positions[0];return this.normalizePositionResponse(i,e.owner)}catch(e){throw this.logger.error("Failed to fetch swap position via compound key",{error:A(e)}),new U(`Failed to fetch swap position: ${A(e)}`,e,"FETCH_FAILED")}}async estimateRemoveLiquidity(e){try{this.logger.debug("Estimating liquidity removal",{token0:e.token0,token1:e.token1,owner:e.owner}),this.calculationService.validateTickSpacing(e.tickLower,e.tickUpper,e.fee);const{gswapToken0:t,gswapToken1:n}=this.convertTokenPair(e.token0,e.token1),r=hc(t),i=hc(n);return await this.gatewayClient.getRemoveLiquidityEstimation({token0:r,token1:i,fee:e.fee,amount:e.liquidity,tickLower:e.tickLower,tickUpper:e.tickUpper,owner:e.owner})}catch(e){throw this.logger.error("Failed to estimate liquidity removal",{error:A(e)}),new U(`Failed to estimate liquidity removal: ${A(e)}`,e,"ESTIMATE_FAILED")}}},exports.GSwapPoolCalculationService=class{constructor(e){this.logger=e?.logger}getTickSpacing(e){switch(e){case 500:return 10;case 3e3:return 60;case 1e4:return 200;default:throw new B(`Invalid fee tier: ${e}. Valid values are 500, 3000, or 10000.`,"feeTier",_.INVALID_FEE_TIER)}}validateTickSpacing(e,t,n){const r=this.getTickSpacing(n);if(e%r!==0)throw new B(`Invalid tickLower: ${e} must be a multiple of ${r} for fee tier ${n}. Tip: Use getAllSwapUserLiquidityPositions() to discover valid positions with correct tick spacing.`,"tickLower","INVALID_TICK_SPACING");if(t%r!==0)throw new B(`Invalid tickUpper: ${t} must be a multiple of ${r} for fee tier ${n}. Tip: Use getAllSwapUserLiquidityPositions() to discover valid positions with correct tick spacing.`,"tickUpper","INVALID_TICK_SPACING")}calculatePriceFromSqrtPriceX96(e){return kr(()=>{const t=Eo();return Lo(e,t).pow(2)},"calculatePriceFromSqrtPriceX96 failed",this.logger)}calculatePriceFromSqrtPriceDecimal(e){return kr(()=>e.pow(2),"calculatePriceFromSqrtPriceDecimal failed",this.logger)}calculateLiquidityFromAmount0(e,t,n){return kr(()=>{const r=c.tickToSqrtPrice(t),i=c.tickToSqrtPrice(n);return c.liquidity0(e,r,i)},"calculateLiquidityFromAmount0 failed",this.logger)}calculateLiquidityFromAmount1(e,t,n){return kr(()=>{const r=c.tickToSqrtPrice(t),i=c.tickToSqrtPrice(n);return c.liquidity1(e,r,i)},"calculateLiquidityFromAmount1 failed",this.logger)}calculateAmount0FromLiquidity(e,t,n){return kr(()=>{const r=c.tickToSqrtPrice(t),i=c.tickToSqrtPrice(n);return c.getAmount0Delta(r,i,e)},"calculateAmount0FromLiquidity failed",this.logger)}calculateAmount1FromLiquidity(e,t,n){return kr(()=>{const r=c.tickToSqrtPrice(t),i=c.tickToSqrtPrice(n);return c.getAmount1Delta(r,i,e)},"calculateAmount1FromLiquidity failed",this.logger)}calculateOptimalPositionSize(e,t,n,r,i){if(!t)throw W("desiredAmount0","Desired amount 0");if(!n)throw W("desiredAmount1","Desired amount 1");const o=c.tickToSqrtPrice(r),s=c.tickToSqrtPrice(e),a=c.tickToSqrtPrice(i),l=c.getLiquidityForAmounts(wo(t),wo(n),o,s,a),u=c.getAmountsForLiquidity(l,s,o,a),d=u[0],h=u[1],g=wo(t),p=wo(n);Co(wo(h))&&this.logger?.warn("GSwapPoolCalculationService: Calculated amount1 is zero - position may be heavily skewed to amount0",{desiredAmount0:t,desiredAmount1:n,currentTick:r,tickUpper:i});const f=Lo(d,h,wo(0));return{amount0:ko(d),amount1:ko(h),liquidity:ko(l),ratio:ko(f),utilizationPercent:{amount0:ko(Po(Lo(d,g),100),2),amount1:ko(Po(Lo(h,p),100),2)}}}validatePositionParameters(e,t,n,r,i,o,s){if(!r)throw W("amount0","Amount 0");if(!i)throw W("amount1","Amount 1");const a=[],c=[],l=[500,3e3,1e4];let u;l.includes(e)||a.push(`Invalid fee tier: ${e}. Must be one of: ${l.join(", ")}`);try{u=kr(()=>this.getTickSpacing(e),"validatePositionParameters tick spacing lookup",this.logger),void 0!==u&&(t%u!==0&&a.push(`tickLower must be multiple of ${u}`),n%u!==0&&a.push(`tickUpper must be multiple of ${u}`))}catch{}t>=n&&a.push(`tickLower (${t}) must be less than tickUpper (${n})`);const d=wo(r),h=wo(i);if(d.isNaN()||h.isNaN())a.push("Amounts must be valid numbers");else try{kr(()=>Ro(d,h),"validatePositionParameters amounts validation",this.logger)}catch(e){a.push(`Liquidity amounts must be non-negative: ${e.message}`)}if(void 0!==o&&(o<t||o>n)&&c.push("Position is out of current price range - will not earn fees until price moves into range"),void 0!==s){wo(s).lt("1000000")&&c.push("Low pool liquidity - consider higher slippage tolerance")}const g=0===a.length?35e4:0,p={valid:0===a.length,errors:a,warnings:c,gasEstimate:g};return void 0!==u&&(p.tickSpacing=u),void 0!==o&&(p.currentTick=o),void 0!==s&&(p.poolLiquidity=s),p}calculateTicksForPrice(e,t,n){if(!e)throw W("minPrice","Minimum price");if(!t)throw W("maxPrice","Maximum price");const r=this.getTickSpacing(n),i=wo(e),o=wo(t);ce(e,t,"priceRange");const s=Re(Math.floor(Ao(i)),0),a=Re(Math.ceil(Ao(o)),0),c=Re(Oo(s,r),0),l=Re(Oo(a,r),0),u=Re(Math.pow(1.0001,c),0===c?1:NaN),d=Re(Math.pow(1.0001,l),0===l?1:NaN),h=wo(u),g=wo(d);return{tickLower:c,tickUpper:l,tickSpacing:r,requestedMinPrice:e,requestedMaxPrice:t,actualMinPrice:h.toFixed(8),actualMaxPrice:g.toFixed(8),priceDeviation:{minPriceDeviation:Po(Lo(h.minus(i),i),100).toFixed(4),maxPriceDeviation:Po(Lo(g.minus(o),o),100).toFixed(4)}}}calculatePriceForTicks(e,t){const n=Re(Math.pow(1.0001,e),1),r=Re(Math.pow(1.0001,t),1),i=wo(n),o=wo(r);return{tickLower:e,tickUpper:t,minPrice:i.toFixed(8),maxPrice:o.toFixed(8),priceRange:`${i.toFixed(4)} - ${o.toFixed(4)}`,tickSpread:Re(t-e,0)}}calculateExecutionPrice(e,t){if(!e)throw W("inputAmount","Input amount");if(!t)throw W("outputAmount","Output amount");return kr(()=>{const n=wo(e);return ko(Lo(wo(t),n,wo("0")))},"calculateExecutionPrice failed",this.logger)}},exports.GSwapPoolError=O,exports.GSwapPoolQueryService=class extends hs{constructor(e){super(e.debugMode||!1),this.gatewayClient=e.gatewayClient,this.galaChainBaseUrl=e.galaChainBaseUrl,this.calculationService=e.calculationService,this.tokenConverter=new aa}convertTokenPair(e,t){return{gswapToken0:this.tokenConverter.toLaunchpadFormat(e),gswapToken1:this.tokenConverter.toLaunchpadFormat(t)}}async getPoolData(e,t,n){try{this.logger.debug("Getting pool data",{tokenA:e,tokenB:t,feeTier:n});const{gswapToken0:r,gswapToken1:i}=this.convertTokenPair(e,t),o=Hs(r),s=Hs(i),a=await this.gatewayClient.getPoolData({token0:o,token1:s,fee:n}),c=this.calculationService.calculatePriceFromSqrtPriceX96(wo(a.sqrtPrice));return{tokenA:e,tokenB:t,feeTier:n,liquidity:a.liquidity.toString(),sqrtPriceX96:a.sqrtPrice.toString(),tick:a.tick,feeGrowthGlobal0X128:a.feeGrowthGlobal0.toString(),feeGrowthGlobal1X128:a.feeGrowthGlobal1.toString(),currentPrice:c.toFixed()}}catch(n){throw this.logger.error("Failed to get pool data",n),new O(`Failed to get pool data: ${A(n)}`,n,e,t)}}async getPoolInfo(e,t){try{this.logger.debug("Fetching pool info",{tokenA:e,tokenB:t});const{gswapToken0:n,gswapToken1:r}=this.convertTokenPair(e,t),i=[500,3e3,1e4];let o=wo(0),s=0;for(const a of i)try{const e=Hs(n),t=Hs(r),i=await this.gatewayClient.getPoolData({token0:e,token1:t,fee:a});i&&(o=o.plus(wo(i.liquidity)),s++)}catch{this.logger.debug("Pool not found for fee tier",{tokenA:e,tokenB:t,feeTier:a})}return{tokenA:e,tokenB:t,liquidity:o.toFixed(),feeTiers:i,swapCount:s}}catch(n){return this.logger.warn("Failed to fetch pool info",n),this.logger.debug("Pool error details",{error:new O(`Failed to fetch pool info: ${A(n)}`,n,e,t)}),{tokenA:e,tokenB:t,liquidity:"0",feeTiers:[500,3e3,1e4],swapCount:0}}}async getPoolSlot0(e,t,n){try{this.logger.debug("Fetching pool slot0 data",{token0:e,token1:t,fee:n});const r="string"==typeof e?Hs(e):e,i="string"==typeof t?Hs(t):t,o=await this.gatewayClient.getSlot0({token0:r,token1:i,fee:n}),s={sqrtPrice:o.sqrtPrice||"0",tick:o.tick||0,liquidity:o.liquidity||"0",grossPoolLiquidity:o.grossPoolLiquidity||"0"};return this.logger.debug("Retrieved pool slot0 data",{sqrtPrice:s.sqrtPrice,tick:s.tick,liquidity:s.liquidity}),s}catch(e){throw this.logger.error("Failed to fetch pool slot0 data",e),new O(`Failed to fetch pool slot0 data: ${A(e)}`,e)}}async calculateDexPoolSpotPrice(e,t,n){try{this.logger.debug("Calculating spot price",{tokenA:e,tokenB:t,feeTier:n});const r=await this.getPoolData(e,t,n),i=wo(r.currentPrice);return{tokenA:e,tokenB:t,feeTier:n,price:i.toFixed(),invertedPrice:To(i,!0),tick:r.tick,liquidity:r.liquidity}}catch(n){throw this.logger.error("Failed to calculate spot price",n),new O(`Failed to calculate spot price: ${A(n)}`,n,e,t)}}async getPositionCurrentPrice(e){try{this.logger.debug("Fetching position current price",{token0:e.token0,token1:e.token1,feeTier:e.feeTier});const t=await this.getPoolSlot0(e.token0,e.token1,e.feeTier),n=wo(t.sqrtPrice),r={price:this.calculationService.calculatePriceFromSqrtPriceDecimal(n).toFixed(18),sqrtPrice:t.sqrtPrice,tick:t.tick,liquidity:t.liquidity};return this.logger.debug("Calculated position current price",{price:r.price,tick:r.tick}),r}catch(e){throw this.logger.error("Failed to fetch position current price",e),new O(`Failed to fetch position current price: ${A(e)}`,e)}}chunkArray(e,t){const n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}},exports.GSwapQuoteError=M,exports.GSwapSwapError=L,exports.GSwapSwapService=class extends hs{constructor(e){super(e.debugMode||!1),this.privateKey=e.privateKey,this.getWalletAddress=e.getWalletAddress,this.bundlerBaseUrl=e.bundlerBaseUrl,this.gatewayBaseUrl=e.gatewayBaseUrl,this.webSocketService=e.webSocketService,this.dexQuoteService=e.dexQuoteService,this.tokenConverter=new aa}convertTokenPair(e,t){return{gswapToken0:this.tokenConverter.toLaunchpadFormat(e),gswapToken1:this.tokenConverter.toLaunchpadFormat(t)}}calculatePersonalSignPrefix(e){return`Ethereum Signed Message:\n${JSON.stringify(e).length}${JSON.stringify(e)}`}calculateExecutionPrice(e,t){try{const n=wo(e),r=wo(t);return ko(Lo(r,n,wo("0")))}catch(n){return this.logger.warn("Failed to calculate execution price",{inputAmount:e,outputAmount:t,error:A(n)}),"0"}}async ensureWebSocketConnected(){this.webSocketService.isConnected()||await this.webSocketService.connect()}buildSwapStringsInstructions(e,t,n,r){const i=Ws(e),o=Ws(t),s=`$pool${i}${o}$${n}`;return[s,`$userPosition${r}`,`$tokenBalance${i}${r}`,`$tokenBalance${o}${r}`,`$tokenBalance${i}${s}`,`$tokenBalance${o}${s}`]}async sendSwapToBundler(t){return wr(async()=>{if(!this.privateKey)throw new D("Swap requires wallet (full-access mode)","privateKey");if(!this.bundlerBaseUrl)throw new D("Bundler URL not configured","bundlerBaseUrl");const n=[500,3e3,1e4];if(!n.includes(t.feeTier))throw new B(`Invalid fee tier ${t.feeTier}. Must be one of: ${n.join(", ")}`,"feeTier","INVALID_FEE_TIER");this.logger.debug("Sending Swap to bundler",{fromToken:"string"==typeof t.fromToken?t.fromToken:t.fromToken?.type??"unknown",toToken:"string"==typeof t.toToken?t.toToken:t.toToken?.type??"unknown",inputAmount:t.inputAmount,minOutput:t.minOutput,feeTier:t.feeTier});let r=t.fromToken,i=t.toToken;"string"==typeof r&&(r=Hs(r)),"string"==typeof i&&(i=Hs(i));const s=Ks(r),a=Ks(i),c=s<a?[r,i,s,a]:[i,r,a,s],[l,u,d,h]=c,g=Ks("string"==typeof t.fromToken?Hs(t.fromToken):t.fromToken),p=g===d,f=`galaswap - operation - ${o.v4()}-${Date.now()}-${t.walletAddress}`;let m;if(!t.currentSqrtPrice)throw W("currentSqrtPrice","Current sqrt price");const y=wo(t.currentSqrtPrice),w=t.slippageTolerance??.01;if(p){const e=vo(w);m=ko(y.multipliedBy(e))}else{const e=So(w);m=ko(y.multipliedBy(e))}const k={token0:l,token1:u,fee:t.feeTier,amount:ko(wo(t.inputAmount)),zeroForOne:p,sqrtPriceLimit:m,recipient:t.walletAddress,amountOutMinimum:ko(wo(t.minOutput).multipliedBy(-1)),uniqueKey:f};this.logger.info("SWAP DTO DETAILS",{orderedToken0String:d,orderedToken1String:h,fromTokenStr:g,zeroForOne:p?`TRUE (${d} -> ${h})`:`FALSE (${h} -> ${d})`,inputAmount:t.inputAmount,expectedOutput:t.minOutput,slippageTolerance:100*(t.slippageTolerance||.01)+"%"});const b=new e.ethers.Wallet(this.privateKey),v={Swap:[{name:"token0",type:"token0"},{name:"token1",type:"token1"},{name:"fee",type:"int256"},{name:"amount",type:"string"},{name:"zeroForOne",type:"bool"},{name:"sqrtPriceLimit",type:"string"},{name:"recipient",type:"string"},{name:"amountOutMinimum",type:"string"},{name:"uniqueKey",type:"string"}],token0:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}],token1:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}]},S={name:"ethereum",chainId:1},A=this.calculatePersonalSignPrefix(k),T={...k,prefix:A},E=await b.signTypedData(S,v,T),I={...T,signature:E,types:v,domain:S},x=this.buildSwapStringsInstructions(l,u,t.feeTier,t.walletAddress),C=dc.createClient(this.bundlerBaseUrl,3e4),N=mr(await C.post("/bundle",{method:"Swap",signedDto:I,stringsInstructions:x})),_=N?.data||N?.transactionId||N?.id;if(!_)throw new R("Bundler response does not contain transaction ID",void 0,"INVALID_RESPONSE");return _},"Failed to send Swap to bundler",this.logger)}async getSwapQuoteExactInput(e){return wr(async()=>{if(wo(e.amount).isLessThanOrEqualTo(0))throw new M("Amount must be greater than zero",{amount:e.amount,fromToken:e.fromToken,toToken:e.toToken});if(!this.dexQuoteService)throw new M("DexQuoteService not configured. Quote operations require DexQuoteService.",{fromToken:e.fromToken,toToken:e.toToken});this.logger.debug("Getting exact input quote",e);const t=this.tokenConverter.toLaunchpadFormat(e.fromToken),n=this.tokenConverter.toLaunchpadFormat(e.toToken),[r,i]=t<n?[t,n]:[n,t],o=[3e3,500,1e4];let s;const a=this.dexQuoteService;for(const c of o)try{return await wr(async()=>{const o=await a.fetchCompositePoolData({token0:r,token1:i,fee:c,gatewayBaseUrl:this.gatewayBaseUrl}),s=await a.calculateDexPoolQuoteExactAmount({compositePoolData:o,fromToken:t,toToken:n,amount:e.amount}),l=wo(s.currentSqrtPrice),u=wo(s.newSqrtPrice),d=l.gt(u)?Lo(l.minus(u),l,"0"):wo(0),h=wo(s.amount0),g=wo(s.amount1);if(!_o(h)&&!_o(g))throw new M("Unexpected quote result: neither amount is negative (no output from pool)",{amount0:s.amount0,amount1:s.amount1,fromToken:e.fromToken,toToken:e.toToken});const p=(_o(h)?h:g).absoluteValue().toFixed();return{fromToken:e.fromToken,toToken:e.toToken,inputAmount:e.amount,estimatedOutput:p,feeTier:c,priceImpact:d.toFixed(),executionPrice:this.calculateExecutionPrice(e.amount,p),currentSqrtPrice:s.currentSqrtPrice,newSqrtPrice:s.newSqrtPrice}},`Quote calculation for fee tier ${c}`,this.logger)}catch(e){s=e,this.logger.debug("Fee tier failed, trying next",{feeTier:c,error:A(e)})}throw s||new M("No available fee tiers for quote",{feeTiers:o,fromToken:e.fromToken,toToken:e.toToken})},"Failed to get exact input quote",this.logger,(t,n,r)=>{throw r?.error(n,t),new M(`${n}: ${A(t)}`,{fromToken:e.fromToken,toToken:e.toToken})})}async getSwapQuoteExactOutput(e){return wr(async()=>{if(wo(e.amount).isLessThanOrEqualTo(0))throw new M("Amount must be greater than zero",{amount:e.amount,fromToken:e.fromToken,toToken:e.toToken});if(!this.dexQuoteService)throw new M("DexQuoteService not configured. Quote operations require DexQuoteService.",{fromToken:e.fromToken,toToken:e.toToken});this.logger.debug("Getting exact output quote",e);const t=this.tokenConverter.toLaunchpadFormat(e.fromToken),n=this.tokenConverter.toLaunchpadFormat(e.toToken),[r,i]=t<n?[t,n]:[n,t],o=[3e3,500,1e4];let s;const a=this.dexQuoteService;for(const c of o)try{return await wr(async()=>{const o=await a.fetchCompositePoolData({token0:r,token1:i,fee:c,gatewayBaseUrl:this.gatewayBaseUrl}),s=await a.calculateDexPoolQuoteExactAmount({compositePoolData:o,fromToken:t,toToken:n,amount:e.amount}),l=wo(s.currentSqrtPrice),u=wo(s.newSqrtPrice),d=l.gt(u)?Lo(l.minus(u),l,"0"):wo(0),h=wo(s.amount0),g=wo(s.amount1),p=(No(h)?h:No(g)?g:h).absoluteValue().toFixed();return{fromToken:e.fromToken,toToken:e.toToken,inputAmount:p,estimatedOutput:e.amount,feeTier:c,priceImpact:d.toFixed(),executionPrice:this.calculateExecutionPrice(p,e.amount),currentSqrtPrice:s.currentSqrtPrice,newSqrtPrice:s.newSqrtPrice}},`Quote calculation for fee tier ${c}`,this.logger)}catch(e){s=e,this.logger.debug("Fee tier failed, trying next",{feeTier:c,error:A(e)})}throw s||new M("No available fee tiers for quote",{feeTiers:o,fromToken:e.fromToken,toToken:e.toToken})},"Failed to get exact output quote",this.logger,(t,n,r)=>{throw r?.error(n,t),new M(`${n}: ${A(t)}`,{fromToken:e.fromToken,toToken:e.toToken})})}async executeSwap(e){return wr(async()=>{if(!this.privateKey)throw new D("ExecuteSwap requires wallet (full-access mode)","privateKey");this.logger.debug("Executing swap",e);const{gswapToken0:t,gswapToken1:n}=this.convertTokenPair(e.fromToken,e.toToken),r=e.slippageTolerance??.01,i=await this.getSwapQuoteExactInput({fromToken:e.fromToken,toToken:e.toToken,amount:e.inputAmount}),o=bo(e.estimatedOutput,r).toFixed();await this.ensureWebSocketConnected();const s=this.getWalletAddress();if(!s)throw new D("Wallet address not available","walletAddress");const a=await this.sendSwapToBundler({fromToken:t,toToken:n,inputAmount:e.inputAmount,minOutput:o,feeTier:e.feeTier,walletAddress:s,currentSqrtPrice:i.currentSqrtPrice,slippageTolerance:r}),c=this.webSocketService.waitForTransaction(a);return{transactionId:a,status:"pending",fromToken:e.fromToken,toToken:e.toToken,inputAmount:e.inputAmount,outputAmount:e.estimatedOutput,feeTier:e.feeTier,slippageTolerance:r,timestamp:new Date,wait:async(e=12e4)=>{await wr(async()=>{const t=new Promise((t,n)=>{setTimeout(()=>n(new Error(`Transaction ${a} timed out after ${e}ms`)),e)});await Promise.race([c,t]),this.logger.debug("Swap confirmed",{transactionId:a})},"Swap failed or timed out",this.logger,(e,t,n)=>{throw n?.error(t,{transactionId:a,error:A(e)}),e})}}},"Failed to execute swap",this.logger,(e,t,n)=>{throw n?.error(t,e),new L(`${t}: ${A(e)}`,e)})}},exports.GalaConnectClient=ST,exports.GalaConnectHttpError=fT,exports.GlobalAndRoomCallbackDispatcher=class{constructor(e){this.globalCallbacks=[],this.roomCallbacks=new Map,this.logger=e}registerGlobalCallback(e){this.globalCallbacks.push(e)}registerRoomCallback(e,t){const n=this.roomCallbacks.get(e)??[];n.push(t),this.roomCallbacks.set(e,n)}dispatch(e,t){for(const e of this.globalCallbacks)try{e(t)}catch(e){this.logger?.error(`Error in global callback: ${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}: ${t}`)}}clear(){this.globalCallbacks=[],this.roomCallbacks.clear()}clearRoom(e){this.roomCallbacks.delete(e)}},exports.IMAGE_EXTENSIONS=ui,exports.INVITE_STATUS=bu,exports.INVITE_STATUSES=vu,exports.JWT_CONSTANTS=St,exports.LAUNCHPAD_TOKEN_DECIMALS=18,exports.LEGACY_TYPED_DATA_TYPES=fl,exports.LaunchpadSDK=JT,exports.ListenerCleanupManager=class{constructor(e){this.listeners=[],this.logger=e}register(e,t){this.listeners.push({id:e,cleanup:t})}async cleanup(){const e=[];for(let t=this.listeners.length-1;t>=0;t--){const{id:n,cleanup:r}=this.listeners[t];try{await r()}catch(t){const r=t instanceof Error?t:new Error(String(t));e.push(r),this.logger?.error(`Cleanup error for listener ${n}:`,r)}}return this.listeners=[],e}clear(){this.listeners=[]}get size(){return this.listeners.length}},exports.LockError=ba,exports.MAX_BURN_BATCH_SIZE=50,exports.MAX_CONCURRENT_POOL_FETCHES=5,exports.MAX_LOCK_BATCH_SIZE=100,exports.MAX_UNLOCK_BATCH_SIZE=100,exports.MODERATOR_ROLE=mu,exports.MODERATOR_ROLES=yu,exports.NFT_FEES=gd,exports.NetworkError=P,exports.NftCollectionService=kd,exports.OVERSEER_INVITE_STATUS=Hu,exports.OVERSEER_STATUS=ju,exports.PAGINATION_DEFAULTS=zo,exports.POOL_FETCH_CONFIG={MAX_CONCURRENT_FETCHES:5,BACKEND_PAGE_SIZE:20},exports.POOL_TYPES={RECENT:"recent",POPULAR:"popular"},exports.PayloadWalkerWithDeduplication=class{constructor(e,t,n=50){this.seen=new Set,this.extractor=e,this.dedupeKeyFn=t,this.maxDepth=n}walk(e){const t=[],n=new WeakSet,r=(e,i=0)=>{if(i>this.maxDepth)return;if(!e||"object"!=typeof e)return;if(n.has(e))return;n.add(e);const o=this.extractor(e);if(o){const e=this.dedupeKeyFn(o);this.seen.has(e)||(this.seen.add(e),t.push(o))}for(const t of Object.values(e))r(t,i+1)};return r(e,0),t}reset(){this.seen.clear()}getSeenCount(){return this.seen.size}},exports.PendingSubscriptionTracker=class{constructor(){this.pending=new Map}addPending(e,t){this.removePending(e);const n=setTimeout(()=>{this.pending.delete(e)},t);this.pending.set(e,{timeoutId:n,addedAt:Date.now()})}removePending(e){const t=this.pending.get(e);t&&(clearTimeout(t.timeoutId),this.pending.delete(e))}isPending(e){return this.pending.has(e)}getPendingCount(){return this.pending.size}clearExpired(){for(const[e,t]of this.pending.entries())t||this.pending.delete(e)}clear(){for(const e of this.pending.values())clearTimeout(e.timeoutId);this.pending.clear()}},exports.PoolStateManager=rE,exports.QUERY_FIELD_NAMES={PAGE:"page",LIMIT:"limit",TOKEN_NAME:"tokenName",VAULT_ADDRESS:"vaultAddress",USER_ADDRESS:"userAddress",TRADE_TYPE:"tradeType",POOL_TYPE:"type",SEARCH:"search",SORT_ORDER:"sortOrder",START_DATE:"startDate",END_DATE:"endDate"},exports.REACTION_EMOJI_MAP={heart:"❤️",fire:"🔥",laugh:"😂",wow:"😮",thumbs_up:"👍"},exports.RECORDING_STATUS=Al,exports.ROLE_SOURCE=Nl,exports.RoomSubscriptionManager=class{constructor(){this.rooms=new Set}addRoom(e){this.rooms.add(e)}removeRoom(e){this.rooms.delete(e)}getRooms(){return Array.from(this.rooms)}isSubscribedTo(e){return this.rooms.has(e)}clear(){this.rooms.clear()}get size(){return this.rooms.size}},exports.SDK_VERSION=XT,exports.SIMULATE_EVENT_TYPE={STREAM_STARTED:"stream.started",STREAM_STOPPED:"stream.stopped",RECORDING_READY:"recording.ready",SIMULCAST_ERROR:"simulcast.error"},exports.SIMULCAST_PLATFORM=Tl,exports.SIMULCAST_STATUS={ACTIVE:"ACTIVE",IDLE:"IDLE",ERRORED:"ERRORED",DISABLED:"DISABLED"},exports.SOLANA_COMPUTE={UNIT_LIMIT:2e5,UNIT_PRICE_MICROLAMPORTS:375e3},exports.SOLANA_DISCRIMINATORS=ll,exports.STREAM_EVENTS=Wl,exports.STREAM_PERMISSION={MANAGE_COMMENTS:"MANAGE_COMMENTS",MANAGE_CHAT:"MANAGE_CHAT",BAN_USERS:"BAN_USERS",UNBAN_USERS:"UNBAN_USERS",MANAGE_SIMULCAST:"MANAGE_SIMULCAST",GET_STREAM_KEY:"GET_STREAM_KEY",STOP_STREAM:"STOP_STREAM",RESET_STREAM_KEY:"RESET_STREAM_KEY",START_STREAM:"START_STREAM",DELETE_RECORDINGS:"DELETE_RECORDINGS",MANAGE_STREAM_SETTINGS:"MANAGE_STREAM_SETTINGS"},exports.STREAM_ROLE=Cl,exports.STREAM_STATUS=Sl,exports.SelectiveEventForwarding=class{constructor(){this.filters=[]}addFilter(e){return this.filters.push(e),this}forward(e){for(const t of this.filters)if(!t(e))return!1;return!0}clearFilters(){this.filters=[]}get filterCount(){return this.filters.length}},exports.SolanaBridgeStrategy=UT,exports.StreamWebSocketService=zl,exports.StreamingEventService=Hl,exports.TIME_CONSTANTS={ONE_SECOND_MS:1e3,ONE_MINUTE_MS:6e4,ONE_HOUR_MS:36e5,ONE_DAY_MS:864e5,ONE_WEEK_MS:6048e5,ONE_MONTH_MS:2592e6},exports.TRADES_QUERY_CONSTRAINTS=ks,exports.TRADING_TYPES=Cd,exports.TokenMetadataService=class extends hs{constructor(e=!1){super(e),this.cache={},this.cacheExpiry=36e5}async resolveTokenMetadata(e){const t=this.getCacheKey(e),n=this.cache[t];if(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}async getTokenSymbol(e){return(await this.resolveTokenMetadata(e)).symbol}async getTokenDecimals(e){return(await this.resolveTokenMetadata(e)).decimals}clearCache(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 rs(e);return rs(`${e.type||e.symbol||"unknown"}|${e.additionalKey||"none"}`)}extractMetadata(e){let t,n,r="Token",i="Unit",o="none";if("string"==typeof e)if(Vs(e)){const s=js(e);"Token"===s.collection&&s.type?(r=s.collection,i=s.category||"Unit",t=s.type,o=s.additionalKey||"none",n=t):(t=s.collection,n=t,i=s.category||"Unit",o=s.additionalKey||"none")}else t=e,n=e;else t=e.type||"unknown",r=e.collection||"Token",i=e.category||"Unit",o=e.additionalKey||"none",n=e.symbol||("Token"===r?t:r)||"unknown";const s=this.getDecimalsForToken(n);return{symbol:n.toUpperCase(),decimals:s,collection:r,category:i,type:t.toUpperCase(),additionalKey:o,verified:!1}}getDecimalsForToken(e){return{GALA:8,GUSDC:6,USDC:6,USDT:6,WETH:18,DAI:18}[e.toUpperCase()]??18}isCacheExpired(e){return Ve(e)>this.cacheExpiry}setCacheExpiry(e){this.cacheExpiry=e,this.logger.debug(`Set token metadata cache expiry to ${e}ms`)}},exports.TransactionError=R,exports.TransactionFailedError=HT,exports.TypingIndicatorDebouncer=class{constructor(e={},t){this.pendingIndicators=new Map,this.activeIndicators=new Set,this.delayMs=e.delayMs??3e3,this.onTyping=e.onTyping,this.onStopTyping=e.onStopTyping,this.logger=t}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}},exports.ValidationError=B,exports.WebSocketError=zT,exports.WebSocketTimeoutError=class extends zT{constructor(e,t){super(`WebSocket confirmation timeout for transaction ${e} after ${t}ms`),this.name="WebSocketTimeoutError"}},exports.addressFormatSchema=Br,exports.aggregateMultipleApiSources=async function(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 o=e.map(async(t,n)=>{try{const o=await i(t);return r?.debug(`Endpoint [${n+1}/${e.length}] succeeded: ${t}`),o}catch(i){return void r?.warn(`Endpoint [${n+1}/${e.length}] failed: ${t} - ${A(i)}`)}}),s=(await Promise.allSettled(o)).map(e=>{if("fulfilled"===e.status)return e.value});return r?.debug(`Aggregating ${s.filter(e=>void 0!==e).length} successful results`),t(s)},exports.amountMethodSchema=ai,exports.amountTypeSchema=si,exports.assertValidWalletAddress=yt,exports.bidirectionalTokenMatch=Cs,exports.browserFileSchema=hi,exports.bufferFileSchema=gi,exports.buildConcurrentBatchRequests=async function(e,t,n,r){const i=r?.logger,o=new Array(e.length);let s=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 o[c]=r,s++,i?.debug(`Fetched [${c+1}/${e.length}]: ${t}`),r}catch(n){throw a++,i?.warn(`Failed [${c+1}/${e.length}]: ${t} - ${A(n)}`),n}})()}),r=await Promise.allSettled(t);for(let e=0;e<r.length;e++){"rejected"===r[e].status&&i?.debug(`Promise rejected in batch at index ${l+e}`)}}catch(e){i?.error(`Batch processing error at index ${r}: ${A(e)}`)}}return i?.debug(`Batch complete: ${s} succeeded, ${a} failed`),o},exports.buildQueryParametersWithValidation=function(e){if(!e||"object"!=typeof e)return"";const t=[];for(const[n,r]of Object.entries(e)){if(Je(r))continue;let e;e="string"==typeof r?r:"number"==typeof r||"boolean"==typeof r?String(r):Array.isArray(r)?r.map(e=>String(e)).join(","):"object"==typeof r?JSON.stringify(r):String(r);const i=encodeURIComponent(n),o=encodeURIComponent(e);t.push(`${i}=${o}`)}return t.length>0?`?${t.join("&")}`:""},exports.buyTokensDataSchema=Ri,exports.calculateLinearFeeInterpolation=function(e,t,n){const r="number"==typeof e?new i(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 o=n-t;return new i(t).plus(new i(o).multipliedBy(r))},exports.calculatePaginationOffset=Ho,exports.calculatePreMintDataSchema=qi,exports.calculateScaledFeeAmount=function(e,t){if(t<0)throw new Error(`feeFactor must be >= 0, got: ${t}`);return wo(e).multipliedBy(t).integerValue(i.ROUND_DOWN)},exports.calculateTotalPages=Xo,exports.capitalize=K,exports.caseInsensitiveTokenComparison=Is,exports.checkPoolOptionsSchema=oi,exports.commonValidators=st,exports.compareAmounts=function(e,t){const n=wo(e),r=wo(t);return n.comparedTo(r)},exports.conditionalSpreadBuilder=function(e,t){const n={...e};for(const[e,r]of Object.entries(t))void 0!==r&&(n[e]=r);return n},exports.conditionalTrimAndValidateString=Es,exports.createLaunchpadSDK=function(t){Ze(t)&&(t={});const{wallet:n,env:r,config:i={},...o}=t,s={...o,...i},{wallet:a,env:c,config:l,...u}=s;let d;if(Ze(n)){d=YT().wallet}else if("string"==typeof n){d=YT(n).wallet}else{if(!(n instanceof e.Wallet))throw j("Invalid wallet input. Expected string (private key or mnemonic) or Wallet instance.","wallet");d=n}const h={wallet:d,...r&&{env:r},debug:!1,timeout:3e4,...u};return new JT(h)},exports.createLimitSchema=$r,exports.createOptionsValidator=function(e){return t=>{const n=[],r=t;for(const t of e){const{field:e,required:i,type:o,validator:s}=t,a=r[e];if(i){if(Ze(a)){n.push(`${e} is required`);continue}if("string"===o){if("string"!=typeof a){n.push(`${e} must be a string`);continue}if(0===a.trim().length){n.push(`${e} is required`);continue}}}if(!Ze(a))if(o&&typeof a!==o)n.push(`${e} must be a ${o}`);else if(s){const e=s(a,r);e&&n.push(e)}}return n}},exports.createPaginatedResultSchema=function(e){return r.z.object({data:r.z.array(e),page:r.z.number().int().min(1),limit:r.z.number().int().min(1),total:r.z.number().int().min(0),totalPages:r.z.number().int().min(0),hasNext:r.z.boolean(),hasPrevious:r.z.boolean()})},exports.createPaginationQuery=function(e,t=zo.DEFAULT_LIMIT){return{offset:Ho(e,t),limit:t}},exports.createPoolStateManager=function(e,t){return new rE(e,t)},exports.createSolanaWallet=function(){const e=LA.generate();return{privateKey:OT.encode(e.secretKey),publicKey:e.publicKey.toBase58(),address:e.publicKey.toBase58()}},exports.createTradeDataSchema=Di,exports.createWallet=YT,exports.decimalRoundingUp=function(e,t){if(t<0)throw new Error(`decimals must be >= 0, got: ${t}`);const n=wo(e),r=new i(10).pow(t);return n.multipliedBy(r).integerValue(i.ROUND_UP).dividedBy(r)},exports.deduplicateByKey=function(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})},exports.errorMessageCaseNormalization=function(e){return e.toLowerCase()},exports.ethereumAddressSchema=Pr,exports.extractFieldWithFallbackPath=function(e,t,n=null){if(!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(!n||"object"!=typeof n){n=null;break}n=n[e]}if(Qe(n))return n;if(null!=n&&""!==n)return n}return n},exports.extractPaginationMetadata=function(e){const t={page:1,pageSize:20,totalCount:-1,hasMore:!1};if(!e||"object"!=typeof e)return t;const n=e,r=Le(String(n.page??n.Page??n.current??1),t.page),i=Le(String(n.pageSize??n.limit??n.size??t.pageSize),t.pageSize),o=n.data,s=o?.meta;let a;a="number"==typeof n.totalCount?n.totalCount:"number"==typeof n.total?n.total:"number"==typeof s?.totalItems?s.totalItems:"number"==typeof o?.count?o.count:Le(String(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 s?.hasMore&&(c=s.hasMore),{page:r,pageSize:i,totalCount:a,hasMore:c}},exports.fetchGalaBalanceOptionsSchema=Ii,exports.fetchPoolDetailsDataSchema=Ki,exports.fetchTokenBalanceOptionsSchema=_i,exports.fileSizeSchema=Wr,exports.fileUploadSchema=di,exports.filenameSchema=zr,exports.filterByFeeTier=function(e,t){return e.filter(e=>e.feeTier===t)},exports.filterByLiquidity=function(e){return e.filter(e=>No(e.liquidity))},exports.filterByMinLiquidity=function(e,t){const n=wo(t);return e.filter(e=>wo(e.liquidity).isGreaterThanOrEqualTo(n))},exports.filterByPoolKey=function(e,t,n,r){const i=t.toUpperCase(),o=n.toUpperCase();return e.filter(e=>{const t=e.token0.toUpperCase(),n=e.token1.toUpperCase();return(t===i&&n===o||t===o&&n===i)&&e.feeTier===r})},exports.filterByToken=function(e,t){return e.filter(e=>Is(e.token0,t)||Is(e.token1,t))},exports.filterByTokenPair=function(e,t,n){const r=t.toUpperCase(),i=n.toUpperCase();return e.filter(e=>{const t=e.token0.toUpperCase(),n=e.token1.toUpperCase();return t===r&&n===i||t===i&&n===r})},exports.flexibleAddressSchema=Dr,exports.flexibleFileSchema=pi,exports.formatGalaForDTO=qe,exports.formatLaunchpadTokenForDTO=Ke,exports.formatTokenAmount=function(e,t=6){const n=wo(e);if(!n.isFinite())return"0";if(n.abs().lt(1e-6)&&!Co(n))return n.toExponential(2);const r=Math.min(t,n.abs().lt(1)?t:n.abs().lt(100)?4:2);return n.toFixed(r).replace(/\.?0+$/,"")},exports.formatTokenDescriptor=function(e){return Ks(e)},exports.fromBackendAddressFormat=pt,exports.fromBaseUnits=Rd,exports.fullNameSchema=_r,exports.generateUniqueKey=ua,exports.getAmountOptionsSchema=$i,exports.getEnv=function(e,t){return process.env[e]??t},exports.getEnvOrThrow=function(e,t){const n=process.env[e];if(Ze(n)||!Qe(n)){throw W(e,`${e} (${t?`${t} (checked root .env and local .env)`:"checked root .env and local .env"})`)}return n},exports.getEthereumAddressFromPrivateKey=function(t){if(!t.match(/^0x[a-fA-F0-9]{64}$/))throw z("privateKey","0x-prefixed 64 hexadecimal characters","Private key");return e.getAddress(e.computeAddress(t))},exports.getEthereumBridgeContractByEnvironment=rl,exports.getEthereumTokenConfig=function(e){const t=os(e);return il.find(e=>os(e.symbol)===t||os(e.symbol)===`G${t}`)},exports.getEthereumTokensByEnvironment=nl,exports.getGalaBridgeTypedDataTypes=yl,exports.getLaunchTokenDataValidationErrors=bd,exports.getNftFeeAsNumber=function(e){return parseFloat(gd[e])},exports.getPublicKeyFromPrivateKey=function(t){if(!t.match(/^0x[a-fA-F0-9]{64}$/))throw z("privateKey","0x-prefixed 64 hexadecimal characters","Private key");const n=new e.SigningKey(t);return{publicKey:n.publicKey,compressedPublicKey:n.compressedPublicKey}},exports.getSolanaTokenConfig=function(e){const t=os(e);return ol.find(e=>os(e.symbol)===t||os(e.symbol)===`G${t}`)},exports.getStaticTokenMetadata=function(e){const t=os(e),n=sl[t];if(n)return n;if(!t.startsWith("G")){const e=sl[`G${t}`];if(e)return e}},exports.getTradeOptionsSchema=Li,exports.graduateTokenOptionsSchema=li,exports.graphDataOptionsSchema=ci,exports.groupByFeeTier=function(e){return eE(e,e=>e.feeTier)},exports.groupByKey=eE,exports.groupByPoolKey=function(e){return eE(e,e=>`${e.token0.toUpperCase()}|${e.token1.toUpperCase()}|${e.feeTier}`)},exports.groupByTokenPair=function(e){return eE(e,e=>`${e.token0.toUpperCase()}/${e.token1.toUpperCase()}`)},exports.hasMorePages=Qo,exports.hexStringExtractionAndNormalization=function(e){if(!e||"string"!=typeof e)return null;if(e.includes("|")){const t=e.split("|");if(t.length>=2){const e=t[1];if(Ns(e))return _s(e)}return null}return Ns(e)?_s(e):null},exports.imageExtensionSchema=fi,exports.imageFilenameSchema=mi,exports.imageMimeTypeSchema=Hr,exports.imageUploadOptionsSchema=ri,exports.isAccessSource=Rl,exports.isActiveUserType=Vl,exports.isBanData=Xl,exports.isBanEnforcementEvent=Zl,exports.isBurnTokenEntry=Ca,exports.isBurnTokensData=Na,exports.isChatDisabledReason=Fl,exports.isChatMessageItem=function(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.id&&"string"==typeof t.tokenName&&"string"==typeof t.userAddress&&"string"==typeof t.content&&"string"==typeof t.createdAt&&"number"==typeof t.flagCount&&"object"==typeof t.reactions},exports.isChatStatusResponse=function(e){if(!e||"object"!=typeof e)return!1;const t=e;return"boolean"==typeof t.enabled&&(void 0===t.reason||Fl(t.reason))},exports.isClaimableInvite=function(e){if(e.status!==Hu.PENDING)return!1;if(e.expiresAt){if(He(e.expiresAt)<=new Date)return!1}return!0},exports.isContentType=Fu,exports.isEmptyValue=Je,exports.isExtendedStreamRole=Dl,exports.isFlagAction=qu,exports.isFlagData=Ku,exports.isFlagReason=Uu,exports.isFlagStatus=$u,exports.isLockTokenEntry=pa,exports.isLockTokensData=ma,exports.isModeratedToken=Iu,exports.isModeratorInvite=Eu,exports.isNonEmptyString=Qe,exports.isOverseerInviteStatus=Vu,exports.isOverseerStatus=Xu,exports.isPinnedMessage=$l,exports.isPublicInviteInfo=xu,exports.isReactionErrorCode=ql,exports.isRecordingStatus=Il,exports.isSimulcastPlatform=xl,exports.isStreamChatDeletedEvent=function(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.messageId&&"string"==typeof t.deletedAt},exports.isStreamChatErrorEvent=function(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.message},exports.isStreamChatMessage=Ul,exports.isStreamChatMessageEvent=function(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&Ul(t.message)},exports.isStreamChatPinnedEvent=function(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&$l(t.pinnedMessage)},exports.isStreamChatUnpinnedEvent=function(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.unpinnedMessageId},exports.isStreamReactionErrorEvent=function(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.message},exports.isStreamReactionEvent=function(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.emoji&&"number"==typeof t.timestamp&&"number"==typeof t.streamTime},exports.isStreamStatus=El,exports.isStreamStatusEvent=function(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&El(t.status)&&(null===t.playbackId||"string"==typeof t.playbackId)&&"boolean"==typeof t.isLive},exports.isStreamingEvent=function(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.type&&["stream_status","user_banned","user_unbanned","ban_enforcement","content_flagged","flag_resolved","stream_chat_message","stream_chat_updated","stream_chat_deleted","stream_chat_pinned","stream_chat_unpinned","chat_status_changed","viewer_count","recording_status","simulcast_status","download_ready","user_typing","stream_reaction","content_reaction_added","content_reaction_removed","stream_countdown_updated","stream_language_updated","stream_control_status_changed","connection","authenticated","token_subscribed","token_unsubscribed","room_subscribed","room_left"].includes(t.type)},exports.isTokenAccessPermissions=Pl,exports.isTokenAccessResult=function(e){if(!e||"object"!=typeof e)return!1;const t=e;return"boolean"==typeof t.hasAccess&&(null===t.role||Dl(t.role))&&Pl(t.permissions)&&(null===t.accessSource||Rl(t.accessSource))&&"boolean"==typeof t.isOwner&&"boolean"==typeof t.isOverseer},exports.isTokenBanData=function(e){if(!e||"object"!=typeof e)return!1;const t=e;return"number"==typeof t.id&&"string"==typeof t.tokenName&&"string"==typeof t.bannedBy&&"string"==typeof t.createdAt&&(null===t.reason||"string"==typeof t.reason)},exports.isTypingIndicatorEvent=function(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&Array.isArray(t.typingUsers)&&t.typingUsers.every(Kl)},exports.isTypingUser=Kl,exports.isUnlockTokenEntry=fa,exports.isUnlockTokensData=ya,exports.isUserBannedEvent=Ql,exports.isUserUnbannedEvent=Jl,exports.isValidAddress=mt,exports.isValidApiKeyRole=uu,exports.isValidBanDuration=eu,exports.isValidBanReason=Yl,exports.isValidChatContent=function(e){return!!Qe(e)&&(e.length>=ve.CHAT_MESSAGE.MIN_LENGTH&&e.length<=ve.CHAT_MESSAGE.MAX_LENGTH)},exports.isValidChatTokenName=function(e){return!!Qe(e)&&he.PATTERN.test(e)},exports.isValidGalaChainChannel=function(e){return Object.values(Qc).includes(e)},exports.isValidInviteCode=Tu,exports.isValidInviteStatus=Au,exports.isValidLaunchTokenData=function(e){return eo(e).success},exports.isValidModeratorRole=Su,exports.isValidTokenBanReason=nu,exports.isValidTokenName=function(e,t=he){if("string"!=typeof e)return!1;const n=e.trim();return 0!==n.length&&t.PATTERN.test(n)},exports.isViewerCountEvent=function(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"number"==typeof t.viewerCount},exports.isoDateStringSchema=jr,exports.launchTokenDataSchema=ni,exports.loadEnvWithFallback=function(){const e=y.join(process.cwd(),"..","..",".env");w.existsSync(e)&&k.config({path:e});const t=y.join(process.cwd(),".env");w.existsSync(t)&&k.config({path:t})},exports.nonNegativeDecimalStringSchema=Lr,exports.normalizeAddressInput=ft,exports.normalizeDataWithMapping=function(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})},exports.normalizeErrorMessage=xs,exports.normalizeLimit=Vo,exports.normalizePage=jo,exports.normalizeTokenKey=is,exports.normalizeTokenName=rs,exports.normalizeTokenSymbol=os,exports.optionalUrlSchema=Fr,exports.pageNumberSchema=Ur,exports.paginationResultMetaSchema=Ai,exports.parseHttpErrorResponse=function(e){const t={statusCode:0,errorMessage:"Unknown error",raw:e};if(!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,o=t.errorMessage;"string"==typeof n.message?o=n.message:"string"==typeof n.error?o=n.error:e instanceof Error?o=e.message:"string"==typeof e&&(o=e);const s=n.response;if(s){const e=s.data;if("object"==typeof e&&null!==e){i=e;const t=e;"string"==typeof t.message?o=t.message:"string"==typeof t.error&&(o=t.error)}}const a={statusCode:r,errorMessage:o,raw:e};return i&&(a.errorData=i),a},exports.percentileIndexCalculation=function(e,t){if(0===e.length)return-1;if(t<0||t>100)throw new Error(`Percentile must be between 0 and 100, got: ${t}`);const n=(e.length-1)*(t/100),r=Math.floor(n);return Math.min(r,e.length-1)},exports.poolFetchTypeSchema=ii,exports.poolPaginationSchema=bi,exports.positiveDecimalStringSchema=Mr,exports.priceTickRangeMapping=function(e,t,n=60){const r=wo(e),o=wo(t);if(r.isLessThanOrEqualTo(0)||o.isLessThanOrEqualTo(0))throw new Error("Prices must be positive");if(r.isGreaterThanOrEqualTo(o))throw new Error(`minPrice must be < maxPrice, got: ${r.toString()} >= ${o.toString()}`);const s=Math.floor(Ao(r)),a=Math.ceil(Ao(o)),c=Math.floor(s/n)*n,l=Math.ceil(a/n)*n;return{minTick:c,maxTick:l,actualMinPrice:new i(1.0001).pow(c),actualMaxPrice:new i(1.0001).pow(l)}},exports.privateKeySchema=Xr,exports.requireNonNegative=Ro,exports.requirePositive=Do,exports.requirePositiveWithContext=Mo,exports.retryableHttpRequest=async function(e,t){const n=t?.maxRetries??3,r=t?.backoffMs??100,i=t?.retryableStatus??[429,503,504];let o,s=0;for(;s<=n;)try{return await e()}catch(e){o=e,s++;const t=tE(e),a=i.includes(t);if(s>n||!a)throw e;const c=r*Math.pow(2,s-1);await new Promise(e=>setTimeout(e,c))}throw o},exports.reverseBondingCurveConfigSchema=ti,exports.reverseBondingCurveConfigurationSchema=Gi,exports.roleHasSufficientPermission=function(e,t){return e===cu.MANAGER?t!==cu.OWNER:e===cu.OWNER||e===t},exports.roundTickBoundaries=function(e,t,n){if(e>=t)throw new Error(`tickLower must be < tickUpper, got: ${e} >= ${t}`);if(n<=0)throw new Error(`tickSpacing must be > 0, got: ${n}`);return{tickLower:Math.floor(e/n)*n,tickUpper:Math.ceil(t/n)*n}},exports.roundTickToSpacing=function(e,t){if(t<=0)throw new Error(`tickSpacing must be > 0, got: ${t}`);return Math.floor(e/t)*t},exports.safeDivideWithMinimum=function(e,t,n,r="0"){const i=wo(t);if(Co(i))return wo(r);const o=wo(e).dividedBy(i);if(null!=n){const e=wo(n);if(e.isLessThan(0))throw new Error(`minimum must be >= 0, got: ${e.toString()}`);if(o.isLessThan(e))return e}return o},exports.searchQuerySchema=Nr,exports.sellTokensDataSchema=Mi,exports.sortByLiquidity=function(e,t="desc"){return[...e].sort((e,n)=>{const r=wo(e.liquidity),i=wo(n.liquidity);return"desc"===t?i.minus(r).toNumber():r.minus(i).toNumber()})},exports.standardLimitSchema=qr,exports.standardPaginationSchema=yi,exports.stripHexPrefix=ct,exports.timestampSchema=Vr,exports.toBackendAddressFormat=gt,exports.toBackendAddressFromEthers=wt,exports.toBaseUnits=Dd,exports.tokenCategorySchema=Yr,exports.tokenCollectionSchema=ei,exports.tokenDescriptionSchema=xr,exports.tokenHoldSchema=Ni,exports.tokenListOptionsSchema=Ei,exports.tokenNameSchema=Er,exports.tokenSymbolSchema=Ir,exports.tokenUrlsSchema=Zr,exports.tradeCalculationMethodSchema=Ui,exports.tradeCalculationTypeSchema=Fi,exports.tradeLimitSchema=Gr,exports.tradeListParamsSchema=Oi,exports.tradePaginationSchema=ki,exports.tradePaginationWithFiltersSchema=Si,exports.tradeTypeBackendSchema=Pi,exports.tradeTypeSchema=Bi,exports.transactionIdSchema=Qr,exports.transformRawApiTokenToDomainModel=function(e){if(!e||"object"!=typeof e)throw new Error("Token must be an object");const t=e,n=(Qe(t.name)?t.name:null)||(Qe(t.tokenName)?t.tokenName:null)||"";if(!Qe(n))throw new Error("Token name is required and must be a non-empty string");const r=(Qe(t.symbol)?t.symbol:null)||(Qe(t.tokenSymbol)?t.tokenSymbol:null)||(Qe(t.collection)?t.collection:null)||"";if(!Qe(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 o={name:n,symbol:r,decimals:i};return Qe(t.address)&&(o.address=t.address),"boolean"==typeof t.verified&&(o.verified=t.verified),o},exports.trimmedLengthValidation=function(e){return!e||"string"!=typeof e||0===e.trim().length},exports.uniqueKeySchema=Jr,exports.updateProfileDataSchema=xi,exports.uploadProfileImageOptionsSchema=Ci,exports.urlSchema=Or,exports.userLimitSchema=Kr,exports.userPaginationSchema=wi,exports.userTokenNameSchema=Cr,exports.userTokenTypeSchema=Ti,exports.userTokensPaginationSchema=vi,exports.validateAddress=Vi,exports.validateAmountString=Qi,exports.validateBanTokenOptions=ru,exports.validateBuyTokensData=uo,exports.validateCalculatePreMintData=mo,exports.validateChatMessageId=dd,exports.validateCheckPoolOptions=ro,exports.validateConstrainedEnumVariant=function(e,t,n){if(!t.includes(e))throw new B(`${n} must be one of [${t.join(", ")}], received "${e}"`,n,"INVALID_ENUM_VALUE")},exports.validateCreateApiKeyOptions=du,exports.validateCreateChatMessageOptions=ld,exports.validateCreateCommentOptions=function(e){if(!Qe(e.tokenName))throw W("tokenName","Token name");const{MIN_LENGTH:t,MAX_LENGTH:n,PATTERN:r}=ge;if(e.tokenName.length<t||e.tokenName.length>n||!r.test(e.tokenName))throw z("tokenName",`${t}-${n} alphanumeric characters`,"Token name");if(!Qe(e.content))throw W("content");if(0===e.content.trim().length)throw ie("content","Content");if(e.content.length>ve.COMMENTS_V1.MAX_LENGTH)throw re("content",ve.COMMENTS_V1.MAX_LENGTH,e.content.length)},exports.validateCreateModeratorInviteOptions=function(e){const t=[],n=e.inviteScope??wu.TOKEN;return void 0===e.inviteScope||Cu(e.inviteScope)||N(t,()=>{throw ne("inviteScope",e.inviteScope,ku,"Invite scope")}),n===wu.TOKEN?N(t,()=>{rt(e.tokenName??"","tokenName",he)}):n===wu.ALL_OWNER_TOKENS&&e.tokenName&&t.push("Token name should not be provided for ALL_OWNER_TOKENS scope invites"),e.role?Su(e.role)||N(t,()=>{throw ne("role",e.role,yu,"Role")}):N(t,()=>{throw W("role","Role")}),e.description&&N(t,()=>{se(e.description,ve.DESCRIPTION.MAX_LENGTH,"description")}),e.expiresAt&&!je(e.expiresAt)&&N(t,()=>{throw function(e,t="a valid date",n){const r=K(e,n);return new B(`${r} must be ${t}`,e,"INVALID_DATE")}("expiresAt","ISO 8601 format")}),t},exports.validateCreateOverseerInviteOptions=Qu,exports.validateCreateTradeData=lo,exports.validateDecimalRangeStrict=function(e,t,n,r){const i="string"==typeof e?parseFloat(e):e;if(!isFinite(i))throw new B(`${r} must be a valid finite number between ${t} and ${n}`,r,"INVALID_NUMBER");if(i<t||i>n)throw Q(r,t,n,i,r)},exports.validateFeePortionConstraints=de,exports.validateFetchGalaBalanceOptions=oo,exports.validateFetchPoolDetailsData=yo,exports.validateFetchTokenBalanceOptions=co,exports.validateFullName=Ji,exports.validateGetAmountOptions=fo,exports.validateGetChatMessagesOptions=cd,exports.validateGetCommentsOptions=function(e){if(!e.tokenName&&!e.userAddress)throw function(e){if(e.length<2)return W(e[0]||"field");let t;t=2===e.length?e.join(" or "):`${e.slice(0,-1).join(", ")} or ${e[e.length-1]}`;return new B(`At least one of ${t} must be provided`,e[0],"REQUIRED")}(["tokenName","userAddress"]);if(e.tokenName){const{MIN_LENGTH:t,MAX_LENGTH:n,PATTERN:r}=ge;if(e.tokenName.length<t||e.tokenName.length>n||!r.test(e.tokenName))throw z("tokenName",`${t}-${n} alphanumeric characters`,"Token name")}Ye(e.page,e.limit,ye.MAX_LIMIT)},exports.validateGetTokenBanOptions=su,exports.validateGetTradeOptions=go,exports.validateGetTradesOptions=bs,exports.validateImageUploadOptions=no,exports.validateInviteCode=function(e){const t=[];return Qe(e)?Tu(e)||t.push("Invalid invite code format"):t.push(W("inviteCode","Invite code").message),t},exports.validateLaunchTokenData=vd,exports.validateListApiKeysOptions=gu,exports.validateListModeratorInvitesOptions=function(e){const t=[];return N(t,()=>{rt(e.tokenName??"","tokenName",he)}),void 0===e.status||Au(e.status)||N(t,()=>{throw ne("status",e.status,vu,"Status")}),N(t,()=>{Ye(e.page,e.limit,fe)}),t},exports.validateListOverseerInvitesOptions=Ju,exports.validateListOverseersOptions=Zu,exports.validateListTokenBansOptions=ou,exports.validateListUsersOptions=nd,exports.validateMinMaxRelationship=function(e,t,n,r){const i="string"==typeof e?parseFloat(e):e,o="string"==typeof t?parseFloat(t):t;if(!isFinite(i))throw new B(`${n} must be a valid finite number`,n,"INVALID_MIN_VALUE");if(!isFinite(o))throw new B(`${r} must be a valid finite number`,r,"INVALID_MAX_VALUE");if(i>o)throw new B(`${n} (${i}) must be less than or equal to ${r} (${o})`,n,"INVALID_RANGE")},exports.validateOptionalTokenName=function(e,t="tokenName",n=he){if(null==e)return;if("string"!=typeof e)throw Y(t,"a string",e);const r=e.trim();if(0!==r.length&&!n.PATTERN.test(r))throw new B(`${t} must be ${n.MIN_LENGTH}-${n.MAX_LENGTH} alphanumeric characters`,t,_.INVALID_FORMAT)},exports.validateOverseerInviteCode=Yu,exports.validateOverseerInviteId=td,exports.validateOverseerWalletAddress=ed,exports.validatePaginationParams=function(e,t,n){ae(e,"page"),ae(t,"limit")},exports.validateSearchQuery=Zi,exports.validateSellTokensData=ho,exports.validateSortOrderDirection=ue,exports.validateTokenDescription=ji,exports.validateTokenListOptions=io,exports.validateTokenName=it,exports.validateTokenSymbol=Hi,exports.validateTokenUrls=to,exports.validateTradeListParams=po,exports.validateUnbanTokenOptions=iu,exports.validateUpdateApiKeyOptions=hu,exports.validateUpdateChatMessageOptions=ud,exports.validateUpdateCommentOptions=function(e){if(!Qe(e.content))throw W("content");if(0===e.content.trim().length)throw ie("content","Content");if(e.content.length>ve.COMMENTS_V1.MAX_LENGTH)throw re("content",ve.COMMENTS_V1.MAX_LENGTH,e.content.length)},exports.validateUpdateProfileData=so,exports.validateUploadProfileImageOptions=ao,exports.validateUserTokenName=Yi,exports.validateVaultAddress=Xi,exports.vaultAddressSchema=Rr;