@gala-chain/launchpad-sdk 5.0.3 → 5.0.4-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (406) hide show
  1. package/EXAMPLES.md +141 -7
  2. package/README.md +68 -36
  3. package/dist/ai-docs.json +7357 -0
  4. package/dist/index.cjs.js +1 -1
  5. package/dist/index.d.ts +70 -11
  6. package/dist/index.d.ts.map +1 -1
  7. package/dist/index.esm.js +1 -1
  8. package/dist/index.js +1 -1
  9. package/dist/src/LaunchpadSDK.d.ts +3288 -214
  10. package/dist/src/LaunchpadSDK.d.ts.map +1 -1
  11. package/dist/src/api/LaunchpadAPI.d.ts +21 -41
  12. package/dist/src/api/LaunchpadAPI.d.ts.map +1 -1
  13. package/dist/src/api/dto/BurnTokensDto.d.ts.map +1 -1
  14. package/dist/src/api/dto/LockTokenDto.d.ts.map +1 -1
  15. package/dist/src/api/dto/TransferTokenDto.d.ts.map +1 -1
  16. package/dist/src/api/dto/UnlockTokenDto.d.ts.map +1 -1
  17. package/dist/src/auth/JwtAuth.d.ts +145 -0
  18. package/dist/src/auth/JwtAuth.d.ts.map +1 -0
  19. package/dist/src/auth/SessionAuthService.d.ts +146 -0
  20. package/dist/src/auth/SessionAuthService.d.ts.map +1 -0
  21. package/dist/src/auth/SignatureAuth.d.ts.map +1 -1
  22. package/dist/src/bridge/BridgeService.d.ts.map +1 -1
  23. package/dist/src/bridge/GalaConnectClient.d.ts.map +1 -1
  24. package/dist/src/bridge/constants/tokens.d.ts +4 -3
  25. package/dist/src/bridge/constants/tokens.d.ts.map +1 -1
  26. package/dist/src/bridge/index.d.ts +1 -0
  27. package/dist/src/bridge/index.d.ts.map +1 -1
  28. package/dist/src/bridge/strategies/BridgeStrategy.d.ts.map +1 -1
  29. package/dist/src/bridge/strategies/EthereumBridgeStrategy.d.ts +1 -38
  30. package/dist/src/bridge/strategies/EthereumBridgeStrategy.d.ts.map +1 -1
  31. package/dist/src/bridge/strategies/SolanaBridgeStrategy.d.ts +1 -21
  32. package/dist/src/bridge/strategies/SolanaBridgeStrategy.d.ts.map +1 -1
  33. package/dist/src/bridge/types/bridge.dto.d.ts +15 -2
  34. package/dist/src/bridge/types/bridge.dto.d.ts.map +1 -1
  35. package/dist/src/bridge/utils/RateLimiter.d.ts +1 -1
  36. package/dist/src/bridge/utils/RateLimiter.d.ts.map +1 -1
  37. package/dist/src/bridge/utils/address-formatter.d.ts +25 -0
  38. package/dist/src/bridge/utils/address-formatter.d.ts.map +1 -0
  39. package/dist/src/bridge/utils/addressValidation.d.ts +200 -0
  40. package/dist/src/bridge/utils/addressValidation.d.ts.map +1 -0
  41. package/dist/src/bridge/utils/balanceHelpers.d.ts +215 -0
  42. package/dist/src/bridge/utils/balanceHelpers.d.ts.map +1 -0
  43. package/dist/src/bridge/utils/bridgeErrors.d.ts +98 -0
  44. package/dist/src/bridge/utils/bridgeErrors.d.ts.map +1 -0
  45. package/dist/src/bridge/utils/bridgeOutHelpers.d.ts +68 -0
  46. package/dist/src/bridge/utils/bridgeOutHelpers.d.ts.map +1 -0
  47. package/dist/src/bridge/utils/bridgePayload.d.ts +107 -0
  48. package/dist/src/bridge/utils/bridgePayload.d.ts.map +1 -0
  49. package/dist/src/bridge/utils/bridgeStatusParser.d.ts +75 -0
  50. package/dist/src/bridge/utils/bridgeStatusParser.d.ts.map +1 -0
  51. package/dist/src/bridge/utils/eip712Helpers.d.ts +66 -0
  52. package/dist/src/bridge/utils/eip712Helpers.d.ts.map +1 -0
  53. package/dist/src/bridge/utils/index.d.ts +9 -0
  54. package/dist/src/bridge/utils/index.d.ts.map +1 -1
  55. package/dist/src/bridge/utils/retry.d.ts +16 -0
  56. package/dist/src/bridge/utils/retry.d.ts.map +1 -1
  57. package/dist/src/bridge/utils/strategyDelegation.d.ts +69 -0
  58. package/dist/src/bridge/utils/strategyDelegation.d.ts.map +1 -0
  59. package/dist/src/bridge/utils/tokenIdUtils.d.ts +7 -0
  60. package/dist/src/bridge/utils/tokenIdUtils.d.ts.map +1 -1
  61. package/dist/src/bridge/utils/tokenMath.d.ts.map +1 -1
  62. package/dist/src/bridge/utils/tokenMetadataResolver.d.ts +97 -0
  63. package/dist/src/bridge/utils/tokenMetadataResolver.d.ts.map +1 -0
  64. package/dist/src/constants/endpoints.d.ts +453 -0
  65. package/dist/src/constants/endpoints.d.ts.map +1 -1
  66. package/dist/src/constants/error-messages.d.ts +1 -1
  67. package/dist/src/constants/error-messages.d.ts.map +1 -1
  68. package/dist/src/constants/jwt.d.ts +41 -0
  69. package/dist/src/constants/jwt.d.ts.map +1 -0
  70. package/dist/src/constants/sdk-defaults.d.ts +37 -0
  71. package/dist/src/constants/sdk-defaults.d.ts.map +1 -0
  72. package/dist/src/constants/version.generated.d.ts +1 -1
  73. package/dist/src/constants/version.generated.d.ts.map +1 -1
  74. package/dist/src/helpers/sdk.d.ts.map +1 -1
  75. package/dist/src/helpers/wallet.d.ts +4 -3
  76. package/dist/src/helpers/wallet.d.ts.map +1 -1
  77. package/dist/src/index.d.ts +70 -11
  78. package/dist/src/index.d.ts.map +1 -1
  79. package/dist/src/schemas/files.d.ts +2 -2
  80. package/dist/src/schemas/launchpad.d.ts +40 -8
  81. package/dist/src/schemas/launchpad.d.ts.map +1 -1
  82. package/dist/src/schemas/pagination.d.ts +7 -7
  83. package/dist/src/schemas/primitives.d.ts.map +1 -1
  84. package/dist/src/schemas/trade.d.ts +6 -6
  85. package/dist/src/schemas/user.d.ts +4 -4
  86. package/dist/src/schemas/validators.d.ts +15 -7
  87. package/dist/src/schemas/validators.d.ts.map +1 -1
  88. package/dist/src/services/AbstractCacheService.d.ts +227 -0
  89. package/dist/src/services/AbstractCacheService.d.ts.map +1 -0
  90. package/dist/src/services/AbstractTokenFetchService.d.ts +150 -0
  91. package/dist/src/services/AbstractTokenFetchService.d.ts.map +1 -0
  92. package/dist/src/services/ApiKeyService.d.ts +205 -0
  93. package/dist/src/services/ApiKeyService.d.ts.map +1 -0
  94. package/dist/src/services/BanService.d.ts +195 -0
  95. package/dist/src/services/BanService.d.ts.map +1 -0
  96. package/dist/src/services/BaseService.d.ts +50 -3
  97. package/dist/src/services/BaseService.d.ts.map +1 -1
  98. package/dist/src/services/BatchedCacheService.d.ts +132 -0
  99. package/dist/src/services/BatchedCacheService.d.ts.map +1 -0
  100. package/dist/src/services/BridgeableTokenCache.d.ts +32 -98
  101. package/dist/src/services/BridgeableTokenCache.d.ts.map +1 -1
  102. package/dist/src/services/BridgeableTokenService.d.ts +18 -13
  103. package/dist/src/services/BridgeableTokenService.d.ts.map +1 -1
  104. package/dist/src/services/BundleService.d.ts.map +1 -1
  105. package/dist/src/services/BundlerClientFactory.d.ts +32 -0
  106. package/dist/src/services/BundlerClientFactory.d.ts.map +1 -0
  107. package/dist/src/services/ChatMessagesService.d.ts +152 -0
  108. package/dist/src/services/ChatMessagesService.d.ts.map +1 -0
  109. package/dist/src/services/CommentService.d.ts +119 -0
  110. package/dist/src/services/CommentService.d.ts.map +1 -0
  111. package/dist/src/services/CommentsService.d.ts +155 -0
  112. package/dist/src/services/CommentsService.d.ts.map +1 -0
  113. package/dist/src/services/ContentFlagService.d.ts +212 -0
  114. package/dist/src/services/ContentFlagService.d.ts.map +1 -0
  115. package/dist/src/services/ContentReactionService.d.ts +175 -0
  116. package/dist/src/services/ContentReactionService.d.ts.map +1 -0
  117. package/dist/src/services/DexBackendClient.d.ts.map +1 -1
  118. package/dist/src/services/DexPoolService.d.ts +3 -3
  119. package/dist/src/services/DexPoolService.d.ts.map +1 -1
  120. package/dist/src/services/DexQuoteService.d.ts.map +1 -1
  121. package/dist/src/services/DexService.d.ts +2 -5
  122. package/dist/src/services/DexService.d.ts.map +1 -1
  123. package/dist/src/services/GSwapAssetService.d.ts +80 -0
  124. package/dist/src/services/GSwapAssetService.d.ts.map +1 -0
  125. package/dist/src/services/GSwapLiquidityMutationService.d.ts +140 -0
  126. package/dist/src/services/GSwapLiquidityMutationService.d.ts.map +1 -0
  127. package/dist/src/services/GSwapLiquidityQueryService.d.ts +87 -0
  128. package/dist/src/services/GSwapLiquidityQueryService.d.ts.map +1 -0
  129. package/dist/src/services/GSwapPoolCalculationService.d.ts +200 -0
  130. package/dist/src/services/GSwapPoolCalculationService.d.ts.map +1 -0
  131. package/dist/src/services/GSwapPoolQueryService.d.ts +116 -0
  132. package/dist/src/services/GSwapPoolQueryService.d.ts.map +1 -0
  133. package/dist/src/services/GSwapService.d.ts +14 -0
  134. package/dist/src/services/GSwapService.d.ts.map +1 -1
  135. package/dist/src/services/GSwapSwapService.d.ts +68 -0
  136. package/dist/src/services/GSwapSwapService.d.ts.map +1 -0
  137. package/dist/src/services/GalaChainBalanceService.d.ts +155 -0
  138. package/dist/src/services/GalaChainBalanceService.d.ts.map +1 -0
  139. package/dist/src/services/GalaChainGatewayClient.d.ts +32 -1
  140. package/dist/src/services/GalaChainGatewayClient.d.ts.map +1 -1
  141. package/dist/src/services/GalaChainLockService.d.ts +144 -0
  142. package/dist/src/services/GalaChainLockService.d.ts.map +1 -0
  143. package/dist/src/services/GalaChainService.d.ts +23 -106
  144. package/dist/src/services/GalaChainService.d.ts.map +1 -1
  145. package/dist/src/services/GalaChainTokenService.d.ts +108 -0
  146. package/dist/src/services/GalaChainTokenService.d.ts.map +1 -0
  147. package/dist/src/services/GalaChainTransferService.d.ts +205 -0
  148. package/dist/src/services/GalaChainTransferService.d.ts.map +1 -0
  149. package/dist/src/services/ImageService.d.ts +24 -8
  150. package/dist/src/services/ImageService.d.ts.map +1 -1
  151. package/dist/src/services/LaunchpadService.d.ts +77 -5
  152. package/dist/src/services/LaunchpadService.d.ts.map +1 -1
  153. package/dist/src/services/ModeratorService.d.ts +269 -0
  154. package/dist/src/services/ModeratorService.d.ts.map +1 -0
  155. package/dist/src/services/MultiPoolStateManager.d.ts +4 -6
  156. package/dist/src/services/MultiPoolStateManager.d.ts.map +1 -1
  157. package/dist/src/services/NetworkKeyedCacheService.d.ts +185 -0
  158. package/dist/src/services/NetworkKeyedCacheService.d.ts.map +1 -0
  159. package/dist/src/services/OverseerService.d.ts +322 -0
  160. package/dist/src/services/OverseerService.d.ts.map +1 -0
  161. package/dist/src/services/PoolCacheManager.d.ts +2 -2
  162. package/dist/src/services/PoolCacheManager.d.ts.map +1 -1
  163. package/dist/src/services/PoolService.d.ts +61 -7
  164. package/dist/src/services/PoolService.d.ts.map +1 -1
  165. package/dist/src/services/PoolStateManager.d.ts +2 -2
  166. package/dist/src/services/PoolStateManager.d.ts.map +1 -1
  167. package/dist/src/services/PriceHistoryService.d.ts.map +1 -1
  168. package/dist/src/services/SignatureService.d.ts.map +1 -1
  169. package/dist/src/services/StreamChatService.d.ts +378 -0
  170. package/dist/src/services/StreamChatService.d.ts.map +1 -0
  171. package/dist/src/services/StreamTokenServiceBase.d.ts +371 -0
  172. package/dist/src/services/StreamTokenServiceBase.d.ts.map +1 -0
  173. package/dist/src/services/StreamWebSocketService.d.ts +268 -0
  174. package/dist/src/services/StreamWebSocketService.d.ts.map +1 -0
  175. package/dist/src/services/StreamingEventService.d.ts +431 -0
  176. package/dist/src/services/StreamingEventService.d.ts.map +1 -0
  177. package/dist/src/services/StreamingService.d.ts +547 -0
  178. package/dist/src/services/StreamingService.d.ts.map +1 -0
  179. package/dist/src/services/SwapEventQueue.d.ts +2 -2
  180. package/dist/src/services/SwapEventQueue.d.ts.map +1 -1
  181. package/dist/src/services/TokenBanService.d.ts +214 -0
  182. package/dist/src/services/TokenBanService.d.ts.map +1 -0
  183. package/dist/src/services/TokenClassKeyService.d.ts.map +1 -1
  184. package/dist/src/services/TokenMetadataCache.d.ts +36 -27
  185. package/dist/src/services/TokenMetadataCache.d.ts.map +1 -1
  186. package/dist/src/services/TokenMetadataService.d.ts +24 -4
  187. package/dist/src/services/TokenMetadataService.d.ts.map +1 -1
  188. package/dist/src/services/TokenResolverService.d.ts.map +1 -1
  189. package/dist/src/services/TradeService.d.ts +73 -0
  190. package/dist/src/services/TradeService.d.ts.map +1 -1
  191. package/dist/src/services/UserService.d.ts +56 -3
  192. package/dist/src/services/UserService.d.ts.map +1 -1
  193. package/dist/src/services/WebSocketService.d.ts +3 -3
  194. package/dist/src/services/WebSocketService.d.ts.map +1 -1
  195. package/dist/src/services/WrapService.d.ts +18 -5
  196. package/dist/src/services/WrapService.d.ts.map +1 -1
  197. package/dist/src/services/WrappableTokenCache.d.ts +8 -36
  198. package/dist/src/services/WrappableTokenCache.d.ts.map +1 -1
  199. package/dist/src/services/WrappableTokenService.d.ts +18 -12
  200. package/dist/src/services/WrappableTokenService.d.ts.map +1 -1
  201. package/dist/src/services/shared/cache-helpers.d.ts +188 -0
  202. package/dist/src/services/shared/cache-helpers.d.ts.map +1 -0
  203. package/dist/src/services/shared/http-helpers.d.ts +146 -0
  204. package/dist/src/services/shared/http-helpers.d.ts.map +1 -0
  205. package/dist/src/services/shared/pagination-helpers.d.ts +157 -0
  206. package/dist/src/services/shared/pagination-helpers.d.ts.map +1 -0
  207. package/dist/src/services/shared/service-validators.d.ts +137 -0
  208. package/dist/src/services/shared/service-validators.d.ts.map +1 -0
  209. package/dist/src/services/shared/websocket-helpers.d.ts +158 -0
  210. package/dist/src/services/shared/websocket-helpers.d.ts.map +1 -0
  211. package/dist/src/test-constants.d.ts +29 -0
  212. package/dist/src/test-constants.d.ts.map +1 -0
  213. package/dist/src/types/api-key.dto.d.ts +300 -0
  214. package/dist/src/types/api-key.dto.d.ts.map +1 -0
  215. package/dist/src/types/backend-responses.d.ts +12 -0
  216. package/dist/src/types/backend-responses.d.ts.map +1 -1
  217. package/dist/src/types/ban.dto.d.ts +413 -0
  218. package/dist/src/types/ban.dto.d.ts.map +1 -0
  219. package/dist/src/types/burn.dto.d.ts +21 -0
  220. package/dist/src/types/burn.dto.d.ts.map +1 -1
  221. package/dist/src/types/chat-messages.dto.d.ts +193 -0
  222. package/dist/src/types/chat-messages.dto.d.ts.map +1 -0
  223. package/dist/src/types/comment.dto.d.ts +180 -0
  224. package/dist/src/types/comment.dto.d.ts.map +1 -0
  225. package/dist/src/types/comments.dto.d.ts +210 -0
  226. package/dist/src/types/comments.dto.d.ts.map +1 -0
  227. package/dist/src/types/common.d.ts +369 -0
  228. package/dist/src/types/common.d.ts.map +1 -1
  229. package/dist/src/types/constraints.d.ts +374 -0
  230. package/dist/src/types/constraints.d.ts.map +1 -0
  231. package/dist/src/types/content-flag.dto.d.ts +310 -0
  232. package/dist/src/types/content-flag.dto.d.ts.map +1 -0
  233. package/dist/src/types/content-reactions.dto.d.ts +132 -0
  234. package/dist/src/types/content-reactions.dto.d.ts.map +1 -0
  235. package/dist/src/types/dex-pool.dto.d.ts +13 -37
  236. package/dist/src/types/dex-pool.dto.d.ts.map +1 -1
  237. package/dist/src/types/dto.d.ts +8 -0
  238. package/dist/src/types/dto.d.ts.map +1 -1
  239. package/dist/src/types/galachain-api.types.d.ts +30 -0
  240. package/dist/src/types/galachain-api.types.d.ts.map +1 -1
  241. package/dist/src/types/gswap-responses.types.d.ts.map +1 -1
  242. package/dist/src/types/launchpad.dto.d.ts +234 -131
  243. package/dist/src/types/launchpad.dto.d.ts.map +1 -1
  244. package/dist/src/types/launchpad.validation.d.ts.map +1 -1
  245. package/dist/src/types/lock.dto.d.ts +20 -35
  246. package/dist/src/types/lock.dto.d.ts.map +1 -1
  247. package/dist/src/types/moderator.dto.d.ts +581 -0
  248. package/dist/src/types/moderator.dto.d.ts.map +1 -0
  249. package/dist/src/types/options.dto.d.ts +25 -115
  250. package/dist/src/types/options.dto.d.ts.map +1 -1
  251. package/dist/src/types/overseer.dto.d.ts +420 -0
  252. package/dist/src/types/overseer.dto.d.ts.map +1 -0
  253. package/dist/src/types/pool.dto.d.ts +106 -0
  254. package/dist/src/types/pool.dto.d.ts.map +1 -0
  255. package/dist/src/types/result.types.d.ts +3 -2
  256. package/dist/src/types/result.types.d.ts.map +1 -1
  257. package/dist/src/types/session-auth.dto.d.ts +91 -0
  258. package/dist/src/types/session-auth.dto.d.ts.map +1 -0
  259. package/dist/src/types/stream-chat.dto.d.ts +815 -0
  260. package/dist/src/types/stream-chat.dto.d.ts.map +1 -0
  261. package/dist/src/types/streaming-events.dto.d.ts +586 -0
  262. package/dist/src/types/streaming-events.dto.d.ts.map +1 -0
  263. package/dist/src/types/streaming.dto.d.ts +1141 -0
  264. package/dist/src/types/streaming.dto.d.ts.map +1 -0
  265. package/dist/src/types/token-ban.dto.d.ts +195 -0
  266. package/dist/src/types/token-ban.dto.d.ts.map +1 -0
  267. package/dist/src/types/trade.dto.d.ts +21 -61
  268. package/dist/src/types/trade.dto.d.ts.map +1 -1
  269. package/dist/src/types/trades-query.dto.d.ts +127 -0
  270. package/dist/src/types/trades-query.dto.d.ts.map +1 -0
  271. package/dist/src/types/transfer.dto.d.ts +20 -15
  272. package/dist/src/types/transfer.dto.d.ts.map +1 -1
  273. package/dist/src/types/user.dto.d.ts +185 -73
  274. package/dist/src/types/user.dto.d.ts.map +1 -1
  275. package/dist/src/types/wrappable-token.dto.d.ts +6 -2
  276. package/dist/src/types/wrappable-token.dto.d.ts.map +1 -1
  277. package/dist/src/utils/LiquidityEventExtractor.d.ts.map +1 -1
  278. package/dist/src/utils/Logger.d.ts.map +1 -1
  279. package/dist/src/utils/MonitoringMetrics.d.ts.map +1 -1
  280. package/dist/src/utils/PoolKeyNormalizer.d.ts.map +1 -1
  281. package/dist/src/utils/ReconnectionManager.d.ts +142 -0
  282. package/dist/src/utils/ReconnectionManager.d.ts.map +1 -0
  283. package/dist/src/utils/SignatureHelper.d.ts +9 -0
  284. package/dist/src/utils/SignatureHelper.d.ts.map +1 -1
  285. package/dist/src/utils/SwapEventExtractor.d.ts.map +1 -1
  286. package/dist/src/utils/adapters.d.ts.map +1 -1
  287. package/dist/src/utils/address-formatter.d.ts +317 -0
  288. package/dist/src/utils/address-formatter.d.ts.map +1 -0
  289. package/dist/src/utils/agent-config.d.ts.map +1 -1
  290. package/dist/src/utils/amount-validator.d.ts +268 -0
  291. package/dist/src/utils/amount-validator.d.ts.map +1 -0
  292. package/dist/src/utils/api-patterns.d.ts +347 -0
  293. package/dist/src/utils/api-patterns.d.ts.map +1 -0
  294. package/dist/src/utils/array-helpers.d.ts +115 -0
  295. package/dist/src/utils/array-helpers.d.ts.map +1 -0
  296. package/dist/src/utils/async-patterns.d.ts +272 -0
  297. package/dist/src/utils/async-patterns.d.ts.map +1 -0
  298. package/dist/src/utils/auto-pagination.d.ts +195 -2
  299. package/dist/src/utils/auto-pagination.d.ts.map +1 -1
  300. package/dist/src/utils/bignumber-helpers.d.ts +119 -13
  301. package/dist/src/utils/bignumber-helpers.d.ts.map +1 -1
  302. package/dist/src/utils/bignumber-pool-cache.d.ts.map +1 -1
  303. package/dist/src/utils/bondingCurveCalculations.d.ts.map +1 -1
  304. package/dist/src/utils/cacheWarmingHelpers.d.ts +2 -2
  305. package/dist/src/utils/cacheWarmingHelpers.d.ts.map +1 -1
  306. package/dist/src/utils/data-transform-patterns.d.ts +393 -0
  307. package/dist/src/utils/data-transform-patterns.d.ts.map +1 -0
  308. package/dist/src/utils/date-utils.d.ts +166 -0
  309. package/dist/src/utils/date-utils.d.ts.map +1 -1
  310. package/dist/src/utils/delimiter-parser.d.ts +139 -0
  311. package/dist/src/utils/delimiter-parser.d.ts.map +1 -0
  312. package/dist/src/utils/error-factories.d.ts +346 -1
  313. package/dist/src/utils/error-factories.d.ts.map +1 -1
  314. package/dist/src/utils/error-handling-patterns.d.ts +390 -0
  315. package/dist/src/utils/error-handling-patterns.d.ts.map +1 -0
  316. package/dist/src/utils/error-patterns.d.ts +360 -0
  317. package/dist/src/utils/error-patterns.d.ts.map +1 -0
  318. package/dist/src/utils/error-utils.d.ts +250 -0
  319. package/dist/src/utils/error-utils.d.ts.map +1 -1
  320. package/dist/src/utils/error-wrapper.d.ts +208 -0
  321. package/dist/src/utils/error-wrapper.d.ts.map +1 -0
  322. package/dist/src/utils/errors.d.ts +70 -0
  323. package/dist/src/utils/errors.d.ts.map +1 -1
  324. package/dist/src/utils/http-factory.d.ts +36 -0
  325. package/dist/src/utils/http-factory.d.ts.map +1 -0
  326. package/dist/src/utils/http.d.ts.map +1 -1
  327. package/dist/src/utils/load-env.d.ts.map +1 -1
  328. package/dist/src/utils/multipart.d.ts.map +1 -1
  329. package/dist/src/utils/numeric-patterns.d.ts +289 -0
  330. package/dist/src/utils/numeric-patterns.d.ts.map +1 -0
  331. package/dist/src/utils/numeric-wrappers.d.ts +146 -0
  332. package/dist/src/utils/numeric-wrappers.d.ts.map +1 -0
  333. package/dist/src/utils/object-extractors.d.ts +115 -0
  334. package/dist/src/utils/object-extractors.d.ts.map +1 -0
  335. package/dist/src/utils/object-patterns.d.ts +81 -0
  336. package/dist/src/utils/object-patterns.d.ts.map +1 -0
  337. package/dist/src/utils/pagination-helpers.d.ts +230 -0
  338. package/dist/src/utils/pagination-helpers.d.ts.map +1 -0
  339. package/dist/src/utils/pool-pair-parser.d.ts +3 -1
  340. package/dist/src/utils/pool-pair-parser.d.ts.map +1 -1
  341. package/dist/src/utils/pool-state-validator.d.ts.map +1 -1
  342. package/dist/src/utils/position-filters.d.ts +1 -2
  343. package/dist/src/utils/position-filters.d.ts.map +1 -1
  344. package/dist/src/utils/query-params.d.ts +0 -16
  345. package/dist/src/utils/query-params.d.ts.map +1 -1
  346. package/dist/src/utils/response-handlers.d.ts +149 -20
  347. package/dist/src/utils/response-handlers.d.ts.map +1 -1
  348. package/dist/src/utils/response-helpers.d.ts +28 -0
  349. package/dist/src/utils/response-helpers.d.ts.map +1 -0
  350. package/dist/src/utils/response-normalizers.d.ts +27 -49
  351. package/dist/src/utils/response-normalizers.d.ts.map +1 -1
  352. package/dist/src/utils/safe-parsers.d.ts +487 -0
  353. package/dist/src/utils/safe-parsers.d.ts.map +1 -0
  354. package/dist/src/utils/service-validators.d.ts +268 -0
  355. package/dist/src/utils/service-validators.d.ts.map +1 -0
  356. package/dist/src/utils/slippage-utils.d.ts.map +1 -1
  357. package/dist/src/utils/string-patterns.d.ts +404 -0
  358. package/dist/src/utils/string-patterns.d.ts.map +1 -0
  359. package/dist/src/utils/string-transforms.d.ts +89 -0
  360. package/dist/src/utils/string-transforms.d.ts.map +1 -0
  361. package/dist/src/utils/string-utils.d.ts +108 -0
  362. package/dist/src/utils/string-utils.d.ts.map +1 -0
  363. package/dist/src/utils/swap-delta-calculator.d.ts.map +1 -1
  364. package/dist/src/utils/tick-crossing-handler.d.ts.map +1 -1
  365. package/dist/src/utils/token-format-converter.d.ts +22 -8
  366. package/dist/src/utils/token-format-converter.d.ts.map +1 -1
  367. package/dist/src/utils/token-parser.d.ts +2 -2
  368. package/dist/src/utils/token-parser.d.ts.map +1 -1
  369. package/dist/src/utils/token-stringification.d.ts +168 -0
  370. package/dist/src/utils/token-stringification.d.ts.map +1 -0
  371. package/dist/src/utils/tokenNameNormalizer.d.ts +96 -0
  372. package/dist/src/utils/tokenNameNormalizer.d.ts.map +1 -0
  373. package/dist/src/utils/tokenNormalizer.d.ts +8 -45
  374. package/dist/src/utils/tokenNormalizer.d.ts.map +1 -1
  375. package/dist/src/utils/transfer-validation.d.ts +1 -1
  376. package/dist/src/utils/transfer-validation.d.ts.map +1 -1
  377. package/dist/src/utils/type-guard-factory.d.ts +260 -0
  378. package/dist/src/utils/type-guard-factory.d.ts.map +1 -0
  379. package/dist/src/utils/unique-key-generator.d.ts +148 -0
  380. package/dist/src/utils/unique-key-generator.d.ts.map +1 -0
  381. package/dist/src/utils/validation-helpers.d.ts +906 -183
  382. package/dist/src/utils/validation-helpers.d.ts.map +1 -1
  383. package/dist/src/utils/validation-patterns.d.ts +745 -0
  384. package/dist/src/utils/validation-patterns.d.ts.map +1 -0
  385. package/dist/src/utils/validation.d.ts +2 -30
  386. package/dist/src/utils/validation.d.ts.map +1 -1
  387. package/dist/src/utils/wallet.d.ts +12 -1
  388. package/dist/src/utils/wallet.d.ts.map +1 -1
  389. package/dist/src/utils/websocket-patterns.d.ts +681 -0
  390. package/dist/src/utils/websocket-patterns.d.ts.map +1 -0
  391. package/dist/src/utils/websocket-validators.d.ts.map +1 -1
  392. package/package.json +86 -19
  393. package/dist/src/bridge/strategies/index.d.ts +0 -9
  394. package/dist/src/bridge/strategies/index.d.ts.map +0 -1
  395. package/dist/src/constants/counts.d.ts +0 -66
  396. package/dist/src/constants/counts.d.ts.map +0 -1
  397. package/dist/src/services/WebSocketManager.d.ts +0 -99
  398. package/dist/src/services/WebSocketManager.d.ts.map +0 -1
  399. package/dist/src/types/eip712-types.d.ts +0 -140
  400. package/dist/src/types/eip712-types.d.ts.map +0 -1
  401. package/dist/src/types/pool-state-manager-config.dto.d.ts +0 -103
  402. package/dist/src/types/pool-state-manager-config.dto.d.ts.map +0 -1
  403. package/dist/src/utils/number-utils.d.ts +0 -94
  404. package/dist/src/utils/number-utils.d.ts.map +0 -1
  405. package/dist/src/utils/precision-math.d.ts +0 -37
  406. package/dist/src/utils/precision-math.d.ts.map +0 -1
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("axios"),require("ethers"),require("@gala-chain/connect"),require("zod"),require("bignumber.js"),require("@gala-chain/dex"),require("@gala-chain/api"),require("uuid"),require("socket.io-client"),require("node:crypto"),require("path"),require("fs"),require("dotenv"),require("crypto")):"function"==typeof define&&define.amd?define(["exports","axios","ethers","@gala-chain/connect","zod","bignumber.js","@gala-chain/dex","@gala-chain/api","uuid","socket.io-client","node:crypto","path","fs","dotenv","crypto"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).GalaLaunchpadSDK={},e.axios,e.ethers,e.GalaChainConnect,e.z,e.BigNumber,e.GalaChainDex,e.GalaChainAPI,e.uuid,e.io,e.crypto$1,e.path,e.fs,e.dotenv,e.crypto$2)}(this,function(e,t,n,r,o,i,s,a,c,u,l,h,d,f,p){"use strict";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 m,y,w=g(h),b=g(d),k=g(f);if("undefined"==typeof File){const{File:e}=require("web-file-polyfill");global.File=e}!function(e){e.WALLET_NOT_CONNECTED="WALLET_NOT_CONNECTED",e.SIGNATURE_FAILED="SIGNATURE_FAILED",e.INVALID_ADDRESS="INVALID_ADDRESS",e.MESSAGE_GENERATION_FAILED="MESSAGE_GENERATION_FAILED"}(m||(m={}));class v extends Error{constructor(e,t,n){super(t),this.type=e,this.originalError=n,this.name="AuthError"}}class E{constructor(e){if(this.wallet=e.wallet,this.messagePrefix=e.messagePrefix||"Create a GalaChain Wallet",""===e.messagePrefix)throw new v(m.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(m.WALLET_NOT_CONNECTED,"Invalid wallet: must be an ethers Wallet instance or undefined");if(!e.address||"string"!=typeof e.address)throw new v(m.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(m.SIGNATURE_FAILED,"Failed to generate signature for authentication",e instanceof Error?e:new Error(String(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(m.WALLET_NOT_CONNECTED,"Wallet private key not available for @gala-chain signing");return this.wallet.privateKey}formatAddress(e){const t=e.replace(/^0x/i,"");if(!/^[a-fA-F0-9]{40}$/.test(t))throw new v(m.INVALID_ADDRESS,`Invalid Ethereum address format: ${e}`);return`eth|${t}`}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;const t=e instanceof Error?e.message:String(e);throw new v(m.SIGNATURE_FAILED,t,e instanceof Error?e:new Error(String(e)))}}async generateAuthHeaders(e,t){this.validateWallet();try{const n=Date.now(),r=`${this.messagePrefix} ${t.toUpperCase()} ${e} ${n}`,o=await this.wallet.signMessage(r);return{"x-signature":o,"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(m.SIGNATURE_FAILED,"Failed to generate authentication headers",e instanceof Error?e:new Error(String(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(m.SIGNATURE_FAILED,"Failed to sign typed data",e instanceof Error?e:new Error(String(e)))}}async generateCustomSignature(e){if(!e||"string"!=typeof e||0===e.trim().length)throw new v(m.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(m.SIGNATURE_FAILED,"Failed to generate custom message signature",e instanceof Error?e:new Error(String(e)))}}validateWallet(){if(!this.wallet)throw new v(m.WALLET_NOT_CONNECTED,"Wallet is required for authentication");if(!this.wallet.address)throw new v(m.WALLET_NOT_CONNECTED,"Wallet address is not available");if(!this.wallet.privateKey&&!this.wallet.signMessage)throw new v(m.WALLET_NOT_CONNECTED,"Wallet must have a private key for signing messages")}}!function(e){e.DEBUG="DEBUG",e.INFO="INFO",e.WARN="WARN",e.ERROR="ERROR"}(y||(y={}));class S{constructor(e){this.levelPriority={[y.DEBUG]:0,[y.INFO]:1,[y.WARN]:2,[y.ERROR]:3},this.debugEnabled=e.debug,this.context=e.context||"SDK",this.minLevel=e.minLevel||(e.debug?y.DEBUG:y.INFO)}debug(e,t){this.log(y.DEBUG,e,t)}info(e,t){this.log(y.INFO,e,t)}warn(e,t){this.log(y.WARN,e,t)}error(e,t){this.log(y.ERROR,e,t)}log(e,t,n){if(this.levelPriority[e]<this.levelPriority[this.minLevel])return;if(e===y.DEBUG&&!this.debugEnabled)return;const r=`[${(new Date).toISOString()}] [${this.context}] [${e}]`,o=this.getConsoleMethod(e);void 0!==n?n instanceof Error?o(`${r} ${t}`,n.message,n.stack):o(`${r} ${t}`,n):o(`${r} ${t}`)}getConsoleMethod(e){switch(e){case y.DEBUG:return console.debug;case y.INFO:return console.info;case y.WARN:return console.warn;case y.ERROR:return console.error;default:return console.log}}child(e){return new S({debug:this.debugEnabled,context:`${this.context}:${e}`,minLevel:this.minLevel})}isDebugEnabled(){return this.debugEnabled&&this.levelPriority[y.DEBUG]>=this.levelPriority[this.minLevel]}}function T(e){if(!e||"object"!=typeof e)return{};const t={};for(const[n,r]of Object.entries(e))null!=r&&("string"==typeof 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 A{constructor(e,n={}){this.auth=e,this.debug=n.debug??!1,this.logger=new S({debug:this.debug,context:"HttpClient"}),this.axios=t.create({baseURL:n.baseUrl||"https://lpad-backend-dev1.defi.gala.com",timeout:n.timeout||3e4,headers:{Accept:"application/json",...n.headers}}),this.setupInterceptors()}async request(e){try{const t={method:e.method,url:e.url,data:e.data,...e.params&&{params:T(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}catch(e){throw this.logger.error("Error:",e),e}}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){try{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()}}catch(e){throw this.logger.error("Custom signature generation failed:",e),new Error(`Failed to generate custom signature for message: ${e instanceof Error?e.message:"Unknown error"}`)}}async signWithGalaChain(e,t,n=r.SigningType.SIGN_TYPED_DATA){const o=this.auth.getPrivateKey(),i=new r.SigningClient(o);return await i.sign(e,t,n)}setupInterceptors(){this.requestInterceptorId=this.axios.interceptors.request.use(async e=>{try{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}catch(e){throw this.logger.error("Failed to add signature:",e),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||e.message,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 I="Token name is required and must be a string",B=e=>`Could not find vault address for token: ${e}`;class x extends Error{constructor(e,t,n){super(e),this.field=t,this.code=n,this.name="ValidationError"}}class C extends Error{constructor(e,t,n){super(e),this.statusCode=t,this.originalError=n,this.name="NetworkError"}}class P extends Error{constructor(e,t){super(e),this.field=t,this.name="ConfigurationError"}}class N extends Error{constructor(e,t,n){super(e),this.transactionId=t,this.code=n,this.name="TransactionError"}}class _ extends Error{constructor(e,t,n){super(e),this.originalError=t,this.code=n,this.name="GSwapQuoteError"}}class D 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,o){super(e),this.originalError=t,this.tokenA=n,this.tokenB=r,this.code=o,this.name="GSwapPoolError"}}class R extends Error{constructor(e,t,n,r){super(e),this.originalError=t,this.walletAddress=n,this.code=r,this.name="GSwapAssetError"}}class L extends Error{constructor(e,t,n){super(e),this.originalError=t,this.code=n,this.name="GSwapPositionError"}}class O extends x{constructor(e,t){super(e,"dexQuote","DEX_QUOTE_ERROR"),this.context=t,this.name="DexQuoteError"}}class F extends x{constructor(e){super(e,"dexPool","DEX_POOL_NOT_FOUND"),this.name="DexPoolNotFoundError"}}function M(e){return e instanceof Error}function $(e){return M(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 q(e){return"object"==typeof e&&null!==e&&"message"in e&&("response"in e||"request"in e||"config"in e)}function K(e,t){return new x(`Token "${e}" not found. Please verify the token name is correct.`,"tokenName","TOKEN_NOT_FOUND")}function z(e,t){const n=t||e.charAt(0).toUpperCase()+e.slice(1);return new x(`${n} is required`,e,"REQUIRED_FIELD")}function G(e,t,n){const r=n||e.charAt(0).toUpperCase()+e.slice(1);return new x(`${r} must be ${t}`,e,"INVALID_FORMAT")}function W(e,t,n){return new C(e,t,n)}function j(e,t){return new P(e,t)}function H(e,t,n){return new N(e,t,n)}function V(e,t,n,r){return n&&n.error(`${t}:`,e),W(`${t}: ${$(e)}`,r,e instanceof Error?e:void 0)}function X(e,t,n){const{MIN_PAGE:r,MAX_PAGE:o,MIN_LIMIT:i,MAX_LIMIT:s}=n.PAGINATION;if("number"!=typeof e||e<r||e>o)throw new x(`Page must be a number between ${r} and ${o}`,"page","INVALID_PAGE");if("number"!=typeof t||t<i||t>s)throw new x(`Limit must be a number between ${i} and ${s}`,"limit","INVALID_LIMIT")}const Q={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 Z(e){return"string"==typeof e&&e.trim().length>0}function Y(e){return!(!e||"string"!=typeof e)&&(Q.ETH_ADDRESS.test(e)||Q.BACKEND_ADDRESS.test(e)||Q.CLIENT_ADDRESS.test(e))}function J(e){return e.startsWith("0x")?`eth|${e.slice(2)}`:e}const ee=o.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"),te=o.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"),ne=o.z.string().min(1,"Token description is required").max(500,"Token description must be at most 500 characters"),re=o.z.string().min(1,"Token name must be at least 1 character").max(50,"Token name must be at most 50 characters"),oe=o.z.string().min(1,"Search query must be at least 1 character").max(100,"Search query must be at most 100 characters"),ie=o.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"),se=o.z.string().regex(Q.BACKEND_ADDRESS,"Address must be in format: eth|[40-hex-chars]"),ae=o.z.string().regex(Q.ETH_ADDRESS,"Invalid Ethereum address format"),ce=o.z.string().refine(e=>Q.BACKEND_ADDRESS.test(e)||Q.ETH_ADDRESS.test(e),"Address must be either eth|[40-hex-chars] or 0x[40-hex-chars] format").transform(e=>e.startsWith("0x")?`eth|${e.slice(2)}`:e),ue=o.z.string().refine(e=>Q.BACKEND_ADDRESS.test(e)||/^service\|Token\$Unit\$[A-Z0-9]+\$eth:[0-9a-fA-F]{40}\$launchpad$/.test(e),"Invalid vault address format"),le=o.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>parseFloat(e)>0,"Amount must be greater than zero"),he=o.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>parseFloat(e)>=0,"Amount must be zero or greater"),de=o.z.string().url("Must be a valid URL").regex(/^https?:\/\//,"URL must start with http:// or https://"),fe=o.z.string().optional().refine(e=>!e||/^https?:\/\/.+\..+/.test(e),"Must be a valid URL if provided"),pe=o.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 ge(e=100){return o.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 me=ge(100),ye=ge(20),we=ge(20),be=o.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"),ke=o.z.string().max(255,"Filename must be at most 255 characters"),ve=o.z.enum(["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"]),Ee=o.z.string().datetime("Must be a valid ISO 8601 date string"),Se=o.z.number().int("Timestamp must be an integer").min(0,"Timestamp must be non-negative"),Te=o.z.string().regex(/^0x[a-fA-F0-9]{64}$/,"Private key must be format: 0x + 64 hex characters"),Ae=o.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"),Ie=o.z.string().regex(/^galaconnect-operation-[a-z0-9-]+$/,"Unique key must be format: galaconnect-operation-{unique-id}"),Be=o.z.object({websiteUrl:fe,telegramUrl:fe,twitterUrl:fe}).refine(e=>e.websiteUrl||e.telegramUrl||e.twitterUrl,"At least one social URL (website, telegram, or twitter) is required"),xe=o.z.string().min(1,"Token category must not be empty").default("Unit"),Ce=o.z.string().min(1,"Token collection must not be empty").default("Token"),Pe=o.z.object({minFeePortion:o.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal string").refine(e=>parseFloat(e)>=.1,"Minimum fee must be >= 0.1").refine(e=>parseFloat(e)<=.5,"Minimum fee must be <= 0.5"),maxFeePortion:o.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal string").refine(e=>parseFloat(e)>=.1,"Maximum fee must be >= 0.1").refine(e=>parseFloat(e)<=.5,"Maximum fee must be <= 0.5")}).refine(e=>parseFloat(e.maxFeePortion)>=parseFloat(e.minFeePortion),{message:"Maximum fee must be >= minimum fee",path:["maxFeePortion"]}),Ne=o.z.object({tokenName:ee,tokenSymbol:te,tokenDescription:ne,tokenImage:o.z.union([o.z.instanceof(File),o.z.instanceof(Buffer),o.z.string().url("Token image must be a valid URL")]).optional(),preBuyQuantity:he.default("0"),websiteUrl:fe,telegramUrl:fe,twitterUrl:fe,tokenCategory:xe,tokenCollection:Ce,reverseBondingCurveConfiguration:Pe.optional(),privateKey:Te.optional()}),_e=o.z.object({file:o.z.union([o.z.instanceof(File),o.z.instanceof(Buffer)]),tokenName:ee}),De=o.z.enum(["recent","popular"]),Ue=o.z.object({tokenName:ee.optional(),symbol:te.optional()}).refine(e=>e.tokenName||e.symbol,"At least one of tokenName or symbol is required"),Re=o.z.enum(["NATIVE","MEME"]),Le=o.z.enum(["IN","OUT"]),Oe=o.z.object({from:o.z.number().int("From timestamp must be an integer").min(173e6,"From timestamp must be at least 173000000"),to:o.z.number().int("To timestamp must be an integer").min(173e6,"To timestamp must be at least 173000000"),resolution:o.z.number().int("Resolution must be an integer").min(1,"Resolution must be at least 1"),tokenName:ee}),Fe=o.z.object({tokenName:ee,slippageToleranceFactor:o.z.number().min(0).max(1).optional(),maxAcceptableReverseBondingCurveFeeSlippageFactor:o.z.number().min(0).max(1).optional(),privateKey:Te.optional()}),Me=[".png",".jpg",".jpeg",".gif",".webp",".svg"],$e=o.z.object({file:o.z.union([o.z.instanceof(File),o.z.instanceof(Buffer)]),name:ke,size:be,type:ve}),qe=o.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"),Ke=o.z.instanceof(Buffer).refine(e=>e.length>=1&&e.length<=10485760,"Buffer size must be between 1 byte and 10MB"),ze=o.z.union([qe,Ke]),Ge=o.z.enum([".png",".jpg",".jpeg",".gif",".webp",".svg"]),We=ke.refine(e=>{const t=e.slice(e.lastIndexOf(".")).toLowerCase();return Me.includes(t)},`Filename must end with one of: ${Me.join(", ")}`),je=o.z.object({page:pe,limit:me}),He=o.z.object({page:pe,limit:ye}),Ve=o.z.object({page:pe,limit:we}),Xe=je.extend({type:o.z.enum(["recent","popular"]).optional(),tokenName:o.z.string().min(1).max(50).optional(),search:o.z.string().min(1).max(100).optional()}),Qe=He.extend({tokenName:o.z.string().min(1).max(50).optional(),search:o.z.string().min(1).max(100).optional()}),Ze=Ve.extend({tradeType:o.z.enum(["BUY","SELL"]).optional(),tokenName:o.z.string().min(1).max(50).optional(),userAddress:o.z.string().regex(/^(0x[a-fA-F0-9]{40}|eth\|[a-fA-F0-9]{40})$/).optional(),startDate:o.z.string().datetime().optional(),endDate:o.z.string().datetime().optional(),sortOrder:o.z.enum(["ASC","DESC"]).default("DESC")}),Ye=o.z.object({page:o.z.number().int().min(1),limit:o.z.number().int().min(1),total:o.z.number().int().min(0),totalPages:o.z.number().int().min(0),hasNext:o.z.boolean(),hasPrevious:o.z.boolean()});const Je=o.z.enum(["all","DEFI","ASSET"]),et=He.extend({type:Je.optional(),address:ce.optional(),search:oe.optional(),tokenName:re.optional()}),tt=o.z.object({address:ce.optional(),refresh:o.z.boolean().optional()}),nt=o.z.object({profileImage:o.z.string(),fullName:ie,address:ce,privateKey:Te.optional()}),rt=o.z.object({file:o.z.union([o.z.instanceof(File),o.z.instanceof(Buffer)]),address:ce.optional(),privateKey:Te.optional()}),ot=o.z.object({created:o.z.number(),createdBy:o.z.string(),expires:o.z.number(),instanceId:o.z.string(),lockAuthority:o.z.string(),name:o.z.string(),quantity:o.z.string(),vestingPeriodStart:o.z.number()}),it=o.z.object({address:ce,tokenId:o.z.union([o.z.string(),o.z.object({collection:o.z.string(),category:o.z.string(),type:o.z.string(),additionalKey:o.z.string()}),o.z.object({collection:o.z.string(),category:o.z.string(),type:o.z.string(),additionalKey:o.z.string(),instance:o.z.string()})]).optional(),tokenName:re.optional(),withExpired:o.z.boolean().optional()}).refine(e=>void 0!==e.tokenId||void 0!==e.tokenName,"At least one token identifier (tokenId or tokenName) is required"),st=o.z.enum(["buy","sell"]),at=o.z.enum(["BUY","SELL"]),ct=o.z.object({tradeType:st,tokenAmount:le,vaultAddress:ue,userAddress:ce,slippageTolerance:le.optional(),deadline:o.z.number().int().positive().optional()}),ut=o.z.object({tokenSymbol:te,nativeTokenQuantity:le,expectedToken:le,maxAcceptableReverseBondingCurveFee:he.default("0").optional()}),lt=o.z.object({tokenSymbol:te,tokenQuantity:le,expectedNativeToken:le,maxAcceptableReverseBondingCurveFee:he.default("0").optional()}),ht=Ve.extend({tokenName:re.optional()}),dt=o.z.object({page:o.z.number().int().min(1).max(1e3).default(1).optional(),limit:o.z.number().int().min(1).max(20).default(10).optional()}),ft=o.z.enum(["NATIVE","MEME"]),pt=o.z.enum(["IN","OUT"]),gt=o.z.object({type:ft,method:pt,vaultAddress:ue,amount:le}),mt=o.z.object({nativeTokenQuantity:le}),yt=o.z.object({vaultAddress:ue}),wt=o.z.object({minFeePortion:le,maxFeePortion:le});function bt(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 kt=bt(ee),vt=bt(te),Et=bt(ne),St=bt(ce),Tt=bt(ue),At=bt(le),It=bt(ie),Bt=bt(oe),xt=bt(re),Ct=bt(Ne),Pt=bt(Be),Nt=bt(_e),_t=bt(Ue),Dt=bt(et),Ut=bt(tt),Rt=bt(nt),Lt=bt(rt),Ot=bt(it),Ft=bt(ct),Mt=bt(ut),$t=bt(lt),qt=bt(ht),Kt=bt(dt),zt=bt(gt),Gt=bt(mt),Wt=bt(yt);function jt(e,t){throw new x(e.join("; "),t,"VALIDATION_ERROR")}function Ht(e){const t=kt(e);!t.success&&t.errors&&jt(t.errors,"tokenName")}function Vt(e){const t=Xe.safeParse(e);t.success||jt(t.error.errors.map(e=>e.message),"pagination")}function Xt(e){const t=_t(e);!t.success&&t.errors&&jt(t.errors,"options")}function Qt(e){const t=zt(e);!t.success&&t.errors&&jt(t.errors,"options")}function Zt(e){const t=Oe.safeParse(e);t.success||jt(t.error.errors.map(e=>e.message),"options")}function Yt(e){const t=ce.safeParse(e);if(!t.success)throw new x("Ethereum address must be 40 hex characters (with or without 0x prefix)","ethereumAddress","INVALID_FORMAT");return t.data}function Jt(e,t,n=!0){if(!e||""===e.trim())throw new x(`${t} cannot be empty or whitespace-only. Provide a valid numeric string or omit the parameter to auto-fetch.`,t,"INVALID_NUMERIC_STRING");if(/[eE]/.test(e))throw new x(`${t} cannot use scientific notation. Use standard decimal format (e.g., "1000" instead of "1e3").`,t,"INVALID_NUMERIC_STRING");const r=parseFloat(e);if(isNaN(r))throw new x(`${t} must be a valid numeric string. Received: "${e}"`,t,"INVALID_NUMERIC_STRING");if(!isFinite(r))throw new x(`${t} must be a finite number. Cannot be Infinity or -Infinity.`,t,"INVALID_NUMERIC_STRING");if(r<0)throw new x(`${t} must be non-negative. Received: "${e}"`,t,"INVALID_NUMERIC_STRING");if(!n&&0===r)throw new x(`${t} must be greater than zero. Received: "${e}"`,t,"INVALID_NUMERIC_STRING")}var en=Object.freeze({__proto__:null,normalizeAddressInput:function(e){if(!e)return;const t=ce.safeParse(e);if(!t.success)throw new x(`Invalid address format: ${e}. Must be either "0x..." (Ethereum) or "eth|..." (GalaChain) format`,"address","INVALID_FORMAT");return t.data},toBackendAddressFormat:Yt,validateCheckPoolOptions:Xt,validateGetAmountOptions:Qt,validateGetGraphOptions:Zt,validateNumericString:Jt,validatePagination:Vt,validateTokenName:Ht});function tn(e,t){const n=e,r=Number(n.page)||t.page,o=Number(n.limit)||t.limit,i=n.data,s=Number(n.total)||Number(i?.count)||0;return{page:r,limit:o,total:s,totalPages:Math.ceil(s/o)}}function nn(e,t){return{hasNext:e<t,hasPrevious:e>1}}function rn(e,t,n=!1){const r=!0===e.error||200!==e.status,o=n&&!e.data;if(r||o)throw new Error(e.message||t)}const on="/launchpad/upload-image",sn="/launchpad/fetch-pool",an="/launchpad/check-pool",cn="/launchpad/get-graph-data",un="/holders",ln="/launchpad/get-badge/",hn="/trade/",dn="/user/profile",fn="/user/profile",pn="/user/token-list",gn="/user/token-hold",mn="/v1/users/referrals/url",yn="/v1/users/referrals",wn="/v1/users/referrals/summary",bn="/v1/registered",kn={DEFAULT_PAGE:1,DEFAULT_LIMIT:10,BACKEND_MAX_PAGE_SIZE:20,SAFETY_MAX_PAGES:100};class vn{constructor(e,t=!1){this.http=e,this.logger=new S({debug:t,context:this.constructor.name})}}class En{constructor(e=!1){this.logger=new S({debug:e,context:this.constructor.name})}}function Sn(e,t){return"string"==typeof e[t]}function Tn(e,t){return void 0===e[t]||"string"==typeof e[t]}function An(e,t){return void 0===e[t]||"number"==typeof e[t]}function In(e){return void 0===e.calculateAmountMode||"local"===e.calculateAmountMode||"external"===e.calculateAmountMode}function Bn(e){if(!e||"object"!=typeof e)return!1;const t=e;return Sn(t,"tokenName")&&An(t,"from")&&An(t,"to")&&An(t,"resolution")}class xn extends vn{constructor(e,t=!1){super(e,t)}async fetchSinglePage(e){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);const n=T(t),r=await this.http.get(sn,n);if(!r)throw W("No response from pool service",500);rn(r,"Failed to fetch pools",!0);const o=function(e){if(!e)return[];let t=[];if(e.tokens)if(Array.isArray(e.tokens))t=e.tokens.map(e=>({...e,createdAt:e.created_at||e.createdAt||""}));else{const n=e.tokens;t=[{...n,createdAt:n.created_at||n.createdAt||""}]}else e.pools&&Array.isArray(e.pools)&&(t=e.pools.map(e=>({...e,createdAt:e.created_at||e.createdAt||""})));return t}(r.data),i=r.data.count??r.data.total??0;return{pools:o,total:i,totalPages:e.limit>0?Math.ceil(i/e.limit):1}}async fetchMultiplePages(e){const{startPage:t,totalPages:n,pageSize:r,...o}=e,i=[];if(n&&n>=t){const e=[];for(let r=t;r<=n;r++)e.push(r);for(let t=0;t<e.length;t+=5){const n=e.slice(t,t+5).map(e=>this.fetchSinglePage({...o,page:e,limit:r}).catch(e=>{if(400===e?.launchpadError?.statusCode)return{pools:[],total:0,totalPages:0};throw e}));(await Promise.all(n)).forEach(e=>{i.push(...e.pools)})}return i}let s=t,a=!0;for(;a;){const e=[];for(let t=0;t<5&&a;t++)e.push(s+t);const t=e.map(e=>this.fetchSinglePage({...o,page:e,limit:r}).catch(e=>{if(400===e?.launchpadError?.statusCode)return{pools:[],total:0,totalPages:0};throw e})),n=await Promise.all(t);for(const e of n){if(0===e.pools.length){a=!1;break}i.push(...e.pools)}s+=e.length,s>kn.SAFETY_MAX_PAGES&&(a=!1)}return i}async fetchPools(e={}){const t=e.page||kn.DEFAULT_PAGE,n=e.limit??kn.DEFAULT_LIMIT;let r;if(0!==n&&Vt({page:t,limit:n}),e.tokenName&&Ht(e.tokenName),"recent"===e.type?r="RECENT":"popular"===e.type&&(r="POPULAR"),n>0&&n<=20){const o=await this.fetchSinglePage({...e.search&&{search:e.search},...e.tokenName&&{tokenName:e.tokenName},...r&&{type:r},page:t,limit:n});return{pools:o.pools,page:t,limit:n,total:o.total,totalPages:o.totalPages,hasNext:t<o.totalPages,hasPrevious:t>1}}if(0===n){const t=kn.BACKEND_MAX_PAGE_SIZE,n=await this.fetchSinglePage({...e.search&&{search:e.search},...e.tokenName&&{tokenName:e.tokenName},...r&&{type:r},page:1,limit:t}),o=[...n.pools];if(n.pools.length<t)return{pools:o,page:1,limit:o.length,total:o.length,totalPages:1,hasNext:!1,hasPrevious:!1};if(n.pools.length>0){const i=await this.fetchMultiplePages({...e.search&&{search:e.search},...e.tokenName&&{tokenName:e.tokenName},...r&&{type:r},startPage:2,totalPages:n.totalPages>1?n.totalPages:null,pageSize:t});o.push(...i)}return{pools:o,page:1,limit:o.length,total:n.total||o.length,totalPages:1,hasNext:!1,hasPrevious:!1}}const o=kn.BACKEND_MAX_PAGE_SIZE,i=Math.ceil(n/o),s=await this.fetchSinglePage({...e.search&&{search:e.search},...e.tokenName&&{tokenName:e.tokenName},...r&&{type:r},page:t,limit:o}),a=[...s.pools],c=Math.min(i,s.totalPages-t+1);if(c>1){const n=t+c-1,i=await this.fetchMultiplePages({...e.search&&{search:e.search},...e.tokenName&&{tokenName:e.tokenName},...r&&{type:r},startPage:t+1,totalPages:n,pageSize:o});a.push(...i)}const u=a.slice(0,n);return{pools:u,page:t,limit:n,total:s.total,totalPages:s.totalPages,hasNext:t<s.totalPages&&u.length<s.total,hasPrevious:t>1}}async fetchAllPools(e){return this.fetchPools({...e,limit:0})}async checkPool(e){Xt(e),e.tokenName&&Ht(e.tokenName);const t=T(e),n=await this.http.get(an,t);if(!n)throw W("No response from pool service",500);rn(n,"Failed to check pool");const r=n.data;return e.symbol?r?.isSymbolExist??!1:e.tokenName?r?.isNameExist??!1:r?.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(!Bn(e))throw new x("Invalid options provided. Expected { tokenName: string, from?: number, to?: number, resolution?: number }","options","INVALID_OPTIONS");const{tokenName:t,from:n,to:r,resolution:o}=e;if(Ht(t),!n||!r||!o)throw new x("Graph options (from, to, resolution) are required","options","MISSING_GRAPH_OPTIONS");const i={tokenName:t,from:n,to:r,resolution:o};Zt(i);const s=T(i),a=await this.http.get(cn,s);if(!a)throw W("No response from pool service",500);return rn(a,"Failed to fetch graph data",!0),{dataPoints:a.data}}async fetchTokenDistribution(e){if(!e)throw z("tokenName","Token name");Ht(e);const t=await this.resolveTokenNameToVault(e);if(!t)throw K(e);const n=encodeURIComponent(t);let r;try{r=await this.http.get(`${un}/${n}`)}catch(t){if(t&&"object"==typeof t&&"response"in t){const n=t;if(500===n.response?.status)throw W(`Token distribution data temporarily unavailable for ${e}. This is a backend issue - please try again later.`,500)}throw t}if(!r)throw W("No response from pool service",500);rn(r,"Failed to fetch token distribution",!0);const o=r.data;if(!Array.isArray(o))throw W("Invalid API response: expected array of holders",r.status);for(const e of o){if(!e.owner||"string"!=typeof e.owner)throw W("Invalid holder data: missing or invalid owner field",r.status);if(!e.quantity||"string"!=typeof e.quantity)throw W("Invalid holder data: missing or invalid quantity field",r.status);const t=parseFloat(e.quantity);if(isNaN(t)||!isFinite(t))throw W(`Invalid holder quantity: "${e.quantity}"`,r.status)}const s=o.reduce((e,t)=>e.plus(t.quantity),new i(0));return{holders:o.map(e=>{const t=new i(e.quantity),n=s.isZero()?0:t.dividedBy(s).multipliedBy(100).toNumber();return{address:e.owner,balance:e.quantity,percentage:n}}),totalSupply:s.toFixed(),totalHolders:o.length,lastUpdated:new Date}}async fetchTokenBadges(e){if(!e)throw z("tokenName","Token name");Ht(e);const t=await this.http.get(ln,{tokenName:e});if(!t)throw W("No response from pool service",500);return rn(t,"Failed to fetch token badges",!0),{volumeBadges:t.data.volumeBadge||[],engagementBadges:t.data.engagementBadge||[]}}async hasTokenBadge(e){const{tokenName:t,badgeType:n,badgeName:r}=e;try{const e=await this.fetchTokenBadges(t);if(!e)return!1;const o=("volume"===n?e.volumeBadges:e.engagementBadges).find(e=>e.badgeName===r);return o?.isActive||!1}catch{return!1}}async resolveTokenNameToVault(e){try{const t=await this.fetchPools({tokenName:e});if(t.pools&&Array.isArray(t.pools)&&t.pools.length>0)return t.pools[0].vaultAddress||null;if(t.pools&&"object"==typeof t.pools){const e=t.pools.tokens;return e?.vaultAddress||null}return null}catch{return null}}}function Cn(e,t={}){const{stringifyFields:n=[],optionalFields:r=[],fieldMappings:o={}}=t,i={};for(const[t,s]of Object.entries(e)){const e=t;if(r.includes(e)&&void 0===s)continue;if(r.includes(e)&&"string"==typeof s&&0===s.trim().length)continue;const a=o[e],c=a?String(a):t;n.includes(e)?i[c]=String(s):i[c]=s}return T(i)}const Pn={PAGINATION:{MIN_PAGE:1,MAX_PAGE:1e3,MIN_LIMIT:1,MAX_LIMIT:20}};class Nn extends vn{constructor(e,t=!1){super(e,t)}async fetchTrades(e){if(!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return Sn(t,"tokenName")&&(void 0===t.tradeType||"buy"===t.tradeType||"sell"===t.tradeType)&&Tn(t,"userAddress")&&An(t,"page")&&An(t,"limit")}(e))throw new x("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:o=kn.DEFAULT_PAGE,limit:i=kn.DEFAULT_LIMIT,startDate:s,endDate:a,sortOrder:c}=e;if(!Z(t))throw new x("Token name is required and must be a non-empty string","tokenName","INVALID_TOKEN_NAME");X(o,i,Pn);const u=function(e,t,n){return Cn({tokenName:e,page:t,limit:n},{stringifyFields:["page","limit"]})}(t,o,i),l=await this.http.get(hn,u);if(!l)throw new x("No response from trade service","response","NO_RESPONSE");const h=(d=l.data)?Array.isArray(d)?d:d.trades:[];var d;const f=tn(l,{page:o,limit:i}),p=nn(f.page,f.totalPages);return{trades:h,...f,...p}}}function _n(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 G("file","a File object (browser) or Buffer (Node.js)");{const o=new Blob([e],{type:"image/png"});r.append(t,o,n)}}return r}const Dn={PAGINATION:{MIN_PAGE:1,MAX_PAGE:1e3,MIN_LIMIT:1,MAX_LIMIT:20},USER_ADDRESS:{PATTERN:/^eth\|[0-9a-fA-F]{40}$/},TOKEN_NAME:{MIN_LENGTH:1,MAX_LENGTH:50},SEARCH:{MIN_LENGTH:1,MAX_LENGTH:100},PROFILE:{FULL_NAME:{MIN_LENGTH:1,MAX_LENGTH:100,ALPHABETS_ONLY_PATTERN:/^[a-zA-Z]+(?:\s[a-zA-Z]+)?$/}}};function Un(e){return!(!e||"string"!=typeof e)&&Dn.USER_ADDRESS.PATTERN.test(e)}const Rn="Update profile",Ln="Upload profile image";class On extends vn{constructor(e,t=!1){super(e,t)}async fetchProfile(e){const t=e??this.http.getAddress();if(!t||!Un(t))throw new x("Address must be in format: eth|[40-hex-chars]","address","INVALID_ADDRESS");const n={userAddress:t},r=await this.http.get(dn,n);if(!r)throw new x("No response from user service","response","NO_RESPONSE");return r}async updateProfile(e){this.validateUpdateProfileData(e);let t=e.profileImage;if(!t||""===t.trim())try{const n=await this.fetchProfile(e.address);t=n.data?.profileImage||""}catch{t=""}const n={profileImage:t,fullName:e.fullName,userAddress:e.address},r=await this.http.signCustomMessage(Rn);if(!r)throw new x("Failed to generate signature - wallet not configured","signature","NO_SIGNATURE");const o={address:r.address,message:Rn,publickey:r.ethereumAddress,sign:r.signature},i=await this.http.put(fn,n,o);if(!i)throw new x("No response from user service","response","NO_RESPONSE");rn(i,"Profile update failed")}async uploadProfileImage(e){this.validateUploadProfileImageOptions(e);const t=e.address??this.http.getAddress();if(!t)throw new x("Wallet address not available - wallet not configured","address","NO_WALLET");try{const n=`profile-image-${t}.png`,r=_n(e.file,"image",n),o=await this.http.signCustomMessage(Ln);if(!o)throw new x("Failed to generate signature - wallet not configured","signature","NO_SIGNATURE");const i={address:o.address,message:Ln,publickey:o.ethereumAddress,sign:o.signature},s=await this.http.request({method:"POST",url:`${on}?tokenName=${encodeURIComponent(t)}`,data:r,headers:i});if(!s)throw new x("No response from user service","response","NO_RESPONSE");return rn(s,"Image upload failed"),"string"==typeof s.data?s.data:""}catch(e){if(e instanceof x)throw e;throw new x(`Profile image upload failed: ${$(e)}`,"file","UPLOAD_FAILED")}}async fetchTokenList(e){return this.buildFetchRequest(pn,e,{includeType:!0,errorMessage:"Failed to fetch token list"})}async fetchTokensHeld(e){return this.buildFetchRequest(gn,e,{includeType:!1,errorMessage:"Failed to fetch tokens held"})}async fetchTokensCreated(e={}){const{page:t=kn.DEFAULT_PAGE,limit:n=kn.DEFAULT_LIMIT,search:r,tokenName:o}=e,i=this.http.getAddress();if(!i)throw new x("Wallet address not available - wallet not configured","address","NO_WALLET");const s={type:"DEFI",address:i,page:t,limit:n};return void 0!==r&&(s.search=r),void 0!==o&&(s.tokenName=o),this.fetchTokenList(s)}async buildFetchRequest(e,t,n){this.validateGetTokenListOptions(t);const r={page:t.page,limit:t.limit,address:t.address,search:t.search,tokenName:t.tokenName},o=Cn(n.includeType?{...r,type:"all"!==t.type&&t.type?t.type:"DEFI"}:r,{stringifyFields:["page","limit"],optionalFields:["address","search","tokenName"]}),i=await this.http.get(e,o);if(!i)throw new x("No response from user service","response","NO_RESPONSE");rn(i,n.errorMessage,!0);const s=(a=i.data)?Array.isArray(a)?a:a.token:[];var a;const c=tn(i,{page:t.page||kn.DEFAULT_PAGE,limit:t.limit||kn.DEFAULT_LIMIT}),u=nn(c.page,c.totalPages);return{tokens:s,...c,...u}}validateGetTokenListOptions(e){if(X(e.page,e.limit,Dn),void 0!==e.address&&!Un(e.address))throw new x("Address must be in format: eth|[40-hex-chars]","address","INVALID_ADDRESS");if(void 0!==e.search&&e.search.trim().length>0&&!((t=e.search)&&"string"==typeof t&&t.length>=Dn.SEARCH.MIN_LENGTH&&t.length<=Dn.SEARCH.MAX_LENGTH))throw new x(`Search query must be between ${Dn.SEARCH.MIN_LENGTH} and ${Dn.SEARCH.MAX_LENGTH} characters`,"search","INVALID_SEARCH");var t,n;if(void 0!==e.tokenName&&e.tokenName.trim().length>0&&!((n=e.tokenName)&&"string"==typeof n&&n.length>=Dn.TOKEN_NAME.MIN_LENGTH&&n.length<=Dn.TOKEN_NAME.MAX_LENGTH))throw new x(`Token name must be between ${Dn.TOKEN_NAME.MIN_LENGTH} and ${Dn.TOKEN_NAME.MAX_LENGTH} characters`,"tokenName","INVALID_TOKEN_NAME")}validateUpdateProfileData(e){if(!Un(e.address))throw new x("Address must be in format: eth|[40-hex-chars]","address","INVALID_ADDRESS");if(!((t=e.fullName)&&"string"==typeof t&&t.length>=Dn.PROFILE.FULL_NAME.MIN_LENGTH&&t.length<=Dn.PROFILE.FULL_NAME.MAX_LENGTH&&Dn.PROFILE.FULL_NAME.ALPHABETS_ONLY_PATTERN.test(t)))throw new x(`Full name must be between ${Dn.PROFILE.FULL_NAME.MIN_LENGTH} and ${Dn.PROFILE.FULL_NAME.MAX_LENGTH} characters`,"fullName","INVALID_FULL_NAME");var t}validateUploadProfileImageOptions(e){if(e.address&&!Un(e.address))throw new x("Address must be in format: eth|[40-hex-chars]","address","INVALID_ADDRESS")}}class Fn extends Error{constructor(e,t,n){super(e),this.filename=t,this.mimeType=n,this.name="FileValidationError"}}function Mn(e,t,n){if(!e)throw new Fn("File is required",t,n);if("undefined"!=typeof File&&e instanceof File){const t=qe.safeParse(e);if(!t.success){const n=t.error.errors.map(e=>e.message).join("; ");throw new Fn(n,e.name,e.type)}return}if(Buffer.isBuffer(e)){if(!t)throw new Fn("Filename is required when uploading Buffer objects",t,n);const r=Ke.safeParse(e);if(!r.success){const e=r.error.errors.map(e=>e.message).join("; ");throw new Fn(e,t,n)}if(t.length>255)throw new Fn(`Filename length ${t.length} exceeds maximum allowed length of 255 characters`,t,n);const o=["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"];if(!o.includes(n))throw new Fn(`Invalid file type "${n}" is not allowed. Allowed types: ${o.join(", ")}`,t,n);const i=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(i))throw new Fn(`File extension "${i}" 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"}}(i);if(a!==n&&"application/octet-stream"!==a)throw new Fn(`File extension "${i}" does not match MIME type "${n}"`,t,n);return}throw new Fn("File must be a File object (browser) or Buffer (Node.js)",t,n)}const $n="Upload token image";class qn extends vn{constructor(e,t=!1){super(e,t)}async uploadImageByTokenName(e){const{tokenName:t,options:n}=e;Ht(t);const r=`${t}.png`;Mn(n.file,r,"image/png");try{const e=`${n.tokenName??t}.png`,r=_n(n.file,"image",e),o=await this.http.signCustomMessage($n);if(!o)throw j("Failed to generate signature - wallet not configured","signature");const i={address:o.address,message:$n,publickey:o.ethereumAddress,sign:o.signature},s=await this.http.request({method:"POST",url:`${on}?tokenName=${encodeURIComponent(n.tokenName??t)}`,data:r,headers:i});if(!s)throw j("No response from image upload service","response");return rn(s,"Image upload failed"),"string"==typeof s.data?s.data:""}catch(e){if(e instanceof Error&&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}}}class Kn{constructor(e,t=!1){this.http=e,this.poolService=new xn(e,t),this.tradeService=new Nn(e,t),this.userService=new On(e,t),this.imageService=new qn(e,t)}async uploadImageByTokenName(e){return this.imageService.uploadImageByTokenName(e)}async fetchPools(e={}){return this.poolService.fetchPools(e)}async fetchAllPools(e){return this.poolService.fetchAllPools(e)}async checkPool(e){return this.poolService.checkPool(e)}async 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 fetchTokenBadges(e){return this.poolService.fetchTokenBadges(e)}async hasTokenBadge(e){return this.poolService.hasTokenBadge(e)}async fetchTrades(e){return this.tradeService.fetchTrades(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)}getAddress(){return this.http.getAddress()}validateTokenName(e){return Ht(e)}}const zn={MAX_UNIQUE_KEY_LENGTH:64,UNIQUE_KEY_PATTERN:/^(galaswap-operation-|galaconnect-operation-)/,TOKEN_NAME_PATTERN:/^[a-zA-Z0-9]+$/};var Gn;!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"}(Gn||(Gn={}));class Wn extends Error{constructor(e,t,n){super(e),this.type=t,this.details=n,this.name="TransferError"}}function jn(e,t="0"){return new i(null==e||""===e?t:e)}function Hn(e){return s.tickToSqrtPrice(e)}function Vn(e){const t=jn(e),n=Math.log(1.0001),r=t.toNumber();return Math.log(r)/n}function Xn(e,t=!1){const n=jn(e),r=new i(1).dividedBy(n);return t?r.toFixed():r}function Qn(...e){e.forEach((e,t)=>{if(e.isNaN())throw new Error(`Value at index ${t} must be a valid number, got: NaN`);if(!e.isFinite())throw new Error(`Value at index ${t} must be finite, got: ${e.toString()}`);if(e.isLessThan(0))throw new Error(`Value at index ${t} must be non-negative, got: ${e.toString()}`)})}function Zn(e,t,n){if(e.isNaN())throw new Error(`${t} must be a valid number, got: NaN`);if(!e.isFinite()){const r=n?`${t} must be finite ${n}, got: ${e.toString()}`:`${t} must be finite, got: ${e.toString()}`;throw new Error(r)}if(e.isLessThanOrEqualTo(0)){const r=n?`${t} must be positive ${n}, got: ${e.toString()}`:`${t} must be positive, got: ${e.toString()}`;throw new Error(r)}}class Yn{static validateAmount(e){const t=new i(e);try{Zn(t,"amount","for transfer")}catch(t){throw new Wn(t.message,Gn.INVALID_AMOUNT,{amount:e})}}static validateUniqueKey(e){if(e){if(e.length>zn.MAX_UNIQUE_KEY_LENGTH)throw new x(`Unique key too long. Maximum length: ${zn.MAX_UNIQUE_KEY_LENGTH}`);if(!zn.UNIQUE_KEY_PATTERN.test(e))throw new Wn('Invalid unique key format. Must start with "galaswap-operation-" or "galaconnect-operation-"',Gn.INVALID_AMOUNT,{uniqueKey:e})}}}class Jn{toLaunchpadFormat(e){if(!e)throw new x('Token is required. Use full tokenId format: "GALA|Unit|none|none"',"token","MISSING_TOKEN");if("string"==typeof e){if(e.includes("|"))return e;throw new x(`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`${e.collection||e.symbol||"unknown"}|${e.category||"Unit"}|${e.type||"none"}|${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=e.split("|");if(t.length<3)throw new Error(`Invalid token format: ${e}`);return{collection:t[0]||"Token",category:t[1]||"Unit",type:t[2]||"none",additionalKey:t[3]||"none"}}isGSwapFormat(e){return"string"==typeof e&&e.includes("|")}normalizeInternalApiResponse(e){return e?e.includes("|")?e:`${e}|Unit|none|none`:""}normalize(e){return"string"==typeof e&&this.isGSwapFormat(e)?e:this.toLaunchpadFormat(e)}}function er(e){if(!e||"string"!=typeof e)throw new Error("Invalid token format: token must be a non-empty string");return e.replace(/\|/g,"$")}function tr(e){try{if(!e||"string"!=typeof e)throw new Error("Token must be a non-empty string");const t=e.split("$");if(t.length<4)throw new Error(`Invalid dollar-delimited token format. Expected at least 4 parts separated by $, got ${t.length}`);const[n,r,o,...i]=t;if(!n||!r||!o)throw new Error("Collection, category, and type must be non-empty");const s=i.join("$");if(!s)throw new Error("AdditionalKey must be non-empty");return{collection:n,category:r,type:o,additionalKey:s}}catch(t){throw new x(`Invalid dollar-delimited token: "${e}". Expected format: "Token$Unit$SYMBOL$additionalKey". Error: ${t instanceof Error?t.message:String(t)}`,"dollarToken","INVALID_DOLLAR_DELIMITED_TOKEN_FORMAT")}}class nr extends r.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,o){let i;if("string"==typeof r){i={...tr(r),instance:"0"}}else i={collection:r.collection,category:r.category,type:r.type,additionalKey:r.additionalKey,instance:"0"};return new nr({from:e,to:t,quantity:n,tokenInstance:i,uniqueKey:o||`galaconnect-operation-${Date.now()}_${Math.random().toString(36).substring(2,8)}`})}static forGALA(e,t,n,r){return new nr({from:e,to:t,quantity:n,tokenInstance:{collection:"GALA",category:"Unit",type:"none",additionalKey:"none",instance:"0"},uniqueKey:r||`galaconnect-operation-${Date.now()}_${Math.random().toString(36).substring(2,8)}`})}getTokenClassKey(){return`${this.tokenInstance.collection}$${this.tokenInstance.category}$${this.tokenInstance.type}$${this.tokenInstance.additionalKey}`}toSigningPayload(){return{from:this.from,to:this.to,quantity:this.quantity,tokenInstance:this.tokenInstance,uniqueKey:this.uniqueKey}}}class rr extends r.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,o){let i;if("string"==typeof r){i={...tr(r),instance:"0"}}else i={collection:r.collection,category:r.category,type:r.type,additionalKey:r.additionalKey,instance:"0"};return new rr({lockAuthority:t||e,tokenInstances:[{owner:e,quantity:n,tokenInstanceKey:i}],...void 0!==o?.expires&&{expires:o.expires},...void 0!==o?.name&&{name:o.name},uniqueKey:o?.uniqueKey||`galaconnect-operation-${Date.now()}_${Math.random().toString(36).substring(2,8)}`})}static forGALA(e,t,n,r){return new rr({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||`galaconnect-operation-${Date.now()}_${Math.random().toString(36).substring(2,8)}`})}getTokenClassKey(){if(0===this.tokenInstances.length)return;const e=this.tokenInstances[0].tokenInstanceKey;return`${e.collection}$${e.category}$${e.type}$${e.additionalKey}`}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 or extends r.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 o;if("string"==typeof n){o={...tr(n),instance:"0"}}else o={collection:n.collection,category:n.category,type:n.type,additionalKey:n.additionalKey,instance:"0"};return new or({tokenInstances:[{owner:e,quantity:t,tokenInstanceKey:o}],...void 0!==r?.name&&{name:r.name},uniqueKey:r?.uniqueKey||`galaconnect-operation-${Date.now()}_${Math.random().toString(36).substring(2,8)}`})}static forGALA(e,t,n){return new or({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||`galaconnect-operation-${Date.now()}_${Math.random().toString(36).substring(2,8)}`})}getTokenClassKey(){if(0===this.tokenInstances.length)return;const e=this.tokenInstances[0].tokenInstanceKey;return`${e.collection}$${e.category}$${e.type}$${e.additionalKey}`}toSigningPayload(){return{tokenInstances:this.tokenInstances,...void 0!==this.name&&{name:this.name},uniqueKey:this.uniqueKey}}}class ir extends r.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={...tr(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 ir({tokenInstances:n,uniqueKey:t?.uniqueKey||`galaconnect-operation-${Date.now()}_${Math.random().toString(36).substring(2,8)}`})}static fromTokenClassKey(e,t,n){return ir.fromTokens([{tokenClassKey:t,quantity:e}],n)}static forGALA(e,t){return new ir({tokenInstances:[{quantity:e,tokenInstanceKey:{collection:"GALA",category:"Unit",type:"none",additionalKey:"none",instance:"0"}}],uniqueKey:t?.uniqueKey||`galaconnect-operation-${Date.now()}_${Math.random().toString(36).substring(2,8)}`})}getTokenClassKey(){if(0===this.tokenInstances.length)return;const e=this.tokenInstances[0].tokenInstanceKey;return`${e.collection}$${e.category}$${e.type}$${e.additionalKey}`}toSigningPayload(){return{tokenInstances:this.tokenInstances,uniqueKey:this.uniqueKey}}}class sr{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){const t=e.replace("0x","");return`eth|${n.ethers.getAddress(`0x${t}`).replace("0x","")}`}static fromGalaChainAddress(e){return e.startsWith("eth|")?e.substring(4):e}static createGALATokenInstance(){return{collection:"GALA",category:"Unit",type:"none",additionalKey:"none",instance:"0"}}static createTokenInstanceFromClassKey(e){return{...tr(e),instance:"0"}}}function ar(e){if("string"==typeof e){const t=e.split("|");if(t.length<4)throw new x(`Invalid tokenId string format: "${e}". Expected format: "collection|category|type|additionalKey" or "collection|category|type|additionalKey|instance"`,"tokenId","INVALID_TOKEN_ID_FORMAT");if(!(t[0]&&t[1]&&t[2]&&t[3]))throw new x(`Invalid tokenId string format: "${e}". All components (collection, category, type, additionalKey) must be non-empty`,"tokenId","INVALID_TOKEN_ID_FORMAT");return{collection:t[0],category:t[1],type:t[2],additionalKey:t[3],instance:t[4]||"0"}}if("object"==typeof e&&null!==e){if(!(e.collection&&e.category&&e.type&&e.additionalKey))throw new x("Invalid tokenId object format. All fields (collection, category, type, additionalKey) are required","tokenId","INVALID_TOKEN_ID_FORMAT");return"instance"in e&&void 0!==e.instance?e:{...e,instance:"0"}}throw new x(`Invalid tokenId type: ${typeof e}. Expected string, TokenClassKey, or TokenInstanceKey`,"tokenId","INVALID_TOKEN_ID_TYPE")}function cr(e){try{const[t,n]=e.split("|");if(!n)throw new Error("Missing token part after service");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}`);if(!(r[0]&&r[1]&&r[2]&&r[3]))throw new Error("All vault address components (collection, category, type, additionalKey) must be non-empty");const o=r.slice(3,-1),i=o.length>0?o.join("$"):r[3];return{collection:r[0],category:r[1],type:r[2],additionalKey:i}}catch(t){throw new x(`Invalid vault address: "${e}". Expected format: "service|Token$Unit$SYMBOL$additionalKey$launchpad". Error: ${t instanceof Error?t.message:String(t)}`,"vaultAddress","INVALID_VAULT_ADDRESS_FORMAT")}}function ur(e){return{...cr(e),instance:"0"}}function lr(e){return cr(e).type}function hr(e){const t=ar(e);return`${t.collection}|${t.category}|${t.type}|${t.additionalKey}`}var dr=Object.freeze({__proto__:null,extractTokenSymbolFromVault:lr,normalizeToTokenInstanceKey:ar,normalizeTokenIdToString:hr,parseVaultAddressToTokenClassKey:cr,parseVaultAddressToTokenInstance:ur});function fr(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.amount&&t.amount.trim().length>0&&(void 0!==t.tokenId||"string"==typeof t.tokenName&&t.tokenName.trim().length>0)&&(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 pr(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.amount&&t.amount.trim().length>0&&(void 0!==t.tokenId||"string"==typeof t.tokenName&&t.tokenName.trim().length>0)&&(void 0===t.name||"string"==typeof t.name)}function gr(e){if(!e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every(fr)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}function mr(e){if(!e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every(pr)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}const yr={MAX_UNIQUE_KEY_LENGTH:64,UNIQUE_KEY_PATTERN:/^(galaswap-operation-|galaconnect-operation-)/,TOKEN_NAME_PATTERN:/^[a-zA-Z0-9]+$/,ETH_ADDRESS_PATTERN:Q.ETH_ADDRESS,BACKEND_ADDRESS_PATTERN:Q.BACKEND_ADDRESS,MAX_LOCK_BATCH_SIZE:100,MAX_UNLOCK_BATCH_SIZE:100};var wr;e.LockErrorType=void 0,(wr=e.LockErrorType||(e.LockErrorType={})).TOKEN_NOT_FOUND="TOKEN_NOT_FOUND",wr.INVALID_AMOUNT="INVALID_AMOUNT",wr.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",wr.SIGNATURE_FAILED="SIGNATURE_FAILED",wr.NETWORK_ERROR="NETWORK_ERROR",wr.WALLET_REQUIRED="WALLET_REQUIRED",wr.VALIDATION_ERROR="VALIDATION_ERROR",wr.LOCK_NOT_FOUND="LOCK_NOT_FOUND",wr.LOCK_EXPIRED="LOCK_EXPIRED",wr.INSUFFICIENT_LOCKED_BALANCE="INSUFFICIENT_LOCKED_BALANCE",wr.NOT_LOCK_AUTHORITY="NOT_LOCK_AUTHORITY",wr.LOCK_NAME_MISMATCH="LOCK_NAME_MISMATCH";class br extends Error{constructor(e,t,n){super(e),this.type=t,this.details=n,this.name="LockError"}}function kr(e){if(!e||"object"!=typeof e)return!1;const t=e;return!(!("string"==typeof t.amount&&t.amount.trim().length>0&&(void 0!==t.tokenId||"string"==typeof t.tokenName&&t.tokenName.trim().length>0))||void 0!==t.lockAuthority&&"string"!=typeof t.lockAuthority||void 0!==t.expires&&"number"!=typeof t.expires||void 0!==t.name&&"string"!=typeof t.name||void 0!==t.uniqueKey&&"string"!=typeof t.uniqueKey)}function vr(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.amount&&t.amount.trim().length>0&&(void 0!==t.tokenId||"string"==typeof t.tokenName&&t.tokenName.trim().length>0)&&(void 0===t.name||"string"==typeof t.name)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)}function Er(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.amount&&t.amount.trim().length>0&&(void 0!==t.tokenId||"string"==typeof t.tokenName&&t.tokenName.trim().length>0)}function Sr(e){if(!e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every(Er)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}var Tr;e.BurnErrorType=void 0,(Tr=e.BurnErrorType||(e.BurnErrorType={})).TOKEN_NOT_FOUND="TOKEN_NOT_FOUND",Tr.INVALID_AMOUNT="INVALID_AMOUNT",Tr.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",Tr.SIGNATURE_FAILED="SIGNATURE_FAILED",Tr.NETWORK_ERROR="NETWORK_ERROR",Tr.WALLET_REQUIRED="WALLET_REQUIRED",Tr.VALIDATION_ERROR="VALIDATION_ERROR";class Ar extends Error{constructor(e,t,n){super(e),this.type=t,this.details=n,this.name="BurnError"}}const Ir="gala-transfer-successful",Br="token-transfer-successful",xr="token-locked-successfully",Cr="token-unlocked-successfully",Pr="transfer-successful-no-id",Nr=50,_r=100,Dr=100;function Ur(e){return e&&0!==e.length?e.reduce((e,t)=>i(e).plus(t.quantity).toString(),"0"):"0"}function Rr(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 Lr extends vn{constructor(e,t,n,r=!1,o){super(e,r),this.wallet=t,this.tokenResolver=n,this.publicAxios=o,this.signatureHelper=t?new sr(t):void 0}async fetchPoolDetails(e){this.validateFetchPoolDetailsData(e);const t=await this.http.post("/api/asset/launchpad-contract/FetchSaleDetails",e);if(!t)throw W("No response from GalaChain service",500);if(1!==t.Status)throw W(`Failed to fetch pool details: Status ${t.Status}`,t.Status);const n=t.Data.reverseBondingCurveConfiguration,r=n?.minFeePortion??"0",o=n?.maxFeePortion??"0",i=(await import("bignumber.js")).default,s=!new i(r).isZero()||!new i(o).isZero(),a=t.Data;return a.reverseBondingCurveMinFeePortion=r,a.reverseBondingCurveMaxFeePortion=o,a.hasReverseBondingCurveFee=s,a.isGraduated="Finished"===t.Data.saleStatus,delete a.reverseBondingCurveConfiguration,t}async fetchLaunchTokenFee(){const e=await this.http.post("/api/asset/launchpad-contract/FetchLaunchpadFeeAmount",{});if(!e)throw W("No response from GalaChain service",500);if(1!==e.Status)throw W(`Failed to fetch launch token fee: Status ${e.Status}`,e.Status);return e.Data.feeAmount}getChannelForCollection(e){return"MUSIC"===(e.startsWith("$")?e.slice(1).toUpperCase():e.toUpperCase())?"music":"asset"}validateFetchPoolDetailsData(e){if(!(t=e)||"object"!=typeof t||"string"!=typeof t.vaultAddress)throw new x("Invalid fetch pool details data: missing required fields","data","INVALID_TYPE");var t;if(!e.vaultAddress||"string"!=typeof e.vaultAddress)throw new x("Vault address is required and must be a string","vaultAddress","INVALID_VAULT_ADDRESS");if(!e.vaultAddress.startsWith("service|Token$Unit$"))throw new x("Vault address must be in service format: service|Token$Unit$...","vaultAddress","INVALID_VAULT_ADDRESS")}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;if(1!==r.Status||!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=`${o.collection}|${o.category}|${o.type}|${o.additionalKey}`,a={quantity:o.quantity,collection:o.collection,category:o.category,tokenId:s};if(o.inUseHolds?.length){const e=Rr(o.inUseHolds??[],t);e.length>0&&(a.inUseHolds=e,a.inUseQuantity=Ur(e))}if(o.lockedHolds?.length){const e=Rr(o.lockedHolds??[],t);e.length>0&&(a.lockedHolds=e,a.lockedQuantity=Ur(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 W(`Failed to fetch token balance from GalaChain: ${$(e)}`,void 0,M(e)?e:void 0)}}async fetchTokenClassFromChain(e){try{const t="string"==typeof e?ar(e):e,n={tokenClasses:[{collection:t.collection,category:t.category,type:t.type,additionalKey:t.additionalKey}]},r=(await this.publicAxios.post("/api/asset/token-contract/FetchTokenClasses",n)).data;if(1!==r.Status)throw W(`Failed to fetch token class from GalaChain: Status ${r.Status}${r.Message?` - ${r.Message}`:""}`,r.Status);if(!r.Data||0===r.Data.length)throw W(`Token not found on GalaChain: ${t.collection}|${t.category}|${t.type}|${t.additionalKey}`,404);return r.Data[0]}catch(e){if(q(e)&&404===e.response?.status)throw W("Token not found on GalaChain",404,M(e)?e:void 0);const t=$(e);if(t.includes("Token not found")||t.includes("Status"))throw e;throw W(`Failed to fetch token class from GalaChain: ${t}`,void 0,M(e)?e:void 0)}}async fetchTokenClassesWithSupply(e){try{if(!e||0===e.length)throw new x("tokenClasses array must not be empty");const t={tokenClasses:e},n=(await this.publicAxios.post("/api/asset/token-contract/FetchTokenClassesWithSupply",t)).data;if(1!==n.Status)throw W(`Failed to fetch token classes with supply from GalaChain: Status ${n.Status}${n.Message?` - ${n.Message}`:""}`,n.Status);if(!n.Data||0===n.Data.length)throw W("No token supply data found for requested token classes",404);return n.Data}catch(e){if(q(e)&&404===e.response?.status)throw W("Token supply data not found on GalaChain",404,M(e)?e:void 0);const t=$(e);if(t.includes("Token")||t.includes("Status")||t.includes("tokenClasses"))throw e;throw W(`Failed to fetch token classes with supply from GalaChain: ${t}`,void 0,M(e)?e:void 0)}}async transferGala(e){if(this.validateTransferGalaData(e),!this.wallet||!this.signatureHelper)throw new Wn("Wallet required for GALA transfer operations",Gn.WALLET_REQUIRED);try{const t=J(e.recipientAddress),n=J(this.wallet.address),r=nr.forGALA(n,t,e.amount,e.uniqueKey),o=await this.signatureHelper.signTransferToken(r.toSigningPayload()),i=new nr({...r.toSigningPayload(),signedPayload:o});this.logger.debug("[DEBUG] Full GALA Transfer Request Payload:",JSON.stringify(i,null,2));const s=await this.http.post("/api/asset/token-contract/TransferToken",i);if(!s)throw new Wn("No response from GalaChain transfer service",Gn.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 Wn("Wallet required for token transfer operations",Gn.WALLET_REQUIRED);try{const t=J(e.to),n=J(this.wallet.address);let r;if(e.tokenId)r=ar(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 Wn("Must provide either tokenId or tokenName for token identification",Gn.TOKEN_NOT_FOUND);r=await this.resolveTokenInstance(e.tokenName)}const o=new nr({from:n,to:t,quantity:e.amount,tokenInstance:r,uniqueKey:e.uniqueKey||`galaconnect-operation-${Date.now()}_${Math.random().toString(36).substring(2,8)}`}),i=await this.signatureHelper.signTransferToken(o.toSigningPayload()),s=new nr({...o.toSigningPayload(),signedPayload:i});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 Wn("No response from GalaChain transfer service",Gn.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 Wn)throw t;throw new Wn(`Failed to resolve token class key for '${e}': ${$(t)}`,Gn.TOKEN_NOT_FOUND,{tokenName:e})}}async lockTokens(t){if(this.validateLockTokensData(t),!this.wallet||!this.signatureHelper)throw new br("Wallet required for token lock operations",e.LockErrorType.WALLET_REQUIRED);try{const n=J(this.wallet.address),r=[],o=[];let i=n;const s=t.tokens.find(e=>e.lockAuthority);s?.lockAuthority&&(i=J(s.lockAuthority));const a=t.tokens.find(e=>void 0!==e.expires),c=t.tokens.find(e=>void 0!==e.name);for(const s of t.tokens){let t;if(s.tokenId)t=ar(s.tokenId),this.logger.debug("[DEBUG] Using provided tokenId:",s.tokenId);else{if(!s.tokenName)throw new br("Must provide either tokenId or tokenName for token identification",e.LockErrorType.TOKEN_NOT_FOUND);t=await this.resolveTokenInstance(s.tokenName)}r.push({owner:n,quantity:s.amount,tokenInstanceKey:t}),o.push({tokenClassKey:{collection:t.collection,category:t.category,type:t.type,additionalKey:t.additionalKey},quantity:s.amount,lockAuthority:s.lockAuthority?J(s.lockAuthority):i})}const u=new rr({lockAuthority:i,tokenInstances:r,...void 0!==a?.expires&&{expires:a.expires},...void 0!==c?.name&&{name:c.name},uniqueKey:t.uniqueKey||`galaconnect-operation-${Date.now()}_${Math.random().toString(36).substring(2,8)}`}),l=await this.signatureHelper.signLockToken(u.toSigningPayload()),h=new rr({...u.toSigningPayload(),signedPayload:l});this.logger.debug("[DEBUG] Full Lock Request Payload:",JSON.stringify(h,null,2));const d=await this.http.post("/api/asset/token-contract/LockTokens",h);if(!d)throw new br("No response from GalaChain lock service",e.LockErrorType.NETWORK_ERROR);if(1!==d.Status)throw new br(`Token lock failed: ${d.Message||`Status ${d.Status}`}`,e.LockErrorType.NETWORK_ERROR);return this.logger.debug("[DEBUG] Token lock response:",JSON.stringify(d,null,2)),this.extractLockResult(d,o)}catch(e){throw this.handleLockError(e,"Token lock failed",t)}}async unlockTokens(t){if(this.validateUnlockTokensData(t),!this.wallet||!this.signatureHelper)throw new br("Wallet required for token unlock operations",e.LockErrorType.WALLET_REQUIRED);try{const n=J(this.wallet.address),r=[],o=[],i=t.tokens.find(e=>void 0!==e.name);for(const i of t.tokens){let t;if(i.tokenId)t=ar(i.tokenId),this.logger.debug("[DEBUG] Using provided tokenId:",i.tokenId);else{if(!i.tokenName)throw new br("Must provide either tokenId or tokenName for token identification",e.LockErrorType.TOKEN_NOT_FOUND);t=await this.resolveTokenInstance(i.tokenName)}r.push({owner:n,quantity:i.amount,tokenInstanceKey:t}),o.push({tokenClassKey:{collection:t.collection,category:t.category,type:t.type,additionalKey:t.additionalKey},quantity:i.amount})}const s=new or({tokenInstances:r,...void 0!==i?.name&&{name:i.name},uniqueKey:t.uniqueKey||`galaconnect-operation-${Date.now()}_${Math.random().toString(36).substring(2,8)}`}),a=await this.signatureHelper.signUnlockToken(s.toSigningPayload()),c=new or({...s.toSigningPayload(),signedPayload:a});this.logger.debug("[DEBUG] Full Unlock Request Payload:",JSON.stringify(c,null,2));const u=await this.http.post("/api/asset/token-contract/UnlockTokens",c);if(!u)throw new br("No response from GalaChain unlock service",e.LockErrorType.NETWORK_ERROR);if(1!==u.Status)throw new br(`Token unlock failed: ${u.Message||`Status ${u.Status}`}`,e.LockErrorType.NETWORK_ERROR);return this.logger.debug("[DEBUG] Token unlock response:",JSON.stringify(u,null,2)),this.extractUnlockResult(u,o)}catch(e){throw this.handleLockError(e,"Token unlock failed",t)}}async burnTokens(t){if(this.validateBurnTokensData(t),!this.wallet||!this.signatureHelper)throw new Ar("Wallet required for token burn operations",e.BurnErrorType.WALLET_REQUIRED);try{const n=[];for(const r of t.tokens){let t;if(r.tokenId)t=ar(r.tokenId),this.logger.debug("[DEBUG] Using provided tokenId:",r.tokenId);else{if(!r.tokenName)throw new Ar("Must provide either tokenId or tokenName for token identification",e.BurnErrorType.TOKEN_NOT_FOUND);t=await this.resolveTokenInstance(r.tokenName)}n.push({quantity:r.amount,tokenInstanceKey:t})}const r=new ir({tokenInstances:n,uniqueKey:t.uniqueKey||`galaconnect-operation-${Date.now()}_${Math.random().toString(36).substring(2,8)}`}),o=await this.signatureHelper.signBurnTokens(r.toSigningPayload()),i=new ir({...r.toSigningPayload(),signedPayload:o});this.logger.debug("[DEBUG] Full Burn Request Payload:",JSON.stringify(i,null,2));const s=await this.http.post("/api/asset/token-contract/BurnTokens",i);if(!s)throw new Ar("No response from GalaChain burn service",e.BurnErrorType.NETWORK_ERROR);if(1!==s.Status)throw new Ar(`Token burn failed: ${s.Message||`Status ${s.Status}`}`,e.BurnErrorType.NETWORK_ERROR);return this.logger.debug("[DEBUG] Token burn response:",JSON.stringify(s,null,2)),this.extractBurnResult(s)}catch(e){throw this.handleBurnError(e,"Token burn failed",t)}}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}}validateBurnTokensData(t){if(!Sr(t))throw new Ar("Invalid burn data: missing required fields",e.BurnErrorType.VALIDATION_ERROR);if(t.tokens.length>Nr)throw new Ar(`Batch size exceeds maximum limit of ${Nr} tokens per burn operation`,e.BurnErrorType.VALIDATION_ERROR);for(const n of t.tokens){if(!n.tokenId&&!n.tokenName)throw new Ar("Must provide either tokenId or tokenName for token identification",e.BurnErrorType.TOKEN_NOT_FOUND);const t=new i(n.amount);if(t.isNaN()||t.lte(0))throw new Ar("Burn amount must be a positive number",e.BurnErrorType.INVALID_AMOUNT,{amount:n.amount})}}handleBurnError(t,n,r){if(t instanceof Ar)return t;let o=n,i=e.BurnErrorType.NETWORK_ERROR;if(q(t)){const r=t.response?.data;if("object"==typeof r&&null!==r){const t=r;t.Message&&"string"==typeof t.Message&&(o=`${n}: ${t.Message}`);const s=String(t.Message||"").toLowerCase();s.includes("insufficient")||s.includes("balance")?i=e.BurnErrorType.INSUFFICIENT_BALANCE:(s.includes("not found")||s.includes("token"))&&(i=e.BurnErrorType.TOKEN_NOT_FOUND)}}else M(t)&&(o=`${n}: ${t.message}`);const s={};return void 0!==r?.tokens?.[0]?.tokenName&&(s.tokenName=r.tokens[0].tokenName),void 0!==r?.tokens?.[0]?.amount&&(s.amount=r.tokens[0].amount),new Ar(o,i,Object.keys(s).length>0?s:void 0)}validateLockTokensData(t){if(!gr(t))throw new br("Invalid lock data: missing required fields",e.LockErrorType.VALIDATION_ERROR);if(t.tokens.length>_r)throw new br(`Batch size exceeds maximum limit of ${_r} tokens per lock operation`,e.LockErrorType.VALIDATION_ERROR);for(const n of t.tokens){if(!n.tokenId&&!n.tokenName)throw new br("Must provide either tokenId or tokenName for token identification",e.LockErrorType.TOKEN_NOT_FOUND);if(n.tokenName&&!zn.TOKEN_NAME_PATTERN.test(n.tokenName))throw new br("Invalid token name format",e.LockErrorType.TOKEN_NOT_FOUND,{tokenName:n.tokenName});const t=new i(n.amount);if(t.isNaN()||t.lte(0))throw new br("Lock amount must be a positive number",e.LockErrorType.INVALID_AMOUNT,{amount:n.amount});if(n.lockAuthority&&!Y(n.lockAuthority))throw new br("Invalid lock authority address format",e.LockErrorType.VALIDATION_ERROR,{lockAuthority:n.lockAuthority});if(void 0!==n.expires&&(n.expires<=0||!Number.isInteger(n.expires)))throw new br("Expires must be a positive integer (epoch milliseconds)",e.LockErrorType.VALIDATION_ERROR)}}validateUnlockTokensData(t){if(!mr(t))throw new br("Invalid unlock data: missing required fields",e.LockErrorType.VALIDATION_ERROR);if(t.tokens.length>Dr)throw new br(`Batch size exceeds maximum limit of ${Dr} tokens per unlock operation`,e.LockErrorType.VALIDATION_ERROR);for(const n of t.tokens){if(!n.tokenId&&!n.tokenName)throw new br("Must provide either tokenId or tokenName for token identification",e.LockErrorType.TOKEN_NOT_FOUND);if(n.tokenName&&!zn.TOKEN_NAME_PATTERN.test(n.tokenName))throw new br("Invalid token name format",e.LockErrorType.TOKEN_NOT_FOUND,{tokenName:n.tokenName});const t=new i(n.amount);if(t.isNaN()||t.lte(0))throw new br("Unlock amount must be a positive number",e.LockErrorType.INVALID_AMOUNT,{amount:n.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(t,n,r){if(t instanceof br)return t;let o=n,i=e.LockErrorType.NETWORK_ERROR;if(q(t)){const r=t.response?.data;if("object"==typeof r&&null!==r){const t=r;t.Message&&"string"==typeof t.Message&&(o=`${n}: ${t.Message}`);const s=String(t.Message||"").toLowerCase();s.includes("insufficient")||s.includes("balance")?i=e.LockErrorType.INSUFFICIENT_BALANCE:s.includes("lock")&&s.includes("not found")?i=e.LockErrorType.LOCK_NOT_FOUND:s.includes("not found")||s.includes("token")?i=e.LockErrorType.TOKEN_NOT_FOUND:s.includes("authority")?i=e.LockErrorType.NOT_LOCK_AUTHORITY:s.includes("expired")&&(i=e.LockErrorType.LOCK_EXPIRED)}}else M(t)&&(o=`${n}: ${t.message}`);const s={};return void 0!==r?.tokens?.[0]?.tokenName&&(s.tokenName=r.tokens[0].tokenName),void 0!==r?.tokens?.[0]?.amount&&(s.amount=r.tokens[0].amount),new br(o,i,Object.keys(s).length>0?s:void 0)}validateTransferGalaData(e){if(!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.recipientAddress&&t.recipientAddress.trim().length>0&&"string"==typeof t.amount&&t.amount.trim().length>0&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)}(e))throw new x("Invalid GALA transfer data: missing required fields");if(!Y(e.recipientAddress))throw new Wn("Invalid recipient address format",Gn.INVALID_RECIPIENT,{recipientAddress:e.recipientAddress});Yn.validateAmount(e.amount),Yn.validateUniqueKey(e.uniqueKey)}validateTransferTokenData(e){if(!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.to&&t.to.trim().length>0&&"string"==typeof t.amount&&t.amount.trim().length>0&&(void 0!==t.tokenId||"string"==typeof t.tokenName&&t.tokenName.trim().length>0)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)}(e))throw new x("Invalid token transfer data: missing required fields");if(!Y(e.to))throw new Wn("Invalid recipient address format",Gn.INVALID_RECIPIENT,{recipientAddress:e.to});if(!e.tokenId&&!e.tokenName)throw new Wn("Must provide either tokenId or tokenName for token identification",Gn.TOKEN_NOT_FOUND);if(e.tokenName&&!zn.TOKEN_NAME_PATTERN.test(e.tokenName))throw new Wn("Invalid token name format",Gn.TOKEN_NOT_FOUND,{tokenName:e.tokenName});Yn.validateAmount(e.amount),Yn.validateUniqueKey(e.uniqueKey)}validateLockTokenData(e){if(!kr(e))throw new x("Invalid lock token data: missing required fields");if(e.lockAuthority&&!Y(e.lockAuthority))throw new Wn("Invalid lock authority address format",Gn.INVALID_RECIPIENT,{recipientAddress:e.lockAuthority});if(!e.tokenId&&!e.tokenName)throw new Wn("Must provide either tokenId or tokenName for token identification",Gn.TOKEN_NOT_FOUND);if(e.tokenName&&!zn.TOKEN_NAME_PATTERN.test(e.tokenName))throw new Wn("Invalid token name format",Gn.TOKEN_NOT_FOUND,{tokenName:e.tokenName});if(void 0!==e.expires&&(e.expires<=0||!Number.isInteger(e.expires)))throw new x("Expires must be a positive integer (epoch milliseconds)");Yn.validateAmount(e.amount),Yn.validateUniqueKey(e.uniqueKey)}validateUnlockTokenData(e){if(!vr(e))throw new x("Invalid unlock token data: missing required fields");if(!e.tokenId&&!e.tokenName)throw new Wn("Must provide either tokenId or tokenName for token identification",Gn.TOKEN_NOT_FOUND);if(e.tokenName&&!zn.TOKEN_NAME_PATTERN.test(e.tokenName))throw new Wn("Invalid token name format",Gn.TOKEN_NOT_FOUND,{tokenName:e.tokenName});Yn.validateAmount(e.amount),Yn.validateUniqueKey(e.uniqueKey)}async resolveTokenInstance(e){try{const t=await this.tokenResolver.resolveTokenToVault(e);if(t){const n=this.resolveTokenInstanceFromVaultAddress(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:e.trim().toUpperCase(),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 Wn)throw t;throw new Wn(`Failed to resolve token '${e}': ${$(t)}`,Gn.TOKEN_NOT_FOUND,{tokenName:e})}}resolveTokenInstanceFromVaultAddress(e){try{return ur(e)}catch(e){if(e instanceof x)throw new Wn(`Invalid vault address format: ${e.message}`,Gn.TOKEN_NOT_FOUND);throw new Wn(`Failed to parse vault address: ${e instanceof Error?e.message:String(e)}`,Gn.TOKEN_NOT_FOUND)}}extractTransactionIdFromResponse(e,t){if(e&&"object"==typeof e){if("Status"in e&&1===e.Status&&"Data"in e){const n=e;if(Array.isArray(n.Data)&&n.Data.length>0)switch(t){case"gala":return Ir;case"token":return Br;case"lock":return xr;case"unlock":return Cr}return Pr}if("transactionId"in e&&"string"==typeof e.transactionId&&e.transactionId)return e.transactionId}throw new Wn("Operation succeeded but transaction ID could not be extracted",Gn.NETWORK_ERROR)}handleTransferError(e,t,n){if(e instanceof Wn)return e;if(e instanceof x)return new Wn(e.message,Gn.INVALID_AMOUNT);if(q(e)&&e.response){const t=e.response.status,r=e.response.data;if(400===t)return new Wn(("string"==typeof r?.message?r.message:void 0)||"Invalid transfer request",Gn.INVALID_AMOUNT);if(403===t)return new Wn("Insufficient balance for transfer",Gn.INSUFFICIENT_BALANCE);if(404===t){const e={};return"tokenName"in n&&(e.tokenName=n.tokenName),new Wn("Token not found",Gn.TOKEN_NOT_FOUND,e)}}if("object"==typeof e&&null!==e&&"code"in e&&("ECONNABORTED"===e.code||"ETIMEDOUT"===e.code))return new Wn("Transfer request timed out",Gn.NETWORK_ERROR);const r=$(e);return new Wn(r||t,Gn.NETWORK_ERROR)}}class Or{constructor(e,t,n,r=!1){this.dexBackendHttp=e,this.cache=t,this.galaChainService=n,this.logger=new S({debug:r,context:"DexService"})}async fetchTokenPrice(e){const{tokenName:t,tokenId:n}=e;if(!t&&!n)throw z("tokenName or tokenId","Either tokenName (for launchpad tokens) or tokenId (for DEX tokens) is required");if(t&&n)throw new x("tokenName and tokenId are mutually exclusive - provide only one","params","INVALID_PARAMS");if(n)return this.logger.debug(`Fetching spot price by tokenId: ${n}`),this._fetchDexTokenSpotPrice(n);throw new x("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=ar(e),n=er(`${t.collection}|${t.category}|${t.type}|${t.additionalKey}`);if(this.logger.debug(`Fetching DEX spot price for token: ${n}`),!this.dexBackendHttp)throw W("DEX Backend API client not configured");const r=await this.dexBackendHttp.request({method:"GET",url:"/v1/trade/price",params:{token:n}});if(!r.data||"string"!=typeof r.data)throw new x("Invalid price response: data must be a string, got "+typeof r.data,"data","INVALID_RESPONSE");const o=parseFloat(r.data);if(isNaN(o))throw new x(`Invalid price value: could not parse "${r.data}" as number`,"data","INVALID_CALCULATION");const i=`${t.collection}|${t.category}|${t.type}|${t.additionalKey}`;let s;try{if(this.cache){const e=this.cache.getByTokenId(i);if(e?.symbol)return s=e.symbol,this.logger.debug(`DEX spot price for ${s} (cached): $${o}`),{symbol:s,price:o}}this.logger.debug(`Symbol cache miss for ${i}, fetching from API`);s=(await this.fetchTokenDetails(e)).symbol,this.cache&&(this.cache.setByTokenId(i,{symbol:s}),this.logger.debug(`Cached symbol for ${i}: ${s}`)),this.logger.debug(`DEX spot price for ${s}: $${o}`)}catch(e){this.logger.debug(`Could not fetch token details for symbol, falling back to token format parsing: ${e instanceof Error?e.message:String(e)}`),s=("Token"===t.collection?t.type:t.collection).toUpperCase(),this.logger.debug(`DEX spot price for ${s} (fallback): $${o}`)}return{symbol:s,price:o}}catch(e){if(e instanceof x)throw e;throw W(`Failed to fetch DEX spot price: ${$(e)}`)}}async fetchLaunchpadTokenSpotPrice(e,t,n){if(!e||"string"!=typeof e)throw new Error(I);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=`${t.sellingToken.collection}|${t.sellingToken.category}|${t.sellingToken.type}|${t.sellingToken.additionalKey}`;return this._fetchDexTokenSpotPrice(n)}}catch(t){this.logger.debug(`Could not determine graduation status for ${e}, falling back to bonding curve: ${$(t)}`)}this.logger.debug(`Using bonding curve calculation for token: ${e}`);const r=await t({tokenName:e,amount:"1",type:"native"}),o=await this._fetchDexTokenSpotPrice({collection:"GALA",category:"Unit",type:"none",additionalKey:"none"});if(!o)throw W("GALA price not available");const i=Number(r.amount)/1e18;if(i<=0)throw new x(`Invalid token amount calculation: ${i}`,"amount","INVALID_CALCULATION");const s=o.price/i;return{symbol:e.toUpperCase(),price:s}}catch(t){if(t instanceof Error)throw W(`Failed to calculate launchpad token spot price for ${e}: ${t.message}`);throw W(`Failed to calculate launchpad token spot price for ${e}: ${$(t)}`)}}async fetchTokenDetails(e){this.logger.debug("Fetching token details from GalaChain for tokenId:",e);try{if(!this.galaChainService)throw W("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 x||t instanceof Error)&&("NetworkError"===t.name||t.message.includes("Token not found")))throw t;throw W(`Failed to fetch token details from GalaChain for ${e}: ${$(t)}`,500)}}async fetchAllDexSeasons(){try{if(!this.dexBackendHttp)throw W("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),[];if(Array.isArray(e.data))t=e.data;else if(e.data&&Array.isArray(e.data.seasons))t=e.data.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:e?.start?new Date(e.start):new Date,end:e?.end?new Date(e.end):new Date,rulesId:e?.rules_id??0}));return this.logger.debug(`Fetched ${n.length} DEX seasons`),n}catch(e){if(e instanceof Error&&e.message.includes("not configured"))throw e;if(e&&"object"==typeof e&&"response"in e){const t=e;if(404===t.response?.status)return this.logger.warn("Seasons endpoint not available"),[]}throw W(`Failed to fetch DEX seasons: ${$(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){if(!e||"number"!=typeof e||e<1)throw z("seasonId","Season ID must be a positive number");try{if(!this.dexBackendHttp)throw W("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};if(t.data&&Array.isArray(t.data.leaderboard))n=t.data.leaderboard;else if(Array.isArray(t.leaderboard))n=t.leaderboard;else{if(!t.data||!Array.isArray(t.data))return this.logger.warn("Leaderboard endpoint returned unexpected structure:",t),{entries:[],seasonId:e,totalEntries:0};n=t.data}}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(t instanceof Error&&t.message.includes("must be a positive number"))throw t;throw W(`Failed to fetch DEX leaderboard for season ${e}: ${$(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 W("DEX Backend API client not configured");const e=await this.dexBackendHttp.request({method:"GET",url:"/explore/volume"}),t={volume1d:e.data.volume1d,volume1dDelta:e.data.volume1dDelta,volume7d:e.data.volume7d,volume7dDelta:e.data.volume7dDelta,volume30d:e.data.volume30d,volume30dDelta:e.data.volume30dDelta};return this.logger.debug(`Fetched DEX volume summary: $${t.volume1d.toFixed(2)} (1d)`),t}catch(e){throw W(`Failed to fetch DEX volume summary: ${$(e)}`)}}}function Fr(e,t=18){const n=parseFloat(e);if(0===n)return"0";return n.toFixed(t).replace(/\.?0+$/,"")}function Mr(e){return Fr(e,8)}function $r(e){return Fr(e,18)}function qr(e){return{maxAcceptableReverseBondingCurveFee:Mr(e.maxAcceptableReverseBondingCurveFee)}}new S({debug:!1,context:"NumberUtils"});class Kr extends r.ChainCallDTO{constructor(e,t,n="0",r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=Mr(t),this.expectedToken=$r(n),this.extraFees=qr(r)}}class zr extends r.ChainCallDTO{constructor(e,t,n,r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=$r(t),this.expectedNativeToken=Mr(n),this.extraFees=qr(r)}}class Gr extends r.ChainCallDTO{constructor(e,t,n="0",r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=$r(t),this.expectedNativeToken=Mr(n),this.extraFees=qr(r)}}class Wr extends r.ChainCallDTO{constructor(e,t,n,r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=Mr(t),this.expectedToken=$r(n),this.extraFees=qr(r)}}const jr={BuyNativeDto:Kr,BuyExactDto:zr,SellExactDto:Gr,SellNativeDto:Wr};class Hr extends En{constructor(e,t=!1){super(t),this.walletProvider=e}async signDTO(e,t,n){try{this.logger.debug("🔐 Signing DTO:",{methodName:t,dtoKeys:Object.keys(e)});const n=this.generateEIP712Types(t,e),o=r.calculatePersonalSignPrefix(e),i={...e,prefix:o},{signature:s,domain:a}=await this.signWithEthersWallet(n,i),c={...e,signature:s,types:n,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 H(`Failed to sign DTO: ${$(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 o=await this.walletProvider.getNetwork();n={name:o.name,chainId:Number(o.chainId)},r=await this.walletProvider.signTypedData(n,e,t)}}return{signature:r,domain:n}}catch(e){throw H(`Ethers.js signing failed: ${$(e)}`)}}generateEIP712Types(e,t){const n={};n[e]=[];const r=Object.fromEntries(Object.entries(t).filter(([e,t])=>void 0!==t)),o=(e,t,r,i=!1)=>{if(void 0!==t){if(Array.isArray(t)){if(0===t.length)return;const s=o(e,t[0],r,!0);return i||n[r].push({name:e,type:(s??e)+"[]"}),s?s+"[]":void 0}if("object"==typeof t&&null!==t){if(n[e])throw new x(`Type name collision not supported: ${e}`,"fieldValue","TYPE_COLLISION");return n[e]=[],Object.entries(t).forEach(([t,n])=>{o(t,n,e)}),i||n[r].push({name:e,type:e}),e}{let o;switch(typeof t){case"string":o="string";break;case"number":o="uint256";break;case"boolean":o="bool";break;default:throw new x(`Unsupported type for field "${e}": ${typeof t} (value: ${JSON.stringify(t)})`,"fieldValue","UNSUPPORTED_TYPE")}return i||n[r].push({name:e,type:o}),o}}};return Object.entries(r).forEach(([t,n])=>{o(t,n,e)}),this.logger.debug("📝 Generated EIP-712 types:",n),n}}class Vr extends En{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(),o=`$service$${n.toStringKey()}$launchpad`,i=`$tokenBalance$${n.toStringKey()}$${e}`,s=`$tokenBalance$${n.toStringKey()}$${e}`,a=`$tokenBalance$${r.toStringKey()}$${e}`,c=[o,i,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=$(e);throw new x(`Failed to generate stringsInstructions: ${t}`,"vaultAddress","INVALID_VAULT_ADDRESS")}}createTokenInstance(e){const t=new a.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 a.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(!e||"string"!=typeof e)throw z("vaultAddress","Vault address");try{const t=lr(e);return this.logger.debug("🔍 Extracted token symbol:",{vaultAddress:e,tokenSymbol:t}),t}catch(e){if(e instanceof x)throw G("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad");throw e}}validateVaultAddress(e){if(!e||"string"!=typeof e)throw z("vaultAddress","Vault address");if(!e.startsWith("service|Token$Unit$"))throw G("vaultAddress",'starting with "service|Token$Unit$"');if(!e.endsWith("$launchpad"))throw G("vaultAddress",'ending with "$launchpad"');const t=e.split("$");if(t.length<5)throw G("vaultAddress",'having at least 5 parts separated by "$"');const n=t[2];if(!n||!/^[A-Za-z]{1,10}$/.test(n))throw G("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 tr(e)}catch(e){if(e instanceof x)throw G("stringKey","format: collection$category$type$additionalKey (4 parts)");throw e}}}function Xr(e,t,n){if(t<0||t>1)throw new Error(`Invalid slippage tolerance factor: ${t}. Must be between 0 and 1 (e.g., 0.05 for 5%)`);const r=new i(e);if(r.isNaN())throw new Error(`Invalid expected amount: ${e}. Must be a valid number`);if(0===t)return e;const o=r.multipliedBy(t);let s;switch(n){case"buy-native":case"sell-exact":s=r.minus(o);break;case"buy-exact":case"sell-native":s=r.plus(o);break;default:throw new Error(`Unknown operation type: ${n}`)}return s.isLessThan(0)&&(s=new i(0)),s.toFixed()}class Qr extends vn{constructor(e,t,n=!1,r,o,i=.05,s=.01){super(e,n),this.tokenResolver=t,this.walletProvider=r,this.userAddress=o,this.defaultSlippageToleranceFactor=i,this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor=s,this.bundleEndpoint="/bundle",r&&o&&(this.signatureService=new Hr(r,n),this.tokenKeyService=new Vr(n))}async submitTransaction(e){try{this.logger.debug("📦 Submitting bundle transaction:",{method:e.method,stringsInstructionsCount:e.stringsInstructions.length,signedDtoKeys:Object.keys(e.signedDto)}),this.validateBundleData(e);const t=this.formatBundleRequest(e);this.logger.debug("🚀 Bundle request payload:",{...t,signedDto:"[REDACTED - Contains signature]"});const n=await this.http.post(this.bundleEndpoint,t);return n?(this.logger.debug("📥 Bundle API response:",{success:n.success,hasData:!!n.data,error:n.error}),this.handleBundleResponse(n)):{success:!1,error:"No response from bundle API"}}catch(e){return this.logger.error("❌ Bundle transaction submission failed:",e),{success:!1,error:this.formatErrorMessage(e)}}}validateBundleData(e){if(!e)throw z("bundleData","Bundle data");if(!e.signedDto)throw z("signedDto","Signed DTO");if(!e.method||"string"!=typeof e.method)throw z("method","Method name");if(!Array.isArray(e.stringsInstructions))throw G("stringsInstructions","an array of resource tracking strings");if(0===e.stringsInstructions.length)throw new x("stringsInstructions cannot be empty","stringsInstructions","EMPTY_ARRAY");const t=["BuyWithNative","BuyExactToken","SellExactToken","SellWithNative"];if(!t.includes(e.method))throw G("method",`one of: ${t.join(", ")}`);e.stringsInstructions.forEach((e,t)=>{if("string"!=typeof e||0===e.length)throw new x(`stringsInstructions[${t}] must be a non-empty string`,`stringsInstructions[${t}]`,"INVALID_INSTRUCTION");if(!e.startsWith("$"))throw new x(`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){if(e.data&&!1===e.error)return this.logger.debug("✅ Bundle transaction successful:",e.data),{success:!0,data:e.data};const t=e.error||e.message||"Bundle transaction failed";return this.logger.debug("❌ Bundle transaction failed:",t),{success:!1,error:t}}formatErrorMessage(e){if("string"==typeof e)return e;if(q(e)&&e.response){const t=e.response.data;if(t&&"object"==typeof t){const e=t;if(e.error)return String(e.error);if(e.message)return String(e.message)}}return $(e)||"Unknown bundle transaction error"}async getBundlerTransactionResult(e){try{if(!e||"string"!=typeof e)throw z("transactionId","Transaction ID");this.logger.debug("🔍 Checking bundler transaction result:",e);const t=await this.http.get(`${this.bundleEndpoint}?id=${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){return this.logger.error("❌ Failed to get bundler transaction result:",e),{success:!1,error:this.formatErrorMessage(e)}}}async cancelTransaction(e){try{if(!e||"string"!=typeof e)throw z("transactionId","Transaction ID");this.logger.debug("🚫 Cancelling transaction:",e);const t=await this.http.delete(`${this.bundleEndpoint}/${e}`);return t?(this.logger.debug("🗑️ Transaction cancellation response:",t),{success:!0,data:t}):{success:!1,error:"No response from transaction cancellation"}}catch(e){return this.logger.error("❌ Failed to cancel transaction:",e),{success:!1,error:this.formatErrorMessage(e)}}}async getHealthStatus(){try{this.logger.debug("🏥 Checking bundle service health");const e=await this.http.get(`${this.bundleEndpoint}/health`);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 this.logger.error("❌ Bundle service health check failed:",e),{success:!1,error:this.formatErrorMessage(e)}}}async buyToken(e){this.ensureTradingServicesAvailable();const{tokenName:t,amount:n,type:r,expectedAmount:o}=e,{effectiveSlippageFactor:i,effectiveMaxFee:s,vaultAddress:a}=await this.prepareTradingOperation(t,e.maxAcceptableReverseBondingCurveFee,e.maxAcceptableReverseBondingCurveFeeSlippageFactor,e.slippageToleranceFactor);if("native"===r){if(!o)throw new x("expectedAmount is required for native buy operations. Use getBuyTokenAmount() first to calculate expected tokens.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Xr(o,i,"buy-native");this.logger.debug("BuyNative slippage applied:",{originalExpectedTokens:o,slippageFactor:i,adjustedMinTokens:e});const t=new jr.BuyNativeDto(a,n,e,{maxAcceptableReverseBondingCurveFee:s});return await this.executeBundleTransaction(t,"BuyWithNative",a)}{if(!o)throw new x("expectedAmount is required for exact buy operations. Use getBuyTokenAmount() first to calculate expected GALA cost.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Xr(o,i,"buy-exact");this.logger.debug("BuyExact slippage applied:",{originalExpectedGalaCost:o,slippageFactor:i,adjustedMaxGalaCost:e});const t=new jr.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:o}=e,{effectiveSlippageFactor:i,effectiveMaxFee:s,vaultAddress:a}=await this.prepareTradingOperation(t,e.maxAcceptableReverseBondingCurveFee,e.maxAcceptableReverseBondingCurveFeeSlippageFactor,e.slippageToleranceFactor);if("exact"===r){if(!o)throw new x("expectedAmount is required for exact sell operations. Use getSellTokenAmount() first to calculate expected GALA.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Xr(o,i,"sell-exact");this.logger.debug("SellExact slippage applied:",{originalExpectedGala:o,slippageFactor:i,adjustedMinGala:e});const t=new jr.SellExactDto(a,n,e,{maxAcceptableReverseBondingCurveFee:s});return await this.executeBundleTransaction(t,"SellExactToken",a)}{if(!o)throw new x("expectedAmount is required for native sell operations. Use getSellTokenAmount() first to calculate tokens to sell.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Xr(o,i,"sell-native");this.logger.debug("SellNative slippage applied:",{originalExpectedTokensToSell:o,slippageFactor:i,adjustedMaxTokensToSell:e});const t=new jr.SellNativeDto(a,n,e,{maxAcceptableReverseBondingCurveFee:s});return await this.executeBundleTransaction(t,"SellWithNative",a)}}async prepareTradingOperation(e,t,n,r){const{effectiveSlippageFactor:o,effectiveMaxFee:i}=this.calculateEffectiveSlippage(t,n,r),s=await this.resolveTokenNameToVault(e);if(!s)throw K(e);return{effectiveSlippageFactor:o,effectiveMaxFee:i,vaultAddress:s}}calculateEffectiveSlippage(e,t,n){const r=n??this.defaultSlippageToleranceFactor,o=t??this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor;let i=e||"0";return e&&(i=Xr(e,o,"buy-exact"),this.logger.debug("Reverse bonding curve fee slippage applied:",{baseFee:e,slippageFactor:o,adjustedMaxFee:i})),{effectiveSlippageFactor:r,effectiveFeeSlippageFactor:o,effectiveMaxFee:i}}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 - ${c.v4()}-${Date.now()}-${this.userAddress}`;const r=await this.signatureService.signDTO(e,t,this.userAddress),o=this.tokenKeyService.generateStringsInstructions(n),i={stringsInstructions:o,method:t,signedDto:r};this.logger.debug("📦 Bundle transaction data:",{method:t,stringsInstructions:o,dtoKeys:Object.keys(r)});const s=await this.submitTransaction(i);if(s.success&&s.data)return this.logger.debug("✅ Bundle transaction submitted:",s.data),{success:!0,data:{transactionId:s.data,message:"Transaction submitted successfully. Monitor WebSocket for completion."}};throw new Error(String(s.error||"Bundle transaction failed"))}catch(e){throw this.logger.error("❌ Bundle transaction error:",e),e}}async resolveTokenNameToVault(e){return await this.tokenResolver.resolveTokenToVault(e)}}var Zr,Yr;!function(e){e.PROCESSED="PROCESSED",e.COMPLETED="COMPLETED",e.SUCCESS="SUCCESS",e.FAILED="FAILED",e.ERROR="ERROR",e.PROCESSING="PROCESSING",e.PENDING="PENDING"}(Zr||(Zr={})),e.SDKTransactionStatus=void 0,(Yr=e.SDKTransactionStatus||(e.SDKTransactionStatus={})).PENDING="pending",Yr.PROCESSING="processing",Yr.COMPLETED="completed",Yr.FAILED="failed",Yr.TIMEOUT="timeout";const Jr={[Zr.PROCESSED]:e.SDKTransactionStatus.COMPLETED,[Zr.COMPLETED]:e.SDKTransactionStatus.COMPLETED,[Zr.SUCCESS]:e.SDKTransactionStatus.COMPLETED,[Zr.FAILED]:e.SDKTransactionStatus.FAILED,[Zr.ERROR]:e.SDKTransactionStatus.FAILED,[Zr.PROCESSING]:e.SDKTransactionStatus.PROCESSING,[Zr.PENDING]:e.SDKTransactionStatus.PENDING};class eo extends En{constructor(e,t=!1){super(t),this.socket=null,this.listeners=new Map,this.timeouts=new Map,this.reconnectCount=0,this.hasOnAnyListener=!1,this.eventBuffer=new Map,this.eventBufferTimeouts=new Map,this.MAX_BUFFER_SIZE=1e3,this.config={reconnectAttempts:5,reconnectDelay:2e3,timeout:3e5,...e},this.debug=t,this.isSocketIOAvailable=this.checkSocketIOAvailability()}checkSocketIOAvailability(){try{return"function"==typeof u.io||(this.logger.warn('⚠️ Socket.IO client not available. Install "socket.io-client" package.'),!1)}catch(e){return this.logger.warn("⚠️ Socket.IO availability check failed:",e),!1}}async connect(){return new Promise((e,t)=>{try{if(!this.isSocketIOAvailable){const e=new Error('Socket.IO not available in current environment. Install "socket.io-client" package.');return this.logger.error("❌ Socket.IO connection failed:",e.message),void t(e)}this.logger.debug("🔌 Connecting to Socket.IO server:",this.config.url),this.socket=u.io(this.config.url,{transports:["websocket"],reconnection:!0,reconnectionAttempts:this.config.reconnectAttempts||5,reconnectionDelay:this.config.reconnectDelay||2e3}),this.socket.on("connect",()=>{this.logger.debug("✅ Socket.IO connected successfully:",this.socket?.id),this.logger.debug("📡 Connected to bundle backend WebSocket:",this.config.url),this.logger.debug("🔗 Ready to monitor transaction updates"),this.reconnectCount=0,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;if(r&&"string"==typeof r){if(this.logger.debug(`📡 [Event Buffer] Buffering event for ${e}: ${r}`),this.eventBuffer.size>=this.MAX_BUFFER_SIZE){const e=this.eventBuffer.keys().next().value;if(e){const t=this.eventBufferTimeouts.get(e);t&&(clearTimeout(t),this.eventBufferTimeouts.delete(e)),this.eventBuffer.delete(e),this.logger.warn(`📡 [Event Buffer] Buffer full (${this.MAX_BUFFER_SIZE}), dropped oldest: ${e}`)}}this.eventBuffer.set(e,n);const t=this.eventBufferTimeouts.get(e);t&&clearTimeout(t);const o=setTimeout(()=>{this.eventBuffer.has(e)&&(this.logger.debug(`📡 [Event Buffer] Cleaning up orphaned event for ${e}`),this.eventBuffer.delete(e),this.eventBufferTimeouts.delete(e))},3e4);this.eventBufferTimeouts.set(e,o)}}this.debug&&this.logger.debug(`📡 [WebSocket Event] "${e}":`,JSON.stringify(t,null,2))}),this.hasOnAnyListener=!0}catch(e){t(e)}})}async monitorTransaction(t,n){this.listeners.set(t,n),this.logger.debug(`📡 Starting to monitor transaction: ${t}`),this.logger.debug(`📡 WebSocket connected: ${!!this.socket&&this.socket.connected}`);const r=this.eventBuffer.get(t);if(r){this.logger.debug(`📡 [Event Buffer] Found buffered event for ${t}, delivering immediately`),setImmediate(()=>{this.processTransactionEvent(t,r,n)});const e=this.eventBufferTimeouts.get(t);e&&(clearTimeout(e),this.eventBufferTimeouts.delete(t)),this.eventBuffer.delete(t)}const o=this.config.timeout||3e5,i=setTimeout(()=>{if(this.listeners.has(t)){const r=Math.round(o/1e3),i={transactionId:t,status:e.SDKTransactionStatus.TIMEOUT,message:`Transaction monitoring timeout - no response after ${r} seconds`,timestamp:Date.now()};this.logger.debug(`📡 Transaction timeout for ${t} (${r}s)`),n(i),this.listeners.delete(t),this.timeouts.delete(t),this.socket?.off(t)}},o);if(this.timeouts.set(t,i),this.socket&&this.socket.connected)this.socket.off(t),this.logger.debug(`📡 Listening for transaction updates: ${t}`),this.logger.debug(`📡 WebSocket connection ID: ${this.socket.id}`),this.logger.debug(`📡 WebSocket URL: ${this.config.url}`),this.socket.on(t,e=>{this.processTransactionEvent(t,e,n)});else{const r={transactionId:t,status:e.SDKTransactionStatus.FAILED,message:"WebSocket not connected - cannot monitor transaction",timestamp:Date.now()};n(r),this.listeners.delete(t),this.timeouts.delete(t)}}processTransactionEvent(t,n,r){this.logger.debug(`📡 Socket.IO transaction update for ${t}:`,JSON.stringify(n,null,2));const o=n,i=o?.data,s=o?.status||o?.Status||i?.status||i?.Status;let a=o?.message||o?.Message||i?.message||i?.Message||o?.error||i?.error;a&&"string"==typeof a||(a=s===Zr.FAILED||s===Zr.ERROR?"Transaction failed - check transaction details":s===Zr.COMPLETED||s===Zr.PROCESSED||s===Zr.SUCCESS?"Transaction completed successfully":s?`Transaction status: ${s}`:"Unknown transaction status");const c=o?.blockHash||i?.blockHash,u=o?.gasUsed||i?.gasUsed,l=o?.Data||i?.Data,h={transactionId:t,status:this.mapSocketStatus(s),message:"string"==typeof a?a:"Transaction update received",timestamp:Date.now(),...c&&{blockHash:c},...u&&{gasUsed:u},...l&&{data:l}};if(this.logger.debug(`📡 Mapped status for ${t}: ${s} -> ${h.status}`),this.logger.debug(`📡 Final message: "${a}"`),r(h),h.status===e.SDKTransactionStatus.COMPLETED||h.status===e.SDKTransactionStatus.FAILED){this.listeners.delete(t);const e=this.timeouts.get(t);e&&(clearTimeout(e),this.timeouts.delete(t)),this.socket?.off(t),this.logger.debug(`📡 Cleaned up listener for ${t} (${h.status})`)}}async waitForTransaction(t){return new Promise((n,r)=>{this.monitorTransaction(t,t=>{t.status===e.SDKTransactionStatus.COMPLETED?n(t):t.status!==e.SDKTransactionStatus.FAILED&&t.status!==e.SDKTransactionStatus.TIMEOUT||r(new Error(`Transaction ${t.status}: ${t.message}`))})})}mapSocketStatus(t){const n=t?.toUpperCase();return Jr[n]||e.SDKTransactionStatus.PENDING}async handleReconnect(){this.reconnectCount<this.config.reconnectAttempts?(this.reconnectCount++,this.logger.debug(`🔄 Attempting Socket.IO reconnect ${this.reconnectCount}/${this.config.reconnectAttempts}`),setTimeout(()=>{this.socket&&!this.socket.connected&&this.socket.connect()},this.config.reconnectDelay)):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.eventBufferTimeouts.forEach(e=>{clearTimeout(e)}),this.eventBufferTimeouts.clear(),this.logger.debug("🧹 Cleared event buffer and timeouts"),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 to extends En{constructor(e,t=!1){super(t),this.poolService=e,this.cache=new Map}async resolveTokenToVault(e){if(!Z(e))throw new x("Token name is required and must be a non-empty string","tokenName","INVALID_TOKEN_NAME");const t=e.trim().toLowerCase(),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 K(e);return this.parseVaultAddressToTokenClassKey(t)}get(e){return this.cache.get(e.toLowerCase())||null}set(e,t){this.cache.set(e.toLowerCase(),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 cr(e)}catch(e){if(e instanceof x)throw G("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad","Vault address");throw e}}}async function no(e,t={}){const{maxPages:n=1e4,logger:r,pageSize:o=20}=t,i=[];let s=1,a=!0,c=0;for(;a&&s<=n;){r&&r.debug(`Auto-pagination: fetching page ${s} with limit ${o}`);const t=await e(s,o);if(!t||!Array.isArray(t.items)){r&&r.warn("Auto-pagination: received invalid result structure, stopping");break}if(i.push(...t.items),c=t.total,r&&r.debug(`Auto-pagination: page ${s} returned ${t.items.length} items, hasNext: ${t.hasNext}`),0===t.items.length){r&&r.debug(`Auto-pagination: no items returned on page ${s}, exiting loop`);break}a=t.hasNext,s++}return s>n&&r&&r.warn(`Auto-pagination: exceeded maxPages limit of ${n}, stopping iteration`),r&&r.debug(`Auto-pagination: completed with total items: ${i.length}, total count: ${c}`),{items:i,total:c}}function ro(e,t=e.length,n="items"){return{...{page:1,limit:e.length||0,total:t,totalPages:Math.ceil(t/(e.length||1))||1,hasNext:!1,hasPrevious:!1},[n]:e}}async function oo(e,t){const{maxLimit:n,logger:r,maxPages:o=1e4}=t,i=[];let s=0,a=!0,c=0;for(;a&&c<o;){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}i.push(...t.items),a=t.rawCount===n,s+=n,c++,r&&r.debug(`Auto-pagination (offset): fetched ${i.length} items so far (hasMore=${a})`)}return c>=o&&r&&r.warn(`Auto-pagination (offset): exceeded maxPages limit of ${o}, stopping`),r&&r.debug(`Auto-pagination (offset): completed with total items: ${i.length}`),i}class io extends vn{constructor(e,t=!1,n){super(e,t),this.tokenResolverService=n}async fetchTokenClassKeyByTokenName(e){if(!this.tokenResolverService)throw j("TokenResolverService is required for token name resolution. Ensure it is passed to PriceHistoryService constructor.","tokenResolverService");if(!e||"string"!=typeof e||e.length<3||e.length>20)throw j("Token name must be a string between 3 and 20 characters","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=cr(t),r=`${n.collection}|${n.category}|${n.type}|${n.additionalKey}`;return this.logger.debug(`Extracted token class key: ${r}`),r}catch(t){if(t instanceof Error&&t.message.includes("ConfigurationError"))throw t;throw W(`Failed to resolve token name '${e}': ${$(t)}`,500)}}async fetchPriceHistory(e){this.logger.debug("Fetching price history from DEX Backend API with options:",e),this.validateOptions(e);try{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 dr}),r=n(t),o=er(`${r.collection}|${r.category}|${r.type}|${r.additionalKey}`),{from:i,to:s,sortOrder:a="DESC",page:c=1,limit:u=10}=e,l={token:o,page:String(c),limit:String(u)};i&&(l.from=i.toISOString()),s&&(l.to=s.toISOString());const h=function(e){if(e)return e.toLowerCase()}(a);h&&(l.order=h),this.logger.debug(`Querying price snapshots for token ${o}, page ${c}, limit ${u}`);const d=await this.http.get("/price-oracle/fetch-price",l);if(!d)throw W("No response from price history service",500);const f=this.transformApiResponseToPriceHistory(d);return this.logger.debug(`Found ${f.snapshots.length} price snapshots, total ${f.total}`),f}catch(e){if(e instanceof Error&&(e.message.includes("ConfigurationError")||e.message.includes("NetworkError")))throw e;throw W(`Failed to fetch price history: ${$(e)}`,500)}}transformApiResponseToPriceHistory(e){if(!e?.data?.data||!Array.isArray(e.data.data))throw W("Invalid API response: missing or invalid data.data array",500);if(!e?.data?.meta)throw W("Invalid API response: missing data.meta pagination info",500);const t=e.data.data.map(e=>({price:e.price,timestamp:new Date(e.createdAt),tokenId:`${e.collection}|${e.category}|${e.type}|${e.additionalKey}`})),n=e.data.meta,r=n.currentPage??1,o=n.totalPages??1;return{snapshots:t,page:r,limit:n.pageSize??50,total:n.totalItems??0,totalPages:o,hasNext:r<o,hasPrevious:r>1}}async fetchAllPriceHistory(e){this.logger.debug("Fetching all price history with options:",e);const t=await no((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 ro(t.items,t.total,"snapshots")}validateOptions(e){const{from:t,to:n,sortOrder:r,page:o=1,limit:i=10}=e;if(function(e,t,n,r={}){const{description:o="parameter",treatEmptyAsNull:i=!0}=r,s=e[t],a=e[n],c=null!=s&&(!i||""!==s),u=null!=a&&(!i||""!==a);if(!c&&!u)throw j(`Either ${t} or ${n} must be provided (${o})`,n);if(c&&u)throw j(`Cannot provide both ${t} and ${n}. Provide exactly one (${o}).`,n)}(e,"tokenName","tokenId",{description:"token identifier"}),t&&!(t instanceof Date)&&isNaN(new Date(t).getTime()))throw j("from must be a valid Date","from");if(n&&!(n instanceof Date)&&isNaN(new Date(n).getTime()))throw j("to must be a valid Date","to");if(r&&"ASC"!==r&&"DESC"!==r)throw j('sortOrder must be either "ASC" or "DESC"',"sortOrder");if(!Number.isInteger(o)||o<1)throw j("page must be a positive integer","page");if(!Number.isInteger(i)||i<1||i>50)throw j("limit must be between 1 and 50","limit")}}function so(e){if("object"==typeof e&&null!==e)return function(e){if(!e||"object"!=typeof e)throw new x("Token object must be a non-null object, got "+typeof e,"token","INVALID_TOKEN_OBJECT");const{collection:t,category:n,type:r,additionalKey:o}=e;if(!t||"string"!=typeof t)throw new x("Token.collection must be a non-empty string, got "+typeof t,"token.collection","MISSING_OR_INVALID_COLLECTION");if(!n||"string"!=typeof n)throw new x("Token.category must be a non-empty string, got "+typeof n,"token.category","MISSING_OR_INVALID_CATEGORY");if(!r||"string"!=typeof r)throw new x("Token.type must be a non-empty string, got "+typeof r,"token.type","MISSING_OR_INVALID_TYPE");if(!o||"string"!=typeof o)throw new x("Token.additionalKey must be a non-empty string, got "+typeof o,"token.additionalKey","MISSING_OR_INVALID_ADDITIONAL_KEY");return{collection:t,category:n,type:r,additionalKey:o}}(e);if(!e)throw new x(`Token cannot be null, undefined, or empty. Received: ${JSON.stringify(e)}`,"token","EMPTY_TOKEN");if("string"!=typeof e)throw new x("Token must be a string or TokenClassKey object, got "+typeof e,"token","INVALID_TOKEN_TYPE");if(e.includes("|"))return function(e){try{if(!e||"string"!=typeof e)throw new Error("Token must be a non-empty string");const t=e.split("|");if(t.length<4)throw new Error(`Invalid pipe-delimited token format. Expected 4+ parts separated by |, got ${t.length}`);const[n,r,o,...i]=t;if(!n||!r||!o)throw new Error("Collection, category, and type must be non-empty");const s=i.join("|");if(!s)throw new Error("AdditionalKey must be non-empty");return{collection:n,category:r,type:o,additionalKey:s}}catch(t){const n=e.split("|");throw new x(`Invalid pipe-delimited token: "${e}" (${n.length} parts). Expected format: "collection|category|type|additionalKey" (4 parts minimum). Received: [${n.map(e=>`"${e}"`).join(", ")}]. Error: ${t instanceof Error?t.message:String(t)}`,"token","INVALID_PIPE_DELIMITED_TOKEN")}}(e);if(e.includes("$"))return function(e){try{if(!e||"string"!=typeof e)throw new Error("Token must be a non-empty string");const t=e.split("$");if(t.length<4)throw new Error(`Invalid dollar-delimited token format. Expected 4+ parts separated by $, got ${t.length}`);const n=t[t.length-1],r=t[t.length-2],o=t[t.length-3],i=t.slice(0,t.length-3).join("$");if(!(i&&o&&r&&n))throw new Error("All components (collection, category, type, additionalKey) must be non-empty");return{collection:i,category:o,type:r,additionalKey:n}}catch(t){const n=e.split("$");throw new x(`Invalid dollar-delimited token: "${e}" (${n.length} parts). Expected format: "collection$category$type$additionalKey" (4 parts minimum). Received: [${n.map(e=>`"${e}"`).join(", ")}]. Error: ${t instanceof Error?t.message:String(t)}`,"token","INVALID_DOLLAR_DELIMITED_TOKEN")}}(e);throw new x(`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")}class ao extends Error{constructor(e,t,n){super(`API Error [${e}]: ${t}`),this.status=e,this.message=t,this.details=n,this.name="ApiError"}}function co(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 uo(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.positionId&&co(t.token0ClassKey)&&co(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 lo{constructor(e){this.client=t.create({baseURL:e.baseUrl,timeout:e.timeout??3e4})}async getPoolData(e){try{if("string"==typeof e.token0||"string"==typeof e.token1)throw new Error(`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" }`);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&&co(t.token0ClassKey)&&co(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 ao(t.status,"Invalid pool data response format",n);return n}catch(e){throw this.handleError(e,"getPoolData")}}async getPositions(e){try{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(!uo(e))throw new ao(t.status,"Invalid position in response",e);return{positions:r,count:r.length}}catch(e){throw this.handleError(e,"getPositions")}}async getPositionById(e,t,n,r,o,i,s){try{let a,c;if(void 0!==t&&void 0!==n&&void 0!==r&&void 0!==o&&void 0!==i){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:o,tickUpper:i},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 ao(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}catch(t){throw this.handleError(t,`getPositionById(${e})`)}}async getRemoveLiquidityEstimation(e){try{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 ao(t.status,"Invalid removal estimation response format",n);return n}catch(e){throw this.handleError(e,"getRemoveLiquidityEstimation")}}validateResponse(e){if(!e||"object"!=typeof e)throw new ao(500,"Invalid response format: not an object");if(!("Data"in e)||!("Status"in e))throw new ao(500,"Invalid response format: missing Data or Status field");if(e.Status>=400)throw new ao(e.Status,e.Message??"Gateway error",e.Data)}handleError(e,n){if(e instanceof ao)return e;if(t.isAxiosError(e)){const t=e.response?.status??500,r=e.response?.data?.Message??e.message,o=e.response?.data?.Data??void 0;return new ao(t,`${n}: ${r}`,o)}return new ao(500,`${n}: ${e instanceof Error?e.message:String(e)}`)}}class ho{constructor(e){this.http=e}async getUserAssets(e,t=20,n=0){try{if(!e||"string"!=typeof e)throw new ao(400,"Invalid wallet address");const r=Math.max(1,Math.floor(n/t)+1),o={};o.address=e,o.page=r,o.limit=t;const i=await this.http.get("/user/assets",o);if(!i||"object"!=typeof i)throw new ao(500,"Invalid response format: not an object");const s=i.data;if(!s||"object"!=typeof s)throw new ao(500,"Invalid response format: missing data wrapper");const a=s.token;if(!Array.isArray(a))throw new ao(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 ao(500,"Invalid asset in response: asset must be an object");const t=e;if("string"!=typeof t.symbol||"string"!=typeof t.name)throw new ao(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 ao(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:s.count??c.length};return void 0!==s.totalValue&&(u.totalValue=s.totalValue),u}catch(t){throw this.handleError(t,`getUserAssets(${e})`)}}async fetchTokenList(e={}){try{const{address:t,search:n,page:r=1,limit:o=20}=e,i={page:r,limit:Math.min(o,20)};t&&(i.address=t),n&&(i.search=n);const s=await this.http.get("/user/token-list",i);if(!s||"object"!=typeof s)throw new ao(500,"Invalid response format: not an object");const a=s.data;if(!a||"object"!=typeof a)throw new ao(500,"Invalid response format: missing data wrapper");const c=a.token;if(!Array.isArray(c))throw new ao(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 ao(500,"Invalid token in response: must be an object");const t=e;if("string"!=typeof t.symbol||""===t.symbol.trim())throw new ao(500,'Invalid token in response: missing required field "symbol"',{token:t});if("string"!=typeof t.name)throw new ao(500,'Invalid token in response: missing required field "name"',{token:t});const n=t.decimals;if("string"!=typeof n&&"number"!=typeof n)throw new ao(500,'Invalid token in response: missing required field "decimals"',{token:t});if("string"!=typeof t.compositeKey||""===t.compositeKey.trim())throw new ao(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}}catch(e){throw this.handleError(e,"fetchTokenList")}}handleError(e,t){if(e instanceof ao)return e;if(e instanceof Error&&e instanceof Error&&"response"in e){const n=e,r=n.response?.status??500,o=n.response?.data?.message??n.response?.data?.Message??n.message,i=n.response?.data?.Data??n.response?.data?.data??void 0;return n.response,new ao(r,`${t}: ${o}`,i)}return new ao(500,`${t}: ${e instanceof Error?e.message:String(e)}`)}}function fo(e){try{if(!e||"string"!=typeof e)throw new Error("Token must be a non-empty string");const t=e.split("|");if(t.length<4)throw new Error(`Invalid pipe-delimited token format. Expected at least 4 parts separated by |, got ${t.length}`);const[n,r,o,...i]=t;if(!n||!r||!o)throw new Error("Collection, category, and type must be non-empty");const s=i.join("|");if(!s)throw new Error("AdditionalKey must be non-empty");return{collection:n,category:r,type:o,additionalKey:s}}catch(t){throw new x(`Invalid pipe-delimited token: "${e}". Expected format: "collection|category|type|additionalKey". Error: ${t instanceof Error?t.message:String(t)}`,"pipeDelimitedToken","INVALID_PIPE_DELIMITED_TOKEN_FORMAT")}}const po=20,go=10;class mo extends En{constructor(e,t,n){if(super(!1),this.pricingConcurrency=5,this.tokenConverter=new Jn,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 Error("GSwapService requires explicit gatewayBaseUrl, bundlerBaseUrl, dexBackendBaseUrl, and dexBackendHttp configuration. These must be provided by LaunchpadSDK to ensure environment alignment.");try{this.gatewayClient=new lo({baseUrl:e.gatewayBaseUrl,timeout:3e4}),this.dexBackendClient=new ho(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 Error("Failed to initialize GSwapService HTTP clients")}}setPricingConcurrency(e){if(e<1)throw new Error("Pricing concurrency must be at least 1");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(new i(e.amount).isLessThanOrEqualTo(0))throw new _("Amount must be greater than zero",{amount:e.amount,fromToken:e.fromToken,toToken:e.toToken});if(!this.dexQuoteService)throw new _("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,o]=t<n?[t,n]:[n,t],s=[3e3,500,1e4];let a;for(const c of s)try{const s=await this.dexQuoteService.fetchCompositePoolData({token0:r,token1:o,fee:c,gatewayBaseUrl:this.gatewayBaseUrl}),a=await this.dexQuoteService.calculateDexPoolQuoteExactAmount({compositePoolData:s,fromToken:t,toToken:n,amount:e.amount}),u=new i(a.currentSqrtPrice),l=new i(a.newSqrtPrice),h=u.gt(l)?u.minus(l).dividedBy(u):new i(0),d=new i(a.amount0),f=new i(a.amount1),p=d.isNegative(),g=f.isNegative();this.logger.debug("=== AMOUNT SELECTION RAW DATA ===",{"quoteResult.amount0":a.amount0,"quoteResult.amount1":a.amount1,"amount0BN.isNegative()":p,"amount1BN.isNegative()":g});const m=p?d:f;this.logger.debug("=== AMOUNT SELECTION RESULT ===",{selectedFromAmount0:p,selectedAmount:m.toFixed(),selectedAmountAbs:m.absoluteValue().toFixed()});const y=m.absoluteValue().toFixed();return{fromToken:e.fromToken,toToken:e.toToken,inputAmount:e.amount,estimatedOutput:y,feeTier:c,priceImpact:h.toFixed(),executionPrice:this.calculateExecutionPrice(e.amount,y),currentSqrtPrice:a.currentSqrtPrice,newSqrtPrice:a.newSqrtPrice}}catch(e){a=e,this.logger.debug("DexQuoteService failed for fee tier, trying next",{feeTier:c,error:e instanceof Error?e.message:"Unknown error"})}throw a||new _("No available fee tiers for quote",{feeTiers:s,fromToken:e.fromToken,toToken:e.toToken})}catch(e){this.handleGSwapError("Failed to get swap quote for exact input",_,e)}}async getSwapQuoteExactOutput(e){try{if(new i(e.amount).isLessThanOrEqualTo(0))throw new _("Amount must be greater than zero",{amount:e.amount,fromToken:e.fromToken,toToken:e.toToken});if(!this.dexQuoteService)throw new _("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,o]=t<n?[t,n]:[n,t],s=[3e3,500,1e4];let a;for(const c of s)try{const s=await this.dexQuoteService.fetchCompositePoolData({token0:r,token1:o,fee:c,gatewayBaseUrl:this.gatewayBaseUrl}),a=await this.dexQuoteService.calculateDexPoolQuoteExactAmount({compositePoolData:s,fromToken:t,toToken:n,amount:e.amount}),u=new i(a.currentSqrtPrice),l=new i(a.newSqrtPrice),h=u.gt(l)?u.minus(l).dividedBy(u):new i(0),d=s.pool.token0,f="string"==typeof d?d.split("|")[0]:"object"==typeof d&&null!==d&&"tokenName"in d?d.tokenName:String(d),p=n.split("|")[0]===f?a.amount1:a.amount0;return{fromToken:e.fromToken,toToken:e.toToken,inputAmount:p,estimatedOutput:e.amount,feeTier:c,priceImpact:h.toFixed(),executionPrice:this.calculateExecutionPrice(p,e.amount),currentSqrtPrice:a.currentSqrtPrice,newSqrtPrice:a.newSqrtPrice}}catch(e){a=e,this.logger.debug("DexQuoteService failed for fee tier, trying next",{feeTier:c,error:e instanceof Error?e.message:"Unknown error"})}throw a||new _("No available fee tiers for quote",{feeTiers:s,fromToken:e.fromToken,toToken:e.toToken})}catch(e){this.handleGSwapError("Failed to get swap quote for exact output",_,e)}}async executeSwap(e){try{if(!this.privateKey)throw new Error("GSwapService not initialized with signing capability (privateKey required)");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=function(e,t=.01){const n=jn(e),r=new i(1).minus(t);return n.multipliedBy(r)}(e.estimatedOutput,e.slippageTolerance||.01),o=this.getWalletAddress();if(!o)throw new Error("Wallet address required for swap execution");let s;try{const t=await this.getSwapQuoteExactInput({fromToken:e.fromToken,toToken:e.toToken,amount:e.inputAmount});s=t.currentSqrtPrice,this.logger.debug("Quote refetch successful - extracted sqrtPrices",{currentSqrtPrice:s,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:t instanceof Error?t.message:String(t)})}const a={fromToken:t,toToken:n,inputAmount:e.inputAmount,minOutput:r.toFixed(),feeTier:e.feeTier,walletAddress:o,slippageTolerance:e.slippageTolerance||.01};void 0!==s&&(a.currentSqrtPrice=s);const c=await this.sendSwapToBundler(a);this.logger.debug("Swap submitted, monitoring transaction",{transactionId:c,fromToken:e.fromToken,toToken:e.toToken}),await this.ensureWebSocketConnected();const u=await this.webSocketService.waitForTransaction(c);return{transactionId:u.transactionId,status:u.status,fromToken:e.fromToken,toToken:e.toToken,inputAmount:e.inputAmount,outputAmount:e.estimatedOutput,feeTier:e.feeTier,slippageTolerance:e.slippageTolerance||.01,timestamp:new Date(u.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(c)}}}catch(e){const t=e;this.handleGSwapError("Failed to execute swap",D,e,{transactionHash:t?.txHash})}}async getUserAssets(e,t=1,n=20){try{if(!Y(e))throw new R(`Invalid wallet address format: "${e}". Expected format: "0x...", "eth|...", or "client|..."`,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)}catch(r){this.handleGSwapError("Failed to fetch user assets",R,r,{walletAddress:e,page:t,limit:n})}}async getAllUserAssets(e){try{if(!Y(e))throw new R(`Invalid wallet address format: "${e}". Expected format: "0x...", "eth|...", or "client|..."`,new Error("INVALID_ADDRESS_FORMAT"),e,"INVALID_ADDRESS");this.logger.debug("Fetching all user assets (auto-paginated with optimization)",{walletAddress:e});const t=[];let n=1;const r=20;let o=!0;for(;o&&n<=po;){const i=await this.dexBackendClient.fetchTokenList({address:e,page:n,limit:r});let s=!1;for(const e of i.token){if("0"===e.quantity){s=!0;break}const n=this.transformRawTokenToUserAsset(e);n&&t.push(n)}o=!s&&i.token.length===r,n++}return n>po&&this.logger.warn("Reached maximum page limit (20) while fetching user assets",{walletAddress:e,totalAssets:t.length}),this.logger.debug("Fetched all user assets",{walletAddress:e,totalAssets:t.length}),t}catch(t){this.handleGSwapError("Failed to fetch all user assets",R,t,{walletAddress:e})}}async fetchAvailableDexTokens(e={}){try{const{search:t,page:n=1,limit:r=20}=e;this.logger.debug("Fetching available DEX tokens",{search:t,page:n,limit:r});const o=await this.dexBackendClient.fetchTokenList({...void 0!==t&&{search:t},page:n,limit:r});return{tokens:o.token.map(e=>this.transformRawTokenToDexToken(e)),count:o.count,page:n,limit:r,hasMore:n*r<o.count}}catch(t){this.handleGSwapError("Failed to fetch available DEX tokens",R,t,{...e})}}async fetchAllAvailableDexTokens(e={}){try{const{search:t}=e;this.logger.debug("Fetching all available DEX tokens (auto-paginated)",{search:t});const n=[];let r=1;const o=20;let i=!0;for(;i&&r<=po;){const e=await this.dexBackendClient.fetchTokenList({...void 0!==t&&{search:t},page:r,limit:o});for(const t of e.token)n.push(this.transformRawTokenToDexToken(t));i=e.token.length===o,r++}return r>po&&this.logger.warn("Reached maximum page limit (20) while fetching available DEX tokens",{search:t,totalTokens:n.length}),this.logger.debug("Fetched all available DEX tokens",{search:t,totalTokens:n.length}),n}catch(t){this.handleGSwapError("Failed to fetch all available DEX tokens",R,t,e)}}async getPoolInfo(e,t){try{this.logger.debug("Fetching pool info",{tokenA:e,tokenB:t});const{gswapToken0:n,gswapToken1:r}=this.convertTokenPair(e,t),o=[500,3e3,1e4];let s=new i(0),a=0;for(const c of o)try{const e="string"==typeof n?so(n):n,t="string"==typeof r?so(r):r,o=await this.gatewayClient.getPoolData({token0:e,token1:t,fee:c});o&&(s=s.plus(new i(o.liquidity||0)),a++)}catch{this.logger.debug("Pool not found for fee tier",{tokenA:e,tokenB:t,feeTier:c})}return{tokenA:e,tokenB:t,liquidity:s.toFixed(),feeTiers:o,swapCount:a}}catch(n){this.logger.warn("Failed to fetch pool info",n);const r=n;return this.logger.debug("Pool error details",{error:new U(`Failed to fetch pool info: ${r?.message||String(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()),o=this.chunkArray(r,t);this.logger.debug("Fetching pricing for positions",{totalPositions:e.length,uniquePoolsToPrice:n.size,chunks:o.length,concurrency:t});const i=new Map;for(let e=0;e<o.length;e++){const t=o[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?i.set(e.value.key,e.value.data):this.logger.warn("Failed to fetch price for pool",{error:e.reason})})}return i}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||"",o=e.token1Symbol||n(e.token1)||n(e.tokenB)||e.tokenSymbol1||"",i=r?this.tokenConverter.normalizeInternalApiResponse(r):"",s=o?this.tokenConverter.normalizeInternalApiResponse(o):"";return{positionId:e.positionId||e.id||"",ownerAddress:t||e.ownerAddress||e.owner||"",token0:i,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 so(e)}catch(t){if(t instanceof Error&&t.message?.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:parseInt(e.decimals,10)||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 o=e.compositeKey?so(e.compositeKey.replace(/\$/g,"|")):so(`${t}|Unit|none|none`);return{...this.transformRawTokenToDexToken(e),tokenId:o,balance:(n=e.quantity||"0",void 0!==r?jn(n).toFixed(r):jn(n).toFixed())}}catch(e){return this.logger.debug(`Skipping asset with processing error: ${t}`,{error:e instanceof Error?e.message:String(e)}),null}var n,r}async getUserLiquidityPositions(e,n=10,r,o){try{this.logger.debug("Fetching user liquidity positions",{ownerAddress:e,limit:n,bookmark:r});const i=`${this.galaChainBaseUrl}/api/asset/dexv3-contract/GetUserPositions`,s={user:e,limit:n,bookmark:r||""};this.logger.debug("Sending position query request",{endpoint:i,payload:s});const a=await t.post(i,s,{headers:{"Content-Type":"application/json",Accept:"application/json"}});if(200!==a.status||1!==a.data?.Status)return this.logger.warn("Unexpected API response status",{httpStatus:a.status,apiStatus:a.data?.Status}),{items:[]};const c=a.data.Data||{},u=c.positions||[],l=c.nextBookMark,h=u.filter(e=>null!=e&&"object"==typeof e&&("positionId"in e||"id"in e)).map(t=>this.normalizePositionResponse(t,e));let d;this.logger.debug("Retrieved liquidity positions",{count:h.length,hasNextBookmark:!!l,nextBookmark:l}),o?.withPrices&&h.length>0&&(d=await this.fetchPositionPrices(h));const f={items:h};return void 0!==l&&(f.nextBookmark=l),void 0!==d&&(f.prices=d),f}catch(t){if(t&&"object"==typeof t&&"response"in t){const n=t;this.logger.error("Position query failed with HTTP error",{status:n.response?.status,statusText:n.response?.statusText,data:n.response?.data,endpoint:this.galaChainBaseUrl,ownerAddress:e})}this.handleGSwapError("Failed to fetch user liquidity positions",L,t)}}async getAllSwapUserLiquidityPositions(e,t){try{this.logger.debug("Fetching all user liquidity positions (auto-paginated)",{ownerAddress:e});const n=async t=>{const n=await this.getUserLiquidityPositions(e,go,t,void 0);return{items:n.items,nextBookmark:n.nextBookmark}},r=await async function(e,t={}){const{maxPages:n=1e4,logger:r,pageSize:o=20}=t,i=[];let s,a=0;for(;a<n;){r&&r.debug(`Auto-pagination (bookmark): fetching page ${a+1} with pageSize ${o}`,{bookmark:s});const t=await e(s,o);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}i.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<o;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:o,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: ${i.length}`,{pageCount:a}),{items:i,total:i.length}}(n,{maxPages:1e4,logger:this.logger,pageSize:go}),o=r.items;if(this.logger.debug("Fetched all user liquidity positions",{ownerAddress:e,totalPositions:o.length}),t?.withPrices&&o.length>0){return{items:o,prices:await this.fetchPositionPrices(o)}}return o}catch(t){this.handleGSwapError("Failed to fetch all user liquidity positions",L,t,{ownerAddress:e})}}async getLiquidityPosition(e,t){try{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),o=fo(n),i=fo(r),s=(await this.gatewayClient.getPositions({owner:e,token0:o,token1:i,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 Error("Invalid position data returned from API");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",L,e)}}async getLiquidityPositionById(e,t,n,r,o,i,s){try{let a;this.logger.debug("Fetching liquidity position by ID",{ownerAddress:e,positionId:t,hasToken0:!!n,hasToken1:!!r,hasFee:!!o,hasTickLower:void 0!==i,hasTickUpper:void 0!==s});let c=null;const u=5,l=2e3;for(let h=1;h<=u;h++)try{if(n&&r&&void 0!==o&&void 0!==i&&void 0!==s)try{this.logger.debug("Attempting compound key lookup",{ownerAddress:e,token0:n,token1:r,feeTier:o,tickLower:i,tickUpper:s});if(a=(await this.gatewayClient.getPositionById(e,n,r,o,i,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 Error("Invalid position data from compound key lookup")}catch(e){this.logger.debug("Compound key lookup failed, trying fallback",{attempt:h,error:e instanceof Error?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 Error("Invalid position data from direct lookup")}catch(n){this.logger.debug("Direct position lookup failed, trying fallback via GetUserPositions",{attempt:h,positionId:t,error:n instanceof Error?n.message:n});const r=await this.getAllSwapUserLiquidityPositions(e),o=Array.isArray(r)?r:r.items;if(o.length>0){const e=o.find(e=>(e.positionId||"").toLowerCase()===t.toLowerCase());if(e){a=e,this.logger.debug("Found position via fallback (GetUserPositions)",{attempt:h,positionId:t,totalPositions:o.length});break}}if(c=new Error("Position not found in owner positions"),h<u){this.logger.warn("Fallback query did not find position, retrying",{attempt:h,positionId:t,ownerAddress:e,foundCount:o.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:e instanceof Error?e.message:e}),await new Promise(e=>setTimeout(e,l));continue}c=e instanceof Error?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||new Error("Invalid position data returned from API");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",L,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={token0:t,token1:"string"==typeof e.token1?this.parseTokenFlexible(e.token1):e.token1,fee:e.fee,tickLower:e.tickLower,tickUpper:e.tickUpper,owner:e.owner},r=`${this.galaChainBaseUrl}/api/asset/dexv3-contract/GetPositions`;this.logger.debug("Calling position endpoint via compound key",{url:r});const o=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(n)});if(!o.ok){if(404===o.status)throw new Error("Position not found (HTTP 404): No position exists for this compound key");if(400===o.status)throw new Error("Invalid parameters (HTTP 400): Check token format, fee (500|3000|10000), and tick ranges");throw new Error(`HTTP ${o.status}: ${o.statusText}`)}const i=await o.json();if(1!==i.Status||!i.Data)throw new Error(`Position not found: ${i.Message||"API returned no position data"}`);const s=this.normalizePositionResponse(i.Data,e.owner);return this.logger.debug("Retrieved swap position via compound key",{positionId:s.positionId,token0:s.token0,token1:s.token1}),s}catch(e){this.handleGSwapError("Failed to fetch swap position via compound key",L,e)}}async estimateRemoveLiquidity(e){try{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=fo(t),o=fo(n),i=await this.gatewayClient.getRemoveLiquidityEstimation({token0:r,token1:o,fee:e.fee,amount:e.liquidity,tickLower:e.tickLower,tickUpper:e.tickUpper,owner:e.owner});return this.logger.debug("Estimated removal",{result:i}),i}catch(e){this.handleGSwapError("Failed to estimate liquidity removal",L,e)}}async addLiquidityByPrice(e){try{if(!this.privateKey)throw new Error("GSwapService not initialized with signing capability (privateKey required)");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=so(t),o=so(n),s=(await this.gatewayClient.getPoolData({token0:r,token1:o,fee:e.fee})).tickSpacing;this.logger.debug("Retrieved tick spacing from pool",{tickSpacing:s,fee:e.fee});const a=new i(e.minPrice),c=new i(e.maxPrice),u=Math.floor(Vn(a)),l=Math.ceil(Vn(c)),h=Math.floor(u/s)*s,d=Math.ceil(l/s)*s;this.logger.debug("Converted price range to ticks",{minPrice:e.minPrice,maxPrice:e.maxPrice,tickLower:h,tickUpper:d,tickSpacing:s});const f=this.getWalletAddress();if(!f)throw new Error("GSwapService: No wallet address available - cannot create position");const p="string"==typeof e.token0?so(e.token0):e.token0,g="string"==typeof e.token1?so(e.token1):e.token1;this.logger.debug("Sending AddLiquidity by price to bundler",{fee:e.fee,tickRange:`${h}-${d}`,walletAddress:f});const m=await this.sendAddLiquidityToBundler({token0:p,token1:g,fee:e.fee,tickLower:h,tickUpper:d,amount0Desired:e.amount0Desired,amount1Desired:e.amount1Desired,amount0Min:e.amount0Min||"0",amount1Min:e.amount1Min||"0",owner:f}),y={transactionId:m};if(y.positionId&&m){this.logger.debug("Position ID returned directly from backend",{transactionId:m,positionId:y.positionId}),await this.ensureWebSocketConnected();const e=await this.webSocketService.waitForTransaction(m);this.logger.debug("Liquidity transaction confirmed on-chain",{transactionId:m,status:e.status});const t=this.getWalletAddress();if(t&&y.positionId)try{const n=await this.getLiquidityPositionById(t,y.positionId),{createdAt:r,updatedAt:o,...i}=n,s=r instanceof Date?r.getTime():"number"==typeof r?r:void 0,a={...y,...i,positionId:y.positionId,status:e.status,transactionId:e.transactionId,timestamp:new Date(e.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(m)}};return void 0!==s&&(a.createdAt=s),a}catch(t){return{...y,positionId:y.positionId,status:e.status,transactionId:e.transactionId,timestamp:new Date(e.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(m)}}}}if(m){this.logger.debug("Monitoring liquidity transaction (discovery mode)",{transactionId:m}),await this.ensureWebSocketConnected();const t=await this.webSocketService.waitForTransaction(m);let n;this.logger.debug("Liquidity transaction confirmed on-chain",{transactionId:m,status:t.status});let r=null;await new Promise(e=>setTimeout(e,2e3));try{const t=this.getWalletAddress();if(!t)throw new Error("No wallet address available");const o=(await this.getUserLiquidityPositions(t,10)).items;if(o&&o.length>0){const t=e.token0.split("|")[0].toUpperCase(),i=e.token1.split("|")[0].toUpperCase(),s=[];for(const n of o){if(!n||!n.positionId)continue;const r=n.token0?.toUpperCase(),o=n.token1?.toUpperCase();if(!r||!o)continue;const a=r===t&&o===i||r===i&&o===t,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:o.length}))}}catch(e){this.logger.debug("Error waiting for position indexing",{error:e instanceof Error?e.message:String(e)})}let o=r;if(n)try{o=await this.getLiquidityPositionById(f,n)}catch(e){}return{...y,...o,positionId:n,status:t.status,transactionId:t.transactionId,timestamp:new Date(t.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(m)}}}return this.logger.warn("No transaction ID in liquidity result, cannot confirm position creation"),y}catch(e){Error,this.handleGSwapError("Failed to add liquidity by price",L,e)}}async addSwapLiquidityByTicks(e){try{if(!this.privateKey)throw new Error("GSwapService not initialized with signing capability (privateKey required)");const t=this.getWalletAddress();if(!t)throw new Error("GSwapService: No wallet address available - cannot create position");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?so(e.token0):e.token0,r="string"==typeof e.token1?so(e.token1):e.token1;await this.ensureWebSocketConnected();const o=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:o});const i=this.webSocketService.waitForTransaction(o),s={transactionId:o};if(s.positionId&&o){this.logger.info("Position ID returned directly from backend",{transactionId:o,positionId:s.positionId});const e=await i;this.logger.debug("Liquidity transaction confirmed on-chain",{transactionId:o,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:i,...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(o)}};return void 0!==c&&(u.createdAt=c),u}catch(t){return this.logger.warn("Could not fetch full position details",{positionId:s.positionId,error:t instanceof Error?t.message:String(t)}),{...s,positionId:s.positionId,status:e.status,transactionId:e.transactionId,timestamp:new Date(e.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(o)}}}}if(o){this.logger.debug("Monitoring liquidity transaction (discovery mode)",{transactionId:o});const n=await i;let r;this.logger.debug("Liquidity transaction confirmed on-chain",{transactionId:o,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 Error("No wallet address available");this.logger.debug("Fetching positions from API",{walletAddress:t,pageSize:go});const n=3,o=5e3,i=3e3;let s=[];for(let c=1;c<=n;c++){const u=1===c?o:i;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:go});if(s=(await this.getUserLiquidityPositions(t,go)).items,this.logger.debug("Got positions from API",{count:s?.length||0}),s&&s.length>0){const t=("string"==typeof e.token0?e.token0.split("|")[0]:e.token0.collection).toUpperCase(),n=("string"==typeof e.token1?e.token1.split("|")[0]:e.token1.collection).toUpperCase(),o=[];for(const r of s){if(!r||!r.positionId)continue;const i=r.token0?.toUpperCase(),s=r.token1?.toUpperCase();if(!i||!s){this.logger.debug("Skipping position with empty tokens",{positionId:r.positionId});continue}const a=i===t&&s===n||i===n&&s===t,c=r.feeTier===e.fee;this.logger.debug("Checking position against target",{positionId:r.positionId,tokens:`${i}/${s}`,tokensMatch:a,fee:r.feeTier,feeMatches:c}),a&&c&&o.push(r)}if(o.length>0){a=o[o.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:e instanceof Error?e.message:String(e)}),this.logger.debug("Error waiting for position indexing",{error:e instanceof Error?e.message:String(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:e instanceof Error?e.message:String(e)})}return{...s,...l,positionId:r,status:n.status,transactionId:n.transactionId,timestamp:new Date(n.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(o)}}}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",L,e)}}async monitorBundlerTransaction(e,t,n="bundler"){let r;try{const o=await t;r={status:o.status,transactionId:o.transactionId||e,timestamp:o.timestamp||Date.now(),data:o.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:t instanceof Error?t.message:String(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 Error("Private key not available for bundler-direct operations");this.logger.debug("Removing liquidity via bundler",{token0:e.token0,token1:e.token1,liquidity:e.liquidity});try{const t=parseFloat(e.liquidity);if(isNaN(t))throw new Error(`Invalid liquidity value: "${e.liquidity}". Must be a valid number. Position ID: ${e.positionId||"unknown"}`);if(0===t)throw new Error(`Cannot remove zero liquidity from position. This would waste gas fees without any effect. Position ID: ${e.positionId||"unknown"}`)}catch(e){if(e instanceof Error&&e.message.includes("Cannot remove zero liquidity"))throw e;if(e instanceof Error&&e.message.includes("Invalid liquidity value"))throw e;throw e}const t="string"==typeof e.token0?so(e.token0):e.token0,n="string"==typeof e.token1?so(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 o=this.webSocketService.waitForTransaction(r);return this.monitorBundlerTransaction(r,o,"liquidity removal")}catch(e){this.handleGSwapError("Failed to remove liquidity",L,e)}}async collectPositionFees(e){try{if(!this.privateKey)throw new Error("Private key not available for bundler-direct operations");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 new Error(`Position ${e.positionId} not found for owner ${e.ownerAddress}`);if(!t.token0||!t.token1)throw new Error("Position missing token information");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 new Error("Missing required parameters: token0, token1, fee, tickLower, tickUpper are required when not using ownerAddress pattern");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?so(e.token0):e.token0,n="string"==typeof e.token1?so(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 o=this.webSocketService.waitForTransaction(r);return this.monitorBundlerTransaction(r,o,"fee collection")}catch(e){this.handleGSwapError("Failed to collect position fees",L,e)}}async getPoolData(e,t,n){try{this.logger.debug("Getting pool data",{tokenA:e,tokenB:t,feeTier:n});const{gswapToken0:r,gswapToken1:o}=this.convertTokenPair(e,t),s=so(r),a=so(o),c=await this.gatewayClient.getPoolData({token0:s,token1:a,fee:n}),u=this.calculatePriceFromSqrtPriceX96(new i(c.sqrtPrice));return{tokenA:e,tokenB:t,feeTier:n,liquidity:c.liquidity.toString(),sqrtPriceX96:c.sqrtPrice.toString(),tick:c.tick,feeGrowthGlobal0X128:c.feeGrowthGlobal0.toString(),feeGrowthGlobal1X128:c.feeGrowthGlobal1.toString(),currentPrice:u.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),o=jn(r.currentPrice);return{tokenA:e,tokenB:t,feeTier:n,price:o.toFixed(),invertedPrice:Xn(o,!0),tick:r.tick,liquidity:r.liquidity}}catch(e){this.handleGSwapError("Failed to calculate spot price",U,e)}}async calculateOptimalPositionSize(e,t,n,r,o,a,c){try{this.logger.debug("Calculating optimal position size",{tokenA:e,tokenB:t,desiredAmount0:r,desiredAmount1:o});const u=(await this.getPoolData(e,t,n)).tick,l=s.tickToSqrtPrice(a),h=s.tickToSqrtPrice(u),d=s.tickToSqrtPrice(c),f=s.getLiquidityForAmounts(new i(r),new i(o),l,h,d),p=s.getAmountsForLiquidity(f,h,l,d),g=p[0],m=p[1],y=new i(r),w=new i(o);return{amount0:g.toFixed(),amount1:m.toFixed(),liquidity:f.toFixed(),ratio:g.dividedBy(m).toFixed(),utilizationPercent:{amount0:g.dividedBy(y).multipliedBy(100).toFixed(2),amount1:m.dividedBy(w).multipliedBy(100).toFixed(2)}}}catch(e){this.handleGSwapError("Failed to calculate optimal position size",L,e)}}async validatePositionParameters(e,t,n,r,o,s,a){const c=[],u=[];try{this.logger.debug("Validating position parameters",{tokenA:e,tokenB:t,tickLower:r,tickUpper:o});const l=[500,3e3,1e4];l.includes(n)||c.push(`Invalid fee tier: ${n}. Must be one of: ${l.join(", ")}`);const h=this.getTickSpacing(n);let d;r%h!==0&&c.push(`tickLower must be multiple of ${h}`),o%h!==0&&c.push(`tickUpper must be multiple of ${h}`),r>=o&&c.push(`tickLower (${r}) must be less than tickUpper (${o})`);try{d=await this.getPoolData(e,t,n)}catch{return c.push(`Pool not found for ${e}/${t} at fee tier ${n}`),{valid:!1,errors:c,warnings:u,gasEstimate:0}}const f=new i(s),p=new i(a);if(f.isNaN()||p.isNaN())c.push("Amounts must be valid numbers");else try{Qn(f,p)}catch(e){c.push(`Liquidity amounts must be non-negative: ${e.message}`)}const g=d.tick;(g<r||g>o)&&u.push("Position is out of current price range - will not earn fees until price moves into range");new i(d.liquidity||"0").lt("1000000")&&u.push("Low pool liquidity - consider higher slippage tolerance");const m=0===c.length?35e4:0;return{valid:0===c.length,errors:c,warnings:u,gasEstimate:m,tickSpacing:h,currentTick:g,poolLiquidity:d.liquidity}}catch(e){const t=e;return c.includes(t?.message||"")||c.push(`Validation failed: ${t?.message||String(e)}`),{valid:!1,errors:c,warnings:u,gasEstimate:0}}}async calculateTicksForPrice(e,t,n,r,o){try{this.logger.debug("Calculating ticks for price range",{tokenA:e,tokenB:t,minPrice:n,maxPrice:r});const s=this.getTickSpacing(o),a=new i(n),c=new i(r);if(a.gte(c))throw new Error("minPrice must be less than maxPrice");const u=Math.floor(Vn(a)),l=Math.ceil(Vn(c)),h=Math.floor(u/s)*s,d=Math.ceil(l/s)*s,f=Math.pow(1.0001,h),p=Math.pow(1.0001,d),g=new i(f),m=new i(p);return{tokenA:e,tokenB:t,feeTier:o,tickLower:h,tickUpper:d,tickSpacing:s,requestedMinPrice:n,requestedMaxPrice:r,actualMinPrice:g.toFixed(8),actualMaxPrice:m.toFixed(8),priceDeviation:{minPriceDeviation:g.minus(a).dividedBy(a).multipliedBy(100).toFixed(4),maxPriceDeviation:m.minus(c).dividedBy(c).multipliedBy(100).toFixed(4)}}}catch(e){this.handleGSwapError("Failed to calculate ticks for price",L,e)}}async calculatePriceForTicks(e,t,n,r){try{this.logger.debug("Calculating price for ticks",{tokenA:e,tokenB:t,tickLower:n,tickUpper:r});const o=Math.pow(1.0001,n),s=Math.pow(1.0001,r);let a;try{a=(await this.getPoolData(e,t,3e3)).currentPrice}catch{}const c=new i(o),u=new i(s),l={tokenA:e,tokenB:t,tickLower:n,tickUpper:r,minPrice:c.toFixed(8),maxPrice:u.toFixed(8),priceRange:`${c.toFixed(4)} - ${u.toFixed(4)}`,tickSpread:r-n};return void 0!==a&&(l.currentPrice=a),l}catch(e){this.handleGSwapError("Failed to calculate price for ticks",L,e)}}calculateExecutionPrice(e,t){try{const n=new i(e),r=new i(t);return n.isZero()?"0":r.dividedBy(n).toFixed()}catch{return"0"}}getTickSpacing(e){switch(e){case 500:return 10;case 3e3:return 60;case 1e4:return 200;default:throw new Error(`Invalid fee tier: ${e}`)}}validateTickSpacing(e,t,n){const r=this.getTickSpacing(n);if(e%r!==0)throw new Error(`Invalid tickLower: ${e} must be a multiple of ${r} for fee tier ${n}. Tip: Use getAllSwapUserLiquidityPositions() to discover valid positions with correct tick spacing.`);if(t%r!==0)throw new Error(`Invalid tickUpper: ${t} must be a multiple of ${r} for fee tier ${n}. Tip: Use getAllSwapUserLiquidityPositions() to discover valid positions with correct tick spacing.`)}calculatePriceFromSqrtPriceX96(e){try{const t=new i(2).pow(96);return e.dividedBy(t).pow(2)}catch{return new i(0)}}calculatePriceFromSqrtPriceDecimal(e){try{return e.pow(2)}catch{return new i(0)}}async getPoolSlot0(e,n,r){try{this.logger.debug("Fetching pool slot0 data",{token0:e,token1:n,fee:r});const o="string"==typeof e?so(e):e,i="string"==typeof n?so(n):n,s=`${this.galaChainBaseUrl}/api/asset/dexv3-contract/GetSlot0`,a=await t.post(s,{token0:o,token1:i,fee:r},{headers:{"Content-Type":"application/json",Accept:"application/json"}});if(200!==a.status||1!==a.data?.Status)throw this.logger.warn("Unexpected GetSlot0 API response",{httpStatus:a.status,apiStatus:a.data?.Status}),new U("GetSlot0 API returned unexpected status",{httpStatus:a.status,apiStatus:a.data?.Status});const c=a.data.Data||{},u={sqrtPrice:c.sqrtPrice||"0",tick:c.tick||0,liquidity:c.liquidity||"0",grossPoolLiquidity:c.grossPoolLiquidity||"0"};return this.logger.debug("Retrieved pool slot0 data",{sqrtPrice:u.sqrtPrice,tick:u.tick,liquidity:u.liquidity}),u}catch(t){this.handleGSwapError("Failed to fetch pool slot0 data",U,t,{token0:e,token1:n,fee:r})}}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=new i(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=Hn(t),o=Hn(n);return s.liquidity0(e,r,o)}catch{return new i(0)}}calculateLiquidityFromAmount1(e,t,n){try{const r=Hn(t),o=Hn(n);return s.liquidity1(e,r,o)}catch{return new i(0)}}calculateAmount0FromLiquidity(e,t,n){try{const r=Hn(t),o=Hn(n);return s.getAmount0Delta(r,o,e)}catch{return new i(0)}}calculateAmount1FromLiquidity(e,t,n){try{const r=Hn(t),o=Hn(n);return s.getAmount1Delta(r,o,e)}catch{return new i(0)}}convertTokenPair(e,t){return{gswapToken0:this.tokenConverter.toLaunchpadFormat(e),gswapToken1:this.tokenConverter.toLaunchpadFormat(t)}}async sendAddLiquidityToBundler(e){if(!this.privateKey)throw new Error("GSwapService: AddLiquidity requires wallet (full-access mode)");if(!this.bundlerBaseUrl)throw new Error("GSwapService: Bundler URL not configured");try{this.logger.debug("Sending AddLiquidity to bundler",{token0:e.token0?.type??"unknown",token1:e.token1?.type??"unknown",fee:e.fee,tickRange:`${e.tickLower}-${e.tickUpper}`});const r=`galaswap - operation - ${c.v4()}-${Date.now()}-${e.owner}`,o={token0:e.token0,token1:e.token1,fee:e.fee,owner:e.owner,tickLower:e.tickLower,tickUpper:e.tickUpper,amount0Desired:e.amount0Desired,amount1Desired:e.amount1Desired,amount0Min:e.amount0Min,amount1Min:e.amount1Min,positionId:"",uniqueKey:r},i=new n.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},u=this.calculatePersonalSignPrefix(o),l={...o,prefix:u},h=await i.signTypedData(a,s,l),d={...l,signature:h,types:s,domain:a};this.logger.debug("AddLiquidity DTO signed with manual types",{signature:d.signature?.substring(0,20)+"...",prefix:d.prefix,tickLower:o.tickLower,tickUpper:o.tickUpper});const f=this.buildLiquidityStringsInstructions(e.token0,e.token1,e.fee,e.owner),p=t.create({baseURL:this.bundlerBaseUrl,timeout:3e4}),g=await p.post("/bundle",{method:"AddLiquidity",signedDto:d,stringsInstructions:f}),m=g.data?.data||g.data?.transactionId||g.data?.id;if(!m)throw this.logger.error("Bundler response structure",{status:g.status,data:g.data,dataType:typeof g.data}),new Error(`Bundler response does not contain transaction ID. Response: ${JSON.stringify(g.data)}`);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(e,r,o,i,s,a,u,l,h){try{if(!this.bundlerBaseUrl)throw new Error("GSwapService: Bundler URL not configured");const d=new n.ethers.Wallet(this.privateKey),f=await d.getAddress(),p=`galaswap - operation - ${c.v4()}-${Date.now()}-${f}`,g={tickLower:e,tickUpper:r,amount:o,token0:i,token1:s,fee:a,amount0Min:u,amount1Min:l,positionId:h,uniqueKey:p},m={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"}]},y={name:"ethereum",chainId:1},w=this.calculatePersonalSignPrefix(g),b={...g,prefix:w},k=await d.signTypedData(y,m,b),v={...b,signature:k,types:m,domain:y},E=this.buildLiquidityStringsInstructions(i,s,a,f);this.logger.debug("Submitting RemoveLiquidity to bundler",{tickLower:e,tickUpper:r,amount:o,fee:a,positionId:h,transactionId:p});const S=t.create({baseURL:this.bundlerBaseUrl,timeout:3e4}),T=await S.post("/bundle",{method:"RemoveLiquidity",signedDto:v,stringsInstructions:E}),A=T.data?.data||T.data?.transactionId||T.data?.id;if(!A)throw this.logger.error("Bundler response structure",{status:T.status,data:T.data,dataType:typeof T.data}),new Error(`Bundler response does not contain transaction ID. Response: ${JSON.stringify(T.data)}`);return this.logger.info("RemoveLiquidity transaction sent to bundler",{transactionId:A}),A}catch(e){throw this.logger.error("Failed to send RemoveLiquidity to bundler",e),e}}async sendCollectPositionFeesToBundler(e,r,o,i,s,a,u,l){try{if(!this.bundlerBaseUrl)throw new Error("GSwapService: Bundler URL not configured");const h=new n.ethers.Wallet(this.privateKey),d=await h.getAddress(),f=`galaswap - operation - ${c.v4()}-${Date.now()}-${d}`,p={token0:e,token1:r,fee:o,amount0Requested:i,amount1Requested:s,tickLower:a,tickUpper:u,positionId:l,uniqueKey:f},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"}]},m={name:"ethereum",chainId:1},y=this.calculatePersonalSignPrefix(p),w={...p,prefix:y},b=await h.signTypedData(m,g,w),k={...w,signature:b,types:g,domain:m},v=this.buildLiquidityStringsInstructions(e,r,o,d);this.logger.debug("Submitting CollectPositionFees to bundler",{fee:o,amount0Requested:i,amount1Requested:s,tickLower:a,tickUpper:u,positionId:l,transactionId:f});const E=t.create({baseURL:this.bundlerBaseUrl,timeout:3e4}),S=await E.post("/bundle",{method:"CollectPositionFees",signedDto:k,stringsInstructions:v}),T=S.data?.data||S.data?.transactionId||S.data?.id;if(!T)throw this.logger.error("Bundler response structure",{status:S.status,data:S.data,dataType:typeof S.data}),new Error(`Bundler response does not contain transaction ID. Response: ${JSON.stringify(S.data)}`);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(e){if(!this.privateKey)throw new Error("GSwapService: Swap requires wallet (full-access mode)");if(!this.bundlerBaseUrl)throw new Error("GSwapService: Bundler URL not configured");const r=[500,3e3,1e4];if(!r.includes(e.feeTier))throw new Error(`GSwapService: Invalid fee tier ${e.feeTier}. Must be one of: ${r.join(", ")} (basis points)`);try{this.logger.debug("Sending Swap to bundler",{fromToken:"string"==typeof e.fromToken?e.fromToken:e.fromToken?.type??"unknown",toToken:"string"==typeof e.toToken?e.toToken:e.toToken?.type??"unknown",inputAmount:e.inputAmount,minOutput:e.minOutput,feeTier:e.feeTier});let r=e.fromToken,o=e.toToken;"string"==typeof r&&(r=so(r)),"string"==typeof o&&(o=so(o));const s=`${r.collection}|${r.category}|${r.type}|${r.additionalKey}`,a=`${o.collection}|${o.category}|${o.type}|${o.additionalKey}`,u=s<a?[r,o,s,a]:[o,r,a,s],[l,h,d,f]=u,p="string"==typeof e.fromToken?so(e.fromToken):e.fromToken,g=`${p.collection}|${p.category}|${p.type}|${p.additionalKey}`,m=g===d,y=`galaswap - operation - ${c.v4()}-${Date.now()}-${e.walletAddress}`;let w;if(!e.currentSqrtPrice)throw new Error("GSwapService: currentSqrtPrice is required for sqrtPriceLimit calculation");const b=new i(e.currentSqrtPrice),k=e.slippageTolerance??.01;if(m){const e=new i(1).minus(k);w=b.multipliedBy(e).toString()}else{const e=new i(1).plus(k);w=b.multipliedBy(e).toString()}this.logger.debug("Calculated sqrtPriceLimit based on slippage tolerance",{currentSqrtPrice:e.currentSqrtPrice,slippageTolerance:100*k+"%",zeroForOne:m,sqrtPriceLimit:w,direction:m?"token0→token1 (downward price movement)":"token1→token0 (upward price movement)",reason:"sqrtPriceLimit sets price boundaries, amountOutMinimum provides volume protection"});const v={token0:l,token1:h,fee:e.feeTier,amount:new i(e.inputAmount).toFixed(),zeroForOne:m,sqrtPriceLimit:w,recipient:e.walletAddress,amountOutMinimum:new i(e.minOutput).multipliedBy(-1).toFixed(),uniqueKey:y};this.logger.info("🔄 SWAP DTO DETAILS (what we're sending to bundler)",{orderedToken0String:d,orderedToken1String:f,fromTokenStr:g,zeroForOne:m?`TRUE (${d} → ${f})`:`FALSE (${f} → ${d})`,inputAmount:e.inputAmount,expectedOutput:e.minOutput,slippageTolerance:100*(e.slippageTolerance||.01)+"%",currentSqrtPrice:e.currentSqrtPrice,swapDto:{amount:v.amount,zeroForOne:v.zeroForOne,sqrtPriceLimit:v.sqrtPriceLimit,amountOutMinimum:v.amountOutMinimum}});const E=new n.ethers.Wallet(this.privateKey),S={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"}]},T={name:"ethereum",chainId:1},A=this.calculatePersonalSignPrefix(v),I={...v,prefix:A},B=await E.signTypedData(T,S,I),x={...I,signature:B,types:S,domain:T};this.logger.debug("Swap DTO signed",{signature:x.signature?.substring(0,20)+"...",prefix:x.prefix,zeroForOne:v.zeroForOne});const C=this.buildLiquidityStringsInstructions(l,h,e.feeTier,e.walletAddress),P=t.create({baseURL:this.bundlerBaseUrl,timeout:3e4}),N=await P.post("/bundle",{method:"Swap",signedDto:x,stringsInstructions:C}),_=N.data?.data||N.data?.transactionId||N.data?.id;if(!_)throw this.logger.error("Bundler response structure",{status:N.status,data:N.data,dataType:typeof N.data}),new Error(`Bundler response does not contain transaction ID. Response: ${JSON.stringify(N.data)}`);return this.logger.debug("Swap transaction sent to bundler",{transactionId:_,inputAmount:e.inputAmount,minOutput:e.minOutput}),_}catch(e){throw this.logger.error("Failed to send Swap to bundler",e),e}}buildLiquidityStringsInstructions(e,t,n,r){const o=`$${e.collection}$${e.category}$${e.type}$${e.additionalKey}`,i=`$${t.collection}$${t.category}$${t.type}$${t.additionalKey}`,s=`$pool${o}${i}$${n}`;return[s,`$userPosition${r}`,`$tokenBalance${o}${r}`,`$tokenBalance${i}${r}`,`$tokenBalance${o}${s}`,`$tokenBalance${i}${s}`]}handleGSwapError(e,t,n,r){this.logger.error(e,n);const o=this.extractGSwapErrorCode(n),i=n,s=[`${e}: ${i?.message||String(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)),o&&s.push(o),new t(...s)}extractGSwapErrorCode(e){if(e&&"object"==typeof e){const t=e;if(t.constructor&&"GSwapSDKError"===t.constructor.name)return t.code;if("code"in t&&"string"==typeof t.code)return t.code}}async ensureWebSocketConnected(){this.webSocketService.isConnected()||await this.webSocketService.connect()}calculatePersonalSignPrefix(e){return`Ethereum Signed Message:\n${JSON.stringify(e).length}${JSON.stringify(e)}`}}class yo{}yo.BASE_PRICE=1650667151e-14,yo.PRICE_SCALING_FACTOR=1166069e-12,yo.TRADING_FEE_FACTOR=.001,yo.GAS_FEE="1",yo.MIN_UNBONDING_FEE_FACTOR=0,yo.MAX_UNBONDING_FEE_FACTOR=.5,yo.NET_UNBONDING_FEE_FACTOR=.5,yo.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY=1e7;class wo extends En{constructor(e=!1){super(e),this.cache=new Map}getLRUKey(){const e=this.cache.keys().next().value;return void 0!==e?e:null}normalizeTokenName(e){return e.trim().toLowerCase().replace(/\s+/g," ").replace(/[\u0000-\u001F\u007F-\u009F\u200B-\u200D\uFEFF]/g,"")}updateCacheEntry(e,t){const n=this.cache.get(e);if(this.cache.has(e)&&this.cache.delete(e),this.cache.size>=wo.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.normalizeTokenName(e);this.updateCacheEntry(n,t)}set(e,t){const n=this.normalizeTokenName(e);this.updateCacheEntry(n,t)}get(e){const t=this.normalizeTokenName(e);return this.cache.get(t)||null}getMaxSupply(e){const t=this.normalizeTokenName(e),n=this.cache.get(t);return n?.maxSupply||yo.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY.toString()}has(e){const t=this.normalizeTokenName(e);return this.cache.has(t)}clear(e){if(e){const t=this.normalizeTokenName(e);this.cache.delete(t)}else this.cache.clear()}dump(){const e={};return this.cache.forEach((t,n)=>{e[n]=t}),e}stats(){let e=Date.now(),t=0;return this.cache.forEach((n,r)=>{n.lastUpdated<e&&(e=n.lastUpdated);let o=0;o+=2*r.length,void 0!==n.reverseBondingCurveMinFeeFactor&&(o+=8),void 0!==n.reverseBondingCurveMaxFeeFactor&&(o+=8),void 0!==n.reverseBondingCurveNetFeeFactor&&(o+=8),o+=8,n.vaultAddress&&(o+=2*n.vaultAddress.length),n.maxSupply&&(o+=2*n.maxSupply.length),n.symbol&&(o+=2*n.symbol.length),o+=32,t+=o}),{totalTokens:this.cache.size,cacheSize:t,oldestEntry:this.cache.size>0?e:0}}getByTokenId(e){const t=`token:${e.toLowerCase().trim()}`;return this.cache.get(t)||null}setByTokenId(e,t){const n=`token:${e.toLowerCase().trim()}`;this.updateCacheEntry(n,t)}hasByTokenId(e){const t=`token:${e.toLowerCase().trim()}`;return this.cache.has(t)}}wo.MAX_CACHE_SIZE=1e4;class bo extends vn{constructor(e,t,n=void 0,r=5,o=!1){super(e,o),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:e.message})})}),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:e.message})})})}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),o=await Promise.allSettled(r.map(e=>e.task));for(let e=0;e<r.length;e++){const t=r[e],i=o[e],s=n.get(t.poolIndex)||{};"fulfilled"===i.status&&i.value&&(t.isToken0?s.token0Price=i.value:s.token1Price=i.value),n.set(t.poolIndex,s)}}const r=e.map((e,t)=>{const r=n.get(t)||{},o={...e};return void 0!==r.token0Price&&(o.token0Price=r.token0Price),void 0!==r.token1Price&&(o.token1Price=r.token1Price),o}),o=r.filter(e=>e.token0Price&&e.token1Price).length;return this.logger.debug("Pricing enrichment complete",{total:e.length,successful:o,failed:e.length-o}),r}async fetchDexPools(e={}){const{search:t,sortBy:n="tvl",sortOrder:r="desc",page:o=kn.DEFAULT_PAGE,limit:i=kn.DEFAULT_LIMIT,withPrices:s=!1}=e;this.logger.debug("Fetching DEX pools",{search:t,sortBy:n,sortOrder:r,page:o,limit:i,withPrices:s});const a=new URLSearchParams({page:o.toString(),limit:Math.min(i,20).toString(),sortBy:n,sortOrder:r});t&&a.append("search",t);const c=`${this.dexBackendBaseUrl}/explore/pools?${a}`;try{const e=await this.http.get(c);if(!e||!e.data)throw new Error("No response from DEX pool service");let t=e.data.pools;const n=e.data.count,r=Math.min(i,20),a=Math.ceil(n/r);return s&&(t=await this.enrichPoolsWithPricing(t)),this.logger.debug("DEX pools fetched successfully",{poolCount:t.length,total:n,totalPages:a,withPrices:s}),{pools:t,page:o,limit:r,total:n,totalPages:a,...nn(o,a)}}catch(e){throw this.logger.error("Failed to fetch DEX pools",{error:e,url:c}),e}}async fetchAllDexPools(e={}){this.logger.debug("Fetching all DEX pools (auto-paginated)",e);const t=await no((t,n)=>this.fetchDexPools({...e,page:t,limit:n}).then(e=>({items:e.pools,page:e.page,limit:e.limit,total:e.total,totalPages:e.totalPages,hasNext:e.hasNext,hasPrevious:e.hasPrevious})),{maxPages:1e4,logger:this.logger,pageSize:20});this.logger.debug("All DEX pools fetched",{totalPoolsFetched:t.items.length,totalCount:t.total,withPrices:e.withPrices});return ro(t.items,t.total,"pools")}}class ko extends vn{constructor(e,t,n=!1,r=3e4){super(e,n),this.compositePoolFetchConcurrency=5,this.galaChainBaseUrl=t,this.networkTimeout=r}validateFetchCompositePoolDataInput(e,t,n){if(!e||"string"!=typeof e)throw new O("token0 must be a non-empty string",{token0:e});if(!t||"string"!=typeof t)throw new O("token1 must be a non-empty string",{token1:t});const r=e.split("|"),o=t.split("|");if(4!==r.length)throw new O("token0 format must be: collection|category|type|additionalKey (4 pipe-separated parts)",{token0:e});if(4!==o.length)throw new O("token1 format must be: collection|category|type|additionalKey (4 pipe-separated parts)",{token1:t});const i=[500,3e3,1e4];if(!Number.isInteger(n)||!i.includes(n))throw new O(`fee must be one of: ${i.join(", ")} (got ${n})`,{fee:n})}validateQuoteAmount(e){if(!e||"string"!=typeof e)throw new O("amount must be a non-empty string",{amount:e});const t=new i(e);try{Zn(t,"amount","for quote calculation")}catch(t){throw new O(t.message,{amount:e})}}convertTokenClassKey(e){const t=new a.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:o}=e;this.logger.debug("Fetching composite pool data",{token0:t,token1:n,fee:r}),this.validateFetchCompositePoolDataInput(t,n,r);try{const e=fo(t),c=fo(n),u=this.convertTokenClassKey(e),l=this.convertTokenClassKey(c),h=new s.GetCompositePoolDto(u,l,r),d=`${o||this.galaChainBaseUrl}/api/asset/dexv3-contract/GetCompositePool`,f=await this.http.post(d,h);if(!f||1!==f.Status)throw new F(`Pool not found: ${t}/${n} with fee ${r}`);const p=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 s.Pool(e.pool.token0,e.pool.token1,e.pool.token0ClassKey,e.pool.token1ClassKey,e.pool.fee,new i(e.pool.sqrtPrice),e.pool.protocolFees);t.bitmap=e.pool.bitmap,t.grossPoolLiquidity=new i(e.pool.grossPoolLiquidity),t.liquidity=new i(e.pool.liquidity),t.feeGrowthGlobal0=new i(e.pool.feeGrowthGlobal0),t.feeGrowthGlobal1=new i(e.pool.feeGrowthGlobal1),t.protocolFeesToken0=new i(e.pool.protocolFeesToken0),t.protocolFeesToken1=new i(e.pool.protocolFeesToken1),t.tickSpacing=e.pool.tickSpacing,t.maxLiquidityPerTick=new i(e.pool.maxLiquidityPerTick);const n={};Object.keys(e.tickDataMap).forEach(t=>{const r=e.tickDataMap[t],o=new s.TickData(r.poolHash,r.tick);o.initialised=r.initialised,o.liquidityNet=new i(r.liquidityNet),o.liquidityGross=new i(r.liquidityGross),o.feeGrowthOutside0=new i(r.feeGrowthOutside0),o.feeGrowthOutside1=new i(r.feeGrowthOutside1),n[t]=o});const r={...e.token0Balance},o=new a.TokenBalance(r);o.quantity=new i(e.token0Balance.quantity);const c={...e.token1Balance},u=new a.TokenBalance(c);return u.quantity=new i(e.token1Balance.quantity),new s.CompositePoolDto(t,n,o,u,e.token0Decimals,e.token1Decimals)}(f.Data),f.Data);return this.logger.debug("Composite pool data fetched successfully",{token0:t,token1:n,fee:r,liquidity:p.pool.liquidity.toString()}),p}catch(e){if(e instanceof F)throw e;const o=e instanceof Error?e.message:String(e);throw this.logger.error("Failed to fetch composite pool data",e),new O(`Failed to fetch composite pool data: ${o}`,{token0:t,token1:n,fee:r})}}async calculateDexPoolQuoteExactAmountLocal(e){const{compositePoolData:t,fromToken:n,toToken:r,amount:o}=e;if(this.logger.debug("Calculating local DEX quote",{fromToken:n,toToken:r,amount:o}),this.validateQuoteAmount(o),!t)throw new O("compositePoolData is required for local quote calculation",{compositePoolData:t});try{const e=n===t.pool.token0.replace(/\$/g,"|"),a=fo(n),c=fo(r),u=this.convertTokenClassKey(a),l=this.convertTokenClassKey(c),[h,d]=n<r?[u,l]:[l,u],f=new s.QuoteExactAmountDto(h,d,t.pool.fee,new i(o),e,t.compositePoolDto),p=await s.quoteExactAmount(void 0,f);return this.logger.debug("Local quote calculated",{amount0:p.amount0,amount1:p.amount1}),{amount0:p.amount0.toString(),amount1:p.amount1.toString(),currentSqrtPrice:p.currentSqrtPrice.toString(),newSqrtPrice:p.newSqrtPrice.toString()}}catch(e){const t=e instanceof Error?e.message:String(e);throw this.logger.error("Local quote calculation failed",e),new O(`Local quote calculation failed: ${t}`,{fromToken:n,toToken:r,amount:o})}}async calculateDexPoolQuoteExactAmountExternal(e){const{compositePoolData:t,fromToken:n,toToken:r,amount:o}=e;if(this.logger.debug("Calculating external DEX quote",{fromToken:n,toToken:r,amount:o}),this.validateQuoteAmount(o),!t)throw new O("compositePoolData is required for external quote calculation (token format info)",{compositePoolData:t});try{const e=n===t.pool.token0.replace(/\$/g,"|"),a=fo(n),c=fo(r),u=this.convertTokenClassKey(a),l=this.convertTokenClassKey(c),h=new s.QuoteExactAmountDto(u,l,t.pool.fee,new i(o),e,void 0),d=`${this.galaChainBaseUrl}/api/asset/dexv3-contract/QuoteExactAmount`,f=await this.http.post(d,h);if(!f||1!==f.Status)throw new O("External quote failed: "+(f?.Message||"Unknown error"));const p=f.Data;return this.logger.debug("External quote calculated",{amount0:p.amount0,amount1:p.amount1}),{amount0:p.amount0.toString(),amount1:p.amount1.toString(),currentSqrtPrice:p.currentSqrtPrice.toString(),newSqrtPrice:p.newSqrtPrice.toString()}}catch(e){const t=e instanceof Error?e.message:String(e);throw this.logger.error("External quote calculation failed",e),new O(`External quote calculation failed: ${t}`,{fromToken:n,toToken:r,amount:o})}}async calculateDexPoolQuoteExactAmount(e,t="local"){return"external"===t?this.calculateDexPoolQuoteExactAmountExternal(e):this.calculateDexPoolQuoteExactAmountLocal(e)}}class vo{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=Math.floor(.5*e.length),n=Math.floor(.95*e.length),r=Math.floor(.99*e.length);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 e/this.eventsProcessed*100}getThroughputPerSecond(){const e=(Date.now()-this.startTime)/1e3;return 0===e?0:this.eventsProcessed/e}recordMemory(){if("undefined"!=typeof process&&process.memoryUsage){const e=process.memoryUsage().heapUsed/1024/1024;this.memorySnapshots.push(e),this.memorySnapshots.length>this.maxMemorySnapshots&&this.memorySnapshots.shift()}}getMemoryUsedMB(){return"undefined"!=typeof process&&process.memoryUsage?process.memoryUsage().heapUsed/1024/1024:0}getPoolAverageLatency(e){const t=this.perPoolMetrics.get(e);return t&&0!==t.eventsProcessed?t.totalLatency/t.eventsProcessed:0}getPoolCacheHitRate(e){const t=this.perPoolMetrics.get(e);if(!t)return 0;const n=t.cacheHits+t.cacheMisses;return 0===n?0:t.cacheHits/n*100}getHealthMetrics(e,t,n,r,o){const i=this.getLatencyPercentiles(),s=this.getMemoryUsedMB();return{eventProcessing:{queueDepth:this.queueDepth,eventsProcessed:this.eventsProcessed,eventsDropped:this.eventsDropped,throughputPerSecond:this.getThroughputPerSecond()},metrics:{latencyP50:i.p50,latencyP95:i.p95,latencyP99:i.p99,cacheHitRate:this.getCacheHitRate()},memory:{usedMB:Math.round(10*s)/10,maxMB:o,percentUsed:Math.round(s/o*1e3)/10},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?this.eventLatencies.reduce((e,t)=>e+t,0)/this.eventLatencies.length:0;return{eventsProcessed:this.eventsProcessed,eventsDropped:this.eventsDropped,cacheHitRate:this.getCacheHitRate(),averageLatency:Math.round(e),memoryUsedMB:Math.round(10*this.getMemoryUsedMB())/10,throughputPerSecond:Math.round(100*this.getThroughputPerSecond())/100}}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 Eo{static createPoolKey(e,t,n){return`${e}/${t}/${n}`}static parsePoolKey(e){if(!e||"string"!=typeof e)return null;const t=e.split("/");if(3!==t.length)return null;const n=t[0]?.trim(),r=t[1]?.trim(),o=t[2]?.trim();if(!n||!r||!o)return null;const i=Number.parseInt(o,10);return Number.isNaN(i)?null:{token0:n,token1:r,feeTier:i}}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 o=r.token0===t||r.token1===t,i=r.token0===n||r.token1===n;return o&&i&&t!==n}static normalizeFee(e){if(null==e)return null;const t="number"==typeof e?e:Number.parseFloat(String(e).replace("%","").trim());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`${(e/1e4).toFixed(2)}%`}static isValidTokenPair(e,t){return Boolean(e)&&Boolean(t)&&e!==t}}class So{constructor(e){this.logger=e||new S({debug:!1,context:"SwapEventExtractor"})}walkPayloadForSwaps(e,t){const n=[],r=new WeakSet,o=(e,i=0)=>{if(i>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))o(t,i+1)}};return o(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,o=this.extractToken(r,"token0","fromToken","source"),i=this.extractToken(r,"token1","toToken","destination");if(!o||!i)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(o,i,c),h=this.determineDirection(r,o,i),d={transactionId:t,poolKey:l,token0:o,token1:i,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("string"==typeof t&&t.trim())return t}return null}extractToken(e,...t){for(const n of t){const t=e[n];if("string"==typeof t&&t.trim())return t}return null}extractAmount(e,...t){for(const n of t){const t=e[n];if(null!=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(null==e)return null;const t="number"==typeof e?e:Number.parseFloat(String(e).replace("%","").trim());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("string"==typeof t&&t.trim())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("zerotoone"===r.toLowerCase()||"0to1"===r)return"zeroForOne";if("onetozero"===r.toLowerCase()||"1to0"===r)return"oneForZero"}if(e.fromToken===t||e.inputToken===t)return"zeroForOne";if(e.fromToken===n||e.inputToken===n)return"oneForZero";const o=this.extractAmount(e,"amount0","amountIn");return o&&Number(o),"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,o=void 0!==e.inputAmount&&null!==e.inputAmount,i=void 0!==e.outputAmount&&null!==e.outputAmount;return!(!n||r)||!(r&&!n)&&(!(!o||i)||!(i&&!o))}buildPoolKey(e,t,n){return`${e}/${t}/${n}`}}class To{static getCached(e){const t=e.toString();return this.CACHE.has(t)||this.CACHE.set(t,new i(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])}}}To.CACHE=new Map,To.ZERO=new i(0),To.ONE=new i(1),To.FEE_PIPS=new i(1e6),To.MIN_SQRT_RATIO=new i("4295128739"),To.MAX_SQRT_RATIO=new i("1461446703485210103287273052203988822378723970342");const Ao={maxIterations:100,enableBigNumberCache:!0,roundingMode:i.ROUND_DOWN,debugLogging:!1};class Io{static calculateSwapDelta(e,t,n={}){const r=Date.now(),o={...Ao,...n};try{const n=this.initializeSwapState(e,t,o);o.debugLogging&&this.logger.debug("Initialized swap state",{sqrtPrice:n.sqrtPrice.toString(),liquidity:n.liquidity.toString(),tick:n.tick,zeroForOne:t.zeroForOne});const s=this.computeSwapLoop(n,e,t,o);o.debugLogging&&this.logger.debug("Swap loop completed",{stepCount:s.stepCount,ticksCrossed:s.ticksCrossed.length,priceHitLimit:s.priceHitLimit});const a=this.createUpdatedPool(e.pool,s.state,t,o),c=this.calculateFinalAmounts(n,s.state,t);let u;if(t.actualSqrtPrice){const e=new i(a.sqrtPrice),n=new i(t.actualSqrtPrice);u=e.minus(n).abs().div(n).times(100).toNumber()}const l=Date.now()-r;o.debugLogging&&this.logger.debug("Swap delta calculated",{calculationTimeMs:l,amount0:c.amount0.toString(),amount1:c.amount1.toString(),driftPercentage:u}),l>100&&this.logger.warn("Swap calculation exceeded 100ms",{calculationTimeMs:l,stepCount:s.stepCount,ticksCrossed:s.ticksCrossed.length}),s.priceHitLimit&&this.logger.warn("Swap price hit limit - partially fulfilled",{zeroForOne:t.zeroForOne,stepCount:s.stepCount}),s.stepCount>50&&this.logger.warn("Unusually complex swap detected",{stepCount:s.stepCount,ticksCrossed:s.ticksCrossed.length});return{updatedPool:a,updatedTicks:s.updatedTicks,amount0:c.amount0,amount1:c.amount1,feeAmount0:c.feeAmount0,feeAmount1:c.feeAmount1,ticksCrossed:s.ticksCrossed,metadata:{calculationTimeMs:l,swapSteps:s.stepCount,priceHitLimit:s.priceHitLimit,...void 0!==u&&{driftPercentage:u}}}}catch(e){this.logger.error("Swap delta calculation failed",e);const t=e instanceof Error?e.message:String(e);throw new Error(`Swap delta calculation failed: ${t}`)}}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 o=n.enableBigNumberCache?To.getCached.bind(To):e=>new i(e),a="string"==typeof r.sqrtPrice?r.sqrtPrice:new i(r.sqrtPrice).toFixed(0),c="string"==typeof r.liquidity?r.liquidity:new i(r.liquidity).toFixed(0),u=o(a),l=o(c),h=r.tick??0,d=s.sqrtPriceToTick(new i(a)),f=Math.abs(d-h);f>100&&this.logger.warn("Significant tick/price mismatch detected in pool state",{poolTick:h,calculatedTick:d,drift:f,threshold:100});const p=o(t.amountSpecified);Zn(p,"amountSpecified","for swap operation");const g="string"==typeof r.feeGrowthGlobal1?r.feeGrowthGlobal1:new i(r.feeGrowthGlobal1).toFixed(0),m="string"==typeof r.feeGrowthGlobal0?r.feeGrowthGlobal0:new i(r.feeGrowthGlobal0).toFixed(0),y=t.zeroForOne?o(g):o(m);return{sqrtPrice:u,liquidity:l,tick:h,amountSpecifiedRemaining:p,amountCalculated:To.ZERO,feeGrowthGlobalX:y,protocolFee:To.ZERO}}static computeSwapLoop(e,t,n,r){const{pool:o,tickDataMap:a}=t,c=[],u={};let l=0;const h=n.zeroForOne?To.MIN_SQRT_RATIO:To.MAX_SQRT_RATIO,d=new i("0.000001");for(;e.amountSpecifiedRemaining.gt(d)&&!e.sqrtPrice.eq(h)&&l<r.maxIterations;){l++;const[t,d]=this.findNextInitializedTick(a,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=s.tickToSqrtPrice(t);f=e instanceof i?e:new i(String(e))}else f=h;const p=n.zeroForOne?i.max(f,h):i.min(f,h),g=this.executeSwapStep(e.sqrtPrice,p,e.liquidity,e.amountSpecifiedRemaining,o.fee,n.exactInput);if(e.sqrtPrice=g.sqrtPriceNext,n.exactInput){const t=g.amountIn.plus(g.feeAmount);t.lte(0)?e.amountSpecifiedRemaining=To.ZERO:(e.amountSpecifiedRemaining=e.amountSpecifiedRemaining.minus(t),e.amountSpecifiedRemaining.lt(0)&&(e.amountSpecifiedRemaining=To.ZERO)),e.amountCalculated=e.amountCalculated.minus(g.amountOut)}else{g.amountOut.lte(0)?e.amountSpecifiedRemaining=To.ZERO:e.amountSpecifiedRemaining=e.amountSpecifiedRemaining.plus(g.amountOut),e.amountCalculated=e.amountCalculated.plus(g.amountIn.plus(g.feeAmount))}if(e.liquidity.gt(0)){const t=g.feeAmount.div(e.liquidity);e.feeGrowthGlobalX=e.feeGrowthGlobalX.plus(t)}if(e.sqrtPrice.eq(f)&&d){const o=a[t.toString()];if(!o)throw new Error(`Missing tick data for initialized tick ${t}`);const s=n.zeroForOne?new i(o.liquidityNet).negated():new i(o.liquidityNet);if(e.liquidity=e.liquidity.plus(s),e.liquidity.lt(0))throw new Error(`Negative liquidity after crossing tick ${t}: ${e.liquidity.toString()}`);c.push(t),u[t.toString()]=o,r.debugLogging&&this.logger.debug(`Crossed tick ${t}`,{liquidityNet:s.toString(),newLiquidity:e.liquidity.toString()})}if(e.sqrtPrice.eq(f))e.tick=n.zeroForOne?t-1:t;else{const t=s.sqrtPriceToTick(new i(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:c,priceHitLimit:f,stepCount:l,updatedTicks:u}}static createUpdatedPool(e,t,n,r){const o=Object.assign(Object.create(Object.getPrototypeOf(e)),e);if(o.sqrtPrice=t.sqrtPrice.toFixed(0),o.liquidity=t.liquidity.toFixed(0),o.tick=t.tick,n.zeroForOne?o.feeGrowthGlobal1=t.feeGrowthGlobalX.toFixed(0):o.feeGrowthGlobal0=t.feeGrowthGlobalX.toFixed(0),n.zeroForOne){const n=new i(e.protocolFeesToken0);o.protocolFeesToken0=n.plus(t.protocolFee).toFixed(0)}else{const n=new i(e.protocolFeesToken1);o.protocolFeesToken1=n.plus(t.protocolFee).toFixed(0)}return o}static calculateFinalAmounts(e,t,n){let r,o,s,a;if(n.exactInput){const e=new i(n.amountSpecified),c=t.amountCalculated.abs();n.zeroForOne?(r=e.negated(),o=c,s=To.ZERO,a=To.ZERO):(r=c,o=e.negated(),s=To.ZERO,a=To.ZERO)}else{const e=new i(n.amountSpecified),c=t.amountCalculated.abs();n.zeroForOne?(r=c.negated(),o=e,s=To.ZERO,a=To.ZERO):(r=e,o=c.negated(),s=To.ZERO,a=To.ZERO)}const c=t.feeGrowthGlobalX.minus(e.feeGrowthGlobalX).times(e.liquidity);return n.zeroForOne?a=c:s=c,{amount0:r,amount1:o,feeAmount0:s,feeAmount1:a}}static findNextInitializedTick(e,t,n,r){const o=Object.keys(e).map(e=>parseInt(e,10)).sort((e,t)=>e-t);if(0===o.length){return[r?-887272:887272,!1]}if(r){const e=o.reverse().find(e=>e<t);return void 0!==e?[e,!0]:[-887272,!1]}{const e=o.find(e=>e>t);return void 0!==e?[e,!0]:[887272,!1]}}static executeSwapStep(e,t,n,r,o,a){Qn(n),Zn(r,"amountRemaining","for swap step");const c=[500,3e3,1e4];if(!c.includes(o))throw new Error(`Invalid fee tier: ${o}. Must be one of: ${c.join(", ")}`);const u=s.computeSwapStep(e,t,n,r,o,t.lt(e)),l=u[0],h=u[1],d=u[2],f=u[3],p=i.isBigNumber(l)?l:new i(String(l)),g=i.isBigNumber(h)?h:new i(String(h)),m=i.isBigNumber(d)?d:new i(String(d)),y=i.isBigNumber(f)?f:new i(String(f));return{sqrtPriceStart:e,tickNext:s.sqrtPriceToTick(p),sqrtPriceNext:p,initialised:!1,amountIn:g,amountOut:m,feeAmount:y}}}Io.logger=new S({debug:!1,context:"SwapDeltaCalculator"});class Bo{constructor(e,t,n,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.logger=r||new S({debug:!1,context:"PoolCacheManager"}),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,o){const i=this.cache.get(e);if(!i)return this.logger.debug(`Pool ${e} not in cache for delta update`),!1;try{if(o){const s="zeroForOne"===t,a=s?n:r,c={transactionId:o.transactionId,timestamp:o.timestamp,amountSpecified:a,zeroForOne:s,exactInput:o.exactInput},u=Io.calculateSwapDelta(i.poolData,c);i.poolData={...i.poolData,pool:u.updatedPool},i.swapsSinceRefetch++,i.lastDeltaAppliedTime=Date.now(),void 0!==u.metadata.driftPercentage?(i.cumulativeDrift+=u.metadata.driftPercentage,this.logger.debug(`Delta applied for ${e}: drift=${u.metadata.driftPercentage.toFixed(4)}%, cumulative=${i.cumulativeDrift.toFixed(2)}%`)):this.logger.debug(`Delta applied for ${e}: ${u.ticksCrossed.length} ticks crossed`)}else i.swapsSinceRefetch++,i.lastDeltaAppliedTime=Date.now();return this.shouldRefetch(i)&&(this.logger.debug(`Refetch needed for ${e}: swaps=${i.swapsSinceRefetch}, drift=${(100*i.cumulativeDrift).toFixed(2)}%`),i.expiresAt=Date.now()),!0}catch(t){return this.logger.error(`Failed to update pool ${e}:`,t),i.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(this.cache.has(e))return!0;try{return await this.getPool(e),this.logger.debug(`Cache warmed for ${e}`),!0}catch(t){return this.logger.error(`Failed to warm cache for ${e}:`,t),!1}}async warmCacheBatch(e,t=5){const n={succeeded:0,failed:0,total:e.length};let r=0;const o=new Set;for(;r<e.length||o.size>0;){for(;r<e.length&&o.size<t;){const t=e[r];r++;const i=this.warmCache(t).then(e=>{e?n.succeeded++:n.failed++});o.add(i),i.finally(()=>o.delete(i))}o.size>0&&await Promise.race(o)}return this.logger.debug(`Cache warming complete: ${n.succeeded}/${n.total} succeeded`),n}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 xo{constructor(e,t,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=n||new S({debug:!1,context:"SwapEventQueue"}),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(Date.now()-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=Date.now()-t;this.metrics.recordEventLatency(n)}catch(t){throw this.logger.error(`Event processing failed for ${e.transactionId}:`,t),t}}}class Co{constructor(e,t,n,r={},o){this.socket=null,this.maxSeenTransactions=1e4,this.listeners=[],this.onErrorCallbacks=[],this.isActive=!1,this.listenerRegistered=!1,this.handleSwapEvent=null,this.warmingIntervalHandle=null,this.reconnectAttempts=0,this.maxReconnectAttempts=3,this.reconnectDelayMs=1e3,this.logger=o||new S({debug:!1,context:"MultiPoolStateManager"}),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 vo,this.config=this.applyDefaults(r),this.eventExtractor=new So(this.logger),this.quoteService=n,this.cacheManager=new Bo(t,this.config,this.metrics,this.logger),this.eventQueue=new xo(this.config,this.metrics,this.logger),this.seenTransactions=new Po(this.maxSeenTransactions),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),o={connected:this.socket?.connected??!1,reconnectAttempts:this.reconnectAttempts};this.socket?.connected&&(o.lastConnectionTime=new Date);const i=t.queueSize/this.config.maxQueueSize*100,s=e.totalCached/this.config.maxPools*100,a=e.memoryUsedMB/this.getMaxMemoryMB()*100,c=this.generateHealthRecommendations(r,i,s,a,n.metrics.cacheHitRate);return{...n,status:r,websocket:o,recommendations:c,detailedMetrics:{eventQueueUtilization:i,cacheUtilization:s,memoryUtilization:a}}}generateHealthRecommendations(e,t,n,r,o){const i=[];return"failed"===e&&(i.push("🔴 System is in FAILED state - immediate action required"),this.socket?.connected||i.push("Reconnect WebSocket - connection lost"),t>90&&i.push("Reduce incoming event rate or increase maxQueueSize")),"degraded"===e&&(i.push("⚠️ System is DEGRADED - performance may be impacted"),t>75&&i.push(`Queue utilization ${t.toFixed(1)}% - consider increasing maxQueueSize`),r>80&&i.push(`Memory usage ${r.toFixed(1)}% - consider reducing cache size or memory profile`)),"healthy"===e&&(o<50&&i.push(`Cache hit rate ${o.toFixed(1)}% is low - consider warming more pools`),r>50&&i.push("Memory usage is moderate - monitor for growth trends"),t>50&&i.push("Queue utilization is elevated - monitor for bottlenecks")),i}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(e instanceof Error?e:new Error(String(e)))}))}async attemptReconnection(){if(this.logger.debug(`Reconnection attempt ${this.reconnectAttempts+1}/${this.maxReconnectAttempts}`),this.reconnectAttempts>=this.maxReconnectAttempts)return this.logger.error(`Max reconnection attempts (${this.maxReconnectAttempts}) exceeded - performing full reset`),void await this.performFullReset();this.reconnectAttempts<2&&(0===this.reconnectAttempts?this.logger.debug("Tier 1: Quick reconnect"):(this.logger.debug(`Tier 2: Exponential backoff (${this.reconnectDelayMs}ms)`),await new Promise(e=>setTimeout(e,this.reconnectDelayMs)),this.reconnectDelayMs=Math.min(2*this.reconnectDelayMs,3e4)));try{this.socket?.disconnect&&(this.socket.disconnect(),this.logger.debug("Disconnected for reconnection")),this.socket?.connect?.(),this.logger.debug("Reconnection initiated"),this.reconnectAttempts++}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.reconnectAttempts=0,this.reconnectDelayMs=1e3,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(),o=r[0],i=t.eventExtractor.walkPayloadForSwaps(o,t.seenTransactions);if(0===i.length)return;t.logger.debug(`Extracted ${i.length} swaps from payload`);for(const n of i){if(t.filterSwap(n,e)){t.eventQueue.enqueue(n)||t.logger.debug(`Swap dropped due to queue overflow: ${n.transactionId}`)}}const s=Date.now()-n;t.metrics.recordEventLatency(s)}catch(e){t.logger.error("Error processing WebSocket payload:",e),t.notifyError(e instanceof Error?e:new Error(String(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(!Eo.containsToken(e.poolKey,t.tokenFilter))return!1}if(t.pairTokens){const[n,r]=t.pairTokens;if(!Eo.containsTokenPair(e.poolKey,n,r))return!1}if(t.feeTierFilter){if(Eo.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=Date.now()-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(t instanceof Error?t:new Error(String(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 Po{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 No extends En{constructor(e=!1){super(e),this.cache=new Map,this.tokenIdIndex=new Map,this.fetchTimestamps=new Map}normalizeSymbol(e){return e.trim().toUpperCase()}normalizeTokenId(e){return e.trim().toUpperCase()}has(e){const t=this.cache.get(e);return void 0!==t&&t.size>0}getAll(e){const t=this.cache.get(e);return t?Array.from(t.values()):[]}getBySymbol(e,t){const n=this.normalizeSymbol(t);return this.cache.get(e)?.get(n)}getContractAddress(e,t){const n=this.getBySymbol(e,t);if(n)return"ETHEREUM"===e?n.ethereumContractAddress:n.solanaContractAddress}set(e,t){const n=new Map,r=new Map;for(const e of t){const t=this.normalizeSymbol(e.symbol);n.set(t,e);const o=this.normalizeTokenId(e.stringifiedTokenClassKey);r.set(o,e)}this.cache.set(e,n),this.tokenIdIndex.set(e,r),this.fetchTimestamps.set(e,Date.now()),this.logger.debug(`Cached ${t.length} bridgeable tokens for ${e}`)}merge(e,t){let n=this.cache.get(e);n||(n=new Map,this.cache.set(e,n));let r=this.tokenIdIndex.get(e);r||(r=new Map,this.tokenIdIndex.set(e,r));for(const e of t){const t=this.normalizeSymbol(e.symbol);n.set(t,e);const o=this.normalizeTokenId(e.stringifiedTokenClassKey);r.set(o,e)}this.fetchTimestamps.set(e,Date.now()),this.logger.debug(`Merged ${t.length} bridgeable tokens for ${e} (total: ${n.size})`)}getFetchTimestamp(e){return this.fetchTimestamps.get(e)}getStats(){const e=[];let t=0;const n={ETHEREUM:0,SOLANA:0},r={};for(const[o,i]of this.cache){e.push(o),t+=i.size,n[o]=i.size;const s=this.fetchTimestamps.get(o);s&&(r[o]=s)}return{networks:e,totalTokens:t,tokensByNetwork:n,fetchTimestamps:r}}clear(e){e?(this.cache.delete(e),this.tokenIdIndex.delete(e),this.fetchTimestamps.delete(e),this.logger.debug(`Cleared bridgeable token cache for ${e}`)):(this.cache.clear(),this.tokenIdIndex.clear(),this.fetchTimestamps.clear(),this.logger.debug("Cleared all bridgeable token caches"))}size(e){return this.cache.get(e)?.size??0}isTokenBridgeable(e,t){return void 0!==this.getBySymbol(e,t)}getByTokenId(e,t){const n=this.normalizeTokenId(t);return this.tokenIdIndex.get(e)?.get(n)}getCachedNetworks(){return Array.from(this.cache.keys())}dump(){const e={};for(const t of["ETHEREUM","SOLANA"])this.has(t)&&(e[t]=this.getAll(t));return e}}const _o=1e3;class Do{constructor(e,t=!1){this.dexApiHttp=e,this.logger=new S({debug:t,context:"BridgeableTokenService"}),this.cache=new No(t)}async fetchBridgeableTokensByNetwork(e){const{network:t,offset:n=0,limit:r=_o}=e,o=Math.min(r,1e3);this.logger.debug(`Fetching bridgeable tokens for ${t} (offset=${n}, limit=${o})`);try{const e=await this.dexApiHttp.request({method:"GET",url:"/v1/tokens",params:{canBridgeTo:t.toLowerCase(),limit:o,offset:n}}),r=this.transformTokens(e.tokens,t);return 0===n?this.cache.set(t,r):this.cache.merge(t,r),{tokens:r,network:t,fetchedAt:Date.now(),tokenCount:r.length}}catch(e){throw V(e,`Failed to fetch bridgeable tokens for ${t}`,this.logger)}}async fetchAllBridgeableTokensByNetwork(e){if(this.cache.has(e)){const t=this.cache.getAll(e);return this.logger.debug(`Returning ${t.length} cached bridgeable tokens for ${e}`),{tokens:t,network:e,fetchedAt:this.cache.getFetchTimestamp(e)||Date.now(),tokenCount:t.length}}this.logger.debug(`Fetching all bridgeable tokens for ${e} (no cache)`);try{const t=await oo(async(t,n)=>{const r=await this.dexApiHttp.request({method:"GET",url:"/v1/tokens",params:{canBridgeTo:e.toLowerCase(),limit:n,offset:t}});return{items:this.transformTokens(r.tokens,e),rawCount:r.tokens.length}},{maxLimit:1e3,logger:this.logger});return this.cache.set(e,t),{tokens:t,network:e,fetchedAt:Date.now(),tokenCount:t.length}}catch(t){throw V(t,`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=hr(t);this.cache.has(n)||await this.fetchAllBridgeableTokensByNetwork(n);const o=this.cache.getByTokenId(n,r),i=void 0!==o,s=i?"ETHEREUM"===n?o.ethereumContractAddress:o.solanaContractAddress:void 0,a={isBridgeable:i,tokenSymbol:o?.symbol??r.split("|")[0],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)}transformTokens(e,t){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),o={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&&(o.ethereumContractAddress=t.contractAddress),t?.symbol&&(o.ethereumSymbol=t.symbol),void 0!==t?.allowanceStorageSlot&&(o.ethereumAllowanceSlot=t.allowanceStorageSlot),n?.contractAddress&&(o.solanaContractAddress=n.contractAddress),n?.symbol&&(o.solanaSymbol=n.symbol),e.image&&(o.image=e.image),e.description&&(o.description=e.description),o})}}class Uo extends En{constructor(e=!1){super(e),this.lastFetchedAt=null,this.cache=new Map}normalizeTokenId(e){return e.trim().toUpperCase()}has(){return this.cache.size>0}getAll(){return Array.from(this.cache.values())}getByTokenId(e){const t=this.normalizeTokenId(e);return this.cache.get(t)}set(e){this.cache.clear();for(const t of e){const e=this.normalizeTokenId(t.stringifiedTokenClassKey);this.cache.set(e,t)}this.lastFetchedAt=Date.now(),this.logger.debug(`Cached ${e.length} wrappable tokens`)}merge(e){for(const t of e){const e=this.normalizeTokenId(t.stringifiedTokenClassKey);this.cache.set(e,t)}this.lastFetchedAt=Date.now(),this.logger.debug(`Merged ${e.length} wrappable tokens (total: ${this.cache.size})`)}getFetchTimestamp(){return this.lastFetchedAt}getStats(){return{tokenCount:this.cache.size,isPopulated:this.cache.size>0,lastFetchedAt:this.lastFetchedAt}}clear(){this.cache.clear(),this.lastFetchedAt=null,this.logger.debug("Cleared wrappable token cache")}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)}}const Ro=1e3;class Lo{constructor(e,t=!1){this.dexApiHttp=e,this.logger=new S({debug:t,context:"WrappableTokenService"}),this.cache=new Uo(t)}async fetchWrappableTokens(e={}){const{offset:t=0,limit:n=Ro}=e,r=Math.min(n,1e3);this.logger.debug(`Fetching wrappable tokens (offset=${t}, limit=${r})`);try{const e={wrappable:!0,limit:r,offset:t},n=await this.dexApiHttp.request({method:"GET",url:"/v1/tokens",params:e});if(!n||!Array.isArray(n.tokens))throw new x("Invalid API response: expected { tokens: WrappableTokenApiResponse[] }","response","INVALID_RESPONSE");const o=this.transformTokens(n.tokens);try{0===t?this.cache.set(o):this.cache.merge(o)}catch(e){this.logger.error("Cache operation failed (non-fatal):",e)}return{tokens:o,fetchedAt:Date.now(),tokenCount:o.length}}catch(e){throw V(e,"Failed to fetch wrappable tokens",this.logger)}}async fetchAllWrappableTokens(){if(this.cache.has()){const e=this.cache.getAll();return this.logger.debug(`Returning ${e.length} cached wrappable tokens`),{tokens:e,fetchedAt:this.cache.getFetchTimestamp()||Date.now(),tokenCount:e.length}}this.logger.debug("Fetching all wrappable tokens");try{const e=await oo(async(e,t)=>{const n=await this.dexApiHttp.request({method:"GET",url:"/v1/tokens",params:{wrappable:!0,limit:t,offset:e}});if(!n||!Array.isArray(n.tokens))throw new x("Invalid API response: expected { tokens: WrappableTokenApiResponse[] }","response","INVALID_RESPONSE");return{items:this.transformTokens(n.tokens),rawCount:n.tokens.length}},{maxLimit:1e3,logger:this.logger});try{this.cache.set(e)}catch(e){this.logger.error("Cache operation failed (non-fatal):",e)}return{tokens:e,fetchedAt:Date.now(),tokenCount:e.length}}catch(e){throw V(e,"Failed to fetch wrappable tokens",this.logger)}}async getWrappableToken(e){const t=hr(e),n=this.cache.getByTokenId(t);return n||(this.cache.has()?void 0:(await this.fetchAllWrappableTokens(),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=hr(e);this.cache.has()||await this.fetchAllWrappableTokens();const n=this.cache.getByTokenId(t),r=void 0!==n,o={isWrappable:r,tokenId:t};return r&&n&&(o.wrapCounterpart=n.wrapCounterpart),o}getCacheStats(){return this.cache.getStats()}clearCache(){this.cache.clear()}transformTokens(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})}}function Oo(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function Fo(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 Mo,$o,qo,Ko,zo,Go;function Wo(){return Ko?qo:(Ko=1,qo={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 jo=function(){if(Go)return zo;Go=1;const e=$o?Mo:($o=1,Mo={space:"",cycles:!1,replacer:(e,t)=>t,stringify:JSON.stringify}),t=Wo().isFunction,n=Wo().isBoolean,r=Wo().isObject,o=Wo().isArray,i=Wo().isRegex,s=Wo().assign,a=Wo().keys;return zo=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,p=u.compare&&(g=u.compare,function(e){return function(t,n){const r={key:t,value:e[t]},o={key:n,value:e[n]};return g(r,o)}});var g;h||f(c);const m=[];return function e(t,n,s,c){const u=l?"\n"+new Array(c+1).join(l):"",g=l?": ":":";if(s=function(e){return null==e?e:i(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(o(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(p&&p(s)),n=[];for(let r=0;r<t.length;r++){const o=t[r],i=e(s,o,s[o],c+1);if(!i)continue;const a=f(o)+g+i;n.push(u+l+a)}return m.splice(m.indexOf(s),1),"{"+n.join(",")+u+"}"}}}({"":c},"",c,0)},zo}(),Ho=Oo(jo);const Vo={GALA_CHAIN:1,ETHEREUM:2,SOLANA:1002},Xo={ASSET:1,MUSIC:3};const Qo="0x9f452b7cC24e6e6FA690fe77CF5dD2ba3DbF1ED9",Zo="0x6a1734E09f3099a3675645D214ce547080ea67e0",Yo="https://dex-api-platform-dex-prod-gala.gala.com",Jo=[{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}],ei=[{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 ti(e){return"PROD"===e?Jo:ei}function ni(e){return"PROD"===e?Qo:Zo}const ri=Jo,oi=[{symbol:"GALA",amount:"1",mintAddress:"eEUiUs4JWYZrp72djAGF1A8PhpR6rHphGeGN7GbVLp6",isNative:!1,decimals:8},{symbol:"GSOL",amount:"0.001",mintAddress:"So11111111111111111111111111111111111111111",isNative:!0,decimals:9}],ii={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"}},si=["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)"],ai=["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"],ci={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 ui={name:"GalaConnect",chainId:1},li=[{name:"destinationChainId",type:"uint256"},{name:"destinationChainTxFee",type:"destinationChainTxFee"},{name:"quantity",type:"string"},{name:"recipient",type:"string"},{name:"tokenInstance",type:"tokenInstance"},{name:"uniqueKey",type:"string"}],hi=[{name:"collection",type:"string"},{name:"category",type:"string"},{name:"type",type:"string"},{name:"additionalKey",type:"string"}],di=[{name:"collection",type:"string"},{name:"category",type:"string"},{name:"type",type:"string"},{name:"additionalKey",type:"string"},{name:"instance",type:"string"}],fi=[{name:"name",type:"string"},{name:"symbol",type:"string"}],pi={GalaTransaction:li,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:hi,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:di,externalQuoteToken:fi,tokenInstance:di},gi={GalaTransaction:li,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:hi,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:fi,externalQuoteToken:fi,externalCrossRateToken:fi,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:di,tokenInstance:di};function mi(e){return e?gi:pi}const yi={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:di};class wi{constructor(e){this.galaConnectClient=e.galaConnectClient,this.wrappableTokenService=e.wrappableTokenService,this.wallet=e.wallet,this.walletAddress=e.walletAddress,this.logger=e.logger??new S({debug:!1,context:"WrapService"})}async wrapToken(e){this.requireWallet();const t=await this.wrappableTokenService.getWrappableToken(e.tokenId);if(!t)throw new x(`Token not found or not wrappable: ${this.formatTokenId(e.tokenId)}`,"tokenId","TOKEN_NOT_WRAPPABLE");if("asset"===t.channel)throw new x(`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 x(`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 x(`Token not found or not wrappable: ${this.formatTokenId(e.tokenId)}`,"tokenId","TOKEN_NOT_WRAPPABLE");if("asset"!==t.channel)throw new x(`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 x(`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){const n=await this.wrappableTokenService.getWrappableToken(e);if(!n)throw new x(`Token not found or not wrappable: ${this.formatTokenId(e)}`,"tokenId","TOKEN_NOT_WRAPPABLE");if("asset"===n.channel)throw new x(`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){const n=await this.wrappableTokenService.getWrappableToken(e);if(!n)throw new x(`Token not found or not wrappable: ${this.formatTokenId(e)}`,"tokenId","TOKEN_NOT_WRAPPABLE");if("asset"!==n.channel)throw new x(`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){return{success:!0,status:"completed",transactionId:e,fromToken:"",toToken:"",amount:"",fromChannel:"",toChannel:""}}async executeChannelBridge(e){const{sourceToken:t,destinationToken:n,amount:r,recipient:o,isWrap:i}=e;if(!this.wallet||!this.walletAddress)throw new x("Wallet required for wrap/unwrap operations. Initialize SDK with a private key.","wallet","WALLET_REQUIRED");const s=this.walletAddress,a=this.determineChannelRouting(t,i),c=`galaswap-operation-${l.randomUUID()}`,u=yi,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:o||s,wrap:!0,uniqueKey:c};this.logger.debug?.(`[WrapService] ${i?"Wrap":"Unwrap"} message (pre-signing):`,JSON.stringify(h,null,2));try{const e=await this.wallet.signTypedData(ui,u,h),o=`Ethereum Signed Message:\n${Ho({domain:ui,message:h,primaryType:"GalaTransaction",types:u}).length}`,s={...h,signature:e,prefix:o,types:u,domain:ui};this.logger.debug?.(`[WrapService] ${i?"Wrap":"Unwrap"} request (signed):`,JSON.stringify(s,null,2));const c=await this.galaConnectClient.requestBridgeOut(s);if(this.logger.debug?.("[WrapService] Response:",JSON.stringify(c,null,2)),function(e){return"object"==typeof e&&null!==e&&"Status"in e&&"number"==typeof e.Status&&1!==e.Status}(c)){const e=`Status=${c.Status}`,o=c.Message?`: ${c.Message}`:"";return{success:!1,fromToken:t.symbol,toToken:n.symbol,amount:r,fromChannel:a.sourceChannel,toChannel:i?"asset":n.channel||"music",error:`GalaChain request failed (${e}${o})`}}if(function(e){return"object"==typeof e&&null!==e&&"Data"in e&&"string"==typeof e.Data}(c)){const e=c.Data;this.logger.debug?.("[WrapService] Step 1 complete, bridgeRequestId:",e);const o={bridgeFromChannel:a.sourceChannel,bridgeRequestId:e};this.logger.debug?.("[WrapService] Step 2 - BridgeTokenOut payload:",JSON.stringify(o,null,2));const s=await this.galaConnectClient.bridgeTokenOut(o);return this.logger.debug?.("[WrapService] BridgeTokenOut response:",JSON.stringify(s,null,2)),1!==s.Status?{success:!1,fromToken:t.symbol,toToken:n.symbol,amount:r,fromChannel:a.sourceChannel,toChannel:i?"asset":n.channel||"music",error:`BridgeTokenOut failed: ${JSON.stringify(s)}`}:{success:!0,transactionId:s.Hash||e,fromToken:t.symbol,toToken:n.symbol,amount:r,fromChannel:a.sourceChannel,toChannel:i?"asset":n.channel||"music",completedAt:Date.now()}}return{success:!1,fromToken:t.symbol,toToken:n.symbol,amount:r,fromChannel:a.sourceChannel,toChannel:i?"asset":n.channel||"music",error:`Unexpected response format from GalaChain: ${JSON.stringify(c)}`}}catch(e){const o=e instanceof Error?e.message:"Unknown error";return this.logger.error?.("[WrapService] Error:",o),{success:!1,fromToken:t.symbol,toToken:n.symbol,amount:r,fromChannel:a.sourceChannel,toChannel:i?"asset":n.channel||"music",error:o}}}determineChannelRouting(e,t){if(t){return{sourceChannel:e.channel||"music",destinationChannelId:Xo.ASSET,authType:"cross_channel_authorization"}}return{sourceChannel:"asset",destinationChannelId:Xo.MUSIC,authType:"automatic"}}requireWallet(){if(!this.walletAddress)throw new x("Wallet required for wrap/unwrap operations. Initialize SDK with a private key.","wallet","WALLET_REQUIRED")}formatTokenId(e){return"string"==typeof e?e:`${e.collection}|${e.category}|${e.type}|${e.additionalKey}`}}function bi(e){const t=function(e){const t=Ct(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 ki="/api/asset/launchpad-contract/CallNativeTokenIn",vi="/api/asset/launchpad-contract/CallNativeTokenOut",Ei="/api/asset/launchpad-contract/CallMemeTokenIn",Si="/api/asset/launchpad-contract/CallMemeTokenOut";class Ti extends r.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),this.tokenCategory=e.tokenCategory,this.tokenCollection=e.tokenCollection,this.uniqueKey=e.uniqueKey,e.reverseBondingCurveConfiguration&&(this.reverseBondingCurveConfiguration=e.reverseBondingCurveConfiguration)}}function Ai(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 Ii={NATIVE:"native",EXACT:"exact"},Bi={LOCAL:"local",EXTERNAL:"external"};class xi{static calculateBuyWithExact(e,t){const n=parseFloat(e),r=parseFloat(t),{BASE_PRICE:o,PRICE_SCALING_FACTOR:s,TRADING_FEE_FACTOR:a,GAS_FEE:c}=yo,u=this.roundUp(o*(Math.exp((r+n)*s)-Math.exp(r*s))/s,8),l=new i(u).multipliedBy(a).toFixed();return{amount:u.toString(),reverseBondingCurveFee:"0",transactionFee:l,gasFee:c}}static calculateBuyWithNative(e,t){const n=parseFloat(e),r=parseFloat(t),{BASE_PRICE:o,PRICE_SCALING_FACTOR:s,TRADING_FEE_FACTOR:a,GAS_FEE:c}=yo,u=Math.log(n*s/o+Math.exp(r*s))/s-r,l=new i(u).multipliedBy(a).toFixed();return{amount:u.toString(),reverseBondingCurveFee:"0",transactionFee:l,gasFee:c}}static calculateSellWithExact(e,t,n,r,o){const s=parseFloat(e),a=parseFloat(t),c=parseFloat(n),{BASE_PRICE:u,PRICE_SCALING_FACTOR:l,TRADING_FEE_FACTOR:h,GAS_FEE:d}=yo,f=u*(Math.exp(a*l)-Math.exp((a-s)*l))/l,p=new i(f),g=r+a/c*(o-r),m=p.multipliedBy(g).toFixed(8,i.ROUND_UP),y=p.multipliedBy(h).toFixed();return{amount:f.toString(),reverseBondingCurveFee:m,transactionFee:y,gasFee:d}}static calculateSellWithNative(e,t,n,r,o){const s=parseFloat(e),a=parseFloat(t),c=parseFloat(n),{BASE_PRICE:u,PRICE_SCALING_FACTOR:l,TRADING_FEE_FACTOR:h,GAS_FEE:d}=yo;if(s>=u*(Math.exp(a*l)-1)/l){const e=new i(s),t=r+a/c*(o-r),n=e.multipliedBy(t).toFixed(8,i.ROUND_UP),u=e.multipliedBy(h).toFixed();return{amount:a.toString(),reverseBondingCurveFee:n,transactionFee:u,gasFee:d}}const f=a-Math.log(Math.exp(a*l)-s*l/u)/l,p=new i(s),g=r+a/c*(o-r),m=p.multipliedBy(g).toFixed(8,i.ROUND_UP),y=p.multipliedBy(h).toFixed();return{amount:f.toString(),reverseBondingCurveFee:m,transactionFee:y,gasFee:d}}static roundUp(e,t){const n=Math.pow(10,t);return Math.ceil(e*n)/n}}class Ci{constructor(e,t,n,r,o,i,s="local"){this.http=e,this.tokenResolver=t,this.logger=n,this.bundleHttp=r,this.galaChainHttp=o,this.dexApiHttp=i,this.defaultCalculateAmountMode=s,this.metadataCache=new wo}addIfDefined(e,t,n){return void 0!==n&&(e[t]=n),e}async uploadImageByTokenName(e){const{tokenName:t,options:n}=e;Ht(t);const r=`${t}.png`;Mn(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 G("file","a File object (browser) or Buffer (Node.js)");{const r=`${n.tokenName||t}.png`,o=new Blob([n.file],{type:"image/png"});e.append("image",o,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||!r.data?.imageUrl)throw W(r.message||"Image upload failed - no URL returned",r.status);return r.data.imageUrl}catch(e){if(e instanceof Error&&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){Vt(e),e.tokenName&&Ht(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);const n=T(t),r=await this.http.get("/launchpad/fetch-pool",n);if(!0===r.error||200!==r.status||!r.data)throw W(r.message||"Failed to fetch pools",r.status);let o=[];const i=(await import("bignumber.js")).default;if(r.data.tokens)if(Array.isArray(r.data.tokens))o=r.data.tokens.map(e=>{const t=e.reverseBondingCurveMinFeePortion??"0",n=e.reverseBondingCurveMaxFeePortion??"0",r=!new i(t).isZero()||!new i(n).isZero();return{...e,reverseBondingCurveMinFeePortion:t,reverseBondingCurveMaxFeePortion:n,hasReverseBondingCurveFee:r,createdAt:e.created_at||e.createdAt||""}});else{const e=r.data.tokens,t=e.reverseBondingCurveMinFeePortion??"0",n=e.reverseBondingCurveMaxFeePortion??"0",s=!new i(t).isZero()||!new i(n).isZero();o=[{...e,reverseBondingCurveMinFeePortion:t,reverseBondingCurveMaxFeePortion:n,hasReverseBondingCurveFee:s,createdAt:e.created_at||e.createdAt||""}]}else r.data.pools&&Array.isArray(r.data.pools)&&(o=r.data.pools.map(e=>{const t=e.reverseBondingCurveMinFeePortion??"0",n=e.reverseBondingCurveMaxFeePortion??"0",r=!new i(t).isZero()||!new i(n).isZero();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 Kw});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=r.data.count??r.data.total??0,u=r.data.page??e.page??1,l=r.data.limit??e.limit??10,h=l>0?Math.ceil(c/l):1;return{pools:o,page:u,limit:l,total:c,totalPages:h,hasNext:u<h,hasPrevious:u>1}}async _getAmount(e){if(Qt(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:ki,body:{vaultAddress:n,tokenQuantity:r,IsPreMint:!1}};if("NATIVE"===e&&"OUT"===t)return{endpoint:vi,body:{vaultAddress:n,tokenQuantity:r,IsPreMint:!1}};if("MEME"===e&&"IN"===t)return{endpoint:Ei,body:{vaultAddress:n,nativeTokenQuantity:r,IsPreMint:!1}};if("MEME"===e&&"OUT"===t)return{endpoint:Si,body:{vaultAddress:n,nativeTokenQuantity:r,IsPreMint:!1}};throw G("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(!Ai(e))throw W("Malformed response data from GalaChain gateway");if(1!==e.Status)throw W(`GalaChain calculation failed with status ${e.Status}`,e.Status);const{calculatedQuantity:r,extraFees:o}=e.Data;return{amount:r,reverseBondingCurveFee:o.reverseBondingCurve,transactionFee:o.transactionFees,gasFee:"1"}}catch(r){throw this.logger.error(`GalaChain ${e.type}-${e.method} operation failed:`,{endpoint:t,requestBody:n,error:r instanceof Error?r.message:r}),r}}async checkPool(e){Xt(e),e.tokenName&&Ht(e.tokenName);const t=T(e),n=await this.http.get("/launchpad/check-pool",t);if(!0===n.error||200!==n.status)throw W(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(!Bn(e))throw new x("Invalid options provided. Expected { tokenName: string, from?: number, to?: number, resolution?: number }","options","INVALID_OPTIONS");const{tokenName:t,from:n,to:r,resolution:o}=e;if(Ht(t),!n||!r||!o)throw new x("Graph options (from, to, resolution) are required","options","MISSING_GRAPH_OPTIONS");const i={tokenName:t,from:n,to:r,resolution:o};Zt(i);const s=T(i),a=await this.http.get("/launchpad/get-graph-data",s);if(!0===a.error||200!==a.status||!a.data)throw W(a.message||"Failed to fetch graph data",a.status);return{dataPoints:a.data}}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),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 new x("Invalid options provided. Expected an options object.","options","INVALID_OPTIONS");const{tokenName:t,amount:n,type:r,currentSupply:o}=e,i=e.mode??this.defaultCalculateAmountMode;if("local"!==i&&"external"!==i)throw new x(`Invalid calculation mode "${i}". Must be "local" or "external".`,"mode","INVALID_CALCULATION_MODE");if(!t||"string"!=typeof t)throw new x("Token name is required and must be a string","tokenName","INVALID_TOKEN_NAME");if(!n||"string"!=typeof n)throw new x("Amount is required and must be a string","amount","INVALID_AMOUNT");if(r!==Ii.NATIVE&&r!==Ii.EXACT)throw new x('Type must be either "native" or "exact"',"type","INVALID_TYPE");return"external"===i?this.calculateBuyAmountExternal({tokenName:t,amount:n,type:r}):this.calculateBuyAmountLocal(this.addIfDefined({tokenName:t,amount:n,type:r},"currentSupply",o))}async calculateBuyAmountExternal(e){const{tokenName:t,amount:n,type:r}=e,o=await this.tokenResolver.resolveTokenToVault(t);if(!o)throw new x(`Token "${t}" not found. Please verify the token name is correct.`,"tokenName","TOKEN_NOT_FOUND");return r===Ii.EXACT?this._getAmount({type:"NATIVE",method:"IN",vaultAddress:o,amount:n}):this._getAmount({type:"MEME",method:"OUT",vaultAddress:o,amount:n})}async calculateSellAmount(e){const{tokenName:t,amount:n,type:r,currentSupply:o,maxSupply:i,reverseBondingCurveMaxFeeFactor:s,reverseBondingCurveMinFeeFactor:a}=e,c=e.mode??this.defaultCalculateAmountMode;if("local"!==c&&"external"!==c)throw new x(`Invalid calculation mode "${c}". Must be "local" or "external".`,"mode","INVALID_CALCULATION_MODE");if(!t||"string"!=typeof t)throw new x("Token name is required and must be a string","tokenName","INVALID_TOKEN_NAME");if(!n||"string"!=typeof n)throw new x("Amount is required and must be a string","amount","INVALID_AMOUNT");if(r!==Ii.EXACT&&r!==Ii.NATIVE)throw new x('Type must be either "exact" or "native"',"type","INVALID_TYPE");if("external"===c)return this.calculateSellAmountExternal({tokenName:t,amount:n,type:r});{const e={tokenName:t,amount:n,type:r,...void 0!==o&&{currentSupply:o},...void 0!==i&&{maxSupply:i},...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,o=await this.tokenResolver.resolveTokenToVault(t);if(!o)throw new x(`Token "${t}" not found. Please verify the token name is correct.`,"tokenName","TOKEN_NOT_FOUND");return r===Ii.EXACT?this._getAmount({type:"NATIVE",method:"OUT",vaultAddress:o,amount:n}):this._getAmount({type:"MEME",method:"IN",vaultAddress:o,amount:n})}async calculateBuyAmountLocal(e){const{tokenName:t,amount:n,type:r,currentSupply:o}=e;if(!n||"string"!=typeof n)throw new x("Amount is required and must be a string","amount","INVALID_AMOUNT");if(r!==Ii.NATIVE&&r!==Ii.EXACT)throw new x('Type must be either "native" or "exact"',"type","INVALID_TYPE");void 0!==o&&Jt(o,"currentSupply");const i=!o;if(i&&!t)throw new x("Token name is required when currentSupply is not provided","tokenName","MISSING_TOKEN_NAME");t&&Ht(t);let s=o;if(i){s=(await this.fetchPoolDetailsForCalculation(t)).currentSupply}return r===Ii.EXACT?xi.calculateBuyWithExact(n,s):xi.calculateBuyWithNative(n,s)}async calculateSellAmountLocal(e){const{tokenName:t,amount:n,type:r,currentSupply:o,maxSupply:i,reverseBondingCurveMaxFeeFactor:s,reverseBondingCurveMinFeeFactor:a}=e;if(!n||"string"!=typeof n)throw new x("Amount is required and must be a string","amount","INVALID_AMOUNT");if(r!==Ii.EXACT&&r!==Ii.NATIVE)throw new x('Type must be either "exact" or "native"',"type","INVALID_TYPE");void 0!==o&&Jt(o,"currentSupply");const c=!o||!i||void 0===s||void 0===a;if(c&&!t)throw new x("Token name is required when currentSupply, maxSupply, or fee factors are not provided","tokenName","MISSING_TOKEN_NAME");t&&Ht(t);let u=o,l=i,h=s,d=a;if(c&&t){const e=this.metadataCache.get(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===Ii.EXACT?xi.calculateSellWithExact(n,u,l,d,h):xi.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 Sn(t,"tokenName")&&In(t)&&Tn(t,"currentSupply")}(e))throw new Error("Invalid CalculateBuyAmountForGraduationOptions provided");const{tokenName:n,calculateAmountMode:r,currentSupply:o}=t;Ht(n);const i=await this.tokenResolver.resolveTokenToVault(n);if(!i)throw new x(B(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:i});if(1!==s.Status)throw W(`Failed to fetch pool details: Status ${s.Status}`,s.Status);const a=s.Data,c=(await import("bignumber.js")).default,u=o??new c(a.maxSupply).minus(a.sellingTokenQuantity).toFixed(),l=a.sellingTokenQuantity;if("0"===l)throw new x(`Token ${n} is already graduated (no tokens remaining in pool)`,"tokenName","ALREADY_GRADUATED");const h={tokenName:n,amount:l,type:"exact",currentSupply:u,...void 0!==r&&{mode:r}};return{...await this.calculateBuyAmount(h),remainingTokens:l}}async launchToken(e){if(!this.bundleHttp)throw j("Bundle backend client not configured. LaunchToken requires bundleHttp client.","bundleHttp");bi(e);const t=e.preBuyQuantity||"0";if(isNaN(Number(t))||Number(t)<0)throw new x("Pre-buy quantity must be a valid non-negative number string","preBuyQuantity","INVALID_PRE_BUY_QUANTITY");if(e.reverseBondingCurveConfiguration){const{minFeePortion:t,maxFeePortion:n}=e.reverseBondingCurveConfiguration,r=Number(t),o=Number(n);if(isNaN(r)||isNaN(o))throw new x("Reverse bonding curve fees must be valid numbers","reverseBondingCurveConfiguration","INVALID_BONDING_CURVE_CONFIG");if(r<.1)throw new x("Minimum fee must be >= 0.1","reverseBondingCurveConfiguration","INVALID_BONDING_CURVE_CONFIG");if(o>.5)throw new x("Maximum fee must be <= 0.5","reverseBondingCurveConfiguration","INVALID_BONDING_CURVE_CONFIG");if(o<r)throw new x("Maximum fee must be >= minimum fee","reverseBondingCurveConfiguration","INVALID_BONDING_CURVE_CONFIG")}let n="";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 W("Image upload failed: No URL returned");n=t}else"string"==typeof e.tokenImage&&(n=e.tokenImage);const o=`galaswap - operation - ${c.v4()}-${Date.now()}-${this.http.getAddress()}`,i={tokenName:e.tokenName.trim(),tokenSymbol:e.tokenSymbol.trim().toUpperCase(),tokenDescription:e.tokenDescription.trim(),tokenImage:n.trim(),preBuyQuantity:t.toString(),tokenCategory:e.tokenCategory||"Unit",tokenCollection:e.tokenCollection||"Token",uniqueKey:o};e.websiteUrl?.trim()&&(i.websiteUrl=e.websiteUrl.trim()),e.telegramUrl?.trim()&&(i.telegramUrl=e.telegramUrl.trim()),e.twitterUrl?.trim()&&(i.twitterUrl=e.twitterUrl.trim()),i.reverseBondingCurveConfiguration={minFeePortion:e.reverseBondingCurveConfiguration?.minFeePortion?.toString()||"0.1",maxFeePortion:e.reverseBondingCurveConfiguration?.maxFeePortion?.toString()||"0.5"};const s=new Ti(i),a=await this.http.signWithGalaChain("CreateSale",s,r.SigningType.SIGN_TYPED_DATA),{signature:u,types:l,domain:h,prefix:d}=a,f={tokenName:s.tokenName,tokenSymbol:s.tokenSymbol,tokenDescription:s.tokenDescription,tokenImage:s.tokenImage,preBuyQuantity:s.preBuyQuantity,...s.websiteUrl&&{websiteUrl:s.websiteUrl},...s.telegramUrl&&{telegramUrl:s.telegramUrl},...s.twitterUrl&&{twitterUrl:s.twitterUrl},tokenCategory:s.tokenCategory,tokenCollection:s.tokenCollection,uniqueKey:s.uniqueKey,signature:u,types:l,domain:h,...d&&{prefix:d},...s.reverseBondingCurveConfiguration&&{reverseBondingCurveConfiguration:s.reverseBondingCurveConfiguration}},p=`${e.tokenName.trim()}$Unit$none$none`,g="GALA$Unit$none$none";let m;if(parseFloat(t)>0){const e=`$service$${p}$launchpad`;m=[e,`$token$${p}$${e}`,`$tokenBalance$${p}$${e}`,`$tokenBalance$${p}$${e}`,`$tokenBalance$${g}$${e}`,`$tokenBalance$${g}$${e}`]}else{const e=`$service$${p}$launchpad`;m=[e,`$token$${p}$${e}`,`$tokenBalance$${p}$${e}`]}const y={signedDto:f,stringsInstructions:m,method:"CreateSale"},w=await this.bundleHttp.post("/bundle",y);if(w.error||!w.data)throw W(w.message||"Token launch failed");return w.data}async fetchTokenDistribution(e){if(!e)throw z("tokenName","Token name");Ht(e);const t=await this.tokenResolver.resolveTokenToVault(e);if(!t)throw new x(B(e),"tokenName","VAULT_NOT_FOUND");this.metadataCache.set(e,{vaultAddress:t});const n=encodeURIComponent(t),r=await this.http.get(`/holders/${n}`);if(!0===r.error||200!==r.status||!r.data)throw W(r.message||"Failed to fetch token distribution",r.status);const o=r.data;if(!Array.isArray(o))throw W("Invalid API response: expected array of holders",r.status);for(const e of o){if(!e.owner||"string"!=typeof e.owner)throw W("Invalid holder data: missing or invalid owner field",r.status);if(!e.quantity||"string"!=typeof e.quantity)throw W("Invalid holder data: missing or invalid quantity field",r.status);const t=parseFloat(e.quantity);if(isNaN(t)||!isFinite(t))throw W(`Invalid holder quantity: "${e.quantity}"`,r.status)}const s=o.reduce((e,t)=>e.plus(t.quantity),new i(0));return{holders:o.map(e=>{const t=new i(e.quantity),n=s.isZero()?0:t.dividedBy(s).multipliedBy(100).toNumber();return{address:e.owner,balance:e.quantity,percentage:n}}),totalSupply:s.toFixed(),totalHolders:o.length,lastUpdated:new Date}}async fetchTokenBadges(e){if(!e)throw z("tokenName","Token name");Ht(e);const t=await this.http.get("/launchpad/get-badge/",{tokenName:e});if(t.error||!t.data)throw W(t.message||"Failed to fetch token badges");return{volumeBadges:t.data.volumeBadge||[],engagementBadges:t.data.engagementBadge||[]}}async hasTokenBadgeByTokenName(e){const{tokenName:t,badgeType:n,badgeName:r}=e;try{const e=await this.fetchTokenBadges(t);if(!e)return!1;const o=("volume"===n?e.volumeBadges:e.engagementBadges).find(e=>e.badgeName===r);return o?.isActive||!1}catch{return!1}}async calculateInitialBuyAmount(e){if(!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.nativeTokenQuantity&&(void 0===t.vaultAddress||"string"==typeof t.vaultAddress)}(e))throw new x("Invalid pre-mint calculation data","data","INVALID_PRE_MINT_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(!Ai(n))throw W("Malformed response data from GalaChain gateway");if(1!==n.Status)throw W(`GalaChain calculation failed with status ${n.Status}`,n.Status);const{calculatedQuantity:r,extraFees:o}=n.Data;return{amount:r,reverseBondingCurveFee:o.reverseBondingCurve,transactionFee:o.transactionFees,gasFee:"1"}}catch(e){if(e instanceof Error){const t=new Error(`Pre-mint calculation failed: ${e.message}`);throw e.stack&&(t.stack=e.stack),t}throw new Error(`Pre-mint calculation failed: ${String(e)}`)}}async fetchPoolDetailsForCalculation(e){const t=await this.tokenResolver.resolveTokenToVault(e);if(!t)throw new x(B(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 W(`Failed to fetch pool details: Status ${n.Status}`,n.Status);const r=n.Data,o=new(0,(await import("bignumber.js")).default)(r.maxSupply).minus(r.sellingTokenQuantity).toFixed(),i=r.sellingTokenQuantity,s=r.maxSupply;let a=.5,c=0;r.reverseBondingCurveConfiguration?(a=parseFloat(r.reverseBondingCurveConfiguration.maxFeePortion),c=parseFloat(r.reverseBondingCurveConfiguration.minFeePortion)):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:o,remainingTokens:i,maxSupply:s,reverseBondingCurveMaxFeeFactor:a,reverseBondingCurveMinFeeFactor:c,reverseBondingCurveNetFeeFactor:u}}async fetchCurrentSupply(e){Ht(e);const t=await this.tokenResolver.resolveTokenToVault(e);if(!t)throw new x(B(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 W(`Failed to fetch pool details: Status ${n.Status}`,n.Status);const r=n.Data,o=new(0,(await import("bignumber.js")).default)(r.maxSupply).minus(r.sellingTokenQuantity).toFixed(),i=r.maxSupply;return this.metadataCache.set(e,{maxSupply:i}),o}getAddress(){return this.http.getAddress()}formatAddressForBackend(e){return Yt(e)}validateTokenName(e){return Ht(e)}validatePagination(e){return Vt(e)}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 W(`Failed to fetch token prices: ${e instanceof Error?e.message:e}`,void 0,e instanceof Error?e:void 0)}}async fetchLaunchpadTokenSpotPrice(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 Sn(t,"tokenName")&&In(t)&&Tn(t,"currentSupply")}(e))throw new Error("Invalid FetchLaunchpadTokenSpotPriceOptions provided");const{tokenName:n,calculateAmountMode:r,currentSupply:o}=t;if(!n||"string"!=typeof n)throw z("tokenName","Token name (string)");try{const e={tokenName:n,amount:"1",type:"native",...void 0!==r&&{mode:r},...void 0!==o&&{currentSupply:o}},t=await this.calculateBuyAmount(e),i=(await this.fetchTokenPrice("GALA"))[0];if(!i)throw W("GALA price not available");const s=Number(t.amount);if(s<=0)throw new x(`Invalid token amount calculation: ${s}`,"amount","INVALID_CALCULATION");const a=i.price/s;return{symbol:n.toUpperCase(),price:a}}catch(e){if(e instanceof Error)throw new Error(`Failed to calculate launchpad token spot price for ${n}: ${e.message}`);throw new Error(`Failed to calculate launchpad token spot price for ${n}: ${String(e)}`)}}warmCacheFromPoolData(e,t){this.metadataCache.warmFromPoolData(e,t)}getCacheStats(){return this.metadataCache.stats()}clearCache(e){this.metadataCache.clear(e)}}class Pi{constructor(e){if(this.lastTimestamp=0,this.pendingPromise=Promise.resolve(),this.chainLength=0,this.maxChainLength=1e3,e<=0)throw new Error("requestsPerSecond must be greater than zero");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,o=Math.max(0,this.minIntervalMs-r);o>0&&await new Promise(e=>setTimeout(e,o)),this.lastTimestamp=Date.now();try{const n=await e();t(n)}catch(e){n(e instanceof Error?e:new Error(String(e)))}}),this.chainLength++,this.chainLength>=this.maxChainLength){this.chainLength=0;const e=this.pendingPromise;this.pendingPromise=e.then(()=>Promise.resolve())}return r}}function Ni(e,t){const n=new i(e);if(!n.isFinite())throw new Error(`Invalid amount: ${e}`);const r=n.multipliedBy(new i(10).pow(t));if(!r.isInteger())throw new Error(`Amount ${e} cannot be represented with ${t} decimals`);return BigInt(r.toFixed(0))}function _i(e,t){return new i(e.toString()).dividedBy(new i(10).pow(t)).toFixed(t).replace(/\.?0+$/,"")}const Di={maxRetries:3,initialDelayMs:1e3,maxDelayMs:3e4,backoffMultiplier:2,jitterFactor:.1},Ui=new Set([408,429,500,502,503,504]),Ri=[/ECONNRESET/i,/ECONNREFUSED/i,/ETIMEDOUT/i,/ENOTFOUND/i,/EAI_AGAIN/i,/socket hang up/i,/network/i,/timeout/i,/aborted/i];function Li(e){if(e&&"object"==typeof e){const t=e;if("number"==typeof t.status)return Ui.has(t.status);if("number"==typeof t.statusCode)return Ui.has(t.statusCode);if("string"==typeof t.code&&("ECONNRESET"===t.code||"ECONNREFUSED"===t.code||"ETIMEDOUT"===t.code||"ENOTFOUND"===t.code||"EAI_AGAIN"===t.code))return!0}const t=e instanceof Error?e.message:String(e);return Ri.some(e=>e.test(t))}function Oi(e,t){const n=t.initialDelayMs*Math.pow(t.backoffMultiplier,e-1),r=Math.min(n,t.maxDelayMs),o=r*t.jitterFactor*Math.random();return Math.floor(r+o)}function Fi(e){let t;if("string"==typeof e)t=function(e){const t=e.split("|");if(t.length<4)throw new Error(`Invalid token string format: "${e}". Expected "collection|category|type|additionalKey" format.`);return{collection:t[0],category:t[1],type:t[2],additionalKey:t[3]}}(e);else{if(!function(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}(e))throw new Error('Invalid tokenId format. Expected pipe-delimited string (e.g., "GALA|Unit|none|none") or TokenClassKey object.');t=e}var n;return{tokenClassKey:t,stringified:`${(n=t).collection}|${n.category}|${n.type}|${n.additionalKey}`}}class Mi 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 $i=Yo,qi="https://galachain-gateway-chain-platform-galachain-mainnet.gala.com",Ki=12,zi=!0,Gi=3,Wi=1e3;class ji{constructor(e){this.baseUrl=e.baseUrl??$i,this.galachainBaseUrl=e.galachainBaseUrl??qi,this.walletAddress=e.walletAddress,this.rateLimiter=new Pi(e.requestsPerSecond??Ki),this.defaultHeaders={"Content-Type":"application/json","X-Wallet-Address":this.walletAddress};const t=e.enableRetry??zi;this.retryOptions=t?{maxRetries:e.maxRetries??Gi,initialDelayMs:e.retryInitialDelayMs??Wi,...e.onRetry&&{onRetry:e.onRetry},shouldRetry:e=>Li(e instanceof Mi?{status:e.status}:e)}:null}getBaseUrl(){return this.baseUrl}async getBridgeConfigurations(e){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)throw new Mi(n.status,"/v1/connect/bridge-configurations",await this.safeParseJson(n));return(await n.json()).data.tokens}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={}){const r=n.baseUrl??this.baseUrl,o=new URL(e,r),i=n.skipWalletHeader?{"Content-Type":"application/json","X-Wallet-Address":""}:this.defaultHeaders,s=await this.request(o.toString(),{method:"POST",headers:i,body:JSON.stringify(t,(e,t)=>"bigint"==typeof t?t.toString():t)}),a=await s.text();let c;if(a)try{c=JSON.parse(a)}catch(t){const n=new Error(`Failed to parse JSON response from ${e}: ${t.message}`);if(!s.ok)throw new Mi(s.status,e,{parseError:n.message,rawBody:a.slice(0,500)});throw n}if(!s.ok)throw new Mi(s.status,e,c);return c}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(),o=await this.safeParseJson(n);throw new Mi(t,e,o)}}return r});return this.retryOptions?async function(e,t={}){const n={...Di,...t},r=t.shouldRetry??(e=>Li(e));let o;for(let i=1;i<=n.maxRetries+1;i++)try{return await e()}catch(e){if(o=e,i>n.maxRetries)break;if(!r(e,i))break;const s=Oi(i,n);t.onRetry&&t.onRetry(e,i,s),await new Promise(e=>setTimeout(e,s))}throw o}(n,this.retryOptions):n()}async safeParseJson(e){const t=await e.text();try{return JSON.parse(t)}catch{return{rawBody:t}}}}var Hi;e.BridgeStatusCode=void 0,(Hi=e.BridgeStatusCode||(e.BridgeStatusCode={}))[Hi.PENDING=0]="PENDING",Hi[Hi.SUBMITTED=1]="SUBMITTED",Hi[Hi.CONFIRMED=2]="CONFIRMED",Hi[Hi.PROCESSING=3]="PROCESSING",Hi[Hi.FINALIZING=4]="FINALIZING",Hi[Hi.COMPLETED=5]="COMPLETED",Hi[Hi.FAILED=6]="FAILED",Hi[Hi.DELIVERY_FAILED=7]="DELIVERY_FAILED";class Vi{async waitForCompletion(t,n={}){const{pollInterval:r=15e3,timeout:o=27e5,onStatusUpdate:i}=n,s=Date.now();for(;;){const n=await this.getStatus(t);if(i&&i(n),n.status===e.BridgeStatusCode.COMPLETED||n.status===e.BridgeStatusCode.FAILED||n.status===e.BridgeStatusCode.DELIVERY_FAILED)return n;if(Date.now()-s>o)throw new Error(`Bridge transaction ${t} timed out after ${o}ms. Last status: ${n.status}`);await new Promise(e=>setTimeout(e,r))}}}class Xi extends Vi{constructor(e){if(super(),this.network="Ethereum",this.tokenMetadataCache=new Map,this.galaConnectClient=e.galaConnectClient,this.galaChainWalletAddress=e.galaChainWalletAddress,!e.ethereumPrivateKey||!/^0x[a-fA-F0-9]{64}$/.test(e.ethereumPrivateKey))throw new Error("Invalid Ethereum private key format. Expected 0x-prefixed 64-character hex string (e.g., 0x1234...abcd)");const t=e.ethereumRpcUrl??"https://ethereum.publicnode.com";this.ethereumProvider=new n.JsonRpcProvider(t),this.ethereumWallet=new n.Wallet(e.ethereumPrivateKey,this.ethereumProvider),this.ethereumWalletAddress=e.ethereumWalletAddress??this.ethereumWallet.address,this.ethereumBridgeContract=e.ethereumBridgeContract??"0x3F98b5A26EF3f04E1DA3B0B41dD350E8C8F3A7c2",this.tokenConfigs=new Map;const r=e.tokenConfigs??ri;for(const e of r)this.tokenConfigs.set(e.symbol.toUpperCase(),e)}async estimateFee(e,t){const n=await this.getTokenMetadata(e),r=await this.galaConnectClient.fetchBridgeFee({chainId:"Ethereum",bridgeToken:n.descriptor});return{estimatedFeeInGala:r.estimatedTotalTxFeeInGala,estimatedFeeInExternalToken:r.estimatedTotalTxFeeInExternalToken,feeToken:r.bridgeToken,pricePerUnit:r.estimatedPricePerTxFeeUnit,estimatedGasUnits:r.estimatedTxFeeUnitsTotal,exchangeRate:r.galaExchangeRate?.exchangeRate??"0",timestamp:r.timestamp,raw:r}}async bridgeOut(e){const{amount:t,recipientAddress:r,tokenSymbol:o}=e;if(!o)throw new Error("Token symbol resolution failed. This is an internal error - BridgeService should resolve tokenId to symbol before calling strategy.");const i=o,s=parseFloat(t);if(isNaN(s)||s<=0)throw new Error(`Invalid bridge amount for ${i}: "${t}". Amount must be a positive number.`);if(!n.isAddress(r))throw new Error(`Invalid Ethereum recipient address: "${r}". Expected valid 0x-prefixed address.`);const a=await this.getTokenMetadata(i),c=await this.galaConnectClient.fetchBridgeFee({chainId:"Ethereum",bridgeToken:a.descriptor}),u={destinationChainId:Vo.ETHEREUM,destinationChainTxFee:c,quantity:t,recipient:r,tokenInstance:{...a.descriptor,instance:"0"}},l=await this.buildBridgeOutPayload(u),h=await this.galaConnectClient.requestBridgeOut(l),d=this.extractBridgeRequestId(h);if(!d)throw new Error("Bridge request ID missing from RequestTokenBridgeOut response");const f=await this.galaConnectClient.bridgeTokenOut({bridgeFromChannel:"asset",bridgeRequestId:d}),p=f.Hash??f.hash??"";if(!p)throw new Error("BridgeTokenOut response missing transaction hash");return{direction:"outbound",fromChain:"GalaChain",toChain:"Ethereum",transactionHash:p,tokenSymbol:i,amount:t,feePaid:c.estimatedTotalTxFeeInGala,timestamp:Date.now(),statusUrl:`${this.galaConnectClient.getBaseUrl()}/v1/bridge/transaction?hash=${p}`}}async bridgeIn(e){const{amount:t,sourcePrivateKey:r,recipientAddress:o,tokenSymbol:i}=e;if(!i)throw new Error("Token symbol resolution failed. This is an internal error - BridgeService should resolve tokenId to symbol before calling strategy.");const s=i,a=parseFloat(t);if(isNaN(a)||a<=0)throw new Error(`Invalid bridge amount for ${s}: "${t}". Amount must be a positive number.`);if(r&&!/^0x[a-fA-F0-9]{64}$/.test(r))throw new Error("Invalid sourcePrivateKey format. Expected 0x-prefixed 64-character hex string.");const c=r?new n.Wallet(r,this.ethereumProvider):this.ethereumWallet,u=this.tokenConfigs.get(s.toUpperCase());if(!u)throw new Error(`Token ${s} not supported for Ethereum bridge`);const l=await this.getTokenMetadata(s),h=new n.Contract(u.contractAddress,si,c),d=await h.decimals(),f=Number(d),p=Ni(t,f),g=BigInt(await h.balanceOf(c.address));if(g<p){const e=_i(p,f),t=_i(g,f);throw new Error(`Insufficient ${s} balance on Ethereum. Needed ${e}, have ${t}`)}const m=this.normalizeGalaChainAddress(o??this.galaChainWalletAddress),y=await this.executeBridgeDeposit({wallet:c,tokenContract:h,tokenConfig:u,amountBaseUnits:p,decimals:f,recipient:m,metadata:l});return{direction:"inbound",fromChain:"Ethereum",toChain:"GalaChain",transactionHash:y.txHash,tokenSymbol:s,amount:t,timestamp:Date.now(),statusUrl:`${this.galaConnectClient.getBaseUrl()}/v1/bridge/transaction?hash=${y.txHash}`}}async getStatus(e){const t=await this.galaConnectClient.getBridgeStatus(e),n=t.status;return{status:n,statusDescription:t.statusDescription,fromChain:t.fromChain,toChain:t.toChain,quantity:t.quantity,transactionHash:t.emitterTransactionHash,tokenInstance:t.tokenInstance,isComplete:5===n,isFailed:6===n||7===n}}getSupportedTokens(){return Array.from(this.tokenConfigs.keys())}isTokenSupported(e){return this.tokenConfigs.has(e.toUpperCase())}isValidAddress(e){return/^0x[a-fA-F0-9]{40}$/.test(e)}getWalletAddress(){return this.ethereumWalletAddress}async getEthereumTokenBalance(e,t){const r=this.tokenConfigs.get(e.toUpperCase());if(!r){const t=Array.from(this.tokenConfigs.keys()).join(", ");throw new Error(`Token ${e} not supported for Ethereum. Supported: ${t}`)}const o=t??this.ethereumWalletAddress;if(!n.isAddress(o))throw new Error(`Invalid Ethereum address: "${o}"`);const i=new n.Contract(r.contractAddress,si,this.ethereumProvider);return _i(await i.balanceOf(o),r.decimals??18)}async getEthereumNativeBalance(e){const t=e??this.ethereumWalletAddress;if(!n.isAddress(t))throw new Error(`Invalid Ethereum address: "${t}"`);return _i(await this.ethereumProvider.getBalance(t),18)}async getEthereumTransactionStatus(e){if(!/^0x[a-fA-F0-9]{64}$/.test(e))throw new Error(`Invalid Ethereum transaction hash format: "${e}". Expected 0x-prefixed 64-character hex string (66 total characters).`);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>=Xi.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: ${e instanceof Error?e.message:String(e)}`}}}async getTokenMetadata(e){const t=this.tokenMetadataCache.get(e.toUpperCase());if(t)return t;const n=ii[e.toUpperCase()];if(n)return this.tokenMetadataCache.set(e.toUpperCase(),n),n;let r=e,o=await this.galaConnectClient.getBridgeConfigurations(r),i=o.find(e=>e.symbol.toUpperCase()===r.toUpperCase()&&e.verified);if(i||e.startsWith("G")||(r=`G${e}`,o=await this.galaConnectClient.getBridgeConfigurations(r),i=o.find(e=>e.symbol.toUpperCase()===r.toUpperCase()&&e.verified)),!i)throw new Error(`Unable to locate token metadata for ${e}`);const s={descriptor:{collection:i.collection,category:i.category,type:i.type,additionalKey:i.additionalKey},decimals:i.decimals,...i.channel&&{channel:i.channel}};return this.tokenMetadataCache.set(e.toUpperCase(),s),s}async buildBridgeOutPayload(e){const t=e.uniqueKey??`galaconnect-operation-${l.randomUUID()}`,n="string"==typeof e.destinationChainId?Number(e.destinationChainId):e.destinationChainId,r=this.normalizeDestinationChainTxFee(e.destinationChainTxFee),o=Boolean(r.galaExchangeCrossRate),i=o?{...r,galaExchangeRate:void 0}:{...r,galaExchangeCrossRate:void 0},s={destinationChainId:n,destinationChainTxFee:this.sanitizeObject(i),quantity:e.quantity,recipient:e.recipient,tokenInstance:e.tokenInstance,uniqueKey:t},a=mi(o),c=await this.ethereumWallet.signTypedData(ui,a,s),u=`Ethereum Signed Message:\n${Ho({domain:ui,message:s,primaryType:"GalaTransaction",types:a}).length}`;return{...s,signature:c,prefix:u,types:a,domain:ui}}async executeBridgeDeposit(e){const t=new n.Contract(this.ethereumBridgeContract,ai,e.wallet),r=(new TextEncoder).encode(e.recipient);let o;o=e.tokenConfig.bridgeUsesPermit?await this.bridgeWithPermit(e.wallet,e.tokenContract,e.tokenConfig,t,e.amountBaseUnits,r):await this.bridgeWithApproval(e.wallet,e.tokenContract,t,e.tokenConfig,e.amountBaseUnits,r);if(!await o.wait())throw new Error("Bridge transaction receipt not available");await this.delay(3e4);const i={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:_i(e.amountBaseUnits,e.decimals),tokenInstance:i,fromChain:"Ethereum",toChain:"GC",hash:o.hash}),{txHash:o.hash}}async bridgeWithPermit(e,t,r,o,i,s){const a=await this.ethereumProvider.getNetwork(),c=await t.name(),u=await t.nonces(e.address),l=BigInt(Math.floor(Date.now()/1e3)+3600),h=await e.signTypedData({name:c,version:"1",chainId:Number(a.chainId),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:e.address,spender:this.ethereumBridgeContract,value:i,nonce:u,deadline:l}),d=n.Signature.from(h);return o.bridgeOutWithPermit(r.contractAddress,i,Vo.GALA_CHAIN,s,l,d.v,d.r,d.s)}async bridgeWithApproval(e,t,n,r,o,i){const s=await t.allowance(e.address,this.ethereumBridgeContract);if(BigInt(s)<o){const e=await t.approve(this.ethereumBridgeContract,o);await e.wait()}return n.bridgeOut(r.contractAddress,o,0,Vo.GALA_CHAIN,i)}normalizeDestinationChainTxFee(e){const t={...e,galaDecimals:"string"==typeof e.galaDecimals?Number(e.galaDecimals):e.galaDecimals,timestamp:"string"==typeof e.timestamp?Number(e.timestamp):e.timestamp};if(e.galaExchangeRate&&(t.galaExchangeRate={...e.galaExchangeRate,timestamp:"string"==typeof e.galaExchangeRate.timestamp?Number(e.galaExchangeRate.timestamp):e.galaExchangeRate.timestamp}),e.galaExchangeCrossRate){const n=e.galaExchangeCrossRate;t.galaExchangeCrossRate={...n,timestamp:"string"==typeof n.timestamp?Number(n.timestamp):n.timestamp},n.baseTokenCrossRate&&(t.galaExchangeCrossRate.baseTokenCrossRate={...n.baseTokenCrossRate,timestamp:"string"==typeof n.baseTokenCrossRate.timestamp?Number(n.baseTokenCrossRate.timestamp):n.baseTokenCrossRate.timestamp}),n.quoteTokenCrossRate&&(t.galaExchangeCrossRate.quoteTokenCrossRate={...n.quoteTokenCrossRate,timestamp:"string"==typeof n.quoteTokenCrossRate.timestamp?Number(n.quoteTokenCrossRate.timestamp):n.quoteTokenCrossRate.timestamp})}return t}sanitizeObject(e){const t={};for(const[n,r]of Object.entries(e))void 0!==r&&(r&&"object"==typeof r&&!Array.isArray(r)?t[n]=this.sanitizeObject(r):t[n]=r);return t}extractBridgeRequestId(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}}}async delay(e){return new Promise(t=>setTimeout(t,e))}normalizeGalaChainAddress(e){let t;if(e.startsWith("eth|"))t=e.slice(4);else{if(e.startsWith("client|"))return e;t=e}if((t.startsWith("0x")||t.startsWith("0X"))&&(t=t.slice(2)),!/^[a-fA-F0-9]{40}$/.test(t))throw new Error(`Invalid GalaChain address format: ${e}`);return`eth|${n.getAddress("0x"+t).slice(2)}`}}Xi.ETHEREUM_FINALITY_THRESHOLD=12;var Qi,Zi={},Yi={};function Ji(){if(Qi)return Yi;Qi=1,Yi.byteLength=function(e){var t=i(e),n=t[0],r=t[1];return 3*(n+r)/4-r},Yi.toByteArray=function(e){var r,o,s=i(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(o=0;o<h;o+=4)r=t[e.charCodeAt(o)]<<18|t[e.charCodeAt(o+1)]<<12|t[e.charCodeAt(o+2)]<<6|t[e.charCodeAt(o+3)],u[l++]=r>>16&255,u[l++]=r>>8&255,u[l++]=255&r;2===c&&(r=t[e.charCodeAt(o)]<<2|t[e.charCodeAt(o+1)]>>4,u[l++]=255&r);1===c&&(r=t[e.charCodeAt(o)]<<10|t[e.charCodeAt(o+1)]<<4|t[e.charCodeAt(o+2)]>>2,u[l++]=r>>8&255,u[l++]=255&r);return u},Yi.fromByteArray=function(t){for(var n,r=t.length,o=r%3,i=[],s=16383,c=0,u=r-o;c<u;c+=s)i.push(a(t,c,c+s>u?u:c+s));1===o?(n=t[r-1],i.push(e[n>>2]+e[n<<4&63]+"==")):2===o&&(n=(t[r-2]<<8)+t[r-1],i.push(e[n>>10]+e[n>>4&63]+e[n<<2&63]+"="));return i.join("")};for(var e=[],t=[],n="undefined"!=typeof Uint8Array?Uint8Array:Array,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",o=0;o<64;++o)e[o]=r[o],t[r.charCodeAt(o)]=o;function i(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var n=e.indexOf("=");return-1===n&&(n=t),[n,n===t?0:4-n%4]}function 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,o=[],i=t;i<n;i+=3)r=(e[i]<<16&16711680)+(e[i+1]<<8&65280)+(255&e[i+2]),o.push(s(r));return o.join("")}return t["-".charCodeAt(0)]=62,t["_".charCodeAt(0)]=63,Yi}var es,ts,ns={};function rs(){return es||(es=1,ns.read=function(e,t,n,r,o){var i,s,a=8*o-r-1,c=(1<<a)-1,u=c>>1,l=-7,h=n?o-1:0,d=n?-1:1,f=e[t+h];for(h+=d,i=f&(1<<-l)-1,f>>=-l,l+=a;l>0;i=256*i+e[t+h],h+=d,l-=8);for(s=i&(1<<-l)-1,i>>=-l,l+=r;l>0;s=256*s+e[t+h],h+=d,l-=8);if(0===i)i=1-u;else{if(i===c)return s?NaN:1/0*(f?-1:1);s+=Math.pow(2,r),i-=u}return(f?-1:1)*s*Math.pow(2,i-r)},ns.write=function(e,t,n,r,o,i){var s,a,c,u=8*i-o-1,l=(1<<u)-1,h=l>>1,d=23===o?Math.pow(2,-24)-Math.pow(2,-77):0,f=r?0:i-1,p=r?1:-1,g=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,o),s+=h):(a=t*Math.pow(2,h-1)*Math.pow(2,o),s=0));o>=8;e[n+f]=255&a,f+=p,a/=256,o-=8);for(s=s<<o|a,u+=o;u>0;e[n+f]=255&s,f+=p,s/=256,u-=8);e[n+f-p]|=128*g}),ns}var os=(ts||(ts=1,function(e){const t=Ji(),n=rs(),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 o=2147483647;function i(e){if(e>o)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=i(n);const o=r.write(e,t);return o!==n&&(r=r.slice(0,o)),r}(e,t);if(ArrayBuffer.isView(e))return function(e){if(H(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(H(e,ArrayBuffer)||e&&H(e.buffer,ArrayBuffer))return h(e,t,n);if("undefined"!=typeof SharedArrayBuffer&&(H(e,SharedArrayBuffer)||e&&H(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 o=function(e){if(s.isBuffer(e)){const t=0|d(e.length),n=i(t);return 0===n.length||e.copy(n,0,0,t),n}return void 0!==e.length?"number"!=typeof e.length||V(e.length)?i(0):l(e):"Buffer"===e.type&&Array.isArray(e.data)?l(e.data):void 0}(e);if(o)return o;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),i(e<0?0:0|d(e))}function l(e){const t=e.length<0?0:0|d(e.length),n=i(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>=o)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+o.toString(16)+" bytes");return 0|e}function f(e,t){if(s.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||H(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 o=!1;for(;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":return G(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(o)return r?-1:G(e).length;t=(""+t).toLowerCase(),o=!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 x(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 B(this,t,n);case"base64":return S(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return C(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function g(e,t,n){const r=e[t];e[t]=e[n],e[n]=r}function m(e,t,n,r,o){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=o?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(o)return-1;n=e.length-1}else if(n<0){if(!o)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,o);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?o?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):y(e,[t],n,r,o);throw new TypeError("val must be string, number or Buffer")}function y(e,t,n,r,o){let i,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(o){let r=-1;for(i=n;i<a;i++)if(u(e,i)===u(t,-1===r?0:i-r)){if(-1===r&&(r=i),i-r+1===c)return r*s}else-1!==r&&(i-=i-r),r=-1}else for(n+c>a&&(n=a-c),i=n;i>=0;i--){let n=!0;for(let r=0;r<c;r++)if(u(e,i+r)!==u(t,r)){n=!1;break}if(n)return i}return-1}function w(e,t,n,r){n=Number(n)||0;const o=e.length-n;r?(r=Number(r))>o&&(r=o):r=o;const i=t.length;let s;for(r>i/2&&(r=i/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 j(G(t,e.length-n),e,n,r)}function k(e,t,n,r){return j(function(e){const t=[];for(let n=0;n<e.length;++n)t.push(255&e.charCodeAt(n));return t}(t),e,n,r)}function v(e,t,n,r){return j(W(t),e,n,r)}function E(e,t,n,r){return j(function(e,t){let n,r,o;const i=[];for(let s=0;s<e.length&&!((t-=2)<0);++s)n=e.charCodeAt(s),r=n>>8,o=n%256,i.push(o),i.push(r);return i}(t,e.length-n),e,n,r)}function S(e,n,r){return 0===n&&r===e.length?t.fromByteArray(e):t.fromByteArray(e.slice(n,r))}function T(e,t,n){n=Math.min(e.length,n);const r=[];let o=t;for(;o<n;){const t=e[o];let i=null,s=t>239?4:t>223?3:t>191?2:1;if(o+s<=n){let n,r,a,c;switch(s){case 1:t<128&&(i=t);break;case 2:n=e[o+1],128==(192&n)&&(c=(31&t)<<6|63&n,c>127&&(i=c));break;case 3:n=e[o+1],r=e[o+2],128==(192&n)&&128==(192&r)&&(c=(15&t)<<12|(63&n)<<6|63&r,c>2047&&(c<55296||c>57343)&&(i=c));break;case 4:n=e[o+1],r=e[o+2],a=e[o+3],128==(192&n)&&128==(192&r)&&128==(192&a)&&(c=(15&t)<<18|(63&n)<<12|(63&r)<<6|63&a,c>65535&&c<1114112&&(i=c))}}null===i?(i=65533,s=1):i>65535&&(i-=65536,r.push(i>>>10&1023|55296),i=56320|1023&i),r.push(i),o+=s}return function(e){const t=e.length;if(t<=A)return String.fromCharCode.apply(String,e);let n="",r=0;for(;r<t;)n+=String.fromCharCode.apply(String,e.slice(r,r+=A));return n}(r)}e.kMaxLength=o,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?i(e):void 0!==t?"string"==typeof n?i(e).fill(t,n):i(e).fill(t):i(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(H(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),H(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 o=0,i=Math.min(n,r);o<i;++o)if(e[o]!==t[o]){n=e[o],r=t[o];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 o=0;for(n=0;n<e.length;++n){let t=e[n];if(H(t,Uint8Array))o+t.length>r.length?(s.isBuffer(t)||(t=s.from(t)),t.copy(r,o)):Uint8Array.prototype.set.call(r,t,o);else{if(!s.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(r,o)}o+=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)g(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)g(this,t,t+3),g(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)g(this,t,t+7),g(this,t+1,t+6),g(this,t+2,t+5),g(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,o){if(H(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===o&&(o=this.length),t<0||n>e.length||r<0||o>this.length)throw new RangeError("out of range index");if(r>=o&&t>=n)return 0;if(r>=o)return-1;if(t>=n)return 1;if(this===e)return 0;let i=(o>>>=0)-(r>>>=0),a=(n>>>=0)-(t>>>=0);const c=Math.min(i,a),u=this.slice(r,o),l=e.slice(t,n);for(let e=0;e<c;++e)if(u[e]!==l[e]){i=u[e],a=l[e];break}return i<a?-1:a<i?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 o=this.length-t;if((void 0===n||n>o)&&(n=o),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");let i=!1;for(;;)switch(r){case"hex":return 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 E(this,e,t,n);default:if(i)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),i=!0}},s.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const A=4096;function I(e,t,n){let r="";n=Math.min(e.length,n);for(let o=t;o<n;++o)r+=String.fromCharCode(127&e[o]);return r}function B(e,t,n){let r="";n=Math.min(e.length,n);for(let o=t;o<n;++o)r+=String.fromCharCode(e[o]);return r}function x(e,t,n){const r=e.length;(!t||t<0)&&(t=0),(!n||n<0||n>r)&&(n=r);let o="";for(let r=t;r<n;++r)o+=X[e[r]];return o}function C(e,t,n){const r=e.slice(t,n);let o="";for(let e=0;e<r.length-1;e+=2)o+=String.fromCharCode(r[e]+256*r[e+1]);return o}function P(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 N(e,t,n,r,o,i){if(!s.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>o||t<i)throw new RangeError('"value" argument is out of bounds');if(n+r>e.length)throw new RangeError("Index out of range")}function _(e,t,n,r,o){$(t,r,o,e,n,7);let i=Number(t&BigInt(4294967295));e[n++]=i,i>>=8,e[n++]=i,i>>=8,e[n++]=i,i>>=8,e[n++]=i;let 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,o){$(t,r,o,e,n,7);let i=Number(t&BigInt(4294967295));e[n+7]=i,i>>=8,e[n+6]=i,i>>=8,e[n+5]=i,i>>=8,e[n+4]=i;let 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 U(e,t,n,r,o,i){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,o,i){return t=+t,r>>>=0,i||U(e,0,r,4),n.write(e,t,r,o,23,4),r+4}function L(e,t,r,o,i){return t=+t,r>>>=0,i||U(e,0,r,8),n.write(e,t,r,o,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||P(e,t,this.length);let r=this[e],o=1,i=0;for(;++i<t&&(o*=256);)r+=this[e+i]*o;return r},s.prototype.readUintBE=s.prototype.readUIntBE=function(e,t,n){e>>>=0,t>>>=0,n||P(e,t,this.length);let r=this[e+--t],o=1;for(;t>0&&(o*=256);)r+=this[e+--t]*o;return r},s.prototype.readUint8=s.prototype.readUInt8=function(e,t){return e>>>=0,t||P(e,1,this.length),this[e]},s.prototype.readUint16LE=s.prototype.readUInt16LE=function(e,t){return e>>>=0,t||P(e,2,this.length),this[e]|this[e+1]<<8},s.prototype.readUint16BE=s.prototype.readUInt16BE=function(e,t){return e>>>=0,t||P(e,2,this.length),this[e]<<8|this[e+1]},s.prototype.readUint32LE=s.prototype.readUInt32LE=function(e,t){return e>>>=0,t||P(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||P(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,o=this[++e]+256*this[++e]+65536*this[++e]+n*2**24;return BigInt(r)+(BigInt(o)<<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],o=this[++e]*2**24+65536*this[++e]+256*this[++e]+n;return(BigInt(r)<<BigInt(32))+BigInt(o)}),s.prototype.readIntLE=function(e,t,n){e>>>=0,t>>>=0,n||P(e,t,this.length);let r=this[e],o=1,i=0;for(;++i<t&&(o*=256);)r+=this[e+i]*o;return o*=128,r>=o&&(r-=Math.pow(2,8*t)),r},s.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||P(e,t,this.length);let r=t,o=1,i=this[e+--r];for(;r>0&&(o*=256);)i+=this[e+--r]*o;return o*=128,i>=o&&(i-=Math.pow(2,8*t)),i},s.prototype.readInt8=function(e,t){return e>>>=0,t||P(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},s.prototype.readInt16LE=function(e,t){e>>>=0,t||P(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||P(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||P(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||P(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||P(e,4,this.length),n.read(this,e,!0,23,4)},s.prototype.readFloatBE=function(e,t){return e>>>=0,t||P(e,4,this.length),n.read(this,e,!1,23,4)},s.prototype.readDoubleLE=function(e,t){return e>>>=0,t||P(e,8,this.length),n.read(this,e,!0,52,8)},s.prototype.readDoubleBE=function(e,t){return e>>>=0,t||P(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||N(this,e,t,n,Math.pow(2,8*n)-1,0);let o=1,i=0;for(this[t]=255&e;++i<n&&(o*=256);)this[t+i]=e/o&255;return t+n},s.prototype.writeUintBE=s.prototype.writeUIntBE=function(e,t,n,r){e=+e,t>>>=0,n>>>=0,r||N(this,e,t,n,Math.pow(2,8*n)-1,0);let o=n-1,i=1;for(this[t+o]=255&e;--o>=0&&(i*=256);)this[t+o]=e/i&255;return t+n},s.prototype.writeUint8=s.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||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||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||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||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||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 _(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);N(this,e,t,n,r-1,-r)}let o=0,i=1,s=0;for(this[t]=255&e;++o<n&&(i*=256);)e<0&&0===s&&0!==this[t+o-1]&&(s=1),this[t+o]=(e/i|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);N(this,e,t,n,r-1,-r)}let o=n-1,i=1,s=0;for(this[t+o]=255&e;--o>=0&&(i*=256);)e<0&&0===s&&0!==this[t+o+1]&&(s=1),this[t+o]=(e/i|0)-s&255;return t+n},s.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||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||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||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||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||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 _(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 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 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 o=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),o},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 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{const i=s.isBuffer(e)?e:s.from(e,r),a=i.length;if(0===a)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(o=0;o<n-t;++o)this[o+t]=i[o%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 M(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,o,i){if(e>n||e<t){const n="bigint"==typeof t?"n":"";let r;throw r=0===t||t===BigInt(0)?`>= 0${n} and < 2${n} ** ${8*(i+1)}${n}`:`>= -(2${n} ** ${8*(i+1)-1}${n}) and < 2 ** ${8*(i+1)-1}${n}`,new 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,o,i)}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.`,o=n;return Number.isInteger(n)&&Math.abs(n)>2**32?o=M(String(n)):"bigint"==typeof n&&(o=String(n),(n>BigInt(2)**BigInt(32)||n<-(BigInt(2)**BigInt(32)))&&(o=M(o)),o+="n"),r+=` It must be ${t}. Received ${o}`,r},RangeError);const z=/[^+/0-9A-Za-z-_]/g;function G(e,t){let n;t=t||1/0;const r=e.length;let o=null;const i=[];for(let s=0;s<r;++s){if(n=e.charCodeAt(s),n>55295&&n<57344){if(!o){if(n>56319){(t-=3)>-1&&i.push(239,191,189);continue}if(s+1===r){(t-=3)>-1&&i.push(239,191,189);continue}o=n;continue}if(n<56320){(t-=3)>-1&&i.push(239,191,189),o=n;continue}n=65536+(o-55296<<10|n-56320)}else o&&(t-=3)>-1&&i.push(239,191,189);if(o=null,n<128){if((t-=1)<0)break;i.push(n)}else if(n<2048){if((t-=2)<0)break;i.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;i.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;i.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return i}function W(e){return t.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(z,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function j(e,t,n,r){let o;for(o=0;o<r&&!(o+n>=t.length||o>=e.length);++o)t[o+n]=e[o];return o}function H(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 o=0;o<16;++o)t[r+o]=e[n]+e[o]}return t}();function Q(e){return"undefined"==typeof BigInt?Z:e}function Z(){throw new Error("BigInt not supported")}}(Zi)),Zi);const is="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0;function ss(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function as(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function cs(e,...t){if(!ss(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 us(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.createHasher");as(e.outputLen),as(e.blockLen)}function ls(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 hs(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function ds(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function fs(e,t){return e<<32-t|e>>>t}const ps=(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)(),gs=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function ms(e){if(cs(e),ps)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=gs[e[n]];return t}const ys=48,ws=57,bs=65,ks=70,vs=97,Es=102;function Ss(e){return e>=ys&&e<=ws?e-ys:e>=bs&&e<=ks?e-(bs-10):e>=vs&&e<=Es?e-(vs-10):void 0}function Ts(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);if(ps)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,o=0;t<n;t++,o+=2){const n=Ss(e.charCodeAt(o)),i=Ss(e.charCodeAt(o+1));if(void 0===n||void 0===i){const t=e[o]+e[o+1];throw new Error('hex string expected, got non-hex character "'+t+'" at index '+o)}r[t]=16*n+i}return r}function As(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)),cs(e),e}function Is(...e){let t=0;for(let n=0;n<e.length;n++){const r=e[n];cs(r),t+=r.length}const n=new Uint8Array(t);for(let t=0,r=0;t<e.length;t++){const o=e[t];n.set(o,r),r+=o.length}return n}class Bs{}function xs(e){const t=t=>e().update(As(t)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function Cs(e=32){if(is&&"function"==typeof is.getRandomValues)return is.getRandomValues(new Uint8Array(e));if(is&&"function"==typeof is.randomBytes)return Uint8Array.from(is.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}function Ps(e,t,n){return e&t^~e&n}function Ns(e,t,n){return e&t^e&n^t&n}class _s extends Bs{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=ds(this.buffer)}update(e){ls(this),cs(e=As(e));const{view:t,buffer:n,blockLen:r}=this,o=e.length;for(let i=0;i<o;){const s=Math.min(r-this.pos,o-i);if(s===r){const t=ds(e);for(;r<=o-i;i+=r)this.process(t,i);continue}n.set(e.subarray(i,i+s),this.pos),this.pos+=s,i+=s,this.pos===r&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){ls(this),function(e,t){cs(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:o}=this;let{pos:i}=this;t[i++]=128,hs(this.buffer.subarray(i)),this.padOffset>r-i&&(this.process(n,0),i=0);for(let e=i;e<r;e++)t[e]=0;!function(e,t,n,r){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,n,r);const o=BigInt(32),i=BigInt(4294967295),s=Number(n>>o&i),a=Number(n&i),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),o),this.process(n,0);const s=ds(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],o)}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:o,destroyed:i,pos:s}=this;return e.destroyed=i,e.finished=o,e.length=r,e.pos=s,r%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}}const Ds=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Us=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Rs=BigInt(2**32-1),Ls=BigInt(32);function Os(e,t=!1){return t?{h:Number(e&Rs),l:Number(e>>Ls&Rs)}:{h:0|Number(e>>Ls&Rs),l:0|Number(e&Rs)}}const Fs=(e,t,n)=>e>>>n,Ms=(e,t,n)=>e<<32-n|t>>>n,$s=(e,t,n)=>e>>>n|t<<32-n,qs=(e,t,n)=>e<<32-n|t>>>n,Ks=(e,t,n)=>e<<64-n|t>>>n-32,zs=(e,t,n)=>e>>>n-32|t<<64-n;function Gs(e,t,n,r){const o=(t>>>0)+(r>>>0);return{h:e+n+(o/2**32|0)|0,l:0|o}}const Ws=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),js=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,Hs=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),Vs=(e,t,n,r,o)=>t+n+r+o+(e/2**32|0)|0,Xs=(e,t,n,r,o)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(o>>>0),Qs=(e,t,n,r,o,i)=>t+n+r+o+i+(e/2**32|0)|0,Zs=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]),Ys=new Uint32Array(64);class Js extends _s{constructor(e=32){super(64,e,8,!1),this.A=0|Ds[0],this.B=0|Ds[1],this.C=0|Ds[2],this.D=0|Ds[3],this.E=0|Ds[4],this.F=0|Ds[5],this.G=0|Ds[6],this.H=0|Ds[7]}get(){const{A:e,B:t,C:n,D:r,E:o,F:i,G:s,H:a}=this;return[e,t,n,r,o,i,s,a]}set(e,t,n,r,o,i,s,a){this.A=0|e,this.B=0|t,this.C=0|n,this.D=0|r,this.E=0|o,this.F=0|i,this.G=0|s,this.H=0|a}process(e,t){for(let n=0;n<16;n++,t+=4)Ys[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){const t=Ys[e-15],n=Ys[e-2],r=fs(t,7)^fs(t,18)^t>>>3,o=fs(n,17)^fs(n,19)^n>>>10;Ys[e]=o+Ys[e-7]+r+Ys[e-16]|0}let{A:n,B:r,C:o,D:i,E:s,F:a,G:c,H:u}=this;for(let e=0;e<64;e++){const t=u+(fs(s,6)^fs(s,11)^fs(s,25))+Ps(s,a,c)+Zs[e]+Ys[e]|0,l=(fs(n,2)^fs(n,13)^fs(n,22))+Ns(n,r,o)|0;u=c,c=a,a=s,s=i+t|0,i=o,o=r,r=n,n=t+l|0}n=n+this.A|0,r=r+this.B|0,o=o+this.C|0,i=i+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,o,i,s,a,c,u)}roundClean(){hs(Ys)}destroy(){this.set(0,0,0,0,0,0,0,0),hs(this.buffer)}}const ea=(()=>function(e,t=!1){const n=e.length;let r=new Uint32Array(n),o=new Uint32Array(n);for(let i=0;i<n;i++){const{h:n,l:s}=Os(e[i],t);[r[i],o[i]]=[n,s]}return[r,o]}(["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))))(),ta=(()=>ea[0])(),na=(()=>ea[1])(),ra=new Uint32Array(80),oa=new Uint32Array(80);class ia extends _s{constructor(e=64){super(128,e,16,!1),this.Ah=0|Us[0],this.Al=0|Us[1],this.Bh=0|Us[2],this.Bl=0|Us[3],this.Ch=0|Us[4],this.Cl=0|Us[5],this.Dh=0|Us[6],this.Dl=0|Us[7],this.Eh=0|Us[8],this.El=0|Us[9],this.Fh=0|Us[10],this.Fl=0|Us[11],this.Gh=0|Us[12],this.Gl=0|Us[13],this.Hh=0|Us[14],this.Hl=0|Us[15]}get(){const{Ah:e,Al:t,Bh:n,Bl:r,Ch:o,Cl:i,Dh:s,Dl:a,Eh:c,El:u,Fh:l,Fl:h,Gh:d,Gl:f,Hh:p,Hl:g}=this;return[e,t,n,r,o,i,s,a,c,u,l,h,d,f,p,g]}set(e,t,n,r,o,i,s,a,c,u,l,h,d,f,p,g){this.Ah=0|e,this.Al=0|t,this.Bh=0|n,this.Bl=0|r,this.Ch=0|o,this.Cl=0|i,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|p,this.Hl=0|g}process(e,t){for(let n=0;n<16;n++,t+=4)ra[n]=e.getUint32(t),oa[n]=e.getUint32(t+=4);for(let e=16;e<80;e++){const t=0|ra[e-15],n=0|oa[e-15],r=$s(t,n,1)^$s(t,n,8)^Fs(t,0,7),o=qs(t,n,1)^qs(t,n,8)^Ms(t,n,7),i=0|ra[e-2],s=0|oa[e-2],a=$s(i,s,19)^Ks(i,s,61)^Fs(i,0,6),c=qs(i,s,19)^zs(i,s,61)^Ms(i,s,6),u=Hs(o,c,oa[e-7],oa[e-16]),l=Vs(u,r,a,ra[e-7],ra[e-16]);ra[e]=0|l,oa[e]=0|u}let{Ah:n,Al:r,Bh:o,Bl:i,Ch:s,Cl:a,Dh:c,Dl:u,Eh:l,El:h,Fh:d,Fl:f,Gh:p,Gl:g,Hh:m,Hl:y}=this;for(let e=0;e<80;e++){const t=$s(l,h,14)^$s(l,h,18)^Ks(l,h,41),w=qs(l,h,14)^qs(l,h,18)^zs(l,h,41),b=l&d^~l&p,k=Xs(y,w,h&f^~h&g,na[e],oa[e]),v=Qs(k,m,t,b,ta[e],ra[e]),E=0|k,S=$s(n,r,28)^Ks(n,r,34)^Ks(n,r,39),T=qs(n,r,28)^zs(n,r,34)^zs(n,r,39),A=n&o^n&s^o&s,I=r&i^r&a^i&a;m=0|p,y=0|g,p=0|d,g=0|f,d=0|l,f=0|h,({h:l,l:h}=Gs(0|c,0|u,0|v,0|E)),c=0|s,u=0|a,s=0|o,a=0|i,o=0|n,i=0|r;const B=Ws(E,T,I);n=js(B,v,S,A),r=0|B}({h:n,l:r}=Gs(0|this.Ah,0|this.Al,0|n,0|r)),({h:o,l:i}=Gs(0|this.Bh,0|this.Bl,0|o,0|i)),({h:s,l:a}=Gs(0|this.Ch,0|this.Cl,0|s,0|a)),({h:c,l:u}=Gs(0|this.Dh,0|this.Dl,0|c,0|u)),({h:l,l:h}=Gs(0|this.Eh,0|this.El,0|l,0|h)),({h:d,l:f}=Gs(0|this.Fh,0|this.Fl,0|d,0|f)),({h:p,l:g}=Gs(0|this.Gh,0|this.Gl,0|p,0|g)),({h:m,l:y}=Gs(0|this.Hh,0|this.Hl,0|m,0|y)),this.set(n,r,o,i,s,a,c,u,l,h,d,f,p,g,m,y)}roundClean(){hs(ra,oa)}destroy(){hs(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const sa=xs(()=>new Js),aa=xs(()=>new ia),ca=BigInt(0),ua=BigInt(1);function la(e,t=""){if("boolean"!=typeof e){throw new Error((t&&`"${t}"`)+"expected boolean, got type="+typeof e)}return e}function ha(e,t,n=""){const r=ss(e),o=e?.length,i=void 0!==t;if(!r||i&&o!==t){throw new Error((n&&`"${n}" `)+"expected Uint8Array"+(i?` of length ${t}`:"")+", got "+(r?`length=${o}`:"type="+typeof e))}return e}function da(e){const t=e.toString(16);return 1&t.length?"0"+t:t}function fa(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);return""===e?ca:BigInt("0x"+e)}function pa(e){return fa(ms(e))}function ga(e){return cs(e),fa(ms(Uint8Array.from(e).reverse()))}function ma(e,t){return Ts(e.toString(16).padStart(2*t,"0"))}function ya(e,t){return ma(e,t).reverse()}function wa(e,t,n){let r;if("string"==typeof t)try{r=Ts(t)}catch(t){throw new Error(e+" must be hex string or Uint8Array, cause: "+t)}else{if(!ss(t))throw new Error(e+" must be hex string or Uint8Array");r=Uint8Array.from(t)}const o=r.length;if("number"==typeof n&&o!==n)throw new Error(e+" of length "+n+" expected, got "+o);return r}function ba(e){return Uint8Array.from(e)}const ka=e=>"bigint"==typeof e&&ca<=e;function va(e,t,n,r){if(!function(e,t,n){return ka(e)&&ka(t)&&ka(n)&&t<=e&&e<n}(t,n,r))throw new Error("expected valid "+e+": "+n+" <= n < "+r+", got "+t)}function Ea(e){let t;for(t=0;e>ca;e>>=ua,t+=1);return t}const Sa=e=>(ua<<BigInt(e))-ua;function Ta(e,t,n={}){if(!e||"object"!=typeof e)throw new Error("expected valid options object");function r(t,n,r){const o=e[t];if(r&&void 0===o)return;const i=typeof o;if(i!==n||null===o)throw new Error(`param "${t}" is invalid: expected ${n}, got ${i}`)}Object.entries(t).forEach(([e,t])=>r(e,t,!1)),Object.entries(n).forEach(([e,t])=>r(e,t,!0))}function Aa(e){const t=new WeakMap;return(n,...r)=>{const o=t.get(n);if(void 0!==o)return o;const i=e(n,...r);return t.set(n,i),i}}const Ia=BigInt(0),Ba=BigInt(1),xa=BigInt(2),Ca=BigInt(3),Pa=BigInt(4),Na=BigInt(5),_a=BigInt(7),Da=BigInt(8),Ua=BigInt(9),Ra=BigInt(16);function La(e,t){const n=e%t;return n>=Ia?n:t+n}function Oa(e,t,n){let r=e;for(;t-- >Ia;)r*=r,r%=n;return r}function Fa(e,t){if(e===Ia)throw new Error("invert: expected non-zero number");if(t<=Ia)throw new Error("invert: expected positive modulus, got "+t);let n=La(e,t),r=t,o=Ia,i=Ba;for(;n!==Ia;){const e=r%n,t=o-i*(r/n);r=n,n=e,o=i,i=t}if(r!==Ba)throw new Error("invert: does not exist");return La(o,t)}function Ma(e,t,n){if(!e.eql(e.sqr(t),n))throw new Error("Cannot find square root")}function $a(e,t){const n=(e.ORDER+Ba)/Pa,r=e.pow(t,n);return Ma(e,r,t),r}function qa(e,t){const n=(e.ORDER-Na)/Da,r=e.mul(t,xa),o=e.pow(r,n),i=e.mul(t,o),s=e.mul(e.mul(i,xa),o),a=e.mul(i,e.sub(s,e.ONE));return Ma(e,a,t),a}function Ka(e){if(e<Ca)throw new Error("sqrt is not defined for small field");let t=e-Ba,n=0;for(;t%xa===Ia;)t/=xa,n++;let r=xa;const o=Va(e);for(;1===ja(o,r);)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(1===n)return $a;let i=o.pow(r,t);const s=(t+Ba)/xa;return function(e,r){if(e.is0(r))return r;if(1!==ja(e,r))throw new Error("Cannot find square root");let o=n,a=e.mul(e.ONE,i),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===o)throw new Error("Cannot find square root");const r=Ba<<BigInt(o-t-1),i=e.pow(a,r);o=t,a=e.sqr(i),c=e.mul(c,a),u=e.mul(u,i)}return u}}function za(e){return e%Pa===Ca?$a:e%Da===Na?qa:e%Ra===Ua?function(e){const t=Va(e),n=Ka(e),r=n(t,t.neg(t.ONE)),o=n(t,r),i=n(t,t.neg(r)),s=(e+_a)/Ra;return(e,t)=>{let n=e.pow(t,s),a=e.mul(n,r);const c=e.mul(n,o),u=e.mul(n,i),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 Ma(e,f,t),f}}(e):Ka(e)}const Ga=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Wa(e,t,n=!1){const r=new Array(t.length).fill(n?e.ZERO:void 0),o=t.reduce((t,n,o)=>e.is0(n)?t:(r[o]=t,e.mul(t,n)),e.ONE),i=e.inv(o);return t.reduceRight((t,n,o)=>e.is0(n)?t:(r[o]=e.mul(t,r[o]),e.mul(t,n)),i),r}function ja(e,t){const n=(e.ORDER-Ba)/xa,r=e.pow(t,n),o=e.eql(r,e.ONE),i=e.eql(r,e.ZERO),s=e.eql(r,e.neg(e.ONE));if(!o&&!i&&!s)throw new Error("invalid Legendre symbol result");return o?1:i?0:-1}function Ha(e,t){void 0!==t&&as(t);const n=void 0!==t?t:e.toString(2).length;return{nBitLength:n,nByteLength:Math.ceil(n/8)}}function Va(e,t,n=!1,r={}){if(e<=Ia)throw new Error("invalid field: expected ORDER > 0, got "+e);let o,i,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&&(o=e.BITS),e.sqrt&&(i=e.sqrt),"boolean"==typeof e.isLE&&(n=e.isLE),"boolean"==typeof e.modFromBytes&&(a=e.modFromBytes),s=e.allowedLengths}else"number"==typeof t&&(o=t),r.sqrt&&(i=r.sqrt);const{nBitLength:c,nByteLength:u}=Ha(e,o);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:Sa(c),ZERO:Ia,ONE:Ba,allowedLengths:s,create:t=>La(t,e),isValid:t=>{if("bigint"!=typeof t)throw new Error("invalid field element: expected bigint, got "+typeof t);return Ia<=t&&t<e},is0:e=>e===Ia,isValidNot0:e=>!h.is0(e)&&h.isValid(e),isOdd:e=>(e&Ba)===Ba,neg:t=>La(-t,e),eql:(e,t)=>e===t,sqr:t=>La(t*t,e),add:(t,n)=>La(t+n,e),sub:(t,n)=>La(t-n,e),mul:(t,n)=>La(t*n,e),pow:(e,t)=>function(e,t,n){if(n<Ia)throw new Error("invalid exponent, negatives unsupported");if(n===Ia)return e.ONE;if(n===Ba)return t;let r=e.ONE,o=t;for(;n>Ia;)n&Ba&&(r=e.mul(r,o)),o=e.sqr(o),n>>=Ba;return r}(h,e,t),div:(t,n)=>La(t*Fa(n,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>Fa(t,e),sqrt:i||(t=>(l||(l=za(e)),l(h,t))),toBytes:e=>n?ya(e,u):ma(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 o=n?ga(t):pa(t);if(a&&(o=La(o,e)),!r&&!h.isValid(o))throw new Error("invalid field element: outside of range 0..ORDER");return o},invertBatch:e=>Wa(h,e),cmov:(e,t,n)=>n?t:e});return Object.freeze(h)}function Xa(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 Qa(e){const t=Xa(e);return t+Math.ceil(t/2)}const Za=BigInt(0),Ya=BigInt(1);function Ja(e,t){const n=t.negate();return e?n:t}function ec(e,t){const n=Wa(e.Fp,t.map(e=>e.Z));return t.map((t,r)=>e.fromAffine(t.toAffine(n[r])))}function tc(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function nc(e,t){tc(e,t);const n=2**e;return{windows:Math.ceil(t/e)+1,windowSize:2**(e-1),mask:Sa(e),maxNumber:n,shiftBy:BigInt(e)}}function rc(e,t,n){const{windowSize:r,mask:o,maxNumber:i,shiftBy:s}=n;let a=Number(e&o),c=e>>s;a>r&&(a-=i,c+=Ya);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 oc=new WeakMap,ic=new WeakMap;function sc(e){return ic.get(e)||1}function ac(e){if(e!==Za)throw new Error("invalid wNAF")}class cc{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>Za;)t&Ya&&(n=n.add(r)),r=r.double(),t>>=Ya;return n}precomputeWindow(e,t){const{windows:n,windowSize:r}=nc(t,this.bits),o=[];let i=e,s=i;for(let e=0;e<n;e++){s=i,o.push(s);for(let e=1;e<r;e++)s=s.add(i),o.push(s);i=s.double()}return o}wNAF(e,t,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let r=this.ZERO,o=this.BASE;const i=nc(e,this.bits);for(let e=0;e<i.windows;e++){const{nextN:s,offset:a,isZero:c,isNeg:u,isNegF:l,offsetF:h}=rc(n,e,i);n=s,c?o=o.add(Ja(l,t[h])):r=r.add(Ja(u,t[a]))}return ac(n),{p:r,f:o}}wNAFUnsafe(e,t,n,r=this.ZERO){const o=nc(e,this.bits);for(let e=0;e<o.windows&&n!==Za;e++){const{nextN:i,offset:s,isZero:a,isNeg:c}=rc(n,e,o);if(n=i,!a){const e=t[s];r=r.add(c?e.negate():e)}}return ac(n),r}getPrecomputes(e,t,n){let r=oc.get(t);return r||(r=this.precomputeWindow(t,e),1!==e&&("function"==typeof n&&(r=n(r)),oc.set(t,r))),r}cached(e,t,n){const r=sc(e);return this.wNAF(r,this.getPrecomputes(r,e,n),t)}unsafe(e,t,n,r){const o=sc(e);return 1===o?this._unsafeLadder(e,t,r):this.wNAFUnsafe(o,this.getPrecomputes(o,e,n),t,r)}createCache(e,t){tc(t,this.bits),ic.set(e,t),oc.delete(e)}hasCache(e){return 1!==sc(e)}}function uc(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 o=n.length,i=r.length;if(o!==i)throw new Error("arrays of points and scalars must have equal length");const s=e.ZERO,a=Ea(BigInt(o));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const u=Sa(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<i;t++){const o=r[t],i=Number(o>>BigInt(e)&u);l[i]=l[i].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 lc(e,t,n){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return function(e){Ta(e,Ga.reduce((e,t)=>(e[t]="function",e),{ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"}))}(t),t}return Va(e,{isLE:n})}function hc(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>Za))throw new Error(`CURVE.${e} must be positive bigint`)}const o=lc(t.p,n.Fp,r),i=lc(t.n,n.Fn,r),s=["Gx","Gy","a","weierstrass"===e?"b":"d"];for(const e of s)if(!o.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:o,Fn:i}}const dc=BigInt(0),fc=BigInt(1),pc=BigInt(2),gc=BigInt(8);function mc(e,t,n={}){if("function"!=typeof t)throw new Error('"hash" function param is required');Ta(n,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});const{prehash:r}=n,{BASE:o,Fp:i,Fn:s}=e,a=n.randomBytes||Cs,c=n.adjustScalarBytes||(e=>e),u=n.domain||((e,t,n)=>{if(la(n,"phflag"),t.length||n)throw new Error("Contexts/pre-hash are not supported");return e});function l(e){return s.create(ga(e))}function h(e){const{head:n,prefix:r,scalar:i}=function(e){const n=m.secretKey;e=wa("private key",e,n);const r=wa("hashed private key",t(e),2*n),o=c(r.slice(0,n));return{head:o,prefix:r.slice(n,2*n),scalar:l(o)}}(e),s=o.multiply(i),a=s.toBytes();return{head:n,prefix:r,scalar:i,point:s,pointBytes:a}}function d(e){return h(e).pointBytes}function f(e=Uint8Array.of(),...n){const o=Is(...n);return l(t(u(o,wa("context",e),!!r)))}const p={zip215:!0};const g=i.BYTES,m={secretKey:g,publicKey:g,signature:2*g,seed:g};function y(e=a(m.seed)){return ha(e,m.seed,"seed")}const w={getExtendedPublicKey:h,randomSecretKey:y,isValidSecretKey:function(e){return ss(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,o=32===r;if(!o&&57!==r)throw new Error("only defined for 25519 and 448");const s=o?i.div(fc+n,fc-n):i.div(n-fc,n+fc);return i.toBytes(s)},toMontgomerySecret(e){const n=m.secretKey;ha(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=wa("message",e),r&&(e=r(e));const{prefix:i,scalar:a,pointBytes:c}=h(t),u=f(n.context,i,e),l=o.multiply(u).toBytes(),d=f(n.context,l,c,e),p=s.create(u+d*a);if(!s.isValid(p))throw new Error("sign failed: invalid s");return ha(Is(l,s.toBytes(p)),m.signature,"result")},verify:function(t,n,i,s=p){const{context:a,zip215:c}=s,u=m.signature;t=wa("signature",t,u),n=wa("message",n),i=wa("publicKey",i,m.publicKey),void 0!==c&&la(c,"zip215"),r&&(n=r(n));const l=u/2,h=t.subarray(0,l),d=ga(t.subarray(l,u));let g,y,w;try{g=e.fromBytes(i,c),y=e.fromBytes(h,c),w=o.multiplyUnsafe(d)}catch(e){return!1}if(!c&&g.isSmallOrder())return!1;const b=f(a,y.toBytes(),g.toBytes(),n);return y.add(g.multiplyUnsafe(b)).subtract(w).clearCofactor().is0()},utils:w,Point:e,lengths:m})}function yc(e){const{CURVE:t,curveOpts:n,hash:r,eddsaOpts:o}=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:Va(t.n,e.nBitLength,!0),uvRatio:e.uvRatio},r={randomBytes:e.randomBytes,adjustScalarBytes:e.adjustScalarBytes,domain:e.domain,prehash:e.prehash,mapToCurve:e.mapToCurve};return{CURVE:t,curveOpts:n,hash:e.hash,eddsaOpts:r}}(e),i=function(e,t={}){const n=hc("edwards",e,t,t.FpFnLE),{Fp:r,Fn:o}=n;let i=n.CURVE;const{h:s}=i;Ta(t,{},{uvRatio:"function"});const a=pc<<BigInt(8*o.BYTES)-fc,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:dc}}});if(!function(e,t,n,r){const o=e.sqr(n),i=e.sqr(r),s=e.add(e.mul(t.a,o),i),a=e.add(e.ONE,e.mul(t.d,e.mul(o,i)));return e.eql(s,a)}(r,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");function l(e,t,n=!1){return va("coordinate "+e,t,n?fc:dc,a),t}function h(e){if(!(e instanceof p))throw new Error("ExtendedPoint expected")}const d=Aa((e,t)=>{const{X:n,Y:o,Z:i}=e,s=e.is0();null==t&&(t=s?gc:r.inv(i));const a=c(n*t),u=c(o*t),l=r.mul(i,t);if(s)return{x:dc,y:fc};if(l!==fc)throw new Error("invZ was invalid");return{x:a,y:u}}),f=Aa(e=>{const{a:t,d:n}=i;if(e.is0())throw new Error("bad point: ZERO");const{X:r,Y:o,Z:s,T:a}=e,u=c(r*r),l=c(o*o),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*o)!==c(s*a))throw new Error("bad point: equation left != right (2)");return!0});class p{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 i}static fromAffine(e){if(e instanceof p)throw new Error("extended point not allowed");const{x:t,y:n}=e||{};return l("x",t),l("y",n),new p(t,n,fc,c(t*n))}static fromBytes(e,t=!1){const n=r.BYTES,{a:o,d:s}=i;e=ba(ha(e,n,"point")),la(t,"zip215");const l=ba(e),h=e[n-1];l[n-1]=-129&h;const d=ga(l),f=t?a:r.ORDER;va("point.y",d,dc,f);const g=c(d*d),m=c(g-fc),y=c(s*g-o);let{isValid:w,value:b}=u(m,y);if(!w)throw new Error("bad point: invalid y coordinate");const k=(b&fc)===fc,v=!!(128&h);if(!t&&b===dc&&v)throw new Error("bad point: x=0 and x_0=1");return v!==k&&(b=c(-b)),p.fromAffine({x:b,y:d})}static fromHex(e,t=!1){return p.fromBytes(wa("point",e),t)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(e=8,t=!0){return g.createCache(this,e),t||this.multiply(pc),this}assertValidity(){f(this)}equals(e){h(e);const{X:t,Y:n,Z:r}=this,{X:o,Y:i,Z:s}=e,a=c(t*s),u=c(o*r),l=c(n*s),d=c(i*r);return a===u&&l===d}is0(){return this.equals(p.ZERO)}negate(){return new p(c(-this.X),this.Y,this.Z,c(-this.T))}double(){const{a:e}=i,{X:t,Y:n,Z:r}=this,o=c(t*t),s=c(n*n),a=c(pc*c(r*r)),u=c(e*o),l=t+n,h=c(c(l*l)-o-s),d=u+s,f=d-a,g=u-s,m=c(h*f),y=c(d*g),w=c(h*g),b=c(f*d);return new p(m,y,b,w)}add(e){h(e);const{a:t,d:n}=i,{X:r,Y:o,Z:s,T:a}=this,{X:u,Y:l,Z:d,T:f}=e,g=c(r*u),m=c(o*l),y=c(a*n*f),w=c(s*d),b=c((r+o)*(u+l)-g-m),k=w-y,v=w+y,E=c(m-t*g),S=c(b*k),T=c(v*E),A=c(b*E),I=c(k*v);return new p(S,T,I,A)}subtract(e){return this.add(e.negate())}multiply(e){if(!o.isValidNot0(e))throw new Error("invalid scalar: expected 1 <= sc < curve.n");const{p:t,f:n}=g.cached(this,e,e=>ec(p,e));return ec(p,[t,n])[0]}multiplyUnsafe(e,t=p.ZERO){if(!o.isValid(e))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return e===dc?p.ZERO:this.is0()||e===fc?this:g.unsafe(this,e,e=>ec(p,e),t)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}isTorsionFree(){return g.unsafe(this,i.n).is0()}toAffine(e){return d(this,e)}clearCofactor(){return s===fc?this:this.multiplyUnsafe(s)}toBytes(){const{x:e,y:t}=this.toAffine(),n=r.toBytes(t);return n[n.length-1]|=e&fc?128:0,n}toHex(){return ms(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 ec(p,e)}static msm(e,t){return uc(p,o,e,t)}_setWindowSize(e){this.precompute(e)}toRawBytes(){return this.toBytes()}}p.BASE=new p(i.Gx,i.Gy,fc,c(i.Gx*i.Gy)),p.ZERO=new p(dc,fc,fc,dc),p.Fp=r,p.Fn=o;const g=new cc(p,o.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,mc(i,r,o))}const wc=BigInt(1),bc=BigInt(2);BigInt(3);const kc=BigInt(5),vc=BigInt(8),Ec=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Sc=(()=>({p:Ec,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:vc,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")}))();function Tc(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}const Ac=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Ic(e,t){const n=Ec,r=La(t*t*t,n),o=function(e){const t=BigInt(10),n=BigInt(20),r=BigInt(40),o=BigInt(80),i=Ec,s=e*e%i*e%i,a=Oa(s,bc,i)*s%i,c=Oa(a,wc,i)*e%i,u=Oa(c,kc,i)*c%i,l=Oa(u,t,i)*u%i,h=Oa(l,n,i)*l%i,d=Oa(h,r,i)*h%i,f=Oa(d,o,i)*d%i,p=Oa(f,o,i)*d%i,g=Oa(p,t,i)*u%i;return{pow_p_5_8:Oa(g,bc,i)*e%i,b2:s}}(e*La(r*r*t,n)).pow_p_5_8;let i=La(e*r*o,n);const s=La(t*i*i,n),a=i,c=La(i*Ac,n),u=s===e,l=s===La(-e,n),h=s===La(-e*Ac,n);return u&&(i=a),(l||h)&&(i=c),(La(i,n)&Ba)===Ba&&(i=La(-i,n)),{isValid:u||l,value:i}}const Bc=(()=>Va(Sc.p,{isLE:!0}))(),xc=(()=>({...Sc,Fp:Bc,hash:aa,adjustScalarBytes:Tc,uvRatio:Ic}))(),Cc=(()=>yc(xc))();var Pc,Nc={exports:{}},_c=Fo(Object.freeze({__proto__:null,default:{}})),Dc=Nc.exports;function Uc(){return Pc||(Pc=1,function(e){!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 o(e,t,n){if(o.isBN(e))return e;this.negative=0,this.words=null,this.length=0,this.red=null,null!==e&&("le"!==t&&"be"!==t||(n=t,t=10),this._init(e||0,t||10,n||"be"))}var i;"object"==typeof e?e.exports=o:t.BN=o,o.BN=o,o.wordSize=26;try{i="undefined"!=typeof window&&void 0!==window.Buffer?window.Buffer:_c.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,o){for(var i=0,s=0,a=Math.min(e.length,r),c=t;c<a;c++){var u=e.charCodeAt(c)-48;i*=o,s=u>=49?u-49+10:u>=17?u-17+10:u,n(u>=0&&s<o,"Invalid character"),i+=s}return i}function u(e,t){e.words=t.words,e.length=t.length,e.negative=t.negative,e.red=t.red}if(o.isBN=function(e){return e instanceof o||null!==e&&"object"==typeof e&&e.constructor.wordSize===o.wordSize&&Array.isArray(e.words)},o.max=function(e,t){return e.cmp(t)>0?e:t},o.min=function(e,t){return e.cmp(t)<0?e:t},o.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 o=0;"-"===(e=e.toString().replace(/\s+/g,""))[0]&&(o++,this.negative=1),o<e.length&&(16===t?this._parseHex(e,o,r):(this._parseBase(e,t,o),"le"===r&&this._initArray(this.toArray(),t,r)))},o.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)},o.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 o=0;o<this.length;o++)this.words[o]=0;var i,s,a=0;if("be"===r)for(o=e.length-1,i=0;o>=0;o-=3)s=e[o]|e[o-1]<<8|e[o-2]<<16,this.words[i]|=s<<a&67108863,this.words[i+1]=s>>>26-a&67108863,(a+=24)>=26&&(a-=26,i++);else if("le"===r)for(o=0,i=0;o<e.length;o+=3)s=e[o]|e[o+1]<<8|e[o+2]<<16,this.words[i]|=s<<a&67108863,this.words[i+1]=s>>>26-a&67108863,(a+=24)>=26&&(a-=26,i++);return this._strip()},o.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 o,i=0,s=0;if("be"===n)for(r=e.length-1;r>=t;r-=2)o=a(e,t,r)<<i,this.words[s]|=67108863&o,i>=18?(i-=18,s+=1,this.words[s]|=o>>>26):i+=8;else for(r=(e.length-t)%2==0?t+1:t;r<e.length;r+=2)o=a(e,t,r)<<i,this.words[s]|=67108863&o,i>=18?(i-=18,s+=1,this.words[s]|=o>>>26):i+=8;this._strip()},o.prototype._parseBase=function(e,t,n){this.words=[0],this.length=1;for(var r=0,o=1;o<=67108863;o*=t)r++;r--,o=o/t|0;for(var i=e.length-n,s=i%r,a=Math.min(i,i-s)+n,u=0,l=n;l<a;l+=r)u=c(e,l,l+r,t),this.imuln(o),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()},o.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},o.prototype._move=function(e){u(e,this)},o.prototype.clone=function(){var e=new o(null);return this.copy(e),e},o.prototype._expand=function(e){for(;this.length<e;)this.words[this.length++]=0;return this},o.prototype._strip=function(){for(;this.length>1&&0===this.words[this.length-1];)this.length--;return this._normSign()},o.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},"undefined"!=typeof Symbol&&"function"==typeof Symbol.for)try{o.prototype[Symbol.for("nodejs.util.inspect.custom")]=l}catch(e){o.prototype.inspect=l}else o.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];o.prototype.toString=function(e,t){var r;if(t=0|t||1,16===(e=e||10)||"hex"===e){r="";for(var o=0,i=0,s=0;s<this.length;s++){var a=this.words[s],c=(16777215&(a<<o|i)).toString(16);i=a>>>24-o&16777215,(o+=2)>=26&&(o-=26,s--),r=0!==i||s!==this.length-1?h[6-c.length]+c+r:c+r}for(0!==i&&(r=i.toString(16)+r);r.length%t!==0;)r="0"+r;return 0!==this.negative&&(r="-"+r),r}if(e===(0|e)&&e>=2&&e<=36){var u=d[e],l=f[e];r="";var p=this.clone();for(p.negative=0;!p.isZero();){var g=p.modrn(l).toString(e);r=(p=p.idivn(l)).isZero()?g+r:h[u-g.length]+g+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")},o.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},o.prototype.toJSON=function(){return this.toString(16,2)},i&&(o.prototype.toBuffer=function(e,t){return this.toArrayLike(i,e,t)}),o.prototype.toArray=function(e,t){return this.toArrayLike(Array,e,t)};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 o=0|e.words[0],i=0|t.words[0],s=o*i,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 p=u-f|0;l+=(s=(o=0|e.words[p])*(i=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()}o.prototype.toArrayLike=function(e,t,r){this._strip();var o=this.byteLength(),i=r||Math.max(1,o);n(o<=i,"byte array longer than desired length"),n(i>0,"Requested array length <= 0");var s=function(e,t){return e.allocUnsafe?e.allocUnsafe(t):new e(t)}(e,i);return this["_toArrayLike"+("le"===t?"LE":"BE")](s,o),s},o.prototype._toArrayLikeLE=function(e,t){for(var n=0,r=0,o=0,i=0;o<this.length;o++){var s=this.words[o]<<i|r;e[n++]=255&s,n<e.length&&(e[n++]=s>>8&255),n<e.length&&(e[n++]=s>>16&255),6===i?(n<e.length&&(e[n++]=s>>24&255),r=0,i=0):(r=s>>>24,i+=2)}if(n<e.length)for(e[n++]=r;n<e.length;)e[n++]=0},o.prototype._toArrayLikeBE=function(e,t){for(var n=e.length-1,r=0,o=0,i=0;o<this.length;o++){var s=this.words[o]<<i|r;e[n--]=255&s,n>=0&&(e[n--]=s>>8&255),n>=0&&(e[n--]=s>>16&255),6===i?(n>=0&&(e[n--]=s>>24&255),r=0,i=0):(r=s>>>24,i+=2)}if(n>=0)for(e[n--]=r;n>=0;)e[n--]=0},Math.clz32?o.prototype._countBits=function(e){return 32-Math.clz32(e)}:o.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},o.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},o.prototype.bitLength=function(){var e=this.words[this.length-1],t=this._countBits(e);return 26*(this.length-1)+t},o.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},o.prototype.byteLength=function(){return Math.ceil(this.bitLength()/8)},o.prototype.toTwos=function(e){return 0!==this.negative?this.abs().inotn(e).iaddn(1):this.clone()},o.prototype.fromTwos=function(e){return this.testn(e-1)?this.notn(e).iaddn(1).ineg():this.clone()},o.prototype.isNeg=function(){return 0!==this.negative},o.prototype.neg=function(){return this.clone().ineg()},o.prototype.ineg=function(){return this.isZero()||(this.negative^=1),this},o.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()},o.prototype.ior=function(e){return n(0===(this.negative|e.negative)),this.iuor(e)},o.prototype.or=function(e){return this.length>e.length?this.clone().ior(e):e.clone().ior(this)},o.prototype.uor=function(e){return this.length>e.length?this.clone().iuor(e):e.clone().iuor(this)},o.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()},o.prototype.iand=function(e){return n(0===(this.negative|e.negative)),this.iuand(e)},o.prototype.and=function(e){return this.length>e.length?this.clone().iand(e):e.clone().iand(this)},o.prototype.uand=function(e){return this.length>e.length?this.clone().iuand(e):e.clone().iuand(this)},o.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()},o.prototype.ixor=function(e){return n(0===(this.negative|e.negative)),this.iuxor(e)},o.prototype.xor=function(e){return this.length>e.length?this.clone().ixor(e):e.clone().ixor(this)},o.prototype.uxor=function(e){return this.length>e.length?this.clone().iuxor(e):e.clone().iuxor(this)},o.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 o=0;o<t;o++)this.words[o]=67108863&~this.words[o];return r>0&&(this.words[o]=~this.words[o]&67108863>>26-r),this._strip()},o.prototype.notn=function(e){return this.clone().inotn(e)},o.prototype.setn=function(e,t){n("number"==typeof e&&e>=0);var r=e/26|0,o=e%26;return this._expand(r+1),this.words[r]=t?this.words[r]|1<<o:this.words[r]&~(1<<o),this._strip()},o.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 o=0,i=0;i<r.length;i++)t=(0|n.words[i])+(0|r.words[i])+o,this.words[i]=67108863&t,o=t>>>26;for(;0!==o&&i<n.length;i++)t=(0|n.words[i])+o,this.words[i]=67108863&t,o=t>>>26;if(this.length=n.length,0!==o)this.words[this.length]=o,this.length++;else if(n!==this)for(;i<n.length;i++)this.words[i]=n.words[i];return this},o.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)},o.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,o=this.cmp(e);if(0===o)return this.negative=0,this.length=1,this.words[0]=0,this;o>0?(n=this,r=e):(n=e,r=this);for(var i=0,s=0;s<r.length;s++)i=(t=(0|n.words[s])-(0|r.words[s])+i)>>26,this.words[s]=67108863&t;for(;0!==i&&s<n.length;s++)i=(t=(0|n.words[s])+i)>>26,this.words[s]=67108863&t;if(0===i&&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()},o.prototype.sub=function(e){return this.clone().isub(e)};var g=function(e,t,n){var r,o,i,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],p=8191&f,g=f>>>13,m=0|s[2],y=8191&m,w=m>>>13,b=0|s[3],k=8191&b,v=b>>>13,E=0|s[4],S=8191&E,T=E>>>13,A=0|s[5],I=8191&A,B=A>>>13,x=0|s[6],C=8191&x,P=x>>>13,N=0|s[7],_=8191&N,D=N>>>13,U=0|s[8],R=8191&U,L=U>>>13,O=0|s[9],F=8191&O,M=O>>>13,$=0|a[0],q=8191&$,K=$>>>13,z=0|a[1],G=8191&z,W=z>>>13,j=0|a[2],H=8191&j,V=j>>>13,X=0|a[3],Q=8191&X,Z=X>>>13,Y=0|a[4],J=8191&Y,ee=Y>>>13,te=0|a[5],ne=8191&te,re=te>>>13,oe=0|a[6],ie=8191&oe,se=oe>>>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],pe=8191&fe,ge=fe>>>13;n.negative=e.negative^t.negative,n.length=19;var me=(u+(r=Math.imul(h,q))|0)+((8191&(o=(o=Math.imul(h,K))+Math.imul(d,q)|0))<<13)|0;u=((i=Math.imul(d,K))+(o>>>13)|0)+(me>>>26)|0,me&=67108863,r=Math.imul(p,q),o=(o=Math.imul(p,K))+Math.imul(g,q)|0,i=Math.imul(g,K);var ye=(u+(r=r+Math.imul(h,G)|0)|0)+((8191&(o=(o=o+Math.imul(h,W)|0)+Math.imul(d,G)|0))<<13)|0;u=((i=i+Math.imul(d,W)|0)+(o>>>13)|0)+(ye>>>26)|0,ye&=67108863,r=Math.imul(y,q),o=(o=Math.imul(y,K))+Math.imul(w,q)|0,i=Math.imul(w,K),r=r+Math.imul(p,G)|0,o=(o=o+Math.imul(p,W)|0)+Math.imul(g,G)|0,i=i+Math.imul(g,W)|0;var we=(u+(r=r+Math.imul(h,H)|0)|0)+((8191&(o=(o=o+Math.imul(h,V)|0)+Math.imul(d,H)|0))<<13)|0;u=((i=i+Math.imul(d,V)|0)+(o>>>13)|0)+(we>>>26)|0,we&=67108863,r=Math.imul(k,q),o=(o=Math.imul(k,K))+Math.imul(v,q)|0,i=Math.imul(v,K),r=r+Math.imul(y,G)|0,o=(o=o+Math.imul(y,W)|0)+Math.imul(w,G)|0,i=i+Math.imul(w,W)|0,r=r+Math.imul(p,H)|0,o=(o=o+Math.imul(p,V)|0)+Math.imul(g,H)|0,i=i+Math.imul(g,V)|0;var be=(u+(r=r+Math.imul(h,Q)|0)|0)+((8191&(o=(o=o+Math.imul(h,Z)|0)+Math.imul(d,Q)|0))<<13)|0;u=((i=i+Math.imul(d,Z)|0)+(o>>>13)|0)+(be>>>26)|0,be&=67108863,r=Math.imul(S,q),o=(o=Math.imul(S,K))+Math.imul(T,q)|0,i=Math.imul(T,K),r=r+Math.imul(k,G)|0,o=(o=o+Math.imul(k,W)|0)+Math.imul(v,G)|0,i=i+Math.imul(v,W)|0,r=r+Math.imul(y,H)|0,o=(o=o+Math.imul(y,V)|0)+Math.imul(w,H)|0,i=i+Math.imul(w,V)|0,r=r+Math.imul(p,Q)|0,o=(o=o+Math.imul(p,Z)|0)+Math.imul(g,Q)|0,i=i+Math.imul(g,Z)|0;var ke=(u+(r=r+Math.imul(h,J)|0)|0)+((8191&(o=(o=o+Math.imul(h,ee)|0)+Math.imul(d,J)|0))<<13)|0;u=((i=i+Math.imul(d,ee)|0)+(o>>>13)|0)+(ke>>>26)|0,ke&=67108863,r=Math.imul(I,q),o=(o=Math.imul(I,K))+Math.imul(B,q)|0,i=Math.imul(B,K),r=r+Math.imul(S,G)|0,o=(o=o+Math.imul(S,W)|0)+Math.imul(T,G)|0,i=i+Math.imul(T,W)|0,r=r+Math.imul(k,H)|0,o=(o=o+Math.imul(k,V)|0)+Math.imul(v,H)|0,i=i+Math.imul(v,V)|0,r=r+Math.imul(y,Q)|0,o=(o=o+Math.imul(y,Z)|0)+Math.imul(w,Q)|0,i=i+Math.imul(w,Z)|0,r=r+Math.imul(p,J)|0,o=(o=o+Math.imul(p,ee)|0)+Math.imul(g,J)|0,i=i+Math.imul(g,ee)|0;var ve=(u+(r=r+Math.imul(h,ne)|0)|0)+((8191&(o=(o=o+Math.imul(h,re)|0)+Math.imul(d,ne)|0))<<13)|0;u=((i=i+Math.imul(d,re)|0)+(o>>>13)|0)+(ve>>>26)|0,ve&=67108863,r=Math.imul(C,q),o=(o=Math.imul(C,K))+Math.imul(P,q)|0,i=Math.imul(P,K),r=r+Math.imul(I,G)|0,o=(o=o+Math.imul(I,W)|0)+Math.imul(B,G)|0,i=i+Math.imul(B,W)|0,r=r+Math.imul(S,H)|0,o=(o=o+Math.imul(S,V)|0)+Math.imul(T,H)|0,i=i+Math.imul(T,V)|0,r=r+Math.imul(k,Q)|0,o=(o=o+Math.imul(k,Z)|0)+Math.imul(v,Q)|0,i=i+Math.imul(v,Z)|0,r=r+Math.imul(y,J)|0,o=(o=o+Math.imul(y,ee)|0)+Math.imul(w,J)|0,i=i+Math.imul(w,ee)|0,r=r+Math.imul(p,ne)|0,o=(o=o+Math.imul(p,re)|0)+Math.imul(g,ne)|0,i=i+Math.imul(g,re)|0;var Ee=(u+(r=r+Math.imul(h,ie)|0)|0)+((8191&(o=(o=o+Math.imul(h,se)|0)+Math.imul(d,ie)|0))<<13)|0;u=((i=i+Math.imul(d,se)|0)+(o>>>13)|0)+(Ee>>>26)|0,Ee&=67108863,r=Math.imul(_,q),o=(o=Math.imul(_,K))+Math.imul(D,q)|0,i=Math.imul(D,K),r=r+Math.imul(C,G)|0,o=(o=o+Math.imul(C,W)|0)+Math.imul(P,G)|0,i=i+Math.imul(P,W)|0,r=r+Math.imul(I,H)|0,o=(o=o+Math.imul(I,V)|0)+Math.imul(B,H)|0,i=i+Math.imul(B,V)|0,r=r+Math.imul(S,Q)|0,o=(o=o+Math.imul(S,Z)|0)+Math.imul(T,Q)|0,i=i+Math.imul(T,Z)|0,r=r+Math.imul(k,J)|0,o=(o=o+Math.imul(k,ee)|0)+Math.imul(v,J)|0,i=i+Math.imul(v,ee)|0,r=r+Math.imul(y,ne)|0,o=(o=o+Math.imul(y,re)|0)+Math.imul(w,ne)|0,i=i+Math.imul(w,re)|0,r=r+Math.imul(p,ie)|0,o=(o=o+Math.imul(p,se)|0)+Math.imul(g,ie)|0,i=i+Math.imul(g,se)|0;var Se=(u+(r=r+Math.imul(h,ce)|0)|0)+((8191&(o=(o=o+Math.imul(h,ue)|0)+Math.imul(d,ce)|0))<<13)|0;u=((i=i+Math.imul(d,ue)|0)+(o>>>13)|0)+(Se>>>26)|0,Se&=67108863,r=Math.imul(R,q),o=(o=Math.imul(R,K))+Math.imul(L,q)|0,i=Math.imul(L,K),r=r+Math.imul(_,G)|0,o=(o=o+Math.imul(_,W)|0)+Math.imul(D,G)|0,i=i+Math.imul(D,W)|0,r=r+Math.imul(C,H)|0,o=(o=o+Math.imul(C,V)|0)+Math.imul(P,H)|0,i=i+Math.imul(P,V)|0,r=r+Math.imul(I,Q)|0,o=(o=o+Math.imul(I,Z)|0)+Math.imul(B,Q)|0,i=i+Math.imul(B,Z)|0,r=r+Math.imul(S,J)|0,o=(o=o+Math.imul(S,ee)|0)+Math.imul(T,J)|0,i=i+Math.imul(T,ee)|0,r=r+Math.imul(k,ne)|0,o=(o=o+Math.imul(k,re)|0)+Math.imul(v,ne)|0,i=i+Math.imul(v,re)|0,r=r+Math.imul(y,ie)|0,o=(o=o+Math.imul(y,se)|0)+Math.imul(w,ie)|0,i=i+Math.imul(w,se)|0,r=r+Math.imul(p,ce)|0,o=(o=o+Math.imul(p,ue)|0)+Math.imul(g,ce)|0,i=i+Math.imul(g,ue)|0;var Te=(u+(r=r+Math.imul(h,he)|0)|0)+((8191&(o=(o=o+Math.imul(h,de)|0)+Math.imul(d,he)|0))<<13)|0;u=((i=i+Math.imul(d,de)|0)+(o>>>13)|0)+(Te>>>26)|0,Te&=67108863,r=Math.imul(F,q),o=(o=Math.imul(F,K))+Math.imul(M,q)|0,i=Math.imul(M,K),r=r+Math.imul(R,G)|0,o=(o=o+Math.imul(R,W)|0)+Math.imul(L,G)|0,i=i+Math.imul(L,W)|0,r=r+Math.imul(_,H)|0,o=(o=o+Math.imul(_,V)|0)+Math.imul(D,H)|0,i=i+Math.imul(D,V)|0,r=r+Math.imul(C,Q)|0,o=(o=o+Math.imul(C,Z)|0)+Math.imul(P,Q)|0,i=i+Math.imul(P,Z)|0,r=r+Math.imul(I,J)|0,o=(o=o+Math.imul(I,ee)|0)+Math.imul(B,J)|0,i=i+Math.imul(B,ee)|0,r=r+Math.imul(S,ne)|0,o=(o=o+Math.imul(S,re)|0)+Math.imul(T,ne)|0,i=i+Math.imul(T,re)|0,r=r+Math.imul(k,ie)|0,o=(o=o+Math.imul(k,se)|0)+Math.imul(v,ie)|0,i=i+Math.imul(v,se)|0,r=r+Math.imul(y,ce)|0,o=(o=o+Math.imul(y,ue)|0)+Math.imul(w,ce)|0,i=i+Math.imul(w,ue)|0,r=r+Math.imul(p,he)|0,o=(o=o+Math.imul(p,de)|0)+Math.imul(g,he)|0,i=i+Math.imul(g,de)|0;var Ae=(u+(r=r+Math.imul(h,pe)|0)|0)+((8191&(o=(o=o+Math.imul(h,ge)|0)+Math.imul(d,pe)|0))<<13)|0;u=((i=i+Math.imul(d,ge)|0)+(o>>>13)|0)+(Ae>>>26)|0,Ae&=67108863,r=Math.imul(F,G),o=(o=Math.imul(F,W))+Math.imul(M,G)|0,i=Math.imul(M,W),r=r+Math.imul(R,H)|0,o=(o=o+Math.imul(R,V)|0)+Math.imul(L,H)|0,i=i+Math.imul(L,V)|0,r=r+Math.imul(_,Q)|0,o=(o=o+Math.imul(_,Z)|0)+Math.imul(D,Q)|0,i=i+Math.imul(D,Z)|0,r=r+Math.imul(C,J)|0,o=(o=o+Math.imul(C,ee)|0)+Math.imul(P,J)|0,i=i+Math.imul(P,ee)|0,r=r+Math.imul(I,ne)|0,o=(o=o+Math.imul(I,re)|0)+Math.imul(B,ne)|0,i=i+Math.imul(B,re)|0,r=r+Math.imul(S,ie)|0,o=(o=o+Math.imul(S,se)|0)+Math.imul(T,ie)|0,i=i+Math.imul(T,se)|0,r=r+Math.imul(k,ce)|0,o=(o=o+Math.imul(k,ue)|0)+Math.imul(v,ce)|0,i=i+Math.imul(v,ue)|0,r=r+Math.imul(y,he)|0,o=(o=o+Math.imul(y,de)|0)+Math.imul(w,he)|0,i=i+Math.imul(w,de)|0;var Ie=(u+(r=r+Math.imul(p,pe)|0)|0)+((8191&(o=(o=o+Math.imul(p,ge)|0)+Math.imul(g,pe)|0))<<13)|0;u=((i=i+Math.imul(g,ge)|0)+(o>>>13)|0)+(Ie>>>26)|0,Ie&=67108863,r=Math.imul(F,H),o=(o=Math.imul(F,V))+Math.imul(M,H)|0,i=Math.imul(M,V),r=r+Math.imul(R,Q)|0,o=(o=o+Math.imul(R,Z)|0)+Math.imul(L,Q)|0,i=i+Math.imul(L,Z)|0,r=r+Math.imul(_,J)|0,o=(o=o+Math.imul(_,ee)|0)+Math.imul(D,J)|0,i=i+Math.imul(D,ee)|0,r=r+Math.imul(C,ne)|0,o=(o=o+Math.imul(C,re)|0)+Math.imul(P,ne)|0,i=i+Math.imul(P,re)|0,r=r+Math.imul(I,ie)|0,o=(o=o+Math.imul(I,se)|0)+Math.imul(B,ie)|0,i=i+Math.imul(B,se)|0,r=r+Math.imul(S,ce)|0,o=(o=o+Math.imul(S,ue)|0)+Math.imul(T,ce)|0,i=i+Math.imul(T,ue)|0,r=r+Math.imul(k,he)|0,o=(o=o+Math.imul(k,de)|0)+Math.imul(v,he)|0,i=i+Math.imul(v,de)|0;var Be=(u+(r=r+Math.imul(y,pe)|0)|0)+((8191&(o=(o=o+Math.imul(y,ge)|0)+Math.imul(w,pe)|0))<<13)|0;u=((i=i+Math.imul(w,ge)|0)+(o>>>13)|0)+(Be>>>26)|0,Be&=67108863,r=Math.imul(F,Q),o=(o=Math.imul(F,Z))+Math.imul(M,Q)|0,i=Math.imul(M,Z),r=r+Math.imul(R,J)|0,o=(o=o+Math.imul(R,ee)|0)+Math.imul(L,J)|0,i=i+Math.imul(L,ee)|0,r=r+Math.imul(_,ne)|0,o=(o=o+Math.imul(_,re)|0)+Math.imul(D,ne)|0,i=i+Math.imul(D,re)|0,r=r+Math.imul(C,ie)|0,o=(o=o+Math.imul(C,se)|0)+Math.imul(P,ie)|0,i=i+Math.imul(P,se)|0,r=r+Math.imul(I,ce)|0,o=(o=o+Math.imul(I,ue)|0)+Math.imul(B,ce)|0,i=i+Math.imul(B,ue)|0,r=r+Math.imul(S,he)|0,o=(o=o+Math.imul(S,de)|0)+Math.imul(T,he)|0,i=i+Math.imul(T,de)|0;var xe=(u+(r=r+Math.imul(k,pe)|0)|0)+((8191&(o=(o=o+Math.imul(k,ge)|0)+Math.imul(v,pe)|0))<<13)|0;u=((i=i+Math.imul(v,ge)|0)+(o>>>13)|0)+(xe>>>26)|0,xe&=67108863,r=Math.imul(F,J),o=(o=Math.imul(F,ee))+Math.imul(M,J)|0,i=Math.imul(M,ee),r=r+Math.imul(R,ne)|0,o=(o=o+Math.imul(R,re)|0)+Math.imul(L,ne)|0,i=i+Math.imul(L,re)|0,r=r+Math.imul(_,ie)|0,o=(o=o+Math.imul(_,se)|0)+Math.imul(D,ie)|0,i=i+Math.imul(D,se)|0,r=r+Math.imul(C,ce)|0,o=(o=o+Math.imul(C,ue)|0)+Math.imul(P,ce)|0,i=i+Math.imul(P,ue)|0,r=r+Math.imul(I,he)|0,o=(o=o+Math.imul(I,de)|0)+Math.imul(B,he)|0,i=i+Math.imul(B,de)|0;var Ce=(u+(r=r+Math.imul(S,pe)|0)|0)+((8191&(o=(o=o+Math.imul(S,ge)|0)+Math.imul(T,pe)|0))<<13)|0;u=((i=i+Math.imul(T,ge)|0)+(o>>>13)|0)+(Ce>>>26)|0,Ce&=67108863,r=Math.imul(F,ne),o=(o=Math.imul(F,re))+Math.imul(M,ne)|0,i=Math.imul(M,re),r=r+Math.imul(R,ie)|0,o=(o=o+Math.imul(R,se)|0)+Math.imul(L,ie)|0,i=i+Math.imul(L,se)|0,r=r+Math.imul(_,ce)|0,o=(o=o+Math.imul(_,ue)|0)+Math.imul(D,ce)|0,i=i+Math.imul(D,ue)|0,r=r+Math.imul(C,he)|0,o=(o=o+Math.imul(C,de)|0)+Math.imul(P,he)|0,i=i+Math.imul(P,de)|0;var Pe=(u+(r=r+Math.imul(I,pe)|0)|0)+((8191&(o=(o=o+Math.imul(I,ge)|0)+Math.imul(B,pe)|0))<<13)|0;u=((i=i+Math.imul(B,ge)|0)+(o>>>13)|0)+(Pe>>>26)|0,Pe&=67108863,r=Math.imul(F,ie),o=(o=Math.imul(F,se))+Math.imul(M,ie)|0,i=Math.imul(M,se),r=r+Math.imul(R,ce)|0,o=(o=o+Math.imul(R,ue)|0)+Math.imul(L,ce)|0,i=i+Math.imul(L,ue)|0,r=r+Math.imul(_,he)|0,o=(o=o+Math.imul(_,de)|0)+Math.imul(D,he)|0,i=i+Math.imul(D,de)|0;var Ne=(u+(r=r+Math.imul(C,pe)|0)|0)+((8191&(o=(o=o+Math.imul(C,ge)|0)+Math.imul(P,pe)|0))<<13)|0;u=((i=i+Math.imul(P,ge)|0)+(o>>>13)|0)+(Ne>>>26)|0,Ne&=67108863,r=Math.imul(F,ce),o=(o=Math.imul(F,ue))+Math.imul(M,ce)|0,i=Math.imul(M,ue),r=r+Math.imul(R,he)|0,o=(o=o+Math.imul(R,de)|0)+Math.imul(L,he)|0,i=i+Math.imul(L,de)|0;var _e=(u+(r=r+Math.imul(_,pe)|0)|0)+((8191&(o=(o=o+Math.imul(_,ge)|0)+Math.imul(D,pe)|0))<<13)|0;u=((i=i+Math.imul(D,ge)|0)+(o>>>13)|0)+(_e>>>26)|0,_e&=67108863,r=Math.imul(F,he),o=(o=Math.imul(F,de))+Math.imul(M,he)|0,i=Math.imul(M,de);var De=(u+(r=r+Math.imul(R,pe)|0)|0)+((8191&(o=(o=o+Math.imul(R,ge)|0)+Math.imul(L,pe)|0))<<13)|0;u=((i=i+Math.imul(L,ge)|0)+(o>>>13)|0)+(De>>>26)|0,De&=67108863;var Ue=(u+(r=Math.imul(F,pe))|0)+((8191&(o=(o=Math.imul(F,ge))+Math.imul(M,pe)|0))<<13)|0;return u=((i=Math.imul(M,ge))+(o>>>13)|0)+(Ue>>>26)|0,Ue&=67108863,c[0]=me,c[1]=ye,c[2]=we,c[3]=be,c[4]=ke,c[5]=ve,c[6]=Ee,c[7]=Se,c[8]=Te,c[9]=Ae,c[10]=Ie,c[11]=Be,c[12]=xe,c[13]=Ce,c[14]=Pe,c[15]=Ne,c[16]=_e,c[17]=De,c[18]=Ue,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,o=0,i=0;i<n.length-1;i++){var s=o;o=0;for(var a=67108863&r,c=Math.min(i,t.length-1),u=Math.max(0,i-e.length+1);u<=c;u++){var l=i-u,h=(0|e.words[l])*(0|t.words[u]),d=67108863&h;a=67108863&(d=d+a|0),o+=(s=(s=s+(h/67108864|0)|0)+(d>>>26)|0)>>>26,s&=67108863}n.words[i]=a,r=s,s=o}return 0!==r?n.words[i]=r:n.length--,n._strip()}function y(e,t,n){return m(e,t,n)}Math.imul||(g=p),o.prototype.mulTo=function(e,t){var n=this.length+e.length;return 10===this.length&&10===e.length?g(this,e,t):n<63?p(this,e,t):n<1024?m(this,e,t):y(this,e,t)},o.prototype.mul=function(e){var t=new o(null);return t.words=new Array(this.length+e.length),this.mulTo(e,t)},o.prototype.mulf=function(e){var t=new o(null);return t.words=new Array(this.length+e.length),y(this,e,t)},o.prototype.imul=function(e){return this.clone().mulTo(e,this)},o.prototype.imuln=function(e){var t=e<0;t&&(e=-e),n("number"==typeof e),n(e<67108864);for(var r=0,o=0;o<this.length;o++){var i=(0|this.words[o])*e,s=(67108863&i)+(67108863&r);r>>=26,r+=i/67108864|0,r+=s>>>26,this.words[o]=67108863&s}return 0!==r&&(this.words[o]=r,this.length++),t?this.ineg():this},o.prototype.muln=function(e){return this.clone().imuln(e)},o.prototype.sqr=function(){return this.mul(this)},o.prototype.isqr=function(){return this.imul(this.clone())},o.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,o=n%26;t[n]=e.words[r]>>>o&1}return t}(e);if(0===t.length)return new o(1);for(var n=this,r=0;r<t.length&&0===t[r];r++,n=n.sqr());if(++r<t.length)for(var i=n.sqr();r<t.length;r++,i=i.sqr())0!==t[r]&&(n=n.mul(i));return n},o.prototype.iushln=function(e){n("number"==typeof e&&e>=0);var t,r=e%26,o=(e-r)/26,i=67108863>>>26-r<<26-r;if(0!==r){var s=0;for(t=0;t<this.length;t++){var a=this.words[t]&i,c=(0|this.words[t])-a<<r;this.words[t]=c|s,s=a>>>26-r}s&&(this.words[t]=s,this.length++)}if(0!==o){for(t=this.length-1;t>=0;t--)this.words[t+o]=this.words[t];for(t=0;t<o;t++)this.words[t]=0;this.length+=o}return this._strip()},o.prototype.ishln=function(e){return n(0===this.negative),this.iushln(e)},o.prototype.iushrn=function(e,t,r){var o;n("number"==typeof e&&e>=0),o=t?(t-t%26)/26:0;var i=e%26,s=Math.min((e-i)/26,this.length),a=67108863^67108863>>>i<<i,c=r;if(o-=s,o=Math.max(0,o),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>=o);u--){var h=0|this.words[u];this.words[u]=l<<26-i|h>>>i,l=h&a}return c&&0!==l&&(c.words[c.length++]=l),0===this.length&&(this.words[0]=0,this.length=1),this._strip()},o.prototype.ishrn=function(e,t,r){return n(0===this.negative),this.iushrn(e,t,r)},o.prototype.shln=function(e){return this.clone().ishln(e)},o.prototype.ushln=function(e){return this.clone().iushln(e)},o.prototype.shrn=function(e){return this.clone().ishrn(e)},o.prototype.ushrn=function(e){return this.clone().iushrn(e)},o.prototype.testn=function(e){n("number"==typeof e&&e>=0);var t=e%26,r=(e-t)/26,o=1<<t;return!(this.length<=r)&&!!(this.words[r]&o)},o.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 o=67108863^67108863>>>t<<t;this.words[this.length-1]&=o}return this._strip()},o.prototype.maskn=function(e){return this.clone().imaskn(e)},o.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)},o.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},o.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()},o.prototype.addn=function(e){return this.clone().iaddn(e)},o.prototype.subn=function(e){return this.clone().isubn(e)},o.prototype.iabs=function(){return this.negative=0,this},o.prototype.abs=function(){return this.clone().iabs()},o.prototype._ishlnsubmul=function(e,t,r){var o,i,s=e.length+r;this._expand(s);var a=0;for(o=0;o<e.length;o++){i=(0|this.words[o+r])+a;var c=(0|e.words[o])*t;a=((i-=67108863&c)>>26)-(c/67108864|0),this.words[o+r]=67108863&i}for(;o<this.length-r;o++)a=(i=(0|this.words[o+r])+a)>>26,this.words[o+r]=67108863&i;if(0===a)return this._strip();for(n(-1===a),a=0,o=0;o<this.length;o++)a=(i=-(0|this.words[o])+a)>>26,this.words[o]=67108863&i;return this.negative=1,this._strip()},o.prototype._wordDiv=function(e,t){var n=(this.length,e.length),r=this.clone(),i=e,s=0|i.words[i.length-1];0!==(n=26-this._countBits(s))&&(i=i.ushln(n),r.iushln(n),s=0|i.words[i.length-1]);var a,c=r.length-i.length;if("mod"!==t){(a=new o(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(i,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[i.length+h])+(0|r.words[i.length+h-1]);for(d=Math.min(d/s|0,67108863),r._ishlnsubmul(i,d,h);0!==r.negative;)d--,r.negative=0,r._ishlnsubmul(i,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}},o.prototype.divmod=function(e,t,r){return n(!e.isZero()),this.isZero()?{div:new o(0),mod:new o(0)}:0!==this.negative&&0===e.negative?(a=this.neg().divmod(e,t),"mod"!==t&&(i=a.div.neg()),"div"!==t&&(s=a.mod.neg(),r&&0!==s.negative&&s.iadd(e)),{div:i,mod:s}):0===this.negative&&0!==e.negative?(a=this.divmod(e.neg(),t),"mod"!==t&&(i=a.div.neg()),{div:i,mod:a.mod}):0!==(this.negative&e.negative)?(a=this.neg().divmod(e.neg(),t),"div"!==t&&(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 o(0),mod:this}:1===e.length?"div"===t?{div:this.divn(e.words[0]),mod:null}:"mod"===t?{div:null,mod:new o(this.modrn(e.words[0]))}:{div:this.divn(e.words[0]),mod:new o(this.modrn(e.words[0]))}:this._wordDiv(e,t);var i,s,a},o.prototype.div=function(e){return this.divmod(e,"div",!1).div},o.prototype.mod=function(e){return this.divmod(e,"mod",!1).mod},o.prototype.umod=function(e){return this.divmod(e,"mod",!0).mod},o.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),o=e.andln(1),i=n.cmp(r);return i<0||1===o&&0===i?t.div:0!==t.div.negative?t.div.isubn(1):t.div.iaddn(1)},o.prototype.modrn=function(e){var t=e<0;t&&(e=-e),n(e<=67108863);for(var r=(1<<26)%e,o=0,i=this.length-1;i>=0;i--)o=(r*o+(0|this.words[i]))%e;return t?-o:o},o.prototype.modn=function(e){return this.modrn(e)},o.prototype.idivn=function(e){var t=e<0;t&&(e=-e),n(e<=67108863);for(var r=0,o=this.length-1;o>=0;o--){var i=(0|this.words[o])+67108864*r;this.words[o]=i/e|0,r=i%e}return this._strip(),t?this.ineg():this},o.prototype.divn=function(e){return this.clone().idivn(e)},o.prototype.egcd=function(e){n(0===e.negative),n(!e.isZero());var t=this,r=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var i=new o(1),s=new o(0),a=new o(0),c=new o(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;)(i.isOdd()||s.isOdd())&&(i.iadd(l),s.isub(h)),i.iushrn(1),s.iushrn(1);for(var p=0,g=1;0===(r.words[0]&g)&&p<26;++p,g<<=1);if(p>0)for(r.iushrn(p);p-- >0;)(a.isOdd()||c.isOdd())&&(a.iadd(l),c.isub(h)),a.iushrn(1),c.iushrn(1);t.cmp(r)>=0?(t.isub(r),i.isub(a),s.isub(c)):(r.isub(t),a.isub(i),c.isub(s))}return{a:a,b:c,gcd:r.iushln(u)}},o.prototype._invmp=function(e){n(0===e.negative),n(!e.isZero());var t=this,r=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var i,s=new o(1),a=new o(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(i=0===t.cmpn(1)?s:a).cmpn(0)<0&&i.iadd(e),i},o.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 o=t.cmp(n);if(o<0){var i=t;t=n,n=i}else if(0===o||0===n.cmpn(1))break;t.isub(n)}return n.iushln(r)},o.prototype.invm=function(e){return this.egcd(e).a.umod(e)},o.prototype.isEven=function(){return!(1&this.words[0])},o.prototype.isOdd=function(){return!(1&~this.words[0])},o.prototype.andln=function(e){return this.words[0]&e},o.prototype.bincn=function(e){n("number"==typeof e);var t=e%26,r=(e-t)/26,o=1<<t;if(this.length<=r)return this._expand(r+1),this.words[r]|=o,this;for(var i=o,s=r;0!==i&&s<this.length;s++){var a=0|this.words[s];i=(a+=i)>>>26,a&=67108863,this.words[s]=a}return 0!==i&&(this.words[s]=i,this.length++),this},o.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},o.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 o=0|this.words[0];t=o===e?0:o<e?-1:1}return 0!==this.negative?0|-t:t},o.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},o.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],o=0|e.words[n];if(r!==o){r<o?t=-1:r>o&&(t=1);break}}return t},o.prototype.gtn=function(e){return 1===this.cmpn(e)},o.prototype.gt=function(e){return 1===this.cmp(e)},o.prototype.gten=function(e){return this.cmpn(e)>=0},o.prototype.gte=function(e){return this.cmp(e)>=0},o.prototype.ltn=function(e){return-1===this.cmpn(e)},o.prototype.lt=function(e){return-1===this.cmp(e)},o.prototype.lten=function(e){return this.cmpn(e)<=0},o.prototype.lte=function(e){return this.cmp(e)<=0},o.prototype.eqn=function(e){return 0===this.cmpn(e)},o.prototype.eq=function(e){return 0===this.cmp(e)},o.red=function(e){return new T(e)},o.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)},o.prototype.fromRed=function(){return n(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},o.prototype._forceRed=function(e){return this.red=e,this},o.prototype.forceRed=function(e){return n(!this.red,"Already a number in reduction context"),this._forceRed(e)},o.prototype.redAdd=function(e){return n(this.red,"redAdd works only with red numbers"),this.red.add(this,e)},o.prototype.redIAdd=function(e){return n(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,e)},o.prototype.redSub=function(e){return n(this.red,"redSub works only with red numbers"),this.red.sub(this,e)},o.prototype.redISub=function(e){return n(this.red,"redISub works only with red numbers"),this.red.isub(this,e)},o.prototype.redShl=function(e){return n(this.red,"redShl works only with red numbers"),this.red.shl(this,e)},o.prototype.redMul=function(e){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.mul(this,e)},o.prototype.redIMul=function(e){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.imul(this,e)},o.prototype.redSqr=function(){return n(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},o.prototype.redISqr=function(){return n(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},o.prototype.redSqrt=function(){return n(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},o.prototype.redInvm=function(){return n(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},o.prototype.redNeg=function(){return n(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},o.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 o(t,16),this.n=this.p.bitLength(),this.k=new o(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 E(){b.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function S(){b.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function T(e){if("string"==typeof e){var t=o._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 A(e){T.call(this,e),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new o(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 o(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),o=0;o<r;o++)t.words[o]=e.words[o];if(t.length=r,e.length<=9)return e.words[0]=0,void(e.length=1);var i=e.words[9];for(t.words[t.length++]=i&n,o=10;o<e.length;o++){var s=0|e.words[o];e.words[o-10]=(s&n)<<4|i>>>22,i=s}i>>>=22,e.words[o-10]=i,0===i&&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(E,b),r(S,b),S.prototype.imulK=function(e){for(var t=0,n=0;n<e.length;n++){var r=19*(0|e.words[n])+t,o=67108863&r;r>>>=26,e.words[n]=o,t=r}return 0!==t&&(e.words[e.length++]=t),e},o._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 E;else{if("p25519"!==e)throw new Error("Unknown prime "+e);t=new S}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 o(1)).iushrn(2);return this.pow(e,r)}for(var i=this.m.subn(1),s=0;!i.isZero()&&0===i.andln(1);)s++,i.iushrn(1);n(!i.isZero());var a=new o(1).toRed(this),c=a.redNeg(),u=this.m.subn(1).iushrn(1),l=this.m.bitLength();for(l=new o(2*l*l).toRed(this);0!==this.pow(l,u).cmp(c);)l.redIAdd(c);for(var h=this.pow(l,i),d=this.pow(e,i.addn(1).iushrn(1)),f=this.pow(e,i),p=s;0!==f.cmp(a);){for(var g=f,m=0;0!==g.cmp(a);m++)g=g.redSqr();n(m<p);var y=this.pow(h,new o(1).iushln(p-m-1));d=d.redMul(y),h=y.redSqr(),f=f.redMul(h),p=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 o(1).toRed(this);if(0===t.cmpn(1))return e.clone();var n=new Array(16);n[0]=new o(1).toRed(this),n[1]=e;for(var r=2;r<n.length;r++)n[r]=this.mul(n[r-1],e);var i=n[0],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;i!==n[0]&&(i=this.sqr(i)),0!==h||0!==s?(s<<=1,s|=h,(4===++a||0===r&&0===l)&&(i=this.mul(i,n[s]),a=0,s=0)):a=0}c=26}return i},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},o.mont=function(e){return new A(e)},r(A,T),A.prototype.convertTo=function(e){return this.imod(e.ushln(this.shift))},A.prototype.convertFrom=function(e){var t=this.imod(e.mul(this.rinv));return t.red=null,t},A.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),o=n.isub(r).iushrn(this.shift),i=o;return o.cmp(this.m)>=0?i=o.isub(this.m):o.cmpn(0)<0&&(i=o.iadd(this.m)),i._forceRed(this)},A.prototype.mul=function(e,t){if(e.isZero()||t.isZero())return new o(0)._forceRed(this);var n=e.mul(t),r=n.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=n.isub(r).iushrn(this.shift),s=i;return i.cmp(this.m)>=0?s=i.isub(this.m):i.cmpn(0)<0&&(s=i.iadd(this.m)),s._forceRed(this)},A.prototype.invm=function(e){return this.imod(e._invmp(this.m).mul(this.r2))._forceRed(this)}}(e,Dc)}(Nc)),Nc.exports}var Rc,Lc,Oc,Fc,Mc,$c,qc=Oo(Uc()),Kc={exports:{}},zc={};function Gc(){return Rc||(Rc=1,function(e){var t=Ji(),n=rs(),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 o=2147483647;function i(e){if(e>o)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=i(n),o=r.write(e,t);o!==n&&(r=r.slice(0,o));return r}(e,t);if(ArrayBuffer.isView(e))return function(e){if(M(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(M(e,ArrayBuffer)||e&&M(e.buffer,ArrayBuffer))return h(e,t,n);if("undefined"!=typeof SharedArrayBuffer&&(M(e,SharedArrayBuffer)||e&&M(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 o=function(e){if(s.isBuffer(e)){var t=0|d(e.length),n=i(t);return 0===n.length||e.copy(n,0,0,t),n}if(void 0!==e.length)return"number"!=typeof e.length||$(e.length)?i(0):l(e);if("Buffer"===e.type&&Array.isArray(e.data))return l(e.data)}(e);if(o)return o;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),i(e<0?0:0|d(e))}function l(e){for(var t=e.length<0?0:0|d(e.length),n=i(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>=o)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+o.toString(16)+" bytes");return 0|e}function f(e,t){if(s.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||M(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 o=!1;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":return L(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return O(e).length;default:if(o)return r?-1:L(e).length;t=(""+t).toLowerCase(),o=!0}}function p(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 x(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 B(this,t,n);case"base64":return S(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return C(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function g(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function m(e,t,n,r,o){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=o?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(o)return-1;n=e.length-1}else if(n<0){if(!o)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,o);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?o?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):y(e,[t],n,r,o);throw new TypeError("val must be string, number or Buffer")}function y(e,t,n,r,o){var i,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(o){var l=-1;for(i=n;i<a;i++)if(u(e,i)===u(t,-1===l?0:i-l)){if(-1===l&&(l=i),i-l+1===c)return l*s}else-1!==l&&(i-=i-l),l=-1}else for(n+c>a&&(n=a-c),i=n;i>=0;i--){for(var h=!0,d=0;d<c;d++)if(u(e,i+d)!==u(t,d)){h=!1;break}if(h)return i}return-1}function w(e,t,n,r){n=Number(n)||0;var o=e.length-n;r?(r=Number(r))>o&&(r=o):r=o;var i=t.length;r>i/2&&(r=i/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 F(L(t,e.length-n),e,n,r)}function k(e,t,n,r){return F(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 F(O(t),e,n,r)}function E(e,t,n,r){return F(function(e,t){for(var n,r,o,i=[],s=0;s<e.length&&!((t-=2)<0);++s)r=(n=e.charCodeAt(s))>>8,o=n%256,i.push(o),i.push(r);return i}(t,e.length-n),e,n,r)}function S(e,n,r){return 0===n&&r===e.length?t.fromByteArray(e):t.fromByteArray(e.slice(n,r))}function T(e,t,n){n=Math.min(e.length,n);for(var r=[],o=t;o<n;){var i,s,a,c,u=e[o],l=null,h=u>239?4:u>223?3:u>191?2:1;if(o+h<=n)switch(h){case 1:u<128&&(l=u);break;case 2:128==(192&(i=e[o+1]))&&(c=(31&u)<<6|63&i)>127&&(l=c);break;case 3:i=e[o+1],s=e[o+2],128==(192&i)&&128==(192&s)&&(c=(15&u)<<12|(63&i)<<6|63&s)>2047&&(c<55296||c>57343)&&(l=c);break;case 4:i=e[o+1],s=e[o+2],a=e[o+3],128==(192&i)&&128==(192&s)&&128==(192&a)&&(c=(15&u)<<18|(63&i)<<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),o+=h}return function(e){var t=e.length;if(t<=A)return String.fromCharCode.apply(String,e);var n="",r=0;for(;r<t;)n+=String.fromCharCode.apply(String,e.slice(r,r+=A));return n}(r)}e.kMaxLength=o,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?i(e):void 0!==t?"string"==typeof n?i(e).fill(t,n):i(e).fill(t):i(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(M(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),M(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,o=0,i=Math.min(n,r);o<i;++o)if(e[o]!==t[o]){n=e[o],r=t[o];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),o=0;for(n=0;n<e.length;++n){var i=e[n];if(M(i,Uint8Array))o+i.length>r.length?s.from(i).copy(r,o):Uint8Array.prototype.set.call(r,i,o);else{if(!s.isBuffer(i))throw new TypeError('"list" argument must be an Array of Buffers');i.copy(r,o)}o+=i.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)g(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)g(this,t,t+3),g(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)g(this,t,t+7),g(this,t+1,t+6),g(this,t+2,t+5),g(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):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(){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,o){if(M(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===o&&(o=this.length),t<0||n>e.length||r<0||o>this.length)throw new RangeError("out of range index");if(r>=o&&t>=n)return 0;if(r>=o)return-1;if(t>=n)return 1;if(this===e)return 0;for(var i=(o>>>=0)-(r>>>=0),a=(n>>>=0)-(t>>>=0),c=Math.min(i,a),u=this.slice(r,o),l=e.slice(t,n),h=0;h<c;++h)if(u[h]!==l[h]){i=u[h],a=l[h];break}return i<a?-1:a<i?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 o=this.length-t;if((void 0===n||n>o)&&(n=o),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");for(var i=!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 E(this,e,t,n);default:if(i)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),i=!0}},s.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var A=4096;function I(e,t,n){var r="";n=Math.min(e.length,n);for(var o=t;o<n;++o)r+=String.fromCharCode(127&e[o]);return r}function B(e,t,n){var r="";n=Math.min(e.length,n);for(var o=t;o<n;++o)r+=String.fromCharCode(e[o]);return r}function x(e,t,n){var r=e.length;(!t||t<0)&&(t=0),(!n||n<0||n>r)&&(n=r);for(var o="",i=t;i<n;++i)o+=q[e[i]];return o}function C(e,t,n){for(var r=e.slice(t,n),o="",i=0;i<r.length-1;i+=2)o+=String.fromCharCode(r[i]+256*r[i+1]);return o}function P(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 N(e,t,n,r,o,i){if(!s.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>o||t<i)throw new RangeError('"value" argument is out of bounds');if(n+r>e.length)throw new RangeError("Index out of range")}function _(e,t,n,r,o,i){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function D(e,t,r,o,i){return t=+t,r>>>=0,i||_(e,0,r,4),n.write(e,t,r,o,23,4),r+4}function U(e,t,r,o,i){return t=+t,r>>>=0,i||_(e,0,r,8),n.write(e,t,r,o,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||P(e,t,this.length);for(var r=this[e],o=1,i=0;++i<t&&(o*=256);)r+=this[e+i]*o;return r},s.prototype.readUintBE=s.prototype.readUIntBE=function(e,t,n){e>>>=0,t>>>=0,n||P(e,t,this.length);for(var r=this[e+--t],o=1;t>0&&(o*=256);)r+=this[e+--t]*o;return r},s.prototype.readUint8=s.prototype.readUInt8=function(e,t){return e>>>=0,t||P(e,1,this.length),this[e]},s.prototype.readUint16LE=s.prototype.readUInt16LE=function(e,t){return e>>>=0,t||P(e,2,this.length),this[e]|this[e+1]<<8},s.prototype.readUint16BE=s.prototype.readUInt16BE=function(e,t){return e>>>=0,t||P(e,2,this.length),this[e]<<8|this[e+1]},s.prototype.readUint32LE=s.prototype.readUInt32LE=function(e,t){return e>>>=0,t||P(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||P(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||P(e,t,this.length);for(var r=this[e],o=1,i=0;++i<t&&(o*=256);)r+=this[e+i]*o;return r>=(o*=128)&&(r-=Math.pow(2,8*t)),r},s.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||P(e,t,this.length);for(var r=t,o=1,i=this[e+--r];r>0&&(o*=256);)i+=this[e+--r]*o;return i>=(o*=128)&&(i-=Math.pow(2,8*t)),i},s.prototype.readInt8=function(e,t){return e>>>=0,t||P(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},s.prototype.readInt16LE=function(e,t){e>>>=0,t||P(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||P(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||P(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||P(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||P(e,4,this.length),n.read(this,e,!0,23,4)},s.prototype.readFloatBE=function(e,t){return e>>>=0,t||P(e,4,this.length),n.read(this,e,!1,23,4)},s.prototype.readDoubleLE=function(e,t){return e>>>=0,t||P(e,8,this.length),n.read(this,e,!0,52,8)},s.prototype.readDoubleBE=function(e,t){return e>>>=0,t||P(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)||N(this,e,t,n,Math.pow(2,8*n)-1,0);var o=1,i=0;for(this[t]=255&e;++i<n&&(o*=256);)this[t+i]=e/o&255;return t+n},s.prototype.writeUintBE=s.prototype.writeUIntBE=function(e,t,n,r){(e=+e,t>>>=0,n>>>=0,r)||N(this,e,t,n,Math.pow(2,8*n)-1,0);var o=n-1,i=1;for(this[t+o]=255&e;--o>=0&&(i*=256);)this[t+o]=e/i&255;return t+n},s.prototype.writeUint8=s.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||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||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||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||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||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 o=Math.pow(2,8*n-1);N(this,e,t,n,o-1,-o)}var i=0,s=1,a=0;for(this[t]=255&e;++i<n&&(s*=256);)e<0&&0===a&&0!==this[t+i-1]&&(a=1),this[t+i]=(e/s|0)-a&255;return t+n},s.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t>>>=0,!r){var o=Math.pow(2,8*n-1);N(this,e,t,n,o-1,-o)}var i=n-1,s=1,a=0;for(this[t+i]=255&e;--i>=0&&(s*=256);)e<0&&0===a&&0!==this[t+i+1]&&(a=1),this[t+i]=(e/s|0)-a&255;return t+n},s.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||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||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||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||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||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 D(this,e,t,!0,n)},s.prototype.writeFloatBE=function(e,t,n){return D(this,e,t,!1,n)},s.prototype.writeDoubleLE=function(e,t,n){return U(this,e,t,!0,n)},s.prototype.writeDoubleBE=function(e,t,n){return U(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 o=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),o},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 o=e.charCodeAt(0);("utf8"===r&&o<128||"latin1"===r)&&(e=o)}}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 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{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(i=0;i<n-t;++i)this[i+t]=a[i%c]}return this};var R=/[^+/0-9A-Za-z-_]/g;function L(e,t){var n;t=t||1/0;for(var r=e.length,o=null,i=[],s=0;s<r;++s){if((n=e.charCodeAt(s))>55295&&n<57344){if(!o){if(n>56319){(t-=3)>-1&&i.push(239,191,189);continue}if(s+1===r){(t-=3)>-1&&i.push(239,191,189);continue}o=n;continue}if(n<56320){(t-=3)>-1&&i.push(239,191,189),o=n;continue}n=65536+(o-55296<<10|n-56320)}else o&&(t-=3)>-1&&i.push(239,191,189);if(o=null,n<128){if((t-=1)<0)break;i.push(n)}else if(n<2048){if((t-=2)<0)break;i.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;i.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;i.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return i}function O(e){return t.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(R,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function F(e,t,n,r){for(var o=0;o<r&&!(o+n>=t.length||o>=e.length);++o)t[o+n]=e[o];return o}function M(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,o=0;o<16;++o)t[r+o]=e[n]+e[o];return t}()}(zc)),zc}function Wc(){return Lc||(Lc=1,function(e,t){var n=Gc(),r=n.Buffer;function o(e,t){for(var n in e)t[n]=e[n]}function i(e,t,n){return r(e,t,n)}r.from&&r.alloc&&r.allocUnsafe&&r.allocUnsafeSlow?e.exports=n:(o(n,t),t.Buffer=i),o(r,i),i.from=function(e,t,n){if("number"==typeof e)throw new TypeError("Argument must not be a number");return r(e,t,n)},i.alloc=function(e,t,n){if("number"!=typeof e)throw new TypeError("Argument must be a number");var o=r(e);return void 0!==t?"string"==typeof n?o.fill(t,n):o.fill(t):o.fill(0),o},i.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return r(e)},i.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return n.SlowBuffer(e)}}(Kc,Kc.exports)),Kc.exports}var jc=function(){if($c)return Mc;$c=1;var e=function(){if(Fc)return Oc;Fc=1;var e=Wc().Buffer;return Oc=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 o=0;o<t.length;o++){var i=t.charAt(o),s=i.charCodeAt(0);if(255!==n[s])throw new TypeError(i+" is ambiguous");n[s]=o}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,o=0,i=0;t[r]===c;)o++,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,p=s-1;(0!==d||f<i)&&-1!==p;p--,f++)d+=a*l[p]>>>0,l[p]=d%256>>>0,d=d/256>>>0;if(0!==d)throw new Error("Non-zero carry");i=f,r++}for(var g=s-i;g!==s&&0===l[g];)g++;var m=e.allocUnsafe(o+(s-g));m.fill(0,0,o);for(var y=o;g!==s;)m[y++]=l[g++];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,o=0,i=0,s=n.length;i!==s&&0===n[i];)i++,r++;for(var u=(s-i)*l+1>>>0,h=new Uint8Array(u);i!==s;){for(var d=n[i],f=0,p=u-1;(0!==d||f<o)&&-1!==p;p--,f++)d+=256*h[p]>>>0,h[p]=d%a>>>0,d=d/a>>>0;if(0!==d)throw new Error("Non-zero carry");o=f,i++}for(var g=u-o;g!==u&&0===h[g];)g++;for(var m=c.repeat(r);g<u;++g)m+=t.charAt(h[g]);return m},decodeUnsafe:h,decode:function(e){var t=h(e);if(t)return t;throw new Error("Non-base"+a+" character")}}},Oc}();return Mc=e("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")}(),Hc=Oo(jc);const Vc=sa;var Xc,Qc,Zc,Yc,Jc={};function eu(){if(Yc)return Zc;Yc=1;var e=function(){if(Qc)return Xc;Qc=1;var e=Wc().Buffer;return Xc=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 o=0;o<t.length;o++){var i=t.charAt(o),s=i.charCodeAt(0);if(255!==n[s])throw new TypeError(i+" is ambiguous");n[s]=o}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,o=0,i=0;t[r]===c;)o++,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,p=s-1;(0!==d||f<i)&&-1!==p;p--,f++)d+=a*l[p]>>>0,l[p]=d%256>>>0,d=d/256>>>0;if(0!==d)throw new Error("Non-zero carry");i=f,r++}for(var g=s-i;g!==s&&0===l[g];)g++;var m=e.allocUnsafe(o+(s-g));m.fill(0,0,o);for(var y=o;g!==s;)m[y++]=l[g++];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,o=0,i=0,s=n.length;i!==s&&0===n[i];)i++,r++;for(var u=(s-i)*l+1>>>0,h=new Uint8Array(u);i!==s;){for(var d=n[i],f=0,p=u-1;(0!==d||f<o)&&-1!==p;p--,f++)d+=256*h[p]>>>0,h[p]=d%a>>>0,d=d/a>>>0;if(0!==d)throw new Error("Non-zero carry");o=f,i++}for(var g=u-o;g!==u&&0===h[g];)g++;for(var m=c.repeat(r);g<u;++g)m+=t.charAt(h[g]);return m},decodeUnsafe:h,decode:function(e){var t=h(e);if(t)return t;throw new Error("Non-base"+a+" character")}}},Xc}();return Zc=e("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")}function tu(e,t,n){return t<=e&&e<=n}function nu(e){if(void 0===e)return{};if(e===Object(e))return e;throw TypeError("Could not convert argument to dictionary")}function ru(e){this.tokens=[].slice.call(e)}ru.prototype={endOfStream:function(){return!this.tokens.length},read:function(){return this.tokens.length?this.tokens.shift():-1},prepend:function(e){if(Array.isArray(e))for(var t=e;t.length;)this.tokens.unshift(t.pop());else this.tokens.unshift(e)},push:function(e){if(Array.isArray(e))for(var t=e;t.length;)this.tokens.push(t.shift());else this.tokens.push(e)}};var ou=-1;function iu(e,t){if(e)throw TypeError("Decoder error");return t||65533}var su="utf-8";function au(e,t){if(!(this instanceof au))return new au(e,t);if((e=void 0!==e?String(e).toLowerCase():su)!==su)throw new Error("Encoding not supported. Only utf-8 is supported");t=nu(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 cu(e,t){if(!(this instanceof cu))return new cu(e,t);if((e=void 0!==e?String(e).toLowerCase():su)!==su)throw new Error("Encoding not supported. Only utf-8 is supported");t=nu(t),this._streaming=!1,this._encoder=null,this._options={fatal:Boolean(t.fatal)},Object.defineProperty(this,"encoding",{value:"utf-8"})}function uu(e){var t=e.fatal,n=0,r=0,o=0,i=128,s=191;this.handler=function(e,a){if(-1===a&&0!==o)return o=0,iu(t);if(-1===a)return ou;if(0===o){if(tu(a,0,127))return a;if(tu(a,194,223))o=1,n=a-192;else if(tu(a,224,239))224===a&&(i=160),237===a&&(s=159),o=2,n=a-224;else{if(!tu(a,240,244))return iu(t);240===a&&(i=144),244===a&&(s=143),o=3,n=a-240}return n<<=6*o,null}if(!tu(a,i,s))return n=o=r=0,i=128,s=191,e.prepend(a),iu(t);if(i=128,s=191,n+=a-128<<6*(o-(r+=1)),r!==o)return null;var c=n;return n=o=r=0,c}}function lu(e){e.fatal,this.handler=function(e,t){if(-1===t)return ou;if(tu(t,0,127))return t;var n,r;tu(t,128,2047)?(n=1,r=192):tu(t,2048,65535)?(n=2,r=224):tu(t,65536,1114111)&&(n=3,r=240);for(var o=[(t>>6*n)+r];n>0;){var i=t>>6*(n-1);o.push(128|63&i),n-=1}return o}}au.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=nu(t),this._streaming||(this._decoder=new uu({fatal:this._fatal}),this._BOMseen=!1),this._streaming=Boolean(t.stream);for(var r,o=new ru(n),i=[];!o.endOfStream()&&(r=this._decoder.handler(o,o.read()))!==ou;)null!==r&&(Array.isArray(r)?i.push.apply(i,r):i.push(r));if(!this._streaming){do{if((r=this._decoder.handler(o,o.read()))===ou)break;null!==r&&(Array.isArray(r)?i.push.apply(i,r):i.push(r))}while(!o.endOfStream());this._decoder=null}return i.length&&(-1===["utf-8"].indexOf(this.encoding)||this._ignoreBOM||this._BOMseen||(65279===i[0]?(this._BOMseen=!0,i.shift()):this._BOMseen=!0)),function(e){for(var t="",n=0;n<e.length;++n){var r=e[n];r<=65535?t+=String.fromCharCode(r):(r-=65536,t+=String.fromCharCode(55296+(r>>10),56320+(1023&r)))}return t}(i)}},cu.prototype={encode:function(e,t){e=e?String(e):"",t=nu(t),this._streaming||(this._encoder=new lu(this._options)),this._streaming=Boolean(t.stream);for(var n,r=[],o=new ru(function(e){for(var t=String(e),n=t.length,r=0,o=[];r<n;){var i=t.charCodeAt(r);if(i<55296||i>57343)o.push(i);else if(56320<=i&&i<=57343)o.push(65533);else if(55296<=i&&i<=56319)if(r===n-1)o.push(65533);else{var s=e.charCodeAt(r+1);if(56320<=s&&s<=57343){var a=1023&i,c=1023&s;o.push(65536+(a<<10)+c),r+=1}else o.push(65533)}r+=1}return o}(e));!o.endOfStream()&&(n=this._encoder.handler(o,o.read()))!==ou;)Array.isArray(n)?r.push.apply(r,n):r.push(n);if(!this._streaming){for(;(n=this._encoder.handler(o,o.read()))!==ou;)Array.isArray(n)?r.push.apply(r,n):r.push(n);this._encoder=null}return new Uint8Array(r)}};var hu,du=Fo(Object.freeze({__proto__:null,TextDecoder:au,TextEncoder:cu}));var fu,pu,gu=function(){if(hu)return Jc;hu=1;var e=Jc&&Jc.__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=Jc&&Jc.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=Jc&&Jc.__decorate||function(e,t,n,r){var o,i=arguments.length,s=i<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--)(o=e[a])&&(s=(i<3?o(s):i>3?o(t,n,s):o(t,n))||s);return i>3&&s&&Object.defineProperty(t,n,s),s},r=Jc&&Jc.__importStar||function(n){if(n&&n.__esModule)return n;var r={};if(null!=n)for(var o in n)"default"!==o&&Object.hasOwnProperty.call(n,o)&&e(r,n,o);return t(r,n),r},o=Jc&&Jc.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Jc,"__esModule",{value:!0}),Jc.deserializeUnchecked=Jc.deserialize=Jc.serialize=Jc.BinaryReader=Jc.BinaryWriter=Jc.BorshError=Jc.baseDecode=Jc.baseEncode=void 0;const i=o(Uc()),s=o(eu()),a=r(du),c=new("function"!=typeof TextDecoder?a.TextDecoder:TextDecoder)("utf-8",{fatal:!0});Jc.baseEncode=function(e){return"string"==typeof e&&(e=Buffer.from(e,"utf8")),s.default.encode(Buffer.from(e))},Jc.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(".")}}Jc.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 i.default(e).toArray("le",8)))}writeU128(e){this.maybeResize(),this.writeBuffer(Buffer.from(new i.default(e).toArray("le",16)))}writeU256(e){this.maybeResize(),this.writeBuffer(Buffer.from(new i.default(e).toArray("le",32)))}writeU512(e){this.maybeResize(),this.writeBuffer(Buffer.from(new i.default(e).toArray("le",64)))}writeBuffer(e){this.buf=Buffer.concat([Buffer.from(this.buf.subarray(0,this.length)),e,Buffer.alloc(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}}}Jc.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 i.default(e,"le")}readU128(){const e=this.readBuffer(16);return new i.default(e,"le")}readU256(){const e=this.readBuffer(32);return new i.default(e,"le")}readU512(){const e=this.readBuffer(64);return new i.default(e,"le")}readBuffer(e){if(this.offset+e>this.buf.length)throw new 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 p(e){return e.charAt(0).toUpperCase()+e.slice(1)}function g(e,t,n,r,o){try{if("string"==typeof r)o[`write${p(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`);o.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++)g(e,null,n[t],r[0],o)}else o.writeArray(n,n=>{g(e,t,n,r[0],o)});else if(void 0!==r.kind)switch(r.kind){case"option":null==n?o.writeU8(0):(o.writeU8(1),g(e,t,n,r.type,o));break;case"map":o.writeU32(n.size),n.forEach((n,i)=>{g(e,t,i,r.key,o),g(e,t,n,r.value,o)});break;default:throw new l(`FieldType ${r} unrecognized`)}else m(e,n,o)}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,o])=>{g(e,r,t[r],o,n)});else{if("enum"!==r.kind)throw new l(`Unexpected schema kind: ${r.kind} for ${t.constructor.name}`);{const o=t[r.field];for(let i=0;i<r.values.length;++i){const[s,a]=r.values[i];if(s===o){n.writeU8(i),g(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 o=0;o<n[1];o++)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 o=new Map;const i=r.readU32();for(let s=0;s<i;s++){const i=y(e,t,n.key,r),s=y(e,t,n.value,r);o.set(i,s)}return o}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[o,i]of e.get(t).fields)r[o]=y(e,o,i,n);return new t(r)}if("enum"===r.kind){const o=n.readU8();if(o>=r.values.length)throw new l(`Enum index: ${o} is out of range`);const[i,s]=r.values[o],a=y(e,i,s,n);return new t({[i]: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),Jc.BinaryReader=f,Jc.serialize=function(e,t,n=h){const r=new n;return m(e,t,r),r.toArray()},Jc.deserialize=function(e,t,n,r=f){const o=new r(n),i=w(e,t,o);if(o.offset<n.length)throw new l(`Unexpected ${n.length-o.offset} bytes after deserialized data`);return i},Jc.deserializeUnchecked=function(e,t,n,r=f){return w(e,t,new r(n))},Jc}(),mu={},yu={};function wu(){return fu||(fu=1,function(e){const t=Ji(),n=rs(),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 o=2147483647;function i(e){if(e>o)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=i(n);const o=r.write(e,t);o!==n&&(r=r.slice(0,o));return r}(e,t);if(ArrayBuffer.isView(e))return function(e){if(H(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(H(e,ArrayBuffer)||e&&H(e.buffer,ArrayBuffer))return h(e,t,n);if("undefined"!=typeof SharedArrayBuffer&&(H(e,SharedArrayBuffer)||e&&H(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 o=function(e){if(s.isBuffer(e)){const t=0|d(e.length),n=i(t);return 0===n.length||e.copy(n,0,0,t),n}if(void 0!==e.length)return"number"!=typeof e.length||V(e.length)?i(0):l(e);if("Buffer"===e.type&&Array.isArray(e.data))return l(e.data)}(e);if(o)return o;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),i(e<0?0:0|d(e))}function l(e){const t=e.length<0?0:0|d(e.length),n=i(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>=o)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+o.toString(16)+" bytes");return 0|e}function f(e,t){if(s.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||H(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 o=!1;for(;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":return G(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(o)return r?-1:G(e).length;t=(""+t).toLowerCase(),o=!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 x(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 B(this,t,n);case"base64":return S(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return C(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function g(e,t,n){const r=e[t];e[t]=e[n],e[n]=r}function m(e,t,n,r,o){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=o?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(o)return-1;n=e.length-1}else if(n<0){if(!o)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,o);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?o?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):y(e,[t],n,r,o);throw new TypeError("val must be string, number or Buffer")}function y(e,t,n,r,o){let i,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(o){let r=-1;for(i=n;i<a;i++)if(u(e,i)===u(t,-1===r?0:i-r)){if(-1===r&&(r=i),i-r+1===c)return r*s}else-1!==r&&(i-=i-r),r=-1}else for(n+c>a&&(n=a-c),i=n;i>=0;i--){let n=!0;for(let r=0;r<c;r++)if(u(e,i+r)!==u(t,r)){n=!1;break}if(n)return i}return-1}function w(e,t,n,r){n=Number(n)||0;const o=e.length-n;r?(r=Number(r))>o&&(r=o):r=o;const i=t.length;let s;for(r>i/2&&(r=i/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 j(G(t,e.length-n),e,n,r)}function k(e,t,n,r){return j(function(e){const t=[];for(let n=0;n<e.length;++n)t.push(255&e.charCodeAt(n));return t}(t),e,n,r)}function v(e,t,n,r){return j(W(t),e,n,r)}function E(e,t,n,r){return j(function(e,t){let n,r,o;const i=[];for(let s=0;s<e.length&&!((t-=2)<0);++s)n=e.charCodeAt(s),r=n>>8,o=n%256,i.push(o),i.push(r);return i}(t,e.length-n),e,n,r)}function S(e,n,r){return 0===n&&r===e.length?t.fromByteArray(e):t.fromByteArray(e.slice(n,r))}function T(e,t,n){n=Math.min(e.length,n);const r=[];let o=t;for(;o<n;){const t=e[o];let i=null,s=t>239?4:t>223?3:t>191?2:1;if(o+s<=n){let n,r,a,c;switch(s){case 1:t<128&&(i=t);break;case 2:n=e[o+1],128==(192&n)&&(c=(31&t)<<6|63&n,c>127&&(i=c));break;case 3:n=e[o+1],r=e[o+2],128==(192&n)&&128==(192&r)&&(c=(15&t)<<12|(63&n)<<6|63&r,c>2047&&(c<55296||c>57343)&&(i=c));break;case 4:n=e[o+1],r=e[o+2],a=e[o+3],128==(192&n)&&128==(192&r)&&128==(192&a)&&(c=(15&t)<<18|(63&n)<<12|(63&r)<<6|63&a,c>65535&&c<1114112&&(i=c))}}null===i?(i=65533,s=1):i>65535&&(i-=65536,r.push(i>>>10&1023|55296),i=56320|1023&i),r.push(i),o+=s}return function(e){const t=e.length;if(t<=A)return String.fromCharCode.apply(String,e);let n="",r=0;for(;r<t;)n+=String.fromCharCode.apply(String,e.slice(r,r+=A));return n}(r)}e.kMaxLength=o,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?i(e):void 0!==t?"string"==typeof n?i(e).fill(t,n):i(e).fill(t):i(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(H(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),H(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 o=0,i=Math.min(n,r);o<i;++o)if(e[o]!==t[o]){n=e[o],r=t[o];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 o=0;for(n=0;n<e.length;++n){let t=e[n];if(H(t,Uint8Array))o+t.length>r.length?(s.isBuffer(t)||(t=s.from(t)),t.copy(r,o)):Uint8Array.prototype.set.call(r,t,o);else{if(!s.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(r,o)}o+=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)g(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)g(this,t,t+3),g(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)g(this,t,t+7),g(this,t+1,t+6),g(this,t+2,t+5),g(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,o){if(H(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===o&&(o=this.length),t<0||n>e.length||r<0||o>this.length)throw new RangeError("out of range index");if(r>=o&&t>=n)return 0;if(r>=o)return-1;if(t>=n)return 1;if(this===e)return 0;let i=(o>>>=0)-(r>>>=0),a=(n>>>=0)-(t>>>=0);const c=Math.min(i,a),u=this.slice(r,o),l=e.slice(t,n);for(let e=0;e<c;++e)if(u[e]!==l[e]){i=u[e],a=l[e];break}return i<a?-1:a<i?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 o=this.length-t;if((void 0===n||n>o)&&(n=o),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");let i=!1;for(;;)switch(r){case"hex":return 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 E(this,e,t,n);default:if(i)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),i=!0}},s.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const A=4096;function I(e,t,n){let r="";n=Math.min(e.length,n);for(let o=t;o<n;++o)r+=String.fromCharCode(127&e[o]);return r}function B(e,t,n){let r="";n=Math.min(e.length,n);for(let o=t;o<n;++o)r+=String.fromCharCode(e[o]);return r}function x(e,t,n){const r=e.length;(!t||t<0)&&(t=0),(!n||n<0||n>r)&&(n=r);let o="";for(let r=t;r<n;++r)o+=X[e[r]];return o}function C(e,t,n){const r=e.slice(t,n);let o="";for(let e=0;e<r.length-1;e+=2)o+=String.fromCharCode(r[e]+256*r[e+1]);return o}function P(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 N(e,t,n,r,o,i){if(!s.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>o||t<i)throw new RangeError('"value" argument is out of bounds');if(n+r>e.length)throw new RangeError("Index out of range")}function _(e,t,n,r,o){$(t,r,o,e,n,7);let i=Number(t&BigInt(4294967295));e[n++]=i,i>>=8,e[n++]=i,i>>=8,e[n++]=i,i>>=8,e[n++]=i;let 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,o){$(t,r,o,e,n,7);let i=Number(t&BigInt(4294967295));e[n+7]=i,i>>=8,e[n+6]=i,i>>=8,e[n+5]=i,i>>=8,e[n+4]=i;let 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 U(e,t,n,r,o,i){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,o,i){return t=+t,r>>>=0,i||U(e,0,r,4),n.write(e,t,r,o,23,4),r+4}function L(e,t,r,o,i){return t=+t,r>>>=0,i||U(e,0,r,8),n.write(e,t,r,o,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||P(e,t,this.length);let r=this[e],o=1,i=0;for(;++i<t&&(o*=256);)r+=this[e+i]*o;return r},s.prototype.readUintBE=s.prototype.readUIntBE=function(e,t,n){e>>>=0,t>>>=0,n||P(e,t,this.length);let r=this[e+--t],o=1;for(;t>0&&(o*=256);)r+=this[e+--t]*o;return r},s.prototype.readUint8=s.prototype.readUInt8=function(e,t){return e>>>=0,t||P(e,1,this.length),this[e]},s.prototype.readUint16LE=s.prototype.readUInt16LE=function(e,t){return e>>>=0,t||P(e,2,this.length),this[e]|this[e+1]<<8},s.prototype.readUint16BE=s.prototype.readUInt16BE=function(e,t){return e>>>=0,t||P(e,2,this.length),this[e]<<8|this[e+1]},s.prototype.readUint32LE=s.prototype.readUInt32LE=function(e,t){return e>>>=0,t||P(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||P(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,o=this[++e]+256*this[++e]+65536*this[++e]+n*2**24;return BigInt(r)+(BigInt(o)<<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],o=this[++e]*2**24+65536*this[++e]+256*this[++e]+n;return(BigInt(r)<<BigInt(32))+BigInt(o)}),s.prototype.readIntLE=function(e,t,n){e>>>=0,t>>>=0,n||P(e,t,this.length);let r=this[e],o=1,i=0;for(;++i<t&&(o*=256);)r+=this[e+i]*o;return o*=128,r>=o&&(r-=Math.pow(2,8*t)),r},s.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||P(e,t,this.length);let r=t,o=1,i=this[e+--r];for(;r>0&&(o*=256);)i+=this[e+--r]*o;return o*=128,i>=o&&(i-=Math.pow(2,8*t)),i},s.prototype.readInt8=function(e,t){return e>>>=0,t||P(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},s.prototype.readInt16LE=function(e,t){e>>>=0,t||P(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||P(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||P(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||P(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||P(e,4,this.length),n.read(this,e,!0,23,4)},s.prototype.readFloatBE=function(e,t){return e>>>=0,t||P(e,4,this.length),n.read(this,e,!1,23,4)},s.prototype.readDoubleLE=function(e,t){return e>>>=0,t||P(e,8,this.length),n.read(this,e,!0,52,8)},s.prototype.readDoubleBE=function(e,t){return e>>>=0,t||P(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){N(this,e,t,n,Math.pow(2,8*n)-1,0)}let o=1,i=0;for(this[t]=255&e;++i<n&&(o*=256);)this[t+i]=e/o&255;return t+n},s.prototype.writeUintBE=s.prototype.writeUIntBE=function(e,t,n,r){if(e=+e,t>>>=0,n>>>=0,!r){N(this,e,t,n,Math.pow(2,8*n)-1,0)}let o=n-1,i=1;for(this[t+o]=255&e;--o>=0&&(i*=256);)this[t+o]=e/i&255;return t+n},s.prototype.writeUint8=s.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||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||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||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||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||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 _(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);N(this,e,t,n,r-1,-r)}let o=0,i=1,s=0;for(this[t]=255&e;++o<n&&(i*=256);)e<0&&0===s&&0!==this[t+o-1]&&(s=1),this[t+o]=(e/i|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);N(this,e,t,n,r-1,-r)}let o=n-1,i=1,s=0;for(this[t+o]=255&e;--o>=0&&(i*=256);)e<0&&0===s&&0!==this[t+o+1]&&(s=1),this[t+o]=(e/i|0)-s&255;return t+n},s.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||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||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||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||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||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 _(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 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 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 o=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),o},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 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{const i=s.isBuffer(e)?e:s.from(e,r),a=i.length;if(0===a)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(o=0;o<n-t;++o)this[o+t]=i[o%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 M(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,o,i){if(e>n||e<t){const n="bigint"==typeof t?"n":"";let r;throw r=0===t||t===BigInt(0)?`>= 0${n} and < 2${n} ** ${8*(i+1)}${n}`:`>= -(2${n} ** ${8*(i+1)-1}${n}) and < 2 ** ${8*(i+1)-1}${n}`,new 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,o,i)}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.`,o=n;return Number.isInteger(n)&&Math.abs(n)>2**32?o=M(String(n)):"bigint"==typeof n&&(o=String(n),(n>BigInt(2)**BigInt(32)||n<-(BigInt(2)**BigInt(32)))&&(o=M(o)),o+="n"),r+=` It must be ${t}. Received ${o}`,r},RangeError);const z=/[^+/0-9A-Za-z-_]/g;function G(e,t){let n;t=t||1/0;const r=e.length;let o=null;const i=[];for(let s=0;s<r;++s){if(n=e.charCodeAt(s),n>55295&&n<57344){if(!o){if(n>56319){(t-=3)>-1&&i.push(239,191,189);continue}if(s+1===r){(t-=3)>-1&&i.push(239,191,189);continue}o=n;continue}if(n<56320){(t-=3)>-1&&i.push(239,191,189),o=n;continue}n=65536+(o-55296<<10|n-56320)}else o&&(t-=3)>-1&&i.push(239,191,189);if(o=null,n<128){if((t-=1)<0)break;i.push(n)}else if(n<2048){if((t-=2)<0)break;i.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;i.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;i.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return i}function W(e){return t.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(z,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function j(e,t,n,r){let o;for(o=0;o<r&&!(o+n>=t.length||o>=e.length);++o)t[o+n]=e[o];return o}function H(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 o=0;o<16;++o)t[r+o]=e[n]+e[o]}return t}();function Q(e){return"undefined"==typeof BigInt?Z:e}function Z(){throw new Error("BigInt not supported")}}(yu)),yu}var bu=function(){if(pu)return mu;pu=1,Object.defineProperty(mu,"__esModule",{value:!0}),mu.s16=mu.s8=mu.nu64be=mu.u48be=mu.u40be=mu.u32be=mu.u24be=mu.u16be=mu.nu64=mu.u48=mu.u40=mu.u32=mu.u24=mu.u16=mu.u8=mu.offset=mu.greedy=mu.Constant=mu.UTF8=mu.CString=mu.Blob=mu.Boolean=mu.BitField=mu.BitStructure=mu.VariantLayout=mu.Union=mu.UnionLayoutDiscriminator=mu.UnionDiscriminator=mu.Structure=mu.Sequence=mu.DoubleBE=mu.Double=mu.FloatBE=mu.Float=mu.NearInt64BE=mu.NearInt64=mu.NearUInt64BE=mu.NearUInt64=mu.IntBE=mu.Int=mu.UIntBE=mu.UInt=mu.OffsetLayout=mu.GreedyCount=mu.ExternalLayout=mu.bindConstructorLayout=mu.nameWithProperty=mu.Layout=mu.uint8ArrayToBuffer=mu.checkUint8Array=void 0,mu.constant=mu.utf8=mu.cstr=mu.blob=mu.unionLayoutDiscriminator=mu.union=mu.seq=mu.bits=mu.struct=mu.f64be=mu.f64=mu.f32be=mu.f32=mu.ns64be=mu.s48be=mu.s40be=mu.s32be=mu.s24be=mu.s16be=mu.ns64=mu.s48=mu.s40=mu.s32=mu.s24=void 0;const e=wu();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)}mu.checkUint8Array=t,mu.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 o(e,t){return t.property?e+"["+t.property+"]":e}mu.Layout=r,mu.nameWithProperty=o,mu.bindConstructorLayout=function(e,t){if("function"!=typeof e)throw new TypeError("Class must be constructor");if(Object.prototype.hasOwnProperty.call(e,"layout_"))throw new Error("Class is already bound to a layout");if(!(t&&t instanceof r))throw new TypeError("layout must be a Layout");if(Object.prototype.hasOwnProperty.call(t,"boundConstructor_"))throw new Error("layout is already bound to a constructor");e.layout_=t,t.boundConstructor_=e,t.makeDestinationObject=()=>new e,Object.defineProperty(e.prototype,"encode",{value(e,n){return t.encode(this,e,n)},writable:!0}),Object.defineProperty(e,"decode",{value:(e,n)=>t.decode(e,n),writable:!0})};class i extends r{isCount(){throw new Error("ExternalLayout is abstract")}}mu.ExternalLayout=i;class s extends i{constructor(e=1,t){if(!Number.isInteger(e)||0>=e)throw new TypeError("elementSpan must be a (positive) integer");super(-1,t),this.elementSpan=e}isCount(){return!0}decode(e,n=0){t(e);const r=e.length-n;return Math.floor(r/this.elementSpan)}encode(e,t,n){return 0}}mu.GreedyCount=s;class a extends i{constructor(e,t=0,n){if(!(e instanceof r))throw new TypeError("layout must be a Layout");if(!Number.isInteger(t))throw new TypeError("offset must be integer or undefined");super(e.span,n||e.property),this.layout=e,this.offset=t}isCount(){return this.layout instanceof c||this.layout instanceof 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)}}mu.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}}mu.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}}mu.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}}mu.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}}mu.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 p(e,t){return e*d+t}class g extends r{constructor(e){super(8,e)}decode(e,t=0){const r=n(e),o=r.readUInt32LE(t);return p(r.readUInt32LE(t+4),o)}encode(e,t,r=0){const o=f(e),i=n(t);return i.writeUInt32LE(o.lo32,r),i.writeUInt32LE(o.hi32,r+4),8}}mu.NearUInt64=g;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 o=f(e),i=n(t);return i.writeUInt32BE(o.hi32,r),i.writeUInt32BE(o.lo32,r+4),8}}mu.NearUInt64BE=m;class y extends r{constructor(e){super(8,e)}decode(e,t=0){const r=n(e),o=r.readUInt32LE(t);return p(r.readInt32LE(t+4),o)}encode(e,t,r=0){const o=f(e),i=n(t);return i.writeUInt32LE(o.lo32,r),i.writeInt32LE(o.hi32,r+4),8}}mu.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 o=f(e),i=n(t);return i.writeInt32BE(o.hi32,r),i.writeUInt32BE(o.lo32,r+4),8}}mu.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}}mu.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}}mu.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}}mu.Double=v;class E 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}}mu.DoubleBE=E;class S extends r{constructor(e,t,n){if(!(e instanceof r))throw new TypeError("elementLayout must be a Layout");if(!(t instanceof i&&t.isCount()||Number.isInteger(t)&&0<=t))throw new TypeError("count must be non-negative integer or an unsigned integer ExternalLayout");let o=-1;!(t instanceof i)&&0<e.span&&(o=t*e.span),super(o,n),this.elementLayout=e,this.count=t}getSpan(e,t=0){if(0<=this.span)return this.span;let n=0,r=this.count;if(r instanceof i&&(r=r.decode(e,t)),0<this.elementLayout.span)n=r*this.elementLayout.span;else{let o=0;for(;o<r;)n+=this.elementLayout.getSpan(e,t+n),++o}return n}decode(e,t=0){const n=[];let r=0,o=this.count;for(o instanceof i&&(o=o.decode(e,t));r<o;)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,o=e.reduce((e,o)=>e+r.encode(o,t,n+e),0);return this.count instanceof i&&this.count.encode(e.length,t,n),o}}mu.Sequence=S;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 o=-1;try{o=e.reduce((e,t)=>e+t.getSpan(),0)}catch(e){}super(o,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 o=r.getSpan(e,t);return t+=o,n+o},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 o=0,i=0;for(const r of this.fields){let s=r.span;if(i=0<s?s:0,void 0!==r.property){const o=e[r.property];void 0!==o&&(i=r.encode(o,t,n),0>s&&(s=r.getSpan(t,n)))}o=n,n+=s}return o+i-r}fromArray(e){const t=this.makeDestinationObject();for(const n of this.fields)void 0!==n.property&&0<e.length&&(t[n.property]=e.shift());return t}layoutFor(e){if("string"!=typeof e)throw new TypeError("property must be string");for(const t of this.fields)if(t.property===e)return t}offsetOf(e){if("string"!=typeof e)throw new TypeError("property must be string");let t=0;for(const n of this.fields){if(n.property===e)return t;0>n.span?t=-1:0<=t&&(t+=n.span)}}}mu.Structure=T;class A{constructor(e){this.property=e}decode(e,t){throw new Error("UnionDiscriminator is abstract")}encode(e,t,n){throw new Error("UnionDiscriminator is abstract")}}mu.UnionDiscriminator=A;class I extends A{constructor(e,t){if(!(e instanceof i&&e.isCount()))throw new TypeError("layout must be an unsigned integer ExternalLayout");super(t||e.property||"variant"),this.layout=e}decode(e,t){return this.layout.decode(e,t)}encode(e,t,n){return this.layout.encode(e,t,n)}}mu.UnionLayoutDiscriminator=I;class B extends r{constructor(e,t,n){let o;if(e instanceof c||e instanceof u)o=new I(new a(e));else if(e instanceof i&&e.isCount())o=new I(e);else{if(!(e instanceof A))throw new TypeError("discr must be a UnionDiscriminator or an unsigned integer layout");o=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+=o.layout.span)),super(s,n),this.discriminator=o,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,o=r.decode(e,t),i=this.registry[o];if(void 0===i){const i=this.defaultLayout;let s=0;this.usesPrefixDiscriminator&&(s=r.layout.span),n=this.makeDestinationObject(),n[r.property]=o,n[i.property]=i.decode(e,t+s)}else n=i.decode(e,t);return n}encode(e,t,n=0){const r=this.getSourceVariant(e);if(void 0===r){const r=this.discriminator,o=this.defaultLayout;let i=0;return this.usesPrefixDiscriminator&&(i=r.layout.span),r.encode(e[r.property],t,n),i+o.encode(e[o.property],t,n+i)}return r.encode(e,t,n)}addVariant(e,t,n){const r=new x(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]}}mu.Union=B;class x extends r{constructor(e,t,n,o){if(!(e instanceof B))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===o&&(o=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 o)throw new TypeError("variant must have a String property")}let i=e.span;0>e.span&&(i=n?n.span:0,0<=i&&e.usesPrefixDiscriminator&&(i+=e.discriminator.layout.span)),super(i,o),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 o=r;if(this.layout&&(this.layout.encode(e[this.property],t,n+r),o+=this.layout.getSpan(t,n+r),0<=this.union.span&&o>this.union.span))throw new Error("encoded variant overruns containing union");return o}fromArray(e){if(this.layout)return this.layout.fromArray(e)}}function C(e){return 0>e&&(e+=4294967296),e}mu.VariantLayout=x;class P 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=C(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 N(this,e,t);return this.fields.push(n),n}addBoolean(e){const t=new _(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}}mu.BitStructure=P;class N{constructor(e,t,n){if(!(e instanceof P))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,o=e.fields.reduce((e,t)=>e+t.bits,0);if(t+o>r)throw new Error("bits too long for span remainder ("+(r-o)+" of "+r+" remain)");this.container=e,this.bits=t,this.valueMask=(1<<t)-1,32===t&&(this.valueMask=4294967295),this.start=o,this.container.msb&&(this.start=r-o-t),this.wordMask=C(this.valueMask<<this.start),this.property=n}decode(e,t){return C(this.container._packedGetValue()&this.wordMask)>>>this.start}encode(e){if("number"!=typeof e||!Number.isInteger(e)||e!==C(e&this.valueMask))throw new TypeError(o("BitField.encode",this)+" value must be integer not exceeding "+this.valueMask);const t=this.container._packedGetValue(),n=C(e<<this.start);this.container._packedSetValue(C(t&~this.wordMask)|n)}}mu.BitField=N;class _ extends N{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)}}mu.Boolean=_;class D extends r{constructor(e,t){if(!(e instanceof i&&e.isCount()||Number.isInteger(e)&&0<=e))throw new TypeError("length must be positive integer or an unsigned integer ExternalLayout");let n=-1;e instanceof i||(n=e),super(n,t),this.length=e}getSpan(e,t){let n=this.span;return 0>n&&(n=this.length.decode(e,t)),n}decode(e,t=0){let r=this.span;return 0>r&&(r=this.length.decode(e,t)),n(e).slice(t,t+r)}encode(e,t,r){let s=this.length;if(this.length instanceof i&&(s=e.length),!(e instanceof Uint8Array&&s===e.length))throw new TypeError(o("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 i&&this.length.encode(s,t,r),s}}mu.Blob=D;class U 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,o=0){"string"!=typeof t&&(t=String(t));const i=e.Buffer.from(t,"utf8"),s=i.length;if(o+s>r.length)throw new RangeError("encoding overruns Buffer");const a=n(r);return i.copy(a,o),a[o+s]=0,s+1}}mu.CString=U;class R 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,o=0){"string"!=typeof t&&(t=String(t));const i=e.Buffer.from(t,"utf8"),s=i.length;if(0<=this.maxSpan&&this.maxSpan<s)throw new RangeError("text length exceeds maxSpan");if(o+s>r.length)throw new RangeError("encoding overruns Buffer");return i.copy(n(r),o),s}}mu.UTF8=R;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 mu.Constant=L,mu.greedy=(e,t)=>new s(e,t),mu.offset=(e,t,n)=>new a(e,t,n),mu.u8=e=>new c(1,e),mu.u16=e=>new c(2,e),mu.u24=e=>new c(3,e),mu.u32=e=>new c(4,e),mu.u40=e=>new c(5,e),mu.u48=e=>new c(6,e),mu.nu64=e=>new g(e),mu.u16be=e=>new u(2,e),mu.u24be=e=>new u(3,e),mu.u32be=e=>new u(4,e),mu.u40be=e=>new u(5,e),mu.u48be=e=>new u(6,e),mu.nu64be=e=>new m(e),mu.s8=e=>new l(1,e),mu.s16=e=>new l(2,e),mu.s24=e=>new l(3,e),mu.s32=e=>new l(4,e),mu.s40=e=>new l(5,e),mu.s48=e=>new l(6,e),mu.ns64=e=>new y(e),mu.s16be=e=>new h(2,e),mu.s24be=e=>new h(3,e),mu.s32be=e=>new h(4,e),mu.s40be=e=>new h(5,e),mu.s48be=e=>new h(6,e),mu.ns64be=e=>new w(e),mu.f32=e=>new b(e),mu.f32be=e=>new k(e),mu.f64=e=>new v(e),mu.f64be=e=>new E(e),mu.struct=(e,t,n)=>new T(e,t,n),mu.bits=(e,t,n)=>new P(e,t,n),mu.seq=(e,t,n)=>new S(e,t,n),mu.union=(e,t,n)=>new B(e,t,n),mu.unionLayoutDiscriminator=(e,t)=>new I(e,t),mu.blob=(e,t)=>new D(e,t),mu.cstr=e=>new U(e),mu.utf8=(e,t)=>new R(e,t),mu.constant=(e,t)=>new L(e,t),mu}(),ku=1,vu=2,Eu=3,Su=4,Tu=5,Au=6,Iu=7,Bu=8,xu=9,Cu=10,Pu=-32700,Nu=-32603,_u=-32602,Du=-32601,Uu=-32600,Ru=-32016,Lu=-32015,Ou=-32014,Fu=-32013,Mu=-32012,$u=-32011,qu=-32010,Ku=-32009,zu=-32008,Gu=-32007,Wu=-32006,ju=-32005,Hu=-32004,Vu=-32003,Xu=-32002,Qu=-32001,Zu=28e5,Yu=2800001,Ju=2800002,el=2800003,tl=2800004,nl=2800005,rl=2800006,ol=2800007,il=2800008,sl=2800009,al=2800010,cl=2800011,ul=323e4,ll=32300001,hl=3230002,dl=3230003,fl=3230004,pl=361e4,gl=3610001,ml=3610002,yl=3610003,wl=3610004,bl=3610005,kl=3610006,vl=3610007,El=3611e3,Sl=3704e3,Tl=3704001,Al=3704002,Il=3704003,Bl=3704004,xl=4128e3,Cl=4128001,Pl=4128002,Nl=4615e3,_l=4615001,Dl=4615002,Ul=4615003,Rl=4615004,Ll=4615005,Ol=4615006,Fl=4615007,Ml=4615008,$l=4615009,ql=4615010,Kl=4615011,zl=4615012,Gl=4615013,Wl=4615014,jl=4615015,Hl=4615016,Vl=4615017,Xl=4615018,Ql=4615019,Zl=4615020,Yl=4615021,Jl=4615022,eh=4615023,th=4615024,nh=4615025,rh=4615026,oh=4615027,ih=4615028,sh=4615029,ah=4615030,ch=4615031,uh=4615032,lh=4615033,hh=4615034,dh=4615035,fh=4615036,ph=4615037,gh=4615038,mh=4615039,yh=4615040,wh=4615041,bh=4615042,kh=4615043,vh=4615044,Eh=4615045,Sh=4615046,Th=4615047,Ah=4615048,Ih=4615049,Bh=4615050,xh=4615051,Ch=4615052,Ph=4615053,Nh=4615054,_h=5508e3,Dh=5508001,Uh=5508002,Rh=5508003,Lh=5508004,Oh=5508005,Fh=5508006,Mh=5508007,$h=5508008,qh=5508009,Kh=5508010,zh=5508011,Gh=5663e3,Wh=5663001,jh=5663002,Hh=5663003,Vh=5663004,Xh=5663005,Qh=5663006,Zh=5663007,Yh=5663008,Jh=5663009,ed=5663010,td=5663011,nd=5663012,rd=5663013,od=5663014,id=5663015,sd=5663016,ad=5663017,cd=5663018,ud=5663019,ld=5663020,hd=705e4,dd=7050001,fd=7050002,pd=7050003,gd=7050004,md=7050005,yd=7050006,wd=7050007,bd=7050008,kd=7050009,vd=7050010,Ed=7050011,Sd=7050012,Td=7050013,Ad=7050014,Id=7050015,Bd=7050016,xd=7050017,Cd=7050018,Pd=7050019,Nd=7050020,_d=7050021,Dd=7050022,Ud=7050023,Rd=7050024,Ld=7050025,Od=7050026,Fd=7050027,Md=7050028,$d=7050029,qd=7050030,Kd=7050031,zd=7050032,Gd=7050033,Wd=7050034,jd=7050035,Hd=7050036,Vd=8078e3,Xd=8078001,Qd=8078002,Zd=8078003,Yd=8078004,Jd=8078005,ef=8078006,tf=8078007,nf=8078008,rf=8078009,of=8078010,sf=8078011,af=8078012,cf=8078013,uf=8078014,lf=8078015,hf=8078016,df=8078017,ff=8078018,pf=8078019,gf=8078020,mf=8078021,yf=8078022,wf=81e5,bf=8100001,kf=8100002,vf=8100003,Ef=819e4,Sf=8190001,Tf=8190002,Af=8190003,If=8190004,Bf=99e5,xf=9900001,Cf=9900002,Pf=9900003,Nf=9900004;function _f(e){if(Array.isArray(e)){return"%5B"+e.map(_f).join("%2C%20")+"%5D"}return"bigint"==typeof e?`${e}n`:encodeURIComponent(String(null!=e&&null===Object.getPrototypeOf(e)?{...e}:e))}function Df([e,t]){return`${e}=${_f(t)}`}var Uf={[ul]:"Account not found at address: $address",[fl]:"Not all accounts were decoded. Encoded accounts found at addresses: $addresses.",[dl]:"Expected decoded account at address: $address",[hl]:"Failed to decode account data at address: $address",[ll]:"Accounts not found at addresses: $addresses",[sl]:"Unable to find a viable program address bump seed.",[Ju]:"$putativeAddress is not a base58-encoded address.",[Zu]:"Expected base58 encoded address to decode to a byte array of length 32. Actual length: $actualLength.",[el]:"The `CryptoKey` must be an `Ed25519` public key.",[cl]:"$putativeOffCurveAddress is not a base58-encoded off-curve address.",[il]:"Invalid seeds; point must fall off the Ed25519 curve.",[tl]:"Expected given program derived address to have the following format: [Address, ProgramDerivedAddressBump].",[rl]:"A maximum of $maxSeeds seeds, including the bump seed, may be supplied when creating an address. Received: $actual.",[ol]:"The seed at index $index with length $actual exceeds the maximum length of $maxSeedLength bytes.",[nl]:"Expected program derived address bump to be in the range [0, 255], got: $bump.",[al]:"Program address cannot end with PDA marker.",[Yu]:"Expected base58-encoded address string of length in the range [32, 44]. Actual length: $actualLength.",[Su]:"Expected base58-encoded blockash string of length in the range [32, 44]. Actual length: $actualLength.",[ku]:"The network has progressed past the last block for which this transaction could have been committed.",[Vd]:"Codec [$codecDescription] cannot decode empty byte arrays.",[yf]:"Enum codec cannot use lexical values [$stringValues] as discriminators. Either remove all lexical values or set `useValuesAsDiscriminators` to `false`.",[gf]:"Sentinel [$hexSentinel] must not be present in encoded bytes [$hexEncodedBytes].",[Jd]:"Encoder and decoder must have the same fixed size, got [$encoderFixedSize] and [$decoderFixedSize].",[ef]:"Encoder and decoder must have the same max size, got [$encoderMaxSize] and [$decoderMaxSize].",[Yd]:"Encoder and decoder must either both be fixed-size or variable-size.",[nf]:"Enum discriminator out of range. Expected a number in [$formattedValidDiscriminators], got $discriminator.",[Qd]:"Expected a fixed-size codec, got a variable-size one.",[cf]:"Codec [$codecDescription] expected a positive byte length, got $bytesLength.",[Zd]:"Expected a variable-size codec, got a fixed-size one.",[pf]:"Codec [$codecDescription] expected zero-value [$hexZeroValue] to have the same size as the provided fixed-size item [$expectedSize bytes].",[Xd]:"Codec [$codecDescription] expected $expected bytes, got $bytesLength.",[ff]:"Expected byte array constant [$hexConstant] to be present in data [$hexData] at offset [$offset].",[rf]:"Invalid discriminated union variant. Expected one of [$variants], got $value.",[of]:"Invalid enum variant. Expected one of [$stringValues] or a number in [$formattedNumericalValues], got $variant.",[lf]:"Invalid literal union variant. Expected one of [$variants], got $value.",[tf]:"Expected [$codecDescription] to have $expected items, got $actual.",[af]:"Invalid value $value for base $base with alphabet $alphabet.",[hf]:"Literal union discriminator out of range. Expected a number between $minRange and $maxRange, got $discriminator.",[sf]:"Codec [$codecDescription] expected number to be in the range [$min, $max], got $value.",[uf]:"Codec [$codecDescription] expected offset to be in the range [0, $bytesLength], got $offset.",[mf]:"Expected sentinel [$hexSentinel] to be present in decoded bytes [$hexDecodedBytes].",[df]:"Union variant out of range. Expected an index between $minRange and $maxRange, got $variant.",[El]:"No random values implementation could be found.",[$l]:"instruction requires an uninitialized account",[eh]:"instruction tries to borrow reference for an account which is already borrowed",[th]:"instruction left account with an outstanding borrowed reference",[Yl]:"program other than the account's owner changed the size of the account data",[Ll]:"account data too small for instruction",[Jl]:"instruction expected an executable account",[Sh]:"An account does not have enough lamports to be rent-exempt",[Ah]:"Program arithmetic overflowed",[Eh]:"Failed to serialize or deserialize account data: $encodedData",[Nh]:"Builtin programs must consume compute units",[uh]:"Cross-program invocation call depth too deep",[gh]:"Computational budget exceeded",[rh]:"custom program error: #$code",[Vl]:"instruction contains duplicate accounts",[nh]:"instruction modifications of multiply-passed account differ",[ah]:"executable accounts must be rent exempt",[ih]:"instruction changed executable accounts data",[sh]:"instruction changed the balance of an executable account",[Xl]:"instruction changed executable bit of an account",[Wl]:"instruction modified data of an account it does not own",[Gl]:"instruction spent from the balance of an account it does not own",[_l]:"generic instruction error",[Bh]:"Provided owner is not allowed",[kh]:"Account is immutable",[vh]:"Incorrect authority provided",[Fl]:"incorrect program id for instruction",[Ol]:"insufficient funds for instruction",[Rl]:"invalid account data for instruction",[Th]:"Invalid account owner",[Dl]:"invalid program argument",[oh]:"program returned invalid error code",[Ul]:"invalid instruction data",[ph]:"Failed to reallocate account data",[fh]:"Provided seeds do not result in a valid address",[xh]:"Accounts data allocations exceeded the maximum allowed per transaction",[Ch]:"Max accounts exceeded",[Ph]:"Max instruction trace length exceeded",[dh]:"Length of the seed is too long for address generation",[lh]:"An account required by the instruction is missing",[Ml]:"missing required signature for instruction",[zl]:"instruction illegally modified the program id of an account",[Zl]:"insufficient account keys for instruction",[mh]:"Cross-program invocation with unauthorized signer or writable account",[yh]:"Failed to create program execution environment",[bh]:"Program failed to compile",[wh]:"Program failed to complete",[Hl]:"instruction modified data of a read-only account",[jl]:"instruction changed the balance of a read-only account",[hh]:"Cross-program invocation reentrancy not allowed for this instruction",[Ql]:"instruction modified rent epoch of an account",[Kl]:"sum of account balances before and after instruction do not match",[ql]:"instruction requires an initialized account",[Nl]:"",[ch]:"Unsupported program id",[Ih]:"Unsupported sysvar",[xl]:"The instruction does not have any accounts.",[Cl]:"The instruction does not have any data.",[Pl]:"Expected instruction to have progress address $expectedProgramAddress, got $actualProgramAddress.",[Tu]:"Expected base58 encoded blockhash to decode to a byte array of length 32. Actual length: $actualLength.",[vu]:"The nonce `$expectedNonceValue` is no longer valid. It has advanced to `$actualNonceValue`",[Cf]:"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",[Nf]:"Invariant violation: This data publisher does not publish to the channel named `$channelName`. Supported channels include $supportedChannelNames.",[xf]:"Invariant violation: WebSocket message iterator state is corrupt; iterated without first resolving existing message promise. It should be impossible to hit this error; please file an issue at https://sola.na/web3invariant",[Bf]:"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",[Pf]:"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",[Nu]:"JSON-RPC error: Internal JSON-RPC error ($__serverMessage)",[_u]:"JSON-RPC error: Invalid method parameter(s) ($__serverMessage)",[Uu]:"JSON-RPC error: The JSON sent is not a valid `Request` object ($__serverMessage)",[Du]:"JSON-RPC error: The method does not exist / is not available ($__serverMessage)",[Pu]:"JSON-RPC error: An error occurred on the server while parsing the JSON text ($__serverMessage)",[Mu]:"$__serverMessage",[Qu]:"$__serverMessage",[Hu]:"$__serverMessage",[Ou]:"$__serverMessage",[qu]:"$__serverMessage",[Ku]:"$__serverMessage",[Ru]:"Minimum context slot has not been reached",[ju]:"Node is unhealthy; behind by $numSlotsBehind slots",[zu]:"No snapshot",[Xu]:"Transaction simulation failed",[Gu]:"$__serverMessage",[$u]:"Transaction history is not available from this node",[Wu]:"$__serverMessage",[Fu]:"Transaction signature length mismatch",[Vu]:"Transaction signature verification failure",[Lu]:"$__serverMessage",[Sl]:"Key pair bytes must be of length 64, got $byteLength.",[Tl]:"Expected private key bytes with length 32. Actual length: $actualLength.",[Al]:"Expected base58-encoded signature to decode to a byte array of length 64. Actual length: $actualLength.",[Bl]:"The provided private key does not match the provided public key.",[Il]:"Expected base58-encoded signature string of length in the range [64, 88]. Actual length: $actualLength.",[Au]:"Lamports value must be in the range [0, 2e64-1]",[Iu]:"`$value` cannot be parsed as a `BigInt`",[Cu]:"$message",[Bu]:"`$value` cannot be parsed as a `Number`",[Eu]:"No nonce account could be found at address `$nonceAccountAddress`",[Ef]:"The notification name must end in 'Notifications' and the API must supply a subscription plan creator function for the notification '$notificationName'.",[Tf]:"WebSocket was closed before payload could be added to the send buffer",[Af]:"WebSocket connection closed",[If]:"WebSocket failed to connect",[Sf]:"Failed to obtain a subscription id from the server",[vf]:"Could not find an API plan for RPC method: `$method`",[wf]:"The $argumentLabel argument to the `$methodName` RPC method$optionalPathLabel was `$value`. This number is unsafe for use with the Solana JSON-RPC because it exceeds `Number.MAX_SAFE_INTEGER`.",[kf]:"HTTP error ($statusCode): $message",[bf]:"HTTP header(s) forbidden: $headers. Learn more at https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name.",[_h]:"Multiple distinct signers were identified for address `$address`. Please ensure that you are using the same signer instance for each address.",[Dh]:"The provided value does not implement the `KeyPairSigner` interface",[Rh]:"The provided value does not implement the `MessageModifyingSigner` interface",[Lh]:"The provided value does not implement the `MessagePartialSigner` interface",[Uh]:"The provided value does not implement any of the `MessageSigner` interfaces",[Fh]:"The provided value does not implement the `TransactionModifyingSigner` interface",[Mh]:"The provided value does not implement the `TransactionPartialSigner` interface",[$h]:"The provided value does not implement the `TransactionSendingSigner` interface",[Oh]:"The provided value does not implement any of the `TransactionSigner` interfaces",[qh]:"More than one `TransactionSendingSigner` was identified.",[Kh]:"No `TransactionSendingSigner` was identified. Please provide a valid `TransactionWithSingleSendingSigner` transaction.",[zh]:"Wallet account signers do not support signing multiple messages/transactions in a single operation",[vl]:"Cannot export a non-extractable key.",[gl]:"No digest implementation could be found.",[pl]:"Cryptographic operations are only allowed in secure browser contexts. Read more here: https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts.",[ml]:"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.",[yl]:"No signature verification implementation could be found.",[wl]:"No key generation implementation could be found.",[bl]:"No signing implementation could be found.",[kl]:"No key export implementation could be found.",[xu]:"Timestamp value must be in the range [-(2n ** 63n), (2n ** 63n) - 1]. `$value` given",[Bd]:"Transaction processing left an account with an outstanding borrowed reference",[dd]:"Account in use",[fd]:"Account loaded twice",[pd]:"Attempt to debit an account but found no record of a prior credit.",[Ud]:"Transaction loads an address table account that doesn't exist",[wd]:"This transaction has already been processed",[bd]:"Blockhash not found",[kd]:"Loader call chain is too deep",[Id]:"Transactions are currently disabled due to cluster maintenance",[qd]:"Transaction contains a duplicate instruction ($index) that is not allowed",[md]:"Insufficient funds for fee",[Kd]:"Transaction results in an account ($accountIndex) with insufficient funds for rent",[yd]:"This account may not be used to pay transaction fees",[Ed]:"Transaction contains an invalid account reference",[Ld]:"Transaction loads an address table account with invalid data",[Od]:"Transaction address table lookup uses an invalid index",[Rd]:"Transaction loads an address table account with an invalid owner",[Gd]:"LoadedAccountsDataSizeLimit set for transaction must be greater than 0.",[Td]:"This program may not be used for executing instructions",[Fd]:"Transaction leaves an account with a lower balance than rent-exempt minimum",[Pd]:"Transaction loads a writable account that cannot be written",[zd]:"Transaction exceeded max loaded accounts data size cap",[vd]:"Transaction requires a fee but has no signature present",[gd]:"Attempt to load a program that does not exist",[jd]:"Execution of the program referenced by account at index $accountIndex is temporarily restricted.",[Wd]:"ResanitizationNeeded",[Ad]:"Transaction failed to sanitize accounts offsets correctly",[Sd]:"Transaction did not pass signature verification",[Dd]:"Transaction locked too many accounts",[Hd]:"Sum of account balances before and after transaction do not match",[hd]:"The transaction failed with the error `$errorName`",[Cd]:"Transaction version is unsupported",[_d]:"Transaction would exceed account data limit within the block",[$d]:"Transaction would exceed total account data limit",[Nd]:"Transaction would exceed max account limit within the block",[xd]:"Transaction would exceed max Block Cost Limit",[Md]:"Transaction would exceed max Vote Cost Limit",[id]:"Attempted to sign a transaction with an address that is not a signer for it",[ed]:"Transaction is missing an address at index: $index.",[sd]:"Transaction has no expected signers therefore it cannot be encoded",[ld]:"Transaction size $transactionSize exceeds limit of $transactionSizeLimit bytes",[jh]:"Transaction does not have a blockhash lifetime",[Hh]:"Transaction is not a durable nonce transaction",[Xh]:"Contents of these address lookup tables unknown: $lookupTableAddresses",[Qh]:"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",[Yh]:"No fee payer set in CompiledTransaction",[Zh]:"Could not find program address at index $index",[cd]:"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",[ud]:"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",[td]:"Transaction is missing a fee payer.",[nd]:"Could not determine this transaction's signature. Make sure that the transaction has been signed by its fee payer.",[od]:"Transaction first instruction is not advance nonce account instruction.",[rd]:"Transaction with no instructions cannot be durable nonce transaction.",[Gh]:"This transaction includes an address (`$programAddress`) which is both invoked and set as the fee payer. Program addresses may not pay fees",[Wh]:"This transaction includes an address (`$programAddress`) which is both invoked and marked writable. Program addresses may not be writable",[ad]:"The transaction message expected the transaction to have $signerAddressesLength signatures, got $signaturesLength.",[Jh]:"Transaction is missing signatures for addresses: $addresses.",[Vh]:"Transaction version must be in the range [0, 127]. `$actualVersion` given"},Rf="i",Lf="t";function Of(e,t={}){if("production"!==process.env.NODE_ENV)return function(e,t={}){const n=Uf[e];if(0===n.length)return"";let r;function o(e){if(2===r[Lf]){const o=n.slice(r[Rf]+1,e);i.push(o in t?`${t[o]}`:`$${o}`)}else 1===r[Lf]&&i.push(n.slice(r[Rf],e))}const i=[];return n.split("").forEach((e,t)=>{if(0===t)return void(r={[Rf]:0,[Lf]:"\\"===n[0]?0:"$"===n[0]?2:1});let i;switch(r[Lf]){case 0:i={[Rf]:t,[Lf]:1};break;case 1:"\\"===e?i={[Rf]:t,[Lf]:0}:"$"===e&&(i={[Rf]:t,[Lf]:2});break;case 2:"\\"===e?i={[Rf]:t,[Lf]:0}:"$"===e?i={[Rf]:t,[Lf]:2}:e.match(/\w/)||(i={[Rf]:t,[Lf]:1})}i&&(r!==i&&o(t),r=i)}),o(),i.join("")}(e,t);{let n=`Solana error #${e}; Decode this error by running \`npx @solana/errors decode -- ${e}`;return Object.keys(t).length&&(n+=` '${function(e){const t=Object.entries(e).map(Df).join("&");return btoa(t)}(t)}'`),`${n}\``}}var Ff=class extends Error{cause=this.cause;context;constructor(...[e,t]){let n,r;if(t){const{cause:e,...o}=t;e&&(r={cause:e}),Object.keys(o).length>0&&(n=o)}super(Of(e,n),r),this.context={__code:e,...n},this.name="SolanaError"}};function Mf(e){return"fixedSize"in e&&"number"==typeof e.fixedSize}function $f(e){return 1!==e?.endian}function qf(e){return t={fixedSize:e.size,write(t,n,r){e.range&&function(e,t,n,r){if(r<t||r>n)throw new Ff(sf,{codecDescription:e,max:n,min:t,value:r})}(e.name,e.range[0],e.range[1],t);const o=new ArrayBuffer(e.size);return e.set(new DataView(o),t,$f(e.config)),n.set(new Uint8Array(o),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 Kf(e){return t={fixedSize:e.size,read(t,n=0){!function(e,t,n=0){if(t.length-n<=0)throw new Ff(Vd,{codecDescription:e})}(e.name,t,n),function(e,t,n,r=0){const o=n.length-r;if(o<t)throw new Ff(Xd,{bytesLength:o,codecDescription:e,expected:t})}(e.name,e.size,t,n);const r=new DataView(function(e,t,n){const r=e.byteOffset+(t??0),o=n??e.byteLength;return e.buffer.slice(r,r+o)}(t,n,e.size));return[e.get(r,$f(e.config)),n+e.size]}},Object.freeze({...t,decode:(e,n=0)=>t.read(e,n)[0]});var t}var zf=(e={})=>function(e,t){if(Mf(e)!==Mf(t))throw new Ff(Yd);if(Mf(e)&&Mf(t)&&e.fixedSize!==t.fixedSize)throw new Ff(Jd,{decoderFixedSize:t.fixedSize,encoderFixedSize:e.fixedSize});if(!Mf(e)&&!Mf(t)&&e.maxSize!==t.maxSize)throw new Ff(ef,{decoderMaxSize:t.maxSize,encoderMaxSize:e.maxSize});return{...t,...e,decode:t.decode,encode:e.encode,read:t.read,write:e.write}}(((e={})=>qf({config:e,name:"u64",range:[0n,BigInt("0xffffffffffffffff")],set:(e,t,n)=>e.setBigUint64(0,BigInt(t),n),size:8}))(e),((e={})=>Kf({config:e,get:(e,t)=>e.getBigUint64(0,t),name:"u64",size:8}))(e));class Gf extends TypeError{constructor(e,t){let n;const{message:r,explanation:o,...i}=e,{path:s}=e,a=0===s.length?r:`At path: ${s.join(".")} -- ${r}`;super(o??a),null!=o&&(this.cause=a),Object.assign(this,i),this.name=this.constructor.name,this.failures=()=>n??(n=[e,...t()])}}function Wf(e){return"object"==typeof e&&null!=e}function jf(e){return Wf(e)&&!Array.isArray(e)}function Hf(e){return"symbol"==typeof e?e.toString():"string"==typeof e?JSON.stringify(e):`${e}`}function Vf(e,t,n,r){if(!0===e)return;!1===e?e={}:"string"==typeof e&&(e={message:e});const{path:o,branch:i}=t,{type:s}=n,{refinement:a,message:c=`Expected a value of type \`${s}\`${a?` with refinement \`${a}\``:""}, but received: \`${Hf(r)}\``}=e;return{value:r,type:s,refinement:a,key:o[o.length-1],path:o,branch:i,...e,message:c}}function*Xf(e,t,n,r){var o;Wf(o=e)&&"function"==typeof o[Symbol.iterator]||(e=[e]);for(const o of e){const e=Vf(o,t,n,r);e&&(yield e)}}function*Qf(e,t,n={}){const{path:r=[],branch:o=[e],coerce:i=!1,mask:s=!1}=n,a={path:r,branch:o,mask:s};i&&(e=t.coercer(e,a));let c="valid";for(const r of t.validator(e,a))r.explanation=n.message,c="not_valid",yield[r,void 0];for(let[u,l,h]of t.entries(e,a)){const t=Qf(l,h,{path:void 0===u?r:[...r,u],branch:void 0===u?o:[...o,l],coerce:i,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]):i&&(l=n[1],void 0===u?e=l:e instanceof Map?e.set(u,l):e instanceof Set?e.add(l):Wf(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 Zf=class{constructor(e){const{type:t,schema:n,validator:r,refiner:o,coercer:i=e=>e,entries:s=function*(){}}=e;this.type=t,this.schema=n,this.entries=s,this.coercer=i,this.validator=r?(e,t)=>Xf(r(e,t),t,this,e):()=>[],this.refiner=o?(e,t)=>Xf(o(e,t),t,this,e):()=>[]}assert(e,t){return function(e,t,n){const r=ep(e,t,{message:n});if(r[0])throw r[0]}(e,this,t)}create(e,t){return Yf(e,this,t)}is(e){return Jf(e,this)}mask(e,t){return function(e,t,n){const r=ep(e,t,{coerce:!0,mask:!0,message:n});if(r[0])throw r[0];return r[1]}(e,this,t)}validate(e,t={}){return ep(e,this,t)}};function Yf(e,t,n){const r=ep(e,t,{coerce:!0,message:n});if(r[0])throw r[0];return r[1]}function Jf(e,t){return!ep(e,t)[0]}function ep(e,t,n={}){const r=Qf(e,t,n),o=function(e){const{done:t,value:n}=e.next();return t?void 0:n}(r);if(o[0]){return[new Gf(o[0],function*(){for(const e of r)e[0]&&(yield e[0])}),void 0]}return[void 0,o[1]]}function tp(e,t){return new Zf({type:e,schema:null,validator:t})}function np(e){return new Zf({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: ${Hf(e)}`})}function rp(){return tp("boolean",e=>"boolean"==typeof e)}function op(e){return tp("instance",t=>t instanceof e||`Expected a \`${e.name}\` instance, but received: ${Hf(t)}`)}function ip(e){const t=Hf(e),n=typeof e;return new Zf({type:"literal",schema:"string"===n||"number"===n||"boolean"===n?e:null,validator:n=>n===e||`Expected the literal \`${t}\`, but received: ${Hf(n)}`})}function sp(e){return new Zf({...e,validator:(t,n)=>null===t||e.validator(t,n),refiner:(t,n)=>null===t||e.refiner(t,n)})}function ap(){return tp("number",e=>"number"==typeof e&&!isNaN(e)||`Expected a number, but received: ${Hf(e)}`)}function cp(e){return new Zf({...e,validator:(t,n)=>void 0===t||e.validator(t,n),refiner:(t,n)=>void 0===t||e.refiner(t,n)})}function up(e,t){return new Zf({type:"record",schema:null,*entries(n){if(Wf(n))for(const r in n){const o=n[r];yield[r,r,e],yield[r,o,t]}},validator:e=>jf(e)||`Expected an object, but received: ${Hf(e)}`,coercer:e=>jf(e)?{...e}:e})}function lp(){return tp("string",e=>"string"==typeof e||`Expected a string, but received: ${Hf(e)}`)}function hp(e){const t=tp("never",()=>!1);return new Zf({type:"tuple",schema:null,*entries(n){if(Array.isArray(n)){const r=Math.max(e.length,n.length);for(let o=0;o<r;o++)yield[o,n[o],e[o]||t]}},validator:e=>Array.isArray(e)||`Expected an array, but received: ${Hf(e)}`,coercer:e=>Array.isArray(e)?e.slice():e})}function dp(e){const t=Object.keys(e);return new Zf({type:"type",schema:e,*entries(n){if(Wf(n))for(const r of t)yield[r,n[r],e[r]]},validator:e=>jf(e)||`Expected an object, but received: ${Hf(e)}`,coercer:e=>jf(e)?{...e}:e})}function fp(e){const t=e.map(e=>e.type).join(" | ");return new Zf({type:"union",schema:null,coercer(t,n){for(const r of e){const[e,o]=r.validate(t,{coerce:!0,mask:n.mask});if(!e)return o}return t},validator(n,r){const o=[];for(const t of e){const[...e]=Qf(n,t,r),[i]=e;if(!i[0])return[];for(const[t]of e)t&&o.push(t)}return[`Expected the value to satisfy a union of \`${t}\`, but received: ${Hf(n)}`,...o]}})}function pp(){return tp("unknown",()=>!0)}function gp(e,t,n){return new Zf({...e,coercer:(r,o)=>Jf(r,t)?e.coercer(n(r,o),o):e.coercer(r,o)})}var mp,yp,wp,bp;var kp,vp=function(){if(bp)return wp;bp=1;const e=c.v4,t=function(){if(yp)return mp;yp=1;const e=c.v4;return mp=function(t,n,r,o){if("string"!=typeof t)throw new TypeError(t+" must be a string");const i="number"==typeof(o=o||{}).version?o.version:2;if(1!==i&&2!==i)throw new TypeError(i+" must be 1 or 2");const s={method:t};if(2===i&&(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 o.generator?o.generator:function(){return e()};s.id=t(s,o)}else 2===i&&null===r?o.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 wp=n,n.prototype.request=function(e,n,r,o){const i=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)o=n,s=e;else{"function"==typeof r&&(o=r,r=void 0);const i="function"==typeof o;try{s=t(e,n,r,{generator:this.options.generator,version:this.options.version,notificationIdNull:this.options.notificationIdNull})}catch(e){if(i)return o(e);throw e}if(!i)return s}let c;try{c=JSON.stringify(s,this.options.replacer)}catch(e){return o(e)}return this.callServer(c,function(e,t){i._parseResponse(e,t,o)}),s},n.prototype._parseResponse=function(e,t,n){if(e)return void n(e);if(!t)return n();let r;try{r=JSON.parse(t,this.options.reviver)}catch(e){return n(e)}if(3===n.length){if(Array.isArray(r)){const e=function(e){return void 0!==e.error},t=function(t){return!e(t)};return n(null,r.filter(e),r.filter(t))}return n(null,r.error,r.result)}n(null,r)},wp}(),Ep=Oo(vp),Sp={};var Tp,Ap=(kp||(kp=1,function(e){const t=Ji(),n=rs(),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 o=2147483647;function i(e){if(e>o)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=i(n);const o=r.write(e,t);return o!==n&&(r=r.slice(0,o)),r}(e,t);if(ArrayBuffer.isView(e))return function(e){if(H(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(H(e,ArrayBuffer)||e&&H(e.buffer,ArrayBuffer))return h(e,t,n);if("undefined"!=typeof SharedArrayBuffer&&(H(e,SharedArrayBuffer)||e&&H(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 o=function(e){if(s.isBuffer(e)){const t=0|d(e.length),n=i(t);return 0===n.length||e.copy(n,0,0,t),n}return void 0!==e.length?"number"!=typeof e.length||V(e.length)?i(0):l(e):"Buffer"===e.type&&Array.isArray(e.data)?l(e.data):void 0}(e);if(o)return o;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),i(e<0?0:0|d(e))}function l(e){const t=e.length<0?0:0|d(e.length),n=i(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>=o)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+o.toString(16)+" bytes");return 0|e}function f(e,t){if(s.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||H(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 o=!1;for(;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":return G(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(o)return r?-1:G(e).length;t=(""+t).toLowerCase(),o=!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 x(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 B(this,t,n);case"base64":return S(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return C(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function g(e,t,n){const r=e[t];e[t]=e[n],e[n]=r}function m(e,t,n,r,o){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=o?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(o)return-1;n=e.length-1}else if(n<0){if(!o)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,o);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?o?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):y(e,[t],n,r,o);throw new TypeError("val must be string, number or Buffer")}function y(e,t,n,r,o){let i,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(o){let r=-1;for(i=n;i<a;i++)if(u(e,i)===u(t,-1===r?0:i-r)){if(-1===r&&(r=i),i-r+1===c)return r*s}else-1!==r&&(i-=i-r),r=-1}else for(n+c>a&&(n=a-c),i=n;i>=0;i--){let n=!0;for(let r=0;r<c;r++)if(u(e,i+r)!==u(t,r)){n=!1;break}if(n)return i}return-1}function w(e,t,n,r){n=Number(n)||0;const o=e.length-n;r?(r=Number(r))>o&&(r=o):r=o;const i=t.length;let s;for(r>i/2&&(r=i/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 j(G(t,e.length-n),e,n,r)}function k(e,t,n,r){return j(function(e){const t=[];for(let n=0;n<e.length;++n)t.push(255&e.charCodeAt(n));return t}(t),e,n,r)}function v(e,t,n,r){return j(W(t),e,n,r)}function E(e,t,n,r){return j(function(e,t){let n,r,o;const i=[];for(let s=0;s<e.length&&!((t-=2)<0);++s)n=e.charCodeAt(s),r=n>>8,o=n%256,i.push(o),i.push(r);return i}(t,e.length-n),e,n,r)}function S(e,n,r){return 0===n&&r===e.length?t.fromByteArray(e):t.fromByteArray(e.slice(n,r))}function T(e,t,n){n=Math.min(e.length,n);const r=[];let o=t;for(;o<n;){const t=e[o];let i=null,s=t>239?4:t>223?3:t>191?2:1;if(o+s<=n){let n,r,a,c;switch(s){case 1:t<128&&(i=t);break;case 2:n=e[o+1],128==(192&n)&&(c=(31&t)<<6|63&n,c>127&&(i=c));break;case 3:n=e[o+1],r=e[o+2],128==(192&n)&&128==(192&r)&&(c=(15&t)<<12|(63&n)<<6|63&r,c>2047&&(c<55296||c>57343)&&(i=c));break;case 4:n=e[o+1],r=e[o+2],a=e[o+3],128==(192&n)&&128==(192&r)&&128==(192&a)&&(c=(15&t)<<18|(63&n)<<12|(63&r)<<6|63&a,c>65535&&c<1114112&&(i=c))}}null===i?(i=65533,s=1):i>65535&&(i-=65536,r.push(i>>>10&1023|55296),i=56320|1023&i),r.push(i),o+=s}return function(e){const t=e.length;if(t<=A)return String.fromCharCode.apply(String,e);let n="",r=0;for(;r<t;)n+=String.fromCharCode.apply(String,e.slice(r,r+=A));return n}(r)}e.kMaxLength=o,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?i(e):void 0!==t?"string"==typeof n?i(e).fill(t,n):i(e).fill(t):i(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(H(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),H(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 o=0,i=Math.min(n,r);o<i;++o)if(e[o]!==t[o]){n=e[o],r=t[o];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 o=0;for(n=0;n<e.length;++n){let t=e[n];if(H(t,Uint8Array))o+t.length>r.length?(s.isBuffer(t)||(t=s.from(t)),t.copy(r,o)):Uint8Array.prototype.set.call(r,t,o);else{if(!s.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(r,o)}o+=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)g(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)g(this,t,t+3),g(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)g(this,t,t+7),g(this,t+1,t+6),g(this,t+2,t+5),g(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,o){if(H(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===o&&(o=this.length),t<0||n>e.length||r<0||o>this.length)throw new RangeError("out of range index");if(r>=o&&t>=n)return 0;if(r>=o)return-1;if(t>=n)return 1;if(this===e)return 0;let i=(o>>>=0)-(r>>>=0),a=(n>>>=0)-(t>>>=0);const c=Math.min(i,a),u=this.slice(r,o),l=e.slice(t,n);for(let e=0;e<c;++e)if(u[e]!==l[e]){i=u[e],a=l[e];break}return i<a?-1:a<i?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 o=this.length-t;if((void 0===n||n>o)&&(n=o),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");let i=!1;for(;;)switch(r){case"hex":return 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 E(this,e,t,n);default:if(i)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),i=!0}},s.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const A=4096;function I(e,t,n){let r="";n=Math.min(e.length,n);for(let o=t;o<n;++o)r+=String.fromCharCode(127&e[o]);return r}function B(e,t,n){let r="";n=Math.min(e.length,n);for(let o=t;o<n;++o)r+=String.fromCharCode(e[o]);return r}function x(e,t,n){const r=e.length;(!t||t<0)&&(t=0),(!n||n<0||n>r)&&(n=r);let o="";for(let r=t;r<n;++r)o+=X[e[r]];return o}function C(e,t,n){const r=e.slice(t,n);let o="";for(let e=0;e<r.length-1;e+=2)o+=String.fromCharCode(r[e]+256*r[e+1]);return o}function P(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 N(e,t,n,r,o,i){if(!s.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>o||t<i)throw new RangeError('"value" argument is out of bounds');if(n+r>e.length)throw new RangeError("Index out of range")}function _(e,t,n,r,o){$(t,r,o,e,n,7);let i=Number(t&BigInt(4294967295));e[n++]=i,i>>=8,e[n++]=i,i>>=8,e[n++]=i,i>>=8,e[n++]=i;let 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,o){$(t,r,o,e,n,7);let i=Number(t&BigInt(4294967295));e[n+7]=i,i>>=8,e[n+6]=i,i>>=8,e[n+5]=i,i>>=8,e[n+4]=i;let 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 U(e,t,n,r,o,i){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,o,i){return t=+t,r>>>=0,i||U(e,0,r,4),n.write(e,t,r,o,23,4),r+4}function L(e,t,r,o,i){return t=+t,r>>>=0,i||U(e,0,r,8),n.write(e,t,r,o,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||P(e,t,this.length);let r=this[e],o=1,i=0;for(;++i<t&&(o*=256);)r+=this[e+i]*o;return r},s.prototype.readUintBE=s.prototype.readUIntBE=function(e,t,n){e>>>=0,t>>>=0,n||P(e,t,this.length);let r=this[e+--t],o=1;for(;t>0&&(o*=256);)r+=this[e+--t]*o;return r},s.prototype.readUint8=s.prototype.readUInt8=function(e,t){return e>>>=0,t||P(e,1,this.length),this[e]},s.prototype.readUint16LE=s.prototype.readUInt16LE=function(e,t){return e>>>=0,t||P(e,2,this.length),this[e]|this[e+1]<<8},s.prototype.readUint16BE=s.prototype.readUInt16BE=function(e,t){return e>>>=0,t||P(e,2,this.length),this[e]<<8|this[e+1]},s.prototype.readUint32LE=s.prototype.readUInt32LE=function(e,t){return e>>>=0,t||P(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||P(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,o=this[++e]+256*this[++e]+65536*this[++e]+n*2**24;return BigInt(r)+(BigInt(o)<<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],o=this[++e]*2**24+65536*this[++e]+256*this[++e]+n;return(BigInt(r)<<BigInt(32))+BigInt(o)}),s.prototype.readIntLE=function(e,t,n){e>>>=0,t>>>=0,n||P(e,t,this.length);let r=this[e],o=1,i=0;for(;++i<t&&(o*=256);)r+=this[e+i]*o;return o*=128,r>=o&&(r-=Math.pow(2,8*t)),r},s.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||P(e,t,this.length);let r=t,o=1,i=this[e+--r];for(;r>0&&(o*=256);)i+=this[e+--r]*o;return o*=128,i>=o&&(i-=Math.pow(2,8*t)),i},s.prototype.readInt8=function(e,t){return e>>>=0,t||P(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},s.prototype.readInt16LE=function(e,t){e>>>=0,t||P(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||P(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||P(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||P(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||P(e,4,this.length),n.read(this,e,!0,23,4)},s.prototype.readFloatBE=function(e,t){return e>>>=0,t||P(e,4,this.length),n.read(this,e,!1,23,4)},s.prototype.readDoubleLE=function(e,t){return e>>>=0,t||P(e,8,this.length),n.read(this,e,!0,52,8)},s.prototype.readDoubleBE=function(e,t){return e>>>=0,t||P(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||N(this,e,t,n,Math.pow(2,8*n)-1,0);let o=1,i=0;for(this[t]=255&e;++i<n&&(o*=256);)this[t+i]=e/o&255;return t+n},s.prototype.writeUintBE=s.prototype.writeUIntBE=function(e,t,n,r){e=+e,t>>>=0,n>>>=0,r||N(this,e,t,n,Math.pow(2,8*n)-1,0);let o=n-1,i=1;for(this[t+o]=255&e;--o>=0&&(i*=256);)this[t+o]=e/i&255;return t+n},s.prototype.writeUint8=s.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||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||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||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||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||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 _(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);N(this,e,t,n,r-1,-r)}let o=0,i=1,s=0;for(this[t]=255&e;++o<n&&(i*=256);)e<0&&0===s&&0!==this[t+o-1]&&(s=1),this[t+o]=(e/i|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);N(this,e,t,n,r-1,-r)}let o=n-1,i=1,s=0;for(this[t+o]=255&e;--o>=0&&(i*=256);)e<0&&0===s&&0!==this[t+o+1]&&(s=1),this[t+o]=(e/i|0)-s&255;return t+n},s.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||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||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||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||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||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 _(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 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 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 o=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),o},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 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{const i=s.isBuffer(e)?e:s.from(e,r),a=i.length;if(0===a)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(o=0;o<n-t;++o)this[o+t]=i[o%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 M(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,o,i){if(e>n||e<t){const n="bigint"==typeof t?"n":"";let r;throw r=0===t||t===BigInt(0)?`>= 0${n} and < 2${n} ** ${8*(i+1)}${n}`:`>= -(2${n} ** ${8*(i+1)-1}${n}) and < 2 ** ${8*(i+1)-1}${n}`,new 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,o,i)}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.`,o=n;return Number.isInteger(n)&&Math.abs(n)>2**32?o=M(String(n)):"bigint"==typeof n&&(o=String(n),(n>BigInt(2)**BigInt(32)||n<-(BigInt(2)**BigInt(32)))&&(o=M(o)),o+="n"),r+=` It must be ${t}. Received ${o}`,r},RangeError);const z=/[^+/0-9A-Za-z-_]/g;function G(e,t){let n;t=t||1/0;const r=e.length;let o=null;const i=[];for(let s=0;s<r;++s){if(n=e.charCodeAt(s),n>55295&&n<57344){if(!o){if(n>56319){(t-=3)>-1&&i.push(239,191,189);continue}if(s+1===r){(t-=3)>-1&&i.push(239,191,189);continue}o=n;continue}if(n<56320){(t-=3)>-1&&i.push(239,191,189),o=n;continue}n=65536+(o-55296<<10|n-56320)}else o&&(t-=3)>-1&&i.push(239,191,189);if(o=null,n<128){if((t-=1)<0)break;i.push(n)}else if(n<2048){if((t-=2)<0)break;i.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;i.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;i.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return i}function W(e){return t.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(z,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function j(e,t,n,r){let o;for(o=0;o<r&&!(o+n>=t.length||o>=e.length);++o)t[o+n]=e[o];return o}function H(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 o=0;o<16;++o)t[r+o]=e[n]+e[o]}return t}();function Q(e){return"undefined"==typeof BigInt?Z:e}function Z(){throw new Error("BigInt not supported")}}(Sp)),Sp),Ip={exports:{}};var Bp=(Tp||(Tp=1,function(e){var t=Object.prototype.hasOwnProperty,n="~";function r(){}function o(e,t,n){this.fn=e,this.context=t,this.once=n||!1}function i(e,t,r,i,s){if("function"!=typeof r)throw new TypeError("The listener must be a function");var a=new o(r,i||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,o=[];if(0===this._eventsCount)return o;for(r in e=this._events)t.call(e,r)&&o.push(n?r.slice(1):r);return Object.getOwnPropertySymbols?o.concat(Object.getOwnPropertySymbols(e)):o},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 o=0,i=r.length,s=new Array(i);o<i;o++)s[o]=r[o].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,o,i,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,o),!0;case 5:return l.fn.call(l.context,t,r,o,i),!0;case 6:return l.fn.call(l.context,t,r,o,i,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,o);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 i(this,e,t,n,!1)},a.prototype.once=function(e,t,n){return i(this,e,t,n,!0)},a.prototype.removeListener=function(e,t,r,o){var i=n?n+e:e;if(!this._events[i])return this;if(!t)return s(this,i),this;var a=this._events[i];if(a.fn)a.fn!==t||o&&!a.once||r&&a.context!==r||s(this,i);else{for(var c=0,u=[],l=a.length;c<l;c++)(a[c].fn!==t||o&&!a[c].once||r&&a[c].context!==r)&&u.push(a[c]);u.length?this._events[i]=1===u.length?u[0]:u:s(this,i)}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}(Ip)),Ip.exports),xp=Oo(Bp),Cp=class extends xp{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 Pp=class{encode(e){return JSON.stringify(e)}decode(e){return JSON.parse(e)}},Np=class extends xp{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:o=1e3,max_reconnects:i=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=o,this.max_reconnects=i,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 Pp,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((o,i)=>{if(!this.ready)return i(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 i(e);this.queue[s]={promise:[o,i]},n&&(this.queue[s].timeout=setTimeout(()=>{delete this.queue[s],i(new Error("reply timeout"))},n))})})}async login(e){const t=await this.call("rpc.login",e);if(!t)throw new Error("authentication failed");return t}async listMethods(){return await this.call("__listMethods")}notify(e,t){return new Promise((n,r)=>{if(!this.ready)return r(new Error("socket not ready"));const o={jsonrpc:"2.0",method:e,params:t};this.socket.send(this.dataPack.encode(o),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=Ap.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 _p extends Bs{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,us(e);const n=As(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,o=new Uint8Array(r);o.set(n.length>r?e.create().update(n).digest():n);for(let e=0;e<o.length;e++)o[e]^=54;this.iHash.update(o),this.oHash=e.create();for(let e=0;e<o.length;e++)o[e]^=106;this.oHash.update(o),hs(o)}update(e){return ls(this),this.iHash.update(e),this}digestInto(e){ls(this),cs(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:o,blockLen:i,outputLen:s}=this;return e.finished=r,e.destroyed=o,e.blockLen=i,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 Dp=(e,t,n)=>new _p(e,t).update(n).digest();Dp.create=(e,t)=>new _p(e,t);const Up=(e,t)=>(e+(e>=0?t:-t)/qp)/t;function Rp(e){if(!["compact","recovered","der"].includes(e))throw new Error('Signature format must be "compact", "recovered", or "der"');return e}function Lp(e,t){const n={};for(let r of Object.keys(t))n[r]=void 0===e[r]?t[r]:e[r];return la(n.lowS,"lowS"),la(n.prehash,"prehash"),void 0!==n.format&&Rp(n.format),n}class Op extends Error{constructor(e=""){super(e)}}const Fp={Err:Op,_tlv:{encode:(e,t)=>{const{Err:n}=Fp;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,o=da(r);if(o.length/2&128)throw new n("tlv.encode: long form length too big");const i=r>127?da(o.length/2|128):"";return da(e)+i+o+t},decode(e,t){const{Err:n}=Fp;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 o=t[r++];let i=0;if(!!(128&o)){const e=127&o;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)i=i<<8|e;if(r+=e,i<128)throw new n("tlv.decode(long): not minimal encoding")}else i=o;const s=t.subarray(r,r+i);if(s.length!==i)throw new n("tlv.decode: wrong value length");return{v:s,l:t.subarray(r+i)}}},_int:{encode(e){const{Err:t}=Fp;if(e<Mp)throw new t("integer: negative integers are not allowed");let n=da(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}=Fp;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 pa(e)}},toSig(e){const{Err:t,_int:n,_tlv:r}=Fp,o=wa("signature",e),{v:i,l:s}=r.decode(48,o);if(s.length)throw new t("invalid signature: left bytes after parsing");const{v:a,l:c}=r.decode(2,i),{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}=Fp,r=t.encode(2,n.encode(e.r))+t.encode(2,n.encode(e.s));return t.encode(48,r)}},Mp=BigInt(0),$p=BigInt(1),qp=BigInt(2),Kp=BigInt(3),zp=BigInt(4);function Gp(e,t){const{BYTES:n}=e;let r;if("bigint"==typeof t)r=t;else{let o=wa("private key",t);try{r=e.fromBytes(o)}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 Wp(e,t={}){const n=hc("weierstrass",e,t),{Fp:r,Fn:o}=n;let i=n.CURVE;const{h:s,n:a}=i;Ta(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:c}=t;if(c&&(!r.is0(i.a)||"bigint"!=typeof c.beta||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const u=Hp(r,o);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:o,y:i}=t.toAffine(),s=r.toBytes(o);if(la(n,"isCompressed"),n){l();return Is(jp(!r.isOdd(i)),s)}return Is(Uint8Array.of(4),s,r.toBytes(i))},d=t.fromBytes||function(e){ha(e,void 0,"Point");const{publicKey:t,publicKeyUncompressed:n}=u,o=e.length,i=e[0],s=e.subarray(1);if(o!==t||2!==i&&3!==i){if(o===n&&4===i){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 ${o}, 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&~i)!==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,i.a)),i.b)}function p(e,t){const n=r.sqr(t),o=f(e);return r.eql(n,o)}if(!p(i.Gx,i.Gy))throw new Error("bad curve params: generator point");const g=r.mul(r.pow(i.a,Kp),zp),m=r.mul(r.sqr(i.b),BigInt(27));if(r.is0(r.add(g,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 S))throw new Error("ProjectivePoint expected")}function b(e){if(!c||!c.basises)throw new Error("no endo");return function(e,t,n){const[[r,o],[i,s]]=t,a=Up(s*e,n),c=Up(-o*e,n);let u=e-a*r-c*i,l=-a*o-c*s;const h=u<Mp,d=l<Mp;h&&(u=-u),d&&(l=-l);const f=Sa(Math.ceil(Ea(n)/2))+$p;if(u<Mp||u>=f||l<Mp||l>=f)throw new Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:h,k1:u,k2neg:d,k2:l}}(e,c.basises,o.ORDER)}const k=Aa((e,t)=>{const{X:n,Y:o,Z:i}=e;if(r.eql(i,r.ONE))return{x:n,y:o};const s=e.is0();null==t&&(t=s?r.ONE:r.inv(i));const a=r.mul(n,t),c=r.mul(o,t),u=r.mul(i,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=Aa(e=>{if(e.is0()){if(t.allowInfinityPoint&&!r.is0(e.Y))return;throw new Error("bad point: ZERO")}const{x:n,y:o}=e.toAffine();if(!r.isValid(n)||!r.isValid(o))throw new Error("bad point: x or y not field elements");if(!p(n,o))throw new Error("bad point: equation left != right");if(!e.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function E(e,t,n,o,i){return n=new S(r.mul(n.X,e),n.Y,n.Z),t=Ja(o,t),n=Ja(i,n),t.add(n)}class S{constructor(e,t,n){this.X=y("x",e),this.Y=y("y",t,!0),this.Z=y("z",n),Object.freeze(this)}static CURVE(){return i}static fromAffine(e){const{x:t,y:n}=e||{};if(!e||!r.isValid(t)||!r.isValid(n))throw new Error("invalid affine point");if(e instanceof S)throw new Error("projective point not allowed");return r.is0(t)&&r.is0(n)?S.ZERO:new S(t,n,r.ONE)}static fromBytes(e){const t=S.fromAffine(d(ha(e,void 0,"point")));return t.assertValidity(),t}static fromHex(e){return S.fromBytes(wa("pointHex",e))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(e=8,t=!0){return A.createCache(this,e),t||this.multiply(Kp),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:o}=this,{X:i,Y:s,Z:a}=e,c=r.eql(r.mul(t,a),r.mul(i,o)),u=r.eql(r.mul(n,a),r.mul(s,o));return c&&u}negate(){return new S(this.X,r.neg(this.Y),this.Z)}double(){const{a:e,b:t}=i,n=r.mul(t,Kp),{X:o,Y:s,Z:a}=this;let c=r.ZERO,u=r.ZERO,l=r.ZERO,h=r.mul(o,o),d=r.mul(s,s),f=r.mul(a,a),p=r.mul(o,s);return p=r.add(p,p),l=r.mul(o,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(p,c),l=r.mul(n,l),f=r.mul(e,f),p=r.sub(h,f),p=r.mul(e,p),p=r.add(p,l),l=r.add(h,h),h=r.add(l,h),h=r.add(h,f),h=r.mul(h,p),u=r.add(u,h),f=r.mul(s,a),f=r.add(f,f),h=r.mul(f,p),c=r.sub(c,h),l=r.mul(f,d),l=r.add(l,l),l=r.add(l,l),new S(c,u,l)}add(e){w(e);const{X:t,Y:n,Z:o}=this,{X:s,Y:a,Z:c}=e;let u=r.ZERO,l=r.ZERO,h=r.ZERO;const d=i.a,f=r.mul(i.b,Kp);let p=r.mul(t,s),g=r.mul(n,a),m=r.mul(o,c),y=r.add(t,n),b=r.add(s,a);y=r.mul(y,b),b=r.add(p,g),y=r.sub(y,b),b=r.add(t,o);let k=r.add(s,c);return b=r.mul(b,k),k=r.add(p,m),b=r.sub(b,k),k=r.add(n,o),u=r.add(a,c),k=r.mul(k,u),u=r.add(g,m),k=r.sub(k,u),h=r.mul(d,b),u=r.mul(f,m),h=r.add(u,h),u=r.sub(g,h),h=r.add(g,h),l=r.mul(u,h),g=r.add(p,p),g=r.add(g,p),m=r.mul(d,m),b=r.mul(f,b),g=r.add(g,m),m=r.sub(p,m),m=r.mul(d,m),b=r.add(b,m),p=r.mul(g,b),l=r.add(l,p),p=r.mul(k,b),u=r.mul(y,u),u=r.sub(u,p),p=r.mul(y,g),h=r.mul(k,h),h=r.add(h,p),new S(u,l,h)}subtract(e){return this.add(e.negate())}is0(){return this.equals(S.ZERO)}multiply(e){const{endo:n}=t;if(!o.isValidNot0(e))throw new Error("invalid scalar: out of range");let r,i;const s=e=>A.cached(this,e,e=>ec(S,e));if(n){const{k1neg:t,k1:o,k2neg:a,k2:c}=b(e),{p:u,f:l}=s(o),{p:h,f:d}=s(c);i=l.add(d),r=E(n.beta,u,h,t,a)}else{const{p:t,f:n}=s(e);r=t,i=n}return ec(S,[r,i])[0]}multiplyUnsafe(e){const{endo:n}=t,r=this;if(!o.isValid(e))throw new Error("invalid scalar: out of range");if(e===Mp||r.is0())return S.ZERO;if(e===$p)return r;if(A.hasCache(this))return this.multiply(e);if(n){const{k1neg:t,k1:o,k2neg:i,k2:s}=b(e),{p1:a,p2:c}=function(e,t,n,r){let o=t,i=e.ZERO,s=e.ZERO;for(;n>Za||r>Za;)n&Ya&&(i=i.add(o)),r&Ya&&(s=s.add(o)),o=o.double(),n>>=Ya,r>>=Ya;return{p1:i,p2:s}}(S,r,o,s);return E(n.beta,a,c,t,i)}return A.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===$p||(e?e(S,this):A.unsafe(this,a).is0())}clearCofactor(){const{clearCofactor:e}=t;return s===$p?this:e?e(S,this):this.multiplyUnsafe(s)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}toBytes(e=!0){return la(e,"isCompressed"),this.assertValidity(),h(S,this,e)}toHex(e=!0){return ms(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 ec(S,e)}static msm(e,t){return uc(S,o,e,t)}static fromPrivateKey(e){return S.BASE.multiply(Gp(o,e))}}S.BASE=new S(i.Gx,i.Gy,r.ONE),S.ZERO=new S(r.ZERO,r.ONE,r.ZERO),S.Fp=r,S.Fn=o;const T=o.BITS,A=new cc(S,t.endo?Math.ceil(T/2):T);return S.BASE.precompute(8),S}function jp(e){return Uint8Array.of(e?2:3)}function Hp(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function Vp(e,t={}){const{Fn:n}=e,r=t.randomBytes||Cs,o=Object.assign(Hp(e.Fp,n),{seed:Qa(n.ORDER)});function i(e){try{return!!Gp(n,e)}catch(e){return!1}}function s(e=r(o.seed)){return function(e,t,n=!1){const r=e.length,o=Xa(t),i=Qa(t);if(r<16||r<i||r>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+r);const s=La(n?ga(e):pa(e),t-Ba)+Ba;return n?ya(s,o):ma(s,o)}(ha(e,o.seed,"seed"),n.ORDER)}function a(t,r=!0){return e.BASE.multiply(Gp(n,t)).toBytes(r)}function c(t){if("bigint"==typeof t)return!1;if(t instanceof e)return!0;const{secretKey:r,publicKey:i,publicKeyUncompressed:s}=o;if(n.allowedLengths||r===i)return;const a=wa("key",t).length;return a===i||a===s}const u={isValidSecretKey:i,isValidPublicKey:function(t,n){const{publicKey:r,publicKeyUncompressed:i}=o;try{const o=t.length;return(!0!==n||o===r)&&((!1!==n||o===i)&&!!e.fromBytes(t))}catch(e){return!1}},randomSecretKey:s,isValidPrivateKey:i,randomPrivateKey:s,normPrivateKeyToScalar:e=>Gp(n,e),precompute:(t=8,n=e.BASE)=>n.precompute(t,!1)};return Object.freeze({getPublicKey:a,getSharedSecret:function(t,r,o=!0){if(!0===c(t))throw new Error("first arg must be private key");if(!1===c(r))throw new Error("second arg must be public key");const i=Gp(n,t);return e.fromHex(r).multiply(i).toBytes(o)},keygen:function(e){const t=s(e);return{secretKey:t,publicKey:a(t)}},Point:e,utils:u,lengths:o})}function Xp(e,t,n={}){us(t),Ta(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const r=n.randomBytes||Cs,o=n.hmac||((e,...n)=>Dp(t,e,Is(...n))),{Fp:i,Fn:s}=e,{ORDER:a,BITS:c}=s,{keygen:u,getPublicKey:l,getSharedSecret:h,utils:d,lengths:f}=Vp(e,n),p={prehash:!1,lowS:"boolean"==typeof n.lowS&&n.lowS,format:void 0,extraEntropy:!1},g="compact";function m(e){return e>a>>$p}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=g){let n;if(function(e,t){Rp(t);const n=f.signature;ha(e,"compact"===t?n:"recovered"===t?n+1:void 0,`${t} signature`)}(e,t),"der"===t){const{r:t,s:n}=Fp.toSig(ha(e));return new w(t,n)}"recovered"===t&&(n=e[0],t="compact",e=e.subarray(1));const r=s.BYTES,o=e.subarray(0,r),i=e.subarray(r,2*r);return new w(s.fromBytes(o),s.fromBytes(i),n)}static fromHex(e,t){return this.fromBytes(Ts(e),t)}addRecoveryBit(e){return new w(this.r,this.s,e)}recoverPublicKey(t){const n=i.ORDER,{r:r,s:o,recovery:c}=this;if(null==c||![0,1,2,3].includes(c))throw new Error("recovery id invalid");if(a*qp<n&&c>1)throw new Error("recovery id is ambiguous for h>1 curve");const u=2===c||3===c?r+a:r;if(!i.isValid(u))throw new Error("recovery id 2 or 3 invalid");const l=i.toBytes(u),h=e.fromBytes(Is(jp(!(1&c)),l)),d=s.inv(u),f=k(wa("msgHash",t)),p=s.create(-f*d),g=s.create(o*d),m=e.BASE.multiplyUnsafe(p).add(h.multiplyUnsafe(g));if(m.is0())throw new Error("point at infinify");return m.assertValidity(),m}hasHighS(){return m(this.s)}toBytes(e=g){if(Rp(e),"der"===e)return Ts(Fp.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 Is(Uint8Array.of(this.recovery),t,n)}return Is(t,n)}toHex(e){return ms(this.toBytes(e))}assertValidity(){}static fromCompact(e){return w.fromBytes(wa("sig",e),"compact")}static fromDER(e){return w.fromBytes(wa("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 ms(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return ms(this.toBytes("compact"))}}const b=n.bits2int||function(e){if(e.length>8192)throw new Error("input is too large");const t=pa(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=Sa(c);function E(e){return va("num < 2^"+c,e,Mp,v),s.toBytes(e)}function S(e,n){return ha(e,void 0,"message"),n?ha(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,i,a={}){n=wa("message",n);const{seed:c,k2sig:u}=function(t,n,o){if(["recovered","canonical"].some(e=>e in o))throw new Error("sign() legacy options not supported");const{lowS:i,prehash:a,extraEntropy:c}=Lp(o,p);t=S(t,a);const u=k(t),l=Gp(s,n),h=[E(l),E(u)];if(null!=c&&!1!==c){const e=!0===c?r(f.secretKey):c;h.push(wa("extraEntropy",e))}const d=Is(...h),g=u;return{seed:d,k2sig:function(t){const n=b(t);if(!s.isValidNot0(n))return;const r=s.inv(n),o=e.BASE.multiply(n).toAffine(),a=s.create(o.x);if(a===Mp)return;const c=s.create(r*s.create(g+a*l));if(c===Mp)return;let u=(o.x===a?0:2)|Number(o.y&$p),h=c;return i&&m(c)&&(h=s.neg(c),u^=1),new w(a,h,u)}}}(n,i,a);return function(e,t,n){if("number"!=typeof e||e<2)throw new Error("hashLen must be a number");if("number"!=typeof t||t<2)throw new Error("qByteLen must be a number");if("function"!=typeof n)throw new Error("hmacFn must be a function");const r=e=>new Uint8Array(e),o=e=>Uint8Array.of(e);let i=r(e),s=r(e),a=0;const c=()=>{i.fill(1),s.fill(0),a=0},u=(...e)=>n(s,i,...e),l=(e=r(0))=>{s=u(o(0),e),i=u(),0!==e.length&&(s=u(o(1),e),i=u())},h=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let e=0;const n=[];for(;e<t;){i=u();const t=i.slice();n.push(t),e+=i.length}return Is(...n)};return(e,t)=>{let n;for(c(),l(e);!(n=t(h()));)l();return c(),n}}(t.outputLen,s.BYTES,o)(c,u)},verify:function(t,n,r,o={}){const{lowS:i,prehash:a,format:c}=Lp(o,p);if(r=wa("publicKey",r),n=S(wa("message",n),a),"strict"in o)throw new Error("options.strict was renamed to lowS");const u=void 0===c?function(e){let t;const n="string"==typeof e||ss(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(wa("sig",e),"der")}catch(e){if(!(e instanceof Fp.Err))throw e}if(!t)try{t=w.fromBytes(wa("sig",e),"compact")}catch(e){return!1}}return t||!1}(t):w.fromBytes(wa("sig",t),c);if(!1===u)return!1;try{const t=e.fromBytes(r);if(i&&u.hasHighS())return!1;const{r:o,s:a}=u,c=k(n),l=s.inv(a),h=s.create(c*l),d=s.create(o*l),f=e.BASE.multiplyUnsafe(h).add(t.multiplyUnsafe(d));if(f.is0())return!1;return s.create(f.x)===o}catch(e){return!1}},recoverPublicKey:function(e,t,n={}){const{prehash:r}=Lp(n,p);return t=S(t,r),w.fromBytes(e,"recovered").recoverPublicKey(t).toBytes()},Signature:w,hash:t})}function Qp(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:Va(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 Zp(e){const{CURVE:t,curveOpts:n,hash:r,ecdsaOpts:o}=Qp(e);return function(e,t){const n=t.Point;return Object.assign({},t,{ProjectivePoint:n,CURVE:Object.assign({},e,Ha(n.Fn.ORDER,n.Fn.BITS))})}(e,Xp(Wp(t,n),r,o))}const Yp={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Jp={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},eg=BigInt(2);const tg=Va(Yp.p,{sqrt:function(e){const t=Yp.p,n=BigInt(3),r=BigInt(6),o=BigInt(11),i=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),u=e*e*e%t,l=u*u*e%t,h=Oa(l,n,t)*l%t,d=Oa(h,n,t)*l%t,f=Oa(d,eg,t)*u%t,p=Oa(f,o,t)*f%t,g=Oa(p,i,t)*p%t,m=Oa(g,a,t)*g%t,y=Oa(m,c,t)*m%t,w=Oa(y,a,t)*g%t,b=Oa(w,n,t)*l%t,k=Oa(b,s,t)*p%t,v=Oa(k,r,t)*u%t,E=Oa(v,eg,t);if(!tg.eql(tg.sqr(E),e))throw new Error("Cannot find square root");return E}}),ng=function(e,t){const n=t=>Zp({...e,hash:t});return{...n(t),create:n}}({...Yp,Fp:tg,lowS:!0,endo:Jp},sa);Cc.utils.randomPrivateKey;const rg=()=>{const e=Cc.utils.randomPrivateKey(),t=og(e),n=new Uint8Array(64);return n.set(e),n.set(t,32),{publicKey:t,secretKey:n}},og=Cc.getPublicKey;function ig(e){try{return Cc.ExtendedPoint.fromHex(e),!0}catch{return!1}}const sg=Cc.verify,ag=e=>os.Buffer.isBuffer(e)?e:e instanceof Uint8Array?os.Buffer.from(e.buffer,e.byteOffset,e.byteLength):os.Buffer.from(e);class cg{constructor(e){Object.assign(this,e)}encode(){return os.Buffer.from(gu.serialize(ug,this))}static decode(e){return gu.deserialize(ug,this,e)}static decodeUnchecked(e){return gu.deserializeUnchecked(ug,this,e)}}const ug=new Map;var lg;const hg=32;let dg=1;class fg extends cg{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=Hc.decode(e);if(t.length!=hg)throw new Error("Invalid public key input");this._bn=new qc(t)}else this._bn=new qc(e);if(this._bn.byteLength()>hg)throw new Error("Invalid public key input")}}static unique(){const e=new fg(dg);return dg+=1,new fg(e.toBuffer())}equals(e){return this._bn.eq(e._bn)}toBase58(){return Hc.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(os.Buffer);if(e.length===hg)return e;const t=os.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=os.Buffer.concat([e.toBuffer(),os.Buffer.from(t),n.toBuffer()]),o=Vc(r);return new fg(o)}static createProgramAddressSync(e,t){let n=os.Buffer.alloc(0);e.forEach(function(e){if(e.length>32)throw new TypeError("Max seed length exceeded");n=os.Buffer.concat([n,ag(e)])}),n=os.Buffer.concat([n,t.toBuffer(),os.Buffer.from("ProgramDerivedAddress")]);const r=Vc(n);if(ig(r))throw new Error("Invalid seeds, address must fall off the curve");return new fg(r)}static async createProgramAddress(e,t){return this.createProgramAddressSync(e,t)}static findProgramAddressSync(e,t){let n,r=255;for(;0!=r;){try{const o=e.concat(os.Buffer.from([r]));n=this.createProgramAddressSync(o,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 ig(new fg(e).toBytes())}}lg=fg,fg.default=new lg("11111111111111111111111111111111"),ug.set(fg,{kind:"struct",fields:[["_bn","u256"]]}),new fg("BPFLoader1111111111111111111111111111111111");const pg=1232;class gg extends Error{constructor(e){super(`Signature ${e} has expired: block height exceeded.`),this.signature=void 0,this.signature=e}}Object.defineProperty(gg.prototype,"name",{value:"TransactionExpiredBlockheightExceededError"});class mg 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(mg.prototype,"name",{value:"TransactionExpiredTimeoutError"});class yg extends Error{constructor(e){super(`Signature ${e} has expired: the nonce is no longer valid.`),this.signature=void 0,this.signature=e}}Object.defineProperty(yg.prototype,"name",{value:"TransactionExpiredNonceInvalidError"});class wg{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 bg=(e="publicKey")=>bu.blob(32,e),kg=(e="string")=>{const t=bu.struct([bu.u32("length"),bu.u32("lengthPadding"),bu.blob(bu.offset(bu.u32(),-8),"chars")],e),n=t.decode.bind(t),r=t.encode.bind(t),o=t;return o.decode=(e,t)=>n(e,t).chars.toString(),o.encode=(e,t,n)=>{const o={chars:os.Buffer.from(e,"utf8")};return r(o,t,n)},o.alloc=e=>bu.u32().span+bu.u32().span+os.Buffer.from(e,"utf8").length,o};function vg(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 vg({layout:e},t[e.property]);return 0};let r=0;return e.layout.fields.forEach(e=>{r+=n(e)}),r}function Eg(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 Sg(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 Tg(e,t){if(!e)throw new Error(t||"Assertion failed")}class Ag{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},o=r(t);o.isSigner=!0,o.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 Ag(t,n)}getMessageComponents(){const e=[...this.keyMetaMap.entries()];Tg(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),o=e.filter(([,e])=>!e.isSigner&&!e.isWritable),i={numRequiredSignatures:t.length+n.length,numReadonlySignedAccounts:n.length,numReadonlyUnsignedAccounts:o.length};{Tg(t.length>0,"Expected at least one writable signer key");const[e]=t[0];Tg(e===this.payer.toBase58(),"Expected first writable signer key to be the fee payer")}return[i,[...t.map(([e])=>new fg(e)),...n.map(([e])=>new fg(e)),...r.map(([e])=>new fg(e)),...o.map(([e])=>new fg(e))]]}extractTableLookup(e){const[t,n]=this.drainKeysFoundInLookupTable(e.state.addresses,e=>!e.isSigner&&!e.isInvoked&&e.isWritable),[r,o]=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:o}]}drainKeysFoundInLookupTable(e,t){const n=new Array,r=new Array;for(const[o,i]of this.keyMetaMap.entries())if(t(i)){const t=new fg(o),i=e.findIndex(e=>e.equals(t));i>=0&&(Tg(i<256,"Max lookup table index exceeded"),n.push(i),r.push(t),this.keyMetaMap.delete(o))}return[n,r]}}const Ig="Reached end of buffer unexpectedly";function Bg(e){if(0===e.length)throw new Error(Ig);return e.shift()}function xg(e,...t){const[n]=t;if(2===t.length?n+(t[1]??0)>e.length:n>=e.length)throw new Error(Ig);return e.splice(...t)}class Cg{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 fg(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:Hc.decode(e.data)}))}get addressTableLookups(){return[]}getAccountKeys(){return new wg(this.staticAccountKeys)}static compile(e){const t=Ag.compile(e.instructions,e.payerKey),[n,r]=t.getMessageComponents(),o=new wg(r).compileInstructions(e.instructions).map(e=>({programIdIndex:e.programIdIndex,accounts:e.accountKeyIndexes,data:Hc.encode(e.data)}));return new Cg({header:n,accountKeys:r,recentBlockhash:e.recentBlockhash,instructions:o})}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=[];Sg(t,e);const n=this.instructions.map(e=>{const{accounts:t,programIdIndex:n}=e,r=Array.from(Hc.decode(e.data));let o=[];Sg(o,t.length);let i=[];return Sg(i,r.length),{programIdIndex:n,keyIndicesCount:os.Buffer.from(o),keyIndices:t,dataLength:os.Buffer.from(i),data:r}});let r=[];Sg(r,n.length);let o=os.Buffer.alloc(pg);os.Buffer.from(r).copy(o);let i=r.length;n.forEach(e=>{const t=bu.struct([bu.u8("programIdIndex"),bu.blob(e.keyIndicesCount.length,"keyIndicesCount"),bu.seq(bu.u8("keyIndex"),e.keyIndices.length,"keyIndices"),bu.blob(e.dataLength.length,"dataLength"),bu.seq(bu.u8("userdatum"),e.data.length,"data")]).encode(e,o,i);i+=t}),o=o.slice(0,i);const s=bu.struct([bu.blob(1,"numRequiredSignatures"),bu.blob(1,"numReadonlySignedAccounts"),bu.blob(1,"numReadonlyUnsignedAccounts"),bu.blob(t.length,"keyCount"),bu.seq(bg("key"),e,"keys"),bg("recentBlockhash")]),a={numRequiredSignatures:os.Buffer.from([this.header.numRequiredSignatures]),numReadonlySignedAccounts:os.Buffer.from([this.header.numReadonlySignedAccounts]),numReadonlyUnsignedAccounts:os.Buffer.from([this.header.numReadonlyUnsignedAccounts]),keyCount:os.Buffer.from(t),keys:this.accountKeys.map(e=>ag(e.toBytes())),recentBlockhash:Hc.decode(this.recentBlockhash)};let c=os.Buffer.alloc(2048);const u=s.encode(a,c);return o.copy(c,u),c.slice(0,u+o.length)}static from(e){let t=[...e];const n=Bg(t);if(n!==(127&n))throw new Error("Versioned messages must be deserialized with VersionedMessage.deserialize()");const r=Bg(t),o=Bg(t),i=Eg(t);let s=[];for(let e=0;e<i;e++){const e=xg(t,0,hg);s.push(new fg(os.Buffer.from(e)))}const a=xg(t,0,hg),c=Eg(t);let u=[];for(let e=0;e<c;e++){const e=Bg(t),n=xg(t,0,Eg(t)),r=xg(t,0,Eg(t)),o=Hc.encode(os.Buffer.from(r));u.push({programIdIndex:e,accounts:n,data:o})}const l={header:{numRequiredSignatures:n,numReadonlySignedAccounts:r,numReadonlyUnsignedAccounts:o},recentBlockhash:Hc.encode(os.Buffer.from(a)),accountKeys:s,instructions:u};return new Cg(l)}}class Pg{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 wg(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=Ag.compile(e.instructions,e.payerKey),n=new Array,r={writable:new Array,readonly:new Array},o=e.addressLookupTableAccounts||[];for(const e of o){const o=t.extractTableLookup(e);if(void 0!==o){const[e,{writable:t,readonly:i}]=o;n.push(e),r.writable.push(...t),r.readonly.push(...i)}}const[i,s]=t.getMessageComponents(),a=new wg(s,r).compileInstructions(e.instructions);return new Pg({header:i,staticAccountKeys:s,recentBlockhash:e.recentBlockhash,compiledInstructions:a,addressTableLookups:n})}serialize(){const e=Array();Sg(e,this.staticAccountKeys.length);const t=this.serializeInstructions(),n=Array();Sg(n,this.compiledInstructions.length);const r=this.serializeAddressTableLookups(),o=Array();Sg(o,this.addressTableLookups.length);const i=bu.struct([bu.u8("prefix"),bu.struct([bu.u8("numRequiredSignatures"),bu.u8("numReadonlySignedAccounts"),bu.u8("numReadonlyUnsignedAccounts")],"header"),bu.blob(e.length,"staticAccountKeysLength"),bu.seq(bg(),this.staticAccountKeys.length,"staticAccountKeys"),bg("recentBlockhash"),bu.blob(n.length,"instructionsLength"),bu.blob(t.length,"serializedInstructions"),bu.blob(o.length,"addressTableLookupsLength"),bu.blob(r.length,"serializedAddressTableLookups")]),s=new Uint8Array(pg),a=i.encode({prefix:128,header:this.header,staticAccountKeysLength:new Uint8Array(e),staticAccountKeys:this.staticAccountKeys.map(e=>e.toBytes()),recentBlockhash:Hc.decode(this.recentBlockhash),instructionsLength:new Uint8Array(n),serializedInstructions:t,addressTableLookupsLength:new Uint8Array(o),serializedAddressTableLookups:r},s);return s.slice(0,a)}serializeInstructions(){let e=0;const t=new Uint8Array(pg);for(const n of this.compiledInstructions){const r=Array();Sg(r,n.accountKeyIndexes.length);const o=Array();Sg(o,n.data.length);e+=bu.struct([bu.u8("programIdIndex"),bu.blob(r.length,"encodedAccountKeyIndexesLength"),bu.seq(bu.u8(),n.accountKeyIndexes.length,"accountKeyIndexes"),bu.blob(o.length,"encodedDataLength"),bu.blob(n.data.length,"data")]).encode({programIdIndex:n.programIdIndex,encodedAccountKeyIndexesLength:new Uint8Array(r),accountKeyIndexes:n.accountKeyIndexes,encodedDataLength:new Uint8Array(o),data:n.data},t,e)}return t.slice(0,e)}serializeAddressTableLookups(){let e=0;const t=new Uint8Array(pg);for(const n of this.addressTableLookups){const r=Array();Sg(r,n.writableIndexes.length);const o=Array();Sg(o,n.readonlyIndexes.length);e+=bu.struct([bg("accountKey"),bu.blob(r.length,"encodedWritableIndexesLength"),bu.seq(bu.u8(),n.writableIndexes.length,"writableIndexes"),bu.blob(o.length,"encodedReadonlyIndexesLength"),bu.seq(bu.u8(),n.readonlyIndexes.length,"readonlyIndexes")]).encode({accountKey:n.accountKey.toBytes(),encodedWritableIndexesLength:new Uint8Array(r),writableIndexes:n.writableIndexes,encodedReadonlyIndexesLength:new Uint8Array(o),readonlyIndexes:n.readonlyIndexes},t,e)}return t.slice(0,e)}static deserialize(e){let t=[...e];const n=Bg(t),r=127&n;Tg(n!==r,"Expected versioned message but received legacy message");Tg(0===r,`Expected versioned message with version 0 but found version ${r}`);const o={numRequiredSignatures:Bg(t),numReadonlySignedAccounts:Bg(t),numReadonlyUnsignedAccounts:Bg(t)},i=[],s=Eg(t);for(let e=0;e<s;e++)i.push(new fg(xg(t,0,hg)));const a=Hc.encode(xg(t,0,hg)),c=Eg(t),u=[];for(let e=0;e<c;e++){const e=Bg(t),n=xg(t,0,Eg(t)),r=Eg(t),o=new Uint8Array(xg(t,0,r));u.push({programIdIndex:e,accountKeyIndexes:n,data:o})}const l=Eg(t),h=[];for(let e=0;e<l;e++){const e=new fg(xg(t,0,hg)),n=xg(t,0,Eg(t)),r=xg(t,0,Eg(t));h.push({accountKey:e,writableIndexes:n,readonlyIndexes:r})}return new Pg({header:o,staticAccountKeys:i,recentBlockhash:a,compiledInstructions:u,addressTableLookups:h})}}let Ng=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 _g=os.Buffer.alloc(64).fill(0);class Dg{constructor(e){this.keys=void 0,this.programId=void 0,this.data=os.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 Ug{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 Dg(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=[],o=[];t.forEach(e=>{e.keys.forEach(e=>{o.push({...e})});const t=e.programId.toString();r.includes(t)||r.push(t)}),r.forEach(e=>{o.push({pubkey:new fg(e),isSigner:!1,isWritable:!1})});const i=[];o.forEach(e=>{const t=e.pubkey.toString(),n=i.findIndex(e=>e.pubkey.toString()===t);n>-1?(i[n].isWritable=i[n].isWritable||e.isWritable,i[n].isSigner=i[n].isSigner||e.isSigner):i.push(e)}),i.sort(function(e,t){if(e.isSigner!==t.isSigner)return e.isSigner?-1:1;if(e.isWritable!==t.isWritable)return e.isWritable?-1:1;return e.pubkey.toBase58().localeCompare(t.pubkey.toBase58(),"en",{localeMatcher:"best fit",usage:"sort",sensitivity:"variant",ignorePunctuation:!1,numeric:!1,caseFirst:"lower"})});const s=i.findIndex(e=>e.pubkey.equals(n));if(s>-1){const[e]=i.splice(s,1);e.isSigner=!0,e.isWritable=!0,i.unshift(e)}else i.unshift({pubkey:n,isSigner:!0,isWritable:!0});for(const e of this.signatures){const t=i.findIndex(t=>t.pubkey.equals(e.publicKey));if(!(t>-1))throw new Error(`unknown signer: ${e.publicKey.toString()}`);i[t].isSigner||(i[t].isSigner=!0)}let a=0,c=0,u=0;const l=[],h=[];i.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:Hc.encode(t)}});return f.forEach(e=>{Tg(e.programIdIndex>=0),e.accounts.forEach(e=>Tg(e>=0))}),new Cg({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)=>Cc.sign(e,t.slice(0,32)))(n,e.secretKey);this._addSignature(e.publicKey,ag(t))})}addSignature(e,t){this._compile(),this._addSignature(e,t)}_addSignature(e,t){Tg(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=os.Buffer.from(t)}verifySignatures(e=!0){return!this._getMessageSignednessErrors(this.serializeMessage(),e)}_getMessageSignednessErrors(e,t){const n={};for(const{signature:r,publicKey:o}of this.signatures)null===r?t&&(n.missing||=[]).push(o):sg(r,e,o.toBytes())||(n.invalid||=[]).push(o);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=[];Sg(n,t.length);const r=n.length+64*t.length+e.length,o=os.Buffer.alloc(r);return Tg(t.length<256),os.Buffer.from(n).copy(o,0),t.forEach(({signature:e},t)=>{null!==e&&(Tg(64===e.length,"signature has invalid length"),os.Buffer.from(e).copy(o,n.length+64*t))}),e.copy(o,n.length+64*t.length),Tg(o.length<=pg,`Transaction too large: ${o.length} > 1232`),o}get keys(){return Tg(1===this.instructions.length),this.instructions[0].keys.map(e=>e.pubkey)}get programId(){return Tg(1===this.instructions.length),this.instructions[0].programId}get data(){return Tg(1===this.instructions.length),this.instructions[0].data}static from(e){let t=[...e];const n=Eg(t);let r=[];for(let e=0;e<n;e++){const e=xg(t,0,64);r.push(Hc.encode(os.Buffer.from(e)))}return Ug.populate(Cg.from(t),r)}static populate(e,t=[]){const n=new Ug;return n.recentBlockhash=e.recentBlockhash,e.header.numRequiredSignatures>0&&(n.feePayer=e.accountKeys[0]),t.forEach((t,r)=>{const o={signature:t==Hc.encode(_g)?null:Hc.decode(t),publicKey:e.accountKeys[r]};n.signatures.push(o)}),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 Dg({keys:r,programId:e.accountKeys[t.programIdIndex],data:Hc.decode(t.data)}))}),n._message=e,n._json=n.toJSON(),n}}new fg("SysvarC1ock11111111111111111111111111111111"),new fg("SysvarEpochSchedu1e111111111111111111111111"),new fg("Sysvar1nstructions1111111111111111111111111");const Rg=new fg("SysvarRecentB1ockHashes11111111111111111111"),Lg=new fg("SysvarRent111111111111111111111111111111111");new fg("SysvarRewards111111111111111111111111111111"),new fg("SysvarS1otHashes111111111111111111111111111"),new fg("SysvarS1otHistory11111111111111111111111111"),new fg("SysvarStakeHistory1111111111111111111111111");class Og extends Error{constructor({action:e,signature:t,transactionMessage:n,logs:r}){const o=r?`Logs: \n${JSON.stringify(r.slice(-10),null,2)}. `:"",i="\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}. `+o+i;break;case"simulate":s=`Simulation failed. \nMessage: ${n}. \n`+o+i;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 Fg 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 Mg(e){return new Promise(t=>setTimeout(t,e))}function $g(e,t){const n=e.layout.span>=0?e.layout.span:vg(e,t),r=os.Buffer.alloc(n),o=Object.assign({instruction:e.index},t);return e.layout.encode(o,r),r}const qg=bu.nu64("lamportsPerSignature"),Kg=bu.struct([bu.u32("version"),bu.u32("state"),bg("authorizedPubkey"),bg("nonce"),bu.struct([qg],"feeCalculator")]),zg=Kg.span;class Gg{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=Kg.decode(ag(e),0);return new Gg({authorizedPubkey:new fg(t.authorizedPubkey),nonce:new fg(t.nonce).toString(),feeCalculator:t.feeCalculator})}}function Wg(e){const t=bu.blob(8,e),n=t.decode.bind(t),r=t.encode.bind(t),o=t,i=zf();return o.decode=(e,t)=>{const r=n(e,t);return i.decode(r)},o.encode=(e,t,n)=>{const o=i.encode(e);return r(o,t,n)},o}const jg=Object.freeze({Create:{index:0,layout:bu.struct([bu.u32("instruction"),bu.ns64("lamports"),bu.ns64("space"),bg("programId")])},Assign:{index:1,layout:bu.struct([bu.u32("instruction"),bg("programId")])},Transfer:{index:2,layout:bu.struct([bu.u32("instruction"),Wg("lamports")])},CreateWithSeed:{index:3,layout:bu.struct([bu.u32("instruction"),bg("base"),kg("seed"),bu.ns64("lamports"),bu.ns64("space"),bg("programId")])},AdvanceNonceAccount:{index:4,layout:bu.struct([bu.u32("instruction")])},WithdrawNonceAccount:{index:5,layout:bu.struct([bu.u32("instruction"),bu.ns64("lamports")])},InitializeNonceAccount:{index:6,layout:bu.struct([bu.u32("instruction"),bg("authorized")])},AuthorizeNonceAccount:{index:7,layout:bu.struct([bu.u32("instruction"),bg("authorized")])},Allocate:{index:8,layout:bu.struct([bu.u32("instruction"),bu.ns64("space")])},AllocateWithSeed:{index:9,layout:bu.struct([bu.u32("instruction"),bg("base"),kg("seed"),bu.ns64("space"),bg("programId")])},AssignWithSeed:{index:10,layout:bu.struct([bu.u32("instruction"),bg("base"),kg("seed"),bg("programId")])},TransferWithSeed:{index:11,layout:bu.struct([bu.u32("instruction"),Wg("lamports"),kg("seed"),bg("programId")])},UpgradeNonceAccount:{index:12,layout:bu.struct([bu.u32("instruction")])}});class Hg{constructor(){}static createAccount(e){const t=$g(jg.Create,{lamports:e.lamports,space:e.space,programId:ag(e.programId.toBuffer())});return new Dg({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=$g(jg.TransferWithSeed,{lamports:BigInt(e.lamports),seed:e.seed,programId:ag(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=$g(jg.Transfer,{lamports:BigInt(e.lamports)}),n=[{pubkey:e.fromPubkey,isSigner:!0,isWritable:!0},{pubkey:e.toPubkey,isSigner:!1,isWritable:!0}]}return new Dg({keys:n,programId:this.programId,data:t})}static assign(e){let t,n;if("basePubkey"in e){t=$g(jg.AssignWithSeed,{base:ag(e.basePubkey.toBuffer()),seed:e.seed,programId:ag(e.programId.toBuffer())}),n=[{pubkey:e.accountPubkey,isSigner:!1,isWritable:!0},{pubkey:e.basePubkey,isSigner:!0,isWritable:!1}]}else{t=$g(jg.Assign,{programId:ag(e.programId.toBuffer())}),n=[{pubkey:e.accountPubkey,isSigner:!0,isWritable:!0}]}return new Dg({keys:n,programId:this.programId,data:t})}static createAccountWithSeed(e){const t=$g(jg.CreateWithSeed,{base:ag(e.basePubkey.toBuffer()),seed:e.seed,lamports:e.lamports,space:e.space,programId:ag(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 Dg({keys:n,programId:this.programId,data:t})}static createNonceAccount(e){const t=new Ug;"basePubkey"in e&&"seed"in e?t.add(Hg.createAccountWithSeed({fromPubkey:e.fromPubkey,newAccountPubkey:e.noncePubkey,basePubkey:e.basePubkey,seed:e.seed,lamports:e.lamports,space:zg,programId:this.programId})):t.add(Hg.createAccount({fromPubkey:e.fromPubkey,newAccountPubkey:e.noncePubkey,lamports:e.lamports,space:zg,programId:this.programId}));const n={noncePubkey:e.noncePubkey,authorizedPubkey:e.authorizedPubkey};return t.add(this.nonceInitialize(n)),t}static nonceInitialize(e){const t=$g(jg.InitializeNonceAccount,{authorized:ag(e.authorizedPubkey.toBuffer())}),n={keys:[{pubkey:e.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:Rg,isSigner:!1,isWritable:!1},{pubkey:Lg,isSigner:!1,isWritable:!1}],programId:this.programId,data:t};return new Dg(n)}static nonceAdvance(e){const t=$g(jg.AdvanceNonceAccount),n={keys:[{pubkey:e.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:Rg,isSigner:!1,isWritable:!1},{pubkey:e.authorizedPubkey,isSigner:!0,isWritable:!1}],programId:this.programId,data:t};return new Dg(n)}static nonceWithdraw(e){const t=$g(jg.WithdrawNonceAccount,{lamports:e.lamports});return new Dg({keys:[{pubkey:e.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:e.toPubkey,isSigner:!1,isWritable:!0},{pubkey:Rg,isSigner:!1,isWritable:!1},{pubkey:Lg,isSigner:!1,isWritable:!1},{pubkey:e.authorizedPubkey,isSigner:!0,isWritable:!1}],programId:this.programId,data:t})}static nonceAuthorize(e){const t=$g(jg.AuthorizeNonceAccount,{authorized:ag(e.newAuthorizedPubkey.toBuffer())});return new Dg({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=$g(jg.AllocateWithSeed,{base:ag(e.basePubkey.toBuffer()),seed:e.seed,space:e.space,programId:ag(e.programId.toBuffer())}),n=[{pubkey:e.accountPubkey,isSigner:!1,isWritable:!0},{pubkey:e.basePubkey,isSigner:!0,isWritable:!1}]}else{t=$g(jg.Allocate,{space:e.space}),n=[{pubkey:e.accountPubkey,isSigner:!0,isWritable:!0}]}return new Dg({keys:n,programId:this.programId,data:t})}}function Vg(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Xg,Qg;function Zg(){if(Qg)return Xg;Qg=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,o){var i,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(),o);if("[object Array]"===(h=e.call(r))){for(a="[",s=r.length-1,i=0;i<s;i++)a+=n(r[i],!0)+",";return s>-1&&(a+=n(r[i],!0)),a+"]"}if("[object Object]"===h){for(s=(c=t(r).sort()).length,a="",i=0;i<s;)void 0!==(l=n(r[u=c[i]],!1))&&(a&&(a+=","),a+=JSON.stringify(u)+":"+l),i++;return"{"+a+"}"}return JSON.stringify(r);case"function":case"undefined":return o?null:void 0;case"string":return JSON.stringify(r);default:return isFinite(r)?r:null}}return Xg=function(e){var t=n(e,!1);if(void 0!==t)return""+t}}Hg.programId=new fg("11111111111111111111111111111111"),new fg("BPFLoader2111111111111111111111111111111111");var Yg=Vg(Zg());function Jg(e){let t=0;for(;e>1;)e/=2,t++;return t}class em{constructor(e,t,n,r,o){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=o}getEpoch(e){return this.getEpochAndSlotIndex(e)[0]}getEpochAndSlotIndex(e){if(e<this.firstNormalSlot){const n=Jg(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)))-Jg(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+Jg(32)):this.slotsPerEpoch}}var tm=globalThis.fetch;class nm extends Np{constructor(e,t,n){super(e=>{const n=function(e,t){return new Cp(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 rm{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}(om,e),n=e.length-56;Tg(n>=0,"lookup table is invalid"),Tg(n%32==0,"lookup table is invalid");const r=n/32,{addresses:o}=bu.struct([bu.seq(bg(),r,"addresses")]).decode(e.slice(56));return{deactivationSlot:t.deactivationSlot,lastExtendedSlot:t.lastExtendedSlot,lastExtendedSlotStartIndex:t.lastExtendedStartIndex,authority:0!==t.authority.length?new fg(t.authority[0]):void 0,addresses:o.map(e=>new fg(e))}}}const om={index:1,layout:bu.struct([bu.u32("typeIndex"),Wg("deactivationSlot"),bu.nu64("lastExtendedSlot"),bu.u8("lastExtendedStartIndex"),bu.u8(),bu.seq(bg(),bu.offset(bu.u8(),-1),"authority")])},im=/^[^:]+:\/\/([^:[]+|\[[^\]]+\])(:\d+)?(.*)/i;const sm=gp(op(fg),lp(),e=>new fg(e)),am=hp([lp(),ip("base64")]),cm=gp(op(os.Buffer),am,e=>os.Buffer.from(e[0],"base64"));function um(e){let t,n;if("string"==typeof e)t=e;else if(e){const{commitment:r,...o}=e;t=r,n=o}return{commitment:t,config:n}}function lm(e){return e.map(e=>"memcmp"in e?{...e,memcmp:{...e.memcmp,encoding:e.memcmp.encoding??"base58"}}:e)}function hm(e){return fp([dp({jsonrpc:ip("2.0"),id:lp(),result:e}),dp({jsonrpc:ip("2.0"),id:lp(),error:dp({code:pp(),message:lp(),data:cp(tp("any",()=>!0))})})])}const dm=hm(pp());function fm(e){return gp(hm(e),dm,t=>"error"in t?t:{...t,result:Yf(t.result,e)})}function pm(e){return fm(dp({context:dp({slot:ap()}),value:e}))}function gm(e){return dp({context:dp({slot:ap()}),value:e})}function mm(e,t){return 0===e?new Pg({header:t.header,staticAccountKeys:t.accountKeys.map(e=>new fg(e)),recentBlockhash:t.recentBlockhash,compiledInstructions:t.instructions.map(e=>({programIdIndex:e.programIdIndex,accountKeyIndexes:e.accounts,data:Hc.decode(e.data)})),addressTableLookups:t.addressTableLookups}):new Cg(t)}const ym=dp({foundation:ap(),foundationTerm:ap(),initial:ap(),taper:ap(),terminal:ap()}),wm=fm(np(sp(dp({epoch:ap(),effectiveSlot:ap(),amount:ap(),postBalance:ap(),commission:cp(sp(ap()))})))),bm=np(dp({slot:ap(),prioritizationFee:ap()})),km=dp({total:ap(),validator:ap(),foundation:ap(),epoch:ap()}),vm=dp({epoch:ap(),slotIndex:ap(),slotsInEpoch:ap(),absoluteSlot:ap(),blockHeight:cp(ap()),transactionCount:cp(ap())}),Em=dp({slotsPerEpoch:ap(),leaderScheduleSlotOffset:ap(),warmup:rp(),firstNormalEpoch:ap(),firstNormalSlot:ap()}),Sm=up(lp(),np(ap())),Tm=sp(fp([dp({}),lp()])),Am=dp({err:Tm}),Im=ip("receivedSignature"),Bm=dp({"solana-core":lp(),"feature-set":cp(ap())}),xm=dp({program:lp(),programId:sm,parsed:pp()}),Cm=dp({programId:sm,accounts:np(sm),data:lp()}),Pm=pm(dp({err:sp(fp([dp({}),lp()])),logs:sp(np(lp())),accounts:cp(sp(np(sp(dp({executable:rp(),owner:lp(),lamports:ap(),data:np(lp()),rentEpoch:cp(ap())}))))),unitsConsumed:cp(ap()),returnData:cp(sp(dp({programId:lp(),data:hp([lp(),ip("base64")])}))),innerInstructions:cp(sp(np(dp({index:ap(),instructions:np(fp([xm,Cm]))}))))})),Nm=pm(dp({byIdentity:up(lp(),np(ap())),range:dp({firstSlot:ap(),lastSlot:ap()})}));const _m=fm(ym),Dm=fm(km),Um=fm(bm),Rm=fm(vm),Lm=fm(Em),Om=fm(Sm),Fm=fm(ap()),Mm=pm(dp({total:ap(),circulating:ap(),nonCirculating:ap(),nonCirculatingAccounts:np(sm)})),$m=dp({amount:lp(),uiAmount:sp(ap()),decimals:ap(),uiAmountString:cp(lp())}),qm=pm(np(dp({address:sm,amount:lp(),uiAmount:sp(ap()),decimals:ap(),uiAmountString:cp(lp())}))),Km=pm(np(dp({pubkey:sm,account:dp({executable:rp(),owner:sm,lamports:ap(),data:cm,rentEpoch:ap()})}))),zm=dp({program:lp(),parsed:pp(),space:ap()}),Gm=pm(np(dp({pubkey:sm,account:dp({executable:rp(),owner:sm,lamports:ap(),data:zm,rentEpoch:ap()})}))),Wm=pm(np(dp({lamports:ap(),address:sm}))),jm=dp({executable:rp(),owner:sm,lamports:ap(),data:cm,rentEpoch:ap()}),Hm=dp({pubkey:sm,account:jm}),Vm=gp(fp([op(os.Buffer),zm]),fp([am,zm]),e=>Array.isArray(e)?Yf(e,cm):e),Xm=dp({executable:rp(),owner:sm,lamports:ap(),data:Vm,rentEpoch:ap()}),Qm=dp({pubkey:sm,account:Xm}),Zm=dp({state:fp([ip("active"),ip("inactive"),ip("activating"),ip("deactivating")]),active:ap(),inactive:ap()}),Ym=fm(np(dp({signature:lp(),slot:ap(),err:Tm,memo:sp(lp()),blockTime:cp(sp(ap()))}))),Jm=fm(np(dp({signature:lp(),slot:ap(),err:Tm,memo:sp(lp()),blockTime:cp(sp(ap()))}))),ey=dp({subscription:ap(),result:gm(jm)}),ty=dp({pubkey:sm,account:jm}),ny=dp({subscription:ap(),result:gm(ty)}),ry=dp({parent:ap(),slot:ap(),root:ap()}),oy=dp({subscription:ap(),result:ry}),iy=fp([dp({type:fp([ip("firstShredReceived"),ip("completed"),ip("optimisticConfirmation"),ip("root")]),slot:ap(),timestamp:ap()}),dp({type:ip("createdBank"),parent:ap(),slot:ap(),timestamp:ap()}),dp({type:ip("frozen"),slot:ap(),timestamp:ap(),stats:dp({numTransactionEntries:ap(),numSuccessfulTransactions:ap(),numFailedTransactions:ap(),maxTransactionsPerEntry:ap()})}),dp({type:ip("dead"),slot:ap(),timestamp:ap(),err:lp()})]),sy=dp({subscription:ap(),result:iy}),ay=dp({subscription:ap(),result:gm(fp([Am,Im]))}),cy=dp({subscription:ap(),result:ap()}),uy=dp({pubkey:lp(),gossip:sp(lp()),tpu:sp(lp()),rpc:sp(lp()),version:sp(lp())}),ly=dp({votePubkey:lp(),nodePubkey:lp(),activatedStake:ap(),epochVoteAccount:rp(),epochCredits:np(hp([ap(),ap(),ap()])),commission:ap(),lastVote:ap(),rootSlot:sp(ap())}),hy=fm(dp({current:np(ly),delinquent:np(ly)})),dy=fp([ip("processed"),ip("confirmed"),ip("finalized")]),fy=dp({slot:ap(),confirmations:sp(ap()),err:Tm,confirmationStatus:cp(dy)}),py=pm(np(sp(fy))),gy=fm(ap()),my=dp({accountKey:sm,writableIndexes:np(ap()),readonlyIndexes:np(ap())}),yy=dp({signatures:np(lp()),message:dp({accountKeys:np(lp()),header:dp({numRequiredSignatures:ap(),numReadonlySignedAccounts:ap(),numReadonlyUnsignedAccounts:ap()}),instructions:np(dp({accounts:np(ap()),data:lp(),programIdIndex:ap()})),recentBlockhash:lp(),addressTableLookups:cp(np(my))})}),wy=dp({pubkey:sm,signer:rp(),writable:rp(),source:cp(fp([ip("transaction"),ip("lookupTable")]))}),by=dp({accountKeys:np(wy),signatures:np(lp())}),ky=dp({parsed:pp(),program:lp(),programId:sm}),vy=dp({accounts:np(sm),data:lp(),programId:sm}),Ey=gp(fp([vy,ky]),fp([dp({parsed:pp(),program:lp(),programId:lp()}),dp({accounts:np(lp()),data:lp(),programId:lp()})]),e=>Yf(e,"accounts"in e?vy:ky)),Sy=dp({signatures:np(lp()),message:dp({accountKeys:np(wy),instructions:np(Ey),recentBlockhash:lp(),addressTableLookups:cp(sp(np(my)))})}),Ty=dp({accountIndex:ap(),mint:lp(),owner:cp(lp()),programId:cp(lp()),uiTokenAmount:$m}),Ay=dp({writable:np(sm),readonly:np(sm)}),Iy=dp({err:Tm,fee:ap(),innerInstructions:cp(sp(np(dp({index:ap(),instructions:np(dp({accounts:np(ap()),data:lp(),programIdIndex:ap()}))})))),preBalances:np(ap()),postBalances:np(ap()),logMessages:cp(sp(np(lp()))),preTokenBalances:cp(sp(np(Ty))),postTokenBalances:cp(sp(np(Ty))),loadedAddresses:cp(Ay),computeUnitsConsumed:cp(ap()),costUnits:cp(ap())}),By=dp({err:Tm,fee:ap(),innerInstructions:cp(sp(np(dp({index:ap(),instructions:np(Ey)})))),preBalances:np(ap()),postBalances:np(ap()),logMessages:cp(sp(np(lp()))),preTokenBalances:cp(sp(np(Ty))),postTokenBalances:cp(sp(np(Ty))),loadedAddresses:cp(Ay),computeUnitsConsumed:cp(ap()),costUnits:cp(ap())}),xy=fp([ip(0),ip("legacy")]),Cy=dp({pubkey:lp(),lamports:ap(),postBalance:sp(ap()),rewardType:sp(lp()),commission:cp(sp(ap()))}),Py=fm(sp(dp({blockhash:lp(),previousBlockhash:lp(),parentSlot:ap(),transactions:np(dp({transaction:yy,meta:sp(Iy),version:cp(xy)})),rewards:cp(np(Cy)),blockTime:sp(ap()),blockHeight:sp(ap())}))),Ny=fm(sp(dp({blockhash:lp(),previousBlockhash:lp(),parentSlot:ap(),rewards:cp(np(Cy)),blockTime:sp(ap()),blockHeight:sp(ap())}))),_y=fm(sp(dp({blockhash:lp(),previousBlockhash:lp(),parentSlot:ap(),transactions:np(dp({transaction:by,meta:sp(Iy),version:cp(xy)})),rewards:cp(np(Cy)),blockTime:sp(ap()),blockHeight:sp(ap())}))),Dy=fm(sp(dp({blockhash:lp(),previousBlockhash:lp(),parentSlot:ap(),transactions:np(dp({transaction:Sy,meta:sp(By),version:cp(xy)})),rewards:cp(np(Cy)),blockTime:sp(ap()),blockHeight:sp(ap())}))),Uy=fm(sp(dp({blockhash:lp(),previousBlockhash:lp(),parentSlot:ap(),transactions:np(dp({transaction:by,meta:sp(By),version:cp(xy)})),rewards:cp(np(Cy)),blockTime:sp(ap()),blockHeight:sp(ap())}))),Ry=fm(sp(dp({blockhash:lp(),previousBlockhash:lp(),parentSlot:ap(),rewards:cp(np(Cy)),blockTime:sp(ap()),blockHeight:sp(ap())}))),Ly=fm(sp(dp({blockhash:lp(),previousBlockhash:lp(),parentSlot:ap(),transactions:np(dp({transaction:yy,meta:sp(Iy)})),rewards:cp(np(Cy)),blockTime:sp(ap())}))),Oy=fm(sp(dp({blockhash:lp(),previousBlockhash:lp(),parentSlot:ap(),signatures:np(lp()),blockTime:sp(ap())}))),Fy=fm(sp(dp({slot:ap(),meta:sp(Iy),blockTime:cp(sp(ap())),transaction:yy,version:cp(xy)}))),My=fm(sp(dp({slot:ap(),transaction:Sy,meta:sp(By),blockTime:cp(sp(ap())),version:cp(xy)}))),$y=pm(dp({blockhash:lp(),lastValidBlockHeight:ap()})),qy=pm(rp()),Ky=fm(np(dp({slot:ap(),numTransactions:ap(),numSlots:ap(),samplePeriodSecs:ap()}))),zy=pm(sp(dp({feeCalculator:dp({lamportsPerSignature:ap()})}))),Gy=fm(lp()),Wy=fm(lp()),jy=dp({err:Tm,logs:np(lp()),signature:lp()}),Hy=dp({result:gm(jy),subscription:ap()}),Vy={"solana-client":"js/1.0.0-maintenance"};class Xy{constructor(e,t){let n,r,o,i,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}=um(t),o=this._buildArgs([],n,void 0,r),i=Yg(o);return e[i]=e[i]??(async()=>{try{const e=Yf(await this._rpcRequest("getBlockHeight",o),fm(ap()));if("error"in e)throw new Fg(e.error,"failed to get block height information");return e.result}finally{delete e[i]}})(),await e[i]}})(),t&&"string"==typeof t?this._commitment=t:t&&(this._commitment=t.commitment,this._confirmTransactionInitialTimeout=t.confirmTransactionInitialTimeout,n=t.wsEndpoint,r=t.httpHeaders,o=t.fetch,i=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(im);if(null==t)throw TypeError(`Failed to validate endpoint URL \`${e}\``);const[n,r,o,i]=t,s=e.startsWith("https:")?"wss:":"ws:",a=null==o?null:parseInt(o.slice(1),10);return`${s}//${r}${null==a?"":`:${a+1}`}${i}`}(e),this._rpcClient=function(e,t,n,r,o){const i=n||tm;let s;return r&&(s=async(e,t)=>{const n=await new Promise((n,o)=>{try{r(e,t,(e,t)=>n([e,t]))}catch(e){o(e)}});return await i(...n)}),new Ep(async(n,r)=>{const a={method:"POST",body:n,agent:void 0,headers:Object.assign({"Content-Type":"application/json"},t||{},Vy)};try{let t,n=5,c=500;for(;t=s?await s(e,a):await i(e,a),429===t.status&&!0!==o&&(n-=1,0!==n);)await Mg(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,o,i,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 o=t.map(t=>e.request(t.methodName,t.args));e.request(o,(e,t)=>{e?r(e):n(t)})})}(this._rpcClient),this._rpcWebSocket=new nm(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}=um(t),o=this._buildArgs([e.toBase58()],n,void 0,r),i=Yf(await this._rpcRequest("getBalance",o),pm(ap()));if("error"in i)throw new Fg(i.error,`failed to get balance for ${e.toBase58()}`);return i.result}async getBalance(e,t){return await this.getBalanceAndContext(e,t).then(e=>e.value).catch(t=>{throw new Error("failed to get balance of account "+e.toBase58()+": "+t)})}async getBlockTime(e){const t=Yf(await this._rpcRequest("getBlockTime",[e]),fm(sp(ap())));if("error"in t)throw new Fg(t.error,`failed to get block time for slot ${e}`);return t.result}async getMinimumLedgerSlot(){const e=Yf(await this._rpcRequest("minimumLedgerSlot",[]),fm(ap()));if("error"in e)throw new Fg(e.error,"failed to get minimum ledger slot");return e.result}async getFirstAvailableBlock(){const e=Yf(await this._rpcRequest("getFirstAvailableBlock",[]),Fm);if("error"in e)throw new Fg(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=Yf(await this._rpcRequest("getSupply",[t]),Mm);if("error"in n)throw new Fg(n.error,"failed to get supply");return n.result}async getTokenSupply(e,t){const n=this._buildArgs([e.toBase58()],t),r=Yf(await this._rpcRequest("getTokenSupply",n),pm($m));if("error"in r)throw new Fg(r.error,"failed to get token supply");return r.result}async getTokenAccountBalance(e,t){const n=this._buildArgs([e.toBase58()],t),r=Yf(await this._rpcRequest("getTokenAccountBalance",n),pm($m));if("error"in r)throw new Fg(r.error,"failed to get token account balance");return r.result}async getTokenAccountsByOwner(e,t,n){const{commitment:r,config:o}=um(n);let i=[e.toBase58()];"mint"in t?i.push({mint:t.mint.toBase58()}):i.push({programId:t.programId.toBase58()});const s=this._buildArgs(i,r,"base64",o),a=Yf(await this._rpcRequest("getTokenAccountsByOwner",s),Km);if("error"in a)throw new Fg(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 o=this._buildArgs(r,n,"jsonParsed"),i=Yf(await this._rpcRequest("getTokenAccountsByOwner",o),Gm);if("error"in i)throw new Fg(i.error,`failed to get token accounts owned by account ${e.toBase58()}`);return i.result}async getLargestAccounts(e){const t={...e,commitment:e&&e.commitment||this.commitment},n=t.filter||t.commitment?[t]:[],r=Yf(await this._rpcRequest("getLargestAccounts",n),Wm);if("error"in r)throw new Fg(r.error,"failed to get largest accounts");return r.result}async getTokenLargestAccounts(e,t){const n=this._buildArgs([e.toBase58()],t),r=Yf(await this._rpcRequest("getTokenLargestAccounts",n),qm);if("error"in r)throw new Fg(r.error,"failed to get token largest accounts");return r.result}async getAccountInfoAndContext(e,t){const{commitment:n,config:r}=um(t),o=this._buildArgs([e.toBase58()],n,"base64",r),i=Yf(await this._rpcRequest("getAccountInfo",o),pm(sp(jm)));if("error"in i)throw new Fg(i.error,`failed to get info about account ${e.toBase58()}`);return i.result}async getParsedAccountInfo(e,t){const{commitment:n,config:r}=um(t),o=this._buildArgs([e.toBase58()],n,"jsonParsed",r),i=Yf(await this._rpcRequest("getAccountInfo",o),pm(sp(Xm)));if("error"in i)throw new Fg(i.error,`failed to get info about account ${e.toBase58()}`);return i.result}async getAccountInfo(e,t){try{return(await this.getAccountInfoAndContext(e,t)).value}catch(t){throw new Error("failed to get info about account "+e.toBase58()+": "+t)}}async getMultipleParsedAccounts(e,t){const{commitment:n,config:r}=um(t),o=e.map(e=>e.toBase58()),i=this._buildArgs([o],n,"jsonParsed",r),s=Yf(await this._rpcRequest("getMultipleAccounts",i),pm(np(sp(Xm))));if("error"in s)throw new Fg(s.error,`failed to get info for accounts ${o}`);return s.result}async getMultipleAccountsInfoAndContext(e,t){const{commitment:n,config:r}=um(t),o=e.map(e=>e.toBase58()),i=this._buildArgs([o],n,"base64",r),s=Yf(await this._rpcRequest("getMultipleAccounts",i),pm(np(sp(jm))));if("error"in s)throw new Fg(s.error,`failed to get info for accounts ${o}`);return s.result}async getMultipleAccountsInfo(e,t){return(await this.getMultipleAccountsInfoAndContext(e,t)).value}async getStakeActivation(e,t,n){const{commitment:r,config:o}=um(t),i=this._buildArgs([e.toBase58()],r,void 0,{...o,epoch:null!=n?n:o?.epoch}),s=Yf(await this._rpcRequest("getStakeActivation",i),fm(Zm));if("error"in s)throw new Fg(s.error,`failed to get Stake Activation ${e.toBase58()}`);return s.result}async getProgramAccounts(e,t){const{commitment:n,config:r}=um(t),{encoding:o,...i}=r||{},s=this._buildArgs([e.toBase58()],n,o||"base64",{...i,...i.filters?{filters:lm(i.filters)}:null}),a=await this._rpcRequest("getProgramAccounts",s),c=np(Hm),u=!0===i.withContext?Yf(a,pm(c)):Yf(a,fm(c));if("error"in u)throw new Fg(u.error,`failed to get accounts owned by program ${e.toBase58()}`);return u.result}async getParsedProgramAccounts(e,t){const{commitment:n,config:r}=um(t),o=this._buildArgs([e.toBase58()],n,"jsonParsed",r),i=Yf(await this._rpcRequest("getProgramAccounts",o),fm(np(Qm)));if("error"in i)throw new Fg(i.error,`failed to get accounts owned by program ${e.toBase58()}`);return i.result}async confirmTransaction(e,t){let n,r;if("string"==typeof e)n=e;else{const t=e;if(t.abortSignal?.aborted)return Promise.reject(t.abortSignal.reason);n=t.signature}try{r=Hc.decode(n)}catch(e){throw new Error("signature must be base58 encoded: "+n)}return Tg(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,o=!1;return{abortConfirmation:()=>{r&&(r(),r=void 0),null!=n&&(this.removeSignatureListener(n),n=void 0)},confirmationPromise:new Promise((i,s)=>{try{n=this.onSignature(t,(e,t)=>{n=void 0;const r={context:t,value:e};i({__type:Ng.PROCESSED,response:r})},e);const a=new Promise(e=>{null==n?e():r=this._onSubscriptionStateChange(n,t=>{"subscribed"===t&&e()})});(async()=>{if(await a,o)return;const n=await this.getSignatureStatus(t);if(o)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}o=!0,i({__type:Ng.PROCESSED,response:{context:r,value:c}})}})()}catch(e){s(e)}})}}async confirmTransactionUsingBlockHeightExceedanceStrategy({commitment:e,strategy:{abortSignal:t,lastValidBlockHeight:n,signature:r}}){let o=!1;const i=new Promise(t=>{const r=async()=>{try{return await this.getBlockHeight(e)}catch(e){return-1}};(async()=>{let e=await r();if(!o){for(;e<=n;){if(await Mg(1e3),o)return;if(e=await r(),o)return}t({__type:Ng.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,i]);if(e.__type!==Ng.PROCESSED)throw new gg(r);u=e.response}finally{o=!0,s()}return u}async confirmTransactionUsingDurableNonceStrategy({commitment:e,strategy:{abortSignal:t,minContextSlot:n,nonceAccountPubkey:r,nonceValue:o,signature:i}}){let s=!1;const a=new Promise(t=>{let i=o,a=null;const c=async()=>{try{const{context:t,value:o}=await this.getNonceAndContext(r,{commitment:e,minContextSlot:n});return a=t.slot,o?.nonce}catch(e){return i}};(async()=>{if(i=await c(),!s)for(;;){if(o!==i)return void t({__type:Ng.NONCE_INVALID,slotInWhichNonceDidAdvance:a});if(await Mg(2e3),s)return;if(i=await c(),s)return}})()}),{abortConfirmation:c,confirmationPromise:u}=this.getTransactionConfirmationPromise({commitment:e,signature:i}),l=this.getCancellationPromise(t);let h;try{const t=await Promise.race([l,u,a]);if(t.__type===Ng.PROCESSED)h=t.response;else{let r;for(;;){const e=await this.getSignatureStatus(i);if(null==e)break;if(!(e.context.slot<(t.slotInWhichNonceDidAdvance??n))){r=e;break}await Mg(400)}if(!r?.value)throw new yg(i);{const t=e||"finalized",{confirmationStatus:n}=r.value;switch(t){case"processed":case"recent":if("processed"!==n&&"confirmed"!==n&&"finalized"!==n)throw new yg(i);break;case"confirmed":case"single":case"singleGossip":if("confirmed"!==n&&"finalized"!==n)throw new yg(i);break;case"finalized":case"max":case"root":if("finalized"!==n)throw new yg(i)}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:Ng.TIMED_OUT,timeoutMs:r}),r)}),{abortConfirmation:o,confirmationPromise:i}=this.getTransactionConfirmationPromise({commitment:e,signature:t});let s;try{const e=await Promise.race([i,r]);if(e.__type!==Ng.PROCESSED)throw new mg(t,e.timeoutMs/1e3);s=e.response}finally{clearTimeout(n),o()}return s}async getClusterNodes(){const e=Yf(await this._rpcRequest("getClusterNodes",[]),fm(np(uy)));if("error"in e)throw new Fg(e.error,"failed to get cluster nodes");return e.result}async getVoteAccounts(e){const t=this._buildArgs([],e),n=Yf(await this._rpcRequest("getVoteAccounts",t),hy);if("error"in n)throw new Fg(n.error,"failed to get vote accounts");return n.result}async getSlot(e){const{commitment:t,config:n}=um(e),r=this._buildArgs([],t,void 0,n),o=Yf(await this._rpcRequest("getSlot",r),fm(ap()));if("error"in o)throw new Fg(o.error,"failed to get slot");return o.result}async getSlotLeader(e){const{commitment:t,config:n}=um(e),r=this._buildArgs([],t,void 0,n),o=Yf(await this._rpcRequest("getSlotLeader",r),fm(lp()));if("error"in o)throw new Fg(o.error,"failed to get slot leader");return o.result}async getSlotLeaders(e,t){const n=[e,t],r=Yf(await this._rpcRequest("getSlotLeaders",n),fm(np(sm)));if("error"in r)throw new Fg(r.error,"failed to get slot leaders");return r.result}async getSignatureStatus(e,t){const{context:n,value:r}=await this.getSignatureStatuses([e],t);Tg(1===r.length);return{context:n,value:r[0]}}async getSignatureStatuses(e,t){const n=[e];t&&n.push(t);const r=Yf(await this._rpcRequest("getSignatureStatuses",n),py);if("error"in r)throw new Fg(r.error,"failed to get signature status");return r.result}async getTransactionCount(e){const{commitment:t,config:n}=um(e),r=this._buildArgs([],t,void 0,n),o=Yf(await this._rpcRequest("getTransactionCount",r),fm(ap()));if("error"in o)throw new Fg(o.error,"failed to get transaction count");return o.result}async getTotalSupply(e){return(await this.getSupply({commitment:e,excludeNonCirculatingAccountsList:!0})).value.total}async getInflationGovernor(e){const t=this._buildArgs([],e),n=Yf(await this._rpcRequest("getInflationGovernor",t),_m);if("error"in n)throw new Fg(n.error,"failed to get inflation");return n.result}async getInflationReward(e,t,n){const{commitment:r,config:o}=um(n),i=this._buildArgs([e.map(e=>e.toBase58())],r,void 0,{...o,epoch:null!=t?t:o?.epoch}),s=Yf(await this._rpcRequest("getInflationReward",i),wm);if("error"in s)throw new Fg(s.error,"failed to get inflation reward");return s.result}async getInflationRate(){const e=Yf(await this._rpcRequest("getInflationRate",[]),Dm);if("error"in e)throw new Fg(e.error,"failed to get inflation rate");return e.result}async getEpochInfo(e){const{commitment:t,config:n}=um(e),r=this._buildArgs([],t,void 0,n),o=Yf(await this._rpcRequest("getEpochInfo",r),Rm);if("error"in o)throw new Fg(o.error,"failed to get epoch info");return o.result}async getEpochSchedule(){const e=Yf(await this._rpcRequest("getEpochSchedule",[]),Lm);if("error"in e)throw new Fg(e.error,"failed to get epoch schedule");const t=e.result;return new em(t.slotsPerEpoch,t.leaderScheduleSlotOffset,t.warmup,t.firstNormalEpoch,t.firstNormalSlot)}async getLeaderSchedule(){const e=Yf(await this._rpcRequest("getLeaderSchedule",[]),Om);if("error"in e)throw new Fg(e.error,"failed to get leader schedule");return e.result}async getMinimumBalanceForRentExemption(e,t){const n=this._buildArgs([e],t),r=Yf(await this._rpcRequest("getMinimumBalanceForRentExemption",n),gy);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=Yf(await this._rpcRequest("getRecentPerformanceSamples",e?[e]:[]),Ky);if("error"in t)throw new Fg(t.error,"failed to get recent performance samples");return t.result}async getFeeCalculatorForBlockhash(e,t){const n=this._buildArgs([e],t),r=Yf(await this._rpcRequest("getFeeCalculatorForBlockhash",n),zy);if("error"in r)throw new Fg(r.error,"failed to get fee calculator");const{context:o,value:i}=r.result;return{context:o,value:null!==i?i.feeCalculator:null}}async getFeeForMessage(e,t){const n=ag(e.serialize()).toString("base64"),r=this._buildArgs([n],t),o=Yf(await this._rpcRequest("getFeeForMessage",r),pm(sp(ap())));if("error"in o)throw new Fg(o.error,"failed to get fee for message");if(null===o.result)throw new Error("invalid blockhash");return o.result}async getRecentPrioritizationFees(e){const t=e?.lockedWritableAccounts?.map(e=>e.toBase58()),n=t?.length?[t]:[],r=Yf(await this._rpcRequest("getRecentPrioritizationFees",n),Um);if("error"in r)throw new Fg(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}=um(e),r=this._buildArgs([],t,void 0,n),o=Yf(await this._rpcRequest("getLatestBlockhash",r),$y);if("error"in o)throw new Fg(o.error,"failed to get latest blockhash");return o.result}async isBlockhashValid(e,t){const{commitment:n,config:r}=um(t),o=this._buildArgs([e],n,void 0,r),i=Yf(await this._rpcRequest("isBlockhashValid",o),qy);if("error"in i)throw new Fg(i.error,"failed to determine if the blockhash `"+e+"`is valid");return i.result}async getVersion(){const e=Yf(await this._rpcRequest("getVersion",[]),fm(Bm));if("error"in e)throw new Fg(e.error,"failed to get version");return e.result}async getGenesisHash(){const e=Yf(await this._rpcRequest("getGenesisHash",[]),fm(lp()));if("error"in e)throw new Fg(e.error,"failed to get genesis hash");return e.result}async getBlock(e,t){const{commitment:n,config:r}=um(t),o=this._buildArgsAtLeastConfirmed([e],n,void 0,r),i=await this._rpcRequest("getBlock",o);try{switch(r?.transactionDetails){case"accounts":{const e=Yf(i,_y);if("error"in e)throw e.error;return e.result}case"none":{const e=Yf(i,Ny);if("error"in e)throw e.error;return e.result}default:{const e=Yf(i,Py);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:mm(n,e.message)},version:n}))}:null}}}catch(e){throw new Fg(e,"failed to get confirmed block")}}async getParsedBlock(e,t){const{commitment:n,config:r}=um(t),o=this._buildArgsAtLeastConfirmed([e],n,"jsonParsed",r),i=await this._rpcRequest("getBlock",o);try{switch(r?.transactionDetails){case"accounts":{const e=Yf(i,Uy);if("error"in e)throw e.error;return e.result}case"none":{const e=Yf(i,Ry);if("error"in e)throw e.error;return e.result}default:{const e=Yf(i,Dy);if("error"in e)throw e.error;return e.result}}}catch(e){throw new Fg(e,"failed to get block")}}async getBlockProduction(e){let t,n;if("string"==typeof e)n=e;else if(e){const{commitment:r,...o}=e;n=r,t=o}const r=this._buildArgs([],n,"base64",t),o=Yf(await this._rpcRequest("getBlockProduction",r),Nm);if("error"in o)throw new Fg(o.error,"failed to get block production information");return o.result}async getTransaction(e,t){const{commitment:n,config:r}=um(t),o=this._buildArgsAtLeastConfirmed([e],n,void 0,r),i=Yf(await this._rpcRequest("getTransaction",o),Fy);if("error"in i)throw new Fg(i.error,"failed to get transaction");const s=i.result;return s?{...s,transaction:{...s.transaction,message:mm(s.version,s.transaction.message)}}:s}async getParsedTransaction(e,t){const{commitment:n,config:r}=um(t),o=this._buildArgsAtLeastConfirmed([e],n,"jsonParsed",r),i=Yf(await this._rpcRequest("getTransaction",o),My);if("error"in i)throw new Fg(i.error,"failed to get transaction");return i.result}async getParsedTransactions(e,t){const{commitment:n,config:r}=um(t),o=e.map(e=>({methodName:"getTransaction",args:this._buildArgsAtLeastConfirmed([e],n,"jsonParsed",r)}));return(await this._rpcBatchRequest(o)).map(e=>{const t=Yf(e,My);if("error"in t)throw new Fg(t.error,"failed to get transactions");return t.result})}async getTransactions(e,t){const{commitment:n,config:r}=um(t),o=e.map(e=>({methodName:"getTransaction",args:this._buildArgsAtLeastConfirmed([e],n,void 0,r)}));return(await this._rpcBatchRequest(o)).map(e=>{const t=Yf(e,Fy);if("error"in t)throw new Fg(t.error,"failed to get transactions");const n=t.result;return n?{...n,transaction:{...n.transaction,message:mm(n.version,n.transaction.message)}}:n})}async getConfirmedBlock(e,t){const n=this._buildArgsAtLeastConfirmed([e],t),r=Yf(await this._rpcRequest("getBlock",n),Ly);if("error"in r)throw new Fg(r.error,"failed to get confirmed block");const o=r.result;if(!o)throw new Error("Confirmed block "+e+" not found");const i={...o,transactions:o.transactions.map(({transaction:e,meta:t})=>{const n=new Cg(e.message);return{meta:t,transaction:{...e,message:n}}})};return{...i,transactions:i.transactions.map(({transaction:e,meta:t})=>({meta:t,transaction:Ug.populate(e.message,e.signatures)}))}}async getBlocks(e,t,n){const r=this._buildArgsAtLeastConfirmed(void 0!==t?[e,t]:[e],n),o=Yf(await this._rpcRequest("getBlocks",r),fm(np(ap())));if("error"in o)throw new Fg(o.error,"failed to get blocks");return o.result}async getBlockSignatures(e,t){const n=this._buildArgsAtLeastConfirmed([e],t,void 0,{transactionDetails:"signatures",rewards:!1}),r=Yf(await this._rpcRequest("getBlock",n),Oy);if("error"in r)throw new Fg(r.error,"failed to get block");const o=r.result;if(!o)throw new Error("Block "+e+" not found");return o}async getConfirmedBlockSignatures(e,t){const n=this._buildArgsAtLeastConfirmed([e],t,void 0,{transactionDetails:"signatures",rewards:!1}),r=Yf(await this._rpcRequest("getBlock",n),Oy);if("error"in r)throw new Fg(r.error,"failed to get confirmed block");const o=r.result;if(!o)throw new Error("Confirmed block "+e+" not found");return o}async getConfirmedTransaction(e,t){const n=this._buildArgsAtLeastConfirmed([e],t),r=Yf(await this._rpcRequest("getTransaction",n),Fy);if("error"in r)throw new Fg(r.error,"failed to get transaction");const o=r.result;if(!o)return o;const i=new Cg(o.transaction.message),s=o.transaction.signatures;return{...o,transaction:Ug.populate(i,s)}}async getParsedConfirmedTransaction(e,t){const n=this._buildArgsAtLeastConfirmed([e],t,"jsonParsed"),r=Yf(await this._rpcRequest("getTransaction",n),My);if("error"in r)throw new Fg(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=Yf(e,My);if("error"in t)throw new Fg(t.error,"failed to get confirmed transactions");return t.result})}async getConfirmedSignaturesForAddress(e,t,n){let r={},o=await this.getFirstAvailableBlock();for(;!("until"in r)&&!(--t<=0||t<o);)try{const e=await this.getConfirmedBlockSignatures(t,"finalized");e.signatures.length>0&&(r.until=e.signatures[e.signatures.length-1].toString())}catch(e){if(e instanceof Error&&e.message.includes("skipped"))continue;throw e}let i=await this.getSlot("finalized");for(;!("before"in r||++n>i);)try{const e=await this.getConfirmedBlockSignatures(n);e.signatures.length>0&&(r.before=e.signatures[e.signatures.length-1].toString())}catch(e){if(e instanceof Error&&e.message.includes("skipped"))continue;throw e}return(await this.getConfirmedSignaturesForAddress2(e,r)).map(e=>e.signature)}async getConfirmedSignaturesForAddress2(e,t,n){const r=this._buildArgsAtLeastConfirmed([e.toBase58()],n,void 0,t),o=Yf(await this._rpcRequest("getConfirmedSignaturesForAddress2",r),Ym);if("error"in o)throw new Fg(o.error,"failed to get confirmed signatures for address");return o.result}async getSignaturesForAddress(e,t,n){const r=this._buildArgsAtLeastConfirmed([e.toBase58()],n,void 0,t),o=Yf(await this._rpcRequest("getSignaturesForAddress",r),Jm);if("error"in o)throw new Fg(o.error,"failed to get signatures for address");return o.result}async getAddressLookupTable(e,t){const{context:n,value:r}=await this.getAccountInfoAndContext(e,t);let o=null;return null!==r&&(o=new rm({key:e,state:rm.deserialize(r.data)})),{context:n,value:o}}async getNonceAndContext(e,t){const{context:n,value:r}=await this.getAccountInfoAndContext(e,t);let o=null;return null!==r&&(o=Gg.fromAccountData(r.data)),{context:n,value:o}}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=Yf(await this._rpcRequest("requestAirdrop",[e.toBase58(),t]),Gy);if("error"in n)throw new Fg(n.error,`airdrop to ${e.toBase58()} failed`);return n.result}async _blockhashWithExpiryBlockHeight(e){if(!e){for(;this._pollingBlockhash;)await Mg(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 Mg(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}=um(e),r=this._buildArgs([],t,"base64",n),o=Yf(await this._rpcRequest("getStakeMinimumDelegation",r),pm(ap()));if("error"in o)throw new Fg(o.error,"failed to get stake minimum delegation");return o.result}async simulateTransaction(e,t,n){if("message"in e){const r=e.serialize(),o=os.Buffer.from(r).toString("base64");if(Array.isArray(t)||void 0!==n)throw new Error("Invalid arguments");const i=t||{};i.encoding="base64","commitment"in i||(i.commitment=this.commitment),t&&"object"==typeof t&&"innerInstructions"in t&&(i.innerInstructions=t.innerInstructions);const s=[o,i],a=Yf(await this._rpcRequest("simulateTransaction",s),Pm);if("error"in a)throw new Error("failed to simulate transaction: "+a.error.message);return a.result}let r;if(e instanceof Ug){let t=e;r=new Ug,r.feePayer=t.feePayer,r.instructions=e.instructions,r.nonceInfo=t.nonceInfo,r.signatures=t.signatures}else r=Ug.populate(e),r._message=r._json=void 0;if(void 0!==t&&!Array.isArray(t))throw new Error("Invalid arguments");const o=t;if(r.nonceInfo&&o)r.sign(...o);else{let e=this._disableBlockhashCaching;for(;;){const t=await this._blockhashWithExpiryBlockHeight(e);if(r.lastValidBlockHeight=t.lastValidBlockHeight,r.recentBlockhash=t.blockhash,!o)break;if(r.sign(...o),!r.signature)throw new Error("!signature");const n=r.signature.toString("base64");if(!this._blockhashInfo.simulatedSignatures.includes(n)&&!this._blockhashInfo.transactionSignatures.includes(n)){this._blockhashInfo.simulatedSignatures.push(n);break}e=!0}}const i=r._compile(),s=i.serialize(),a=r._serialize(s).toString("base64"),c={encoding:"base64",commitment:this.commitment};if(n){const e=(Array.isArray(n)?n:i.nonProgramIds()).map(e=>e.toBase58());c.accounts={encoding:"base64",addresses:e}}o&&(c.sigVerify=!0),t&&"object"==typeof t&&"innerInstructions"in t&&(c.innerInstructions=t.innerInstructions);const u=[a,c],l=Yf(await this._rpcRequest("simulateTransaction",u),Pm);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 Og({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 o=e.signature.toString("base64");if(!this._blockhashInfo.transactionSignatures.includes(o)){this._blockhashInfo.transactionSignatures.push(o);break}t=!0}}const o=e.serialize();return await this.sendRawTransaction(o,n)}async sendRawTransaction(e,t){const n=ag(e).toString("base64");return await this.sendEncodedTransaction(n,t)}async sendEncodedTransaction(e,t){const n={encoding:"base64"},r=t&&t.skipPreflight,o=!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),o&&(n.preflightCommitment=o);const i=[e,n],s=Yf(await this._rpcRequest("sendTransaction",i),Wy);if("error"in s){let e;throw"data"in s.error&&(e=s.error.data.logs),new Og({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:o}=n;try{this._setSubscription(e,{...n,state:"subscribing"});const t=await this._rpcWebSocket.call(o,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:o}=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(o,[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}=Yf(e,ey);this._handleServerNotification(n,[t.value,t.context])}_makeSubscription(e,t){const n=this._nextClientSubscriptionId++,r=Yg([e.method,t]),o=this._subscriptionsByHash[r];return void 0===o?this._subscriptionsByHash[r]={...e,args:t,callbacks:new Set([e.callback]),state:"pending"}:o.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];Tg(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:o}=um(n),i=this._buildArgs([e.toBase58()],r||this._commitment||"finalized","base64",o);return this._makeSubscription({callback:t,method:"accountSubscribe",unsubscribeMethod:"accountUnsubscribe"},i)}async removeAccountChangeListener(e){await this._unsubscribeClientSubscription(e,"account change")}_wsOnProgramAccountNotification(e){const{result:t,subscription:n}=Yf(e,ny);this._handleServerNotification(n,[{accountId:t.value.pubkey,accountInfo:t.value.account},t.context])}onProgramAccountChange(e,t,n,r){const{commitment:o,config:i}=um(n),s=this._buildArgs([e.toBase58()],o||this._commitment||"finalized","base64",i||(r?{filters:lm(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}=Yf(e,Hy);this._handleServerNotification(n,[t.value,t.context])}_wsOnSlotNotification(e){const{result:t,subscription:n}=Yf(e,oy);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}=Yf(e,sy);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 o=t||this._commitment;if(o||n||r){let t={};n&&(t.encoding=n),o&&(t.commitment=o),r&&(t=Object.assign(t,r)),e.push(t)}return e}_buildArgsAtLeastConfirmed(e,t,n,r){const o=t||this._commitment;if(o&&!["confirmed","finalized"].includes(o))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}=Yf(e,ay);"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"),o=this._makeSubscription({callback:(e,n)=>{if("status"===e.type){t(e.result,n);try{this.removeSignatureListener(o)}catch(e){}}},method:"signatureSubscribe",unsubscribeMethod:"signatureUnsubscribe"},r);return o}onSignatureWithOptions(e,t,n){const{commitment:r,...o}={...n,commitment:n&&n.commitment||this._commitment||"finalized"},i=this._buildArgs([e],r,void 0,o),s=this._makeSubscription({callback:(e,n)=>{t(e,n);try{this.removeSignatureListener(s)}catch(e){}},method:"signatureSubscribe",unsubscribeMethod:"signatureUnsubscribe"},i);return s}async removeSignatureListener(e){await this._unsubscribeClientSubscription(e,"signature result")}_wsOnRootNotification(e){const{result:t,subscription:n}=Yf(e,cy);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 Qy{constructor(e){this._keypair=void 0,this._keypair=e??rg()}static generate(){return new Qy(rg())}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=og(t);for(let e=0;e<32;e++)if(n[e]!==r[e])throw new Error("provided secretKey is invalid")}return new Qy({publicKey:n,secretKey:e})}static fromSeed(e){const t=og(e),n=new Uint8Array(64);return n.set(e),n.set(t,32),new Qy({publicKey:t,secretKey:n})}get publicKey(){return new fg(this._keypair.publicKey)}get secretKey(){return new Uint8Array(this._keypair.secretKey)}}Object.freeze({CreateLookupTable:{index:0,layout:bu.struct([bu.u32("instruction"),Wg("recentSlot"),bu.u8("bumpSeed")])},FreezeLookupTable:{index:1,layout:bu.struct([bu.u32("instruction")])},ExtendLookupTable:{index:2,layout:bu.struct([bu.u32("instruction"),Wg(),bu.seq(bg(),bu.offset(bu.u32(),-8),"addresses")])},DeactivateLookupTable:{index:3,layout:bu.struct([bu.u32("instruction")])},CloseLookupTable:{index:4,layout:bu.struct([bu.u32("instruction")])}}),new fg("AddressLookupTab1e1111111111111111111111111");const Zy=Object.freeze({RequestUnits:{index:0,layout:bu.struct([bu.u8("instruction"),bu.u32("units"),bu.u32("additionalFee")])},RequestHeapFrame:{index:1,layout:bu.struct([bu.u8("instruction"),bu.u32("bytes")])},SetComputeUnitLimit:{index:2,layout:bu.struct([bu.u8("instruction"),bu.u32("units")])},SetComputeUnitPrice:{index:3,layout:bu.struct([bu.u8("instruction"),Wg("microLamports")])}});class Yy{constructor(){}static requestUnits(e){const t=$g(Zy.RequestUnits,e);return new Dg({keys:[],programId:this.programId,data:t})}static requestHeapFrame(e){const t=$g(Zy.RequestHeapFrame,e);return new Dg({keys:[],programId:this.programId,data:t})}static setComputeUnitLimit(e){const t=$g(Zy.SetComputeUnitLimit,e);return new Dg({keys:[],programId:this.programId,data:t})}static setComputeUnitPrice(e){const t=$g(Zy.SetComputeUnitPrice,{microLamports:BigInt(e.microLamports)});return new Dg({keys:[],programId:this.programId,data:t})}}var Jy;Yy.programId=new fg("ComputeBudget111111111111111111111111111111"),bu.struct([bu.u8("numSignatures"),bu.u8("padding"),bu.u16("signatureOffset"),bu.u16("signatureInstructionIndex"),bu.u16("publicKeyOffset"),bu.u16("publicKeyInstructionIndex"),bu.u16("messageDataOffset"),bu.u16("messageDataSize"),bu.u16("messageInstructionIndex")]),new fg("Ed25519SigVerify111111111111111111111111111"),ng.utils.isValidPrivateKey,bu.struct([bu.u8("numSignatures"),bu.u16("signatureOffset"),bu.u8("signatureInstructionIndex"),bu.u16("ethAddressOffset"),bu.u8("ethAddressInstructionIndex"),bu.u16("messageDataOffset"),bu.u16("messageDataSize"),bu.u8("messageInstructionIndex"),bu.blob(20,"ethAddress"),bu.blob(64,"signature"),bu.u8("recoveryId")]),new fg("KeccakSecp256k11111111111111111111111111111"),new fg("StakeConfig11111111111111111111111111111111");class ew{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}}Jy=ew,ew.default=new Jy(0,0,fg.default),Object.freeze({Initialize:{index:0,layout:bu.struct([bu.u32("instruction"),((e="authorized")=>bu.struct([bg("staker"),bg("withdrawer")],e))(),((e="lockup")=>bu.struct([bu.ns64("unixTimestamp"),bu.ns64("epoch"),bg("custodian")],e))()])},Authorize:{index:1,layout:bu.struct([bu.u32("instruction"),bg("newAuthorized"),bu.u32("stakeAuthorizationType")])},Delegate:{index:2,layout:bu.struct([bu.u32("instruction")])},Split:{index:3,layout:bu.struct([bu.u32("instruction"),bu.ns64("lamports")])},Withdraw:{index:4,layout:bu.struct([bu.u32("instruction"),bu.ns64("lamports")])},Deactivate:{index:5,layout:bu.struct([bu.u32("instruction")])},Merge:{index:7,layout:bu.struct([bu.u32("instruction")])},AuthorizeWithSeed:{index:8,layout:bu.struct([bu.u32("instruction"),bg("newAuthorized"),bu.u32("stakeAuthorizationType"),kg("authoritySeed"),bg("authorityOwner")])}}),new fg("Stake11111111111111111111111111111111111111"),Object.freeze({InitializeAccount:{index:0,layout:bu.struct([bu.u32("instruction"),((e="voteInit")=>bu.struct([bg("nodePubkey"),bg("authorizedVoter"),bg("authorizedWithdrawer"),bu.u8("commission")],e))()])},Authorize:{index:1,layout:bu.struct([bu.u32("instruction"),bg("newAuthorized"),bu.u32("voteAuthorizationType")])},Withdraw:{index:3,layout:bu.struct([bu.u32("instruction"),bu.ns64("lamports")])},UpdateValidatorIdentity:{index:4,layout:bu.struct([bu.u32("instruction")])},AuthorizeWithSeed:{index:10,layout:bu.struct([bu.u32("instruction"),((e="voteAuthorizeWithSeedArgs")=>bu.struct([bu.u32("voteAuthorizationType"),bg("currentAuthorityDerivedKeyOwnerPubkey"),kg("currentAuthorityDerivedKeySeed"),bg("newAuthorized")],e))()])}}),new fg("Vote111111111111111111111111111111111111111"),new fg("Va1idator1nfo111111111111111111111111111111"),dp({name:lp(),website:cp(lp()),details:cp(lp()),iconUrl:cp(lp()),keybaseUsername:cp(lp())}),new fg("Vote111111111111111111111111111111111111111"),bu.struct([bg("nodePubkey"),bg("authorizedWithdrawer"),bu.u8("commission"),bu.nu64(),bu.seq(bu.struct([bu.nu64("slot"),bu.u32("confirmationCount")]),bu.offset(bu.u32(),-8),"votes"),bu.u8("rootSlotValid"),bu.nu64("rootSlot"),bu.nu64(),bu.seq(bu.struct([bu.nu64("epoch"),bg("authorizedVoter")]),bu.offset(bu.u32(),-8),"authorizedVoters"),bu.struct([bu.seq(bu.struct([bg("authorizedPubkey"),bu.nu64("epochOfLastAuthorizedSwitch"),bu.nu64("targetEpoch")]),32,"buf"),bu.nu64("idx"),bu.u8("isEmpty")],"priorVoters"),bu.nu64(),bu.seq(bu.struct([bu.nu64("epoch"),bu.nu64("credits"),bu.nu64("prevCredits")]),bu.offset(bu.u32(),-8),"epochCredits"),bu.struct([bu.nu64("slot"),bu.nu64("timestamp")],"lastTimestamp")]);const tw=new fg("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA");new fg("TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb");const nw=new fg("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL");new fg("So11111111111111111111111111111111111111112"),new fg("9pan9bMn5HatX4EJdBwg9VgCa7Uz5HL8N1m5D3NdXejP");const rw=e=>({decode:e.decode.bind(e),encode:e.encode.bind(e)});var ow,iw={};var sw=(ow||(ow=1,Object.defineProperty(iw,"__esModule",{value:!0}),iw.toBigIntLE=function(e){{const t=Buffer.from(e);t.reverse();const n=t.toString("hex");return 0===n.length?BigInt(0):BigInt(`0x${n}`)}},iw.toBigIntBE=function(e){{const t=e.toString("hex");return 0===t.length?BigInt(0):BigInt(`0x${t}`)}},iw.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}},iw.toBufferBE=function(e,t){{const n=e.toString(16);return Buffer.from(n.padStart(2*t,"0").slice(0,2*t),"hex")}}),iw);const aw=(cw=8,e=>{const t=bu.blob(cw,e),{encode:n,decode:r}=rw(t),o=t;return o.decode=(e,t)=>{const n=r(e,t);return sw.toBigIntLE(Buffer.from(n))},o.encode=(e,t,r)=>{const o=sw.toBufferLE(e,cw);return n(o,t,r)},o});var cw;const uw=e=>{const t=bu.u8(e),{encode:n,decode:r}=rw(t),o=t;return o.decode=(e,t)=>!!r(e,t),o.encode=(e,t,r)=>{const o=Number(e);return n(o,t,r)},o},lw=e=>{const t=bu.blob(32,e),{encode:n,decode:r}=rw(t),o=t;return o.decode=(e,t)=>{const n=r(e,t);return new fg(n)},o.encode=(e,t,r)=>{const o=e.toBuffer();return n(o,t,r)},o};class hw extends Error{constructor(e){super(e)}}class dw extends hw{constructor(){super(...arguments),this.name="TokenAccountNotFoundError"}}class fw extends hw{constructor(){super(...arguments),this.name="TokenInvalidAccountError"}}class pw extends hw{constructor(){super(...arguments),this.name="TokenInvalidAccountOwnerError"}}class gw extends hw{constructor(){super(...arguments),this.name="TokenInvalidAccountSizeError"}}class mw extends hw{constructor(){super(...arguments),this.name="TokenOwnerOffCurveError"}}var yw;!function(e){e[e.Uninitialized=0]="Uninitialized",e[e.Mint=1]="Mint",e[e.Account=2]="Account"}(yw||(yw={}));const ww=bu.struct([bu.u8("m"),bu.u8("n"),uw("isInitialized"),lw("signer1"),lw("signer2"),lw("signer3"),lw("signer4"),lw("signer5"),lw("signer6"),lw("signer7"),lw("signer8"),lw("signer9"),lw("signer10"),lw("signer11")]).span;var bw;!function(e){e[e.Uninitialized=0]="Uninitialized",e[e.Initialized=1]="Initialized",e[e.Frozen=2]="Frozen"}(bw||(bw={}));const kw=bu.struct([lw("mint"),lw("owner"),aw("amount"),bu.u32("delegateOption"),lw("delegate"),bu.u8("state"),bu.u32("isNativeOption"),aw("isNative"),aw("delegatedAmount"),bu.u32("closeAuthorityOption"),lw("closeAuthority")]),vw=kw.span;async function Ew(e,t,n,r=tw){return function(e,t,n=tw){if(!t)throw new dw;if(!t.owner.equals(n))throw new pw;if(t.data.length<vw)throw new gw;const r=kw.decode(t.data.slice(0,vw));let o=Buffer.alloc(0);if(t.data.length>vw){if(t.data.length===ww)throw new gw;if(t.data[vw]!=yw.Account)throw new fw;o=t.data.slice(vw+1)}return{address:e,mint:r.mint,owner:r.owner,amount:r.amount,delegate:r.delegateOption?r.delegate:null,delegatedAmount:r.delegatedAmount,isInitialized:r.state!==bw.Uninitialized,isFrozen:r.state===bw.Frozen,isNative:!!r.isNativeOption,rentExemptReserve:r.isNativeOption?r.isNative:null,closeAuthority:r.closeAuthorityOption?r.closeAuthority:null,tlvData:o}}(t,await e.getAccountInfo(t,n),r)}function Sw(e,t,n=!1,r=tw,o=nw){if(!n&&!fg.isOnCurve(t.toBuffer()))throw new mw;const[i]=fg.findProgramAddressSync([t.toBuffer(),r.toBuffer(),e.toBuffer()],o);return i}bu.struct([bu.u32("mintAuthorityOption"),lw("mintAuthority"),aw("supply"),bu.u8("decimals"),uw("isInitialized"),bu.u32("freezeAuthorityOption"),lw("freezeAuthority")]).span;var Tw=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),o=r.charCodeAt(0);if(255!==t[o])throw new TypeError(r+" is ambiguous");t[o]=n}const n=e.length,r=e.charAt(0),o=Math.log(n)/Math.log(256),i=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 i=0,s=0,a=0;for(;e[i]===r;)s++,i++;const c=(e.length-i)*o+1>>>0,u=new Uint8Array(c);for(;i<e.length;){const r=e.charCodeAt(i);if(r>255)return;let o=t[r];if(255===o)return;let s=0;for(let e=c-1;(0!==o||s<a)&&-1!==e;e--,s++)o+=n*u[e]>>>0,u[e]=o%256>>>0,o=o/256>>>0;if(0!==o)throw new Error("Non-zero carry");a=s,i++}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 o=0,s=0,a=0;const c=t.length;for(;a!==c&&0===t[a];)a++,o++;const u=(c-a)*i+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(o);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");class Aw extends Vi{constructor(e){if(super(),this.network="Solana",this.solanaBridgeAccountCache=new Map,this.tokenMetadataCache=new Map,this.galaConnectClient=e.galaConnectClient,this.galaChainWalletAddress=e.galaChainWalletAddress,!e.ethereumPrivateKey||!/^0x[a-fA-F0-9]{64}$/.test(e.ethereumPrivateKey))throw new Error("Invalid Ethereum private key format. Expected 0x-prefixed 64-character hex string (e.g., 0x1234...abcd)");const t=new n.JsonRpcProvider("https://ethereum.publicnode.com");this.ethereumWallet=new n.Wallet(e.ethereumPrivateKey,t);const r=e.solanaRpcUrl??"https://api.mainnet-beta.solana.com";let o;this.solanaConnection=new Xy(r,"confirmed");try{o=Tw.decode(e.solanaPrivateKeyBase58)}catch(e){throw new Error(`Invalid Solana private key format (expected base58-encoded string): ${e instanceof Error?e.message:"decode failed"}`)}if(64!==o.length)throw new Error(`Invalid Solana private key length: expected 64 bytes, got ${o.length} bytes`);this.solanaKeypair=Qy.fromSecretKey(o);const i=e.solanaBridgeProgram??"AaE4dTnL75XqgUJpdxBKg6vS9sTJgBPJwBQRVhD29WwS";this.solanaBridgeProgramId=new fg(i),[this.solanaBridgeTokenAuthority]=fg.findProgramAddressSync([Buffer.from("bridge_token_authority")],this.solanaBridgeProgramId),[this.solanaBridgeConfigPda]=fg.findProgramAddressSync([Buffer.from("configv1")],this.solanaBridgeProgramId),[this.solanaNativeBridgePda]=fg.findProgramAddressSync([Buffer.from("native_sol_bridge")],this.solanaBridgeProgramId),this.tokenConfigs=new Map;const s=e.tokenConfigs??oi;for(const e of s)this.tokenConfigs.set(e.symbol.toUpperCase(),e)}async estimateFee(e,t){const n=await this.getTokenMetadata(e),r=await this.galaConnectClient.fetchBridgeFee({chainId:"Solana",bridgeToken:n.descriptor});return{estimatedFeeInGala:r.estimatedTotalTxFeeInGala,estimatedFeeInExternalToken:r.estimatedTotalTxFeeInExternalToken,feeToken:r.bridgeToken,pricePerUnit:r.estimatedPricePerTxFeeUnit,estimatedGasUnits:r.estimatedTxFeeUnitsTotal,exchangeRate:r.galaExchangeRate?.exchangeRate??"0",timestamp:r.timestamp,raw:r}}async bridgeOut(e){const{amount:t,recipientAddress:n,tokenSymbol:r}=e;if(!r)throw new Error("Token symbol resolution failed. This is an internal error - BridgeService should resolve tokenId to symbol before calling strategy.");const o=r,i=parseFloat(t);if(isNaN(i)||i<=0)throw new Error(`Invalid bridge amount for ${o}: "${t}". Amount must be a positive number.`);try{new fg(n)}catch(e){throw new Error(`Invalid Solana recipient address: "${n}". ${e instanceof Error?e.message:"Expected valid base58 public key."}`)}const s=await this.getTokenMetadata(o),a=await this.galaConnectClient.fetchBridgeFee({chainId:"Solana",bridgeToken:s.descriptor}),c={destinationChainId:Vo.SOLANA,destinationChainTxFee:a,quantity:t,recipient:n,tokenInstance:{...s.descriptor,instance:"0"}},u=await this.buildBridgeOutPayload(c),l=await this.galaConnectClient.requestBridgeOut(u),h=this.extractBridgeRequestId(l);if(!h)throw new Error("Bridge request ID missing from RequestTokenBridgeOut response");const d=await this.galaConnectClient.bridgeTokenOut({bridgeFromChannel:"asset",bridgeRequestId:h}),f=d.Hash??d.hash??"";if(!f)throw new Error("BridgeTokenOut response missing transaction hash");return{direction:"outbound",fromChain:"GalaChain",toChain:"Solana",transactionHash:f,tokenSymbol:o,amount:t,feePaid:a.estimatedTotalTxFeeInGala,timestamp:Date.now(),statusUrl:`${this.galaConnectClient.getBaseUrl()}/v1/bridge/transaction?hash=${f}`}}async bridgeIn(e){const{amount:t,sourcePrivateKey:n,recipientAddress:r,tokenSymbol:o}=e;if(!o)throw new Error("Token symbol resolution failed. This is an internal error - BridgeService should resolve tokenId to symbol before calling strategy.");const i=o,s=parseFloat(t);if(isNaN(s)||s<=0)throw new Error(`Invalid bridge amount for ${i}: "${t}". Amount must be a positive number.`);let a=this.solanaKeypair;if(n){let e;try{e=Tw.decode(n)}catch(e){throw new Error(`Invalid sourcePrivateKey format (expected base58): ${e instanceof Error?e.message:"decode failed"}`)}if(64!==e.length)throw new Error(`Invalid sourcePrivateKey length: expected 64 bytes, got ${e.length} bytes`);a=Qy.fromSecretKey(e)}const c=this.tokenConfigs.get(i.toUpperCase());if(!c)throw new Error(`Token ${i} not supported for Solana bridge`);const u=await this.getTokenMetadata(i),l=Ni(t,u.decimals),h=r??this.galaChainWalletAddress,d=await this.executeSolanaBridgeOut({keypair:a,tokenConfig:c,metadata:u,amountBaseUnits:l,recipient:h,amount:t});return{direction:"inbound",fromChain:"Solana",toChain:"GalaChain",transactionHash:d,tokenSymbol:i,amount:t,timestamp:Date.now(),statusUrl:`${this.galaConnectClient.getBaseUrl()}/v1/bridge/transaction?hash=${d}`}}async getStatus(e){const t=await this.galaConnectClient.getBridgeStatus(e),n=t.status;return{status:n,statusDescription:t.statusDescription,fromChain:t.fromChain,toChain:t.toChain,quantity:t.quantity,transactionHash:t.emitterTransactionHash,tokenInstance:t.tokenInstance,isComplete:5===n,isFailed:6===n||7===n}}getSupportedTokens(){return Array.from(this.tokenConfigs.keys())}isTokenSupported(e){return this.tokenConfigs.has(e.toUpperCase())}isValidAddress(e){try{return new fg(e),!0}catch{return!1}}getWalletAddress(){return this.solanaKeypair.publicKey.toBase58()}async getSolanaTokenBalance(e,t){const n=this.tokenConfigs.get(e.toUpperCase());if(!n)throw new Error(`Token ${e} not supported for Solana. Supported: GALA (8 decimals), GSOL (9 decimals)`);if(n.isNative)return this.getSolanaNativeBalance(t);const r=t??this.solanaKeypair.publicKey.toBase58();let o;try{o=new fg(r)}catch{throw new Error(`Invalid Solana address: "${r}"`)}const i=Sw(new fg(n.mintAddress),o,!1,tw,nw);try{const e=await Ew(this.solanaConnection,i,"confirmed",tw),t=n.decimals??8;return _i(e.amount,t)}catch(t){if(t instanceof Error&&t.message.includes("could not find")){return _i(0n,n.decimals??8)}throw new Error(`Failed to fetch ${e} balance for ${r}: ${t instanceof Error?t.message:"Unknown error"}`)}}async getSolanaNativeBalance(e){const t=e??this.solanaKeypair.publicKey.toBase58();let n;try{n=new fg(t)}catch{throw new Error(`Invalid Solana address: "${t}"`)}const r=await this.solanaConnection.getBalance(n,"confirmed");return _i(BigInt(r),9)}async requestDevnetAirdrop(e=1,t){if(e<=0||e>2)throw new Error(`Invalid airdrop amount: ${e} SOL. Devnet faucet limits: minimum >0 SOL, maximum 2 SOL per request.`);let n;if(t)try{n=new fg(t)}catch{throw new Error(`Invalid Solana address: "${t}"`)}else n=this.solanaKeypair.publicKey;const r=this.solanaConnection.rpcEndpoint;if(!r.includes("devnet"))throw new Error(`Solana devnet faucet only available on devnet. Current RPC: ${r}. Ensure SDK is configured with environment='STAGE' for devnet access.`);const o=Math.floor(1e9*e);return await this.solanaConnection.requestAirdrop(n,o)}async getSolanaTransactionStatus(e){if(!e||"string"!=typeof e)throw new Error("Invalid signature: must be a non-empty string");if(!/^[1-9A-HJ-NP-Za-km-z]{80,90}$/.test(e))throw new Error(`Invalid Solana signature format: "${e.slice(0,20)}...". Expected base58-encoded string (87-88 characters).`);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 getTokenMetadata(e){const t=this.tokenMetadataCache.get(e.toUpperCase());if(t)return t;const n=ii[e.toUpperCase()];if(n)return this.tokenMetadataCache.set(e.toUpperCase(),n),n;let r=e,o=await this.galaConnectClient.getBridgeConfigurations(r),i=o.find(e=>e.symbol.toUpperCase()===r.toUpperCase()&&e.verified);if(i||e.startsWith("G")||(r=`G${e}`,o=await this.galaConnectClient.getBridgeConfigurations(r),i=o.find(e=>e.symbol.toUpperCase()===r.toUpperCase()&&e.verified)),!i)throw new Error(`Unable to locate token metadata for ${e}`);const s={descriptor:{collection:i.collection,category:i.category,type:i.type,additionalKey:i.additionalKey},decimals:i.decimals,...i.channel&&{channel:i.channel}};return this.tokenMetadataCache.set(e.toUpperCase(),s),s}async buildBridgeOutPayload(e){const t=e.uniqueKey??`galaconnect-operation-${l.randomUUID()}`,n="string"==typeof e.destinationChainId?Number(e.destinationChainId):e.destinationChainId,r=this.normalizeDestinationChainTxFee(e.destinationChainTxFee),o=Boolean(r.galaExchangeCrossRate),i=o?{...r,galaExchangeRate:void 0}:{...r,galaExchangeCrossRate:void 0},s={destinationChainId:n,destinationChainTxFee:this.sanitizeObject(i),quantity:e.quantity,recipient:e.recipient,tokenInstance:e.tokenInstance,uniqueKey:t},a=mi(o),c=await this.ethereumWallet.signTypedData(ui,a,s),u=`Ethereum Signed Message:\n${Ho({domain:ui,message:s,primaryType:"GalaTransaction",types:a}).length}`;return{...s,signature:c,prefix:u,types:a,domain:ui}}async executeSolanaBridgeOut(e){const t=new fg(e.tokenConfig.mintAddress),n=Boolean(e.tokenConfig.isNative),r=n?void 0:await this.getSolanaBridgeAccounts(t),o=n?void 0:Sw(t,e.keypair.publicKey,!1,tw,nw),i=Buffer.from(e.recipient,"utf8"),s=Buffer.alloc(8);s.writeBigUInt64LE(e.amountBaseUnits);const a=Buffer.alloc(4);a.writeUInt32LE(i.length);const c=n?this.buildNativeBridgeInstruction(e.keypair.publicKey,s,a,i):this.buildTokenBridgeInstruction(e.keypair.publicKey,o,t,r,s,a,i),u=new Ug;u.add(Yy.setComputeUnitPrice({microLamports:375e3}),Yy.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 o=1;o<=n;o++){try{const i=await this.solanaConnection.getLatestBlockhash("confirmed");e.recentBlockhash=i.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:i.blockhash,lastValidBlockHeight:i.lastValidBlockHeight},"confirmed"),s}catch(e){const t=e instanceof Error?e.message.toLowerCase():"";if(!(t.includes("block height exceeded")||t.includes("blockhash not found")||t.includes("expired")))throw e;const i=await this.solanaConnection.getSignatureStatuses([s]);if("confirmed"===i.value[0]?.confirmationStatus||"finalized"===i.value[0]?.confirmationStatus)return s;r=new Error(`Transaction ${s} not confirmed - block height exceeded (attempt ${o}/${n})`)}}catch(e){r=e instanceof Error?e:new Error(String(e));const t=r.message.toLowerCase();if(!(t.includes("block height exceeded")||t.includes("blockhash not found")||t.includes("timeout")||t.includes("expired"))||o===n)throw r}const i=Math.min(1e3*Math.pow(2,o-1),5e3);await new Promise(e=>setTimeout(e,i))}throw r??new Error("Transaction confirmation failed after max retries")}buildNativeBridgeInstruction(e,t,n,r){const o=Buffer.concat([ci.BRIDGE_OUT_NATIVE,t,n,r]);return new Dg({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:Hg.programId,isSigner:!1,isWritable:!1}],data:o})}buildTokenBridgeInstruction(e,t,n,r,o,i,s){const a=Buffer.concat([ci.BRIDGE_OUT,o,i,s]);return new Dg({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:Hg.programId,isSigner:!1,isWritable:!1},{pubkey:tw,isSigner:!1,isWritable:!1}],data:a})}async getSolanaBridgeAccounts(e){const t=e.toBase58(),n=this.solanaBridgeAccountCache.get(t);if(n)return n;const[r]=fg.findProgramAddressSync([Buffer.from("mint_lookup_v1"),e.toBuffer()],this.solanaBridgeProgramId),o=await this.solanaConnection.getAccountInfo(r,"confirmed");if(!o)throw new Error(`Mint lookup account not found for ${r.toBase58()}`);if(!o.owner.equals(this.solanaBridgeProgramId))throw new Error("Mint lookup account owner mismatch for Solana bridge program");if(o.data.length<40)throw new Error("Mint lookup account data is unexpectedly short");const i={mintLookup:r,tokenBridge:new fg(o.data.slice(8,40)),bridgeTokenAccount:Sw(e,this.solanaBridgeTokenAuthority,!0,tw,nw)};return this.solanaBridgeAccountCache.set(t,i),i}normalizeDestinationChainTxFee(e){const t={...e,galaDecimals:"string"==typeof e.galaDecimals?Number(e.galaDecimals):e.galaDecimals,timestamp:"string"==typeof e.timestamp?Number(e.timestamp):e.timestamp};if(e.galaExchangeRate&&(t.galaExchangeRate={...e.galaExchangeRate,timestamp:"string"==typeof e.galaExchangeRate.timestamp?Number(e.galaExchangeRate.timestamp):e.galaExchangeRate.timestamp}),e.galaExchangeCrossRate){const n=e.galaExchangeCrossRate;t.galaExchangeCrossRate={...n,timestamp:"string"==typeof n.timestamp?Number(n.timestamp):n.timestamp},n.baseTokenCrossRate&&(t.galaExchangeCrossRate.baseTokenCrossRate={...n.baseTokenCrossRate,timestamp:"string"==typeof n.baseTokenCrossRate.timestamp?Number(n.baseTokenCrossRate.timestamp):n.baseTokenCrossRate.timestamp}),n.quoteTokenCrossRate&&(t.galaExchangeCrossRate.quoteTokenCrossRate={...n.quoteTokenCrossRate,timestamp:"string"==typeof n.quoteTokenCrossRate.timestamp?Number(n.quoteTokenCrossRate.timestamp):n.quoteTokenCrossRate.timestamp})}return t}sanitizeObject(e){const t={};for(const[n,r]of Object.entries(e))void 0!==r&&(r&&"object"==typeof r&&!Array.isArray(r)?t[n]=this.sanitizeObject(r):t[n]=r);return t}extractBridgeRequestId(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}}}}const Iw={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 Bw(e){return Iw[e]}const xw={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"}},Cw={solanaBridgeProgram:"AaE4dTnL75XqgUJpdxBKg6vS9sTJgBPJwBQRVhD29WwS",rateLimit:12,pollInterval:15e3,pollTimeout:27e5};class Pw{static normalizeGalaChainAddress(e){let t;if(e.startsWith("eth|"))t=e.slice(4);else{if(e.startsWith("client|"))return e;t=e}(t.startsWith("0x")||t.startsWith("0X"))&&(t=t.slice(2));return`eth|${Pw.checksumAddress(t)}`}static checksumAddress(e){const t=e.toLowerCase(),{keccak256:n,toUtf8Bytes:r}=require("ethers"),o=n(r(t)).slice(2);let i="";for(let e=0;e<t.length;e++){const n=t[e];parseInt(o[e],16)>=8?i+=n.toUpperCase():i+=n}return i}constructor(e){const t=Pw.normalizeGalaChainAddress(e.galaChainWalletAddress),n=e.environment??"STAGE",r=Iw[n],o=xw[n],i={galaConnectBaseUrl:e.galaConnectBaseUrl??r.dexApiBaseUrl,galaChainApiBaseUrl:e.galaChainApiBaseUrl??r.galaChainBaseUrl,ethereumRpcUrl:e.ethereumRpcUrl??o.ethereum,solanaRpcUrl:e.solanaRpcUrl??o.solana,ethereumBridgeContract:e.ethereumBridgeContract??ni(n),solanaBridgeProgram:e.solanaBridgeProgram??Cw.solanaBridgeProgram,rateLimit:e.rateLimit??Cw.rateLimit,pollInterval:e.pollInterval??Cw.pollInterval,pollTimeout:e.pollTimeout??Cw.pollTimeout,galaChainWalletAddress:t,ethereumPrivateKey:e.ethereumPrivateKey,environment:n};this.config=e.solanaPrivateKey?{...i,solanaPrivateKey:e.solanaPrivateKey}:i,this.galaConnectClient=new ji({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=ti(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 Xi(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:oi};this.strategies.set("Solana",new Aw(e))}}async resolveTokenSymbol(e,t){if(!this.bridgeableTokenService)throw new Error("BridgeableTokenService is required for tokenId resolution. Pass bridgeableTokenService in BridgeServiceConfig or use the SDK's bridge methods.");const n=Fi(e).stringified,r="Ethereum"===t?"ETHEREUM":"SOLANA",o=await this.bridgeableTokenService.getTokenByTokenId(n,r);if(!o){throw new Error([`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"))}return o.symbol}async estimateBridgeFee(e){const t=await this.resolveTokenSymbol(e.tokenId,e.destinationChain);return this.getStrategy(e.destinationChain).estimateFee(t,e.amount??"0")}async bridgeOut(e){const t=await this.resolveTokenSymbol(e.tokenId,e.destinationChain),n=this.getStrategy(e.destinationChain);if(!n.isValidAddress(e.recipientAddress))throw new Error(`Invalid recipient address for ${e.destinationChain}: ${e.recipientAddress}`);if(!n.isTokenSupported(t))throw new Error(`Token ${t} is not supported for ${e.destinationChain} bridging`);return n.bridgeOut({...e,tokenSymbol:t})}async bridgeIn(e){const t=await this.resolveTokenSymbol(e.tokenId,e.sourceChain),n=this.getStrategy(e.sourceChain);if(!n.isTokenSupported(t))throw new Error(`Token ${t} is not supported for ${e.sourceChain} bridging`);return n.bridgeIn({...e,tokenSymbol:t})}async getBridgeStatus(e,t){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=e instanceof Error?e:new Error(String(e))}const o=this.strategies.get("Solana");if(o)try{return await o.getStatus(e)}catch(e){r=e instanceof Error?e:new Error(String(e))}const i=r?` (last error: ${r.message})`:"";throw new Error(`Unable to get status for transaction ${e}${i}`)}async waitForBridgeCompletion(e,t){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 o=this.strategies.get("Solana");if(o)return o.waitForCompletion(e,n);throw new Error(`Unable to wait for transaction ${e}: no suitable strategy found`)}getSupportedBridgeTokens(e){const t=[],n=ti(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 oi){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){const n=this.strategies.get("Ethereum");if(!n)throw new Error("Ethereum bridge not configured");return n.getEthereumTokenBalance(e,t)}async getEthereumNativeBalance(e){const t=this.strategies.get("Ethereum");if(!t)throw new Error("Ethereum bridge not configured");return t.getEthereumNativeBalance(e)}async getSolanaTokenBalance(e,t){const n=this.strategies.get("Solana");if(!n)throw new Error("Solana bridging not configured. Provide solanaPrivateKey in config.");return n.getSolanaTokenBalance(e,t)}async getSolanaNativeBalance(e){const t=this.strategies.get("Solana");if(!t)throw new Error("Solana bridging not configured. Provide solanaPrivateKey in config.");return t.getSolanaNativeBalance(e)}async fetchEthereumWalletTokenBalance(e,t){const n=this.strategies.get("Ethereum");if(!n)throw new Error("Ethereum bridging not configured. Provide ethereumPrivateKey in config.");const r=ti(this.config.environment),o=r.find(t=>t.symbol===e);if(!o){const t=r.map(e=>e.symbol).join(", ");throw new Error(`Unsupported Ethereum token: ${e}. Supported: ${t}`)}const i=n,s=t??i.getWalletAddress(),a=await i.getEthereumTokenBalance(e,s);return{symbol:o.symbol,quantity:a,decimals:o.decimals??18,contractAddress:o.contractAddress,isNative:!1}}async fetchEthereumWalletNativeBalance(e){const t=this.strategies.get("Ethereum");if(!t)throw new Error("Ethereum bridging not configured. Provide ethereumPrivateKey in config.");const n=t,r=e??n.getWalletAddress();return{symbol:"ETH",quantity:await n.getEthereumNativeBalance(r),decimals:18,contractAddress:null,isNative:!0}}async fetchSolanaWalletTokenBalance(e,t){const n=this.strategies.get("Solana");if(!n)throw new Error("Solana bridging not configured. Provide solanaPrivateKey in config.");const r=oi.find(t=>t.symbol===e);if(!r){const t=oi.map(e=>e.symbol).join(", ");throw new Error(`Unsupported Solana token: ${e}. Supported: ${t}`)}const o=n,i=t??o.getWalletAddress(),s=await o.getSolanaTokenBalance(e,i);return{symbol:r.symbol,quantity:s,decimals:r.decimals??9,contractAddress:r.mintAddress,isNative:r.isNative??!1}}async fetchSolanaWalletNativeBalance(e){const t=this.strategies.get("Solana");if(!t)throw new Error("Solana bridging not configured. Provide solanaPrivateKey in config.");const n=t,r=e??n.getWalletAddress();return{symbol:"SOL",quantity:await n.getSolanaNativeBalance(r),decimals:9,contractAddress:null,isNative:!0}}async requestSolanaDevnetAirdrop(e,t){const n=this.strategies.get("Solana");if(!n)throw new Error("Solana bridging not configured. Provide solanaPrivateKey in config.");return n.requestDevnetAirdrop(e,t)}async getSolanaTransactionStatus(e){const t=this.strategies.get("Solana");if(!t)throw new Error("Solana bridge strategy not configured. This method requires Solana wallet configuration. Initialize SDK with solanaPrivateKey to use Solana features.");const n=t;try{return await n.getSolanaTransactionStatus(e)}catch(e){const t=e instanceof Error?e.message:"Unknown error";throw new Error(`Failed to query Solana transaction status: ${t}`)}}async getEthereumTransactionStatus(e){const t=this.strategies.get("Ethereum");if(!t)throw new Error("Ethereum bridge strategy not configured. This method requires Ethereum wallet configuration. Initialize SDK with ethereumPrivateKey to use Ethereum features.");const n=t;try{return await n.getEthereumTransactionStatus(e)}catch(e){const t=e instanceof Error?e.message:"Unknown error";throw new Error(`Failed to query Ethereum transaction status: ${t}`)}}async fetchEthereumWalletAllBalances(e){const t=this.strategies.get("Ethereum");if(!t)throw new Error("Ethereum bridging not configured. Provide ethereumPrivateKey in config.");const n=t,r=e??n.getWalletAddress(),o=ti(this.config.environment),[i,...s]=await Promise.all([n.getEthereumNativeBalance(r),...o.map(async e=>{const t=await n.getEthereumTokenBalance(e.symbol,r);return{symbol:e.symbol,quantity:t,decimals:e.decimals??18,contractAddress:e.contractAddress,isNative:!1}})]);return{address:r,native:{symbol:"ETH",quantity:i,decimals:18,contractAddress:null,isNative:!0},tokens:s,timestamp:Date.now()}}async fetchSolanaWalletAllBalances(e){const t=this.strategies.get("Solana");if(!t)throw new Error("Solana bridging not configured. Provide solanaPrivateKey in config.");const n=t,r=e??n.getWalletAddress(),[o,...i]=await Promise.all([n.getSolanaNativeBalance(r),...oi.map(async e=>{const t=await n.getSolanaTokenBalance(e.symbol,r);return{symbol:e.symbol,quantity:t,decimals:e.decimals??9,contractAddress:e.mintAddress,isNative:e.isNative??!1}})]);return{address:r,native:{symbol:"SOL",quantity:o,decimals:9,contractAddress:null,isNative:!0},tokens:i,timestamp:Date.now()}}getStrategy(e){const t=this.strategies.get(e);if(!t)throw new Error(`Bridging to ${e} is not configured. `+("Solana"===e?"Please provide solanaPrivateKey in config.":"Please check your configuration."));return t}}class Nw extends Error{constructor(e,t){super(e),this.cause=t,this.name="WebSocketError"}}class _w 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 Dw(e,t){if(!e)throw new Nw(`Invalid WebSocket response received for transaction ${t}: response is null or undefined`);if("object"!=typeof e)throw new Nw(`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 Nw(`Invalid WebSocket response received for transaction ${t}: missing status field`)}function Uw(e,t,n,r){Dw(e,t);const o=e,i=o.data||{};if(!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return!(void 0!==t.inputQuantity&&"string"!=typeof t.inputQuantity||void 0!==t.outputQuantity&&"string"!=typeof t.outputQuantity||void 0!==t.totalFees&&"string"!=typeof t.totalFees||void 0!==t.vaultAddress&&"string"!=typeof t.vaultAddress)}(i))throw new Nw(`Invalid trade data received for transaction ${t}`);const s={transactionId:t,type:n,method:"native"===r.type?"native":"exact",inputAmount:i.inputQuantity||r.amount,outputAmount:i.outputQuantity||r.expectedAmount||"0",totalFees:i.totalFees||"0",tokenName:r.tokenName,vaultAddress:i.vaultAddress||"",timestamp:Date.now()};return void 0!==o.blockHash&&(s.blockHash=o.blockHash),void 0!==o.gasUsed&&(s.gasUsed=o.gasUsed),void 0!==r.slippageToleranceFactor&&(s.slippageTolerance=r.slippageToleranceFactor),s}const Rw="5.0.3";class Lw{constructor(e){this.logger=e||new S({debug:!1,context:"LiquidityEventExtractor"})}walkPayloadForLiquidityEvents(e,t){const n=[],r=new WeakSet,o=(e,i=0)=>{if(i>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.extractLiquidityFromObject(e);s&&!t.has(s.transactionId)&&(n.push(s),t.add(s.transactionId));for(const t of Object.values(e))o(t,i+1)}};return o(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,o=this.extractPositionId(r),i=this.extractPoolHash(r),s=this.extractAmounts(r),a=this.extractUserAddress(r),c=this.extractPoolFee(r);if(!(o&&i&&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,p={transactionId:t,positionId:o,poolHash:i,poolFee:c,amounts:s,userAddress:a};return void 0!==d&&(p.token0=d),void 0!==f&&(p.token1=f),void 0!==h&&(p.timestamp=h),void 0!==u&&(p.poolAlias=u),void 0!==l&&(p.userBalanceDelta=l),p}extractTransactionId(e){const t=["transactionId","txId","tx_id","hash","txHash","id"];for(const n of t){const t=e[n];if("string"==typeof t&&t.trim())return t}return null}extractPositionId(e){const t=["positionId","position_id","tokenId","nftId"];for(const n of t){const t=e[n];if("string"==typeof t&&t.trim())return t}return null}extractPoolHash(e){const t=["poolHash","pool_hash","poolId","pool"];for(const n of t){const t=e[n];if("string"==typeof t&&t.trim())return t}return null}extractPoolAlias(e){const t=["poolAlias","pool_alias"];for(const n of t){const t=e[n];if("string"==typeof t&&t.trim())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("string"==typeof t&&t.trim())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("string"==typeof t){const e=Number(t);if(!Number.isNaN(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("string"==typeof t){const e=new Date(t).getTime();if(!Number.isNaN(e))return e}}}extractUserBalanceDelta(e){const t=e.userBalanceDelta;if(!t||"object"!=typeof t)return;const n=t,r=this.extractBalanceObject(n.token0Balance),o=this.extractBalanceObject(n.token1Balance);if(!r&&!o)return;const i={};return void 0!==r&&(i.token0Balance=r),void 0!==o&&(i.token1Balance=o),i}extractBalanceObject(e){if(!e||"object"!=typeof e)return;const t=e,n=t.collection,r=t.category,o=t.type,i=t.additionalKey,s=t.quantity,a=t.owner;return"string"==typeof n&&"string"==typeof r&&"string"==typeof o&&"string"==typeof i&&"string"==typeof s&&"string"==typeof a?{collection:n,category:r,type:o,additionalKey:i,quantity:s,owner:a}:void 0}}class Ow{constructor(e){this.wallet=e.wallet;let n=null,r="STAGE";e.env?(r=e.env,n=Bw(e.env)):e.baseUrl?.includes("prod")?(r="PROD",n=Bw("PROD")):(r="STAGE",n=Bw("STAGE")),this.environment=r,this.config={baseUrl:n.launchpadBaseUrl,galaChainBaseUrl:n.galaChainBaseUrl,bundleBaseUrl:n.bundleBaseUrl,webSocketUrl:n.webSocketUrl,dexApiBaseUrl:n.dexApiBaseUrl,dexBackendBaseUrl:n.dexBackendBaseUrl,launchpadFrontendUrl:n.launchpadFrontendUrl,timeout:3e4,debug:!1,...e},this.logger=new S({debug:this.config.debug??!1,context:"LaunchpadSDK"}),this.validateConfiguration(),this.slippageToleranceFactor=void 0===e.slippageToleranceFactor?Ow.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR:this.parseSlippageToleranceFactor(e.slippageToleranceFactor),this.maxAcceptableReverseBondingCurveFeeSlippageFactor=void 0===e.maxAcceptableReverseBondingCurveFeeSlippageFactor?Ow.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR:this.parseFeeSlippageFactor(e.maxAcceptableReverseBondingCurveFeeSlippageFactor),this.calculateAmountMode=e.calculateAmountMode||Ow.DEFAULT_CALCULATE_AMOUNT_MODE,this.pricingConcurrency=e.pricingConcurrency||5,this.galaChainAddressOverride=e.galaChainAddress,this.auth=new E({wallet:e.wallet,messagePrefix:"Create a GalaChain Wallet"}),this.http=new A(this.auth,this.config),this.galaChainHttp=new A(this.auth,{...this.config,baseUrl:this.config.galaChainBaseUrl}),this.bundleHttp=new A(this.auth,{...this.config,baseUrl:this.config.bundleBaseUrl}),this.dexApiHttp=new A(this.auth,{...this.config,baseUrl:this.config.dexApiBaseUrl}),this.dexBackendHttp=new A(this.auth,{...this.config,baseUrl:this.config.dexBackendBaseUrl}),this.galaChainPublicAxios=t.create({baseURL:this.config.galaChainBaseUrl,timeout:this.config.timeout||3e4,headers:{"Content-Type":"application/json",Accept:"application/json"}}),this.cache=new wo(e.debug||!1),this.launchpadService=new Kn(this.http),this.tokenResolverService=new to(this.launchpadService.poolService),this.launchpadAPI=new Ci(this.http,this.tokenResolverService,this.logger,this.bundleHttp,this.galaChainHttp,this.dexApiHttp,this.calculateAmountMode),this.galaChainService=new Lr(this.galaChainHttp,e.wallet,this.tokenResolverService,e.debug||!1,this.galaChainPublicAxios),this.dexService=new Or(this.dexBackendHttp,this.cache,this.galaChainService,e.debug||!1),this.bundleService=new Qr(this.bundleHttp,this.tokenResolverService,this.config.debug||!1,e.wallet,e.wallet?this.getAddress():void 0,this.slippageToleranceFactor,this.maxAcceptableReverseBondingCurveFeeSlippageFactor),this.websocketService=new eo({url:this.config.webSocketUrl},this.config.debug),this.priceHistoryService=new io(this.dexBackendHttp,this.config.debug||!1,this.tokenResolverService),this.dexQuoteService=new ko(this.galaChainHttp,this.config.galaChainBaseUrl,e.debug||!1,e.dexQuoteNetworkTimeout||3e4),this.gswapService=new mo({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 bo(this.dexBackendHttp,this.config.dexBackendBaseUrl,this.gswapService,this.pricingConcurrency,e.debug||!1)}createOverrideSdk(e){if(!e||"string"!=typeof e)throw j("Invalid privateKey: must be a non-empty string","privateKey");if(!e.match(/^0x[a-fA-F0-9]{64}$/))throw j('Invalid privateKey format: must be "0x" followed by 64 hexadecimal characters',"privateKey");const t=new n.Wallet(e),r={...this.config,wallet:t};return new Ow(r)}getAddress(){return this.galaChainAddressOverride?this.galaChainAddressOverride:(this.validateWallet(),this.auth.getAddress())}getEthereumAddress(){return this.validateWallet(),this.wallet.address}validateWallet(){if(!this.wallet)throw new x("Wallet is required for this operation",void 0,"WALLET_REQUIRED");return this.wallet}setWallet(e){if(!e||"object"!=typeof e||!("address"in e))throw new x("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:yo.GAS_FEE}}getVersion(){return Rw}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.pools),t}async fetchAllPools(e){const t=await this.launchpadService.fetchAllPools(e);return await this.warmCacheFromPools(t.pools),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 fetchTokenBadges(e){return this.launchpadService.fetchTokenBadges(e)}async fetchTokenPrice(e){const{tokenName:t,tokenId:n,currentSupply:r,calculateAmountMode:o}=e;if(t&&!n){const e={tokenName:t};return r&&(e.currentSupply=r),o&&(e.calculateAmountMode=o),this.fetchLaunchpadTokenSpotPrice(e)}if(n&&!t)try{return await this.dexService.fetchTokenPrice({tokenId:n})}catch(e){const t=function(e){if(q(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=(await this.fetchTokenDetails(n)).name.trim().toLowerCase();if(!/^[a-z0-9]{3,20}$/.test(t))throw this.logger.error(`Token name extracted from GalaChain doesn't match launchpad format: "${t}"`),e;this.logger.debug(`Falling back to launchpad pricing using extracted token name: "${t}"`);const i={tokenName:t};return r&&(i.currentSupply=r),o&&(i.calculateAmountMode=o),this.fetchLaunchpadTokenSpotPrice(i)}catch(t){throw this.logger.error(`Launchpad fallback failed: ${$(t)}`),e}}throw e}if(!t&&!n)throw z("tokenName or tokenId","Either tokenName (for launchpad tokens) or tokenId (for DEX tokens) is required");throw new x("tokenName and tokenId are mutually exclusive - provide only one","params","INVALID_PARAMS")}async fetchGalaPrice(){return this.fetchTokenPrice({tokenId:{collection:"GALA",category:"Unit",type:"none",additionalKey:"none"}})}async fetchLaunchpadTokenSpotPrice(e){const t="string"==typeof e?{tokenName:e}:e;return this.dexService.fetchLaunchpadTokenSpotPrice(t.tokenName,e=>this.launchpadAPI.calculateBuyAmount(e),e=>this.fetchPoolDetails(e))}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(B(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 en}),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 Pw({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 Do(this.dexApiHttp,this.config.debug??!1)),this._bridgeableTokenService}getWrappableTokenService(){return this._wrappableTokenService||(this._wrappableTokenService=new Lo(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 ji({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 wi({galaConnectClient:this.getGalaConnectClient(),wrappableTokenService:this.getWrappableTokenService(),...e&&{walletAddress:this.getAddress(),wallet:e}})}return this._wrapService}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 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 en}),n=t(e.address);if(e.tokenId){const{normalizeToTokenInstanceKey:t}=await Promise.resolve().then(function(){return dr}),r=t(e.tokenId),{collection:o,category:i,type:s,additionalKey:a}=r;return this.galaChainService.fetchTokenBalance({owner:n,collection:o,category:i,additionalKey:a,type:s,instance:"0"},e.withExpired??!1)}if(e.tokenName){const t=e.tokenName.toUpperCase();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];return t?{quantity:t.quantity,collection:t.collection||"Token",category:"Unit",tokenId:`${t.collection||"Token"}|Unit|${t.symbol}|none`,symbol:t.symbol,name:t.name}:null}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:o,calculateAmountMode:i,currentSupply:s}=e;let a=t;void 0===i&&void 0===s||(a={tokenName:t,...void 0!==i&&{calculateAmountMode:i},...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!==o&&(u.privateKey=o),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 H("No transaction ID returned from buy operation");return this.waitForConfirmation(n,t=>Uw(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 H("No transaction ID returned from sell operation");return this.waitForConfirmation(n,t=>Uw(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=>{Dw(n,t);const r=n?.data||{};if(!function(e){if(!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 Nw(`Invalid launch data received for transaction ${t}`);const o={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&&(o.tokenImage=e.tokenImage),void 0!==e.preBuyQuantity&&(o.preBuyQuantity=e.preBuyQuantity),o.vaultAddress&&this.tokenResolverService.set(e.tokenName,o.vaultAddress),o})}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 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 en}),n=t(e)||this.getAddress();return this.launchpadService.fetchProfile(n)}async fetchReferralUrl(){this.validateWallet();const e=this.getAddress();return await this.dexApiHttp.get(mn,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 en}),r=n(e.address);if(!r)throw new x(`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,o={pageNumber:n,limit:r,sortBy:e?.sortBy??"joined",sortDir:e?.sortDir??"desc"},i=await this.dexApiHttp.get(yn,o,{"x-wallet-address":t});if(!Array.isArray(i))throw new C("Unexpected API response: expected array, got "+typeof i);return{referrals:i,page:n,limit:r,hasMore:i.length===r}}async fetchAllReferrals(e){const t=[];let n=1;let r=!0;for(;r&&n<=100;){const o=await this.fetchReferrals({...e,page:n,limit:100});t.push(...o.referrals),r=o.hasMore,n++}return{referrals:t,total:t.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 en}),r=n(e.address);if(!r)throw new x(`Invalid address format: "${e.address}". Expected formats: eth|0x..., 0x..., or client|...`);t=r}else t=this.getAddress();const n=await this.dexApiHttp.get(wn,void 0,{"x-wallet-address":t});if(!n||"number"!=typeof n.referralCount||!n.rewardTotals)throw new C(`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 en}),r=n(e.address);if(!r)throw new x(`Invalid address format: "${e.address}". Expected formats: eth|0x..., 0x..., or client|...`);t=r}else t=this.getAddress();const n=await this.dexApiHttp.post(bn,{address:t});if(!n||"boolean"!=typeof n.exists)throw new C(`Unexpected API response: expected { exists, walletAlias? }, got ${JSON.stringify(n)}`);if(n.exists){if(!n.walletAlias)throw new C(`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 en}),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 en}),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 en}),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 en}),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 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 en}),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 en}),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 en});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(){if(("number"!=typeof this.config.timeout||this.config.timeout<=0||this.config.timeout>3e5)&&(this.logger.warn(`Invalid timeout value: ${this.config.timeout}. Using default 30000ms.`),this.config.timeout=3e4),!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=parseFloat(String(e));return isNaN(t)||t<0||t>1?(this.logger.warn(`Invalid slippage tolerance factor: ${e}, using default: ${Ow.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR}`),Ow.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR):t}parseFeeSlippageFactor(e){const t=parseFloat(String(e));return isNaN(t)||t<0||t>1?(this.logger.warn(`Invalid fee slippage factor: ${e}, using default: ${Ow.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR}`),Ow.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 _w(e,n.status,n.message);let r;try{r=t(n)}catch(t){if(t instanceof Nw)throw t;throw new Nw(`Failed to transform WebSocket response for transaction ${e}`,t instanceof Error?t:new Error(String(t)))}return this.logger.debug(`Transaction confirmed: ${e}`,r),r}catch(t){if(this.logger.error(`Transaction confirmation failed: ${e}`,t),t instanceof _w||t instanceof Nw)throw t;throw new Nw(`WebSocket confirmation failed for transaction ${e}`,t instanceof Error?t:new Error(String(t)))}}async warmCacheFromPools(e){if(!e||!Array.isArray(e))return;const{extractMetadataFromPoolData:t,isValidPoolForCaching:n}=await Promise.resolve().then(function(){return Kw});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,o,i=.01){return this.validateWallet(),this.gswapService.executeSwap({fromToken:e,toToken:t,inputAmount:n,estimatedOutput:r,feeTier:o,slippageTolerance:i})}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 o,i;"string"==typeof n?(o=n,i=r):"object"==typeof n?i=n:r&&(i=r);return await this.gswapService.getUserLiquidityPositions(e,t,o,i)}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,o,i,s){return this.gswapService.getLiquidityPositionById(e,t,n,r,o,i,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 o=t?.minTVL,i=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.pools.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),o){if((t.token0Tvl+t.token1Tvl)/2<o)return}if(i&&i.length>0){if(!(i.includes(t.token0)||i.includes(t.token1)))return}e(t)}})}catch(e){u++;const t=e instanceof Error?e.message:String(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 o=t?.creatorAddress,i=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.pools.forEach(t=>{i.has(t.tokenName)||((e=>{if(i.set(e,!0),i.size>1e3){const e=i.keys().next().value;void 0!==e&&i.delete(e)}})(t.tokenName),o&&t.creatorAddress!==o||e(t))})}catch(e){c++;const t=e instanceof Error?e.message:String(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="number"==typeof e?e:Number.parseFloat(String(e).replace("%","").trim());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();if(!t.includes("/"))return null;const n=t.split("/");return 3!==n.length?null:n[0]&&n[1]&&n[2]?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")||"",o=this.normalizeFee(t.feeTier??t.fee??t.feeTierBps??t.liquidityFeeBps??t.feeBps);return n&&r&&null!==o?`${n}/${r}/${o}`:null}parsePoolPairString(e){const t=e.split("/");if(3!==t.length)return null;const n=t[0].split("|")[0],r=t[1].split("|")[0],o=t[2];return n&&r&&o?{token0:n,token1:r,fee:o,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,o=r.token0Balance??r.token0??r.baseBalance??r.primaryBalance,i=r.token1Balance??r.token1??r.quoteBalance??r.secondaryBalance,s=this.serializeBalanceToken(o),a=this.serializeBalanceToken(i),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 o=this.buildPoolPairFromObject(t);if(o)return this.parsePoolPairString(o);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,o=e.token0===n||e.token1===n,i=e.token0===r||e.token1===r;if(!o||!i||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 new Error("WebSocket service not initialized");let n=!1,r=null;const o=(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||"",isFinalized:r.isFinalized||!1};this.matchesCreatorFilter(n,t?.creatorFilter)&&e(n)}}}}catch(e){this.logger.warn(`Error processing token creation broadcast: ${e instanceof Error?e.message:String(e)}`)}};let i=this.websocketService.getSocket();if(i)i.onAny(o),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: ${e instanceof Error?e.message:String(e)}`);this.logger.warn("Failed to establish WebSocket connection:",e),t?.onError&&t.onError(n)});let e=0;const s=()=>{if(i=this.websocketService.getSocket(),!i&&e<Ow.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS)return e++,void(r=setTimeout(()=>s(),Ow.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS));if(!i&&e>=Ow.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS){const e=new Error(`WebSocket not available after ${Ow.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS*Ow.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS}ms`);return this.logger.warn("Token creation broadcast subscription timeout:",e.message),void(t?.onError&&t.onError(e))}i&&(i.onAny(o),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(o),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 o=this.extractPoolDataFromPayload(e);o&&!t.has(o.poolPair)&&(t.add(o.poolPair),r.push(o));for(const o of Object.values(e)){const e=this.walkPayloadForPools(o,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 new Error("WebSocket service not initialized");let n=!1,r=null;const o=new Set,i=(n,...r)=>{try{for(const n of r){const r=this.walkPayloadForPools(n,o);for(const n of r)this.matchesPoolFilter(n,t)&&e(n)}}catch(e){this.logger.warn(`Error processing DEX pool broadcast: ${e instanceof Error?e.message:String(e)}`)}};let s=this.websocketService.getSocket();if(s)s.onAny(i),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: ${e instanceof Error?e.message:String(e)}`);this.logger.warn("Failed to establish WebSocket connection:",e),t?.onError&&t.onError(n)});let e=0;const o=()=>{if(s=this.websocketService.getSocket(),!s&&e<Ow.DEX_POOL_SOCKET_WAIT_ATTEMPTS)return e++,void(r=setTimeout(()=>o(),Ow.DEX_POOL_SOCKET_POLL_INTERVAL_MS));if(!s&&e>=Ow.DEX_POOL_SOCKET_WAIT_ATTEMPTS){const e=new Error(`WebSocket not available after ${Ow.DEX_POOL_SOCKET_WAIT_ATTEMPTS*Ow.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(i),n=!0,this.logger.debug("DEX pool broadcast listener registered"))};o()}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(i),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 new Error("WebSocket service not initialized");let n=null,r=null,o=null,i=!1;const s=async e=>{const t=Eo.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));i=!0,r=new Co(c,s,this.dexQuoteService,t||{},this.logger),o=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: ${e instanceof Error?e.message:String(e)}`);this.logger.warn("Failed to establish WebSocket connection:",e),t?.onError&&t.onError(n)})),a(),()=>{try{n&&clearTimeout(n),o&&i&&o(),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 new Error("WebSocket service not initialized");let n=!1,r=null;const o=new Set,i=new Lw(this.logger),s=(n,...r)=>{try{for(const n of r){const r=i.walkPayloadForLiquidityEvents(n,o);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: ${e instanceof Error?e.message:String(e)}`)})}catch(e){this.logger.warn(`Error in liquidity event callback: ${e instanceof Error?e.message:String(e)}`)}}}catch(e){this.logger.warn(`Error processing DEX liquidity broadcast: ${e instanceof Error?e.message:String(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: ${e instanceof Error?e.message:String(e)}`);this.logger.warn("Failed to establish WebSocket connection:",e),t?.onError&&t.onError(n)});let e=0;const o=()=>{if(a=this.websocketService.getSocket(),!a&&e<Ow.DEX_POOL_SOCKET_WAIT_ATTEMPTS)return e++,void(r=setTimeout(()=>o(),Ow.DEX_POOL_SOCKET_POLL_INTERVAL_MS));if(!a&&e>=Ow.DEX_POOL_SOCKET_WAIT_ATTEMPTS){const e=new Error(`WebSocket not available after ${Ow.DEX_POOL_SOCKET_WAIT_ATTEMPTS*Ow.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"))};o()}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?.toLowerCase().includes(t.tokenFilter.toLowerCase()),r=e.token1?.toLowerCase().includes(t.tokenFilter.toLowerCase());if(!n&&!r)return!1}if(t.pairTokens){const[n,r]=t.pairTokens.map(e=>e.toLowerCase()),o=e.token0?.toLowerCase()||"",i=e.token1?.toLowerCase()||"",s=o.includes(n)&&i.includes(r),a=o.includes(r)&&i.includes(n);if(!s&&!a)return!1}if(t.minAmount){const n=parseFloat(t.minAmount),r=parseFloat(e.amounts[0])||0,o=parseFloat(e.amounts[1])||0;if(Math.abs(r)<n&&Math.abs(o)<n)return!1}return!0}normalizeFeeTier(e){if("number"==typeof e)return e>=100?e:Math.round(1e4*e);const t=e.replace("%","").trim(),n=parseFloat(t);return n>=100?n:Math.round(1e4*n)}async cleanup(){try{this.logger.debug("Starting cleanup..."),this.http.cleanup(),this.websocketService&&this.websocketService.disconnect(),this.logger.debug("Cleanup completed")}catch(e){this.logger.error("Error during cleanup:",e)}}static cleanupAll(e=!1){const t=new S({debug:e,context:"LaunchpadSDK"});t.debug("Starting global cleanup...");const{WebSocketService:n}=require("./services/WebSocketService");n.cleanupAll(e),t.debug("Global cleanup completed")}}Ow.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR=.15,Ow.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR=.01,Ow.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY=yo.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY,Ow.DEFAULT_CALCULATE_AMOUNT_MODE=Bi.LOCAL,Ow.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS=30,Ow.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS=100,Ow.DEX_POOL_SOCKET_WAIT_ATTEMPTS=30,Ow.DEX_POOL_SOCKET_POLL_INTERVAL_MS=100;class Fw{static generateWallet(){try{const e=n.Wallet.createRandom();if(!e.mnemonic?.phrase)throw new Error("Failed to generate wallet with mnemonic phrase");const t=this.toGalaAddress(e.address);return{privateKey:e.privateKey,address:e.address,galaAddress:t,mnemonic:e.mnemonic.phrase,wallet:new n.Wallet(e.privateKey)}}catch(e){if("undefined"!=typeof process&&"test"===process.env.NODE_ENV){const e=`test-wallet-${Date.now()}-${++this.testCounter}`,t="0x"+Buffer.from(e).toString("hex").padStart(64,"1").slice(0,64),r=new n.Wallet(t),o=this.toGalaAddress(r.address);return{privateKey:r.privateKey,address:r.address,galaAddress:o,mnemonic:"test test test test test test test test test test test junk",wallet:r}}throw e}}static fromPrivateKey(e){const t=new n.Wallet(e),r=this.toGalaAddress(t.address);return{privateKey:t.privateKey,address:t.address,galaAddress:r,mnemonic:"",wallet:t}}static fromMnemonic(e,t=0){try{const r=n.Mnemonic.fromPhrase(e),o=n.HDNodeWallet.fromMnemonic(r,`m/44'/60'/0'/0/${t}`),i=new n.Wallet(o.privateKey),s=this.toGalaAddress(i.address);return{privateKey:i.privateKey,address:i.address,galaAddress:s,mnemonic:e,wallet:i}}catch(r){if("undefined"!=typeof process&&"test"===process.env.NODE_ENV){const r=`test-mnemonic-index-${t}-${e}`,o="0x"+Buffer.from(r).toString("hex").padStart(64,"1").slice(0,64),i=new n.Wallet(o),s=this.toGalaAddress(i.address);return{privateKey:i.privateKey,address:i.address,galaAddress:s,mnemonic:e,wallet:i}}throw r}}static toGalaAddress(e){const t=e.replace(/^0x/i,"");if(!/^[a-fA-F0-9]{40}$/.test(t))throw new Error(`Invalid Ethereum address format: ${e}`);return`eth|${t}`}static toEthereumAddress(e){if(!e.startsWith("eth|"))throw new Error(`Invalid Gala address format: ${e}. Must start with 'eth|'`);const t=e.slice(4);if(!/^[a-fA-F0-9]{40}$/.test(t))throw new Error(`Invalid address in Gala format: ${e}`);return`0x${t}`}static isValidEthereumAddress(e){try{const t=e.replace(/^0x/i,"");return/^[a-fA-F0-9]{40}$/.test(t)}catch{return!1}}static isValidGalaAddress(e){try{if(!e.startsWith("eth|"))return!1;const t=e.slice(4);return/^[a-fA-F0-9]{40}$/.test(t)}catch{return!1}}static generateMultipleWallets(e=1){if(e<1||e>100)throw new Error("Count must be between 1 and 100");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 Mw(e){if(void 0===e)return Fw.generateWallet();const t=e.trim();if(!t)throw new Error("Input cannot be empty string");if(function(e){const t=e.replace(/^0x/i,"");return/^[a-fA-F0-9]{64}$/.test(t)}(t))return Fw.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 Fw.fromMnemonic(t);throw new Error(`Unable to detect input format. Expected:\n- Private key: 64 hexadecimal characters (with or without 0x prefix)\n- Mnemonic: 12 or 24 space-separated words\nReceived: "${t.slice(0,50)}${t.length>50?"...":""}"`)}Fw.testCounter=0;class $w{static fastValidation(e,t,n,r=$w.DEFAULT_CONFIG){const o=Date.now();let s=!0;try{const a=new i(e.sqrtPrice),c=new i(t.sqrtPrice);n.zeroForOne?c.gte(a)&&(this.logger.error("Fast validation failed: price did not decrease for zeroForOne swap",{originalSqrtPrice:a.toString(),updatedSqrtPrice:c.toString(),zeroForOne:n.zeroForOne}),s=!1):c.lte(a)&&(this.logger.error("Fast validation failed: price did not increase for oneForZero swap",{originalSqrtPrice:a.toString(),updatedSqrtPrice:c.toString(),zeroForOne:n.zeroForOne}),s=!1);const u=new i(e.liquidity),l=new i(t.liquidity);if(!u.isZero()){const e=l.minus(u).abs().div(u);e.gt(r.maxLiquidityChangePct)&&this.logger.warn("Fast validation warning: large liquidity change detected (could be legitimate)",{originalLiquidity:u.toString(),updatedLiquidity:l.toString(),changePct:e.times(100).toFixed(2)})}const h=new i(e.feeGrowthGlobal0),d=new i(t.feeGrowthGlobal0),f=new i(e.feeGrowthGlobal1),p=new i(t.feeGrowthGlobal1);n.zeroForOne?p.lt(f)&&(this.logger.error("Fast validation failed: feeGrowthGlobal1 decreased for zeroForOne",{originalFeeGrowth1:f.toString(),updatedFeeGrowth1:p.toString()}),s=!1):d.lt(h)&&(this.logger.error("Fast validation failed: feeGrowthGlobal0 decreased for oneForZero",{originalFeeGrowth0:h.toString(),updatedFeeGrowth0:d.toString()}),s=!1);const g=new i(e.protocolFeesToken0),m=new i(t.protocolFeesToken0),y=new i(e.protocolFeesToken1),w=new i(t.protocolFeesToken1);m.lt(g)&&(this.logger.error("Fast validation failed: protocolFeesToken0 decreased",{originalProtocolFees0:g.toString(),updatedProtocolFees0:m.toString()}),s=!1),w.lt(y)&&(this.logger.error("Fast validation failed: protocolFeesToken1 decreased",{originalProtocolFees1:y.toString(),updatedProtocolFees1:w.toString()}),s=!1);const b=Date.now()-o;return this.logger.debug("Fast validation completed",{passed:s,elapsedMs:b}),s}catch(e){return this.logger.error("Fast validation exception",e),!1}}static moderateValidation(e,t,n=$w.DEFAULT_CONFIG){const r=Date.now(),o=[];let a=0;try{if(t.actualSqrtPrice){const r=new i(e.sqrtPrice),s=new i(t.actualSqrtPrice),c=this.calculateDriftPercentage(r,s);a=c,c>100*n.maxDriftThreshold&&o.push(`Price drift detected: ${c.toFixed(4)}% (threshold: ${(100*n.maxDriftThreshold).toFixed(4)}%)`),this.logger.debug("Price drift comparison",{calculatedSqrtPrice:r.toString(),actualSqrtPrice:s.toString(),driftPct:c.toFixed(4)})}const c=new i(e.sqrtPrice),u=new i(2).pow(96),l=c.dividedBy(u),h=s.sqrtPriceToTick(l),d=e.tick??0,f=Math.abs(h-d);f>n.maxTickDrift&&o.push(`Tick/price mismatch: tick=${d}, calculated=${h}, drift=${f}`);const p=new i(e.feeGrowthGlobal0),g=new i(e.feeGrowthGlobal1),m=new i(e.liquidity);try{Qn(p,g,m)}catch(e){o.push(e.message)}const y=0===o.length,w=!y||a>100*n.maxDriftThreshold,b=Date.now()-r;return this.logger.debug("Moderate validation completed",{isValid:y,shouldRefetch:w,driftPercentage:a,errorCount:o.length,elapsedMs:b}),this.buildValidationResult(y,a,w,o)}catch(e){this.logger.error("Moderate validation exception",e);const t=e instanceof Error?e.message:String(e);return this.buildValidationResult(!1,0,!0,[`Exception during validation: ${t}`])}}static async fullValidation(e,t,n){const r=Date.now(),o=[];let s=0;try{this.logger.debug("Starting full validation with fresh pool data fetch",{poolKey:e});const a=await n(),c=new i(t.pool.sqrtPrice),u=new i(a.pool.sqrtPrice),l=this.calculateDriftPercentage(c,u);s=Math.max(s,l),l>100*this.DEFAULT_CONFIG.maxPriceDriftPct&&o.push(`Price drift: ${l.toFixed(4)}% (cached: ${c.toString()}, fresh: ${u.toString()})`);const h=new i(t.pool.liquidity),d=new i(a.pool.liquidity),f=this.calculateDriftPercentage(h,d);s=Math.max(s,f),f>100*this.DEFAULT_CONFIG.maxLiquidityDriftPct&&o.push(`Liquidity drift: ${f.toFixed(4)}% (cached: ${h.toString()}, fresh: ${d.toString()})`);const p=Object.keys(t.tickDataMap).length,g=Object.keys(a.tickDataMap).length;if(g>0){const e=Math.abs(g-p)/g;e>this.DEFAULT_CONFIG.maxTickCountDriftPct&&o.push(`Tick data incomplete: cached has ${p} ticks, fresh has ${g} ticks (${(100*e).toFixed(2)}% difference)`)}const m=0===o.length,y=!m,w=Date.now()-r;return this.logger.debug("Full validation completed",{poolKey:e,isValid:m,shouldRefetch:y,maxDriftPercentage:s,priceDrift:l,liquidityDrift:f,cachedTickCount:p,freshTickCount:g,errorCount:o.length,elapsedMs:w}),this.buildValidationResult(m,s,y,o)}catch(t){this.logger.error("Full validation exception",{poolKey:e,error:t});const n=t instanceof Error?t.message:String(t);return this.buildValidationResult(!1,0,!0,[`Exception during full validation: ${n}`])}}static calculateDriftPercentage(e,t){if(t.isZero())return this.logger.warn("Cannot calculate drift: actual value is zero"),1/0;return t.minus(e).abs().div(t).times(100).toNumber()}static buildValidationResult(e,t,n,r=[]){let o;if(n&&r.length>0){const e=r.join(" ").toLowerCase();o=e.includes("drift")?"drift":e.includes("tick")&&e.includes("mismatch")?"tick-mismatch":e.includes("tick")?"missing-tick-data":"manual"}const i={isValid:e,driftPercentage:t,shouldRefetch:n,validationErrors:r};return void 0!==o&&(i.refetchReason=o),i}}$w.logger=new S({debug:!1,context:"PoolStateValidator"}),$w.DEFAULT_CONFIG={maxDriftThreshold:.001,maxLiquidityChangePct:.5,maxTickDrift:1,maxTickCountDriftPct:.1,maxPriceDriftPct:.001,maxLiquidityDriftPct:.01};class qw{static calculatePoolStateHash(e){const t=`${e.sqrtPrice.toString()}|${e.liquidity.toString()}|${e.tick||0}`;return p.createHash("sha256").update(t).digest("hex").substring(0,16)}constructor(e,t){this.logger=new S({debug:t?.debug??!1,context:"PoolStateManager"});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=$w.DEFAULT_CONFIG,this.pool=e.pool,this.tickDataMap=e.tickDataMap,this.metadata={lastFullRefetch:Date.now(),swapsSinceRefetch:0,cumulativeDrift:0,processedTransactions:[],stateHash:qw.calculatePoolStateHash(this.pool)};if(!$w.fastValidation(this.pool,this.pool,{transactionId:"init",timestamp:Date.now(),amountSpecified:"0",zeroForOne:!1,exactInput:!0},this.validationConfig)&&this.config.strictValidation)throw new Error("Initial pool state 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){const t=Date.now();if(this.metadata.processedTransactions.includes(e.transactionId))throw this.logger.warn("Duplicate swap transaction",{transactionId:e.transactionId}),new Error(`Duplicate transaction ID: ${e.transactionId}`);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=Io.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(!$w.fastValidation(t.pool,r.updatedPool,e,this.validationConfig)&&this.config.strictValidation)throw new Error("Swap validation failed");if(e.actualAmount0&&e.actualAmount1&&e.actualSqrtPrice){const t=new i(e.actualAmount0),n=new i(e.actualAmount1),o=r.amount0.minus(t).abs(),s=r.amount1.minus(n).abs(),a=t.isZero()?0:o.div(t.abs()).times(100).toNumber(),c=n.isZero()?0:s.div(n.abs()).times(100).toNumber(),u=Math.max(a,c);u>1&&(this.logger.warn("Drift detected in swap delta",{driftPercentage:u.toFixed(2),swapId:e.transactionId}),this.metadata.cumulativeDrift+=u)}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=qw.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=qw.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=n instanceof Error?n.message:String(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:new i(0),amount1:new i(0),feeAmount0:new i(0),feeAmount1:new i(0),ticksCrossed:[],metadata:{calculationTimeMs:Date.now()-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:qw.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 Kw=Object.freeze({__proto__:null,extractMetadataFromPoolData:function(e,t){const n={};if(e.vaultAddress&&(n.vaultAddress=e.vaultAddress),void 0!==e.reverseBondingCurveMinFeePortion){const r=parseFloat(e.reverseBondingCurveMinFeePortion);isNaN(r)?t&&t.debug(`Skipping invalid reverseBondingCurveMinFeePortion for ${e.tokenName}: "${e.reverseBondingCurveMinFeePortion}"`):n.reverseBondingCurveMinFeeFactor=r}if(void 0!==e.reverseBondingCurveMaxFeePortion){const r=parseFloat(e.reverseBondingCurveMaxFeePortion);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}});e.AgentConfig=class{static async quickSetup(e={}){const t=e.environment||this.detectEnvironment(),n=this.setupWallet(e.privateKey),r=e.galaChainAddress||process.env.WALLET_ADDRESS,o={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}:{}},i=new Ow(o),s={sdk:i,wallet:n,config:o};if(!1!==e.autoValidate){const e=await this.validateSetup(i,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 Ow(r),config:r}}static async validateSetup(e,t){const n=[],r=[],o={canTrade:!1,canCreateTokens:!1,hasBalance:!1,connectionHealthy:!1};try{const t=await e.fetchGalaBalance(e.getAddress());if(o.connectionHealthy=!0,t&&t.quantity){const e=parseFloat(t.quantity);o.hasBalance=e>0,o.canTrade=e>=.1,o.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: ${e instanceof Error?e.message:String(e)}`)}try{const t=await e.fetchPools({type:"recent",page:1,limit:1});t.pools&&0!==t.pools.length||r.push("Pool listing not accessible - some features may be limited")}catch(e){r.push(`Pool access test failed: ${e instanceof Error?e.message:String(e)}`)}return{ready:0===n.length&&o.connectionHealthy,sdk:e,wallet:t||Fw.generateWallet(),issues:n,warnings:r,capabilities:o}}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,o]of Object.entries(e)){const{sdk:e}=await this.quickSetup({environment:t,privateKey:o,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?Fw.fromPrivateKey(e):Fw.generateWallet()}return"generate"===e?Fw.generateWallet():Fw.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}},e.BRIDGE_CONTRACT_ABI=ai,e.BRIDGE_TOKEN_METADATA=ii,e.BaseBridgeStrategy=Vi,e.BridgeRateLimiter=Pi,e.BurnError=Ar,e.CALCULATION_MODES=Bi,e.CHAIN_IDS=Vo,e.COMPOSITE_POOL_FETCH_CONCURRENCY=5,e.CROSS_RATE_TYPED_DATA_TYPES=gi,e.ConfigurationError=P,e.DEFAULT_ETHEREUM_BRIDGE_CONTRACT=Qo,e.DEFAULT_ETHEREUM_RPC_URL="https://ethereum.publicnode.com",e.DEFAULT_ETHEREUM_TOKENS=ri,e.DEFAULT_POLL_INTERVAL_MS=15e3,e.DEFAULT_POLL_TIMEOUT_MS=27e5,e.DEFAULT_RATE_LIMIT_RPS=12,e.DEFAULT_SOLANA_BRIDGE_PROGRAM="AaE4dTnL75XqgUJpdxBKg6vS9sTJgBPJwBQRVhD29WwS",e.DEFAULT_SOLANA_RPC_URL="https://api.mainnet-beta.solana.com",e.DEFAULT_SOLANA_TOKENS=oi,e.DexPoolNotFoundError=F,e.DexQuoteError=O,e.ERC20_ABI=si,e.ETHEREUM_BRIDGE_CONTRACT_SEPOLIA=Zo,e.ETHEREUM_TOKENS_PROD=Jo,e.ETHEREUM_TOKENS_STAGE=ei,e.EthereumBridgeStrategy=Xi,e.FileValidationError=Fn,e.GALACHAIN_CHANNELS=Xo,e.GALACONNECT_PRODUCTION_URL=Yo,e.GALA_BRIDGE_TYPED_DATA_DOMAIN=ui,e.GALA_DECIMALS=8,e.GALA_TOKEN_CLASS_KEY={collection:"GALA",category:"Unit",type:"none",additionalKey:"none"},e.GSwapAssetError=R,e.GSwapPoolError=U,e.GSwapQuoteError=_,e.GSwapSwapError=D,e.GalaConnectClient=ji,e.GalaConnectHttpError=Mi,e.IMAGE_EXTENSIONS=Me,e.LAUNCHPAD_TOKEN_DECIMALS=18,e.LEGACY_TYPED_DATA_TYPES=pi,e.LOCK_CONSTRAINTS=yr,e.LaunchpadSDK=Ow,e.LockError=br,e.MAX_BURN_BATCH_SIZE=50,e.MAX_CONCURRENT_POOL_FETCHES=5,e.MAX_LOCK_BATCH_SIZE=100,e.MAX_UNLOCK_BATCH_SIZE=100,e.NetworkError=C,e.PAGINATION_DEFAULTS=kn,e.POOL_FETCH_CONFIG={MAX_CONCURRENT_FETCHES:5,BACKEND_PAGE_SIZE:20},e.POOL_TYPES={RECENT:"recent",POPULAR:"popular"},e.PoolStateManager=qw,e.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"},e.SDK_VERSION=Rw,e.SOLANA_COMPUTE={UNIT_LIMIT:2e5,UNIT_PRICE_MICROLAMPORTS:375e3},e.SOLANA_DISCRIMINATORS=ci,e.SolanaBridgeStrategy=Aw,e.TRADING_TYPES=Ii,e.TokenMetadataService=class extends En{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 e.toLowerCase();return`${e.type||e.symbol||"unknown"}|${e.additionalKey||"none"}`.toLowerCase()}extractMetadata(e){let t,n,r="Token",o="Unit",i="none";if("string"==typeof e)if(e.includes("|")){const s=e.split("|");"Token"===s[0]&&s[2]?(r=s[0],o=s[1]||"Unit",t=s[2],i=s[3]||"none",n=t):(t=s[0],n=t,o=s[1]||"Unit",i=s[3]||"none")}else t=e,n=e;else t=e.type||"unknown",r=e.collection||"Token",o=e.category||"Unit",i=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:o,type:t.toUpperCase(),additionalKey:i,verified:!1}}getDecimalsForToken(e){return{GALA:8,GUSDC:6,USDC:6,USDT:6,WETH:18,DAI:18}[e.toUpperCase()]??18}isCacheExpired(e){return Date.now()-e>this.cacheExpiry}setCacheExpiry(e){this.cacheExpiry=e,this.logger.debug(`Set token metadata cache expiry to ${e}ms`)}},e.TransactionError=N,e.TransactionFailedError=_w,e.ValidationError=x,e.WebSocketError=Nw,e.WebSocketTimeoutError=class extends Nw{constructor(e,t){super(`WebSocket confirmation timeout for transaction ${e} after ${t}ms`),this.name="WebSocketTimeoutError"}},e.addressFormatSchema=se,e.amountMethodSchema=Le,e.amountTypeSchema=Re,e.browserFileSchema=qe,e.bufferFileSchema=Ke,e.buyTokensDataSchema=ut,e.calculatePreMintDataSchema=mt,e.checkPoolOptionsSchema=Ue,e.compareAmounts=function(e,t){const n=new i(e),r=new i(t);return n.comparedTo(r)},e.createLaunchpadSDK=function(e){e||(e={});const{wallet:t,env:r,config:o={},...i}=e,s={...i,...o},{wallet:a,env:c,config:u,...l}=s;let h;if(t)if("string"==typeof t){h=Mw(t).wallet}else{if(!(t instanceof n.Wallet))throw new Error("Invalid wallet input. Expected string (private key or mnemonic) or Wallet instance.");h=t}else{h=Mw().wallet}const d={wallet:h,...r&&{env:r},debug:!1,timeout:3e4,...l};return new Ow(d)},e.createLimitSchema=ge,e.createPaginatedResultSchema=function(e){return o.z.object({data:o.z.array(e),page:o.z.number().int().min(1),limit:o.z.number().int().min(1),total:o.z.number().int().min(0),totalPages:o.z.number().int().min(0),hasNext:o.z.boolean(),hasPrevious:o.z.boolean()})},e.createPoolStateManager=function(e,t){return new qw(e,t)},e.createSolanaWallet=function(){const e=Qy.generate();return{privateKey:Tw.encode(e.secretKey),publicKey:e.publicKey.toBase58(),address:e.publicKey.toBase58()}},e.createTradeDataSchema=ct,e.createWallet=Mw,e.ethereumAddressSchema=ae,e.fetchGalaBalanceOptionsSchema=tt,e.fetchPoolDetailsDataSchema=yt,e.fetchTokenBalanceOptionsSchema=it,e.fileSizeSchema=be,e.fileUploadSchema=$e,e.filenameSchema=ke,e.filterByFeeTier=function(e,t){return e.filter(e=>e.feeTier===t)},e.filterByLiquidity=function(e){return e.filter(e=>new i(e.liquidity).isGreaterThan(0))},e.filterByMinLiquidity=function(e,t){const n=new i(t);return e.filter(e=>new i(e.liquidity).isGreaterThanOrEqualTo(n))},e.filterByPoolKey=function(e,t,n,r){const o=t.toUpperCase(),i=n.toUpperCase();return e.filter(e=>{const t=e.token0.toUpperCase(),n=e.token1.toUpperCase();return(t===o&&n===i||t===i&&n===o)&&e.feeTier===r})},e.filterByToken=function(e,t){const n=t.toUpperCase();return e.filter(e=>e.token0.toUpperCase()===n||e.token1.toUpperCase()===n)},e.filterByTokenPair=function(e,t,n){const r=t.toUpperCase(),o=n.toUpperCase();return e.filter(e=>{const t=e.token0.toUpperCase(),n=e.token1.toUpperCase();return t===r&&n===o||t===o&&n===r})},e.flexibleAddressSchema=ce,e.flexibleFileSchema=ze,e.formatGalaForDTO=Mr,e.formatLaunchpadTokenForDTO=$r,e.formatTokenAmount=function(e,t=6){const n=new i(e);if(!n.isFinite())return"0";if(n.abs().lt(1e-6)&&!n.isZero())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+$/,"")},e.formatTokenDescriptor=function(e){return`${e.collection}|${e.category}|${e.type}|${e.additionalKey}`},e.fromBaseUnits=_i,e.fullNameSchema=ie,e.getAmountOptionsSchema=gt,e.getEnv=function(e,t){return process.env[e]??t},e.getEnvOrThrow=function(e,t){const n=process.env[e];if(!n){throw new Error(t?`${e} not set in root or local .env (${t})`:`${e} not set in root or local .env`)}return n},e.getEthereumAddressFromPrivateKey=function(e){if(!e.match(/^0x[a-fA-F0-9]{64}$/))throw new Error("Invalid private key format. Expected 0x-prefixed 64 hex characters.");return n.getAddress(n.computeAddress(e))},e.getEthereumBridgeContractByEnvironment=ni,e.getEthereumTokenConfig=function(e){const t=e.toUpperCase();return ri.find(e=>e.symbol.toUpperCase()===t||e.symbol.toUpperCase()===`G${t}`)},e.getEthereumTokensByEnvironment=ti,e.getGalaBridgeTypedDataTypes=mi,e.getPublicKeyFromPrivateKey=function(e){if(!e.match(/^0x[a-fA-F0-9]{64}$/))throw new Error("Invalid private key format. Expected 0x-prefixed 64 hex characters.");const t=new n.SigningKey(e);return{publicKey:t.publicKey,compressedPublicKey:t.compressedPublicKey}},e.getSolanaTokenConfig=function(e){const t=e.toUpperCase();return oi.find(e=>e.symbol.toUpperCase()===t||e.symbol.toUpperCase()===`G${t}`)},e.getStaticTokenMetadata=function(e){const t=e.toUpperCase(),n=ii[t];if(n)return n;if(!t.startsWith("G")){const e=ii[`G${t}`];if(e)return e}},e.getTradeOptionsSchema=ht,e.graduateTokenOptionsSchema=Fe,e.graphDataOptionsSchema=Oe,e.groupByFeeTier=function(e){const t=new Map;return e.forEach(e=>{t.has(e.feeTier)||t.set(e.feeTier,[]),t.get(e.feeTier).push(e)}),t},e.groupByPoolKey=function(e){const t=new Map;return e.forEach(e=>{const n=`${e.token0.toUpperCase()}|${e.token1.toUpperCase()}|${e.feeTier}`;t.has(n)||t.set(n,[]),t.get(n).push(e)}),t},e.groupByTokenPair=function(e){const t=new Map;return e.forEach(e=>{const n=`${e.token0.toUpperCase()}/${e.token1.toUpperCase()}`;t.has(n)||t.set(n,[]),t.get(n).push(e)}),t},e.imageExtensionSchema=Ge,e.imageFilenameSchema=We,e.imageMimeTypeSchema=ve,e.imageUploadOptionsSchema=_e,e.isBurnTokenEntry=Er,e.isBurnTokensData=Sr,e.isLockTokenData=kr,e.isLockTokenEntry=fr,e.isLockTokensData=gr,e.isUnlockTokenData=vr,e.isUnlockTokenEntry=pr,e.isUnlockTokensData=mr,e.isValidGalaChainChannel=function(e){return Object.values(Xo).includes(e)},e.isoDateStringSchema=Ee,e.launchTokenDataSchema=Ne,e.loadEnvWithFallback=function(){const e=w.join(process.cwd(),"..","..",".env");b.existsSync(e)&&k.config({path:e});const t=w.join(process.cwd(),".env");b.existsSync(t)&&k.config({path:t})},e.nonNegativeDecimalStringSchema=he,e.optionalUrlSchema=fe,e.pageNumberSchema=pe,e.paginationResultMetaSchema=Ye,e.poolFetchTypeSchema=De,e.poolPaginationSchema=Xe,e.positiveDecimalStringSchema=le,e.privateKeySchema=Te,e.requireNonNegative=Qn,e.requirePositive=function(...e){e.forEach((e,t)=>{if(e.isNaN())throw new Error(`Value at index ${t} must be a valid number, got: NaN`);if(!e.isFinite())throw new Error(`Value at index ${t} must be finite, got: ${e.toString()}`);if(e.isLessThanOrEqualTo(0))throw new Error(`Value at index ${t} must be positive, got: ${e.toString()}`)})},e.requirePositiveWithContext=Zn,e.reverseBondingCurveConfigSchema=Pe,e.reverseBondingCurveConfigurationSchema=wt,e.searchQuerySchema=oe,e.sellTokensDataSchema=lt,e.sortByLiquidity=function(e,t="desc"){return[...e].sort((e,n)=>{const r=new i(e.liquidity),o=new i(n.liquidity);return"desc"===t?o.minus(r).toNumber():r.minus(o).toNumber()})},e.standardLimitSchema=me,e.standardPaginationSchema=je,e.timestampSchema=Se,e.toBaseUnits=Ni,e.tokenCategorySchema=xe,e.tokenCollectionSchema=Ce,e.tokenDescriptionSchema=ne,e.tokenHoldSchema=ot,e.tokenListOptionsSchema=et,e.tokenNameSchema=ee,e.tokenSymbolSchema=te,e.tokenUrlsSchema=Be,e.tradeCalculationMethodSchema=pt,e.tradeCalculationTypeSchema=ft,e.tradeLimitSchema=we,e.tradeListParamsSchema=dt,e.tradePaginationSchema=Ve,e.tradePaginationWithFiltersSchema=Ze,e.tradeTypeBackendSchema=at,e.tradeTypeSchema=st,e.transactionIdSchema=Ae,e.uniqueKeySchema=Ie,e.updateProfileDataSchema=nt,e.uploadProfileImageOptionsSchema=rt,e.urlSchema=de,e.userLimitSchema=ye,e.userPaginationSchema=He,e.userTokenNameSchema=re,e.userTokenTypeSchema=Je,e.userTokensPaginationSchema=Qe,e.validateAddress=St,e.validateAmountString=At,e.validateBuyTokensData=Mt,e.validateCalculatePreMintData=Gt,e.validateCheckPoolOptions=_t,e.validateCreateTradeData=Ft,e.validateFetchGalaBalanceOptions=Ut,e.validateFetchPoolDetailsData=Wt,e.validateFetchTokenBalanceOptions=Ot,e.validateFullName=It,e.validateGetAmountOptions=zt,e.validateGetTradeOptions=qt,e.validateImageUploadOptions=Nt,e.validateLaunchTokenData=Ct,e.validateSearchQuery=Bt,e.validateSellTokensData=$t,e.validateTokenDescription=Et,e.validateTokenListOptions=Dt,e.validateTokenName=kt,e.validateTokenSymbol=vt,e.validateTokenUrls=Pt,e.validateTradeListParams=Kt,e.validateUpdateProfileData=Rt,e.validateUploadProfileImageOptions=Lt,e.validateUserTokenName=xt,e.validateVaultAddress=Tt,e.vaultAddressSchema=ue});
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("ethers"),require("axios"),require("@gala-chain/connect"),require("zod"),require("bignumber.js"),require("uuid"),require("@gala-chain/api"),require("socket.io-client"),require("@gala-chain/dex"),require("node:crypto"),require("path"),require("fs"),require("dotenv"),require("crypto")):"function"==typeof define&&define.amd?define(["exports","ethers","axios","@gala-chain/connect","zod","bignumber.js","uuid","@gala-chain/api","socket.io-client","@gala-chain/dex","node:crypto","path","fs","dotenv","crypto"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).GalaLaunchpadSDK={},e.ethers,e.axios,e.GalaChainConnect,e.z,e.BigNumber,e.uuid,e.GalaChainAPI,e.io,e.GalaChainDex,e.crypto$1,e.path,e.fs,e.dotenv,e.crypto$2)}(this,function(e,t,n,r,i,o,s,a,c,u,l,h,d,f,g){"use strict";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 m,y=p(l),w=p(h),b=p(d),k=p(f);if("undefined"==typeof File){const{File:e}=require("web-file-polyfill");global.File=e}function v(e,t=3e4){return n.create({baseURL:e,timeout:t,headers:{"Content-Type":"application/json"}})}e.AuthErrorType=void 0,(m=e.AuthErrorType||(e.AuthErrorType={})).WALLET_NOT_CONNECTED="WALLET_NOT_CONNECTED",m.SIGNATURE_FAILED="SIGNATURE_FAILED",m.INVALID_ADDRESS="INVALID_ADDRESS",m.MESSAGE_GENERATION_FAILED="MESSAGE_GENERATION_FAILED";class S extends Error{constructor(e,t,n){super(t),this.type=e,this.originalError=n,this.name="AuthError"}}function A(e){return e instanceof Error}function T(e){return A(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 E(e){return A(e)||"object"==typeof e&&null!==e&&"stack"in e&&"string"==typeof e.stack?e.stack:void 0}function I(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 C(e){return"object"==typeof e&&null!==e&&"message"in e&&("response"in e||"request"in e||"config"in e)}function N(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 B(e){if(!e||"object"!=typeof e)return"";const t=e.Message;return"string"==typeof t&&t.trim()?` - ${t}`:""}function x(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 P extends Error{constructor(e,t,n){super(e),this.field=t,this.code=n,this.name="ValidationError"}}class R 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 L extends Error{constructor(e,t,n){super(e),this.transactionId=t,this.code=n,this.name="TransactionError"}}class O extends Error{constructor(e,t,n){super(e),this.originalError=t,this.code=n,this.name="GSwapQuoteError"}}class U extends Error{constructor(e,t,n,r){super(e),this.originalError=t,this.transactionHash=n,this.code=r,this.name="GSwapSwapError"}}class M 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 $ extends Error{constructor(e,t,n){super(e),this.originalError=t,this.code=n,this.name="GSwapPositionError"}}class q extends P{constructor(e,t){super(e,"dexQuote","DEX_QUOTE_ERROR"),this.context=t,this.name="DexQuoteError"}}class K extends P{constructor(e){super(e,"dexPool","DEX_POOL_NOT_FOUND"),this.name="DexPoolNotFoundError"}}function G(e,t){return t||e.charAt(0).toUpperCase()+e.slice(1)}function z(e,t){return new P(`Token "${e}" not found. Please verify the token name is correct.`,"tokenName","TOKEN_NOT_FOUND")}function W(e,t){const n=G(e,t);return new P(`${n} is required`,e,"REQUIRED")}function H(e,t,n){const r=G(e,n);return new P(`${r} must be ${t}`,e,"INVALID_FORMAT")}function j(e,t,n){return new R(e,t,n)}function V(e,t){return new D(e,t)}function X(e,t,n){return new L(e,t,n)}function Q(e,t,n,r){return n&&n.error(`${t}:`,e),j(`${t}: ${T(e)}`,r,A(e)?e:void 0)}function J(e,t,n,r,i){const o=G(e,i);return new P(`${o} must be between ${t} and ${n}${void 0!==r?`, received: ${r}`:""}`,e,"OUT_OF_RANGE")}function Y(e,t,n,r){const i=G(e,r);return new P(`${i} must be at least ${t}${void 0!==n?`, received: ${n}`:""}`,e,"TOO_SMALL")}function Z(e,t,n,r){const i=G(e,r);return new P(`${i} must be at most ${t}${void 0!==n?`, received: ${n}`:""}`,e,"TOO_LARGE")}function ee(e,t,n,r){const i=G(e,r),o=void 0!==n?`, received: ${"object"==typeof n?"object":String(n)}`:"";return new P(`${i} must be ${t}${o}`,e,"INVALID_TYPE")}function te(e,t,n){const r=G(e,n);return new P(`${r} must be a valid number${void 0!==t?`: "${t}"`:""}`,e,"INVALID_NUMBER")}function ne(e){return new P(`Liquidity position not found: ${e}`,"positionId","POSITION_NOT_FOUND")}function re(e,t,n,r){const i=G(e,r);return new P(`Invalid ${i}: ${t}. Must be one of: ${n.join(", ")}`,e,"INVALID_ENUM")}function ie(e,t,n,r){const i=G(e,r);return new P(`${i} must be at most ${t} characters${void 0!==n?`, received: ${n}`:""}`,e,"TOO_LONG")}function oe(e,t){const n=G(e,t);return new P(`${n} cannot be empty`,e,"EMPTY_STRING")}function se(e,t,n,r){if("number"!=typeof e)throw ee(r,"a number",e,r);if(e<t||e>n)throw J(r,t,n,e)}function ae(e,t,n){if("string"!=typeof e)throw ee(n,"a string",e,n);if(e.length>t)throw Z(n,t,e.length)}function ce(e,t){if("number"!=typeof e)throw ee(t,"a number",e,t);if(!Number.isInteger(e))throw ee(t,"an integer",e,t);if(e<=0)throw Y(t,1,e,t)}function ue(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 ee(n,"numeric values",void 0,n);if(r>i)throw new P(`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 ee(t,"a string",e,t);if(!n&&0===e.trim().length)throw W(t,`${t} (non-empty string)`)}function he(e,t){if("ASC"!==e&&"DESC"!==e)throw new P(`${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 P(`${n} minFee must be a valid finite number`,n,"INVALID_FEE_MINIMUM");if(!isFinite(i))throw new P(`${n} maxFee must be a valid finite number`,n,"INVALID_FEE_MAXIMUM");if(r<.1)throw new P(`${n} minFee must be >= 0.1, received ${r}`,n,"INVALID_FEE_MINIMUM");if(i>.5)throw new P(`${n} maxFee must be <= 0.5, received ${i}`,n,"INVALID_FEE_MAXIMUM");if(r>i)throw new P(`${n} minFee (${r}) must be <= maxFee (${i})`,n,"INVALID_FEE_RANGE")}const fe={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},me=100,ye=20,we={MAX_LIMIT:50,DEFAULT_PAGE:1,DEFAULT_LIMIT:20},be=100,ke={PATTERN:/^eth\|[0-9a-fA-F]{40}$/},ve={MAX_LENGTH:100},Se={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}},Ae={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})$/}},Te=60,Ee=31536e3,Ie={MAX_LENGTH:64,PATTERN:/^(galaswap-operation-|galaconnect-operation-)/},Ce={PATTERN:/^[a-fA-F0-9]{64}$/},Ne={STREAM_URL_PATTERN:/^(rtmps?|srt):\/\/.+/},Be=50,xe=1,_e=100,Pe={FULL_NAME:{MIN_LENGTH:1,MAX_LENGTH:100,ALPHABETS_ONLY_PATTERN:/^[a-zA-Z]+(?:\s[a-zA-Z]+)?$/}};function Re(e,t){if(Ye(e))return t;try{return JSON.parse(e)}catch{return t}}function De(e,t=0){if(Ye(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 Le(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 Oe(e,t=0){if(Ye(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 Ue(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 Me(e,t="0"){if(Ye(e))return new o(t);if(o.isBigNumber(e))return e.isNaN()?new o(t):e;try{const n=new o(e);return n.isNaN()||!n.isFinite()?new o(t):n}catch{return new o(t)}}function Fe(e,t){if(Ze(e)||""===e)throw W(t);if(o.isBigNumber(e)){if(e.isNaN())throw te(t,"NaN");return e}try{const n=new o(e);if(n.isNaN())throw te(t,e);if(!n.isFinite())throw te(t,e);return n}catch(n){if(n instanceof P)throw n;throw te(t,e)}}function $e(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 qe(e,t=18){const n=De(e,0);if(0===n)return"0";return n.toFixed(t).replace(/\.?0+$/,"")}function Ke(e){return qe(e,8)}function Ge(e){return qe(e,18)}var ze;!function(e){e.DEBUG="DEBUG",e.INFO="INFO",e.WARN="WARN",e.ERROR="ERROR"}(ze||(ze={}));class We{constructor(e){this.levelPriority={[ze.DEBUG]:0,[ze.INFO]:1,[ze.WARN]:2,[ze.ERROR]:3},this.debugEnabled=e.debug,this.context=e.context||"SDK",this.minLevel=e.minLevel||(e.debug?ze.DEBUG:ze.INFO)}debug(e,t){this.log(ze.DEBUG,e,t)}info(e,t){this.log(ze.INFO,e,t)}warn(e,t){this.log(ze.WARN,e,t)}error(e,t){this.log(ze.ERROR,e,t)}log(e,t,n){if(this.levelPriority[e]<this.levelPriority[this.minLevel])return;if(e===ze.DEBUG&&!this.debugEnabled)return;const r=`[${(new Date).toISOString()}] [${this.context}] [${e}]`,i=this.getConsoleMethod(e);void 0!==n?A(n)?i(`${r} ${t}`,n.message,E(n)??""):i(`${r} ${t}`,n):i(`${r} ${t}`)}getConsoleMethod(e){switch(e){case ze.DEBUG:return console.debug;case ze.INFO:return console.info;case ze.WARN:return console.warn;case ze.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[ze.DEBUG]>=this.levelPriority[this.minLevel]}}const He=new We({debug:!1,context:"DateUtils"});function je(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())?(He.warn(`Invalid date string received: "${e}". Using fallback.`),t||new Date):n}catch(t){return He.warn(`Date parsing error for "${e}":`,t),new Date}}function Ve(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 Xe(e){return Date.now()-e}const Qe={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 Je(e){return"string"==typeof e&&e.trim().length>0}function Ye(e){return null==e||""===e}function Ze(e){return null==e}function et(e,t,n=100){if(void 0!==e&&ce(e,"page"),void 0!==t&&(ce(t,"limit"),t>n))throw new P(`limit must be at most ${n}`,"limit",_.TOO_LARGE)}function tt(e){const t=Object.values(e);return e=>"string"==typeof e&&t.includes(e)}function nt(e){return Object.values(e)}function rt(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 V(`Either ${t} or ${n} must be provided (${i})`,n);if(c&&u)throw V(`Cannot provide both ${t} and ${n}. Provide exactly one (${i}).`,n);return{chosen:c?t:n,hasA:c,hasB:u}}function it(e,t="tokenName",n=fe){if(!Je(e))throw W(t);const r=e.trim();if(0===r.length)throw W(t);if(r.length<n.MIN_LENGTH)throw J(t,n.MIN_LENGTH,n.MAX_LENGTH,r.length,`${t} length`);if(r.length>n.MAX_LENGTH)throw J(t,n.MIN_LENGTH,n.MAX_LENGTH,r.length,`${t} length`);if(!n.PATTERN.test(r))throw new P(`${t} must contain only alphanumeric characters`,t,_.INVALID_FORMAT)}function ot(e,t="tokenName",n=fe){if(null==e)throw W(t,t);if("string"!=typeof e)throw ee(t,"a string",e);const r=e.trim();if(0===r.length)throw W(t,t);if(!n.PATTERN.test(r))throw new P(`${t} must be ${n.MIN_LENGTH}-${n.MAX_LENGTH} alphanumeric characters`,t,_.INVALID_FORMAT)}function st(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 at={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(!Ye(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`:Ve(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 Qe.ETH_ADDRESS.test(n)||Qe.BACKEND_ADDRESS.test(n)||Qe.CLIENT_ADDRESS.test(n)?void 0:`${e} must be a valid wallet address`}};function ct(e){return!e||0===e.trim().length}function ut(e){return e?e.startsWith("0x")?e.slice(2):e:""}const lt={ETHEREUM:Qe.ETH_ADDRESS,ETHEREUM_NO_PREFIX:/^[a-fA-F0-9]{40}$/,BACKEND:Qe.BACKEND_ADDRESS,CLIENT:Qe.CLIENT_ADDRESS};class ht{toBackendFormat(e){if(!Je(e))throw new P("Address is required and must be a string","address","REQUIRED");const t=ut(e);if(!/^[a-fA-F0-9]{40}$/.test(t))throw new P(`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(!Je(e))throw new P("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 P(`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 P(`Invalid backend address format: "${e}"`,"address","INVALID_FORMAT");return e}return this.toBackendFormat(e)}}isValid(e){return!!Je(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 P(`${t} must be a valid wallet address (Ethereum or backend format)`,t,"INVALID_FORMAT")}detectFormat(e){return Je(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 ut(e).toLowerCase();if(/^[a-fA-F0-9]{40}$/.test(e))return e.toLowerCase();throw new P(`Cannot extract hex from address: "${e}". Expected Ethereum or backend format.`,"address","INVALID_FORMAT")}}const dt=new ht,ft=ut;function gt(e){return dt.toBackendFormat(e)}function pt(e){return dt.toEthereumFormat(e)}function mt(e){return dt.normalizeInput(e)}function yt(e){return dt.isValid(e)}function wt(e,t="address"){dt.assertValid(e,t)}function bt(e){const t="string"==typeof e?e:e.address;return dt.toBackendFormat(t)}function kt(e){return dt.detectFormat(e)}var vt=Object.freeze({__proto__:null,AddressFormatter:ht,assertValidWalletAddress:wt,detectFormat:kt,fromBackendAddressFormat:pt,isValidAddress:yt,normalizeAddressInput:mt,stripHexPrefix:ft,toBackendAddressFormat:gt,toBackendAddressFromEthers:bt});class St{constructor(t){if(this.wallet=t.wallet,this.messagePrefix=t.messagePrefix||"Create a GalaChain Wallet",void 0!==t.messagePrefix)try{le(t.messagePrefix,"messagePrefix",!1)}catch{throw new S(e.AuthErrorType.SIGNATURE_FAILED,"Message prefix cannot be empty")}}hasWallet(){return void 0!==this.wallet}setWallet(t){if(void 0!==t){if("object"!=typeof t||!("address"in t))throw new S(e.AuthErrorType.WALLET_NOT_CONNECTED,"Invalid wallet: must be an ethers Wallet instance or undefined");if(!t.address||"string"!=typeof t.address)throw new S(e.AuthErrorType.INVALID_ADDRESS,"Wallet address is not available")}this.wallet=t}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(t){if(t instanceof S)throw t;throw new S(e.AuthErrorType.SIGNATURE_FAILED,"Failed to generate signature for authentication",A(t)?t:new Error(T(t)))}}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 S(e.AuthErrorType.WALLET_NOT_CONNECTED,"Wallet private key not available for @gala-chain signing");return this.wallet.privateKey}formatAddress(t){try{return gt(t)}catch{throw new S(e.AuthErrorType.INVALID_ADDRESS,`Invalid Ethereum address format: ${t}`)}}async signMessage(t){this.validateWallet();try{return{message:t,signature:await this.wallet.signMessage(t),address:this.wallet.address,timestamp:Date.now()}}catch(t){if(t instanceof S)throw t;throw new S(e.AuthErrorType.SIGNATURE_FAILED,T(t),A(t)?t:new Error(T(t)))}}async generateAuthHeaders(t,n){this.validateWallet();try{const e=Date.now(),r=`${this.messagePrefix} ${n.toUpperCase()} ${t} ${e}`,i=await this.wallet.signMessage(r);return{"x-signature":i,"x-address":this.formatAddress(this.wallet.address),"x-message":r,"x-timestamp":e.toString()}}catch(t){if(t instanceof S)throw t;throw new S(e.AuthErrorType.SIGNATURE_FAILED,"Failed to generate authentication headers",A(t)?t:new Error(T(t)))}}async signTypedData(t,n,r){this.validateWallet();try{return await this.wallet.signTypedData(t,n,r)}catch(t){if(t instanceof S)throw t;throw new S(e.AuthErrorType.SIGNATURE_FAILED,"Failed to sign typed data",A(t)?t:new Error(T(t)))}}async generateCustomSignature(t){if(!Je(t))throw new S(e.AuthErrorType.SIGNATURE_FAILED,"Custom message must be a non-empty string");this.validateWallet();try{const e=await this.wallet.signMessage(t);return{message:t,signature:e,address:this.formatAddress(this.wallet.address),timestamp:Date.now()}}catch(t){if(t instanceof S)throw t;throw new S(e.AuthErrorType.SIGNATURE_FAILED,"Failed to generate custom message signature",A(t)?t:new Error(T(t)))}}validateWallet(){if(!this.wallet)throw new S(e.AuthErrorType.WALLET_NOT_CONNECTED,"Wallet is required for authentication");if(!this.wallet.address)throw new S(e.AuthErrorType.WALLET_NOT_CONNECTED,"Wallet address is not available");if(!this.wallet.privateKey&&!this.wallet.signMessage)throw new S(e.AuthErrorType.WALLET_NOT_CONNECTED,"Wallet must have a private key for signing messages")}}const At={REFRESH_THRESHOLD_MS:3e5,DEFAULT_EXPIRY_S:86400,LOGIN_MESSAGE_PREFIX:"Sign in to Launchpad t:",AUTH_HEADER:"Authorization",BEARER_PREFIX:"Bearer "};class Tt{constructor(e=At.REFRESH_THRESHOLD_MS){this.tokenState=null,this.refreshThresholdMs=e}setToken(t,n){if(!Je(t))throw new S(e.AuthErrorType.SIGNATURE_FAILED,"JWT token must be a non-empty string");if("number"!=typeof n)throw new S(e.AuthErrorType.SIGNATURE_FAILED,"Token expiration must be a positive finite number (seconds)");if(!isFinite(n))throw new S(e.AuthErrorType.SIGNATURE_FAILED,"Token expiration must be a positive finite number (seconds)");if(n<=0)throw new S(e.AuthErrorType.SIGNATURE_FAILED,"Token expiration must be a positive finite number (seconds)");const r=Date.now();this.tokenState={token:t.trim(),issuedAt:r,expiresAt:r+1e3*n}}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?`${At.BEARER_PREFIX}${e}`:null}getJwtHeaders(){const t=this.getAuthorizationHeader();if(!t)throw new S(e.AuthErrorType.WALLET_NOT_CONNECTED,"No JWT token available. Call login() first.");return{[At.AUTH_HEADER]:t}}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 Et="/launchpad/upload-image",It="/launchpad/fetch-pool",Ct="/launchpad/check-pool",Nt="/launchpad/get-graph-data",Bt="/holders",xt="/launchpad/get-badge/",_t="/launchpad/socials",Pt="/trade/",Rt="/user/profile",Dt="/user/profile",Lt="/user/token-list",Ot="/user/token-hold",Ut="/v1/user/managed-tokens",Mt="/v1/users/referrals/url",Ft="/v1/users/referrals",$t="/v1/users/referrals/summary",qt="/v1/registered",Kt="/live/:tokenName/start",Gt="/live/:tokenName/stop",zt="/live/:tokenName",Wt="/live/:tokenName/disable",Ht="/live/:tokenName/enable",jt="/live/:tokenName/reset-key",Vt="/live/:tokenName/recordings",Xt="/live/:tokenName/recordings/:assetId/download",Qt="/live/:tokenName/recordings/:assetId",Jt="/live/:tokenName/simulcast",Yt="/live/:tokenName/simulcast",Zt="/live/:tokenName/simulcast/:targetId",en="/live/global/streaming/status",tn="/live/global/streaming/disable",nn="/live/global/streaming/enable",rn="/live/:tokenName/stream/countdown",on="/live/:tokenName/stream/countdown",sn="/live/:tokenName/stream/language",an="/live/:tokenName/role",cn="/live/roles",un="/live/:tokenName/access",ln="/live/:tokenName/chat",hn="/live/:tokenName/chat",dn="/live/:tokenName/chat/:messageId",fn="/live/:tokenName/chat/status",gn="/live/:tokenName/chat/disable",pn="/live/:tokenName/chat/enable",mn="/live/:tokenName/chat/pinned",yn="/live/:tokenName/chat/pin",wn="/live/:tokenName/chat/pin",bn="/live/chat/global/status",kn="/live/chat/global/disable",vn="/live/chat/global/enable",Sn="/live/:tokenName/engagement/stats",An="/auth/login",Tn="/auth/refresh",En="/auth/session",In="/live/:tokenName/bans",Cn="/live/:tokenName/bans",Nn="/live/:tokenName/bans/:userAddress",Bn="/live/:tokenName/bans/:userAddress",xn="/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"},Pn="/v1/moderators/invites",Rn="/v1/moderators/invites/claim",Dn="/v1/moderators/tokens",Ln="/v1/moderators/invites",On="/v1/moderators/invites/:id",Un="/v1/moderators/invites/:id/role",Mn="/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"},$n="/v1/overseer/invites",qn="/v1/overseer/invites",Kn="/v1/overseer/invites/code/:code",Gn="/v1/overseer/invites/claim",zn="/v1/overseer/invites/:id",Wn="/v1/overseer",Hn="/v1/overseer/:address",jn="/v1/overseer/me",Vn="/v1/overseer/summary",Xn="/v1/overseer/users",Qn="/v1/overseer/users/:address",Jn="/v1/overseer/token-bans",Yn="/v1/overseer/token-bans",Zn="/v1/overseer/token-bans/:tokenName",er="/v1/overseer/token-bans/:tokenName",tr="/token/comment",nr="/token/comment",rr="/token/comment/:commentId",ir="/reactions",or="/reactions/:messageId/:reactionType",sr="/v1/trades",ar="/v1/chat-messages",cr="/v1/chat-messages",ur="/v1/chat-messages/:id",lr="/v1/chat-messages/:id",hr="/v1/comments",dr="/v1/comments",fr="/v1/comments/:id",gr="/v1/comments/:id";function pr(e){return null!=e&&"object"==typeof e&&"data"in e}function mr(e,t,n=!1){const r=!0===e.error,i=n&&!e.data;if(r||i)throw j(e?.message||t)}function yr(e){if(pr(e))return e.data}function wr(e,t="No data found in response"){if(!pr(e))throw j(t);const n=e.data;if(null==n)throw j(t);return n}async function br(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),Q(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),Q(e,t,n))}}class vr{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 S(e.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 br(async()=>{const e=Date.now(),t=`${At.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();wt(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(An,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,(t,n,r)=>{if(t instanceof S)throw t;throw new S(e.AuthErrorType.SIGNATURE_FAILED,`Login failed: ${T(t)}`,A(t)?t: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 S(e.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 br(async()=>{this.logger.debug("Refreshing JWT token");const e=await this.http.post(Tn,{},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,(t,n,r)=>{if(t instanceof S)throw t;throw new S(e.AuthErrorType.SIGNATURE_FAILED,`Token refresh failed: ${T(t)}`,A(t)?t:void 0)})}logout(){this.logger.debug("Logging out"),this.jwtAuth.clear()}async getSession(){if(!this.jwtAuth.hasToken())throw new S(e.AuthErrorType.WALLET_NOT_CONNECTED,"Not authenticated. Call login() first.");return br(async()=>{const e=await this.http.get(En,void 0,this.jwtAuth.getJwtHeaders());return this.extractSessionData(e)},"SessionAuthService.getSession",this.logger,(t,n,r)=>{if(t instanceof S)throw t;throw new S(e.AuthErrorType.SIGNATURE_FAILED,`Failed to get session: ${T(t)}`,A(t)?t:void 0)})}getAccessToken(){return this.jwtAuth.getToken()}isAuthenticated(){return this.jwtAuth.isValid()}shouldRefresh(e){return this.jwtAuth.shouldRefresh(e)}async ensureValidToken(t){if(!this.jwtAuth.hasToken())throw new S(e.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(t)){this.logger.debug("Token near expiry - refreshing");return(await this.refresh()).accessToken}return this.jwtAuth.getToken()}extractLoginData(t){if(t.error)throw new S(e.AuthErrorType.SIGNATURE_FAILED,T(t)||"Authentication failed");const n=wr(t,"No data in authentication response"),{accessToken:r,expiresIn:i,address:o}=n;if(!Je(r))throw new S(e.AuthErrorType.SIGNATURE_FAILED,"Invalid access token in response");if(!i||"number"!=typeof i)throw new S(e.AuthErrorType.SIGNATURE_FAILED,"Invalid expiration in response");return{accessToken:r,expiresIn:i,address:o}}extractSessionData(t){if(t.error)throw new S(e.AuthErrorType.SIGNATURE_FAILED,T(t)||"Failed to get session");return wr(t,"No data in session response")}}function Sr(e){if(Ze(e)||"object"!=typeof e)return{};const t={};for(const[n,r]of Object.entries(e))Ze(r)||(Je(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 Ar{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=v(n,r),t.headers&&(this.axios.defaults.headers.common={...this.axios.defaults.headers.common,...t.headers}),this.setupInterceptors()}async request(e){return br(async()=>{const t={method:e.method,url:e.url,data:e.data,...e.params&&{params:Sr(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 br(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,n=r.SigningType.SIGN_TYPED_DATA){const i=this.auth.getPrivateKey(),o=new r.SigningClient(i);return await o.sign(e,t,n)}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||T(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 Tr="Token name is required and must be a string",Er=e=>`Could not find vault address for token: ${e}`,Ir=i.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"),Cr=i.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"),Nr=i.z.string().min(1,"Token description is required").max(500,"Token description must be at most 500 characters"),Br=i.z.string().min(1,"Token name must be at least 1 character").max(50,"Token name must be at most 50 characters"),xr=i.z.string().min(1,"Search query must be at least 1 character").max(100,"Search query must be at most 100 characters"),_r=i.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"),Pr=i.z.string().regex(Qe.BACKEND_ADDRESS,"Address must be in format: eth|[40-hex-chars]"),Rr=i.z.string().regex(Qe.ETH_ADDRESS,"Invalid Ethereum address format"),Dr=i.z.string().refine(e=>Qe.BACKEND_ADDRESS.test(e)||Qe.ETH_ADDRESS.test(e),"Address must be either eth|[40-hex-chars] or 0x[40-hex-chars] format").transform(e=>(new ht).normalizeInput(e)||e),Lr=i.z.string().refine(e=>Qe.BACKEND_ADDRESS.test(e)||/^service\|Token\$Unit\$[A-Z0-9]+\$eth:[0-9a-fA-F]{40}\$launchpad$/.test(e),"Invalid vault address format"),Or=i.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>De(e,0)>0,"Amount must be greater than zero"),Ur=i.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>De(e,0)>=0,"Amount must be zero or greater"),Mr=i.z.string().url("Must be a valid URL").regex(/^https?:\/\//,"URL must start with http:// or https://"),Fr=i.z.string().optional().refine(e=>!e||/^https?:\/\/.+\..+/.test(e),"Must be a valid URL if provided"),$r=i.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 qr(e=100){return i.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 Kr=qr(100),Gr=qr(20),zr=qr(20),Wr=i.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"),Hr=i.z.string().max(255,"Filename must be at most 255 characters"),jr=i.z.enum(["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"]),Vr=i.z.string().datetime("Must be a valid ISO 8601 date string"),Xr=i.z.number().int("Timestamp must be an integer").min(0,"Timestamp must be non-negative"),Qr=i.z.string().regex(/^0x[a-fA-F0-9]{64}$/,"Private key must be format: 0x + 64 hex characters"),Jr=i.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"),Yr=i.z.string().regex(/^galaconnect-operation-[a-z0-9-]+$/,"Unique key must be format: galaconnect-operation-{unique-id}"),Zr=i.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"),ei=i.z.string().min(1,"Token category must not be empty").default("Unit"),ti=i.z.string().min(1,"Token collection must not be empty").default("Token"),ni=i.z.object({minFeePortion:i.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:i.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"]}),ri=i.z.object({tokenName:Ir,tokenSymbol:Cr,tokenDescription:Nr,tokenImage:i.z.union([i.z.instanceof(File),i.z.instanceof(Buffer),i.z.string().url("Token image must be a valid URL")]).optional(),preBuyQuantity:Ur.default("0"),websiteUrl:Fr,telegramUrl:Fr,twitterUrl:Fr,instagramUrl:Fr,facebookUrl:Fr,redditUrl:Fr,tiktokUrl:Fr,tokenCategory:ei,tokenCollection:ti,reverseBondingCurveConfiguration:ni.optional(),privateKey:Qr.optional()}),ii=i.z.object({file:i.z.union([i.z.instanceof(File),i.z.instanceof(Buffer)]),tokenName:Ir}),oi=i.z.enum(["RECENT","POPULAR"]),si=i.z.object({tokenName:Ir.optional(),symbol:Cr.optional()}).refine(e=>e.tokenName||e.symbol,"At least one of tokenName or symbol is required"),ai=i.z.enum(["NATIVE","MEME"]),ci=i.z.enum(["IN","OUT"]),ui=i.z.object({from:i.z.number().int("From timestamp must be an integer").min(173e6,"From timestamp must be at least 173000000"),to:i.z.number().int("To timestamp must be an integer").min(173e6,"To timestamp must be at least 173000000"),resolution:i.z.number().int("Resolution must be an integer").min(1,"Resolution must be at least 1"),tokenName:Ir}),li=i.z.object({tokenName:Ir,slippageToleranceFactor:i.z.number().min(0).max(1).optional(),maxAcceptableReverseBondingCurveFeeSlippageFactor:i.z.number().min(0).max(1).optional(),privateKey:Qr.optional()}),hi=[".png",".jpg",".jpeg",".gif",".webp",".svg"],di=i.z.object({file:i.z.union([i.z.instanceof(File),i.z.instanceof(Buffer)]),name:Hr,size:Wr,type:jr}),fi=i.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=i.z.instanceof(Buffer).refine(e=>e.length>=1&&e.length<=10485760,"Buffer size must be between 1 byte and 10MB"),pi=i.z.union([fi,gi]),mi=i.z.enum([".png",".jpg",".jpeg",".gif",".webp",".svg"]),yi=Hr.refine(e=>{const t=e.slice(e.lastIndexOf(".")).toLowerCase();return hi.includes(t)},`Filename must end with one of: ${hi.join(", ")}`),wi=i.z.object({page:$r,limit:Kr}),bi=i.z.object({page:$r,limit:Gr}),ki=i.z.object({page:$r,limit:zr}),vi=wi.extend({type:i.z.enum(["RECENT","POPULAR"]).optional(),tokenName:i.z.string().min(1).max(50).optional(),search:i.z.string().min(1).max(100).optional()}),Si=bi.extend({tokenName:i.z.string().min(1).max(50).optional(),search:i.z.string().min(1).max(100).optional()}),Ai=ki.extend({tradeType:i.z.enum(["BUY","SELL"]).optional(),tokenName:i.z.string().min(1).max(50).optional(),userAddress:i.z.string().regex(/^(0x[a-fA-F0-9]{40}|eth\|[a-fA-F0-9]{40})$/).optional(),startDate:i.z.string().datetime().optional(),endDate:i.z.string().datetime().optional(),sortOrder:i.z.enum(["ASC","DESC"]).default("DESC")}),Ti=i.z.object({page:i.z.number().int().min(1),limit:i.z.number().int().min(1),total:i.z.number().int().min(0),totalPages:i.z.number().int().min(0),hasNext:i.z.boolean(),hasPrevious:i.z.boolean()});const Ei=i.z.enum(["all","DEFI","ASSET"]),Ii=bi.extend({type:Ei.optional(),address:Dr.optional(),search:xr.optional(),tokenName:Br.optional()}),Ci=i.z.object({address:Dr.optional(),refresh:i.z.boolean().optional()}),Ni=i.z.object({profileImage:i.z.string(),fullName:_r,address:Dr,privateKey:Qr.optional()}),Bi=i.z.object({file:i.z.union([i.z.instanceof(File),i.z.instanceof(Buffer)]),address:Dr.optional(),privateKey:Qr.optional()}),xi=i.z.object({created:i.z.number(),createdBy:i.z.string(),expires:i.z.number(),instanceId:i.z.string(),lockAuthority:i.z.string(),name:i.z.string(),quantity:i.z.string(),vestingPeriodStart:i.z.number()}),_i=i.z.object({address:Dr,tokenId:i.z.union([i.z.string(),i.z.object({collection:i.z.string(),category:i.z.string(),type:i.z.string(),additionalKey:i.z.string()}),i.z.object({collection:i.z.string(),category:i.z.string(),type:i.z.string(),additionalKey:i.z.string(),instance:i.z.string()})]).optional(),tokenName:Br.optional(),withExpired:i.z.boolean().optional()}).refine(e=>void 0!==e.tokenId||void 0!==e.tokenName,"At least one token identifier (tokenId or tokenName) is required"),Pi=i.z.enum(["buy","sell"]),Ri=i.z.enum(["BUY","SELL"]),Di=i.z.object({tradeType:Pi,tokenAmount:Or,vaultAddress:Lr,userAddress:Dr,slippageTolerance:Or.optional(),deadline:i.z.number().int().positive().optional()}),Li=i.z.object({tokenSymbol:Cr,nativeTokenQuantity:Or,expectedToken:Or,maxAcceptableReverseBondingCurveFee:Ur.default("0").optional()}),Oi=i.z.object({tokenSymbol:Cr,tokenQuantity:Or,expectedNativeToken:Or,maxAcceptableReverseBondingCurveFee:Ur.default("0").optional()}),Ui=ki.extend({tokenName:Br.optional()}),Mi=i.z.object({page:i.z.number().int().min(1).max(1e3).default(1).optional(),limit:i.z.number().int().min(1).max(20).default(10).optional()}),Fi=i.z.enum(["NATIVE","MEME"]),$i=i.z.enum(["IN","OUT"]),qi=i.z.object({type:Fi,method:$i,vaultAddress:Lr,amount:Or}),Ki=i.z.object({nativeTokenQuantity:Or}),Gi=i.z.object({vaultAddress:Lr}),zi=i.z.object({minFeePortion:Or,maxFeePortion:Or});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.errors.map(e=>e.message)}}}const Hi=Wi(Ir),ji=Wi(Cr),Vi=Wi(Nr),Xi=Wi(Dr),Qi=Wi(Lr),Ji=Wi(Or),Yi=Wi(_r),Zi=Wi(xr),eo=Wi(Br),to=Wi(ri),no=Wi(Zr),ro=Wi(ii),io=Wi(si),oo=Wi(Ii),so=Wi(Ci),ao=Wi(Ni),co=Wi(Bi),uo=Wi(_i),lo=Wi(Di),ho=Wi(Li),fo=Wi(Oi),go=Wi(Ui),po=Wi(Mi),mo=Wi(qi),yo=Wi(Ki),wo=Wi(Gi);function bo(e,t="0"){return Me(e,t)}function ko(e,t){return void 0!==t?bo(e).toFixed(t):bo(e).toFixed()}function vo(e,t=.01){const n=bo(e),r=new o(1).minus(t);return n.multipliedBy(r)}function So(e=.01){return new o(1).minus(e)}function Ao(e=.01){return new o(1).plus(e)}function To(e){const t=bo(e),n=Math.log(1.0001),r=t.toNumber();return Math.log(r)/n}function Eo(e,t=!1){const n=bo(e),r=new o(1).dividedBy(n);return t?r.toFixed():r}function Io(){return new o(2).pow(96)}function Co(e,t){return o.min(bo(e),bo(t))}function No(e,t){return o.max(bo(e),bo(t))}function Bo(e){return bo(e).isZero()}function xo(e){return bo(e).isGreaterThan(0)}function _o(e){return bo(e).isLessThan(0)}function Po(e,t){return bo(e).isLessThan(bo(t))}function Ro(e,t){return bo(e).multipliedBy(t).dividedBy(100)}function Do(...e){e.forEach(e=>{if(e.isNaN())throw te("value","NaN");if(!e.isFinite())throw Z("value","finite");if(e.isLessThanOrEqualTo(0))throw Y("value","0",e.toString())})}function Lo(...e){e.forEach(e=>{if(e.isNaN())throw te("value","NaN");if(!e.isFinite())throw Z("value","finite");if(e.isLessThan(0))throw Y("value","0",e.toString())})}function Oo(e,t,n){if(e.isNaN())throw te(t,"NaN");if(!e.isFinite())throw Z(t,"finite");if(e.isLessThanOrEqualTo(0))throw Y(t,"0",e.toString())}function Uo(e,t,n="0"){const r=bo(t);return Bo(r)?bo(n):bo(e).dividedBy(r)}function Mo(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(!Je(e))throw new P(`${s} cannot be empty or whitespace-only. Provide a valid numeric string.`,s,"INVALID_NUMERIC_STRING");if(/[eE]/.test(e))throw new P(`${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 P(`${s} must be a valid numeric string. Received: "${e}"`,s,"INVALID_NUMERIC_STRING");if(!isFinite(a))throw new P(`${s} must be a finite number. Cannot be Infinity or -Infinity.`,s,"INVALID_NUMERIC_STRING");if(a<0)throw new P(`${s} must be non-negative. Received: "${e}"`,s,"INVALID_NUMERIC_STRING");if(!n&&0===a)throw new P(`${s} must be greater than zero. Received: "${e}"`,s,"INVALID_NUMERIC_STRING");const c=bo(e),u=c.decimalPlaces()??0;if(u>o)throw new P(`${s} cannot exceed ${o} decimal places. Received: ${u} decimal places`,s,"PRECISION_EXCEEDED");if(void 0!==r&&Po(c,r))throw new P(`${s} must be at least ${r}. Received: "${e}"`,s,"BELOW_MINIMUM");if(void 0!==i&&(l=i,bo(c).isGreaterThan(bo(l))))throw new P(`${s} cannot exceed ${i}. Received: "${e}"`,s,"EXCEEDS_MAXIMUM");var l}parseAmount(e,t="0"){return bo(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=bo(e),i=bo(t),o=bo(n);return function(e,t,n){const r=bo(e),i=bo(t),o=bo(n);return r.isGreaterThanOrEqualTo(i)&&r.isLessThanOrEqualTo(o)}(r,i,o)?ko(r):Po(r,i)?ko(i):ko(o)}}function $o(e,t){throw new P(e.join("; "),t,"VALIDATION_ERROR")}function qo(e){const t=Hi(e);!t.success&&t.errors&&$o(t.errors,"tokenName")}function Ko(e){const t=io(e);!t.success&&t.errors&&$o(t.errors,"options")}function Go(e){const t=ui.safeParse(e);var n;t.success||$o((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 zo(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 Ho={DEFAULT_PAGE:1,DEFAULT_LIMIT:10,BACKEND_MAX_PAGE_SIZE:20,SAFETY_MAX_PAGES:100};function jo(e,t){return ce(e,"page"),ce(t,"limit"),(e-1)*t}function Vo(e,t=1){return Math.max(t,Math.ceil(e||t))}function Xo(e,t=1,n=Ho.BACKEND_MAX_PAGE_SIZE){return Math.max(t,Math.min(n,Math.ceil(e||t)))}function Qo(e,t){if("number"!=typeof e||!Number.isInteger(e))throw ee("total","a non-negative integer",e);if(e<0)throw J("total",0,1/0,e);if("number"!=typeof t||!Number.isInteger(t))throw ee("limit","a non-negative integer",t);if(t<0)throw J("limit",0,1/0,t);return 0===t?1:0===e?0:Math.ceil(e/t)}function Jo(e,t,n){if("number"!=typeof e||!Number.isInteger(e))throw ee("offset","a non-negative integer",e);if(e<0)throw J("offset",0,1/0,e);return e+t<n}function Yo(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=Ue(String(n.page),t.page),i=Ue(String(n.limit),t.limit),o=n.data,s=o?.meta,a=Ue(String(o?.count),0),c=Ue(String(s?.totalItems),a),u=Ue(String(n.total),c);return{page:r,limit:i,total:u,totalPages:Qo(u,i)}}async function es(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 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();if(null==t)throw new P(`${n}: No response from server`,"response","NO_RESPONSE");if(mr(t,n,!0),i&&r&&r.debug(`${n}: completed successfully`),void 0===t.data)throw new P(`${n}: No data returned from API`,"data","NO_DATA");return t.data}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();return i&&r&&r.debug(`${n}: completed successfully`),t}catch(e){throw r&&r.error(n,{error:e}),e}}async function rs(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 P(`${n}: No response from server`,"response","NO_RESPONSE");return mr(t,n,!0),i&&r&&r.debug(`${n}: completed successfully`),t}catch(e){throw r&&r.error(n,{error:e}),e}}function is(e){return e.trim().toLowerCase()}function os(e){return e.trim().toUpperCase()}function ss(e){return e.trim().toUpperCase()}function as(e,t,n){if(!Ze(e)){if("string"!=typeof e)throw ee(t,"a string",e,t);if(e.length>n)throw new P(`${t} must be at most ${n} characters`,t,_.TOO_LARGE)}}function cs(e,t){ce(e,t)}function us(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 ee(t,"a date",e,t);n=new Date(e)}if(isNaN(n.getTime()))throw new P(`${t} must be a valid date`,t,_.INVALID_FORMAT)}function ls(e,t,n){try{ce(e,t)}catch{throw function(e,t,n,r="OPERATION_FAILED"){return new P(`${e} failed: ${t}`,n,r)}(n,"must be a positive integer",t)}}function hs(e,t,n="status"){void 0!==e&&function(e,t,n){const r=Object.values(t);if(!r.includes(e))throw new P(`${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=E(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 fs{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 ms(e,t){return void 0===e[t]||"number"==typeof e[t]}function ys(e){if(!e||"object"!=typeof e)return!1;const t=e;return gs(t,"tokenName")&&ms(t,"from")&&ms(t,"to")&&ms(t,"resolution")}class ws 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=Sr(t),r=yr(await rs(()=>this.http.get(It,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=Qo(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=jo(t,n),o=r.items.length===n&&Jo(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||Ho.DEFAULT_PAGE,n=e.limit??Ho.DEFAULT_LIMIT;0!==n&&et(t,n),Je(e.tokenName)&&qo(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=Ho.BACKEND_MAX_PAGE_SIZE,t=await es((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=Ho.BACKEND_MAX_PAGE_SIZE,a=Qo(n,s),c=await es((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=Qo(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){Ko(e),Je(e.tokenName)&&qo(e.tokenName);const t=Sr(e),n=await ts(()=>this.http.get(Ct,t),{errorContext:"Failed to check pool"});return Je(e.symbol)?n?.isSymbolExist??!1:Je(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(!ys(e))throw new P("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(qo(t),!n||!r||!i)throw new P("Graph options (from, to, resolution) are required","options","MISSING_GRAPH_OPTIONS");const o={tokenName:t,from:n,to:r,resolution:i};Go(o);const s=Sr(o);return{dataPoints:await ts(()=>this.http.get(Nt,s),{errorContext:"Failed to fetch graph data"})}}async fetchTokenDistribution(e){if(!e)throw W("tokenName","Token name");let t;qo(e);try{t=await rs(()=>this.http.get(`${Bt}/${e}`),{errorContext:"Failed to fetch token distribution"})}catch(t){if(C(t)&&500===t.response?.status)throw j(`Token distribution data temporarily unavailable for ${e}. This is a backend issue - please try again later.`,500);throw t}const n=yr(t);if(!Array.isArray(n))throw j("Invalid API response: expected array of holders",t.status);for(const e of n){if(!e.owner||"string"!=typeof e.owner)throw j("Invalid holder data: missing or invalid owner field",t.status);if(!e.quantity||"string"!=typeof e.quantity)throw j("Invalid holder data: missing or invalid quantity field",t.status);const n=De(e.quantity,NaN);if(isNaN(n)||!isFinite(n))throw j(`Invalid holder quantity: "${e.quantity}"`,t.status)}const r=n.reduce((e,t)=>e.plus(t.quantity),bo(0));return{holders:n.map(e=>{const t=Uo(bo(e.quantity),r,bo(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 qo(e),ts(()=>this.http.get(`${Bt}/${e}`,{userAddress:t}),{errorContext:"Failed to fetch user holder context"})}async fetchTokenBadges(e){if(!e)throw W("tokenName","Token name");qo(e);const t=await ts(()=>this.http.get(xt,{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 bs(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&&!Je(s))continue}const a=i[e],c=a?String(a):t;n.includes(e)?o[c]=String(s):o[c]=s}return Sr(o)}({tokenName:e,page:t,limit:n},{stringifyFields:["page","limit"]})}const ks={PAGINATION:we,TOKEN_NAME:pe,USER_ADDRESS:ve};function vs(e){if(!e.tokenName&&!e.userAddress)throw new P("At least one of tokenName or userAddress is required","options","MISSING_FILTER");if(void 0!==e.tokenName){if(!Je(e.tokenName))throw ee("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(!Je(e.userAddress))throw ee("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(et(e.page,e.limit,ks.PAGINATION.MAX_LIMIT),void 0!==e.txnType&&"BUY"!==e.txnType&&"SELL"!==e.txnType)throw H("txnType",'"BUY" or "SELL"');if(void 0!==e.startDate){if(!Je(e.startDate))throw ee("startDate","a non-empty string",typeof e.startDate);if(isNaN(Date.parse(e.startDate)))throw H("startDate","a valid ISO 8601 date")}if(void 0!==e.endDate){if(!Je(e.endDate))throw ee("endDate","a non-empty string",typeof e.endDate);if(isNaN(Date.parse(e.endDate)))throw H("endDate","a valid ISO 8601 date")}if(void 0!==e.minAmount)try{se(e.minAmount,0,Number.MAX_SAFE_INTEGER,"minAmount")}catch{throw H("minAmount","a non-negative number")}if(void 0!==e.maxAmount)try{se(e.maxAmount,0,Number.MAX_SAFE_INTEGER,"maxAmount")}catch{throw H("maxAmount","a non-negative number")}void 0!==e.minAmount&&void 0!==e.maxAmount&&ue(e.minAmount,e.maxAmount,"amountRange")}class Ss 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")&&ms(t,"page")&&ms(t,"limit")}(e))throw new P("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=Ho.DEFAULT_PAGE,limit:o=Ho.DEFAULT_LIMIT,startDate:s,endDate:a,sortOrder:c}=e;if(!Je(t))throw W("tokenName","Token name");et(i,o,ye);const u=bs(t,i,o),l=await this.http.get(Pt,u);if(!l)throw new P("No response from trade service","response","NO_RESPONSE");return{items:Yo(yr(l),"trades"),meta:Zo(l,{page:i,limit:o})}}buildTradesQueryParams(e){const t={};if(e.tokenName&&(t.tokenName=is(e.tokenName)),e.userAddress&&(t.userAddress=e.userAddress),void 0!==e.page&&(t.page=String(e.page)),void 0!==e.limit){const n=Xo(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){vs(e);const t=this.buildTradesQueryParams(e);return ts(()=>this.http.get(sr,t),{errorContext:"Failed to fetch trades"})}}function As(e,t){const n={};return e.page&&(n.page=String(e.page)),e.limit&&(n.limit=String(Math.min(e.limit,t))),n}function Ts(e,t=e.length){return{page:1,limit:e.length,total:t,totalPages:e.length>0?Qo(t,e.length):1}}function Es(e,t,n){for(const r of n){const n=t[r];null!=n&&""!==n&&(e[r]=String(n))}return e}function Is(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 Cs(e,t){return e.toLowerCase()===t.toLowerCase()}function Ns(e,t){return e.toLowerCase().includes(t.toLowerCase())}function Bs(e,t,n,r){return e===n&&t===r||e===r&&t===n}function xs(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 Ps(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 H("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 Rs(e){return!!Je(e)&&ke.PATTERN.test(e)}tt({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||!Rs(t))throw H("address","eth|[40-hex-chars]","Address");const n={userAddress:t},r=await this.http.get(Rt,n);if(!r)throw new P("No response from user service","response","NO_RESPONSE");return r}async updateProfile(e){this.validateUpdateProfileData(e);let t=e.profileImage;if(!Je(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 ts(()=>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 P("Wallet address not available - wallet not configured","address","NO_WALLET");try{const n=`profile-image-${t}.png`,r=Ps(e.file,"image",n),i=await ts(()=>this.http.request({method:"POST",url:`${Et}?tokenName=${encodeURIComponent(t)}`,data:r,headers:this.getJwtHeaders()}),{errorContext:"Image upload failed"});return"string"==typeof i?i:""}catch(e){if(e instanceof P||e instanceof D)throw e;throw new P(`Profile image upload failed: ${T(e)}`,"file","UPLOAD_FAILED")}}async fetchTokenList(e){return this.buildFetchRequest(Lt,e,{includeType:!0,errorMessage:"Failed to fetch token list"})}async fetchTokensHeld(e){return this.buildFetchRequest(Ot,e,{includeType:!1,errorMessage:"Failed to fetch tokens held"})}async fetchTokensCreated(e={}){const{page:t=Ho.DEFAULT_PAGE,limit:n=Ho.DEFAULT_LIMIT,search:r,tokenName:i}=e,o=this.http.getAddress();if(!o)throw new P("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=Vo(e.page),n=Xo(e.limit);et(t,n,ye);const r={};void 0!==t&&(r.page=t),void 0!==n&&(r.limit=n);const i=As(r,ye);return ts(()=>this.http.get(Ut,{...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=As(r,ye);Es(i,t,["address","search","tokenName"]),n.includeType&&(i.type="all"!==t.type&&t.type?t.type:"DEFI");const o=await rs(()=>this.http.get(e,i),{errorContext:n.errorMessage}),s=Yo(yr(o),"token"),a=Zo(o,{page:t.page||Ho.DEFAULT_PAGE,limit:t.limit||Ho.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(et(e.page,e.limit,ye),void 0!==e.address&&!Rs(e.address))throw H("address","eth|[40-hex-chars]","Address");const t=Is(e.search);if(null!==t&&!(Je(n=t)&&n.length>=xe&&n.length<=_e))throw J("search",xe,_e,t.length,"Search query");var n;const r=Is(e.tokenName);if(null!==r&&!(Je(i=r)&&i.length>=pe.MIN_LENGTH&&i.length<=pe.MAX_LENGTH))throw J("tokenName",pe.MIN_LENGTH,pe.MAX_LENGTH,r.length,"Token name");var i}validateUpdateProfileData(e){if(!Rs(e.address))throw H("address","eth|[40-hex-chars]","Address");if(!(Je(t=e.fullName)&&t.length>=Pe.FULL_NAME.MIN_LENGTH&&t.length<=Pe.FULL_NAME.MAX_LENGTH&&Pe.FULL_NAME.ALPHABETS_ONLY_PATTERN.test(t)))throw J("fullName",Pe.FULL_NAME.MIN_LENGTH,Pe.FULL_NAME.MAX_LENGTH,e.fullName.length,"Full name");var t}validateUploadProfileImageOptions(e){if(e.address&&!Rs(e.address))throw H("address","eth|[40-hex-chars]","Address")}}class Ls extends Error{constructor(e,t,n){super(e),this.filename=t,this.mimeType=n,this.name="FileValidationError"}}function Os(e,t,n){if(!e)throw new Ls("File is required",t,n);if("undefined"!=typeof File&&e instanceof File){const t=fi.safeParse(e);if(!t.success){const n=t.error.errors.map(e=>e.message).join("; ");throw new Ls(n,e.name,e.type)}return}if(Buffer.isBuffer(e)){if(!t)throw new Ls("Filename is required when uploading Buffer objects",t,n);const r=gi.safeParse(e);if(!r.success){const e=r.error.errors.map(e=>e.message).join("; ");throw new Ls(e,t,n)}try{ae(t,255,"filename")}catch(e){throw new Ls(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 Ls(`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 Ls(`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 Ls(`File extension "${o}" does not match MIME type "${n}"`,t,n);return}throw new Ls("File must be a File object (browser) or Buffer (Node.js)",t,n)}class Us extends ds{constructor(e,t,n=!1){super(e,n,t)}async uploadImageByTokenName(e){const{tokenName:t,options:n}=e;qo(t);const r=`${t}.png`;Os(n.file,r,"image/png");try{const e=`${n.tokenName??t}.png`,r=Ps(n.file,"image",e),i=await ts(()=>this.http.request({method:"POST",url:`${Et}?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(A(e)&&T(e).includes("FormData"))throw V("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(!Je(e.tokenName))throw W("tokenName","Token name");if(qo(e.tokenName),!this.jwtAuth)throw V("JWT authentication required for updating token social links. Initialize SDK with a wallet or provide JWT token.","JWT_AUTH_REQUIRED");const t=_t,n=yr(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 Ms{constructor(e,t,n=!1){this.http=e,this.poolService=new ws(e,n),this.tradeService=new Ss(e,n),this.userService=new Ds(e,t,n),this.imageService=new Us(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 qo(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 $s(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}}tt({BUY:"buy",SELL:"sell"});const qs=$s({vaultAddress:"string"}),Ks=$s({nativeTokenQuantity:"string"});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){return`$${e.collection}$${e.category}$${e.type}$${e.additionalKey}`}function Hs(e,t,n){const r=n?` (${n})`:"";try{if(!Je(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 P(`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: ${T(n)}`,"token",`INVALID_${"|"===t?"PIPE":"DOLLAR"}_DELIMITED_TOKEN`)}}function js(e){if("object"==typeof e&&null!==e)return function(e){if(!e||"object"!=typeof e)throw new P("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(!Je(t))throw new P("Token.collection must be a non-empty string, got "+typeof t,"token.collection","MISSING_OR_INVALID_COLLECTION");if(!Je(n))throw new P("Token.category must be a non-empty string, got "+typeof n,"token.category","MISSING_OR_INVALID_CATEGORY");if(!Je(r))throw new P("Token.type must be a non-empty string, got "+typeof r,"token.type","MISSING_OR_INVALID_TYPE");if(!Je(i))throw new P("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 P(`Token cannot be null, undefined, or empty. Received: ${JSON.stringify(e)}`,"token","EMPTY_TOKEN");if("string"!=typeof e)throw new P("Token must be a string or TokenClassKey object, got "+typeof e,"token","INVALID_TOKEN_TYPE");if(Xs(e))return Vs(e);if(Qs(e))return function(e){return function(e,t,n){const r=` (${n})`;try{if(!Je(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 P(`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: ${T(n)}`,"token","INVALID_DOLLAR_DELIMITED_TOKEN")}}(e,"$","dollar-delimited token")}(e);throw new P(`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 Vs(e){return Hs(e,"|","pipe-delimited token")}function Xs(e){return Je(e)&&e.includes("|")}function Qs(e){return"string"==typeof e&&e.includes("$")}function Js(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 Ys(e){return e&&0!==e.length?e.reduce((e,t)=>o(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 ea extends ds{constructor(e,t=!1){super(e,t)}getChannelForCollection(e){return"MUSIC"===(Qs(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{N(r,"Fetch balances")}catch{return null}if(!r.Data||0===r.Data.length)return null;const i=r.Data.find(t=>t.collection===e.collection&&t.category===e.category&&t.additionalKey===e.additionalKey&&t.type===e.type);if(!i||"0"===i.quantity)return null;const s=Gs(i),a={quantity:i.quantity,collection:i.collection,category:i.category,tokenId:s};if(i.inUseHolds?.length){const e=Zs(i.inUseHolds??[],t);e.length>0&&(a.inUseHolds=e,a.inUseQuantity=Ys(e))}if(i.lockedHolds?.length){const e=Zs(i.lockedHolds??[],t);e.length>0&&(a.lockedHolds=e,a.lockedQuantity=Ys(e))}return(a.lockedQuantity||a.inUseQuantity)&&(a.availableQuantity=function(e,t="0",n="0"){return o(e).minus(t).minus(n).toString()}(a.quantity,a.lockedQuantity,a.inUseQuantity)),a}catch(e){throw j(`Failed to fetch token balance from GalaChain: ${T(e)}`,void 0,A(e)?e:void 0)}}}function ta(e){if("string"==typeof e){if(!Xs(e))throw new P(`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{...Vs(t.slice(0,4).join("|")),instance:t[4]||"0"}}return{...Vs(e),instance:"0"}}if("object"==typeof e&&null!==e){if("instance"in e&&void 0!==e.instance){if(!Js(e))throw new P("Invalid tokenId object format. All fields (collection, category, type, additionalKey) must be non-empty strings","tokenId","INVALID_TOKEN_ID_FORMAT");return e}if(!Js(e))throw new P("Invalid tokenId object format. All fields (collection, category, type, additionalKey) are required","tokenId","INVALID_TOKEN_ID_FORMAT");return{...e,instance:"0"}}throw new P(`Invalid tokenId type: ${typeof e}. Expected string, TokenClassKey, or TokenInstanceKey`,"tokenId","INVALID_TOKEN_ID_TYPE")}function na(e){return function(e){try{if(!Je(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 P(`Invalid vault address: "${e}". Expected format: "service|Token$Unit$SYMBOL$additionalKey$launchpad". Error: ${T(t)}`,"vaultAddress","INVALID_VAULT_ADDRESS_FORMAT")}}(e)}function ra(e){return{...na(e),instance:"0"}}function ia(e){return na(e).type}function oa(e){return Gs(ta(e))}var sa=Object.freeze({__proto__:null,extractTokenSymbolFromVault:ia,isTokenClassKeyStrict:Js,normalizeToTokenInstanceKey:ta,normalizeTokenIdToString:oa,parseVaultAddressToTokenClassKey:na,parseVaultAddressToTokenInstance:ra});class aa extends ds{constructor(e,t=!1,n){super(e,t),this.publicAxios=n}async fetchTokenClassFromChain(e){try{const t="string"==typeof e?ta(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(N(r,"Failed to fetch token class from GalaChain"),!r.Data||0===r.Data.length)throw j(`Token not found on GalaChain: ${Gs(t)}`,404);return r.Data[0]}catch(e){if(e instanceof P)throw e;if(C(e)&&404===e.response?.status)throw j("Token not found on GalaChain",404,A(e)?e:void 0);if(A(e)&&"Error"===e.name&&T(e).includes("status indicates failure"))throw j(T(e),400,A(e)?e:void 0);const t=T(e);if(t.includes("Token not found"))throw e;throw j(`Failed to fetch token class from GalaChain: ${t}`,void 0,A(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(N(n,"Failed to fetch token classes with supply from GalaChain"),!n.Data||0===n.Data.length)throw j("No token supply data found for requested token classes",404);return n.Data}catch(e){if(e instanceof P)throw e;if(C(e)&&404===e.response?.status)throw j("Token supply data not found on GalaChain",404,A(e)?e:void 0);if(A(e)&&"Error"===e.name&&T(e).includes("status indicates failure"))throw j(T(e),400,A(e)?e:void 0);const t=T(e);if(t.includes("Token not found"))throw e;throw j(`Failed to fetch token classes with supply from GalaChain: ${t}`,void 0,A(e)?e:void 0)}}}class ca{toLaunchpadFormat(e){if(!e)throw new P('Token is required. Use full tokenId format: "GALA|Unit|none|none"',"token","MISSING_TOKEN");if("string"==typeof e){if(Xs(e))return e;throw new P(`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 Gs({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=Hs(e,"|","token format conversion");return{collection:t.collection,category:t.category,type:t.type,additionalKey:t.additionalKey}}normalizeInternalApiResponse(e){return e?Xs(e)?e:`${e}|Unit|none|none`:""}normalize(e){return"string"==typeof e&&Xs(e)?e:this.toLaunchpadFormat(e)}}function ua(e){if(!Je(e))throw new Error("Invalid token format: token must be a non-empty string");return e.replace(/\|/g,"$")}function la(e){return Hs(e,"$","dollar-delimited token")}function ha(){return`galaconnect-operation-${Date.now()}_${Math.random().toString(36).substring(2,8)}`}class da extends r.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||ha()})}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||ha()})}getTokenClassKey(){if(0===this.tokenInstances.length)return;return zs(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 fa extends r.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 fa({tokenInstances:[{owner:e,quantity:t,tokenInstanceKey:i}],...void 0!==r?.name&&{name:r.name},uniqueKey:r?.uniqueKey||ha()})}static forGALA(e,t,n){return new fa({tokenInstances:[{owner:e,quantity:t,tokenInstanceKey:{collection:"GALA",category:"Unit",type:"none",additionalKey:"none",instance:"0"}}],...void 0!==n?.name&&{name:n.name},uniqueKey:n?.uniqueKey||ha()})}getTokenClassKey(){if(0===this.tokenInstances.length)return;return zs(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 ht).toBackendFormat(e)}static fromGalaChainAddress(e){try{return(new ht).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 Je(t.amount)&&(void 0!==t.tokenId||Je(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 ma(e){if(!e||"object"!=typeof e)return!1;const t=e;return Je(t.amount)&&(void 0!==t.tokenId||Je(t.tokenName))&&(void 0===t.name||"string"==typeof t.name)}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)}function wa(e){if(!e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every(ma)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}var ba,ka;e.LockErrorType=void 0,(ba=e.LockErrorType||(e.LockErrorType={})).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",ba.LOCK_NOT_FOUND="LOCK_NOT_FOUND",ba.LOCK_EXPIRED="LOCK_EXPIRED",ba.INSUFFICIENT_LOCKED_BALANCE="INSUFFICIENT_LOCKED_BALANCE",ba.NOT_LOCK_AUTHORITY="NOT_LOCK_AUTHORITY",ba.LOCK_NAME_MISMATCH="LOCK_NAME_MISMATCH";class va 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 Sa extends Error{constructor(e,t,n){super(e),this.type=t,this.details=n,this.name="TransferError"}}const Aa=100,Ta=100;class Ea 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(t){if(this.validateLockTokensData(t),!this.wallet||!this.signatureHelper)throw new va("Wallet required for token lock operations",e.LockErrorType.WALLET_REQUIRED);return br(async()=>{const n=gt(this.wallet.address),r=[],i=[];let o=n;const s=t.tokens.find(e=>e.lockAuthority);s?.lockAuthority&&(o=gt(s.lockAuthority));const a=t.tokens.find(e=>void 0!==e.expires),c=t.tokens.find(e=>void 0!==e.name);for(const s of t.tokens){let t;if(s.tokenId)t=ta(s.tokenId),this.logger.debug("[DEBUG] Using provided tokenId:",s.tokenId);else{if(!s.tokenName)throw new va("Must provide either tokenId or tokenName for token identification",e.LockErrorType.TOKEN_NOT_FOUND);t=await this.resolveTokenInstance(s.tokenName)}r.push({owner:n,quantity:s.amount,tokenInstanceKey:t}),i.push({tokenClassKey:{collection:t.collection,category:t.category,type:t.type,additionalKey:t.additionalKey},quantity:s.amount,lockAuthority:s.lockAuthority?gt(s.lockAuthority):o})}const u=new da({lockAuthority:o,tokenInstances:r,...void 0!==a?.expires&&{expires:a.expires},...void 0!==c?.name&&{name:c.name},uniqueKey:t.uniqueKey||ha()}),l=await this.signatureHelper.signLockToken(u.toSigningPayload()),h=new da({...u.toSigningPayload(),signedPayload:l});this.logger.debug("[DEBUG] Full Lock Request Payload:",JSON.stringify(h,null,2));const d=await this.http.post("/api/asset/token-contract/LockTokens",h);try{N(d,"Token lock failed")}catch(t){const n=B(d);throw new va(`${T(t)}${n}`,e.LockErrorType.NETWORK_ERROR)}return this.logger.debug("[DEBUG] Token lock response:",JSON.stringify(d,null,2)),this.extractLockResult(d,i)},"Token lock failed",this.logger,e=>{throw this.handleLockError(e,"Token lock failed",t)})}async unlockTokens(t){if(this.validateUnlockTokensData(t),!this.wallet||!this.signatureHelper)throw new va("Wallet required for token unlock operations",e.LockErrorType.WALLET_REQUIRED);return br(async()=>{const n=gt(this.wallet.address),r=[],i=[],o=t.tokens.find(e=>void 0!==e.name);for(const o of t.tokens){let t;if(o.tokenId)t=ta(o.tokenId),this.logger.debug("[DEBUG] Using provided tokenId:",o.tokenId);else{if(!o.tokenName)throw new va("Must provide either tokenId or tokenName for token identification",e.LockErrorType.TOKEN_NOT_FOUND);t=await this.resolveTokenInstance(o.tokenName)}r.push({owner:n,quantity:o.amount,tokenInstanceKey:t}),i.push({tokenClassKey:{collection:t.collection,category:t.category,type:t.type,additionalKey:t.additionalKey},quantity:o.amount})}const s=new fa({tokenInstances:r,...void 0!==o?.name&&{name:o.name},uniqueKey:t.uniqueKey||ha()}),a=await this.signatureHelper.signUnlockToken(s.toSigningPayload()),c=new fa({...s.toSigningPayload(),signedPayload:a});this.logger.debug("[DEBUG] Full Unlock Request Payload:",JSON.stringify(c,null,2));const u=await this.http.post("/api/asset/token-contract/UnlockTokens",c);try{N(u,"Token unlock failed")}catch(t){const n=B(u);throw new va(`${T(t)}${n}`,e.LockErrorType.NETWORK_ERROR)}return this.logger.debug("[DEBUG] Token unlock response:",JSON.stringify(u,null,2)),this.extractUnlockResult(u,i)},"Token unlock failed",this.logger,e=>{throw this.handleLockError(e,"Token unlock failed",t)})}validateLockTokensData(t){if(!ya(t))throw new va("Invalid lock data: missing required fields",e.LockErrorType.VALIDATION_ERROR);if(t.tokens.length>Aa)throw new va(`Batch size exceeds maximum limit of ${Aa} tokens per lock operation`,e.LockErrorType.VALIDATION_ERROR);for(const n of t.tokens){if(!n.tokenId&&!n.tokenName)throw new va("Must provide either tokenId or tokenName for token identification",e.LockErrorType.TOKEN_NOT_FOUND);if(n.tokenName)try{ot(n.tokenName,"tokenName")}catch{throw new va("Invalid token name format",e.LockErrorType.TOKEN_NOT_FOUND,{tokenName:n.tokenName})}const t=bo(n.amount);try{Do(t)}catch{throw new va(H("lockAmount","a positive number","Lock amount").message,e.LockErrorType.INVALID_AMOUNT,{amount:n.amount})}if(n.lockAuthority&&!yt(n.lockAuthority))throw new va("Invalid lock authority address format",e.LockErrorType.VALIDATION_ERROR,{lockAuthority:n.lockAuthority});if(void 0!==n.expires)try{ce(n.expires,"expires")}catch{throw new va(H("expires","a positive integer (epoch milliseconds)","Expires").message,e.LockErrorType.VALIDATION_ERROR)}}}validateUnlockTokensData(t){if(!wa(t))throw new va("Invalid unlock data: missing required fields",e.LockErrorType.VALIDATION_ERROR);if(t.tokens.length>Ta)throw new va(`Batch size exceeds maximum limit of ${Ta} tokens per unlock operation`,e.LockErrorType.VALIDATION_ERROR);for(const n of t.tokens){if(!n.tokenId&&!n.tokenName)throw new va("Must provide either tokenId or tokenName for token identification",e.LockErrorType.TOKEN_NOT_FOUND);if(n.tokenName)try{ot(n.tokenName,"tokenName")}catch{throw new va("Invalid token name format",e.LockErrorType.TOKEN_NOT_FOUND,{tokenName:n.tokenName})}const t=bo(n.amount);try{Do(t)}catch{throw new va(H("unlockAmount","a positive number","Unlock amount").message,e.LockErrorType.INVALID_AMOUNT,{amount:n.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(t,n,r){if(t instanceof va)return t;let i=n,o=e.LockErrorType.NETWORK_ERROR;if(C(t)){const r=t.response?.data;if("object"==typeof r&&null!==r){const t=r;t.Message&&"string"==typeof t.Message&&(i=`${n}: ${t.Message}`);const s=String(t.Message||"").toLowerCase();s.includes("insufficient")||s.includes("balance")?o=e.LockErrorType.INSUFFICIENT_BALANCE:s.includes("lock")&&s.includes("not found")?o=e.LockErrorType.LOCK_NOT_FOUND:s.includes("not found")||s.includes("token")?o=e.LockErrorType.TOKEN_NOT_FOUND:s.includes("authority")?o=e.LockErrorType.NOT_LOCK_AUTHORITY:s.includes("expired")&&(o=e.LockErrorType.LOCK_EXPIRED)}}else A(t)&&(i=`${n}: ${T(t)}`);const s={};return void 0!==r?.tokens?.[0]?.tokenName&&(s.tokenName=r.tokens[0].tokenName),void 0!==r?.tokens?.[0]?.amount&&(s.amount=r.tokens[0].amount),new va(i,o,Object.keys(s).length>0?s:void 0)}async resolveTokenInstance(t){return br(async()=>{const e=await this.tokenResolver.resolveTokenToVault(t);if(e){const n=ra(e);return this.logger.debug(`[DEBUG] Token resolution for '${t}' (launchpad):\n Vault Address: ${e}\n Token Instance: ${JSON.stringify(n,null,2)}`),n}const n={collection:os(t),category:"Unit",type:"none",additionalKey:"none",instance:"0"};return this.logger.debug(`[DEBUG] Token resolution for '${t}' (standard format):\n Token Instance: ${JSON.stringify(n,null,2)}`),n},`Failed to resolve token '${t}'`,this.logger,n=>{if(n instanceof Sa)throw new va(T(n),e.LockErrorType.TOKEN_NOT_FOUND);throw new va(`Failed to resolve token '${t}': ${T(n)}`,e.LockErrorType.TOKEN_NOT_FOUND,{tokenName:t})})}}class Ia{static validateAmount(e){const t=bo(e);try{Oo(t,"amount")}catch(t){throw new Sa(t.message,ka.INVALID_AMOUNT,{amount:e})}}static validateUniqueKey(e){if(!Ze(e)&&Je(e)){if(e.length>Ie.MAX_LENGTH)throw new P(`Unique key too long. Maximum length: ${Ie.MAX_LENGTH}`);if(!Ie.PATTERN.test(e))throw new Sa('Invalid unique key format. Must start with "galaswap-operation-" or "galaconnect-operation-"',ka.INVALID_AMOUNT,{uniqueKey:e})}}}class Ca extends r.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 Ca({from:e,to:t,quantity:n,tokenInstance:o,uniqueKey:i||ha()})}static forGALA(e,t,n,r){return new Ca({from:e,to:t,quantity:n,tokenInstance:{collection:"GALA",category:"Unit",type:"none",additionalKey:"none",instance:"0"},uniqueKey:r||ha()})}getTokenClassKey(){return zs(this.tokenInstance)}toSigningPayload(){return{from:this.from,to:this.to,quantity:this.quantity,tokenInstance:this.tokenInstance,uniqueKey:this.uniqueKey}}}class Na extends r.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 Na({tokenInstances:n,uniqueKey:t?.uniqueKey||ha()})}static fromTokenClassKey(e,t,n){return Na.fromTokens([{tokenClassKey:t,quantity:e}],n)}static forGALA(e,t){return new Na({tokenInstances:[{quantity:e,tokenInstanceKey:{collection:"GALA",category:"Unit",type:"none",additionalKey:"none",instance:"0"}}],uniqueKey:t?.uniqueKey||ha()})}getTokenClassKey(){if(0===this.tokenInstances.length)return;return zs(this.tokenInstances[0].tokenInstanceKey)}toSigningPayload(){return{tokenInstances:this.tokenInstances,uniqueKey:this.uniqueKey}}}function Ba(e){if(!e||"object"!=typeof e)return!1;const t=e;return Je(t.amount)&&(void 0!==t.tokenId||Je(t.tokenName))}function xa(e){if(!e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every(Ba)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}var _a;e.BurnErrorType=void 0,(_a=e.BurnErrorType||(e.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 Pa extends Error{constructor(e,t,n){super(e),this.type=t,this.details=n,this.name="BurnError"}}const Ra="gala-transfer-successful",Da="token-transfer-successful",La="token-locked-successfully",Oa="token-unlocked-successfully",Ua="transfer-successful-no-id",Ma=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 Sa("Wallet required for GALA transfer operations",ka.WALLET_REQUIRED);try{const t=gt(e.recipientAddress),n=gt(this.wallet.address),r=Ca.forGALA(n,t,e.amount,e.uniqueKey),i=await this.signatureHelper.signTransferToken(r.toSigningPayload()),o=new Ca({...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 Sa("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 Sa("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=ta(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 Sa("Must provide either tokenId or tokenName for token identification",ka.TOKEN_NOT_FOUND);r=await this.resolveTokenInstance(e.tokenName)}const i=new Ca({from:n,to:t,quantity:e.amount,tokenInstance:r,uniqueKey:e.uniqueKey||ha()}),o=await this.signatureHelper.signTransferToken(i.toSigningPayload()),s=new Ca({...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 Sa("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 Sa)throw t;throw new Sa(`Failed to resolve token class key for '${e}': ${T(t)}`,ka.TOKEN_NOT_FOUND,{tokenName:e})}}async burnTokens(t){if(this.validateBurnTokensData(t),!this.wallet||!this.signatureHelper)throw new Pa("Wallet required for token burn operations",e.BurnErrorType.WALLET_REQUIRED);try{const n=[];for(const r of t.tokens){let t;if(r.tokenId)t=ta(r.tokenId),this.logger.debug("[DEBUG] Using provided tokenId:",r.tokenId);else{if(!r.tokenName)throw new Pa("Must provide either tokenId or tokenName for token identification",e.BurnErrorType.TOKEN_NOT_FOUND);t=await this.resolveTokenInstance(r.tokenName)}n.push({quantity:r.amount,tokenInstanceKey:t})}const r=new Na({tokenInstances:n,uniqueKey:t.uniqueKey||ha()}),i=await this.signatureHelper.signBurnTokens(r.toSigningPayload()),o=new Na({...r.toSigningPayload(),signedPayload:i});this.logger.debug("[DEBUG] Full Burn Request Payload:",JSON.stringify(o,null,2));const s=await this.http.post("/api/asset/token-contract/BurnTokens",o);if(!s)throw new Pa("No response from GalaChain burn service",e.BurnErrorType.NETWORK_ERROR);try{N(s,"Token burn operation")}catch(e){throw new R(T(e),500)}return this.logger.debug("[DEBUG] Token burn response:",JSON.stringify(s,null,2)),this.extractBurnResult(s)}catch(e){throw this.handleBurnError(e,"Token burn failed",t)}}validateTransferGalaData(e){if(!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return Je(t.recipientAddress)&&Je(t.amount)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)}(e))throw new P("Invalid GALA transfer data: missing required fields");if(!yt(e.recipientAddress))throw new Sa("Invalid recipient address format",ka.INVALID_RECIPIENT,{recipientAddress:e.recipientAddress});Ia.validateAmount(e.amount),Ia.validateUniqueKey(e.uniqueKey)}validateTransferTokenData(e){if(!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return Je(t.to)&&Je(t.amount)&&(void 0!==t.tokenId||Je(t.tokenName))&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)}(e))throw new P("Invalid token transfer data: missing required fields");if(!yt(e.to))throw new Sa("Invalid recipient address format",ka.INVALID_RECIPIENT,{recipientAddress:e.to});if(!e.tokenId&&!e.tokenName)throw new Sa("Must provide either tokenId or tokenName for token identification",ka.TOKEN_NOT_FOUND);if(e.tokenName)try{ot(e.tokenName,"tokenName")}catch{throw new Sa("Invalid token name format",ka.TOKEN_NOT_FOUND,{tokenName:e.tokenName})}Ia.validateAmount(e.amount),Ia.validateUniqueKey(e.uniqueKey)}validateBurnTokensData(t){if(!xa(t))throw new Pa("Invalid burn data: missing required fields",e.BurnErrorType.VALIDATION_ERROR);if(t.tokens.length>Ma)throw new Pa(`Batch size exceeds maximum limit of ${Ma} tokens per burn operation`,e.BurnErrorType.VALIDATION_ERROR);for(const n of t.tokens){if(!n.tokenId&&!n.tokenName)throw new Pa("Must provide either tokenId or tokenName for token identification",e.BurnErrorType.TOKEN_NOT_FOUND);const t=bo(n.amount);try{Do(t)}catch{throw new Pa("Burn amount must be a positive number",e.BurnErrorType.INVALID_AMOUNT,{amount:n.amount})}}}async resolveTokenInstance(e){try{const t=await this.tokenResolver.resolveTokenToVault(e);if(t){const n=ra(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:os(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 Sa)throw t;throw new Sa(`Failed to resolve token '${e}': ${T(t)}`,ka.TOKEN_NOT_FOUND,{tokenName:e})}}extractTransactionIdFromResponse(e,t){if(e&&"object"==typeof e){if("Status"in e&&"Data"in e)try{N(e,"Extract transaction ID");const n=e;if(Array.isArray(n.Data)&&n.Data.length>0)switch(t){case"gala":return Ra;case"token":return Da;case"lock":return La;case"unlock":return Oa}return Ua}catch{}if("transactionId"in e&&"string"==typeof e.transactionId&&e.transactionId)return e.transactionId}throw new Sa("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 Sa)return e;if(e instanceof P)return new Sa(T(e),ka.INVALID_AMOUNT);if(C(e)&&e.response){const t=e.response.status,r=e.response.data;if(400===t)return new Sa(("string"==typeof r?.message?r.message:void 0)||"Invalid transfer request",ka.INVALID_AMOUNT);if(403===t)return new Sa("Insufficient balance for transfer",ka.INSUFFICIENT_BALANCE);if(404===t){const e={};return"tokenName"in n&&(e.tokenName=n.tokenName),new Sa("Token not found",ka.TOKEN_NOT_FOUND,e)}}if("object"==typeof e&&null!==e&&"code"in e&&("ECONNABORTED"===I(e)||"ETIMEDOUT"===I(e)))return new Sa("Transfer request timed out",ka.NETWORK_ERROR);const r=T(e);return new Sa(r||t,ka.NETWORK_ERROR)}handleBurnError(t,n,r){if(t instanceof Pa)return t;let i=n,o=e.BurnErrorType.NETWORK_ERROR;if(C(t)){const r=t.response?.data;if("object"==typeof r&&null!==r&&r.Message&&"string"==typeof r.Message){i=`${n}: ${r.Message}`;const t=r.Message.toLowerCase();t.includes("insufficient")||t.includes("balance")?o=e.BurnErrorType.INSUFFICIENT_BALANCE:(t.includes("not found")||t.includes("token"))&&(o=e.BurnErrorType.TOKEN_NOT_FOUND)}}else A(t)&&(i=`${n}: ${T(t)}`);const s={};return void 0!==r?.tokens?.[0]?.tokenName&&(s.tokenName=r.tokens[0].tokenName),void 0!==r?.tokens?.[0]?.amount&&(s.amount=r.tokens[0].amount),new Pa(i,o,Object.keys(s).length>0?s:void 0)}}class $a extends ds{constructor(e,t,n,r=!1,i){super(e,r),this.wallet=t,this.tokenResolver=n,this.publicAxios=i,this.balanceService=new ea(e,r),this.tokenService=new aa(e,r,i),this.lockService=new Ea(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 j("No response from GalaChain service",500);kr(()=>N(t,"Failed to fetch pool details"),"Failed to fetch pool details",this.logger,e=>{throw j(T(e),500)});const n=t.Data.reverseBondingCurveConfiguration,r=n?.minFeePortion??"0",i=n?.maxFeePortion??"0",o=!Bo(r)||!Bo(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 j("No response from GalaChain service",500);return kr(()=>N(e,"Failed to fetch launch token fee"),"Failed to fetch launch token fee",this.logger,e=>{throw j(T(e),500)}),e.Data.feeAmount}validateFetchPoolDetailsData(e){if(!qs(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 P("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 qa extends fs{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}=rt(e,"tokenName","tokenId",{description:"token identifier"});if(n&&t)return this.logger.debug(`Fetching spot price by tokenId: ${t}`),this._fetchDexTokenSpotPrice(t);throw new P("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=ta(e),n=Gs(t),r=ua(n);if(this.logger.debug(`Fetching DEX spot price for token: ${r}`),!this.dexBackendHttp)throw j("DEX Backend API client not configured");const i=yr(await this.dexBackendHttp.request({method:"GET",url:"/v1/trade/price",params:{token:r}}));if(!i||"string"!=typeof i)throw new P("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 te(t,e);if(!isFinite(n))throw te(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: ${A(e)?e.message:String(e)}`),a=ss("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 P)throw e;throw j(`Failed to fetch DEX spot price: ${T(e)}`)}}async fetchLaunchpadTokenSpotPrice(e,t,n){if(!Je(e))throw new P(Tr,"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=Gs(t.sellingToken);return this._fetchDexTokenSpotPrice(n)}}catch(t){this.logger.debug(`Could not determine graduation status for ${e}, falling back to bonding curve: ${T(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 j("GALA price not available");const o=De(r.amount,0)/1e18;if(o<=0)throw new P(`Invalid token amount calculation: ${o}`,"amount","INVALID_CALCULATION");const s=i.price/o;return{symbol:ss(e),price:s}}catch(t){if(A(t))throw j(`Failed to calculate launchpad token spot price for ${e}: ${T(t)}`);throw j(`Failed to calculate launchpad token spot price for ${e}: ${T(t)}`)}}async fetchTokenDetails(e){this.logger.debug("Fetching token details from GalaChain for tokenId:",e);try{if(!this.galaChainService)throw j("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 P||A(t))&&("NetworkError"===t.name||T(t).includes("Token not found")))throw t;throw j(`Failed to fetch token details from GalaChain for ${e}: ${T(t)}`,500)}}async fetchAllDexSeasons(){try{if(!this.dexBackendHttp)throw j("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=yr(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:je(e?.start),end:je(e?.end),rulesId:e?.rules_id??0}));return this.logger.debug(`Fetched ${n.length} DEX seasons`),n}catch(e){if(A(e)&&T(e).includes("not configured"))throw e;if(C(e)&&404===e.response?.status)return this.logger.warn("Seasons endpoint not available"),[];throw j(`Failed to fetch DEX seasons: ${T(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{ce(e,"seasonId")}catch{throw W("seasonId","Season ID must be a positive number")}try{if(!this.dexBackendHttp)throw j("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=yr(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(A(t)&&T(t).includes("must be a positive number"))throw t;throw j(`Failed to fetch DEX leaderboard for season ${e}: ${T(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 j("DEX Backend API client not configured");const e=yr(await this.dexBackendHttp.request({method:"GET",url:"/explore/volume"}));if(!e)throw j("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 j(`Failed to fetch DEX volume summary: ${T(e)}`)}}}function Ka(e){return{maxAcceptableReverseBondingCurveFee:Ke(e.maxAcceptableReverseBondingCurveFee)}}class Ga extends r.ChainCallDTO{constructor(e,t,n="0",r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=Ke(t),this.expectedToken=Ge(n),this.extraFees=Ka(r)}}class za extends r.ChainCallDTO{constructor(e,t,n,r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=Ge(t),this.expectedNativeToken=Ke(n),this.extraFees=Ka(r)}}class Wa extends r.ChainCallDTO{constructor(e,t,n="0",r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=Ge(t),this.expectedNativeToken=Ke(n),this.extraFees=Ka(r)}}class Ha extends r.ChainCallDTO{constructor(e,t,n,r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=Ke(t),this.expectedToken=Ge(n),this.extraFees=Ka(r)}}const ja={BuyNativeDto:Ga,BuyExactDto:za,SellExactDto:Wa,SellNativeDto:Ha};class Va extends fs{constructor(e,t=!1){super(t),this.walletProvider=e}async signDTO(e,t,n){try{this.logger.debug("🔐 Signing DTO:",{methodName:t,dtoKeys:Object.keys(e)});const n=this.generateEIP712Types(t,e),i=r.calculatePersonalSignPrefix(e),o={...e,prefix:i},{signature:s,domain:a}=await this.signWithEthersWallet(n,o),c={...e,signature:s,types:n,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 X(`Failed to sign DTO: ${T(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 V("Wallet provider does not support typed data signing","walletProvider");{const i=await this.walletProvider.getNetwork();n={name:i.name,chainId:Ue(i.chainId,1)},r=await this.walletProvider.signTypedData(n,e,t)}}return{signature:r,domain:n}}catch(e){throw X(`Ethers.js signing failed: ${T(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 P(`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 P(`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 Xa extends fs{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=T(e);throw new P(`Failed to generate stringsInstructions: ${t}`,"vaultAddress","INVALID_VAULT_ADDRESS")}}createTokenInstance(e){const t=new a.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 a.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(!Je(e))throw W("vaultAddress","Vault address");try{const t=ia(e);return this.logger.debug("🔍 Extracted token symbol:",{vaultAddress:e,tokenSymbol:t}),t}catch(e){if(e instanceof P)throw H("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad");throw e}}validateVaultAddress(e){if(!Je(e))throw W("vaultAddress","Vault address");if(!e.startsWith("service|Token$Unit$"))throw H("vaultAddress",'starting with "service|Token$Unit$"');if(!e.endsWith("$launchpad"))throw H("vaultAddress",'ending with "$launchpad"');const t=function(e){if(!Je(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 H("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 H("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 P)throw H("stringKey","format: collection$category$type$additionalKey (4 parts)");throw e}}}function Qa(e,t,n){let r;se(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=bo(0)),ko(o)}class Ja 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 Va(r,n),this.tokenKeyService=new Xa(n))}async submitTransaction(e){try{this.validateBundleData(e),this.logger.debug("📦 Submitting bundle transaction:",{method:e.method,stringsInstructionsCount:e.stringsInstructions.length,signedDtoKeys:Object.keys(e.signedDto)});const t=this.formatBundleRequest(e);this.logger.debug("🚀 Bundle request payload:",{...t,signedDto:"[REDACTED - Contains signature]"});let n=null;try{n=await ns(()=>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 P)return{success:!1,error:T(e)};throw e}}validateBundleData(e){if(!e)throw W("bundleData","Bundle data");if(!e.signedDto)throw W("signedDto","Signed DTO");if(!Je(e.method))throw W("method","Method name");if(!Array.isArray(e.stringsInstructions))throw H("stringsInstructions","an array of resource tracking strings");if(0===e.stringsInstructions.length)throw new P("stringsInstructions cannot be empty","stringsInstructions","EMPTY_ARRAY");const t=["BuyWithNative","BuyExactToken","SellExactToken","SellWithNative"];if(!t.includes(e.method))throw H("method",`one of: ${t.join(", ")}`);e.stringsInstructions.forEach((e,t)=>{if(!Je(e))throw new P(`stringsInstructions[${t}] must be a non-empty string`,`stringsInstructions[${t}]`,"INVALID_INSTRUCTION");if(!Qs(e))throw new P(`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=yr(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(C(e)&&e.response){const t=yr(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 T(e)||"Unknown bundle transaction error"}async getBundlerTransactionResult(e){try{if(!Je(e))throw W("transactionId","Transaction ID");let t;this.logger.debug("🔍 Checking bundler transaction result:",e);try{t=await ns(()=>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 P)return{success:!1,error:T(e)};throw e}}async cancelTransaction(e){try{if(!Je(e))throw W("transactionId","Transaction ID");let t;this.logger.debug("🚫 Cancelling transaction:",e);try{t=await ns(()=>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 P)return{success:!1,error:T(e)};throw e}}async getHealthStatus(){this.logger.debug("🏥 Checking bundle service health");try{const e=await ns(()=>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 P("expectedAmount is required for native buy operations. Use getBuyTokenAmount() first to calculate expected tokens.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Qa(i,o,"buy-native");this.logger.debug("BuyNative slippage applied:",{originalExpectedTokens:i,slippageFactor:o,adjustedMinTokens:e});const t=new ja.BuyNativeDto(a,n,e,{maxAcceptableReverseBondingCurveFee:s});return await this.executeBundleTransaction(t,"BuyWithNative",a)}{if(!i)throw new P("expectedAmount is required for exact buy operations. Use getBuyTokenAmount() first to calculate expected GALA cost.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Qa(i,o,"buy-exact");this.logger.debug("BuyExact slippage applied:",{originalExpectedGalaCost:i,slippageFactor:o,adjustedMaxGalaCost:e});const t=new ja.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 P("expectedAmount is required for exact sell operations. Use getSellTokenAmount() first to calculate expected GALA.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Qa(i,o,"sell-exact");this.logger.debug("SellExact slippage applied:",{originalExpectedGala:i,slippageFactor:o,adjustedMinGala:e});const t=new ja.SellExactDto(a,n,e,{maxAcceptableReverseBondingCurveFee:s});return await this.executeBundleTransaction(t,"SellExactToken",a)}{if(!i)throw new P("expectedAmount is required for native sell operations. Use getSellTokenAmount() first to calculate tokens to sell.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Qa(i,o,"sell-native");this.logger.debug("SellNative slippage applied:",{originalExpectedTokensToSell:i,slippageFactor:o,adjustedMaxTokensToSell:e});const t=new ja.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 z(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=Qa(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 V("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 - ${s.v4()}-${Date.now()}-${this.userAddress}`;const r=await this.signatureService.signDTO(e,t,this.userAddress),i=this.tokenKeyService.generateStringsInstructions(n),o={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(o);if(a.success){const e=yr(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 L(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 Ya{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 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 ec,tc;!function(e){e.PROCESSED="PROCESSED",e.COMPLETED="COMPLETED",e.SUCCESS="SUCCESS",e.FAILED="FAILED",e.ERROR="ERROR",e.PROCESSING="PROCESSING",e.PENDING="PENDING"}(ec||(ec={})),e.SDKTransactionStatus=void 0,(tc=e.SDKTransactionStatus||(e.SDKTransactionStatus={})).PENDING="pending",tc.PROCESSING="processing",tc.COMPLETED="completed",tc.FAILED="failed",tc.TIMEOUT="timeout";const nc={[ec.PROCESSED]:e.SDKTransactionStatus.COMPLETED,[ec.COMPLETED]:e.SDKTransactionStatus.COMPLETED,[ec.SUCCESS]:e.SDKTransactionStatus.COMPLETED,[ec.FAILED]:e.SDKTransactionStatus.FAILED,[ec.ERROR]:e.SDKTransactionStatus.FAILED,[ec.PROCESSING]:e.SDKTransactionStatus.PROCESSING,[ec.PENDING]:e.SDKTransactionStatus.PENDING};class rc{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 ic extends fs{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 rc({maxAttempts:this.config.reconnectAttempts??5,baseDelayMs:this.config.reconnectDelay??2e3}),this.eventBuffer=new Ya(3e4),this.isSocketIOAvailable=this.checkSocketIOAvailability()}checkSocketIOAvailability(){try{return"function"==typeof c.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)=>{br(async()=>{if(!this.isSocketIOAvailable){const e=new Error('Socket.IO not available in current environment. Install "socket.io-client" package.');throw this.logger.error("❌ Socket.IO connection failed:",T(e)),e}this.logger.debug("🔌 Connecting to Socket.IO server:",this.config.url),this.socket=c.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(t,n){this.listeners.set(t,n),this.logger.debug(`📡 Starting to monitor transaction: ${t}`),this.logger.debug(`📡 WebSocket connected: ${!!this.socket&&this.socket.connected}`);const r=this.eventBuffer.get(t);r&&(this.logger.debug(`📡 [Event Buffer] Found buffered event for ${t}, delivering immediately`),setImmediate(()=>{this.processTransactionEvent(t,r,n)}),this.eventBuffer.delete(t));const i=this.config.timeout||3e5,o=setTimeout(()=>{if(this.listeners.has(t)){const r=Math.round(i/1e3),o={transactionId:t,status:e.SDKTransactionStatus.TIMEOUT,message:`Transaction monitoring timeout - no response after ${r} seconds`,timestamp:Date.now()};this.logger.debug(`📡 Transaction timeout for ${t} (${r}s)`),n(o),this.listeners.delete(t),this.timeouts.delete(t),this.socket?.off(t)}},i);if(this.timeouts.set(t,o),this.socket&&this.socket.connected)this.socket.off(t),this.logger.debug(`📡 Listening for transaction updates: ${t}`),this.logger.debug(`📡 WebSocket connection ID: ${this.socket.id}`),this.logger.debug(`📡 WebSocket URL: ${this.config.url}`),this.socket.on(t,e=>{this.processTransactionEvent(t,e,n)});else{const r={transactionId:t,status:e.SDKTransactionStatus.FAILED,message:"WebSocket not connected - cannot monitor transaction",timestamp:Date.now()};n(r),this.listeners.delete(t),this.timeouts.delete(t)}}processTransactionEvent(t,n,r){this.logger.debug(`📡 Socket.IO transaction update for ${t}:`,JSON.stringify(n,null,2));const i=n,o=i?.data,s=i?.status||i?.Status||o?.status||o?.Status;let a=i?.message||i?.Message||o?.message||o?.Message||i?.error||o?.error;Je(a)||(a=s===ec.FAILED||s===ec.ERROR?"Transaction failed - check transaction details":s===ec.COMPLETED||s===ec.PROCESSED||s===ec.SUCCESS?"Transaction completed successfully":s?`Transaction status: ${s}`:"Unknown transaction status");const c=i?.blockHash||o?.blockHash,u=i?.gasUsed||o?.gasUsed,l=i?.Data||o?.Data,h={transactionId:t,status:this.mapSocketStatus(s),message:"string"==typeof a?a:"Transaction update received",timestamp:Date.now(),...c&&{blockHash:c},...u&&{gasUsed:u},...l&&{data:l}};if(this.logger.debug(`📡 Mapped status for ${t}: ${s} -> ${h.status}`),this.logger.debug(`📡 Final message: "${a}"`),r(h),h.status===e.SDKTransactionStatus.COMPLETED||h.status===e.SDKTransactionStatus.FAILED){this.listeners.delete(t);const e=this.timeouts.get(t);e&&(clearTimeout(e),this.timeouts.delete(t)),this.socket?.off(t),this.logger.debug(`📡 Cleaned up listener for ${t} (${h.status})`)}}async waitForTransaction(t){return new Promise((n,r)=>{this.monitorTransaction(t,t=>{t.status===e.SDKTransactionStatus.COMPLETED?n(t):t.status!==e.SDKTransactionStatus.FAILED&&t.status!==e.SDKTransactionStatus.TIMEOUT||r(new Error(`Transaction ${t.status}: ${t.message}`))})})}mapSocketStatus(t){const n=t?.toUpperCase();return nc[n]||e.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 oc extends fs{constructor(e,t=!1){super(t),this.poolService=e,this.cache=new Map}async resolveTokenToVault(e){if(!Je(e))throw W("tokenName","Token name");const t=is(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 z(e);return this.parseVaultAddressToTokenClassKey(t)}get(e){return this.cache.get(is(e))||null}set(e,t){this.cache.set(is(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 na(e)}catch(e){if(e instanceof P)throw H("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad","Vault address");throw e}}}class sc 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 V("TokenResolverService is required for token name resolution. Ensure it is passed to PriceHistoryService constructor.","tokenResolverService");try{it(e)}catch(e){throw V(T(e),"tokenName")}this.logger.debug(`Resolving token name '${e}' to token class key`);try{const t=await this.tokenResolverService.resolveTokenToVault(e);if(!t)throw V(`Token '${e}' not found or could not be resolved to vault address`,"tokenName");this.logger.debug(`Resolved '${e}' to vault address: ${t}`);const n=Gs(na(t));return this.logger.debug(`Extracted token class key: ${n}`),n}catch(t){if(A(t)&&T(t).includes("ConfigurationError"))throw t;throw j(`Failed to resolve token name '${e}': ${T(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),br(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 V("Token ID is required but was not provided or resolved","tokenId");const{normalizeToTokenInstanceKey:n}=await Promise.resolve().then(function(){return sa}),r=ua(Gs(n(t))),{from:i,to:o,sortOrder:s="DESC"}=e,a=Le(e.page,1),c=Le(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 j("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(!pr(e))throw j("Invalid API response: missing data wrapper",500);const t=yr(e);if(!t||"object"!=typeof t)throw j("Invalid API response: data is not an object",500);const n=t,r=n.data;if(!Array.isArray(r))throw j("Invalid API response: missing or invalid data.data array",500);const i=n.meta;if(!i||"object"!=typeof i)throw j("Invalid API response: missing data.meta pagination info",500);const o=i,s=r.map(e=>{if("object"!=typeof e||null===e)throw j("Invalid API response: invalid snapshot item",500);const t=e;return{price:t.price,timestamp:je(t.createdAt),tokenId:Gs({collection:t.collection,category:t.category,type:t.type,additionalKey:t.additionalKey})}}),a=Oe(o.currentPage,1),c=Oe(o.totalPages,1);return{snapshots:s,page:a,limit:Oe(o.pageSize,50),total:Oe(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),br(async()=>{const t=await es((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?Qo(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=Le(e.page,1),n=Le(e.limit,10),{from:r,to:i,sortOrder:o}=e;if(rt(e,"tokenName","tokenId",{description:"token identifier"}),r&&!Ve(r))throw V("from must be a valid Date","from");if(i&&!Ve(i))throw V("to must be a valid Date","to");o&&he(o,"sortOrder"),et(t,n,50)}}class ac extends Error{constructor(e,t,n){super(`API Error [${e}]: ${t}`),this.status=e,this.message=t,this.details=n,this.name="ApiError"}}function cc(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 uc(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.positionId&&cc(t.token0ClassKey)&&cc(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=v(e.baseUrl,e.timeout??3e4)}async getPoolData(e){return br(async()=>{if("string"==typeof e.token0||"string"==typeof e.token1)throw new P(`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&&cc(t.token0ClassKey)&&cc(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 ac(t.status,"Invalid pool data response format",n);return n},"GalaChainGatewayClient.getPoolData",void 0,e=>{throw this.handleError(e,"getPoolData")})}async getSlot0(e){return br(async()=>{if("string"==typeof e.token0||"string"==typeof e.token1)throw new P(`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 ac(t.status,"Invalid slot0 data response format",n);return n},"GalaChainGatewayClient.getSlot0",void 0,e=>{throw this.handleError(e,"getSlot0")})}async getPositions(e){return br(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(!uc(e))throw new ac(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 br(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 ac(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 br(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 ac(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 ac(500,"Invalid response format: not an object");if(!("Data"in e)||!("Status"in e))throw new ac(500,"Invalid response format: missing Data or Status field");if(e.Status>=400)throw new ac(e.Status,e.Message??"Gateway error",e.Data)}handleError(e,t){if(e instanceof ac)return e;if(C(e)){const n=e.response?.status??500,r=e.response?.data,i=r?.Message??T(e);return new ac(n,`${t}: ${i}`,r?.Data??void 0)}return new ac(500,`${t}: ${T(e)}`)}}class hc{constructor(e){this.http=e}async getUserAssets(e,t=20,n=0){return br(async()=>{if(!Je(e))throw W("walletAddress","Wallet address");const r=Vo(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 ac(500,"Invalid response format: not an object");const s=yr(o);if(!s||"object"!=typeof s)throw new ac(500,"Invalid response format: missing data wrapper");const a=s.token;if(!Array.isArray(a))throw new ac(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 ac(500,"Invalid asset in response: asset must be an object");const t=e;if(!Je(t.symbol)||!Je(t.name))throw new ac(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 ac(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 br(async()=>{const{address:t,search:n,page:r=1,limit:i=20}=e,o={page:r,limit:Xo(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 ac(500,"Invalid response format: not an object");const a=yr(s);if(!a||"object"!=typeof a)throw new ac(500,"Invalid response format: missing data wrapper");const c=a.token;if(!Array.isArray(c))throw new ac(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 ac(500,"Invalid token in response: must be an object");const t=e;if(!Je(t.symbol))throw new ac(500,'Invalid token in response: missing required field "symbol"',{token:t});if(!Je(t.name))throw new ac(500,'Invalid token in response: missing required field "name"',{token:t});const n=t.decimals;if("string"!=typeof n&&"number"!=typeof n)throw new ac(500,'Invalid token in response: missing required field "decimals"',{token:t});if(!Je(t.compositeKey))throw new ac(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 ac)return e;if(C(e)){const n=e.response?.status??500,r=e.response?.data,i=r?.message??r?.Message??T(e),o=r?.Data??r?.data??void 0;if(r){e.config}return new ac(n,`${t}: ${i}`,o)}return new ac(500,`${t}: ${T(e)}`)}}class dc{static createClient(e,t=6e4){return v(e,t)}}function fc(e){try{if(!Je(e))throw new Error("Token must be a non-empty string");return Vs(e)}catch(t){throw new P(`Invalid pipe-delimited token: "${e}". Expected format: "collection|category|type|additionalKey". Error: ${T(t)}`,"pipeDelimitedToken","INVALID_PIPE_DELIMITED_TOKEN_FORMAT")}}const gc=10;class pc extends fs{constructor(e,t,n){if(super(!1),this.pricingConcurrency=5,this.tokenConverter=new ca,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 hc(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 Y("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(bo(e.amount).isLessThanOrEqualTo(0))throw new O("Amount must be greater than zero",{amount:e.amount,fromToken:e.fromToken,toToken:e.toToken});if(!this.dexQuoteService)throw new O("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=bo(s.currentSqrtPrice),u=bo(s.newSqrtPrice),l=c.gt(u)?c.minus(u).dividedBy(c):bo(0),h=bo(s.amount0),d=bo(s.amount1),f=_o(h),g=_o(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:A(e)?e.message:"Unknown error"})}throw s||new O("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",O,e)}}async getSwapQuoteExactOutput(e){try{if(bo(e.amount).isLessThanOrEqualTo(0))throw new O("Amount must be greater than zero",{amount:e.amount,fromToken:e.fromToken,toToken:e.toToken});if(!this.dexQuoteService)throw new O("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=bo(s.currentSqrtPrice),u=bo(s.newSqrtPrice),l=c.gt(u)?c.minus(u).dividedBy(c):bo(0),h=o.pool.token0,d="string"==typeof h?js(h).collection:"object"==typeof h&&null!==h&&"tokenName"in h?h.tokenName:String(h),f=js(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:A(e)?e.message:"Unknown error"})}throw s||new O("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",O,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=vo(e.estimatedOutput,e.slippageTolerance||.01),i=this.getWalletAddress();if(!i)throw new P("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:T(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",U,e,{transactionHash:t?.txHash})}}async getUserAssets(e,t=1,n=20){return br(async()=>{if(!yt(e))throw new F(H("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 br(async()=>{if(!yt(e))throw new F(H("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 es(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 br(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=Jo(jo(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 br(async()=>{const{search:t}=e;this.logger.debug("Fetching all available DEX tokens (auto-paginated)",{search:t});const n=await es(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=bo(0),s=0;for(const a of i)try{const e="string"==typeof n?js(n):n,t="string"==typeof r?js(r):r,i=await this.gatewayClient.getPoolData({token0:e,token1:t,fee:a});i&&(o=o.plus(bo(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 M(`Failed to fetch pool info: ${T(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 js(e)}catch(t){if(A(t)&&T(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:Ue(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?js(e.compositeKey.replace(/\$/g,"|")):js(`${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:T(e)}),null}}async getUserLiquidityPositions(e,t=10,r,i){try{if(!e)throw W("ownerAddress","Owner address");this.logger.debug("Fetching user liquidity positions",{ownerAddress:e,limit:t,bookmark:r});const o=`${this.galaChainBaseUrl}/api/asset/dexv3-contract/GetUserPositions`,s={user:e,limit:t,bookmark:r||""};this.logger.debug("Sending position query request",{endpoint:o,payload:s});const a=await n.post(o,s,{headers:{"Content-Type":"application/json",Accept:"application/json"}}),c=yr(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 Ze(h)||(g.nextBookmark=h),Ze(f)||(g.prices=f),g}catch(t){C(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",$,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,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: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",$,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=fc(n),o=fc(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 $("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",$,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 u=5,l=2e3;for(let h=1;h<=u;h++)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:h,positionId:t});break}throw new $("Invalid position data from compound key lookup",null,"INVALID_DATA")}catch(e){this.logger.debug("Compound key lookup failed, trying fallback",{attempt:h,error:A(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 $("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:A(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=>Cs(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=ne(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:T(e)}),await new Promise(e=>setTimeout(e,l));continue}c=A(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||ne(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",$,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 $("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",$,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=fc(t),i=fc(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",$,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=js(t),i=js(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=bo(e.minPrice),a=bo(e.maxPrice),c=Math.floor(To(s)),u=Math.ceil(To(a)),l=Mo(c,o),h=Mo(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 D("GSwapService: No wallet address available - cannot create position","walletAddress");const f="string"==typeof e.token0?js(e.token0):e.token0,g="string"==typeof e.token1?js(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 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(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 D("No wallet address available","walletAddress");const i=(await this.getUserLiquidityPositions(t,10)).items;if(i&&i.length>0){const t=js(e.token0).collection.toUpperCase(),o=js(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=Bs(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:T(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(A(e)){const t=E(e);t?.split("\n").slice(0,3).join(" | ")}this.handleGSwapError("Failed to add liquidity by price",$,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?js(e.token0):e.token0,r="string"==typeof e.token1?js(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 Ze(c)||(u.createdAt=c),u}catch(t){return this.logger.warn("Could not fetch full position details",{positionId:s.positionId,error:T(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 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 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: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?js(e.token0).collection:e.token0.collection).toUpperCase(),n=("string"==typeof e.token1?js(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=Bs(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:T(e)}),this.logger.debug("Error waiting for position indexing",{error:T(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:T(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",$,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:T(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 P(`Invalid liquidity value: "${e.liquidity}". Must be a valid number. Position ID: ${e.positionId||"unknown"}`,"liquidity","INVALID_VALUE");if(0===t)throw new P(`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(A(e)&&T(e).includes("Cannot remove zero liquidity"))throw e;if(A(e)&&T(e).includes("Invalid liquidity value"))throw e;throw e}const t="string"==typeof e.token0?js(e.token0):e.token0,n="string"==typeof e.token1?js(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",$,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 ne(e.positionId);if(!t.token0||!t.token1)throw new $("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?js(e.token0):e.token0,n="string"==typeof e.token1?js(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",$,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=js(r),s=js(i),a=await this.gatewayClient.getPoolData({token0:o,token1:s,fee:n}),c=this.calculatePriceFromSqrtPriceX96(bo(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",M,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=bo(r.currentPrice);return{tokenA:e,tokenB:t,feeTier:n,price:i.toFixed(),invertedPrice:Eo(i,!0),tick:r.tick,liquidity:r.liquidity}}catch(e){this.handleGSwapError("Failed to calculate spot price",M,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,c=u.tickToSqrtPrice(o),l=u.tickToSqrtPrice(a),h=u.tickToSqrtPrice(s),d=u.getLiquidityForAmounts(bo(r),bo(i),c,l,h),f=u.getAmountsForLiquidity(d,l,c,h),g=f[0],p=f[1],m=bo(r),y=bo(i);return{amount0:g.toFixed(),amount1:p.toFixed(),liquidity:d.toFixed(),ratio:Uo(g,p).toFixed(),utilizationPercent:{amount0:Ro(Uo(g,m),100).toFixed(2),amount1:Ro(Uo(p,y),100).toFixed(2)}}}catch(e){this.handleGSwapError("Failed to calculate optimal position size",$,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=bo(o),f=bo(s);if(d.isNaN()||f.isNaN())a.push("Amounts must be valid numbers");else try{Lo(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");bo(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=T(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=bo(n),a=bo(r);ue(n,r,"priceRange");const c=Math.floor(To(s)),u=Math.ceil(To(a)),l=Mo(c,o),h=Mo(u,o),d=Math.pow(1.0001,l),f=Math.pow(1.0001,h),g=bo(d),p=bo(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:Ro(g.minus(s).dividedBy(s),100).toFixed(4),maxPriceDeviation:Ro(p.minus(a).dividedBy(a),100).toFixed(4)}}}catch(e){this.handleGSwapError("Failed to calculate ticks for price",$,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=bo(i),c=bo(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 Ze(s)||(u.currentPrice=s),u}catch(e){this.handleGSwapError("Failed to calculate price for ticks",$,e)}}calculateExecutionPrice(e,t){try{const n=bo(e);return Uo(bo(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 H("feeTier","500, 3000, or 10000","Fee tier")}}validateTickSpacing(e,t,n){const r=this.getTickSpacing(n);if(e%r!==0)throw new P(`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 P(`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=Io();return Uo(e,t).pow(2)}catch{return bo(0)}}calculatePriceFromSqrtPriceDecimal(e){try{return e.pow(2)}catch{return bo(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?js(e):e,i="string"==typeof t?js(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",M,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=bo(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",M,t,{token0:e.token0,token1:e.token1})}}calculateLiquidityFromAmount0(e,t,n){try{const r=u.tickToSqrtPrice(t),i=u.tickToSqrtPrice(n);return u.liquidity0(e,r,i)}catch{return bo(0)}}calculateLiquidityFromAmount1(e,t,n){try{const r=u.tickToSqrtPrice(t),i=u.tickToSqrtPrice(n);return u.liquidity1(e,r,i)}catch{return bo(0)}}calculateAmount0FromLiquidity(e,t,n){try{const r=u.tickToSqrtPrice(t),i=u.tickToSqrtPrice(n);return u.getAmount0Delta(r,i,e)}catch{return bo(0)}}calculateAmount1FromLiquidity(e,t,n){try{const r=u.tickToSqrtPrice(t),i=u.tickToSqrtPrice(n);return u.getAmount1Delta(r,i,e)}catch{return bo(0)}}convertTokenPair(e,t){return{gswapToken0:this.tokenConverter.toLaunchpadFormat(e),gswapToken1:this.tokenConverter.toLaunchpadFormat(t)}}async sendAddLiquidityToBundler(e){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:e.token0?.type??"unknown",token1:e.token1?.type??"unknown",fee:e.fee,tickRange:`${e.tickLower}-${e.tickUpper}`});const n=`galaswap - operation - ${s.v4()}-${Date.now()}-${e.owner}`,r={token0:e.token0,token1:e.token1,fee:e.fee,owner:e.owner,tickLower:e.tickLower,tickUpper:e.tickUpper,amount0Desired:e.amount0Desired,amount1Desired:e.amount1Desired,amount0Min:e.amount0Min,amount1Min:e.amount1Min,positionId:"",uniqueKey:n},i=new t.ethers.Wallet(this.privateKey),o={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,o,u),h={...u,signature:l,types:o,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(e.token0,e.token1,e.fee,e.owner),f=dc.createClient(this.bundlerBaseUrl,3e4),g=await f.post("/bundle",{method:"AddLiquidity",signedDto:h,stringsInstructions:d}),p=yr(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 L(`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(e,n,r,i,o,a,c,u,l){try{if(!this.bundlerBaseUrl)throw new D("GSwapService: Bundler URL not configured","bundlerBaseUrl");const h=new t.ethers.Wallet(this.privateKey),d=await h.getAddress(),f=`galaswap - operation - ${s.v4()}-${Date.now()}-${d}`,g={tickLower:e,tickUpper:n,amount:r,token0:i,token1:o,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,o,a,d);this.logger.debug("Submitting RemoveLiquidity to bundler",{tickLower:e,tickUpper:n,amount:r,fee:a,positionId:l,transactionId:f});const S=dc.createClient(this.bundlerBaseUrl,3e4),A=await S.post("/bundle",{method:"RemoveLiquidity",signedDto:k,stringsInstructions:v}),T=yr(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 L(`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(e,n,r,i,o,a,c,u){try{if(!this.bundlerBaseUrl)throw new D("GSwapService: Bundler URL not configured","bundlerBaseUrl");const l=new t.ethers.Wallet(this.privateKey),h=await l.getAddress(),d=`galaswap - operation - ${s.v4()}-${Date.now()}-${h}`,f={token0:e,token1:n,fee:r,amount0Requested:i,amount1Requested:o,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(e,n,r,h);this.logger.debug("Submitting CollectPositionFees to bundler",{fee:r,amount0Requested:i,amount1Requested:o,tickLower:a,tickUpper:c,positionId:u,transactionId:d});const v=dc.createClient(this.bundlerBaseUrl,3e4),S=await v.post("/bundle",{method:"CollectPositionFees",signedDto:b,stringsInstructions:k}),A=yr(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 L(`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(e){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(e.feeTier))throw new P(`GSwapService: Invalid fee tier ${e.feeTier}. Must be one of: ${n.join(", ")} (basis points)`,"feeTier","INVALID_FEE_TIER");try{this.logger.debug("Sending Swap to bundler",{fromToken:"string"==typeof e.fromToken?e.fromToken:e.fromToken?.type??"unknown",toToken:"string"==typeof e.toToken?e.toToken:e.toToken?.type??"unknown",inputAmount:e.inputAmount,minOutput:e.minOutput,feeTier:e.feeTier});let n=e.fromToken,r=e.toToken;"string"==typeof n&&(n=js(n)),"string"==typeof r&&(r=js(r));const i=Gs(n),o=Gs(r),a=i<o?[n,r,i,o]:[r,n,o,i],[c,u,l,h]=a,d=Gs("string"==typeof e.fromToken?js(e.fromToken):e.fromToken),f=d===l,g=`galaswap - operation - ${s.v4()}-${Date.now()}-${e.walletAddress}`;let p;if(!e.currentSqrtPrice)throw new P("GSwapService: currentSqrtPrice is required for sqrtPriceLimit calculation","currentSqrtPrice",_.REQUIRED);const m=bo(e.currentSqrtPrice),y=e.slippageTolerance??.01;if(f){const e=So(y);p=m.multipliedBy(e).toString()}else{const e=Ao(y);p=m.multipliedBy(e).toString()}this.logger.debug("Calculated sqrtPriceLimit based on slippage tolerance",{currentSqrtPrice:e.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:e.feeTier,amount:bo(e.inputAmount).toFixed(),zeroForOne:f,sqrtPriceLimit:p,recipient:e.walletAddress,amountOutMinimum:bo(e.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:e.inputAmount,expectedOutput:e.minOutput,slippageTolerance:100*(e.slippageTolerance||.01)+"%",currentSqrtPrice:e.currentSqrtPrice,swapDto:{amount:w.amount,zeroForOne:w.zeroForOne,sqrtPriceLimit:w.sqrtPriceLimit,amountOutMinimum:w.amountOutMinimum}});const b=new t.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,e.feeTier,e.walletAddress),C=dc.createClient(this.bundlerBaseUrl,3e4),N=await C.post("/bundle",{method:"Swap",signedDto:E,stringsInstructions:I}),B=yr(N),x=B?.data||B?.transactionId||B?.id;if(!x)throw this.logger.error("Bundler response structure",{status:N.status,data:B,dataType:typeof B}),new L(`Bundler response does not contain transaction ID. Response: ${JSON.stringify(B)}`,void 0,"INVALID_RESPONSE");return this.logger.debug("Swap transaction sent to bundler",{transactionId:x,inputAmount:e.inputAmount,minOutput:e.minOutput}),x}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||T(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=I(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 mc{}mc.BASE_PRICE=1650667151e-14,mc.PRICE_SCALING_FACTOR=1166069e-12,mc.TRADING_FEE_FACTOR=.001,mc.GAS_FEE="1",mc.MIN_UNBONDING_FEE_FACTOR=0,mc.MAX_UNBONDING_FEE_FACTOR=.5,mc.NET_UNBONDING_FEE_FACTOR=.5,mc.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY=1e7;class yc extends fs{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 wc extends yc{constructor(e=!1){super(e)}normalizeKey(e){return is(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>=wc.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||mc.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:${is(e)}`;return this.cache.get(t)||null}setByTokenId(e,t){const n=`token:${is(e)}`;this.updateCacheEntry(n,t)}hasByTokenId(e){const t=`token:${is(e)}`;return this.cache.has(t)}}wc.MAX_CACHE_SIZE=1e4;class bc 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:T(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:T(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=Ho.DEFAULT_PAGE,limit:o=Ho.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=As({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 ts(()=>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:Qo(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 es((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:Ts(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(!Je(e))throw new q("token0 must be a non-empty string",{token0:e});if(!Je(t))throw new q("token1 must be a non-empty string",{token1:t});try{Vs(e),Vs(t)}catch(n){throw new q(`Token format must be: collection|category|type|additionalKey (4 pipe-separated parts). ${T(n)}`,{token0:e,token1:t})}try{ce(n,"fee")}catch{throw new q(`fee must be a positive integer (got ${n})`,{fee:n})}const r=[500,3e3,1e4];if(!r.includes(n))throw new q(`fee must be one of: ${r.join(", ")} (got ${n})`,{fee:n})}validateQuoteAmount(e){if(!Je(e))throw new q("amount must be a non-empty string",{amount:e});const t=bo(e);try{Oo(t,"amount")}catch(t){throw new q(t.message,{amount:e})}}convertTokenClassKey(e){const t=new a.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=fc(t),o=fc(n),s=this.convertTokenClassKey(e),c=this.convertTokenClassKey(o),l=new u.GetCompositePoolDto(s,c,r),h=`${i||this.galaChainBaseUrl}/api/asset/dexv3-contract/GetCompositePool`,d=await this.http.post(h,l);N(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 u.Pool(e.pool.token0,e.pool.token1,e.pool.token0ClassKey,e.pool.token1ClassKey,e.pool.fee,bo(e.pool.sqrtPrice),e.pool.protocolFees);t.bitmap=e.pool.bitmap,t.grossPoolLiquidity=bo(e.pool.grossPoolLiquidity),t.liquidity=bo(e.pool.liquidity),t.feeGrowthGlobal0=bo(e.pool.feeGrowthGlobal0),t.feeGrowthGlobal1=bo(e.pool.feeGrowthGlobal1),t.protocolFeesToken0=bo(e.pool.protocolFeesToken0),t.protocolFeesToken1=bo(e.pool.protocolFeesToken1),t.tickSpacing=e.pool.tickSpacing,t.maxLiquidityPerTick=bo(e.pool.maxLiquidityPerTick);const n={};Object.keys(e.tickDataMap).forEach(t=>{const r=e.tickDataMap[t],i=new u.TickData(r.poolHash,r.tick);i.initialised=r.initialised,i.liquidityNet=bo(r.liquidityNet),i.liquidityGross=bo(r.liquidityGross),i.feeGrowthOutside0=bo(r.feeGrowthOutside0),i.feeGrowthOutside1=bo(r.feeGrowthOutside1),n[t]=i});const r={...e.token0Balance},i=new a.TokenBalance(r);i.quantity=bo(e.token0Balance.quantity);const o={...e.token1Balance},s=new a.TokenBalance(o);return s.quantity=bo(e.token1Balance.quantity),new u.CompositePoolDto(t,n,i,s,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 K)throw e;const i=T(e);if(i.includes("status indicates failure")||i.includes("Pool not found"))throw new K(i);throw this.logger.error("Failed to fetch composite pool data",e),new q(`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 q("compositePoolData is required for local quote calculation",{compositePoolData:t});try{const e=n===t.pool.token0.replace(/\$/g,"|"),o=fc(n),s=fc(r),a=this.convertTokenClassKey(o),c=this.convertTokenClassKey(s),[l,h]=n<r?[a,c]:[c,a],d=new u.QuoteExactAmountDto(l,h,t.pool.fee,bo(i),e,t.compositePoolDto),f=await u.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 q(`Local quote calculation failed: ${T(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 q("compositePoolData is required for external quote calculation (token format info)",{compositePoolData:t});try{const e=n===t.pool.token0.replace(/\$/g,"|"),o=fc(n),s=fc(r),a=this.convertTokenClassKey(o),c=this.convertTokenClassKey(s),l=new u.QuoteExactAmountDto(a,c,t.pool.fee,bo(i),e,void 0),h=`${this.galaChainBaseUrl}/api/asset/dexv3-contract/QuoteExactAmount`,d=await this.http.post(h,l);N(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 q(`External quote calculation failed: ${T(e)}`,{fromToken:n,toToken:r,amount:i})}}async calculateDexPoolQuoteExactAmount(e,t="local"){return"external"===t?this.calculateDexPoolQuoteExactAmountExternal(e):this.calculateDexPoolQuoteExactAmountLocal(e)}}class vc{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=Le(Math.floor(.5*e.length),0),n=Le(Math.floor(.95*e.length),0),r=Le(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 Le(e/this.eventsProcessed*100,NaN)}getThroughputPerSecond(){const e=Le(Xe(this.startTime)/1e3,0);return 0===e?0:Le(this.eventsProcessed/e,0)}recordMemory(){if("undefined"!=typeof process&&process.memoryUsage){const e=Le(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?Le(process.memoryUsage().heapUsed/1024/1024,0):0}getPoolAverageLatency(e){const t=this.perPoolMetrics.get(e);return t&&0!==t.eventsProcessed?Le(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:Le(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:Le(ko(s,1),0),maxMB:i,percentUsed:Math.min(100,Le(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?Le(this.eventLatencies.reduce((e,t)=>e+t,0)/this.eventLatencies.length,0):0;return{eventsProcessed:this.eventsProcessed,eventsDropped:this.eventsDropped,cacheHitRate:this.getCacheHitRate(),averageLatency:Le(ko(e,0),0),memoryUsedMB:Le(ko(this.getMemoryUsedMB(),1),0),throughputPerSecond:Le(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 Sc{static createPoolKey(e,t,n){return`${e}/${t}/${n}`}static parsePoolKey(e){if(!Je(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=Oe(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:$e(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(bo(e).dividedBy(1e4),2)}%`}static isValidTokenPair(e,t){return Boolean(e)&&Boolean(t)&&e!==t}}class Ac{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 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(Je(t))return t}return null}extractToken(e,...t){for(const n of t){const t=e[n];if(Je(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:$e(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(Je(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(Cs(r,"zerotoone")||"0to1"===r)return"zeroForOne";if(Cs(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 Tc{static getCached(e){const t=e.toString();return this.CACHE.has(t)||this.CACHE.set(t,bo(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])}}}Tc.CACHE=new Map,Tc.ZERO=Me(0),Tc.ONE=Me(1),Tc.FEE_PIPS=Me(1e6),Tc.MIN_SQRT_RATIO=Me("4295128739"),Tc.MAX_SQRT_RATIO=new o("1461446703485210103287273052203988822378723970342");const Ec={maxIterations:100,enableBigNumberCache:!0,roundingMode:o.ROUND_DOWN,debugLogging:!1};class Ic{static calculateSwapDelta(e,t,n={}){const r=Date.now(),i={...Ec,...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=bo(s.sqrtPrice),n=bo(t.actualSqrtPrice),r=e.minus(n).abs();c=Le(Uo(r,n).times(100).toNumber(),0)}const u=Xe(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: ${T(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?Tc.getCached.bind(Tc):e=>Me(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),c=i(s),l=r.tick??0,h=u.sqrtPriceToTick(bo(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);Oo(f,"amountSpecified");const g="string"==typeof r.feeGrowthGlobal1?r.feeGrowthGlobal1:ko(r.feeGrowthGlobal1,0),p="string"==typeof r.feeGrowthGlobal0?r.feeGrowthGlobal0:ko(r.feeGrowthGlobal0,0),m=t.zeroForOne?i(g):i(p);return{sqrtPrice:a,liquidity:c,tick:l,amountSpecifiedRemaining:f,amountCalculated:Tc.ZERO,feeGrowthGlobalX:m,protocolFee:Tc.ZERO}}static computeSwapLoop(e,t,n,r){const{pool:i,tickDataMap:s}=t,a=[],c={};let l=0;const h=n.zeroForOne?Tc.MIN_SQRT_RATIO:Tc.MAX_SQRT_RATIO,d=bo("0.000001");for(;e.amountSpecifiedRemaining.gt(d)&&!e.sqrtPrice.eq(h)&&l<r.maxIterations;){l++;const[t,d]=this.findNextInitializedTick(s,e.tick,i.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=u.tickToSqrtPrice(t);f=e instanceof o?e:bo(String(e))}else f=h;const g=n.zeroForOne?No(f,h):Co(f,h),p=this.executeSwapStep(e.sqrtPrice,g,e.liquidity,e.amountSpecifiedRemaining,i.fee,n.exactInput);if(e.sqrtPrice=p.sqrtPriceNext,n.exactInput){const t=p.amountIn.plus(p.feeAmount);t.lte(0)?e.amountSpecifiedRemaining=Tc.ZERO:(e.amountSpecifiedRemaining=e.amountSpecifiedRemaining.minus(t),e.amountSpecifiedRemaining.lt(0)&&(e.amountSpecifiedRemaining=Tc.ZERO)),e.amountCalculated=e.amountCalculated.minus(p.amountOut)}else{p.amountOut.lte(0)?e.amountSpecifiedRemaining=Tc.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=Uo(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?bo(i.liquidityNet).negated():bo(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),c[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=u.sqrtPriceToTick(bo(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:c}}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=bo(e.protocolFeesToken0);i.protocolFeesToken0=ko(n.plus(t.protocolFee),0)}else{const n=bo(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=bo(n.amountSpecified),a=t.amountCalculated.abs();n.zeroForOne?(r=e.negated(),i=a,o=Tc.ZERO,s=Tc.ZERO):(r=a,i=e.negated(),o=Tc.ZERO,s=Tc.ZERO)}else{const e=bo(n.amountSpecified),a=t.amountCalculated.abs();n.zeroForOne?(r=a.negated(),i=e,o=Tc.ZERO,s=Tc.ZERO):(r=e,i=a.negated(),o=Tc.ZERO,s=Tc.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=>Ue(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,i,s){Lo(n),Oo(r,"amountRemaining");const a=[500,3e3,1e4];if(!a.includes(i))throw new Error(`Invalid fee tier: ${i}. Must be one of: ${a.join(", ")}`);const c=u.computeSwapStep(e,t,n,r,i,t.lt(e)),l=c[0],h=c[1],d=c[2],f=c[3],g=o.isBigNumber(l)?l:bo(String(l)),p=o.isBigNumber(h)?h:bo(String(h)),m=o.isBigNumber(d)?d:bo(String(d)),y=o.isBigNumber(f)?f:bo(String(f));return{sqrtPriceStart:e,tickNext:u.sqrtPriceToTick(g),sqrtPriceNext:g,initialised:!1,amountIn:p,amountOut:m,feeAmount:y}}}Ic.logger=new We({debug:!1,context:"SwapDeltaCalculator"});class Cc extends fs{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=Ic.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 W("poolKey","Pool key");if(this.cache.has(e))return!0;try{return await br(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 br(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 Nc extends fs{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(Xe(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=Xe(t);this.metrics.recordEventLatency(n)}catch(t){throw this.logger.error(`Event processing failed for ${e.transactionId}:`,t),t}}}class Bc extends fs{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 vc,this.config=this.applyDefaults(r),this.eventExtractor=new Ac(this.logger),this.quoteService=n,this.cacheManager=new Cc(t,this.config,this.metrics,this.logger),this.eventQueue=new Nc(this.config,this.metrics,this.logger),this.seenTransactions=new xc(this.maxSeenTransactions),this.reconnectionManager=new rc({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(A(e)?e:new Error(T(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=Xe(n);t.metrics.recordEventLatency(s)}catch(e){t.logger.error("Error processing WebSocket payload:",e),t.notifyError(A(e)?e:new Error(T(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(!Sc.containsToken(e.poolKey,t.tokenFilter))return!1}if(t.pairTokens){const[n,r]=t.pairTokens;if(!Sc.containsTokenPair(e.poolKey,n,r))return!1}if(t.feeTierFilter){if(Sc.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=Xe(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(A(t)?t:new Error(T(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 xc{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 fs{constructor(e=!1){super(e),this.primaryIndex=new Map,this.secondaryIndex=new Map,this.fetchTimestamps=new Map}normalizeKey(e){return os(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 Pc=["ETHEREUM","SOLANA"];class Rc 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(Pc);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 P("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 Q(e,t,this.logger)}}class Lc extends Dc{constructor(e,t=!1){super(e,t,"BridgeableTokenService"),this.cache=new Rc(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})`),br(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 br(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=oa(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??Vs(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 Oc extends yc{constructor(e=!1){super(e),this.lastFetchedAt=null}normalizeKey(e){return os(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 Uc extends Oc{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 Mc extends Dc{constructor(e,t=!1){super(e,t,"WrappableTokenService"),this.cache=new Uc(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())})`),br(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 br(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=oa(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=oa(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 $c(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 qc,Kc,Gc,zc,Wc,Hc;function jc(){return zc?Gc:(zc=1,Gc={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 Vc=function(){if(Hc)return Wc;Hc=1;const e=Kc?qc:(Kc=1,qc={space:"",cycles:!1,replacer:(e,t)=>t,stringify:JSON.stringify}),t=jc().isFunction,n=jc().isBoolean,r=jc().isObject,i=jc().isArray,o=jc().isRegex,s=jc().assign,a=jc().keys;return Wc=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)},Wc}(),Xc=Fc(Vc);const Qc={GALA_CHAIN:1,ETHEREUM:2,SOLANA:1002},Jc={ASSET:1,MUSIC:3};const Yc="0x9f452b7cC24e6e6FA690fe77CF5dD2ba3DbF1ED9",Zc="0x6a1734E09f3099a3675645D214ce547080ea67e0",eu="https://dex-api-platform-dex-prod-gala.gala.com",tu=[{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}],nu=[{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 ru(e){return"PROD"===e?tu:nu}function iu(e){return"PROD"===e?Yc:Zc}const ou=tu,su=[{symbol:"GALA",amount:"1",mintAddress:"eEUiUs4JWYZrp72djAGF1A8PhpR6rHphGeGN7GbVLp6",isNative:!1,decimals:8},{symbol:"GSOL",amount:"0.001",mintAddress:"So11111111111111111111111111111111111111111",isNative:!0,decimals:9}],au={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"}},cu=["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)"],uu=["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"],lu={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 hu={name:"GalaConnect",chainId:1},du=[{name:"destinationChainId",type:"uint256"},{name:"destinationChainTxFee",type:"destinationChainTxFee"},{name:"quantity",type:"string"},{name:"recipient",type:"string"},{name:"tokenInstance",type:"tokenInstance"},{name:"uniqueKey",type:"string"}],fu=[{name:"collection",type:"string"},{name:"category",type:"string"},{name:"type",type:"string"},{name:"additionalKey",type:"string"}],gu=[{name:"collection",type:"string"},{name:"category",type:"string"},{name:"type",type:"string"},{name:"additionalKey",type:"string"},{name:"instance",type:"string"}],pu=[{name:"name",type:"string"},{name:"symbol",type:"string"}],mu={GalaTransaction:du,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:fu,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:gu,externalQuoteToken:pu,tokenInstance:gu},yu={GalaTransaction:du,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:fu,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:pu,externalQuoteToken:pu,externalCrossRateToken:pu,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:gu,tokenInstance:gu};function wu(e){return e?yu:mu}const bu={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:gu};class ku extends fs{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 P(`Token not found or not wrappable: ${this.formatTokenId(e.tokenId)}`,"tokenId","TOKEN_NOT_WRAPPABLE");if("asset"===t.channel)throw new P(`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 P(`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 P(`Token not found or not wrappable: ${this.formatTokenId(e.tokenId)}`,"tokenId","TOKEN_NOT_WRAPPABLE");if("asset"!==t.channel)throw new P(`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 P(`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 P(`Token not found or not wrappable: ${this.formatTokenId(e)}`,"tokenId","TOKEN_NOT_WRAPPABLE");if("asset"===n.channel)throw new P(`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 P(`Token not found or not wrappable: ${this.formatTokenId(e)}`,"tokenId","TOKEN_NOT_WRAPPABLE");if("asset"!==n.channel)throw new P(`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 P("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=bu,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: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(hu,a,i),c=`Ethereum Signed Message:\n${Xc({domain:hu,message:i,primaryType:"GalaTransaction",types:a}).length}`,u={...i,signature:e,prefix:c,types:a,domain:hu};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=T(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:Jc.ASSET,authType:"cross_channel_authorization"}}return{sourceChannel:"asset",destinationChannelId:Jc.MUSIC,authType:"automatic"}}requireWallet(){if(!this.walletAddress)throw new P("Wallet required for wrap/unwrap operations. Initialize SDK with a private key.","wallet","WALLET_REQUIRED")}formatTokenId(e){return"string"==typeof e?e:Gs(e)}}const vu="x-api-key";class Su 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(!Je(e))throw W("tokenName","Token name");const n=is(e);if(!t.PATTERN.test(n))throw H("tokenName",`${t.MIN_LENGTH}-${t.MAX_LENGTH} alphanumeric characters`,"Token name")}(e,t)}validateRequiredString(e,t,n){!function(e,t,n){if(!Je(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 ee(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 ee(t,"number",typeof e,n);if(e<r||e>i)throw J(t,r,i,e,n)}}(e,t,n,r,i)}validateOptionalDate(e,t,n){!function(e,t,n){if(null!=e&&!Ve(e))throw H(t,"a valid ISO 8601 date string",n)}(e,t,n)}validatePositiveInteger(e,t,n){ls(e,t,n)}validateStatusFilter(e,t,n="status"){hs(e,t,n)}buildPaginationParams(e,t){return As(e,t)}addOptionalFilterParams(e,t,n){return Es(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{[vu]: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 mr(e,"Backend request failed",!0),wr(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??is(e)}}}const Au={IDLE:"IDLE",ACTIVE:"ACTIVE",DISABLED:"DISABLED"},Tu={READY:"READY",PROCESSING:"PROCESSING",ERRORED:"ERRORED",DELETED:"DELETED"},Eu={YOUTUBE:"YOUTUBE",TWITCH:"TWITCH",FACEBOOK:"FACEBOOK",CUSTOM:"CUSTOM"},Iu=tt(Au),Cu=tt(Tu),Nu=tt(Eu);const Bu={OWNER:"OWNER",MANAGER:"MANAGER",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MODERATOR:"MODERATOR"},xu={OWNER:"OWNER",MODERATOR:"MODERATOR"};tt(Bu),tt(xu);const _u={...Bu,OVERSEER:"OVERSEER"},Pu={OWNERSHIP:"ownership",MODERATOR_INVITE:"moderator_invite",OVERSEER:"overseer"};function Ru(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 Du=tt(_u),Lu=tt(Pu);function Ou(e,t="tokenName"){it(e,t,fe)}function Uu(e){if(Ou(e.tokenName),!Je(e.language))throw W("language");if(!function(e){return!!Je(e)&&/^[a-z]{2}(-[A-Z]{2})?$/.test(e)}(e.language))throw new P('language must be a valid ISO 639-1 code (e.g., "en", "es", "zh-CN")',"language",_.INVALID_FORMAT)}class Mu extends Su{constructor(e,t,n,r=!1){super(e,t,n,r)}async getStreamInfo(e){this.validateTokenName(e,fe);const t=this.buildEndpoint(zt,{tokenName:e}),n=await this.http.get(t);return this.extractData(n)}async startStream(e){this.validateTokenName(e,fe);const t=this.buildEndpoint(Kt,{tokenName:e}),n=await this.http.post(t,{},this.getJwtHeaders());return this.extractData(n)}async stopStream(e){this.validateTokenName(e,fe);const t=this.buildEndpoint(Gt,{tokenName:e});await this.http.post(t,{},this.getJwtHeaders())}async disableStream(e){return this.toggleFeature(e,Wt,fe)}async enableStream(e){return this.toggleFeature(e,Ht,fe)}async resetStreamKey(e){this.validateTokenName(e,fe);const t=this.buildEndpoint(jt,{tokenName:e}),n=await this.http.post(t,{},this.getJwtHeaders());return this.extractData(n)}async getRecordings(e){!function(e){Ou(e.tokenName),et(e.page,e.limit,Be)}(e);const t=this.buildEndpoint(Vt,{tokenName:e.tokenName}),n=this.buildPaginationParams(e,Be),r=await this.http.get(t,n),i=this.extractData(r);return{recordings:i.recordings,tokenName:is(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,fe),this.validateRequiredString(t,"assetId","Asset ID");const n=this.buildEndpoint(Xt,{tokenName:e,assetId:t}),r=await this.http.get(n,this.getJwtHeaders());return this.extractData(r)}async deleteRecording(e,t){this.validateTokenName(e,fe),this.validateRequiredString(t,"assetId","Asset ID");const n=this.buildEndpoint(Qt,{tokenName:e,assetId:t});await this.http.delete(n,void 0,this.getJwtHeaders())}async getSimulcastTargets(e){this.validateTokenName(e,fe);const t=this.buildEndpoint(Jt,{tokenName:e}),n=await this.http.get(t);return this.extractData(n)}async addSimulcastTarget(e){!function(e){if(Ou(e.tokenName),!Je(e.platform))throw W("platform");if(!Nu(e.platform))throw new P("platform must be one of: 'YOUTUBE', 'TWITCH', 'FACEBOOK', 'CUSTOM'","platform",_.INVALID_VALUE);if(!Je(e.rtmpUrl))throw W("rtmpUrl");if(!Ne.STREAM_URL_PATTERN.test(e.rtmpUrl))throw new P("rtmpUrl must be a valid RTMP, RTMPS, or SRT URL","rtmpUrl",_.INVALID_FORMAT);if(!Je(e.streamKey))throw W("streamKey");if(void 0!==e.name&&"string"!=typeof e.name)throw new P("name must be a string","name",_.INVALID_TYPE)}(e);const t=this.buildEndpoint(Yt,{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,fe),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(en);return this.extractData(e)}async disableGlobalStreaming(){const e=await this.http.post(tn,{},this.getAdminHeaders());return this.extractData(e)}async enableGlobalStreaming(){const e=await this.http.post(nn,{},this.getAdminHeaders());return this.extractData(e)}async setNextLiveStream(e){let t;!function(e){if(Ou(e.tokenName),null!==e.nextLiveStreamAt){if(!(e.nextLiveStreamAt instanceof Date||Je(e.nextLiveStreamAt)))throw new P("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 P("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(rn,{tokenName:e.tokenName}),r=await this.http.post(n,{nextLiveStreamAt:t},this.getDualAuthHeaders());return this.extractData(r)}async clearNextLiveStream(e){this.validateTokenName(e,fe);const t=this.buildEndpoint(on,{tokenName:e}),n=await this.http.delete(t,void 0,this.getDualAuthHeaders());return this.extractData(n)}async setStreamLanguage(e){Uu(e);const t=this.buildEndpoint(sn,{tokenName:e.tokenName}),n=await this.http.put(t,{language:e.language},this.getDualAuthHeaders());return this.extractData(n)}async getStreamRole(e){!function(e){Ou(e.tokenName)}(e);const t=this.buildEndpoint(an,{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(cn);return this.extractData(e)}async getTokenAccess(e){!function(e){Ou(e.tokenName)}(e);const t=this.buildEndpoint(un,{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})}}fe.MIN_LENGTH,fe.MAX_LENGTH,fe.PATTERN;tt({ENABLED:"ENABLED",DISABLED:"DISABLED",ADMIN_DISABLED:"ADMIN_DISABLED"});function Fu(e){return"global"===e||"token"===e}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&&"number"==typeof t.poolId&&"string"==typeof t.createdAt}function qu(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 Ku=tt({RATE_LIMITED:"RATE_LIMITED",INVALID_EMOJI:"INVALID_EMOJI",NOT_AUTHENTICATED:"NOT_AUTHENTICATED",STREAM_NOT_LIVE:"STREAM_NOT_LIVE"});function Gu(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 zu extends Su{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(!Je(e.tokenName))throw W("tokenName","Token name");const t=e.tokenName.trim();if(0===t.length)throw W("tokenName","Token name");if(!fe.PATTERN.test(t))throw H("tokenName",`match pattern ${fe.PATTERN}`,"Token name");if(et(e.page,e.limit,be),void 0!==e.cursor&&!Je(e.cursor))throw ee("cursor","a non-empty string",typeof e.cursor);if(void 0!==e.sortOrder&&"asc"!==e.sortOrder&&"desc"!==e.sortOrder)throw H("sortOrder","'asc' or 'desc'")}(e),br(async()=>{const t=this.buildEndpoint(ln,{tokenName:e.tokenName}),n=this.buildPaginationParams(e,be);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=Xo(e.limit),s=i.page??Vo(e.page),a={messages:i.messages,tokenName:is(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(!Je(e.tokenName))throw W("tokenName","Token name");const t=e.tokenName.trim();if(0===t.length)throw W("tokenName","Token name");if(!fe.PATTERN.test(t))throw H("tokenName",`match pattern ${fe.PATTERN}`,"Token name");if(t.length>fe.MAX_LENGTH)throw Z("tokenName",fe.MAX_LENGTH,t.length,"Token name");if(!Je(e.content))throw W("content","Message content");if(e.content.length<Se.CHAT_MESSAGE.MIN_LENGTH)throw Y("content",Se.CHAT_MESSAGE.MIN_LENGTH,e.content.length,"Message content");if(e.content.length>Se.CHAT_MESSAGE.MAX_LENGTH)throw Z("content",Se.CHAT_MESSAGE.MAX_LENGTH,e.content.length,"Message content")}(e),br(async()=>{const t=this.buildEndpoint(hn,{tokenName:e.tokenName}),n=await this.http.post(t,{content:e.content},this.getJwtHeaders());return{message:this.extractData(n),tokenName:is(e.tokenName)}},"Failed to send chat message",this.logger)}async deleteMessage(e){if(!e)throw W("options","Delete message options");return function(e){if(!Je(e.tokenName))throw W("tokenName","Token name");const t=e.tokenName.trim();if(0===t.length)throw W("tokenName","Token name");if(!fe.PATTERN.test(t))throw H("tokenName",`match pattern ${fe.PATTERN}`,"Token name");if(!Je(e.messageId))throw W("messageId","Message ID")}(e),br(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:is(e.tokenName)}},"Failed to delete chat message",this.logger)}async getChatStatus(e){if(!e)throw W("tokenName","Token name");return this.validateTokenName(e,fe),br(async()=>{const t=this.buildEndpoint(fn,{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,fe),br(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??is(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,fe),br(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??is(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(bn);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(vn,{},this.getAdminHeaders());return this.extractData(e)}async getPinnedMessage(e){this.validateTokenName(e,fe);const t=this.buildEndpoint(mn,{tokenName:e}),n=await this.http.get(t),r=this.extractData(n);return{tokenName:r.tokenName??is(e),pinnedMessage:r.pinnedMessage}}async pinMessage(e){!function(e){if(!Je(e.tokenName))throw W("tokenName","Token name");const t=e.tokenName.trim();if(0===t.length)throw W("tokenName","Token name");if(!fe.PATTERN.test(t))throw H("tokenName",`match pattern ${fe.PATTERN}`,"Token name");if(!Je(e.messageId))throw W("messageId","Message ID")}(e);const t=this.buildEndpoint(yn,{tokenName:e.tokenName}),n=await this.http.post(t,{messageId:e.messageId},this.getAdminHeaders()),r=this.extractData(n);return{tokenName:r.tokenName??is(e.tokenName),pinnedMessage:r.pinnedMessage}}async unpinMessage(e){this.validateTokenName(e,fe);const t=this.buildEndpoint(wn,{tokenName:e}),n=await this.http.delete(t,this.getAdminHeaders()),r=this.extractData(n),i={tokenName:r.tokenName??is(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(!Je(e.tokenName))throw W("tokenName","Token name");const t=e.tokenName.trim();if(0===t.length)throw W("tokenName","Token name");if(!fe.PATTERN.test(t))throw H("tokenName",`match pattern ${fe.PATTERN}`,"Token name")}(e),br(async()=>{const t=this.buildEndpoint(Sn,{tokenName:e.tokenName}),n=await this.http.get(t,void 0,this.getDualAuthHeaders()),r=this.extractData(n);return{tokenName:is(e.tokenName),chat:r.chat,comments:r.comments}},"Failed to get engagement stats",this.logger)}}const Wu={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 Hu extends fs{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 rc({maxAttempts:this.config.reconnectAttempts,baseDelayMs:this.config.reconnectDelay}),this.isSocketIOAvailable=this.checkSocketIOAvailability()}checkSocketIOAvailability(){try{return"function"==typeof c.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:",T(e)),!1}}getRoomName(e){return`token:${is(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=is(e),r=[{key:`${Wu.STREAM_STATUS}:${n}`,callback:t.onStreamStatus},{key:`${Wu.VIEWER_COUNT}:${n}`,callback:t.onViewerCount},{key:`${Wu.CHAT_MESSAGE}:${n}`,callback:t.onChatMessage},{key:`${Wu.CHAT_STATUS}:${n}`,callback:t.onChatStatus},{key:`${Wu.CHAT_PINNED}:${n}`,callback:t.onChatPinned},{key:`${Wu.CHAT_UNPINNED}:${n}`,callback:t.onChatUnpinned},{key:`${Wu.COUNTDOWN_UPDATED}:${n}`,callback:t.onCountdownUpdated},{key:`${Wu.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(Wu.STREAM_STATUS,e=>{this.logger.debug(`📡 [Stream Status] ${e.tokenName}: ${e.status}`),this.bufferEvent(Wu.STREAM_STATUS,e.tokenName,e);const t=this.roomCallbacks.get(is(e.tokenName));t?.onStreamStatus&&t.onStreamStatus(e),this.globalCallbacks.onStreamStatus&&this.globalCallbacks.onStreamStatus(e)}),this.socket.on(Wu.STREAM_SUBSCRIBED,e=>{this.logger.debug(`📡 [Subscribed] ${e.tokenName}`);const t=is(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(Wu.STREAM_UNSUBSCRIBED,e=>{const t=e.room.replace("token:","");this.logger.debug(`📡 [Unsubscribed] ${t}`);const n=this.roomCallbacks.get(is(t));n?.onStreamUnsubscribed&&n.onStreamUnsubscribed(e)}),this.socket.on(Wu.VIEWER_COUNT,e=>{this.logger.debug(`📡 [Viewer Count] ${e.tokenName}: ${e.viewerCount}`),this.bufferEvent(Wu.VIEWER_COUNT,e.tokenName,e);const t=this.roomCallbacks.get(is(e.tokenName));t?.onViewerCount&&t.onViewerCount(e),this.globalCallbacks.onViewerCount&&this.globalCallbacks.onViewerCount(e)}),this.socket.on(Wu.STREAM_GLOBAL_STATUS,e=>{this.logger.debug(`📡 [Global Stream Status] enabled: ${e.enabled}`),this.globalCallbacks.onStreamGlobalStatus&&this.globalCallbacks.onStreamGlobalStatus(e)}),this.socket.on(Wu.CHAT_MESSAGE,e=>{this.logger.debug(`📡 [Chat Message] ${e.tokenName}: ${e.message.content.slice(0,50)}...`),this.bufferEvent(Wu.CHAT_MESSAGE,e.tokenName,e);const t=this.roomCallbacks.get(is(e.tokenName));t?.onChatMessage&&t.onChatMessage(e),this.globalCallbacks.onChatMessage&&this.globalCallbacks.onChatMessage(e)}),this.socket.on(Wu.CHAT_SENT,e=>{this.logger.debug(`📡 [Chat Sent] ${e.tokenName}: ${e.messageId}`);const t=this.roomCallbacks.get(is(e.tokenName));t?.onChatSent&&t.onChatSent(e)}),this.socket.on(Wu.CHAT_ERROR,e=>{this.logger.error(`📡 [Chat Error] ${e.tokenName}: ${e.message}`);const t=this.roomCallbacks.get(is(e.tokenName));t?.onChatError&&t.onChatError(e),this.globalCallbacks.onChatError&&this.globalCallbacks.onChatError(e)}),this.socket.on(Wu.CHAT_STATUS,e=>{this.logger.debug(`📡 [Chat Status] ${e.tokenName}: ${e.enabled}`),this.bufferEvent(Wu.CHAT_STATUS,e.tokenName,e);const t=this.roomCallbacks.get(is(e.tokenName));t?.onChatStatus&&t.onChatStatus(e),this.globalCallbacks.onChatStatus&&this.globalCallbacks.onChatStatus(e)}),this.socket.on(Wu.CHAT_GLOBAL_STATUS,e=>{this.logger.debug(`📡 [Global Chat Status] enabled: ${e.enabled}`),this.globalCallbacks.onChatGlobalStatus&&this.globalCallbacks.onChatGlobalStatus(e)}),this.socket.on(Wu.CHAT_AUTHENTICATED,e=>{this.logger.debug(`📡 [Authenticated] ${e.address}`),this.isAuthenticated=!0,this.globalCallbacks.onChatAuthenticated&&this.globalCallbacks.onChatAuthenticated(e)}),this.socket.on(Wu.CHAT_AUTH_ERROR,e=>{this.logger.error(`📡 [Auth Error] ${e.message}`),this.isAuthenticated=!1,this.globalCallbacks.onChatAuthError&&this.globalCallbacks.onChatAuthError(e)}),this.socket.on(Wu.REACTION,e=>{this.logger.debug(`📡 [Reaction] ${e.tokenName}: ${e.emoji}`);const t=this.roomCallbacks.get(is(e.tokenName));t?.onReaction&&t.onReaction(e),this.globalCallbacks.onReaction&&this.globalCallbacks.onReaction(e)}),this.socket.on(Wu.REACTION_ERROR,e=>{this.logger.error(`📡 [Reaction Error] ${e.tokenName}: ${e.message}`);const t=this.roomCallbacks.get(is(e.tokenName));t?.onReactionError&&t.onReactionError(e),this.globalCallbacks.onReactionError&&this.globalCallbacks.onReactionError(e)}),this.socket.on(Wu.USER_TYPING,e=>{const t=e.typingUsers.length;this.logger.debug(`📡 [Typing] ${e.tokenName}: ${t} user(s) typing`);const n=this.roomCallbacks.get(is(e.tokenName));n?.onTypingIndicator&&n.onTypingIndicator(e),this.globalCallbacks.onTypingIndicator&&this.globalCallbacks.onTypingIndicator(e)}),this.socket.on(Wu.CHAT_PINNED,e=>{this.logger.debug(`📡 [Chat Pinned] ${e.tokenName}: ${e.pinnedMessage.messageId}`),this.bufferEvent(Wu.CHAT_PINNED,e.tokenName,e);const t=this.roomCallbacks.get(is(e.tokenName));t?.onChatPinned&&t.onChatPinned(e),this.globalCallbacks.onChatPinned&&this.globalCallbacks.onChatPinned(e)}),this.socket.on(Wu.CHAT_UNPINNED,e=>{this.logger.debug(`📡 [Chat Unpinned] ${e.tokenName}: ${e.unpinnedMessageId}`),this.bufferEvent(Wu.CHAT_UNPINNED,e.tokenName,e);const t=this.roomCallbacks.get(is(e.tokenName));t?.onChatUnpinned&&t.onChatUnpinned(e),this.globalCallbacks.onChatUnpinned&&this.globalCallbacks.onChatUnpinned(e)}),this.socket.on(Wu.COUNTDOWN_UPDATED,e=>{const t=e.nextLiveStreamAt??"cleared";this.logger.debug(`📡 [Countdown Updated] ${e.tokenName}: ${t}`),this.bufferEvent(Wu.COUNTDOWN_UPDATED,e.tokenName,e);const n=this.roomCallbacks.get(is(e.tokenName));n?.onCountdownUpdated&&n.onCountdownUpdated(e),this.globalCallbacks.onCountdownUpdated&&this.globalCallbacks.onCountdownUpdated(e)}),this.socket.on(Wu.LANGUAGE_UPDATED,e=>{this.logger.debug(`📡 [Language Updated] ${e.tokenName}: ${e.language}`),this.bufferEvent(Wu.LANGUAGE_UPDATED,e.tokenName,e);const t=this.roomCallbacks.get(is(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(Wu.SUBSCRIBE,{tokenName:t})}catch(e){this.logger.error(`Failed to re-subscribe to ${t}:`,e)}}async connect(){return new Promise((e,t)=>{br(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=c.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 P("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(Wu.AUTHENTICATE,{token:e}),this.config.authToken=e}async subscribeToStream(e,t={}){if(!e)throw W("tokenName","Token name");if(!this.socket?.connected)throw new P("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");const n=is(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(Wu.SUBSCRIBE,{tokenName:n})})}unsubscribeFromStream(e){const t=is(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(Wu.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 P("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(!this.isAuthenticated)throw new P("Not authenticated. Call authenticate() first.","auth","NOT_AUTHENTICATED");const n=is(e);this.logger.debug(`📡 Sending chat message to ${n}: ${t.slice(0,30)}...`),this.socket.emit(Wu.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 P("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(!this.isAuthenticated)throw new P("Not authenticated. Call authenticate() first.","auth","NOT_AUTHENTICATED");const r=is(e);this.logger.debug(`📡 Sending reaction to ${r}: ${t}`),this.socket.emit(Wu.SEND_REACTION,{tokenName:r,emoji:t,streamTime:n})}sendTypingStart(e){if(!e)throw W("tokenName","Token name");if(!this.socket?.connected)throw new P("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(!this.isAuthenticated)throw new P("Not authenticated. Call authenticate() first.","auth","NOT_AUTHENTICATED");const t=is(e);this.logger.debug(`📡 Sending typing_start to ${t}`),this.socket.emit(Wu.TYPING_START,{tokenName:t})}sendTypingStop(e){if(!e)throw W("tokenName","Token name");if(!this.socket?.connected)throw new P("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(!this.isAuthenticated)throw new P("Not authenticated. Call authenticate() first.","auth","NOT_AUTHENTICATED");const t=is(e);this.logger.debug(`📡 Sending typing_stop to ${t}`),this.socket.emit(Wu.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 ju extends fs{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 Vu={VIEWERS:"viewers",CHAT_PARTICIPANTS:"chat_participants"},Xu=tt(Vu),Qu=st([{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}]),Ju=st([{field:"userAddress",type:"string"},{field:"isPermanent",type:"boolean"}]),Yu=st([{field:"userAddress",type:"string"}]),Zu=st([{field:"tokenName",type:"string"},{field:"action",type:"string",validator:e=>"chat"===e||"comment"===e||"reaction"===e}]);function el(e){return null==e||""===e||"string"==typeof e&&(!ct(e)&&e.length<=Se.BAN_REASON.MAX_LENGTH)}function tl(e){return!!Ze(e)||"number"==typeof e&&(e>=Te&&e<=Ee)}class nl extends Su{constructor(e,t,n,r=!1){super(e,t,n,r)}async createBan(e){!function(e){if(it(e.tokenName,"tokenName",fe),!Je(e.userAddress))throw W("userAddress");if(!el(e.reason))throw new P(`reason must be at most ${Se.BAN_REASON.MAX_LENGTH} characters`,"reason","TOO_LONG");if(!tl(e.durationSeconds))throw new P(`durationSeconds must be between ${Te} and ${Ee} seconds`,"durationSeconds","OUT_OF_RANGE")}(e);const t=this.buildEndpoint(In,{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:is(e.tokenName)}}async removeBan(e){!function(e){if(it(e.tokenName,"tokenName",fe),!Je(e.userAddress))throw W("userAddress")}(e);const t=this.buildEndpoint(Bn,{tokenName:e.tokenName,userAddress:e.userAddress}),n=await this.http.delete(t,this.getDualAuthHeaders()),r=this.extractData(n);return{removed:r.removed,tokenName:is(e.tokenName),userAddress:r.userAddress}}async listBans(e){!function(e){it(e.tokenName,"tokenName",fe),et(e.page,e.limit,me)}(e);const t=this.buildEndpoint(Cn,{tokenName:e.tokenName}),n=this.buildPaginationParams(e,me);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(it(e.tokenName,"tokenName",fe),!Je(e.userAddress))throw W("userAddress")}(e);const t=this.buildEndpoint(Nn,{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:is(e.tokenName),userAddress:e.userAddress.toLowerCase()}}async getActiveUsers(e){!function(e){if(it(e.tokenName,"tokenName",fe),void 0!==e.type&&!Xu(e.type))throw new P(`type must be one of: ${Object.values(Vu).join(", ")}`,"type",_.INVALID_VALUE)}(e);const t=this.buildEndpoint(xn,{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 rl(e){return null==e||""===e||"string"==typeof e&&(!ct(e)&&e.length<=Se.BAN_REASON.MAX_LENGTH)}function il(e){if(it(e.tokenName,"tokenName",fe),!rl(e.reason))throw new P(`reason must be at most ${Se.BAN_REASON.MAX_LENGTH} characters`,"reason","TOO_LONG")}function ol(e){it(e.tokenName,"tokenName",fe)}function sl(e){et(e.page,e.limit,me)}function al(e){it(e.tokenName,"tokenName",fe)}class cl extends Su{constructor(e,t,n,r=!1){super(e,t,n,r)}async banToken(e){il(e);const t=Jn,n={tokenName:is(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:is(e.tokenName)}}async unbanToken(e){ol(e);const t=this.buildEndpoint(er,{tokenName:e.tokenName}),n=await this.http.delete(t,this.getDualAuthHeaders());return{removed:this.extractData(n).removed,tokenName:is(e.tokenName)}}async listTokenBans(e={}){sl(e);const t=Yn,n=this.buildPaginationParams(e,me);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){al(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:is(e.tokenName)}}async isTokenBanned(e){return this.getTokenBan(e)}}const ul={MODERATOR:"MODERATOR",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MANAGER:"MANAGER",OWNER:"OWNER"},ll=nt(ul);function hl(e){return ll.includes(e)}function dl(e){const t=[];e.role?hl(e.role)||t.push(`Invalid role. Must be one of: ${ll.join(", ")}`):t.push(W("role").message);const n=t.length;if(x(t,()=>{as(e.description,"description",255)}),t.length>n&&(t[n]="Description must be 255 characters or less"),void 0!==e.tokenNames){const n=t.length;x(t,()=>{if(!Array.isArray(e.tokenNames))throw ee("tokenNames","an array",e.tokenNames);if(!e.tokenNames.every(e=>"string"==typeof e))throw ee("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;x(t,()=>{us(e.expiresAt,"expiresAt")}),t.length>n&&(t[n]="expiresAt must be a valid ISO 8601 date string")}return t}function fl(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||hl(e.role)||t.push(`Invalid role. Must be one of: ${ll.join(", ")}`);const n=t.length;if(x(t,()=>{as(e.description,"description",255)}),t.length>n&&(t[n]="Description must be 255 characters or less"),void 0!==e.tokenNames){const n=t.length;x(t,()=>{if(!Array.isArray(e.tokenNames))throw ee("tokenNames","an array",e.tokenNames);if(!e.tokenNames.every(e=>"string"==typeof e))throw ee("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;x(t,()=>{us(e.expiresAt,"expiresAt")}),t.length>n&&(t[n]="expiresAt must be a valid ISO 8601 date string")}return t}function gl(e){et(e.page,e.limit,me)}const pl={[ul.MODERATOR]:1,[ul.TECHNICAL_PRODUCER]:1,[ul.MANAGER]:2,[ul.OWNER]:3};class ml 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),mr(t,"API key operation failed",!0),e.data}validateApiKeyId(e){this.validatePositiveInteger(e,"id","API key ID")}async create(e){const t=dl(e);if(t.length>0)throw new P(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={}){gl(e),this.logger.debug("Listing API keys",e);const t=void 0!==e.limit?Xo(e.limit,1,me):void 0,n={};void 0!==e.page&&(n.page=e.page),void 0!==t&&(n.limit=t);const r={...As(n,me)},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=fl(t);if(n.length>0)throw new P(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[...ll]}}const yl={MODERATOR:"MODERATOR",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MANAGER:"MANAGER"},wl=nt(yl),bl={TOKEN:"TOKEN",ALL_OWNER_TOKENS:"ALL_OWNER_TOKENS"},kl=nt(bl),vl={PENDING:"PENDING",CLAIMED:"CLAIMED",REVOKED:"REVOKED",EXPIRED:"EXPIRED"},Sl=nt(vl);function Al(e){return wl.includes(e)}function Tl(e){return Sl.includes(e)}function El(e){return Ce.PATTERN.test(e)}const Il=st([{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"}]),Cl=st([{field:"tokenName",type:"string"},{field:"tokenSymbol",type:"string"},{field:"role",type:"string"},{field:"inviteScope",type:"string"},{field:"creatorAddress",type:"string"},{field:"claimedAt",type:"string"}]),Nl=st([{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 Bl(e){return kl.includes(e)}class xl extends Su{constructor(e,t,n,r=!1){super(e,t,n,r)}validateRole(e){if(!Je(e))throw W("role","Role");if(!Al(e))throw H("role",`one of: ${wl.join(", ")}`,"Role")}validateInviteCodeFormat(e){if(!Je(e))throw W("inviteCode","Invite code");if(!El(e))throw H("inviteCode","valid invite code format","Invite code")}validateInviteScope(e){if(void 0!==e&&!Bl(e))throw new P(`Invalid invite scope. Must be one of: ${kl.join(", ")}`,"inviteScope","INVALID_VALUE")}async createInvite(e){this.validateInviteScope(e.inviteScope);const t=e.inviteScope??bl.TOKEN;if(t===bl.TOKEN){if(!e.tokenName)throw new P("Token name is required for TOKEN scope invites","tokenName","REQUIRED");this.validateTokenName(e.tokenName,fe)}else if(t===bl.ALL_OWNER_TOKENS&&e.tokenName)throw new P("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",Se.DESCRIPTION.MAX_LENGTH),this.validateOptionalDate(e.expiresAt,"expiresAt","Expiration date");const n=Pn,r={inviteScope:t,role:e.role};t===bl.TOKEN&&e.tokenName&&(r.tokenName=is(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,fe),this.validateStatusFilter(e.status,vl);const t=Ln,n={...this.buildPaginationParams(e,we.MAX_LIMIT)};e.tokenName&&(n.tokenName=is(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(On,{id:String(e)});mr(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(Un,{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=Rn,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??{},we.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(Mn,{code:e}),n=await this.http.get(t,{});return this.extractData(n)}}var _l,Pl,Rl,Dl;e.ContentType=void 0,(_l=e.ContentType||(e.ContentType={})).CHAT_MESSAGE="CHAT_MESSAGE",_l.COMMENT="COMMENT",_l.STREAM="STREAM",e.FlagReason=void 0,(Pl=e.FlagReason||(e.FlagReason={})).INAPPROPRIATE_CONTENT="INAPPROPRIATE_CONTENT",Pl.SPAM="SPAM",Pl.HARASSMENT="HARASSMENT",Pl.SCAM="SCAM",Pl.OTHER="OTHER",e.FlagStatus=void 0,(Rl=e.FlagStatus||(e.FlagStatus={})).PENDING="PENDING",Rl.DISMISSED="DISMISSED",Rl.ACTIONED="ACTIONED",e.FlagAction=void 0,(Dl=e.FlagAction||(e.FlagAction={})).DELETE_CONTENT="DELETE_CONTENT",Dl.BAN_USER="BAN_USER",Dl.DELETE_AND_BAN="DELETE_AND_BAN";const Ll={[e.FlagReason.INAPPROPRIATE_CONTENT]:"Inappropriate Content",[e.FlagReason.SPAM]:"Spam",[e.FlagReason.HARASSMENT]:"Harassment",[e.FlagReason.SCAM]:"Scam",[e.FlagReason.OTHER]:"Other"},Ol={[e.FlagStatus.PENDING]:"Pending",[e.FlagStatus.DISMISSED]:"Dismissed",[e.FlagStatus.ACTIONED]:"Actioned"},Ul={[e.FlagAction.DELETE_CONTENT]:"Delete Content",[e.FlagAction.BAN_USER]:"Ban User",[e.FlagAction.DELETE_AND_BAN]:"Delete & Ban"},Ml={[e.ContentType.CHAT_MESSAGE]:"Chat Message",[e.ContentType.COMMENT]:"Comment",[e.ContentType.STREAM]:"Stream"},Fl=tt(e.ContentType),$l=tt(e.FlagReason),ql=tt(e.FlagStatus),Kl=tt(e.FlagAction),Gl=st([{field:"id",type:"number"},{field:"tokenName",type:"string"},{field:"contentType",type:"string",validator:Fl},{field:"contentId",type:"string"},{field:"reporterAddress",type:"string"},{field:"reportedUserAddress",type:"string"},{field:"status",type:"string",validator:ql}]),zl={TOKEN_NAME:ge,CONTENT_ID:Se.CONTENT_ID,DETAILS:Se.FLAG_DETAILS,PAGINATION:{MAX_LIMIT:me}};function Wl(e,t="tokenName"){it(e,t,zl.TOKEN_NAME)}class Hl extends Su{constructor(e,t,n,r=!1){super(e,t,n,r)}async createFlag(t){!function(t){if(Wl(t.tokenName),!t.contentType)throw W("contentType","Content type");if(!Fl(t.contentType))throw H("contentType",`one of: ${Object.values(e.ContentType).join(", ")}`,"Content type");if(!Je(t.contentId))throw W("contentId","Content ID");if(t.contentId.length>zl.CONTENT_ID.MAX_LENGTH)throw Z("contentId",zl.CONTENT_ID.MAX_LENGTH,t.contentId.length,"Content ID");if(!Je(t.reportedUserAddress))throw W("reportedUserAddress","Reported user address");if(wt(t.reportedUserAddress,"reportedUserAddress"),t.contentType===e.ContentType.STREAM&&!t.reason)throw W("reason","Reason");if(void 0!==t.reason&&!$l(t.reason))throw H("reason",`one of: ${Object.values(e.FlagReason).join(", ")}`,"Reason");if(void 0!==t.details&&!Je(t.details))throw ee("details","a non-empty string",typeof t.details);if(void 0!==t.details&&t.details.length>zl.DETAILS.MAX_LENGTH)throw Z("details",zl.DETAILS.MAX_LENGTH,t.details.length)}(t);const n={tokenName:t.tokenName,contentType:t.contentType,contentId:t.contentId,reportedUserAddress:t.reportedUserAddress};t.reason&&(n.reason=t.reason),t.details&&(n.details=t.details);const r=await this.http.post(Fn.CREATE,n,this.getJwtHeaders());return{flag:this.extractData(r).flag}}async listFlags(t){!function(t){if(Wl(t.tokenName),void 0!==t.contentType&&!Fl(t.contentType))throw H("contentType",`one of: ${Object.values(e.ContentType).join(", ")}`,"Content type");if(void 0!==t.status&&!ql(t.status))throw H("status",`one of: ${Object.values(e.FlagStatus).join(", ")}`);if(void 0!==t.reason&&!$l(t.reason))throw H("reason",`one of: ${Object.values(e.FlagReason).join(", ")}`);if(void 0!==t.reporterAddress&&!Je(t.reporterAddress))throw ee("reporterAddress","a non-empty string",typeof t.reporterAddress);if(void 0!==t.reporterAddress&&wt(t.reporterAddress,"reporterAddress"),void 0!==t.reportedUserAddress&&!Je(t.reportedUserAddress))throw ee("reportedUserAddress","a non-empty string",typeof t.reportedUserAddress);void 0!==t.reportedUserAddress&&wt(t.reportedUserAddress,"reportedUserAddress"),et(t.page,t.limit,zl.PAGINATION.MAX_LIMIT)}(t);const n={};void 0!==t.page&&(n.page=t.page),void 0!==t.limit&&(n.limit=t.limit);const r=As(n,me);Es(r,t,["contentType","status","reason","reporterAddress","reportedUserAddress"]);const i=Fn.LIST.replace(":tokenName",encodeURIComponent(t.tokenName)),o=await this.http.get(i,r,this.getDualAuthHeaders()),s=this.extractData(o);return{items:s.flags,meta:s.meta}}async listGlobalFlags(t={}){!function(t){if(void 0!==t.tokenName&&Wl(t.tokenName),void 0!==t.contentType&&!Fl(t.contentType))throw H("contentType",`one of: ${Object.values(e.ContentType).join(", ")}`,"Content type");if(void 0!==t.status&&!ql(t.status))throw H("status",`one of: ${Object.values(e.FlagStatus).join(", ")}`);if(void 0!==t.reason&&!$l(t.reason))throw H("reason",`one of: ${Object.values(e.FlagReason).join(", ")}`);if(void 0!==t.reporterAddress&&!Je(t.reporterAddress))throw ee("reporterAddress","a non-empty string",typeof t.reporterAddress);if(void 0!==t.reporterAddress&&wt(t.reporterAddress,"reporterAddress"),void 0!==t.reportedUserAddress&&!Je(t.reportedUserAddress))throw ee("reportedUserAddress","a non-empty string",typeof t.reportedUserAddress);void 0!==t.reportedUserAddress&&wt(t.reportedUserAddress,"reportedUserAddress"),et(t.page,t.limit,zl.PAGINATION.MAX_LIMIT)}(t);const n={};void 0!==t.page&&(n.page=t.page),void 0!==t.limit&&(n.limit=t.limit);const r=As(n,me);Es(r,t,["tokenName","contentType","status","reason","reporterAddress","reportedUserAddress"]);const i=await this.http.get(Fn.LIST_GLOBAL,r,this.getDualAuthHeaders()),o=this.extractData(i);return{items:o.flags,meta:o.meta}}async dismissFlag(e){!function(e){if(void 0===e.flagId||null===e.flagId)throw W("flagId","Flag ID");try{ce(e.flagId,"flagId")}catch{throw H("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(t){!function(t){if(void 0===t.flagId||null===t.flagId)throw W("flagId","Flag ID");try{ce(t.flagId,"flagId")}catch{throw H("flagId","a positive integer","Flag ID")}if(!t.action)throw W("action","Action");if(!Kl(t.action))throw H("action",`one of: ${Object.values(e.FlagAction).join(", ")}`,"Action")}(t);const n=Fn.ACTION.replace(":id",t.flagId.toString()),r=await this.http.post(n,{action:t.action},this.getDualAuthHeaders());return{flag:this.extractData(r).flag}}}const jl={PENDING:"PENDING",CLAIMED:"CLAIMED",REVOKED:"REVOKED",EXPIRED:"EXPIRED"},Vl={ACTIVE:"ACTIVE",REVOKED:"REVOKED"},Xl=tt(jl),Ql=tt(Vl);function Jl(e){try{as(e.description,"description",255)}catch(e){if(e instanceof P){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(!Je(e.expiresAt))throw new Error("expiresAt must be a non-empty string");try{us(e.expiresAt,"expiresAt")}catch(e){if(e instanceof P)throw new Error("expiresAt must be a valid ISO 8601 date string");throw e}if(Ve(e.expiresAt)){if(je(e.expiresAt)<=new Date)throw new Error("expiresAt must be in the future")}}}function Yl(e){if(void 0!==e.status&&!Xl(e.status))throw re("status",e.status,Object.values(jl),"status");et(e.page,e.limit,50)}function Zl(e){if(void 0!==e.status&&!Ql(e.status))throw re("status",e.status,Object.values(Vl),"status");et(e.page,e.limit,50)}function eh(e){if(!Je(e))throw new Error("Invite code must be a non-empty string");ae(e,100,"code")}function th(e){if(!Je(e))throw new Error("Address must be a non-empty string");try{wt(e,"address")}catch{throw new Error("Invalid wallet address format. Must be eth|..., 0x..., or client|... format")}}function nh(e){try{cs(e,"id")}catch(e){if(e instanceof P)throw new Error("Invite ID must be a positive integer");throw e}}function rh(e){if(!e||"object"!=typeof e)throw new P("Options are required");if(void 0===e.page&&void 0===e.limit||et(e.page,e.limit,100),void 0!==e.search){if("string"!=typeof e.search)throw new P("Search must be a string");if(0===e.search.length)throw new P("Search query cannot be empty string")}if(void 0!==e.sortBy){if("string"!=typeof e.sortBy)throw new P("Sort field must be a string");if(0===e.sortBy.length)throw new P("Sort field cannot be empty string")}if(void 0!==e.sortOrder&&"asc"!==e.sortOrder&&"desc"!==e.sortOrder)throw new P('Sort order must be "asc" or "desc"')}class ih extends Su{constructor(e,t,n,r=!1){super(e,t,n,r)}validateInviteCodeFormat(e){if(!Je(e))throw W("inviteCode","Invite code");eh(e)}validateWalletAddressFormat(e){if(!Je(e))throw W("address","Address");th(e)}async createInvite(e={}){Jl(e),this.validateOptionalString(e.description,"description","Description",Se.DESCRIPTION.MAX_LENGTH),this.validateOptionalDate(e.expiresAt,"expiresAt","Expiration date");const t=$n,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={}){Yl(e),this.validateStatusFilter(e.status,jl);const t=qn,n={...this.buildPaginationParams(e,we.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(Kn,{code:e}),n=await this.http.get(t,{});return this.extractData(n)}async revokeInvite(e){nh(e);const t=this.buildEndpoint(zn,{id:String(e)});mr(await this.http.delete(t,this.getDualAuthHeaders()),"Failed to revoke invite")}async claimInvite(e){this.validateInviteCodeFormat(e);const t=Gn,n={inviteCode:e},r=await this.http.post(t,n,this.getJwtHeaders());return{invite:this.extractData(r)}}async listOverseers(e={}){Zl(e),this.validateStatusFilter(e.status,Vl);const t=Wn,n={...this.buildPaginationParams(e,we.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(Hn,{address:e});mr(await this.http.delete(t,this.getDualAuthHeaders()),"Failed to revoke overseer")}async getMyStatus(){const e=jn,t=await this.http.get(e,{},this.getJwtHeaders());return this.extractData(t)}async getSummary(){const e=Vn,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async listOverseerUsers(e){const t=e||{};Object.keys(t).length>0&&rh(t);const n=Xn,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(!Je(e))throw W("address","User address");th(e);const t=this.buildEndpoint(Qn,{address:e}),n=await this.http.get(t,{},this.getDualAuthHeaders());return this.extractData(n)}}class oh extends Su{constructor(e,t,n,r=!1){super(e,t,n,r)}async fetchComments(e){!function(e){it(e.tokenName,"tokenName",ge),et(e.page,e.limit,me)}(e);const t=is(e.tokenName),n=void 0!==e.limit?Xo(e.limit,1,me):void 0,r={};void 0!==e.page&&(r.page=e.page),void 0!==n&&(r.limit=n);const i={tokenName:t,...As(r,me)},o=await this.http.get(tr,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(it(e.tokenName,"tokenName",ge),!Je(e.content))throw W("content");if(e.content.length>Se.COMMENT.MAX_LENGTH)throw new P(`content must be at most ${Se.COMMENT.MAX_LENGTH} characters`,"content",_.TOO_LONG)}(e);const t=nr,n={content:e.content.trim(),tokenName:is(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");cs(e.commentId,"commentId")}(e);const t=this.buildEndpoint(rr,{commentId:String(e.commentId)});return await this.http.delete(t,void 0,this.getJwtHeaders()),{success:!0}}}const sh=["heart","fire","laugh","wow","thumbs_up"];class ah extends Su{constructor(e,t,n,r=!1){super(e,t,n,r)}validateReactionTokenName(e){this.validateTokenName(e,ge)}validateMessageId(e){if(!Je(e))throw W("messageId","Message ID");if(ae(e,Ae.CONTENT_REACTION.MAX_LENGTH,"messageId"),!Ae.CONTENT_REACTION.PATTERN.test(e))throw H("messageId","msg-{timestamp}-{uuid} or chat-{timestamp}-{uuid} format","Message ID")}validateReactionType(e){if(!Je(e))throw W("reactionType","Reaction type");if(!sh.includes(e))throw H("reactionType",`one of: ${sh.join(", ")}`,"Reaction type")}async addContentReaction(e){this.validateReactionTokenName(e.tokenName),this.validateMessageId(e.messageId),this.validateReactionType(e.reactionType);const t={tokenName:is(e.tokenName),messageId:e.messageId,reactionType:e.reactionType},n=await this.http.post(ir,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(or,{messageId:e.messageId,reactionType:e.reactionType}),n={tokenName:is(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 ch extends Su{constructor(e,t,n,r=!1){super(e,t,n,r)}validateContent(e){if(!Je(e))throw W("content","Comment content");if(0===e.trim().length)throw W("content","Comment content");ae(e,Se.COMMENTS_V1.MAX_LENGTH,"content")}validateMessageId(e){if(!Je(e))throw W("id","Message ID");if(e.length<10||e.length>64)throw H("id","valid message ID format","Message ID")}async getComments(e){if(!e.tokenName&&!e.userAddress)throw new P("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={...As(t,we.MAX_LIMIT)};e.tokenName&&(n.tokenName=is(e.tokenName)),e.userAddress&&(n.userAddress=e.userAddress);const r=await this.http.get(hr,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:is(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(fr,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 uh(e){if(!e.tokenName&&!e.userAddress)throw new P("At least one of tokenName or userAddress is required","options",_.REQUIRED);if(void 0!==e.tokenName){if(!Je(e.tokenName))throw ee("tokenName","string");if(e.tokenName.length>pe.MAX_LENGTH)throw new P(`tokenName must be at most ${pe.MAX_LENGTH} characters`,"tokenName",_.TOO_LONG)}if(void 0!==e.userAddress){if(!Je(e.userAddress))throw ee("userAddress","string");if(e.userAddress.length>ve.MAX_LENGTH)throw new P(`userAddress must be at most ${ve.MAX_LENGTH} characters`,"userAddress",_.TOO_LONG)}et(e.page,e.limit,we.MAX_LIMIT)}function lh(e){if(!Je(e.tokenName))throw W("tokenName");if(e.tokenName.length>pe.MAX_LENGTH)throw new P(`tokenName must be at most ${pe.MAX_LENGTH} characters`,"tokenName",_.TOO_LONG);if(!Je(e.content))throw W("content");if(0===e.content.trim().length)throw new P("content cannot be empty","content",_.REQUIRED);if(e.content.length>Se.CHAT_MESSAGES_V1.MAX_LENGTH)throw new P(`content must be at most ${Se.CHAT_MESSAGES_V1.MAX_LENGTH} characters`,"content",_.TOO_LONG)}function hh(e){if(!Je(e.content))throw W("content");if(0===e.content.trim().length)throw new P("content cannot be empty","content",_.REQUIRED);if(e.content.length>Se.CHAT_MESSAGES_V1.MAX_LENGTH)throw new P(`content must be at most ${Se.CHAT_MESSAGES_V1.MAX_LENGTH} characters`,"content",_.TOO_LONG)}function dh(e){if(!Je(e))throw W("id","Message ID");if(!Ae.CHAT_MESSAGE.PATTERN.test(e))throw new P("Invalid message ID format. Expected: chat-{timestamp}-{uuid}","id",_.INVALID_FORMAT)}class fh extends Su{constructor(e,t,n,r=!1){super(e,t,n,r)}async getChatMessages(e){uh(e);const t=this.buildPaginationParams(e,we.MAX_LIMIT);e.tokenName&&(t.tokenName=is(e.tokenName)),e.userAddress&&(t.userAddress=e.userAddress);const n=await this.http.get(ar,t);return this.extractData(n)}async sendMessage(e){lh(e);const t={tokenName:is(e.tokenName),content:e.content.trim()},n=await this.http.post(cr,t,this.getJwtHeaders());return{message:this.extractData(n)}}async updateMessage(e,t){dh(e),hh(t);const n=this.buildEndpointWithId(ur,e),r={content:t.content.trim()},i=await this.http.put(n,r,this.getJwtHeaders());return{message:this.extractData(i)}}async deleteMessage(e){dh(e);const t=this.buildEndpointWithId(lr,e);mr(await this.http.delete(t,this.getDualAuthHeaders()),"Failed to delete message")}}function gh(e){const t=function(e){const t=to(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 ph="/api/asset/launchpad-contract/CallNativeTokenIn",mh="/api/asset/launchpad-contract/CallNativeTokenOut",yh="/api/asset/launchpad-contract/CallMemeTokenIn",wh="/api/asset/launchpad-contract/CallMemeTokenOut";class bh extends r.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 kh(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 vh={NATIVE:"native",EXACT:"exact"},Sh={LOCAL:"local",EXTERNAL:"external"};class Ah{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}=mc,c=this.roundUp(i*(Math.exp((r+n)*o)-Math.exp(r*o))/o,8),u=ko(bo(c).multipliedBy(s));return{amount:c.toString(),reverseBondingCurveFee:"0",transactionFee:u,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}=mc,c=Math.log(n*o/i+Math.exp(r*o))/o-r,u=ko(bo(c).multipliedBy(s));return{amount:c.toString(),reverseBondingCurveFee:"0",transactionFee:u,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:u,TRADING_FEE_FACTOR:l,GAS_FEE:h}=mc,d=c*(Math.exp(s*u)-Math.exp((s-o)*u))/u,f=bo(d),g=r+s/a*(i-r),p=ko(f.multipliedBy(g),8),m=ko(f.multipliedBy(l));return{amount:d.toString(),reverseBondingCurveFee:p,transactionFee:m,gasFee:h}}static calculateSellWithNative(e,t,n,r,i){const o=De(e),s=De(t),a=De(n),{BASE_PRICE:c,PRICE_SCALING_FACTOR:u,TRADING_FEE_FACTOR:l,GAS_FEE:h}=mc;if(o>=c*(Math.exp(s*u)-1)/u){const e=bo(o),t=r+s/a*(i-r),n=ko(e.multipliedBy(t),8),c=ko(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=bo(o),g=r+s/a*(i-r),p=ko(f.multipliedBy(g),8),m=ko(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 Th{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 wc}addIfDefined(e,t,n){return void 0!==n&&(e[t]=n),e}async uploadImageByTokenName(e){const{tokenName:t,options:n}=e;qo(t);const r=`${t}.png`;Os(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 H("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 j(r.message||"Image upload failed - no URL returned",r.status);const i=yr(r);if(!i?.imageUrl)throw j("Image upload failed - no URL returned",r.status);return i.imageUrl}catch(e){if(A(e)&&e.message.includes("FormData"))throw V("File upload failed: FormData not supported in this environment. Ensure you have proper polyfills for Node.js environments.","FormData");throw e}}async fetchPoolsFromAPI(e){et(e.page,e.limit),e.tokenName&&qo(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=Sr(t),r=await this.http.get("/launchpad/fetch-pool",n);if(!0===r.error||200!==r.status)throw j(r.message||"Failed to fetch pools",r.status);const i=yr(r);if(!i)throw j("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=!Bo(t)||!Bo(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=!Bo(t)||!Bo(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=!Bo(t)||!Bo(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 HE});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:Qo(c,l)}}}async _getAmount(e){if(function(e){const t=mo(e);!t.success&&t.errors&&$o(t.errors,"options")}(e),!this.galaChainHttp)throw V("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:ph,body:{vaultAddress:n,tokenQuantity:r,IsPreMint:!1}};if("NATIVE"===e&&"OUT"===t)return{endpoint:mh,body:{vaultAddress:n,tokenQuantity:r,IsPreMint:!1}};if("MEME"===e&&"IN"===t)return{endpoint:yh,body:{vaultAddress:n,nativeTokenQuantity:r,IsPreMint:!1}};if("MEME"===e&&"OUT"===t)return{endpoint:wh,body:{vaultAddress:n,nativeTokenQuantity:r,IsPreMint:!1}};throw H("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(!kh(e))throw j("Malformed response data from GalaChain gateway");try{N(e,"GalaChain calculation")}catch(e){throw j(T(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:T(r)}),j(T(r),500)}}async checkPool(e){Ko(e),e.tokenName&&qo(e.tokenName);const t=Sr(e),n=await this.http.get("/launchpad/check-pool",t);if(!0===n.error||200!==n.status)throw j(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(!ys(e))throw H("options","{ tokenName: string, from?: number, to?: number, resolution?: number }");const{tokenName:t,from:n,to:r,resolution:i}=e;if(qo(t),!n||!r||!i)throw W("graphOptions","Graph options (from, to, resolution)");const o={tokenName:t,from:n,to:r,resolution:i};Go(o);const s=Sr(o),a=await this.http.get("/launchpad/get-graph-data",s);if(!0===a.error||200!==a.status)throw j(a.message||"Failed to fetch graph data",a.status);const c=yr(a);if(!c)throw j("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 H("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 ee("mode",'"local" or "external"',o);if(!Je(t))throw W("tokenName","Token name");if(!Je(n))throw W("amount","Amount");if(r!==vh.NATIVE&&r!==vh.EXACT)throw ee("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===vh.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 ee("mode",'"local" or "external"',c);if(!Je(t))throw W("tokenName","Token name");if(!Je(n))throw W("amount","Amount");if(r!==vh.EXACT&&r!==vh.NATIVE)throw ee("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===vh.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(!Je(n))throw W("amount","Amount");if(r!==vh.NATIVE&&r!==vh.EXACT)throw ee("type",'"native" or "exact"',r);void 0!==i&&zo(i,"currentSupply");const o=!i;if(o&&!t)throw W("tokenName","Token name (required when currentSupply is not provided)");t&&qo(t);let s=i;if(o){s=(await this.fetchPoolDetailsForCalculation(t)).currentSupply}return r===vh.EXACT?Ah.calculateBuyWithExact(n,s):Ah.calculateBuyWithNative(n,s)}async calculateSellAmountLocal(e){const{tokenName:t,amount:n,type:r,currentSupply:i,maxSupply:o,reverseBondingCurveMaxFeeFactor:s,reverseBondingCurveMinFeeFactor:a}=e;if(!Je(n))throw W("amount","Amount");if(r!==vh.EXACT&&r!==vh.NATIVE)throw ee("type",'"exact" or "native"',r);void 0!==i&&zo(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&&qo(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===vh.EXACT?Ah.calculateSellWithExact(n,u,l,d,h):Ah.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 gs(t,"tokenName")&&function(e){return void 0===e.calculateAmountMode||"local"===e.calculateAmountMode||"external"===e.calculateAmountMode}(t)&&ps(t,"currentSupply")}(e))throw ee("options","CalculateBuyAmountForGraduationOptions or string (token name)",typeof e);const{tokenName:n,calculateAmountMode:r,currentSupply:i}=t;qo(n);const o=await this.tokenResolver.resolveTokenToVault(n);if(!o)throw new P(Er(n),"tokenName","VAULT_NOT_FOUND");if(!this.galaChainHttp)throw V("GalaChain HTTP client not configured");const s=await this.galaChainHttp.post("/api/asset/launchpad-contract/FetchSaleDetails",{vaultAddress:o});if(1!==s.Status)throw j(`Failed to fetch pool details: Status ${s.Status}`,s.Status);const a=s.Data,c=i??ko(bo(a.maxSupply).minus(a.sellingTokenQuantity)),u=a.sellingTokenQuantity;if("0"===u)throw W("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 V("Bundle backend client not configured. LaunchToken requires bundleHttp client.","bundleHttp");gh(e);const t=e.preBuyQuantity||"0",n=De(t);if(0===n&&"0"!==t)throw te("preBuyQuantity",t,"Pre-buy quantity");if(n<0)throw te("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 j("Image upload failed: No URL returned");i=t}else"string"==typeof e.tokenImage&&(i=e.tokenImage);const o=`galaswap - operation - ${s.v4()}-${Date.now()}-${this.http.getAddress()}`,a={tokenName:e.tokenName.trim(),tokenSymbol:ss(e.tokenSymbol),tokenDescription:e.tokenDescription.trim(),tokenImage:i.trim(),preBuyQuantity:t.toString(),tokenCategory:e.tokenCategory||"Unit",tokenCollection:e.tokenCollection||"Token",uniqueKey:o},c=Is(e.websiteUrl);null!==c&&(a.websiteUrl=c);const u=Is(e.telegramUrl);null!==u&&(a.telegramUrl=u);const l=Is(e.twitterUrl);null!==l&&(a.twitterUrl=l);const h=Is(e.instagramUrl);null!==h&&(a.instagramUrl=h);const d=Is(e.facebookUrl);null!==d&&(a.facebookUrl=d);const f=Is(e.redditUrl);null!==f&&(a.redditUrl=f);const g=Is(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 bh(a),m=await this.http.signWithGalaChain("CreateSale",p,r.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(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 j(I.message||"Token launch failed");const C=yr(I);if(!C)throw j("Token launch failed - no transaction ID returned");return C}async fetchTokenDistribution(e){if(!e)throw W("tokenName","Token name");qo(e);const t=await this.http.get(`/holders/${e}`);if(!0===t.error||200!==t.status)throw j(t.message||"Failed to fetch token distribution",t.status);const n=yr(t);if(!n)throw j("Failed to fetch token distribution - no data returned",t.status);if(!Array.isArray(n))throw j("Invalid API response: expected array of holders",t.status);for(const e of n){if(!e.owner||"string"!=typeof e.owner)throw j("Invalid holder data: missing or invalid owner field",t.status);if(!e.quantity||"string"!=typeof e.quantity)throw j("Invalid holder data: missing or invalid quantity field",t.status);const n=De(e.quantity,NaN);if(isNaN(n)||!isFinite(n))throw j(`Invalid holder quantity: "${e.quantity}"`,t.status)}const r=n.reduce((e,t)=>e.plus(t.quantity),bo(0));return{holders:n.map(e=>{const t=Uo(bo(e.quantity),r,bo(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");qo(e);const t=await this.http.get("/launchpad/get-badge/",{tokenName:e});if(t.error)throw j(t.message||"Failed to fetch token badges");const n=yr(t);if(!n)throw j("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(!Ks(e))throw H("data","valid pre-mint calculation data");if(!this.galaChainHttp)throw V("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(!kh(n))throw j("Malformed response data from GalaChain gateway");try{N(n,"Pre-mint calculation")}catch(e){throw j(T(e),500)}const{calculatedQuantity:r,extraFees:i}=n.Data;return{amount:r,reverseBondingCurveFee:i.reverseBondingCurve,transactionFee:i.transactionFees,gasFee:"1"}}catch(e){if(A(e)&&e instanceof R)throw e;throw j(T(e),500)}}async fetchPoolDetailsForCalculation(e){const t=await this.tokenResolver.resolveTokenToVault(e);if(!t)throw new P(Er(e),"tokenName","VAULT_NOT_FOUND");if(!this.galaChainHttp)throw V("GalaChain HTTP client not configured");const n=await this.galaChainHttp.post("/api/asset/launchpad-contract/FetchSaleDetails",{vaultAddress:t});if(1!==n.Status)throw j(`Failed to fetch pool details: Status ${n.Status}`,n.Status);const r=n.Data,i=ko(bo(r.maxSupply).minus(r.sellingTokenQuantity)),o=r.sellingTokenQuantity,s=r.maxSupply;let a=.5,c=0;r.reverseBondingCurveConfiguration?(a=$e(r.reverseBondingCurveConfiguration.maxFeePortion,.5),c=$e(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){qo(e);const t=await this.tokenResolver.resolveTokenToVault(e);if(!t)throw new P(Er(e),"tokenName","VAULT_NOT_FOUND");if(!this.galaChainHttp)throw V("GalaChain HTTP client not configured");const n=await this.galaChainHttp.post("/api/asset/launchpad-contract/FetchSaleDetails",{vaultAddress:t});if(1!==n.Status)throw j(`Failed to fetch pool details: Status ${n.Status}`,n.Status);const r=n.Data,i=ko(bo(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 qo(e)}validatePagination(e){return et(e.page,e.limit)}async fetchTokenPrice(e){if(!this.dexApiHttp)throw V("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 j(`Failed to fetch token prices: ${T(e)}`,void 0,A(e)?e:void 0)}}warmCacheFromPoolData(e,t){this.metadataCache.warmFromPoolData(e,t)}getCacheStats(){return this.metadataCache.getStats()}clearCache(e){this.metadataCache.clear(e)}}class Eh{constructor(e){if(this.lastTimestamp=0,this.pendingPromise=Promise.resolve(),this.chainLength=0,this.maxChainLength=1e3,e<=0)throw Y("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(A(e)?e:new Error(T(e)))}}),this.chainLength++,this.chainLength>=this.maxChainLength){this.chainLength=0;const e=this.pendingPromise;this.pendingPromise=e.then(()=>Promise.resolve())}return r}}function Ih(e,t){let n;try{n=Fe(e,"amount")}catch(t){throw te("amount",`${e} (${T(t)})`)}if(!n.isFinite())throw te("amount",e);const r=n.multipliedBy(bo(10).pow(t));if(!r.isInteger())throw te("amount",`${e} (cannot be represented with ${t} decimals)`);return BigInt(r.toFixed(0))}function Ch(e,t){return bo(e.toString()).dividedBy(bo(10).pow(t)).toFixed(t).replace(/\.?0+$/,"")}const Nh={maxRetries:3,initialDelayMs:1e3,maxDelayMs:3e4,backoffMultiplier:2,jitterFactor:.1},Bh=new Set([408,429,500,502,503,504]),xh=[/ECONNRESET/i,/ECONNREFUSED/i,/ETIMEDOUT/i,/ENOTFOUND/i,/EAI_AGAIN/i,/socket hang up/i,/network/i,/timeout/i,/aborted/i];function _h(e){if(e&&"object"==typeof e){const t=e;if("number"==typeof t.status)return Bh.has(t.status);if("number"==typeof t.statusCode)return Bh.has(t.statusCode);const n=I(e);if("string"==typeof n&&("ECONNRESET"===n||"ECONNREFUSED"===n||"ETIMEDOUT"===n||"ENOTFOUND"===n||"EAI_AGAIN"===n))return!0}const t=T(e);return xh.some(e=>e.test(t))}function Ph(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 Rh(e){return new Promise(t=>setTimeout(t,e))}function Dh(e){let t;if("string"==typeof e)t=Vs(e);else{if(!Js(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:Gs(t)}}function Lh(e){const t={};for(const[n,r]of Object.entries(e))void 0!==r&&(r&&"object"==typeof r&&!Array.isArray(r)?t[n]=Lh(r):t[n]=r);return t}function Oh(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 Uh(e){const t="string"==typeof e.timestamp?Ue(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 Mh,Fh={},$h={};function qh(){if(Mh)return $h;Mh=1,$h.byteLength=function(e){var t=o(e),n=t[0],r=t[1];return 3*(n+r)/4-r},$h.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},$h.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,$h}var Kh,Gh,zh={};function Wh(){return Kh||(Kh=1,zh.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)},zh.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}),zh}var Hh=(Gh||(Gh=1,function(e){const t=qh(),n=Wh(),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 N(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 C(this,t,n);case"base64":return A(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return B(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 C(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 N(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 B(e,t,n){const r=e.slice(t,n);let i="";for(let e=0;e<r.length-1;e+=2)i+=String.fromCharCode(r[e]+256*r[e+1]);return i}function x(e,t,n){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>n)throw new RangeError("Trying to access beyond buffer length")}function _(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||x(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||x(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||x(e,1,this.length),this[e]},s.prototype.readUint16LE=s.prototype.readUInt16LE=function(e,t){return e>>>=0,t||x(e,2,this.length),this[e]|this[e+1]<<8},s.prototype.readUint16BE=s.prototype.readUInt16BE=function(e,t){return e>>>=0,t||x(e,2,this.length),this[e]<<8|this[e+1]},s.prototype.readUint32LE=s.prototype.readUInt32LE=function(e,t){return e>>>=0,t||x(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},s.prototype.readUint32BE=s.prototype.readUInt32BE=function(e,t){return e>>>=0,t||x(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},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||x(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||x(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||x(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},s.prototype.readInt16LE=function(e,t){e>>>=0,t||x(e,2,this.length);const n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},s.prototype.readInt16BE=function(e,t){e>>>=0,t||x(e,2,this.length);const n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},s.prototype.readInt32LE=function(e,t){return e>>>=0,t||x(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},s.prototype.readInt32BE=function(e,t){return e>>>=0,t||x(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},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||x(e,4,this.length),n.read(this,e,!0,23,4)},s.prototype.readFloatBE=function(e,t){return e>>>=0,t||x(e,4,this.length),n.read(this,e,!1,23,4)},s.prototype.readDoubleLE=function(e,t){return e>>>=0,t||x(e,8,this.length),n.read(this,e,!0,52,8)},s.prototype.readDoubleBE=function(e,t){return e>>>=0,t||x(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")}}(Fh)),Fh);const jh="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0;function Vh(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function Xh(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function Qh(e,...t){if(!Vh(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 Jh(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.createHasher");Xh(e.outputLen),Xh(e.blockLen)}function Yh(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 Zh(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function ed(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function td(e,t){return e<<32-t|e>>>t}const nd=(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)(),rd=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function id(e){if(Qh(e),nd)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=rd[e[n]];return t}const od=48,sd=57,ad=65,cd=70,ud=97,ld=102;function hd(e){return e>=od&&e<=sd?e-od:e>=ad&&e<=cd?e-(ad-10):e>=ud&&e<=ld?e-(ud-10):void 0}function dd(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);if(nd)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=hd(e.charCodeAt(i)),o=hd(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 fd(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)),Qh(e),e}function gd(...e){let t=0;for(let n=0;n<e.length;n++){const r=e[n];Qh(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 pd{}function md(e){const t=t=>e().update(fd(t)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function yd(e=32){if(jh&&"function"==typeof jh.getRandomValues)return jh.getRandomValues(new Uint8Array(e));if(jh&&"function"==typeof jh.randomBytes)return Uint8Array.from(jh.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}function wd(e,t,n){return e&t^~e&n}function bd(e,t,n){return e&t^e&n^t&n}class kd extends pd{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=ed(this.buffer)}update(e){Yh(this),Qh(e=fd(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=ed(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){Yh(this),function(e,t){Qh(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,Zh(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=ed(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 vd=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Sd=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Ad=BigInt(2**32-1),Td=BigInt(32);function Ed(e,t=!1){return t?{h:Number(e&Ad),l:Number(e>>Td&Ad)}:{h:0|Number(e>>Td&Ad),l:0|Number(e&Ad)}}const Id=(e,t,n)=>e>>>n,Cd=(e,t,n)=>e<<32-n|t>>>n,Nd=(e,t,n)=>e>>>n|t<<32-n,Bd=(e,t,n)=>e<<32-n|t>>>n,xd=(e,t,n)=>e<<64-n|t>>>n-32,_d=(e,t,n)=>e>>>n-32|t<<64-n;function Pd(e,t,n,r){const i=(t>>>0)+(r>>>0);return{h:e+n+(i/2**32|0)|0,l:0|i}}const Rd=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),Dd=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,Ld=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),Od=(e,t,n,r,i)=>t+n+r+i+(e/2**32|0)|0,Ud=(e,t,n,r,i)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(i>>>0),Md=(e,t,n,r,i,o)=>t+n+r+i+o+(e/2**32|0)|0,Fd=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]),$d=new Uint32Array(64);class qd extends kd{constructor(e=32){super(64,e,8,!1),this.A=0|vd[0],this.B=0|vd[1],this.C=0|vd[2],this.D=0|vd[3],this.E=0|vd[4],this.F=0|vd[5],this.G=0|vd[6],this.H=0|vd[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)$d[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){const t=$d[e-15],n=$d[e-2],r=td(t,7)^td(t,18)^t>>>3,i=td(n,17)^td(n,19)^n>>>10;$d[e]=i+$d[e-7]+r+$d[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+(td(s,6)^td(s,11)^td(s,25))+wd(s,a,c)+Fd[e]+$d[e]|0,l=(td(n,2)^td(n,13)^td(n,22))+bd(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(){Zh($d)}destroy(){this.set(0,0,0,0,0,0,0,0),Zh(this.buffer)}}const Kd=(()=>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}=Ed(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))))(),Gd=(()=>Kd[0])(),zd=(()=>Kd[1])(),Wd=new Uint32Array(80),Hd=new Uint32Array(80);class jd extends kd{constructor(e=64){super(128,e,16,!1),this.Ah=0|Sd[0],this.Al=0|Sd[1],this.Bh=0|Sd[2],this.Bl=0|Sd[3],this.Ch=0|Sd[4],this.Cl=0|Sd[5],this.Dh=0|Sd[6],this.Dl=0|Sd[7],this.Eh=0|Sd[8],this.El=0|Sd[9],this.Fh=0|Sd[10],this.Fl=0|Sd[11],this.Gh=0|Sd[12],this.Gl=0|Sd[13],this.Hh=0|Sd[14],this.Hl=0|Sd[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)Wd[n]=e.getUint32(t),Hd[n]=e.getUint32(t+=4);for(let e=16;e<80;e++){const t=0|Wd[e-15],n=0|Hd[e-15],r=Nd(t,n,1)^Nd(t,n,8)^Id(t,0,7),i=Bd(t,n,1)^Bd(t,n,8)^Cd(t,n,7),o=0|Wd[e-2],s=0|Hd[e-2],a=Nd(o,s,19)^xd(o,s,61)^Id(o,0,6),c=Bd(o,s,19)^_d(o,s,61)^Cd(o,s,6),u=Ld(i,c,Hd[e-7],Hd[e-16]),l=Od(u,r,a,Wd[e-7],Wd[e-16]);Wd[e]=0|l,Hd[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=Nd(l,h,14)^Nd(l,h,18)^xd(l,h,41),w=Bd(l,h,14)^Bd(l,h,18)^_d(l,h,41),b=l&d^~l&g,k=Ud(y,w,h&f^~h&p,zd[e],Hd[e]),v=Md(k,m,t,b,Gd[e],Wd[e]),S=0|k,A=Nd(n,r,28)^xd(n,r,34)^xd(n,r,39),T=Bd(n,r,28)^_d(n,r,34)^_d(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}=Pd(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 C=Rd(S,T,I);n=Dd(C,v,A,E),r=0|C}({h:n,l:r}=Pd(0|this.Ah,0|this.Al,0|n,0|r)),({h:i,l:o}=Pd(0|this.Bh,0|this.Bl,0|i,0|o)),({h:s,l:a}=Pd(0|this.Ch,0|this.Cl,0|s,0|a)),({h:c,l:u}=Pd(0|this.Dh,0|this.Dl,0|c,0|u)),({h:l,l:h}=Pd(0|this.Eh,0|this.El,0|l,0|h)),({h:d,l:f}=Pd(0|this.Fh,0|this.Fl,0|d,0|f)),({h:g,l:p}=Pd(0|this.Gh,0|this.Gl,0|g,0|p)),({h:m,l:y}=Pd(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(){Zh(Wd,Hd)}destroy(){Zh(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const Vd=md(()=>new qd),Xd=md(()=>new jd),Qd=BigInt(0),Jd=BigInt(1);function Yd(e,t=""){if("boolean"!=typeof e){throw new Error((t&&`"${t}"`)+"expected boolean, got type="+typeof e)}return e}function Zd(e,t,n=""){const r=Vh(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 ef(e){const t=e.toString(16);return 1&t.length?"0"+t:t}function tf(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);return""===e?Qd:BigInt("0x"+e)}function nf(e){return tf(id(e))}function rf(e){return Qh(e),tf(id(Uint8Array.from(e).reverse()))}function of(e,t){return dd(e.toString(16).padStart(2*t,"0"))}function sf(e,t){return of(e,t).reverse()}function af(e,t,n){let r;if("string"==typeof t)try{r=dd(t)}catch(t){throw new Error(e+" must be hex string or Uint8Array, cause: "+t)}else{if(!Vh(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 cf(e){return Uint8Array.from(e)}const uf=e=>"bigint"==typeof e&&Qd<=e;function lf(e,t,n,r){if(!function(e,t,n){return uf(e)&&uf(t)&&uf(n)&&t<=e&&e<n}(t,n,r))throw new Error("expected valid "+e+": "+n+" <= n < "+r+", got "+t)}function hf(e){let t;for(t=0;e>Qd;e>>=Jd,t+=1);return t}const df=e=>(Jd<<BigInt(e))-Jd;function ff(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 gf(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 pf=BigInt(0),mf=BigInt(1),yf=BigInt(2),wf=BigInt(3),bf=BigInt(4),kf=BigInt(5),vf=BigInt(7),Sf=BigInt(8),Af=BigInt(9),Tf=BigInt(16);function Ef(e,t){const n=e%t;return n>=pf?n:t+n}function If(e,t,n){let r=e;for(;t-- >pf;)r*=r,r%=n;return r}function Cf(e,t){if(e===pf)throw new Error("invert: expected non-zero number");if(t<=pf)throw new Error("invert: expected positive modulus, got "+t);let n=Ef(e,t),r=t,i=pf,o=mf;for(;n!==pf;){const e=r%n,t=i-o*(r/n);r=n,n=e,i=o,o=t}if(r!==mf)throw new Error("invert: does not exist");return Ef(i,t)}function Nf(e,t,n){if(!e.eql(e.sqr(t),n))throw new Error("Cannot find square root")}function Bf(e,t){const n=(e.ORDER+mf)/bf,r=e.pow(t,n);return Nf(e,r,t),r}function xf(e,t){const n=(e.ORDER-kf)/Sf,r=e.mul(t,yf),i=e.pow(r,n),o=e.mul(t,i),s=e.mul(e.mul(o,yf),i),a=e.mul(o,e.sub(s,e.ONE));return Nf(e,a,t),a}function _f(e){if(e<wf)throw new Error("sqrt is not defined for small field");let t=e-mf,n=0;for(;t%yf===pf;)t/=yf,n++;let r=yf;const i=Uf(e);for(;1===Lf(i,r);)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(1===n)return Bf;let o=i.pow(r,t);const s=(t+mf)/yf;return function(e,r){if(e.is0(r))return r;if(1!==Lf(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=mf<<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 Pf(e){return e%bf===wf?Bf:e%Sf===kf?xf:e%Tf===Af?function(e){const t=Uf(e),n=_f(e),r=n(t,t.neg(t.ONE)),i=n(t,r),o=n(t,t.neg(r)),s=(e+vf)/Tf;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 Nf(e,f,t),f}}(e):_f(e)}const Rf=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Df(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 Lf(e,t){const n=(e.ORDER-mf)/yf,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 Of(e,t){void 0!==t&&Xh(t);const n=void 0!==t?t:e.toString(2).length;return{nBitLength:n,nByteLength:Math.ceil(n/8)}}function Uf(e,t,n=!1,r={}){if(e<=pf)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}=Of(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:df(c),ZERO:pf,ONE:mf,allowedLengths:s,create:t=>Ef(t,e),isValid:t=>{if("bigint"!=typeof t)throw new Error("invalid field element: expected bigint, got "+typeof t);return pf<=t&&t<e},is0:e=>e===pf,isValidNot0:e=>!h.is0(e)&&h.isValid(e),isOdd:e=>(e&mf)===mf,neg:t=>Ef(-t,e),eql:(e,t)=>e===t,sqr:t=>Ef(t*t,e),add:(t,n)=>Ef(t+n,e),sub:(t,n)=>Ef(t-n,e),mul:(t,n)=>Ef(t*n,e),pow:(e,t)=>function(e,t,n){if(n<pf)throw new Error("invalid exponent, negatives unsupported");if(n===pf)return e.ONE;if(n===mf)return t;let r=e.ONE,i=t;for(;n>pf;)n&mf&&(r=e.mul(r,i)),i=e.sqr(i),n>>=mf;return r}(h,e,t),div:(t,n)=>Ef(t*Cf(n,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>Cf(t,e),sqrt:o||(t=>(l||(l=Pf(e)),l(h,t))),toBytes:e=>n?sf(e,u):of(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?rf(t):nf(t);if(a&&(i=Ef(i,e)),!r&&!h.isValid(i))throw new Error("invalid field element: outside of range 0..ORDER");return i},invertBatch:e=>Df(h,e),cmov:(e,t,n)=>n?t:e});return Object.freeze(h)}function Mf(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 Ff(e){const t=Mf(e);return t+Math.ceil(t/2)}const $f=BigInt(0),qf=BigInt(1);function Kf(e,t){const n=t.negate();return e?n:t}function Gf(e,t){const n=Df(e.Fp,t.map(e=>e.Z));return t.map((t,r)=>e.fromAffine(t.toAffine(n[r])))}function zf(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function Wf(e,t){zf(e,t);const n=2**e;return{windows:Math.ceil(t/e)+1,windowSize:2**(e-1),mask:df(e),maxNumber:n,shiftBy:BigInt(e)}}function Hf(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+=qf);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 jf=new WeakMap,Vf=new WeakMap;function Xf(e){return Vf.get(e)||1}function Qf(e){if(e!==$f)throw new Error("invalid wNAF")}class Jf{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>$f;)t&qf&&(n=n.add(r)),r=r.double(),t>>=qf;return n}precomputeWindow(e,t){const{windows:n,windowSize:r}=Wf(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=Wf(e,this.bits);for(let e=0;e<o.windows;e++){const{nextN:s,offset:a,isZero:c,isNeg:u,isNegF:l,offsetF:h}=Hf(n,e,o);n=s,c?i=i.add(Kf(l,t[h])):r=r.add(Kf(u,t[a]))}return Qf(n),{p:r,f:i}}wNAFUnsafe(e,t,n,r=this.ZERO){const i=Wf(e,this.bits);for(let e=0;e<i.windows&&n!==$f;e++){const{nextN:o,offset:s,isZero:a,isNeg:c}=Hf(n,e,i);if(n=o,!a){const e=t[s];r=r.add(c?e.negate():e)}}return Qf(n),r}getPrecomputes(e,t,n){let r=jf.get(t);return r||(r=this.precomputeWindow(t,e),1!==e&&("function"==typeof n&&(r=n(r)),jf.set(t,r))),r}cached(e,t,n){const r=Xf(e);return this.wNAF(r,this.getPrecomputes(r,e,n),t)}unsafe(e,t,n,r){const i=Xf(e);return 1===i?this._unsafeLadder(e,t,r):this.wNAFUnsafe(i,this.getPrecomputes(i,e,n),t,r)}createCache(e,t){zf(t,this.bits),Vf.set(e,t),jf.delete(e)}hasCache(e){return 1!==Xf(e)}}function Yf(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=hf(BigInt(i));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const u=df(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 Zf(e,t,n){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return function(e){ff(e,Rf.reduce((e,t)=>(e[t]="function",e),{ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"}))}(t),t}return Uf(e,{isLE:n})}function eg(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>$f))throw new Error(`CURVE.${e} must be positive bigint`)}const i=Zf(t.p,n.Fp,r),o=Zf(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 tg=BigInt(0),ng=BigInt(1),rg=BigInt(2),ig=BigInt(8);function og(e,t,n={}){if("function"!=typeof t)throw new Error('"hash" function param is required');ff(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||yd,c=n.adjustScalarBytes||(e=>e),u=n.domain||((e,t,n)=>{if(Yd(n,"phflag"),t.length||n)throw new Error("Contexts/pre-hash are not supported");return e});function l(e){return s.create(rf(e))}function h(e){const{head:n,prefix:r,scalar:o}=function(e){const n=m.secretKey;e=af("private key",e,n);const r=af("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=gd(...n);return l(t(u(i,af("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 Zd(e,m.seed,"seed")}const w={getExtendedPublicKey:h,randomSecretKey:y,isValidSecretKey:function(e){return Vh(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(ng+n,ng-n):o.div(n-ng,n+ng);return o.toBytes(s)},toMontgomerySecret(e){const n=m.secretKey;Zd(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=af("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 Zd(gd(l,s.toBytes(g)),m.signature,"result")},verify:function(t,n,o,s=g){const{context:a,zip215:c}=s,u=m.signature;t=af("signature",t,u),n=af("message",n),o=af("publicKey",o,m.publicKey),void 0!==c&&Yd(c,"zip215"),r&&(n=r(n));const l=u/2,h=t.subarray(0,l),d=rf(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 sg(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:Uf(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=eg("edwards",e,t,t.FpFnLE),{Fp:r,Fn:i}=n;let o=n.CURVE;const{h:s}=o;ff(t,{},{uvRatio:"function"});const a=rg<<BigInt(8*i.BYTES)-ng,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:tg}}});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 lf("coordinate "+e,t,n?ng:tg,a),t}function h(e){if(!(e instanceof g))throw new Error("ExtendedPoint expected")}const d=gf((e,t)=>{const{X:n,Y:i,Z:o}=e,s=e.is0();null==t&&(t=s?ig:r.inv(o));const a=c(n*t),u=c(i*t),l=r.mul(o,t);if(s)return{x:tg,y:ng};if(l!==ng)throw new Error("invZ was invalid");return{x:a,y:u}}),f=gf(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,ng,c(t*n))}static fromBytes(e,t=!1){const n=r.BYTES,{a:i,d:s}=o;e=cf(Zd(e,n,"point")),Yd(t,"zip215");const l=cf(e),h=e[n-1];l[n-1]=-129&h;const d=rf(l),f=t?a:r.ORDER;lf("point.y",d,tg,f);const p=c(d*d),m=c(p-ng),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&ng)===ng,v=!!(128&h);if(!t&&b===tg&&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(af("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(rg),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(rg*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=>Gf(g,e));return Gf(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===tg?g.ZERO:this.is0()||e===ng?this:p.unsafe(this,e,e=>Gf(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===ng?this:this.multiplyUnsafe(s)}toBytes(){const{x:e,y:t}=this.toAffine(),n=r.toBytes(t);return n[n.length-1]|=e&ng?128:0,n}toHex(){return id(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 Gf(g,e)}static msm(e,t){return Yf(g,i,e,t)}_setWindowSize(e){this.precompute(e)}toRawBytes(){return this.toBytes()}}g.BASE=new g(o.Gx,o.Gy,ng,c(o.Gx*o.Gy)),g.ZERO=new g(tg,ng,ng,tg),g.Fp=r,g.Fn=i;const p=new Jf(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,og(o,r,i))}const ag=BigInt(1),cg=BigInt(2);BigInt(3);const ug=BigInt(5),lg=BigInt(8),hg=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),dg=(()=>({p:hg,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:lg,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")}))();function fg(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}const gg=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function pg(e,t){const n=hg,r=Ef(t*t*t,n),i=function(e){const t=BigInt(10),n=BigInt(20),r=BigInt(40),i=BigInt(80),o=hg,s=e*e%o*e%o,a=If(s,cg,o)*s%o,c=If(a,ag,o)*e%o,u=If(c,ug,o)*c%o,l=If(u,t,o)*u%o,h=If(l,n,o)*l%o,d=If(h,r,o)*h%o,f=If(d,i,o)*d%o,g=If(f,i,o)*d%o,p=If(g,t,o)*u%o;return{pow_p_5_8:If(p,cg,o)*e%o,b2:s}}(e*Ef(r*r*t,n)).pow_p_5_8;let o=Ef(e*r*i,n);const s=Ef(t*o*o,n),a=o,c=Ef(o*gg,n),u=s===e,l=s===Ef(-e,n),h=s===Ef(-e*gg,n);return u&&(o=a),(l||h)&&(o=c),(Ef(o,n)&mf)===mf&&(o=Ef(-o,n)),{isValid:u||l,value:o}}const mg=(()=>Uf(dg.p,{isLE:!0}))(),yg=(()=>({...dg,Fp:mg,hash:Xd,adjustScalarBytes:fg,uvRatio:pg}))(),wg=(()=>sg(yg))();var bg,kg={exports:{}},vg=$c(Object.freeze({__proto__:null,default:{}})),Sg=kg.exports;function Ag(){return bg||(bg=1,function(e){!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:vg.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];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)};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.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,C=E>>>13,N=0|s[6],B=8191&N,x=N>>>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(C,q)|0,o=Math.imul(C,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(B,q),i=(i=Math.imul(B,K))+Math.imul(x,q)|0,o=Math.imul(x,K),r=r+Math.imul(I,z)|0,i=(i=i+Math.imul(I,W)|0)+Math.imul(C,z)|0,o=o+Math.imul(C,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(B,z)|0,i=(i=i+Math.imul(B,W)|0)+Math.imul(x,z)|0,o=o+Math.imul(x,W)|0,r=r+Math.imul(I,j)|0,i=(i=i+Math.imul(I,V)|0)+Math.imul(C,j)|0,o=o+Math.imul(C,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(B,j)|0,i=(i=i+Math.imul(B,V)|0)+Math.imul(x,j)|0,o=o+Math.imul(x,V)|0,r=r+Math.imul(I,Q)|0,i=(i=i+Math.imul(I,J)|0)+Math.imul(C,Q)|0,o=o+Math.imul(C,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(B,Q)|0,i=(i=i+Math.imul(B,J)|0)+Math.imul(x,Q)|0,o=o+Math.imul(x,J)|0,r=r+Math.imul(I,Z)|0,i=(i=i+Math.imul(I,ee)|0)+Math.imul(C,Z)|0,o=o+Math.imul(C,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(B,Z)|0,i=(i=i+Math.imul(B,ee)|0)+Math.imul(x,Z)|0,o=o+Math.imul(x,ee)|0,r=r+Math.imul(I,ne)|0,i=(i=i+Math.imul(I,re)|0)+Math.imul(C,ne)|0,o=o+Math.imul(C,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(B,ne)|0,i=(i=i+Math.imul(B,re)|0)+Math.imul(x,ne)|0,o=o+Math.imul(x,re)|0,r=r+Math.imul(I,oe)|0,i=(i=i+Math.imul(I,se)|0)+Math.imul(C,oe)|0,o=o+Math.imul(C,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 Ce=(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)+(Ce>>>26)|0,Ce&=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(B,oe)|0,i=(i=i+Math.imul(B,se)|0)+Math.imul(x,oe)|0,o=o+Math.imul(x,se)|0,r=r+Math.imul(I,ce)|0,i=(i=i+Math.imul(I,ue)|0)+Math.imul(C,ce)|0,o=o+Math.imul(C,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 Ne=(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)+(Ne>>>26)|0,Ne&=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(B,ce)|0,i=(i=i+Math.imul(B,ue)|0)+Math.imul(x,ce)|0,o=o+Math.imul(x,ue)|0,r=r+Math.imul(I,he)|0,i=(i=i+Math.imul(I,de)|0)+Math.imul(C,he)|0,o=o+Math.imul(C,de)|0;var Be=(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)+(Be>>>26)|0,Be&=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(B,he)|0,i=(i=i+Math.imul(B,de)|0)+Math.imul(x,he)|0,o=o+Math.imul(x,de)|0;var xe=(u+(r=r+Math.imul(I,ge)|0)|0)+((8191&(i=(i=i+Math.imul(I,pe)|0)+Math.imul(C,ge)|0))<<13)|0;u=((o=o+Math.imul(C,pe)|0)+(i>>>13)|0)+(xe>>>26)|0,xe&=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(B,ge)|0)|0)+((8191&(i=(i=i+Math.imul(B,pe)|0)+Math.imul(x,ge)|0))<<13)|0;u=((o=o+Math.imul(x,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]=Ce,c[12]=Ne,c[13]=Be,c[14]=xe,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)}}(e,Sg)}(kg)),kg.exports}var Tg,Eg,Ig,Cg,Ng,Bg,xg=Fc(Ag()),_g={exports:{}},Pg={};function Rg(){return Tg||(Tg=1,function(e){var t=qh(),n=Wh(),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 N(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 C(this,t,n);case"base64":return A(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return B(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 C(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 N(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 B(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 x(e,t,n){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>n)throw new RangeError("Trying to access beyond buffer length")}function _(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||x(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||x(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||x(e,1,this.length),this[e]},s.prototype.readUint16LE=s.prototype.readUInt16LE=function(e,t){return e>>>=0,t||x(e,2,this.length),this[e]|this[e+1]<<8},s.prototype.readUint16BE=s.prototype.readUInt16BE=function(e,t){return e>>>=0,t||x(e,2,this.length),this[e]<<8|this[e+1]},s.prototype.readUint32LE=s.prototype.readUInt32LE=function(e,t){return e>>>=0,t||x(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},s.prototype.readUint32BE=s.prototype.readUInt32BE=function(e,t){return e>>>=0,t||x(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},s.prototype.readIntLE=function(e,t,n){e>>>=0,t>>>=0,n||x(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||x(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||x(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},s.prototype.readInt16LE=function(e,t){e>>>=0,t||x(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||x(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||x(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||x(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||x(e,4,this.length),n.read(this,e,!0,23,4)},s.prototype.readFloatBE=function(e,t){return e>>>=0,t||x(e,4,this.length),n.read(this,e,!1,23,4)},s.prototype.readDoubleLE=function(e,t){return e>>>=0,t||x(e,8,this.length),n.read(this,e,!0,52,8)},s.prototype.readDoubleBE=function(e,t){return e>>>=0,t||x(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}()}(Pg)),Pg}function Dg(){return Eg||(Eg=1,function(e,t){var n=Rg(),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)}}(_g,_g.exports)),_g.exports}var Lg=function(){if(Bg)return Ng;Bg=1;var e=function(){if(Cg)return Ig;Cg=1;var e=Dg().Buffer;return Ig=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")}}},Ig}();return Ng=e("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")}(),Og=Fc(Lg);const Ug=Vd;var Mg,Fg,$g,qg,Kg={};function Gg(){if(qg)return $g;qg=1;var e=function(){if(Fg)return Mg;Fg=1;var e=Dg().Buffer;return Mg=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")}}},Mg}();return $g=e("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")}function zg(e,t,n){return t<=e&&e<=n}function Wg(e){if(void 0===e)return{};if(e===Object(e))return e;throw TypeError("Could not convert argument to dictionary")}function Hg(e){this.tokens=[].slice.call(e)}Hg.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 jg=-1;function Vg(e,t){if(e)throw TypeError("Decoder error");return t||65533}var Xg="utf-8";function Qg(e,t){if(!(this instanceof Qg))return new Qg(e,t);if((e=void 0!==e?String(e).toLowerCase():Xg)!==Xg)throw new Error("Encoding not supported. Only utf-8 is supported");t=Wg(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 Jg(e,t){if(!(this instanceof Jg))return new Jg(e,t);if((e=void 0!==e?String(e).toLowerCase():Xg)!==Xg)throw new Error("Encoding not supported. Only utf-8 is supported");t=Wg(t),this._streaming=!1,this._encoder=null,this._options={fatal:Boolean(t.fatal)},Object.defineProperty(this,"encoding",{value:"utf-8"})}function Yg(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,Vg(t);if(-1===a)return jg;if(0===i){if(zg(a,0,127))return a;if(zg(a,194,223))i=1,n=a-192;else if(zg(a,224,239))224===a&&(o=160),237===a&&(s=159),i=2,n=a-224;else{if(!zg(a,240,244))return Vg(t);240===a&&(o=144),244===a&&(s=143),i=3,n=a-240}return n<<=6*i,null}if(!zg(a,o,s))return n=i=r=0,o=128,s=191,e.prepend(a),Vg(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 Zg(e){e.fatal,this.handler=function(e,t){if(-1===t)return jg;if(zg(t,0,127))return t;var n,r;zg(t,128,2047)?(n=1,r=192):zg(t,2048,65535)?(n=2,r=224):zg(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}}Qg.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=Wg(t),this._streaming||(this._decoder=new Yg({fatal:this._fatal}),this._BOMseen=!1),this._streaming=Boolean(t.stream);for(var r,i=new Hg(n),o=[];!i.endOfStream()&&(r=this._decoder.handler(i,i.read()))!==jg;)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()))===jg)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)}},Jg.prototype={encode:function(e,t){e=e?String(e):"",t=Wg(t),this._streaming||(this._encoder=new Zg(this._options)),this._streaming=Boolean(t.stream);for(var n,r=[],i=new Hg(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()))!==jg;)Array.isArray(n)?r.push.apply(r,n):r.push(n);if(!this._streaming){for(;(n=this._encoder.handler(i,i.read()))!==jg;)Array.isArray(n)?r.push.apply(r,n):r.push(n);this._encoder=null}return new Uint8Array(r)}};var ep,tp=$c(Object.freeze({__proto__:null,TextDecoder:Qg,TextEncoder:Jg}));var np,rp,ip=function(){if(ep)return Kg;ep=1;var e=Kg&&Kg.__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=Kg&&Kg.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=Kg&&Kg.__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=Kg&&Kg.__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=Kg&&Kg.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Kg,"__esModule",{value:!0}),Kg.deserializeUnchecked=Kg.deserialize=Kg.serialize=Kg.BinaryReader=Kg.BinaryWriter=Kg.BorshError=Kg.baseDecode=Kg.baseEncode=void 0;const o=i(Ag()),s=i(Gg()),a=r(tp),c=new("function"!=typeof TextDecoder?a.TextDecoder:TextDecoder)("utf-8",{fatal:!0});Kg.baseEncode=function(e){return"string"==typeof e&&(e=Buffer.from(e,"utf8")),s.default.encode(Buffer.from(e))},Kg.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(".")}}Kg.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}}}Kg.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),Kg.BinaryReader=f,Kg.serialize=function(e,t,n=h){const r=new n;return m(e,t,r),r.toArray()},Kg.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},Kg.deserializeUnchecked=function(e,t,n,r=f){return w(e,t,new r(n))},Kg}(),op={},sp={};function ap(){return np||(np=1,function(e){const t=qh(),n=Wh(),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 N(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 C(this,t,n);case"base64":return A(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return B(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 C(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 N(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 B(e,t,n){const r=e.slice(t,n);let i="";for(let e=0;e<r.length-1;e+=2)i+=String.fromCharCode(r[e]+256*r[e+1]);return i}function x(e,t,n){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>n)throw new RangeError("Trying to access beyond buffer length")}function _(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||x(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||x(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||x(e,1,this.length),this[e]},s.prototype.readUint16LE=s.prototype.readUInt16LE=function(e,t){return e>>>=0,t||x(e,2,this.length),this[e]|this[e+1]<<8},s.prototype.readUint16BE=s.prototype.readUInt16BE=function(e,t){return e>>>=0,t||x(e,2,this.length),this[e]<<8|this[e+1]},s.prototype.readUint32LE=s.prototype.readUInt32LE=function(e,t){return e>>>=0,t||x(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},s.prototype.readUint32BE=s.prototype.readUInt32BE=function(e,t){return e>>>=0,t||x(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},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||x(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||x(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||x(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},s.prototype.readInt16LE=function(e,t){e>>>=0,t||x(e,2,this.length);const n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},s.prototype.readInt16BE=function(e,t){e>>>=0,t||x(e,2,this.length);const n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},s.prototype.readInt32LE=function(e,t){return e>>>=0,t||x(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},s.prototype.readInt32BE=function(e,t){return e>>>=0,t||x(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},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||x(e,4,this.length),n.read(this,e,!0,23,4)},s.prototype.readFloatBE=function(e,t){return e>>>=0,t||x(e,4,this.length),n.read(this,e,!1,23,4)},s.prototype.readDoubleLE=function(e,t){return e>>>=0,t||x(e,8,this.length),n.read(this,e,!0,52,8)},s.prototype.readDoubleBE=function(e,t){return e>>>=0,t||x(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")}}(sp)),sp}var cp=function(){if(rp)return op;rp=1,Object.defineProperty(op,"__esModule",{value:!0}),op.s16=op.s8=op.nu64be=op.u48be=op.u40be=op.u32be=op.u24be=op.u16be=op.nu64=op.u48=op.u40=op.u32=op.u24=op.u16=op.u8=op.offset=op.greedy=op.Constant=op.UTF8=op.CString=op.Blob=op.Boolean=op.BitField=op.BitStructure=op.VariantLayout=op.Union=op.UnionLayoutDiscriminator=op.UnionDiscriminator=op.Structure=op.Sequence=op.DoubleBE=op.Double=op.FloatBE=op.Float=op.NearInt64BE=op.NearInt64=op.NearUInt64BE=op.NearUInt64=op.IntBE=op.Int=op.UIntBE=op.UInt=op.OffsetLayout=op.GreedyCount=op.ExternalLayout=op.bindConstructorLayout=op.nameWithProperty=op.Layout=op.uint8ArrayToBuffer=op.checkUint8Array=void 0,op.constant=op.utf8=op.cstr=op.blob=op.unionLayoutDiscriminator=op.union=op.seq=op.bits=op.struct=op.f64be=op.f64=op.f32be=op.f32=op.ns64be=op.s48be=op.s40be=op.s32be=op.s24be=op.s16be=op.ns64=op.s48=op.s40=op.s32=op.s24=void 0;const e=ap();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)}op.checkUint8Array=t,op.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}op.Layout=r,op.nameWithProperty=i,op.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")}}op.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}}op.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)}}op.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}}op.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}}op.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}}op.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}}op.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}}op.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}}op.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}}op.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}}op.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}}op.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}}op.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}}op.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}}op.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}}op.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)}}}op.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")}}op.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)}}op.UnionLayoutDiscriminator=I;class C 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 N(this,e,t,n);return this.registry[e]=r,r}getVariant(e,t=0){let n;return n=e instanceof Uint8Array?this.discriminator.decode(e,t):e,this.registry[n]}}op.Union=C;class N extends r{constructor(e,t,n,i){if(!(e instanceof C))throw new TypeError("union must be a Union");if(!Number.isInteger(t)||0>t)throw new TypeError("variant must be a (non-negative) integer");if("string"==typeof n&&void 0===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 B(e){return 0>e&&(e+=4294967296),e}op.VariantLayout=N;class x 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=B(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}}op.BitStructure=x;class _{constructor(e,t,n){if(!(e instanceof x))throw new TypeError("container must be a BitStructure");if(!Number.isInteger(t)||0>=t)throw new TypeError("bits must be positive integer");const r=8*e.span,i=e.fields.reduce((e,t)=>e+t.bits,0);if(t+i>r)throw new Error("bits too long for span remainder ("+(r-i)+" of "+r+" remain)");this.container=e,this.bits=t,this.valueMask=(1<<t)-1,32===t&&(this.valueMask=4294967295),this.start=i,this.container.msb&&(this.start=r-i-t),this.wordMask=B(this.valueMask<<this.start),this.property=n}decode(e,t){return B(this.container._packedGetValue()&this.wordMask)>>>this.start}encode(e){if("number"!=typeof e||!Number.isInteger(e)||e!==B(e&this.valueMask))throw new TypeError(i("BitField.encode",this)+" value must be integer not exceeding "+this.valueMask);const t=this.container._packedGetValue(),n=B(e<<this.start);this.container._packedSetValue(B(t&~this.wordMask)|n)}}op.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)}}op.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}}op.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}}op.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}}op.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 op.Constant=O,op.greedy=(e,t)=>new s(e,t),op.offset=(e,t,n)=>new a(e,t,n),op.u8=e=>new c(1,e),op.u16=e=>new c(2,e),op.u24=e=>new c(3,e),op.u32=e=>new c(4,e),op.u40=e=>new c(5,e),op.u48=e=>new c(6,e),op.nu64=e=>new p(e),op.u16be=e=>new u(2,e),op.u24be=e=>new u(3,e),op.u32be=e=>new u(4,e),op.u40be=e=>new u(5,e),op.u48be=e=>new u(6,e),op.nu64be=e=>new m(e),op.s8=e=>new l(1,e),op.s16=e=>new l(2,e),op.s24=e=>new l(3,e),op.s32=e=>new l(4,e),op.s40=e=>new l(5,e),op.s48=e=>new l(6,e),op.ns64=e=>new y(e),op.s16be=e=>new h(2,e),op.s24be=e=>new h(3,e),op.s32be=e=>new h(4,e),op.s40be=e=>new h(5,e),op.s48be=e=>new h(6,e),op.ns64be=e=>new w(e),op.f32=e=>new b(e),op.f32be=e=>new k(e),op.f64=e=>new v(e),op.f64be=e=>new S(e),op.struct=(e,t,n)=>new T(e,t,n),op.bits=(e,t,n)=>new x(e,t,n),op.seq=(e,t,n)=>new A(e,t,n),op.union=(e,t,n)=>new C(e,t,n),op.unionLayoutDiscriminator=(e,t)=>new I(e,t),op.blob=(e,t)=>new R(e,t),op.cstr=e=>new D(e),op.utf8=(e,t)=>new L(e,t),op.constant=(e,t)=>new O(e,t),op}(),up=1,lp=2,hp=3,dp=4,fp=5,gp=6,pp=7,mp=8,yp=9,wp=10,bp=-32700,kp=-32603,vp=-32602,Sp=-32601,Ap=-32600,Tp=-32016,Ep=-32015,Ip=-32014,Cp=-32013,Np=-32012,Bp=-32011,xp=-32010,_p=-32009,Pp=-32008,Rp=-32007,Dp=-32006,Lp=-32005,Op=-32004,Up=-32003,Mp=-32002,Fp=-32001,$p=28e5,qp=2800001,Kp=2800002,Gp=2800003,zp=2800004,Wp=2800005,Hp=2800006,jp=2800007,Vp=2800008,Xp=2800009,Qp=2800010,Jp=2800011,Yp=323e4,Zp=32300001,em=3230002,tm=3230003,nm=3230004,rm=361e4,im=3610001,om=3610002,sm=3610003,am=3610004,cm=3610005,um=3610006,lm=3610007,hm=3611e3,dm=3704e3,fm=3704001,gm=3704002,pm=3704003,mm=3704004,ym=4128e3,wm=4128001,bm=4128002,km=4615e3,vm=4615001,Sm=4615002,Am=4615003,Tm=4615004,Em=4615005,Im=4615006,Cm=4615007,Nm=4615008,Bm=4615009,xm=4615010,_m=4615011,Pm=4615012,Rm=4615013,Dm=4615014,Lm=4615015,Om=4615016,Um=4615017,Mm=4615018,Fm=4615019,$m=4615020,qm=4615021,Km=4615022,Gm=4615023,zm=4615024,Wm=4615025,Hm=4615026,jm=4615027,Vm=4615028,Xm=4615029,Qm=4615030,Jm=4615031,Ym=4615032,Zm=4615033,ey=4615034,ty=4615035,ny=4615036,ry=4615037,iy=4615038,oy=4615039,sy=4615040,ay=4615041,cy=4615042,uy=4615043,ly=4615044,hy=4615045,dy=4615046,fy=4615047,gy=4615048,py=4615049,my=4615050,yy=4615051,wy=4615052,by=4615053,ky=4615054,vy=5508e3,Sy=5508001,Ay=5508002,Ty=5508003,Ey=5508004,Iy=5508005,Cy=5508006,Ny=5508007,By=5508008,xy=5508009,_y=5508010,Py=5508011,Ry=5663e3,Dy=5663001,Ly=5663002,Oy=5663003,Uy=5663004,My=5663005,Fy=5663006,$y=5663007,qy=5663008,Ky=5663009,Gy=5663010,zy=5663011,Wy=5663012,Hy=5663013,jy=5663014,Vy=5663015,Xy=5663016,Qy=5663017,Jy=5663018,Yy=5663019,Zy=5663020,ew=705e4,tw=7050001,nw=7050002,rw=7050003,iw=7050004,ow=7050005,sw=7050006,aw=7050007,cw=7050008,uw=7050009,lw=7050010,hw=7050011,dw=7050012,fw=7050013,gw=7050014,pw=7050015,mw=7050016,yw=7050017,ww=7050018,bw=7050019,kw=7050020,vw=7050021,Sw=7050022,Aw=7050023,Tw=7050024,Ew=7050025,Iw=7050026,Cw=7050027,Nw=7050028,Bw=7050029,xw=7050030,_w=7050031,Pw=7050032,Rw=7050033,Dw=7050034,Lw=7050035,Ow=7050036,Uw=8078e3,Mw=8078001,Fw=8078002,$w=8078003,qw=8078004,Kw=8078005,Gw=8078006,zw=8078007,Ww=8078008,Hw=8078009,jw=8078010,Vw=8078011,Xw=8078012,Qw=8078013,Jw=8078014,Yw=8078015,Zw=8078016,eb=8078017,tb=8078018,nb=8078019,rb=8078020,ib=8078021,ob=8078022,sb=81e5,ab=8100001,cb=8100002,ub=8100003,lb=819e4,hb=8190001,db=8190002,fb=8190003,gb=8190004,pb=99e5,mb=9900001,yb=9900002,wb=9900003,bb=9900004;function kb(e){if(Array.isArray(e)){return"%5B"+e.map(kb).join("%2C%20")+"%5D"}return"bigint"==typeof e?`${e}n`:encodeURIComponent(String(null!=e&&null===Object.getPrototypeOf(e)?{...e}:e))}function vb([e,t]){return`${e}=${kb(t)}`}var Sb={[Yp]:"Account not found at address: $address",[nm]:"Not all accounts were decoded. Encoded accounts found at addresses: $addresses.",[tm]:"Expected decoded account at address: $address",[em]:"Failed to decode account data at address: $address",[Zp]:"Accounts not found at addresses: $addresses",[Xp]:"Unable to find a viable program address bump seed.",[Kp]:"$putativeAddress is not a base58-encoded address.",[$p]:"Expected base58 encoded address to decode to a byte array of length 32. Actual length: $actualLength.",[Gp]:"The `CryptoKey` must be an `Ed25519` public key.",[Jp]:"$putativeOffCurveAddress is not a base58-encoded off-curve address.",[Vp]:"Invalid seeds; point must fall off the Ed25519 curve.",[zp]:"Expected given program derived address to have the following format: [Address, ProgramDerivedAddressBump].",[Hp]:"A maximum of $maxSeeds seeds, including the bump seed, may be supplied when creating an address. Received: $actual.",[jp]:"The seed at index $index with length $actual exceeds the maximum length of $maxSeedLength bytes.",[Wp]:"Expected program derived address bump to be in the range [0, 255], got: $bump.",[Qp]:"Program address cannot end with PDA marker.",[qp]:"Expected base58-encoded address string of length in the range [32, 44]. Actual length: $actualLength.",[dp]:"Expected base58-encoded blockash string of length in the range [32, 44]. Actual length: $actualLength.",[up]:"The network has progressed past the last block for which this transaction could have been committed.",[Uw]:"Codec [$codecDescription] cannot decode empty byte arrays.",[ob]:"Enum codec cannot use lexical values [$stringValues] as discriminators. Either remove all lexical values or set `useValuesAsDiscriminators` to `false`.",[rb]:"Sentinel [$hexSentinel] must not be present in encoded bytes [$hexEncodedBytes].",[Kw]:"Encoder and decoder must have the same fixed size, got [$encoderFixedSize] and [$decoderFixedSize].",[Gw]:"Encoder and decoder must have the same max size, got [$encoderMaxSize] and [$decoderMaxSize].",[qw]:"Encoder and decoder must either both be fixed-size or variable-size.",[Ww]:"Enum discriminator out of range. Expected a number in [$formattedValidDiscriminators], got $discriminator.",[Fw]:"Expected a fixed-size codec, got a variable-size one.",[Qw]:"Codec [$codecDescription] expected a positive byte length, got $bytesLength.",[$w]:"Expected a variable-size codec, got a fixed-size one.",[nb]:"Codec [$codecDescription] expected zero-value [$hexZeroValue] to have the same size as the provided fixed-size item [$expectedSize bytes].",[Mw]:"Codec [$codecDescription] expected $expected bytes, got $bytesLength.",[tb]:"Expected byte array constant [$hexConstant] to be present in data [$hexData] at offset [$offset].",[Hw]:"Invalid discriminated union variant. Expected one of [$variants], got $value.",[jw]:"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.",[Xw]:"Invalid value $value for base $base with alphabet $alphabet.",[Zw]:"Literal union discriminator out of range. Expected a number between $minRange and $maxRange, got $discriminator.",[Vw]:"Codec [$codecDescription] expected number to be in the range [$min, $max], got $value.",[Jw]:"Codec [$codecDescription] expected offset to be in the range [0, $bytesLength], got $offset.",[ib]:"Expected sentinel [$hexSentinel] to be present in decoded bytes [$hexDecodedBytes].",[eb]:"Union variant out of range. Expected an index between $minRange and $maxRange, got $variant.",[hm]:"No random values implementation could be found.",[Bm]:"instruction requires an uninitialized account",[Gm]:"instruction tries to borrow reference for an account which is already borrowed",[zm]:"instruction left account with an outstanding borrowed reference",[qm]:"program other than the account's owner changed the size of the account data",[Em]:"account data too small for instruction",[Km]:"instruction expected an executable account",[dy]:"An account does not have enough lamports to be rent-exempt",[gy]:"Program arithmetic overflowed",[hy]:"Failed to serialize or deserialize account data: $encodedData",[ky]:"Builtin programs must consume compute units",[Ym]:"Cross-program invocation call depth too deep",[iy]:"Computational budget exceeded",[Hm]:"custom program error: #$code",[Um]:"instruction contains duplicate accounts",[Wm]:"instruction modifications of multiply-passed account differ",[Qm]:"executable accounts must be rent exempt",[Vm]:"instruction changed executable accounts data",[Xm]:"instruction changed the balance of an executable account",[Mm]:"instruction changed executable bit of an account",[Dm]:"instruction modified data of an account it does not own",[Rm]:"instruction spent from the balance of an account it does not own",[vm]:"generic instruction error",[my]:"Provided owner is not allowed",[uy]:"Account is immutable",[ly]:"Incorrect authority provided",[Cm]:"incorrect program id for instruction",[Im]:"insufficient funds for instruction",[Tm]:"invalid account data for instruction",[fy]:"Invalid account owner",[Sm]:"invalid program argument",[jm]:"program returned invalid error code",[Am]:"invalid instruction data",[ry]:"Failed to reallocate account data",[ny]:"Provided seeds do not result in a valid address",[yy]:"Accounts data allocations exceeded the maximum allowed per transaction",[wy]:"Max accounts exceeded",[by]:"Max instruction trace length exceeded",[ty]:"Length of the seed is too long for address generation",[Zm]:"An account required by the instruction is missing",[Nm]:"missing required signature for instruction",[Pm]:"instruction illegally modified the program id of an account",[$m]:"insufficient account keys for instruction",[oy]:"Cross-program invocation with unauthorized signer or writable account",[sy]:"Failed to create program execution environment",[cy]:"Program failed to compile",[ay]:"Program failed to complete",[Om]:"instruction modified data of a read-only account",[Lm]:"instruction changed the balance of a read-only account",[ey]:"Cross-program invocation reentrancy not allowed for this instruction",[Fm]:"instruction modified rent epoch of an account",[_m]:"sum of account balances before and after instruction do not match",[xm]:"instruction requires an initialized account",[km]:"",[Jm]:"Unsupported program id",[py]:"Unsupported sysvar",[ym]:"The instruction does not have any accounts.",[wm]:"The instruction does not have any data.",[bm]:"Expected instruction to have progress address $expectedProgramAddress, got $actualProgramAddress.",[fp]:"Expected base58 encoded blockhash to decode to a byte array of length 32. Actual length: $actualLength.",[lp]:"The nonce `$expectedNonceValue` is no longer valid. It has advanced to `$actualNonceValue`",[yb]:"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",[bb]:"Invariant violation: This data publisher does not publish to the channel named `$channelName`. Supported channels include $supportedChannelNames.",[mb]:"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",[pb]:"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",[wb]:"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",[kp]:"JSON-RPC error: Internal JSON-RPC error ($__serverMessage)",[vp]:"JSON-RPC error: Invalid method parameter(s) ($__serverMessage)",[Ap]:"JSON-RPC error: The JSON sent is not a valid `Request` object ($__serverMessage)",[Sp]:"JSON-RPC error: The method does not exist / is not available ($__serverMessage)",[bp]:"JSON-RPC error: An error occurred on the server while parsing the JSON text ($__serverMessage)",[Np]:"$__serverMessage",[Fp]:"$__serverMessage",[Op]:"$__serverMessage",[Ip]:"$__serverMessage",[xp]:"$__serverMessage",[_p]:"$__serverMessage",[Tp]:"Minimum context slot has not been reached",[Lp]:"Node is unhealthy; behind by $numSlotsBehind slots",[Pp]:"No snapshot",[Mp]:"Transaction simulation failed",[Rp]:"$__serverMessage",[Bp]:"Transaction history is not available from this node",[Dp]:"$__serverMessage",[Cp]:"Transaction signature length mismatch",[Up]:"Transaction signature verification failure",[Ep]:"$__serverMessage",[dm]:"Key pair bytes must be of length 64, got $byteLength.",[fm]:"Expected private key bytes with length 32. Actual length: $actualLength.",[gm]:"Expected base58-encoded signature to decode to a byte array of length 64. Actual length: $actualLength.",[mm]:"The provided private key does not match the provided public key.",[pm]:"Expected base58-encoded signature string of length in the range [64, 88]. Actual length: $actualLength.",[gp]:"Lamports value must be in the range [0, 2e64-1]",[pp]:"`$value` cannot be parsed as a `BigInt`",[wp]:"$message",[mp]:"`$value` cannot be parsed as a `Number`",[hp]:"No nonce account could be found at address `$nonceAccountAddress`",[lb]:"The notification name must end in 'Notifications' and the API must supply a subscription plan creator function for the notification '$notificationName'.",[db]:"WebSocket was closed before payload could be added to the send buffer",[fb]:"WebSocket connection closed",[gb]:"WebSocket failed to connect",[hb]:"Failed to obtain a subscription id from the server",[ub]:"Could not find an API plan for RPC method: `$method`",[sb]:"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`.",[cb]:"HTTP error ($statusCode): $message",[ab]:"HTTP header(s) forbidden: $headers. Learn more at https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name.",[vy]:"Multiple distinct signers were identified for address `$address`. Please ensure that you are using the same signer instance for each address.",[Sy]:"The provided value does not implement the `KeyPairSigner` interface",[Ty]:"The provided value does not implement the `MessageModifyingSigner` interface",[Ey]:"The provided value does not implement the `MessagePartialSigner` interface",[Ay]:"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",[By]:"The provided value does not implement the `TransactionSendingSigner` interface",[Iy]:"The provided value does not implement any of the `TransactionSigner` interfaces",[xy]:"More than one `TransactionSendingSigner` was identified.",[_y]:"No `TransactionSendingSigner` was identified. Please provide a valid `TransactionWithSingleSendingSigner` transaction.",[Py]:"Wallet account signers do not support signing multiple messages/transactions in a single operation",[lm]:"Cannot export a non-extractable key.",[im]:"No digest implementation could be found.",[rm]:"Cryptographic operations are only allowed in secure browser contexts. Read more here: https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts.",[om]:"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.",[sm]:"No signature verification implementation could be found.",[am]:"No key generation implementation could be found.",[cm]:"No signing implementation could be found.",[um]:"No key export implementation could be found.",[yp]:"Timestamp value must be in the range [-(2n ** 63n), (2n ** 63n) - 1]. `$value` given",[mw]:"Transaction processing left an account with an outstanding borrowed reference",[tw]:"Account in use",[nw]:"Account loaded twice",[rw]:"Attempt to debit an account but found no record of a prior credit.",[Aw]:"Transaction loads an address table account that doesn't exist",[aw]:"This transaction has already been processed",[cw]:"Blockhash not found",[uw]:"Loader call chain is too deep",[pw]:"Transactions are currently disabled due to cluster maintenance",[xw]:"Transaction contains a duplicate instruction ($index) that is not allowed",[ow]:"Insufficient funds for fee",[_w]:"Transaction results in an account ($accountIndex) with insufficient funds for rent",[sw]:"This account may not be used to pay transaction fees",[hw]:"Transaction contains an invalid account reference",[Ew]:"Transaction loads an address table account with invalid data",[Iw]:"Transaction address table lookup uses an invalid index",[Tw]:"Transaction loads an address table account with an invalid owner",[Rw]:"LoadedAccountsDataSizeLimit set for transaction must be greater than 0.",[fw]:"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",[Pw]:"Transaction exceeded max loaded accounts data size cap",[lw]:"Transaction requires a fee but has no signature present",[iw]:"Attempt to load a program that does not exist",[Lw]:"Execution of the program referenced by account at index $accountIndex is temporarily restricted.",[Dw]:"ResanitizationNeeded",[gw]:"Transaction failed to sanitize accounts offsets correctly",[dw]:"Transaction did not pass signature verification",[Sw]:"Transaction locked too many accounts",[Ow]:"Sum of account balances before and after transaction do not match",[ew]:"The transaction failed with the error `$errorName`",[ww]:"Transaction version is unsupported",[vw]:"Transaction would exceed account data limit within the block",[Bw]:"Transaction would exceed total account data limit",[kw]:"Transaction would exceed max account limit within the block",[yw]:"Transaction would exceed max Block Cost Limit",[Nw]:"Transaction would exceed max Vote Cost Limit",[Vy]:"Attempted to sign a transaction with an address that is not a signer for it",[Gy]:"Transaction is missing an address at index: $index.",[Xy]:"Transaction has no expected signers therefore it cannot be encoded",[Zy]:"Transaction size $transactionSize exceeds limit of $transactionSizeLimit bytes",[Ly]:"Transaction does not have a blockhash lifetime",[Oy]:"Transaction is not a durable nonce transaction",[My]:"Contents of these address lookup tables unknown: $lookupTableAddresses",[Fy]:"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",[qy]:"No fee payer set in CompiledTransaction",[$y]:"Could not find program address at index $index",[Jy]:"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.",[Wy]:"Could not determine this transaction's signature. Make sure that the transaction has been signed by its fee payer.",[jy]:"Transaction first instruction is not advance nonce account instruction.",[Hy]:"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",[Dy]:"This transaction includes an address (`$programAddress`) which is both invoked and marked writable. Program addresses may not be writable",[Qy]:"The transaction message expected the transaction to have $signerAddressesLength signatures, got $signaturesLength.",[Ky]:"Transaction is missing signatures for addresses: $addresses.",[Uy]:"Transaction version must be in the range [0, 127]. `$actualVersion` given"},Ab="i",Tb="t";function Eb(e,t={}){if("production"!==process.env.NODE_ENV)return function(e,t={}){const n=Sb[e];if(0===n.length)return"";let r;function i(e){if(2===r[Tb]){const i=n.slice(r[Ab]+1,e);o.push(i in t?`${t[i]}`:`$${i}`)}else 1===r[Tb]&&o.push(n.slice(r[Ab],e))}const o=[];return n.split("").forEach((e,t)=>{if(0===t)return void(r={[Ab]:0,[Tb]:"\\"===n[0]?0:"$"===n[0]?2:1});let o;switch(r[Tb]){case 0:o={[Ab]:t,[Tb]:1};break;case 1:"\\"===e?o={[Ab]:t,[Tb]:0}:"$"===e&&(o={[Ab]:t,[Tb]:2});break;case 2:"\\"===e?o={[Ab]:t,[Tb]:0}:"$"===e?o={[Ab]:t,[Tb]:2}:e.match(/\w/)||(o={[Ab]:t,[Tb]: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(vb).join("&");return btoa(t)}(t)}'`),`${n}\``}}var Ib=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(Eb(e,n),r),this.context={__code:e,...n},this.name="SolanaError"}};function Cb(e){return"fixedSize"in e&&"number"==typeof e.fixedSize}function Nb(e){return 1!==e?.endian}function Bb(e){return t={fixedSize:e.size,write(t,n,r){e.range&&function(e,t,n,r){if(r<t||r>n)throw new Ib(Vw,{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,Nb(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 xb(e){return t={fixedSize:e.size,read(t,n=0){!function(e,t,n=0){if(t.length-n<=0)throw new Ib(Uw,{codecDescription:e})}(e.name,t,n),function(e,t,n,r=0){const i=n.length-r;if(i<t)throw new Ib(Mw,{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,Nb(e.config)),n+e.size]}},Object.freeze({...t,decode:(e,n=0)=>t.read(e,n)[0]});var t}var _b=(e={})=>function(e,t){if(Cb(e)!==Cb(t))throw new Ib(qw);if(Cb(e)&&Cb(t)&&e.fixedSize!==t.fixedSize)throw new Ib(Kw,{decoderFixedSize:t.fixedSize,encoderFixedSize:e.fixedSize});if(!Cb(e)&&!Cb(t)&&e.maxSize!==t.maxSize)throw new Ib(Gw,{decoderMaxSize:t.maxSize,encoderMaxSize:e.maxSize});return{...t,...e,decode:t.decode,encode:e.encode,read:t.read,write:e.write}}(((e={})=>Bb({config:e,name:"u64",range:[0n,BigInt("0xffffffffffffffff")],set:(e,t,n)=>e.setBigUint64(0,BigInt(t),n),size:8}))(e),((e={})=>xb({config:e,get:(e,t)=>e.getBigUint64(0,t),name:"u64",size:8}))(e));class Pb 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 Rb(e){return"object"==typeof e&&null!=e}function Db(e){return Rb(e)&&!Array.isArray(e)}function Lb(e){return"symbol"==typeof e?e.toString():"string"==typeof e?JSON.stringify(e):`${e}`}function Ob(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: \`${Lb(r)}\``}=e;return{value:r,type:s,refinement:a,key:i[i.length-1],path:i,branch:o,...e,message:c}}function*Ub(e,t,n,r){var i;Rb(i=e)&&"function"==typeof i[Symbol.iterator]||(e=[e]);for(const i of e){const e=Ob(i,t,n,r);e&&(yield e)}}function*Mb(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=Mb(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):Rb(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 Fb=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)=>Ub(r(e,t),t,this,e):()=>[],this.refiner=i?(e,t)=>Ub(i(e,t),t,this,e):()=>[]}assert(e,t){return function(e,t,n){const r=Kb(e,t,{message:n});if(r[0])throw r[0]}(e,this,t)}create(e,t){return $b(e,this,t)}is(e){return qb(e,this)}mask(e,t){return function(e,t,n){const r=Kb(e,t,{coerce:!0,mask:!0,message:n});if(r[0])throw r[0];return r[1]}(e,this,t)}validate(e,t={}){return Kb(e,this,t)}};function $b(e,t,n){const r=Kb(e,t,{coerce:!0,message:n});if(r[0])throw r[0];return r[1]}function qb(e,t){return!Kb(e,t)[0]}function Kb(e,t,n={}){const r=Mb(e,t,n),i=function(e){const{done:t,value:n}=e.next();return t?void 0:n}(r);if(i[0]){return[new Pb(i[0],function*(){for(const e of r)e[0]&&(yield e[0])}),void 0]}return[void 0,i[1]]}function Gb(e,t){return new Fb({type:e,schema:null,validator:t})}function zb(e){return new Fb({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: ${Lb(e)}`})}function Wb(){return Gb("boolean",e=>"boolean"==typeof e)}function Hb(e){return Gb("instance",t=>t instanceof e||`Expected a \`${e.name}\` instance, but received: ${Lb(t)}`)}function jb(e){const t=Lb(e),n=typeof e;return new Fb({type:"literal",schema:"string"===n||"number"===n||"boolean"===n?e:null,validator:n=>n===e||`Expected the literal \`${t}\`, but received: ${Lb(n)}`})}function Vb(e){return new Fb({...e,validator:(t,n)=>null===t||e.validator(t,n),refiner:(t,n)=>null===t||e.refiner(t,n)})}function Xb(){return Gb("number",e=>"number"==typeof e&&!isNaN(e)||`Expected a number, but received: ${Lb(e)}`)}function Qb(e){return new Fb({...e,validator:(t,n)=>void 0===t||e.validator(t,n),refiner:(t,n)=>void 0===t||e.refiner(t,n)})}function Jb(e,t){return new Fb({type:"record",schema:null,*entries(n){if(Rb(n))for(const r in n){const i=n[r];yield[r,r,e],yield[r,i,t]}},validator:e=>Db(e)||`Expected an object, but received: ${Lb(e)}`,coercer:e=>Db(e)?{...e}:e})}function Yb(){return Gb("string",e=>"string"==typeof e||`Expected a string, but received: ${Lb(e)}`)}function Zb(e){const t=Gb("never",()=>!1);return new Fb({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: ${Lb(e)}`,coercer:e=>Array.isArray(e)?e.slice():e})}function ek(e){const t=Object.keys(e);return new Fb({type:"type",schema:e,*entries(n){if(Rb(n))for(const r of t)yield[r,n[r],e[r]]},validator:e=>Db(e)||`Expected an object, but received: ${Lb(e)}`,coercer:e=>Db(e)?{...e}:e})}function tk(e){const t=e.map(e=>e.type).join(" | ");return new Fb({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]=Mb(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: ${Lb(n)}`,...i]}})}function nk(){return Gb("unknown",()=>!0)}function rk(e,t,n){return new Fb({...e,coercer:(r,i)=>qb(r,t)?e.coercer(n(r,i),i):e.coercer(r,i)})}var ik,ok,sk,ak;var ck,uk=function(){if(ak)return sk;ak=1;const e=s.v4,t=function(){if(ok)return ik;ok=1;const e=s.v4;return ik=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 sk=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)}},sk}(),lk=Fc(uk),hk={};var dk,fk=(ck||(ck=1,function(e){const t=qh(),n=Wh(),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 N(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 C(this,t,n);case"base64":return A(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return B(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 C(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 N(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 B(e,t,n){const r=e.slice(t,n);let i="";for(let e=0;e<r.length-1;e+=2)i+=String.fromCharCode(r[e]+256*r[e+1]);return i}function x(e,t,n){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>n)throw new RangeError("Trying to access beyond buffer length")}function _(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||x(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||x(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||x(e,1,this.length),this[e]},s.prototype.readUint16LE=s.prototype.readUInt16LE=function(e,t){return e>>>=0,t||x(e,2,this.length),this[e]|this[e+1]<<8},s.prototype.readUint16BE=s.prototype.readUInt16BE=function(e,t){return e>>>=0,t||x(e,2,this.length),this[e]<<8|this[e+1]},s.prototype.readUint32LE=s.prototype.readUInt32LE=function(e,t){return e>>>=0,t||x(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},s.prototype.readUint32BE=s.prototype.readUInt32BE=function(e,t){return e>>>=0,t||x(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},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||x(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||x(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||x(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},s.prototype.readInt16LE=function(e,t){e>>>=0,t||x(e,2,this.length);const n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},s.prototype.readInt16BE=function(e,t){e>>>=0,t||x(e,2,this.length);const n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},s.prototype.readInt32LE=function(e,t){return e>>>=0,t||x(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},s.prototype.readInt32BE=function(e,t){return e>>>=0,t||x(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},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||x(e,4,this.length),n.read(this,e,!0,23,4)},s.prototype.readFloatBE=function(e,t){return e>>>=0,t||x(e,4,this.length),n.read(this,e,!1,23,4)},s.prototype.readDoubleLE=function(e,t){return e>>>=0,t||x(e,8,this.length),n.read(this,e,!0,52,8)},s.prototype.readDoubleBE=function(e,t){return e>>>=0,t||x(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")}}(hk)),hk),gk={exports:{}};var pk=(dk||(dk=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}(gk)),gk.exports),mk=Fc(pk),yk=class extends mk{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 wk=class{encode(e){return JSON.stringify(e)}decode(e){return JSON.parse(e)}},bk=class extends mk{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 wk,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=fk.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 kk extends pd{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,Jh(e);const n=fd(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),Zh(i)}update(e){return Yh(this),this.iHash.update(e),this}digestInto(e){Yh(this),Qh(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 vk=(e,t,n)=>new kk(e,t).update(n).digest();vk.create=(e,t)=>new kk(e,t);const Sk=(e,t)=>(e+(e>=0?t:-t)/Bk)/t;function Ak(e){if(!["compact","recovered","der"].includes(e))throw new Error('Signature format must be "compact", "recovered", or "der"');return e}function Tk(e,t){const n={};for(let r of Object.keys(t))n[r]=void 0===e[r]?t[r]:e[r];return Yd(n.lowS,"lowS"),Yd(n.prehash,"prehash"),void 0!==n.format&&Ak(n.format),n}class Ek extends Error{constructor(e=""){super(e)}}const Ik={Err:Ek,_tlv:{encode:(e,t)=>{const{Err:n}=Ik;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=ef(r);if(i.length/2&128)throw new n("tlv.encode: long form length too big");const o=r>127?ef(i.length/2|128):"";return ef(e)+o+i+t},decode(e,t){const{Err:n}=Ik;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}=Ik;if(e<Ck)throw new t("integer: negative integers are not allowed");let n=ef(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}=Ik;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 nf(e)}},toSig(e){const{Err:t,_int:n,_tlv:r}=Ik,i=af("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}=Ik,r=t.encode(2,n.encode(e.r))+t.encode(2,n.encode(e.s));return t.encode(48,r)}},Ck=BigInt(0),Nk=BigInt(1),Bk=BigInt(2),xk=BigInt(3),_k=BigInt(4);function Pk(e,t){const{BYTES:n}=e;let r;if("bigint"==typeof t)r=t;else{let i=af("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 Rk(e,t={}){const n=eg("weierstrass",e,t),{Fp:r,Fn:i}=n;let o=n.CURVE;const{h:s,n:a}=o;ff(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=Lk(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(Yd(n,"isCompressed"),n){l();return gd(Dk(!r.isOdd(o)),s)}return gd(Uint8Array.of(4),s,r.toBytes(o))},d=t.fromBytes||function(e){Zd(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,xk),_k),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=Sk(s*e,n),c=Sk(-i*e,n);let u=e-a*r-c*o,l=-a*i-c*s;const h=u<Ck,d=l<Ck;h&&(u=-u),d&&(l=-l);const f=df(Math.ceil(hf(n)/2))+Nk;if(u<Ck||u>=f||l<Ck||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=gf((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=gf(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=Kf(i,t),n=Kf(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(Zd(e,void 0,"point")));return t.assertValidity(),t}static fromHex(e){return A.fromBytes(af("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(xk),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,xk),{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,xk);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=>Gf(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 Gf(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===Ck||r.is0())return A.ZERO;if(e===Nk)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>$f||r>$f;)n&qf&&(o=o.add(i)),r&qf&&(s=s.add(i)),i=i.double(),n>>=qf,r>>=qf;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===Nk||(e?e(A,this):E.unsafe(this,a).is0())}clearCofactor(){const{clearCofactor:e}=t;return s===Nk?this:e?e(A,this):this.multiplyUnsafe(s)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}toBytes(e=!0){return Yd(e,"isCompressed"),this.assertValidity(),h(A,this,e)}toHex(e=!0){return id(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 Gf(A,e)}static msm(e,t){return Yf(A,i,e,t)}static fromPrivateKey(e){return A.BASE.multiply(Pk(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 Jf(A,t.endo?Math.ceil(T/2):T);return A.BASE.precompute(8),A}function Dk(e){return Uint8Array.of(e?2:3)}function Lk(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function Ok(e,t={}){const{Fn:n}=e,r=t.randomBytes||yd,i=Object.assign(Lk(e.Fp,n),{seed:Ff(n.ORDER)});function o(e){try{return!!Pk(n,e)}catch(e){return!1}}function s(e=r(i.seed)){return function(e,t,n=!1){const r=e.length,i=Mf(t),o=Ff(t);if(r<16||r<o||r>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+r);const s=Ef(n?rf(e):nf(e),t-mf)+mf;return n?sf(s,i):of(s,i)}(Zd(e,i.seed,"seed"),n.ORDER)}function a(t,r=!0){return e.BASE.multiply(Pk(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=af("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=>Pk(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=Pk(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 Uk(e,t,n={}){Jh(t),ff(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const r=n.randomBytes||yd,i=n.hmac||((e,...n)=>vk(t,e,gd(...n))),{Fp:o,Fn:s}=e,{ORDER:a,BITS:c}=s,{keygen:u,getPublicKey:l,getSharedSecret:h,utils:d,lengths:f}=Ok(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>>Nk}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){Ak(t);const n=f.signature;Zd(e,"compact"===t?n:"recovered"===t?n+1:void 0,`${t} signature`)}(e,t),"der"===t){const{r:t,s:n}=Ik.toSig(Zd(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(dd(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*Bk<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(gd(Dk(!(1&c)),l)),d=s.inv(u),f=k(af("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(Ak(e),"der"===e)return dd(Ik.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 gd(Uint8Array.of(this.recovery),t,n)}return gd(t,n)}toHex(e){return id(this.toBytes(e))}assertValidity(){}static fromCompact(e){return w.fromBytes(af("sig",e),"compact")}static fromDER(e){return w.fromBytes(af("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 id(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return id(this.toBytes("compact"))}}const b=n.bits2int||function(e){if(e.length>8192)throw new Error("input is too large");const t=nf(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=df(c);function S(e){return lf("num < 2^"+c,e,Ck,v),s.toBytes(e)}function A(e,n){return Zd(e,void 0,"message"),n?Zd(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=af("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}=Tk(i,g);t=A(t,a);const u=k(t),l=Pk(s,n),h=[S(l),S(u)];if(null!=c&&!1!==c){const e=!0===c?r(f.secretKey):c;h.push(af("extraEntropy",e))}const d=gd(...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===Ck)return;const c=s.create(r*s.create(p+a*l));if(c===Ck)return;let u=(i.x===a?0:2)|Number(i.y&Nk),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 gd(...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}=Tk(i,g);if(r=af("publicKey",r),n=A(af("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||Vh(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(af("sig",e),"der")}catch(e){if(!(e instanceof Ik.Err))throw e}if(!t)try{t=w.fromBytes(af("sig",e),"compact")}catch(e){return!1}}return t||!1}(t):w.fromBytes(af("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}=Tk(n,g);return t=A(t,r),w.fromBytes(e,"recovered").recoverPublicKey(t).toBytes()},Signature:w,hash:t})}function Mk(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:Uf(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 Fk(e){const{CURVE:t,curveOpts:n,hash:r,ecdsaOpts:i}=Mk(e);return function(e,t){const n=t.Point;return Object.assign({},t,{ProjectivePoint:n,CURVE:Object.assign({},e,Of(n.Fn.ORDER,n.Fn.BITS))})}(e,Uk(Rk(t,n),r,i))}const $k={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},qk={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},Kk=BigInt(2);const Gk=Uf($k.p,{sqrt:function(e){const t=$k.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=If(l,n,t)*l%t,d=If(h,n,t)*l%t,f=If(d,Kk,t)*u%t,g=If(f,i,t)*f%t,p=If(g,o,t)*g%t,m=If(p,a,t)*p%t,y=If(m,c,t)*m%t,w=If(y,a,t)*p%t,b=If(w,n,t)*l%t,k=If(b,s,t)*g%t,v=If(k,r,t)*u%t,S=If(v,Kk,t);if(!Gk.eql(Gk.sqr(S),e))throw new Error("Cannot find square root");return S}}),zk=function(e,t){const n=t=>Fk({...e,hash:t});return{...n(t),create:n}}({...$k,Fp:Gk,lowS:!0,endo:qk},Vd);wg.utils.randomPrivateKey;const Wk=()=>{const e=wg.utils.randomPrivateKey(),t=Hk(e),n=new Uint8Array(64);return n.set(e),n.set(t,32),{publicKey:t,secretKey:n}},Hk=wg.getPublicKey;function jk(e){try{return wg.ExtendedPoint.fromHex(e),!0}catch{return!1}}const Vk=wg.verify,Xk=e=>Hh.Buffer.isBuffer(e)?e:e instanceof Uint8Array?Hh.Buffer.from(e.buffer,e.byteOffset,e.byteLength):Hh.Buffer.from(e);class Qk{constructor(e){Object.assign(this,e)}encode(){return Hh.Buffer.from(ip.serialize(Jk,this))}static decode(e){return ip.deserialize(Jk,this,e)}static decodeUnchecked(e){return ip.deserializeUnchecked(Jk,this,e)}}const Jk=new Map;var Yk;const Zk=32;let ev=1;class tv extends Qk{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=Og.decode(e);if(t.length!=Zk)throw new Error("Invalid public key input");this._bn=new xg(t)}else this._bn=new xg(e);if(this._bn.byteLength()>Zk)throw new Error("Invalid public key input")}}static unique(){const e=new tv(ev);return ev+=1,new tv(e.toBuffer())}equals(e){return this._bn.eq(e._bn)}toBase58(){return Og.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(Hh.Buffer);if(e.length===Zk)return e;const t=Hh.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=Hh.Buffer.concat([e.toBuffer(),Hh.Buffer.from(t),n.toBuffer()]),i=Ug(r);return new tv(i)}static createProgramAddressSync(e,t){let n=Hh.Buffer.alloc(0);e.forEach(function(e){if(e.length>32)throw new TypeError("Max seed length exceeded");n=Hh.Buffer.concat([n,Xk(e)])}),n=Hh.Buffer.concat([n,t.toBuffer(),Hh.Buffer.from("ProgramDerivedAddress")]);const r=Ug(n);if(jk(r))throw new Error("Invalid seeds, address must fall off the curve");return new tv(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(Hh.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 jk(new tv(e).toBytes())}}Yk=tv,tv.default=new Yk("11111111111111111111111111111111"),Jk.set(tv,{kind:"struct",fields:[["_bn","u256"]]}),new tv("BPFLoader1111111111111111111111111111111111");const nv=1232;class rv extends Error{constructor(e){super(`Signature ${e} has expired: block height exceeded.`),this.signature=void 0,this.signature=e}}Object.defineProperty(rv.prototype,"name",{value:"TransactionExpiredBlockheightExceededError"});class iv 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(iv.prototype,"name",{value:"TransactionExpiredTimeoutError"});class ov extends Error{constructor(e){super(`Signature ${e} has expired: the nonce is no longer valid.`),this.signature=void 0,this.signature=e}}Object.defineProperty(ov.prototype,"name",{value:"TransactionExpiredNonceInvalidError"});class sv{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 av=(e="publicKey")=>cp.blob(32,e),cv=(e="string")=>{const t=cp.struct([cp.u32("length"),cp.u32("lengthPadding"),cp.blob(cp.offset(cp.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:Hh.Buffer.from(e,"utf8")};return r(i,t,n)},i.alloc=e=>cp.u32().span+cp.u32().span+Hh.Buffer.from(e,"utf8").length,i};function uv(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 uv({layout:e},t[e.property]);return 0};let r=0;return e.layout.fields.forEach(e=>{r+=n(e)}),r}function lv(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 hv(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 dv(e,t){if(!e)throw new Error(t||"Assertion failed")}class fv{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 fv(t,n)}getMessageComponents(){const e=[...this.keyMetaMap.entries()];dv(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};{dv(t.length>0,"Expected at least one writable signer key");const[e]=t[0];dv(e===this.payer.toBase58(),"Expected first writable signer key to be the fee payer")}return[o,[...t.map(([e])=>new tv(e)),...n.map(([e])=>new tv(e)),...r.map(([e])=>new tv(e)),...i.map(([e])=>new tv(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 tv(i),o=e.findIndex(e=>e.equals(t));o>=0&&(dv(o<256,"Max lookup table index exceeded"),n.push(o),r.push(t),this.keyMetaMap.delete(i))}return[n,r]}}const gv="Reached end of buffer unexpectedly";function pv(e){if(0===e.length)throw new Error(gv);return e.shift()}function mv(e,...t){const[n]=t;if(2===t.length?n+(t[1]??0)>e.length:n>=e.length)throw new Error(gv);return e.splice(...t)}class yv{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 tv(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:Og.decode(e.data)}))}get addressTableLookups(){return[]}getAccountKeys(){return new sv(this.staticAccountKeys)}static compile(e){const t=fv.compile(e.instructions,e.payerKey),[n,r]=t.getMessageComponents(),i=new sv(r).compileInstructions(e.instructions).map(e=>({programIdIndex:e.programIdIndex,accounts:e.accountKeyIndexes,data:Og.encode(e.data)}));return new yv({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=[];hv(t,e);const n=this.instructions.map(e=>{const{accounts:t,programIdIndex:n}=e,r=Array.from(Og.decode(e.data));let i=[];hv(i,t.length);let o=[];return hv(o,r.length),{programIdIndex:n,keyIndicesCount:Hh.Buffer.from(i),keyIndices:t,dataLength:Hh.Buffer.from(o),data:r}});let r=[];hv(r,n.length);let i=Hh.Buffer.alloc(nv);Hh.Buffer.from(r).copy(i);let o=r.length;n.forEach(e=>{const t=cp.struct([cp.u8("programIdIndex"),cp.blob(e.keyIndicesCount.length,"keyIndicesCount"),cp.seq(cp.u8("keyIndex"),e.keyIndices.length,"keyIndices"),cp.blob(e.dataLength.length,"dataLength"),cp.seq(cp.u8("userdatum"),e.data.length,"data")]).encode(e,i,o);o+=t}),i=i.slice(0,o);const s=cp.struct([cp.blob(1,"numRequiredSignatures"),cp.blob(1,"numReadonlySignedAccounts"),cp.blob(1,"numReadonlyUnsignedAccounts"),cp.blob(t.length,"keyCount"),cp.seq(av("key"),e,"keys"),av("recentBlockhash")]),a={numRequiredSignatures:Hh.Buffer.from([this.header.numRequiredSignatures]),numReadonlySignedAccounts:Hh.Buffer.from([this.header.numReadonlySignedAccounts]),numReadonlyUnsignedAccounts:Hh.Buffer.from([this.header.numReadonlyUnsignedAccounts]),keyCount:Hh.Buffer.from(t),keys:this.accountKeys.map(e=>Xk(e.toBytes())),recentBlockhash:Og.decode(this.recentBlockhash)};let c=Hh.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=pv(t);if(n!==(127&n))throw new Error("Versioned messages must be deserialized with VersionedMessage.deserialize()");const r=pv(t),i=pv(t),o=lv(t);let s=[];for(let e=0;e<o;e++){const e=mv(t,0,Zk);s.push(new tv(Hh.Buffer.from(e)))}const a=mv(t,0,Zk),c=lv(t);let u=[];for(let e=0;e<c;e++){const e=pv(t),n=mv(t,0,lv(t)),r=mv(t,0,lv(t)),i=Og.encode(Hh.Buffer.from(r));u.push({programIdIndex:e,accounts:n,data:i})}const l={header:{numRequiredSignatures:n,numReadonlySignedAccounts:r,numReadonlyUnsignedAccounts:i},recentBlockhash:Og.encode(Hh.Buffer.from(a)),accountKeys:s,instructions:u};return new yv(l)}}class wv{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 sv(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=fv.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 sv(s,r).compileInstructions(e.instructions);return new wv({header:o,staticAccountKeys:s,recentBlockhash:e.recentBlockhash,compiledInstructions:a,addressTableLookups:n})}serialize(){const e=Array();hv(e,this.staticAccountKeys.length);const t=this.serializeInstructions(),n=Array();hv(n,this.compiledInstructions.length);const r=this.serializeAddressTableLookups(),i=Array();hv(i,this.addressTableLookups.length);const o=cp.struct([cp.u8("prefix"),cp.struct([cp.u8("numRequiredSignatures"),cp.u8("numReadonlySignedAccounts"),cp.u8("numReadonlyUnsignedAccounts")],"header"),cp.blob(e.length,"staticAccountKeysLength"),cp.seq(av(),this.staticAccountKeys.length,"staticAccountKeys"),av("recentBlockhash"),cp.blob(n.length,"instructionsLength"),cp.blob(t.length,"serializedInstructions"),cp.blob(i.length,"addressTableLookupsLength"),cp.blob(r.length,"serializedAddressTableLookups")]),s=new Uint8Array(nv),a=o.encode({prefix:128,header:this.header,staticAccountKeysLength:new Uint8Array(e),staticAccountKeys:this.staticAccountKeys.map(e=>e.toBytes()),recentBlockhash:Og.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(nv);for(const n of this.compiledInstructions){const r=Array();hv(r,n.accountKeyIndexes.length);const i=Array();hv(i,n.data.length);e+=cp.struct([cp.u8("programIdIndex"),cp.blob(r.length,"encodedAccountKeyIndexesLength"),cp.seq(cp.u8(),n.accountKeyIndexes.length,"accountKeyIndexes"),cp.blob(i.length,"encodedDataLength"),cp.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(nv);for(const n of this.addressTableLookups){const r=Array();hv(r,n.writableIndexes.length);const i=Array();hv(i,n.readonlyIndexes.length);e+=cp.struct([av("accountKey"),cp.blob(r.length,"encodedWritableIndexesLength"),cp.seq(cp.u8(),n.writableIndexes.length,"writableIndexes"),cp.blob(i.length,"encodedReadonlyIndexesLength"),cp.seq(cp.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=pv(t),r=127&n;dv(n!==r,"Expected versioned message but received legacy message");dv(0===r,`Expected versioned message with version 0 but found version ${r}`);const i={numRequiredSignatures:pv(t),numReadonlySignedAccounts:pv(t),numReadonlyUnsignedAccounts:pv(t)},o=[],s=lv(t);for(let e=0;e<s;e++)o.push(new tv(mv(t,0,Zk)));const a=Og.encode(mv(t,0,Zk)),c=lv(t),u=[];for(let e=0;e<c;e++){const e=pv(t),n=mv(t,0,lv(t)),r=lv(t),i=new Uint8Array(mv(t,0,r));u.push({programIdIndex:e,accountKeyIndexes:n,data:i})}const l=lv(t),h=[];for(let e=0;e<l;e++){const e=new tv(mv(t,0,Zk)),n=mv(t,0,lv(t)),r=mv(t,0,lv(t));h.push({accountKey:e,writableIndexes:n,readonlyIndexes:r})}return new wv({header:i,staticAccountKeys:o,recentBlockhash:a,compiledInstructions:u,addressTableLookups:h})}}let bv=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 kv=Hh.Buffer.alloc(64).fill(0);class vv{constructor(e){this.keys=void 0,this.programId=void 0,this.data=Hh.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 Sv{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 vv(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 tv(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:Og.encode(t)}});return f.forEach(e=>{dv(e.programIdIndex>=0),e.accounts.forEach(e=>dv(e>=0))}),new yv({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)=>wg.sign(e,t.slice(0,32)))(n,e.secretKey);this._addSignature(e.publicKey,Xk(t))})}addSignature(e,t){this._compile(),this._addSignature(e,t)}_addSignature(e,t){dv(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=Hh.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):Vk(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=[];hv(n,t.length);const r=n.length+64*t.length+e.length,i=Hh.Buffer.alloc(r);return dv(t.length<256),Hh.Buffer.from(n).copy(i,0),t.forEach(({signature:e},t)=>{null!==e&&(dv(64===e.length,"signature has invalid length"),Hh.Buffer.from(e).copy(i,n.length+64*t))}),e.copy(i,n.length+64*t.length),dv(i.length<=nv,`Transaction too large: ${i.length} > 1232`),i}get keys(){return dv(1===this.instructions.length),this.instructions[0].keys.map(e=>e.pubkey)}get programId(){return dv(1===this.instructions.length),this.instructions[0].programId}get data(){return dv(1===this.instructions.length),this.instructions[0].data}static from(e){let t=[...e];const n=lv(t);let r=[];for(let e=0;e<n;e++){const e=mv(t,0,64);r.push(Og.encode(Hh.Buffer.from(e)))}return Sv.populate(yv.from(t),r)}static populate(e,t=[]){const n=new Sv;return n.recentBlockhash=e.recentBlockhash,e.header.numRequiredSignatures>0&&(n.feePayer=e.accountKeys[0]),t.forEach((t,r)=>{const i={signature:t==Og.encode(kv)?null:Og.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 vv({keys:r,programId:e.accountKeys[t.programIdIndex],data:Og.decode(t.data)}))}),n._message=e,n._json=n.toJSON(),n}}new tv("SysvarC1ock11111111111111111111111111111111"),new tv("SysvarEpochSchedu1e111111111111111111111111"),new tv("Sysvar1nstructions1111111111111111111111111");const Av=new tv("SysvarRecentB1ockHashes11111111111111111111"),Tv=new tv("SysvarRent111111111111111111111111111111111");new tv("SysvarRewards111111111111111111111111111111"),new tv("SysvarS1otHashes111111111111111111111111111"),new tv("SysvarS1otHistory11111111111111111111111111"),new tv("SysvarStakeHistory1111111111111111111111111");class Ev 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 Iv 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 Cv(e){return new Promise(t=>setTimeout(t,e))}function Nv(e,t){const n=e.layout.span>=0?e.layout.span:uv(e,t),r=Hh.Buffer.alloc(n),i=Object.assign({instruction:e.index},t);return e.layout.encode(i,r),r}const Bv=cp.nu64("lamportsPerSignature"),xv=cp.struct([cp.u32("version"),cp.u32("state"),av("authorizedPubkey"),av("nonce"),cp.struct([Bv],"feeCalculator")]),_v=xv.span;class Pv{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=xv.decode(Xk(e),0);return new Pv({authorizedPubkey:new tv(t.authorizedPubkey),nonce:new tv(t.nonce).toString(),feeCalculator:t.feeCalculator})}}function Rv(e){const t=cp.blob(8,e),n=t.decode.bind(t),r=t.encode.bind(t),i=t,o=_b();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 Dv=Object.freeze({Create:{index:0,layout:cp.struct([cp.u32("instruction"),cp.ns64("lamports"),cp.ns64("space"),av("programId")])},Assign:{index:1,layout:cp.struct([cp.u32("instruction"),av("programId")])},Transfer:{index:2,layout:cp.struct([cp.u32("instruction"),Rv("lamports")])},CreateWithSeed:{index:3,layout:cp.struct([cp.u32("instruction"),av("base"),cv("seed"),cp.ns64("lamports"),cp.ns64("space"),av("programId")])},AdvanceNonceAccount:{index:4,layout:cp.struct([cp.u32("instruction")])},WithdrawNonceAccount:{index:5,layout:cp.struct([cp.u32("instruction"),cp.ns64("lamports")])},InitializeNonceAccount:{index:6,layout:cp.struct([cp.u32("instruction"),av("authorized")])},AuthorizeNonceAccount:{index:7,layout:cp.struct([cp.u32("instruction"),av("authorized")])},Allocate:{index:8,layout:cp.struct([cp.u32("instruction"),cp.ns64("space")])},AllocateWithSeed:{index:9,layout:cp.struct([cp.u32("instruction"),av("base"),cv("seed"),cp.ns64("space"),av("programId")])},AssignWithSeed:{index:10,layout:cp.struct([cp.u32("instruction"),av("base"),cv("seed"),av("programId")])},TransferWithSeed:{index:11,layout:cp.struct([cp.u32("instruction"),Rv("lamports"),cv("seed"),av("programId")])},UpgradeNonceAccount:{index:12,layout:cp.struct([cp.u32("instruction")])}});class Lv{constructor(){}static createAccount(e){const t=Nv(Dv.Create,{lamports:e.lamports,space:e.space,programId:Xk(e.programId.toBuffer())});return new vv({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=Nv(Dv.TransferWithSeed,{lamports:BigInt(e.lamports),seed:e.seed,programId:Xk(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=Nv(Dv.Transfer,{lamports:BigInt(e.lamports)}),n=[{pubkey:e.fromPubkey,isSigner:!0,isWritable:!0},{pubkey:e.toPubkey,isSigner:!1,isWritable:!0}]}return new vv({keys:n,programId:this.programId,data:t})}static assign(e){let t,n;if("basePubkey"in e){t=Nv(Dv.AssignWithSeed,{base:Xk(e.basePubkey.toBuffer()),seed:e.seed,programId:Xk(e.programId.toBuffer())}),n=[{pubkey:e.accountPubkey,isSigner:!1,isWritable:!0},{pubkey:e.basePubkey,isSigner:!0,isWritable:!1}]}else{t=Nv(Dv.Assign,{programId:Xk(e.programId.toBuffer())}),n=[{pubkey:e.accountPubkey,isSigner:!0,isWritable:!0}]}return new vv({keys:n,programId:this.programId,data:t})}static createAccountWithSeed(e){const t=Nv(Dv.CreateWithSeed,{base:Xk(e.basePubkey.toBuffer()),seed:e.seed,lamports:e.lamports,space:e.space,programId:Xk(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 vv({keys:n,programId:this.programId,data:t})}static createNonceAccount(e){const t=new Sv;"basePubkey"in e&&"seed"in e?t.add(Lv.createAccountWithSeed({fromPubkey:e.fromPubkey,newAccountPubkey:e.noncePubkey,basePubkey:e.basePubkey,seed:e.seed,lamports:e.lamports,space:_v,programId:this.programId})):t.add(Lv.createAccount({fromPubkey:e.fromPubkey,newAccountPubkey:e.noncePubkey,lamports:e.lamports,space:_v,programId:this.programId}));const n={noncePubkey:e.noncePubkey,authorizedPubkey:e.authorizedPubkey};return t.add(this.nonceInitialize(n)),t}static nonceInitialize(e){const t=Nv(Dv.InitializeNonceAccount,{authorized:Xk(e.authorizedPubkey.toBuffer())}),n={keys:[{pubkey:e.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:Av,isSigner:!1,isWritable:!1},{pubkey:Tv,isSigner:!1,isWritable:!1}],programId:this.programId,data:t};return new vv(n)}static nonceAdvance(e){const t=Nv(Dv.AdvanceNonceAccount),n={keys:[{pubkey:e.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:Av,isSigner:!1,isWritable:!1},{pubkey:e.authorizedPubkey,isSigner:!0,isWritable:!1}],programId:this.programId,data:t};return new vv(n)}static nonceWithdraw(e){const t=Nv(Dv.WithdrawNonceAccount,{lamports:e.lamports});return new vv({keys:[{pubkey:e.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:e.toPubkey,isSigner:!1,isWritable:!0},{pubkey:Av,isSigner:!1,isWritable:!1},{pubkey:Tv,isSigner:!1,isWritable:!1},{pubkey:e.authorizedPubkey,isSigner:!0,isWritable:!1}],programId:this.programId,data:t})}static nonceAuthorize(e){const t=Nv(Dv.AuthorizeNonceAccount,{authorized:Xk(e.newAuthorizedPubkey.toBuffer())});return new vv({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=Nv(Dv.AllocateWithSeed,{base:Xk(e.basePubkey.toBuffer()),seed:e.seed,space:e.space,programId:Xk(e.programId.toBuffer())}),n=[{pubkey:e.accountPubkey,isSigner:!1,isWritable:!0},{pubkey:e.basePubkey,isSigner:!0,isWritable:!1}]}else{t=Nv(Dv.Allocate,{space:e.space}),n=[{pubkey:e.accountPubkey,isSigner:!0,isWritable:!0}]}return new vv({keys:n,programId:this.programId,data:t})}}function Ov(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Uv,Mv;function Fv(){if(Mv)return Uv;Mv=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 Uv=function(e){var t=n(e,!1);if(void 0!==t)return""+t}}Lv.programId=new tv("11111111111111111111111111111111"),new tv("BPFLoader2111111111111111111111111111111111");var $v=Ov(Fv());function qv(e){let t=0;for(;e>1;)e/=2,t++;return t}class Kv{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=qv(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)))-qv(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+qv(32)):this.slotsPerEpoch}}var Gv=globalThis.fetch;class zv extends bk{constructor(e,t,n){super(e=>{const n=function(e,t){return new yk(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 Wv{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}(Hv,e),n=e.length-56;dv(n>=0,"lookup table is invalid"),dv(n%32==0,"lookup table is invalid");const r=n/32,{addresses:i}=cp.struct([cp.seq(av(),r,"addresses")]).decode(e.slice(56));return{deactivationSlot:t.deactivationSlot,lastExtendedSlot:t.lastExtendedSlot,lastExtendedSlotStartIndex:t.lastExtendedStartIndex,authority:0!==t.authority.length?new tv(t.authority[0]):void 0,addresses:i.map(e=>new tv(e))}}}const Hv={index:1,layout:cp.struct([cp.u32("typeIndex"),Rv("deactivationSlot"),cp.nu64("lastExtendedSlot"),cp.u8("lastExtendedStartIndex"),cp.u8(),cp.seq(av(),cp.offset(cp.u8(),-1),"authority")])},jv=/^[^:]+:\/\/([^:[]+|\[[^\]]+\])(:\d+)?(.*)/i;const Vv=rk(Hb(tv),Yb(),e=>new tv(e)),Xv=Zb([Yb(),jb("base64")]),Qv=rk(Hb(Hh.Buffer),Xv,e=>Hh.Buffer.from(e[0],"base64"));function Jv(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 Yv(e){return e.map(e=>"memcmp"in e?{...e,memcmp:{...e.memcmp,encoding:e.memcmp.encoding??"base58"}}:e)}function Zv(e){return tk([ek({jsonrpc:jb("2.0"),id:Yb(),result:e}),ek({jsonrpc:jb("2.0"),id:Yb(),error:ek({code:nk(),message:Yb(),data:Qb(Gb("any",()=>!0))})})])}const eS=Zv(nk());function tS(e){return rk(Zv(e),eS,t=>"error"in t?t:{...t,result:$b(t.result,e)})}function nS(e){return tS(ek({context:ek({slot:Xb()}),value:e}))}function rS(e){return ek({context:ek({slot:Xb()}),value:e})}function iS(e,t){return 0===e?new wv({header:t.header,staticAccountKeys:t.accountKeys.map(e=>new tv(e)),recentBlockhash:t.recentBlockhash,compiledInstructions:t.instructions.map(e=>({programIdIndex:e.programIdIndex,accountKeyIndexes:e.accounts,data:Og.decode(e.data)})),addressTableLookups:t.addressTableLookups}):new yv(t)}const oS=ek({foundation:Xb(),foundationTerm:Xb(),initial:Xb(),taper:Xb(),terminal:Xb()}),sS=tS(zb(Vb(ek({epoch:Xb(),effectiveSlot:Xb(),amount:Xb(),postBalance:Xb(),commission:Qb(Vb(Xb()))})))),aS=zb(ek({slot:Xb(),prioritizationFee:Xb()})),cS=ek({total:Xb(),validator:Xb(),foundation:Xb(),epoch:Xb()}),uS=ek({epoch:Xb(),slotIndex:Xb(),slotsInEpoch:Xb(),absoluteSlot:Xb(),blockHeight:Qb(Xb()),transactionCount:Qb(Xb())}),lS=ek({slotsPerEpoch:Xb(),leaderScheduleSlotOffset:Xb(),warmup:Wb(),firstNormalEpoch:Xb(),firstNormalSlot:Xb()}),hS=Jb(Yb(),zb(Xb())),dS=Vb(tk([ek({}),Yb()])),fS=ek({err:dS}),gS=jb("receivedSignature"),pS=ek({"solana-core":Yb(),"feature-set":Qb(Xb())}),mS=ek({program:Yb(),programId:Vv,parsed:nk()}),yS=ek({programId:Vv,accounts:zb(Vv),data:Yb()}),wS=nS(ek({err:Vb(tk([ek({}),Yb()])),logs:Vb(zb(Yb())),accounts:Qb(Vb(zb(Vb(ek({executable:Wb(),owner:Yb(),lamports:Xb(),data:zb(Yb()),rentEpoch:Qb(Xb())}))))),unitsConsumed:Qb(Xb()),returnData:Qb(Vb(ek({programId:Yb(),data:Zb([Yb(),jb("base64")])}))),innerInstructions:Qb(Vb(zb(ek({index:Xb(),instructions:zb(tk([mS,yS]))}))))})),bS=nS(ek({byIdentity:Jb(Yb(),zb(Xb())),range:ek({firstSlot:Xb(),lastSlot:Xb()})}));const kS=tS(oS),vS=tS(cS),SS=tS(aS),AS=tS(uS),TS=tS(lS),ES=tS(hS),IS=tS(Xb()),CS=nS(ek({total:Xb(),circulating:Xb(),nonCirculating:Xb(),nonCirculatingAccounts:zb(Vv)})),NS=ek({amount:Yb(),uiAmount:Vb(Xb()),decimals:Xb(),uiAmountString:Qb(Yb())}),BS=nS(zb(ek({address:Vv,amount:Yb(),uiAmount:Vb(Xb()),decimals:Xb(),uiAmountString:Qb(Yb())}))),xS=nS(zb(ek({pubkey:Vv,account:ek({executable:Wb(),owner:Vv,lamports:Xb(),data:Qv,rentEpoch:Xb()})}))),_S=ek({program:Yb(),parsed:nk(),space:Xb()}),PS=nS(zb(ek({pubkey:Vv,account:ek({executable:Wb(),owner:Vv,lamports:Xb(),data:_S,rentEpoch:Xb()})}))),RS=nS(zb(ek({lamports:Xb(),address:Vv}))),DS=ek({executable:Wb(),owner:Vv,lamports:Xb(),data:Qv,rentEpoch:Xb()}),LS=ek({pubkey:Vv,account:DS}),OS=rk(tk([Hb(Hh.Buffer),_S]),tk([Xv,_S]),e=>Array.isArray(e)?$b(e,Qv):e),US=ek({executable:Wb(),owner:Vv,lamports:Xb(),data:OS,rentEpoch:Xb()}),MS=ek({pubkey:Vv,account:US}),FS=ek({state:tk([jb("active"),jb("inactive"),jb("activating"),jb("deactivating")]),active:Xb(),inactive:Xb()}),$S=tS(zb(ek({signature:Yb(),slot:Xb(),err:dS,memo:Vb(Yb()),blockTime:Qb(Vb(Xb()))}))),qS=tS(zb(ek({signature:Yb(),slot:Xb(),err:dS,memo:Vb(Yb()),blockTime:Qb(Vb(Xb()))}))),KS=ek({subscription:Xb(),result:rS(DS)}),GS=ek({pubkey:Vv,account:DS}),zS=ek({subscription:Xb(),result:rS(GS)}),WS=ek({parent:Xb(),slot:Xb(),root:Xb()}),HS=ek({subscription:Xb(),result:WS}),jS=tk([ek({type:tk([jb("firstShredReceived"),jb("completed"),jb("optimisticConfirmation"),jb("root")]),slot:Xb(),timestamp:Xb()}),ek({type:jb("createdBank"),parent:Xb(),slot:Xb(),timestamp:Xb()}),ek({type:jb("frozen"),slot:Xb(),timestamp:Xb(),stats:ek({numTransactionEntries:Xb(),numSuccessfulTransactions:Xb(),numFailedTransactions:Xb(),maxTransactionsPerEntry:Xb()})}),ek({type:jb("dead"),slot:Xb(),timestamp:Xb(),err:Yb()})]),VS=ek({subscription:Xb(),result:jS}),XS=ek({subscription:Xb(),result:rS(tk([fS,gS]))}),QS=ek({subscription:Xb(),result:Xb()}),JS=ek({pubkey:Yb(),gossip:Vb(Yb()),tpu:Vb(Yb()),rpc:Vb(Yb()),version:Vb(Yb())}),YS=ek({votePubkey:Yb(),nodePubkey:Yb(),activatedStake:Xb(),epochVoteAccount:Wb(),epochCredits:zb(Zb([Xb(),Xb(),Xb()])),commission:Xb(),lastVote:Xb(),rootSlot:Vb(Xb())}),ZS=tS(ek({current:zb(YS),delinquent:zb(YS)})),eA=tk([jb("processed"),jb("confirmed"),jb("finalized")]),tA=ek({slot:Xb(),confirmations:Vb(Xb()),err:dS,confirmationStatus:Qb(eA)}),nA=nS(zb(Vb(tA))),rA=tS(Xb()),iA=ek({accountKey:Vv,writableIndexes:zb(Xb()),readonlyIndexes:zb(Xb())}),oA=ek({signatures:zb(Yb()),message:ek({accountKeys:zb(Yb()),header:ek({numRequiredSignatures:Xb(),numReadonlySignedAccounts:Xb(),numReadonlyUnsignedAccounts:Xb()}),instructions:zb(ek({accounts:zb(Xb()),data:Yb(),programIdIndex:Xb()})),recentBlockhash:Yb(),addressTableLookups:Qb(zb(iA))})}),sA=ek({pubkey:Vv,signer:Wb(),writable:Wb(),source:Qb(tk([jb("transaction"),jb("lookupTable")]))}),aA=ek({accountKeys:zb(sA),signatures:zb(Yb())}),cA=ek({parsed:nk(),program:Yb(),programId:Vv}),uA=ek({accounts:zb(Vv),data:Yb(),programId:Vv}),lA=rk(tk([uA,cA]),tk([ek({parsed:nk(),program:Yb(),programId:Yb()}),ek({accounts:zb(Yb()),data:Yb(),programId:Yb()})]),e=>$b(e,"accounts"in e?uA:cA)),hA=ek({signatures:zb(Yb()),message:ek({accountKeys:zb(sA),instructions:zb(lA),recentBlockhash:Yb(),addressTableLookups:Qb(Vb(zb(iA)))})}),dA=ek({accountIndex:Xb(),mint:Yb(),owner:Qb(Yb()),programId:Qb(Yb()),uiTokenAmount:NS}),fA=ek({writable:zb(Vv),readonly:zb(Vv)}),gA=ek({err:dS,fee:Xb(),innerInstructions:Qb(Vb(zb(ek({index:Xb(),instructions:zb(ek({accounts:zb(Xb()),data:Yb(),programIdIndex:Xb()}))})))),preBalances:zb(Xb()),postBalances:zb(Xb()),logMessages:Qb(Vb(zb(Yb()))),preTokenBalances:Qb(Vb(zb(dA))),postTokenBalances:Qb(Vb(zb(dA))),loadedAddresses:Qb(fA),computeUnitsConsumed:Qb(Xb()),costUnits:Qb(Xb())}),pA=ek({err:dS,fee:Xb(),innerInstructions:Qb(Vb(zb(ek({index:Xb(),instructions:zb(lA)})))),preBalances:zb(Xb()),postBalances:zb(Xb()),logMessages:Qb(Vb(zb(Yb()))),preTokenBalances:Qb(Vb(zb(dA))),postTokenBalances:Qb(Vb(zb(dA))),loadedAddresses:Qb(fA),computeUnitsConsumed:Qb(Xb()),costUnits:Qb(Xb())}),mA=tk([jb(0),jb("legacy")]),yA=ek({pubkey:Yb(),lamports:Xb(),postBalance:Vb(Xb()),rewardType:Vb(Yb()),commission:Qb(Vb(Xb()))}),wA=tS(Vb(ek({blockhash:Yb(),previousBlockhash:Yb(),parentSlot:Xb(),transactions:zb(ek({transaction:oA,meta:Vb(gA),version:Qb(mA)})),rewards:Qb(zb(yA)),blockTime:Vb(Xb()),blockHeight:Vb(Xb())}))),bA=tS(Vb(ek({blockhash:Yb(),previousBlockhash:Yb(),parentSlot:Xb(),rewards:Qb(zb(yA)),blockTime:Vb(Xb()),blockHeight:Vb(Xb())}))),kA=tS(Vb(ek({blockhash:Yb(),previousBlockhash:Yb(),parentSlot:Xb(),transactions:zb(ek({transaction:aA,meta:Vb(gA),version:Qb(mA)})),rewards:Qb(zb(yA)),blockTime:Vb(Xb()),blockHeight:Vb(Xb())}))),vA=tS(Vb(ek({blockhash:Yb(),previousBlockhash:Yb(),parentSlot:Xb(),transactions:zb(ek({transaction:hA,meta:Vb(pA),version:Qb(mA)})),rewards:Qb(zb(yA)),blockTime:Vb(Xb()),blockHeight:Vb(Xb())}))),SA=tS(Vb(ek({blockhash:Yb(),previousBlockhash:Yb(),parentSlot:Xb(),transactions:zb(ek({transaction:aA,meta:Vb(pA),version:Qb(mA)})),rewards:Qb(zb(yA)),blockTime:Vb(Xb()),blockHeight:Vb(Xb())}))),AA=tS(Vb(ek({blockhash:Yb(),previousBlockhash:Yb(),parentSlot:Xb(),rewards:Qb(zb(yA)),blockTime:Vb(Xb()),blockHeight:Vb(Xb())}))),TA=tS(Vb(ek({blockhash:Yb(),previousBlockhash:Yb(),parentSlot:Xb(),transactions:zb(ek({transaction:oA,meta:Vb(gA)})),rewards:Qb(zb(yA)),blockTime:Vb(Xb())}))),EA=tS(Vb(ek({blockhash:Yb(),previousBlockhash:Yb(),parentSlot:Xb(),signatures:zb(Yb()),blockTime:Vb(Xb())}))),IA=tS(Vb(ek({slot:Xb(),meta:Vb(gA),blockTime:Qb(Vb(Xb())),transaction:oA,version:Qb(mA)}))),CA=tS(Vb(ek({slot:Xb(),transaction:hA,meta:Vb(pA),blockTime:Qb(Vb(Xb())),version:Qb(mA)}))),NA=nS(ek({blockhash:Yb(),lastValidBlockHeight:Xb()})),BA=nS(Wb()),xA=tS(zb(ek({slot:Xb(),numTransactions:Xb(),numSlots:Xb(),samplePeriodSecs:Xb()}))),_A=nS(Vb(ek({feeCalculator:ek({lamportsPerSignature:Xb()})}))),PA=tS(Yb()),RA=tS(Yb()),DA=ek({err:dS,logs:zb(Yb()),signature:Yb()}),LA=ek({result:rS(DA),subscription:Xb()}),OA={"solana-client":"js/1.0.0-maintenance"};class UA{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}=Jv(t),i=this._buildArgs([],n,void 0,r),o=$v(i);return e[o]=e[o]??(async()=>{try{const e=$b(await this._rpcRequest("getBlockHeight",i),tS(Xb()));if("error"in e)throw new Iv(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(jv);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||Gv;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 lk(async(n,r)=>{const a={method:"POST",body:n,agent:void 0,headers:Object.assign({"Content-Type":"application/json"},t||{},OA)};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 Cv(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 zv(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}=Jv(t),i=this._buildArgs([e.toBase58()],n,void 0,r),o=$b(await this._rpcRequest("getBalance",i),nS(Xb()));if("error"in o)throw new Iv(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=$b(await this._rpcRequest("getBlockTime",[e]),tS(Vb(Xb())));if("error"in t)throw new Iv(t.error,`failed to get block time for slot ${e}`);return t.result}async getMinimumLedgerSlot(){const e=$b(await this._rpcRequest("minimumLedgerSlot",[]),tS(Xb()));if("error"in e)throw new Iv(e.error,"failed to get minimum ledger slot");return e.result}async getFirstAvailableBlock(){const e=$b(await this._rpcRequest("getFirstAvailableBlock",[]),IS);if("error"in e)throw new Iv(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=$b(await this._rpcRequest("getSupply",[t]),CS);if("error"in n)throw new Iv(n.error,"failed to get supply");return n.result}async getTokenSupply(e,t){const n=this._buildArgs([e.toBase58()],t),r=$b(await this._rpcRequest("getTokenSupply",n),nS(NS));if("error"in r)throw new Iv(r.error,"failed to get token supply");return r.result}async getTokenAccountBalance(e,t){const n=this._buildArgs([e.toBase58()],t),r=$b(await this._rpcRequest("getTokenAccountBalance",n),nS(NS));if("error"in r)throw new Iv(r.error,"failed to get token account balance");return r.result}async getTokenAccountsByOwner(e,t,n){const{commitment:r,config:i}=Jv(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=$b(await this._rpcRequest("getTokenAccountsByOwner",s),xS);if("error"in a)throw new Iv(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=$b(await this._rpcRequest("getTokenAccountsByOwner",i),PS);if("error"in o)throw new Iv(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=$b(await this._rpcRequest("getLargestAccounts",n),RS);if("error"in r)throw new Iv(r.error,"failed to get largest accounts");return r.result}async getTokenLargestAccounts(e,t){const n=this._buildArgs([e.toBase58()],t),r=$b(await this._rpcRequest("getTokenLargestAccounts",n),BS);if("error"in r)throw new Iv(r.error,"failed to get token largest accounts");return r.result}async getAccountInfoAndContext(e,t){const{commitment:n,config:r}=Jv(t),i=this._buildArgs([e.toBase58()],n,"base64",r),o=$b(await this._rpcRequest("getAccountInfo",i),nS(Vb(DS)));if("error"in o)throw new Iv(o.error,`failed to get info about account ${e.toBase58()}`);return o.result}async getParsedAccountInfo(e,t){const{commitment:n,config:r}=Jv(t),i=this._buildArgs([e.toBase58()],n,"jsonParsed",r),o=$b(await this._rpcRequest("getAccountInfo",i),nS(Vb(US)));if("error"in o)throw new Iv(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}=Jv(t),i=e.map(e=>e.toBase58()),o=this._buildArgs([i],n,"jsonParsed",r),s=$b(await this._rpcRequest("getMultipleAccounts",o),nS(zb(Vb(US))));if("error"in s)throw new Iv(s.error,`failed to get info for accounts ${i}`);return s.result}async getMultipleAccountsInfoAndContext(e,t){const{commitment:n,config:r}=Jv(t),i=e.map(e=>e.toBase58()),o=this._buildArgs([i],n,"base64",r),s=$b(await this._rpcRequest("getMultipleAccounts",o),nS(zb(Vb(DS))));if("error"in s)throw new Iv(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}=Jv(t),o=this._buildArgs([e.toBase58()],r,void 0,{...i,epoch:null!=n?n:i?.epoch}),s=$b(await this._rpcRequest("getStakeActivation",o),tS(FS));if("error"in s)throw new Iv(s.error,`failed to get Stake Activation ${e.toBase58()}`);return s.result}async getProgramAccounts(e,t){const{commitment:n,config:r}=Jv(t),{encoding:i,...o}=r||{},s=this._buildArgs([e.toBase58()],n,i||"base64",{...o,...o.filters?{filters:Yv(o.filters)}:null}),a=await this._rpcRequest("getProgramAccounts",s),c=zb(LS),u=!0===o.withContext?$b(a,nS(c)):$b(a,tS(c));if("error"in u)throw new Iv(u.error,`failed to get accounts owned by program ${e.toBase58()}`);return u.result}async getParsedProgramAccounts(e,t){const{commitment:n,config:r}=Jv(t),i=this._buildArgs([e.toBase58()],n,"jsonParsed",r),o=$b(await this._rpcRequest("getProgramAccounts",i),tS(zb(MS)));if("error"in o)throw new Iv(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=Og.decode(n)}catch(e){throw new Error("signature must be base58 encoded: "+n)}return dv(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:bv.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:bv.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 Cv(1e3),i)return;if(e=await r(),i)return}t({__type:bv.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!==bv.PROCESSED)throw new rv(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:bv.NONCE_INVALID,slotInWhichNonceDidAdvance:a});if(await Cv(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===bv.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 Cv(400)}if(!r?.value)throw new ov(o);{const t=e||"finalized",{confirmationStatus:n}=r.value;switch(t){case"processed":case"recent":if("processed"!==n&&"confirmed"!==n&&"finalized"!==n)throw new ov(o);break;case"confirmed":case"single":case"singleGossip":if("confirmed"!==n&&"finalized"!==n)throw new ov(o);break;case"finalized":case"max":case"root":if("finalized"!==n)throw new ov(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:bv.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!==bv.PROCESSED)throw new iv(t,e.timeoutMs/1e3);s=e.response}finally{clearTimeout(n),i()}return s}async getClusterNodes(){const e=$b(await this._rpcRequest("getClusterNodes",[]),tS(zb(JS)));if("error"in e)throw new Iv(e.error,"failed to get cluster nodes");return e.result}async getVoteAccounts(e){const t=this._buildArgs([],e),n=$b(await this._rpcRequest("getVoteAccounts",t),ZS);if("error"in n)throw new Iv(n.error,"failed to get vote accounts");return n.result}async getSlot(e){const{commitment:t,config:n}=Jv(e),r=this._buildArgs([],t,void 0,n),i=$b(await this._rpcRequest("getSlot",r),tS(Xb()));if("error"in i)throw new Iv(i.error,"failed to get slot");return i.result}async getSlotLeader(e){const{commitment:t,config:n}=Jv(e),r=this._buildArgs([],t,void 0,n),i=$b(await this._rpcRequest("getSlotLeader",r),tS(Yb()));if("error"in i)throw new Iv(i.error,"failed to get slot leader");return i.result}async getSlotLeaders(e,t){const n=[e,t],r=$b(await this._rpcRequest("getSlotLeaders",n),tS(zb(Vv)));if("error"in r)throw new Iv(r.error,"failed to get slot leaders");return r.result}async getSignatureStatus(e,t){const{context:n,value:r}=await this.getSignatureStatuses([e],t);dv(1===r.length);return{context:n,value:r[0]}}async getSignatureStatuses(e,t){const n=[e];t&&n.push(t);const r=$b(await this._rpcRequest("getSignatureStatuses",n),nA);if("error"in r)throw new Iv(r.error,"failed to get signature status");return r.result}async getTransactionCount(e){const{commitment:t,config:n}=Jv(e),r=this._buildArgs([],t,void 0,n),i=$b(await this._rpcRequest("getTransactionCount",r),tS(Xb()));if("error"in i)throw new Iv(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=$b(await this._rpcRequest("getInflationGovernor",t),kS);if("error"in n)throw new Iv(n.error,"failed to get inflation");return n.result}async getInflationReward(e,t,n){const{commitment:r,config:i}=Jv(n),o=this._buildArgs([e.map(e=>e.toBase58())],r,void 0,{...i,epoch:null!=t?t:i?.epoch}),s=$b(await this._rpcRequest("getInflationReward",o),sS);if("error"in s)throw new Iv(s.error,"failed to get inflation reward");return s.result}async getInflationRate(){const e=$b(await this._rpcRequest("getInflationRate",[]),vS);if("error"in e)throw new Iv(e.error,"failed to get inflation rate");return e.result}async getEpochInfo(e){const{commitment:t,config:n}=Jv(e),r=this._buildArgs([],t,void 0,n),i=$b(await this._rpcRequest("getEpochInfo",r),AS);if("error"in i)throw new Iv(i.error,"failed to get epoch info");return i.result}async getEpochSchedule(){const e=$b(await this._rpcRequest("getEpochSchedule",[]),TS);if("error"in e)throw new Iv(e.error,"failed to get epoch schedule");const t=e.result;return new Kv(t.slotsPerEpoch,t.leaderScheduleSlotOffset,t.warmup,t.firstNormalEpoch,t.firstNormalSlot)}async getLeaderSchedule(){const e=$b(await this._rpcRequest("getLeaderSchedule",[]),ES);if("error"in e)throw new Iv(e.error,"failed to get leader schedule");return e.result}async getMinimumBalanceForRentExemption(e,t){const n=this._buildArgs([e],t),r=$b(await this._rpcRequest("getMinimumBalanceForRentExemption",n),rA);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=$b(await this._rpcRequest("getRecentPerformanceSamples",e?[e]:[]),xA);if("error"in t)throw new Iv(t.error,"failed to get recent performance samples");return t.result}async getFeeCalculatorForBlockhash(e,t){const n=this._buildArgs([e],t),r=$b(await this._rpcRequest("getFeeCalculatorForBlockhash",n),_A);if("error"in r)throw new Iv(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=Xk(e.serialize()).toString("base64"),r=this._buildArgs([n],t),i=$b(await this._rpcRequest("getFeeForMessage",r),nS(Vb(Xb())));if("error"in i)throw new Iv(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=$b(await this._rpcRequest("getRecentPrioritizationFees",n),SS);if("error"in r)throw new Iv(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}=Jv(e),r=this._buildArgs([],t,void 0,n),i=$b(await this._rpcRequest("getLatestBlockhash",r),NA);if("error"in i)throw new Iv(i.error,"failed to get latest blockhash");return i.result}async isBlockhashValid(e,t){const{commitment:n,config:r}=Jv(t),i=this._buildArgs([e],n,void 0,r),o=$b(await this._rpcRequest("isBlockhashValid",i),BA);if("error"in o)throw new Iv(o.error,"failed to determine if the blockhash `"+e+"`is valid");return o.result}async getVersion(){const e=$b(await this._rpcRequest("getVersion",[]),tS(pS));if("error"in e)throw new Iv(e.error,"failed to get version");return e.result}async getGenesisHash(){const e=$b(await this._rpcRequest("getGenesisHash",[]),tS(Yb()));if("error"in e)throw new Iv(e.error,"failed to get genesis hash");return e.result}async getBlock(e,t){const{commitment:n,config:r}=Jv(t),i=this._buildArgsAtLeastConfirmed([e],n,void 0,r),o=await this._rpcRequest("getBlock",i);try{switch(r?.transactionDetails){case"accounts":{const e=$b(o,kA);if("error"in e)throw e.error;return e.result}case"none":{const e=$b(o,bA);if("error"in e)throw e.error;return e.result}default:{const e=$b(o,wA);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:iS(n,e.message)},version:n}))}:null}}}catch(e){throw new Iv(e,"failed to get confirmed block")}}async getParsedBlock(e,t){const{commitment:n,config:r}=Jv(t),i=this._buildArgsAtLeastConfirmed([e],n,"jsonParsed",r),o=await this._rpcRequest("getBlock",i);try{switch(r?.transactionDetails){case"accounts":{const e=$b(o,SA);if("error"in e)throw e.error;return e.result}case"none":{const e=$b(o,AA);if("error"in e)throw e.error;return e.result}default:{const e=$b(o,vA);if("error"in e)throw e.error;return e.result}}}catch(e){throw new Iv(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=$b(await this._rpcRequest("getBlockProduction",r),bS);if("error"in i)throw new Iv(i.error,"failed to get block production information");return i.result}async getTransaction(e,t){const{commitment:n,config:r}=Jv(t),i=this._buildArgsAtLeastConfirmed([e],n,void 0,r),o=$b(await this._rpcRequest("getTransaction",i),IA);if("error"in o)throw new Iv(o.error,"failed to get transaction");const s=o.result;return s?{...s,transaction:{...s.transaction,message:iS(s.version,s.transaction.message)}}:s}async getParsedTransaction(e,t){const{commitment:n,config:r}=Jv(t),i=this._buildArgsAtLeastConfirmed([e],n,"jsonParsed",r),o=$b(await this._rpcRequest("getTransaction",i),CA);if("error"in o)throw new Iv(o.error,"failed to get transaction");return o.result}async getParsedTransactions(e,t){const{commitment:n,config:r}=Jv(t),i=e.map(e=>({methodName:"getTransaction",args:this._buildArgsAtLeastConfirmed([e],n,"jsonParsed",r)}));return(await this._rpcBatchRequest(i)).map(e=>{const t=$b(e,CA);if("error"in t)throw new Iv(t.error,"failed to get transactions");return t.result})}async getTransactions(e,t){const{commitment:n,config:r}=Jv(t),i=e.map(e=>({methodName:"getTransaction",args:this._buildArgsAtLeastConfirmed([e],n,void 0,r)}));return(await this._rpcBatchRequest(i)).map(e=>{const t=$b(e,IA);if("error"in t)throw new Iv(t.error,"failed to get transactions");const n=t.result;return n?{...n,transaction:{...n.transaction,message:iS(n.version,n.transaction.message)}}:n})}async getConfirmedBlock(e,t){const n=this._buildArgsAtLeastConfirmed([e],t),r=$b(await this._rpcRequest("getBlock",n),TA);if("error"in r)throw new Iv(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 yv(e.message);return{meta:t,transaction:{...e,message:n}}})};return{...o,transactions:o.transactions.map(({transaction:e,meta:t})=>({meta:t,transaction:Sv.populate(e.message,e.signatures)}))}}async getBlocks(e,t,n){const r=this._buildArgsAtLeastConfirmed(void 0!==t?[e,t]:[e],n),i=$b(await this._rpcRequest("getBlocks",r),tS(zb(Xb())));if("error"in i)throw new Iv(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=$b(await this._rpcRequest("getBlock",n),EA);if("error"in r)throw new Iv(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=$b(await this._rpcRequest("getBlock",n),EA);if("error"in r)throw new Iv(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=$b(await this._rpcRequest("getTransaction",n),IA);if("error"in r)throw new Iv(r.error,"failed to get transaction");const i=r.result;if(!i)return i;const o=new yv(i.transaction.message),s=i.transaction.signatures;return{...i,transaction:Sv.populate(o,s)}}async getParsedConfirmedTransaction(e,t){const n=this._buildArgsAtLeastConfirmed([e],t,"jsonParsed"),r=$b(await this._rpcRequest("getTransaction",n),CA);if("error"in r)throw new Iv(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=$b(e,CA);if("error"in t)throw new Iv(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=$b(await this._rpcRequest("getConfirmedSignaturesForAddress2",r),$S);if("error"in i)throw new Iv(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=$b(await this._rpcRequest("getSignaturesForAddress",r),qS);if("error"in i)throw new Iv(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 Wv({key:e,state:Wv.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=Pv.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=$b(await this._rpcRequest("requestAirdrop",[e.toBase58(),t]),PA);if("error"in n)throw new Iv(n.error,`airdrop to ${e.toBase58()} failed`);return n.result}async _blockhashWithExpiryBlockHeight(e){if(!e){for(;this._pollingBlockhash;)await Cv(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 Cv(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}=Jv(e),r=this._buildArgs([],t,"base64",n),i=$b(await this._rpcRequest("getStakeMinimumDelegation",r),nS(Xb()));if("error"in i)throw new Iv(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=Hh.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=$b(await this._rpcRequest("simulateTransaction",s),wS);if("error"in a)throw new Error("failed to simulate transaction: "+a.error.message);return a.result}let r;if(e instanceof Sv){let t=e;r=new Sv,r.feePayer=t.feePayer,r.instructions=e.instructions,r.nonceInfo=t.nonceInfo,r.signatures=t.signatures}else r=Sv.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=$b(await this._rpcRequest("simulateTransaction",u),wS);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 Ev({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=Xk(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=$b(await this._rpcRequest("sendTransaction",o),RA);if("error"in s){let e;throw"data"in s.error&&(e=s.error.data.logs),new Ev({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}=$b(e,KS);this._handleServerNotification(n,[t.value,t.context])}_makeSubscription(e,t){const n=this._nextClientSubscriptionId++,r=$v([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];dv(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}=Jv(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}=$b(e,zS);this._handleServerNotification(n,[{accountId:t.value.pubkey,accountInfo:t.value.account},t.context])}onProgramAccountChange(e,t,n,r){const{commitment:i,config:o}=Jv(n),s=this._buildArgs([e.toBase58()],i||this._commitment||"finalized","base64",o||(r?{filters:Yv(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}=$b(e,LA);this._handleServerNotification(n,[t.value,t.context])}_wsOnSlotNotification(e){const{result:t,subscription:n}=$b(e,HS);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}=$b(e,VS);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}=$b(e,XS);"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}=$b(e,QS);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 MA{constructor(e){this._keypair=void 0,this._keypair=e??Wk()}static generate(){return new MA(Wk())}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=Hk(t);for(let e=0;e<32;e++)if(n[e]!==r[e])throw new Error("provided secretKey is invalid")}return new MA({publicKey:n,secretKey:e})}static fromSeed(e){const t=Hk(e),n=new Uint8Array(64);return n.set(e),n.set(t,32),new MA({publicKey:t,secretKey:n})}get publicKey(){return new tv(this._keypair.publicKey)}get secretKey(){return new Uint8Array(this._keypair.secretKey)}}Object.freeze({CreateLookupTable:{index:0,layout:cp.struct([cp.u32("instruction"),Rv("recentSlot"),cp.u8("bumpSeed")])},FreezeLookupTable:{index:1,layout:cp.struct([cp.u32("instruction")])},ExtendLookupTable:{index:2,layout:cp.struct([cp.u32("instruction"),Rv(),cp.seq(av(),cp.offset(cp.u32(),-8),"addresses")])},DeactivateLookupTable:{index:3,layout:cp.struct([cp.u32("instruction")])},CloseLookupTable:{index:4,layout:cp.struct([cp.u32("instruction")])}}),new tv("AddressLookupTab1e1111111111111111111111111");const FA=Object.freeze({RequestUnits:{index:0,layout:cp.struct([cp.u8("instruction"),cp.u32("units"),cp.u32("additionalFee")])},RequestHeapFrame:{index:1,layout:cp.struct([cp.u8("instruction"),cp.u32("bytes")])},SetComputeUnitLimit:{index:2,layout:cp.struct([cp.u8("instruction"),cp.u32("units")])},SetComputeUnitPrice:{index:3,layout:cp.struct([cp.u8("instruction"),Rv("microLamports")])}});class $A{constructor(){}static requestUnits(e){const t=Nv(FA.RequestUnits,e);return new vv({keys:[],programId:this.programId,data:t})}static requestHeapFrame(e){const t=Nv(FA.RequestHeapFrame,e);return new vv({keys:[],programId:this.programId,data:t})}static setComputeUnitLimit(e){const t=Nv(FA.SetComputeUnitLimit,e);return new vv({keys:[],programId:this.programId,data:t})}static setComputeUnitPrice(e){const t=Nv(FA.SetComputeUnitPrice,{microLamports:BigInt(e.microLamports)});return new vv({keys:[],programId:this.programId,data:t})}}var qA;$A.programId=new tv("ComputeBudget111111111111111111111111111111"),cp.struct([cp.u8("numSignatures"),cp.u8("padding"),cp.u16("signatureOffset"),cp.u16("signatureInstructionIndex"),cp.u16("publicKeyOffset"),cp.u16("publicKeyInstructionIndex"),cp.u16("messageDataOffset"),cp.u16("messageDataSize"),cp.u16("messageInstructionIndex")]),new tv("Ed25519SigVerify111111111111111111111111111"),zk.utils.isValidPrivateKey,cp.struct([cp.u8("numSignatures"),cp.u16("signatureOffset"),cp.u8("signatureInstructionIndex"),cp.u16("ethAddressOffset"),cp.u8("ethAddressInstructionIndex"),cp.u16("messageDataOffset"),cp.u16("messageDataSize"),cp.u8("messageInstructionIndex"),cp.blob(20,"ethAddress"),cp.blob(64,"signature"),cp.u8("recoveryId")]),new tv("KeccakSecp256k11111111111111111111111111111"),new tv("StakeConfig11111111111111111111111111111111");class KA{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}}qA=KA,KA.default=new qA(0,0,tv.default),Object.freeze({Initialize:{index:0,layout:cp.struct([cp.u32("instruction"),((e="authorized")=>cp.struct([av("staker"),av("withdrawer")],e))(),((e="lockup")=>cp.struct([cp.ns64("unixTimestamp"),cp.ns64("epoch"),av("custodian")],e))()])},Authorize:{index:1,layout:cp.struct([cp.u32("instruction"),av("newAuthorized"),cp.u32("stakeAuthorizationType")])},Delegate:{index:2,layout:cp.struct([cp.u32("instruction")])},Split:{index:3,layout:cp.struct([cp.u32("instruction"),cp.ns64("lamports")])},Withdraw:{index:4,layout:cp.struct([cp.u32("instruction"),cp.ns64("lamports")])},Deactivate:{index:5,layout:cp.struct([cp.u32("instruction")])},Merge:{index:7,layout:cp.struct([cp.u32("instruction")])},AuthorizeWithSeed:{index:8,layout:cp.struct([cp.u32("instruction"),av("newAuthorized"),cp.u32("stakeAuthorizationType"),cv("authoritySeed"),av("authorityOwner")])}}),new tv("Stake11111111111111111111111111111111111111"),Object.freeze({InitializeAccount:{index:0,layout:cp.struct([cp.u32("instruction"),((e="voteInit")=>cp.struct([av("nodePubkey"),av("authorizedVoter"),av("authorizedWithdrawer"),cp.u8("commission")],e))()])},Authorize:{index:1,layout:cp.struct([cp.u32("instruction"),av("newAuthorized"),cp.u32("voteAuthorizationType")])},Withdraw:{index:3,layout:cp.struct([cp.u32("instruction"),cp.ns64("lamports")])},UpdateValidatorIdentity:{index:4,layout:cp.struct([cp.u32("instruction")])},AuthorizeWithSeed:{index:10,layout:cp.struct([cp.u32("instruction"),((e="voteAuthorizeWithSeedArgs")=>cp.struct([cp.u32("voteAuthorizationType"),av("currentAuthorityDerivedKeyOwnerPubkey"),cv("currentAuthorityDerivedKeySeed"),av("newAuthorized")],e))()])}}),new tv("Vote111111111111111111111111111111111111111"),new tv("Va1idator1nfo111111111111111111111111111111"),ek({name:Yb(),website:Qb(Yb()),details:Qb(Yb()),iconUrl:Qb(Yb()),keybaseUsername:Qb(Yb())}),new tv("Vote111111111111111111111111111111111111111"),cp.struct([av("nodePubkey"),av("authorizedWithdrawer"),cp.u8("commission"),cp.nu64(),cp.seq(cp.struct([cp.nu64("slot"),cp.u32("confirmationCount")]),cp.offset(cp.u32(),-8),"votes"),cp.u8("rootSlotValid"),cp.nu64("rootSlot"),cp.nu64(),cp.seq(cp.struct([cp.nu64("epoch"),av("authorizedVoter")]),cp.offset(cp.u32(),-8),"authorizedVoters"),cp.struct([cp.seq(cp.struct([av("authorizedPubkey"),cp.nu64("epochOfLastAuthorizedSwitch"),cp.nu64("targetEpoch")]),32,"buf"),cp.nu64("idx"),cp.u8("isEmpty")],"priorVoters"),cp.nu64(),cp.seq(cp.struct([cp.nu64("epoch"),cp.nu64("credits"),cp.nu64("prevCredits")]),cp.offset(cp.u32(),-8),"epochCredits"),cp.struct([cp.nu64("slot"),cp.nu64("timestamp")],"lastTimestamp")]);function GA(e){return/^0x[a-fA-F0-9]{64}$/.test(e)}function zA(e){const t=new Map;for(const n of e)t.set(os(n.symbol),n);return t}function WA(e,t,n){const r=function(e,t){return e.get(os(t))}(e,t);if(!r){throw V(`Token ${t} not supported for ${n}. Supported: ${Array.from(e.keys()).join(", ")}`,"tokenSymbol")}return r}function HA(e){if(!e||!GA(e))throw H("privateKey","a 0x-prefixed 64-character hex string (e.g., 0x1234...abcd)","Ethereum private key")}class jA{constructor(e){this.cache=new Map,this.galaConnectClient=e.galaConnectClient}async getTokenMetadata(e){const t=ss(e),n=this.cache.get(t);if(n)return n;const r=au[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=ss(e);return this.cache.has(t)||t in au}clearCache(){this.cache.clear()}async fetchFromApi(e){let t=e,n=await this.galaConnectClient.getBridgeConfigurations(t),r=n.find(e=>ss(e.symbol)===ss(t)&&e.verified);if(r||e.startsWith("G")||(t=`G${e}`,n=await this.galaConnectClient.getBridgeConfigurations(t),r=n.find(e=>ss(e.symbol)===ss(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 VA(e,t){const{wallet:n}=t,r=e.uniqueKey??`galaconnect-operation-${y.randomUUID()}`,i="string"==typeof e.destinationChainId?Ue(e.destinationChainId,1):e.destinationChainId,o=function(e){const t={...e,galaDecimals:"string"==typeof e.galaDecimals?Ue(e.galaDecimals,0):e.galaDecimals,timestamp:"string"==typeof e.timestamp?Ue(e.timestamp,0):e.timestamp};if(e.galaExchangeRate&&(t.galaExchangeRate={...e.galaExchangeRate,timestamp:"string"==typeof e.galaExchangeRate.timestamp?Ue(e.galaExchangeRate.timestamp,0):e.galaExchangeRate.timestamp}),e.galaExchangeCrossRate){const n=e.galaExchangeCrossRate;t.galaExchangeCrossRate={...n,timestamp:"string"==typeof n.timestamp?Ue(n.timestamp,0):n.timestamp},n.baseTokenCrossRate&&(t.galaExchangeCrossRate.baseTokenCrossRate={...n.baseTokenCrossRate,timestamp:"string"==typeof n.baseTokenCrossRate.timestamp?Ue(n.baseTokenCrossRate.timestamp,0):n.baseTokenCrossRate.timestamp}),n.quoteTokenCrossRate&&(t.galaExchangeCrossRate.quoteTokenCrossRate={...n.quoteTokenCrossRate,timestamp:"string"==typeof n.quoteTokenCrossRate.timestamp?Ue(n.quoteTokenCrossRate.timestamp,0):n.quoteTokenCrossRate.timestamp})}return t}(e.destinationChainTxFee),s=Boolean(o.galaExchangeCrossRate),a={destinationChainId:i,destinationChainTxFee:Lh(s?{...o,galaExchangeRate:void 0}:{...o,galaExchangeCrossRate:void 0}),quantity:e.quantity,recipient:e.recipient,tokenInstance:e.tokenInstance,uniqueKey:r},c=wu(s),u=await n.signTypedData(hu,c,a),l=`Ethereum Signed Message:\n${Xc({domain:hu,message:a,primaryType:"GalaTransaction",types:c}).length}`;return{...a,signature:u,prefix:l,types:c,domain:hu}}const XA=5,QA=6,JA=7;function YA(e){const t=Ue(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===XA,isFailed:t===QA||t===JA}}const ZA="Token symbol resolution failed. This is an internal error - BridgeService should resolve tokenId to symbol before calling strategy.",eT="Bridge request ID missing from RequestTokenBridgeOut response",tT="BridgeTokenOut response missing transaction hash";function nT(e){if(!e)throw V(ZA,"tokenSymbol");return e}function rT(e,n){if(!t.isAddress(e)){throw H(n||"address","a valid 0x-prefixed Ethereum address",e)}}function iT(e,t){try{return new tv(e)}catch{throw H(t||"address","a valid Solana address (base58)",e)}}function oT(e){try{return new tv(e)}catch{throw H("address","a valid Solana address (base58)",e)}}function sT(e,t,n){return{symbol:e,quantity:t,decimals:n,contractAddress:null,isNative:!0}}function aT(e,t){return{symbol:e.symbol,quantity:t,decimals:e.decimals??18,contractAddress:e.contractAddress,isNative:!1}}function cT(e,t){return{symbol:e.symbol,quantity:t,decimals:e.decimals??9,contractAddress:e.mintAddress,isNative:e.isNative??!1}}function uT(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 lT={Ethereum:"Ethereum bridging not configured. Provide ethereumPrivateKey in config.",Solana:"Solana bridging not configured. Provide solanaPrivateKey in config."};function hT(e,t,n){if(!e)throw V(n??lT[t],`${t.toLowerCase()}Strategy`);return e}function dT(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 fT(e,t){return hT(e.get("Ethereum"),"Ethereum",t)}function gT(e,t){return hT(e.get("Solana"),"Solana",t)}function pT(e,t){return e??t.getWalletAddress()}async function mT(e,t){const{amount:n,recipientAddress:r,tokenSymbol:i}=e,{galaConnectClient:o,tokenMetadataResolver:s,ethereumWallet:a,destinationChainId:c,destinationChain:u,validateRecipientAddress:l}=t,h=nT(i);Oh(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 VA(g,{wallet:a}),m=function(e){if(!e)throw V(eT,"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 V(tT,"transactionHash");return t}(await o.bridgeTokenOut({bridgeFromChannel:"asset",bridgeRequestId:m})),tokenSymbol:h,amount:n,feePaid:f.estimatedTotalTxFeeInGala,baseUrl:o.getBaseUrl()})}class yT 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 wT=eu,bT="https://galachain-gateway-chain-platform-galachain-mainnet.gala.com",kT=12,vT=!0,ST=3,AT=1e3;class TT{constructor(e){this.baseUrl=e.baseUrl??wT,this.galachainBaseUrl=e.galachainBaseUrl??bT,this.walletAddress=e.walletAddress,this.rateLimiter=new Eh(e.requestsPerSecond??kT),this.defaultHeaders={"Content-Type":"application/json","X-Wallet-Address":this.walletAddress};const t=e.enableRetry??vT;this.retryOptions=t?{maxRetries:e.maxRetries??ST,initialDelayMs:e.retryInitialDelayMs??AT,...e.onRetry&&{onRetry:e.onRetry},shouldRetry:e=>_h(e instanceof yT?{status:e.status}:e)}:null}getBaseUrl(){return this.baseUrl}async getBridgeConfigurations(e){return br(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?Re(e,{rawBody:e}):{message:"Failed to fetch bridge configurations"},new yT(n.status,"/v1/connect/bridge-configurations",t)}return(await n.json()).data.tokens},"GalaConnectClient.getBridgeConfigurations",void 0,(e,t,n)=>{if(e instanceof yT)throw e;throw Q(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 br(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=Re(t,{rawBody:t.slice(0,n)});throw new yT(s.status,e,r)}const a=await s.text();if(a){const t=function(e){if(Ye(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: ${T(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 yT)throw e;throw Q(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 yT(t,e,i)}}return r});return this.retryOptions?async function(e,t={}){const n={...Nh,...t},r=t.shouldRetry??(e=>_h(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=Ph(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 ET;e.BridgeStatusCode=void 0,(ET=e.BridgeStatusCode||(e.BridgeStatusCode={}))[ET.PENDING=0]="PENDING",ET[ET.SUBMITTED=1]="SUBMITTED",ET[ET.CONFIRMED=2]="CONFIRMED",ET[ET.PROCESSING=3]="PROCESSING",ET[ET.FINALIZING=4]="FINALIZING",ET[ET.COMPLETED=5]="COMPLETED",ET[ET.FAILED=6]="FAILED",ET[ET.DELIVERY_FAILED=7]="DELIVERY_FAILED";class IT{async waitForCompletion(t,n={}){const{pollInterval:r=15e3,timeout:i=27e5,onStatusUpdate:o}=n,s=Date.now();for(;;){const n=await this.getStatus(t);if(o&&o(n),n.status===e.BridgeStatusCode.COMPLETED||n.status===e.BridgeStatusCode.FAILED||n.status===e.BridgeStatusCode.DELIVERY_FAILED)return n;if(Xe(s)>i)throw X(`Bridge transaction timed out after ${i}ms. Last status: ${n.status}`,t,"TIMEOUT");await new Promise(e=>setTimeout(e,r))}}}class CT extends IT{constructor(e){super(),this.network="Ethereum",this.galaConnectClient=e.galaConnectClient,this.galaChainWalletAddress=e.galaChainWalletAddress,HA(e.ethereumPrivateKey);const n=e.ethereumRpcUrl??"https://ethereum.publicnode.com";this.ethereumProvider=new t.JsonRpcProvider(n),this.ethereumWallet=new t.Wallet(e.ethereumPrivateKey,this.ethereumProvider),this.ethereumWalletAddress=e.ethereumWalletAddress??this.ethereumWallet.address,this.ethereumBridgeContract=e.ethereumBridgeContract??"0x3F98b5A26EF3f04E1DA3B0B41dD350E8C8F3A7c2";const r=e.tokenConfigs??ou;this.tokenConfigs=zA(r),this.tokenMetadataResolver=new jA({galaConnectClient:this.galaConnectClient})}async estimateFee(e,t){const n=await this.tokenMetadataResolver.getTokenMetadata(e);return Uh(await this.galaConnectClient.fetchBridgeFee({chainId:"Ethereum",bridgeToken:n.descriptor}))}async bridgeOut(e){return mT(e,{galaConnectClient:this.galaConnectClient,tokenMetadataResolver:this.tokenMetadataResolver,ethereumWallet:this.ethereumWallet,destinationChainId:Qc.ETHEREUM,destinationChain:"Ethereum",validateRecipientAddress:rT})}async bridgeIn(e){const{amount:n,sourcePrivateKey:r,recipientAddress:i,tokenSymbol:o}=e,s=nT(o);if(Oh(n,s),r&&!GA(r))throw H("sourcePrivateKey","0x-prefixed 64-character hex string",r.slice(0,10)+"...");const a=r?new t.Wallet(r,this.ethereumProvider):this.ethereumWallet,c=WA(this.tokenConfigs,s,"Ethereum bridge"),u=await this.tokenMetadataResolver.getTokenMetadata(s),l=new t.Contract(c.contractAddress,cu,a),h=Ue(await l.decimals(),18),d=Ih(n,h),f=BigInt(await l.balanceOf(a.address));if(f<d){throw V(`Insufficient ${s} balance on Ethereum. Needed ${Ch(d,h)}, have ${Ch(f,h)}`,"amount")}const g=function(e){const n=new ht;if("client"===n.detectFormat(e))return e;const r=n.normalizeInput(e);if(!r)throw H("address","a valid GalaChain address (eth|0x{40-hex}, 0x{40-hex}, or {40-hex})","GalaChain address");const i=n.extractHex(r);return`eth|${t.getAddress("0x"+i).slice(2)}`}(i??this.galaChainWalletAddress);return dT({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 YA(await this.galaConnectClient.getBridgeStatus(e))}getSupportedTokens(){return Array.from(this.tokenConfigs.keys())}isTokenSupported(e){return this.tokenConfigs.has(os(e))}isValidAddress(e){return Qe.ETH_ADDRESS.test(e)}getWalletAddress(){return this.ethereumWalletAddress}async getEthereumTokenBalance(e,n){const r=WA(this.tokenConfigs,e,"Ethereum"),i=n??this.ethereumWalletAddress;rT(i);const o=new t.Contract(r.contractAddress,cu,this.ethereumProvider);return Ch(await o.balanceOf(i),r.decimals??18)}async getEthereumNativeBalance(e){const t=e??this.ethereumWalletAddress;rT(t);return Ch(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 H("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>=CT.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: ${T(e)}`}}}async executeBridgeDeposit(e){const n=new t.Contract(this.ethereumBridgeContract,uu,e.wallet),r=(new TextEncoder).encode(e.recipient);let i;i=e.tokenConfig.bridgeUsesPermit?await this.bridgeWithPermit(e.wallet,e.tokenContract,e.tokenConfig,n,e.amountBaseUnits,r):await this.bridgeWithApproval(e.wallet,e.tokenContract,n,e.tokenConfig,e.amountBaseUnits,r);if(!await i.wait())throw V("Bridge transaction receipt not available","ethereumRpcUrl");await Rh(3e4);const o={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:Ch(e.amountBaseUnits,e.decimals),tokenInstance:o,fromChain:"Ethereum",toChain:"GC",hash:i.hash}),{txHash:i.hash}}async bridgeWithPermit(e,n,r,i,o,s){const a=await this.ethereumProvider.getNetwork(),c=await n.name(),u=await n.nonces(e.address),l=BigInt(Math.floor(Date.now()/1e3)+3600),h=await e.signTypedData({name:c,version:"1",chainId:Ue(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:e.address,spender:this.ethereumBridgeContract,value:o,nonce:u,deadline:l}),d=t.Signature.from(h);return i.bridgeOutWithPermit(r.contractAddress,o,Qc.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,Qc.GALA_CHAIN,o)}}CT.ETHEREUM_FINALITY_THRESHOLD=12;for(var NT={},BT={byteLength:function(e){var t=LT(e),n=t[0],r=t[1];return 3*(n+r)/4-r},toByteArray:function(e){var t,n,r=LT(e),i=r[0],o=r[1],s=new PT(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=_T[e.charCodeAt(n)]<<18|_T[e.charCodeAt(n+1)]<<12|_T[e.charCodeAt(n+2)]<<6|_T[e.charCodeAt(n+3)],s[a++]=t>>16&255,s[a++]=t>>8&255,s[a++]=255&t;2===o&&(t=_T[e.charCodeAt(n)]<<2|_T[e.charCodeAt(n+1)]>>4,s[a++]=255&t);1===o&&(t=_T[e.charCodeAt(n)]<<10|_T[e.charCodeAt(n+1)]<<4|_T[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(UT(e,s,s+o>a?a:s+o));1===r?(t=e[n-1],i.push(xT[t>>2]+xT[t<<4&63]+"==")):2===r&&(t=(e[n-2]<<8)+e[n-1],i.push(xT[t>>10]+xT[t>>4&63]+xT[t<<2&63]+"="));return i.join("")}},xT=[],_T=[],PT="undefined"!=typeof Uint8Array?Uint8Array:Array,RT="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",DT=0;DT<64;++DT)xT[DT]=RT[DT],_T[RT.charCodeAt(DT)]=DT;function LT(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 OT(e){return xT[e>>18&63]+xT[e>>12&63]+xT[e>>6&63]+xT[63&e]}function UT(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(OT(r));return i.join("")}_T["-".charCodeAt(0)]=62,_T["_".charCodeAt(0)]=63;var MT={};MT.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)},MT.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=BT,n=MT,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 N(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 C(this,t,n);case"base64":return A(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return B(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 C(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 N(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 B(e,t,n){const r=e.slice(t,n);let i="";for(let e=0;e<r.length-1;e+=2)i+=String.fromCharCode(r[e]+256*r[e+1]);return i}function x(e,t,n){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>n)throw new RangeError("Trying to access beyond buffer length")}function _(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||x(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||x(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||x(e,1,this.length),this[e]},s.prototype.readUint16LE=s.prototype.readUInt16LE=function(e,t){return e>>>=0,t||x(e,2,this.length),this[e]|this[e+1]<<8},s.prototype.readUint16BE=s.prototype.readUInt16BE=function(e,t){return e>>>=0,t||x(e,2,this.length),this[e]<<8|this[e+1]},s.prototype.readUint32LE=s.prototype.readUInt32LE=function(e,t){return e>>>=0,t||x(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},s.prototype.readUint32BE=s.prototype.readUInt32BE=function(e,t){return e>>>=0,t||x(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},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||x(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||x(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||x(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},s.prototype.readInt16LE=function(e,t){e>>>=0,t||x(e,2,this.length);const n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},s.prototype.readInt16BE=function(e,t){e>>>=0,t||x(e,2,this.length);const n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},s.prototype.readInt32LE=function(e,t){return e>>>=0,t||x(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},s.prototype.readInt32BE=function(e,t){return e>>>=0,t||x(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},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||x(e,4,this.length),n.read(this,e,!0,23,4)},s.prototype.readFloatBE=function(e,t){return e>>>=0,t||x(e,4,this.length),n.read(this,e,!1,23,4)},s.prototype.readDoubleLE=function(e,t){return e>>>=0,t||x(e,8,this.length),n.read(this,e,!0,52,8)},s.prototype.readDoubleBE=function(e,t){return e>>>=0,t||x(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")}}(NT);var FT,$T="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 qT(e,t){var n={seen:[],stylize:GT};return arguments.length>=3&&(n.depth=arguments[2]),arguments.length>=4&&(n.colors=arguments[3]),jT(t)?n.showHidden=t:t&&function(e,t){if(!t||!YT(t))return e;var n=Object.keys(t),r=n.length;for(;r--;)e[n[r]]=t[n[r]]}(n,t),QT(n.showHidden)&&(n.showHidden=!1),QT(n.depth)&&(n.depth=2),QT(n.colors)&&(n.colors=!1),QT(n.customInspect)&&(n.customInspect=!0),n.colors&&(n.stylize=KT),zT(n,e,n.depth)}function KT(e,t){var n=qT.styles[t];return n?"["+qT.colors[n][0]+"m"+e+"["+qT.colors[n][1]+"m":e}function GT(e,t){return e}function zT(e,t,n){if(e.customInspect&&t&&tE(t.inspect)&&t.inspect!==qT&&(!t.constructor||t.constructor.prototype!==t)){var r=t.inspect(n,e);return XT(r)||(r=zT(e,r,n)),r}var i=function(e,t){if(QT(t))return e.stylize("undefined","undefined");if(XT(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(jT(t))return e.stylize(""+t,"boolean");if(VT(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)),eE(t)&&(o.indexOf("message")>=0||o.indexOf("description")>=0))return WT(t);if(0===o.length){if(tE(t)){var a=t.name?": "+t.name:"";return e.stylize("[Function"+a+"]","special")}if(JT(t))return e.stylize(RegExp.prototype.toString.call(t),"regexp");if(ZT(t))return e.stylize(Date.prototype.toString.call(t),"date");if(eE(t))return WT(t)}var c,u,l="",h=!1,d=["{","}"];(c=t,Array.isArray(c)&&(h=!0,d=["[","]"]),tE(t))&&(l=" [Function"+(t.name?": "+t.name:"")+"]");return JT(t)&&(l=" "+RegExp.prototype.toString.call(t)),ZT(t)&&(l=" "+Date.prototype.toUTCString.call(t)),eE(t)&&(l=" "+WT(t)),0!==o.length||h&&0!=t.length?n<0?JT(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)rE(t,String(s))?o.push(HT(e,t,n,r,String(s),!0)):o.push("");return i.forEach(function(i){i.match(/^\d+$/)||o.push(HT(e,t,n,r,i,!0))}),o}(e,t,n,s,o):o.map(function(r){return HT(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 WT(e){return"["+Error.prototype.toString.call(e)+"]"}function HT(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")),rE(r,i)||(s="["+i+"]"),a||(e.seen.indexOf(c.value)<0?(a=VT(n)?zT(e,c.value,null):zT(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")),QT(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 jT(e){return"boolean"==typeof e}function VT(e){return null===e}function XT(e){return"string"==typeof e}function QT(e){return void 0===e}function JT(e){return YT(e)&&"[object RegExp]"===nE(e)}function YT(e){return"object"==typeof e&&null!==e}function ZT(e){return YT(e)&&"[object Date]"===nE(e)}function eE(e){return YT(e)&&("[object Error]"===nE(e)||e instanceof Error)}function tE(e){return"function"==typeof e}function nE(e){return Object.prototype.toString.call(e)}function rE(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function iE(){return void 0!==FT?FT:FT="foo"===function(){}.name}qT.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]},qT.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};var oE=/\s*function\s+([^\(\s]*)\s*/;function sE(e){if(tE(e)){if(iE())return e.name;var t=e.toString().match(oE);return t&&t[1]}}function aE(e){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=function(e){return cE(uE(e.actual),128)+" "+e.operator+" "+cE(uE(e.expected),128)}(this),this.generatedMessage=!0);var t=e.stackStartFunction||lE;if(Error.captureStackTrace)Error.captureStackTrace(this,t);else{var n=new Error;if(n.stack){var r=n.stack,i=sE(t),o=r.indexOf("\n"+i);if(o>=0){var s=r.indexOf("\n",o+1);r=r.substring(s+1)}this.stack=r}}}function cE(e,t){return"string"==typeof e?e.length<t?e:e.slice(0,t):e}function uE(e){if(iE()||!tE(e))return qT(e);var t=sE(e);return"[Function"+(t?": "+t:"")+"]"}function lE(e,t,n,r,i){throw new aE({message:n,actual:e,expected:t,operator:r,stackStartFunction:i})}$T(aE,Error);class hE{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 dE extends hE{isCount(){throw new Error("ExternalLayout is abstract")}}class fE extends hE{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 gE extends hE{constructor(e,t,n){if(!Array.isArray(e)||!e.reduce((e,t)=>e&&t instanceof hE,!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 pE=class extends hE{constructor(e,t){if(!(e instanceof dE&&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 dE||(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 dE&&(r=e.length),!NT.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 dE&&this.length.encode(r,t,n),r}};var mE=e=>new fE(1,e),yE=e=>new fE(4,e),wE=(e,t,n)=>new gE(e,t,n),bE=(e,t)=>new pE(e,t);const kE=(e="publicKey")=>bE(32,e),vE=(e="uint64")=>bE(8,e),SE=new tv("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"),AE=new tv("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL");new tv("So11111111111111111111111111111111111111112"),wE([yE("mintAuthorityOption"),kE("mintAuthority"),vE("supply"),mE("decimals"),mE("isInitialized"),yE("freezeAuthorityOption"),kE("freezeAuthority")]);const TE=wE([kE("mint"),kE("owner"),vE("amount"),yE("delegateOption"),kE("delegate"),mE("state"),yE("isNativeOption"),vE("isNative"),vE("delegatedAmount"),yE("closeAuthorityOption"),kE("closeAuthority")]);wE([mE("m"),mE("n"),mE("is_initialized"),kE("signer1"),kE("signer2"),kE("signer3"),kE("signer4"),kE("signer5"),kE("signer6"),kE("signer7"),kE("signer8"),kE("signer9"),kE("signer10"),kE("signer11")]);var EE=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 IE(e,t,n,r,i){const[o]=tv.findProgramAddressSync([t.toBuffer(),r.toBuffer(),e.toBuffer()],i);return o}class CE extends IT{constructor(e){super(),this.network="Solana",this.solanaBridgeAccountCache=new Map,this.galaConnectClient=e.galaConnectClient,this.galaChainWalletAddress=e.galaChainWalletAddress,HA(e.ethereumPrivateKey);const n=new t.JsonRpcProvider("https://ethereum.publicnode.com");this.ethereumWallet=new t.Wallet(e.ethereumPrivateKey,n);const r=e.solanaRpcUrl??"https://api.mainnet-beta.solana.com";let i;this.solanaConnection=new UA(r,"confirmed");try{i=EE.decode(e.solanaPrivateKeyBase58)}catch{throw H("solanaPrivateKeyBase58","base58-encoded string",e.solanaPrivateKeyBase58.slice(0,20)+"...")}if(64!==i.length)throw H("solanaPrivateKeyBase58","64 bytes when decoded",`${i.length} bytes`);this.solanaKeypair=MA.fromSecretKey(i);const o=e.solanaBridgeProgram??"AaE4dTnL75XqgUJpdxBKg6vS9sTJgBPJwBQRVhD29WwS";this.solanaBridgeProgramId=new tv(o),[this.solanaBridgeTokenAuthority]=tv.findProgramAddressSync([Buffer.from("bridge_token_authority")],this.solanaBridgeProgramId),[this.solanaBridgeConfigPda]=tv.findProgramAddressSync([Buffer.from("configv1")],this.solanaBridgeProgramId),[this.solanaNativeBridgePda]=tv.findProgramAddressSync([Buffer.from("native_sol_bridge")],this.solanaBridgeProgramId);const s=e.tokenConfigs??su;this.tokenConfigs=zA(s),this.tokenMetadataResolver=new jA({galaConnectClient:this.galaConnectClient})}async estimateFee(e,t){const n=await this.tokenMetadataResolver.getTokenMetadata(e);return Uh(await this.galaConnectClient.fetchBridgeFee({chainId:"Solana",bridgeToken:n.descriptor}))}async bridgeOut(e){return mT(e,{galaConnectClient:this.galaConnectClient,tokenMetadataResolver:this.tokenMetadataResolver,ethereumWallet:this.ethereumWallet,destinationChainId:Qc.SOLANA,destinationChain:"Solana",validateRecipientAddress:iT})}async bridgeIn(e){const{amount:t,sourcePrivateKey:n,recipientAddress:r,tokenSymbol:i}=e,o=nT(i);Oh(t,o);let s=this.solanaKeypair;if(n){let e;try{e=EE.decode(n)}catch{throw H("sourcePrivateKey","base58-encoded string",n.slice(0,20)+"...")}if(64!==e.length)throw H("sourcePrivateKey","64 bytes when decoded",`${e.length} bytes`);s=MA.fromSecretKey(e)}const a=WA(this.tokenConfigs,o,"Solana bridge"),c=await this.tokenMetadataResolver.getTokenMetadata(o),u=Ih(t,c.decimals),l=r??this.galaChainWalletAddress;return dT({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 YA(await this.galaConnectClient.getBridgeStatus(e))}getSupportedTokens(){return Array.from(this.tokenConfigs.keys())}isTokenSupported(e){return this.tokenConfigs.has(os(e))}isValidAddress(e){try{return new tv(e),!0}catch{return!1}}getWalletAddress(){return this.solanaKeypair.publicKey.toBase58()}async getSolanaTokenBalance(e,t){const n=WA(this.tokenConfigs,e,"Solana");if(n.isNative)return this.getSolanaNativeBalance(t);const r=t??this.solanaKeypair.publicKey.toBase58(),i=oT(r),o=IE(new tv(n.mintAddress),i,0,SE,AE);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:TE.decode(i.data).amount,decimals:0}}(this.solanaConnection,o,0,SE),t=n.decimals??8;return Ch(e.amount,t)}catch(t){if(A(t)&&t.message.includes("could not find")){return Ch(0n,n.decimals??8)}throw V(`Failed to fetch ${e} balance for ${r}: ${T(t)}`,`${e}Account`)}}async getSolanaNativeBalance(e){const t=oT(e??this.solanaKeypair.publicKey.toBase58()),n=await this.solanaConnection.getBalance(t,"confirmed");return Ch(BigInt(n),9)}async requestDevnetAirdrop(e=1,t){se(e,1e-5,2,"amount");const n=t?oT(t):this.solanaKeypair.publicKey,r=this.solanaConnection.rpcEndpoint;if(!r.includes("devnet"))throw V(`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(!Je(e))throw H("signature","a non-empty string");if(!/^[1-9A-HJ-NP-Za-km-z]{80,90}$/.test(e))throw H("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 tv(e.tokenConfig.mintAddress),n=Boolean(e.tokenConfig.isNative),r=n?void 0:await this.getSolanaBridgeAccounts(t),i=n?void 0:IE(t,e.keypair.publicKey,0,SE,AE),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 Sv;u.add($A.setComputeUnitPrice({microLamports:375e3}),$A.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=A(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=A(e)?e:new Error(T(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 Rh(o)}throw r??new Error("Transaction confirmation failed after max retries")}buildNativeBridgeInstruction(e,t,n,r){const i=Buffer.concat([lu.BRIDGE_OUT_NATIVE,t,n,r]);return new vv({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:Lv.programId,isSigner:!1,isWritable:!1}],data:i})}buildTokenBridgeInstruction(e,t,n,r,i,o,s){const a=Buffer.concat([lu.BRIDGE_OUT,i,o,s]);return new vv({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:Lv.programId,isSigner:!1,isWritable:!1},{pubkey:SE,isSigner:!1,isWritable:!1}],data:a})}async getSolanaBridgeAccounts(e){const t=e.toBase58(),n=this.solanaBridgeAccountCache.get(t);if(n)return n;const[r]=tv.findProgramAddressSync([Buffer.from("mint_lookup_v1"),e.toBuffer()],this.solanaBridgeProgramId),i=await this.solanaConnection.getAccountInfo(r,"confirmed");if(!i)throw V(`Mint lookup account not found for ${r.toBase58()}`,"solanaBridgeProgram");if(!i.owner.equals(this.solanaBridgeProgramId))throw V("Mint lookup account owner mismatch for Solana bridge program","solanaBridgeProgram");if(i.data.length<40)throw V("Mint lookup account data is unexpectedly short","solanaBridgeProgram");const o={mintLookup:r,tokenBridge:new tv(i.data.slice(8,40)),bridgeTokenAccount:IE(e,this.solanaBridgeTokenAuthority,0,SE,AE)};return this.solanaBridgeAccountCache.set(t,o),o}}const NE={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 BE(e){return NE[e]}const xE={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"}},_E={solanaBridgeProgram:"AaE4dTnL75XqgUJpdxBKg6vS9sTJgBPJwBQRVhD29WwS",rateLimit:12,pollInterval:15e3,pollTimeout:27e5};class PE{static normalizeGalaChainAddress(e){const t=new ht;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 V(`Invalid GalaChain address format: ${e}`,"galaChainWalletAddress");const i=t.extractHex(r);return`eth|${PE.checksumAddress(i)}`}static checksumAddress(e){const n=e.toLowerCase(),r=ut(t.keccak256(t.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=PE.normalizeGalaChainAddress(e.galaChainWalletAddress),n=e.environment??"STAGE",r=NE[n],i=xE[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??iu(n),solanaBridgeProgram:e.solanaBridgeProgram??_E.solanaBridgeProgram,rateLimit:e.rateLimit??_E.rateLimit,pollInterval:e.pollInterval??_E.pollInterval,pollTimeout:e.pollTimeout??_E.pollTimeout,galaChainWalletAddress:t,ethereumPrivateKey:e.ethereumPrivateKey,environment:n};this.config=e.solanaPrivateKey?{...o,solanaPrivateKey:e.solanaPrivateKey}:o,this.galaConnectClient=new TT({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=ru(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 CT(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:su};this.strategies.set("Solana",new CE(e))}}async resolveTokenSymbol(e,t){return br(async()=>{if(!this.bridgeableTokenService)throw V("BridgeableTokenService is required for tokenId resolution. Pass bridgeableTokenService in BridgeServiceConfig or use the SDK's bridge methods.","bridgeableTokenService");const n=Dh(e).stringified,r="Ethereum"===t?"ETHEREUM":"SOLANA",i=await this.bridgeableTokenService.getTokenByTokenId(n,r);if(!i){throw V([`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 br(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 br(async()=>{const t=await this.resolveTokenSymbol(e.tokenId,e.destinationChain),n=this.getStrategy(e.destinationChain);if(!n.isValidAddress(e.recipientAddress))throw V(`Invalid recipient address for ${e.destinationChain}: ${e.recipientAddress}`,"recipientAddress");if(!n.isTokenSupported(t))throw V(`Token ${t} is not supported for ${e.destinationChain} bridging`,"tokenSymbol");return n.bridgeOut({...e,tokenSymbol:t})},"BridgeService.bridgeOut")}async bridgeIn(e){return br(async()=>{const t=await this.resolveTokenSymbol(e.tokenId,e.sourceChain),n=this.getStrategy(e.sourceChain);if(!n.isTokenSupported(t))throw V(`Token ${t} is not supported for ${e.sourceChain} bridging`,"tokenSymbol");return n.bridgeIn({...e,tokenSymbol:t})},"BridgeService.bridgeIn")}async getBridgeStatus(e,t){return br(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=A(e)?e:new Error(T(e))}const i=this.strategies.get("Solana");if(i)try{return await i.getStatus(e)}catch(e){r=A(e)?e:new Error(T(e))}const o=r?` (last error: ${r.message})`:"";throw X(`Unable to get status for transaction ${e}${o}`,e)},"BridgeService.getBridgeStatus")}async waitForBridgeCompletion(e,t){return br(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 X(`Unable to wait for transaction ${e}: no suitable strategy found`,e)},"BridgeService.waitForBridgeCompletion")}getSupportedBridgeTokens(e){const t=[],n=ru(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 su){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 br(async()=>fT(this.strategies).getEthereumTokenBalance(e,t),"BridgeService.getEthereumTokenBalance")}async getEthereumNativeBalance(e){return br(async()=>fT(this.strategies).getEthereumNativeBalance(e),"BridgeService.getEthereumNativeBalance")}async getSolanaTokenBalance(e,t){return br(async()=>gT(this.strategies).getSolanaTokenBalance(e,t),"BridgeService.getSolanaTokenBalance")}async getSolanaNativeBalance(e){return br(async()=>gT(this.strategies).getSolanaNativeBalance(e),"BridgeService.getSolanaNativeBalance")}async fetchEthereumWalletTokenBalance(e,t){return br(async()=>{const n=fT(this.strategies),r=uT(ru(this.config.environment),e,"Ethereum"),i=pT(t,n);return aT(r,await n.getEthereumTokenBalance(e,i))},"BridgeService.fetchEthereumWalletTokenBalance")}async fetchEthereumWalletNativeBalance(e){return br(async()=>{const t=fT(this.strategies),n=pT(e,t);return sT("ETH",await t.getEthereumNativeBalance(n),18)},"BridgeService.fetchEthereumWalletNativeBalance")}async fetchSolanaWalletTokenBalance(e,t){return br(async()=>{const n=gT(this.strategies),r=uT(su,e,"Solana"),i=pT(t,n);return cT(r,await n.getSolanaTokenBalance(e,i))},"BridgeService.fetchSolanaWalletTokenBalance")}async fetchSolanaWalletNativeBalance(e){return br(async()=>{const t=gT(this.strategies),n=pT(e,t);return sT("SOL",await t.getSolanaNativeBalance(n),9)},"BridgeService.fetchSolanaWalletNativeBalance")}async requestSolanaDevnetAirdrop(e,t){return br(async()=>gT(this.strategies).requestDevnetAirdrop(e,t),"BridgeService.requestSolanaDevnetAirdrop")}async getSolanaTransactionStatus(e){return br(async()=>gT(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 br(async()=>fT(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 br(async()=>{const t=fT(this.strategies),n=pT(e,t),r=ru(this.config.environment),[i,...o]=await Promise.all([t.getEthereumNativeBalance(n),...r.map(async e=>aT(e,await t.getEthereumTokenBalance(e.symbol,n)))]);return{address:n,native:sT("ETH",i,18),tokens:o,timestamp:Date.now()}},"BridgeService.fetchEthereumWalletAllBalances")}async fetchSolanaWalletAllBalances(e){return br(async()=>{const t=gT(this.strategies),n=pT(e,t),[r,...i]=await Promise.all([t.getSolanaNativeBalance(n),...su.map(async e=>cT(e,await t.getSolanaTokenBalance(e.symbol,n)))]);return{address:n,native:sT("SOL",r,9),tokens:i,timestamp:Date.now()}},"BridgeService.fetchSolanaWalletAllBalances")}getStrategy(e){const t=this.strategies.get(e);if(!t)throw V(`Bridging to ${e} is not configured. `+("Solana"===e?"Please provide solanaPrivateKey in config.":"Please check your configuration."),`${e.toLowerCase()}PrivateKey`);return t}}class RE extends Error{constructor(e,t){super(e),this.cause=t,this.name="WebSocketError"}}class DE 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 LE(e,t){if(Ze(e))throw new RE(`Invalid WebSocket response received for transaction ${t}: response is null or undefined`);if("object"!=typeof e)throw new RE(`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 RE(`Invalid WebSocket response received for transaction ${t}: missing status field`)}function OE(e,t,n,r){LE(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 RE(`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 UE="5.0.4-beta.0";class ME{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&&!Je(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(Je(t))return t}return null}extractPositionId(e){const t=["positionId","position_id","tokenId","nftId"];for(const n of t){const t=e[n];if(Je(t))return t}return null}extractPoolHash(e){const t=["poolHash","pool_hash","poolId","pool"];for(const n of t){const t=e[n];if(Je(t))return t}return null}extractPoolAlias(e){const t=["poolAlias","pool_alias"];for(const n of t){const t=e[n];if(Je(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(Je(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(Je(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(Je(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 Je(n)&&Je(r)&&Je(i)&&Je(o)&&Je(s)&&Je(a)?{collection:n,category:r,type:i,additionalKey:o,quantity:s,owner:a}:void 0}}class FE{constructor(e){this.wallet=e.wallet;let t=null,n="STAGE";if(e.env?(n=e.env,t=BE(e.env)):e.baseUrl?.includes("prod")?(n="PROD",t=BE("PROD")):(n="STAGE",t=BE("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?FE.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR:this.parseSlippageToleranceFactor(e.slippageToleranceFactor),this.maxAcceptableReverseBondingCurveFeeSlippageFactor=void 0===e.maxAcceptableReverseBondingCurveFeeSlippageFactor?FE.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR:this.parseFeeSlippageFactor(e.maxAcceptableReverseBondingCurveFeeSlippageFactor),this.calculateAmountMode=e.calculateAmountMode||FE.DEFAULT_CALCULATE_AMOUNT_MODE,this.pricingConcurrency=e.pricingConcurrency||5,this.galaChainAddressOverride=e.galaChainAddress,this.auth=new St({wallet:e.wallet,messagePrefix:"Create a GalaChain Wallet"}),this.jwtAuth=new Tt,e.accessToken){const t=e.accessTokenExpiresIn??86400;this.jwtAuth.setToken(e.accessToken,t)}this.http=new Ar(this.auth,this.config),this.sessionAuth=new vr(this.http,this.auth,this.jwtAuth,e.debug||!1),this.galaChainHttp=new Ar(this.auth,{...this.config,baseUrl:this.config.galaChainBaseUrl}),this.bundleHttp=new Ar(this.auth,{...this.config,baseUrl:this.config.bundleBaseUrl}),this.dexApiHttp=new Ar(this.auth,{...this.config,baseUrl:this.config.dexApiBaseUrl}),this.dexBackendHttp=new Ar(this.auth,{...this.config,baseUrl:this.config.dexBackendBaseUrl}),this.galaChainPublicAxios=v(this.config.galaChainBaseUrl,this.config.timeout||3e4),this.cache=new wc(e.debug||!1),this.launchpadService=new Ms(this.http,this.jwtAuth),this.tokenResolverService=new oc(this.launchpadService.poolService),this.launchpadAPI=new Th(this.http,this.tokenResolverService,this.logger,this.bundleHttp,this.galaChainHttp,this.dexApiHttp,this.calculateAmountMode),this.galaChainService=new $a(this.galaChainHttp,e.wallet,this.tokenResolverService,e.debug||!1,this.galaChainPublicAxios),this.dexService=new qa(this.dexBackendHttp,this.cache,this.galaChainService,e.debug||!1),this.bundleService=new Ja(this.bundleHttp,this.tokenResolverService,this.config.debug||!1,e.wallet,e.wallet?this.getAddress():void 0,this.slippageToleranceFactor,this.maxAcceptableReverseBondingCurveFeeSlippageFactor),this.websocketService=new ic({url:this.config.webSocketUrl},this.config.debug),this.priceHistoryService=new sc(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 bc(this.dexBackendHttp,this.config.dexBackendBaseUrl,this.gswapService,this.pricingConcurrency,e.debug||!1)}createOverrideSdk(e){if(!Je(e))throw V("Invalid privateKey: must be a non-empty string","privateKey");if(!e.match(/^0x[a-fA-F0-9]{64}$/))throw V('Invalid privateKey format: must be "0x" followed by 64 hexadecimal characters',"privateKey");const n=new t.Wallet(e),r={...this.config,wallet:n};return new FE(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 P("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:mc.GAS_FEE}}getVersion(){return UE}getUrlByTokenName(e){const t=this.config.launchpadFrontendUrl;if(!t)throw V("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}=rt(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(C(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=is((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: ${T(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(Er(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 vt}),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 PE({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 Lc(this.dexApiHttp,this.config.debug??!1)),this._bridgeableTokenService}getWrappableTokenService(){return this._wrappableTokenService||(this._wrappableTokenService=new Mc(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 TT({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 ku({galaConnectClient:this.getGalaConnectClient(),wrappableTokenService:this.getWrappableTokenService(),...e&&{walletAddress:this.getAddress(),wallet:e}})}return this._wrapService}getStreamingService(){return this._streamingService||(this._streamingService=new Mu(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1)),this._streamingService}getStreamChatService(){return this._streamChatService||(this._streamChatService=new zu(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1)),this._streamChatService}getBanService(){return this._banService||(this._banService=new nl(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1)),this._banService}getTokenBanService(){return this._tokenBanService||(this._tokenBanService=new cl(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1)),this._tokenBanService}getApiKeyService(){return this._apiKeyService||(this._apiKeyService=new ml(this.http,this.jwtAuth,this.config.debug??!1)),this._apiKeyService}getModeratorService(){return this._moderatorService||(this._moderatorService=new xl(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1)),this._moderatorService}getFlagService(){return this._flagService||(this._flagService=new Hl(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1)),this._flagService}getOverseerService(){return this._overseerService||(this._overseerService=new ih(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1)),this._overseerService}getCommentService(){return this._commentService||(this._commentService=new oh(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1)),this._commentService}getContentReactionService(){return this._contentReactionService||(this._contentReactionService=new ah(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1)),this._contentReactionService}getCommentsService(){return this._commentsService||(this._commentsService=new ch(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1)),this._commentsService}getChatMessagesService(){return this._chatMessagesService||(this._chatMessagesService=new fh(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 Hu({url:this.config.streamWebSocketUrl},this.config.debug??!1)}return this._streamWebSocketService}getStreamingEventService(){return this._streamingEventService||(this._streamingEventService=new ju(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===Is(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 vt}),n=t(e.address);if(e.tokenId){const{normalizeToTokenInstanceKey:t}=await Promise.resolve().then(function(){return sa}),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=ss(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:Gs(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),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 X("No transaction ID returned from buy operation");return this.waitForConfirmation(n,t=>OE(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 X("No transaction ID returned from sell operation");return this.waitForConfirmation(n,t=>OE(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=>{LE(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 RE(`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 vt}),n=t(e)||this.getAddress();return this.launchpadService.fetchProfile(n)}async fetchReferralUrl(){this.validateWallet();const e=this.getAddress();return await this.dexApiHttp.get(Mt,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 vt}),r=n(e.address);if(!r)throw new P(`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 R("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 es((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 vt}),r=n(e.address);if(!r)throw new P(`Invalid address format: "${e.address}". Expected formats: eth|0x..., 0x..., or client|...`);t=r}else t=this.getAddress();const n=await this.dexApiHttp.get($t,void 0,{"x-wallet-address":t});if(!n||"number"!=typeof n.referralCount||!n.rewardTotals)throw new R(`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 vt}),r=n(e.address);if(!r)throw new P(`Invalid address format: "${e.address}". Expected formats: eth|0x..., 0x..., or client|...`);t=r}else t=this.getAddress();const n=await this.dexApiHttp.post(qt,{address:t});if(!n||"boolean"!=typeof n.exists)throw new R(`Unexpected API response: expected { exists, walletAlias? }, got ${JSON.stringify(n)}`);if(n.exists){if(!n.walletAlias)throw new R(`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 vt}),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 vt}),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 vt}),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 vt}),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 vt}),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 vt}),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 vt});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{se(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 V("baseUrl is required in configuration","baseUrl");if(!this.config.webSocketUrl)throw V("webSocketUrl is required in configuration","webSocketUrl");try{new URL(this.config.baseUrl)}catch{throw V(`Invalid baseUrl format: ${this.config.baseUrl}`,"baseUrl")}try{new URL(this.config.webSocketUrl)}catch{throw V(`Invalid webSocketUrl format: ${this.config.webSocketUrl}`,"webSocketUrl")}if(this.config.galaChainBaseUrl)try{new URL(this.config.galaChainBaseUrl)}catch{throw V(`Invalid galaChainBaseUrl format: ${this.config.galaChainBaseUrl}`,"galaChainBaseUrl")}if(this.config.bundleBaseUrl)try{new URL(this.config.bundleBaseUrl)}catch{throw V(`Invalid bundleBaseUrl format: ${this.config.bundleBaseUrl}`,"bundleBaseUrl")}if(this.config.launchpadFrontendUrl)try{new URL(this.config.launchpadFrontendUrl)}catch{throw V(`Invalid launchpadFrontendUrl format: ${this.config.launchpadFrontendUrl}`,"launchpadFrontendUrl")}}parseSlippageToleranceFactor(e){const t=De("string"==typeof e||"number"==typeof e?e:String(e),FE.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR);return t<0||t>1?(this.logger.warn(`Invalid slippage tolerance factor: ${e}, using default: ${FE.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR}`),FE.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR):t}parseFeeSlippageFactor(e){const t=De("string"==typeof e||"number"==typeof e?e:String(e),FE.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR);return t<0||t>1?(this.logger.warn(`Invalid fee slippage factor: ${e}, using default: ${FE.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR}`),FE.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 DE(e,n.status,n.message);let r;try{r=t(n)}catch(t){if(t instanceof RE)throw t;throw new RE(`Failed to transform WebSocket response for transaction ${e}`,A(t)?t:new Error(T(t)))}return this.logger.debug(`Transaction confirmed: ${e}`,r),r}catch(t){if(this.logger.error(`Transaction confirmation failed: ${e}`,t),t instanceof DE||t instanceof RE)throw t;throw new RE(`WebSocket confirmation failed for transaction ${e}`,A(t)?t:new Error(T(t)))}}async warmCacheFromPools(e){if(!e||!Array.isArray(e))return;const{extractMetadataFromPoolData:t,isValidPoolForCaching:n}=await Promise.resolve().then(function(){return HE});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=T(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=T(e);c>=5?this.logger.error(`Polling for new launchpad tokens failed ${c} consecutive times. Last error: ${t}. Continuing to retry...`):c>1?this.logger.warn(`Error polling for new launchpad tokens (attempt ${c}/5): ${t}`):this.logger.debug(`Error polling for new launchpad tokens: ${t}`)}if(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=$e("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 Sc.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=Sc.parsePoolKey(e);if(!t)return null;const n=Xs(t.token0)?Vs(t.token0).collection:t.token0,r=Xs(t.token1)?Vs(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 V("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: ${T(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: ${T(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<FE.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS)return e++,void(r=setTimeout(()=>s(),FE.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS));if(!o&&e>=FE.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS){const e=new Error(`WebSocket not available after ${FE.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS*FE.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 V("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: ${T(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: ${T(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<FE.DEX_POOL_SOCKET_WAIT_ATTEMPTS)return e++,void(r=setTimeout(()=>i(),FE.DEX_POOL_SOCKET_POLL_INTERVAL_MS));if(!s&&e>=FE.DEX_POOL_SOCKET_WAIT_ATTEMPTS){const e=new Error(`WebSocket not available after ${FE.DEX_POOL_SOCKET_WAIT_ATTEMPTS*FE.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 V("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=Sc.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 Bc(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: ${T(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 V("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 ME(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: ${T(e)}`)})}catch(e){this.logger.warn(`Error in liquidity event callback: ${T(e)}`)}}}catch(e){this.logger.warn(`Error processing DEX liquidity broadcast: ${T(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: ${T(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<FE.DEX_POOL_SOCKET_WAIT_ATTEMPTS)return e++,void(r=setTimeout(()=>i(),FE.DEX_POOL_SOCKET_POLL_INTERVAL_MS));if(!a&&e>=FE.DEX_POOL_SOCKET_WAIT_ATTEMPTS){const e=new Error(`WebSocket not available after ${FE.DEX_POOL_SOCKET_WAIT_ATTEMPTS*FE.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&&Ns(e.token0,t.tokenFilter),r=!!e.token1&&Ns(e.token1,t.tokenFilter);if(!n&&!r)return!1}if(t.pairTokens){const[n,r]=t.pairTokens,i=e.token0||"",o=e.token1||"",s=Ns(i,n)&&Ns(o,r),a=Ns(i,r)&&Ns(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)}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")}}FE.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR=.15,FE.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR=.01,FE.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY=mc.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY,FE.DEFAULT_CALCULATE_AMOUNT_MODE=Sh.LOCAL,FE.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS=30,FE.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS=100,FE.DEX_POOL_SOCKET_WAIT_ATTEMPTS=30,FE.DEX_POOL_SOCKET_POLL_INTERVAL_MS=100;class $E{static generateWallet(){try{const e=t.Wallet.createRandom();if(!e.mnemonic?.phrase)throw W("mnemonic","Mnemonic phrase");const n=this.toGalaAddress(e.address);return{privateKey:e.privateKey,address:e.address,galaAddress:n,mnemonic:e.mnemonic.phrase,wallet:new t.Wallet(e.privateKey)}}catch(e){if("undefined"!=typeof process&&"test"===process.env.NODE_ENV){const e=`test-wallet-${Date.now()}-${++this.testCounter}`,n="0x"+Buffer.from(e).toString("hex").padStart(64,"1").slice(0,64),r=new t.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 e}}static fromPrivateKey(e){const n=new t.Wallet(e),r=this.toGalaAddress(n.address);return{privateKey:n.privateKey,address:n.address,galaAddress:r,mnemonic:"",wallet:n}}static fromMnemonic(e,n=0){try{const r=t.Mnemonic.fromPhrase(e),i=t.HDNodeWallet.fromMnemonic(r,`m/44'/60'/0'/0/${n}`),o=new t.Wallet(i.privateKey),s=this.toGalaAddress(o.address);return{privateKey:o.privateKey,address:o.address,galaAddress:s,mnemonic:e,wallet:o}}catch(r){if("undefined"!=typeof process&&"test"===process.env.NODE_ENV){const r=`test-mnemonic-index-${n}-${e}`,i="0x"+Buffer.from(r).toString("hex").padStart(64,"1").slice(0,64),o=new t.Wallet(i),s=this.toGalaAddress(o.address);return{privateKey:o.privateKey,address:o.address,galaAddress:s,mnemonic:e,wallet:o}}throw r}}static toGalaAddress(e){const t=ft(e);if(!/^[a-fA-F0-9]{40}$/.test(t))throw H("address","a valid Ethereum address (40 hex characters)");return`eth|${t}`}static toEthereumAddress(e){try{return pt(e)}catch(t){const n=T(t);if(n.includes("required")||!e?.startsWith("eth|"))throw W("galaAddress","Gala address starting with eth|");if(n.includes("Invalid backend"))throw H("galaAddress","Gala format (eth|{40-hex-chars})");throw t}}static isValidEthereumAddress(e){try{const t=ft(e);return/^[a-fA-F0-9]{40}$/.test(t)}catch{return!1}}static isValidGalaAddress(e){return!!e&&"backend"===kt(e)}static generateMultipleWallets(e=1){se(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 qE(e){if(void 0===e)return $E.generateWallet();const t=e.trim();if(!Je(t))throw H("input","a non-empty string");if(function(e){const t=ft(e);return/^[a-fA-F0-9]{64}$/.test(t)}(t))return $E.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 $E.fromMnemonic(t);throw H("input","a private key (64 hex characters) or mnemonic (12/24 words)","Wallet input")}$E.testCounter=0;function KE(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 GE(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 zE{static fastValidation(e,t,n,r=zE.DEFAULT_CONFIG){const i=Date.now();let o=!0;try{const s=bo(e.sqrtPrice),a=bo(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=bo(e.liquidity),u=bo(t.liquidity);if(!Bo(c)){const e=Uo(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:ko(e.times(100),2)})}const l=bo(e.feeGrowthGlobal0),h=bo(t.feeGrowthGlobal0),d=bo(e.feeGrowthGlobal1),f=bo(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=bo(e.protocolFeesToken0),p=bo(t.protocolFeesToken0),m=bo(e.protocolFeesToken1),y=bo(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=Xe(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=zE.DEFAULT_CONFIG){const r=Date.now(),i=[];let o=0;try{if(t.actualSqrtPrice){const r=bo(e.sqrtPrice),s=bo(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=bo(e.sqrtPrice),a=Uo(s,Io()),c=u.sqrtPriceToTick(a),l=e.tick??0,h=Math.abs(c-l);h>n.maxTickDrift&&i.push(`Tick/price mismatch: tick=${l}, calculated=${c}, drift=${h}`);const d=bo(e.feeGrowthGlobal0),f=bo(e.feeGrowthGlobal1),g=bo(e.liquidity);try{Lo(d,f,g)}catch(e){i.push(e.message)}const p=0===i.length,m=!p||o>100*n.maxDriftThreshold,y=Xe(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: ${T(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=bo(t.pool.sqrtPrice),c=bo(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=bo(t.pool.liquidity),h=bo(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=Xe(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: ${T(t)}`])}}static calculateDriftPercentage(e,t){if(Bo(t))return this.logger.warn("Cannot calculate drift: actual value is zero"),1/0;return Uo(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}}zE.logger=new We({debug:!1,context:"PoolStateValidator"}),zE.DEFAULT_CONFIG={maxDriftThreshold:.001,maxLiquidityChangePct:.5,maxTickDrift:1,maxTickCountDriftPct:.1,maxPriceDriftPct:.001,maxLiquidityDriftPct:.01};class WE extends fs{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??o.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=zE.DEFAULT_CONFIG,this.pool=e.pool,this.tickDataMap=e.tickDataMap,this.metadata={lastFullRefetch:Date.now(),swapsSinceRefetch:0,cumulativeDrift:0,processedTransactions:[],stateHash:WE.calculatePoolStateHash(this.pool)};if(!zE.fastValidation(this.pool,this.pool,{transactionId:"init",timestamp:Date.now(),amountSpecified:"0",zeroForOne:!1,exactInput:!0},this.validationConfig)&&this.config.strictValidation)throw new P("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 L(`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=Ic.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(!zE.fastValidation(t.pool,r.updatedPool,e,this.validationConfig)&&this.config.strictValidation)throw new P("Swap validation failed","swapResult","VALIDATION_FAILED");if(e.actualAmount0&&e.actualAmount1&&e.actualSqrtPrice){const t=bo(e.actualAmount0),n=bo(e.actualAmount1),i=r.amount0.minus(t).abs(),o=r.amount1.minus(n).abs(),s=Uo(i,t.abs(),bo(0)).times(100).toNumber(),a=Uo(o,n.abs(),bo(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=WE.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=WE.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=T(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:bo(0),amount1:bo(0),feeAmount0:bo(0),feeAmount1:bo(0),ticksCrossed:[],metadata:{calculationTimeMs:Xe(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:WE.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 HE=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}});e.ACCESS_SOURCE=Pu,e.ACTIVE_USER_TYPE=Vu,e.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"},e.API_KEY_ROLE=ul,e.API_KEY_ROLES=ll,e.API_KEY_ROLE_HIERARCHY=pl,e.AddressFormatter=ht,e.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 FE(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 FE(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: ${T(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: ${T(e)}`)}return{ready:0===n.length&&i.connectionHealthy,sdk:e,wallet:t||$E.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?$E.fromPrivateKey(e):$E.generateWallet()}return"generate"===e?$E.generateWallet():$E.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}},e.AuthError=S,e.BAN_DURATIONS={ONE_HOUR:3600,ONE_DAY:86400,ONE_WEEK:604800,ONE_MONTH:2592e3},e.BRIDGE_CONTRACT_ABI=uu,e.BRIDGE_TOKEN_METADATA=au,e.BaseBridgeStrategy=IT,e.BridgeRateLimiter=Eh,e.BurnError=Pa,e.CALCULATION_MODES=Sh,e.CHAIN_IDS=Qc,e.COMPOSITE_POOL_FETCH_CONCURRENCY=5,e.CONTENT_REACTION_TYPES=sh,e.CONTENT_TYPE_LABELS=Ml,e.CROSS_RATE_TYPED_DATA_TYPES=yu,e.ChatMessagesService=fh,e.ConfigurationError=D,e.DEFAULT_ETHEREUM_BRIDGE_CONTRACT=Yc,e.DEFAULT_ETHEREUM_RPC_URL="https://ethereum.publicnode.com",e.DEFAULT_ETHEREUM_TOKENS=ou,e.DEFAULT_POLL_INTERVAL_MS=15e3,e.DEFAULT_POLL_TIMEOUT_MS=27e5,e.DEFAULT_PRICING_CONCURRENCY=5,e.DEFAULT_RATE_LIMIT_RPS=12,e.DEFAULT_SOLANA_BRIDGE_PROGRAM="AaE4dTnL75XqgUJpdxBKg6vS9sTJgBPJwBQRVhD29WwS",e.DEFAULT_SOLANA_RPC_URL="https://api.mainnet-beta.solana.com",e.DEFAULT_SOLANA_TOKENS=su,e.DEFAULT_WEBSOCKET_RECONNECT_ATTEMPTS=5,e.DexPoolNotFoundError=K,e.DexQuoteError=q,e.ERC20_ABI=cu,e.ERROR_CODES=_,e.ETHEREUM_BRIDGE_CONTRACT_SEPOLIA=Zc,e.ETHEREUM_TOKENS_PROD=tu,e.ETHEREUM_TOKENS_STAGE=nu,e.EXTENDED_STREAM_ROLE=_u,e.EthereumBridgeStrategy=CT,e.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}},e.FLAG_ACTION_LABELS=Ul,e.FLAG_DETAILS_MAX_LENGTH=500,e.FLAG_REASON_LABELS=Ll,e.FLAG_STATUS_LABELS=Ol,e.FileValidationError=Ls,e.GALACHAIN_CHANNELS=Jc,e.GALACONNECT_PRODUCTION_URL=eu,e.GALA_BRIDGE_TYPED_DATA_DOMAIN=hu,e.GALA_DECIMALS=8,e.GALA_TOKEN_CLASS_KEY={collection:"GALA",category:"Unit",type:"none",additionalKey:"none"},e.GSwapAssetError=F,e.GSwapAssetService=class extends fs{constructor(e){super(e.debugMode||!1),this.dexBackendBaseUrl=e.dexBackendBaseUrl,e.dexBackendHttp?this.dexBackendHttp=e.dexBackendHttp:this.dexBackendHttp=v(e.dexBackendBaseUrl,3e4)}parseTokenFlexible(e){try{return js(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=yr(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: ${T(t)}`,t,e)}}async getAllUserAssets(e){try{this.logger.debug("Fetching all user assets",{walletAddress:e});return(await es(async(t,n)=>{const r=await this.getUserAssets(e,n,t);return{items:r.assets,page:t,limit:n,total:r.count,totalPages:Qo(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: ${T(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=yr(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: ${T(e)}`,e)}}async fetchAllAvailableDexTokens(e={}){try{this.logger.debug("Fetching all available DEX tokens",e);return(await es(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:Qo(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: ${T(e)}`,e)}}},e.GSwapLiquidityMutationService=class extends fs{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 ca,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)=>br(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:T(t),operationType:n,transactionId:e}),t})}}async sendAddLiquidityToBundler(e){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 br(async()=>{const n=`galaswap - operation - ${s.v4()}-${Date.now()}-${e.owner}`,r={token0:e.token0,token1:e.token1,fee:e.fee,owner:e.owner,tickLower:e.tickLower,tickUpper:e.tickUpper,amount0Desired:e.amount0Desired,amount1Desired:e.amount1Desired,amount0Min:e.amount0Min,amount1Min:e.amount1Min,positionId:"",uniqueKey:n},i=new t.ethers.Wallet(this.privateKey),o={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,o,u),h={...u,signature:l,types:o,domain:a},d=this.buildLiquidityStringsInstructions(e.token0,e.token1,e.fee,e.owner),f=yr(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 L("Bundler response does not contain transaction ID",void 0,"INVALID_RESPONSE");return g},"Failed to send AddLiquidity to bundler",this.logger)}async sendRemoveLiquidityToBundler(e,n,r,i,o,a,c,u,l){if(!this.privateKey)throw new D("RemoveLiquidity requires wallet (full-access mode)","privateKey");return br(async()=>{const h=new t.ethers.Wallet(this.privateKey),d=await h.getAddress(),f=`galaswap - operation - ${s.v4()}-${Date.now()}-${d}`,g={tickLower:e,tickUpper:n,amount:r,token0:i,token1:o,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,o,a,d),S=yr(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 L("Bundler response does not contain transaction ID",void 0,"INVALID_RESPONSE");return A},"Failed to send RemoveLiquidity to bundler",this.logger)}async sendCollectPositionFeesToBundler(e,n,r,i,o,a,c,u){if(!this.privateKey)throw new D("CollectPositionFees requires wallet (full-access mode)","privateKey");return br(async()=>{const l=new t.ethers.Wallet(this.privateKey),h=await l.getAddress(),d=`galaswap - operation - ${s.v4()}-${Date.now()}-${h}`,f={token0:e,token1:n,fee:r,amount0Requested:i,amount1Requested:o,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(e,n,r,h),v=yr(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 L("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 br(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=js(t),i=js(n),o=(await this.gatewayClient.getPoolData({token0:r,token1:i,fee:e.fee})).tickSpacing,s=bo(e.minPrice),a=bo(e.maxPrice),c=Math.floor(To(s)),u=Math.ceil(To(a)),l=Mo(c,o),h=Mo(u,o),d=this.getWalletAddress();if(!d)throw new D("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:T(e)}),new $(`${t}: ${T(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 br(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=js(t),i=js(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:T(e)}),new $(`${t}: ${T(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 br(async()=>{this.logger.debug("Removing liquidity via bundler",{token0:e.token0,token1:e.token1,liquidity:e.liquidity});const t=bo(e.liquidity);try{Lo(t)}catch(t){const n=`Invalid liquidity value: "${e.liquidity}". Must be a valid number.`;throw this.logger.error(n,{error:T(t)}),new P(n,"liquidity","INVALID_VALUE")}if(Bo(t))throw new P("Cannot remove zero liquidity from position.","liquidity","ZERO_VALUE");const n="string"==typeof e.token0?js(e.token0):e.token0,r="string"==typeof e.token1?js(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:T(e)}),new $(`${t}: ${T(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 br(async()=>{if(e.ownerAddress&&e.positionId&&!e.token0)throw new P("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 P("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?js(e.token0):e.token0,n="string"==typeof e.token1?js(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:T(e)}),new $(`${t}: ${T(e)}`,e,"COLLECT_FAILED")})}},e.GSwapLiquidityQueryService=class extends fs{constructor(e){super(e.debugMode||!1),this.gatewayClient=e.gatewayClient,this.galaChainBaseUrl=e.galaChainBaseUrl,this.calculationService=e.calculationService,this.tokenConverter=new ca}convertTokenPair(e,t){return{gswapToken0:this.tokenConverter.toLaunchpadFormat(e),gswapToken1:this.tokenConverter.toLaunchpadFormat(t)}}parseTokenFlexible(e){try{return js(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:Ue(a,3e3),tickLower:Ue(c,0),tickUpper:Ue(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=fc(n),o=fc(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 $("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:T(e)}),new $(`Failed to fetch liquidity position: ${T(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 $("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:T(e)}),new $(`Failed to fetch swap position: ${T(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=fc(t),i=fc(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:T(e)}),new $(`Failed to estimate liquidity removal: ${T(e)}`,e,"ESTIMATE_FAILED")}}},e.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 P(`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 P(`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 P(`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=Io();return Uo(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=u.tickToSqrtPrice(t),i=u.tickToSqrtPrice(n);return u.liquidity0(e,r,i)},"calculateLiquidityFromAmount0 failed",this.logger)}calculateLiquidityFromAmount1(e,t,n){return kr(()=>{const r=u.tickToSqrtPrice(t),i=u.tickToSqrtPrice(n);return u.liquidity1(e,r,i)},"calculateLiquidityFromAmount1 failed",this.logger)}calculateAmount0FromLiquidity(e,t,n){return kr(()=>{const r=u.tickToSqrtPrice(t),i=u.tickToSqrtPrice(n);return u.getAmount0Delta(r,i,e)},"calculateAmount0FromLiquidity failed",this.logger)}calculateAmount1FromLiquidity(e,t,n){return kr(()=>{const r=u.tickToSqrtPrice(t),i=u.tickToSqrtPrice(n);return u.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=u.tickToSqrtPrice(r),s=u.tickToSqrtPrice(e),a=u.tickToSqrtPrice(i),c=u.getLiquidityForAmounts(bo(t),bo(n),o,s,a),l=u.getAmountsForLiquidity(c,s,o,a),h=l[0],d=l[1],f=bo(t),g=bo(n);Bo(bo(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=Uo(h,d,bo(0));return{amount0:ko(h),amount1:ko(d),liquidity:ko(c),ratio:ko(p),utilizationPercent:{amount0:ko(Ro(Uo(h,f),100),2),amount1:ko(Ro(Uo(d,g),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=[],u=[500,3e3,1e4];let l;u.includes(e)||a.push(`Invalid fee tier: ${e}. Must be one of: ${u.join(", ")}`);try{l=kr(()=>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=bo(r),d=bo(i);if(h.isNaN()||d.isNaN())a.push("Amounts must be valid numbers");else try{kr(()=>Lo(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){bo(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 W("minPrice","Minimum price");if(!t)throw W("maxPrice","Maximum price");const r=this.getTickSpacing(n),i=bo(e),o=bo(t);ue(e,t,"priceRange");const s=Le(Math.floor(To(i)),0),a=Le(Math.ceil(To(o)),0),c=Le(Mo(s,r),0),u=Le(Mo(a,r),0),l=Le(Math.pow(1.0001,c),0===c?1:NaN),h=Le(Math.pow(1.0001,u),0===u?1:NaN),d=bo(l),f=bo(h);return{tickLower:c,tickUpper:u,tickSpacing:r,requestedMinPrice:e,requestedMaxPrice:t,actualMinPrice:d.toFixed(8),actualMaxPrice:f.toFixed(8),priceDeviation:{minPriceDeviation:Ro(Uo(d.minus(i),i),100).toFixed(4),maxPriceDeviation:Ro(Uo(f.minus(o),o),100).toFixed(4)}}}calculatePriceForTicks(e,t){const n=Le(Math.pow(1.0001,e),1),r=Le(Math.pow(1.0001,t),1),i=bo(n),o=bo(r);return{tickLower:e,tickUpper:t,minPrice:i.toFixed(8),maxPrice:o.toFixed(8),priceRange:`${i.toFixed(4)} - ${o.toFixed(4)}`,tickSpread:Le(t-e,0)}}calculateExecutionPrice(e,t){if(!e)throw W("inputAmount","Input amount");if(!t)throw W("outputAmount","Output amount");return kr(()=>{const n=bo(e);return ko(Uo(bo(t),n,bo("0")))},"calculateExecutionPrice failed",this.logger)}},e.GSwapPoolError=M,e.GSwapPoolQueryService=class extends fs{constructor(e){super(e.debugMode||!1),this.gatewayClient=e.gatewayClient,this.galaChainBaseUrl=e.galaChainBaseUrl,this.calculationService=e.calculationService,this.tokenConverter=new ca}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=js(r),s=js(i),a=await this.gatewayClient.getPoolData({token0:o,token1:s,fee:n}),c=this.calculationService.calculatePriceFromSqrtPriceX96(bo(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 M(`Failed to get pool data: ${T(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=bo(0),s=0;for(const a of i)try{const e=js(n),t=js(r),i=await this.gatewayClient.getPoolData({token0:e,token1:t,fee:a});i&&(o=o.plus(bo(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 M(`Failed to fetch pool info: ${T(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?js(e):e,i="string"==typeof t?js(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 M(`Failed to fetch pool slot0 data: ${T(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=bo(r.currentPrice);return{tokenA:e,tokenB:t,feeTier:n,price:i.toFixed(),invertedPrice:Eo(i,!0),tick:r.tick,liquidity:r.liquidity}}catch(n){throw this.logger.error("Failed to calculate spot price",n),new M(`Failed to calculate spot price: ${T(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=bo(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 M(`Failed to fetch position current price: ${T(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}},e.GSwapQuoteError=O,e.GSwapSwapError=U,e.GSwapSwapService=class extends fs{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 ca}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=bo(e),r=bo(t);return ko(Uo(r,n,bo("0")))}catch(n){return this.logger.warn("Failed to calculate execution price",{inputAmount:e,outputAmount:t,error:T(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(e){return br(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(e.feeTier))throw new P(`Invalid fee tier ${e.feeTier}. Must be one of: ${n.join(", ")}`,"feeTier","INVALID_FEE_TIER");this.logger.debug("Sending Swap to bundler",{fromToken:"string"==typeof e.fromToken?e.fromToken:e.fromToken?.type??"unknown",toToken:"string"==typeof e.toToken?e.toToken:e.toToken?.type??"unknown",inputAmount:e.inputAmount,minOutput:e.minOutput,feeTier:e.feeTier});let r=e.fromToken,i=e.toToken;"string"==typeof r&&(r=js(r)),"string"==typeof i&&(i=js(i));const o=Gs(r),a=Gs(i),c=o<a?[r,i,o,a]:[i,r,a,o],[u,l,h,d]=c,f=Gs("string"==typeof e.fromToken?js(e.fromToken):e.fromToken),g=f===h,p=`galaswap - operation - ${s.v4()}-${Date.now()}-${e.walletAddress}`;let m;if(!e.currentSqrtPrice)throw W("currentSqrtPrice","Current sqrt price");const y=bo(e.currentSqrtPrice),w=e.slippageTolerance??.01;if(g){const e=So(w);m=ko(y.multipliedBy(e))}else{const e=Ao(w);m=ko(y.multipliedBy(e))}const b={token0:u,token1:l,fee:e.feeTier,amount:ko(bo(e.inputAmount)),zeroForOne:g,sqrtPriceLimit:m,recipient:e.walletAddress,amountOutMinimum:ko(bo(e.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:e.inputAmount,expectedOutput:e.minOutput,slippageTolerance:100*(e.slippageTolerance||.01)+"%"});const k=new t.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},C=this.buildSwapStringsInstructions(u,l,e.feeTier,e.walletAddress),N=dc.createClient(this.bundlerBaseUrl,3e4),B=yr(await N.post("/bundle",{method:"Swap",signedDto:I,stringsInstructions:C})),x=B?.data||B?.transactionId||B?.id;if(!x)throw new L("Bundler response does not contain transaction ID",void 0,"INVALID_RESPONSE");return x},"Failed to send Swap to bundler",this.logger)}async getSwapQuoteExactInput(e){return br(async()=>{if(bo(e.amount).isLessThanOrEqualTo(0))throw new O("Amount must be greater than zero",{amount:e.amount,fromToken:e.fromToken,toToken:e.toToken});if(!this.dexQuoteService)throw new O("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 br(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=bo(s.currentSqrtPrice),l=bo(s.newSqrtPrice),h=u.gt(l)?Uo(u.minus(l),u,"0"):bo(0),d=bo(s.amount0),f=bo(s.amount1);if(!_o(d)&&!_o(f))throw new O("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=(_o(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:T(e)})}throw s||new O("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 O(`${n}: ${T(t)}`,{fromToken:e.fromToken,toToken:e.toToken})})}async getSwapQuoteExactOutput(e){return br(async()=>{if(bo(e.amount).isLessThanOrEqualTo(0))throw new O("Amount must be greater than zero",{amount:e.amount,fromToken:e.fromToken,toToken:e.toToken});if(!this.dexQuoteService)throw new O("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 br(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=bo(s.currentSqrtPrice),l=bo(s.newSqrtPrice),h=u.gt(l)?Uo(u.minus(l),u,"0"):bo(0),d=bo(s.amount0),f=bo(s.amount1),g=(xo(d)?d:xo(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:T(e)})}throw s||new O("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 O(`${n}: ${T(t)}`,{fromToken:e.fromToken,toToken:e.toToken})})}async executeSwap(e){return br(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=vo(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 br(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:T(e)}),e})}}},"Failed to execute swap",this.logger,(e,t,n)=>{throw n?.error(t,e),new U(`${t}: ${T(e)}`,e)})}},e.GalaConnectClient=TT,e.GalaConnectHttpError=yT,e.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)}},e.IMAGE_EXTENSIONS=hi,e.INVITE_STATUS=vl,e.INVITE_STATUSES=Sl,e.JWT_CONSTANTS=At,e.LAUNCHPAD_TOKEN_DECIMALS=18,e.LEGACY_TYPED_DATA_TYPES=mu,e.LaunchpadSDK=FE,e.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}},e.LockError=va,e.MAX_BURN_BATCH_SIZE=50,e.MAX_CONCURRENT_POOL_FETCHES=5,e.MAX_LOCK_BATCH_SIZE=100,e.MAX_UNLOCK_BATCH_SIZE=100,e.MODERATOR_ROLE=yl,e.MODERATOR_ROLES=wl,e.NetworkError=R,e.OVERSEER_INVITE_STATUS=jl,e.OVERSEER_STATUS=Vl,e.PAGINATION_DEFAULTS=Ho,e.POOL_FETCH_CONFIG={MAX_CONCURRENT_FETCHES:5,BACKEND_PAGE_SIZE:20},e.POOL_TYPES={RECENT:"recent",POPULAR:"popular"},e.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}},e.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()}},e.PoolStateManager=WE,e.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"},e.REACTION_EMOJI_MAP={heart:"❤️",fire:"🔥",laugh:"😂",wow:"😮",thumbs_up:"👍"},e.RECORDING_STATUS=Tu,e.ROLE_SOURCE=xu,e.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}},e.SDK_VERSION=UE,e.SIMULATE_EVENT_TYPE={STREAM_STARTED:"stream.started",STREAM_STOPPED:"stream.stopped",RECORDING_READY:"recording.ready",SIMULCAST_ERROR:"simulcast.error"},e.SIMULCAST_PLATFORM=Eu,e.SIMULCAST_STATUS={ACTIVE:"ACTIVE",IDLE:"IDLE",ERRORED:"ERRORED",DISABLED:"DISABLED"},e.SOLANA_COMPUTE={UNIT_LIMIT:2e5,UNIT_PRICE_MICROLAMPORTS:375e3},e.SOLANA_DISCRIMINATORS=lu,e.STREAM_EVENTS=Wu,e.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"},e.STREAM_ROLE=Bu,e.STREAM_STATUS=Au,e.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}},e.SolanaBridgeStrategy=CE,e.StreamWebSocketService=Hu,e.StreamingEventService=ju,e.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},e.TRADES_QUERY_CONSTRAINTS=ks,e.TRADING_TYPES=vh,e.TokenMetadataService=class extends fs{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 is(e);return is(`${e.type||e.symbol||"unknown"}|${e.additionalKey||"none"}`)}extractMetadata(e){let t,n,r="Token",i="Unit",o="none";if("string"==typeof e)if(Xs(e)){const s=Vs(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 Xe(e)>this.cacheExpiry}setCacheExpiry(e){this.cacheExpiry=e,this.logger.debug(`Set token metadata cache expiry to ${e}ms`)}},e.TransactionError=L,e.TransactionFailedError=DE,e.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}},e.ValidationError=P,e.WebSocketError=RE,e.WebSocketTimeoutError=class extends RE{constructor(e,t){super(`WebSocket confirmation timeout for transaction ${e} after ${t}ms`),this.name="WebSocketTimeoutError"}},e.addressFormatSchema=Pr,e.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} - ${T(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)},e.amountMethodSchema=ci,e.amountTypeSchema=ai,e.assertValidWalletAddress=wt,e.bidirectionalTokenMatch=Bs,e.browserFileSchema=fi,e.bufferFileSchema=gi,e.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} - ${T(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}: ${T(e)}`)}}return i?.debug(`Batch complete: ${s} succeeded, ${a} failed`),o},e.buildQueryParametersWithValidation=function(e){if(!e||"object"!=typeof e)return"";const t=[];for(const[n,r]of Object.entries(e)){if(Ye(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("&")}`:""},e.buyTokensDataSchema=Li,e.calculateLinearFeeInterpolation=function(e,t,n){const r="number"==typeof e?new o(e):e;if(r.isLessThan(0)||r.isGreaterThan(1))throw new Error(`Progress must be between 0 and 1, got: ${r.toString()}`);if(n<t)throw new Error(`maxFee must be >= minFee, got minFee: ${t}, maxFee: ${n}`);const i=n-t;return new o(t).plus(new o(i).multipliedBy(r))},e.calculatePaginationOffset=jo,e.calculatePreMintDataSchema=Ki,e.calculateScaledFeeAmount=function(e,t){if(t<0)throw new Error(`feeFactor must be >= 0, got: ${t}`);return bo(e).multipliedBy(t).integerValue(o.ROUND_DOWN)},e.calculateTotalPages=Qo,e.capitalize=G,e.caseInsensitiveTokenComparison=Cs,e.checkPoolOptionsSchema=si,e.commonValidators=at,e.compareAmounts=function(e,t){const n=bo(e),r=bo(t);return n.comparedTo(r)},e.conditionalSpreadBuilder=function(e,t){const n={...e};for(const[e,r]of Object.entries(t))void 0!==r&&(n[e]=r);return n},e.conditionalTrimAndValidateString=Is,e.createLaunchpadSDK=function(e){Ze(e)&&(e={});const{wallet:n,env:r,config:i={},...o}=e,s={...o,...i},{wallet:a,env:c,config:u,...l}=s;let h;if(Ze(n)){h=qE().wallet}else if("string"==typeof n){h=qE(n).wallet}else{if(!(n instanceof t.Wallet))throw V("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 FE(d)},e.createLimitSchema=qr,e.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}},e.createPaginatedResultSchema=function(e){return i.z.object({data:i.z.array(e),page:i.z.number().int().min(1),limit:i.z.number().int().min(1),total:i.z.number().int().min(0),totalPages:i.z.number().int().min(0),hasNext:i.z.boolean(),hasPrevious:i.z.boolean()})},e.createPaginationQuery=function(e,t=Ho.DEFAULT_LIMIT){return{offset:jo(e,t),limit:t}},e.createPoolStateManager=function(e,t){return new WE(e,t)},e.createSolanaWallet=function(){const e=MA.generate();return{privateKey:EE.encode(e.secretKey),publicKey:e.publicKey.toBase58(),address:e.publicKey.toBase58()}},e.createTradeDataSchema=Di,e.createWallet=qE,e.decimalRoundingUp=function(e,t){if(t<0)throw new Error(`decimals must be >= 0, got: ${t}`);const n=bo(e),r=new o(10).pow(t);return n.multipliedBy(r).integerValue(o.ROUND_UP).dividedBy(r)},e.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})},e.errorMessageCaseNormalization=function(e){return e.toLowerCase()},e.ethereumAddressSchema=Rr,e.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(Je(n))return n;if(null!=n&&""!==n)return n}return n},e.extractPaginationMetadata=function(e){const t={page:1,pageSize:20,totalCount:-1,hasMore:!1};if(!e||"object"!=typeof e)return t;const n=e,r=Ue(String(n.page??n.Page??n.current??1),t.page),i=Ue(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:Ue(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}},e.fetchGalaBalanceOptionsSchema=Ci,e.fetchPoolDetailsDataSchema=Gi,e.fetchTokenBalanceOptionsSchema=_i,e.fileSizeSchema=Wr,e.fileUploadSchema=di,e.filenameSchema=Hr,e.filterByFeeTier=function(e,t){return e.filter(e=>e.feeTier===t)},e.filterByLiquidity=function(e){return e.filter(e=>xo(e.liquidity))},e.filterByMinLiquidity=function(e,t){const n=bo(t);return e.filter(e=>bo(e.liquidity).isGreaterThanOrEqualTo(n))},e.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})},e.filterByToken=function(e,t){return e.filter(e=>Cs(e.token0,t)||Cs(e.token1,t))},e.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})},e.flexibleAddressSchema=Dr,e.flexibleFileSchema=pi,e.formatGalaForDTO=Ke,e.formatLaunchpadTokenForDTO=Ge,e.formatTokenAmount=function(e,t=6){const n=bo(e);if(!n.isFinite())return"0";if(n.abs().lt(1e-6)&&!Bo(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+$/,"")},e.formatTokenDescriptor=function(e){return Gs(e)},e.fromBackendAddressFormat=pt,e.fromBaseUnits=Ch,e.fullNameSchema=_r,e.generateUniqueKey=ha,e.getAmountOptionsSchema=qi,e.getEnv=function(e,t){return process.env[e]??t},e.getEnvOrThrow=function(e,t){const n=process.env[e];if(Ze(n)||!Je(n)){throw W(e,`${e} (${t?`${t} (checked root .env and local .env)`:"checked root .env and local .env"})`)}return n},e.getEthereumAddressFromPrivateKey=function(e){if(!e.match(/^0x[a-fA-F0-9]{64}$/))throw H("privateKey","0x-prefixed 64 hexadecimal characters","Private key");return t.getAddress(t.computeAddress(e))},e.getEthereumBridgeContractByEnvironment=iu,e.getEthereumTokenConfig=function(e){const t=ss(e);return ou.find(e=>ss(e.symbol)===t||ss(e.symbol)===`G${t}`)},e.getEthereumTokensByEnvironment=ru,e.getGalaBridgeTypedDataTypes=wu,e.getPublicKeyFromPrivateKey=function(e){if(!e.match(/^0x[a-fA-F0-9]{64}$/))throw H("privateKey","0x-prefixed 64 hexadecimal characters","Private key");const n=new t.SigningKey(e);return{publicKey:n.publicKey,compressedPublicKey:n.compressedPublicKey}},e.getSolanaTokenConfig=function(e){const t=ss(e);return su.find(e=>ss(e.symbol)===t||ss(e.symbol)===`G${t}`)},e.getStaticTokenMetadata=function(e){const t=ss(e),n=au[t];if(n)return n;if(!t.startsWith("G")){const e=au[`G${t}`];if(e)return e}},e.getTradeOptionsSchema=Ui,e.graduateTokenOptionsSchema=li,e.graphDataOptionsSchema=ui,e.groupByFeeTier=function(e){return KE(e,e=>e.feeTier)},e.groupByKey=KE,e.groupByPoolKey=function(e){return KE(e,e=>`${e.token0.toUpperCase()}|${e.token1.toUpperCase()}|${e.feeTier}`)},e.groupByTokenPair=function(e){return KE(e,e=>`${e.token0.toUpperCase()}/${e.token1.toUpperCase()}`)},e.hasMorePages=Jo,e.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(xs(e))return _s(e)}return null}return xs(e)?_s(e):null},e.imageExtensionSchema=mi,e.imageFilenameSchema=yi,e.imageMimeTypeSchema=jr,e.imageUploadOptionsSchema=ii,e.isAccessSource=Lu,e.isActiveUserType=Xu,e.isBanData=Qu,e.isBanEnforcementEvent=Zu,e.isBurnTokenEntry=Ba,e.isBurnTokensData=xa,e.isChatDisabledReason=Fu,e.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},e.isChatStatusResponse=function(e){if(!e||"object"!=typeof e)return!1;const t=e;return"boolean"==typeof t.enabled&&(void 0===t.reason||Fu(t.reason))},e.isClaimableInvite=function(e){if(e.status!==jl.PENDING)return!1;if(e.expiresAt){if(je(e.expiresAt)<=new Date)return!1}return!0},e.isContentType=Fl,e.isExtendedStreamRole=Du,e.isFlagAction=Kl,e.isFlagData=Gl,e.isFlagReason=$l,e.isFlagStatus=ql,e.isLockTokenEntry=pa,e.isLockTokensData=ya,e.isModeratedToken=Cl,e.isModeratorInvite=Il,e.isOverseerInviteStatus=Xl,e.isOverseerStatus=Ql,e.isPinnedMessage=qu,e.isPublicInviteInfo=Nl,e.isReactionErrorCode=Ku,e.isRecordingStatus=Cu,e.isSimulcastPlatform=Nu,e.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},e.isStreamChatErrorEvent=function(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.message},e.isStreamChatMessage=$u,e.isStreamChatMessageEvent=function(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&$u(t.message)},e.isStreamChatPinnedEvent=function(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&qu(t.pinnedMessage)},e.isStreamChatUnpinnedEvent=function(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.unpinnedMessageId},e.isStreamReactionErrorEvent=function(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.message},e.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},e.isStreamStatus=Iu,e.isStreamStatusEvent=function(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&Iu(t.status)&&(null===t.playbackId||"string"==typeof t.playbackId)&&"boolean"==typeof t.isLive},e.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)},e.isTokenAccessPermissions=Ru,e.isTokenAccessResult=function(e){if(!e||"object"!=typeof e)return!1;const t=e;return"boolean"==typeof t.hasAccess&&(null===t.role||Du(t.role))&&Ru(t.permissions)&&(null===t.accessSource||Lu(t.accessSource))&&"boolean"==typeof t.isOwner&&"boolean"==typeof t.isOverseer},e.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)},e.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(Gu)},e.isTypingUser=Gu,e.isUnlockTokenEntry=ma,e.isUnlockTokensData=wa,e.isUserBannedEvent=Ju,e.isUserUnbannedEvent=Yu,e.isValidAddress=yt,e.isValidApiKeyRole=hl,e.isValidBanDuration=tl,e.isValidBanReason=el,e.isValidChatContent=function(e){return!!Je(e)&&(e.length>=Se.CHAT_MESSAGE.MIN_LENGTH&&e.length<=Se.CHAT_MESSAGE.MAX_LENGTH)},e.isValidChatTokenName=function(e){return!!Je(e)&&fe.PATTERN.test(e)},e.isValidGalaChainChannel=function(e){return Object.values(Jc).includes(e)},e.isValidInviteCode=El,e.isValidInviteStatus=Tl,e.isValidModeratorRole=Al,e.isValidTokenBanReason=rl,e.isValidTokenName=function(e,t=fe){if("string"!=typeof e)return!1;const n=e.trim();return 0!==n.length&&t.PATTERN.test(n)},e.isViewerCountEvent=function(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"number"==typeof t.viewerCount},e.isoDateStringSchema=Vr,e.launchTokenDataSchema=ri,e.loadEnvWithFallback=function(){const e=w.join(process.cwd(),"..","..",".env");b.existsSync(e)&&k.config({path:e});const t=w.join(process.cwd(),".env");b.existsSync(t)&&k.config({path:t})},e.nonNegativeDecimalStringSchema=Ur,e.normalizeAddressInput=mt,e.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})},e.normalizeErrorMessage=Ns,e.normalizeLimit=Xo,e.normalizePage=Vo,e.normalizeTokenKey=os,e.normalizeTokenName=is,e.normalizeTokenSymbol=ss,e.optionalUrlSchema=Fr,e.pageNumberSchema=$r,e.paginationResultMetaSchema=Ti,e.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},e.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)},e.poolFetchTypeSchema=oi,e.poolPaginationSchema=vi,e.positiveDecimalStringSchema=Or,e.priceTickRangeMapping=function(e,t,n=60){const r=bo(e),i=bo(t);if(r.isLessThanOrEqualTo(0)||i.isLessThanOrEqualTo(0))throw new Error("Prices must be positive");if(r.isGreaterThanOrEqualTo(i))throw new Error(`minPrice must be < maxPrice, got: ${r.toString()} >= ${i.toString()}`);const s=Math.floor(To(r)),a=Math.ceil(To(i)),c=Math.floor(s/n)*n,u=Math.ceil(a/n)*n;return{minTick:c,maxTick:u,actualMinPrice:new o(1.0001).pow(c),actualMaxPrice:new o(1.0001).pow(u)}},e.privateKeySchema=Qr,e.requireNonNegative=Lo,e.requirePositive=Do,e.requirePositiveWithContext=Oo,e.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=GE(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},e.reverseBondingCurveConfigSchema=ni,e.reverseBondingCurveConfigurationSchema=zi,e.roleHasSufficientPermission=function(e,t){return e===ul.MANAGER?t!==ul.OWNER:e===ul.OWNER||e===t},e.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}},e.roundTickToSpacing=function(e,t){if(t<=0)throw new Error(`tickSpacing must be > 0, got: ${t}`);return Math.floor(e/t)*t},e.safeDivideWithMinimum=function(e,t,n,r="0"){const i=bo(t);if(Bo(i))return bo(r);const o=bo(e).dividedBy(i);if(null!=n){const e=bo(n);if(e.isLessThan(0))throw new Error(`minimum must be >= 0, got: ${e.toString()}`);if(o.isLessThan(e))return e}return o},e.searchQuerySchema=xr,e.sellTokensDataSchema=Oi,e.sortByLiquidity=function(e,t="desc"){return[...e].sort((e,n)=>{const r=bo(e.liquidity),i=bo(n.liquidity);return"desc"===t?i.minus(r).toNumber():r.minus(i).toNumber()})},e.standardLimitSchema=Kr,e.standardPaginationSchema=wi,e.stripHexPrefix=ut,e.timestampSchema=Xr,e.toBackendAddressFormat=gt,e.toBackendAddressFromEthers=bt,e.toBaseUnits=Ih,e.tokenCategorySchema=ei,e.tokenCollectionSchema=ti,e.tokenDescriptionSchema=Nr,e.tokenHoldSchema=xi,e.tokenListOptionsSchema=Ii,e.tokenNameSchema=Ir,e.tokenSymbolSchema=Cr,e.tokenUrlsSchema=Zr,e.tradeCalculationMethodSchema=$i,e.tradeCalculationTypeSchema=Fi,e.tradeLimitSchema=zr,e.tradeListParamsSchema=Mi,e.tradePaginationSchema=ki,e.tradePaginationWithFiltersSchema=Ai,e.tradeTypeBackendSchema=Ri,e.tradeTypeSchema=Pi,e.transactionIdSchema=Jr,e.transformRawApiTokenToDomainModel=function(e){if(!e||"object"!=typeof e)throw new Error("Token must be an object");const t=e,n=(Je(t.name)?t.name:null)||(Je(t.tokenName)?t.tokenName:null)||"";if(!Je(n))throw new Error("Token name is required and must be a non-empty string");const r=(Je(t.symbol)?t.symbol:null)||(Je(t.tokenSymbol)?t.tokenSymbol:null)||(Je(t.collection)?t.collection:null)||"";if(!Je(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 Je(t.address)&&(o.address=t.address),"boolean"==typeof t.verified&&(o.verified=t.verified),o},e.trimmedLengthValidation=function(e){return!e||"string"!=typeof e||0===e.trim().length},e.uniqueKeySchema=Yr,e.updateProfileDataSchema=Ni,e.uploadProfileImageOptionsSchema=Bi,e.urlSchema=Mr,e.userLimitSchema=Gr,e.userPaginationSchema=bi,e.userTokenNameSchema=Br,e.userTokenTypeSchema=Ei,e.userTokensPaginationSchema=Si,e.validateAddress=Xi,e.validateAmountString=Ji,e.validateBanTokenOptions=il,e.validateBuyTokensData=ho,e.validateCalculatePreMintData=yo,e.validateChatMessageId=dh,e.validateCheckPoolOptions=io,e.validateConstrainedEnumVariant=function(e,t,n){if(!t.includes(e))throw new P(`${n} must be one of [${t.join(", ")}], received "${e}"`,n,"INVALID_ENUM_VALUE")},e.validateCreateApiKeyOptions=dl,e.validateCreateChatMessageOptions=lh,e.validateCreateCommentOptions=function(e){if(!Je(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 H("tokenName",`${t}-${n} alphanumeric characters`,"Token name");if(!Je(e.content))throw W("content");if(0===e.content.trim().length)throw oe("content","Content");if(e.content.length>Se.COMMENTS_V1.MAX_LENGTH)throw ie("content",Se.COMMENTS_V1.MAX_LENGTH,e.content.length)},e.validateCreateModeratorInviteOptions=function(e){const t=[],n=e.inviteScope??bl.TOKEN;return void 0===e.inviteScope||Bl(e.inviteScope)||x(t,()=>{throw re("inviteScope",e.inviteScope,kl,"Invite scope")}),n===bl.TOKEN?x(t,()=>{it(e.tokenName??"","tokenName",fe)}):n===bl.ALL_OWNER_TOKENS&&e.tokenName&&t.push("Token name should not be provided for ALL_OWNER_TOKENS scope invites"),e.role?Al(e.role)||x(t,()=>{throw re("role",e.role,wl,"Role")}):x(t,()=>{throw W("role","Role")}),e.description&&x(t,()=>{ae(e.description,Se.DESCRIPTION.MAX_LENGTH,"description")}),e.expiresAt&&!Ve(e.expiresAt)&&x(t,()=>{throw function(e,t="a valid date",n){const r=G(e,n);return new P(`${r} must be ${t}`,e,"INVALID_DATE")}("expiresAt","ISO 8601 format")}),t},e.validateCreateOverseerInviteOptions=Jl,e.validateCreateTradeData=lo,e.validateDecimalRangeStrict=function(e,t,n,r){const i="string"==typeof e?parseFloat(e):e;if(!isFinite(i))throw new P(`${r} must be a valid finite number between ${t} and ${n}`,r,"INVALID_NUMBER");if(i<t||i>n)throw J(r,t,n,i,r)},e.validateFeePortionConstraints=de,e.validateFetchGalaBalanceOptions=so,e.validateFetchPoolDetailsData=wo,e.validateFetchTokenBalanceOptions=uo,e.validateFullName=Yi,e.validateGetAmountOptions=mo,e.validateGetChatMessagesOptions=uh,e.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 P(`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 H("tokenName",`${t}-${n} alphanumeric characters`,"Token name")}et(e.page,e.limit,we.MAX_LIMIT)},e.validateGetTokenBanOptions=al,e.validateGetTradeOptions=go,e.validateGetTradesOptions=vs,e.validateImageUploadOptions=ro,e.validateInviteCode=function(e){const t=[];return Je(e)?El(e)||t.push("Invalid invite code format"):t.push(W("inviteCode","Invite code").message),t},e.validateLaunchTokenData=to,e.validateListApiKeysOptions=gl,e.validateListModeratorInvitesOptions=function(e){const t=[];return x(t,()=>{it(e.tokenName??"","tokenName",fe)}),void 0===e.status||Tl(e.status)||x(t,()=>{throw re("status",e.status,Sl,"Status")}),x(t,()=>{et(e.page,e.limit,me)}),t},e.validateListOverseerInvitesOptions=Yl,e.validateListOverseersOptions=Zl,e.validateListTokenBansOptions=sl,e.validateListUsersOptions=rh,e.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 P(`${n} must be a valid finite number`,n,"INVALID_MIN_VALUE");if(!isFinite(o))throw new P(`${r} must be a valid finite number`,r,"INVALID_MAX_VALUE");if(i>o)throw new P(`${n} (${i}) must be less than or equal to ${r} (${o})`,n,"INVALID_RANGE")},e.validateOptionalTokenName=function(e,t="tokenName",n=fe){if(null==e)return;if("string"!=typeof e)throw ee(t,"a string",e);const r=e.trim();if(0!==r.length&&!n.PATTERN.test(r))throw new P(`${t} must be ${n.MIN_LENGTH}-${n.MAX_LENGTH} alphanumeric characters`,t,_.INVALID_FORMAT)},e.validateOverseerInviteCode=eh,e.validateOverseerInviteId=nh,e.validateOverseerWalletAddress=th,e.validatePaginationParams=function(e,t,n){ce(e,"page"),ce(t,"limit")},e.validateSearchQuery=Zi,e.validateSellTokensData=fo,e.validateSortOrderDirection=he,e.validateTokenDescription=Vi,e.validateTokenListOptions=oo,e.validateTokenName=ot,e.validateTokenSymbol=ji,e.validateTokenUrls=no,e.validateTradeListParams=po,e.validateUnbanTokenOptions=ol,e.validateUpdateApiKeyOptions=fl,e.validateUpdateChatMessageOptions=hh,e.validateUpdateCommentOptions=function(e){if(!Je(e.content))throw W("content");if(0===e.content.trim().length)throw oe("content","Content");if(e.content.length>Se.COMMENTS_V1.MAX_LENGTH)throw ie("content",Se.COMMENTS_V1.MAX_LENGTH,e.content.length)},e.validateUpdateProfileData=ao,e.validateUploadProfileImageOptions=co,e.validateUserTokenName=eo,e.validateVaultAddress=Qi,e.vaultAddressSchema=Lr});